Completed
Pull Request — master (#4350)
by Lukas
12:31
created
core/Controller/LostController.php 3 patches
Unused Use Statements   -1 removed lines patch added patch discarded remove patch
@@ -30,7 +30,6 @@
 block discarded – undo
30 30
 
31 31
 namespace OC\Core\Controller;
32 32
 
33
-use OCA\Encryption\Exceptions\PrivateKeyMissingException;
34 33
 use \OCP\AppFramework\Controller;
35 34
 use OCP\AppFramework\Http\JSONResponse;
36 35
 use \OCP\AppFramework\Http\TemplateResponse;
Please login to merge, or discard this patch.
Indentation   +282 added lines, -282 removed lines patch added patch discarded remove patch
@@ -56,286 +56,286 @@
 block discarded – undo
56 56
  */
57 57
 class LostController extends Controller {
58 58
 
59
-	/** @var IURLGenerator */
60
-	protected $urlGenerator;
61
-	/** @var IUserManager */
62
-	protected $userManager;
63
-	/** @var Defaults */
64
-	protected $defaults;
65
-	/** @var IL10N */
66
-	protected $l10n;
67
-	/** @var string */
68
-	protected $from;
69
-	/** @var IManager */
70
-	protected $encryptionManager;
71
-	/** @var IConfig */
72
-	protected $config;
73
-	/** @var ISecureRandom */
74
-	protected $secureRandom;
75
-	/** @var IMailer */
76
-	protected $mailer;
77
-	/** @var ITimeFactory */
78
-	protected $timeFactory;
79
-	/** @var ICrypto */
80
-	protected $crypto;
81
-
82
-	/**
83
-	 * @param string $appName
84
-	 * @param IRequest $request
85
-	 * @param IURLGenerator $urlGenerator
86
-	 * @param IUserManager $userManager
87
-	 * @param Defaults $defaults
88
-	 * @param IL10N $l10n
89
-	 * @param IConfig $config
90
-	 * @param ISecureRandom $secureRandom
91
-	 * @param string $defaultMailAddress
92
-	 * @param IManager $encryptionManager
93
-	 * @param IMailer $mailer
94
-	 * @param ITimeFactory $timeFactory
95
-	 * @param ICrypto $crypto
96
-	 */
97
-	public function __construct($appName,
98
-								IRequest $request,
99
-								IURLGenerator $urlGenerator,
100
-								IUserManager $userManager,
101
-								Defaults $defaults,
102
-								IL10N $l10n,
103
-								IConfig $config,
104
-								ISecureRandom $secureRandom,
105
-								$defaultMailAddress,
106
-								IManager $encryptionManager,
107
-								IMailer $mailer,
108
-								ITimeFactory $timeFactory,
109
-								ICrypto $crypto) {
110
-		parent::__construct($appName, $request);
111
-		$this->urlGenerator = $urlGenerator;
112
-		$this->userManager = $userManager;
113
-		$this->defaults = $defaults;
114
-		$this->l10n = $l10n;
115
-		$this->secureRandom = $secureRandom;
116
-		$this->from = $defaultMailAddress;
117
-		$this->encryptionManager = $encryptionManager;
118
-		$this->config = $config;
119
-		$this->mailer = $mailer;
120
-		$this->timeFactory = $timeFactory;
121
-		$this->crypto = $crypto;
122
-	}
123
-
124
-	/**
125
-	 * Someone wants to reset their password:
126
-	 *
127
-	 * @PublicPage
128
-	 * @NoCSRFRequired
129
-	 *
130
-	 * @param string $token
131
-	 * @param string $userId
132
-	 * @return TemplateResponse
133
-	 */
134
-	public function resetform($token, $userId) {
135
-		try {
136
-			$this->checkPasswordResetToken($token, $userId);
137
-		} catch (\Exception $e) {
138
-			return new TemplateResponse(
139
-				'core', 'error', [
140
-					"errors" => array(array("error" => $e->getMessage()))
141
-				],
142
-				'guest'
143
-			);
144
-		}
145
-
146
-		return new TemplateResponse(
147
-			'core',
148
-			'lostpassword/resetpassword',
149
-			array(
150
-				'link' => $this->urlGenerator->linkToRouteAbsolute('core.lost.setPassword', array('userId' => $userId, 'token' => $token)),
151
-			),
152
-			'guest'
153
-		);
154
-	}
155
-
156
-	/**
157
-	 * @param string $token
158
-	 * @param string $userId
159
-	 * @throws \Exception
160
-	 */
161
-	protected function checkPasswordResetToken($token, $userId) {
162
-		$user = $this->userManager->get($userId);
163
-		if($user === null) {
164
-			throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
165
-		}
166
-
167
-		try {
168
-			$encryptedToken = $this->config->getUserValue($userId, 'core', 'lostpassword', null);
169
-			$mailAddress = !is_null($user->getEMailAddress()) ? $user->getEMailAddress() : '';
170
-			$decryptedToken = $this->crypto->decrypt($encryptedToken, $mailAddress.$this->config->getSystemValue('secret'));
171
-		} catch (\Exception $e) {
172
-			throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
173
-		}
174
-
175
-		$splittedToken = explode(':', $decryptedToken);
176
-		if(count($splittedToken) !== 2) {
177
-			throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
178
-		}
179
-
180
-		if ($splittedToken[0] < ($this->timeFactory->getTime() - 60*60*12) ||
181
-			$user->getLastLogin() > $splittedToken[0]) {
182
-			throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is expired'));
183
-		}
184
-
185
-		if (!hash_equals($splittedToken[1], $token)) {
186
-			throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
187
-		}
188
-	}
189
-
190
-	/**
191
-	 * @param $message
192
-	 * @param array $additional
193
-	 * @return array
194
-	 */
195
-	private function error($message, array $additional=array()) {
196
-		return array_merge(array('status' => 'error', 'msg' => $message), $additional);
197
-	}
198
-
199
-	/**
200
-	 * @return array
201
-	 */
202
-	private function success() {
203
-		return array('status'=>'success');
204
-	}
205
-
206
-	/**
207
-	 * @PublicPage
208
-	 * @BruteForceProtection(action=passwordResetEmail)
209
-	 *
210
-	 * @param string $user
211
-	 * @return JSONResponse
212
-	 */
213
-	public function email($user){
214
-		// FIXME: use HTTP error codes
215
-		try {
216
-			$this->sendEmail($user);
217
-		} catch (\Exception $e){
218
-			$response = new JSONResponse($this->error($e->getMessage()));
219
-			$response->throttle();
220
-			return $response;
221
-		}
222
-
223
-		$response = new JSONResponse($this->success());
224
-		$response->throttle();
225
-		return $response;
226
-	}
227
-
228
-	/**
229
-	 * @PublicPage
230
-	 * @param string $token
231
-	 * @param string $userId
232
-	 * @param string $password
233
-	 * @param boolean $proceed
234
-	 * @return array
235
-	 */
236
-	public function setPassword($token, $userId, $password, $proceed) {
237
-		if ($this->encryptionManager->isEnabled() && !$proceed) {
238
-			return $this->error('', array('encryption' => true));
239
-		}
240
-
241
-		try {
242
-			$this->checkPasswordResetToken($token, $userId);
243
-			$user = $this->userManager->get($userId);
244
-
245
-			\OC_Hook::emit('\OC\Core\LostPassword\Controller\LostController', 'pre_passwordReset', array('uid' => $userId, 'password' => $password));
246
-
247
-			if (!$user->setPassword($password)) {
248
-				throw new \Exception();
249
-			}
250
-
251
-			\OC_Hook::emit('\OC\Core\LostPassword\Controller\LostController', 'post_passwordReset', array('uid' => $userId, 'password' => $password));
252
-
253
-			$this->config->deleteUserValue($userId, 'core', 'lostpassword');
254
-			@\OC_User::unsetMagicInCookie();
255
-		} catch (\Exception $e){
256
-			return $this->error($e->getMessage());
257
-		}
258
-
259
-		return $this->success();
260
-	}
261
-
262
-	/**
263
-	 * @param string $input
264
-	 * @throws \Exception
265
-	 */
266
-	protected function sendEmail($input) {
267
-		$user = $this->findUserByIdOrMail($input);
268
-		$email = $user->getEMailAddress();
269
-
270
-		if (empty($email)) {
271
-			throw new \Exception(
272
-				$this->l10n->t('Could not send reset email because there is no email address for this username. Please contact your administrator.')
273
-			);
274
-		}
275
-
276
-		// Generate the token. It is stored encrypted in the database with the
277
-		// secret being the users' email address appended with the system secret.
278
-		// This makes the token automatically invalidate once the user changes
279
-		// their email address.
280
-		$token = $this->secureRandom->generate(
281
-			21,
282
-			ISecureRandom::CHAR_DIGITS.
283
-			ISecureRandom::CHAR_LOWER.
284
-			ISecureRandom::CHAR_UPPER
285
-		);
286
-		$tokenValue = $this->timeFactory->getTime() .':'. $token;
287
-		$encryptedValue = $this->crypto->encrypt($tokenValue, $email . $this->config->getSystemValue('secret'));
288
-		$this->config->setUserValue($user->getUID(), 'core', 'lostpassword', $encryptedValue);
289
-
290
-		$link = $this->urlGenerator->linkToRouteAbsolute('core.lost.resetform', array('userId' => $user->getUID(), 'token' => $token));
291
-
292
-		$emailTemplate = $this->mailer->createEMailTemplate();
293
-
294
-		$emailTemplate->addHeader();
295
-		$emailTemplate->addHeading($this->l10n->t('Password reset'));
296
-
297
-		$emailTemplate->addBodyText(
298
-			$this->l10n->t('Click the following button to reset your password. If you have not requested the password reset, then ignore this email.'),
299
-			$this->l10n->t('Click the following link to reset your password. If you have not requested the password reset, then ignore this email.')
300
-		);
301
-
302
-		$emailTemplate->addBodyButton(
303
-			$this->l10n->t('Reset your password'),
304
-			$link,
305
-			false
306
-		);
307
-		$emailTemplate->addFooter();
308
-
309
-		try {
310
-			$message = $this->mailer->createMessage();
311
-			$message->setTo([$email => $user->getUID()]);
312
-			$message->setSubject($this->l10n->t('%s password reset', [$this->defaults->getName()]));
313
-			$message->setPlainBody($emailTemplate->renderText());
314
-			$message->setHtmlBody($emailTemplate->renderHTML());
315
-			$message->setFrom([$this->from => $this->defaults->getName()]);
316
-			$this->mailer->send($message);
317
-		} catch (\Exception $e) {
318
-			throw new \Exception($this->l10n->t(
319
-				'Couldn\'t send reset email. Please contact your administrator.'
320
-			));
321
-		}
322
-	}
323
-
324
-	/**
325
-	 * @param string $input
326
-	 * @return IUser
327
-	 * @throws \Exception
328
-	 */
329
-	protected function findUserByIdOrMail($input) {
330
-		$user = $this->userManager->get($input);
331
-		if ($user instanceof IUser) {
332
-			return $user;
333
-		}
334
-		$users = $this->userManager->getByEmail($input);
335
-		if (count($users) === 1) {
336
-			return $users[0];
337
-		}
338
-
339
-		throw new \InvalidArgumentException($this->l10n->t('Couldn\'t send reset email. Please make sure your username is correct.'));
340
-	}
59
+    /** @var IURLGenerator */
60
+    protected $urlGenerator;
61
+    /** @var IUserManager */
62
+    protected $userManager;
63
+    /** @var Defaults */
64
+    protected $defaults;
65
+    /** @var IL10N */
66
+    protected $l10n;
67
+    /** @var string */
68
+    protected $from;
69
+    /** @var IManager */
70
+    protected $encryptionManager;
71
+    /** @var IConfig */
72
+    protected $config;
73
+    /** @var ISecureRandom */
74
+    protected $secureRandom;
75
+    /** @var IMailer */
76
+    protected $mailer;
77
+    /** @var ITimeFactory */
78
+    protected $timeFactory;
79
+    /** @var ICrypto */
80
+    protected $crypto;
81
+
82
+    /**
83
+     * @param string $appName
84
+     * @param IRequest $request
85
+     * @param IURLGenerator $urlGenerator
86
+     * @param IUserManager $userManager
87
+     * @param Defaults $defaults
88
+     * @param IL10N $l10n
89
+     * @param IConfig $config
90
+     * @param ISecureRandom $secureRandom
91
+     * @param string $defaultMailAddress
92
+     * @param IManager $encryptionManager
93
+     * @param IMailer $mailer
94
+     * @param ITimeFactory $timeFactory
95
+     * @param ICrypto $crypto
96
+     */
97
+    public function __construct($appName,
98
+                                IRequest $request,
99
+                                IURLGenerator $urlGenerator,
100
+                                IUserManager $userManager,
101
+                                Defaults $defaults,
102
+                                IL10N $l10n,
103
+                                IConfig $config,
104
+                                ISecureRandom $secureRandom,
105
+                                $defaultMailAddress,
106
+                                IManager $encryptionManager,
107
+                                IMailer $mailer,
108
+                                ITimeFactory $timeFactory,
109
+                                ICrypto $crypto) {
110
+        parent::__construct($appName, $request);
111
+        $this->urlGenerator = $urlGenerator;
112
+        $this->userManager = $userManager;
113
+        $this->defaults = $defaults;
114
+        $this->l10n = $l10n;
115
+        $this->secureRandom = $secureRandom;
116
+        $this->from = $defaultMailAddress;
117
+        $this->encryptionManager = $encryptionManager;
118
+        $this->config = $config;
119
+        $this->mailer = $mailer;
120
+        $this->timeFactory = $timeFactory;
121
+        $this->crypto = $crypto;
122
+    }
123
+
124
+    /**
125
+     * Someone wants to reset their password:
126
+     *
127
+     * @PublicPage
128
+     * @NoCSRFRequired
129
+     *
130
+     * @param string $token
131
+     * @param string $userId
132
+     * @return TemplateResponse
133
+     */
134
+    public function resetform($token, $userId) {
135
+        try {
136
+            $this->checkPasswordResetToken($token, $userId);
137
+        } catch (\Exception $e) {
138
+            return new TemplateResponse(
139
+                'core', 'error', [
140
+                    "errors" => array(array("error" => $e->getMessage()))
141
+                ],
142
+                'guest'
143
+            );
144
+        }
145
+
146
+        return new TemplateResponse(
147
+            'core',
148
+            'lostpassword/resetpassword',
149
+            array(
150
+                'link' => $this->urlGenerator->linkToRouteAbsolute('core.lost.setPassword', array('userId' => $userId, 'token' => $token)),
151
+            ),
152
+            'guest'
153
+        );
154
+    }
155
+
156
+    /**
157
+     * @param string $token
158
+     * @param string $userId
159
+     * @throws \Exception
160
+     */
161
+    protected function checkPasswordResetToken($token, $userId) {
162
+        $user = $this->userManager->get($userId);
163
+        if($user === null) {
164
+            throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
165
+        }
166
+
167
+        try {
168
+            $encryptedToken = $this->config->getUserValue($userId, 'core', 'lostpassword', null);
169
+            $mailAddress = !is_null($user->getEMailAddress()) ? $user->getEMailAddress() : '';
170
+            $decryptedToken = $this->crypto->decrypt($encryptedToken, $mailAddress.$this->config->getSystemValue('secret'));
171
+        } catch (\Exception $e) {
172
+            throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
173
+        }
174
+
175
+        $splittedToken = explode(':', $decryptedToken);
176
+        if(count($splittedToken) !== 2) {
177
+            throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
178
+        }
179
+
180
+        if ($splittedToken[0] < ($this->timeFactory->getTime() - 60*60*12) ||
181
+            $user->getLastLogin() > $splittedToken[0]) {
182
+            throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is expired'));
183
+        }
184
+
185
+        if (!hash_equals($splittedToken[1], $token)) {
186
+            throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
187
+        }
188
+    }
189
+
190
+    /**
191
+     * @param $message
192
+     * @param array $additional
193
+     * @return array
194
+     */
195
+    private function error($message, array $additional=array()) {
196
+        return array_merge(array('status' => 'error', 'msg' => $message), $additional);
197
+    }
198
+
199
+    /**
200
+     * @return array
201
+     */
202
+    private function success() {
203
+        return array('status'=>'success');
204
+    }
205
+
206
+    /**
207
+     * @PublicPage
208
+     * @BruteForceProtection(action=passwordResetEmail)
209
+     *
210
+     * @param string $user
211
+     * @return JSONResponse
212
+     */
213
+    public function email($user){
214
+        // FIXME: use HTTP error codes
215
+        try {
216
+            $this->sendEmail($user);
217
+        } catch (\Exception $e){
218
+            $response = new JSONResponse($this->error($e->getMessage()));
219
+            $response->throttle();
220
+            return $response;
221
+        }
222
+
223
+        $response = new JSONResponse($this->success());
224
+        $response->throttle();
225
+        return $response;
226
+    }
227
+
228
+    /**
229
+     * @PublicPage
230
+     * @param string $token
231
+     * @param string $userId
232
+     * @param string $password
233
+     * @param boolean $proceed
234
+     * @return array
235
+     */
236
+    public function setPassword($token, $userId, $password, $proceed) {
237
+        if ($this->encryptionManager->isEnabled() && !$proceed) {
238
+            return $this->error('', array('encryption' => true));
239
+        }
240
+
241
+        try {
242
+            $this->checkPasswordResetToken($token, $userId);
243
+            $user = $this->userManager->get($userId);
244
+
245
+            \OC_Hook::emit('\OC\Core\LostPassword\Controller\LostController', 'pre_passwordReset', array('uid' => $userId, 'password' => $password));
246
+
247
+            if (!$user->setPassword($password)) {
248
+                throw new \Exception();
249
+            }
250
+
251
+            \OC_Hook::emit('\OC\Core\LostPassword\Controller\LostController', 'post_passwordReset', array('uid' => $userId, 'password' => $password));
252
+
253
+            $this->config->deleteUserValue($userId, 'core', 'lostpassword');
254
+            @\OC_User::unsetMagicInCookie();
255
+        } catch (\Exception $e){
256
+            return $this->error($e->getMessage());
257
+        }
258
+
259
+        return $this->success();
260
+    }
261
+
262
+    /**
263
+     * @param string $input
264
+     * @throws \Exception
265
+     */
266
+    protected function sendEmail($input) {
267
+        $user = $this->findUserByIdOrMail($input);
268
+        $email = $user->getEMailAddress();
269
+
270
+        if (empty($email)) {
271
+            throw new \Exception(
272
+                $this->l10n->t('Could not send reset email because there is no email address for this username. Please contact your administrator.')
273
+            );
274
+        }
275
+
276
+        // Generate the token. It is stored encrypted in the database with the
277
+        // secret being the users' email address appended with the system secret.
278
+        // This makes the token automatically invalidate once the user changes
279
+        // their email address.
280
+        $token = $this->secureRandom->generate(
281
+            21,
282
+            ISecureRandom::CHAR_DIGITS.
283
+            ISecureRandom::CHAR_LOWER.
284
+            ISecureRandom::CHAR_UPPER
285
+        );
286
+        $tokenValue = $this->timeFactory->getTime() .':'. $token;
287
+        $encryptedValue = $this->crypto->encrypt($tokenValue, $email . $this->config->getSystemValue('secret'));
288
+        $this->config->setUserValue($user->getUID(), 'core', 'lostpassword', $encryptedValue);
289
+
290
+        $link = $this->urlGenerator->linkToRouteAbsolute('core.lost.resetform', array('userId' => $user->getUID(), 'token' => $token));
291
+
292
+        $emailTemplate = $this->mailer->createEMailTemplate();
293
+
294
+        $emailTemplate->addHeader();
295
+        $emailTemplate->addHeading($this->l10n->t('Password reset'));
296
+
297
+        $emailTemplate->addBodyText(
298
+            $this->l10n->t('Click the following button to reset your password. If you have not requested the password reset, then ignore this email.'),
299
+            $this->l10n->t('Click the following link to reset your password. If you have not requested the password reset, then ignore this email.')
300
+        );
301
+
302
+        $emailTemplate->addBodyButton(
303
+            $this->l10n->t('Reset your password'),
304
+            $link,
305
+            false
306
+        );
307
+        $emailTemplate->addFooter();
308
+
309
+        try {
310
+            $message = $this->mailer->createMessage();
311
+            $message->setTo([$email => $user->getUID()]);
312
+            $message->setSubject($this->l10n->t('%s password reset', [$this->defaults->getName()]));
313
+            $message->setPlainBody($emailTemplate->renderText());
314
+            $message->setHtmlBody($emailTemplate->renderHTML());
315
+            $message->setFrom([$this->from => $this->defaults->getName()]);
316
+            $this->mailer->send($message);
317
+        } catch (\Exception $e) {
318
+            throw new \Exception($this->l10n->t(
319
+                'Couldn\'t send reset email. Please contact your administrator.'
320
+            ));
321
+        }
322
+    }
323
+
324
+    /**
325
+     * @param string $input
326
+     * @return IUser
327
+     * @throws \Exception
328
+     */
329
+    protected function findUserByIdOrMail($input) {
330
+        $user = $this->userManager->get($input);
331
+        if ($user instanceof IUser) {
332
+            return $user;
333
+        }
334
+        $users = $this->userManager->getByEmail($input);
335
+        if (count($users) === 1) {
336
+            return $users[0];
337
+        }
338
+
339
+        throw new \InvalidArgumentException($this->l10n->t('Couldn\'t send reset email. Please make sure your username is correct.'));
340
+    }
341 341
 }
Please login to merge, or discard this patch.
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -160,7 +160,7 @@  discard block
 block discarded – undo
160 160
 	 */
161 161
 	protected function checkPasswordResetToken($token, $userId) {
162 162
 		$user = $this->userManager->get($userId);
163
-		if($user === null) {
163
+		if ($user === null) {
164 164
 			throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
165 165
 		}
166 166
 
@@ -173,11 +173,11 @@  discard block
 block discarded – undo
173 173
 		}
174 174
 
175 175
 		$splittedToken = explode(':', $decryptedToken);
176
-		if(count($splittedToken) !== 2) {
176
+		if (count($splittedToken) !== 2) {
177 177
 			throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
178 178
 		}
179 179
 
180
-		if ($splittedToken[0] < ($this->timeFactory->getTime() - 60*60*12) ||
180
+		if ($splittedToken[0] < ($this->timeFactory->getTime() - 60 * 60 * 12) ||
181 181
 			$user->getLastLogin() > $splittedToken[0]) {
182 182
 			throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is expired'));
183 183
 		}
@@ -192,7 +192,7 @@  discard block
 block discarded – undo
192 192
 	 * @param array $additional
193 193
 	 * @return array
194 194
 	 */
195
-	private function error($message, array $additional=array()) {
195
+	private function error($message, array $additional = array()) {
196 196
 		return array_merge(array('status' => 'error', 'msg' => $message), $additional);
197 197
 	}
198 198
 
@@ -210,11 +210,11 @@  discard block
 block discarded – undo
210 210
 	 * @param string $user
211 211
 	 * @return JSONResponse
212 212
 	 */
213
-	public function email($user){
213
+	public function email($user) {
214 214
 		// FIXME: use HTTP error codes
215 215
 		try {
216 216
 			$this->sendEmail($user);
217
-		} catch (\Exception $e){
217
+		} catch (\Exception $e) {
218 218
 			$response = new JSONResponse($this->error($e->getMessage()));
219 219
 			$response->throttle();
220 220
 			return $response;
@@ -252,7 +252,7 @@  discard block
 block discarded – undo
252 252
 
253 253
 			$this->config->deleteUserValue($userId, 'core', 'lostpassword');
254 254
 			@\OC_User::unsetMagicInCookie();
255
-		} catch (\Exception $e){
255
+		} catch (\Exception $e) {
256 256
 			return $this->error($e->getMessage());
257 257
 		}
258 258
 
@@ -283,8 +283,8 @@  discard block
 block discarded – undo
283 283
 			ISecureRandom::CHAR_LOWER.
284 284
 			ISecureRandom::CHAR_UPPER
285 285
 		);
286
-		$tokenValue = $this->timeFactory->getTime() .':'. $token;
287
-		$encryptedValue = $this->crypto->encrypt($tokenValue, $email . $this->config->getSystemValue('secret'));
286
+		$tokenValue = $this->timeFactory->getTime().':'.$token;
287
+		$encryptedValue = $this->crypto->encrypt($tokenValue, $email.$this->config->getSystemValue('secret'));
288 288
 		$this->config->setUserValue($user->getUID(), 'core', 'lostpassword', $encryptedValue);
289 289
 
290 290
 		$link = $this->urlGenerator->linkToRouteAbsolute('core.lost.resetform', array('userId' => $user->getUID(), 'token' => $token));
Please login to merge, or discard this patch.
apps/user_ldap/lib/Controller/ConfigAPIController.php 1 patch
Indentation   +260 added lines, -260 removed lines patch added patch discarded remove patch
@@ -39,281 +39,281 @@
 block discarded – undo
39 39
 
40 40
 class ConfigAPIController extends OCSController {
41 41
 
42
-	/** @var Helper */
43
-	private $ldapHelper;
42
+    /** @var Helper */
43
+    private $ldapHelper;
44 44
 
45
-	/** @var ILogger */
46
-	private $logger;
45
+    /** @var ILogger */
46
+    private $logger;
47 47
 
48
-	public function __construct(
49
-		$appName,
50
-		IRequest $request,
51
-		CapabilitiesManager $capabilitiesManager,
52
-		IUserSession $userSession,
53
-		IUserManager $userManager,
54
-		Manager $keyManager,
55
-		Helper $ldapHelper,
56
-		ILogger $logger
57
-	) {
58
-		parent::__construct(
59
-			$appName,
60
-			$request,
61
-			$capabilitiesManager,
62
-			$userSession,
63
-			$userManager,
64
-			$keyManager
65
-		);
48
+    public function __construct(
49
+        $appName,
50
+        IRequest $request,
51
+        CapabilitiesManager $capabilitiesManager,
52
+        IUserSession $userSession,
53
+        IUserManager $userManager,
54
+        Manager $keyManager,
55
+        Helper $ldapHelper,
56
+        ILogger $logger
57
+    ) {
58
+        parent::__construct(
59
+            $appName,
60
+            $request,
61
+            $capabilitiesManager,
62
+            $userSession,
63
+            $userManager,
64
+            $keyManager
65
+        );
66 66
 
67 67
 
68
-		$this->ldapHelper = $ldapHelper;
69
-		$this->logger = $logger;
70
-	}
68
+        $this->ldapHelper = $ldapHelper;
69
+        $this->logger = $logger;
70
+    }
71 71
 
72
-	/**
73
-	 * creates a new (empty) configuration and returns the resulting prefix
74
-	 *
75
-	 * Example: curl -X POST -H "OCS-APIREQUEST: true"  -u $admin:$password \
76
-	 *   https://nextcloud.server/ocs/v2.php/apps/user_ldap/api/v1/config
77
-	 *
78
-	 * results in:
79
-	 *
80
-	 * <?xml version="1.0"?>
81
-	 * <ocs>
82
-	 *   <meta>
83
-	 *     <status>ok</status>
84
-	 *     <statuscode>200</statuscode>
85
-	 *     <message>OK</message>
86
-	 *   </meta>
87
-	 *   <data>
88
-	 *     <configID>s40</configID>
89
-	 *   </data>
90
-	 * </ocs>
91
-	 *
92
-	 * Failing example: if an exception is thrown (e.g. Database connection lost)
93
-	 * the detailed error will be logged. The output will then look like:
94
-	 *
95
-	 * <?xml version="1.0"?>
96
-	 * <ocs>
97
-	 *   <meta>
98
-	 *     <status>failure</status>
99
-	 *     <statuscode>999</statuscode>
100
-	 *     <message>An issue occurred when creating the new config.</message>
101
-	 *   </meta>
102
-	 *   <data/>
103
-	 * </ocs>
104
-	 *
105
-	 * For JSON output provide the format=json parameter
106
-	 *
107
-	 * @return DataResponse
108
-	 * @throws OCSException
109
-	 */
110
-	public function create() {
111
-		try {
112
-			$configPrefix = $this->ldapHelper->getNextServerConfigurationPrefix();
113
-			$configHolder = new Configuration($configPrefix);
114
-			$configHolder->saveConfiguration();
115
-		} catch (\Exception $e) {
116
-			$this->logger->logException($e);
117
-			throw new OCSException('An issue occurred when creating the new config.');
118
-		}
119
-		return new DataResponse(['configID' => $configPrefix]);
120
-	}
72
+    /**
73
+     * creates a new (empty) configuration and returns the resulting prefix
74
+     *
75
+     * Example: curl -X POST -H "OCS-APIREQUEST: true"  -u $admin:$password \
76
+     *   https://nextcloud.server/ocs/v2.php/apps/user_ldap/api/v1/config
77
+     *
78
+     * results in:
79
+     *
80
+     * <?xml version="1.0"?>
81
+     * <ocs>
82
+     *   <meta>
83
+     *     <status>ok</status>
84
+     *     <statuscode>200</statuscode>
85
+     *     <message>OK</message>
86
+     *   </meta>
87
+     *   <data>
88
+     *     <configID>s40</configID>
89
+     *   </data>
90
+     * </ocs>
91
+     *
92
+     * Failing example: if an exception is thrown (e.g. Database connection lost)
93
+     * the detailed error will be logged. The output will then look like:
94
+     *
95
+     * <?xml version="1.0"?>
96
+     * <ocs>
97
+     *   <meta>
98
+     *     <status>failure</status>
99
+     *     <statuscode>999</statuscode>
100
+     *     <message>An issue occurred when creating the new config.</message>
101
+     *   </meta>
102
+     *   <data/>
103
+     * </ocs>
104
+     *
105
+     * For JSON output provide the format=json parameter
106
+     *
107
+     * @return DataResponse
108
+     * @throws OCSException
109
+     */
110
+    public function create() {
111
+        try {
112
+            $configPrefix = $this->ldapHelper->getNextServerConfigurationPrefix();
113
+            $configHolder = new Configuration($configPrefix);
114
+            $configHolder->saveConfiguration();
115
+        } catch (\Exception $e) {
116
+            $this->logger->logException($e);
117
+            throw new OCSException('An issue occurred when creating the new config.');
118
+        }
119
+        return new DataResponse(['configID' => $configPrefix]);
120
+    }
121 121
 
122
-	/**
123
-	 * Deletes a LDAP configuration, if present.
124
-	 *
125
-	 * Example:
126
-	 *   curl -X DELETE -H "OCS-APIREQUEST: true" -u $admin:$password \
127
-	 *    https://nextcloud.server/ocs/v2.php/apps/user_ldap/api/v1/config/s60
128
-	 *
129
-	 * <?xml version="1.0"?>
130
-	 * <ocs>
131
-	 *   <meta>
132
-	 *     <status>ok</status>
133
-	 *     <statuscode>200</statuscode>
134
-	 *     <message>OK</message>
135
-	 *   </meta>
136
-	 *   <data/>
137
-	 * </ocs>
138
-	 *
139
-	 * @param string $configID
140
-	 * @return DataResponse
141
-	 * @throws OCSBadRequestException
142
-	 * @throws OCSException
143
-	 */
144
-	public function delete($configID) {
145
-		try {
146
-			$this->ensureConfigIDExists($configID);
147
-			if(!$this->ldapHelper->deleteServerConfiguration($configID)) {
148
-				throw new OCSException('Could not delete configuration');
149
-			}
150
-		} catch(OCSException $e) {
151
-			throw $e;
152
-		} catch(\Exception $e) {
153
-			$this->logger->logException($e);
154
-			throw new OCSException('An issue occurred when deleting the config.');
155
-		}
122
+    /**
123
+     * Deletes a LDAP configuration, if present.
124
+     *
125
+     * Example:
126
+     *   curl -X DELETE -H "OCS-APIREQUEST: true" -u $admin:$password \
127
+     *    https://nextcloud.server/ocs/v2.php/apps/user_ldap/api/v1/config/s60
128
+     *
129
+     * <?xml version="1.0"?>
130
+     * <ocs>
131
+     *   <meta>
132
+     *     <status>ok</status>
133
+     *     <statuscode>200</statuscode>
134
+     *     <message>OK</message>
135
+     *   </meta>
136
+     *   <data/>
137
+     * </ocs>
138
+     *
139
+     * @param string $configID
140
+     * @return DataResponse
141
+     * @throws OCSBadRequestException
142
+     * @throws OCSException
143
+     */
144
+    public function delete($configID) {
145
+        try {
146
+            $this->ensureConfigIDExists($configID);
147
+            if(!$this->ldapHelper->deleteServerConfiguration($configID)) {
148
+                throw new OCSException('Could not delete configuration');
149
+            }
150
+        } catch(OCSException $e) {
151
+            throw $e;
152
+        } catch(\Exception $e) {
153
+            $this->logger->logException($e);
154
+            throw new OCSException('An issue occurred when deleting the config.');
155
+        }
156 156
 
157
-		return new DataResponse();
158
-	}
157
+        return new DataResponse();
158
+    }
159 159
 
160
-	/**
161
-	 * modifies a configuration
162
-	 *
163
-	 * Example:
164
-	 *   curl -X PUT -d "configData[ldapHost]=ldaps://my.ldap.server&configData[ldapPort]=636" \
165
-	 *    -H "OCS-APIREQUEST: true" -u $admin:$password \
166
-	 *    https://nextcloud.server/ocs/v2.php/apps/user_ldap/api/v1/config/s60
167
-	 *
168
-	 * <?xml version="1.0"?>
169
-	 * <ocs>
170
-	 *   <meta>
171
-	 *     <status>ok</status>
172
-	 *     <statuscode>200</statuscode>
173
-	 *     <message>OK</message>
174
-	 *   </meta>
175
-	 *   <data/>
176
-	 * </ocs>
177
-	 *
178
-	 * @param string $configID
179
-	 * @param array $configData
180
-	 * @return DataResponse
181
-	 * @throws OCSException
182
-	 */
183
-	public function modify($configID, $configData) {
184
-		try {
185
-			$this->ensureConfigIDExists($configID);
160
+    /**
161
+     * modifies a configuration
162
+     *
163
+     * Example:
164
+     *   curl -X PUT -d "configData[ldapHost]=ldaps://my.ldap.server&configData[ldapPort]=636" \
165
+     *    -H "OCS-APIREQUEST: true" -u $admin:$password \
166
+     *    https://nextcloud.server/ocs/v2.php/apps/user_ldap/api/v1/config/s60
167
+     *
168
+     * <?xml version="1.0"?>
169
+     * <ocs>
170
+     *   <meta>
171
+     *     <status>ok</status>
172
+     *     <statuscode>200</statuscode>
173
+     *     <message>OK</message>
174
+     *   </meta>
175
+     *   <data/>
176
+     * </ocs>
177
+     *
178
+     * @param string $configID
179
+     * @param array $configData
180
+     * @return DataResponse
181
+     * @throws OCSException
182
+     */
183
+    public function modify($configID, $configData) {
184
+        try {
185
+            $this->ensureConfigIDExists($configID);
186 186
 
187
-			if(!is_array($configData)) {
188
-				throw new OCSBadRequestException('configData is not properly set');
189
-			}
187
+            if(!is_array($configData)) {
188
+                throw new OCSBadRequestException('configData is not properly set');
189
+            }
190 190
 
191
-			$configuration = new Configuration($configID);
192
-			$configKeys = $configuration->getConfigTranslationArray();
191
+            $configuration = new Configuration($configID);
192
+            $configKeys = $configuration->getConfigTranslationArray();
193 193
 
194
-			foreach ($configKeys as $i => $key) {
195
-				if(isset($configData[$key])) {
196
-					$configuration->$key = $configData[$key];
197
-				}
198
-			}
194
+            foreach ($configKeys as $i => $key) {
195
+                if(isset($configData[$key])) {
196
+                    $configuration->$key = $configData[$key];
197
+                }
198
+            }
199 199
 
200
-			$configuration->saveConfiguration();
201
-		} catch(OCSException $e) {
202
-			throw $e;
203
-		} catch (\Exception $e) {
204
-			$this->logger->logException($e);
205
-			throw new OCSException('An issue occurred when modifying the config.');
206
-		}
200
+            $configuration->saveConfiguration();
201
+        } catch(OCSException $e) {
202
+            throw $e;
203
+        } catch (\Exception $e) {
204
+            $this->logger->logException($e);
205
+            throw new OCSException('An issue occurred when modifying the config.');
206
+        }
207 207
 
208
-		return new DataResponse();
209
-	}
208
+        return new DataResponse();
209
+    }
210 210
 
211
-	/**
212
-	 * retrieves a configuration
213
-	 *
214
-	 * <?xml version="1.0"?>
215
-	 * <ocs>
216
-	 *   <meta>
217
-	 *     <status>ok</status>
218
-	 *     <statuscode>200</statuscode>
219
-	 *     <message>OK</message>
220
-	 *   </meta>
221
-	 *   <data>
222
-	 *     <ldapHost>ldaps://my.ldap.server</ldapHost>
223
-	 *     <ldapPort>7770</ldapPort>
224
-	 *     <ldapBackupHost></ldapBackupHost>
225
-	 *     <ldapBackupPort></ldapBackupPort>
226
-	 *     <ldapBase>ou=small,dc=my,dc=ldap,dc=server</ldapBase>
227
-	 *     <ldapBaseUsers>ou=users,ou=small,dc=my,dc=ldap,dc=server</ldapBaseUsers>
228
-	 *     <ldapBaseGroups>ou=small,dc=my,dc=ldap,dc=server</ldapBaseGroups>
229
-	 *     <ldapAgentName>cn=root,dc=my,dc=ldap,dc=server</ldapAgentName>
230
-	 *     <ldapAgentPassword>clearTextWithShowPassword=1</ldapAgentPassword>
231
-	 *     <ldapTLS>1</ldapTLS>
232
-	 *     <turnOffCertCheck>0</turnOffCertCheck>
233
-	 *     <ldapIgnoreNamingRules/>
234
-	 *     <ldapUserDisplayName>displayname</ldapUserDisplayName>
235
-	 *     <ldapUserDisplayName2>uid</ldapUserDisplayName2>
236
-	 *     <ldapUserFilterObjectclass>inetOrgPerson</ldapUserFilterObjectclass>
237
-	 *     <ldapUserFilterGroups></ldapUserFilterGroups>
238
-	 *     <ldapUserFilter>(&amp;(objectclass=nextcloudUser)(nextcloudEnabled=TRUE))</ldapUserFilter>
239
-	 *     <ldapUserFilterMode>1</ldapUserFilterMode>
240
-	 *     <ldapGroupFilter>(&amp;(|(objectclass=nextcloudGroup)))</ldapGroupFilter>
241
-	 *     <ldapGroupFilterMode>0</ldapGroupFilterMode>
242
-	 *     <ldapGroupFilterObjectclass>nextcloudGroup</ldapGroupFilterObjectclass>
243
-	 *     <ldapGroupFilterGroups></ldapGroupFilterGroups>
244
-	 *     <ldapGroupDisplayName>cn</ldapGroupDisplayName>
245
-	 *     <ldapGroupMemberAssocAttr>memberUid</ldapGroupMemberAssocAttr>
246
-	 *     <ldapLoginFilter>(&amp;(|(objectclass=inetOrgPerson))(uid=%uid))</ldapLoginFilter>
247
-	 *     <ldapLoginFilterMode>0</ldapLoginFilterMode>
248
-	 *     <ldapLoginFilterEmail>0</ldapLoginFilterEmail>
249
-	 *     <ldapLoginFilterUsername>1</ldapLoginFilterUsername>
250
-	 *     <ldapLoginFilterAttributes></ldapLoginFilterAttributes>
251
-	 *     <ldapQuotaAttribute></ldapQuotaAttribute>
252
-	 *     <ldapQuotaDefault></ldapQuotaDefault>
253
-	 *     <ldapEmailAttribute>mail</ldapEmailAttribute>
254
-	 *     <ldapCacheTTL>20</ldapCacheTTL>
255
-	 *     <ldapUuidUserAttribute>auto</ldapUuidUserAttribute>
256
-	 *     <ldapUuidGroupAttribute>auto</ldapUuidGroupAttribute>
257
-	 *     <ldapOverrideMainServer></ldapOverrideMainServer>
258
-	 *     <ldapConfigurationActive>1</ldapConfigurationActive>
259
-	 *     <ldapAttributesForUserSearch>uid;sn;givenname</ldapAttributesForUserSearch>
260
-	 *     <ldapAttributesForGroupSearch></ldapAttributesForGroupSearch>
261
-	 *     <ldapExperiencedAdmin>0</ldapExperiencedAdmin>
262
-	 *     <homeFolderNamingRule></homeFolderNamingRule>
263
-	 *     <hasPagedResultSupport></hasPagedResultSupport>
264
-	 *     <hasMemberOfFilterSupport></hasMemberOfFilterSupport>
265
-	 *     <useMemberOfToDetectMembership>1</useMemberOfToDetectMembership>
266
-	 *     <ldapExpertUsernameAttr>uid</ldapExpertUsernameAttr>
267
-	 *     <ldapExpertUUIDUserAttr>uid</ldapExpertUUIDUserAttr>
268
-	 *     <ldapExpertUUIDGroupAttr></ldapExpertUUIDGroupAttr>
269
-	 *     <lastJpegPhotoLookup>0</lastJpegPhotoLookup>
270
-	 *     <ldapNestedGroups>0</ldapNestedGroups>
271
-	 *     <ldapPagingSize>500</ldapPagingSize>
272
-	 *     <turnOnPasswordChange>1</turnOnPasswordChange>
273
-	 *     <ldapDynamicGroupMemberURL></ldapDynamicGroupMemberURL>
274
-	 *   </data>
275
-	 * </ocs>
276
-	 *
277
-	 * @param string $configID
278
-	 * @param bool|string $showPassword
279
-	 * @return DataResponse
280
-	 * @throws OCSException
281
-	 */
282
-	public function show($configID, $showPassword = false) {
283
-		try {
284
-			$this->ensureConfigIDExists($configID);
211
+    /**
212
+     * retrieves a configuration
213
+     *
214
+     * <?xml version="1.0"?>
215
+     * <ocs>
216
+     *   <meta>
217
+     *     <status>ok</status>
218
+     *     <statuscode>200</statuscode>
219
+     *     <message>OK</message>
220
+     *   </meta>
221
+     *   <data>
222
+     *     <ldapHost>ldaps://my.ldap.server</ldapHost>
223
+     *     <ldapPort>7770</ldapPort>
224
+     *     <ldapBackupHost></ldapBackupHost>
225
+     *     <ldapBackupPort></ldapBackupPort>
226
+     *     <ldapBase>ou=small,dc=my,dc=ldap,dc=server</ldapBase>
227
+     *     <ldapBaseUsers>ou=users,ou=small,dc=my,dc=ldap,dc=server</ldapBaseUsers>
228
+     *     <ldapBaseGroups>ou=small,dc=my,dc=ldap,dc=server</ldapBaseGroups>
229
+     *     <ldapAgentName>cn=root,dc=my,dc=ldap,dc=server</ldapAgentName>
230
+     *     <ldapAgentPassword>clearTextWithShowPassword=1</ldapAgentPassword>
231
+     *     <ldapTLS>1</ldapTLS>
232
+     *     <turnOffCertCheck>0</turnOffCertCheck>
233
+     *     <ldapIgnoreNamingRules/>
234
+     *     <ldapUserDisplayName>displayname</ldapUserDisplayName>
235
+     *     <ldapUserDisplayName2>uid</ldapUserDisplayName2>
236
+     *     <ldapUserFilterObjectclass>inetOrgPerson</ldapUserFilterObjectclass>
237
+     *     <ldapUserFilterGroups></ldapUserFilterGroups>
238
+     *     <ldapUserFilter>(&amp;(objectclass=nextcloudUser)(nextcloudEnabled=TRUE))</ldapUserFilter>
239
+     *     <ldapUserFilterMode>1</ldapUserFilterMode>
240
+     *     <ldapGroupFilter>(&amp;(|(objectclass=nextcloudGroup)))</ldapGroupFilter>
241
+     *     <ldapGroupFilterMode>0</ldapGroupFilterMode>
242
+     *     <ldapGroupFilterObjectclass>nextcloudGroup</ldapGroupFilterObjectclass>
243
+     *     <ldapGroupFilterGroups></ldapGroupFilterGroups>
244
+     *     <ldapGroupDisplayName>cn</ldapGroupDisplayName>
245
+     *     <ldapGroupMemberAssocAttr>memberUid</ldapGroupMemberAssocAttr>
246
+     *     <ldapLoginFilter>(&amp;(|(objectclass=inetOrgPerson))(uid=%uid))</ldapLoginFilter>
247
+     *     <ldapLoginFilterMode>0</ldapLoginFilterMode>
248
+     *     <ldapLoginFilterEmail>0</ldapLoginFilterEmail>
249
+     *     <ldapLoginFilterUsername>1</ldapLoginFilterUsername>
250
+     *     <ldapLoginFilterAttributes></ldapLoginFilterAttributes>
251
+     *     <ldapQuotaAttribute></ldapQuotaAttribute>
252
+     *     <ldapQuotaDefault></ldapQuotaDefault>
253
+     *     <ldapEmailAttribute>mail</ldapEmailAttribute>
254
+     *     <ldapCacheTTL>20</ldapCacheTTL>
255
+     *     <ldapUuidUserAttribute>auto</ldapUuidUserAttribute>
256
+     *     <ldapUuidGroupAttribute>auto</ldapUuidGroupAttribute>
257
+     *     <ldapOverrideMainServer></ldapOverrideMainServer>
258
+     *     <ldapConfigurationActive>1</ldapConfigurationActive>
259
+     *     <ldapAttributesForUserSearch>uid;sn;givenname</ldapAttributesForUserSearch>
260
+     *     <ldapAttributesForGroupSearch></ldapAttributesForGroupSearch>
261
+     *     <ldapExperiencedAdmin>0</ldapExperiencedAdmin>
262
+     *     <homeFolderNamingRule></homeFolderNamingRule>
263
+     *     <hasPagedResultSupport></hasPagedResultSupport>
264
+     *     <hasMemberOfFilterSupport></hasMemberOfFilterSupport>
265
+     *     <useMemberOfToDetectMembership>1</useMemberOfToDetectMembership>
266
+     *     <ldapExpertUsernameAttr>uid</ldapExpertUsernameAttr>
267
+     *     <ldapExpertUUIDUserAttr>uid</ldapExpertUUIDUserAttr>
268
+     *     <ldapExpertUUIDGroupAttr></ldapExpertUUIDGroupAttr>
269
+     *     <lastJpegPhotoLookup>0</lastJpegPhotoLookup>
270
+     *     <ldapNestedGroups>0</ldapNestedGroups>
271
+     *     <ldapPagingSize>500</ldapPagingSize>
272
+     *     <turnOnPasswordChange>1</turnOnPasswordChange>
273
+     *     <ldapDynamicGroupMemberURL></ldapDynamicGroupMemberURL>
274
+     *   </data>
275
+     * </ocs>
276
+     *
277
+     * @param string $configID
278
+     * @param bool|string $showPassword
279
+     * @return DataResponse
280
+     * @throws OCSException
281
+     */
282
+    public function show($configID, $showPassword = false) {
283
+        try {
284
+            $this->ensureConfigIDExists($configID);
285 285
 
286
-			$config = new Configuration($configID);
287
-			$data = $config->getConfiguration();
288
-			if(!boolval(intval($showPassword))) {
289
-				$data['ldapAgentPassword'] = '***';
290
-			}
291
-			foreach ($data as $key => $value) {
292
-				if(is_array($value)) {
293
-					$value = implode(';', $value);
294
-					$data[$key] = $value;
295
-				}
296
-			}
297
-		} catch(OCSException $e) {
298
-			throw $e;
299
-		} catch (\Exception $e) {
300
-			$this->logger->logException($e);
301
-			throw new OCSException('An issue occurred when modifying the config.');
302
-		}
286
+            $config = new Configuration($configID);
287
+            $data = $config->getConfiguration();
288
+            if(!boolval(intval($showPassword))) {
289
+                $data['ldapAgentPassword'] = '***';
290
+            }
291
+            foreach ($data as $key => $value) {
292
+                if(is_array($value)) {
293
+                    $value = implode(';', $value);
294
+                    $data[$key] = $value;
295
+                }
296
+            }
297
+        } catch(OCSException $e) {
298
+            throw $e;
299
+        } catch (\Exception $e) {
300
+            $this->logger->logException($e);
301
+            throw new OCSException('An issue occurred when modifying the config.');
302
+        }
303 303
 
304
-		return new DataResponse($data);
305
-	}
304
+        return new DataResponse($data);
305
+    }
306 306
 
307
-	/**
308
-	 * if the given config ID is not available, an exception is thrown
309
-	 *
310
-	 * @param string $configID
311
-	 * @throws OCSNotFoundException
312
-	 */
313
-	private function ensureConfigIDExists($configID) {
314
-		$prefixes = $this->ldapHelper->getServerConfigurationPrefixes();
315
-		if(!in_array($configID, $prefixes, true)) {
316
-			throw new OCSNotFoundException('Config ID not found');
317
-		}
318
-	}
307
+    /**
308
+     * if the given config ID is not available, an exception is thrown
309
+     *
310
+     * @param string $configID
311
+     * @throws OCSNotFoundException
312
+     */
313
+    private function ensureConfigIDExists($configID) {
314
+        $prefixes = $this->ldapHelper->getServerConfigurationPrefixes();
315
+        if(!in_array($configID, $prefixes, true)) {
316
+            throw new OCSNotFoundException('Config ID not found');
317
+        }
318
+    }
319 319
 }
Please login to merge, or discard this patch.
apps/files_sharing/lib/Controller/ShareController.php 1 patch
Indentation   +550 added lines, -550 removed lines patch added patch discarded remove patch
@@ -64,558 +64,558 @@
 block discarded – undo
64 64
  */
65 65
 class ShareController extends Controller {
66 66
 
67
-	/** @var IConfig */
68
-	protected $config;
69
-	/** @var IURLGenerator */
70
-	protected $urlGenerator;
71
-	/** @var IUserManager */
72
-	protected $userManager;
73
-	/** @var ILogger */
74
-	protected $logger;
75
-	/** @var \OCP\Activity\IManager */
76
-	protected $activityManager;
77
-	/** @var \OCP\Share\IManager */
78
-	protected $shareManager;
79
-	/** @var ISession */
80
-	protected $session;
81
-	/** @var IPreview */
82
-	protected $previewManager;
83
-	/** @var IRootFolder */
84
-	protected $rootFolder;
85
-	/** @var FederatedShareProvider */
86
-	protected $federatedShareProvider;
87
-	/** @var EventDispatcherInterface */
88
-	protected $eventDispatcher;
89
-	/** @var IL10N */
90
-	protected $l10n;
91
-	/** @var Defaults */
92
-	protected $defaults;
93
-
94
-	/**
95
-	 * @param string $appName
96
-	 * @param IRequest $request
97
-	 * @param IConfig $config
98
-	 * @param IURLGenerator $urlGenerator
99
-	 * @param IUserManager $userManager
100
-	 * @param ILogger $logger
101
-	 * @param \OCP\Activity\IManager $activityManager
102
-	 * @param \OCP\Share\IManager $shareManager
103
-	 * @param ISession $session
104
-	 * @param IPreview $previewManager
105
-	 * @param IRootFolder $rootFolder
106
-	 * @param FederatedShareProvider $federatedShareProvider
107
-	 * @param EventDispatcherInterface $eventDispatcher
108
-	 * @param IL10N $l10n
109
-	 * @param Defaults $defaults
110
-	 */
111
-	public function __construct($appName,
112
-								IRequest $request,
113
-								IConfig $config,
114
-								IURLGenerator $urlGenerator,
115
-								IUserManager $userManager,
116
-								ILogger $logger,
117
-								\OCP\Activity\IManager $activityManager,
118
-								\OCP\Share\IManager $shareManager,
119
-								ISession $session,
120
-								IPreview $previewManager,
121
-								IRootFolder $rootFolder,
122
-								FederatedShareProvider $federatedShareProvider,
123
-								EventDispatcherInterface $eventDispatcher,
124
-								IL10N $l10n,
125
-								Defaults $defaults) {
126
-		parent::__construct($appName, $request);
127
-
128
-		$this->config = $config;
129
-		$this->urlGenerator = $urlGenerator;
130
-		$this->userManager = $userManager;
131
-		$this->logger = $logger;
132
-		$this->activityManager = $activityManager;
133
-		$this->shareManager = $shareManager;
134
-		$this->session = $session;
135
-		$this->previewManager = $previewManager;
136
-		$this->rootFolder = $rootFolder;
137
-		$this->federatedShareProvider = $federatedShareProvider;
138
-		$this->eventDispatcher = $eventDispatcher;
139
-		$this->l10n = $l10n;
140
-		$this->defaults = $defaults;
141
-	}
142
-
143
-	/**
144
-	 * @PublicPage
145
-	 * @NoCSRFRequired
146
-	 *
147
-	 * @param string $token
148
-	 * @return TemplateResponse|RedirectResponse
149
-	 */
150
-	public function showAuthenticate($token) {
151
-		$share = $this->shareManager->getShareByToken($token);
152
-
153
-		if($this->linkShareAuth($share)) {
154
-			return new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.showShare', array('token' => $token)));
155
-		}
156
-
157
-		return new TemplateResponse($this->appName, 'authenticate', array(), 'guest');
158
-	}
159
-
160
-	/**
161
-	 * @PublicPage
162
-	 * @UseSession
163
-	 * @BruteForceProtection(action=publicLinkAuth)
164
-	 *
165
-	 * Authenticates against password-protected shares
166
-	 * @param string $token
167
-	 * @param string $password
168
-	 * @return RedirectResponse|TemplateResponse|NotFoundResponse
169
-	 */
170
-	public function authenticate($token, $password = '') {
171
-
172
-		// Check whether share exists
173
-		try {
174
-			$share = $this->shareManager->getShareByToken($token);
175
-		} catch (ShareNotFound $e) {
176
-			return new NotFoundResponse();
177
-		}
178
-
179
-		$authenticate = $this->linkShareAuth($share, $password);
180
-
181
-		if($authenticate === true) {
182
-			return new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.showShare', array('token' => $token)));
183
-		}
184
-
185
-		$response = new TemplateResponse($this->appName, 'authenticate', array('wrongpw' => true), 'guest');
186
-		$response->throttle();
187
-		return $response;
188
-	}
189
-
190
-	/**
191
-	 * Authenticate a link item with the given password.
192
-	 * Or use the session if no password is provided.
193
-	 *
194
-	 * This is a modified version of Helper::authenticate
195
-	 * TODO: Try to merge back eventually with Helper::authenticate
196
-	 *
197
-	 * @param \OCP\Share\IShare $share
198
-	 * @param string|null $password
199
-	 * @return bool
200
-	 */
201
-	private function linkShareAuth(\OCP\Share\IShare $share, $password = null) {
202
-		if ($password !== null) {
203
-			if ($this->shareManager->checkPassword($share, $password)) {
204
-				$this->session->set('public_link_authenticated', (string)$share->getId());
205
-			} else {
206
-				$this->emitAccessShareHook($share, 403, 'Wrong password');
207
-				return false;
208
-			}
209
-		} else {
210
-			// not authenticated ?
211
-			if ( ! $this->session->exists('public_link_authenticated')
212
-				|| $this->session->get('public_link_authenticated') !== (string)$share->getId()) {
213
-				return false;
214
-			}
215
-		}
216
-		return true;
217
-	}
218
-
219
-	/**
220
-	 * throws hooks when a share is attempted to be accessed
221
-	 *
222
-	 * @param \OCP\Share\IShare|string $share the Share instance if available,
223
-	 * otherwise token
224
-	 * @param int $errorCode
225
-	 * @param string $errorMessage
226
-	 * @throws \OC\HintException
227
-	 * @throws \OC\ServerNotAvailableException
228
-	 */
229
-	protected function emitAccessShareHook($share, $errorCode = 200, $errorMessage = '') {
230
-		$itemType = $itemSource = $uidOwner = '';
231
-		$token = $share;
232
-		$exception = null;
233
-		if($share instanceof \OCP\Share\IShare) {
234
-			try {
235
-				$token = $share->getToken();
236
-				$uidOwner = $share->getSharedBy();
237
-				$itemType = $share->getNodeType();
238
-				$itemSource = $share->getNodeId();
239
-			} catch (\Exception $e) {
240
-				// we log what we know and pass on the exception afterwards
241
-				$exception = $e;
242
-			}
243
-		}
244
-		\OC_Hook::emit('OCP\Share', 'share_link_access', [
245
-			'itemType' => $itemType,
246
-			'itemSource' => $itemSource,
247
-			'uidOwner' => $uidOwner,
248
-			'token' => $token,
249
-			'errorCode' => $errorCode,
250
-			'errorMessage' => $errorMessage,
251
-		]);
252
-		if(!is_null($exception)) {
253
-			throw $exception;
254
-		}
255
-	}
256
-
257
-	/**
258
-	 * Validate the permissions of the share
259
-	 *
260
-	 * @param Share\IShare $share
261
-	 * @return bool
262
-	 */
263
-	private function validateShare(\OCP\Share\IShare $share) {
264
-		return $share->getNode()->isReadable() && $share->getNode()->isShareable();
265
-	}
266
-
267
-	/**
268
-	 * @PublicPage
269
-	 * @NoCSRFRequired
270
-	 *
271
-	 * @param string $token
272
-	 * @param string $path
273
-	 * @return TemplateResponse|RedirectResponse|NotFoundResponse
274
-	 * @throws NotFoundException
275
-	 * @throws \Exception
276
-	 */
277
-	public function showShare($token, $path = '') {
278
-		\OC_User::setIncognitoMode(true);
279
-
280
-		// Check whether share exists
281
-		try {
282
-			$share = $this->shareManager->getShareByToken($token);
283
-		} catch (ShareNotFound $e) {
284
-			$this->emitAccessShareHook($token, 404, 'Share not found');
285
-			return new NotFoundResponse();
286
-		}
287
-
288
-		// Share is password protected - check whether the user is permitted to access the share
289
-		if ($share->getPassword() !== null && !$this->linkShareAuth($share)) {
290
-			return new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.authenticate',
291
-				array('token' => $token)));
292
-		}
293
-
294
-		if (!$this->validateShare($share)) {
295
-			throw new NotFoundException();
296
-		}
297
-		// We can't get the path of a file share
298
-		try {
299
-			if ($share->getNode() instanceof \OCP\Files\File && $path !== '') {
300
-				$this->emitAccessShareHook($share, 404, 'Share not found');
301
-				throw new NotFoundException();
302
-			}
303
-		} catch (\Exception $e) {
304
-			$this->emitAccessShareHook($share, 404, 'Share not found');
305
-			throw $e;
306
-		}
307
-
308
-		$shareTmpl = [];
309
-		$shareTmpl['displayName'] = $this->userManager->get($share->getShareOwner())->getDisplayName();
310
-		$shareTmpl['owner'] = $share->getShareOwner();
311
-		$shareTmpl['filename'] = $share->getNode()->getName();
312
-		$shareTmpl['directory_path'] = $share->getTarget();
313
-		$shareTmpl['mimetype'] = $share->getNode()->getMimetype();
314
-		$shareTmpl['previewSupported'] = $this->previewManager->isMimeSupported($share->getNode()->getMimetype());
315
-		$shareTmpl['dirToken'] = $token;
316
-		$shareTmpl['sharingToken'] = $token;
317
-		$shareTmpl['server2serversharing'] = $this->federatedShareProvider->isOutgoingServer2serverShareEnabled();
318
-		$shareTmpl['protected'] = $share->getPassword() !== null ? 'true' : 'false';
319
-		$shareTmpl['dir'] = '';
320
-		$shareTmpl['nonHumanFileSize'] = $share->getNode()->getSize();
321
-		$shareTmpl['fileSize'] = \OCP\Util::humanFileSize($share->getNode()->getSize());
322
-
323
-		// Show file list
324
-		$hideFileList = false;
325
-		if ($share->getNode() instanceof \OCP\Files\Folder) {
326
-			/** @var \OCP\Files\Folder $rootFolder */
327
-			$rootFolder = $share->getNode();
328
-
329
-			try {
330
-				$folderNode = $rootFolder->get($path);
331
-			} catch (\OCP\Files\NotFoundException $e) {
332
-				$this->emitAccessShareHook($share, 404, 'Share not found');
333
-				throw new NotFoundException();
334
-			}
335
-
336
-			$shareTmpl['dir'] = $rootFolder->getRelativePath($folderNode->getPath());
337
-
338
-			/*
67
+    /** @var IConfig */
68
+    protected $config;
69
+    /** @var IURLGenerator */
70
+    protected $urlGenerator;
71
+    /** @var IUserManager */
72
+    protected $userManager;
73
+    /** @var ILogger */
74
+    protected $logger;
75
+    /** @var \OCP\Activity\IManager */
76
+    protected $activityManager;
77
+    /** @var \OCP\Share\IManager */
78
+    protected $shareManager;
79
+    /** @var ISession */
80
+    protected $session;
81
+    /** @var IPreview */
82
+    protected $previewManager;
83
+    /** @var IRootFolder */
84
+    protected $rootFolder;
85
+    /** @var FederatedShareProvider */
86
+    protected $federatedShareProvider;
87
+    /** @var EventDispatcherInterface */
88
+    protected $eventDispatcher;
89
+    /** @var IL10N */
90
+    protected $l10n;
91
+    /** @var Defaults */
92
+    protected $defaults;
93
+
94
+    /**
95
+     * @param string $appName
96
+     * @param IRequest $request
97
+     * @param IConfig $config
98
+     * @param IURLGenerator $urlGenerator
99
+     * @param IUserManager $userManager
100
+     * @param ILogger $logger
101
+     * @param \OCP\Activity\IManager $activityManager
102
+     * @param \OCP\Share\IManager $shareManager
103
+     * @param ISession $session
104
+     * @param IPreview $previewManager
105
+     * @param IRootFolder $rootFolder
106
+     * @param FederatedShareProvider $federatedShareProvider
107
+     * @param EventDispatcherInterface $eventDispatcher
108
+     * @param IL10N $l10n
109
+     * @param Defaults $defaults
110
+     */
111
+    public function __construct($appName,
112
+                                IRequest $request,
113
+                                IConfig $config,
114
+                                IURLGenerator $urlGenerator,
115
+                                IUserManager $userManager,
116
+                                ILogger $logger,
117
+                                \OCP\Activity\IManager $activityManager,
118
+                                \OCP\Share\IManager $shareManager,
119
+                                ISession $session,
120
+                                IPreview $previewManager,
121
+                                IRootFolder $rootFolder,
122
+                                FederatedShareProvider $federatedShareProvider,
123
+                                EventDispatcherInterface $eventDispatcher,
124
+                                IL10N $l10n,
125
+                                Defaults $defaults) {
126
+        parent::__construct($appName, $request);
127
+
128
+        $this->config = $config;
129
+        $this->urlGenerator = $urlGenerator;
130
+        $this->userManager = $userManager;
131
+        $this->logger = $logger;
132
+        $this->activityManager = $activityManager;
133
+        $this->shareManager = $shareManager;
134
+        $this->session = $session;
135
+        $this->previewManager = $previewManager;
136
+        $this->rootFolder = $rootFolder;
137
+        $this->federatedShareProvider = $federatedShareProvider;
138
+        $this->eventDispatcher = $eventDispatcher;
139
+        $this->l10n = $l10n;
140
+        $this->defaults = $defaults;
141
+    }
142
+
143
+    /**
144
+     * @PublicPage
145
+     * @NoCSRFRequired
146
+     *
147
+     * @param string $token
148
+     * @return TemplateResponse|RedirectResponse
149
+     */
150
+    public function showAuthenticate($token) {
151
+        $share = $this->shareManager->getShareByToken($token);
152
+
153
+        if($this->linkShareAuth($share)) {
154
+            return new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.showShare', array('token' => $token)));
155
+        }
156
+
157
+        return new TemplateResponse($this->appName, 'authenticate', array(), 'guest');
158
+    }
159
+
160
+    /**
161
+     * @PublicPage
162
+     * @UseSession
163
+     * @BruteForceProtection(action=publicLinkAuth)
164
+     *
165
+     * Authenticates against password-protected shares
166
+     * @param string $token
167
+     * @param string $password
168
+     * @return RedirectResponse|TemplateResponse|NotFoundResponse
169
+     */
170
+    public function authenticate($token, $password = '') {
171
+
172
+        // Check whether share exists
173
+        try {
174
+            $share = $this->shareManager->getShareByToken($token);
175
+        } catch (ShareNotFound $e) {
176
+            return new NotFoundResponse();
177
+        }
178
+
179
+        $authenticate = $this->linkShareAuth($share, $password);
180
+
181
+        if($authenticate === true) {
182
+            return new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.showShare', array('token' => $token)));
183
+        }
184
+
185
+        $response = new TemplateResponse($this->appName, 'authenticate', array('wrongpw' => true), 'guest');
186
+        $response->throttle();
187
+        return $response;
188
+    }
189
+
190
+    /**
191
+     * Authenticate a link item with the given password.
192
+     * Or use the session if no password is provided.
193
+     *
194
+     * This is a modified version of Helper::authenticate
195
+     * TODO: Try to merge back eventually with Helper::authenticate
196
+     *
197
+     * @param \OCP\Share\IShare $share
198
+     * @param string|null $password
199
+     * @return bool
200
+     */
201
+    private function linkShareAuth(\OCP\Share\IShare $share, $password = null) {
202
+        if ($password !== null) {
203
+            if ($this->shareManager->checkPassword($share, $password)) {
204
+                $this->session->set('public_link_authenticated', (string)$share->getId());
205
+            } else {
206
+                $this->emitAccessShareHook($share, 403, 'Wrong password');
207
+                return false;
208
+            }
209
+        } else {
210
+            // not authenticated ?
211
+            if ( ! $this->session->exists('public_link_authenticated')
212
+                || $this->session->get('public_link_authenticated') !== (string)$share->getId()) {
213
+                return false;
214
+            }
215
+        }
216
+        return true;
217
+    }
218
+
219
+    /**
220
+     * throws hooks when a share is attempted to be accessed
221
+     *
222
+     * @param \OCP\Share\IShare|string $share the Share instance if available,
223
+     * otherwise token
224
+     * @param int $errorCode
225
+     * @param string $errorMessage
226
+     * @throws \OC\HintException
227
+     * @throws \OC\ServerNotAvailableException
228
+     */
229
+    protected function emitAccessShareHook($share, $errorCode = 200, $errorMessage = '') {
230
+        $itemType = $itemSource = $uidOwner = '';
231
+        $token = $share;
232
+        $exception = null;
233
+        if($share instanceof \OCP\Share\IShare) {
234
+            try {
235
+                $token = $share->getToken();
236
+                $uidOwner = $share->getSharedBy();
237
+                $itemType = $share->getNodeType();
238
+                $itemSource = $share->getNodeId();
239
+            } catch (\Exception $e) {
240
+                // we log what we know and pass on the exception afterwards
241
+                $exception = $e;
242
+            }
243
+        }
244
+        \OC_Hook::emit('OCP\Share', 'share_link_access', [
245
+            'itemType' => $itemType,
246
+            'itemSource' => $itemSource,
247
+            'uidOwner' => $uidOwner,
248
+            'token' => $token,
249
+            'errorCode' => $errorCode,
250
+            'errorMessage' => $errorMessage,
251
+        ]);
252
+        if(!is_null($exception)) {
253
+            throw $exception;
254
+        }
255
+    }
256
+
257
+    /**
258
+     * Validate the permissions of the share
259
+     *
260
+     * @param Share\IShare $share
261
+     * @return bool
262
+     */
263
+    private function validateShare(\OCP\Share\IShare $share) {
264
+        return $share->getNode()->isReadable() && $share->getNode()->isShareable();
265
+    }
266
+
267
+    /**
268
+     * @PublicPage
269
+     * @NoCSRFRequired
270
+     *
271
+     * @param string $token
272
+     * @param string $path
273
+     * @return TemplateResponse|RedirectResponse|NotFoundResponse
274
+     * @throws NotFoundException
275
+     * @throws \Exception
276
+     */
277
+    public function showShare($token, $path = '') {
278
+        \OC_User::setIncognitoMode(true);
279
+
280
+        // Check whether share exists
281
+        try {
282
+            $share = $this->shareManager->getShareByToken($token);
283
+        } catch (ShareNotFound $e) {
284
+            $this->emitAccessShareHook($token, 404, 'Share not found');
285
+            return new NotFoundResponse();
286
+        }
287
+
288
+        // Share is password protected - check whether the user is permitted to access the share
289
+        if ($share->getPassword() !== null && !$this->linkShareAuth($share)) {
290
+            return new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.authenticate',
291
+                array('token' => $token)));
292
+        }
293
+
294
+        if (!$this->validateShare($share)) {
295
+            throw new NotFoundException();
296
+        }
297
+        // We can't get the path of a file share
298
+        try {
299
+            if ($share->getNode() instanceof \OCP\Files\File && $path !== '') {
300
+                $this->emitAccessShareHook($share, 404, 'Share not found');
301
+                throw new NotFoundException();
302
+            }
303
+        } catch (\Exception $e) {
304
+            $this->emitAccessShareHook($share, 404, 'Share not found');
305
+            throw $e;
306
+        }
307
+
308
+        $shareTmpl = [];
309
+        $shareTmpl['displayName'] = $this->userManager->get($share->getShareOwner())->getDisplayName();
310
+        $shareTmpl['owner'] = $share->getShareOwner();
311
+        $shareTmpl['filename'] = $share->getNode()->getName();
312
+        $shareTmpl['directory_path'] = $share->getTarget();
313
+        $shareTmpl['mimetype'] = $share->getNode()->getMimetype();
314
+        $shareTmpl['previewSupported'] = $this->previewManager->isMimeSupported($share->getNode()->getMimetype());
315
+        $shareTmpl['dirToken'] = $token;
316
+        $shareTmpl['sharingToken'] = $token;
317
+        $shareTmpl['server2serversharing'] = $this->federatedShareProvider->isOutgoingServer2serverShareEnabled();
318
+        $shareTmpl['protected'] = $share->getPassword() !== null ? 'true' : 'false';
319
+        $shareTmpl['dir'] = '';
320
+        $shareTmpl['nonHumanFileSize'] = $share->getNode()->getSize();
321
+        $shareTmpl['fileSize'] = \OCP\Util::humanFileSize($share->getNode()->getSize());
322
+
323
+        // Show file list
324
+        $hideFileList = false;
325
+        if ($share->getNode() instanceof \OCP\Files\Folder) {
326
+            /** @var \OCP\Files\Folder $rootFolder */
327
+            $rootFolder = $share->getNode();
328
+
329
+            try {
330
+                $folderNode = $rootFolder->get($path);
331
+            } catch (\OCP\Files\NotFoundException $e) {
332
+                $this->emitAccessShareHook($share, 404, 'Share not found');
333
+                throw new NotFoundException();
334
+            }
335
+
336
+            $shareTmpl['dir'] = $rootFolder->getRelativePath($folderNode->getPath());
337
+
338
+            /*
339 339
 			 * The OC_Util methods require a view. This just uses the node API
340 340
 			 */
341
-			$freeSpace = $share->getNode()->getStorage()->free_space($share->getNode()->getInternalPath());
342
-			if ($freeSpace < \OCP\Files\FileInfo::SPACE_UNLIMITED) {
343
-				$freeSpace = max($freeSpace, 0);
344
-			} else {
345
-				$freeSpace = (INF > 0) ? INF: PHP_INT_MAX; // work around https://bugs.php.net/bug.php?id=69188
346
-			}
347
-
348
-			$hideFileList = $share->getPermissions() & \OCP\Constants::PERMISSION_READ ? false : true;
349
-			$maxUploadFilesize = $freeSpace;
350
-
351
-			$folder = new Template('files', 'list', '');
352
-			$folder->assign('dir', $rootFolder->getRelativePath($folderNode->getPath()));
353
-			$folder->assign('dirToken', $token);
354
-			$folder->assign('permissions', \OCP\Constants::PERMISSION_READ);
355
-			$folder->assign('isPublic', true);
356
-			$folder->assign('hideFileList', $hideFileList);
357
-			$folder->assign('publicUploadEnabled', 'no');
358
-			$folder->assign('uploadMaxFilesize', $maxUploadFilesize);
359
-			$folder->assign('uploadMaxHumanFilesize', \OCP\Util::humanFileSize($maxUploadFilesize));
360
-			$folder->assign('freeSpace', $freeSpace);
361
-			$folder->assign('usedSpacePercent', 0);
362
-			$folder->assign('trash', false);
363
-			$shareTmpl['folder'] = $folder->fetchPage();
364
-		}
365
-
366
-		$shareTmpl['hideFileList'] = $hideFileList;
367
-		$shareTmpl['shareOwner'] = $this->userManager->get($share->getShareOwner())->getDisplayName();
368
-		$shareTmpl['downloadURL'] = $this->urlGenerator->linkToRouteAbsolute('files_sharing.sharecontroller.downloadShare', ['token' => $token]);
369
-		$shareTmpl['shareUrl'] = $this->urlGenerator->linkToRouteAbsolute('files_sharing.sharecontroller.showShare', ['token' => $token]);
370
-		$shareTmpl['maxSizeAnimateGif'] = $this->config->getSystemValue('max_filesize_animated_gifs_public_sharing', 10);
371
-		$shareTmpl['previewEnabled'] = $this->config->getSystemValue('enable_previews', true);
372
-		$shareTmpl['previewMaxX'] = $this->config->getSystemValue('preview_max_x', 1024);
373
-		$shareTmpl['previewMaxY'] = $this->config->getSystemValue('preview_max_y', 1024);
374
-		$shareTmpl['disclaimer'] = $this->config->getAppValue('core', 'shareapi_public_link_disclaimertext', null);
375
-		if ($shareTmpl['previewSupported']) {
376
-			$shareTmpl['previewImage'] = $this->urlGenerator->linkToRouteAbsolute( 'files_sharing.PublicPreview.getPreview',
377
-				['x' => 200, 'y' => 200, 'file' => $shareTmpl['directory_path'], 't' => $shareTmpl['dirToken']]);
378
-		} else {
379
-			$shareTmpl['previewImage'] = $this->urlGenerator->getAbsoluteURL($this->urlGenerator->imagePath('core', 'favicon-fb.png'));
380
-		}
381
-
382
-		// Load files we need
383
-		\OCP\Util::addScript('files', 'file-upload');
384
-		\OCP\Util::addStyle('files_sharing', 'publicView');
385
-		\OCP\Util::addScript('files_sharing', 'public');
386
-		\OCP\Util::addScript('files', 'fileactions');
387
-		\OCP\Util::addScript('files', 'fileactionsmenu');
388
-		\OCP\Util::addScript('files', 'jquery.fileupload');
389
-		\OCP\Util::addScript('files_sharing', 'files_drop');
390
-
391
-		if (isset($shareTmpl['folder'])) {
392
-			// JS required for folders
393
-			\OCP\Util::addStyle('files', 'merged');
394
-			\OCP\Util::addScript('files', 'filesummary');
395
-			\OCP\Util::addScript('files', 'breadcrumb');
396
-			\OCP\Util::addScript('files', 'fileinfomodel');
397
-			\OCP\Util::addScript('files', 'newfilemenu');
398
-			\OCP\Util::addScript('files', 'files');
399
-			\OCP\Util::addScript('files', 'filelist');
400
-			\OCP\Util::addScript('files', 'keyboardshortcuts');
401
-		}
402
-
403
-		// OpenGraph Support: http://ogp.me/
404
-		\OCP\Util::addHeader('meta', ['property' => "og:title", 'content' => $this->defaults->getName() . ' - ' . $this->defaults->getSlogan()]);
405
-		\OCP\Util::addHeader('meta', ['property' => "og:description", 'content' => $this->l10n->t('%s is publicly shared', [$shareTmpl['filename']])]);
406
-		\OCP\Util::addHeader('meta', ['property' => "og:site_name", 'content' => $this->defaults->getName()]);
407
-		\OCP\Util::addHeader('meta', ['property' => "og:url", 'content' => $shareTmpl['shareUrl']]);
408
-		\OCP\Util::addHeader('meta', ['property' => "og:type", 'content' => "object"]);
409
-		\OCP\Util::addHeader('meta', ['property' => "og:image", 'content' => $shareTmpl['previewImage']]);
410
-
411
-		$this->eventDispatcher->dispatch('OCA\Files_Sharing::loadAdditionalScripts');
412
-
413
-		$csp = new \OCP\AppFramework\Http\ContentSecurityPolicy();
414
-		$csp->addAllowedFrameDomain('\'self\'');
415
-		$response = new TemplateResponse($this->appName, 'public', $shareTmpl, 'base');
416
-		$response->setContentSecurityPolicy($csp);
417
-
418
-		$this->emitAccessShareHook($share);
419
-
420
-		return $response;
421
-	}
422
-
423
-	/**
424
-	 * @PublicPage
425
-	 * @NoCSRFRequired
426
-	 *
427
-	 * @param string $token
428
-	 * @param string $files
429
-	 * @param string $path
430
-	 * @param string $downloadStartSecret
431
-	 * @return void|\OCP\AppFramework\Http\Response
432
-	 * @throws NotFoundException
433
-	 */
434
-	public function downloadShare($token, $files = null, $path = '', $downloadStartSecret = '') {
435
-		\OC_User::setIncognitoMode(true);
436
-
437
-		$share = $this->shareManager->getShareByToken($token);
438
-
439
-		if(!($share->getPermissions() & \OCP\Constants::PERMISSION_READ)) {
440
-			return new \OCP\AppFramework\Http\DataResponse('Share is read-only');
441
-		}
442
-
443
-		// Share is password protected - check whether the user is permitted to access the share
444
-		if ($share->getPassword() !== null && !$this->linkShareAuth($share)) {
445
-			return new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.authenticate',
446
-				['token' => $token]));
447
-		}
448
-
449
-		$files_list = null;
450
-		if (!is_null($files)) { // download selected files
451
-			$files_list = json_decode($files);
452
-			// in case we get only a single file
453
-			if ($files_list === null) {
454
-				$files_list = [$files];
455
-			}
456
-		}
457
-
458
-		$userFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
459
-		$originalSharePath = $userFolder->getRelativePath($share->getNode()->getPath());
460
-
461
-		if (!$this->validateShare($share)) {
462
-			throw new NotFoundException();
463
-		}
464
-
465
-		// Single file share
466
-		if ($share->getNode() instanceof \OCP\Files\File) {
467
-			// Single file download
468
-			$this->singleFileDownloaded($share, $share->getNode());
469
-		}
470
-		// Directory share
471
-		else {
472
-			/** @var \OCP\Files\Folder $node */
473
-			$node = $share->getNode();
474
-
475
-			// Try to get the path
476
-			if ($path !== '') {
477
-				try {
478
-					$node = $node->get($path);
479
-				} catch (NotFoundException $e) {
480
-					$this->emitAccessShareHook($share, 404, 'Share not found');
481
-					return new NotFoundResponse();
482
-				}
483
-			}
484
-
485
-			$originalSharePath = $userFolder->getRelativePath($node->getPath());
486
-
487
-			if ($node instanceof \OCP\Files\File) {
488
-				// Single file download
489
-				$this->singleFileDownloaded($share, $share->getNode());
490
-			} else if (!empty($files_list)) {
491
-				$this->fileListDownloaded($share, $files_list, $node);
492
-			} else {
493
-				// The folder is downloaded
494
-				$this->singleFileDownloaded($share, $share->getNode());
495
-			}
496
-		}
497
-
498
-		/* FIXME: We should do this all nicely in OCP */
499
-		OC_Util::tearDownFS();
500
-		OC_Util::setupFS($share->getShareOwner());
501
-
502
-		/**
503
-		 * this sets a cookie to be able to recognize the start of the download
504
-		 * the content must not be longer than 32 characters and must only contain
505
-		 * alphanumeric characters
506
-		 */
507
-		if (!empty($downloadStartSecret)
508
-			&& !isset($downloadStartSecret[32])
509
-			&& preg_match('!^[a-zA-Z0-9]+$!', $downloadStartSecret) === 1) {
510
-
511
-			// FIXME: set on the response once we use an actual app framework response
512
-			setcookie('ocDownloadStarted', $downloadStartSecret, time() + 20, '/');
513
-		}
514
-
515
-		$this->emitAccessShareHook($share);
516
-
517
-		$server_params = array( 'head' => $this->request->getMethod() == 'HEAD' );
518
-
519
-		/**
520
-		 * Http range requests support
521
-		 */
522
-		if (isset($_SERVER['HTTP_RANGE'])) {
523
-			$server_params['range'] = $this->request->getHeader('Range');
524
-		}
525
-
526
-		// download selected files
527
-		if (!is_null($files) && $files !== '') {
528
-			// FIXME: The exit is required here because otherwise the AppFramework is trying to add headers as well
529
-			// after dispatching the request which results in a "Cannot modify header information" notice.
530
-			OC_Files::get($originalSharePath, $files_list, $server_params);
531
-			exit();
532
-		} else {
533
-			// FIXME: The exit is required here because otherwise the AppFramework is trying to add headers as well
534
-			// after dispatching the request which results in a "Cannot modify header information" notice.
535
-			OC_Files::get(dirname($originalSharePath), basename($originalSharePath), $server_params);
536
-			exit();
537
-		}
538
-	}
539
-
540
-	/**
541
-	 * create activity for every downloaded file
542
-	 *
543
-	 * @param Share\IShare $share
544
-	 * @param array $files_list
545
-	 * @param \OCP\Files\Folder $node
546
-	 */
547
-	protected function fileListDownloaded(Share\IShare $share, array $files_list, \OCP\Files\Folder $node) {
548
-		foreach ($files_list as $file) {
549
-			$subNode = $node->get($file);
550
-			$this->singleFileDownloaded($share, $subNode);
551
-		}
552
-
553
-	}
554
-
555
-	/**
556
-	 * create activity if a single file was downloaded from a link share
557
-	 *
558
-	 * @param Share\IShare $share
559
-	 */
560
-	protected function singleFileDownloaded(Share\IShare $share, \OCP\Files\Node $node) {
561
-
562
-		$fileId = $node->getId();
563
-
564
-		$userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
565
-		$userNodeList = $userFolder->getById($fileId);
566
-		$userNode = $userNodeList[0];
567
-		$ownerFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
568
-		$userPath = $userFolder->getRelativePath($userNode->getPath());
569
-		$ownerPath = $ownerFolder->getRelativePath($node->getPath());
570
-
571
-		$parameters = [$userPath];
572
-
573
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
574
-			if ($node instanceof \OCP\Files\File) {
575
-				$subject = Downloads::SUBJECT_SHARED_FILE_BY_EMAIL_DOWNLOADED;
576
-			} else {
577
-				$subject = Downloads::SUBJECT_SHARED_FOLDER_BY_EMAIL_DOWNLOADED;
578
-			}
579
-			$parameters[] = $share->getSharedWith();
580
-		} else {
581
-			if ($node instanceof \OCP\Files\File) {
582
-				$subject = Downloads::SUBJECT_PUBLIC_SHARED_FILE_DOWNLOADED;
583
-			} else {
584
-				$subject = Downloads::SUBJECT_PUBLIC_SHARED_FOLDER_DOWNLOADED;
585
-			}
586
-		}
587
-
588
-		$this->publishActivity($subject, $parameters, $share->getSharedBy(), $fileId, $userPath);
589
-
590
-		if ($share->getShareOwner() !== $share->getSharedBy()) {
591
-			$parameters[0] = $ownerPath;
592
-			$this->publishActivity($subject, $parameters, $share->getShareOwner(), $fileId, $ownerPath);
593
-		}
594
-	}
595
-
596
-	/**
597
-	 * publish activity
598
-	 *
599
-	 * @param string $subject
600
-	 * @param array $parameters
601
-	 * @param string $affectedUser
602
-	 * @param int $fileId
603
-	 * @param string $filePath
604
-	 */
605
-	protected function publishActivity($subject,
606
-										array $parameters,
607
-										$affectedUser,
608
-										$fileId,
609
-										$filePath) {
610
-
611
-		$event = $this->activityManager->generateEvent();
612
-		$event->setApp('files_sharing')
613
-			->setType('public_links')
614
-			->setSubject($subject, $parameters)
615
-			->setAffectedUser($affectedUser)
616
-			->setObject('files', $fileId, $filePath);
617
-		$this->activityManager->publish($event);
618
-	}
341
+            $freeSpace = $share->getNode()->getStorage()->free_space($share->getNode()->getInternalPath());
342
+            if ($freeSpace < \OCP\Files\FileInfo::SPACE_UNLIMITED) {
343
+                $freeSpace = max($freeSpace, 0);
344
+            } else {
345
+                $freeSpace = (INF > 0) ? INF: PHP_INT_MAX; // work around https://bugs.php.net/bug.php?id=69188
346
+            }
347
+
348
+            $hideFileList = $share->getPermissions() & \OCP\Constants::PERMISSION_READ ? false : true;
349
+            $maxUploadFilesize = $freeSpace;
350
+
351
+            $folder = new Template('files', 'list', '');
352
+            $folder->assign('dir', $rootFolder->getRelativePath($folderNode->getPath()));
353
+            $folder->assign('dirToken', $token);
354
+            $folder->assign('permissions', \OCP\Constants::PERMISSION_READ);
355
+            $folder->assign('isPublic', true);
356
+            $folder->assign('hideFileList', $hideFileList);
357
+            $folder->assign('publicUploadEnabled', 'no');
358
+            $folder->assign('uploadMaxFilesize', $maxUploadFilesize);
359
+            $folder->assign('uploadMaxHumanFilesize', \OCP\Util::humanFileSize($maxUploadFilesize));
360
+            $folder->assign('freeSpace', $freeSpace);
361
+            $folder->assign('usedSpacePercent', 0);
362
+            $folder->assign('trash', false);
363
+            $shareTmpl['folder'] = $folder->fetchPage();
364
+        }
365
+
366
+        $shareTmpl['hideFileList'] = $hideFileList;
367
+        $shareTmpl['shareOwner'] = $this->userManager->get($share->getShareOwner())->getDisplayName();
368
+        $shareTmpl['downloadURL'] = $this->urlGenerator->linkToRouteAbsolute('files_sharing.sharecontroller.downloadShare', ['token' => $token]);
369
+        $shareTmpl['shareUrl'] = $this->urlGenerator->linkToRouteAbsolute('files_sharing.sharecontroller.showShare', ['token' => $token]);
370
+        $shareTmpl['maxSizeAnimateGif'] = $this->config->getSystemValue('max_filesize_animated_gifs_public_sharing', 10);
371
+        $shareTmpl['previewEnabled'] = $this->config->getSystemValue('enable_previews', true);
372
+        $shareTmpl['previewMaxX'] = $this->config->getSystemValue('preview_max_x', 1024);
373
+        $shareTmpl['previewMaxY'] = $this->config->getSystemValue('preview_max_y', 1024);
374
+        $shareTmpl['disclaimer'] = $this->config->getAppValue('core', 'shareapi_public_link_disclaimertext', null);
375
+        if ($shareTmpl['previewSupported']) {
376
+            $shareTmpl['previewImage'] = $this->urlGenerator->linkToRouteAbsolute( 'files_sharing.PublicPreview.getPreview',
377
+                ['x' => 200, 'y' => 200, 'file' => $shareTmpl['directory_path'], 't' => $shareTmpl['dirToken']]);
378
+        } else {
379
+            $shareTmpl['previewImage'] = $this->urlGenerator->getAbsoluteURL($this->urlGenerator->imagePath('core', 'favicon-fb.png'));
380
+        }
381
+
382
+        // Load files we need
383
+        \OCP\Util::addScript('files', 'file-upload');
384
+        \OCP\Util::addStyle('files_sharing', 'publicView');
385
+        \OCP\Util::addScript('files_sharing', 'public');
386
+        \OCP\Util::addScript('files', 'fileactions');
387
+        \OCP\Util::addScript('files', 'fileactionsmenu');
388
+        \OCP\Util::addScript('files', 'jquery.fileupload');
389
+        \OCP\Util::addScript('files_sharing', 'files_drop');
390
+
391
+        if (isset($shareTmpl['folder'])) {
392
+            // JS required for folders
393
+            \OCP\Util::addStyle('files', 'merged');
394
+            \OCP\Util::addScript('files', 'filesummary');
395
+            \OCP\Util::addScript('files', 'breadcrumb');
396
+            \OCP\Util::addScript('files', 'fileinfomodel');
397
+            \OCP\Util::addScript('files', 'newfilemenu');
398
+            \OCP\Util::addScript('files', 'files');
399
+            \OCP\Util::addScript('files', 'filelist');
400
+            \OCP\Util::addScript('files', 'keyboardshortcuts');
401
+        }
402
+
403
+        // OpenGraph Support: http://ogp.me/
404
+        \OCP\Util::addHeader('meta', ['property' => "og:title", 'content' => $this->defaults->getName() . ' - ' . $this->defaults->getSlogan()]);
405
+        \OCP\Util::addHeader('meta', ['property' => "og:description", 'content' => $this->l10n->t('%s is publicly shared', [$shareTmpl['filename']])]);
406
+        \OCP\Util::addHeader('meta', ['property' => "og:site_name", 'content' => $this->defaults->getName()]);
407
+        \OCP\Util::addHeader('meta', ['property' => "og:url", 'content' => $shareTmpl['shareUrl']]);
408
+        \OCP\Util::addHeader('meta', ['property' => "og:type", 'content' => "object"]);
409
+        \OCP\Util::addHeader('meta', ['property' => "og:image", 'content' => $shareTmpl['previewImage']]);
410
+
411
+        $this->eventDispatcher->dispatch('OCA\Files_Sharing::loadAdditionalScripts');
412
+
413
+        $csp = new \OCP\AppFramework\Http\ContentSecurityPolicy();
414
+        $csp->addAllowedFrameDomain('\'self\'');
415
+        $response = new TemplateResponse($this->appName, 'public', $shareTmpl, 'base');
416
+        $response->setContentSecurityPolicy($csp);
417
+
418
+        $this->emitAccessShareHook($share);
419
+
420
+        return $response;
421
+    }
422
+
423
+    /**
424
+     * @PublicPage
425
+     * @NoCSRFRequired
426
+     *
427
+     * @param string $token
428
+     * @param string $files
429
+     * @param string $path
430
+     * @param string $downloadStartSecret
431
+     * @return void|\OCP\AppFramework\Http\Response
432
+     * @throws NotFoundException
433
+     */
434
+    public function downloadShare($token, $files = null, $path = '', $downloadStartSecret = '') {
435
+        \OC_User::setIncognitoMode(true);
436
+
437
+        $share = $this->shareManager->getShareByToken($token);
438
+
439
+        if(!($share->getPermissions() & \OCP\Constants::PERMISSION_READ)) {
440
+            return new \OCP\AppFramework\Http\DataResponse('Share is read-only');
441
+        }
442
+
443
+        // Share is password protected - check whether the user is permitted to access the share
444
+        if ($share->getPassword() !== null && !$this->linkShareAuth($share)) {
445
+            return new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.authenticate',
446
+                ['token' => $token]));
447
+        }
448
+
449
+        $files_list = null;
450
+        if (!is_null($files)) { // download selected files
451
+            $files_list = json_decode($files);
452
+            // in case we get only a single file
453
+            if ($files_list === null) {
454
+                $files_list = [$files];
455
+            }
456
+        }
457
+
458
+        $userFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
459
+        $originalSharePath = $userFolder->getRelativePath($share->getNode()->getPath());
460
+
461
+        if (!$this->validateShare($share)) {
462
+            throw new NotFoundException();
463
+        }
464
+
465
+        // Single file share
466
+        if ($share->getNode() instanceof \OCP\Files\File) {
467
+            // Single file download
468
+            $this->singleFileDownloaded($share, $share->getNode());
469
+        }
470
+        // Directory share
471
+        else {
472
+            /** @var \OCP\Files\Folder $node */
473
+            $node = $share->getNode();
474
+
475
+            // Try to get the path
476
+            if ($path !== '') {
477
+                try {
478
+                    $node = $node->get($path);
479
+                } catch (NotFoundException $e) {
480
+                    $this->emitAccessShareHook($share, 404, 'Share not found');
481
+                    return new NotFoundResponse();
482
+                }
483
+            }
484
+
485
+            $originalSharePath = $userFolder->getRelativePath($node->getPath());
486
+
487
+            if ($node instanceof \OCP\Files\File) {
488
+                // Single file download
489
+                $this->singleFileDownloaded($share, $share->getNode());
490
+            } else if (!empty($files_list)) {
491
+                $this->fileListDownloaded($share, $files_list, $node);
492
+            } else {
493
+                // The folder is downloaded
494
+                $this->singleFileDownloaded($share, $share->getNode());
495
+            }
496
+        }
497
+
498
+        /* FIXME: We should do this all nicely in OCP */
499
+        OC_Util::tearDownFS();
500
+        OC_Util::setupFS($share->getShareOwner());
501
+
502
+        /**
503
+         * this sets a cookie to be able to recognize the start of the download
504
+         * the content must not be longer than 32 characters and must only contain
505
+         * alphanumeric characters
506
+         */
507
+        if (!empty($downloadStartSecret)
508
+            && !isset($downloadStartSecret[32])
509
+            && preg_match('!^[a-zA-Z0-9]+$!', $downloadStartSecret) === 1) {
510
+
511
+            // FIXME: set on the response once we use an actual app framework response
512
+            setcookie('ocDownloadStarted', $downloadStartSecret, time() + 20, '/');
513
+        }
514
+
515
+        $this->emitAccessShareHook($share);
516
+
517
+        $server_params = array( 'head' => $this->request->getMethod() == 'HEAD' );
518
+
519
+        /**
520
+         * Http range requests support
521
+         */
522
+        if (isset($_SERVER['HTTP_RANGE'])) {
523
+            $server_params['range'] = $this->request->getHeader('Range');
524
+        }
525
+
526
+        // download selected files
527
+        if (!is_null($files) && $files !== '') {
528
+            // FIXME: The exit is required here because otherwise the AppFramework is trying to add headers as well
529
+            // after dispatching the request which results in a "Cannot modify header information" notice.
530
+            OC_Files::get($originalSharePath, $files_list, $server_params);
531
+            exit();
532
+        } else {
533
+            // FIXME: The exit is required here because otherwise the AppFramework is trying to add headers as well
534
+            // after dispatching the request which results in a "Cannot modify header information" notice.
535
+            OC_Files::get(dirname($originalSharePath), basename($originalSharePath), $server_params);
536
+            exit();
537
+        }
538
+    }
539
+
540
+    /**
541
+     * create activity for every downloaded file
542
+     *
543
+     * @param Share\IShare $share
544
+     * @param array $files_list
545
+     * @param \OCP\Files\Folder $node
546
+     */
547
+    protected function fileListDownloaded(Share\IShare $share, array $files_list, \OCP\Files\Folder $node) {
548
+        foreach ($files_list as $file) {
549
+            $subNode = $node->get($file);
550
+            $this->singleFileDownloaded($share, $subNode);
551
+        }
552
+
553
+    }
554
+
555
+    /**
556
+     * create activity if a single file was downloaded from a link share
557
+     *
558
+     * @param Share\IShare $share
559
+     */
560
+    protected function singleFileDownloaded(Share\IShare $share, \OCP\Files\Node $node) {
561
+
562
+        $fileId = $node->getId();
563
+
564
+        $userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
565
+        $userNodeList = $userFolder->getById($fileId);
566
+        $userNode = $userNodeList[0];
567
+        $ownerFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
568
+        $userPath = $userFolder->getRelativePath($userNode->getPath());
569
+        $ownerPath = $ownerFolder->getRelativePath($node->getPath());
570
+
571
+        $parameters = [$userPath];
572
+
573
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
574
+            if ($node instanceof \OCP\Files\File) {
575
+                $subject = Downloads::SUBJECT_SHARED_FILE_BY_EMAIL_DOWNLOADED;
576
+            } else {
577
+                $subject = Downloads::SUBJECT_SHARED_FOLDER_BY_EMAIL_DOWNLOADED;
578
+            }
579
+            $parameters[] = $share->getSharedWith();
580
+        } else {
581
+            if ($node instanceof \OCP\Files\File) {
582
+                $subject = Downloads::SUBJECT_PUBLIC_SHARED_FILE_DOWNLOADED;
583
+            } else {
584
+                $subject = Downloads::SUBJECT_PUBLIC_SHARED_FOLDER_DOWNLOADED;
585
+            }
586
+        }
587
+
588
+        $this->publishActivity($subject, $parameters, $share->getSharedBy(), $fileId, $userPath);
589
+
590
+        if ($share->getShareOwner() !== $share->getSharedBy()) {
591
+            $parameters[0] = $ownerPath;
592
+            $this->publishActivity($subject, $parameters, $share->getShareOwner(), $fileId, $ownerPath);
593
+        }
594
+    }
595
+
596
+    /**
597
+     * publish activity
598
+     *
599
+     * @param string $subject
600
+     * @param array $parameters
601
+     * @param string $affectedUser
602
+     * @param int $fileId
603
+     * @param string $filePath
604
+     */
605
+    protected function publishActivity($subject,
606
+                                        array $parameters,
607
+                                        $affectedUser,
608
+                                        $fileId,
609
+                                        $filePath) {
610
+
611
+        $event = $this->activityManager->generateEvent();
612
+        $event->setApp('files_sharing')
613
+            ->setType('public_links')
614
+            ->setSubject($subject, $parameters)
615
+            ->setAffectedUser($affectedUser)
616
+            ->setObject('files', $fileId, $filePath);
617
+        $this->activityManager->publish($event);
618
+    }
619 619
 
