1
0

AvatarController.php 12 KB

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