jonnybarnes.uk/app/Jobs/SaveProfileImage.php

80 lines
2.4 KiB
PHP
Raw Normal View History

2016-08-03 16:08:30 +01:00
<?php
declare(strict_types=1);
2016-08-03 16:08:30 +01:00
namespace App\Jobs;
2019-10-27 16:29:15 +00:00
use Illuminate\Bus\Queueable;
2016-08-03 16:08:30 +01:00
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Http\Client\RequestException;
2019-10-27 16:29:15 +00:00
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Http;
2016-08-03 16:08:30 +01:00
use Jonnybarnes\WebmentionsParser\Authorship;
use Jonnybarnes\WebmentionsParser\Exceptions\AuthorshipParserException;
2016-09-20 13:13:05 +01:00
class SaveProfileImage implements ShouldQueue
2016-08-03 16:08:30 +01:00
{
2019-10-27 19:31:33 +00:00
use InteractsWithQueue;
use Queueable;
use SerializesModels;
2016-08-03 16:08:30 +01:00
/**
* Create a new job instance.
*/
2023-02-18 09:34:57 +00:00
public function __construct(
protected array $microformats
) {}
2016-08-03 16:08:30 +01:00
/**
* Execute the job.
*/
2023-02-18 09:34:57 +00:00
public function handle(Authorship $authorship): void
2016-08-03 16:08:30 +01:00
{
try {
$author = $authorship->findAuthor($this->microformats);
2021-03-17 18:38:18 +00:00
} catch (AuthorshipParserException) {
2023-02-18 09:34:57 +00:00
return;
2016-08-03 16:08:30 +01:00
}
2021-03-17 18:38:18 +00:00
$photo = Arr::get($author, 'properties.photo.0');
$home = Arr::get($author, 'properties.url.0');
2021-03-17 18:38:18 +00:00
if (is_array($photo) && array_key_exists('value', $photo)) {
$photo = $photo['value'];
}
if (is_array($home)) {
$home = array_shift($home);
}
2025-03-01 15:00:41 +00:00
// dont save pbs.twimg.com links
2019-10-27 19:31:33 +00:00
if (
$photo
2023-02-18 09:34:57 +00:00
&& parse_url($photo, PHP_URL_HOST) !== 'pbs.twimg.com'
&& parse_url($photo, PHP_URL_HOST) !== 'twitter.com'
2019-10-27 19:31:33 +00:00
) {
2016-08-03 16:08:30 +01:00
try {
$response = Http::throw()->get($photo);
$image = $response->body();
} catch (ConnectionException|RequestException) {
2019-10-27 19:31:33 +00:00
// we are opening and reading the default image so that
2026-04-07 09:01:19 +01:00
$default = public_path().'/assets/profile-images/default-image';
2016-08-03 16:08:30 +01:00
$handle = fopen($default, 'rb');
$image = fread($handle, filesize($default));
fclose($handle);
}
2021-03-17 18:38:18 +00:00
2026-04-07 09:01:19 +01:00
$path = public_path().'/assets/profile-images/'.parse_url($home, PHP_URL_HOST).'/image';
2016-08-03 16:08:30 +01:00
$parts = explode('/', $path);
$name = array_pop($parts);
$dir = implode('/', $parts);
2023-02-18 09:53:57 +00:00
if (! is_dir($dir) && ! mkdir($dir, 0755, true) && ! is_dir($dir)) {
2023-02-18 09:34:57 +00:00
throw new \RuntimeException(sprintf('Directory "%s" was not created', $dir));
2016-08-03 16:08:30 +01:00
}
file_put_contents("$dir/$name", $image);
}
}
}