AvatarController.php 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Joas Schilling <coding@schilljs.com>
  6. * @author John Molakvoæ (skjnldsv) <skjnldsv@protonmail.com>
  7. * @author Lukas Reschke <lukas@statuscode.ch>
  8. * @author Morris Jobke <hey@morrisjobke.de>
  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\Accounts\IAccountManager;
  31. use OCP\AppFramework\Controller;
  32. use OCP\AppFramework\Http;
  33. use OCP\AppFramework\Http\DataDisplayResponse;
  34. use OCP\AppFramework\Http\FileDisplayResponse;
  35. use OCP\AppFramework\Http\JSONResponse;
  36. use OCP\Files\File;
  37. use OCP\Files\IRootFolder;
  38. use OCP\IAvatarManager;
  39. use OCP\ICache;
  40. use OCP\IL10N;
  41. use OCP\ILogger;
  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. /** @var IAccountManager */
  70. private $accountManager;
  71. public function __construct($appName,
  72. IRequest $request,
  73. IAvatarManager $avatarManager,
  74. ICache $cache,
  75. IL10N $l10n,
  76. IUserManager $userManager,
  77. IRootFolder $rootFolder,
  78. ILogger $logger,
  79. $userId,
  80. TimeFactory $timeFactory,
  81. IAccountManager $accountManager) {
  82. parent::__construct($appName, $request);
  83. $this->avatarManager = $avatarManager;
  84. $this->cache = $cache;
  85. $this->l = $l10n;
  86. $this->userManager = $userManager;
  87. $this->rootFolder = $rootFolder;
  88. $this->logger = $logger;
  89. $this->userId = $userId;
  90. $this->timeFactory = $timeFactory;
  91. $this->accountManager = $accountManager;
  92. }
  93. /**
  94. * @NoAdminRequired
  95. * @NoCSRFRequired
  96. * @NoSameSiteCookieRequired
  97. * @PublicPage
  98. *
  99. * @param string $userId
  100. * @param int $size
  101. * @return JSONResponse|FileDisplayResponse
  102. */
  103. public function getAvatar($userId, $size) {
  104. // min/max size
  105. if ($size > 2048) {
  106. $size = 2048;
  107. } elseif ($size <= 0) {
  108. $size = 64;
  109. }
  110. $user = $this->userManager->get($userId);
  111. if ($user === null) {
  112. return new JSONResponse([], Http::STATUS_NOT_FOUND);
  113. }
  114. $account = $this->accountManager->getAccount($user);
  115. $scope = $account->getProperty(IAccountManager::PROPERTY_AVATAR)->getScope();
  116. if ($scope !== IAccountManager::VISIBILITY_PUBLIC && $this->userId === null) {
  117. // Public avatar access is not allowed
  118. return new JSONResponse([], Http::STATUS_NOT_FOUND);
  119. }
  120. try {
  121. $avatar = $this->avatarManager->getAvatar($userId);
  122. $avatarFile = $avatar->getFile($size);
  123. $resp = new FileDisplayResponse(
  124. $avatarFile,
  125. $avatar->isCustomAvatar() ? Http::STATUS_OK : Http::STATUS_CREATED,
  126. ['Content-Type' => $avatarFile->getMimeType()]
  127. );
  128. } catch (\Exception $e) {
  129. return new JSONResponse([], Http::STATUS_NOT_FOUND);
  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. }