AvatarController.php 11 KB

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