1 <?php namespace BookStack\Uploads;
3 use BookStack\Auth\User;
4 use BookStack\Exceptions\HttpFetchException;
6 use Illuminate\Support\Facades\Log;
10 protected $imageService;
13 public function __construct(ImageService $imageService, HttpFetcher $http)
15 $this->imageService = $imageService;
20 * Fetch and assign an avatar image to the given user.
22 public function fetchAndAssignToUser(User $user): void
24 if (!$this->avatarFetchEnabled()) {
29 $avatar = $this->saveAvatarImage($user);
30 $user->avatar()->associate($avatar);
32 } catch (Exception $e) {
33 Log::error('Failed to save user avatar image');
38 * Save an avatar image from an external service.
41 protected function saveAvatarImage(User $user, int $size = 500): Image
43 $avatarUrl = $this->getAvatarUrl();
44 $email = strtolower(trim($user->email));
47 '${hash}' => md5($email),
49 '${email}' => urlencode($email),
52 $userAvatarUrl = strtr($avatarUrl, $replacements);
53 $imageName = str_replace(' ', '-', $user->id . '-avatar.png');
54 $imageData = $this->getAvatarImageData($userAvatarUrl);
56 $image = $this->imageService->saveNew($imageName, $imageData, 'user', $user->id);
57 $image->created_by = $user->id;
58 $image->updated_by = $user->id;
65 * Gets an image from url and returns it as a string of image data.
68 protected function getAvatarImageData(string $url): string
71 $imageData = $this->http->fetch($url);
72 } catch (HttpFetchException $exception) {
73 throw new Exception(trans('errors.cannot_get_image_from_url', ['url' => $url]));
79 * Check if fetching external avatars is enabled.
81 protected function avatarFetchEnabled(): bool
83 $fetchUrl = $this->getAvatarUrl();
84 return is_string($fetchUrl) && strpos($fetchUrl, 'http') === 0;
88 * Get the URL to fetch avatars from.
90 protected function getAvatarUrl(): string
92 $url = trim(config('services.avatar_url'));
94 if (empty($url) && !config('services.disable_services')) {
95 $url = 'https://www.gravatar.com/avatar/${hash}?s=${size}&d=identicon';