1
0

AvatarController.php 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  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. // min/max size
  103. if ($size > 2048) {
  104. $size = 2048;
  105. } elseif ($size <= 0) {
  106. $size = 64;
  107. }
  108. try {
  109. $avatar = $this->avatarManager->getAvatar($userId);
  110. $avatarFile = $avatar->getFile($size);
  111. $response = new FileDisplayResponse(
  112. $avatarFile,
  113. Http::STATUS_OK,
  114. ['Content-Type' => $avatarFile->getMimeType(), 'X-NC-IsCustomAvatar' => (int)$avatar->isCustomAvatar()]
  115. );
  116. } catch (\Exception $e) {
  117. return new JSONResponse([], Http::STATUS_NOT_FOUND);
  118. }
  119. // Cache for 1 day
  120. $response->cacheFor(60 * 60 * 24);
  121. return $response;
  122. }
  123. /**
  124. * @NoAdminRequired
  125. *
  126. * @param string $path
  127. * @return JSONResponse
  128. */
  129. public function postAvatar($path) {
  130. $files = $this->request->getUploadedFile('files');
  131. if (isset($path)) {
  132. $path = stripslashes($path);
  133. $userFolder = $this->rootFolder->getUserFolder($this->userId);
  134. /** @var File $node */
  135. $node = $userFolder->get($path);
  136. if (!($node instanceof File)) {
  137. return new JSONResponse(['data' => ['message' => $this->l->t('Please select a file.')]]);
  138. }
  139. if ($node->getSize() > 20 * 1024 * 1024) {
  140. return new JSONResponse(
  141. ['data' => ['message' => $this->l->t('File is too big')]],
  142. Http::STATUS_BAD_REQUEST
  143. );
  144. }
  145. if ($node->getMimeType() !== 'image/jpeg' && $node->getMimeType() !== 'image/png') {
  146. return new JSONResponse(
  147. ['data' => ['message' => $this->l->t('The selected file is not an image.')]],
  148. Http::STATUS_BAD_REQUEST
  149. );
  150. }
  151. try {
  152. $content = $node->getContent();
  153. } catch (\OCP\Files\NotPermittedException $e) {
  154. return new JSONResponse(
  155. ['data' => ['message' => $this->l->t('The selected file cannot be read.')]],
  156. Http::STATUS_BAD_REQUEST
  157. );
  158. }
  159. } elseif (!is_null($files)) {
  160. if (
  161. $files['error'][0] === 0 &&
  162. is_uploaded_file($files['tmp_name'][0]) &&
  163. !\OC\Files\Filesystem::isFileBlacklisted($files['tmp_name'][0])
  164. ) {
  165. if ($files['size'][0] > 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. $this->cache->set('avatar_upload', file_get_contents($files['tmp_name'][0]), 7200);
  172. $content = $this->cache->get('avatar_upload');
  173. unlink($files['tmp_name'][0]);
  174. } else {
  175. $phpFileUploadErrors = [
  176. UPLOAD_ERR_OK => $this->l->t('The file was uploaded'),
  177. UPLOAD_ERR_INI_SIZE => $this->l->t('The uploaded file exceeds the upload_max_filesize directive in php.ini'),
  178. UPLOAD_ERR_FORM_SIZE => $this->l->t('The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form'),
  179. UPLOAD_ERR_PARTIAL => $this->l->t('The file was only partially uploaded'),
  180. UPLOAD_ERR_NO_FILE => $this->l->t('No file was uploaded'),
  181. UPLOAD_ERR_NO_TMP_DIR => $this->l->t('Missing a temporary folder'),
  182. UPLOAD_ERR_CANT_WRITE => $this->l->t('Could not write file to disk'),
  183. UPLOAD_ERR_EXTENSION => $this->l->t('A PHP extension stopped the file upload'),
  184. ];
  185. $message = $phpFileUploadErrors[$files['error'][0]] ?? $this->l->t('Invalid file provided');
  186. $this->logger->warning($message, ['app' => 'core']);
  187. return new JSONResponse(
  188. ['data' => ['message' => $message]],
  189. Http::STATUS_BAD_REQUEST
  190. );
  191. }
  192. } else {
  193. //Add imgfile
  194. return new JSONResponse(
  195. ['data' => ['message' => $this->l->t('No image or file provided')]],
  196. Http::STATUS_BAD_REQUEST
  197. );
  198. }
  199. try {
  200. $image = new \OC_Image();
  201. $image->loadFromData($content);
  202. $image->readExif($content);
  203. $image->fixOrientation();
  204. if ($image->valid()) {
  205. $mimeType = $image->mimeType();
  206. if ($mimeType !== 'image/jpeg' && $mimeType !== 'image/png') {
  207. return new JSONResponse(
  208. ['data' => ['message' => $this->l->t('Unknown filetype')]],
  209. Http::STATUS_OK
  210. );
  211. }
  212. $this->cache->set('tmpAvatar', $image->data(), 7200);
  213. return new JSONResponse(
  214. ['data' => 'notsquare'],
  215. Http::STATUS_OK
  216. );
  217. } else {
  218. return new JSONResponse(
  219. ['data' => ['message' => $this->l->t('Invalid image')]],
  220. Http::STATUS_OK
  221. );
  222. }
  223. } catch (\Exception $e) {
  224. $this->logger->logException($e, ['app' => 'core']);
  225. return new JSONResponse(['data' => ['message' => $this->l->t('An error occurred. Please contact your admin.')]], Http::STATUS_OK);
  226. }
  227. }
  228. /**
  229. * @NoAdminRequired
  230. *
  231. * @return JSONResponse
  232. */
  233. public function deleteAvatar() {
  234. try {
  235. $avatar = $this->avatarManager->getAvatar($this->userId);
  236. $avatar->remove();
  237. return new JSONResponse();
  238. } catch (\Exception $e) {
  239. $this->logger->logException($e, ['app' => 'core']);
  240. return new JSONResponse(['data' => ['message' => $this->l->t('An error occurred. Please contact your admin.')]], Http::STATUS_BAD_REQUEST);
  241. }
  242. }
  243. /**
  244. * @NoAdminRequired
  245. *
  246. * @return JSONResponse|DataDisplayResponse
  247. */
  248. public function getTmpAvatar() {
  249. $tmpAvatar = $this->cache->get('tmpAvatar');
  250. if (is_null($tmpAvatar)) {
  251. return new JSONResponse(['data' => [
  252. 'message' => $this->l->t("No temporary profile picture available, try again")
  253. ]],
  254. Http::STATUS_NOT_FOUND);
  255. }
  256. $image = new \OC_Image();
  257. $image->loadFromData($tmpAvatar);
  258. $resp = new DataDisplayResponse($image->data(),
  259. Http::STATUS_OK,
  260. ['Content-Type' => $image->mimeType()]);
  261. $resp->setETag((string)crc32($image->data()));
  262. $resp->cacheFor(0);
  263. $resp->setLastModified(new \DateTime('now', new \DateTimeZone('GMT')));
  264. return $resp;
  265. }
  266. /**
  267. * @NoAdminRequired
  268. *
  269. * @param array $crop
  270. * @return JSONResponse
  271. */
  272. public function postCroppedAvatar($crop) {
  273. if (is_null($crop)) {
  274. return new JSONResponse(['data' => ['message' => $this->l->t("No crop data provided")]],
  275. Http::STATUS_BAD_REQUEST);
  276. }
  277. if (!isset($crop['x'], $crop['y'], $crop['w'], $crop['h'])) {
  278. return new JSONResponse(['data' => ['message' => $this->l->t("No valid crop data provided")]],
  279. Http::STATUS_BAD_REQUEST);
  280. }
  281. $tmpAvatar = $this->cache->get('tmpAvatar');
  282. if (is_null($tmpAvatar)) {
  283. return new JSONResponse(['data' => [
  284. 'message' => $this->l->t("No temporary profile picture available, try again")
  285. ]],
  286. Http::STATUS_BAD_REQUEST);
  287. }
  288. $image = new \OC_Image();
  289. $image->loadFromData($tmpAvatar);
  290. $image->crop($crop['x'], $crop['y'], (int)round($crop['w']), (int)round($crop['h']));
  291. try {
  292. $avatar = $this->avatarManager->getAvatar($this->userId);
  293. $avatar->set($image);
  294. // Clean up
  295. $this->cache->remove('tmpAvatar');
  296. return new JSONResponse(['status' => 'success']);
  297. } catch (\OC\NotSquareException $e) {
  298. return new JSONResponse(['data' => ['message' => $this->l->t('Crop is not square')]],
  299. Http::STATUS_BAD_REQUEST);
  300. } catch (\Exception $e) {
  301. $this->logger->logException($e, ['app' => 'core']);
  302. return new JSONResponse(['data' => ['message' => $this->l->t('An error occurred. Please contact your admin.')]], Http::STATUS_BAD_REQUEST);
  303. }
  304. }
  305. }