620 620
 
621 621
 }
Please login to merge, or discard this patch.
apps/federatedfilesharing/lib/Controller/MountPublicLinkController.php 2 patches
Indentation   +280 added lines, -280 removed lines patch added patch discarded remove patch
@@ -54,285 +54,285 @@
 block discarded – undo
54 54
  */
55 55
 class MountPublicLinkController extends Controller {
56 56
 
57
-	/** @var FederatedShareProvider */
58
-	private $federatedShareProvider;
59
-
60
-	/** @var AddressHandler */
61
-	private $addressHandler;
62
-
63
-	/** @var IManager  */
64
-	private $shareManager;
65
-
66
-	/** @var  ISession */
67
-	private $session;
68
-
69
-	/** @var IL10N */
70
-	private $l;
71
-
72
-	/** @var IUserSession */
73
-	private $userSession;
74
-
75
-	/** @var IClientService */
76
-	private $clientService;
77
-
78
-	/** @var ICloudIdManager  */
79
-	private $cloudIdManager;
80
-
81
-	/**
82
-	 * MountPublicLinkController constructor.
83
-	 *
84
-	 * @param string $appName
85
-	 * @param IRequest $request
86
-	 * @param FederatedShareProvider $federatedShareProvider
87
-	 * @param IManager $shareManager
88
-	 * @param AddressHandler $addressHandler
89
-	 * @param ISession $session
90
-	 * @param IL10N $l
91
-	 * @param IUserSession $userSession
92
-	 * @param IClientService $clientService
93
-	 * @param ICloudIdManager $cloudIdManager
94
-	 */
95
-	public function __construct($appName,
96
-								IRequest $request,
97
-								FederatedShareProvider $federatedShareProvider,
98
-								IManager $shareManager,
99
-								AddressHandler $addressHandler,
100
-								ISession $session,
101
-								IL10N $l,
102
-								IUserSession $userSession,
103
-								IClientService $clientService,
104
-								ICloudIdManager $cloudIdManager
105
-	) {
106
-		parent::__construct($appName, $request);
107
-
108
-		$this->federatedShareProvider = $federatedShareProvider;
109
-		$this->shareManager = $shareManager;
110
-		$this->addressHandler = $addressHandler;
111
-		$this->session = $session;
112
-		$this->l = $l;
113
-		$this->userSession = $userSession;
114
-		$this->clientService = $clientService;
115
-		$this->cloudIdManager = $cloudIdManager;
116
-	}
117
-
118
-	/**
119
-	 * send federated share to a user of a public link
120
-	 *
121
-	 * @NoCSRFRequired
122
-	 * @PublicPage
123
-	 * @BruteForceProtection(action=publicLink2FederatedShare)
124
-	 *
125
-	 * @param string $shareWith
126
-	 * @param string $token
127
-	 * @param string $password
128
-	 * @return JSONResponse
129
-	 */
130
-	public function createFederatedShare($shareWith, $token, $password = '') {
131
-
132
-		if (!$this->federatedShareProvider->isOutgoingServer2serverShareEnabled()) {
133
-			return new JSONResponse(
134
-				['message' => 'This server doesn\'t support outgoing federated shares'],
135
-				Http::STATUS_BAD_REQUEST
136
-			);
137
-		}
138
-
139
-		try {
140
-			list(, $server) = $this->addressHandler->splitUserRemote($shareWith);
141
-			$share = $this->shareManager->getShareByToken($token);
142
-		} catch (HintException $e) {
143
-			return new JSONResponse(['message' => $e->getHint()], Http::STATUS_BAD_REQUEST);
144
-		}
145
-
146
-		// make sure that user is authenticated in case of a password protected link
147
-		$storedPassword = $share->getPassword();
148
-		$authenticated = $this->session->get('public_link_authenticated') === $share->getId() ||
149
-			$this->shareManager->checkPassword($share, $password);
150
-		if (!empty($storedPassword) && !$authenticated ) {
151
-			$response = new JSONResponse(
152
-				['message' => 'No permission to access the share'],
153
-				Http::STATUS_BAD_REQUEST
154
-			);
155
-			$response->throttle();
156
-			return $response;
157
-		}
158
-
159
-		$share->setSharedWith($shareWith);
160
-
161
-		try {
162
-			$this->federatedShareProvider->create($share);
163
-		} catch (\Exception $e) {
164
-			return new JSONResponse(['message' => $e->getMessage()], Http::STATUS_BAD_REQUEST);
165
-		}
166
-
167
-		return new JSONResponse(['remoteUrl' => $server]);
168
-	}
169
-
170
-	/**
171
-	 * ask other server to get a federated share
172
-	 *
173
-	 * @NoAdminRequired
174
-	 *
175
-	 * @param string $token
176
-	 * @param string $remote
177
-	 * @param string $password
178
-	 * @param string $owner (only for legacy reasons, can be removed with legacyMountPublicLink())
179
-	 * @param string $ownerDisplayName (only for legacy reasons, can be removed with legacyMountPublicLink())
180
-	 * @param string $name (only for legacy reasons, can be removed with legacyMountPublicLink())
181
-	 * @return JSONResponse
182
-	 */
183
-	public function askForFederatedShare($token, $remote, $password = '', $owner = '', $ownerDisplayName = '', $name = '') {
184
-		// check if server admin allows to mount public links from other servers
185
-		if ($this->federatedShareProvider->isIncomingServer2serverShareEnabled() === false) {
186
-			return new JSONResponse(['message' => $this->l->t('Server to server sharing is not enabled on this server')], Http::STATUS_BAD_REQUEST);
187
-		}
188
-
189
-		$cloudId = $this->cloudIdManager->getCloudId($this->userSession->getUser()->getUID(), $this->addressHandler->generateRemoteURL());
190
-
191
-		$httpClient = $this->clientService->newClient();
192
-
193
-		try {
194
-			$response = $httpClient->post($remote . '/index.php/apps/federatedfilesharing/createFederatedShare',
195
-				[
196
-					'body' =>
197
-						[
198
-							'token' => $token,
199
-							'shareWith' => rtrim($cloudId->getId(), '/'),
200
-							'password' => $password
201
-						],
202
-					'connect_timeout' => 10,
203
-				]
204
-			);
205
-		} catch (\Exception $e) {
206
-			if (empty($password)) {
207
-				$message = $this->l->t("Couldn't establish a federated share.");
208
-			} else {
209
-				$message = $this->l->t("Couldn't establish a federated share, maybe the password was wrong.");
210
-			}
211
-			return new JSONResponse(['message' => $message], Http::STATUS_BAD_REQUEST);
212
-		}
213
-
214
-		$body = $response->getBody();
215
-		$result = json_decode($body, true);
216
-
217
-		if (is_array($result) && isset($result['remoteUrl'])) {
218
-			return new JSONResponse(['message' => $this->l->t('Federated Share request was successful, you will receive a invitation. Check your notifications.')]);
219
-		}
220
-
221
-		// if we doesn't get the expected response we assume that we try to add
222
-		// a federated share from a Nextcloud <= 9 server
223
-		return $this->legacyMountPublicLink($token, $remote, $password, $name, $owner, $ownerDisplayName);
224
-	}
225
-
226
-	/**
227
-	 * Allow Nextcloud to mount a public link directly
228
-	 *
229
-	 * This code was copied from the apps/files_sharing/ajax/external.php with
230
-	 * minimal changes, just to guarantee backward compatibility
231
-	 *
232
-	 * ToDo: Remove this method once Nextcloud 9 reaches end of life
233
-	 *
234
-	 * @param string $token
235
-	 * @param string $remote
236
-	 * @param string $password
237
-	 * @param string $name
238
-	 * @param string $owner
239
-	 * @param string $ownerDisplayName
240
-	 * @return JSONResponse
241
-	 */
242
-	private function legacyMountPublicLink($token, $remote, $password, $name, $owner, $ownerDisplayName) {
243
-
244
-		// Check for invalid name
245
-		if (!Util::isValidFileName($name)) {
246
-			return new JSONResponse(['message' => $this->l->t('The mountpoint name contains invalid characters.')], Http::STATUS_BAD_REQUEST);
247
-		}
248
-		$currentUser = $this->userSession->getUser()->getUID();
249
-		$currentServer = $this->addressHandler->generateRemoteURL();
250
-		if (Helper::isSameUserOnSameServer($owner, $remote, $currentUser, $currentServer)) {
251
-			return new JSONResponse(['message' => $this->l->t('Not allowed to create a federated share with the owner.')], Http::STATUS_BAD_REQUEST);
252
-		}
253
-		$externalManager = new Manager(
254
-			\OC::$server->getDatabaseConnection(),
255
-			Filesystem::getMountManager(),
256
-			Filesystem::getLoader(),
257
-			\OC::$server->getHTTPClientService(),
258
-			\OC::$server->getNotificationManager(),
259
-			\OC::$server->query(\OCP\OCS\IDiscoveryService::class),
260
-			\OC::$server->getUserSession()->getUser()->getUID()
261
-		);
262
-
263
-		// check for ssl cert
264
-
265
-		if (strpos($remote, 'https') === 0) {
266
-			try {
267
-				$client = $this->clientService->newClient();
268
-				$client->get($remote, [
269
-					'timeout' => 10,
270
-					'connect_timeout' => 10,
271
-				])->getBody();
272
-			} catch (\Exception $e) {
273
-				return new JSONResponse(['message' => $this->l->t('Invalid or untrusted SSL certificate')], Http::STATUS_BAD_REQUEST);
274
-			}
275
-		}
276
-		$mount = $externalManager->addShare($remote, $token, $password, $name, $ownerDisplayName, true);
277
-		/**
278
-		 * @var \OCA\Files_Sharing\External\Storage $storage
279
-		 */
280
-		$storage = $mount->getStorage();
281
-		try {
282
-			// check if storage exists
283
-			$storage->checkStorageAvailability();
284
-		} catch (StorageInvalidException $e) {
285
-			// note: checkStorageAvailability will already remove the invalid share
286
-			Util::writeLog(
287
-				'federatedfilesharing',
288
-				'Invalid remote storage: ' . get_class($e) . ': ' . $e->getMessage(),
289
-				Util::DEBUG
290
-			);
291
-			return new JSONResponse(['message' => $this->l->t('Could not authenticate to remote share, password might be wrong')], Http::STATUS_BAD_REQUEST);
292
-		} catch (\Exception $e) {
293
-			Util::writeLog(
294
-				'federatedfilesharing',
295
-				'Invalid remote storage: ' . get_class($e) . ': ' . $e->getMessage(),
296
-				Util::DEBUG
297
-			);
298
-			$externalManager->removeShare($mount->getMountPoint());
299
-			return new JSONResponse(['message' => $this->l->t('Storage not valid')], Http::STATUS_BAD_REQUEST);
300
-		}
301
-		$result = $storage->file_exists('');
302
-		if ($result) {
303
-			try {
304
-				$storage->getScanner()->scanAll();
305
-				return new JSONResponse(
306
-					[
307
-						'message' => $this->l->t('Federated Share successfully added'),
308
-						'legacyMount' => '1'
309
-					]
310
-				);
311
-			} catch (StorageInvalidException $e) {
312
-				Util::writeLog(
313
-					'federatedfilesharing',
314
-					'Invalid remote storage: ' . get_class($e) . ': ' . $e->getMessage(),
315
-					Util::DEBUG
316
-				);
317
-				return new JSONResponse(['message' => $this->l->t('Storage not valid')], Http::STATUS_BAD_REQUEST);
318
-			} catch (\Exception $e) {
319
-				Util::writeLog(
320
-					'federatedfilesharing',
321
-					'Invalid remote storage: ' . get_class($e) . ': ' . $e->getMessage(),
322
-					Util::DEBUG
323
-				);
324
-				return new JSONResponse(['message' => $this->l->t('Couldn\'t add remote share')], Http::STATUS_BAD_REQUEST);
325
-			}
326
-		} else {
327
-			$externalManager->removeShare($mount->getMountPoint());
328
-			Util::writeLog(
329
-				'federatedfilesharing',
330
-				'Couldn\'t add remote share',
331
-				Util::DEBUG
332
-			);
333
-			return new JSONResponse(['message' => $this->l->t('Couldn\'t add remote share')], Http::STATUS_BAD_REQUEST);
334
-		}
335
-
336
-	}
57
+    /** @var FederatedShareProvider */
58
+    private $federatedShareProvider;
59
+
60
+    /** @var AddressHandler */
61
+    private $addressHandler;
62
+
63
+    /** @var IManager  */
64
+    private $shareManager;
65
+
66
+    /** @var  ISession */
67
+    private $session;
68
+
69
+    /** @var IL10N */
70
+    private $l;
71
+
72
+    /** @var IUserSession */
73
+    private $userSession;
74
+
75
+    /** @var IClientService */
76
+    private $clientService;
77
+
78
+    /** @var ICloudIdManager  */
79
+    private $cloudIdManager;
80
+
81
+    /**
82
+     * MountPublicLinkController constructor.
83
+     *
84
+     * @param string $appName
85
+     * @param IRequest $request
86
+     * @param FederatedShareProvider $federatedShareProvider
87
+     * @param IManager $shareManager
88
+     * @param AddressHandler $addressHandler
89
+     * @param ISession $session
90
+     * @param IL10N $l
91
+     * @param IUserSession $userSession
92
+     * @param IClientService $clientService
93
+     * @param ICloudIdManager $cloudIdManager
94
+     */
95
+    public function __construct($appName,
96
+                                IRequest $request,
97
+                                FederatedShareProvider $federatedShareProvider,
98
+                                IManager $shareManager,
99
+                                AddressHandler $addressHandler,
100
+                                ISession $session,
101
+                                IL10N $l,
102
+                                IUserSession $userSession,
103
+                                IClientService $clientService,
104
+                                ICloudIdManager $cloudIdManager
105
+    ) {
106
+        parent::__construct($appName, $request);
107
+
108
+        $this->federatedShareProvider = $federatedShareProvider;
109
+        $this->shareManager = $shareManager;
110
+        $this->addressHandler = $addressHandler;
111
+        $this->session = $session;
112
+        $this->l = $l;
113
+        $this->userSession = $userSession;
114
+        $this->clientService = $clientService;
115
+        $this->cloudIdManager = $cloudIdManager;
116
+    }
117
+
118
+    /**
119
+     * send federated share to a user of a public link
120
+     *
121
+     * @NoCSRFRequired
122
+     * @PublicPage
123
+     * @BruteForceProtection(action=publicLink2FederatedShare)
124
+     *
125
+     * @param string $shareWith
126
+     * @param string $token
127
+     * @param string $password
128
+     * @return JSONResponse
129
+     */
130
+    public function createFederatedShare($shareWith, $token, $password = '') {
131
+
132
+        if (!$this->federatedShareProvider->isOutgoingServer2serverShareEnabled()) {
133
+            return new JSONResponse(
134
+                ['message' => 'This server doesn\'t support outgoing federated shares'],
135
+                Http::STATUS_BAD_REQUEST
136
+            );
137
+        }
138
+
139
+        try {
140
+            list(, $server) = $this->addressHandler->splitUserRemote($shareWith);
141
+            $share = $this->shareManager->getShareByToken($token);
142
+        } catch (HintException $e) {
143
+            return new JSONResponse(['message' => $e->getHint()], Http::STATUS_BAD_REQUEST);
144
+        }
145
+
146
+        // make sure that user is authenticated in case of a password protected link
147
+        $storedPassword = $share->getPassword();
148
+        $authenticated = $this->session->get('public_link_authenticated') === $share->getId() ||
149
+            $this->shareManager->checkPassword($share, $password);
150
+        if (!empty($storedPassword) && !$authenticated ) {
151
+            $response = new JSONResponse(
152
+                ['message' => 'No permission to access the share'],
153
+                Http::STATUS_BAD_REQUEST
154
+            );
155
+            $response->throttle();
156
+            return $response;
157
+        }
158
+
159
+        $share->setSharedWith($shareWith);
160
+
161
+        try {
162
+            $this->federatedShareProvider->create($share);
163
+        } catch (\Exception $e) {
164
+            return new JSONResponse(['message' => $e->getMessage()], Http::STATUS_BAD_REQUEST);
165
+        }
166
+
167
+        return new JSONResponse(['remoteUrl' => $server]);
168
+    }
169
+
170
+    /**
171
+     * ask other server to get a federated share
172
+     *
173
+     * @NoAdminRequired
174
+     *
175
+     * @param string $token
176
+     * @param string $remote
177
+     * @param string $password
178
+     * @param string $owner (only for legacy reasons, can be removed with legacyMountPublicLink())
179
+     * @param string $ownerDisplayName (only for legacy reasons, can be removed with legacyMountPublicLink())
180
+     * @param string $name (only for legacy reasons, can be removed with legacyMountPublicLink())
181
+     * @return JSONResponse
182
+     */
183
+    public function askForFederatedShare($token, $remote, $password = '', $owner = '', $ownerDisplayName = '', $name = '') {
184
+        // check if server admin allows to mount public links from other servers
185
+        if ($this->federatedShareProvider->isIncomingServer2serverShareEnabled() === false) {
186
+            return new JSONResponse(['message' => $this->l->t('Server to server sharing is not enabled on this server')], Http::STATUS_BAD_REQUEST);
187
+        }
188
+
189
+        $cloudId = $this->cloudIdManager->getCloudId($this->userSession->getUser()->getUID(), $this->addressHandler->generateRemoteURL());
190
+
191
+        $httpClient = $this->clientService->newClient();
192
+
193
+        try {
194
+            $response = $httpClient->post($remote . '/index.php/apps/federatedfilesharing/createFederatedShare',
195
+                [
196
+                    'body' =>
197
+                        [
198
+                            'token' => $token,
199
+                            'shareWith' => rtrim($cloudId->getId(), '/'),
200
+                            'password' => $password
201
+                        ],
202
+                    'connect_timeout' => 10,
203
+                ]
204
+            );
205
+        } catch (\Exception $e) {
206
+            if (empty($password)) {
207
+                $message = $this->l->t("Couldn't establish a federated share.");
208
+            } else {
209
+                $message = $this->l->t("Couldn't establish a federated share, maybe the password was wrong.");
210
+            }
211
+            return new JSONResponse(['message' => $message], Http::STATUS_BAD_REQUEST);
212
+        }
213
+
214
+        $body = $response->getBody();
215
+        $result = json_decode($body, true);
216
+
217
+        if (is_array($result) && isset($result['remoteUrl'])) {
218
+            return new JSONResponse(['message' => $this->l->t('Federated Share request was successful, you will receive a invitation. Check your notifications.')]);
219
+        }
220
+
221
+        // if we doesn't get the expected response we assume that we try to add
222
+        // a federated share from a Nextcloud <= 9 server
223
+        return $this->legacyMountPublicLink($token, $remote, $password, $name, $owner, $ownerDisplayName);
224
+    }
225
+
226
+    /**
227
+     * Allow Nextcloud to mount a public link directly
228
+     *
229
+     * This code was copied from the apps/files_sharing/ajax/external.php with
230
+     * minimal changes, just to guarantee backward compatibility
231
+     *
232
+     * ToDo: Remove this method once Nextcloud 9 reaches end of life
233
+     *
234
+     * @param string $token
235
+     * @param string $remote
236
+     * @param string $password
237
+     * @param string $name
238
+     * @param string $owner
239
+     * @param string $ownerDisplayName
240
+     * @return JSONResponse
241
+     */
242
+    private function legacyMountPublicLink($token, $remote, $password, $name, $owner, $ownerDisplayName) {
243
+
244
+        // Check for invalid name
245
+        if (!Util::isValidFileName($name)) {
246
+            return new JSONResponse(['message' => $this->l->t('The mountpoint name contains invalid characters.')], Http::STATUS_BAD_REQUEST);
247
+        }
248
+        $currentUser = $this->userSession->getUser()->getUID();
249
+        $currentServer = $this->addressHandler->generateRemoteURL();
250
+        if (Helper::isSameUserOnSameServer($owner, $remote, $currentUser, $currentServer)) {
251
+            return new JSONResponse(['message' => $this->l->t('Not allowed to create a federated share with the owner.')], Http::STATUS_BAD_REQUEST);
252
+        }
253
+        $externalManager = new Manager(
254
+            \OC::$server->getDatabaseConnection(),
255
+            Filesystem::getMountManager(),
256
+            Filesystem::getLoader(),
257
+            \OC::$server->getHTTPClientService(),
258
+            \OC::$server->getNotificationManager(),
259
+            \OC::$server->query(\OCP\OCS\IDiscoveryService::class),
260
+            \OC::$server->getUserSession()->getUser()->getUID()
261
+        );
262
+
263
+        // check for ssl cert
264
+
265
+        if (strpos($remote, 'https') === 0) {
266
+            try {
267
+                $client = $this->clientService->newClient();
268
+                $client->get($remote, [
269
+                    'timeout' => 10,
270
+                    'connect_timeout' => 10,
271
+                ])->getBody();
272
+            } catch (\Exception $e) {
273
+                return new JSONResponse(['message' => $this->l->t('Invalid or untrusted SSL certificate')], Http::STATUS_BAD_REQUEST);
274
+            }
275
+        }
276
+        $mount = $externalManager->addShare($remote, $token, $password, $name, $ownerDisplayName, true);
277
+        /**
278
+         * @var \OCA\Files_Sharing\External\Storage $storage
279
+         */
280
+        $storage = $mount->getStorage();
281
+        try {
282
+            // check if storage exists
283
+            $storage->checkStorageAvailability();
284
+        } catch (StorageInvalidException $e) {
285
+            // note: checkStorageAvailability will already remove the invalid share
286
+            Util::writeLog(
287
+                'federatedfilesharing',
288
+                'Invalid remote storage: ' . get_class($e) . ': ' . $e->getMessage(),
289
+                Util::DEBUG
290
+            );
291
+            return new JSONResponse(['message' => $this->l->t('Could not authenticate to remote share, password might be wrong')], Http::STATUS_BAD_REQUEST);
292
+        } catch (\Exception $e) {
293
+            Util::writeLog(
294
+                'federatedfilesharing',
295
+                'Invalid remote storage: ' . get_class($e) . ': ' . $e->getMessage(),
296
+                Util::DEBUG
297
+            );
298
+            $externalManager->removeShare($mount->getMountPoint());
299
+            return new JSONResponse(['message' => $this->l->t('Storage not valid')], Http::STATUS_BAD_REQUEST);
300
+        }
301
+        $result = $storage->file_exists('');
302
+        if ($result) {
303
+            try {
304
+                $storage->getScanner()->scanAll();
305
+                return new JSONResponse(
306
+                    [
307
+                        'message' => $this->l->t('Federated Share successfully added'),
308
+                        'legacyMount' => '1'
309
+                    ]
310
+                );
311
+            } catch (StorageInvalidException $e) {
312
+                Util::writeLog(
313
+                    'federatedfilesharing',
314
+                    'Invalid remote storage: ' . get_class($e) . ': ' . $e->getMessage(),
315
+                    Util::DEBUG
316
+                );
317
+                return new JSONResponse(['message' => $this->l->t('Storage not valid')], Http::STATUS_BAD_REQUEST);
318
+            } catch (\Exception $e) {
319
+                Util::writeLog(
320
+                    'federatedfilesharing',
321
+                    'Invalid remote storage: ' . get_class($e) . ': ' . $e->getMessage(),
322
+                    Util::DEBUG
323
+                );
324
+                return new JSONResponse(['message' => $this->l->t('Couldn\'t add remote share')], Http::STATUS_BAD_REQUEST);
325
+            }
326
+        } else {
327
+            $externalManager->removeShare($mount->getMountPoint());
328
+            Util::writeLog(
329
+                'federatedfilesharing',
330
+                'Couldn\'t add remote share',
331
+                Util::DEBUG
332
+            );
333
+            return new JSONResponse(['message' => $this->l->t('Couldn\'t add remote share')], Http::STATUS_BAD_REQUEST);
334
+        }
335
+
336
+    }
337 337
 
338 338
 }
