AvatarController.php 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  6. * @author Daniel Kesselberg <mail@danielkesselberg.de>
  7. * @author Joas Schilling <coding@schilljs.com>
  8. * @author John Molakvoæ (skjnldsv) <skjnldsv@protonmail.com>
  9. * @author Lukas Reschke <lukas@statuscode.ch>
  10. * @author Morris Jobke <hey@morrisjobke.de>
  11. * @author Roeland Jago Douma <roeland@famdouma.nl>
  12. * @author Thomas Müller <thomas.mueller@tmit.eu>
  13. * @author Vincent Petry <pvince81@owncloud.com>
  14. *
  15. * @license AGPL-3.0
  16. *
  17. * This code is free software: you can redistribute it and/or modify
  18. * it under the terms of the GNU Affero General Public License, version 3,
  19. * as published by the Free Software Foundation.
  20. *
  21. * This program is distributed in the hope that it will be useful,
  22. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  23. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  24. * GNU Affero General Public License for more details.
  25. *
  26. * You should have received a copy of the GNU Affero General Public License, version 3,
  27. * along with this program. If not, see <http://www.gnu.org/licenses/>
  28. *
  29. */
  30. namespace OC\Core\Controller;
  31. use OC\AppFramework\Utility\TimeFactory;
  32. use OCP\Accounts\IAccountManager;
  33. use OCP\AppFramework\Controller;
  34. use OCP\AppFramework\Http;
  35. use OCP\AppFramework\Http\DataDisplayResponse;
  36. use OCP\AppFramework\Http\FileDisplayResponse;
  37. use OCP\AppFramework\Http\JSONResponse;
  38. use OCP\Files\File;
  39. use OCP\Files\IRootFolder;
  40. use OCP\IAvatarManager;
  41. use OCP\ICache;
  42. use OCP\IL10N;
  43. use OCP\ILogger;
  44. use OCP\IRequest;
  45. use OCP\IUserManager;
  46. use OCP\IUserSession;
  47. /**
  48. * Class AvatarController
  49. *
  50. * @package OC\Core\Controller
  51. */
  52. class AvatarController extends Controller {
  53. /** @var IAvatarManager */
  54. protected $avatarManager;
  55. /** @var ICache */
  56. protected $cache;
  57. /** @var IL10N */
  58. protected $l;
  59. /** @var IUserManager */
  60. protected $userManager;
  61. /** @var IUserSession */
  62. protected $userSession;
  63. /** @var IRootFolder */
  64. protected $rootFolder;
  65. /** @var ILogger */
  66. protected $logger;
  67. /** @var string */
  68. protected $userId;
  69. /** @var TimeFactory */
  70. protected $timeFactory;
  71. /** @var IAccountManager */
  72. private $accountManager;
  73. public function __construct($appName,
  74. IRequest $request,
  75. IAvatarManager $avatarManager,
  76. ICache $cache,
  77. IL10N $l10n,
  78. IUserManager $userManager,
  79. IRootFolder $rootFolder,
  80. ILogger $logger,
  81. $userId,
  82. TimeFactory $timeFactory,
  83. IAccountManager $accountManager) {
  84. parent::__construct($appName, $request);
  85. $this->avatarManager = $avatarManager;
  86. $this->cache = $cache;
  87. $this->l = $l10n;
  88. $this->userManager = $userManager;
  89. $this->rootFolder = $rootFolder;
  90. $this->logger = $logger;
  91. $this->userId = $userId;
  92. $this->timeFactory = $timeFactory;
  93. $this->accountManager = $accountManager;
  94. }
  95. /**
  96. * @NoAdminRequired
  97. * @NoCSRFRequired
  98. * @NoSameSiteCookieRequired
  99. * @PublicPage
  100. *
  101. * @param string $userId
  102. * @param int $size
  103. * @return JSONResponse|FileDisplayResponse
  104. */
  105. public function getAvatar($userId, $size) {
  106. // min/max size
  107. if ($size > 2048) {
  108. $size = 2048;
  109. } elseif ($size <= 0) {
  110. $size = 64;
  111. }
  112. $user = $this->userManager->get($userId);
  113. if ($user === null) {
  114. return new JSONResponse([], Http::STATUS_NOT_FOUND);
  115. }
  116. $account = $this->accountManager->getAccount($user);
  117. $scope = $account->getProperty(IAccountManager::PROPERTY_AVATAR)->getScope();
  118. if ($scope !== IAccountManager::VISIBILITY_PUBLIC && $this->userId === null) {
  119. // Public avatar access is not allowed
  120. $response = new JSONResponse([], Http::STATUS_NOT_FOUND);
  121. $response->cacheFor(1800);
  122. return $response;
  123. }
  124. try {
  125. $avatar = $this->avatarManager->getAvatar($userId);
  126. $avatarFile = $avatar->getFile($size);
  127. $response = new FileDisplayResponse(
  128. $avatarFile,
  129. Http::STATUS_OK,
  130. ['Content-Type' => $avatarFile->getMimeType(), 'X-NC-IsCustomAvatar' => (int)$avatar->isCustomAvatar()]
  131. );
  132. } catch (\Exception $e) {
  133. return new JSONResponse([], Http::STATUS_NOT_FOUND);
  134. }
  135. // Cache for 1 day
  136. $response->cacheFor(60*60*24);
  137. return $response;
  138. }
  139. /**
  140. * @NoAdminRequired
  141. *
  142. * @param string $path
  143. * @return JSONResponse
  144. */
  145. public function postAvatar($path) {
  146. $files = $this->request->getUploadedFile('files');
  147. if (isset($path)) {
  148. $path = stripslashes($path);
  149. $userFolder = $this->rootFolder->getUserFolder($this->userId);
  150. /** @var File $node */
  151. $node = $userFolder->get($path);
  152. if (!($node instanceof File)) {
  153. return new JSONResponse(['data' => ['message' => $this->l->t('Please select a file.')]]);
  154. }
  155. if ($node->getSize() > 20*1024*1024) {
  156. return new JSONResponse(
  157. ['data' => ['message' => $this->l->t('File is too big')]],
  158. Http::STATUS_BAD_REQUEST
  159. );
  160. }
  161. if ($node->getMimeType() !== 'image/jpeg' && $node->getMimeType() !== 'image/png') {
  162. return new JSONResponse(
  163. ['data' => ['message' => $this->l->t('The selected file is not an image.')]],
  164. Http::STATUS_BAD_REQUEST
  165. );
  166. }
  167. try {
  168. $content = $node->getContent();
  169. } catch (\OCP\Files\NotPermittedException $e) {
  170. return new JSONResponse(
  171. ['data' => ['message' => $this->l->t('The selected file cannot be read.')]],
  172. Http::STATUS_BAD_REQUEST
  173. );
  174. }
  175. } elseif (!is_null($files)) {
  176. if (
  177. $files['error'][0] === 0 &&
  178. is_uploaded_file($files['tmp_name'][0]) &&
  179. !\OC\Files\Filesystem::isFileBlacklisted($files['tmp_name'][0])
  180. ) {
  181. if ($files['size'][0] > 20*1024*1024) {
  182. return new JSONResponse(
  183. ['data' => ['message' => $this->l->t('File is too big')]],
  184. Http::STATUS_BAD_REQUEST
  185. );
  186. }
  187. $this->cache->set('avatar_upload', file_get_contents($files['tmp_name'][0]), 7200);
  188. $content = $this->cache->get('avatar_upload');
  189. unlink($files['tmp_name'][0]);
  190. } else {
  191. return new JSONResponse(
  192. ['data' => ['message' => $this->l->t('Invalid file provided')]],
  193. Http::STATUS_BAD_REQUEST
  194. );
  195. }
  196. } else {
  197. //Add imgfile
  198. return new JSONResponse(
  199. ['data' => ['message' => $this->l->t('No image or file provided')]],
  200. Http::STATUS_BAD_REQUEST
  201. );
  202. }
  203. try {
  204. $image = new \OC_Image();
  205. $image->loadFromData($content);
  206. $image->readExif($content);
  207. $image->fixOrientation();
  208. if ($image->valid()) {
  209. $mimeType = $image->mimeType();
  210. if ($mimeType !== 'image/jpeg' && $mimeType !== 'image/png') {
  211. return new JSONResponse(
  212. ['data' => ['message' => $this->l->t('Unknown filetype')]],
  213. Http::STATUS_OK
  214. );
  215. }
  216. $this->cache->set('tmpAvatar', $image->data(), 7200);
  217. return new JSONResponse(
  218. ['data' => 'notsquare'],
  219. Http::STATUS_OK
  220. );
  221. } else {
  222. return new JSONResponse(
  223. ['data' => ['message' => $this->l->t('Invalid image')]],
  224. Http::STATUS_OK
  225. );
  226. }
  227. } catch (\Exception $e) {
  228. $this->logger->logException($e, ['app' => 'core']);
  229. return new JSONResponse(['data' => ['message' => $this->l->t('An error occurred. Please contact your admin.')]], Http::STATUS_OK);
  230. }
  231. }
  232. /**
  233. * @NoAdminRequired
  234. *
  235. * @return JSONResponse
  236. */
  237. public function deleteAvatar() {
  238. try {
  239. $avatar = $this->avatarManager->getAvatar($this->userId);
  240. $avatar->remove();
  241. return new JSONResponse();
  242. } catch (\Exception $e) {
  243. $this->logger->logException($e, ['app' => 'core']);
  244. return new JSONResponse(['data' => ['message' => $this->l->t('An error occurred. Please contact your admin.')]], Http::STATUS_BAD_REQUEST);
  245. }
  246. }
  247. /**
  248. * @NoAdminRequired
  249. *
  250. * @return JSONResponse|DataDisplayResponse
  251. */
  252. public function getTmpAvatar() {
  253. $tmpAvatar = $this->cache->get('tmpAvatar');
  254. if (is_null($tmpAvatar)) {
  255. return new JSONResponse(['data' => [
  256. 'message' => $this->l->t("No temporary profile picture available, try again")
  257. ]],
  258. Http::STATUS_NOT_FOUND);
  259. }
  260. $image = new \OC_Image();
  261. $image->loadFromData($tmpAvatar);
  262. $resp = new DataDisplayResponse($image->data(),
  263. Http::STATUS_OK,
  264. ['Content-Type' => $image->mimeType()]);
  265. $resp->setETag((string)crc32($image->data()));
  266. $resp->cacheFor(0);
  267. $resp->setLastModified(new \DateTime('now', new \DateTimeZone('GMT')));
  268. return $resp;
  269. }
  270. /**
  271. * @NoAdminRequired
  272. *
  273. * @param array $crop
  274. * @return JSONResponse
  275. */
  276. public function postCroppedAvatar($crop) {
  277. if (is_null($crop)) {
  278. return new JSONResponse(['data' => ['message' => $this->l->t("No crop data provided")]],
  279. Http::STATUS_BAD_REQUEST);
  280. }
  281. if (!isset($crop['x'], $crop['y'], $crop['w'], $crop['h'])) {
  282. return new JSONResponse(['data' => ['message' => $this->l->t("No valid crop data provided")]],
  283. Http::STATUS_BAD_REQUEST);
  284. }
  285. $tmpAvatar = $this->cache->get('tmpAvatar');
  286. if (is_null($tmpAvatar)) {
  287. return new JSONResponse(['data' => [
  288. 'message' => $this->l->t("No temporary profile picture available, try again")
  289. ]],
  290. Http::STATUS_BAD_REQUEST);
  291. }
  292. $image = new \OC_Image();
  293. $image->loadFromData($tmpAvatar);
  294. $image->crop($crop['x'], $crop['y'], (int)round($crop['w']), (int)round($crop['h']));
  295. try {
  296. $avatar = $this->avatarManager->getAvatar($this->userId);
  297. $avatar->set($image);
  298. // Clean up
  299. $this->cache->remove('tmpAvatar');
  300. return new JSONResponse(['status' => 'success']);
  301. } catch (\OC\NotSquareException $e) {
  302. return new JSONResponse(['data' => ['message' => $this->l->t('Crop is not square')]],
  303. Http::STATUS_BAD_REQUEST);
  304. } catch (\Exception $e) {
  305. $this->logger->logException($e, ['app' => 'core']);
  306. return new JSONResponse(['data' => ['message' => $this->l->t('An error occurred. Please contact your admin.')]], Http::STATUS_BAD_REQUEST);
  307. }
  308. }
  309. }