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.

331 lines
8.3 KiB

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