Please login to merge, or discard this patch.
Spacing   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -147,7 +147,7 @@  discard block
 block discarded – undo
147 147
 		$storedPassword = $share->getPassword();
148 148
 		$authenticated = $this->session->get('public_link_authenticated') === $share->getId() ||
149 149
 			$this->shareManager->checkPassword($share, $password);
150
-		if (!empty($storedPassword) && !$authenticated ) {
150
+		if (!empty($storedPassword) && !$authenticated) {
151 151
 			$response = new JSONResponse(
152 152
 				['message' => 'No permission to access the share'],
153 153
 				Http::STATUS_BAD_REQUEST
@@ -191,7 +191,7 @@  discard block
 block discarded – undo
191 191
 		$httpClient = $this->clientService->newClient();
192 192
 
193 193
 		try {
194
-			$response = $httpClient->post($remote . '/index.php/apps/federatedfilesharing/createFederatedShare',
194
+			$response = $httpClient->post($remote.'/index.php/apps/federatedfilesharing/createFederatedShare',
195 195
 				[
196 196
 					'body' =>
197 197
 						[
@@ -285,14 +285,14 @@  discard block
 block discarded – undo
285 285
 			// note: checkStorageAvailability will already remove the invalid share
286 286
 			Util::writeLog(
287 287
 				'federatedfilesharing',
288
-				'Invalid remote storage: ' . get_class($e) . ': ' . $e->getMessage(),
288
+				'Invalid remote storage: '.get_class($e).': '.$e->getMessage(),
289 289
 				Util::DEBUG
290 290
 			);
291 291
 			return new JSONResponse(['message' => $this->l->t('Could not authenticate to remote share, password might be wrong')], Http::STATUS_BAD_REQUEST);
292 292
 		} catch (\Exception $e) {
293 293
 			Util::writeLog(
294 294
 				'federatedfilesharing',
295
-				'Invalid remote storage: ' . get_class($e) . ': ' . $e->getMessage(),
295
+				'Invalid remote storage: '.get_class($e).': '.$e->getMessage(),
296 296
 				Util::DEBUG
297 297
 			);
298 298
 			$externalManager->removeShare($mount->getMountPoint());
@@ -311,14 +311,14 @@  discard block
 block discarded – undo
311 311
 			} catch (StorageInvalidException $e) {
312 312
 				Util::writeLog(
313 313
 					'federatedfilesharing',
314
-					'Invalid remote storage: ' . get_class($e) . ': ' . $e->getMessage(),
314
+					'Invalid remote storage: '.get_class($e).': '.$e->getMessage(),
315 315
 					Util::DEBUG
316 316
 				);
317 317
 				return new JSONResponse(['message' => $this->l->t('Storage not valid')], Http::STATUS_BAD_REQUEST);
318 318
 			} catch (\Exception $e) {
319 319
 				Util::writeLog(
320 320
 					'federatedfilesharing',
321
-					'Invalid remote storage: ' . get_class($e) . ': ' . $e->getMessage(),
321
+					'Invalid remote storage: '.get_class($e).': '.$e->getMessage(),
322 322
 					Util::DEBUG
323 323
 				);
324 324
 				return new JSONResponse(['message' => $this->l->t('Couldn\'t add remote share')], Http::STATUS_BAD_REQUEST);
Please login to merge, or discard this patch.
core/Controller/OCSController.php 1 patch
Indentation   +102 added lines, -102 removed lines patch added patch discarded remove patch
@@ -30,117 +30,117 @@
 block discarded – undo
30 30
 
31 31
 class OCSController extends \OCP\AppFramework\OCSController {
32 32
 
33
-	/** @var CapabilitiesManager */
34
-	private $capabilitiesManager;
35
-	/** @var IUserSession */
36
-	private $userSession;
37
-	/** @var IUserManager */
38
-	private $userManager;
39
-	/** @var Manager */
40
-	private $keyManager;
33
+    /** @var CapabilitiesManager */
34
+    private $capabilitiesManager;
35
+    /** @var IUserSession */
36
+    private $userSession;
37
+    /** @var IUserManager */
38
+    private $userManager;
39
+    /** @var Manager */
40
+    private $keyManager;
41 41
 
42
-	/**
43
-	 * OCSController constructor.
44
-	 *
45
-	 * @param string $appName
46
-	 * @param IRequest $request
47
-	 * @param CapabilitiesManager $capabilitiesManager
48
-	 * @param IUserSession $userSession
49
-	 * @param IUserManager $userManager
50
-	 * @param Manager $keyManager
51
-	 */
52
-	public function __construct($appName,
53
-								IRequest $request,
54
-								CapabilitiesManager $capabilitiesManager,
55
-								IUserSession $userSession,
56
-								IUserManager $userManager,
57
-								Manager $keyManager) {
58
-		parent::__construct($appName, $request);
59
-		$this->capabilitiesManager = $capabilitiesManager;
60
-		$this->userSession = $userSession;
61
-		$this->userManager = $userManager;
62
-		$this->keyManager = $keyManager;
63
-	}
42
+    /**
43
+     * OCSController constructor.
44
+     *
45
+     * @param string $appName
46
+     * @param IRequest $request
47
+     * @param CapabilitiesManager $capabilitiesManager
48
+     * @param IUserSession $userSession
49
+     * @param IUserManager $userManager
50
+     * @param Manager $keyManager
51
+     */
52
+    public function __construct($appName,
53
+                                IRequest $request,
54
+                                CapabilitiesManager $capabilitiesManager,
55
+                                IUserSession $userSession,
56
+                                IUserManager $userManager,
57
+                                Manager $keyManager) {
58
+        parent::__construct($appName, $request);
59
+        $this->capabilitiesManager = $capabilitiesManager;
60
+        $this->userSession = $userSession;
61
+        $this->userManager = $userManager;
62
+        $this->keyManager = $keyManager;
63
+    }
64 64
 
65
-	/**
66
-	 * @PublicPage
67
-	 *
68
-	 * @return DataResponse
69
-	 */
70
-	public function getConfig() {
71
-		$data = [
72
-			'version' => '1.7',
73
-			'website' => 'Nextcloud',
74
-			'host' => $this->request->getServerHost(),
75
-			'contact' => '',
76
-			'ssl' => 'false',
77
-		];
65
+    /**
66
+     * @PublicPage
67
+     *
68
+     * @return DataResponse
69
+     */
70
+    public function getConfig() {
71
+        $data = [
72
+            'version' => '1.7',
73
+            'website' => 'Nextcloud',
74
+            'host' => $this->request->getServerHost(),
75
+            'contact' => '',
76
+            'ssl' => 'false',
77
+        ];
78 78
 
79
-		return new DataResponse($data);
80
-	}
79
+        return new DataResponse($data);
80
+    }
81 81
 
82
-	/**
83
-	 * @NoAdminRequired
84
-	 * @return DataResponse
85
-	 */
86
-	public function getCapabilities() {
87
-		$result = [];
88
-		list($major, $minor, $micro) = \OCP\Util::getVersion();
89
-		$result['version'] = array(
90
-			'major' => $major,
91
-			'minor' => $minor,
92
-			'micro' => $micro,
93
-			'string' => \OC_Util::getVersionString(),
94
-			'edition' => '',
95
-		);
82
+    /**
83
+     * @NoAdminRequired
84
+     * @return DataResponse
85
+     */
86
+    public function getCapabilities() {
87
+        $result = [];
88
+        list($major, $minor, $micro) = \OCP\Util::getVersion();
89
+        $result['version'] = array(
90
+            'major' => $major,
91
+            'minor' => $minor,
92
+            'micro' => $micro,
93
+            'string' => \OC_Util::getVersionString(),
94
+            'edition' => '',
95
+        );
96 96
 
97
-		$result['capabilities'] = $this->capabilitiesManager->getCapabilities();
97
+        $result['capabilities'] = $this->capabilitiesManager->getCapabilities();
98 98
 
99
-		return new DataResponse($result);
100
-	}
99
+        return new DataResponse($result);
100
+    }
101 101
 
102
-	/**
103
-	 * @PublicPage
104
-	 * @BruteForceProtection(action=login)
105
-	 *
106
-	 * @param string $login
107
-	 * @param string $password
108
-	 * @return DataResponse
109
-	 */
110
-	public function personCheck($login = '', $password = '') {
111
-		if ($login !== '' && $password !== '') {
112
-			if ($this->userManager->checkPassword($login, $password)) {
113
-				return new DataResponse([
114
-					'person' => [
115
-						'personid' => $login
116
-					]
117
-				]);
118
-			}
102
+    /**
103
+     * @PublicPage
104
+     * @BruteForceProtection(action=login)
105
+     *
106
+     * @param string $login
107
+     * @param string $password
108
+     * @return DataResponse
109
+     */
110
+    public function personCheck($login = '', $password = '') {
111
+        if ($login !== '' && $password !== '') {
112
+            if ($this->userManager->checkPassword($login, $password)) {
113
+                return new DataResponse([
114
+                    'person' => [
115
+                        'personid' => $login
116
+                    ]
117
+                ]);
118
+            }
119 119
 
120
-			$response = new DataResponse(null, 102);
121
-			$response->throttle();
122
-			return $response;
123
-		}
124
-		return new DataResponse(null, 101);
125
-	}
120
+            $response = new DataResponse(null, 102);
121
+            $response->throttle();
122
+            return $response;
123
+        }
124
+        return new DataResponse(null, 101);
125
+    }
126 126
 
127
-	/**
128
-	 * @PublicPage
129
-	 *
130
-	 * @param string $cloudId
131
-	 * @return DataResponse
132
-	 */
133
-	public function getIdentityProof($cloudId) {
134
-		$userObject = $this->userManager->get($cloudId);
127
+    /**
128
+     * @PublicPage
129
+     *
130
+     * @param string $cloudId
131
+     * @return DataResponse
132
+     */
133
+    public function getIdentityProof($cloudId) {
134
+        $userObject = $this->userManager->get($cloudId);
135 135
 
136
-		if($userObject !== null) {
137
-			$key = $this->keyManager->getKey($userObject);
138
-			$data = [
139
-				'public' => $key->getPublic(),
140
-			];
141
-			return new DataResponse($data);
142
-		}
136
+        if($userObject !== null) {
137
+            $key = $this->keyManager->getKey($userObject);
138
+            $data = [
139
+                'public' => $key->getPublic(),
140
+            ];
141
+            return new DataResponse($data);
142
+        }
143 143
 
144
-		return new DataResponse('User not found', 404);
145
-	}
144
+        return new DataResponse('User not found', 404);
145
+    }
146 146
 }
Please login to merge, or discard this patch.