aboutsummaryrefslogtreecommitdiffstats
path: root/lib/private/Avatar
diff options
context:
space:
mode:
Diffstat (limited to 'lib/private/Avatar')
-rw-r--r--lib/private/Avatar/Avatar.php292
-rw-r--r--lib/private/Avatar/AvatarManager.php134
-rw-r--r--lib/private/Avatar/GuestAvatar.php91
-rw-r--r--lib/private/Avatar/PlaceholderAvatar.php135
-rw-r--r--lib/private/Avatar/UserAvatar.php303
5 files changed, 955 insertions, 0 deletions
diff --git a/lib/private/Avatar/Avatar.php b/lib/private/Avatar/Avatar.php
new file mode 100644
index 00000000000..dc65c9d5743
--- /dev/null
+++ b/lib/private/Avatar/Avatar.php
@@ -0,0 +1,292 @@
+<?php
+
+declare(strict_types=1);
+
+/**
+ * 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\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 {
+ /**
+ * https://github.com/sebdesign/cap-height -- for 500px height
+ * Automated check: https://codepen.io/skjnldsv/pen/PydLBK/
+ * Noto Sans cap-height is 0.715 and we want a 200px caps height size
+ * (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
+ */
+ 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:#{fgFill}">{letter}</text>
+ </svg>';
+
+ public function __construct(
+ protected IConfig $config,
+ protected LoggerInterface $logger,
+ ) {
+ }
+
+ /**
+ * Returns the user display name.
+ */
+ abstract public function getDisplayName(): string;
+
+ /**
+ * Returns the first letter of the display name, or "?" if no name given.
+ */
+ private function getAvatarText(): string {
+ $displayName = $this->getDisplayName();
+ if (empty($displayName) === true) {
+ return '?';
+ }
+ $firstTwoLetters = array_map(function ($namePart) {
+ return mb_strtoupper(mb_substr($namePart, 0, 1), 'UTF-8');
+ }, explode(' ', $displayName, 2));
+ return implode('', $firstTwoLetters);
+ }
+
+ /**
+ * @inheritdoc
+ */
+ public function get(int $size = 64, bool $darkTheme = false) {
+ try {
+ $file = $this->getFile($size, $darkTheme);
+ } catch (NotFoundException $e) {
+ return false;
+ }
+
+ $avatar = new \OCP\Image();
+ $avatar->loadFromData($file->getContent());
+ return $avatar;
+ }
+
+ /**
+ * {size} = 500
+ * {fill} = hex color to fill
+ * {letter} = Letter to display
+ *
+ * Generate SVG avatar
+ *
+ * @param int $size The requested image size in pixel
+ * @return string
+ *
+ */
+ 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}', '{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
+ */
+ protected function generateAvatarFromSvg(string $userDisplayName, int $size, bool $darkTheme): ?string {
+ if (!extension_loaded('imagick')) {
+ 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 = $this->getFont($text);
+ $svg = $this->getAvatarVector($userDisplayName, $size, $darkTheme);
+ $avatar = new Imagick();
+ $avatar->setFont($font);
+ $avatar->readImageBlob($svg);
+ $avatar->setImageFormat('png');
+ $image = new \OCP\Image();
+ $image->loadFromData((string)$avatar);
+ return $image->data();
+ } catch (\Exception $e) {
+ return null;
+ }
+ }
+
+ /**
+ * Generate png avatar with GD
+ * @throws \Exception when an error occurs in gd calls
+ */
+ protected function generateAvatar(string $userDisplayName, int $size, bool $darkTheme): string {
+ $text = $this->getAvatarText();
+ $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->red(),
+ $backgroundColor->green(),
+ $backgroundColor->blue()
+ );
+ $textColor = imagecolorallocate($im,
+ $textColor->red(),
+ $textColor->green(),
+ $textColor->blue()
+ );
+ if ($background === false || $textColor === false) {
+ throw new \Exception('Failed to create avatar image color');
+ }
+ imagefilledrectangle($im, 0, 0, $size, $size, $background);
+
+ $font = $this->getFont($text);
+
+ $fontSize = $size * 0.4;
+ [$x, $y] = $this->imageTTFCenter(
+ $im, $text, $font, (int)$fontSize
+ );
+
+ imagettftext($im, $fontSize, 0, $x, $y, $textColor, $font, $text);
+
+ ob_start();
+ imagepng($im);
+ $data = ob_get_contents();
+ ob_end_clean();
+
+ return $data;
+ }
+
+ /**
+ * Calculate real image ttf center
+ *
+ * @param \GdImage $image
+ * @param string $text text string
+ * @param string $font font path
+ * @param int $size font size
+ * @param int $angle
+ * @return array
+ */
+ protected function imageTTFCenter(
+ $image,
+ string $text,
+ string $font,
+ int $size,
+ int $angle = 0,
+ ): array {
+ // Image width & height
+ $xi = imagesx($image);
+ $yi = imagesy($image);
+
+ // bounding box
+ $box = imagettfbbox($size, $angle, $font, $text);
+
+ // imagettfbbox can return negative int
+ $xr = abs(max($box[2], $box[4]));
+ $yr = abs(max($box[5], $box[7]));
+
+ // calculate bottom left placement
+ $x = intval(($xi - $xr) / 2);
+ $y = intval(($yi + $yr) / 2);
+
+ return [$x, $y];
+ }
+
+
+ /**
+ * 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 hashToInt(string $hash, int $maximum): int {
+ $final = 0;
+ $result = [];
+
+ // Splitting evenly the string
+ for ($i = 0; $i < strlen($hash); $i++) {
+ // chars in md5 goes up to f, hex:16
+ $result[] = intval(substr($hash, $i, 1), 16) % 16;
+ }
+ // Adds up all results
+ foreach ($result as $value) {
+ $final += $value;
+ }
+ // chars in md5 goes up to f, hex:16
+ return intval($final % $maximum);
+ }
+
+ /**
+ * @return Color Object containing r g b int in the range [0, 255]
+ */
+ public function avatarBackgroundColor(string $hash): Color {
+ // Normalize hash
+ $hash = strtolower($hash);
+
+ // Already a md5 hash?
+ if (preg_match('/^([0-9a-f]{4}-?){8}$/', $hash, $matches) !== 1) {
+ $hash = md5($hash);
+ }
+
+ // Remove unwanted char
+ $hash = preg_replace('/[^0-9a-f]+/', '', $hash);
+
+ $red = new Color(182, 70, 157);
+ $yellow = new Color(221, 203, 85);
+ $blue = new Color(0, 130, 201); // Nextcloud blue
+
+ // Number of steps to go from a color to another
+ // 3 colors * 6 will result in 18 generated colors
+ $steps = 6;
+
+ $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
new file mode 100644
index 00000000000..c68467085f0
--- /dev/null
+++ b/lib/private/Avatar/AvatarManager.php
@@ -0,0 +1,134 @@
+<?php
+
+declare(strict_types=1);
+/**
+ * SPDX-FileCopyrightText: 2019-2024 Nextcloud GmbH and Nextcloud contributors
+ * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
+ * SPDX-License-Identifier: AGPL-3.0-only
+ */
+namespace OC\Avatar;
+
+use OC\KnownUser\KnownUserService;
+use OC\User\Manager;
+use OC\User\NoUserException;
+use OCP\Accounts\IAccountManager;
+use OCP\Accounts\PropertyDoesNotExistException;
+use OCP\Files\IAppData;
+use OCP\Files\NotFoundException;
+use OCP\Files\NotPermittedException;
+use OCP\Files\StorageNotAvailableException;
+use OCP\IAvatar;
+use OCP\IAvatarManager;
+use OCP\IConfig;
+use OCP\IL10N;
+use OCP\IUserSession;
+use Psr\Log\LoggerInterface;
+
+/**
+ * This class implements methods to access Avatar functionality
+ */
+class AvatarManager implements IAvatarManager {
+ public function __construct(
+ private IUserSession $userSession,
+ private Manager $userManager,
+ private IAppData $appData,
+ private IL10N $l,
+ private LoggerInterface $logger,
+ private IConfig $config,
+ private IAccountManager $accountManager,
+ private 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
+ * @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 {
+ $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 = $this->userSession->getUser();
+
+ try {
+ $folder = $this->appData->getFolder($userId);
+ } catch (NotFoundException $e) {
+ $folder = $this->appData->newFolder($userId);
+ }
+
+ try {
+ $account = $this->accountManager->getAccount($user);
+ $avatarProperties = $account->getProperty(IAccountManager::PROPERTY_AVATAR);
+ $avatarScope = $avatarProperties->getScope();
+ } catch (PropertyDoesNotExistException $e) {
+ $avatarScope = '';
+ }
+
+ switch ($avatarScope) {
+ // v2-private scope hides the avatar from public access and from unknown users
+ 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 PlaceholderAvatar($folder, $user, $this->config, $this->logger);
+ }
+
+ /**
+ * Clear generated avatars
+ */
+ public function clearCachedAvatars(): void {
+ $users = $this->config->getUsersForUserValue('avatar', 'generated', 'true');
+ foreach ($users as $userId) {
+ // This also bumps the avatar version leading to cache invalidation in browsers
+ $this->getAvatar($userId)->remove();
+ }
+ }
+
+ public function deleteUserAvatar(string $userId): void {
+ try {
+ $folder = $this->appData->getFolder($userId);
+ $folder->delete();
+ } catch (NotFoundException $e) {
+ $this->logger->debug("No cache for the user $userId. Ignoring avatar deletion");
+ } catch (NotPermittedException|StorageNotAvailableException $e) {
+ $this->logger->error("Unable to delete user avatars for $userId. gnoring avatar deletion");
+ } catch (NoUserException $e) {
+ $this->logger->debug("Account $userId not found. Ignoring avatar deletion");
+ }
+ $this->config->deleteUserValue($userId, 'avatar', 'generated');
+ }
+
+ /**
+ * Returns a GuestAvatar.
+ *
+ * @param string $name The guest name, e.g. "Albert".
+ */
+ public function getGuestAvatar(string $name): IAvatar {
+ return new GuestAvatar($name, $this->config, $this->logger);
+ }
+}
diff --git a/lib/private/Avatar/GuestAvatar.php b/lib/private/Avatar/GuestAvatar.php
new file mode 100644
index 00000000000..c0c7de0c078
--- /dev/null
+++ b/lib/private/Avatar/GuestAvatar.php
@@ -0,0 +1,91 @@
+<?php
+
+declare(strict_types=1);
+
+/**
+ * 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;
+
+/**
+ * This class represents a guest user's avatar.
+ */
+class GuestAvatar extends Avatar {
+ /**
+ * GuestAvatar constructor.
+ *
+ * @param string $userDisplayName The guest user display name
+ */
+ public function __construct(
+ private string $userDisplayName,
+ IConfig $config,
+ LoggerInterface $logger,
+ ) {
+ parent::__construct($config, $logger);
+ }
+
+ /**
+ * Tests if the user has an avatar.
+ */
+ public function exists(): bool {
+ // Guests always have an avatar.
+ return true;
+ }
+
+ /**
+ * Returns the guest user display name.
+ */
+ public function getDisplayName(): string {
+ return $this->userDisplayName;
+ }
+
+ /**
+ * Setting avatars isn't implemented for guests.
+ *
+ * @param \OCP\IImage|resource|string $data
+ */
+ public function set($data): void {
+ // unimplemented for guest user avatars
+ }
+
+ /**
+ * Removing avatars isn't implemented for guests.
+ */
+ public function remove(bool $silent = false): void {
+ // unimplemented for guest user avatars
+ }
+
+ /**
+ * Generates an avatar for the guest.
+ */
+ public function getFile(int $size, bool $darkTheme = false): ISimpleFile {
+ $avatar = $this->generateAvatar($this->userDisplayName, $size, $darkTheme);
+ return new InMemoryFile('avatar.png', $avatar);
+ }
+
+ /**
+ * Updates the display name if changed.
+ *
+ * @param string $feature The changed feature
+ * @param mixed $oldValue The previous value
+ * @param mixed $newValue The new value
+ */
+ public function userChanged(string $feature, $oldValue, $newValue): void {
+ if ($feature === 'displayName') {
+ $this->userDisplayName = $newValue;
+ }
+ }
+
+ /**
+ * Guests don't have custom avatars.
+ */
+ public function isCustomAvatar(): bool {
+ return false;
+ }
+}
diff --git a/lib/private/Avatar/PlaceholderAvatar.php b/lib/private/Avatar/PlaceholderAvatar.php
new file mode 100644
index 00000000000..f5f49fb7cb2
--- /dev/null
+++ b/lib/private/Avatar/PlaceholderAvatar.php
@@ -0,0 +1,135 @@
+<?php
+
+declare(strict_types=1);
+
+/**
+ * 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 OCP\Files\NotFoundException;
+use OCP\Files\NotPermittedException;
+use OCP\Files\SimpleFS\ISimpleFile;
+use OCP\Files\SimpleFS\ISimpleFolder;
+use OCP\IConfig;
+use OCP\IImage;
+use Psr\Log\LoggerInterface;
+
+/**
+ * This class represents a registered user's placeholder avatar.
+ *
+ * It generates an image based on the user's initials and caches it on storage
+ * for faster retrieval, unlike the GuestAvatar.
+ */
+class PlaceholderAvatar extends Avatar {
+ public function __construct(
+ private ISimpleFolder $folder,
+ private User $user,
+ IConfig $config,
+ LoggerInterface $logger,
+ ) {
+ parent::__construct($config, $logger);
+ }
+
+ /**
+ * Check if an avatar exists for the user
+ */
+ public function exists(): bool {
+ return true;
+ }
+
+ /**
+ * Sets the users avatar.
+ *
+ * @param IImage|resource|string $data An image object, imagedata or path to set a new 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
+ */
+ public function set($data): void {
+ // unimplemented for placeholder avatars
+ }
+
+ /**
+ * Removes the users avatar.
+ */
+ public function remove(bool $silent = false): void {
+ $avatars = $this->folder->getDirectoryListing();
+
+ foreach ($avatars as $avatar) {
+ $avatar->delete();
+ }
+ }
+
+ /**
+ * Returns the avatar for an user.
+ *
+ * If there is no avatar file yet, one is generated.
+ *
+ * @throws NotFoundException
+ * @throws \OCP\Files\NotPermittedException
+ * @throws \OCP\PreConditionNotMetException
+ */
+ public function getFile(int $size, bool $darkTheme = false): ISimpleFile {
+ $ext = 'png';
+
+ if ($size === -1) {
+ $path = 'avatar-placeholder' . ($darkTheme ? '-dark' : '') . '.' . $ext;
+ } else {
+ $path = 'avatar-placeholder' . ($darkTheme ? '-dark' : '') . '.' . $size . '.' . $ext;
+ }
+
+ try {
+ $file = $this->folder->getFile($path);
+ } catch (NotFoundException $e) {
+ if ($size <= 0) {
+ throw new NotFoundException;
+ }
+
+ $userDisplayName = $this->getDisplayName();
+ if (!$data = $this->generateAvatarFromSvg($userDisplayName, $size, $darkTheme)) {
+ $data = $this->generateAvatar($userDisplayName, $size, $darkTheme);
+ }
+
+ try {
+ $file = $this->folder->newFile($path);
+ $file->putContent($data);
+ } catch (NotPermittedException $e) {
+ $this->logger->error('Failed to save avatar placeholder for ' . $this->user->getUID());
+ throw new NotFoundException();
+ }
+ }
+
+ return $file;
+ }
+
+ /**
+ * Returns the user display name.
+ */
+ public function getDisplayName(): string {
+ return $this->user->getDisplayName();
+ }
+
+ /**
+ * Handles user changes.
+ *
+ * @param string $feature The changed feature
+ * @param mixed $oldValue The previous value
+ * @param mixed $newValue The new value
+ * @throws NotPermittedException
+ * @throws \OCP\PreConditionNotMetException
+ */
+ public function userChanged(string $feature, $oldValue, $newValue): void {
+ $this->remove();
+ }
+
+ /**
+ * Check if the avatar of a user is a custom uploaded one
+ */
+ public function isCustomAvatar(): bool {
+ return false;
+ }
+}
diff --git a/lib/private/Avatar/UserAvatar.php b/lib/private/Avatar/UserAvatar.php
new file mode 100644
index 00000000000..aca2aa574bc
--- /dev/null
+++ b/lib/private/Avatar/UserAvatar.php
@@ -0,0 +1,303 @@
+<?php
+
+declare(strict_types=1);
+
+/**
+ * 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 OCP\Files\NotFoundException;
+use OCP\Files\NotPermittedException;
+use OCP\Files\SimpleFS\ISimpleFile;
+use OCP\Files\SimpleFS\ISimpleFolder;
+use OCP\IConfig;
+use OCP\IImage;
+use OCP\IL10N;
+use Psr\Log\LoggerInterface;
+
+/**
+ * This class represents a registered user's avatar.
+ */
+class UserAvatar extends Avatar {
+ public function __construct(
+ private ISimpleFolder $folder,
+ private IL10N $l,
+ protected User $user,
+ LoggerInterface $logger,
+ IConfig $config,
+ ) {
+ parent::__construct($config, $logger);
+ }
+
+ /**
+ * Check if an avatar exists for the user
+ */
+ public function exists(): bool {
+ return $this->folder->fileExists('avatar.jpg') || $this->folder->fileExists('avatar.png');
+ }
+
+ /**
+ * Sets the users avatar.
+ *
+ * @param IImage|resource|string $data An image object, imagedata or path to set a new 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
+ */
+ public function set($data): void {
+ $img = $this->getAvatarImage($data);
+ $data = $img->data();
+
+ $this->validateAvatar($img);
+
+ $this->remove(true);
+ $type = $this->getAvatarImageType($img);
+ $file = $this->folder->newFile('avatar.' . $type);
+ $file->putContent($data);
+
+ try {
+ $generated = $this->folder->getFile('generated');
+ $generated->delete();
+ } catch (NotFoundException $e) {
+ //
+ }
+
+ $this->config->setUserValue($this->user->getUID(), 'avatar', 'generated', 'false');
+ $this->user->triggerChange('avatar', $file);
+ }
+
+ /**
+ * Returns an image from several sources.
+ *
+ * @param IImage|resource|string|\GdImage $data An image object, imagedata or path to the avatar
+ */
+ private function getAvatarImage($data): IImage {
+ if ($data instanceof IImage) {
+ return $data;
+ }
+
+ $img = new \OCP\Image();
+ if (
+ (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);
+ } else {
+ try {
+ // detect if it is a path or maybe the images as string
+ $result = @realpath($data);
+ if ($result === false || $result === null) {
+ $img->loadFromData($data);
+ } else {
+ $img->loadFromFile($data);
+ }
+ } catch (\Error $e) {
+ $img->loadFromData($data);
+ }
+ }
+
+ return $img;
+ }
+
+ /**
+ * Returns the avatar image type.
+ */
+ private function getAvatarImageType(IImage $avatar): string {
+ $type = substr($avatar->mimeType(), -3);
+ if ($type === 'peg') {
+ $type = 'jpg';
+ }
+ return $type;
+ }
+
+ /**
+ * Validates an avatar image:
+ * - must be "png" or "jpg"
+ * - must be "valid"
+ * - must be in square format
+ *
+ * @param IImage $avatar The avatar to validate
+ * @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
+ */
+ private function validateAvatar(IImage $avatar): void {
+ $type = $this->getAvatarImageType($avatar);
+
+ if ($type !== 'jpg' && $type !== 'png') {
+ throw new \Exception($this->l->t('Unknown filetype'));
+ }
+
+ if (!$avatar->valid()) {
+ throw new \Exception($this->l->t('Invalid image'));
+ }
+
+ if (!($avatar->height() === $avatar->width())) {
+ throw new NotSquareException($this->l->t('Avatar image is not square'));
+ }
+ }
+
+ /**
+ * Removes the users avatar.
+ * @throws \OCP\Files\NotPermittedException
+ * @throws \OCP\PreConditionNotMetException
+ */
+ public function remove(bool $silent = false): void {
+ $avatars = $this->folder->getDirectoryListing();
+
+ $this->config->setUserValue($this->user->getUID(), 'avatar', 'version',
+ (string)((int)$this->config->getUserValue($this->user->getUID(), 'avatar', 'version', '0') + 1));
+
+ foreach ($avatars as $avatar) {
+ $avatar->delete();
+ }
+ $this->config->setUserValue($this->user->getUID(), 'avatar', 'generated', 'true');
+ if (!$silent) {
+ $this->user->triggerChange('avatar', '');
+ }
+ }
+
+ /**
+ * Get the extension of the avatar. If there is no avatar throw Exception
+ *
+ * @throws NotFoundException
+ */
+ 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';
+ }
+
+ if ($this->folder->fileExists($name . 'png')) {
+ return 'png';
+ }
+
+ throw new NotFoundException;
+ }
+
+ /**
+ * Returns the avatar for an user.
+ *
+ * If there is no avatar file yet, one is generated.
+ *
+ * @throws NotFoundException
+ * @throws \OCP\Files\NotPermittedException
+ * @throws \OCP\PreConditionNotMetException
+ */
+ public function getFile(int $size, bool $darkTheme = false): ISimpleFile {
+ $generated = $this->folder->fileExists('generated');
+
+ try {
+ $ext = $this->getExtension($generated, $darkTheme);
+ } catch (NotFoundException $e) {
+ $userDisplayName = $this->getDisplayName();
+ if (!$data = $this->generateAvatarFromSvg($userDisplayName, 1024, $darkTheme)) {
+ $data = $this->generateAvatar($userDisplayName, 1024, $darkTheme);
+ }
+ $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 ($generated) {
+ if ($size === -1) {
+ $path = 'avatar' . ($darkTheme ? '-dark' : '') . '.' . $ext;
+ } else {
+ $path = 'avatar' . ($darkTheme ? '-dark' : '') . '.' . $size . '.' . $ext;
+ }
+ } else {
+ if ($size === -1) {
+ $path = 'avatar.' . $ext;
+ } else {
+ $path = 'avatar.' . $size . '.' . $ext;
+ }
+ }
+
+ try {
+ $file = $this->folder->getFile($path);
+ } catch (NotFoundException $e) {
+ if ($size <= 0) {
+ throw new NotFoundException;
+ }
+ if ($generated) {
+ $userDisplayName = $this->getDisplayName();
+ if (!$data = $this->generateAvatarFromSvg($userDisplayName, $size, $darkTheme)) {
+ $data = $this->generateAvatar($userDisplayName, $size, $darkTheme);
+ }
+ } else {
+ $avatar = new \OCP\Image();
+ $file = $this->folder->getFile('avatar.' . $ext);
+ $avatar->loadFromData($file->getContent());
+ $avatar->resize($size);
+ $data = $avatar->data();
+ }
+
+ try {
+ $file = $this->folder->newFile($path);
+ $file->putContent($data);
+ } catch (NotPermittedException $e) {
+ $this->logger->error('Failed to save avatar for ' . $this->user->getUID());
+ throw new NotFoundException();
+ }
+ }
+
+ if ($this->config->getUserValue($this->user->getUID(), 'avatar', 'generated', null) === null) {
+ $generated = $generated ? 'true' : 'false';
+ $this->config->setUserValue($this->user->getUID(), 'avatar', 'generated', $generated);
+ }
+
+ return $file;
+ }
+
+ /**
+ * Returns the user display name.
+ */
+ public function getDisplayName(): string {
+ return $this->user->getDisplayName();
+ }
+
+ /**
+ * Handles user changes.
+ *
+ * @param string $feature The changed feature
+ * @param mixed $oldValue The previous value
+ * @param mixed $newValue The new value
+ * @throws NotPermittedException
+ * @throws \OCP\PreConditionNotMetException
+ */
+ 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;
+ }
+
+ $this->remove();
+ }
+
+ /**
+ * Check if the avatar of a user is a custom uploaded one
+ */
+ 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());
+ }
+}