UserAvatar.php 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * @copyright Copyright (c) 2018, Michael Weimann <mail@michael-weimann.eu>
  5. *
  6. * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
  7. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  8. * @author Joas Schilling <coding@schilljs.com>
  9. * @author Michael Weimann <mail@michael-weimann.eu>
  10. * @author Vincent Petry <vincent@nextcloud.com>
  11. *
  12. * @license GNU AGPL version 3 or any later version
  13. *
  14. * This program is free software: you can redistribute it and/or modify
  15. * it under the terms of the GNU Affero General Public License as
  16. * published by the Free Software Foundation, either version 3 of the
  17. * License, or (at your option) any later version.
  18. *
  19. * This program is distributed in the hope that it will be useful,
  20. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  21. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  22. * GNU Affero General Public License for more details.
  23. *
  24. * You should have received a copy of the GNU Affero General Public License
  25. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  26. *
  27. */
  28. namespace OC\Avatar;
  29. use OC\NotSquareException;
  30. use OC\User\User;
  31. use OCP\Files\NotFoundException;
  32. use OCP\Files\NotPermittedException;
  33. use OCP\Files\SimpleFS\ISimpleFile;
  34. use OCP\Files\SimpleFS\ISimpleFolder;
  35. use OCP\IConfig;
  36. use OCP\IImage;
  37. use OCP\IL10N;
  38. use Psr\Log\LoggerInterface;
  39. /**
  40. * This class represents a registered user's avatar.
  41. */
  42. class UserAvatar extends Avatar {
  43. private IConfig $config;
  44. private ISimpleFolder $folder;
  45. private IL10N $l;
  46. private User $user;
  47. /**
  48. * UserAvatar constructor.
  49. *
  50. * @param IConfig $config The configuration
  51. * @param ISimpleFolder $folder The avatar files folder
  52. * @param IL10N $l The localization helper
  53. * @param User $user The user this class manages the avatar for
  54. * @param LoggerInterface $logger The logger
  55. */
  56. public function __construct(
  57. ISimpleFolder $folder,
  58. IL10N $l,
  59. User $user,
  60. LoggerInterface $logger,
  61. IConfig $config) {
  62. parent::__construct($logger);
  63. $this->folder = $folder;
  64. $this->l = $l;
  65. $this->user = $user;
  66. $this->config = $config;
  67. }
  68. /**
  69. * Check if an avatar exists for the user
  70. */
  71. public function exists(): bool {
  72. return $this->folder->fileExists('avatar.jpg') || $this->folder->fileExists('avatar.png');
  73. }
  74. /**
  75. * Sets the users avatar.
  76. *
  77. * @param IImage|resource|string $data An image object, imagedata or path to set a new avatar
  78. * @throws \Exception if the provided file is not a jpg or png image
  79. * @throws \Exception if the provided image is not valid
  80. * @throws NotSquareException if the image is not square
  81. * @return void
  82. */
  83. public function set($data): void {
  84. $img = $this->getAvatarImage($data);
  85. $data = $img->data();
  86. $this->validateAvatar($img);
  87. $this->remove(true);
  88. $type = $this->getAvatarImageType($img);
  89. $file = $this->folder->newFile('avatar.' . $type);
  90. $file->putContent($data);
  91. try {
  92. $generated = $this->folder->getFile('generated');
  93. $generated->delete();
  94. } catch (NotFoundException $e) {
  95. //
  96. }
  97. $this->config->setUserValue($this->user->getUID(), 'avatar', 'generated', 'false');
  98. $this->user->triggerChange('avatar', $file);
  99. }
  100. /**
  101. * Returns an image from several sources.
  102. *
  103. * @param IImage|resource|string|\GdImage $data An image object, imagedata or path to the avatar
  104. * @return IImage
  105. */
  106. private function getAvatarImage($data): IImage {
  107. if ($data instanceof IImage) {
  108. return $data;
  109. }
  110. $img = new \OCP\Image();
  111. if (
  112. (is_resource($data) && get_resource_type($data) === 'gd') ||
  113. (is_object($data) && get_class($data) === \GdImage::class)
  114. ) {
  115. $img->setResource($data);
  116. } elseif (is_resource($data)) {
  117. $img->loadFromFileHandle($data);
  118. } else {
  119. try {
  120. // detect if it is a path or maybe the images as string
  121. $result = @realpath($data);
  122. if ($result === false || $result === null) {
  123. $img->loadFromData($data);
  124. } else {
  125. $img->loadFromFile($data);
  126. }
  127. } catch (\Error $e) {
  128. $img->loadFromData($data);
  129. }
  130. }
  131. return $img;
  132. }
  133. /**
  134. * Returns the avatar image type.
  135. */
  136. private function getAvatarImageType(IImage $avatar): string {
  137. $type = substr($avatar->mimeType(), -3);
  138. if ($type === 'peg') {
  139. $type = 'jpg';
  140. }
  141. return $type;
  142. }
  143. /**
  144. * Validates an avatar image:
  145. * - must be "png" or "jpg"
  146. * - must be "valid"
  147. * - must be in square format
  148. *
  149. * @param IImage $avatar The avatar to validate
  150. * @throws \Exception if the provided file is not a jpg or png image
  151. * @throws \Exception if the provided image is not valid
  152. * @throws NotSquareException if the image is not square
  153. */
  154. private function validateAvatar(IImage $avatar): void {
  155. $type = $this->getAvatarImageType($avatar);
  156. if ($type !== 'jpg' && $type !== 'png') {
  157. throw new \Exception($this->l->t('Unknown filetype'));
  158. }
  159. if (!$avatar->valid()) {
  160. throw new \Exception($this->l->t('Invalid image'));
  161. }
  162. if (!($avatar->height() === $avatar->width())) {
  163. throw new NotSquareException($this->l->t('Avatar image is not square'));
  164. }
  165. }
  166. /**
  167. * Removes the users avatar.
  168. * @throws \OCP\Files\NotPermittedException
  169. * @throws \OCP\PreConditionNotMetException
  170. */
  171. public function remove(bool $silent = false): void {
  172. $avatars = $this->folder->getDirectoryListing();
  173. $this->config->setUserValue($this->user->getUID(), 'avatar', 'version',
  174. (string)((int)$this->config->getUserValue($this->user->getUID(), 'avatar', 'version', '0') + 1));
  175. foreach ($avatars as $avatar) {
  176. $avatar->delete();
  177. }
  178. $this->config->setUserValue($this->user->getUID(), 'avatar', 'generated', 'true');
  179. if (!$silent) {
  180. $this->user->triggerChange('avatar', '');
  181. }
  182. }
  183. /**
  184. * Get the extension of the avatar. If there is no avatar throw Exception
  185. *
  186. * @throws NotFoundException
  187. */
  188. private function getExtension(bool $generated, bool $darkTheme): string {
  189. if ($darkTheme && !$generated) {
  190. if ($this->folder->fileExists('avatar-dark.jpg')) {
  191. return 'jpg';
  192. } elseif ($this->folder->fileExists('avatar-dark.png')) {
  193. return 'png';
  194. }
  195. }
  196. if ($this->folder->fileExists('avatar.jpg')) {
  197. return 'jpg';
  198. } elseif ($this->folder->fileExists('avatar.png')) {
  199. return 'png';
  200. }
  201. throw new NotFoundException;
  202. }
  203. /**
  204. * Returns the avatar for an user.
  205. *
  206. * If there is no avatar file yet, one is generated.
  207. *
  208. * @param int $size
  209. * @return ISimpleFile
  210. * @throws NotFoundException
  211. * @throws \OCP\Files\NotPermittedException
  212. * @throws \OCP\PreConditionNotMetException
  213. */
  214. public function getFile(int $size, bool $darkTheme = false): ISimpleFile {
  215. $generated = $this->folder->fileExists('generated');
  216. try {
  217. $ext = $this->getExtension($generated, $darkTheme);
  218. } catch (NotFoundException $e) {
  219. if (!$data = $this->generateAvatarFromSvg(1024, $darkTheme)) {
  220. $data = $this->generateAvatar($this->getDisplayName(), 1024, $darkTheme);
  221. }
  222. $avatar = $this->folder->newFile($darkTheme ? 'avatar-dark.png' : 'avatar.png');
  223. $avatar->putContent($data);
  224. $ext = 'png';
  225. $this->folder->newFile('generated', '');
  226. $this->config->setUserValue($this->user->getUID(), 'avatar', 'generated', 'true');
  227. $generated = true;
  228. }
  229. if ($generated) {
  230. if ($size === -1) {
  231. $path = 'avatar' . ($darkTheme ? '-dark' : '') . '.' . $ext;
  232. } else {
  233. $path = 'avatar' . ($darkTheme ? '-dark' : '') . '.' . $size . '.' . $ext;
  234. }
  235. } else {
  236. if ($size === -1) {
  237. $path = 'avatar.' . $ext;
  238. } else {
  239. $path = 'avatar.' . $size . '.' . $ext;
  240. }
  241. }
  242. try {
  243. $file = $this->folder->getFile($path);
  244. } catch (NotFoundException $e) {
  245. if ($size <= 0) {
  246. throw new NotFoundException;
  247. }
  248. if ($generated) {
  249. if (!$data = $this->generateAvatarFromSvg($size, $darkTheme)) {
  250. $data = $this->generateAvatar($this->getDisplayName(), $size, $darkTheme);
  251. }
  252. } else {
  253. $avatar = new \OCP\Image();
  254. $file = $this->folder->getFile('avatar.' . $ext);
  255. $avatar->loadFromData($file->getContent());
  256. $avatar->resize($size);
  257. $data = $avatar->data();
  258. }
  259. try {
  260. $file = $this->folder->newFile($path);
  261. $file->putContent($data);
  262. } catch (NotPermittedException $e) {
  263. $this->logger->error('Failed to save avatar for ' . $this->user->getUID());
  264. throw new NotFoundException();
  265. }
  266. }
  267. if ($this->config->getUserValue($this->user->getUID(), 'avatar', 'generated', null) === null) {
  268. $generated = $generated ? 'true' : 'false';
  269. $this->config->setUserValue($this->user->getUID(), 'avatar', 'generated', $generated);
  270. }
  271. return $file;
  272. }
  273. /**
  274. * Returns the user display name.
  275. */
  276. public function getDisplayName(): string {
  277. return $this->user->getDisplayName();
  278. }
  279. /**
  280. * Handles user changes.
  281. *
  282. * @param string $feature The changed feature
  283. * @param mixed $oldValue The previous value
  284. * @param mixed $newValue The new value
  285. * @throws NotPermittedException
  286. * @throws \OCP\PreConditionNotMetException
  287. */
  288. public function userChanged(string $feature, $oldValue, $newValue): void {
  289. // If the avatar is not generated (so an uploaded image) we skip this
  290. if (!$this->folder->fileExists('generated')) {
  291. return;
  292. }
  293. $this->remove();
  294. }
  295. /**
  296. * Check if the avatar of a user is a custom uploaded one
  297. */
  298. public function isCustomAvatar(): bool {
  299. return $this->config->getUserValue($this->user->getUID(), 'avatar', 'generated', 'false') !== 'true';
  300. }
  301. }