You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

AvatarController.php 9.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  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. *
  12. * @license AGPL-3.0
  13. *
  14. * This code is free software: you can redistribute it and/or modify
  15. * it under the terms of the GNU Affero General Public License, version 3,
  16. * as published by the Free Software Foundation.
  17. *
  18. * This program is distributed in the hope that it will be useful,
  19. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  20. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  21. * GNU Affero General Public License for more details.
  22. *
  23. * You should have received a copy of the GNU Affero General Public License, version 3,
  24. * along with this program. If not, see <http://www.gnu.org/licenses/>
  25. *
  26. */
  27. namespace OC\Core\Controller;
  28. use OC\AppFramework\Utility\TimeFactory;
  29. use OCP\AppFramework\Controller;
  30. use OCP\AppFramework\Http;
  31. use OCP\AppFramework\Http\DataDisplayResponse;
  32. use OCP\AppFramework\Http\FileDisplayResponse;
  33. use OCP\AppFramework\Http\JSONResponse;
  34. use OCP\Files\File;
  35. use OCP\Files\IRootFolder;
  36. use OCP\IAvatarManager;
  37. use OCP\ICache;
  38. use OCP\ILogger;
  39. use OCP\IL10N;
  40. use OCP\IRequest;
  41. use OCP\IUserManager;
  42. use OCP\IUserSession;
  43. /**
  44. * Class AvatarController
  45. *
  46. * @package OC\Core\Controller
  47. */
  48. class AvatarController extends Controller {
  49. /** @var IAvatarManager */
  50. protected $avatarManager;
  51. /** @var ICache */
  52. protected $cache;
  53. /** @var IL10N */
  54. protected $l;
  55. /** @var IUserManager */
  56. protected $userManager;
  57. /** @var IUserSession */
  58. protected $userSession;
  59. /** @var IRootFolder */
  60. protected $rootFolder;
  61. /** @var ILogger */
  62. protected $logger;
  63. /** @var string */
  64. protected $userId;
  65. /** @var TimeFactory */
  66. protected $timeFactory;
  67. /**
  68. * @param string $appName
  69. * @param IRequest $request
  70. * @param IAvatarManager $avatarManager
  71. * @param ICache $cache
  72. * @param IL10N $l10n
  73. * @param IUserManager $userManager
  74. * @param IRootFolder $rootFolder
  75. * @param ILogger $logger
  76. * @param string $userId
  77. * @param TimeFactory $timeFactory
  78. */
  79. public function __construct($appName,
  80. IRequest $request,
  81. IAvatarManager $avatarManager,
  82. ICache $cache,
  83. IL10N $l10n,
  84. IUserManager $userManager,
  85. IRootFolder $rootFolder,
  86. ILogger $logger,
  87. $userId,
  88. TimeFactory $timeFactory) {
  89. parent::__construct($appName, $request);
  90. $this->avatarManager = $avatarManager;
  91. $this->cache = $cache;
  92. $this->l = $l10n;
  93. $this->userManager = $userManager;
  94. $this->rootFolder = $rootFolder;
  95. $this->logger = $logger;
  96. $this->userId = $userId;
  97. $this->timeFactory = $timeFactory;
  98. }
  99. /**
  100. * @NoAdminRequired
  101. * @NoCSRFRequired
  102. * @NoSameSiteCookieRequired
  103. * @PublicPage
  104. *
  105. * @param string $userId
  106. * @param int $size
  107. * @return JSONResponse|FileDisplayResponse
  108. */
  109. public function getAvatar($userId, $size) {
  110. if ($size > 2048) {
  111. $size = 2048;
  112. } elseif ($size <= 0) {
  113. $size = 64;
  114. }
  115. try {
  116. $avatar = $this->avatarManager->getAvatar($userId)->getFile($size);
  117. $resp = new FileDisplayResponse($avatar,
  118. Http::STATUS_OK,
  119. ['Content-Type' => $avatar->getMimeType()]);
  120. } catch (\Exception $e) {
  121. $resp = new Http\Response();
  122. $resp->setStatus(Http::STATUS_NOT_FOUND);
  123. return $resp;
  124. }
  125. // Let cache this!
  126. $resp->addHeader('Pragma', 'public');
  127. // Cache for 30 minutes
  128. $resp->cacheFor(1800);
  129. $expires = new \DateTime();
  130. $expires->setTimestamp($this->timeFactory->getTime());
  131. $expires->add(new \DateInterval('PT30M'));
  132. $resp->addHeader('Expires', $expires->format(\DateTime::RFC1123));
  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. }