AvatarController.php 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  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 Robin Appelman <robin@icewind.nl>
  9. * @author Roeland Jago Douma <roeland@famdouma.nl>
  10. * @author Thomas Müller <thomas.mueller@tmit.eu>
  11. * @author Vincent Petry <pvince81@owncloud.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\Files\NotFoundException;
  38. use OCP\IAvatarManager;
  39. use OCP\ICache;
  40. use OCP\ILogger;
  41. use OCP\IL10N;
  42. use OCP\IRequest;
  43. use OCP\IUserManager;
  44. use OCP\IUserSession;
  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. * @PublicPage
  105. *
  106. * @param string $userId
  107. * @param int $size
  108. * @return JSONResponse|FileDisplayResponse
  109. */
  110. public function getAvatar($userId, $size) {
  111. if ($size > 2048) {
  112. $size = 2048;
  113. } elseif ($size <= 0) {
  114. $size = 64;
  115. }
  116. try {
  117. $avatar = $this->avatarManager->getAvatar($userId)->getFile($size);
  118. $resp = new FileDisplayResponse($avatar,
  119. Http::STATUS_OK,
  120. ['Content-Type' => $avatar->getMimeType()]);
  121. // Let cache this!
  122. $resp->addHeader('Pragma', 'public');
  123. // Cache for 15 minutes
  124. $resp->cacheFor(900);
  125. $expires = new \DateTime();
  126. $expires->setTimestamp($this->timeFactory->getTime());
  127. $expires->add(new \DateInterval('PT15M'));
  128. $resp->addHeader('Expires', $expires->format(\DateTime::RFC2822));
  129. } catch (NotFoundException $e) {
  130. $user = $this->userManager->get($userId);
  131. $resp = new JSONResponse([
  132. 'data' => [
  133. 'displayname' => $user->getDisplayName(),
  134. ],
  135. ]);
  136. // Don't cache this
  137. $resp->cacheFor(0);
  138. $resp->setLastModified(new \DateTime('now', new \DateTimeZone('GMT')));
  139. } catch (\Exception $e) {
  140. $resp = new JSONResponse([
  141. 'data' => [
  142. 'displayname' => '',
  143. ],
  144. ]);
  145. // Don't cache this
  146. $resp->cacheFor(0);
  147. $resp->setLastModified(new \DateTime('now', new \DateTimeZone('GMT')));
  148. }
  149. return $resp;
  150. }
  151. /**
  152. * @NoAdminRequired
  153. *
  154. * @param string $path
  155. * @return JSONResponse
  156. */
  157. public function postAvatar($path) {
  158. $files = $this->request->getUploadedFile('files');
  159. if (isset($path)) {
  160. $path = stripslashes($path);
  161. $userFolder = $this->rootFolder->getUserFolder($this->userId);
  162. $node = $userFolder->get($path);
  163. if (!($node instanceof File)) {
  164. return new JSONResponse(['data' => ['message' => $this->l->t('Please select a file.')]]);
  165. }
  166. if ($node->getSize() > 20*1024*1024) {
  167. return new JSONResponse(
  168. ['data' => ['message' => $this->l->t('File is too big')]],
  169. Http::STATUS_BAD_REQUEST
  170. );
  171. }
  172. if ($node->getMimeType() !== 'image/jpeg' && $node->getMimeType() !== 'image/png') {
  173. return new JSONResponse(
  174. ['data' => ['message' => $this->l->t('The selected file is not an image.')]],
  175. Http::STATUS_BAD_REQUEST
  176. );
  177. }
  178. try {
  179. $content = $node->getContent();
  180. } catch (\OCP\Files\NotPermittedException $e) {
  181. return new JSONResponse(
  182. ['data' => ['message' => $this->l->t('The selected file cannot be read.')]],
  183. Http::STATUS_BAD_REQUEST
  184. );
  185. }
  186. } elseif (!is_null($files)) {
  187. if (
  188. $files['error'][0] === 0 &&
  189. is_uploaded_file($files['tmp_name'][0]) &&
  190. !\OC\Files\Filesystem::isFileBlacklisted($files['tmp_name'][0])
  191. ) {
  192. if ($files['size'][0] > 20*1024*1024) {
  193. return new JSONResponse(
  194. ['data' => ['message' => $this->l->t('File is too big')]],
  195. Http::STATUS_BAD_REQUEST
  196. );
  197. }
  198. $this->cache->set('avatar_upload', file_get_contents($files['tmp_name'][0]), 7200);
  199. $content = $this->cache->get('avatar_upload');
  200. unlink($files['tmp_name'][0]);
  201. } else {
  202. return new JSONResponse(
  203. ['data' => ['message' => $this->l->t('Invalid file provided')]],
  204. Http::STATUS_BAD_REQUEST
  205. );
  206. }
  207. } else {
  208. //Add imgfile
  209. return new JSONResponse(
  210. ['data' => ['message' => $this->l->t('No image or file provided')]],
  211. Http::STATUS_BAD_REQUEST
  212. );
  213. }
  214. try {
  215. $image = new \OC_Image();
  216. $image->loadFromData($content);
  217. $image->readExif($content);
  218. $image->fixOrientation();
  219. if ($image->valid()) {
  220. $mimeType = $image->mimeType();
  221. if ($mimeType !== 'image/jpeg' && $mimeType !== 'image/png') {
  222. return new JSONResponse(
  223. ['data' => ['message' => $this->l->t('Unknown filetype')]],
  224. Http::STATUS_OK
  225. );
  226. }
  227. $this->cache->set('tmpAvatar', $image->data(), 7200);
  228. return new JSONResponse(
  229. ['data' => 'notsquare'],
  230. Http::STATUS_OK
  231. );
  232. } else {
  233. return new JSONResponse(
  234. ['data' => ['message' => $this->l->t('Invalid image')]],
  235. Http::STATUS_OK
  236. );
  237. }
  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_OK);
  241. }
  242. }
  243. /**
  244. * @NoAdminRequired
  245. *
  246. * @return JSONResponse
  247. */
  248. public function deleteAvatar() {
  249. try {
  250. $avatar = $this->avatarManager->getAvatar($this->userId);
  251. $avatar->remove();
  252. return new JSONResponse();
  253. } catch (\Exception $e) {
  254. $this->logger->logException($e, ['app' => 'core']);
  255. return new JSONResponse(['data' => ['message' => $this->l->t('An error occurred. Please contact your admin.')]], Http::STATUS_BAD_REQUEST);
  256. }
  257. }
  258. /**
  259. * @NoAdminRequired
  260. *
  261. * @return JSONResponse|DataDisplayResponse
  262. */
  263. public function getTmpAvatar() {
  264. $tmpAvatar = $this->cache->get('tmpAvatar');
  265. if (is_null($tmpAvatar)) {
  266. return new JSONResponse(['data' => [
  267. 'message' => $this->l->t("No temporary profile picture available, try again")
  268. ]],
  269. Http::STATUS_NOT_FOUND);
  270. }
  271. $image = new \OC_Image($tmpAvatar);
  272. $resp = new DataDisplayResponse($image->data(),
  273. Http::STATUS_OK,
  274. ['Content-Type' => $image->mimeType()]);
  275. $resp->setETag(crc32($image->data()));
  276. $resp->cacheFor(0);
  277. $resp->setLastModified(new \DateTime('now', new \DateTimeZone('GMT')));
  278. return $resp;
  279. }
  280. /**
  281. * @NoAdminRequired
  282. *
  283. * @param array $crop
  284. * @return JSONResponse
  285. */
  286. public function postCroppedAvatar($crop) {
  287. if (is_null($crop)) {
  288. return new JSONResponse(['data' => ['message' => $this->l->t("No crop data provided")]],
  289. Http::STATUS_BAD_REQUEST);
  290. }
  291. if (!isset($crop['x'], $crop['y'], $crop['w'], $crop['h'])) {
  292. return new JSONResponse(['data' => ['message' => $this->l->t("No valid crop data provided")]],
  293. Http::STATUS_BAD_REQUEST);
  294. }
  295. $tmpAvatar = $this->cache->get('tmpAvatar');
  296. if (is_null($tmpAvatar)) {
  297. return new JSONResponse(['data' => [
  298. 'message' => $this->l->t("No temporary profile picture available, try again")
  299. ]],
  300. Http::STATUS_BAD_REQUEST);
  301. }
  302. $image = new \OC_Image($tmpAvatar);
  303. $image->crop($crop['x'], $crop['y'], round($crop['w']), round($crop['h']));
  304. try {
  305. $avatar = $this->avatarManager->getAvatar($this->userId);
  306. $avatar->set($image);
  307. // Clean up
  308. $this->cache->remove('tmpAvatar');
  309. return new JSONResponse(['status' => 'success']);
  310. } catch (\OC\NotSquareException $e) {
  311. return new JSONResponse(['data' => ['message' => $this->l->t('Crop is not square')]],
  312. Http::STATUS_BAD_REQUEST);
  313. } catch (\Exception $e) {
  314. $this->logger->logException($e, ['app' => 'core']);
  315. return new JSONResponse(['data' => ['message' => $this->l->t('An error occurred. Please contact your admin.')]], Http::STATUS_BAD_REQUEST);
  316. }
  317. }
  318. }