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.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  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. /**
  45. * Class AvatarController
  46. *
  47. * @package OC\Core\Controller
  48. */
  49. class AvatarController extends Controller {
  50. /** @var IAvatarManager */
  51. protected $avatarManager;
  52. /** @var ICache */
  53. protected $cache;
  54. /** @var IL10N */
  55. protected $l;
  56. /** @var IUserManager */
  57. protected $userManager;
  58. /** @var IUserSession */
  59. protected $userSession;
  60. /** @var IRootFolder */
  61. protected $rootFolder;
  62. /** @var ILogger */
  63. protected $logger;
  64. /** @var string */
  65. protected $userId;
  66. /** @var TimeFactory */
  67. protected $timeFactory;
  68. /**
  69. * @param string $appName
  70. * @param IRequest $request
  71. * @param IAvatarManager $avatarManager
  72. * @param ICache $cache
  73. * @param IL10N $l10n
  74. * @param IUserManager $userManager
  75. * @param IRootFolder $rootFolder
  76. * @param ILogger $logger
  77. * @param string $userId
  78. * @param TimeFactory $timeFactory
  79. */
  80. public function __construct($appName,
  81. IRequest $request,
  82. IAvatarManager $avatarManager,
  83. ICache $cache,
  84. IL10N $l10n,
  85. IUserManager $userManager,
  86. IRootFolder $rootFolder,
  87. ILogger $logger,
  88. $userId,
  89. TimeFactory $timeFactory) {
  90. parent::__construct($appName, $request);
  91. $this->avatarManager = $avatarManager;
  92. $this->cache = $cache;
  93. $this->l = $l10n;
  94. $this->userManager = $userManager;
  95. $this->rootFolder = $rootFolder;
  96. $this->logger = $logger;
  97. $this->userId = $userId;
  98. $this->timeFactory = $timeFactory;
  99. }
  100. /**
  101. * @NoAdminRequired
  102. * @NoCSRFRequired
  103. * @NoSameSiteCookieRequired
  104. * @PublicPage
  105. *
  106. * @param string $userId
  107. * @param int $size
  108. * @return JSONResponse|FileDisplayResponse
  109. */
  110. public function getAvatar($userId, $size) {
  111. // min/max size
  112. if ($size > 2048) {
  113. $size = 2048;
  114. } elseif ($size <= 0) {
  115. $size = 64;
  116. }
  117. try {
  118. $avatar = $this->avatarManager->getAvatar($userId);
  119. $avatarFile = $avatar->getFile($size);
  120. $resp = new FileDisplayResponse(
  121. $avatarFile,
  122. $avatar->isCustomAvatar() ? Http::STATUS_OK : Http::STATUS_CREATED,
  123. ['Content-Type' => $avatarFile->getMimeType()]
  124. );
  125. } catch (\Exception $e) {
  126. $resp = new Http\Response();
  127. $resp->setStatus(Http::STATUS_NOT_FOUND);
  128. return $resp;
  129. }
  130. // Cache for 30 minutes
  131. $resp->cacheFor(1800);
  132. return $resp;
  133. }
  134. /**
  135. * @NoAdminRequired
  136. *
  137. * @param string $path
  138. * @return JSONResponse
  139. */
  140. public function postAvatar($path) {
  141. $files = $this->request->getUploadedFile('files');
  142. if (isset($path)) {
  143. $path = stripslashes($path);
  144. $userFolder = $this->rootFolder->getUserFolder($this->userId);
  145. /** @var File $node */
  146. $node = $userFolder->get($path);
  147. if (!($node instanceof File)) {
  148. return new JSONResponse(['data' => ['message' => $this->l->t('Please select a file.')]]);
  149. }
  150. if ($node->getSize() > 20*1024*1024) {
  151. return new JSONResponse(
  152. ['data' => ['message' => $this->l->t('File is too big')]],
  153. Http::STATUS_BAD_REQUEST
  154. );
  155. }
  156. if ($node->getMimeType() !== 'image/jpeg' && $node->getMimeType() !== 'image/png') {
  157. return new JSONResponse(
  158. ['data' => ['message' => $this->l->t('The selected file is not an image.')]],
  159. Http::STATUS_BAD_REQUEST
  160. );
  161. }
  162. try {
  163. $content = $node->getContent();
  164. } catch (\OCP\Files\NotPermittedException $e) {
  165. return new JSONResponse(
  166. ['data' => ['message' => $this->l->t('The selected file cannot be read.')]],
  167. Http::STATUS_BAD_REQUEST
  168. );
  169. }
  170. } elseif (!is_null($files)) {
  171. if (
  172. $files['error'][0] === 0 &&
  173. is_uploaded_file($files['tmp_name'][0]) &&
  174. !\OC\Files\Filesystem::isFileBlacklisted($files['tmp_name'][0])
  175. ) {
  176. if ($files['size'][0] > 20*1024*1024) {
  177. return new JSONResponse(
  178. ['data' => ['message' => $this->l->t('File is too big')]],
  179. Http::STATUS_BAD_REQUEST
  180. );
  181. }
  182. $this->cache->set('avatar_upload', file_get_contents($files['tmp_name'][0]), 7200);
  183. $content = $this->cache->get('avatar_upload');
  184. unlink($files['tmp_name'][0]);
  185. } else {
  186. return new JSONResponse(
  187. ['data' => ['message' => $this->l->t('Invalid file provided')]],
  188. Http::STATUS_BAD_REQUEST
  189. );
  190. }
  191. } else {
  192. //Add imgfile
  193. return new JSONResponse(
  194. ['data' => ['message' => $this->l->t('No image or file provided')]],
  195. Http::STATUS_BAD_REQUEST
  196. );
  197. }
  198. try {
  199. $image = new \OC_Image();
  200. $image->loadFromData($content);
  201. $image->readExif($content);
  202. $image->fixOrientation();
  203. if ($image->valid()) {
  204. $mimeType = $image->mimeType();
  205. if ($mimeType !== 'image/jpeg' && $mimeType !== 'image/png') {
  206. return new JSONResponse(
  207. ['data' => ['message' => $this->l->t('Unknown filetype')]],
  208. Http::STATUS_OK
  209. );
  210. }
  211. $this->cache->set('tmpAvatar', $image->data(), 7200);
  212. return new JSONResponse(
  213. ['data' => 'notsquare'],
  214. Http::STATUS_OK
  215. );
  216. } else {
  217. return new JSONResponse(
  218. ['data' => ['message' => $this->l->t('Invalid image')]],
  219. Http::STATUS_OK
  220. );
  221. }
  222. } catch (\Exception $e) {
  223. $this->logger->logException($e, ['app' => 'core']);
  224. return new JSONResponse(['data' => ['message' => $this->l->t('An error occurred. Please contact your admin.')]], Http::STATUS_OK);
  225. }
  226. }
  227. /**
  228. * @NoAdminRequired
  229. *
  230. * @return JSONResponse
  231. */
  232. public function deleteAvatar() {
  233. try {
  234. $avatar = $this->avatarManager->getAvatar($this->userId);
  235. $avatar->remove();
  236. return new JSONResponse();
  237. } catch (\Exception $e) {
  238. $this->logger->logException($e, ['app' => 'core']);
  239. return new JSONResponse(['data' => ['message' => $this->l->t('An error occurred. Please contact your admin.')]], Http::STATUS_BAD_REQUEST);
  240. }
  241. }
  242. /**
  243. * @NoAdminRequired
  244. *
  245. * @return JSONResponse|DataDisplayResponse
  246. */
  247. public function getTmpAvatar() {
  248. $tmpAvatar = $this->cache->get('tmpAvatar');
  249. if (is_null($tmpAvatar)) {
  250. return new JSONResponse(['data' => [
  251. 'message' => $this->l->t("No temporary profile picture available, try again")
  252. ]],
  253. Http::STATUS_NOT_FOUND);
  254. }
  255. $image = new \OC_Image();
  256. $image->loadFromData($tmpAvatar);
  257. $resp = new DataDisplayResponse($image->data(),
  258. Http::STATUS_OK,
  259. ['Content-Type' => $image->mimeType()]);
  260. $resp->setETag((string)crc32($image->data()));
  261. $resp->cacheFor(0);
  262. $resp->setLastModified(new \DateTime('now', new \DateTimeZone('GMT')));
  263. return $resp;
  264. }
  265. /**
  266. * @NoAdminRequired
  267. *
  268. * @param array $crop
  269. * @return JSONResponse
  270. */
  271. public function postCroppedAvatar($crop) {
  272. if (is_null($crop)) {
  273. return new JSONResponse(['data' => ['message' => $this->l->t("No crop data provided")]],
  274. Http::STATUS_BAD_REQUEST);
  275. }
  276. if (!isset($crop['x'], $crop['y'], $crop['w'], $crop['h'])) {
  277. return new JSONResponse(['data' => ['message' => $this->l->t("No valid crop data provided")]],
  278. Http::STATUS_BAD_REQUEST);
  279. }
  280. $tmpAvatar = $this->cache->get('tmpAvatar');
  281. if (is_null($tmpAvatar)) {
  282. return new JSONResponse(['data' => [
  283. 'message' => $this->l->t("No temporary profile picture available, try again")
  284. ]],
  285. Http::STATUS_BAD_REQUEST);
  286. }
  287. $image = new \OC_Image();
  288. $image->loadFromData($tmpAvatar);
  289. $image->crop($crop['x'], $crop['y'], (int)round($crop['w']), (int)round($crop['h']));
  290. try {
  291. $avatar = $this->avatarManager->getAvatar($this->userId);
  292. $avatar->set($image);
  293. // Clean up
  294. $this->cache->remove('tmpAvatar');
  295. return new JSONResponse(['status' => 'success']);
  296. } catch (\OC\NotSquareException $e) {
  297. return new JSONResponse(['data' => ['message' => $this->l->t('Crop is not square')]],
  298. Http::STATUS_BAD_REQUEST);
  299. } catch (\Exception $e) {
  300. $this->logger->logException($e, ['app' => 'core']);
  301. return new JSONResponse(['data' => ['message' => $this->l->t('An error occurred. Please contact your admin.')]], Http::STATUS_BAD_REQUEST);
  302. }
  303. }
  304. }