You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

UserAvatar.php 8.4KB

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