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 8.9KB

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