Completed
Push — master ( 853701...6db34d )
by
unknown
13:57 queued 10s
created

AvatarController::getAvatar()   A

Complexity

Conditions 5
Paths 21

Size

Total Lines 34

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
nc 21
nop 2
dl 0
loc 34
rs 9.0648
c 0
b 0
f 0
1
<?php
2
/**
3
 * @author Joas Schilling <[email protected]>
4
 * @author Lukas Reschke <[email protected]>
5
 * @author Martin Mattel <[email protected]>
6
 * @author Morris Jobke <[email protected]>
7
 * @author Robin Appelman <[email protected]>
8
 * @author Roeland Jago Douma <[email protected]>
9
 * @author Thomas Müller <[email protected]>
10
 * @author Vincent Petry <[email protected]>
11
 *
12
 * @copyright Copyright (c) 2018, ownCloud GmbH
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
30
use OC\AppFramework\Http\Request;
31
use OC\Cache\File;
32
use OC\Files\Filesystem;
33
use OC\NotSquareException;
34
use OCP\AppFramework\Controller;
35
use OCP\AppFramework\Http;
36
use OCP\AppFramework\Http\DataResponse;
37
use OCP\AppFramework\Http\DataDisplayResponse;
38
use OCP\Files\IRootFolder;
39
use OCP\Files\NotFoundException;
40
use OCP\IAvatarManager;
41
use OCP\ILogger;
42
use OCP\IL10N;
43
use OCP\IRequest;
44
use OCP\IUserManager;
45
use OCP\IUserSession;
46
47
/**
48
 * Class AvatarController
49
 *
50
 * @package OC\Core\Controller
51
 */
52
class AvatarController extends Controller {
53
54
	/** @var IAvatarManager */
55
	protected $avatarManager;
56
57
	/** @var File */
58
	protected $cache;
59
60
	/** @var IL10N */
61
	protected $l;
62
63
	/** @var IUserManager */
64
	protected $userManager;
65
66
	/** @var IUserSession */
67
	protected $userSession;
68
69
	/** @var IRootFolder */
70
	protected $rootFolder;
71
72
	/** @var ILogger */
73
	protected $logger;
74
75
	/**
76
	 * @param string $appName
77
	 * @param IRequest $request
78
	 * @param IAvatarManager $avatarManager
79
	 * @param File $cache
80
	 * @param IL10N $l10n
81
	 * @param IUserManager $userManager
82
	 * @param IUserSession $userSession
83
	 * @param IRootFolder $rootFolder
84
	 * @param ILogger $logger
85
	 */
86
	public function __construct($appName,
87
								IRequest $request,
88
								IAvatarManager $avatarManager,
89
								File $cache,
90
								IL10N $l10n,
91
								IUserManager $userManager,
92
								IUserSession $userSession,
93
								IRootFolder $rootFolder,
94
								ILogger $logger) {
95
		parent::__construct($appName, $request);
96
97
		$this->avatarManager = $avatarManager;
98
		$this->cache = $cache;
99
		$this->l = $l10n;
100
		$this->userManager = $userManager;
101
		$this->userSession = $userSession;
102
		$this->rootFolder = $rootFolder;
103
		$this->logger = $logger;
104
	}
105
106
	/**
107
	 * @NoAdminRequired
108
	 *
109
	 * @param string $path
110
	 * @return DataResponse
111
	 */
112
	public function postAvatar($path) {
113
		$userId = $this->userSession->getUser()->getUID();
114
		$files = $this->request->getUploadedFile('files');
115
116
		$headers = [];
117
		if ($this->request->isUserAgent([Request::USER_AGENT_IE_8])) {
118
			// due to upload iframe workaround, need to set content-type to text/plain
119
			$headers['Content-Type'] = 'text/plain';
120
		}
121
122
		if (isset($path)) {
123
			$path = \stripslashes($path);
124
			$node = $this->rootFolder->getUserFolder($userId)->get($path);
125 View Code Duplication
			if (!($node instanceof \OCP\Files\File)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
126
				return new DataResponse(['data' => ['message' => $this->l->t('Please select a file.')]], Http::STATUS_OK, $headers);
127
			}
128 View Code Duplication
			if ($node->getSize() > 20*1024*1024) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
129
				return new DataResponse(
130
					['data' => ['message' => $this->l->t('File is too big')]],
131
					Http::STATUS_BAD_REQUEST,
132
					$headers
133
				);
134
			}
135
			$content = $node->getContent();
136
		} elseif ($files !== null) {
137
			if (
138
				$files['error'][0] === 0 &&
139
				$this->isUploadFile($files['tmp_name'][0]) &&
140
				!Filesystem::isForbiddenFileOrDir($files['tmp_name'][0])
141
			) {
142 View Code Duplication
				if ($files['size'][0] > 20*1024*1024) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
143
					return new DataResponse(
144
						['data' => ['message' => $this->l->t('File is too big')]],
145
						Http::STATUS_BAD_REQUEST,
146
						$headers
147
					);
148
				}
149
				$this->cache->set('avatar_upload', \file_get_contents($files['tmp_name'][0]), 7200);
150
				$content = $this->cache->get('avatar_upload');
151
				\unlink($files['tmp_name'][0]);
152 View Code Duplication
			} else {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
153
				return new DataResponse(
154
					['data' => ['message' => $this->l->t('Invalid file provided')]],
155
					Http::STATUS_BAD_REQUEST,
156
					$headers
157
				);
158
			}
159 View Code Duplication
		} else {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
160
			//Add imgfile
161
			return new DataResponse(
162
				['data' => ['message' => $this->l->t('No image or file provided')]],
163
				Http::STATUS_BAD_REQUEST,
164
				$headers
165
			);
166
		}
