AvatarController.php 9.4 KB

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