AvatarController.php 9.5 KB

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