AvatarController.php 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Joas Schilling <coding@schilljs.com>
  6. * @author Lukas Reschke <lukas@statuscode.ch>
  7. * @author Morris Jobke <hey@morrisjobke.de>
  8. * @author Roeland Jago Douma <roeland@famdouma.nl>
  9. * @author Thomas Müller <thomas.mueller@tmit.eu>
  10. * @author Vincent Petry <pvince81@owncloud.com>
  11. * @author John Molakvoæ <skjnldsv@protonmail.com>
  12. *
  13. * @license AGPL-3.0
  14. *
  15. * This code is free software: you can redistribute it and/or modify
  16. * it under the terms of the GNU Affero General Public License, version 3,
  17. * as published by the Free Software Foundation.
  18. *
  19. * This program is distributed in the hope that it will be useful,
  20. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  21. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  22. * GNU Affero General Public License for more details.
  23. *
  24. * You should have received a copy of the GNU Affero General Public License, version 3,
  25. * along with this program. If not, see <http://www.gnu.org/licenses/>
  26. *
  27. */
  28. namespace OC\Core\Controller;
  29. use OC\AppFramework\Utility\TimeFactory;
  30. use OCP\AppFramework\Controller;
  31. use OCP\AppFramework\Http;
  32. use OCP\AppFramework\Http\DataDisplayResponse;
  33. use OCP\AppFramework\Http\FileDisplayResponse;
  34. use OCP\AppFramework\Http\JSONResponse;
  35. use OCP\Files\File;
  36. use OCP\Files\IRootFolder;
  37. use OCP\IAvatarManager;
  38. use OCP\ICache;
  39. use OCP\ILogger;
  40. use OCP\IL10N;
  41. use OCP\IRequest;
  42. use OCP\IUserManager;
  43. use OCP\IUserSession;
  44. use OCP\AppFramework\Http\DataResponse;
  45. /**
  46. * Class AvatarController
  47. *
  48. * @package OC\Core\Controller
  49. */
  50. class AvatarController extends Controller {
  51. /** @var IAvatarManager */
  52. protected $avatarManager;
  53. /** @var ICache */
  54. protected $cache;
  55. /** @var IL10N */
  56. protected $l;
  57. /** @var IUserManager */
  58. protected $userManager;
  59. /** @var IUserSession */
  60. protected $userSession;
  61. /** @var IRootFolder */
  62. protected $rootFolder;
  63. /** @var ILogger */
  64. protected $logger;
  65. /** @var string */
  66. protected $userId;
  67. /** @var TimeFactory */
  68. protected $timeFactory;
  69. /**
  70. * @param string $appName
  71. * @param IRequest $request
  72. * @param IAvatarManager $avatarManager
  73. * @param ICache $cache
  74. * @param IL10N $l10n
  75. * @param IUserManager $userManager
  76. * @param IRootFolder $rootFolder
  77. * @param ILogger $logger
  78. * @param string $userId
  79. * @param TimeFactory $timeFactory
  80. */
  81. public function __construct($appName,
  82. IRequest $request,
  83. IAvatarManager $avatarManager,
  84. ICache $cache,
  85. IL10N $l10n,
  86. IUserManager $userManager,
  87. IRootFolder $rootFolder,
  88. ILogger $logger,
  89. $userId,
  90. TimeFactory $timeFactory) {
  91. parent::__construct($appName, $request);
  92. $this->avatarManager = $avatarManager;
  93. $this->cache = $cache;
  94. $this->l = $l10n;
  95. $this->userManager = $userManager;
  96. $this->rootFolder = $rootFolder;
  97. $this->logger = $logger;
  98. $this->userId = $userId;
  99. $this->timeFactory = $timeFactory;
  100. }
  101. /**
  102. * @NoAdminRequired
  103. * @NoCSRFRequired
  104. * @NoSameSiteCookieRequired
  105. * @PublicPage
  106. *
  107. * @param string $userId
  108. * @param int $size
  109. * @return JSONResponse|FileDisplayResponse
  110. */
  111. public function getAvatar($userId, $size) {
  112. // min/max size
  113. if ($size > 2048) {
  114. $size = 2048;
  115. } elseif ($size <= 0) {
  116. $size = 64;
  117. }
  118. try {
  119. $avatar = $this->avatarManager->getAvatar($userId);
  120. $avatarFile = $avatar->getFile($size);
  121. $resp = new FileDisplayResponse(
  122. $avatarFile,
  123. $avatar->isCustomAvatar() ? Http::STATUS_OK : Http::STATUS_CREATED,
  124. ['Content-Type' => $avatarFile->getMimeType()]
  125. );
  126. } catch (\Exception $e) {
  127. $resp = new Http\Response();
  128. $resp->setStatus(Http::STATUS_NOT_FOUND);
  129. return $resp;
  130. }
  131. // Cache for 30 minutes
  132. $resp->cacheFor(1800);
  133. return $resp;
  134. }
  135. /**
  136. * @NoAdminRequired
  137. *
  138. * @param string $path
  139. * @return JSONResponse
  140. */
  141. public function postAvatar($path) {
  142. $files = $this->request->getUploadedFile('files');
  143. if (isset($path)) {
  144. $path = stripslashes($path);
  145. $userFolder = $this->rootFolder->getUserFolder($this->userId);
  146. /** @var File $node */
  147. $node = $userFolder->get($path);
  148. if (!($node instanceof File)) {
  149. return new JSONResponse(['data' => ['message' => $this->l->t('Please select a file.')]]);
  150. }
  151. if ($node->getSize() > 20*1024*1024) {
  152. return new JSONResponse(
  153. ['data' => ['message' => $this->l->t('File is too big')]],
  154. Http::STATUS_BAD_REQUEST
  155. );
  156. }
  157. if ($node->getMimeType() !== 'image/jpeg' && $node->getMimeType() !== 'image/png') {
  158. return new JSONResponse(
  159. ['data' => ['message' => $this->l->t('The selected file is not an image.')]],
  160. Http::STATUS_BAD_REQUEST
  161. );
  162. }
  163. try {
  164. $content = $node->getContent();
  165. } catch (\OCP\Files\NotPermittedException $e) {
  166. return new JSONResponse(
  167. ['data' => ['message' => $this->l->t('The selected file cannot be read.')]],
  168. Http::STATUS_BAD_REQUEST
  169. );
  170. }
  171. } elseif (!is_null($files)) {
  172. if (
  173. $files['error'][0] === 0 &&
  174. is_uploaded_file($files['tmp_name'][0]) &&
  175. !\OC\Files\Filesystem::isFileBlacklisted($files['tmp_name'][0])
  176. ) {
  177. if ($files['size'][0] > 20*1024*1024) {
  178. return new JSONResponse(
  179. ['data' => ['message' => $this->l->t('File is too big')]],
  180. Http::STATUS_BAD_REQUEST
  181. );
  182. }
  183. $this->cache->set('avatar_upload', file_get_contents($files['tmp_name'][0]), 7200);
  184. $content = $this->cache->get('avatar_upload');
  185. unlink($files['tmp_name'][0]);
  186. } else {
  187. return new JSONResponse(
  188. ['data' => ['message' => $this->l->t('Invalid file provided')]],
  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. }