UserAvatar.php 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  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. public function __construct(
  44. private ISimpleFolder $folder,
  45. private IL10N $l,
  46. private User $user,
  47. LoggerInterface $logger,
  48. private IConfig $config,
  49. ) {
  50. parent::__construct($logger);
  51. }
  52. /**
  53. * Check if an avatar exists for the user
  54. */
  55. public function exists(): bool {
  56. return $this->folder->fileExists('avatar.jpg') || $this->folder->fileExists('avatar.png');
  57. }
  58. /**
  59. * Sets the users avatar.
  60. *
  61. * @param IImage|resource|string $data An image object, imagedata or path to set a new avatar
  62. * @throws \Exception if the provided file is not a jpg or png image
  63. * @throws \Exception if the provided image is not valid
  64. * @throws NotSquareException if the image is not square
  65. */
  66. public function set($data): void {
  67. $img = $this->getAvatarImage($data);
  68. $data = $img->data();
  69. $this->validateAvatar($img);
  70. $this->remove(true);
  71. $type = $this->getAvatarImageType($img);
  72. $file = $this->folder->newFile('avatar.' . $type);
  73. $file->putContent($data);
  74. try {
  75. $generated = $this->folder->getFile('generated');
  76. $generated->delete();
  77. } catch (NotFoundException $e) {
  78. //
  79. }
  80. $this->config->setUserValue($this->user->getUID(), 'avatar', 'generated', 'false');
  81. $this->user->triggerChange('avatar', $file);
  82. }
  83. /**
  84. * Returns an image from several sources.
  85. *
  86. * @param IImage|resource|string|\GdImage $data An image object, imagedata or path to the avatar
  87. */
  88. private function getAvatarImage($data): IImage {
  89. if ($data instanceof IImage) {
  90. return $data;
  91. }
  92. $img = new \OCP\Image();
  93. if (
  94. (is_resource($data) && get_resource_type($data) === 'gd') ||
  95. (is_object($data) && get_class($data) === \GdImage::class)
  96. ) {
  97. $img->setResource($data);
  98. } elseif (is_resource($data)) {
  99. $img->loadFromFileHandle($data);
  100. } else {
  101. try {
  102. // detect if it is a path or maybe the images as string
  103. $result = @realpath($data);
  104. if ($result === false || $result === null) {
  105. $img->loadFromData($data);
  106. } else {
  107. $img->loadFromFile($data);
  108. }
  109. } catch (\Error $e) {
  110. $img->loadFromData($data);
  111. }
  112. }
  113. return $img;
  114. }
  115. /**
  116. * Returns the avatar image type.
  117. */
  118. private function getAvatarImageType(IImage $avatar): string {
  119. $type = substr($avatar->mimeType(), -3);
  120. if ($type === 'peg') {
  121. $type = 'jpg';
  122. }
  123. return $type;
  124. }
  125. /**
  126. * Validates an avatar image:
  127. * - must be "png" or "jpg"
  128. * - must be "valid"
  129. * - must be in square format
  130. *
  131. * @param IImage $avatar The avatar to validate
  132. * @throws \Exception if the provided file is not a jpg or png image
  133. * @throws \Exception if the provided image is not valid
  134. * @throws NotSquareException if the image is not square
  135. */
  136. private function validateAvatar(IImage $avatar): void {
  137. $type = $this->getAvatarImageType($avatar);
  138. if ($type !== 'jpg' && $type !== 'png') {
  139. throw new \Exception($this->l->t('Unknown filetype'));
  140. }
  141. if (!$avatar->valid()) {
  142. throw new \Exception($this->l->t('Invalid image'));
  143. }
  144. if (!($avatar->height() === $avatar->width())) {
  145. throw new NotSquareException($this->l->t('Avatar image is not square'));
  146. }
  147. }
  148. /**
  149. * Removes the users avatar.
  150. * @throws \OCP\Files\NotPermittedException
  151. * @throws \OCP\PreConditionNotMetException
  152. */
  153. public function remove(bool $silent = false): void {
  154. $avatars = $this->folder->getDirectoryListing();
  155. $this->config->setUserValue($this->user->getUID(), 'avatar', 'version',
  156. (string)((int)$this->config->getUserValue($this->user->getUID(), 'avatar', 'version', '0') + 1));
  157. foreach ($avatars as $avatar) {
  158. $avatar->delete();
  159. }
  160. $this->config->setUserValue($this->user->getUID(), 'avatar', 'generated', 'true');
  161. if (!$silent) {
  162. $this->user->triggerChange('avatar', '');
  163. }
  164. }
  165. /**
  166. * Get the extension of the avatar. If there is no avatar throw Exception
  167. *
  168. * @throws NotFoundException
  169. */
  170. private function getExtension(bool $generated, bool $darkTheme): string {
  171. if ($darkTheme && !$generated) {
  172. if ($this->folder->fileExists('avatar-dark.jpg')) {
  173. return 'jpg';
  174. } elseif ($this->folder->fileExists('avatar-dark.png')) {
  175. return 'png';
  176. }
  177. }
  178. if ($this->folder->fileExists('avatar.jpg')) {
  179. return 'jpg';
  180. } elseif ($this->folder->fileExists('avatar.png')) {
  181. return 'png';
  182. }
  183. throw new NotFoundException;
  184. }
  185. /**
  186. * Returns the avatar for an user.
  187. *
  188. * If there is no avatar file yet, one is generated.
  189. *
  190. * @throws NotFoundException
  191. * @throws \OCP\Files\NotPermittedException
  192. * @throws \OCP\PreConditionNotMetException
  193. */
  194. public function getFile(int $size, bool $darkTheme = false): ISimpleFile {
  195. $generated = $this->folder->fileExists('generated');
  196. try {
  197. $ext = $this->getExtension($generated, $darkTheme);
  198. } catch (NotFoundException $e) {
  199. if (!$data = $this->generateAvatarFromSvg(1024, $darkTheme)) {
  200. $data = $this->generateAvatar($this->getDisplayName(), 1024, $darkTheme);
  201. }
  202. $avatar = $this->folder->newFile($darkTheme ? 'avatar-dark.png' : 'avatar.png');
  203. $avatar->putContent($data);
  204. $ext = 'png';
  205. $this->folder->newFile('generated', '');
  206. $this->config->setUserValue($this->user->getUID(), 'avatar', 'generated', 'true');
  207. $generated = true;
  208. }
  209. if ($generated) {
  210. if ($size === -1) {
  211. $path = 'avatar' . ($darkTheme ? '-dark' : '') . '.' . $ext;
  212. } else {
  213. $path = 'avatar' . ($darkTheme ? '-dark' : '') . '.' . $size . '.' . $ext;
  214. }
  215. } else {
  216. if ($size === -1) {
  217. $path = 'avatar.' . $ext;
  218. } else {
  219. $path = 'avatar.' . $size . '.' . $ext;
  220. }
  221. }
  222. try {
  223. $file = $this->folder->getFile($path);
  224. } catch (NotFoundException $e) {
  225. if ($size <= 0) {
  226. throw new NotFoundException;
  227. }
  228. if ($generated) {
  229. if (!$data = $this->generateAvatarFromSvg($size, $darkTheme)) {
  230. $data = $this->generateAvatar($this->getDisplayName(), $size, $darkTheme);
  231. }
  232. } else {
  233. $avatar = new \OCP\Image();
  234. $file = $this->folder->getFile('avatar.' . $ext);
  235. $avatar->loadFromData($file->getContent());
  236. $avatar->resize($size);
  237. $data = $avatar->data();
  238. }
  239. try {
  240. $file = $this->folder->newFile($path);
  241. $file->putContent($data);
  242. } catch (NotPermittedException $e) {
  243. $this->logger->error('Failed to save avatar for ' . $this->user->getUID());
  244. throw new NotFoundException();
  245. }
  246. }
  247. if ($this->config->getUserValue($this->user->getUID(), 'avatar', 'generated', null) === null) {
  248. $generated = $generated ? 'true' : 'false';
  249. $this->config->setUserValue($this->user->getUID(), 'avatar', 'generated', $generated);
  250. }
  251. return $file;
  252. }
  253. /**
  254. * Returns the user display name.
  255. */
  256. public function getDisplayName(): string {
  257. return $this->user->getDisplayName();
  258. }
  259. /**
  260. * Handles user changes.
  261. *
  262. * @param string $feature The changed feature
  263. * @param mixed $oldValue The previous value
  264. * @param mixed $newValue The new value
  265. * @throws NotPermittedException
  266. * @throws \OCP\PreConditionNotMetException
  267. */
  268. public function userChanged(string $feature, $oldValue, $newValue): void {
  269. // If the avatar is not generated (so an uploaded image) we skip this
  270. if (!$this->folder->fileExists('generated')) {
  271. return;
  272. }
  273. $this->remove();
  274. }
  275. /**
  276. * Check if the avatar of a user is a custom uploaded one
  277. */
  278. public function isCustomAvatar(): bool {
  279. return $this->config->getUserValue($this->user->getUID(), 'avatar', 'generated', 'false') !== 'true';
  280. }
  281. }