UserAvatar.php 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  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(): string {
  189. if ($this->folder->fileExists('avatar.jpg')) {
  190. return 'jpg';
  191. } elseif ($this->folder->fileExists('avatar.png')) {
  192. return 'png';
  193. }
  194. throw new NotFoundException;
  195. }
  196. /**
  197. * Returns the avatar for an user.
  198. *
  199. * If there is no avatar file yet, one is generated.
  200. *
  201. * @param int $size
  202. * @return ISimpleFile
  203. * @throws NotFoundException
  204. * @throws \OCP\Files\NotPermittedException
  205. * @throws \OCP\PreConditionNotMetException
  206. */
  207. public function getFile(int $size): ISimpleFile {
  208. try {
  209. $ext = $this->getExtension();
  210. } catch (NotFoundException $e) {
  211. if (!$data = $this->generateAvatarFromSvg(1024)) {
  212. $data = $this->generateAvatar($this->getDisplayName(), 1024);
  213. }
  214. $avatar = $this->folder->newFile('avatar.png');
  215. $avatar->putContent($data);
  216. $ext = 'png';
  217. $this->folder->newFile('generated', '');
  218. $this->config->setUserValue($this->user->getUID(), 'avatar', 'generated', 'true');
  219. }
  220. if ($size === -1) {
  221. $path = 'avatar.' . $ext;
  222. } else {
  223. $path = 'avatar.' . $size . '.' . $ext;
  224. }
  225. try {
  226. $file = $this->folder->getFile($path);
  227. } catch (NotFoundException $e) {
  228. if ($size <= 0) {
  229. throw new NotFoundException;
  230. }
  231. // TODO: rework to integrate with the PlaceholderAvatar in a compatible way
  232. if ($this->folder->fileExists('generated')) {
  233. if (!$data = $this->generateAvatarFromSvg($size)) {
  234. $data = $this->generateAvatar($this->getDisplayName(), $size);
  235. }
  236. } else {
  237. $avatar = new \OCP\Image();
  238. $file = $this->folder->getFile('avatar.' . $ext);
  239. $avatar->loadFromData($file->getContent());
  240. $avatar->resize($size);
  241. $data = $avatar->data();
  242. }
  243. try {
  244. $file = $this->folder->newFile($path);
  245. $file->putContent($data);
  246. } catch (NotPermittedException $e) {
  247. $this->logger->error('Failed to save avatar for ' . $this->user->getUID());
  248. throw new NotFoundException();
  249. }
  250. }
  251. if ($this->config->getUserValue($this->user->getUID(), 'avatar', 'generated', null) === null) {
  252. $generated = $this->folder->fileExists('generated') ? 'true' : 'false';
  253. $this->config->setUserValue($this->user->getUID(), 'avatar', 'generated', $generated);
  254. }
  255. return $file;
  256. }
  257. /**
  258. * Returns the user display name.
  259. */
  260. public function getDisplayName(): string {
  261. return $this->user->getDisplayName();
  262. }
  263. /**
  264. * Handles user changes.
  265. *
  266. * @param string $feature The changed feature
  267. * @param mixed $oldValue The previous value
  268. * @param mixed $newValue The new value
  269. * @throws NotPermittedException
  270. * @throws \OCP\PreConditionNotMetException
  271. */
  272. public function userChanged(string $feature, $oldValue, $newValue): void {
  273. // If the avatar is not generated (so an uploaded image) we skip this
  274. if (!$this->folder->fileExists('generated')) {
  275. return;
  276. }
  277. $this->remove();
  278. }
  279. /**
  280. * Check if the avatar of a user is a custom uploaded one
  281. */
  282. public function isCustomAvatar(): bool {
  283. return $this->config->getUserValue($this->user->getUID(), 'avatar', 'generated', 'false') !== 'true';
  284. }
  285. }