AvatarController.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  6. * @author Daniel Kesselberg <mail@danielkesselberg.de>
  7. * @author Joas Schilling <coding@schilljs.com>
  8. * @author John Molakvoæ <skjnldsv@protonmail.com>
  9. * @author Julien Veyssier <eneiluj@posteo.net>
  10. * @author Lukas Reschke <lukas@statuscode.ch>
  11. * @author Morris Jobke <hey@morrisjobke.de>
  12. * @author Roeland Jago Douma <roeland@famdouma.nl>
  13. * @author Thomas Müller <thomas.mueller@tmit.eu>
  14. * @author Vincent Petry <vincent@nextcloud.com>
  15. * @author Kate Döen <kate.doeen@nextcloud.com>
  16. *
  17. * @license AGPL-3.0
  18. *
  19. * This code is free software: you can redistribute it and/or modify
  20. * it under the terms of the GNU Affero General Public License, version 3,
  21. * as published by the Free Software Foundation.
  22. *
  23. * This program is distributed in the hope that it will be useful,
  24. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  25. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  26. * GNU Affero General Public License for more details.
  27. *
  28. * You should have received a copy of the GNU Affero General Public License, version 3,
  29. * along with this program. If not, see <http://www.gnu.org/licenses/>
  30. *
  31. */
  32. namespace OC\Core\Controller;
  33. use OC\AppFramework\Utility\TimeFactory;
  34. use OCP\AppFramework\Controller;
  35. use OCP\AppFramework\Http;
  36. use OCP\AppFramework\Http\Attribute\FrontpageRoute;
  37. use OCP\AppFramework\Http\DataDisplayResponse;
  38. use OCP\AppFramework\Http\FileDisplayResponse;
  39. use OCP\AppFramework\Http\JSONResponse;
  40. use OCP\AppFramework\Http\Response;
  41. use OCP\Files\File;
  42. use OCP\Files\IRootFolder;
  43. use OCP\IAvatarManager;
  44. use OCP\ICache;
  45. use OCP\IL10N;
  46. use OCP\IRequest;
  47. use OCP\IUserManager;
  48. use Psr\Log\LoggerInterface;
  49. /**
  50. * Class AvatarController
  51. *
  52. * @package OC\Core\Controller
  53. */
  54. class AvatarController extends Controller {
  55. public function __construct(
  56. string $appName,
  57. IRequest $request,
  58. protected IAvatarManager $avatarManager,
  59. protected ICache $cache,
  60. protected IL10N $l10n,
  61. protected IUserManager $userManager,
  62. protected IRootFolder $rootFolder,
  63. protected LoggerInterface $logger,
  64. protected ?string $userId,
  65. protected TimeFactory $timeFactory,
  66. protected GuestAvatarController $guestAvatarController,
  67. ) {
  68. parent::__construct($appName, $request);
  69. }
  70. /**
  71. * @NoAdminRequired
  72. * @NoCSRFRequired
  73. * @NoSameSiteCookieRequired
  74. * @PublicPage
  75. *
  76. * Get the dark avatar
  77. *
  78. * @param string $userId ID of the user
  79. * @param int $size Size of the avatar
  80. * @param bool $guestFallback Fallback to guest avatar if not found
  81. * @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{}>
  82. *
  83. * 200: Avatar returned
  84. * 201: Avatar returned
  85. * 404: Avatar not found
  86. */
  87. #[FrontpageRoute(verb: 'GET', url: '/avatar/{userId}/{size}/dark')]
  88. public function getAvatarDark(string $userId, int $size, bool $guestFallback = false) {
  89. if ($size <= 64) {
  90. if ($size !== 64) {
  91. $this->logger->debug('Avatar requested in deprecated size ' . $size);
  92. }
  93. $size = 64;
  94. } else {
  95. if ($size !== 512) {
  96. $this->logger->debug('Avatar requested in deprecated size ' . $size);
  97. }
  98. $size = 512;
  99. }
  100. try {
  101. $avatar = $this->avatarManager->getAvatar($userId);
  102. $avatarFile = $avatar->getFile($size, true);
  103. $response = new FileDisplayResponse(
  104. $avatarFile,
  105. Http::STATUS_OK,
  106. ['Content-Type' => $avatarFile->getMimeType(), 'X-NC-IsCustomAvatar' => (int)$avatar->isCustomAvatar()]
  107. );
  108. } catch (\Exception $e) {
  109. if ($guestFallback) {
  110. return $this->guestAvatarController->getAvatarDark($userId, (string)$size);
  111. }
  112. return new JSONResponse([], Http::STATUS_NOT_FOUND);
  113. }
  114. // Cache for 1 day
  115. $response->cacheFor(60 * 60 * 24, false, true);
  116. return $response;
  117. }
  118. /**
  119. * @NoAdminRequired
  120. * @NoCSRFRequired
  121. * @NoSameSiteCookieRequired
  122. * @PublicPage
  123. *
  124. * Get the avatar
  125. *
  126. * @param string $userId ID of the user
  127. * @param int $size Size of the avatar
  128. * @param bool $guestFallback Fallback to guest avatar if not found
  129. * @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{}>
  130. *
  131. * 200: Avatar returned
  132. * 201: Avatar returned
  133. * 404: Avatar not found
  134. */
  135. #[FrontpageRoute(verb: 'GET', url: '/avatar/{userId}/{size}')]
  136. public function getAvatar(string $userId, int $size, bool $guestFallback = false) {
  137. if ($size <= 64) {
  138. if ($size !== 64) {
  139. $this->logger->debug('Avatar requested in deprecated size ' . $size);
  140. }
  141. $size = 64;
  142. } else {
  143. if ($size !== 512) {
  144. $this->logger->debug('Avatar requested in deprecated size ' . $size);
  145. }
  146. $size = 512;
  147. }
  148. try {
  149. $avatar = $this->avatarManager->getAvatar($userId);
  150. $avatarFile = $avatar->getFile($size);
  151. $response = new FileDisplayResponse(
  152. $avatarFile,
  153. Http::STATUS_OK,
  154. ['Content-Type' => $avatarFile->getMimeType(), 'X-NC-IsCustomAvatar' => (int)$avatar->isCustomAvatar()]
  155. );
  156. } catch (\Exception $e) {
  157. if ($guestFallback) {
  158. return $this->guestAvatarController->getAvatar($userId, (string)$size);
  159. }
  160. return new JSONResponse([], Http::STATUS_NOT_FOUND);
  161. }
  162. // Cache for 1 day
  163. $response->cacheFor(60 * 60 * 24, false, true);
  164. return $response;
  165. }
  166. /**
  167. * @NoAdminRequired
  168. */
  169. #[FrontpageRoute(verb: 'POST', url: '/avatar/')]
  170. public function postAvatar(?string $path = null): JSONResponse {
  171. $files = $this->request->getUploadedFile('files');
  172. if (isset($path)) {
  173. $path = stripslashes($path);
  174. $userFolder = $this->rootFolder->getUserFolder($this->userId);
  175. /** @var File $node */
  176. $node = $userFolder->get($path);
  177. if (!($node instanceof File)) {
  178. return new JSONResponse(['data' => ['message' => $this->l10n->t('Please select a file.')]]);
  179. }
  180. if ($node->getSize() > 20 * 1024 * 1024) {
  181. return new JSONResponse(
  182. ['data' => ['message' => $this->l10n->t('File is too big')]],
  183. Http::STATUS_BAD_REQUEST
  184. );
  185. }
  186. if ($node->getMimeType() !== 'image/jpeg' && $node->getMimeType() !== 'image/png') {
  187. return new JSONResponse(
  188. ['data' => ['message' => $this->l10n->t('The selected file is not an image.')]],
  189. Http::STATUS_BAD_REQUEST
  190. );
  191. }
  192. try {
  193. $content = $node->getContent();
  194. } catch (\OCP\Files\NotPermittedException $e) {
  195. return new JSONResponse(
  196. ['data' => ['message' => $this->l10n->t('The selected file cannot be read.')]],
  197. Http::STATUS_BAD_REQUEST
  198. );
  199. }
  200. } elseif (!is_null($files)) {
  201. if (
  202. $files['error'][0] === 0 &&
  203. is_uploaded_file($files['tmp_name'][0]) &&
  204. !\OC\Files\Filesystem::isFileBlacklisted($files['tmp_name'][0])
  205. ) {
  206. if ($files['size'][0] > 20 * 1024 * 1024) {
  207. return new JSONResponse(
  208. ['data' => ['message' => $this->l10n->t('File is too big')]],
  209. Http::STATUS_BAD_REQUEST
  210. );
  211. }
  212. $this->cache->set('avatar_upload', file_get_contents($files['tmp_name'][0]), 7200);
  213. $content = $this->cache->get('avatar_upload');
  214. unlink($files['tmp_name'][0]);
  215. } else {
  216. $phpFileUploadErrors = [
  217. UPLOAD_ERR_OK => $this->l10n->t('The file was uploaded'),
  218. UPLOAD_ERR_INI_SIZE => $this->l10n->t('The uploaded file exceeds the upload_max_filesize directive in php.ini'),
  219. UPLOAD_ERR_FORM_SIZE => $this->l10n->t('The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form'),
  220. UPLOAD_ERR_PARTIAL => $this->l10n->t('The file was only partially uploaded'),
  221. UPLOAD_ERR_NO_FILE => $this->l10n->t('No file was uploaded'),
  222. UPLOAD_ERR_NO_TMP_DIR => $this->l10n->t('Missing a temporary folder'),
  223. UPLOAD_ERR_CANT_WRITE => $this->l10n->t('Could not write file to disk'),
  224. UPLOAD_ERR_EXTENSION => $this->l10n->t('A PHP extension stopped the file upload'),
  225. ];
  226. $message = $phpFileUploadErrors[$files['error'][0]] ?? $this->l10n->t('Invalid file provided');
  227. $this->logger->warning($message, ['app' => 'core']);
  228. return new JSONResponse(
  229. ['data' => ['message' => $message]],
  230. Http::STATUS_BAD_REQUEST
  231. );
  232. }
  233. } else {
  234. //Add imgfile
  235. return new JSONResponse(
  236. ['data' => ['message' => $this->l10n->t('No image or file provided')]],
  237. Http::STATUS_BAD_REQUEST
  238. );
  239. }
  240. try {
  241. $image = new \OCP\Image();
  242. $image->loadFromData($content);
  243. $image->readExif($content);
  244. $image->fixOrientation();
  245. if ($image->valid()) {
  246. $mimeType = $image->mimeType();
  247. if ($mimeType !== 'image/jpeg' && $mimeType !== 'image/png') {
  248. return new JSONResponse(
  249. ['data' => ['message' => $this->l10n->t('Unknown filetype')]],
  250. Http::STATUS_OK
  251. );
  252. }
  253. if ($image->width() === $image->height()) {
  254. try {
  255. $avatar = $this->avatarManager->getAvatar($this->userId);
  256. $avatar->set($image);
  257. // Clean up
  258. $this->cache->remove('tmpAvatar');
  259. return new JSONResponse(['status' => 'success']);
  260. } catch (\Throwable $e) {
  261. $this->logger->error($e->getMessage(), ['exception' => $e, 'app' => 'core']);
  262. return new JSONResponse(['data' => ['message' => $this->l10n->t('An error occurred. Please contact your admin.')]], Http::STATUS_BAD_REQUEST);
  263. }
  264. }
  265. $this->cache->set('tmpAvatar', $image->data(), 7200);
  266. return new JSONResponse(
  267. ['data' => 'notsquare'],
  268. Http::STATUS_OK
  269. );
  270. } else {
  271. return new JSONResponse(
  272. ['data' => ['message' => $this->l10n->t('Invalid image')]],
  273. Http::STATUS_OK
  274. );
  275. }
  276. } catch (\Exception $e) {
  277. $this->logger->error($e->getMessage(), ['exception' => $e, 'app' => 'core']);
  278. return new JSONResponse(['data' => ['message' => $this->l10n->t('An error occurred. Please contact your admin.')]], Http::STATUS_OK);
  279. }
  280. }
  281. /**
  282. * @NoAdminRequired
  283. */
  284. #[FrontpageRoute(verb: 'DELETE', url: '/avatar/')]
  285. public function deleteAvatar(): JSONResponse {
  286. try {
  287. $avatar = $this->avatarManager->getAvatar($this->userId);
  288. $avatar->remove();
  289. return new JSONResponse();
  290. } catch (\Exception $e) {
  291. $this->logger->error($e->getMessage(), ['exception' => $e, 'app' => 'core']);
  292. return new JSONResponse(['data' => ['message' => $this->l10n->t('An error occurred. Please contact your admin.')]], Http::STATUS_BAD_REQUEST);
  293. }
  294. }
  295. /**
  296. * @NoAdminRequired
  297. *
  298. * @return JSONResponse|DataDisplayResponse
  299. */
  300. #[FrontpageRoute(verb: 'GET', url: '/avatar/tmp')]
  301. public function getTmpAvatar() {
  302. $tmpAvatar = $this->cache->get('tmpAvatar');
  303. if (is_null($tmpAvatar)) {
  304. return new JSONResponse(['data' => [
  305. 'message' => $this->l10n->t("No temporary profile picture available, try again")
  306. ]],
  307. Http::STATUS_NOT_FOUND);
  308. }
  309. $image = new \OCP\Image();
  310. $image->loadFromData($tmpAvatar);
  311. $resp = new DataDisplayResponse(
  312. $image->data() ?? '',
  313. Http::STATUS_OK,
  314. ['Content-Type' => $image->mimeType()]);
  315. $resp->setETag((string)crc32($image->data() ?? ''));
  316. $resp->cacheFor(0);
  317. $resp->setLastModified(new \DateTime('now', new \DateTimeZone('GMT')));
  318. return $resp;
  319. }
  320. /**
  321. * @NoAdminRequired
  322. */
  323. #[FrontpageRoute(verb: 'POST', url: '/avatar/cropped')]
  324. public function postCroppedAvatar(?array $crop = null): JSONResponse {
  325. if (is_null($crop)) {
  326. return new JSONResponse(['data' => ['message' => $this->l10n->t("No crop data provided")]],
  327. Http::STATUS_BAD_REQUEST);
  328. }
  329. if (!isset($crop['x'], $crop['y'], $crop['w'], $crop['h'])) {
  330. return new JSONResponse(['data' => ['message' => $this->l10n->t("No valid crop data provided")]],
  331. Http::STATUS_BAD_REQUEST);
  332. }
  333. $tmpAvatar = $this->cache->get('tmpAvatar');
  334. if (is_null($tmpAvatar)) {
  335. return new JSONResponse(['data' => [
  336. 'message' => $this->l10n->t("No temporary profile picture available, try again")
  337. ]],
  338. Http::STATUS_BAD_REQUEST);
  339. }
  340. $image = new \OCP\Image();
  341. $image->loadFromData($tmpAvatar);
  342. $image->crop($crop['x'], $crop['y'], (int)round($crop['w']), (int)round($crop['h']));
  343. try {
  344. $avatar = $this->avatarManager->getAvatar($this->userId);
  345. $avatar->set($image);
  346. // Clean up
  347. $this->cache->remove('tmpAvatar');
  348. return new JSONResponse(['status' => 'success']);
  349. } catch (\OC\NotSquareException $e) {
  350. return new JSONResponse(['data' => ['message' => $this->l10n->t('Crop is not square')]],
  351. Http::STATUS_BAD_REQUEST);
  352. } catch (\Exception $e) {
  353. $this->logger->error($e->getMessage(), ['exception' => $e, 'app' => 'core']);
  354. return new JSONResponse(['data' => ['message' => $this->l10n->t('An error occurred. Please contact your admin.')]], Http::STATUS_BAD_REQUEST);
  355. }
  356. }
  357. }