3 namespace BookStack\Console\Commands;
5 use BookStack\Users\Models\User;
7 use Illuminate\Console\Command;
8 use BookStack\Uploads\UserAvatars;
10 class RefreshAvatarCommand extends Command
12 use HandlesSingleUser;
15 * The name and signature of the console command.
19 protected $signature = 'bookstack:refresh-avatar
20 {--id= : Numeric ID of the user to refresh avatar for}
21 {--email= : Email address of the user to refresh avatar for}
22 {--users-without-avatars : Refresh avatars for users that currently have no avatar}
23 {--a|all : Refresh avatars for all users}
24 {--f|force : Actually run the update, Defaults to a dry-run}';
27 * The console command description.
31 protected $description = 'Refresh avatar for the given user(s)';
33 public function handle(UserAvatars $userAvatar): int
35 if (!$userAvatar->avatarFetchEnabled()) {
36 $this->error("Avatar fetching is disabled on this instance.");
40 if ($this->option('users-without-avatars')) {
41 return $this->processUsers(User::query()->whereDoesntHave('avatar')->get()->all(), $userAvatar);
44 if ($this->option('all')) {
45 return $this->processUsers(User::query()->get()->all(), $userAvatar);
49 $user = $this->fetchProvidedUser();
50 return $this->processUsers([$user], $userAvatar);
51 } catch (Exception $exception) {
52 $this->error($exception->getMessage());
58 * @param User[] $users
60 private function processUsers(array $users, UserAvatars $userAvatar): int
62 $dryRun = !$this->option('force');
63 $this->info(count($users) . " user(s) found to update avatars for.");
65 if (count($users) === 0) {
70 $fetchHost = parse_url($userAvatar->getAvatarUrl(), PHP_URL_HOST);
71 $this->warn("This will destroy any existing avatar images these users have, and attempt to fetch new avatar images from {$fetchHost}.");
72 $proceed = !$this->input->isInteractive() || $this->confirm('Are you sure you want to proceed?');
80 $exitCode = self::SUCCESS;
81 foreach ($users as $user) {
82 $linePrefix = "[ID: {$user->id}] $user->email -";
85 $this->warn("{$linePrefix} Not updated");
89 if ($this->fetchAvatar($userAvatar, $user)) {
90 $this->info("{$linePrefix} Updated");
92 $this->error("{$linePrefix} Not updated");
93 $exitCode = self::FAILURE;
99 $this->comment("Dry run, no avatars were updated.");
100 $this->comment('Run with -f or --force to perform the update.');
106 private function fetchAvatar(UserAvatars $userAvatar, User $user): bool
108 $oldId = $user->avatar->id ?? 0;
110 $userAvatar->fetchAndAssignToUser($user);
113 $newId = $user->avatar->id ?? $oldId;
114 return $oldId !== $newId;