1 <?php namespace BookStack\Uploads;
3 use BookStack\Auth\User;
4 use BookStack\Exceptions\HttpFetchException;
9 protected $imageService;
12 public function __construct(ImageService $imageService, HttpFetcher $http)
14 $this->imageService = $imageService;
19 * Fetch and assign an avatar image to the given user.
21 public function fetchAndAssignToUser(User $user): void
23 if (!$this->avatarFetchEnabled()) {
28 $avatar = $this->saveAvatarImage($user);
29 $user->avatar()->associate($avatar);
31 } catch (Exception $e) {
32 Log::error('Failed to save user avatar image');
37 * Save an avatar image from an external service.
40 protected function saveAvatarImage(User $user, int $size = 500): Image
42 $avatarUrl = $this->getAvatarUrl();
43 $email = strtolower(trim($user->email));
46 '${hash}' => md5($email),
48 '${email}' => urlencode($email),
51 $userAvatarUrl = strtr($avatarUrl, $replacements);
52 $imageName = str_replace(' ', '-', $user->id . '-avatar.png');
53 $imageData = $this->getAvatarImageData($userAvatarUrl);
55 $image = $this->imageService->saveNew($imageName, $imageData, 'user', $user->id);
56 $image->created_by = $user->id;
57 $image->updated_by = $user->id;
64 * Gets an image from url and returns it as a string of image data.
67 protected function getAvatarImageData(string $url): string
70 $imageData = $this->http->fetch($url);
71 } catch (HttpFetchException $exception) {
72 throw new Exception(trans('errors.cannot_get_image_from_url', ['url' => $url]));
78 * Check if fetching external avatars is enabled.
80 protected function avatarFetchEnabled(): bool
82 $fetchUrl = $this->getAvatarUrl();
83 return is_string($fetchUrl) && strpos($fetchUrl, 'http') === 0;
87 * Get the URL to fetch avatars from.
89 protected function getAvatarUrl(): string
91 $url = trim(config('services.avatar_url'));
93 if (empty($url) && !config('services.disable_services')) {
94 $url = 'https://www.gravatar.com/avatar/${hash}?s=${size}&d=identicon';