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.

337 lines
8.6 KiB

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