AvatarController.php 11 KB

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