AvatarController.php 10.0 KB

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