Completed
Pull Request — master (#6813)
by Lukas
15:07
created
core/Controller/AvatarController.php 1 patch
Indentation   +293 added lines, -293 removed lines patch added patch discarded remove patch
@@ -51,298 +51,298 @@
 block discarded – undo
51 51
  */
52 52
 class AvatarController extends Controller {
53 53
 
54
-	/** @var IAvatarManager */
55
-	protected $avatarManager;
56
-
57
-	/** @var ICache */
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
-	/** @var string */
76
-	protected $userId;
77
-
78
-	/** @var TimeFactory */
79
-	protected $timeFactory;
80
-
81
-	/**
82
-	 * @param string $appName
83
-	 * @param IRequest $request
84
-	 * @param IAvatarManager $avatarManager
85
-	 * @param ICache $cache
86
-	 * @param IL10N $l10n
87
-	 * @param IUserManager $userManager
88
-	 * @param IRootFolder $rootFolder
89
-	 * @param ILogger $logger
90
-	 * @param string $userId
91
-	 * @param TimeFactory $timeFactory
92
-	 */
93
-	public function __construct($appName,
94
-								IRequest $request,
95
-								IAvatarManager $avatarManager,
96
-								ICache $cache,
97
-								IL10N $l10n,
98
-								IUserManager $userManager,
99
-								IRootFolder $rootFolder,
100
-								ILogger $logger,
101
-								$userId,
102
-								TimeFactory $timeFactory) {
103
-		parent::__construct($appName, $request);
104
-
105
-		$this->avatarManager = $avatarManager;
106
-		$this->cache = $cache;
107
-		$this->l = $l10n;
108
-		$this->userManager = $userManager;
109
-		$this->rootFolder = $rootFolder;
110
-		$this->logger = $logger;
111
-		$this->userId = $userId;
112
-		$this->timeFactory = $timeFactory;
113
-	}
114
-
115
-	/**
116
-	 * @NoAdminRequired
117
-	 * @NoCSRFRequired
118
-	 * @NoSameSiteCookieRequired
119
-	 * @PublicPage
120
-	 *
121
-	 * @param string $userId
122
-	 * @param int $size
123
-	 * @return JSONResponse|FileDisplayResponse
124
-	 */
125
-	public function getAvatar($userId, $size) {
126
-		if ($size > 2048) {
127
-			$size = 2048;
128
-		} elseif ($size <= 0) {
129
-			$size = 64;
130
-		}
131
-
132
-		try {
133
-			$avatar = $this->avatarManager->getAvatar($userId)->getFile($size);
134
-			$resp = new FileDisplayResponse($avatar,
135
-				Http::STATUS_OK,
136
-				['Content-Type' => $avatar->getMimeType()]);
137
-		} catch (NotFoundException $e) {
138
-			$user = $this->userManager->get($userId);
139
-			$resp = new JSONResponse([
140
-				'data' => [
141
-					'displayname' => $user->getDisplayName(),
142
-				],
143
-			]);
144
-		} catch (\Exception $e) {
145
-			$resp = new JSONResponse([
146
-				'data' => [
147
-					'displayname' => $userId,
148
-				],
149
-			]);
150
-		}
151
-
152
-		// Let cache this!
153
-		$resp->addHeader('Pragma', 'public');
154
-		// Cache for 30 minutes
155
-		$resp->cacheFor(1800);
156
-
157
-		$expires = new \DateTime();
158
-		$expires->setTimestamp($this->timeFactory->getTime());
159
-		$expires->add(new \DateInterval('PT30M'));
160
-		$resp->addHeader('Expires', $expires->format(\DateTime::RFC1123));
161
-
162
-		return $resp;
163
-	}
164
-
165
-	/**
166
-	 * @NoAdminRequired
167
-	 *
168
-	 * @param string $path
169
-	 * @return JSONResponse
170
-	 */
171
-	public function postAvatar($path) {
172
-		$files = $this->request->getUploadedFile('files');
173
-
174
-		if (isset($path)) {
175
-			$path = stripslashes($path);
176
-			$userFolder = $this->rootFolder->getUserFolder($this->userId);
177
-			/** @var File $node */
178
-			$node = $userFolder->get($path);
179
-			if (!($node instanceof File)) {
180
-				return new JSONResponse(['data' => ['message' => $this->l->t('Please select a file.')]]);
181
-			}
182
-			if ($node->getSize() > 20*1024*1024) {
183
-				return new JSONResponse(
184
-					['data' => ['message' => $this->l->t('File is too big')]],
185
-					Http::STATUS_BAD_REQUEST
186
-				);
187
-			}
188
-
189
-			if ($node->getMimeType() !== 'image/jpeg' && $node->getMimeType() !== 'image/png') {
190
-				return new JSONResponse(
191
-					['data' => ['message' => $this->l->t('The selected file is not an image.')]],
192
-					Http::STATUS_BAD_REQUEST
193
-				);
194
-			}
195
-
196
-			try {
197
-				$content = $node->getContent();
198
-			} catch (\OCP\Files\NotPermittedException $e) {
199
-				return new JSONResponse(
200
-					['data' => ['message' => $this->l->t('The selected file cannot be read.')]],
201
-					Http::STATUS_BAD_REQUEST
202
-				);
203
-			}
204
-		} elseif (!is_null($files)) {
205
-			if (
206
-				$files['error'][0] === 0 &&
207
-				 is_uploaded_file($files['tmp_name'][0]) &&
208
-				!\OC\Files\Filesystem::isFileBlacklisted($files['tmp_name'][0])
209
-			) {
210
-				if ($files['size'][0] > 20*1024*1024) {
211
-					return new JSONResponse(
212
-						['data' => ['message' => $this->l->t('File is too big')]],
213
-						Http::STATUS_BAD_REQUEST
214
-					);
215
-				}
216
-				$this->cache->set('avatar_upload', file_get_contents($files['tmp_name'][0]), 7200);
217
-				$content = $this->cache->get('avatar_upload');
218
-				unlink($files['tmp_name'][0]);
219
-			} else {
220
-				return new JSONResponse(
221
-					['data' => ['message' => $this->l->t('Invalid file provided')]],
222
-					Http::STATUS_BAD_REQUEST
223
-				);
224
-			}
225
-		} else {
226
-			//Add imgfile
227
-			return new JSONResponse(
228
-				['data' => ['message' => $this->l->t('No image or file provided')]],
229
-				Http::STATUS_BAD_REQUEST
230
-			);
231
-		}
232
-
233
-		try {
234
-			$image = new \OC_Image();
235
-			$image->loadFromData($content);
236
-			$image->readExif($content);
237
-			$image->fixOrientation();
238
-
239
-			if ($image->valid()) {
240
-				$mimeType = $image->mimeType();
241
-				if ($mimeType !== 'image/jpeg' && $mimeType !== 'image/png') {
242
-					return new JSONResponse(
243
-						['data' => ['message' => $this->l->t('Unknown filetype')]],
244
-						Http::STATUS_OK
245
-					);
246
-				}
247
-
248
-				$this->cache->set('tmpAvatar', $image->data(), 7200);
249
-				return new JSONResponse(
250
-					['data' => 'notsquare'],
251
-					Http::STATUS_OK
252
-				);
253
-			} else {
254
-				return new JSONResponse(
255
-					['data' => ['message' => $this->l->t('Invalid image')]],
256
-					Http::STATUS_OK
257
-				);
258
-			}
259
-		} catch (\Exception $e) {
260
-			$this->logger->logException($e, ['app' => 'core']);
261
-			return new JSONResponse(['data' => ['message' => $this->l->t('An error occurred. Please contact your admin.')]], Http::STATUS_OK);
262
-		}
263
-	}
264
-
265
-	/**
266
-	 * @NoAdminRequired
54
+    /** @var IAvatarManager */
55
+    protected $avatarManager;
56
+
57
+    /** @var ICache */
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
+    /** @var string */
76
+    protected $userId;
77
+
78
+    /** @var TimeFactory */
79
+    protected $timeFactory;
80
+
81
+    /**
82
+     * @param string $appName
83
+     * @param IRequest $request
84
+     * @param IAvatarManager $avatarManager
85
+     * @param ICache $cache
86
+     * @param IL10N $l10n
87
+     * @param IUserManager $userManager
88
+     * @param IRootFolder $rootFolder
89
+     * @param ILogger $logger
90
+     * @param string $userId
91
+     * @param TimeFactory $timeFactory
92
+     */
93
+    public function __construct($appName,
94
+                                IRequest $request,
95
+                                IAvatarManager $avatarManager,
96
+                                ICache $cache,
97
+                                IL10N $l10n,
98
+                                IUserManager $userManager,
99
+                                IRootFolder $rootFolder,
100
+                                ILogger $logger,
101
+                                $userId,
102
+                                TimeFactory $timeFactory) {
103
+        parent::__construct($appName, $request);
104
+
105
+        $this->avatarManager = $avatarManager;
106
+        $this->cache = $cache;
107
+        $this->l = $l10n;
108
+        $this->userManager = $userManager;
109
+        $this->rootFolder = $rootFolder;
110
+        $this->logger = $logger;
111
+        $this->userId = $userId;
112
+        $this->timeFactory = $timeFactory;
113
+    }
114
+
115
+    /**
116
+     * @NoAdminRequired
117
+     * @NoCSRFRequired
118
+     * @NoSameSiteCookieRequired
119
+     * @PublicPage
267 120
      *
268
-	 * @return JSONResponse
269
-	 */
270
-	public function deleteAvatar() {
271
-		try {
272
-			$avatar = $this->avatarManager->getAvatar($this->userId);
273
-			$avatar->remove();
274
-			return new JSONResponse();
275
-		} catch (\Exception $e) {
276
-			$this->logger->logException($e, ['app' => 'core']);
277
-			return new JSONResponse(['data' => ['message' => $this->l->t('An error occurred. Please contact your admin.')]], Http::STATUS_BAD_REQUEST);
278
-		}
279
-	}
280
-
281
-	/**
282
-	 * @NoAdminRequired
283
-	 *
284
-	 * @return JSONResponse|DataDisplayResponse
285
-	 */
286
-	public function getTmpAvatar() {
287
-		$tmpAvatar = $this->cache->get('tmpAvatar');
288
-		if (is_null($tmpAvatar)) {
289
-			return new JSONResponse(['data' => [
290
-										'message' => $this->l->t("No temporary profile picture available, try again")
291
-									]],
292
-									Http::STATUS_NOT_FOUND);
293
-		}
294
-
295
-		$image = new \OC_Image($tmpAvatar);
296
-
297
-		$resp = new DataDisplayResponse($image->data(),
298
-				Http::STATUS_OK,
299
-				['Content-Type' => $image->mimeType()]);
300
-
301
-		$resp->setETag((string)crc32($image->data()));
302
-		$resp->cacheFor(0);
303
-		$resp->setLastModified(new \DateTime('now', new \DateTimeZone('GMT')));
304
-		return $resp;
305
-	}
306
-
307
-	/**
308
-	 * @NoAdminRequired
309
-	 *
310
-	 * @param array $crop
311
-	 * @return JSONResponse
312
-	 */
313
-	public function postCroppedAvatar($crop) {
314
-		if (is_null($crop)) {
315
-			return new JSONResponse(['data' => ['message' => $this->l->t("No crop data provided")]],
316
-									Http::STATUS_BAD_REQUEST);
317
-		}
318
-
319
-		if (!isset($crop['x'], $crop['y'], $crop['w'], $crop['h'])) {
320
-			return new JSONResponse(['data' => ['message' => $this->l->t("No valid crop data provided")]],
321
-									Http::STATUS_BAD_REQUEST);
322
-		}
323
-
324
-		$tmpAvatar = $this->cache->get('tmpAvatar');
325
-		if (is_null($tmpAvatar)) {
326
-			return new JSONResponse(['data' => [
327
-										'message' => $this->l->t("No temporary profile picture available, try again")
328
-									]],
329
-									Http::STATUS_BAD_REQUEST);
330
-		}
331
-
332
-		$image = new \OC_Image($tmpAvatar);
333
-		$image->crop($crop['x'], $crop['y'], (int)round($crop['w']), (int)round($crop['h']));
334
-		try {
335
-			$avatar = $this->avatarManager->getAvatar($this->userId);
336
-			$avatar->set($image);
337
-			// Clean up
338
-			$this->cache->remove('tmpAvatar');
339
-			return new JSONResponse(['status' => 'success']);
340
-		} catch (\OC\NotSquareException $e) {
341
-			return new JSONResponse(['data' => ['message' => $this->l->t('Crop is not square')]],
342
-									Http::STATUS_BAD_REQUEST);
343
-		} catch (\Exception $e) {
344
-			$this->logger->logException($e, ['app' => 'core']);
345
-			return new JSONResponse(['data' => ['message' => $this->l->t('An error occurred. Please contact your admin.')]], Http::STATUS_BAD_REQUEST);
346
-		}
347
-	}
121
+     * @param string $userId
122
+     * @param int $size
123
+     * @return JSONResponse|FileDisplayResponse
124
+     */
125
+    public function getAvatar($userId, $size) {
126
+        if ($size > 2048) {
127
+            $size = 2048;
128
+        } elseif ($size <= 0) {
129
+            $size = 64;
130
+        }
131
+
132
+        try {
133
+            $avatar = $this->avatarManager->getAvatar($userId)->getFile($size);
134
+            $resp = new FileDisplayResponse($avatar,
135
+                Http::STATUS_OK,
136
+                ['Content-Type' => $avatar->getMimeType()]);
137
+        } catch (NotFoundException $e) {
138
+            $user = $this->userManager->get($userId);
139
+            $resp = new JSONResponse([
140
+                'data' => [
141
+                    'displayname' => $user->getDisplayName(),
142
+                ],
143
+            ]);
144
+        } catch (\Exception $e) {
145
+            $resp = new JSONResponse([
146
+                'data' => [
147
+                    'displayname' => $userId,
148
+                ],
149
+            ]);
150
+        }
151
+
152
+        // Let cache this!
153
+        $resp->addHeader('Pragma', 'public');
154
+        // Cache for 30 minutes
155
+        $resp->cacheFor(1800);
156
+
157
+        $expires = new \DateTime();
158
+        $expires->setTimestamp($this->timeFactory->getTime());
159
+        $expires->add(new \DateInterval('PT30M'));
160
+        $resp->addHeader('Expires', $expires->format(\DateTime::RFC1123));
161
+
162
+        return $resp;
163
+    }
164
+
165
+    /**
166
+     * @NoAdminRequired
167
+     *
168
+     * @param string $path
169
+     * @return JSONResponse
170
+     */
171
+    public function postAvatar($path) {
172
+        $files = $this->request->getUploadedFile('files');
173
+
174
+        if (isset($path)) {
175
+            $path = stripslashes($path);
176
+            $userFolder = $this->rootFolder->getUserFolder($this->userId);
177
+            /** @var File $node */
178
+            $node = $userFolder->get($path);
179
+            if (!($node instanceof File)) {
180
+                return new JSONResponse(['data' => ['message' => $this->l->t('Please select a file.')]]);
181
+            }
182
+            if ($node->getSize() > 20*1024*1024) {
183
+                return new JSONResponse(
184
+                    ['data' => ['message' => $this->l->t('File is too big')]],
185
+                    Http::STATUS_BAD_REQUEST
186
+                );
187
+            }
188
+
189
+            if ($node->getMimeType() !== 'image/jpeg' && $node->getMimeType() !== 'image/png') {
190
+                return new JSONResponse(
191
+                    ['data' => ['message' => $this->l->t('The selected file is not an image.')]],
192
+                    Http::STATUS_BAD_REQUEST
193
+                );
194
+            }
195
+
196
+            try {
197
+                $content = $node->getContent();
198
+            } catch (\OCP\Files\NotPermittedException $e) {
199
+                return new JSONResponse(
200
+                    ['data' => ['message' => $this->l->t('The selected file cannot be read.')]],
201
+                    Http::STATUS_BAD_REQUEST
202
+                );
203
+            }
204
+        } elseif (!is_null($files)) {
205
+            if (
206
+                $files['error'][0] === 0 &&
207
+                 is_uploaded_file($files['tmp_name'][0]) &&
208
+                !\OC\Files\Filesystem::isFileBlacklisted($files['tmp_name'][0])
209
+            ) {
210
+                if ($files['size'][0] > 20*1024*1024) {
211
+                    return new JSONResponse(
212
+                        ['data' => ['message' => $this->l->t('File is too big')]],
213
+                        Http::STATUS_BAD_REQUEST
214
+                    );
215
+                }
216
+                $this->cache->set('avatar_upload', file_get_contents($files['tmp_name'][0]), 7200);
217
+                $content = $this->cache->get('avatar_upload');
218
+                unlink($files['tmp_name'][0]);
219
+            } else {
220
+                return new JSONResponse(
221
+                    ['data' => ['message' => $this->l->t('Invalid file provided')]],
222
+                    Http::STATUS_BAD_REQUEST
223
+                );
224
+            }
225
+        } else {
226
+            //Add imgfile
227
+            return new JSONResponse(
228
+                ['data' => ['message' => $this->l->t('No image or file provided')]],
229
+                Http::STATUS_BAD_REQUEST
230
+            );
231
+        }
232
+
233
+        try {
234
+            $image = new \OC_Image();
235
+            $image->loadFromData($content);
236
+            $image->readExif($content);
237
+            $image->fixOrientation();
238
+
239
+            if ($image->valid()) {
240
+                $mimeType = $image->mimeType();
241
+                if ($mimeType !== 'image/jpeg' && $mimeType !== 'image/png') {
242
+                    return new JSONResponse(
243
+                        ['data' => ['message' => $this->l->t('Unknown filetype')]],
244
+                        Http::STATUS_OK
245
+                    );
246
+                }
247
+
248
+                $this->cache->set('tmpAvatar', $image->data(), 7200);
249
+                return new JSONResponse(
250
+                    ['data' => 'notsquare'],
251
+                    Http::STATUS_OK
252
+                );
253
+            } else {
254
+                return new JSONResponse(
255
+                    ['data' => ['message' => $this->l->t('Invalid image')]],
256
+                    Http::STATUS_OK
257
+                );
258
+            }
259
+        } catch (\Exception $e) {
260
+            $this->logger->logException($e, ['app' => 'core']);
261
+            return new JSONResponse(['data' => ['message' => $this->l->t('An error occurred. Please contact your admin.')]], Http::STATUS_OK);
262
+        }
263
+    }
264
+
265
+    /**
266
+     * @NoAdminRequired
267
+     *
268
+     * @return JSONResponse
269
+     */
270
+    public function deleteAvatar() {
271
+        try {
272
+            $avatar = $this->avatarManager->getAvatar($this->userId);
273
+            $avatar->remove();
274
+            return new JSONResponse();
275
+        } catch (\Exception $e) {
276
+            $this->logger->logException($e, ['app' => 'core']);
277
+            return new JSONResponse(['data' => ['message' => $this->l->t('An error occurred. Please contact your admin.')]], Http::STATUS_BAD_REQUEST);
278
+        }
279
+    }
280
+
281
+    /**
282
+     * @NoAdminRequired
283
+     *
284
+     * @return JSONResponse|DataDisplayResponse
285
+     */
286
+    public function getTmpAvatar() {
287
+        $tmpAvatar = $this->cache->get('tmpAvatar');
288
+        if (is_null($tmpAvatar)) {
289
+            return new JSONResponse(['data' => [
290
+                                        'message' => $this->l->t("No temporary profile picture available, try again")
291
+                                    ]],
292
+                                    Http::STATUS_NOT_FOUND);
293
+        }
294
+
295
+        $image = new \OC_Image($tmpAvatar);
296
+
297
+        $resp = new DataDisplayResponse($image->data(),
298
+                Http::STATUS_OK,
299
+                ['Content-Type' => $image->mimeType()]);
300
+
301
+        $resp->setETag((string)crc32($image->data()));
302
+        $resp->cacheFor(0);
303
+        $resp->setLastModified(new \DateTime('now', new \DateTimeZone('GMT')));
304
+        return $resp;
305
+    }
306
+
307
+    /**
308
+     * @NoAdminRequired
309
+     *
310
+     * @param array $crop
311
+     * @return JSONResponse
312
+     */
313
+    public function postCroppedAvatar($crop) {
314
+        if (is_null($crop)) {
315
+            return new JSONResponse(['data' => ['message' => $this->l->t("No crop data provided")]],
316
+                                    Http::STATUS_BAD_REQUEST);
317
+        }
318
+
319
+        if (!isset($crop['x'], $crop['y'], $crop['w'], $crop['h'])) {
320
+            return new JSONResponse(['data' => ['message' => $this->l->t("No valid crop data provided")]],
321
+                                    Http::STATUS_BAD_REQUEST);
322
+        }
323
+
324
+        $tmpAvatar = $this->cache->get('tmpAvatar');
325
+        if (is_null($tmpAvatar)) {
326
+            return new JSONResponse(['data' => [
327
+                                        'message' => $this->l->t("No temporary profile picture available, try again")
328
+                                    ]],
329
+                                    Http::STATUS_BAD_REQUEST);
330
+        }
331
+
332
+        $image = new \OC_Image($tmpAvatar);
333
+        $image->crop($crop['x'], $crop['y'], (int)round($crop['w']), (int)round($crop['h']));
334
+        try {
335
+            $avatar = $this->avatarManager->getAvatar($this->userId);
336
+            $avatar->set($image);
337
+            // Clean up
338
+            $this->cache->remove('tmpAvatar');
339
+            return new JSONResponse(['status' => 'success']);
340
+        } catch (\OC\NotSquareException $e) {
341
+            return new JSONResponse(['data' => ['message' => $this->l->t('Crop is not square')]],
342
+                                    Http::STATUS_BAD_REQUEST);
343
+        } catch (\Exception $e) {
344
+            $this->logger->logException($e, ['app' => 'core']);
345
+            return new JSONResponse(['data' => ['message' => $this->l->t('An error occurred. Please contact your admin.')]], Http::STATUS_BAD_REQUEST);
346
+        }
347
+    }
348 348
 }
Please login to merge, or discard this patch.