167
168
		try {
169
			$image = new \OC_Image();
170
			$image->loadFromData($content);
171
			$image->fixOrientation();
172
173
			if ($image->valid()) {
174
				$mimeType = $image->mimeType();
175
				if ($mimeType !== 'image/jpeg' && $mimeType !== 'image/png') {
176
					return new DataResponse(
177
						['data' => ['message' => $this->l->t('Unknown filetype')]],
178
						Http::STATUS_OK,
179
						$headers
180
					);
181
				}
182
183
				$this->cache->set('tmpAvatar', $image->data(), 7200);
184
				return new DataResponse(
185
					['data' => 'notsquare'],
186
					Http::STATUS_OK,
187
					$headers
188
				);
189 View Code Duplication
			} else {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
190
				return new DataResponse(
191
					['data' => ['message' => $this->l->t('Invalid image')]],
192
					Http::STATUS_OK,
193
					$headers
194
				);
195
			}
196
		} catch (\Exception $e) {
197
			$this->logger->logException($e, ['app' => 'core']);
198
			return new DataResponse(['data' => ['message' => $this->l->t('An error occurred. Please contact your admin.')]], Http::STATUS_OK, $headers);
199
		}
200
	}
201
202
	/**
203
	 * @NoAdminRequired
204
	 *
205
	 * @return DataResponse
206
	 */
207
	public function deleteAvatar() {
208
		$userId = $this->userSession->getUser()->getUID();
209
210
		try {
211
			$avatar = $this->avatarManager->getAvatar($userId);
212
			$avatar->remove();
213
			return new DataResponse();
214
		} catch (\Exception $e) {
215
			$this->logger->logException($e, ['app' => 'core']);
216
			return new DataResponse(['data' => ['message' => $this->l->t('An error occurred. Please contact your admin.')]], Http::STATUS_BAD_REQUEST);
217
		}
218
	}
219
220
	/**
221
	 * @NoAdminRequired
222
	 *
223
	 * @return DataResponse|DataDisplayResponse
224
	 */
225
	public function getTmpAvatar() {
226
		$tmpAvatar = $this->cache->get('tmpAvatar');
227 View Code Duplication
		if ($tmpAvatar === null) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
228
			return new DataResponse(['data' => [
229
										'message' => $this->l->t("No temporary profile picture available, try again")
230
									]],
231
									Http::STATUS_NOT_FOUND);
232
		}
233
234
		$image = new \OC_Image($tmpAvatar);
235
236
		$resp = new DataDisplayResponse($image->data(),
237
				Http::STATUS_OK,
238
				['Content-Type' => $image->mimeType()]);
239
240
		$resp->setETag(\crc32($image->data()));
241
		$resp->cacheFor(0);
242
		$resp->setLastModified(new \DateTime('now', new \DateTimeZone('GMT')));
243
		return $resp;
244
	}
245
246
	/**
247
	 * @NoAdminRequired
248
	 *
249
	 * @param array $crop
250
	 * @return DataResponse
251
	 */
252
	public function postCroppedAvatar($crop) {
253
		$userId = $this->userSession->getUser()->getUID();
254
255 View Code Duplication
		if ($crop === null) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
256
			return new DataResponse(['data' => ['message' => $this->l->t("No crop data provided")]],
257
									Http::STATUS_BAD_REQUEST);
258
		}
259
260
		if (!isset($crop['x'], $crop['y'], $crop['w'], $crop['h'])) {
261
			return new DataResponse(['data' => ['message' => $this->l->t("No valid crop data provided")]],
262
									Http::STATUS_BAD_REQUEST);
263
		}
264
265
		$tmpAvatar = $this->cache->get('tmpAvatar');
266 View Code Duplication
		if ($tmpAvatar === null) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
267
			return new DataResponse(['data' => [
268
										'message' => $this->l->t("No temporary profile picture available, try again")
269
									]],
270
									Http::STATUS_BAD_REQUEST);
271
		}
272
273
		$image = new \OC_Image($tmpAvatar);
274
		$image->crop($crop['x'], $crop['y'], \round($crop['w']), \round($crop['h']));
275
		try {
276
			$avatar = $this->avatarManager->getAvatar($userId);
277
			$avatar->set($image);
278
			// Clean up
279
			$this->cache->remove('tmpAvatar');
280
			return new DataResponse(['status' => 'success']);
281
		} catch (NotSquareException $e) {
282
			return new DataResponse(['data' => ['message' => $this->l->t('Crop is not square')]],
283
									Http::STATUS_BAD_REQUEST);
284
		} catch (\Exception $e) {
285
			$this->logger->logException($e, ['app' => 'core']);
286
			return new DataResponse(['data' => ['message' => $this->l->t('An error occurred. Please contact your admin.')]], Http::STATUS_BAD_REQUEST);
287
		}
288
	}
289
290
	/**
291
	 * @param string $file
292
	 * @return bool
293
	 */
294
	protected function isUploadFile($file) {
295
		return \is_uploaded_file($file);
296
	}
297
}
298