UserAvatar.php 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  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 $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 (is_resource($data) && get_resource_type($data) === 'gd') {
  119. $img->setResource($data);
  120. } elseif (is_resource($data)) {
  121. $img->loadFromFileHandle($data);
  122. } else {
  123. try {
  124. // detect if it is a path or maybe the images as string
  125. $result = @realpath($data);
  126. if ($result === false || $result === null) {
  127. $img->loadFromData($data);
  128. } else {
  129. $img->loadFromFile($data);
  130. }
  131. } catch (\Error $e) {
  132. $img->loadFromData($data);
  133. }
  134. }
  135. return $img;
  136. }
  137. /**
  138. * Returns the avatar image type.
  139. *
  140. * @param IImage $avatar
  141. * @return string
  142. */
  143. private function getAvatarImageType(IImage $avatar) {
  144. $type = substr($avatar->mimeType(), -3);
  145. if ($type === 'peg') {
  146. $type = 'jpg';
  147. }
  148. return $type;
  149. }
  150. /**
  151. * Validates an avatar image:
  152. * - must be "png" or "jpg"
  153. * - must be "valid"
  154. * - must be in square format
  155. *
  156. * @param IImage $avatar The avatar to validate
  157. * @throws \Exception if the provided file is not a jpg or png image
  158. * @throws \Exception if the provided image is not valid
  159. * @throws NotSquareException if the image is not square
  160. */
  161. private function validateAvatar(IImage $avatar) {
  162. $type = $this->getAvatarImageType($avatar);
  163. if ($type !== 'jpg' && $type !== 'png') {
  164. throw new \Exception($this->l->t('Unknown filetype'));
  165. }
  166. if (!$avatar->valid()) {
  167. throw new \Exception($this->l->t('Invalid image'));
  168. }
  169. if (!($avatar->height() === $avatar->width())) {
  170. throw new NotSquareException($this->l->t('Avatar image is not square'));
  171. }
  172. }
  173. /**
  174. * Removes the users avatar.
  175. * @return void
  176. * @throws \OCP\Files\NotPermittedException
  177. * @throws \OCP\PreConditionNotMetException
  178. */
  179. public function remove(bool $silent = false) {
  180. $avatars = $this->folder->getDirectoryListing();
  181. $this->config->setUserValue($this->user->getUID(), 'avatar', 'version',
  182. (int) $this->config->getUserValue($this->user->getUID(), 'avatar', 'version', 0) + 1);
  183. foreach ($avatars as $avatar) {
  184. $avatar->delete();
  185. }
  186. $this->config->setUserValue($this->user->getUID(), 'avatar', 'generated', 'true');
  187. if (!$silent) {
  188. $this->user->triggerChange('avatar', '');
  189. }
  190. }
  191. /**
  192. * Get the extension of the avatar. If there is no avatar throw Exception
  193. *
  194. * @return string
  195. * @throws NotFoundException
  196. */
  197. private function getExtension() {
  198. if ($this->folder->fileExists('avatar.jpg')) {
  199. return 'jpg';
  200. } elseif ($this->folder->fileExists('avatar.png')) {
  201. return 'png';
  202. }
  203. throw new NotFoundException;
  204. }
  205. /**
  206. * Returns the avatar for an user.
  207. *
  208. * If there is no avatar file yet, one is generated.
  209. *
  210. * @param int $size
  211. * @return ISimpleFile
  212. * @throws NotFoundException
  213. * @throws \OCP\Files\NotPermittedException
  214. * @throws \OCP\PreConditionNotMetException
  215. */
  216. public function getFile($size) {
  217. $size = (int) $size;
  218. try {
  219. $ext = $this->getExtension();
  220. } catch (NotFoundException $e) {
  221. if (!$data = $this->generateAvatarFromSvg(1024)) {
  222. $data = $this->generateAvatar($this->getDisplayName(), 1024);
  223. }
  224. $avatar = $this->folder->newFile('avatar.png');
  225. $avatar->putContent($data);
  226. $ext = 'png';
  227. $this->folder->newFile('generated', '');
  228. $this->config->setUserValue($this->user->getUID(), 'avatar', 'generated', 'true');
  229. }
  230. if ($size === -1) {
  231. $path = 'avatar.' . $ext;
  232. } else {
  233. $path = 'avatar.' . $size . '.' . $ext;
  234. }
  235. try {
  236. $file = $this->folder->getFile($path);
  237. } catch (NotFoundException $e) {
  238. if ($size <= 0) {
  239. throw new NotFoundException;
  240. }
  241. // TODO: rework to integrate with the PlaceholderAvatar in a compatible way
  242. if ($this->folder->fileExists('generated')) {
  243. if (!$data = $this->generateAvatarFromSvg($size)) {
  244. $data = $this->generateAvatar($this->getDisplayName(), $size);
  245. }
  246. } else {
  247. $avatar = new OC_Image();
  248. $file = $this->folder->getFile('avatar.' . $ext);
  249. $avatar->loadFromData($file->getContent());
  250. $avatar->resize($size);
  251. $data = $avatar->data();
  252. }
  253. try {
  254. $file = $this->folder->newFile($path);
  255. $file->putContent($data);
  256. } catch (NotPermittedException $e) {
  257. $this->logger->error('Failed to save avatar for ' . $this->user->getUID());
  258. throw new NotFoundException();
  259. }
  260. }
  261. if ($this->config->getUserValue($this->user->getUID(), 'avatar', 'generated', null) === null) {
  262. $generated = $this->folder->fileExists('generated') ? 'true' : 'false';
  263. $this->config->setUserValue($this->user->getUID(), 'avatar', 'generated', $generated);
  264. }
  265. return $file;
  266. }
  267. /**
  268. * Returns the user display name.
  269. *
  270. * @return string
  271. */
  272. public function getDisplayName(): string {
  273. return $this->user->getDisplayName();
  274. }
  275. /**
  276. * Handles user changes.
  277. *
  278. * @param string $feature The changed feature
  279. * @param mixed $oldValue The previous value
  280. * @param mixed $newValue The new value
  281. * @throws NotPermittedException
  282. * @throws \OCP\PreConditionNotMetException
  283. */
  284. public function userChanged($feature, $oldValue, $newValue) {
  285. // If the avatar is not generated (so an uploaded image) we skip this
  286. if (!$this->folder->fileExists('generated')) {
  287. return;
  288. }
  289. $this->remove();
  290. }
  291. /**
  292. * Check if the avatar of a user is a custom uploaded one
  293. *
  294. * @return bool
  295. */
  296. public function isCustomAvatar(): bool {
  297. return $this->config->getUserValue($this->user->getUID(), 'avatar', 'generated', 'false') !== 'true';
  298. }
  299. }