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.

338 lines
9.8 KiB

10 years ago
10 years ago
10 years ago
10 years ago
  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 <vincent@nextcloud.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. $phpFileUploadErrors = [
  175. UPLOAD_ERR_OK => $this->l->t('The file was uploaded'),
  176. UPLOAD_ERR_INI_SIZE => $this->l->t('The uploaded file exceeds the upload_max_filesize directive in php.ini'),
  177. UPLOAD_ERR_FORM_SIZE => $this->l->t('The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form'),
  178. UPLOAD_ERR_PARTIAL => $this->l->t('The file was only partially uploaded'),
  179. UPLOAD_ERR_NO_FILE => $this->l->t('No file was uploaded'),
  180. UPLOAD_ERR_NO_TMP_DIR => $this->l->t('Missing a temporary folder'),
  181. UPLOAD_ERR_CANT_WRITE => $this->l->t('Could not write file to disk'),
  182. UPLOAD_ERR_EXTENSION => $this->l->t('A PHP extension stopped the file upload'),
  183. ];
  184. $message = $phpFileUploadErrors[$files['error'][0]] ?? $this->l->t('Invalid file provided');
  185. $this->logger->warning($message, ['app' => 'core']);
  186. return new JSONResponse(
  187. ['data' => ['message' => $message]],
  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. }