1
0

AvatarController.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  5. * SPDX-License-Identifier: AGPL-3.0-only
  6. */
  7. namespace OC\Core\Controller;
  8. use OC\AppFramework\Utility\TimeFactory;
  9. use OCP\AppFramework\Controller;
  10. use OCP\AppFramework\Http;
  11. use OCP\AppFramework\Http\Attribute\FrontpageRoute;
  12. use OCP\AppFramework\Http\DataDisplayResponse;
  13. use OCP\AppFramework\Http\FileDisplayResponse;
  14. use OCP\AppFramework\Http\JSONResponse;
  15. use OCP\AppFramework\Http\Response;
  16. use OCP\Files\File;
  17. use OCP\Files\IRootFolder;
  18. use OCP\IAvatarManager;
  19. use OCP\ICache;
  20. use OCP\IL10N;
  21. use OCP\IRequest;
  22. use OCP\IUserManager;
  23. use Psr\Log\LoggerInterface;
  24. /**
  25. * Class AvatarController
  26. *
  27. * @package OC\Core\Controller
  28. */
  29. class AvatarController extends Controller {
  30. public function __construct(
  31. string $appName,
  32. IRequest $request,
  33. protected IAvatarManager $avatarManager,
  34. protected ICache $cache,
  35. protected IL10N $l10n,
  36. protected IUserManager $userManager,
  37. protected IRootFolder $rootFolder,
  38. protected LoggerInterface $logger,
  39. protected ?string $userId,
  40. protected TimeFactory $timeFactory,
  41. protected GuestAvatarController $guestAvatarController,
  42. ) {
  43. parent::__construct($appName, $request);
  44. }
  45. /**
  46. * @NoAdminRequired
  47. * @NoCSRFRequired
  48. * @NoSameSiteCookieRequired
  49. * @PublicPage
  50. *
  51. * Get the dark avatar
  52. *
  53. * @param string $userId ID of the user
  54. * @param int $size Size of the avatar
  55. * @param bool $guestFallback Fallback to guest avatar if not found
  56. * @return FileDisplayResponse<Http::STATUS_OK|Http::STATUS_CREATED, array{Content-Type: string, X-NC-IsCustomAvatar: int}>|JSONResponse<Http::STATUS_NOT_FOUND, array<empty>, array{}>|Response<Http::STATUS_INTERNAL_SERVER_ERROR, array{}>
  57. *
  58. * 200: Avatar returned
  59. * 201: Avatar returned
  60. * 404: Avatar not found
  61. */
  62. #[FrontpageRoute(verb: 'GET', url: '/avatar/{userId}/{size}/dark')]
  63. public function getAvatarDark(string $userId, int $size, bool $guestFallback = false) {
  64. if ($size <= 64) {
  65. if ($size !== 64) {
  66. $this->logger->debug('Avatar requested in deprecated size ' . $size);
  67. }
  68. $size = 64;
  69. } else {
  70. if ($size !== 512) {
  71. $this->logger->debug('Avatar requested in deprecated size ' . $size);
  72. }
  73. $size = 512;
  74. }
  75. try {
  76. $avatar = $this->avatarManager->getAvatar($userId);
  77. $avatarFile = $avatar->getFile($size, true);
  78. $response = new FileDisplayResponse(
  79. $avatarFile,
  80. Http::STATUS_OK,
  81. ['Content-Type' => $avatarFile->getMimeType(), 'X-NC-IsCustomAvatar' => (int)$avatar->isCustomAvatar()]
  82. );
  83. } catch (\Exception $e) {
  84. if ($guestFallback) {
  85. return $this->guestAvatarController->getAvatarDark($userId, (string)$size);
  86. }
  87. return new JSONResponse([], Http::STATUS_NOT_FOUND);
  88. }
  89. // Cache for 1 day
  90. $response->cacheFor(60 * 60 * 24, false, true);
  91. return $response;
  92. }
  93. /**
  94. * @NoAdminRequired
  95. * @NoCSRFRequired
  96. * @NoSameSiteCookieRequired
  97. * @PublicPage
  98. *
  99. * Get the avatar
  100. *
  101. * @param string $userId ID of the user
  102. * @param int $size Size of the avatar
  103. * @param bool $guestFallback Fallback to guest avatar if not found
  104. * @return FileDisplayResponse<Http::STATUS_OK|Http::STATUS_CREATED, array{Content-Type: string, X-NC-IsCustomAvatar: int}>|JSONResponse<Http::STATUS_NOT_FOUND, array<empty>, array{}>|Response<Http::STATUS_INTERNAL_SERVER_ERROR, array{}>
  105. *
  106. * 200: Avatar returned
  107. * 201: Avatar returned
  108. * 404: Avatar not found
  109. */
  110. #[FrontpageRoute(verb: 'GET', url: '/avatar/{userId}/{size}')]
  111. public function getAvatar(string $userId, int $size, bool $guestFallback = false) {
  112. if ($size <= 64) {
  113. if ($size !== 64) {
  114. $this->logger->debug('Avatar requested in deprecated size ' . $size);
  115. }
  116. $size = 64;
  117. } else {
  118. if ($size !== 512) {
  119. $this->logger->debug('Avatar requested in deprecated size ' . $size);
  120. }
  121. $size = 512;
  122. }
  123. try {
  124. $avatar = $this->avatarManager->getAvatar($userId);
  125. $avatarFile = $avatar->getFile($size);
  126. $response = new FileDisplayResponse(
  127. $avatarFile,
  128. Http::STATUS_OK,
  129. ['Content-Type' => $avatarFile->getMimeType(), 'X-NC-IsCustomAvatar' => (int)$avatar->isCustomAvatar()]
  130. );
  131. } catch (\Exception $e) {
  132. if ($guestFallback) {
  133. return $this->guestAvatarController->getAvatar($userId, (string)$size);
  134. }
  135. return new JSONResponse([], Http::STATUS_NOT_FOUND);
  136. }
  137. // Cache for 1 day
  138. $response->cacheFor(60 * 60 * 24, false, true);
  139. return $response;
  140. }
  141. /**
  142. * @NoAdminRequired
  143. */
  144. #[FrontpageRoute(verb: 'POST', url: '/avatar/')]
  145. public function postAvatar(?string $path = null): JSONResponse {
  146. $files = $this->request->getUploadedFile('files');
  147. if (isset($path)) {
  148. $path = stripslashes($path);
  149. $userFolder = $this->rootFolder->getUserFolder($this->userId);
  150. /** @var File $node */
  151. $node = $userFolder->get($path);
  152. if (!($node instanceof File)) {
  153. return new JSONResponse(['data' => ['message' => $this->l10n->t('Please select a file.')]]);
  154. }
  155. if ($node->getSize() > 20 * 1024 * 1024) {
  156. return new JSONResponse(
  157. ['data' => ['message' => $this->l10n->t('File is too big')]],
  158. Http::STATUS_BAD_REQUEST
  159. );
  160. }
  161. if ($node->getMimeType() !== 'image/jpeg' && $node->getMimeType() !== 'image/png') {
  162. return new JSONResponse(
  163. ['data' => ['message' => $this->l10n->t('The selected file is not an image.')]],
  164. Http::STATUS_BAD_REQUEST
  165. );
  166. }
  167. try {
  168. $content = $node->getContent();
  169. } catch (\OCP\Files\NotPermittedException $e) {
  170. return new JSONResponse(
  171. ['data' => ['message' => $this->l10n->t('The selected file cannot be read.')]],
  172. Http::STATUS_BAD_REQUEST
  173. );
  174. }
  175. } elseif (!is_null($files)) {
  176. if (
  177. $files['error'][0] === 0 &&
  178. is_uploaded_file($files['tmp_name'][0]) &&
  179. !\OC\Files\Filesystem::isFileBlacklisted($files['tmp_name'][0])
  180. ) {
  181. if ($files['size'][0] > 20 * 1024 * 1024) {
  182. return new JSONResponse(
  183. ['data' => ['message' => $this->l10n->t('File is too big')]],
  184. Http::STATUS_BAD_REQUEST
  185. );
  186. }
  187. $this->cache->set('avatar_upload', file_get_contents($files['tmp_name'][0]), 7200);
  188. $content = $this->cache->get('avatar_upload');
  189. unlink($files['tmp_name'][0]);
  190. } else {
  191. $phpFileUploadErrors = [
  192. UPLOAD_ERR_OK => $this->l10n->t('The file was uploaded'),
  193. UPLOAD_ERR_INI_SIZE => $this->l10n->t('The uploaded file exceeds the upload_max_filesize directive in php.ini'),
  194. UPLOAD_ERR_FORM_SIZE => $this->l10n->t('The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form'),
  195. UPLOAD_ERR_PARTIAL => $this->l10n->t('The file was only partially uploaded'),
  196. UPLOAD_ERR_NO_FILE => $this->l10n->t('No file was uploaded'),
  197. UPLOAD_ERR_NO_TMP_DIR => $this->l10n->t('Missing a temporary folder'),
  198. UPLOAD_ERR_CANT_WRITE => $this->l10n->t('Could not write file to disk'),
  199. UPLOAD_ERR_EXTENSION => $this->l10n->t('A PHP extension stopped the file upload'),
  200. ];
  201. $message = $phpFileUploadErrors[$files['error'][0]] ?? $this->l10n->t('Invalid file provided');
  202. $this->logger->warning($message, ['app' => 'core']);
  203. return new JSONResponse(
  204. ['data' => ['message' => $message]],
  205. Http::STATUS_BAD_REQUEST
  206. );
  207. }
  208. } else {
  209. //Add imgfile
  210. return new JSONResponse(
  211. ['data' => ['message' => $this->l10n->t('No image or file provided')]],
  212. Http::STATUS_BAD_REQUEST
  213. );
  214. }
  215. try {
  216. $image = new \OCP\Image();
  217. $image->loadFromData($content);
  218. $image->readExif($content);
  219. $image->fixOrientation();
  220. if ($image->valid()) {
  221. $mimeType = $image->mimeType();
  222. if ($mimeType !== 'image/jpeg' && $mimeType !== 'image/png') {
  223. return new JSONResponse(
  224. ['data' => ['message' => $this->l10n->t('Unknown filetype')]],
  225. Http::STATUS_OK
  226. );
  227. }
  228. if ($image->width() === $image->height()) {
  229. try {
  230. $avatar = $this->avatarManager->getAvatar($this->userId);
  231. $avatar->set($image);
  232. // Clean up
  233. $this->cache->remove('tmpAvatar');
  234. return new JSONResponse(['status' => 'success']);
  235. } catch (\Throwable $e) {
  236. $this->logger->error($e->getMessage(), ['exception' => $e, 'app' => 'core']);
  237. return new JSONResponse(['data' => ['message' => $this->l10n->t('An error occurred. Please contact your admin.')]], Http::STATUS_BAD_REQUEST);
  238. }
  239. }
  240. $this->cache->set('tmpAvatar', $image->data(), 7200);
  241. return new JSONResponse(
  242. ['data' => 'notsquare'],
  243. Http::STATUS_OK
  244. );
  245. } else {
  246. return new JSONResponse(
  247. ['data' => ['message' => $this->l10n->t('Invalid image')]],
  248. Http::STATUS_OK
  249. );
  250. }
  251. } catch (\Exception $e) {
  252. $this->logger->error($e->getMessage(), ['exception' => $e, 'app' => 'core']);
  253. return new JSONResponse(['data' => ['message' => $this->l10n->t('An error occurred. Please contact your admin.')]], Http::STATUS_OK);
  254. }
  255. }
  256. /**
  257. * @NoAdminRequired
  258. */
  259. #[FrontpageRoute(verb: 'DELETE', url: '/avatar/')]
  260. public function deleteAvatar(): JSONResponse {
  261. try {
  262. $avatar = $this->avatarManager->getAvatar($this->userId);
  263. $avatar->remove();
  264. return new JSONResponse();
  265. } catch (\Exception $e) {
  266. $this->logger->error($e->getMessage(), ['exception' => $e, 'app' => 'core']);
  267. return new JSONResponse(['data' => ['message' => $this->l10n->t('An error occurred. Please contact your admin.')]], Http::STATUS_BAD_REQUEST);
  268. }
  269. }
  270. /**
  271. * @NoAdminRequired
  272. *
  273. * @return JSONResponse|DataDisplayResponse
  274. */
  275. #[FrontpageRoute(verb: 'GET', url: '/avatar/tmp')]
  276. public function getTmpAvatar() {
  277. $tmpAvatar = $this->cache->get('tmpAvatar');
  278. if (is_null($tmpAvatar)) {
  279. return new JSONResponse(['data' => [
  280. 'message' => $this->l10n->t("No temporary profile picture available, try again")
  281. ]],
  282. Http::STATUS_NOT_FOUND);
  283. }
  284. $image = new \OCP\Image();
  285. $image->loadFromData($tmpAvatar);
  286. $resp = new DataDisplayResponse(
  287. $image->data() ?? '',
  288. Http::STATUS_OK,
  289. ['Content-Type' => $image->mimeType()]);
  290. $resp->setETag((string)crc32($image->data() ?? ''));
  291. $resp->cacheFor(0);
  292. $resp->setLastModified(new \DateTime('now', new \DateTimeZone('GMT')));
  293. return $resp;
  294. }
  295. /**
  296. * @NoAdminRequired
  297. */
  298. #[FrontpageRoute(verb: 'POST', url: '/avatar/cropped')]
  299. public function postCroppedAvatar(?array $crop = null): JSONResponse {
  300. if (is_null($crop)) {
  301. return new JSONResponse(['data' => ['message' => $this->l10n->t("No crop data provided")]],
  302. Http::STATUS_BAD_REQUEST);
  303. }
  304. if (!isset($crop['x'], $crop['y'], $crop['w'], $crop['h'])) {
  305. return new JSONResponse(['data' => ['message' => $this->l10n->t("No valid crop data provided")]],
  306. Http::STATUS_BAD_REQUEST);
  307. }
  308. $tmpAvatar = $this->cache->get('tmpAvatar');
  309. if (is_null($tmpAvatar)) {
  310. return new JSONResponse(['data' => [
  311. 'message' => $this->l10n->t("No temporary profile picture available, try again")
  312. ]],
  313. Http::STATUS_BAD_REQUEST);
  314. }
  315. $image = new \OCP\Image();
  316. $image->loadFromData($tmpAvatar);
  317. $image->crop($crop['x'], $crop['y'], (int)round($crop['w']), (int)round($crop['h']));
  318. try {
  319. $avatar = $this->avatarManager->getAvatar($this->userId);
  320. $avatar->set($image);
  321. // Clean up
  322. $this->cache->remove('tmpAvatar');
  323. return new JSONResponse(['status' => 'success']);
  324. } catch (\OC\NotSquareException $e) {
  325. return new JSONResponse(['data' => ['message' => $this->l10n->t('Crop is not square')]],
  326. Http::STATUS_BAD_REQUEST);
  327. } catch (\Exception $e) {
  328. $this->logger->error($e->getMessage(), ['exception' => $e, 'app' => 'core']);
  329. return new JSONResponse(['data' => ['message' => $this->l10n->t('An error occurred. Please contact your admin.')]], Http::STATUS_BAD_REQUEST);
  330. }
  331. }
  332. }