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.9KB

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