AvatarController.php 11 KB

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