diff options
Diffstat (limited to 'lib/private/Avatar')
-rw-r--r-- | lib/private/Avatar/Avatar.php | 212 | ||||
-rw-r--r-- | lib/private/Avatar/AvatarManager.php | 140 | ||||
-rw-r--r-- | lib/private/Avatar/GuestAvatar.php | 65 | ||||
-rw-r--r-- | lib/private/Avatar/PlaceholderAvatar.php | 81 | ||||
-rw-r--r-- | lib/private/Avatar/UserAvatar.php | 162 |
5 files changed, 229 insertions, 431 deletions
diff --git a/lib/private/Avatar/Avatar.php b/lib/private/Avatar/Avatar.php index 3bd58bb7681..dc65c9d5743 100644 --- a/lib/private/Avatar/Avatar.php +++ b/lib/private/Avatar/Avatar.php @@ -3,54 +3,24 @@ declare(strict_types=1); /** - * @copyright Copyright (c) 2016, ownCloud, Inc. - * @copyright 2018 John Molakvoæ <skjnldsv@protonmail.com> - * - * @author Christopher Schäpers <kondou@ts.unde.re> - * @author Christoph Wurst <christoph@winzerhof-wurst.at> - * @author Jan-Christoph Borchardt <hey@jancborchardt.net> - * @author Joas Schilling <coding@schilljs.com> - * @author John Molakvoæ <skjnldsv@protonmail.com> - * @author Julius Härtl <jus@bitgrid.net> - * @author Michael Weimann <mail@michael-weimann.eu> - * @author Morris Jobke <hey@morrisjobke.de> - * @author Robin Appelman <robin@icewind.nl> - * @author Roeland Jago Douma <roeland@famdouma.nl> - * @author Sergey Shliakhov <husband.sergey@gmail.com> - * @author Thomas Müller <thomas.mueller@tmit.eu> - * - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see <http://www.gnu.org/licenses/> - * + * SPDX-FileCopyrightText: 2018 Nextcloud GmbH and Nextcloud contributors + * SPDX-FileCopyrightText: 2016 ownCloud, Inc. + * SPDX-License-Identifier: AGPL-3.0-only */ namespace OC\Avatar; use Imagick; -use OC\Color; -use OC_Image; +use OC\User\User; +use OCP\Color; use OCP\Files\NotFoundException; use OCP\IAvatar; +use OCP\IConfig; use Psr\Log\LoggerInterface; /** * This class gets and sets users avatars. */ abstract class Avatar implements IAvatar { - - /** @var LoggerInterface */ - protected $logger; - /** * https://github.com/sebdesign/cap-height -- for 500px height * Automated check: https://codepen.io/skjnldsv/pen/PydLBK/ @@ -58,30 +28,26 @@ abstract class Avatar implements IAvatar { * (0.4 letter-to-total-height ratio, 500*0.4=200), so: 200/0.715 = 280px. * Since we start from the baseline (text-anchor) we need to * shift the y axis by 100px (half the caps height): 500/2+100=350 - * - * @var string */ - private $svgTemplate = '<?xml version="1.0" encoding="UTF-8" standalone="no"?> + private string $svgTemplate = '<?xml version="1.0" encoding="UTF-8" standalone="no"?> <svg width="{size}" height="{size}" version="1.1" viewBox="0 0 500 500" xmlns="http://www.w3.org/2000/svg"> <rect width="100%" height="100%" fill="#{fill}"></rect> - <text x="50%" y="350" style="font-weight:normal;font-size:280px;font-family:\'Noto Sans\';text-anchor:middle;fill:#fff">{letter}</text> + <text x="50%" y="350" style="font-weight:normal;font-size:280px;font-family:\'Noto Sans\';text-anchor:middle;fill:#{fgFill}">{letter}</text> </svg>'; - public function __construct(LoggerInterface $logger) { - $this->logger = $logger; + public function __construct( + protected IConfig $config, + protected LoggerInterface $logger, + ) { } /** * Returns the user display name. - * - * @return string */ abstract public function getDisplayName(): string; /** * Returns the first letter of the display name, or "?" if no name given. - * - * @return string */ private function getAvatarText(): string { $displayName = $this->getDisplayName(); @@ -97,16 +63,14 @@ abstract class Avatar implements IAvatar { /** * @inheritdoc */ - public function get($size = 64) { - $size = (int) $size; - + public function get(int $size = 64, bool $darkTheme = false) { try { - $file = $this->getFile($size); + $file = $this->getFile($size, $darkTheme); } catch (NotFoundException $e) { return false; } - $avatar = new OC_Image(); + $avatar = new \OCP\Image(); $avatar->loadFromData($file->getContent()); return $avatar; } @@ -122,70 +86,102 @@ abstract class Avatar implements IAvatar { * @return string * */ - protected function getAvatarVector(int $size): string { - $userDisplayName = $this->getDisplayName(); - $bgRGB = $this->avatarBackgroundColor($userDisplayName); - $bgHEX = sprintf("%02x%02x%02x", $bgRGB->r, $bgRGB->g, $bgRGB->b); + protected function getAvatarVector(string $userDisplayName, int $size, bool $darkTheme): string { + $fgRGB = $this->avatarBackgroundColor($userDisplayName); + $bgRGB = $fgRGB->alphaBlending(0.1, $darkTheme ? new Color(0, 0, 0) : new Color(255, 255, 255)); + $fill = sprintf('%02x%02x%02x', $bgRGB->red(), $bgRGB->green(), $bgRGB->blue()); + $fgFill = sprintf('%02x%02x%02x', $fgRGB->red(), $fgRGB->green(), $fgRGB->blue()); $text = $this->getAvatarText(); - $toReplace = ['{size}', '{fill}', '{letter}']; - return str_replace($toReplace, [$size, $bgHEX, $text], $this->svgTemplate); + $toReplace = ['{size}', '{fill}', '{fgFill}', '{letter}']; + return str_replace($toReplace, [$size, $fill, $fgFill, $text], $this->svgTemplate); + } + + /** + * Select the rendering font based on the user's display name and language + */ + private function getFont(string $userDisplayName): string { + if (preg_match('/\p{Han}/u', $userDisplayName) === 1) { + switch ($this->getAvatarLanguage()) { + case 'zh_TW': + return __DIR__ . '/../../../core/fonts/NotoSansTC-Regular.ttf'; + case 'zh_HK': + return __DIR__ . '/../../../core/fonts/NotoSansHK-Regular.ttf'; + case 'ja': + return __DIR__ . '/../../../core/fonts/NotoSansJP-Regular.ttf'; + case 'ko': + return __DIR__ . '/../../../core/fonts/NotoSansKR-Regular.ttf'; + default: + return __DIR__ . '/../../../core/fonts/NotoSansSC-Regular.ttf'; + } + } + return __DIR__ . '/../../../core/fonts/NotoSans-Regular.ttf'; } /** * Generate png avatar from svg with Imagick - * - * @param int $size - * @return string|boolean */ - protected function generateAvatarFromSvg(int $size) { + protected function generateAvatarFromSvg(string $userDisplayName, int $size, bool $darkTheme): ?string { if (!extension_loaded('imagick')) { - return false; + return null; } + $formats = Imagick::queryFormats(); + // Avatar generation breaks if RSVG format is enabled. Fall back to gd in that case + if (in_array('RSVG', $formats, true)) { + return null; + } + $text = $this->getAvatarText(); try { - $font = __DIR__ . '/../../core/fonts/NotoSans-Regular.ttf'; - $svg = $this->getAvatarVector($size); + $font = $this->getFont($text); + $svg = $this->getAvatarVector($userDisplayName, $size, $darkTheme); $avatar = new Imagick(); $avatar->setFont($font); $avatar->readImageBlob($svg); $avatar->setImageFormat('png'); - $image = new OC_Image(); + $image = new \OCP\Image(); $image->loadFromData((string)$avatar); - $data = $image->data(); - return $data === null ? false : $data; + return $image->data(); } catch (\Exception $e) { - return false; + return null; } } /** * Generate png avatar with GD - * - * @param string $userDisplayName - * @param int $size - * @return string + * @throws \Exception when an error occurs in gd calls */ - protected function generateAvatar($userDisplayName, $size) { + protected function generateAvatar(string $userDisplayName, int $size, bool $darkTheme): string { $text = $this->getAvatarText(); - $backgroundColor = $this->avatarBackgroundColor($userDisplayName); + $textColor = $this->avatarBackgroundColor($userDisplayName); + $backgroundColor = $textColor->alphaBlending(0.1, $darkTheme ? new Color(0, 0, 0) : new Color(255, 255, 255)); $im = imagecreatetruecolor($size, $size); + if ($im === false) { + throw new \Exception('Failed to create avatar image'); + } $background = imagecolorallocate( $im, - $backgroundColor->r, - $backgroundColor->g, - $backgroundColor->b + $backgroundColor->red(), + $backgroundColor->green(), + $backgroundColor->blue() + ); + $textColor = imagecolorallocate($im, + $textColor->red(), + $textColor->green(), + $textColor->blue() ); - $white = imagecolorallocate($im, 255, 255, 255); + if ($background === false || $textColor === false) { + throw new \Exception('Failed to create avatar image color'); + } imagefilledrectangle($im, 0, 0, $size, $size, $background); - $font = __DIR__ . '/../../../core/fonts/NotoSans-Regular.ttf'; + $font = $this->getFont($text); $fontSize = $size * 0.4; [$x, $y] = $this->imageTTFCenter( $im, $text, $font, (int)$fontSize ); - imagettftext($im, $fontSize, 0, $x, $y, $white, $font, $text); + imagettftext($im, $fontSize, 0, $x, $y, $textColor, $font, $text); ob_start(); imagepng($im); @@ -198,7 +194,7 @@ abstract class Avatar implements IAvatar { /** * Calculate real image ttf center * - * @param resource $image + * @param \GdImage $image * @param string $text text string * @param string $font font path * @param int $size font size @@ -210,7 +206,7 @@ abstract class Avatar implements IAvatar { string $text, string $font, int $size, - $angle = 0 + int $angle = 0, ): array { // Image width & height $xi = imagesx($image); @@ -230,37 +226,6 @@ abstract class Avatar implements IAvatar { return [$x, $y]; } - /** - * Calculate steps between two Colors - * @param object Color $steps start color - * @param object Color $ends end color - * @return array [r,g,b] steps for each color to go from $steps to $ends - */ - private function stepCalc($steps, $ends) { - $step = []; - $step[0] = ($ends[1]->r - $ends[0]->r) / $steps; - $step[1] = ($ends[1]->g - $ends[0]->g) / $steps; - $step[2] = ($ends[1]->b - $ends[0]->b) / $steps; - return $step; - } - - /** - * Convert a string to an integer evenly - * @param string $hash the text to parse - * @param int $maximum the maximum range - * @return int[] between 0 and $maximum - */ - private function mixPalette($steps, $color1, $color2) { - $palette = [$color1]; - $step = $this->stepCalc($steps, [$color1, $color2]); - for ($i = 1; $i < $steps; $i++) { - $r = intval($color1->r + ($step[0] * $i)); - $g = intval($color1->g + ($step[1] * $i)); - $b = intval($color1->b + ($step[2] * $i)); - $palette[] = new Color($r, $g, $b); - } - return $palette; - } /** * Convert a string to an integer evenly @@ -268,7 +233,7 @@ abstract class Avatar implements IAvatar { * @param int $maximum the maximum range * @return int between 0 and $maximum */ - private function hashToInt($hash, $maximum) { + private function hashToInt(string $hash, int $maximum): int { $final = 0; $result = []; @@ -286,10 +251,9 @@ abstract class Avatar implements IAvatar { } /** - * @param string $hash - * @return Color Object containting r g b int in the range [0, 255] + * @return Color Object containing r g b int in the range [0, 255] */ - public function avatarBackgroundColor(string $hash) { + public function avatarBackgroundColor(string $hash): Color { // Normalize hash $hash = strtolower($hash); @@ -309,12 +273,20 @@ abstract class Avatar implements IAvatar { // 3 colors * 6 will result in 18 generated colors $steps = 6; - $palette1 = $this->mixPalette($steps, $red, $yellow); - $palette2 = $this->mixPalette($steps, $yellow, $blue); - $palette3 = $this->mixPalette($steps, $blue, $red); + $palette1 = Color::mixPalette($steps, $red, $yellow); + $palette2 = Color::mixPalette($steps, $yellow, $blue); + $palette3 = Color::mixPalette($steps, $blue, $red); $finalPalette = array_merge($palette1, $palette2, $palette3); return $finalPalette[$this->hashToInt($hash, $steps * 3)]; } + + /** + * Get the language to be used for avatar generation. + * This is used to determine the font to use for the avatar text (e.g. CJK characters). + */ + protected function getAvatarLanguage(): string { + return $this->config->getSystemValueString('default_language', 'en'); + } } diff --git a/lib/private/Avatar/AvatarManager.php b/lib/private/Avatar/AvatarManager.php index 77138085dc9..c68467085f0 100644 --- a/lib/private/Avatar/AvatarManager.php +++ b/lib/private/Avatar/AvatarManager.php @@ -1,37 +1,10 @@ <?php declare(strict_types=1); - /** - * @copyright Copyright (c) 2016, ownCloud, Inc. - * - * @author Arthur Schiwon <blizzz@arthur-schiwon.de> - * @author Christoph Wurst <christoph@winzerhof-wurst.at> - * @author Joas Schilling <coding@schilljs.com> - * @author John Molakvoæ <skjnldsv@protonmail.com> - * @author Julius Härtl <jus@bitgrid.net> - * @author Lukas Reschke <lukas@statuscode.ch> - * @author Michael Weimann <mail@michael-weimann.eu> - * @author Morris Jobke <hey@morrisjobke.de> - * @author Robin Appelman <robin@icewind.nl> - * @author Roeland Jago Douma <roeland@famdouma.nl> - * @author Thomas Müller <thomas.mueller@tmit.eu> - * @author Vincent Petry <vincent@nextcloud.com> - * - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see <http://www.gnu.org/licenses/> - * + * SPDX-FileCopyrightText: 2019-2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-FileCopyrightText: 2016 ownCloud, Inc. + * SPDX-License-Identifier: AGPL-3.0-only */ namespace OC\Avatar; @@ -55,72 +28,42 @@ use Psr\Log\LoggerInterface; * This class implements methods to access Avatar functionality */ class AvatarManager implements IAvatarManager { - - /** @var IUserSession */ - private $userSession; - - /** @var Manager */ - private $userManager; - - /** @var IAppData */ - private $appData; - - /** @var IL10N */ - private $l; - - /** @var LoggerInterface */ - private $logger; - - /** @var IConfig */ - private $config; - - /** @var IAccountManager */ - private $accountManager; - - /** @var KnownUserService */ - private $knownUserService; - public function __construct( - IUserSession $userSession, - Manager $userManager, - IAppData $appData, - IL10N $l, - LoggerInterface $logger, - IConfig $config, - IAccountManager $accountManager, - KnownUserService $knownUserService + private IUserSession $userSession, + private Manager $userManager, + private IAppData $appData, + private IL10N $l, + private LoggerInterface $logger, + private IConfig $config, + private IAccountManager $accountManager, + private KnownUserService $knownUserService, ) { - $this->userSession = $userSession; - $this->userManager = $userManager; - $this->appData = $appData; - $this->l = $l; - $this->logger = $logger; - $this->config = $config; - $this->accountManager = $accountManager; - $this->knownUserService = $knownUserService; } /** * return a user specific instance of \OCP\IAvatar + * + * If the user is disabled a guest avatar will be returned + * * @see \OCP\IAvatar * @param string $userId the ownCloud user id - * @return \OCP\IAvatar * @throws \Exception In case the username is potentially dangerous * @throws NotFoundException In case there is no user folder yet */ - public function getAvatar(string $userId) : IAvatar { + public function getAvatar(string $userId): IAvatar { $user = $this->userManager->get($userId); if ($user === null) { throw new \Exception('user does not exist'); } + if (!$user->isEnabled()) { + return $this->getGuestAvatar($userId); + } + // sanitize userID - fixes casing issue (needed for the filesystem stuff that is done below) $userId = $user->getUID(); - $requestingUser = null; - if ($this->userSession !== null) { - $requestingUser = $this->userSession->getUser(); - } + $requestingUser = $this->userSession->getUser(); try { $folder = $this->appData->getFolder($userId); @@ -136,35 +79,33 @@ class AvatarManager implements IAvatarManager { $avatarScope = ''; } - if ( + switch ($avatarScope) { // v2-private scope hides the avatar from public access and from unknown users - $avatarScope === IAccountManager::SCOPE_PRIVATE - && ( - // accessing from public link - $requestingUser === null - // logged in, but unknown to user - || !$this->knownUserService->isKnownToUser($requestingUser->getUID(), $userId) - )) { - // use a placeholder avatar which caches the generated images - return new PlaceholderAvatar($folder, $user, $this->logger); + case IAccountManager::SCOPE_PRIVATE: + if ($requestingUser !== null && $this->knownUserService->isKnownToUser($requestingUser->getUID(), $userId)) { + return new UserAvatar($folder, $this->l, $user, $this->logger, $this->config); + } + break; + case IAccountManager::SCOPE_LOCAL: + case IAccountManager::SCOPE_FEDERATED: + case IAccountManager::SCOPE_PUBLISHED: + return new UserAvatar($folder, $this->l, $user, $this->logger, $this->config); + default: + // use a placeholder avatar which caches the generated images + return new PlaceholderAvatar($folder, $user, $this->config, $this->logger); } - return new UserAvatar($folder, $this->l, $user, $this->logger, $this->config); + return new PlaceholderAvatar($folder, $user, $this->config, $this->logger); } /** * Clear generated avatars */ - public function clearCachedAvatars() { + public function clearCachedAvatars(): void { $users = $this->config->getUsersForUserValue('avatar', 'generated', 'true'); foreach ($users as $userId) { - try { - $folder = $this->appData->getFolder($userId); - $folder->delete(); - } catch (NotFoundException $e) { - $this->logger->debug("No cache for the user $userId. Ignoring..."); - } - $this->config->setUserValue($userId, 'avatar', 'generated', 'false'); + // This also bumps the avatar version leading to cache invalidation in browsers + $this->getAvatar($userId)->remove(); } } @@ -174,10 +115,10 @@ class AvatarManager implements IAvatarManager { $folder->delete(); } catch (NotFoundException $e) { $this->logger->debug("No cache for the user $userId. Ignoring avatar deletion"); - } catch (NotPermittedException | StorageNotAvailableException $e) { + } catch (NotPermittedException|StorageNotAvailableException $e) { $this->logger->error("Unable to delete user avatars for $userId. gnoring avatar deletion"); } catch (NoUserException $e) { - $this->logger->debug("User $userId not found. gnoring avatar deletion"); + $this->logger->debug("Account $userId not found. Ignoring avatar deletion"); } $this->config->deleteUserValue($userId, 'avatar', 'generated'); } @@ -186,9 +127,8 @@ class AvatarManager implements IAvatarManager { * Returns a GuestAvatar. * * @param string $name The guest name, e.g. "Albert". - * @return IAvatar */ public function getGuestAvatar(string $name): IAvatar { - return new GuestAvatar($name, $this->logger); + return new GuestAvatar($name, $this->config, $this->logger); } } diff --git a/lib/private/Avatar/GuestAvatar.php b/lib/private/Avatar/GuestAvatar.php index f0297b3a93c..c0c7de0c078 100644 --- a/lib/private/Avatar/GuestAvatar.php +++ b/lib/private/Avatar/GuestAvatar.php @@ -3,30 +3,14 @@ declare(strict_types=1); /** - * @copyright Copyright (c) 2018, Michael Weimann <mail@michael-weimann.eu> - * - * @author Joas Schilling <coding@schilljs.com> - * @author Michael Weimann <mail@michael-weimann.eu> - * - * @license GNU AGPL version 3 or any later version - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. - * + * SPDX-FileCopyrightText: 2018 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: AGPL-3.0-or-later */ namespace OC\Avatar; use OCP\Files\SimpleFS\InMemoryFile; +use OCP\Files\SimpleFS\ISimpleFile; +use OCP\IConfig; use Psr\Log\LoggerInterface; /** @@ -34,36 +18,28 @@ use Psr\Log\LoggerInterface; */ class GuestAvatar extends Avatar { /** - * Holds the guest user display name. - * - * @var string - */ - private $userDisplayName; - - /** * GuestAvatar constructor. * * @param string $userDisplayName The guest user display name - * @param LoggerInterface $logger The logger */ - public function __construct(string $userDisplayName, LoggerInterface $logger) { - parent::__construct($logger); - $this->userDisplayName = $userDisplayName; + public function __construct( + private string $userDisplayName, + IConfig $config, + LoggerInterface $logger, + ) { + parent::__construct($config, $logger); } /** * Tests if the user has an avatar. - * - * @return true Guests always have an avatar. */ - public function exists() { + public function exists(): bool { + // Guests always have an avatar. return true; } /** * Returns the guest user display name. - * - * @return string */ public function getDisplayName(): string { return $this->userDisplayName; @@ -73,27 +49,23 @@ class GuestAvatar extends Avatar { * Setting avatars isn't implemented for guests. * * @param \OCP\IImage|resource|string $data - * @return void */ - public function set($data) { + public function set($data): void { // unimplemented for guest user avatars } /** * Removing avatars isn't implemented for guests. */ - public function remove() { + public function remove(bool $silent = false): void { // unimplemented for guest user avatars } /** * Generates an avatar for the guest. - * - * @param int $size The desired image size. - * @return InMemoryFile */ - public function getFile($size) { - $avatar = $this->generateAvatar($this->userDisplayName, $size); + public function getFile(int $size, bool $darkTheme = false): ISimpleFile { + $avatar = $this->generateAvatar($this->userDisplayName, $size, $darkTheme); return new InMemoryFile('avatar.png', $avatar); } @@ -103,9 +75,8 @@ class GuestAvatar extends Avatar { * @param string $feature The changed feature * @param mixed $oldValue The previous value * @param mixed $newValue The new value - * @return void */ - public function userChanged($feature, $oldValue, $newValue) { + public function userChanged(string $feature, $oldValue, $newValue): void { if ($feature === 'displayName') { $this->userDisplayName = $newValue; } @@ -113,8 +84,6 @@ class GuestAvatar extends Avatar { /** * Guests don't have custom avatars. - * - * @return bool */ public function isCustomAvatar(): bool { return false; diff --git a/lib/private/Avatar/PlaceholderAvatar.php b/lib/private/Avatar/PlaceholderAvatar.php index df7a490cbe4..f5f49fb7cb2 100644 --- a/lib/private/Avatar/PlaceholderAvatar.php +++ b/lib/private/Avatar/PlaceholderAvatar.php @@ -3,26 +3,8 @@ declare(strict_types=1); /** - * @copyright Copyright (c) 2018, Michael Weimann <mail@michael-weimann.eu> - * - * @author Joas Schilling <coding@schilljs.com> - * @author Vincent Petry <vincent@nextcloud.com> - * - * @license GNU AGPL version 3 or any later version - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. - * + * SPDX-FileCopyrightText: 2018 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: AGPL-3.0-or-later */ namespace OC\Avatar; @@ -34,7 +16,6 @@ use OCP\Files\SimpleFS\ISimpleFile; use OCP\Files\SimpleFS\ISimpleFolder; use OCP\IConfig; use OCP\IImage; -use OCP\IL10N; use Psr\Log\LoggerInterface; /** @@ -44,37 +25,19 @@ use Psr\Log\LoggerInterface; * for faster retrieval, unlike the GuestAvatar. */ class PlaceholderAvatar extends Avatar { - /** @var ISimpleFolder */ - private $folder; - - /** @var User */ - private $user; - - /** - * UserAvatar constructor. - * - * @param IConfig $config The configuration - * @param ISimpleFolder $folder The avatar files folder - * @param IL10N $l The localization helper - * @param User $user The user this class manages the avatar for - * @param LoggerInterface $logger The logger - */ public function __construct( - ISimpleFolder $folder, - $user, - LoggerInterface $logger) { - parent::__construct($logger); - - $this->folder = $folder; - $this->user = $user; + private ISimpleFolder $folder, + private User $user, + IConfig $config, + LoggerInterface $logger, + ) { + parent::__construct($config, $logger); } /** * Check if an avatar exists for the user - * - * @return bool */ - public function exists() { + public function exists(): bool { return true; } @@ -85,16 +48,15 @@ class PlaceholderAvatar extends Avatar { * @throws \Exception if the provided file is not a jpg or png image * @throws \Exception if the provided image is not valid * @throws NotSquareException if the image is not square - * @return void */ - public function set($data) { + public function set($data): void { // unimplemented for placeholder avatars } /** * Removes the users avatar. */ - public function remove(bool $silent = false) { + public function remove(bool $silent = false): void { $avatars = $this->folder->getDirectoryListing(); foreach ($avatars as $avatar) { @@ -107,21 +69,17 @@ class PlaceholderAvatar extends Avatar { * * If there is no avatar file yet, one is generated. * - * @param int $size - * @return ISimpleFile * @throws NotFoundException * @throws \OCP\Files\NotPermittedException * @throws \OCP\PreConditionNotMetException */ - public function getFile($size) { - $size = (int) $size; - + public function getFile(int $size, bool $darkTheme = false): ISimpleFile { $ext = 'png'; if ($size === -1) { - $path = 'avatar-placeholder.' . $ext; + $path = 'avatar-placeholder' . ($darkTheme ? '-dark' : '') . '.' . $ext; } else { - $path = 'avatar-placeholder.' . $size . '.' . $ext; + $path = 'avatar-placeholder' . ($darkTheme ? '-dark' : '') . '.' . $size . '.' . $ext; } try { @@ -131,8 +89,9 @@ class PlaceholderAvatar extends Avatar { throw new NotFoundException; } - if (!$data = $this->generateAvatarFromSvg($size)) { - $data = $this->generateAvatar($this->getDisplayName(), $size); + $userDisplayName = $this->getDisplayName(); + if (!$data = $this->generateAvatarFromSvg($userDisplayName, $size, $darkTheme)) { + $data = $this->generateAvatar($userDisplayName, $size, $darkTheme); } try { @@ -149,8 +108,6 @@ class PlaceholderAvatar extends Avatar { /** * Returns the user display name. - * - * @return string */ public function getDisplayName(): string { return $this->user->getDisplayName(); @@ -165,14 +122,12 @@ class PlaceholderAvatar extends Avatar { * @throws NotPermittedException * @throws \OCP\PreConditionNotMetException */ - public function userChanged($feature, $oldValue, $newValue) { + public function userChanged(string $feature, $oldValue, $newValue): void { $this->remove(); } /** * Check if the avatar of a user is a custom uploaded one - * - * @return bool */ public function isCustomAvatar(): bool { return false; diff --git a/lib/private/Avatar/UserAvatar.php b/lib/private/Avatar/UserAvatar.php index b46e4816fa2..aca2aa574bc 100644 --- a/lib/private/Avatar/UserAvatar.php +++ b/lib/private/Avatar/UserAvatar.php @@ -3,35 +3,13 @@ declare(strict_types=1); /** - * @copyright Copyright (c) 2018, Michael Weimann <mail@michael-weimann.eu> - * - * @author Arthur Schiwon <blizzz@arthur-schiwon.de> - * @author Christoph Wurst <christoph@winzerhof-wurst.at> - * @author Joas Schilling <coding@schilljs.com> - * @author Michael Weimann <mail@michael-weimann.eu> - * @author Vincent Petry <vincent@nextcloud.com> - * - * @license GNU AGPL version 3 or any later version - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. - * + * SPDX-FileCopyrightText: 2018 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: AGPL-3.0-or-later */ namespace OC\Avatar; use OC\NotSquareException; use OC\User\User; -use OC_Image; use OCP\Files\NotFoundException; use OCP\Files\NotPermittedException; use OCP\Files\SimpleFS\ISimpleFile; @@ -45,46 +23,20 @@ use Psr\Log\LoggerInterface; * This class represents a registered user's avatar. */ class UserAvatar extends Avatar { - /** @var IConfig */ - private $config; - - /** @var ISimpleFolder */ - private $folder; - - /** @var IL10N */ - private $l; - - /** @var User */ - private $user; - - /** - * UserAvatar constructor. - * - * @param IConfig $config The configuration - * @param ISimpleFolder $folder The avatar files folder - * @param IL10N $l The localization helper - * @param User $user The user this class manages the avatar for - * @param LoggerInterface $logger The logger - */ public function __construct( - ISimpleFolder $folder, - IL10N $l, - $user, + private ISimpleFolder $folder, + private IL10N $l, + protected User $user, LoggerInterface $logger, - IConfig $config) { - parent::__construct($logger); - $this->folder = $folder; - $this->l = $l; - $this->user = $user; - $this->config = $config; + IConfig $config, + ) { + parent::__construct($config, $logger); } /** * Check if an avatar exists for the user - * - * @return bool */ - public function exists() { + public function exists(): bool { return $this->folder->fileExists('avatar.jpg') || $this->folder->fileExists('avatar.png'); } @@ -95,9 +47,8 @@ class UserAvatar extends Avatar { * @throws \Exception if the provided file is not a jpg or png image * @throws \Exception if the provided image is not valid * @throws NotSquareException if the image is not square - * @return void */ - public function set($data) { + public function set($data): void { $img = $this->getAvatarImage($data); $data = $img->data(); @@ -123,18 +74,17 @@ class UserAvatar extends Avatar { * Returns an image from several sources. * * @param IImage|resource|string|\GdImage $data An image object, imagedata or path to the avatar - * @return IImage */ - private function getAvatarImage($data) { + private function getAvatarImage($data): IImage { if ($data instanceof IImage) { return $data; } - $img = new OC_Image(); + $img = new \OCP\Image(); if ( - (is_resource($data) && get_resource_type($data) === 'gd') || - (is_object($data) && get_class($data) === \GdImage::class) - ) { + (is_resource($data) && get_resource_type($data) === 'gd') + || (is_object($data) && get_class($data) === \GdImage::class) + ) { $img->setResource($data); } elseif (is_resource($data)) { $img->loadFromFileHandle($data); @@ -157,11 +107,8 @@ class UserAvatar extends Avatar { /** * Returns the avatar image type. - * - * @param IImage $avatar - * @return string */ - private function getAvatarImageType(IImage $avatar) { + private function getAvatarImageType(IImage $avatar): string { $type = substr($avatar->mimeType(), -3); if ($type === 'peg') { $type = 'jpg'; @@ -180,7 +127,7 @@ class UserAvatar extends Avatar { * @throws \Exception if the provided image is not valid * @throws NotSquareException if the image is not square */ - private function validateAvatar(IImage $avatar) { + private function validateAvatar(IImage $avatar): void { $type = $this->getAvatarImageType($avatar); if ($type !== 'jpg' && $type !== 'png') { @@ -198,15 +145,14 @@ class UserAvatar extends Avatar { /** * Removes the users avatar. - * @return void * @throws \OCP\Files\NotPermittedException * @throws \OCP\PreConditionNotMetException */ - public function remove(bool $silent = false) { + public function remove(bool $silent = false): void { $avatars = $this->folder->getDirectoryListing(); $this->config->setUserValue($this->user->getUID(), 'avatar', 'version', - (int) $this->config->getUserValue($this->user->getUID(), 'avatar', 'version', 0) + 1); + (string)((int)$this->config->getUserValue($this->user->getUID(), 'avatar', 'version', '0') + 1)); foreach ($avatars as $avatar) { $avatar->delete(); @@ -220,15 +166,23 @@ class UserAvatar extends Avatar { /** * Get the extension of the avatar. If there is no avatar throw Exception * - * @return string * @throws NotFoundException */ - private function getExtension() { - if ($this->folder->fileExists('avatar.jpg')) { + private function getExtension(bool $generated, bool $darkTheme): string { + if ($darkTheme && $generated) { + $name = 'avatar-dark.'; + } else { + $name = 'avatar.'; + } + + if ($this->folder->fileExists($name . 'jpg')) { return 'jpg'; - } elseif ($this->folder->fileExists('avatar.png')) { + } + + if ($this->folder->fileExists($name . 'png')) { return 'png'; } + throw new NotFoundException; } @@ -237,33 +191,41 @@ class UserAvatar extends Avatar { * * If there is no avatar file yet, one is generated. * - * @param int $size - * @return ISimpleFile * @throws NotFoundException * @throws \OCP\Files\NotPermittedException * @throws \OCP\PreConditionNotMetException */ - public function getFile($size) { - $size = (int) $size; + public function getFile(int $size, bool $darkTheme = false): ISimpleFile { + $generated = $this->folder->fileExists('generated'); try { - $ext = $this->getExtension(); + $ext = $this->getExtension($generated, $darkTheme); } catch (NotFoundException $e) { - if (!$data = $this->generateAvatarFromSvg(1024)) { - $data = $this->generateAvatar($this->getDisplayName(), 1024); + $userDisplayName = $this->getDisplayName(); + if (!$data = $this->generateAvatarFromSvg($userDisplayName, 1024, $darkTheme)) { + $data = $this->generateAvatar($userDisplayName, 1024, $darkTheme); } - $avatar = $this->folder->newFile('avatar.png'); + $avatar = $this->folder->newFile($darkTheme ? 'avatar-dark.png' : 'avatar.png'); $avatar->putContent($data); $ext = 'png'; $this->folder->newFile('generated', ''); $this->config->setUserValue($this->user->getUID(), 'avatar', 'generated', 'true'); + $generated = true; } - if ($size === -1) { - $path = 'avatar.' . $ext; + if ($generated) { + if ($size === -1) { + $path = 'avatar' . ($darkTheme ? '-dark' : '') . '.' . $ext; + } else { + $path = 'avatar' . ($darkTheme ? '-dark' : '') . '.' . $size . '.' . $ext; + } } else { - $path = 'avatar.' . $size . '.' . $ext; + if ($size === -1) { + $path = 'avatar.' . $ext; + } else { + $path = 'avatar.' . $size . '.' . $ext; + } } try { @@ -272,14 +234,13 @@ class UserAvatar extends Avatar { if ($size <= 0) { throw new NotFoundException; } - - // TODO: rework to integrate with the PlaceholderAvatar in a compatible way - if ($this->folder->fileExists('generated')) { - if (!$data = $this->generateAvatarFromSvg($size)) { - $data = $this->generateAvatar($this->getDisplayName(), $size); + if ($generated) { + $userDisplayName = $this->getDisplayName(); + if (!$data = $this->generateAvatarFromSvg($userDisplayName, $size, $darkTheme)) { + $data = $this->generateAvatar($userDisplayName, $size, $darkTheme); } } else { - $avatar = new OC_Image(); + $avatar = new \OCP\Image(); $file = $this->folder->getFile('avatar.' . $ext); $avatar->loadFromData($file->getContent()); $avatar->resize($size); @@ -296,7 +257,7 @@ class UserAvatar extends Avatar { } if ($this->config->getUserValue($this->user->getUID(), 'avatar', 'generated', null) === null) { - $generated = $this->folder->fileExists('generated') ? 'true' : 'false'; + $generated = $generated ? 'true' : 'false'; $this->config->setUserValue($this->user->getUID(), 'avatar', 'generated', $generated); } @@ -305,8 +266,6 @@ class UserAvatar extends Avatar { /** * Returns the user display name. - * - * @return string */ public function getDisplayName(): string { return $this->user->getDisplayName(); @@ -321,7 +280,7 @@ class UserAvatar extends Avatar { * @throws NotPermittedException * @throws \OCP\PreConditionNotMetException */ - public function userChanged($feature, $oldValue, $newValue) { + public function userChanged(string $feature, $oldValue, $newValue): void { // If the avatar is not generated (so an uploaded image) we skip this if (!$this->folder->fileExists('generated')) { return; @@ -332,10 +291,13 @@ class UserAvatar extends Avatar { /** * Check if the avatar of a user is a custom uploaded one - * - * @return bool */ public function isCustomAvatar(): bool { return $this->config->getUserValue($this->user->getUID(), 'avatar', 'generated', 'false') !== 'true'; } + + #[\Override] + protected function getAvatarLanguage(): string { + return $this->config->getUserValue($this->user->getUID(), 'core', 'lang', parent::getAvatarLanguage()); + } } |