Completed
Push — master ( d842b2...8a1d3c )
by Lukas
17:12
created
apps/files_sharing/lib/Controller/ShareController.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -597,7 +597,7 @@
 block discarded – undo
597 597
 	 * publish activity
598 598
 	 *
599 599
 	 * @param string $subject
600
-	 * @param array $parameters
600
+	 * @param string[] $parameters
601 601
 	 * @param string $affectedUser
602 602
 	 * @param int $fileId
603 603
 	 * @param string $filePath
Please login to merge, or discard this patch.
Spacing   +12 added lines, -12 removed lines patch added patch discarded remove patch
@@ -150,7 +150,7 @@  discard block
 block discarded – undo
150 150
 	public function showAuthenticate($token) {
151 151
 		$share = $this->shareManager->getShareByToken($token);
152 152
 
153
-		if($this->linkShareAuth($share)) {
153
+		if ($this->linkShareAuth($share)) {
154 154
 			return new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.showShare', array('token' => $token)));
155 155
 		}
156 156
 
@@ -178,7 +178,7 @@  discard block
 block discarded – undo
178 178
 
179 179
 		$authenticate = $this->linkShareAuth($share, $password);
180 180
 
181
-		if($authenticate === true) {
181
+		if ($authenticate === true) {
182 182
 			return new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.showShare', array('token' => $token)));
183 183
 		}
184 184
 
@@ -199,15 +199,15 @@  discard block
 block discarded – undo
199 199
 	private function linkShareAuth(\OCP\Share\IShare $share, $password = null) {
200 200
 		if ($password !== null) {
201 201
 			if ($this->shareManager->checkPassword($share, $password)) {
202
-				$this->session->set('public_link_authenticated', (string)$share->getId());
202
+				$this->session->set('public_link_authenticated', (string) $share->getId());
203 203
 			} else {
204 204
 				$this->emitAccessShareHook($share, 403, 'Wrong password');
205 205
 				return false;
206 206
 			}
207 207
 		} else {
208 208
 			// not authenticated ?
209
-			if ( ! $this->session->exists('public_link_authenticated')
210
-				|| $this->session->get('public_link_authenticated') !== (string)$share->getId()) {
209
+			if (!$this->session->exists('public_link_authenticated')
210
+				|| $this->session->get('public_link_authenticated') !== (string) $share->getId()) {
211 211
 				return false;
212 212
 			}
213 213
 		}
@@ -228,7 +228,7 @@  discard block
 block discarded – undo
228 228
 		$itemType = $itemSource = $uidOwner = '';
229 229
 		$token = $share;
230 230
 		$exception = null;
231
-		if($share instanceof \OCP\Share\IShare) {
231
+		if ($share instanceof \OCP\Share\IShare) {
232 232
 			try {
233 233
 				$token = $share->getToken();
234 234
 				$uidOwner = $share->getSharedBy();
@@ -247,7 +247,7 @@  discard block
 block discarded – undo
247 247
 			'errorCode' => $errorCode,
248 248
 			'errorMessage' => $errorMessage,
249 249
 		]);
250
-		if(!is_null($exception)) {
250
+		if (!is_null($exception)) {
251 251
 			throw $exception;
252 252
 		}
253 253
 	}
@@ -340,7 +340,7 @@  discard block
 block discarded – undo
340 340
 			if ($freeSpace < \OCP\Files\FileInfo::SPACE_UNLIMITED) {
341 341
 				$freeSpace = max($freeSpace, 0);
342 342
 			} else {
343
-				$freeSpace = (INF > 0) ? INF: PHP_INT_MAX; // work around https://bugs.php.net/bug.php?id=69188
343
+				$freeSpace = (INF > 0) ? INF : PHP_INT_MAX; // work around https://bugs.php.net/bug.php?id=69188
344 344
 			}
345 345
 
346 346
 			$hideFileList = $share->getPermissions() & \OCP\Constants::PERMISSION_READ ? false : true;
@@ -371,7 +371,7 @@  discard block
 block discarded – undo
371 371
 		$shareTmpl['previewMaxY'] = $this->config->getSystemValue('preview_max_y', 1024);
372 372
 		$shareTmpl['disclaimer'] = $this->config->getAppValue('core', 'shareapi_public_link_disclaimertext', null);
373 373
 		if ($shareTmpl['previewSupported']) {
374
-			$shareTmpl['previewImage'] = $this->urlGenerator->linkToRouteAbsolute( 'files_sharing.PublicPreview.getPreview',
374
+			$shareTmpl['previewImage'] = $this->urlGenerator->linkToRouteAbsolute('files_sharing.PublicPreview.getPreview',
375 375
 				['x' => 200, 'y' => 200, 'file' => $shareTmpl['directory_path'], 't' => $shareTmpl['dirToken']]);
376 376
 		} else {
377 377
 			$shareTmpl['previewImage'] = $this->urlGenerator->getAbsoluteURL($this->urlGenerator->imagePath('core', 'favicon-fb.png'));
@@ -401,7 +401,7 @@  discard block
 block discarded – undo
401 401
 		}
402 402
 
403 403
 		// OpenGraph Support: http://ogp.me/
404
-		\OCP\Util::addHeader('meta', ['property' => "og:title", 'content' => $this->defaults->getName() . ' - ' . $this->defaults->getSlogan()]);
404
+		\OCP\Util::addHeader('meta', ['property' => "og:title", 'content' => $this->defaults->getName().' - '.$this->defaults->getSlogan()]);
405 405
 		\OCP\Util::addHeader('meta', ['property' => "og:description", 'content' => $this->l10n->t('%s is publicly shared', [$shareTmpl['filename']])]);
406 406
 		\OCP\Util::addHeader('meta', ['property' => "og:site_name", 'content' => $this->defaults->getName()]);
407 407
 		\OCP\Util::addHeader('meta', ['property' => "og:url", 'content' => $shareTmpl['shareUrl']]);
@@ -436,7 +436,7 @@  discard block
 block discarded – undo
436 436
 
437 437
 		$share = $this->shareManager->getShareByToken($token);
438 438
 
439
-		if(!($share->getPermissions() & \OCP\Constants::PERMISSION_READ)) {
439
+		if (!($share->getPermissions() & \OCP\Constants::PERMISSION_READ)) {
440 440
 			return new \OCP\AppFramework\Http\DataResponse('Share is read-only');
441 441
 		}
442 442
 
@@ -514,7 +514,7 @@  discard block
 block discarded – undo
514 514
 
515 515
 		$this->emitAccessShareHook($share);
516 516
 
517
-		$server_params = array( 'head' => $this->request->getMethod() == 'HEAD' );
517
+		$server_params = array('head' => $this->request->getMethod() == 'HEAD');
518 518
 
519 519
 		/**
520 520
 		 * Http range requests support
Please login to merge, or discard this 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/files_sharing/lib/Controller/ShareesAPIController.php 3 patches
Doc Comments   +4 added lines, -1 removed lines patch added patch discarded remove patch
@@ -358,7 +358,7 @@  discard block
 block discarded – undo
358 358
 	 * split user and remote from federated cloud id
359 359
 	 *
360 360
 	 * @param string $address federated share address
361
-	 * @return array [user, remoteURL]
361
+	 * @return string[] [user, remoteURL]
362 362
 	 * @throws \Exception
363 363
 	 */
364 364
 	public function splitUserRemote($address) {
@@ -633,6 +633,9 @@  discard block
 block discarded – undo
633 633
 		return $result;
634 634
 	}
635 635
 
636
+	/**
637
+	 * @param string $search
638
+	 */
636 639
 	protected function getLookup($search) {
637 640
 		$isEnabled = $this->config->getAppValue('files_sharing', 'lookupServerEnabled', 'no');
638 641
 		$result = [];
Please login to merge, or discard this patch.
Spacing   +14 added lines, -14 removed lines patch added patch discarded remove patch
@@ -234,17 +234,17 @@  discard block
 block discarded – undo
234 234
 		$this->result['groups'] = $this->result['exact']['groups'] = [];
235 235
 
236 236
 		$groups = $this->groupManager->search($search, $this->limit, $this->offset);
237
-		$groupIds = array_map(function (IGroup $group) { return $group->getGID(); }, $groups);
237
+		$groupIds = array_map(function(IGroup $group) { return $group->getGID(); }, $groups);
238 238
 
239 239
 		if (!$this->shareeEnumeration || sizeof($groups) < $this->limit) {
240 240
 			$this->reachedEndFor[] = 'groups';
241 241
 		}
242 242
 
243
-		$userGroups =  [];
243
+		$userGroups = [];
244 244
 		if (!empty($groups) && $this->shareWithGroupOnly) {
245 245
 			// Intersect all the groups that match with the groups this user is a member of
246 246
 			$userGroups = $this->groupManager->getUserGroups($this->userSession->getUser());
247
-			$userGroups = array_map(function (IGroup $group) { return $group->getGID(); }, $userGroups);
247
+			$userGroups = array_map(function(IGroup $group) { return $group->getGID(); }, $userGroups);
248 248
 			$groupIds = array_intersect($groupIds, $userGroups);
249 249
 		}
250 250
 
@@ -322,7 +322,7 @@  discard block
 block discarded – undo
322 322
 							$result['exactIdMatch'] = true;
323 323
 						}
324 324
 						$result['exact'][] = [
325
-							'label' => $contact['FN'] . " ($cloudId)",
325
+							'label' => $contact['FN']." ($cloudId)",
326 326
 							'value' => [
327 327
 								'shareType' => Share::SHARE_TYPE_REMOTE,
328 328
 								'shareWith' => $cloudId,
@@ -331,7 +331,7 @@  discard block
 block discarded – undo
331 331
 						];
332 332
 					} else {
333 333
 						$result['results'][] = [
334
-							'label' => $contact['FN'] . " ($cloudId)",
334
+							'label' => $contact['FN']." ($cloudId)",
335 335
 							'value' => [
336 336
 								'shareType' => Share::SHARE_TYPE_REMOTE,
337 337
 								'shareWith' => $cloudId,
@@ -415,13 +415,13 @@  discard block
 block discarded – undo
415 415
 	public function search($search = '', $itemType = null, $page = 1, $perPage = 200, $shareType = null, $lookup = true) {
416 416
 
417 417
 		// only search for string larger than a given threshold
418
-		$threshold = (int)$this->config->getSystemValue('sharing.minSearchStringLength', 0);
418
+		$threshold = (int) $this->config->getSystemValue('sharing.minSearchStringLength', 0);
419 419
 		if (strlen($search) < $threshold) {
420 420
 			return new DataResponse($this->result);
421 421
 		}
422 422
 
423 423
 		// never return more than the max. number of results configured in the config.php
424
-		$maxResults = (int)$this->config->getSystemValue('sharing.maxAutocompleteResults', 0);
424
+		$maxResults = (int) $this->config->getSystemValue('sharing.maxAutocompleteResults', 0);
425 425
 		if ($maxResults > 0) {
426 426
 			$perPage = min($perPage, $maxResults);
427 427
 		}
@@ -585,7 +585,7 @@  discard block
 block discarded – undo
585 585
 							$result['exactIdMatch'] = true;
586 586
 						}
587 587
 						$result['exact'][] = [
588
-							'label' => $contact['FN'] . " ($emailAddress)",
588
+							'label' => $contact['FN']." ($emailAddress)",
589 589
 							'value' => [
590 590
 								'shareType' => Share::SHARE_TYPE_EMAIL,
591 591
 								'shareWith' => $emailAddress,
@@ -593,7 +593,7 @@  discard block
 block discarded – undo
593 593
 						];
594 594
 					} else {
595 595
 						$result['results'][] = [
596
-							'label' => $contact['FN'] . " ($emailAddress)",
596
+							'label' => $contact['FN']." ($emailAddress)",
597 597
 							'value' => [
598 598
 								'shareType' => Share::SHARE_TYPE_EMAIL,
599 599
 								'shareWith' => $emailAddress,
@@ -627,11 +627,11 @@  discard block
 block discarded – undo
627 627
 		$isEnabled = $this->config->getAppValue('files_sharing', 'lookupServerEnabled', 'no');
628 628
 		$result = [];
629 629
 
630
-		if($isEnabled === 'yes') {
630
+		if ($isEnabled === 'yes') {
631 631
 			try {
632 632
 				$client = $this->clientService->newClient();
633 633
 				$response = $client->get(
634
-					'https://lookup.nextcloud.com/users?search=' . urlencode($search),
634
+					'https://lookup.nextcloud.com/users?search='.urlencode($search),
635 635
 					[
636 636
 						'timeout' => 10,
637 637
 						'connect_timeout' => 3,
@@ -666,12 +666,12 @@  discard block
 block discarded – undo
666 666
 	 */
667 667
 	protected function getPaginationLink($page, array $params) {
668 668
 		if ($this->isV2()) {
669
-			$url = $this->urlGenerator->getAbsoluteURL('/ocs/v2.php/apps/files_sharing/api/v1/sharees') . '?';
669
+			$url = $this->urlGenerator->getAbsoluteURL('/ocs/v2.php/apps/files_sharing/api/v1/sharees').'?';
670 670
 		} else {
671
-			$url = $this->urlGenerator->getAbsoluteURL('/ocs/v1.php/apps/files_sharing/api/v1/sharees') . '?';
671
+			$url = $this->urlGenerator->getAbsoluteURL('/ocs/v1.php/apps/files_sharing/api/v1/sharees').'?';
672 672
 		}
673 673
 		$params['page'] = $page + 1;
674
-		$link = '<' . $url . http_build_query($params) . '>; rel="next"';
674
+		$link = '<'.$url.http_build_query($params).'>; rel="next"';
675 675
 
676 676
 		return $link;
677 677
 	}
Please login to merge, or discard this patch.
Indentation   +668 added lines, -668 removed lines patch added patch discarded remove patch
@@ -43,672 +43,672 @@
 block discarded – undo
43 43
 
44 44
 class ShareesAPIController extends OCSController {
45 45
 
46
-	/** @var IGroupManager */
47
-	protected $groupManager;
48
-
49
-	/** @var IUserManager */
50
-	protected $userManager;
51
-
52
-	/** @var IManager */
53
-	protected $contactsManager;
54
-
55
-	/** @var IConfig */
56
-	protected $config;
57
-
58
-	/** @var IUserSession */
59
-	protected $userSession;
60
-
61
-	/** @var IURLGenerator */
62
-	protected $urlGenerator;
63
-
64
-	/** @var ILogger */
65
-	protected $logger;
66
-
67
-	/** @var \OCP\Share\IManager */
68
-	protected $shareManager;
69
-
70
-	/** @var IClientService */
71
-	protected $clientService;
72
-
73
-	/** @var ICloudIdManager  */
74
-	protected $cloudIdManager;
75
-
76
-	/** @var bool */
77
-	protected $shareWithGroupOnly = false;
78
-
79
-	/** @var bool */
80
-	protected $shareeEnumeration = true;
81
-
82
-	/** @var int */
83
-	protected $offset = 0;
84
-
85
-	/** @var int */
86
-	protected $limit = 10;
87
-
88
-	/** @var array */
89
-	protected $result = [
90
-		'exact' => [
91
-			'users' => [],
92
-			'groups' => [],
93
-			'remotes' => [],
94
-			'emails' => [],
95
-			'circles' => [],
96
-		],
97
-		'users' => [],
98
-		'groups' => [],
99
-		'remotes' => [],
100
-		'emails' => [],
101
-		'lookup' => [],
102
-		'circles' => [],
103
-	];
104
-
105
-	protected $reachedEndFor = [];
106
-
107
-	/**
108
-	 * @param string $appName
109
-	 * @param IRequest $request
110
-	 * @param IGroupManager $groupManager
111
-	 * @param IUserManager $userManager
112
-	 * @param IManager $contactsManager
113
-	 * @param IConfig $config
114
-	 * @param IUserSession $userSession
115
-	 * @param IURLGenerator $urlGenerator
116
-	 * @param ILogger $logger
117
-	 * @param \OCP\Share\IManager $shareManager
118
-	 * @param IClientService $clientService
119
-	 * @param ICloudIdManager $cloudIdManager
120
-	 */
121
-	public function __construct($appName,
122
-								IRequest $request,
123
-								IGroupManager $groupManager,
124
-								IUserManager $userManager,
125
-								IManager $contactsManager,
126
-								IConfig $config,
127
-								IUserSession $userSession,
128
-								IURLGenerator $urlGenerator,
129
-								ILogger $logger,
130
-								\OCP\Share\IManager $shareManager,
131
-								IClientService $clientService,
132
-								ICloudIdManager $cloudIdManager
133
-	) {
134
-		parent::__construct($appName, $request);
135
-
136
-		$this->groupManager = $groupManager;
137
-		$this->userManager = $userManager;
138
-		$this->contactsManager = $contactsManager;
139
-		$this->config = $config;
140
-		$this->userSession = $userSession;
141
-		$this->urlGenerator = $urlGenerator;
142
-		$this->logger = $logger;
143
-		$this->shareManager = $shareManager;
144
-		$this->clientService = $clientService;
145
-		$this->cloudIdManager = $cloudIdManager;
146
-	}
147
-
148
-	/**
149
-	 * @param string $search
150
-	 */
151
-	protected function getUsers($search) {
152
-		$this->result['users'] = $this->result['exact']['users'] = $users = [];
153
-
154
-		$userGroups = [];
155
-		if ($this->shareWithGroupOnly) {
156
-			// Search in all the groups this user is part of
157
-			$userGroups = $this->groupManager->getUserGroupIds($this->userSession->getUser());
158
-			foreach ($userGroups as $userGroup) {
159
-				$usersTmp = $this->groupManager->displayNamesInGroup($userGroup, $search, $this->limit, $this->offset);
160
-				foreach ($usersTmp as $uid => $userDisplayName) {
161
-					$users[$uid] = $userDisplayName;
162
-				}
163
-			}
164
-		} else {
165
-			// Search in all users
166
-			$usersTmp = $this->userManager->searchDisplayName($search, $this->limit, $this->offset);
167
-
168
-			foreach ($usersTmp as $user) {
169
-				$users[$user->getUID()] = $user->getDisplayName();
170
-			}
171
-		}
172
-
173
-		if (!$this->shareeEnumeration || sizeof($users) < $this->limit) {
174
-			$this->reachedEndFor[] = 'users';
175
-		}
176
-
177
-		$foundUserById = false;
178
-		$lowerSearch = strtolower($search);
179
-		foreach ($users as $uid => $userDisplayName) {
180
-			if (strtolower($uid) === $lowerSearch || strtolower($userDisplayName) === $lowerSearch) {
181
-				if (strtolower($uid) === $lowerSearch) {
182
-					$foundUserById = true;
183
-				}
184
-				$this->result['exact']['users'][] = [
185
-					'label' => $userDisplayName,
186
-					'value' => [
187
-						'shareType' => Share::SHARE_TYPE_USER,
188
-						'shareWith' => $uid,
189
-					],
190
-				];
191
-			} else {
192
-				$this->result['users'][] = [
193
-					'label' => $userDisplayName,
194
-					'value' => [
195
-						'shareType' => Share::SHARE_TYPE_USER,
196
-						'shareWith' => $uid,
197
-					],
198
-				];
199
-			}
200
-		}
201
-
202
-		if ($this->offset === 0 && !$foundUserById) {
203
-			// On page one we try if the search result has a direct hit on the
204
-			// user id and if so, we add that to the exact match list
205
-			$user = $this->userManager->get($search);
206
-			if ($user instanceof IUser) {
207
-				$addUser = true;
208
-
209
-				if ($this->shareWithGroupOnly) {
210
-					// Only add, if we have a common group
211
-					$commonGroups = array_intersect($userGroups, $this->groupManager->getUserGroupIds($user));
212
-					$addUser = !empty($commonGroups);
213
-				}
214
-
215
-				if ($addUser) {
216
-					array_push($this->result['exact']['users'], [
217
-						'label' => $user->getDisplayName(),
218
-						'value' => [
219
-							'shareType' => Share::SHARE_TYPE_USER,
220
-							'shareWith' => $user->getUID(),
221
-						],
222
-					]);
223
-				}
224
-			}
225
-		}
226
-
227
-		if (!$this->shareeEnumeration) {
228
-			$this->result['users'] = [];
229
-		}
230
-	}
231
-
232
-	/**
233
-	 * @param string $search
234
-	 */
235
-	protected function getGroups($search) {
236
-		$this->result['groups'] = $this->result['exact']['groups'] = [];
237
-
238
-		$groups = $this->groupManager->search($search, $this->limit, $this->offset);
239
-		$groupIds = array_map(function (IGroup $group) { return $group->getGID(); }, $groups);
240
-
241
-		if (!$this->shareeEnumeration || sizeof($groups) < $this->limit) {
242
-			$this->reachedEndFor[] = 'groups';
243
-		}
244
-
245
-		$userGroups =  [];
246
-		if (!empty($groups) && $this->shareWithGroupOnly) {
247
-			// Intersect all the groups that match with the groups this user is a member of
248
-			$userGroups = $this->groupManager->getUserGroups($this->userSession->getUser());
249
-			$userGroups = array_map(function (IGroup $group) { return $group->getGID(); }, $userGroups);
250
-			$groupIds = array_intersect($groupIds, $userGroups);
251
-		}
252
-
253
-		$lowerSearch = strtolower($search);
254
-		foreach ($groups as $group) {
255
-			// FIXME: use a more efficient approach
256
-			$gid = $group->getGID();
257
-			if (!in_array($gid, $groupIds)) {
258
-				continue;
259
-			}
260
-			if (strtolower($gid) === $lowerSearch || strtolower($group->getDisplayName()) === $lowerSearch) {
261
-				$this->result['exact']['groups'][] = [
262
-					'label' => $group->getDisplayName(),
263
-					'value' => [
264
-						'shareType' => Share::SHARE_TYPE_GROUP,
265
-						'shareWith' => $gid,
266
-					],
267
-				];
268
-			} else {
269
-				$this->result['groups'][] = [
270
-					'label' => $group->getDisplayName(),
271
-					'value' => [
272
-						'shareType' => Share::SHARE_TYPE_GROUP,
273
-						'shareWith' => $gid,
274
-					],
275
-				];
276
-			}
277
-		}
278
-
279
-		if ($this->offset === 0 && empty($this->result['exact']['groups'])) {
280
-			// On page one we try if the search result has a direct hit on the
281
-			// user id and if so, we add that to the exact match list
282
-			$group = $this->groupManager->get($search);
283
-			if ($group instanceof IGroup && (!$this->shareWithGroupOnly || in_array($group->getGID(), $userGroups))) {
284
-				array_push($this->result['exact']['groups'], [
285
-					'label' => $group->getDisplayName(),
286
-					'value' => [
287
-						'shareType' => Share::SHARE_TYPE_GROUP,
288
-						'shareWith' => $group->getGID(),
289
-					],
290
-				]);
291
-			}
292
-		}
293
-
294
-		if (!$this->shareeEnumeration) {
295
-			$this->result['groups'] = [];
296
-		}
297
-	}
298
-
299
-
300
-	/**
301
-	 * @param string $search
302
-	 */
303
-	protected function getCircles($search) {
304
-		$this->result['circles'] = $this->result['exact']['circles'] = [];
305
-
306
-		$result = \OCA\Circles\Api\Sharees::search($search, $this->limit, $this->offset);
307
-		if (array_key_exists('circles', $result['exact'])) {
308
-			$this->result['exact']['circles'] = $result['exact']['circles'];
309
-		}
310
-		if (array_key_exists('circles', $result)) {
311
-			$this->result['circles'] = $result['circles'];
312
-		}
313
-	}
314
-
315
-
316
-	/**
317
-	 * @param string $search
318
-	 * @return array
319
-	 */
320
-	protected function getRemote($search) {
321
-		$result = ['results' => [], 'exact' => []];
322
-
323
-		// Search in contacts
324
-		//@todo Pagination missing
325
-		$addressBookContacts = $this->contactsManager->search($search, ['CLOUD', 'FN']);
326
-		$result['exactIdMatch'] = false;
327
-		foreach ($addressBookContacts as $contact) {
328
-			if (isset($contact['isLocalSystemBook'])) {
329
-				continue;
330
-			}
331
-			if (isset($contact['CLOUD'])) {
332
-				$cloudIds = $contact['CLOUD'];
333
-				if (!is_array($cloudIds)) {
334
-					$cloudIds = [$cloudIds];
335
-				}
336
-				$lowerSearch = strtolower($search);
337
-				foreach ($cloudIds as $cloudId) {
338
-					list(, $serverUrl) = $this->splitUserRemote($cloudId);
339
-					if (strtolower($contact['FN']) === $lowerSearch || strtolower($cloudId) === $lowerSearch) {
340
-						if (strtolower($cloudId) === $lowerSearch) {
341
-							$result['exactIdMatch'] = true;
342
-						}
343
-						$result['exact'][] = [
344
-							'label' => $contact['FN'] . " ($cloudId)",
345
-							'value' => [
346
-								'shareType' => Share::SHARE_TYPE_REMOTE,
347
-								'shareWith' => $cloudId,
348
-								'server' => $serverUrl,
349
-							],
350
-						];
351
-					} else {
352
-						$result['results'][] = [
353
-							'label' => $contact['FN'] . " ($cloudId)",
354
-							'value' => [
355
-								'shareType' => Share::SHARE_TYPE_REMOTE,
356
-								'shareWith' => $cloudId,
357
-								'server' => $serverUrl,
358
-							],
359
-						];
360
-					}
361
-				}
362
-			}
363
-		}
364
-
365
-		if (!$this->shareeEnumeration) {
366
-			$result['results'] = [];
367
-		}
368
-
369
-		if (!$result['exactIdMatch'] && $this->cloudIdManager->isValidCloudId($search) && $this->offset === 0) {
370
-			$result['exact'][] = [
371
-				'label' => $search,
372
-				'value' => [
373
-					'shareType' => Share::SHARE_TYPE_REMOTE,
374
-					'shareWith' => $search,
375
-				],
376
-			];
377
-		}
378
-
379
-		$this->reachedEndFor[] = 'remotes';
380
-
381
-		return $result;
382
-	}
383
-
384
-	/**
385
-	 * split user and remote from federated cloud id
386
-	 *
387
-	 * @param string $address federated share address
388
-	 * @return array [user, remoteURL]
389
-	 * @throws \Exception
390
-	 */
391
-	public function splitUserRemote($address) {
392
-		try {
393
-			$cloudId = $this->cloudIdManager->resolveCloudId($address);
394
-			return [$cloudId->getUser(), $cloudId->getRemote()];
395
-		} catch (\InvalidArgumentException $e) {
396
-			throw new \Exception('Invalid Federated Cloud ID', 0, $e);
397
-		}
398
-	}
399
-
400
-	/**
401
-	 * Strips away a potential file names and trailing slashes:
402
-	 * - http://localhost
403
-	 * - http://localhost/
404
-	 * - http://localhost/index.php
405
-	 * - http://localhost/index.php/s/{shareToken}
406
-	 *
407
-	 * all return: http://localhost
408
-	 *
409
-	 * @param string $remote
410
-	 * @return string
411
-	 */
412
-	protected function fixRemoteURL($remote) {
413
-		$remote = str_replace('\\', '/', $remote);
414
-		if ($fileNamePosition = strpos($remote, '/index.php')) {
415
-			$remote = substr($remote, 0, $fileNamePosition);
416
-		}
417
-		$remote = rtrim($remote, '/');
418
-
419
-		return $remote;
420
-	}
421
-
422
-	/**
423
-	 * @NoAdminRequired
424
-	 *
425
-	 * @param string $search
426
-	 * @param string $itemType
427
-	 * @param int $page
428
-	 * @param int $perPage
429
-	 * @param int|int[] $shareType
430
-	 * @param bool $lookup
431
-	 * @return DataResponse
432
-	 * @throws OCSBadRequestException
433
-	 */
434
-	public function search($search = '', $itemType = null, $page = 1, $perPage = 200, $shareType = null, $lookup = true) {
435
-
436
-		// only search for string larger than a given threshold
437
-		$threshold = (int)$this->config->getSystemValue('sharing.minSearchStringLength', 0);
438
-		if (strlen($search) < $threshold) {
439
-			return new DataResponse($this->result);
440
-		}
441
-
442
-		// never return more than the max. number of results configured in the config.php
443
-		$maxResults = (int)$this->config->getSystemValue('sharing.maxAutocompleteResults', 0);
444
-		if ($maxResults > 0) {
445
-			$perPage = min($perPage, $maxResults);
446
-		}
447
-		if ($perPage <= 0) {
448
-			throw new OCSBadRequestException('Invalid perPage argument');
449
-		}
450
-		if ($page <= 0) {
451
-			throw new OCSBadRequestException('Invalid page');
452
-		}
453
-
454
-		$shareTypes = [
455
-			Share::SHARE_TYPE_USER,
456
-		];
457
-
458
-		if ($itemType === 'file' || $itemType === 'folder') {
459
-			if ($this->shareManager->allowGroupSharing()) {
460
-				$shareTypes[] = Share::SHARE_TYPE_GROUP;
461
-			}
462
-
463
-			if ($this->isRemoteSharingAllowed($itemType)) {
464
-				$shareTypes[] = Share::SHARE_TYPE_REMOTE;
465
-			}
466
-
467
-			if ($this->shareManager->shareProviderExists(Share::SHARE_TYPE_EMAIL)) {
468
-				$shareTypes[] = Share::SHARE_TYPE_EMAIL;
469
-			}
470
-		} else {
471
-			$shareTypes[] = Share::SHARE_TYPE_GROUP;
472
-			$shareTypes[] = Share::SHARE_TYPE_EMAIL;
473
-		}
474
-
475
-		if (\OCP\App::isEnabled('circles')) {
476
-			$shareTypes[] = Share::SHARE_TYPE_CIRCLE;
477
-		}
478
-
479
-		if (isset($_GET['shareType']) && is_array($_GET['shareType'])) {
480
-			$shareTypes = array_intersect($shareTypes, $_GET['shareType']);
481
-			sort($shareTypes);
482
-		} else if (is_numeric($shareType)) {
483
-			$shareTypes = array_intersect($shareTypes, [(int) $shareType]);
484
-			sort($shareTypes);
485
-		}
486
-
487
-		$this->shareWithGroupOnly = $this->config->getAppValue('core', 'shareapi_only_share_with_group_members', 'no') === 'yes';
488
-		$this->shareeEnumeration = $this->config->getAppValue('core', 'shareapi_allow_share_dialog_user_enumeration', 'yes') === 'yes';
489
-		$this->limit = (int) $perPage;
490
-		$this->offset = $perPage * ($page - 1);
491
-
492
-		return $this->searchSharees($search, $itemType, $shareTypes, $page, $perPage, $lookup);
493
-	}
494
-
495
-	/**
496
-	 * Method to get out the static call for better testing
497
-	 *
498
-	 * @param string $itemType
499
-	 * @return bool
500
-	 */
501
-	protected function isRemoteSharingAllowed($itemType) {
502
-		try {
503
-			$backend = Share::getBackend($itemType);
504
-			return $backend->isShareTypeAllowed(Share::SHARE_TYPE_REMOTE);
505
-		} catch (\Exception $e) {
506
-			return false;
507
-		}
508
-	}
509
-
510
-	/**
511
-	 * Testable search function that does not need globals
512
-	 *
513
-	 * @param string $search
514
-	 * @param string $itemType
515
-	 * @param array $shareTypes
516
-	 * @param int $page
517
-	 * @param int $perPage
518
-	 * @param bool $lookup
519
-	 * @return DataResponse
520
-	 * @throws OCSBadRequestException
521
-	 */
522
-	protected function searchSharees($search, $itemType, array $shareTypes, $page, $perPage, $lookup) {
523
-		// Verify arguments
524
-		if ($itemType === null) {
525
-			throw new OCSBadRequestException('Missing itemType');
526
-		}
527
-
528
-		// Get users
529
-		if (in_array(Share::SHARE_TYPE_USER, $shareTypes)) {
530
-			$this->getUsers($search);
531
-		}
532
-
533
-		// Get groups
534
-		if (in_array(Share::SHARE_TYPE_GROUP, $shareTypes)) {
535
-			$this->getGroups($search);
536
-		}
537
-
538
-		// Get circles
539
-		if (in_array(Share::SHARE_TYPE_CIRCLE, $shareTypes)) {
540
-			$this->getCircles($search);
541
-		}
542
-
543
-
544
-		// Get remote
545
-		$remoteResults = ['results' => [], 'exact' => [], 'exactIdMatch' => false];
546
-		if (in_array(Share::SHARE_TYPE_REMOTE, $shareTypes)) {
547
-			$remoteResults = $this->getRemote($search);
548
-		}
549
-
550
-		// Get emails
551
-		$mailResults = ['results' => [], 'exact' => [], 'exactIdMatch' => false];
552
-		if (in_array(Share::SHARE_TYPE_EMAIL, $shareTypes)) {
553
-			$mailResults = $this->getEmail($search);
554
-		}
555
-
556
-		// Get from lookup server
557
-		if ($lookup) {
558
-			$this->getLookup($search);
559
-		}
560
-
561
-		// if we have a exact match, either for the federated cloud id or for the
562
-		// email address we only return the exact match. It is highly unlikely
563
-		// that the exact same email address and federated cloud id exists
564
-		if ($mailResults['exactIdMatch'] && !$remoteResults['exactIdMatch']) {
565
-			$this->result['emails'] = $mailResults['results'];
566
-			$this->result['exact']['emails'] = $mailResults['exact'];
567
-		} else if (!$mailResults['exactIdMatch'] && $remoteResults['exactIdMatch']) {
568
-			$this->result['remotes'] = $remoteResults['results'];
569
-			$this->result['exact']['remotes'] = $remoteResults['exact'];
570
-		} else {
571
-			$this->result['remotes'] = $remoteResults['results'];
572
-			$this->result['exact']['remotes'] = $remoteResults['exact'];
573
-			$this->result['emails'] = $mailResults['results'];
574
-			$this->result['exact']['emails'] = $mailResults['exact'];
575
-		}
576
-
577
-		$response = new DataResponse($this->result);
578
-
579
-		if (sizeof($this->reachedEndFor) < 3) {
580
-			$response->addHeader('Link', $this->getPaginationLink($page, [
581
-				'search' => $search,
582
-				'itemType' => $itemType,
583
-				'shareType' => $shareTypes,
584
-				'perPage' => $perPage,
585
-			]));
586
-		}
587
-
588
-		return $response;
589
-	}
590
-
591
-	/**
592
-	 * @param string $search
593
-	 * @return array
594
-	 */
595
-	protected function getEmail($search) {
596
-		$result = ['results' => [], 'exact' => []];
597
-
598
-		// Search in contacts
599
-		//@todo Pagination missing
600
-		$addressBookContacts = $this->contactsManager->search($search, ['EMAIL', 'FN']);
601
-		$result['exactIdMatch'] = false;
602
-		foreach ($addressBookContacts as $contact) {
603
-			if (isset($contact['isLocalSystemBook'])) {
604
-				continue;
605
-			}
606
-			if (isset($contact['EMAIL'])) {
607
-				$emailAddresses = $contact['EMAIL'];
608
-				if (!is_array($emailAddresses)) {
609
-					$emailAddresses = [$emailAddresses];
610
-				}
611
-				foreach ($emailAddresses as $emailAddress) {
612
-					if (strtolower($contact['FN']) === strtolower($search) || strtolower($emailAddress) === strtolower($search)) {
613
-						if (strtolower($emailAddress) === strtolower($search)) {
614
-							$result['exactIdMatch'] = true;
615
-						}
616
-						$result['exact'][] = [
617
-							'label' => $contact['FN'] . " ($emailAddress)",
618
-							'value' => [
619
-								'shareType' => Share::SHARE_TYPE_EMAIL,
620
-								'shareWith' => $emailAddress,
621
-							],
622
-						];
623
-					} else {
624
-						$result['results'][] = [
625
-							'label' => $contact['FN'] . " ($emailAddress)",
626
-							'value' => [
627
-								'shareType' => Share::SHARE_TYPE_EMAIL,
628
-								'shareWith' => $emailAddress,
629
-							],
630
-						];
631
-					}
632
-				}
633
-			}
634
-		}
635
-
636
-		if (!$this->shareeEnumeration) {
637
-			$result['results'] = [];
638
-		}
639
-
640
-		if (!$result['exactIdMatch'] && filter_var($search, FILTER_VALIDATE_EMAIL)) {
641
-			$result['exact'][] = [
642
-				'label' => $search,
643
-				'value' => [
644
-					'shareType' => Share::SHARE_TYPE_EMAIL,
645
-					'shareWith' => $search,
646
-				],
647
-			];
648
-		}
649
-
650
-		$this->reachedEndFor[] = 'emails';
651
-
652
-		return $result;
653
-	}
654
-
655
-	protected function getLookup($search) {
656
-		$isEnabled = $this->config->getAppValue('files_sharing', 'lookupServerEnabled', 'no');
657
-		$result = [];
658
-
659
-		if($isEnabled === 'yes') {
660
-			try {
661
-				$client = $this->clientService->newClient();
662
-				$response = $client->get(
663
-					'https://lookup.nextcloud.com/users?search=' . urlencode($search),
664
-					[
665
-						'timeout' => 10,
666
-						'connect_timeout' => 3,
667
-					]
668
-				);
669
-
670
-				$body = json_decode($response->getBody(), true);
671
-
672
-				$result = [];
673
-				foreach ($body as $lookup) {
674
-					$result[] = [
675
-						'label' => $lookup['federationId'],
676
-						'value' => [
677
-							'shareType' => Share::SHARE_TYPE_REMOTE,
678
-							'shareWith' => $lookup['federationId'],
679
-						],
680
-						'extra' => $lookup,
681
-					];
682
-				}
683
-			} catch (\Exception $e) {}
684
-		}
685
-
686
-		$this->result['lookup'] = $result;
687
-	}
688
-
689
-	/**
690
-	 * Generates a bunch of pagination links for the current page
691
-	 *
692
-	 * @param int $page Current page
693
-	 * @param array $params Parameters for the URL
694
-	 * @return string
695
-	 */
696
-	protected function getPaginationLink($page, array $params) {
697
-		if ($this->isV2()) {
698
-			$url = $this->urlGenerator->getAbsoluteURL('/ocs/v2.php/apps/files_sharing/api/v1/sharees') . '?';
699
-		} else {
700
-			$url = $this->urlGenerator->getAbsoluteURL('/ocs/v1.php/apps/files_sharing/api/v1/sharees') . '?';
701
-		}
702
-		$params['page'] = $page + 1;
703
-		$link = '<' . $url . http_build_query($params) . '>; rel="next"';
704
-
705
-		return $link;
706
-	}
707
-
708
-	/**
709
-	 * @return bool
710
-	 */
711
-	protected function isV2() {
712
-		return $this->request->getScriptName() === '/ocs/v2.php';
713
-	}
46
+    /** @var IGroupManager */
47
+    protected $groupManager;
48
+
49
+    /** @var IUserManager */
50
+    protected $userManager;
51
+
52
+    /** @var IManager */
53
+    protected $contactsManager;
54
+
55
+    /** @var IConfig */
56
+    protected $config;
57
+
58
+    /** @var IUserSession */
59
+    protected $userSession;
60
+
61
+    /** @var IURLGenerator */
62
+    protected $urlGenerator;
63
+
64
+    /** @var ILogger */
65
+    protected $logger;
66
+
67
+    /** @var \OCP\Share\IManager */
68
+    protected $shareManager;
69
+
70
+    /** @var IClientService */
71
+    protected $clientService;
72
+
73
+    /** @var ICloudIdManager  */
74
+    protected $cloudIdManager;
75
+
76
+    /** @var bool */
77
+    protected $shareWithGroupOnly = false;
78
+
79
+    /** @var bool */
80
+    protected $shareeEnumeration = true;
81
+
82
+    /** @var int */
83
+    protected $offset = 0;
84
+
85
+    /** @var int */
86
+    protected $limit = 10;
87
+
88
+    /** @var array */
89
+    protected $result = [
90
+        'exact' => [
91
+            'users' => [],
92
+            'groups' => [],
93
+            'remotes' => [],
94
+            'emails' => [],
95
+            'circles' => [],
96
+        ],
97
+        'users' => [],
98
+        'groups' => [],
99
+        'remotes' => [],
100
+        'emails' => [],
101
+        'lookup' => [],
102
+        'circles' => [],
103
+    ];
104
+
105
+    protected $reachedEndFor = [];
106
+
107
+    /**
108
+     * @param string $appName
109
+     * @param IRequest $request
110
+     * @param IGroupManager $groupManager
111
+     * @param IUserManager $userManager
112
+     * @param IManager $contactsManager
113
+     * @param IConfig $config
114
+     * @param IUserSession $userSession
115
+     * @param IURLGenerator $urlGenerator
116
+     * @param ILogger $logger
117
+     * @param \OCP\Share\IManager $shareManager
118
+     * @param IClientService $clientService
119
+     * @param ICloudIdManager $cloudIdManager
120
+     */
121
+    public function __construct($appName,
122
+                                IRequest $request,
123
+                                IGroupManager $groupManager,
124
+                                IUserManager $userManager,
125
+                                IManager $contactsManager,
126
+                                IConfig $config,
127
+                                IUserSession $userSession,
128
+                                IURLGenerator $urlGenerator,
129
+                                ILogger $logger,
130
+                                \OCP\Share\IManager $shareManager,
131
+                                IClientService $clientService,
132
+                                ICloudIdManager $cloudIdManager
133
+    ) {
134
+        parent::__construct($appName, $request);
135
+
136
+        $this->groupManager = $groupManager;
137
+        $this->userManager = $userManager;
138
+        $this->contactsManager = $contactsManager;
139
+        $this->config = $config;
140
+        $this->userSession = $userSession;
141
+        $this->urlGenerator = $urlGenerator;
142
+        $this->logger = $logger;
143
+        $this->shareManager = $shareManager;
144
+        $this->clientService = $clientService;
145
+        $this->cloudIdManager = $cloudIdManager;
146
+    }
147
+
148
+    /**
149
+     * @param string $search
150
+     */
151
+    protected function getUsers($search) {
152
+        $this->result['users'] = $this->result['exact']['users'] = $users = [];
153
+
154
+        $userGroups = [];
155
+        if ($this->shareWithGroupOnly) {
156
+            // Search in all the groups this user is part of
157
+            $userGroups = $this->groupManager->getUserGroupIds($this->userSession->getUser());
158
+            foreach ($userGroups as $userGroup) {
159
+                $usersTmp = $this->groupManager->displayNamesInGroup($userGroup, $search, $this->limit, $this->offset);
160
+                foreach ($usersTmp as $uid => $userDisplayName) {
161
+                    $users[$uid] = $userDisplayName;
162
+                }
163
+            }
164
+        } else {
165
+            // Search in all users
166
+            $usersTmp = $this->userManager->searchDisplayName($search, $this->limit, $this->offset);
167
+
168
+            foreach ($usersTmp as $user) {
169
+                $users[$user->getUID()] = $user->getDisplayName();
170
+            }
171
+        }
172
+
173
+        if (!$this->shareeEnumeration || sizeof($users) < $this->limit) {
174
+            $this->reachedEndFor[] = 'users';
175
+        }
176
+
177
+        $foundUserById = false;
178
+        $lowerSearch = strtolower($search);
179
+        foreach ($users as $uid => $userDisplayName) {
180
+            if (strtolower($uid) === $lowerSearch || strtolower($userDisplayName) === $lowerSearch) {
181
+                if (strtolower($uid) === $lowerSearch) {
182
+                    $foundUserById = true;
183
+                }
184
+                $this->result['exact']['users'][] = [
185
+                    'label' => $userDisplayName,
186
+                    'value' => [
187
+                        'shareType' => Share::SHARE_TYPE_USER,
188
+                        'shareWith' => $uid,
189
+                    ],
190
+                ];
191
+            } else {
192
+                $this->result['users'][] = [
193
+                    'label' => $userDisplayName,
194
+                    'value' => [
195
+                        'shareType' => Share::SHARE_TYPE_USER,
196
+                        'shareWith' => $uid,
197
+                    ],
198
+                ];
199
+            }
200
+        }
201
+
202
+        if ($this->offset === 0 && !$foundUserById) {
203
+            // On page one we try if the search result has a direct hit on the
204
+            // user id and if so, we add that to the exact match list
205
+            $user = $this->userManager->get($search);
206
+            if ($user instanceof IUser) {
207
+                $addUser = true;
208
+
209
+                if ($this->shareWithGroupOnly) {
210
+                    // Only add, if we have a common group
211
+                    $commonGroups = array_intersect($userGroups, $this->groupManager->getUserGroupIds($user));
212
+                    $addUser = !empty($commonGroups);
213
+                }
214
+
215
+                if ($addUser) {
216
+                    array_push($this->result['exact']['users'], [
217
+                        'label' => $user->getDisplayName(),
218
+                        'value' => [
219
+                            'shareType' => Share::SHARE_TYPE_USER,
220
+                            'shareWith' => $user->getUID(),
221
+                        ],
222
+                    ]);
223
+                }
224
+            }
225
+        }
226
+
227
+        if (!$this->shareeEnumeration) {
228
+            $this->result['users'] = [];
229
+        }
230
+    }
231
+
232
+    /**
233
+     * @param string $search
234
+     */
235
+    protected function getGroups($search) {
236
+        $this->result['groups'] = $this->result['exact']['groups'] = [];
237
+
238
+        $groups = $this->groupManager->search($search, $this->limit, $this->offset);
239
+        $groupIds = array_map(function (IGroup $group) { return $group->getGID(); }, $groups);
240
+
241
+        if (!$this->shareeEnumeration || sizeof($groups) < $this->limit) {
242
+            $this->reachedEndFor[] = 'groups';
243
+        }
244
+
245
+        $userGroups =  [];
246
+        if (!empty($groups) && $this->shareWithGroupOnly) {
247
+            // Intersect all the groups that match with the groups this user is a member of
248
+            $userGroups = $this->groupManager->getUserGroups($this->userSession->getUser());
249
+            $userGroups = array_map(function (IGroup $group) { return $group->getGID(); }, $userGroups);
250
+            $groupIds = array_intersect($groupIds, $userGroups);
251
+        }
252
+
253
+        $lowerSearch = strtolower($search);
254
+        foreach ($groups as $group) {
255
+            // FIXME: use a more efficient approach
256
+            $gid = $group->getGID();
257
+            if (!in_array($gid, $groupIds)) {
258
+                continue;
259
+            }
260
+            if (strtolower($gid) === $lowerSearch || strtolower($group->getDisplayName()) === $lowerSearch) {
261
+                $this->result['exact']['groups'][] = [
262
+                    'label' => $group->getDisplayName(),
263
+                    'value' => [
264
+                        'shareType' => Share::SHARE_TYPE_GROUP,
265
+                        'shareWith' => $gid,
266
+                    ],
267
+                ];
268
+            } else {
269
+                $this->result['groups'][] = [
270
+                    'label' => $group->getDisplayName(),
271
+                    'value' => [
272
+                        'shareType' => Share::SHARE_TYPE_GROUP,
273
+                        'shareWith' => $gid,
274
+                    ],
275
+                ];
276
+            }
277
+        }
278
+
279
+        if ($this->offset === 0 && empty($this->result['exact']['groups'])) {
280
+            // On page one we try if the search result has a direct hit on the
281
+            // user id and if so, we add that to the exact match list
282
+            $group = $this->groupManager->get($search);
283
+            if ($group instanceof IGroup && (!$this->shareWithGroupOnly || in_array($group->getGID(), $userGroups))) {
284
+                array_push($this->result['exact']['groups'], [
285
+                    'label' => $group->getDisplayName(),
286
+                    'value' => [
287
+                        'shareType' => Share::SHARE_TYPE_GROUP,
288
+                        'shareWith' => $group->getGID(),
289
+                    ],
290
+                ]);
291
+            }
292
+        }
293
+
294
+        if (!$this->shareeEnumeration) {
295
+            $this->result['groups'] = [];
296
+        }
297
+    }
298
+
299
+
300
+    /**
301
+     * @param string $search
302
+     */
303
+    protected function getCircles($search) {
304
+        $this->result['circles'] = $this->result['exact']['circles'] = [];
305
+
306
+        $result = \OCA\Circles\Api\Sharees::search($search, $this->limit, $this->offset);
307
+        if (array_key_exists('circles', $result['exact'])) {
308
+            $this->result['exact']['circles'] = $result['exact']['circles'];
309
+        }
310
+        if (array_key_exists('circles', $result)) {
311
+            $this->result['circles'] = $result['circles'];
312
+        }
313
+    }
314
+
315
+
316
+    /**
317
+     * @param string $search
318
+     * @return array
319
+     */
320
+    protected function getRemote($search) {
321
+        $result = ['results' => [], 'exact' => []];
322
+
323
+        // Search in contacts
324
+        //@todo Pagination missing
325
+        $addressBookContacts = $this->contactsManager->search($search, ['CLOUD', 'FN']);
326
+        $result['exactIdMatch'] = false;
327
+        foreach ($addressBookContacts as $contact) {
328
+            if (isset($contact['isLocalSystemBook'])) {
329
+                continue;
330
+            }
331
+            if (isset($contact['CLOUD'])) {
332
+                $cloudIds = $contact['CLOUD'];
333
+                if (!is_array($cloudIds)) {
334
+                    $cloudIds = [$cloudIds];
335
+                }
336
+                $lowerSearch = strtolower($search);
337
+                foreach ($cloudIds as $cloudId) {
338
+                    list(, $serverUrl) = $this->splitUserRemote($cloudId);
339
+                    if (strtolower($contact['FN']) === $lowerSearch || strtolower($cloudId) === $lowerSearch) {
340
+                        if (strtolower($cloudId) === $lowerSearch) {
341
+                            $result['exactIdMatch'] = true;
342
+                        }
343
+                        $result['exact'][] = [
344
+                            'label' => $contact['FN'] . " ($cloudId)",
345
+                            'value' => [
346
+                                'shareType' => Share::SHARE_TYPE_REMOTE,
347
+                                'shareWith' => $cloudId,
348
+                                'server' => $serverUrl,
349
+                            ],
350
+                        ];
351
+                    } else {
352
+                        $result['results'][] = [
353
+                            'label' => $contact['FN'] . " ($cloudId)",
354
+                            'value' => [
355
+                                'shareType' => Share::SHARE_TYPE_REMOTE,
356
+                                'shareWith' => $cloudId,
357
+                                'server' => $serverUrl,
358
+                            ],
359
+                        ];
360
+                    }
361
+                }
362
+            }
363
+        }
364
+
365
+        if (!$this->shareeEnumeration) {
366
+            $result['results'] = [];
367
+        }
368
+
369
+        if (!$result['exactIdMatch'] && $this->cloudIdManager->isValidCloudId($search) && $this->offset === 0) {
370
+            $result['exact'][] = [
371
+                'label' => $search,
372
+                'value' => [
373
+                    'shareType' => Share::SHARE_TYPE_REMOTE,
374
+                    'shareWith' => $search,
375
+                ],
376
+            ];
377
+        }
378
+
379
+        $this->reachedEndFor[] = 'remotes';
380
+
381
+        return $result;
382
+    }
383
+
384
+    /**
385
+     * split user and remote from federated cloud id
386
+     *
387
+     * @param string $address federated share address
388
+     * @return array [user, remoteURL]
389
+     * @throws \Exception
390
+     */
391
+    public function splitUserRemote($address) {
392
+        try {
393
+            $cloudId = $this->cloudIdManager->resolveCloudId($address);
394
+            return [$cloudId->getUser(), $cloudId->getRemote()];
395
+        } catch (\InvalidArgumentException $e) {
396
+            throw new \Exception('Invalid Federated Cloud ID', 0, $e);
397
+        }
398
+    }
399
+
400
+    /**
401
+     * Strips away a potential file names and trailing slashes:
402
+     * - http://localhost
403
+     * - http://localhost/
404
+     * - http://localhost/index.php
405
+     * - http://localhost/index.php/s/{shareToken}
406
+     *
407
+     * all return: http://localhost
408
+     *
409
+     * @param string $remote
410
+     * @return string
411
+     */
412
+    protected function fixRemoteURL($remote) {
413
+        $remote = str_replace('\\', '/', $remote);
414
+        if ($fileNamePosition = strpos($remote, '/index.php')) {
415
+            $remote = substr($remote, 0, $fileNamePosition);
416
+        }
417
+        $remote = rtrim($remote, '/');
418
+
419
+        return $remote;
420
+    }
421
+
422
+    /**
423
+     * @NoAdminRequired
424
+     *
425
+     * @param string $search
426
+     * @param string $itemType
427
+     * @param int $page
428
+     * @param int $perPage
429
+     * @param int|int[] $shareType
430
+     * @param bool $lookup
431
+     * @return DataResponse
432
+     * @throws OCSBadRequestException
433
+     */
434
+    public function search($search = '', $itemType = null, $page = 1, $perPage = 200, $shareType = null, $lookup = true) {
435
+
436
+        // only search for string larger than a given threshold
437
+        $threshold = (int)$this->config->getSystemValue('sharing.minSearchStringLength', 0);
438
+        if (strlen($search) < $threshold) {
439
+            return new DataResponse($this->result);
440
+        }
441
+
442
+        // never return more than the max. number of results configured in the config.php
443
+        $maxResults = (int)$this->config->getSystemValue('sharing.maxAutocompleteResults', 0);
444
+        if ($maxResults > 0) {
445
+            $perPage = min($perPage, $maxResults);
446
+        }
447
+        if ($perPage <= 0) {
448
+            throw new OCSBadRequestException('Invalid perPage argument');
449
+        }
450
+        if ($page <= 0) {
451
+            throw new OCSBadRequestException('Invalid page');
452
+        }
453
+
454
+        $shareTypes = [
455
+            Share::SHARE_TYPE_USER,
456
+        ];
457
+
458
+        if ($itemType === 'file' || $itemType === 'folder') {
459
+            if ($this->shareManager->allowGroupSharing()) {
460
+                $shareTypes[] = Share::SHARE_TYPE_GROUP;
461
+            }
462
+
463
+            if ($this->isRemoteSharingAllowed($itemType)) {
464
+                $shareTypes[] = Share::SHARE_TYPE_REMOTE;
465
+            }
466
+
467
+            if ($this->shareManager->shareProviderExists(Share::SHARE_TYPE_EMAIL)) {
468
+                $shareTypes[] = Share::SHARE_TYPE_EMAIL;
469
+            }
470
+        } else {
471
+            $shareTypes[] = Share::SHARE_TYPE_GROUP;
472
+            $shareTypes[] = Share::SHARE_TYPE_EMAIL;
473
+        }
474
+
475
+        if (\OCP\App::isEnabled('circles')) {
476
+            $shareTypes[] = Share::SHARE_TYPE_CIRCLE;
477
+        }
478
+
479
+        if (isset($_GET['shareType']) && is_array($_GET['shareType'])) {
480
+            $shareTypes = array_intersect($shareTypes, $_GET['shareType']);
481
+            sort($shareTypes);
482
+        } else if (is_numeric($shareType)) {
483
+            $shareTypes = array_intersect($shareTypes, [(int) $shareType]);
484
+            sort($shareTypes);
485
+        }
486
+
487
+        $this->shareWithGroupOnly = $this->config->getAppValue('core', 'shareapi_only_share_with_group_members', 'no') === 'yes';
488
+        $this->shareeEnumeration = $this->config->getAppValue('core', 'shareapi_allow_share_dialog_user_enumeration', 'yes') === 'yes';
489
+        $this->limit = (int) $perPage;
490
+        $this->offset = $perPage * ($page - 1);
491
+
492
+        return $this->searchSharees($search, $itemType, $shareTypes, $page, $perPage, $lookup);
493
+    }
494
+
495
+    /**
496
+     * Method to get out the static call for better testing
497
+     *
498
+     * @param string $itemType
499
+     * @return bool
500
+     */
501
+    protected function isRemoteSharingAllowed($itemType) {
502
+        try {
503
+            $backend = Share::getBackend($itemType);
504
+            return $backend->isShareTypeAllowed(Share::SHARE_TYPE_REMOTE);
505
+        } catch (\Exception $e) {
506
+            return false;
507
+        }
508
+    }
509
+
510
+    /**
511
+     * Testable search function that does not need globals
512
+     *
513
+     * @param string $search
514
+     * @param string $itemType
515
+     * @param array $shareTypes
516
+     * @param int $page
517
+     * @param int $perPage
518
+     * @param bool $lookup
519
+     * @return DataResponse
520
+     * @throws OCSBadRequestException
521
+     */
522
+    protected function searchSharees($search, $itemType, array $shareTypes, $page, $perPage, $lookup) {
523
+        // Verify arguments
524
+        if ($itemType === null) {
525
+            throw new OCSBadRequestException('Missing itemType');
526
+        }
527
+
528
+        // Get users
529
+        if (in_array(Share::SHARE_TYPE_USER, $shareTypes)) {
530
+            $this->getUsers($search);
531
+        }
532
+
533
+        // Get groups
534
+        if (in_array(Share::SHARE_TYPE_GROUP, $shareTypes)) {
535
+            $this->getGroups($search);
536
+        }
537
+
538
+        // Get circles
539
+        if (in_array(Share::SHARE_TYPE_CIRCLE, $shareTypes)) {
540
+            $this->getCircles($search);
541
+        }
542
+
543
+
544
+        // Get remote
545
+        $remoteResults = ['results' => [], 'exact' => [], 'exactIdMatch' => false];
546
+        if (in_array(Share::SHARE_TYPE_REMOTE, $shareTypes)) {
547
+            $remoteResults = $this->getRemote($search);
548
+        }
549
+
550
+        // Get emails
551
+        $mailResults = ['results' => [], 'exact' => [], 'exactIdMatch' => false];
552
+        if (in_array(Share::SHARE_TYPE_EMAIL, $shareTypes)) {
553
+            $mailResults = $this->getEmail($search);
554
+        }
555
+
556
+        // Get from lookup server
557
+        if ($lookup) {
558
+            $this->getLookup($search);
559
+        }
560
+
561
+        // if we have a exact match, either for the federated cloud id or for the
562
+        // email address we only return the exact match. It is highly unlikely
563
+        // that the exact same email address and federated cloud id exists
564
+        if ($mailResults['exactIdMatch'] && !$remoteResults['exactIdMatch']) {
565
+            $this->result['emails'] = $mailResults['results'];
566
+            $this->result['exact']['emails'] = $mailResults['exact'];
567
+        } else if (!$mailResults['exactIdMatch'] && $remoteResults['exactIdMatch']) {
568
+            $this->result['remotes'] = $remoteResults['results'];
569
+            $this->result['exact']['remotes'] = $remoteResults['exact'];
570
+        } else {
571
+            $this->result['remotes'] = $remoteResults['results'];
572
+            $this->result['exact']['remotes'] = $remoteResults['exact'];
573
+            $this->result['emails'] = $mailResults['results'];
574
+            $this->result['exact']['emails'] = $mailResults['exact'];
575
+        }
576
+
577
+        $response = new DataResponse($this->result);
578
+
579
+        if (sizeof($this->reachedEndFor) < 3) {
580
+            $response->addHeader('Link', $this->getPaginationLink($page, [
581
+                'search' => $search,
582
+                'itemType' => $itemType,
583
+                'shareType' => $shareTypes,
584
+                'perPage' => $perPage,
585
+            ]));
586
+        }
587
+
588
+        return $response;
589
+    }
590
+
591
+    /**
592
+     * @param string $search
593
+     * @return array
594
+     */
595
+    protected function getEmail($search) {
596
+        $result = ['results' => [], 'exact' => []];
597
+
598
+        // Search in contacts
599
+        //@todo Pagination missing
600
+        $addressBookContacts = $this->contactsManager->search($search, ['EMAIL', 'FN']);
601
+        $result['exactIdMatch'] = false;
602
+        foreach ($addressBookContacts as $contact) {
603
+            if (isset($contact['isLocalSystemBook'])) {
604
+                continue;
605
+            }
606
+            if (isset($contact['EMAIL'])) {
607
+                $emailAddresses = $contact['EMAIL'];
608
+                if (!is_array($emailAddresses)) {
609
+                    $emailAddresses = [$emailAddresses];
610
+                }
611
+                foreach ($emailAddresses as $emailAddress) {
612
+                    if (strtolower($contact['FN']) === strtolower($search) || strtolower($emailAddress) === strtolower($search)) {
613
+                        if (strtolower($emailAddress) === strtolower($search)) {
614
+                            $result['exactIdMatch'] = true;
615
+                        }
616
+                        $result['exact'][] = [
617
+                            'label' => $contact['FN'] . " ($emailAddress)",
618
+                            'value' => [
619
+                                'shareType' => Share::SHARE_TYPE_EMAIL,
620
+                                'shareWith' => $emailAddress,
621
+                            ],
622
+                        ];
623
+                    } else {
624
+                        $result['results'][] = [
625
+                            'label' => $contact['FN'] . " ($emailAddress)",
626
+                            'value' => [
627
+                                'shareType' => Share::SHARE_TYPE_EMAIL,
628
+                                'shareWith' => $emailAddress,
629
+                            ],
630
+                        ];
631
+                    }
632
+                }
633
+            }
634
+        }
635
+
636
+        if (!$this->shareeEnumeration) {
637
+            $result['results'] = [];
638
+        }
639
+
640
+        if (!$result['exactIdMatch'] && filter_var($search, FILTER_VALIDATE_EMAIL)) {
641
+            $result['exact'][] = [
642
+                'label' => $search,
643
+                'value' => [
644
+                    'shareType' => Share::SHARE_TYPE_EMAIL,
645
+                    'shareWith' => $search,
646
+                ],
647
+            ];
648
+        }
649
+
650
+        $this->reachedEndFor[] = 'emails';
651
+
652
+        return $result;
653
+    }
654
+
655
+    protected function getLookup($search) {
656
+        $isEnabled = $this->config->getAppValue('files_sharing', 'lookupServerEnabled', 'no');
657
+        $result = [];
658
+
659
+        if($isEnabled === 'yes') {
660
+            try {
661
+                $client = $this->clientService->newClient();
662
+                $response = $client->get(
663
+                    'https://lookup.nextcloud.com/users?search=' . urlencode($search),
664
+                    [
665
+                        'timeout' => 10,
666
+                        'connect_timeout' => 3,
667
+                    ]
668
+                );
669
+
670
+                $body = json_decode($response->getBody(), true);
671
+
672
+                $result = [];
673
+                foreach ($body as $lookup) {
674
+                    $result[] = [
675
+                        'label' => $lookup['federationId'],
676
+                        'value' => [
677
+                            'shareType' => Share::SHARE_TYPE_REMOTE,
678
+                            'shareWith' => $lookup['federationId'],
679
+                        ],
680
+                        'extra' => $lookup,
681
+                    ];
682
+                }
683
+            } catch (\Exception $e) {}
684
+        }
685
+
686
+        $this->result['lookup'] = $result;
687
+    }
688
+
689
+    /**
690
+     * Generates a bunch of pagination links for the current page
691
+     *
692
+     * @param int $page Current page
693
+     * @param array $params Parameters for the URL
694
+     * @return string
695
+     */
696
+    protected function getPaginationLink($page, array $params) {
697
+        if ($this->isV2()) {
698
+            $url = $this->urlGenerator->getAbsoluteURL('/ocs/v2.php/apps/files_sharing/api/v1/sharees') . '?';
699
+        } else {
700
+            $url = $this->urlGenerator->getAbsoluteURL('/ocs/v1.php/apps/files_sharing/api/v1/sharees') . '?';
701
+        }
702
+        $params['page'] = $page + 1;
703
+        $link = '<' . $url . http_build_query($params) . '>; rel="next"';
704
+
705
+        return $link;
706
+    }
707
+
708
+    /**
709
+     * @return bool
710
+     */
711
+    protected function isV2() {
712
+        return $this->request->getScriptName() === '/ocs/v2.php';
713
+    }
714 714
 }
Please login to merge, or discard this patch.
apps/provisioning_api/lib/Controller/UsersController.php 4 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -225,7 +225,7 @@
 block discarded – undo
225 225
 	/**
226 226
 	 * creates a array with all user data
227 227
 	 *
228
-	 * @param $userId
228
+	 * @param string $userId
229 229
 	 * @return array
230 230
 	 * @throws OCSException
231 231
 	 */
Please login to merge, or discard this patch.
Braces   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -335,7 +335,7 @@
 block discarded – undo
335 335
 					}
336 336
 					if($quota === 0) {
337 337
 						$quota = 'default';
338
-					}else if($quota === -1) {
338
+					} else if($quota === -1) {
339 339
 						$quota = 'none';
340 340
 					} else {
341 341
 						$quota = \OCP\Util::humanFileSize($quota);
Please login to merge, or discard this patch.
Indentation   +773 added lines, -773 removed lines patch added patch discarded remove patch
@@ -51,777 +51,777 @@
 block discarded – undo
51 51
 
52 52
 class UsersController extends OCSController {
53 53
 
54
-	/** @var IUserManager */
55
-	private $userManager;
56
-	/** @var IConfig */
57
-	private $config;
58
-	/** @var IGroupManager|\OC\Group\Manager */ // FIXME Requires a method that is not on the interface
59
-	private $groupManager;
60
-	/** @var IUserSession */
61
-	private $userSession;
62
-	/** @var AccountManager */
63
-	private $accountManager;
64
-	/** @var ILogger */
65
-	private $logger;
66
-	/** @var string */
67
-	private $fromMailAddress;
68
-	/** @var IURLGenerator */
69
-	private $urlGenerator;
70
-	/** @var IMailer */
71
-	private $mailer;
72
-	/** @var Defaults */
73
-	private $defaults;
74
-	/** @var IFactory */
75
-	private $l10nFactory;
76
-	/** @var NewUserMailHelper */
77
-	private $newUserMailHelper;
78
-
79
-	/**
80
-	 * @param string $appName
81
-	 * @param IRequest $request
82
-	 * @param IUserManager $userManager
83
-	 * @param IConfig $config
84
-	 * @param IGroupManager $groupManager
85
-	 * @param IUserSession $userSession
86
-	 * @param AccountManager $accountManager
87
-	 * @param ILogger $logger
88
-	 * @param string $fromMailAddress
89
-	 * @param IURLGenerator $urlGenerator
90
-	 * @param IMailer $mailer
91
-	 * @param Defaults $defaults
92
-	 * @param IFactory $l10nFactory
93
-	 * @param NewUserMailHelper $newUserMailHelper
94
-	 */
95
-	public function __construct($appName,
96
-								IRequest $request,
97
-								IUserManager $userManager,
98
-								IConfig $config,
99
-								IGroupManager $groupManager,
100
-								IUserSession $userSession,
101
-								AccountManager $accountManager,
102
-								ILogger $logger,
103
-								$fromMailAddress,
104
-								IURLGenerator $urlGenerator,
105
-								IMailer $mailer,
106
-								Defaults $defaults,
107
-								IFactory $l10nFactory,
108
-								NewUserMailHelper $newUserMailHelper) {
109
-		parent::__construct($appName, $request);
110
-
111
-		$this->userManager = $userManager;
112
-		$this->config = $config;
113
-		$this->groupManager = $groupManager;
114
-		$this->userSession = $userSession;
115
-		$this->accountManager = $accountManager;
116
-		$this->logger = $logger;
117
-		$this->fromMailAddress = $fromMailAddress;
118
-		$this->urlGenerator = $urlGenerator;
119
-		$this->mailer = $mailer;
120
-		$this->defaults = $defaults;
121
-		$this->l10nFactory = $l10nFactory;
122
-		$this->newUserMailHelper = $newUserMailHelper;
123
-	}
124
-
125
-	/**
126
-	 * @NoAdminRequired
127
-	 *
128
-	 * returns a list of users
129
-	 *
130
-	 * @param string $search
131
-	 * @param int $limit
132
-	 * @param int $offset
133
-	 * @return DataResponse
134
-	 */
135
-	public function getUsers($search = '', $limit = null, $offset = null) {
136
-		$user = $this->userSession->getUser();
137
-		$users = [];
138
-
139
-		// Admin? Or SubAdmin?
140
-		$uid = $user->getUID();
141
-		$subAdminManager = $this->groupManager->getSubAdmin();
142
-		if($this->groupManager->isAdmin($uid)){
143
-			$users = $this->userManager->search($search, $limit, $offset);
144
-		} else if ($subAdminManager->isSubAdmin($user)) {
145
-			$subAdminOfGroups = $subAdminManager->getSubAdminsGroups($user);
146
-			foreach ($subAdminOfGroups as $key => $group) {
147
-				$subAdminOfGroups[$key] = $group->getGID();
148
-			}
149
-
150
-			if($offset === null) {
151
-				$offset = 0;
152
-			}
153
-
154
-			$users = [];
155
-			foreach ($subAdminOfGroups as $group) {
156
-				$users = array_merge($users, $this->groupManager->displayNamesInGroup($group, $search));
157
-			}
158
-
159
-			$users = array_slice($users, $offset, $limit);
160
-		}
161
-
162
-		$users = array_keys($users);
163
-
164
-		return new DataResponse([
165
-			'users' => $users
166
-		]);
167
-	}
168
-
169
-	/**
170
-	 * @PasswordConfirmationRequired
171
-	 * @NoAdminRequired
172
-	 *
173
-	 * @param string $userid
174
-	 * @param string $password
175
-	 * @param array $groups
176
-	 * @return DataResponse
177
-	 * @throws OCSException
178
-	 */
179
-	public function addUser($userid, $password, $groups = null) {
180
-		$user = $this->userSession->getUser();
181
-		$isAdmin = $this->groupManager->isAdmin($user->getUID());
182
-		$subAdminManager = $this->groupManager->getSubAdmin();
183
-
184
-		if($this->userManager->userExists($userid)) {
185
-			$this->logger->error('Failed addUser attempt: User already exists.', ['app' => 'ocs_api']);
186
-			throw new OCSException('User already exists', 102);
187
-		}
188
-
189
-		if(is_array($groups)) {
190
-			foreach ($groups as $group) {
191
-				if(!$this->groupManager->groupExists($group)) {
192
-					throw new OCSException('group '.$group.' does not exist', 104);
193
-				}
194
-				if(!$isAdmin && !$subAdminManager->isSubAdminofGroup($user, $this->groupManager->get($group))) {
195
-					throw new OCSException('insufficient privileges for group '. $group, 105);
196
-				}
197
-			}
198
-		} else {
199
-			if(!$isAdmin) {
200
-				throw new OCSException('no group specified (required for subadmins)', 106);
201
-			}
202
-		}
203
-
204
-		try {
205
-			$newUser = $this->userManager->createUser($userid, $password);
206
-			$this->logger->info('Successful addUser call with userid: '.$userid, ['app' => 'ocs_api']);
207
-
208
-			if (is_array($groups)) {
209
-				foreach ($groups as $group) {
210
-					$this->groupManager->get($group)->addUser($newUser);
211
-					$this->logger->info('Added userid '.$userid.' to group '.$group, ['app' => 'ocs_api']);
212
-				}
213
-			}
214
-			return new DataResponse();
215
-		} catch (\Exception $e) {
216
-			$this->logger->error('Failed addUser attempt with exception: '.$e->getMessage(), ['app' => 'ocs_api']);
217
-			throw new OCSException('Bad request', 101);
218
-		}
219
-	}
220
-
221
-	/**
222
-	 * @NoAdminRequired
223
-	 * @NoSubAdminRequired
224
-	 *
225
-	 * gets user info
226
-	 *
227
-	 * @param string $userId
228
-	 * @return DataResponse
229
-	 * @throws OCSException
230
-	 */
231
-	public function getUser($userId) {
232
-		$data = $this->getUserData($userId);
233
-		return new DataResponse($data);
234
-	}
235
-
236
-	/**
237
-	 * @NoAdminRequired
238
-	 * @NoSubAdminRequired
239
-	 *
240
-	 * gets user info from the currently logged in user
241
-	 *
242
-	 * @return DataResponse
243
-	 * @throws OCSException
244
-	 */
245
-	public function getCurrentUser() {
246
-		$user = $this->userSession->getUser();
247
-		if ($user) {
248
-			$data =  $this->getUserData($user->getUID());
249
-			// rename "displayname" to "display-name" only for this call to keep
250
-			// the API stable.
251
-			$data['display-name'] = $data['displayname'];
252
-			unset($data['displayname']);
253
-			return new DataResponse($data);
254
-
255
-		}
256
-
257
-		throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
258
-	}
259
-
260
-	/**
261
-	 * creates a array with all user data
262
-	 *
263
-	 * @param $userId
264
-	 * @return array
265
-	 * @throws OCSException
266
-	 */
267
-	protected function getUserData($userId) {
268
-		$currentLoggedInUser = $this->userSession->getUser();
269
-
270
-		$data = [];
271
-
272
-		// Check if the target user exists
273
-		$targetUserObject = $this->userManager->get($userId);
274
-		if($targetUserObject === null) {
275
-			throw new OCSException('The requested user could not be found', \OCP\API::RESPOND_NOT_FOUND);
276
-		}
277
-
278
-		// Admin? Or SubAdmin?
279
-		if($this->groupManager->isAdmin($currentLoggedInUser->getUID())
280
-			|| $this->groupManager->getSubAdmin()->isUserAccessible($currentLoggedInUser, $targetUserObject)) {
281
-			$data['enabled'] = $this->config->getUserValue($userId, 'core', 'enabled', 'true');
282
-		} else {
283
-			// Check they are looking up themselves
284
-			if($currentLoggedInUser->getUID() !== $userId) {
285
-				throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
286
-			}
287
-		}
288
-
289
-		$userAccount = $this->accountManager->getUser($targetUserObject);
290
-		$groups = $this->groupManager->getUserGroups($targetUserObject);
291
-		$gids = [];
292
-		foreach ($groups as $group) {
293
-			$gids[] = $group->getDisplayName();
294
-		}
295
-
296
-		// Find the data
297
-		$data['id'] = $targetUserObject->getUID();
298
-		$data['quota'] = $this->fillStorageInfo($userId);
299
-		$data[AccountManager::PROPERTY_EMAIL] = $targetUserObject->getEMailAddress();
300
-		$data[AccountManager::PROPERTY_DISPLAYNAME] = $targetUserObject->getDisplayName();
301
-		$data[AccountManager::PROPERTY_PHONE] = $userAccount[AccountManager::PROPERTY_PHONE]['value'];
302
-		$data[AccountManager::PROPERTY_ADDRESS] = $userAccount[AccountManager::PROPERTY_ADDRESS]['value'];
303
-		$data[AccountManager::PROPERTY_WEBSITE] = $userAccount[AccountManager::PROPERTY_WEBSITE]['value'];
304
-		$data[AccountManager::PROPERTY_TWITTER] = $userAccount[AccountManager::PROPERTY_TWITTER]['value'];
305
-		$data['groups'] = $gids;
306
-
307
-		return $data;
308
-	}
309
-
310
-	/**
311
-	 * @NoAdminRequired
312
-	 * @NoSubAdminRequired
313
-	 * @PasswordConfirmationRequired
314
-	 *
315
-	 * edit users
316
-	 *
317
-	 * @param string $userId
318
-	 * @param string $key
319
-	 * @param string $value
320
-	 * @return DataResponse
321
-	 * @throws OCSException
322
-	 * @throws OCSForbiddenException
323
-	 */
324
-	public function editUser($userId, $key, $value) {
325
-		$currentLoggedInUser = $this->userSession->getUser();
326
-
327
-		$targetUser = $this->userManager->get($userId);
328
-		if($targetUser === null) {
329
-			throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
330
-		}
331
-
332
-		$permittedFields = [];
333
-		if($userId === $currentLoggedInUser->getUID()) {
334
-			// Editing self (display, email)
335
-			$permittedFields[] = 'display';
336
-			$permittedFields[] = AccountManager::PROPERTY_DISPLAYNAME;
337
-			$permittedFields[] = AccountManager::PROPERTY_EMAIL;
338
-			$permittedFields[] = 'password';
339
-			$permittedFields[] = AccountManager::PROPERTY_PHONE;
340
-			$permittedFields[] = AccountManager::PROPERTY_ADDRESS;
341
-			$permittedFields[] = AccountManager::PROPERTY_WEBSITE;
342
-			$permittedFields[] = AccountManager::PROPERTY_TWITTER;
343
-			// If admin they can edit their own quota
344
-			if($this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
345
-				$permittedFields[] = 'quota';
346
-			}
347
-		} else {
348
-			// Check if admin / subadmin
349
-			$subAdminManager = $this->groupManager->getSubAdmin();
350
-			if($subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)
351
-			|| $this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
352
-				// They have permissions over the user
353
-				$permittedFields[] = 'display';
354
-				$permittedFields[] = AccountManager::PROPERTY_DISPLAYNAME;
355
-				$permittedFields[] = AccountManager::PROPERTY_EMAIL;
356
-				$permittedFields[] = 'password';
357
-				$permittedFields[] = AccountManager::PROPERTY_PHONE;
358
-				$permittedFields[] = AccountManager::PROPERTY_ADDRESS;
359
-				$permittedFields[] = AccountManager::PROPERTY_WEBSITE;
360
-				$permittedFields[] = AccountManager::PROPERTY_TWITTER;
361
-				$permittedFields[] = 'quota';
362
-			} else {
363
-				// No rights
364
-				throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
365
-			}
366
-		}
367
-		// Check if permitted to edit this field
368
-		if(!in_array($key, $permittedFields)) {
369
-			throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
370
-		}
371
-		// Process the edit
372
-		switch($key) {
373
-			case 'display':
374
-			case AccountManager::PROPERTY_DISPLAYNAME:
375
-				$targetUser->setDisplayName($value);
376
-				break;
377
-			case 'quota':
378
-				$quota = $value;
379
-				if($quota !== 'none' && $quota !== 'default') {
380
-					if (is_numeric($quota)) {
381
-						$quota = (float) $quota;
382
-					} else {
383
-						$quota = \OCP\Util::computerFileSize($quota);
384
-					}
385
-					if ($quota === false) {
386
-						throw new OCSException('Invalid quota value '.$value, 103);
387
-					}
388
-					if($quota === 0) {
389
-						$quota = 'default';
390
-					}else if($quota === -1) {
391
-						$quota = 'none';
392
-					} else {
393
-						$quota = \OCP\Util::humanFileSize($quota);
394
-					}
395
-				}
396
-				$targetUser->setQuota($quota);
397
-				break;
398
-			case 'password':
399
-				$targetUser->setPassword($value);
400
-				break;
401
-			case AccountManager::PROPERTY_EMAIL:
402
-				if(filter_var($value, FILTER_VALIDATE_EMAIL)) {
403
-					$targetUser->setEMailAddress($value);
404
-				} else {
405
-					throw new OCSException('', 102);
406
-				}
407
-				break;
408
-			case AccountManager::PROPERTY_PHONE:
409
-			case AccountManager::PROPERTY_ADDRESS:
410
-			case AccountManager::PROPERTY_WEBSITE:
411
-			case AccountManager::PROPERTY_TWITTER:
412
-				$userAccount = $this->accountManager->getUser($targetUser);
413
-				if ($userAccount[$key]['value'] !== $value) {
414
-					$userAccount[$key]['value'] = $value;
415
-					$this->accountManager->updateUser($targetUser, $userAccount);
416
-				}
417
-				break;
418
-			default:
419
-				throw new OCSException('', 103);
420
-		}
421
-		return new DataResponse();
422
-	}
423
-
424
-	/**
425
-	 * @PasswordConfirmationRequired
426
-	 * @NoAdminRequired
427
-	 *
428
-	 * @param string $userId
429
-	 * @return DataResponse
430
-	 * @throws OCSException
431
-	 * @throws OCSForbiddenException
432
-	 */
433
-	public function deleteUser($userId) {
434
-		$currentLoggedInUser = $this->userSession->getUser();
435
-
436
-		$targetUser = $this->userManager->get($userId);
437
-
438
-		if($targetUser === null || $targetUser->getUID() === $currentLoggedInUser->getUID()) {
439
-			throw new OCSException('', 101);
440
-		}
441
-
442
-		// If not permitted
443
-		$subAdminManager = $this->groupManager->getSubAdmin();
444
-		if(!$this->groupManager->isAdmin($currentLoggedInUser->getUID()) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) {
445
-			throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
446
-		}
447
-
448
-		// Go ahead with the delete
449
-		if($targetUser->delete()) {
450
-			return new DataResponse();
451
-		} else {
452
-			throw new OCSException('', 101);
453
-		}
454
-	}
455
-
456
-	/**
457
-	 * @PasswordConfirmationRequired
458
-	 * @NoAdminRequired
459
-	 *
460
-	 * @param string $userId
461
-	 * @return DataResponse
462
-	 * @throws OCSException
463
-	 * @throws OCSForbiddenException
464
-	 */
465
-	public function disableUser($userId) {
466
-		return $this->setEnabled($userId, false);
467
-	}
468
-
469
-	/**
470
-	 * @PasswordConfirmationRequired
471
-	 * @NoAdminRequired
472
-	 *
473
-	 * @param string $userId
474
-	 * @return DataResponse
475
-	 * @throws OCSException
476
-	 * @throws OCSForbiddenException
477
-	 */
478
-	public function enableUser($userId) {
479
-		return $this->setEnabled($userId, true);
480
-	}
481
-
482
-	/**
483
-	 * @param string $userId
484
-	 * @param bool $value
485
-	 * @return DataResponse
486
-	 * @throws OCSException
487
-	 * @throws OCSForbiddenException
488
-	 */
489
-	private function setEnabled($userId, $value) {
490
-		$currentLoggedInUser = $this->userSession->getUser();
491
-
492
-		$targetUser = $this->userManager->get($userId);
493
-		if($targetUser === null || $targetUser->getUID() === $currentLoggedInUser->getUID()) {
494
-			throw new OCSException('', 101);
495
-		}
496
-
497
-		// If not permitted
498
-		$subAdminManager = $this->groupManager->getSubAdmin();
499
-		if(!$this->groupManager->isAdmin($currentLoggedInUser->getUID()) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) {
500
-			throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
501
-		}
502
-
503
-		// enable/disable the user now
504
-		$targetUser->setEnabled($value);
505
-		return new DataResponse();
506
-	}
507
-
508
-	/**
509
-	 * @NoAdminRequired
510
-	 * @NoSubAdminRequired
511
-	 *
512
-	 * @param string $userId
513
-	 * @return DataResponse
514
-	 * @throws OCSException
515
-	 */
516
-	public function getUsersGroups($userId) {
517
-		$loggedInUser = $this->userSession->getUser();
518
-
519
-		$targetUser = $this->userManager->get($userId);
520
-		if($targetUser === null) {
521
-			throw new OCSException('', \OCP\API::RESPOND_NOT_FOUND);
522
-		}
523
-
524
-		if($targetUser->getUID() === $loggedInUser->getUID() || $this->groupManager->isAdmin($loggedInUser->getUID())) {
525
-			// Self lookup or admin lookup
526
-			return new DataResponse([
527
-				'groups' => $this->groupManager->getUserGroupIds($targetUser)
528
-			]);
529
-		} else {
530
-			$subAdminManager = $this->groupManager->getSubAdmin();
531
-
532
-			// Looking up someone else
533
-			if($subAdminManager->isUserAccessible($loggedInUser, $targetUser)) {
534
-				// Return the group that the method caller is subadmin of for the user in question
535
-				/** @var IGroup[] $getSubAdminsGroups */
536
-				$getSubAdminsGroups = $subAdminManager->getSubAdminsGroups($loggedInUser);
537
-				foreach ($getSubAdminsGroups as $key => $group) {
538
-					$getSubAdminsGroups[$key] = $group->getGID();
539
-				}
540
-				$groups = array_intersect(
541
-					$getSubAdminsGroups,
542
-					$this->groupManager->getUserGroupIds($targetUser)
543
-				);
544
-				return new DataResponse(['groups' => $groups]);
545
-			} else {
546
-				// Not permitted
547
-				throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
548
-			}
549
-		}
550
-
551
-	}
552
-
553
-	/**
554
-	 * @PasswordConfirmationRequired
555
-	 * @NoAdminRequired
556
-	 *
557
-	 * @param string $userId
558
-	 * @param string $groupid
559
-	 * @return DataResponse
560
-	 * @throws OCSException
561
-	 */
562
-	public function addToGroup($userId, $groupid = '') {
563
-		if($groupid === '') {
564
-			throw new OCSException('', 101);
565
-		}
566
-
567
-		$group = $this->groupManager->get($groupid);
568
-		$targetUser = $this->userManager->get($userId);
569
-		if($group === null) {
570
-			throw new OCSException('', 102);
571
-		}
572
-		if($targetUser === null) {
573
-			throw new OCSException('', 103);
574
-		}
575
-
576
-		// If they're not an admin, check they are a subadmin of the group in question
577
-		$loggedInUser = $this->userSession->getUser();
578
-		$subAdminManager = $this->groupManager->getSubAdmin();
579
-		if (!$this->groupManager->isAdmin($loggedInUser->getUID()) && !$subAdminManager->isSubAdminOfGroup($loggedInUser, $group)) {
580
-			throw new OCSException('', 104);
581
-		}
582
-
583
-		// Add user to group
584
-		$group->addUser($targetUser);
585
-		return new DataResponse();
586
-	}
587
-
588
-	/**
589
-	 * @PasswordConfirmationRequired
590
-	 * @NoAdminRequired
591
-	 *
592
-	 * @param string $userId
593
-	 * @param string $groupid
594
-	 * @return DataResponse
595
-	 * @throws OCSException
596
-	 */
597
-	public function removeFromGroup($userId, $groupid) {
598
-		$loggedInUser = $this->userSession->getUser();
599
-
600
-		if($groupid === null) {
601
-			throw new OCSException('', 101);
602
-		}
603
-
604
-		$group = $this->groupManager->get($groupid);
605
-		if($group === null) {
606
-			throw new OCSException('', 102);
607
-		}
608
-
609
-		$targetUser = $this->userManager->get($userId);
610
-		if($targetUser === null) {
611
-			throw new OCSException('', 103);
612
-		}
613
-
614
-		// If they're not an admin, check they are a subadmin of the group in question
615
-		$subAdminManager = $this->groupManager->getSubAdmin();
616
-		if (!$this->groupManager->isAdmin($loggedInUser->getUID()) && !$subAdminManager->isSubAdminOfGroup($loggedInUser, $group)) {
617
-			throw new OCSException('', 104);
618
-		}
619
-
620
-		// Check they aren't removing themselves from 'admin' or their 'subadmin; group
621
-		if ($userId === $loggedInUser->getUID()) {
622
-			if ($this->groupManager->isAdmin($loggedInUser->getUID())) {
623
-				if ($group->getGID() === 'admin') {
624
-					throw new OCSException('Cannot remove yourself from the admin group', 105);
625
-				}
626
-			} else {
627
-				// Not an admin, so the user must be a subadmin of this group, but that is not allowed.
628
-				throw new OCSException('Cannot remove yourself from this group as you are a SubAdmin', 105);
629
-			}
630
-
631
-		} else if (!$this->groupManager->isAdmin($loggedInUser->getUID())) {
632
-			/** @var IGroup[] $subAdminGroups */
633
-			$subAdminGroups = $subAdminManager->getSubAdminsGroups($loggedInUser);
634
-			$subAdminGroups = array_map(function (IGroup $subAdminGroup) {
635
-				return $subAdminGroup->getGID();
636
-			}, $subAdminGroups);
637
-			$userGroups = $this->groupManager->getUserGroupIds($targetUser);
638
-			$userSubAdminGroups = array_intersect($subAdminGroups, $userGroups);
639
-
640
-			if (count($userSubAdminGroups) <= 1) {
641
-				// Subadmin must not be able to remove a user from all their subadmin groups.
642
-				throw new OCSException('Cannot remove user from this group as this is the only remaining group you are a SubAdmin of', 105);
643
-			}
644
-		}
645
-
646
-		// Remove user from group
647
-		$group->removeUser($targetUser);
648
-		return new DataResponse();
649
-	}
650
-
651
-	/**
652
-	 * Creates a subadmin
653
-	 *
654
-	 * @PasswordConfirmationRequired
655
-	 *
656
-	 * @param string $userId
657
-	 * @param string $groupid
658
-	 * @return DataResponse
659
-	 * @throws OCSException
660
-	 */
661
-	public function addSubAdmin($userId, $groupid) {
662
-		$group = $this->groupManager->get($groupid);
663
-		$user = $this->userManager->get($userId);
664
-
665
-		// Check if the user exists
666
-		if($user === null) {
667
-			throw new OCSException('User does not exist', 101);
668
-		}
669
-		// Check if group exists
670
-		if($group === null) {
671
-			throw new OCSException('Group:'.$groupid.' does not exist',  102);
672
-		}
673
-		// Check if trying to make subadmin of admin group
674
-		if(strtolower($groupid) === 'admin') {
675
-			throw new OCSException('Cannot create subadmins for admin group', 103);
676
-		}
677
-
678
-		$subAdminManager = $this->groupManager->getSubAdmin();
679
-
680
-		// We cannot be subadmin twice
681
-		if ($subAdminManager->isSubAdminofGroup($user, $group)) {
682
-			return new DataResponse();
683
-		}
684
-		// Go
685
-		if($subAdminManager->createSubAdmin($user, $group)) {
686
-			return new DataResponse();
687
-		} else {
688
-			throw new OCSException('Unknown error occurred', 103);
689
-		}
690
-	}
691
-
692
-	/**
693
-	 * Removes a subadmin from a group
694
-	 *
695
-	 * @PasswordConfirmationRequired
696
-	 *
697
-	 * @param string $userId
698
-	 * @param string $groupid
699
-	 * @return DataResponse
700
-	 * @throws OCSException
701
-	 */
702
-	public function removeSubAdmin($userId, $groupid) {
703
-		$group = $this->groupManager->get($groupid);
704
-		$user = $this->userManager->get($userId);
705
-		$subAdminManager = $this->groupManager->getSubAdmin();
706
-
707
-		// Check if the user exists
708
-		if($user === null) {
709
-			throw new OCSException('User does not exist', 101);
710
-		}
711
-		// Check if the group exists
712
-		if($group === null) {
713
-			throw new OCSException('Group does not exist', 101);
714
-		}
715
-		// Check if they are a subadmin of this said group
716
-		if(!$subAdminManager->isSubAdminofGroup($user, $group)) {
717
-			throw new OCSException('User is not a subadmin of this group', 102);
718
-		}
719
-
720
-		// Go
721
-		if($subAdminManager->deleteSubAdmin($user, $group)) {
722
-			return new DataResponse();
723
-		} else {
724
-			throw new OCSException('Unknown error occurred', 103);
725
-		}
726
-	}
727
-
728
-	/**
729
-	 * Get the groups a user is a subadmin of
730
-	 *
731
-	 * @param string $userId
732
-	 * @return DataResponse
733
-	 * @throws OCSException
734
-	 */
735
-	public function getUserSubAdminGroups($userId) {
736
-		$user = $this->userManager->get($userId);
737
-		// Check if the user exists
738
-		if($user === null) {
739
-			throw new OCSException('User does not exist', 101);
740
-		}
741
-
742
-		// Get the subadmin groups
743
-		$groups = $this->groupManager->getSubAdmin()->getSubAdminsGroups($user);
744
-		foreach ($groups as $key => $group) {
745
-			$groups[$key] = $group->getGID();
746
-		}
747
-
748
-		if(!$groups) {
749
-			throw new OCSException('Unknown error occurred', 102);
750
-		} else {
751
-			return new DataResponse($groups);
752
-		}
753
-	}
754
-
755
-	/**
756
-	 * @param string $userId
757
-	 * @return array
758
-	 * @throws \OCP\Files\NotFoundException
759
-	 */
760
-	protected function fillStorageInfo($userId) {
761
-		try {
762
-			\OC_Util::tearDownFS();
763
-			\OC_Util::setupFS($userId);
764
-			$storage = OC_Helper::getStorageInfo('/');
765
-			$data = [
766
-				'free' => $storage['free'],
767
-				'used' => $storage['used'],
768
-				'total' => $storage['total'],
769
-				'relative' => $storage['relative'],
770
-				'quota' => $storage['quota'],
771
-			];
772
-		} catch (NotFoundException $ex) {
773
-			$data = [];
774
-		}
775
-		return $data;
776
-	}
777
-
778
-	/**
779
-	 * @NoAdminRequired
780
-	 * @PasswordConfirmationRequired
781
-	 *
782
-	 * resend welcome message
783
-	 *
784
-	 * @param string $userId
785
-	 * @return DataResponse
786
-	 * @throws OCSException
787
-	 */
788
-	public function resendWelcomeMessage($userId) {
789
-		$currentLoggedInUser = $this->userSession->getUser();
790
-
791
-		$targetUser = $this->userManager->get($userId);
792
-		if($targetUser === null) {
793
-			throw new OCSException('', \OCP\API::RESPOND_NOT_FOUND);
794
-		}
795
-
796
-		// Check if admin / subadmin
797
-		$subAdminManager = $this->groupManager->getSubAdmin();
798
-		if(!$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)
799
-			&& !$this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
800
-			// No rights
801
-			throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
802
-		}
803
-
804
-		$email = $targetUser->getEMailAddress();
805
-		if ($email === '' || $email === null) {
806
-			throw new OCSException('Email address not available', 101);
807
-		}
808
-		$username = $targetUser->getUID();
809
-		$lang = $this->config->getUserValue($username, 'core', 'lang', 'en');
810
-		if (!$this->l10nFactory->languageExists('settings', $lang)) {
811
-			$lang = 'en';
812
-		}
813
-
814
-		$l10n = $this->l10nFactory->get('settings', $lang);
815
-
816
-		try {
817
-			$this->newUserMailHelper->setL10N($l10n);
818
-			$emailTemplate = $this->newUserMailHelper->generateTemplate($targetUser, false);
819
-			$this->newUserMailHelper->sendMail($targetUser, $emailTemplate);
820
-		} catch(\Exception $e) {
821
-			$this->logger->error("Can't send new user mail to $email: " . $e->getMessage(), array('app' => 'settings'));
822
-			throw new OCSException('Sending email failed', 102);
823
-		}
824
-
825
-		return new DataResponse();
826
-	}
54
+    /** @var IUserManager */
55
+    private $userManager;
56
+    /** @var IConfig */
57
+    private $config;
58
+    /** @var IGroupManager|\OC\Group\Manager */ // FIXME Requires a method that is not on the interface
59
+    private $groupManager;
60
+    /** @var IUserSession */
61
+    private $userSession;
62
+    /** @var AccountManager */
63
+    private $accountManager;
64
+    /** @var ILogger */
65
+    private $logger;
66
+    /** @var string */
67
+    private $fromMailAddress;
68
+    /** @var IURLGenerator */
69
+    private $urlGenerator;
70
+    /** @var IMailer */
71
+    private $mailer;
72
+    /** @var Defaults */
73
+    private $defaults;
74
+    /** @var IFactory */
75
+    private $l10nFactory;
76
+    /** @var NewUserMailHelper */
77
+    private $newUserMailHelper;
78
+
79
+    /**
80
+     * @param string $appName
81
+     * @param IRequest $request
82
+     * @param IUserManager $userManager
83
+     * @param IConfig $config
84
+     * @param IGroupManager $groupManager
85
+     * @param IUserSession $userSession
86
+     * @param AccountManager $accountManager
87
+     * @param ILogger $logger
88
+     * @param string $fromMailAddress
89
+     * @param IURLGenerator $urlGenerator
90
+     * @param IMailer $mailer
91
+     * @param Defaults $defaults
92
+     * @param IFactory $l10nFactory
93
+     * @param NewUserMailHelper $newUserMailHelper
94
+     */
95
+    public function __construct($appName,
96
+                                IRequest $request,
97
+                                IUserManager $userManager,
98
+                                IConfig $config,
99
+                                IGroupManager $groupManager,
100
+                                IUserSession $userSession,
101
+                                AccountManager $accountManager,
102
+                                ILogger $logger,
103
+                                $fromMailAddress,
104
+                                IURLGenerator $urlGenerator,
105
+                                IMailer $mailer,
106
+                                Defaults $defaults,
107
+                                IFactory $l10nFactory,
108
+                                NewUserMailHelper $newUserMailHelper) {
109
+        parent::__construct($appName, $request);
110
+
111
+        $this->userManager = $userManager;
112
+        $this->config = $config;
113
+        $this->groupManager = $groupManager;
114
+        $this->userSession = $userSession;
115
+        $this->accountManager = $accountManager;
116
+        $this->logger = $logger;
117
+        $this->fromMailAddress = $fromMailAddress;
118
+        $this->urlGenerator = $urlGenerator;
119
+        $this->mailer = $mailer;
120
+        $this->defaults = $defaults;
121
+        $this->l10nFactory = $l10nFactory;
122
+        $this->newUserMailHelper = $newUserMailHelper;
123
+    }
124
+
125
+    /**
126
+     * @NoAdminRequired
127
+     *
128
+     * returns a list of users
129
+     *
130
+     * @param string $search
131
+     * @param int $limit
132
+     * @param int $offset
133
+     * @return DataResponse
134
+     */
135
+    public function getUsers($search = '', $limit = null, $offset = null) {
136
+        $user = $this->userSession->getUser();
137
+        $users = [];
138
+
139
+        // Admin? Or SubAdmin?
140
+        $uid = $user->getUID();
141
+        $subAdminManager = $this->groupManager->getSubAdmin();
142
+        if($this->groupManager->isAdmin($uid)){
143
+            $users = $this->userManager->search($search, $limit, $offset);
144
+        } else if ($subAdminManager->isSubAdmin($user)) {
145
+            $subAdminOfGroups = $subAdminManager->getSubAdminsGroups($user);
146
+            foreach ($subAdminOfGroups as $key => $group) {
147
+                $subAdminOfGroups[$key] = $group->getGID();
148
+            }
149
+
150
+            if($offset === null) {
151
+                $offset = 0;
152
+            }
153
+
154
+            $users = [];
155
+            foreach ($subAdminOfGroups as $group) {
156
+                $users = array_merge($users, $this->groupManager->displayNamesInGroup($group, $search));
157
+            }
158
+
159
+            $users = array_slice($users, $offset, $limit);
160
+        }
161
+
162
+        $users = array_keys($users);
163
+
164
+        return new DataResponse([
165
+            'users' => $users
166
+        ]);
167
+    }
168
+
169
+    /**
170
+     * @PasswordConfirmationRequired
171
+     * @NoAdminRequired
172
+     *
173
+     * @param string $userid
174
+     * @param string $password
175
+     * @param array $groups
176
+     * @return DataResponse
177
+     * @throws OCSException
178
+     */
179
+    public function addUser($userid, $password, $groups = null) {
180
+        $user = $this->userSession->getUser();
181
+        $isAdmin = $this->groupManager->isAdmin($user->getUID());
182
+        $subAdminManager = $this->groupManager->getSubAdmin();
183
+
184
+        if($this->userManager->userExists($userid)) {
185
+            $this->logger->error('Failed addUser attempt: User already exists.', ['app' => 'ocs_api']);
186
+            throw new OCSException('User already exists', 102);
187
+        }
188
+
189
+        if(is_array($groups)) {
190
+            foreach ($groups as $group) {
191
+                if(!$this->groupManager->groupExists($group)) {
192
+                    throw new OCSException('group '.$group.' does not exist', 104);
193
+                }
194
+                if(!$isAdmin && !$subAdminManager->isSubAdminofGroup($user, $this->groupManager->get($group))) {
195
+                    throw new OCSException('insufficient privileges for group '. $group, 105);
196
+                }
197
+            }
198
+        } else {
199
+            if(!$isAdmin) {
200
+                throw new OCSException('no group specified (required for subadmins)', 106);
201
+            }
202
+        }
203
+
204
+        try {
205
+            $newUser = $this->userManager->createUser($userid, $password);
206
+            $this->logger->info('Successful addUser call with userid: '.$userid, ['app' => 'ocs_api']);
207
+
208
+            if (is_array($groups)) {
209
+                foreach ($groups as $group) {
210
+                    $this->groupManager->get($group)->addUser($newUser);
211
+                    $this->logger->info('Added userid '.$userid.' to group '.$group, ['app' => 'ocs_api']);
212
+                }
213
+            }
214
+            return new DataResponse();
215
+        } catch (\Exception $e) {
216
+            $this->logger->error('Failed addUser attempt with exception: '.$e->getMessage(), ['app' => 'ocs_api']);
217
+            throw new OCSException('Bad request', 101);
218
+        }
219
+    }
220
+
221
+    /**
222
+     * @NoAdminRequired
223
+     * @NoSubAdminRequired
224
+     *
225
+     * gets user info
226
+     *
227
+     * @param string $userId
228
+     * @return DataResponse
229
+     * @throws OCSException
230
+     */
231
+    public function getUser($userId) {
232
+        $data = $this->getUserData($userId);
233
+        return new DataResponse($data);
234
+    }
235
+
236
+    /**
237
+     * @NoAdminRequired
238
+     * @NoSubAdminRequired
239
+     *
240
+     * gets user info from the currently logged in user
241
+     *
242
+     * @return DataResponse
243
+     * @throws OCSException
244
+     */
245
+    public function getCurrentUser() {
246
+        $user = $this->userSession->getUser();
247
+        if ($user) {
248
+            $data =  $this->getUserData($user->getUID());
249
+            // rename "displayname" to "display-name" only for this call to keep
250
+            // the API stable.
251
+            $data['display-name'] = $data['displayname'];
252
+            unset($data['displayname']);
253
+            return new DataResponse($data);
254
+
255
+        }
256
+
257
+        throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
258
+    }
259
+
260
+    /**
261
+     * creates a array with all user data
262
+     *
263
+     * @param $userId
264
+     * @return array
265
+     * @throws OCSException
266
+     */
267
+    protected function getUserData($userId) {
268
+        $currentLoggedInUser = $this->userSession->getUser();
269
+
270
+        $data = [];
271
+
272
+        // Check if the target user exists
273
+        $targetUserObject = $this->userManager->get($userId);
274
+        if($targetUserObject === null) {
275
+            throw new OCSException('The requested user could not be found', \OCP\API::RESPOND_NOT_FOUND);
276
+        }
277
+
278
+        // Admin? Or SubAdmin?
279
+        if($this->groupManager->isAdmin($currentLoggedInUser->getUID())
280
+            || $this->groupManager->getSubAdmin()->isUserAccessible($currentLoggedInUser, $targetUserObject)) {
281
+            $data['enabled'] = $this->config->getUserValue($userId, 'core', 'enabled', 'true');
282
+        } else {
283
+            // Check they are looking up themselves
284
+            if($currentLoggedInUser->getUID() !== $userId) {
285
+                throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
286
+            }
287
+        }
288
+
289
+        $userAccount = $this->accountManager->getUser($targetUserObject);
290
+        $groups = $this->groupManager->getUserGroups($targetUserObject);
291
+        $gids = [];
292
+        foreach ($groups as $group) {
293
+            $gids[] = $group->getDisplayName();
294
+        }
295
+
296
+        // Find the data
297
+        $data['id'] = $targetUserObject->getUID();
298
+        $data['quota'] = $this->fillStorageInfo($userId);
299
+        $data[AccountManager::PROPERTY_EMAIL] = $targetUserObject->getEMailAddress();
300
+        $data[AccountManager::PROPERTY_DISPLAYNAME] = $targetUserObject->getDisplayName();
301
+        $data[AccountManager::PROPERTY_PHONE] = $userAccount[AccountManager::PROPERTY_PHONE]['value'];
302
+        $data[AccountManager::PROPERTY_ADDRESS] = $userAccount[AccountManager::PROPERTY_ADDRESS]['value'];
303
+        $data[AccountManager::PROPERTY_WEBSITE] = $userAccount[AccountManager::PROPERTY_WEBSITE]['value'];
304
+        $data[AccountManager::PROPERTY_TWITTER] = $userAccount[AccountManager::PROPERTY_TWITTER]['value'];
305
+        $data['groups'] = $gids;
306
+
307
+        return $data;
308
+    }
309
+
310
+    /**
311
+     * @NoAdminRequired
312
+     * @NoSubAdminRequired
313
+     * @PasswordConfirmationRequired
314
+     *
315
+     * edit users
316
+     *
317
+     * @param string $userId
318
+     * @param string $key
319
+     * @param string $value
320
+     * @return DataResponse
321
+     * @throws OCSException
322
+     * @throws OCSForbiddenException
323
+     */
324
+    public function editUser($userId, $key, $value) {
325
+        $currentLoggedInUser = $this->userSession->getUser();
326
+
327
+        $targetUser = $this->userManager->get($userId);
328
+        if($targetUser === null) {
329
+            throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
330
+        }
331
+
332
+        $permittedFields = [];
333
+        if($userId === $currentLoggedInUser->getUID()) {
334
+            // Editing self (display, email)
335
+            $permittedFields[] = 'display';
336
+            $permittedFields[] = AccountManager::PROPERTY_DISPLAYNAME;
337
+            $permittedFields[] = AccountManager::PROPERTY_EMAIL;
338
+            $permittedFields[] = 'password';
339
+            $permittedFields[] = AccountManager::PROPERTY_PHONE;
340
+            $permittedFields[] = AccountManager::PROPERTY_ADDRESS;
341
+            $permittedFields[] = AccountManager::PROPERTY_WEBSITE;
342
+            $permittedFields[] = AccountManager::PROPERTY_TWITTER;
343
+            // If admin they can edit their own quota
344
+            if($this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
345
+                $permittedFields[] = 'quota';
346
+            }
347
+        } else {
348
+            // Check if admin / subadmin
349
+            $subAdminManager = $this->groupManager->getSubAdmin();
350
+            if($subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)
351
+            || $this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
352
+                // They have permissions over the user
353
+                $permittedFields[] = 'display';
354
+                $permittedFields[] = AccountManager::PROPERTY_DISPLAYNAME;
355
+                $permittedFields[] = AccountManager::PROPERTY_EMAIL;
356
+                $permittedFields[] = 'password';
357
+                $permittedFields[] = AccountManager::PROPERTY_PHONE;
358
+                $permittedFields[] = AccountManager::PROPERTY_ADDRESS;
359
+                $permittedFields[] = AccountManager::PROPERTY_WEBSITE;
360
+                $permittedFields[] = AccountManager::PROPERTY_TWITTER;
361
+                $permittedFields[] = 'quota';
362
+            } else {
363
+                // No rights
364
+                throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
365
+            }
366
+        }
367
+        // Check if permitted to edit this field
368
+        if(!in_array($key, $permittedFields)) {
369
+            throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
370
+        }
371
+        // Process the edit
372
+        switch($key) {
373
+            case 'display':
374
+            case AccountManager::PROPERTY_DISPLAYNAME:
375
+                $targetUser->setDisplayName($value);
376
+                break;
377
+            case 'quota':
378
+                $quota = $value;
379
+                if($quota !== 'none' && $quota !== 'default') {
380
+                    if (is_numeric($quota)) {
381
+                        $quota = (float) $quota;
382
+                    } else {
383
+                        $quota = \OCP\Util::computerFileSize($quota);
384
+                    }
385
+                    if ($quota === false) {
386
+                        throw new OCSException('Invalid quota value '.$value, 103);
387
+                    }
388
+                    if($quota === 0) {
389
+                        $quota = 'default';
390
+                    }else if($quota === -1) {
391
+                        $quota = 'none';
392
+                    } else {
393
+                        $quota = \OCP\Util::humanFileSize($quota);
394
+                    }
395
+                }
396
+                $targetUser->setQuota($quota);
397
+                break;
398
+            case 'password':
399
+                $targetUser->setPassword($value);
400
+                break;
401
+            case AccountManager::PROPERTY_EMAIL:
402
+                if(filter_var($value, FILTER_VALIDATE_EMAIL)) {
403
+                    $targetUser->setEMailAddress($value);
404
+                } else {
405
+                    throw new OCSException('', 102);
406
+                }
407
+                break;
408
+            case AccountManager::PROPERTY_PHONE:
409
+            case AccountManager::PROPERTY_ADDRESS:
410
+            case AccountManager::PROPERTY_WEBSITE:
411
+            case AccountManager::PROPERTY_TWITTER:
412
+                $userAccount = $this->accountManager->getUser($targetUser);
413
+                if ($userAccount[$key]['value'] !== $value) {
414
+                    $userAccount[$key]['value'] = $value;
415
+                    $this->accountManager->updateUser($targetUser, $userAccount);
416
+                }
417
+                break;
418
+            default:
419
+                throw new OCSException('', 103);
420
+        }
421
+        return new DataResponse();
422
+    }
423
+
424
+    /**
425
+     * @PasswordConfirmationRequired
426
+     * @NoAdminRequired
427
+     *
428
+     * @param string $userId
429
+     * @return DataResponse
430
+     * @throws OCSException
431
+     * @throws OCSForbiddenException
432
+     */
433
+    public function deleteUser($userId) {
434
+        $currentLoggedInUser = $this->userSession->getUser();
435
+
436
+        $targetUser = $this->userManager->get($userId);
437
+
438
+        if($targetUser === null || $targetUser->getUID() === $currentLoggedInUser->getUID()) {
439
+            throw new OCSException('', 101);
440
+        }
441
+
442
+        // If not permitted
443
+        $subAdminManager = $this->groupManager->getSubAdmin();
444
+        if(!$this->groupManager->isAdmin($currentLoggedInUser->getUID()) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) {
445
+            throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
446
+        }
447
+
448
+        // Go ahead with the delete
449
+        if($targetUser->delete()) {
450
+            return new DataResponse();
451
+        } else {
452
+            throw new OCSException('', 101);
453
+        }
454
+    }
455
+
456
+    /**
457
+     * @PasswordConfirmationRequired
458
+     * @NoAdminRequired
459
+     *
460
+     * @param string $userId
461
+     * @return DataResponse
462
+     * @throws OCSException
463
+     * @throws OCSForbiddenException
464
+     */
465
+    public function disableUser($userId) {
466
+        return $this->setEnabled($userId, false);
467
+    }
468
+
469
+    /**
470
+     * @PasswordConfirmationRequired
471
+     * @NoAdminRequired
472
+     *
473
+     * @param string $userId
474
+     * @return DataResponse
475
+     * @throws OCSException
476
+     * @throws OCSForbiddenException
477
+     */
478
+    public function enableUser($userId) {
479
+        return $this->setEnabled($userId, true);
480
+    }
481
+
482
+    /**
483
+     * @param string $userId
484
+     * @param bool $value
485
+     * @return DataResponse
486
+     * @throws OCSException
487
+     * @throws OCSForbiddenException
488
+     */
489
+    private function setEnabled($userId, $value) {
490
+        $currentLoggedInUser = $this->userSession->getUser();
491
+
492
+        $targetUser = $this->userManager->get($userId);
493
+        if($targetUser === null || $targetUser->getUID() === $currentLoggedInUser->getUID()) {
494
+            throw new OCSException('', 101);
495
+        }
496
+
497
+        // If not permitted
498
+        $subAdminManager = $this->groupManager->getSubAdmin();
499
+        if(!$this->groupManager->isAdmin($currentLoggedInUser->getUID()) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) {
500
+            throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
501
+        }
502
+
503
+        // enable/disable the user now
504
+        $targetUser->setEnabled($value);
505
+        return new DataResponse();
506
+    }
507
+
508
+    /**
509
+     * @NoAdminRequired
510
+     * @NoSubAdminRequired
511
+     *
512
+     * @param string $userId
513
+     * @return DataResponse
514
+     * @throws OCSException
515
+     */
516
+    public function getUsersGroups($userId) {
517
+        $loggedInUser = $this->userSession->getUser();
518
+
519
+        $targetUser = $this->userManager->get($userId);
520
+        if($targetUser === null) {
521
+            throw new OCSException('', \OCP\API::RESPOND_NOT_FOUND);
522
+        }
523
+
524
+        if($targetUser->getUID() === $loggedInUser->getUID() || $this->groupManager->isAdmin($loggedInUser->getUID())) {
525
+            // Self lookup or admin lookup
526
+            return new DataResponse([
527
+                'groups' => $this->groupManager->getUserGroupIds($targetUser)
528
+            ]);
529
+        } else {
530
+            $subAdminManager = $this->groupManager->getSubAdmin();
531
+
532
+            // Looking up someone else
533
+            if($subAdminManager->isUserAccessible($loggedInUser, $targetUser)) {
534
+                // Return the group that the method caller is subadmin of for the user in question
535
+                /** @var IGroup[] $getSubAdminsGroups */
536
+                $getSubAdminsGroups = $subAdminManager->getSubAdminsGroups($loggedInUser);
537
+                foreach ($getSubAdminsGroups as $key => $group) {
538
+                    $getSubAdminsGroups[$key] = $group->getGID();
539
+                }
540
+                $groups = array_intersect(
541
+                    $getSubAdminsGroups,
542
+                    $this->groupManager->getUserGroupIds($targetUser)
543
+                );
544
+                return new DataResponse(['groups' => $groups]);
545
+            } else {
546
+                // Not permitted
547
+                throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
548
+            }
549
+        }
550
+
551
+    }
552
+
553
+    /**
554
+     * @PasswordConfirmationRequired
555
+     * @NoAdminRequired
556
+     *
557
+     * @param string $userId
558
+     * @param string $groupid
559
+     * @return DataResponse
560
+     * @throws OCSException
561
+     */
562
+    public function addToGroup($userId, $groupid = '') {
563
+        if($groupid === '') {
564
+            throw new OCSException('', 101);
565
+        }
566
+
567
+        $group = $this->groupManager->get($groupid);
568
+        $targetUser = $this->userManager->get($userId);
569
+        if($group === null) {
570
+            throw new OCSException('', 102);
571
+        }
572
+        if($targetUser === null) {
573
+            throw new OCSException('', 103);
574
+        }
575
+
576
+        // If they're not an admin, check they are a subadmin of the group in question
577
+        $loggedInUser = $this->userSession->getUser();
578
+        $subAdminManager = $this->groupManager->getSubAdmin();
579
+        if (!$this->groupManager->isAdmin($loggedInUser->getUID()) && !$subAdminManager->isSubAdminOfGroup($loggedInUser, $group)) {
580
+            throw new OCSException('', 104);
581
+        }
582
+
583
+        // Add user to group
584
+        $group->addUser($targetUser);
585
+        return new DataResponse();
586
+    }
587
+
588
+    /**
589
+     * @PasswordConfirmationRequired
590
+     * @NoAdminRequired
591
+     *
592
+     * @param string $userId
593
+     * @param string $groupid
594
+     * @return DataResponse
595
+     * @throws OCSException
596
+     */
597
+    public function removeFromGroup($userId, $groupid) {
598
+        $loggedInUser = $this->userSession->getUser();
599
+
600
+        if($groupid === null) {
601
+            throw new OCSException('', 101);
602
+        }
603
+
604
+        $group = $this->groupManager->get($groupid);
605
+        if($group === null) {
606
+            throw new OCSException('', 102);
607
+        }
608
+
609
+        $targetUser = $this->userManager->get($userId);
610
+        if($targetUser === null) {
611
+            throw new OCSException('', 103);
612
+        }
613
+
614
+        // If they're not an admin, check they are a subadmin of the group in question
615
+        $subAdminManager = $this->groupManager->getSubAdmin();
616
+        if (!$this->groupManager->isAdmin($loggedInUser->getUID()) && !$subAdminManager->isSubAdminOfGroup($loggedInUser, $group)) {
617
+            throw new OCSException('', 104);
618
+        }
619
+
620
+        // Check they aren't removing themselves from 'admin' or their 'subadmin; group
621
+        if ($userId === $loggedInUser->getUID()) {
622
+            if ($this->groupManager->isAdmin($loggedInUser->getUID())) {
623
+                if ($group->getGID() === 'admin') {
624
+                    throw new OCSException('Cannot remove yourself from the admin group', 105);
625
+                }
626
+            } else {
627
+                // Not an admin, so the user must be a subadmin of this group, but that is not allowed.
628
+                throw new OCSException('Cannot remove yourself from this group as you are a SubAdmin', 105);
629
+            }
630
+
631
+        } else if (!$this->groupManager->isAdmin($loggedInUser->getUID())) {
632
+            /** @var IGroup[] $subAdminGroups */
633
+            $subAdminGroups = $subAdminManager->getSubAdminsGroups($loggedInUser);
634
+            $subAdminGroups = array_map(function (IGroup $subAdminGroup) {
635
+                return $subAdminGroup->getGID();
636
+            }, $subAdminGroups);
637
+            $userGroups = $this->groupManager->getUserGroupIds($targetUser);
638
+            $userSubAdminGroups = array_intersect($subAdminGroups, $userGroups);
639
+
640
+            if (count($userSubAdminGroups) <= 1) {
641
+                // Subadmin must not be able to remove a user from all their subadmin groups.
642
+                throw new OCSException('Cannot remove user from this group as this is the only remaining group you are a SubAdmin of', 105);
643
+            }
644
+        }
645
+
646
+        // Remove user from group
647
+        $group->removeUser($targetUser);
648
+        return new DataResponse();
649
+    }
650
+
651
+    /**
652
+     * Creates a subadmin
653
+     *
654
+     * @PasswordConfirmationRequired
655
+     *
656
+     * @param string $userId
657
+     * @param string $groupid
658
+     * @return DataResponse
659
+     * @throws OCSException
660
+     */
661
+    public function addSubAdmin($userId, $groupid) {
662
+        $group = $this->groupManager->get($groupid);
663
+        $user = $this->userManager->get($userId);
664
+
665
+        // Check if the user exists
666
+        if($user === null) {
667
+            throw new OCSException('User does not exist', 101);
668
+        }
669
+        // Check if group exists
670
+        if($group === null) {
671
+            throw new OCSException('Group:'.$groupid.' does not exist',  102);
672
+        }
673
+        // Check if trying to make subadmin of admin group
674
+        if(strtolower($groupid) === 'admin') {
675
+            throw new OCSException('Cannot create subadmins for admin group', 103);
676
+        }
677
+
678
+        $subAdminManager = $this->groupManager->getSubAdmin();
679
+
680
+        // We cannot be subadmin twice
681
+        if ($subAdminManager->isSubAdminofGroup($user, $group)) {
682
+            return new DataResponse();
683
+        }
684
+        // Go
685
+        if($subAdminManager->createSubAdmin($user, $group)) {
686
+            return new DataResponse();
687
+        } else {
688
+            throw new OCSException('Unknown error occurred', 103);
689
+        }
690
+    }
691
+
692
+    /**
693
+     * Removes a subadmin from a group
694
+     *
695
+     * @PasswordConfirmationRequired
696
+     *
697
+     * @param string $userId
698
+     * @param string $groupid
699
+     * @return DataResponse
700
+     * @throws OCSException
701
+     */
702
+    public function removeSubAdmin($userId, $groupid) {
703
+        $group = $this->groupManager->get($groupid);
704
+        $user = $this->userManager->get($userId);
705
+        $subAdminManager = $this->groupManager->getSubAdmin();
706
+
707
+        // Check if the user exists
708
+        if($user === null) {
709
+            throw new OCSException('User does not exist', 101);
710
+        }
711
+        // Check if the group exists
712
+        if($group === null) {
713
+            throw new OCSException('Group does not exist', 101);
714
+        }
715
+        // Check if they are a subadmin of this said group
716
+        if(!$subAdminManager->isSubAdminofGroup($user, $group)) {
717
+            throw new OCSException('User is not a subadmin of this group', 102);
718
+        }
719
+
720
+        // Go
721
+        if($subAdminManager->deleteSubAdmin($user, $group)) {
722
+            return new DataResponse();
723
+        } else {
724
+            throw new OCSException('Unknown error occurred', 103);
725
+        }
726
+    }
727
+
728
+    /**
729
+     * Get the groups a user is a subadmin of
730
+     *
731
+     * @param string $userId
732
+     * @return DataResponse
733
+     * @throws OCSException
734
+     */
735
+    public function getUserSubAdminGroups($userId) {
736
+        $user = $this->userManager->get($userId);
737
+        // Check if the user exists
738
+        if($user === null) {
739
+            throw new OCSException('User does not exist', 101);
740
+        }
741
+
742
+        // Get the subadmin groups
743
+        $groups = $this->groupManager->getSubAdmin()->getSubAdminsGroups($user);
744
+        foreach ($groups as $key => $group) {
745
+            $groups[$key] = $group->getGID();
746
+        }
747
+
748
+        if(!$groups) {
749
+            throw new OCSException('Unknown error occurred', 102);
750
+        } else {
751
+            return new DataResponse($groups);
752
+        }
753
+    }
754
+
755
+    /**
756
+     * @param string $userId
757
+     * @return array
758
+     * @throws \OCP\Files\NotFoundException
759
+     */
760
+    protected function fillStorageInfo($userId) {
761
+        try {
762
+            \OC_Util::tearDownFS();
763
+            \OC_Util::setupFS($userId);
764
+            $storage = OC_Helper::getStorageInfo('/');
765
+            $data = [
766
+                'free' => $storage['free'],
767
+                'used' => $storage['used'],
768
+                'total' => $storage['total'],
769
+                'relative' => $storage['relative'],
770
+                'quota' => $storage['quota'],
771
+            ];
772
+        } catch (NotFoundException $ex) {
773
+            $data = [];
774
+        }
775
+        return $data;
776
+    }
777
+
778
+    /**
779
+     * @NoAdminRequired
780
+     * @PasswordConfirmationRequired
781
+     *
782
+     * resend welcome message
783
+     *
784
+     * @param string $userId
785
+     * @return DataResponse
786
+     * @throws OCSException
787
+     */
788
+    public function resendWelcomeMessage($userId) {
789
+        $currentLoggedInUser = $this->userSession->getUser();
790
+
791
+        $targetUser = $this->userManager->get($userId);
792
+        if($targetUser === null) {
793
+            throw new OCSException('', \OCP\API::RESPOND_NOT_FOUND);
794
+        }
795
+
796
+        // Check if admin / subadmin
797
+        $subAdminManager = $this->groupManager->getSubAdmin();
798
+        if(!$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)
799
+            && !$this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
800
+            // No rights
801
+            throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
802
+        }
803
+
804
+        $email = $targetUser->getEMailAddress();
805
+        if ($email === '' || $email === null) {
806
+            throw new OCSException('Email address not available', 101);
807
+        }
808
+        $username = $targetUser->getUID();
809
+        $lang = $this->config->getUserValue($username, 'core', 'lang', 'en');
810
+        if (!$this->l10nFactory->languageExists('settings', $lang)) {
811
+            $lang = 'en';
812
+        }
813
+
814
+        $l10n = $this->l10nFactory->get('settings', $lang);
815
+
816
+        try {
817
+            $this->newUserMailHelper->setL10N($l10n);
818
+            $emailTemplate = $this->newUserMailHelper->generateTemplate($targetUser, false);
819
+            $this->newUserMailHelper->sendMail($targetUser, $emailTemplate);
820
+        } catch(\Exception $e) {
821
+            $this->logger->error("Can't send new user mail to $email: " . $e->getMessage(), array('app' => 'settings'));
822
+            throw new OCSException('Sending email failed', 102);
823
+        }
824
+
825
+        return new DataResponse();
826
+    }
827 827
 }
Please login to merge, or discard this patch.
Spacing   +52 added lines, -52 removed lines patch added patch discarded remove patch
@@ -139,7 +139,7 @@  discard block
 block discarded – undo
139 139
 		// Admin? Or SubAdmin?
140 140
 		$uid = $user->getUID();
141 141
 		$subAdminManager = $this->groupManager->getSubAdmin();
142
-		if($this->groupManager->isAdmin($uid)){
142
+		if ($this->groupManager->isAdmin($uid)) {
143 143
 			$users = $this->userManager->search($search, $limit, $offset);
144 144
 		} else if ($subAdminManager->isSubAdmin($user)) {
145 145
 			$subAdminOfGroups = $subAdminManager->getSubAdminsGroups($user);
@@ -147,7 +147,7 @@  discard block
 block discarded – undo
147 147
 				$subAdminOfGroups[$key] = $group->getGID();
148 148
 			}
149 149
 
150
-			if($offset === null) {
150
+			if ($offset === null) {
151 151
 				$offset = 0;
152 152
 			}
153 153
 
@@ -181,22 +181,22 @@  discard block
 block discarded – undo
181 181
 		$isAdmin = $this->groupManager->isAdmin($user->getUID());
182 182
 		$subAdminManager = $this->groupManager->getSubAdmin();
183 183
 
184
-		if($this->userManager->userExists($userid)) {
184
+		if ($this->userManager->userExists($userid)) {
185 185
 			$this->logger->error('Failed addUser attempt: User already exists.', ['app' => 'ocs_api']);
186 186
 			throw new OCSException('User already exists', 102);
187 187
 		}
188 188
 
189
-		if(is_array($groups)) {
189
+		if (is_array($groups)) {
190 190
 			foreach ($groups as $group) {
191
-				if(!$this->groupManager->groupExists($group)) {
191
+				if (!$this->groupManager->groupExists($group)) {
192 192
 					throw new OCSException('group '.$group.' does not exist', 104);
193 193
 				}
194
-				if(!$isAdmin && !$subAdminManager->isSubAdminofGroup($user, $this->groupManager->get($group))) {
195
-					throw new OCSException('insufficient privileges for group '. $group, 105);
194
+				if (!$isAdmin && !$subAdminManager->isSubAdminofGroup($user, $this->groupManager->get($group))) {
195
+					throw new OCSException('insufficient privileges for group '.$group, 105);
196 196
 				}
197 197
 			}
198 198
 		} else {
199
-			if(!$isAdmin) {
199
+			if (!$isAdmin) {
200 200
 				throw new OCSException('no group specified (required for subadmins)', 106);
201 201
 			}
202 202
 		}
@@ -245,7 +245,7 @@  discard block
 block discarded – undo
245 245
 	public function getCurrentUser() {
246 246
 		$user = $this->userSession->getUser();
247 247
 		if ($user) {
248
-			$data =  $this->getUserData($user->getUID());
248
+			$data = $this->getUserData($user->getUID());
249 249
 			// rename "displayname" to "display-name" only for this call to keep
250 250
 			// the API stable.
251 251
 			$data['display-name'] = $data['displayname'];
@@ -271,17 +271,17 @@  discard block
 block discarded – undo
271 271
 
272 272
 		// Check if the target user exists
273 273
 		$targetUserObject = $this->userManager->get($userId);
274
-		if($targetUserObject === null) {
274
+		if ($targetUserObject === null) {
275 275
 			throw new OCSException('The requested user could not be found', \OCP\API::RESPOND_NOT_FOUND);
276 276
 		}
277 277
 
278 278
 		// Admin? Or SubAdmin?
279
-		if($this->groupManager->isAdmin($currentLoggedInUser->getUID())
279
+		if ($this->groupManager->isAdmin($currentLoggedInUser->getUID())
280 280
 			|| $this->groupManager->getSubAdmin()->isUserAccessible($currentLoggedInUser, $targetUserObject)) {
281 281
 			$data['enabled'] = $this->config->getUserValue($userId, 'core', 'enabled', 'true');
282 282
 		} else {
283 283
 			// Check they are looking up themselves
284
-			if($currentLoggedInUser->getUID() !== $userId) {
284
+			if ($currentLoggedInUser->getUID() !== $userId) {
285 285
 				throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
286 286
 			}
287 287
 		}
@@ -325,12 +325,12 @@  discard block
 block discarded – undo
325 325
 		$currentLoggedInUser = $this->userSession->getUser();
326 326
 
327 327
 		$targetUser = $this->userManager->get($userId);
328
-		if($targetUser === null) {
328
+		if ($targetUser === null) {
329 329
 			throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
330 330
 		}
331 331
 
332 332
 		$permittedFields = [];
333
-		if($userId === $currentLoggedInUser->getUID()) {
333
+		if ($userId === $currentLoggedInUser->getUID()) {
334 334
 			// Editing self (display, email)
335 335
 			$permittedFields[] = 'display';
336 336
 			$permittedFields[] = AccountManager::PROPERTY_DISPLAYNAME;
@@ -341,13 +341,13 @@  discard block
 block discarded – undo
341 341
 			$permittedFields[] = AccountManager::PROPERTY_WEBSITE;
342 342
 			$permittedFields[] = AccountManager::PROPERTY_TWITTER;
343 343
 			// If admin they can edit their own quota
344
-			if($this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
344
+			if ($this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
345 345
 				$permittedFields[] = 'quota';
346 346
 			}
347 347
 		} else {
348 348
 			// Check if admin / subadmin
349 349
 			$subAdminManager = $this->groupManager->getSubAdmin();
350
-			if($subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)
350
+			if ($subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)
351 351
 			|| $this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
352 352
 				// They have permissions over the user
353 353
 				$permittedFields[] = 'display';
@@ -365,18 +365,18 @@  discard block
 block discarded – undo
365 365
 			}
366 366
 		}
367 367
 		// Check if permitted to edit this field
368
-		if(!in_array($key, $permittedFields)) {
368
+		if (!in_array($key, $permittedFields)) {
369 369
 			throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
370 370
 		}
371 371
 		// Process the edit
372
-		switch($key) {
372
+		switch ($key) {
373 373
 			case 'display':
374 374
 			case AccountManager::PROPERTY_DISPLAYNAME:
375 375
 				$targetUser->setDisplayName($value);
376 376
 				break;
377 377
 			case 'quota':
378 378
 				$quota = $value;
379
-				if($quota !== 'none' && $quota !== 'default') {
379
+				if ($quota !== 'none' && $quota !== 'default') {
380 380
 					if (is_numeric($quota)) {
381 381
 						$quota = (float) $quota;
382 382
 					} else {
@@ -385,9 +385,9 @@  discard block
 block discarded – undo
385 385
 					if ($quota === false) {
386 386
 						throw new OCSException('Invalid quota value '.$value, 103);
387 387
 					}
388
-					if($quota === 0) {
388
+					if ($quota === 0) {
389 389
 						$quota = 'default';
390
-					}else if($quota === -1) {
390
+					} else if ($quota === -1) {
391 391
 						$quota = 'none';
392 392
 					} else {
393 393
 						$quota = \OCP\Util::humanFileSize($quota);
@@ -399,7 +399,7 @@  discard block
 block discarded – undo
399 399
 				$targetUser->setPassword($value);
400 400
 				break;
401 401
 			case AccountManager::PROPERTY_EMAIL:
402
-				if(filter_var($value, FILTER_VALIDATE_EMAIL)) {
402
+				if (filter_var($value, FILTER_VALIDATE_EMAIL)) {
403 403
 					$targetUser->setEMailAddress($value);
404 404
 				} else {
405 405
 					throw new OCSException('', 102);
@@ -435,18 +435,18 @@  discard block
 block discarded – undo
435 435
 
436 436
 		$targetUser = $this->userManager->get($userId);
437 437
 
438
-		if($targetUser === null || $targetUser->getUID() === $currentLoggedInUser->getUID()) {
438
+		if ($targetUser === null || $targetUser->getUID() === $currentLoggedInUser->getUID()) {
439 439
 			throw new OCSException('', 101);
440 440
 		}
441 441
 
442 442
 		// If not permitted
443 443
 		$subAdminManager = $this->groupManager->getSubAdmin();
444
-		if(!$this->groupManager->isAdmin($currentLoggedInUser->getUID()) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) {
444
+		if (!$this->groupManager->isAdmin($currentLoggedInUser->getUID()) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) {
445 445
 			throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
446 446
 		}
447 447
 
448 448
 		// Go ahead with the delete
449
-		if($targetUser->delete()) {
449
+		if ($targetUser->delete()) {
450 450
 			return new DataResponse();
451 451
 		} else {
452 452
 			throw new OCSException('', 101);
@@ -490,13 +490,13 @@  discard block
 block discarded – undo
490 490
 		$currentLoggedInUser = $this->userSession->getUser();
491 491
 
492 492
 		$targetUser = $this->userManager->get($userId);
493
-		if($targetUser === null || $targetUser->getUID() === $currentLoggedInUser->getUID()) {
493
+		if ($targetUser === null || $targetUser->getUID() === $currentLoggedInUser->getUID()) {
494 494
 			throw new OCSException('', 101);
495 495
 		}
496 496
 
497 497
 		// If not permitted
498 498
 		$subAdminManager = $this->groupManager->getSubAdmin();
499
-		if(!$this->groupManager->isAdmin($currentLoggedInUser->getUID()) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) {
499
+		if (!$this->groupManager->isAdmin($currentLoggedInUser->getUID()) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) {
500 500
 			throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
501 501
 		}
502 502
 
@@ -517,11 +517,11 @@  discard block
 block discarded – undo
517 517
 		$loggedInUser = $this->userSession->getUser();
518 518
 
519 519
 		$targetUser = $this->userManager->get($userId);
520
-		if($targetUser === null) {
520
+		if ($targetUser === null) {
521 521
 			throw new OCSException('', \OCP\API::RESPOND_NOT_FOUND);
522 522
 		}
523 523
 
524
-		if($targetUser->getUID() === $loggedInUser->getUID() || $this->groupManager->isAdmin($loggedInUser->getUID())) {
524
+		if ($targetUser->getUID() === $loggedInUser->getUID() || $this->groupManager->isAdmin($loggedInUser->getUID())) {
525 525
 			// Self lookup or admin lookup
526 526
 			return new DataResponse([
527 527
 				'groups' => $this->groupManager->getUserGroupIds($targetUser)
@@ -530,7 +530,7 @@  discard block
 block discarded – undo
530 530
 			$subAdminManager = $this->groupManager->getSubAdmin();
531 531
 
532 532
 			// Looking up someone else
533
-			if($subAdminManager->isUserAccessible($loggedInUser, $targetUser)) {
533
+			if ($subAdminManager->isUserAccessible($loggedInUser, $targetUser)) {
534 534
 				// Return the group that the method caller is subadmin of for the user in question
535 535
 				/** @var IGroup[] $getSubAdminsGroups */
536 536
 				$getSubAdminsGroups = $subAdminManager->getSubAdminsGroups($loggedInUser);
@@ -560,16 +560,16 @@  discard block
 block discarded – undo
560 560
 	 * @throws OCSException
561 561
 	 */
562 562
 	public function addToGroup($userId, $groupid = '') {
563
-		if($groupid === '') {
563
+		if ($groupid === '') {
564 564
 			throw new OCSException('', 101);
565 565
 		}
566 566
 
567 567
 		$group = $this->groupManager->get($groupid);
568 568
 		$targetUser = $this->userManager->get($userId);
569
-		if($group === null) {
569
+		if ($group === null) {
570 570
 			throw new OCSException('', 102);
571 571
 		}
572
-		if($targetUser === null) {
572
+		if ($targetUser === null) {
573 573
 			throw new OCSException('', 103);
574 574
 		}
575 575
 
@@ -597,17 +597,17 @@  discard block
 block discarded – undo
597 597
 	public function removeFromGroup($userId, $groupid) {
598 598
 		$loggedInUser = $this->userSession->getUser();
599 599
 
600
-		if($groupid === null) {
600
+		if ($groupid === null) {
601 601
 			throw new OCSException('', 101);
602 602
 		}
603 603
 
604 604
 		$group = $this->groupManager->get($groupid);
605
-		if($group === null) {
605
+		if ($group === null) {
606 606
 			throw new OCSException('', 102);
607 607
 		}
608 608
 
609 609
 		$targetUser = $this->userManager->get($userId);
610
-		if($targetUser === null) {
610
+		if ($targetUser === null) {
611 611
 			throw new OCSException('', 103);
612 612
 		}
613 613
 
@@ -631,7 +631,7 @@  discard block
 block discarded – undo
631 631
 		} else if (!$this->groupManager->isAdmin($loggedInUser->getUID())) {
632 632
 			/** @var IGroup[] $subAdminGroups */
633 633
 			$subAdminGroups = $subAdminManager->getSubAdminsGroups($loggedInUser);
634
-			$subAdminGroups = array_map(function (IGroup $subAdminGroup) {
634
+			$subAdminGroups = array_map(function(IGroup $subAdminGroup) {
635 635
 				return $subAdminGroup->getGID();
636 636
 			}, $subAdminGroups);
637 637
 			$userGroups = $this->groupManager->getUserGroupIds($targetUser);
@@ -663,15 +663,15 @@  discard block
 block discarded – undo
663 663
 		$user = $this->userManager->get($userId);
664 664
 
665 665
 		// Check if the user exists
666
-		if($user === null) {
666
+		if ($user === null) {
667 667
 			throw new OCSException('User does not exist', 101);
668 668
 		}
669 669
 		// Check if group exists
670
-		if($group === null) {
671
-			throw new OCSException('Group:'.$groupid.' does not exist',  102);
670
+		if ($group === null) {
671
+			throw new OCSException('Group:'.$groupid.' does not exist', 102);
672 672
 		}
673 673
 		// Check if trying to make subadmin of admin group
674
-		if(strtolower($groupid) === 'admin') {
674
+		if (strtolower($groupid) === 'admin') {
675 675
 			throw new OCSException('Cannot create subadmins for admin group', 103);
676 676
 		}
677 677
 
@@ -682,7 +682,7 @@  discard block
 block discarded – undo
682 682
 			return new DataResponse();
683 683
 		}
684 684
 		// Go
685
-		if($subAdminManager->createSubAdmin($user, $group)) {
685
+		if ($subAdminManager->createSubAdmin($user, $group)) {
686 686
 			return new DataResponse();
687 687
 		} else {
688 688
 			throw new OCSException('Unknown error occurred', 103);
@@ -705,20 +705,20 @@  discard block
 block discarded – undo
705 705
 		$subAdminManager = $this->groupManager->getSubAdmin();
706 706
 
707 707
 		// Check if the user exists
708
-		if($user === null) {
708
+		if ($user === null) {
709 709
 			throw new OCSException('User does not exist', 101);
710 710
 		}
711 711
 		// Check if the group exists
712
-		if($group === null) {
712
+		if ($group === null) {
713 713
 			throw new OCSException('Group does not exist', 101);
714 714
 		}
715 715
 		// Check if they are a subadmin of this said group
716
-		if(!$subAdminManager->isSubAdminofGroup($user, $group)) {
716
+		if (!$subAdminManager->isSubAdminofGroup($user, $group)) {
717 717
 			throw new OCSException('User is not a subadmin of this group', 102);
718 718
 		}
719 719
 
720 720
 		// Go
721
-		if($subAdminManager->deleteSubAdmin($user, $group)) {
721
+		if ($subAdminManager->deleteSubAdmin($user, $group)) {
722 722
 			return new DataResponse();
723 723
 		} else {
724 724
 			throw new OCSException('Unknown error occurred', 103);
@@ -735,7 +735,7 @@  discard block
 block discarded – undo
735 735
 	public function getUserSubAdminGroups($userId) {
736 736
 		$user = $this->userManager->get($userId);
737 737
 		// Check if the user exists
738
-		if($user === null) {
738
+		if ($user === null) {
739 739
 			throw new OCSException('User does not exist', 101);
740 740
 		}
741 741
 
@@ -745,7 +745,7 @@  discard block
 block discarded – undo
745 745
 			$groups[$key] = $group->getGID();
746 746
 		}
747 747
 
748
-		if(!$groups) {
748
+		if (!$groups) {
749 749
 			throw new OCSException('Unknown error occurred', 102);
750 750
 		} else {
751 751
 			return new DataResponse($groups);
@@ -789,13 +789,13 @@  discard block
 block discarded – undo
789 789
 		$currentLoggedInUser = $this->userSession->getUser();
790 790
 
791 791
 		$targetUser = $this->userManager->get($userId);
792
-		if($targetUser === null) {
792
+		if ($targetUser === null) {
793 793
 			throw new OCSException('', \OCP\API::RESPOND_NOT_FOUND);
794 794
 		}
795 795
 
796 796
 		// Check if admin / subadmin
797 797
 		$subAdminManager = $this->groupManager->getSubAdmin();
798
-		if(!$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)
798
+		if (!$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)
799 799
 			&& !$this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
800 800
 			// No rights
801 801
 			throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
@@ -817,8 +817,8 @@  discard block
 block discarded – undo
817 817
 			$this->newUserMailHelper->setL10N($l10n);
818 818
 			$emailTemplate = $this->newUserMailHelper->generateTemplate($targetUser, false);
819 819
 			$this->newUserMailHelper->sendMail($targetUser, $emailTemplate);
820
-		} catch(\Exception $e) {
821
-			$this->logger->error("Can't send new user mail to $email: " . $e->getMessage(), array('app' => 'settings'));
820
+		} catch (\Exception $e) {
821
+			$this->logger->error("Can't send new user mail to $email: ".$e->getMessage(), array('app' => 'settings'));
822 822
 			throw new OCSException('Sending email failed', 102);
823 823
 		}
824 824
 
Please login to merge, or discard this patch.
apps/user_ldap/lib/Helper.php 3 patches
Doc Comments   +3 added lines patch added patch discarded remove patch
@@ -124,6 +124,9 @@
 block discarded – undo
124 124
 		return $nextPrefix;
125 125
 	}
126 126
 
127
+	/**
128
+	 * @param string $value
129
+	 */
127 130
 	private function getServersConfig($value) {
128 131
 		$regex = '/' . $value . '$/S';
129 132
 
Please login to merge, or discard this patch.
Indentation   +258 added lines, -258 removed lines patch added patch discarded remove patch
@@ -34,126 +34,126 @@  discard block
 block discarded – undo
34 34
 
35 35
 class Helper {
36 36
 
37
-	/** @var IConfig */
38
-	private $config;
39
-
40
-	/**
41
-	 * Helper constructor.
42
-	 *
43
-	 * @param IConfig $config
44
-	 */
45
-	public function __construct(IConfig $config) {
46
-		$this->config = $config;
47
-	}
48
-
49
-	/**
50
-	 * returns prefixes for each saved LDAP/AD server configuration.
51
-	 * @param bool $activeConfigurations optional, whether only active configuration shall be
52
-	 * retrieved, defaults to false
53
-	 * @return array with a list of the available prefixes
54
-	 *
55
-	 * Configuration prefixes are used to set up configurations for n LDAP or
56
-	 * AD servers. Since configuration is stored in the database, table
57
-	 * appconfig under appid user_ldap, the common identifiers in column
58
-	 * 'configkey' have a prefix. The prefix for the very first server
59
-	 * configuration is empty.
60
-	 * Configkey Examples:
61
-	 * Server 1: ldap_login_filter
62
-	 * Server 2: s1_ldap_login_filter
63
-	 * Server 3: s2_ldap_login_filter
64
-	 *
65
-	 * The prefix needs to be passed to the constructor of Connection class,
66
-	 * except the default (first) server shall be connected to.
67
-	 *
68
-	 */
69
-	public function getServerConfigurationPrefixes($activeConfigurations = false) {
70
-		$referenceConfigkey = 'ldap_configuration_active';
71
-
72
-		$keys = $this->getServersConfig($referenceConfigkey);
73
-
74
-		$prefixes = [];
75
-		foreach ($keys as $key) {
76
-			if ($activeConfigurations && $this->config->getAppValue('user_ldap', $key, '0') !== '1') {
77
-				continue;
78
-			}
79
-
80
-			$len = strlen($key) - strlen($referenceConfigkey);
81
-			$prefixes[] = substr($key, 0, $len);
82
-		}
83
-
84
-		return $prefixes;
85
-	}
86
-
87
-	/**
88
-	 *
89
-	 * determines the host for every configured connection
90
-	 * @return array an array with configprefix as keys
91
-	 *
92
-	 */
93
-	public function getServerConfigurationHosts() {
94
-		$referenceConfigkey = 'ldap_host';
95
-
96
-		$keys = $this->getServersConfig($referenceConfigkey);
97
-
98
-		$result = array();
99
-		foreach($keys as $key) {
100
-			$len = strlen($key) - strlen($referenceConfigkey);
101
-			$prefix = substr($key, 0, $len);
102
-			$result[$prefix] = $this->config->getAppValue('user_ldap', $key);
103
-		}
104
-
105
-		return $result;
106
-	}
107
-
108
-	/**
109
-	 * return the next available configuration prefix
110
-	 *
111
-	 * @return string
112
-	 */
113
-	public function getNextServerConfigurationPrefix() {
114
-		$serverConnections = $this->getServerConfigurationPrefixes();
115
-
116
-		if(count($serverConnections) === 0) {
117
-			return 's01';
118
-		}
119
-
120
-		sort($serverConnections);
121
-		$lastKey = array_pop($serverConnections);
122
-		$lastNumber = intval(str_replace('s', '', $lastKey));
123
-		$nextPrefix = 's' . str_pad($lastNumber + 1, 2, '0', STR_PAD_LEFT);
124
-		return $nextPrefix;
125
-	}
126
-
127
-	private function getServersConfig($value) {
128
-		$regex = '/' . $value . '$/S';
129
-
130
-		$keys = $this->config->getAppKeys('user_ldap');
131
-		$result = [];
132
-		foreach ($keys as $key) {
133
-			if (preg_match($regex, $key) === 1) {
134
-				$result[] = $key;
135
-			}
136
-		}
137
-
138
-		return $result;
139
-	}
140
-
141
-	/**
142
-	 * deletes a given saved LDAP/AD server configuration.
143
-	 * @param string $prefix the configuration prefix of the config to delete
144
-	 * @return bool true on success, false otherwise
145
-	 */
146
-	public function deleteServerConfiguration($prefix) {
147
-		if(!in_array($prefix, self::getServerConfigurationPrefixes())) {
148
-			return false;
149
-		}
150
-
151
-		$saveOtherConfigurations = '';
152
-		if(empty($prefix)) {
153
-			$saveOtherConfigurations = 'AND `configkey` NOT LIKE \'s%\'';
154
-		}
155
-
156
-		$query = \OCP\DB::prepare('
37
+    /** @var IConfig */
38
+    private $config;
39
+
40
+    /**
41
+     * Helper constructor.
42
+     *
43
+     * @param IConfig $config
44
+     */
45
+    public function __construct(IConfig $config) {
46
+        $this->config = $config;
47
+    }
48
+
49
+    /**
50
+     * returns prefixes for each saved LDAP/AD server configuration.
51
+     * @param bool $activeConfigurations optional, whether only active configuration shall be
52
+     * retrieved, defaults to false
53
+     * @return array with a list of the available prefixes
54
+     *
55
+     * Configuration prefixes are used to set up configurations for n LDAP or
56
+     * AD servers. Since configuration is stored in the database, table
57
+     * appconfig under appid user_ldap, the common identifiers in column
58
+     * 'configkey' have a prefix. The prefix for the very first server
59
+     * configuration is empty.
60
+     * Configkey Examples:
61
+     * Server 1: ldap_login_filter
62
+     * Server 2: s1_ldap_login_filter
63
+     * Server 3: s2_ldap_login_filter
64
+     *
65
+     * The prefix needs to be passed to the constructor of Connection class,
66
+     * except the default (first) server shall be connected to.
67
+     *
68
+     */
69
+    public function getServerConfigurationPrefixes($activeConfigurations = false) {
70
+        $referenceConfigkey = 'ldap_configuration_active';
71
+
72
+        $keys = $this->getServersConfig($referenceConfigkey);
73
+
74
+        $prefixes = [];
75
+        foreach ($keys as $key) {
76
+            if ($activeConfigurations && $this->config->getAppValue('user_ldap', $key, '0') !== '1') {
77
+                continue;
78
+            }
79
+
80
+            $len = strlen($key) - strlen($referenceConfigkey);
81
+            $prefixes[] = substr($key, 0, $len);
82
+        }
83
+
84
+        return $prefixes;
85
+    }
86
+
87
+    /**
88
+     *
89
+     * determines the host for every configured connection
90
+     * @return array an array with configprefix as keys
91
+     *
92
+     */
93
+    public function getServerConfigurationHosts() {
94
+        $referenceConfigkey = 'ldap_host';
95
+
96
+        $keys = $this->getServersConfig($referenceConfigkey);
97
+
98
+        $result = array();
99
+        foreach($keys as $key) {
100
+            $len = strlen($key) - strlen($referenceConfigkey);
101
+            $prefix = substr($key, 0, $len);
102
+            $result[$prefix] = $this->config->getAppValue('user_ldap', $key);
103
+        }
104
+
105
+        return $result;
106
+    }
107
+
108
+    /**
109
+     * return the next available configuration prefix
110
+     *
111
+     * @return string
112
+     */
113
+    public function getNextServerConfigurationPrefix() {
114
+        $serverConnections = $this->getServerConfigurationPrefixes();
115
+
116
+        if(count($serverConnections) === 0) {
117
+            return 's01';
118
+        }
119
+
120
+        sort($serverConnections);
121
+        $lastKey = array_pop($serverConnections);
122
+        $lastNumber = intval(str_replace('s', '', $lastKey));
123
+        $nextPrefix = 's' . str_pad($lastNumber + 1, 2, '0', STR_PAD_LEFT);
124
+        return $nextPrefix;
125
+    }
126
+
127
+    private function getServersConfig($value) {
128
+        $regex = '/' . $value . '$/S';
129
+
130
+        $keys = $this->config->getAppKeys('user_ldap');
131
+        $result = [];
132
+        foreach ($keys as $key) {
133
+            if (preg_match($regex, $key) === 1) {
134
+                $result[] = $key;
135
+            }
136
+        }
137
+
138
+        return $result;
139
+    }
140
+
141
+    /**
142
+     * deletes a given saved LDAP/AD server configuration.
143
+     * @param string $prefix the configuration prefix of the config to delete
144
+     * @return bool true on success, false otherwise
145
+     */
146
+    public function deleteServerConfiguration($prefix) {
147
+        if(!in_array($prefix, self::getServerConfigurationPrefixes())) {
148
+            return false;
149
+        }
150
+
151
+        $saveOtherConfigurations = '';
152
+        if(empty($prefix)) {
153
+            $saveOtherConfigurations = 'AND `configkey` NOT LIKE \'s%\'';
154
+        }
155
+
156
+        $query = \OCP\DB::prepare('
157 157
 			DELETE
158 158
 			FROM `*PREFIX*appconfig`
159 159
 			WHERE `configkey` LIKE ?
@@ -161,145 +161,145 @@  discard block
 block discarded – undo
161 161
 				AND `appid` = \'user_ldap\'
162 162
 				AND `configkey` NOT IN (\'enabled\', \'installed_version\', \'types\', \'bgjUpdateGroupsLastRun\')
163 163
 		');
164
-		$delRows = $query->execute(array($prefix.'%'));
165
-
166
-		if(\OCP\DB::isError($delRows)) {
167
-			return false;
168
-		}
169
-
170
-		if($delRows === 0) {
171
-			return false;
172
-		}
173
-
174
-		return true;
175
-	}
176
-
177
-	/**
178
-	 * checks whether there is one or more disabled LDAP configurations
179
-	 * @throws \Exception
180
-	 * @return bool
181
-	 */
182
-	public function haveDisabledConfigurations() {
183
-		$all = $this->getServerConfigurationPrefixes(false);
184
-		$active = $this->getServerConfigurationPrefixes(true);
185
-
186
-		if(!is_array($all) || !is_array($active)) {
187
-			throw new \Exception('Unexpected Return Value');
188
-		}
189
-
190
-		return count($all) !== count($active) || count($all) === 0;
191
-	}
192
-
193
-	/**
194
-	 * extracts the domain from a given URL
195
-	 * @param string $url the URL
196
-	 * @return string|false domain as string on success, false otherwise
197
-	 */
198
-	public function getDomainFromURL($url) {
199
-		$uinfo = parse_url($url);
200
-		if(!is_array($uinfo)) {
201
-			return false;
202
-		}
203
-
204
-		$domain = false;
205
-		if(isset($uinfo['host'])) {
206
-			$domain = $uinfo['host'];
207
-		} else if(isset($uinfo['path'])) {
208
-			$domain = $uinfo['path'];
209
-		}
210
-
211
-		return $domain;
212
-	}
164
+        $delRows = $query->execute(array($prefix.'%'));
165
+
166
+        if(\OCP\DB::isError($delRows)) {
167
+            return false;
168
+        }
169
+
170
+        if($delRows === 0) {
171
+            return false;
172
+        }
173
+
174
+        return true;
175
+    }
176
+
177
+    /**
178
+     * checks whether there is one or more disabled LDAP configurations
179
+     * @throws \Exception
180
+     * @return bool
181
+     */
182
+    public function haveDisabledConfigurations() {
183
+        $all = $this->getServerConfigurationPrefixes(false);
184
+        $active = $this->getServerConfigurationPrefixes(true);
185
+
186
+        if(!is_array($all) || !is_array($active)) {
187
+            throw new \Exception('Unexpected Return Value');
188
+        }
189
+
190
+        return count($all) !== count($active) || count($all) === 0;
191
+    }
192
+
193
+    /**
194
+     * extracts the domain from a given URL
195
+     * @param string $url the URL
196
+     * @return string|false domain as string on success, false otherwise
197
+     */
198
+    public function getDomainFromURL($url) {
199
+        $uinfo = parse_url($url);
200
+        if(!is_array($uinfo)) {
201
+            return false;
202
+        }
203
+
204
+        $domain = false;
205
+        if(isset($uinfo['host'])) {
206
+            $domain = $uinfo['host'];
207
+        } else if(isset($uinfo['path'])) {
208
+            $domain = $uinfo['path'];
209
+        }
210
+
211
+        return $domain;
212
+    }
213 213
 	
214
-	/**
215
-	 *
216
-	 * Set the LDAPProvider in the config
217
-	 *
218
-	 */
219
-	public function setLDAPProvider() {
220
-		$current = \OC::$server->getConfig()->getSystemValue('ldapProviderFactory', null);
221
-		if(is_null($current)) {
222
-			\OC::$server->getConfig()->setSystemValue('ldapProviderFactory', '\\OCA\\User_LDAP\\LDAPProviderFactory');
223
-		}
224
-	}
214
+    /**
215
+     *
216
+     * Set the LDAPProvider in the config
217
+     *
218
+     */
219
+    public function setLDAPProvider() {
220
+        $current = \OC::$server->getConfig()->getSystemValue('ldapProviderFactory', null);
221
+        if(is_null($current)) {
222
+            \OC::$server->getConfig()->setSystemValue('ldapProviderFactory', '\\OCA\\User_LDAP\\LDAPProviderFactory');
223
+        }
224
+    }
225 225
 	
226
-	/**
227
-	 * sanitizes a DN received from the LDAP server
228
-	 * @param array $dn the DN in question
229
-	 * @return array the sanitized DN
230
-	 */
231
-	public function sanitizeDN($dn) {
232
-		//treating multiple base DNs
233
-		if(is_array($dn)) {
234
-			$result = array();
235
-			foreach($dn as $singleDN) {
236
-				$result[] = $this->sanitizeDN($singleDN);
237
-			}
238
-			return $result;
239
-		}
240
-
241
-		//OID sometimes gives back DNs with whitespace after the comma
242
-		// a la "uid=foo, cn=bar, dn=..." We need to tackle this!
243
-		$dn = preg_replace('/([^\\\]),(\s+)/u', '\1,', $dn);
244
-
245
-		//make comparisons and everything work
246
-		$dn = mb_strtolower($dn, 'UTF-8');
247
-
248
-		//escape DN values according to RFC 2253 – this is already done by ldap_explode_dn
249
-		//to use the DN in search filters, \ needs to be escaped to \5c additionally
250
-		//to use them in bases, we convert them back to simple backslashes in readAttribute()
251
-		$replacements = array(
252
-			'\,' => '\5c2C',
253
-			'\=' => '\5c3D',
254
-			'\+' => '\5c2B',
255
-			'\<' => '\5c3C',
256
-			'\>' => '\5c3E',
257
-			'\;' => '\5c3B',
258
-			'\"' => '\5c22',
259
-			'\#' => '\5c23',
260
-			'('  => '\28',
261
-			')'  => '\29',
262
-			'*'  => '\2A',
263
-		);
264
-		$dn = str_replace(array_keys($replacements), array_values($replacements), $dn);
265
-
266
-		return $dn;
267
-	}
226
+    /**
227
+     * sanitizes a DN received from the LDAP server
228
+     * @param array $dn the DN in question
229
+     * @return array the sanitized DN
230
+     */
231
+    public function sanitizeDN($dn) {
232
+        //treating multiple base DNs
233
+        if(is_array($dn)) {
234
+            $result = array();
235
+            foreach($dn as $singleDN) {
236
+                $result[] = $this->sanitizeDN($singleDN);
237
+            }
238
+            return $result;
239
+        }
240
+
241
+        //OID sometimes gives back DNs with whitespace after the comma
242
+        // a la "uid=foo, cn=bar, dn=..." We need to tackle this!
243
+        $dn = preg_replace('/([^\\\]),(\s+)/u', '\1,', $dn);
244
+
245
+        //make comparisons and everything work
246
+        $dn = mb_strtolower($dn, 'UTF-8');
247
+
248
+        //escape DN values according to RFC 2253 – this is already done by ldap_explode_dn
249
+        //to use the DN in search filters, \ needs to be escaped to \5c additionally
250
+        //to use them in bases, we convert them back to simple backslashes in readAttribute()
251
+        $replacements = array(
252
+            '\,' => '\5c2C',
253
+            '\=' => '\5c3D',
254
+            '\+' => '\5c2B',
255
+            '\<' => '\5c3C',
256
+            '\>' => '\5c3E',
257
+            '\;' => '\5c3B',
258
+            '\"' => '\5c22',
259
+            '\#' => '\5c23',
260
+            '('  => '\28',
261
+            ')'  => '\29',
262
+            '*'  => '\2A',
263
+        );
264
+        $dn = str_replace(array_keys($replacements), array_values($replacements), $dn);
265
+
266
+        return $dn;
267
+    }
268 268
 	
269
-	/**
270
-	 * converts a stored DN so it can be used as base parameter for LDAP queries, internally we store them for usage in LDAP filters
271
-	 * @param string $dn the DN
272
-	 * @return string
273
-	 */
274
-	public function DNasBaseParameter($dn) {
275
-		return str_ireplace('\\5c', '\\', $dn);
276
-	}
277
-
278
-	/**
279
-	 * listens to a hook thrown by server2server sharing and replaces the given
280
-	 * login name by a username, if it matches an LDAP user.
281
-	 *
282
-	 * @param array $param
283
-	 * @throws \Exception
284
-	 */
285
-	public static function loginName2UserName($param) {
286
-		if(!isset($param['uid'])) {
287
-			throw new \Exception('key uid is expected to be set in $param');
288
-		}
289
-
290
-		//ain't it ironic?
291
-		$helper = new Helper(\OC::$server->getConfig());
292
-
293
-		$configPrefixes = $helper->getServerConfigurationPrefixes(true);
294
-		$ldapWrapper = new LDAP();
295
-		$ocConfig = \OC::$server->getConfig();
296
-
297
-		$userBackend  = new User_Proxy(
298
-			$configPrefixes, $ldapWrapper, $ocConfig
299
-		);
300
-		$uid = $userBackend->loginName2UserName($param['uid'] );
301
-		if($uid !== false) {
302
-			$param['uid'] = $uid;
303
-		}
304
-	}
269
+    /**
270
+     * converts a stored DN so it can be used as base parameter for LDAP queries, internally we store them for usage in LDAP filters
271
+     * @param string $dn the DN
272
+     * @return string
273
+     */
274
+    public function DNasBaseParameter($dn) {
275
+        return str_ireplace('\\5c', '\\', $dn);
276
+    }
277
+
278
+    /**
279
+     * listens to a hook thrown by server2server sharing and replaces the given
280
+     * login name by a username, if it matches an LDAP user.
281
+     *
282
+     * @param array $param
283
+     * @throws \Exception
284
+     */
285
+    public static function loginName2UserName($param) {
286
+        if(!isset($param['uid'])) {
287
+            throw new \Exception('key uid is expected to be set in $param');
288
+        }
289
+
290
+        //ain't it ironic?
291
+        $helper = new Helper(\OC::$server->getConfig());
292
+
293
+        $configPrefixes = $helper->getServerConfigurationPrefixes(true);
294
+        $ldapWrapper = new LDAP();
295
+        $ocConfig = \OC::$server->getConfig();
296
+
297
+        $userBackend  = new User_Proxy(
298
+            $configPrefixes, $ldapWrapper, $ocConfig
299
+        );
300
+        $uid = $userBackend->loginName2UserName($param['uid'] );
301
+        if($uid !== false) {
302
+            $param['uid'] = $uid;
303
+        }
304
+    }
305 305
 }
Please login to merge, or discard this patch.
Spacing   +19 added lines, -19 removed lines patch added patch discarded remove patch
@@ -96,7 +96,7 @@  discard block
 block discarded – undo
96 96
 		$keys = $this->getServersConfig($referenceConfigkey);
97 97
 
98 98
 		$result = array();
99
-		foreach($keys as $key) {
99
+		foreach ($keys as $key) {
100 100
 			$len = strlen($key) - strlen($referenceConfigkey);
101 101
 			$prefix = substr($key, 0, $len);
102 102
 			$result[$prefix] = $this->config->getAppValue('user_ldap', $key);
@@ -113,19 +113,19 @@  discard block
 block discarded – undo
113 113
 	public function getNextServerConfigurationPrefix() {
114 114
 		$serverConnections = $this->getServerConfigurationPrefixes();
115 115
 
116
-		if(count($serverConnections) === 0) {
116
+		if (count($serverConnections) === 0) {
117 117
 			return 's01';
118 118
 		}
119 119
 
120 120
 		sort($serverConnections);
121 121
 		$lastKey = array_pop($serverConnections);
122 122
 		$lastNumber = intval(str_replace('s', '', $lastKey));
123
-		$nextPrefix = 's' . str_pad($lastNumber + 1, 2, '0', STR_PAD_LEFT);
123
+		$nextPrefix = 's'.str_pad($lastNumber + 1, 2, '0', STR_PAD_LEFT);
124 124
 		return $nextPrefix;
125 125
 	}
126 126
 
127 127
 	private function getServersConfig($value) {
128
-		$regex = '/' . $value . '$/S';
128
+		$regex = '/'.$value.'$/S';
129 129
 
130 130
 		$keys = $this->config->getAppKeys('user_ldap');
131 131
 		$result = [];
@@ -144,12 +144,12 @@  discard block
 block discarded – undo
144 144
 	 * @return bool true on success, false otherwise
145 145
 	 */
146 146
 	public function deleteServerConfiguration($prefix) {
147
-		if(!in_array($prefix, self::getServerConfigurationPrefixes())) {
147
+		if (!in_array($prefix, self::getServerConfigurationPrefixes())) {
148 148
 			return false;
149 149
 		}
150 150
 
151 151
 		$saveOtherConfigurations = '';
152
-		if(empty($prefix)) {
152
+		if (empty($prefix)) {
153 153
 			$saveOtherConfigurations = 'AND `configkey` NOT LIKE \'s%\'';
154 154
 		}
155 155
 
@@ -163,11 +163,11 @@  discard block
 block discarded – undo
163 163
 		');
164 164
 		$delRows = $query->execute(array($prefix.'%'));
165 165
 
166
-		if(\OCP\DB::isError($delRows)) {
166
+		if (\OCP\DB::isError($delRows)) {
167 167
 			return false;
168 168
 		}
169 169
 
170
-		if($delRows === 0) {
170
+		if ($delRows === 0) {
171 171
 			return false;
172 172
 		}
173 173
 
@@ -183,7 +183,7 @@  discard block
 block discarded – undo
183 183
 		$all = $this->getServerConfigurationPrefixes(false);
184 184
 		$active = $this->getServerConfigurationPrefixes(true);
185 185
 
186
-		if(!is_array($all) || !is_array($active)) {
186
+		if (!is_array($all) || !is_array($active)) {
187 187
 			throw new \Exception('Unexpected Return Value');
188 188
 		}
189 189
 
@@ -197,14 +197,14 @@  discard block
 block discarded – undo
197 197
 	 */
198 198
 	public function getDomainFromURL($url) {
199 199
 		$uinfo = parse_url($url);
200
-		if(!is_array($uinfo)) {
200
+		if (!is_array($uinfo)) {
201 201
 			return false;
202 202
 		}
203 203
 
204 204
 		$domain = false;
205
-		if(isset($uinfo['host'])) {
205
+		if (isset($uinfo['host'])) {
206 206
 			$domain = $uinfo['host'];
207
-		} else if(isset($uinfo['path'])) {
207
+		} else if (isset($uinfo['path'])) {
208 208
 			$domain = $uinfo['path'];
209 209
 		}
210 210
 
@@ -218,7 +218,7 @@  discard block
 block discarded – undo
218 218
 	 */
219 219
 	public function setLDAPProvider() {
220 220
 		$current = \OC::$server->getConfig()->getSystemValue('ldapProviderFactory', null);
221
-		if(is_null($current)) {
221
+		if (is_null($current)) {
222 222
 			\OC::$server->getConfig()->setSystemValue('ldapProviderFactory', '\\OCA\\User_LDAP\\LDAPProviderFactory');
223 223
 		}
224 224
 	}
@@ -230,9 +230,9 @@  discard block
 block discarded – undo
230 230
 	 */
231 231
 	public function sanitizeDN($dn) {
232 232
 		//treating multiple base DNs
233
-		if(is_array($dn)) {
233
+		if (is_array($dn)) {
234 234
 			$result = array();
235
-			foreach($dn as $singleDN) {
235
+			foreach ($dn as $singleDN) {
236 236
 				$result[] = $this->sanitizeDN($singleDN);
237 237
 			}
238 238
 			return $result;
@@ -283,7 +283,7 @@  discard block
 block discarded – undo
283 283
 	 * @throws \Exception
284 284
 	 */
285 285
 	public static function loginName2UserName($param) {
286
-		if(!isset($param['uid'])) {
286
+		if (!isset($param['uid'])) {
287 287
 			throw new \Exception('key uid is expected to be set in $param');
288 288
 		}
289 289
 
@@ -294,11 +294,11 @@  discard block
 block discarded – undo
294 294
 		$ldapWrapper = new LDAP();
295 295
 		$ocConfig = \OC::$server->getConfig();
296 296
 
297
-		$userBackend  = new User_Proxy(
297
+		$userBackend = new User_Proxy(
298 298
 			$configPrefixes, $ldapWrapper, $ocConfig
299 299
 		);
300
-		$uid = $userBackend->loginName2UserName($param['uid'] );
301
-		if($uid !== false) {
300
+		$uid = $userBackend->loginName2UserName($param['uid']);
301
+		if ($uid !== false) {
302 302
 			$param['uid'] = $uid;
303 303
 		}
304 304
 	}
Please login to merge, or discard this patch.
core/Middleware/TwoFactorMiddleware.php 2 patches
Doc Comments   +4 added lines patch added patch discarded remove patch
@@ -104,6 +104,10 @@
 block discarded – undo
104 104
 		// TODO: dont check/enforce 2FA if a auth token is used
105 105
 	}
106 106
 
107
+	/**
108
+	 * @param Controller $controller
109
+	 * @param string $methodName
110
+	 */
107 111
 	private function checkTwoFactor($controller, $methodName, IUser $user) {
108 112
 		// If two-factor auth is in progress disallow access to any controllers
109 113
 		// defined within "LoginController".
Please login to merge, or discard this patch.
Indentation   +93 added lines, -93 removed lines patch added patch discarded remove patch
@@ -41,98 +41,98 @@
 block discarded – undo
41 41
 
42 42
 class TwoFactorMiddleware extends Middleware {
43 43
 
44
-	/** @var Manager */
45
-	private $twoFactorManager;
46
-
47
-	/** @var Session */
48
-	private $userSession;
49
-
50
-	/** @var ISession */
51
-	private $session;
52
-
53
-	/** @var IURLGenerator */
54
-	private $urlGenerator;
55
-
56
-	/** @var IControllerMethodReflector */
57
-	private $reflector;
58
-
59
-	/** @var IRequest */
60
-	private $request;
61
-
62
-	/**
63
-	 * @param Manager $twoFactorManager
64
-	 * @param Session $userSession
65
-	 * @param ISession $session
66
-	 * @param IURLGenerator $urlGenerator
67
-	 */
68
-	public function __construct(Manager $twoFactorManager, Session $userSession, ISession $session,
69
-		IURLGenerator $urlGenerator, IControllerMethodReflector $reflector, IRequest $request) {
70
-		$this->twoFactorManager = $twoFactorManager;
71
-		$this->userSession = $userSession;
72
-		$this->session = $session;
73
-		$this->urlGenerator = $urlGenerator;
74
-		$this->reflector = $reflector;
75
-		$this->request = $request;
76
-	}
77
-
78
-	/**
79
-	 * @param Controller $controller
80
-	 * @param string $methodName
81
-	 */
82
-	public function beforeController($controller, $methodName) {
83
-		if ($this->reflector->hasAnnotation('PublicPage')) {
84
-			// Don't block public pages
85
-			return;
86
-		}
87
-
88
-		if ($controller instanceof LoginController && $methodName === 'logout') {
89
-			// Don't block the logout page, to allow canceling the 2FA
90
-			return;
91
-		}
92
-
93
-		if ($this->userSession->isLoggedIn()) {
94
-			$user = $this->userSession->getUser();
95
-
96
-			if ($this->twoFactorManager->isTwoFactorAuthenticated($user)) {
97
-				$this->checkTwoFactor($controller, $methodName, $user);
98
-			} else if ($controller instanceof TwoFactorChallengeController) {
99
-				// Allow access to the two-factor controllers only if two-factor authentication
100
-				// is in progress.
101
-				throw new UserAlreadyLoggedInException();
102
-			}
103
-		}
104
-		// TODO: dont check/enforce 2FA if a auth token is used
105
-	}
106
-
107
-	private function checkTwoFactor($controller, $methodName, IUser $user) {
108
-		// If two-factor auth is in progress disallow access to any controllers
109
-		// defined within "LoginController".
110
-		$needsSecondFactor = $this->twoFactorManager->needsSecondFactor($user);
111
-		$twoFactor = $controller instanceof TwoFactorChallengeController;
112
-
113
-		// Disallow access to any controller if 2FA needs to be checked
114
-		if ($needsSecondFactor && !$twoFactor) {
115
-			throw new TwoFactorAuthRequiredException();
116
-		}
117
-
118
-		// Allow access to the two-factor controllers only if two-factor authentication
119
-		// is in progress.
120
-		if (!$needsSecondFactor && $twoFactor) {
121
-			throw new UserAlreadyLoggedInException();
122
-		}
123
-	}
124
-
125
-	public function afterException($controller, $methodName, Exception $exception) {
126
-		if ($exception instanceof TwoFactorAuthRequiredException) {
127
-			return new RedirectResponse($this->urlGenerator->linkToRoute('core.TwoFactorChallenge.selectChallenge', [
128
-					'redirect_url' => urlencode($this->request->server['REQUEST_URI']),
129
-			]));
130
-		}
131
-		if ($exception instanceof UserAlreadyLoggedInException) {
132
-			return new RedirectResponse($this->urlGenerator->linkToRoute('files.view.index'));
133
-		}
134
-
135
-		throw $exception;
136
-	}
44
+    /** @var Manager */
45
+    private $twoFactorManager;
46
+
47
+    /** @var Session */
48
+    private $userSession;
49
+
50
+    /** @var ISession */
51
+    private $session;
52
+
53
+    /** @var IURLGenerator */
54
+    private $urlGenerator;
55
+
56
+    /** @var IControllerMethodReflector */
57
+    private $reflector;
58
+
59
+    /** @var IRequest */
60
+    private $request;
61
+
62
+    /**
63
+     * @param Manager $twoFactorManager
64
+     * @param Session $userSession
65
+     * @param ISession $session
66
+     * @param IURLGenerator $urlGenerator
67
+     */
68
+    public function __construct(Manager $twoFactorManager, Session $userSession, ISession $session,
69
+        IURLGenerator $urlGenerator, IControllerMethodReflector $reflector, IRequest $request) {
70
+        $this->twoFactorManager = $twoFactorManager;
71
+        $this->userSession = $userSession;
72
+        $this->session = $session;
73
+        $this->urlGenerator = $urlGenerator;
74
+        $this->reflector = $reflector;
75
+        $this->request = $request;
76
+    }
77
+
78
+    /**
79
+     * @param Controller $controller
80
+     * @param string $methodName
81
+     */
82
+    public function beforeController($controller, $methodName) {
83
+        if ($this->reflector->hasAnnotation('PublicPage')) {
84
+            // Don't block public pages
85
+            return;
86
+        }
87
+
88
+        if ($controller instanceof LoginController && $methodName === 'logout') {
89
+            // Don't block the logout page, to allow canceling the 2FA
90
+            return;
91
+        }
92
+
93
+        if ($this->userSession->isLoggedIn()) {
94
+            $user = $this->userSession->getUser();
95
+
96
+            if ($this->twoFactorManager->isTwoFactorAuthenticated($user)) {
97
+                $this->checkTwoFactor($controller, $methodName, $user);
98
+            } else if ($controller instanceof TwoFactorChallengeController) {
99
+                // Allow access to the two-factor controllers only if two-factor authentication
100
+                // is in progress.
101
+                throw new UserAlreadyLoggedInException();
102
+            }
103
+        }
104
+        // TODO: dont check/enforce 2FA if a auth token is used
105
+    }
106
+
107
+    private function checkTwoFactor($controller, $methodName, IUser $user) {
108
+        // If two-factor auth is in progress disallow access to any controllers
109
+        // defined within "LoginController".
110
+        $needsSecondFactor = $this->twoFactorManager->needsSecondFactor($user);
111
+        $twoFactor = $controller instanceof TwoFactorChallengeController;
112
+
113
+        // Disallow access to any controller if 2FA needs to be checked
114
+        if ($needsSecondFactor && !$twoFactor) {
115
+            throw new TwoFactorAuthRequiredException();
116
+        }
117
+
118
+        // Allow access to the two-factor controllers only if two-factor authentication
119
+        // is in progress.
120
+        if (!$needsSecondFactor && $twoFactor) {
121
+            throw new UserAlreadyLoggedInException();
122
+        }
123
+    }
124
+
125
+    public function afterException($controller, $methodName, Exception $exception) {
126
+        if ($exception instanceof TwoFactorAuthRequiredException) {
127
+            return new RedirectResponse($this->urlGenerator->linkToRoute('core.TwoFactorChallenge.selectChallenge', [
128
+                    'redirect_url' => urlencode($this->request->server['REQUEST_URI']),
129
+            ]));
130
+        }
131
+        if ($exception instanceof UserAlreadyLoggedInException) {
132
+            return new RedirectResponse($this->urlGenerator->linkToRoute('files.view.index'));
133
+        }
134
+
135
+        throw $exception;
136
+    }
137 137
 
138 138
 }
Please login to merge, or discard this patch.
lib/private/Archive/ZIP.php 4 patches
Doc Comments   +1 added lines patch added patch discarded remove patch
@@ -370,6 +370,7 @@
 block discarded – undo
370 370
 
371 371
 	/**
372 372
 	 * write back temporary files
373
+	 * @param string $path
373 374
 	 */
374 375
 	function writeBack($tmpFile, $path) {
375 376
 		$this->addFile($path, $tmpFile);
Please login to merge, or discard this patch.
Indentation   +192 added lines, -192 removed lines patch added patch discarded remove patch
@@ -34,199 +34,199 @@
 block discarded – undo
34 34
 use Icewind\Streams\CallbackWrapper;
35 35
 
36 36
 class ZIP extends Archive{
37
-	/**
38
-	 * @var \ZipArchive zip
39
-	 */
40
-	private $zip=null;
41
-	private $path;
37
+    /**
38
+     * @var \ZipArchive zip
39
+     */
40
+    private $zip=null;
41
+    private $path;
42 42
 
43
-	/**
44
-	 * @param string $source
45
-	 */
46
-	function __construct($source) {
47
-		$this->path=$source;
48
-		$this->zip=new \ZipArchive();
49
-		if($this->zip->open($source, \ZipArchive::CREATE)) {
50
-		}else{
51
-			\OCP\Util::writeLog('files_archive', 'Error while opening archive '.$source, \OCP\Util::WARN);
52
-		}
53
-	}
54
-	/**
55
-	 * add an empty folder to the archive
56
-	 * @param string $path
57
-	 * @return bool
58
-	 */
59
-	function addFolder($path) {
60
-		return $this->zip->addEmptyDir($path);
61
-	}
62
-	/**
63
-	 * add a file to the archive
64
-	 * @param string $path
65
-	 * @param string $source either a local file or string data
66
-	 * @return bool
67
-	 */
68
-	function addFile($path, $source='') {
69
-		if($source and $source[0]=='/' and file_exists($source)) {
70
-			$result=$this->zip->addFile($source, $path);
71
-		}else{
72
-			$result=$this->zip->addFromString($path, $source);
73
-		}
74
-		if($result) {
75
-			$this->zip->close();//close and reopen to save the zip
76
-			$this->zip->open($this->path);
77
-		}
78
-		return $result;
79
-	}
80
-	/**
81
-	 * rename a file or folder in the archive
82
-	 * @param string $source
83
-	 * @param string $dest
84
-	 * @return boolean|null
85
-	 */
86
-	function rename($source, $dest) {
87
-		$source=$this->stripPath($source);
88
-		$dest=$this->stripPath($dest);
89
-		$this->zip->renameName($source, $dest);
90
-	}
91
-	/**
92
-	 * get the uncompressed size of a file in the archive
93
-	 * @param string $path
94
-	 * @return int
95
-	 */
96
-	function filesize($path) {
97
-		$stat=$this->zip->statName($path);
98
-		return $stat['size'];
99
-	}
100
-	/**
101
-	 * get the last modified time of a file in the archive
102
-	 * @param string $path
103
-	 * @return int
104
-	 */
105
-	function mtime($path) {
106
-		return filemtime($this->path);
107
-	}
108
-	/**
109
-	 * get the files in a folder
110
-	 * @param string $path
111
-	 * @return array
112
-	 */
113
-	function getFolder($path) {
114
-		$files=$this->getFiles();
115
-		$folderContent=array();
116
-		$pathLength=strlen($path);
117
-		foreach($files as $file) {
118
-			if(substr($file, 0, $pathLength)==$path and $file!=$path) {
119
-				if(strrpos(substr($file, 0, -1), '/')<=$pathLength) {
120
-					$folderContent[]=substr($file, $pathLength);
121
-				}
122
-			}
123
-		}
124
-		return $folderContent;
125
-	}
126
-	/**
127
-	 * get all files in the archive
128
-	 * @return array
129
-	 */
130
-	function getFiles() {
131
-		$fileCount=$this->zip->numFiles;
132
-		$files=array();
133
-		for($i=0;$i<$fileCount;$i++) {
134
-			$files[]=$this->zip->getNameIndex($i);
135
-		}
136
-		return $files;
137
-	}
138
-	/**
139
-	 * get the content of a file
140
-	 * @param string $path
141
-	 * @return string
142
-	 */
143
-	function getFile($path) {
144
-		return $this->zip->getFromName($path);
145
-	}
146
-	/**
147
-	 * extract a single file from the archive
148
-	 * @param string $path
149
-	 * @param string $dest
150
-	 * @return boolean|null
151
-	 */
152
-	function extractFile($path, $dest) {
153
-		$fp = $this->zip->getStream($path);
154
-		file_put_contents($dest, $fp);
155
-	}
156
-	/**
157
-	 * extract the archive
158
-	 * @param string $dest
159
-	 * @return bool
160
-	 */
161
-	function extract($dest) {
162
-		return $this->zip->extractTo($dest);
163
-	}
164
-	/**
165
-	 * check if a file or folder exists in the archive
166
-	 * @param string $path
167
-	 * @return bool
168
-	 */
169
-	function fileExists($path) {
170
-		return ($this->zip->locateName($path)!==false) or ($this->zip->locateName($path.'/')!==false);
171
-	}
172
-	/**
173
-	 * remove a file or folder from the archive
174
-	 * @param string $path
175
-	 * @return bool
176
-	 */
177
-	function remove($path) {
178
-		if($this->fileExists($path.'/')) {
179
-			return $this->zip->deleteName($path.'/');
180
-		}else{
181
-			return $this->zip->deleteName($path);
182
-		}
183
-	}
184
-	/**
185
-	 * get a file handler
186
-	 * @param string $path
187
-	 * @param string $mode
188
-	 * @return resource
189
-	 */
190
-	function getStream($path, $mode) {
191
-		if($mode=='r' or $mode=='rb') {
192
-			return $this->zip->getStream($path);
193
-		} else {
194
-			//since we can't directly get a writable stream,
195
-			//make a temp copy of the file and put it back
196
-			//in the archive when the stream is closed
197
-			if(strrpos($path, '.')!==false) {
198
-				$ext=substr($path, strrpos($path, '.'));
199
-			}else{
200
-				$ext='';
201
-			}
202
-			$tmpFile=\OCP\Files::tmpFile($ext);
203
-			if($this->fileExists($path)) {
204
-				$this->extractFile($path, $tmpFile);
205
-			}
206
-			$handle = fopen($tmpFile, $mode);
207
-			return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
208
-				$this->writeBack($tmpFile, $path);
209
-			});
210
-		}
211
-	}
43
+    /**
44
+     * @param string $source
45
+     */
46
+    function __construct($source) {
47
+        $this->path=$source;
48
+        $this->zip=new \ZipArchive();
49
+        if($this->zip->open($source, \ZipArchive::CREATE)) {
50
+        }else{
51
+            \OCP\Util::writeLog('files_archive', 'Error while opening archive '.$source, \OCP\Util::WARN);
52
+        }
53
+    }
54
+    /**
55
+     * add an empty folder to the archive
56
+     * @param string $path
57
+     * @return bool
58
+     */
59
+    function addFolder($path) {
60
+        return $this->zip->addEmptyDir($path);
61
+    }
62
+    /**
63
+     * add a file to the archive
64
+     * @param string $path
65
+     * @param string $source either a local file or string data
66
+     * @return bool
67
+     */
68
+    function addFile($path, $source='') {
69
+        if($source and $source[0]=='/' and file_exists($source)) {
70
+            $result=$this->zip->addFile($source, $path);
71
+        }else{
72
+            $result=$this->zip->addFromString($path, $source);
73
+        }
74
+        if($result) {
75
+            $this->zip->close();//close and reopen to save the zip
76
+            $this->zip->open($this->path);
77
+        }
78
+        return $result;
79
+    }
80
+    /**
81
+     * rename a file or folder in the archive
82
+     * @param string $source
83
+     * @param string $dest
84
+     * @return boolean|null
85
+     */
86
+    function rename($source, $dest) {
87
+        $source=$this->stripPath($source);
88
+        $dest=$this->stripPath($dest);
89
+        $this->zip->renameName($source, $dest);
90
+    }
91
+    /**
92
+     * get the uncompressed size of a file in the archive
93
+     * @param string $path
94
+     * @return int
95
+     */
96
+    function filesize($path) {
97
+        $stat=$this->zip->statName($path);
98
+        return $stat['size'];
99
+    }
100
+    /**
101
+     * get the last modified time of a file in the archive
102
+     * @param string $path
103
+     * @return int
104
+     */
105
+    function mtime($path) {
106
+        return filemtime($this->path);
107
+    }
108
+    /**
109
+     * get the files in a folder
110
+     * @param string $path
111
+     * @return array
112
+     */
113
+    function getFolder($path) {
114
+        $files=$this->getFiles();
115
+        $folderContent=array();
116
+        $pathLength=strlen($path);
117
+        foreach($files as $file) {
118
+            if(substr($file, 0, $pathLength)==$path and $file!=$path) {
119
+                if(strrpos(substr($file, 0, -1), '/')<=$pathLength) {
120
+                    $folderContent[]=substr($file, $pathLength);
121
+                }
122
+            }
123
+        }
124
+        return $folderContent;
125
+    }
126
+    /**
127
+     * get all files in the archive
128
+     * @return array
129
+     */
130
+    function getFiles() {
131
+        $fileCount=$this->zip->numFiles;
132
+        $files=array();
133
+        for($i=0;$i<$fileCount;$i++) {
134
+            $files[]=$this->zip->getNameIndex($i);
135
+        }
136
+        return $files;
137
+    }
138
+    /**
139
+     * get the content of a file
140
+     * @param string $path
141
+     * @return string
142
+     */
143
+    function getFile($path) {
144
+        return $this->zip->getFromName($path);
145
+    }
146
+    /**
147
+     * extract a single file from the archive
148
+     * @param string $path
149
+     * @param string $dest
150
+     * @return boolean|null
151
+     */
152
+    function extractFile($path, $dest) {
153
+        $fp = $this->zip->getStream($path);
154
+        file_put_contents($dest, $fp);
155
+    }
156
+    /**
157
+     * extract the archive
158
+     * @param string $dest
159
+     * @return bool
160
+     */
161
+    function extract($dest) {
162
+        return $this->zip->extractTo($dest);
163
+    }
164
+    /**
165
+     * check if a file or folder exists in the archive
166
+     * @param string $path
167
+     * @return bool
168
+     */
169
+    function fileExists($path) {
170
+        return ($this->zip->locateName($path)!==false) or ($this->zip->locateName($path.'/')!==false);
171
+    }
172
+    /**
173
+     * remove a file or folder from the archive
174
+     * @param string $path
175
+     * @return bool
176
+     */
177
+    function remove($path) {
178
+        if($this->fileExists($path.'/')) {
179
+            return $this->zip->deleteName($path.'/');
180
+        }else{
181
+            return $this->zip->deleteName($path);
182
+        }
183
+    }
184
+    /**
185
+     * get a file handler
186
+     * @param string $path
187
+     * @param string $mode
188
+     * @return resource
189
+     */
190
+    function getStream($path, $mode) {
191
+        if($mode=='r' or $mode=='rb') {
192
+            return $this->zip->getStream($path);
193
+        } else {
194
+            //since we can't directly get a writable stream,
195
+            //make a temp copy of the file and put it back
196
+            //in the archive when the stream is closed
197
+            if(strrpos($path, '.')!==false) {
198
+                $ext=substr($path, strrpos($path, '.'));
199
+            }else{
200
+                $ext='';
201
+            }
202
+            $tmpFile=\OCP\Files::tmpFile($ext);
203
+            if($this->fileExists($path)) {
204
+                $this->extractFile($path, $tmpFile);
205
+            }
206
+            $handle = fopen($tmpFile, $mode);
207
+            return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
208
+                $this->writeBack($tmpFile, $path);
209
+            });
210
+        }
211
+    }
212 212
 
213
-	/**
214
-	 * write back temporary files
215
-	 */
216
-	function writeBack($tmpFile, $path) {
217
-		$this->addFile($path, $tmpFile);
218
-		unlink($tmpFile);
219
-	}
213
+    /**
214
+     * write back temporary files
215
+     */
216
+    function writeBack($tmpFile, $path) {
217
+        $this->addFile($path, $tmpFile);
218
+        unlink($tmpFile);
219
+    }
220 220
 
221
-	/**
222
-	 * @param string $path
223
-	 * @return string
224
-	 */
225
-	private function stripPath($path) {
226
-		if(!$path || $path[0]=='/') {
227
-			return substr($path, 1);
228
-		}else{
229
-			return $path;
230
-		}
231
-	}
221
+    /**
222
+     * @param string $path
223
+     * @return string
224
+     */
225
+    private function stripPath($path) {
226
+        if(!$path || $path[0]=='/') {
227
+            return substr($path, 1);
228
+        }else{
229
+            return $path;
230
+        }
231
+    }
232 232
 }
Please login to merge, or discard this patch.
Spacing   +40 added lines, -40 removed lines patch added patch discarded remove patch
@@ -33,21 +33,21 @@  discard block
 block discarded – undo
33 33
 
34 34
 use Icewind\Streams\CallbackWrapper;
35 35
 
36
-class ZIP extends Archive{
36
+class ZIP extends Archive {
37 37
 	/**
38 38
 	 * @var \ZipArchive zip
39 39
 	 */
40
-	private $zip=null;
40
+	private $zip = null;
41 41
 	private $path;
42 42
 
43 43
 	/**
44 44
 	 * @param string $source
45 45
 	 */
46 46
 	function __construct($source) {
47
-		$this->path=$source;
48
-		$this->zip=new \ZipArchive();
49
-		if($this->zip->open($source, \ZipArchive::CREATE)) {
50
-		}else{
47
+		$this->path = $source;
48
+		$this->zip = new \ZipArchive();
49
+		if ($this->zip->open($source, \ZipArchive::CREATE)) {
50
+		} else {
51 51
 			\OCP\Util::writeLog('files_archive', 'Error while opening archive '.$source, \OCP\Util::WARN);
52 52
 		}
53 53
 	}
@@ -65,14 +65,14 @@  discard block
 block discarded – undo
65 65
 	 * @param string $source either a local file or string data
66 66
 	 * @return bool
67 67
 	 */
68
-	function addFile($path, $source='') {
69
-		if($source and $source[0]=='/' and file_exists($source)) {
70
-			$result=$this->zip->addFile($source, $path);
71
-		}else{
72
-			$result=$this->zip->addFromString($path, $source);
68
+	function addFile($path, $source = '') {
69
+		if ($source and $source[0] == '/' and file_exists($source)) {
70
+			$result = $this->zip->addFile($source, $path);
71
+		} else {
72
+			$result = $this->zip->addFromString($path, $source);
73 73
 		}
74
-		if($result) {
75
-			$this->zip->close();//close and reopen to save the zip
74
+		if ($result) {
75
+			$this->zip->close(); //close and reopen to save the zip
76 76
 			$this->zip->open($this->path);
77 77
 		}
78 78
 		return $result;
@@ -84,8 +84,8 @@  discard block
 block discarded – undo
84 84
 	 * @return boolean|null
85 85
 	 */
86 86
 	function rename($source, $dest) {
87
-		$source=$this->stripPath($source);
88
-		$dest=$this->stripPath($dest);
87
+		$source = $this->stripPath($source);
88
+		$dest = $this->stripPath($dest);
89 89
 		$this->zip->renameName($source, $dest);
90 90
 	}
91 91
 	/**
@@ -94,7 +94,7 @@  discard block
 block discarded – undo
94 94
 	 * @return int
95 95
 	 */
96 96
 	function filesize($path) {
97
-		$stat=$this->zip->statName($path);
97
+		$stat = $this->zip->statName($path);
98 98
 		return $stat['size'];
99 99
 	}
100 100
 	/**
@@ -111,13 +111,13 @@  discard block
 block discarded – undo
111 111
 	 * @return array
112 112
 	 */
113 113
 	function getFolder($path) {
114
-		$files=$this->getFiles();
115
-		$folderContent=array();
116
-		$pathLength=strlen($path);
117
-		foreach($files as $file) {
118
-			if(substr($file, 0, $pathLength)==$path and $file!=$path) {
119
-				if(strrpos(substr($file, 0, -1), '/')<=$pathLength) {
120
-					$folderContent[]=substr($file, $pathLength);
114
+		$files = $this->getFiles();
115
+		$folderContent = array();
116
+		$pathLength = strlen($path);
117
+		foreach ($files as $file) {
118
+			if (substr($file, 0, $pathLength) == $path and $file != $path) {
119
+				if (strrpos(substr($file, 0, -1), '/') <= $pathLength) {
120
+					$folderContent[] = substr($file, $pathLength);
121 121
 				}
122 122
 			}
123 123
 		}
@@ -128,10 +128,10 @@  discard block
 block discarded – undo
128 128
 	 * @return array
129 129
 	 */
130 130
 	function getFiles() {
131
-		$fileCount=$this->zip->numFiles;
132
-		$files=array();
133
-		for($i=0;$i<$fileCount;$i++) {
134
-			$files[]=$this->zip->getNameIndex($i);
131
+		$fileCount = $this->zip->numFiles;
132
+		$files = array();
133
+		for ($i = 0; $i < $fileCount; $i++) {
134
+			$files[] = $this->zip->getNameIndex($i);
135 135
 		}
136 136
 		return $files;
137 137
 	}
@@ -167,7 +167,7 @@  discard block
 block discarded – undo
167 167
 	 * @return bool
168 168
 	 */
169 169
 	function fileExists($path) {
170
-		return ($this->zip->locateName($path)!==false) or ($this->zip->locateName($path.'/')!==false);
170
+		return ($this->zip->locateName($path) !== false) or ($this->zip->locateName($path.'/') !== false);
171 171
 	}
172 172
 	/**
173 173
 	 * remove a file or folder from the archive
@@ -175,9 +175,9 @@  discard block
 block discarded – undo
175 175
 	 * @return bool
176 176
 	 */
177 177
 	function remove($path) {
178
-		if($this->fileExists($path.'/')) {
178
+		if ($this->fileExists($path.'/')) {
179 179
 			return $this->zip->deleteName($path.'/');
180
-		}else{
180
+		} else {
181 181
 			return $this->zip->deleteName($path);
182 182
 		}
183 183
 	}
@@ -188,23 +188,23 @@  discard block
 block discarded – undo
188 188
 	 * @return resource
189 189
 	 */
190 190
 	function getStream($path, $mode) {
191
-		if($mode=='r' or $mode=='rb') {
191
+		if ($mode == 'r' or $mode == 'rb') {
192 192
 			return $this->zip->getStream($path);
193 193
 		} else {
194 194
 			//since we can't directly get a writable stream,
195 195
 			//make a temp copy of the file and put it back
196 196
 			//in the archive when the stream is closed
197
-			if(strrpos($path, '.')!==false) {
198
-				$ext=substr($path, strrpos($path, '.'));
199
-			}else{
200
-				$ext='';
197
+			if (strrpos($path, '.') !== false) {
198
+				$ext = substr($path, strrpos($path, '.'));
199
+			} else {
200
+				$ext = '';
201 201
 			}
202
-			$tmpFile=\OCP\Files::tmpFile($ext);
203
-			if($this->fileExists($path)) {
202
+			$tmpFile = \OCP\Files::tmpFile($ext);
203
+			if ($this->fileExists($path)) {
204 204
 				$this->extractFile($path, $tmpFile);
205 205
 			}
206 206
 			$handle = fopen($tmpFile, $mode);
207
-			return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
207
+			return CallbackWrapper::wrap($handle, null, null, function() use ($path, $tmpFile) {
208 208
 				$this->writeBack($tmpFile, $path);
209 209
 			});
210 210
 		}
@@ -223,9 +223,9 @@  discard block
 block discarded – undo
223 223
 	 * @return string
224 224
 	 */
225 225
 	private function stripPath($path) {
226
-		if(!$path || $path[0]=='/') {
226
+		if (!$path || $path[0] == '/') {
227 227
 			return substr($path, 1);
228
-		}else{
228
+		} else {
229 229
 			return $path;
230 230
 		}
231 231
 	}
Please login to merge, or discard this patch.
Braces   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -47,7 +47,7 @@  discard block
 block discarded – undo
47 47
 		$this->path=$source;
48 48
 		$this->zip=new \ZipArchive();
49 49
 		if($this->zip->open($source, \ZipArchive::CREATE)) {
50
-		}else{
50
+		} else{
51 51
 			\OCP\Util::writeLog('files_archive', 'Error while opening archive '.$source, \OCP\Util::WARN);
52 52
 		}
53 53
 	}
@@ -68,7 +68,7 @@  discard block
 block discarded – undo
68 68
 	function addFile($path, $source='') {
69 69
 		if($source and $source[0]=='/' and file_exists($source)) {
70 70
 			$result=$this->zip->addFile($source, $path);
71
-		}else{
71
+		} else{
72 72
 			$result=$this->zip->addFromString($path, $source);
73 73
 		}
74 74
 		if($result) {
@@ -177,7 +177,7 @@  discard block
 block discarded – undo
177 177
 	function remove($path) {
178 178
 		if($this->fileExists($path.'/')) {
179 179
 			return $this->zip->deleteName($path.'/');
180
-		}else{
180
+		} else{
181 181
 			return $this->zip->deleteName($path);
182 182
 		}
183 183
 	}
@@ -196,7 +196,7 @@  discard block
 block discarded – undo
196 196
 			//in the archive when the stream is closed
197 197
 			if(strrpos($path, '.')!==false) {
198 198
 				$ext=substr($path, strrpos($path, '.'));
199
-			}else{
199
+			} else{
200 200
 				$ext='';
201 201
 			}
202 202
 			$tmpFile=\OCP\Files::tmpFile($ext);
@@ -225,7 +225,7 @@  discard block
 block discarded – undo
225 225
 	private function stripPath($path) {
226 226
 		if(!$path || $path[0]=='/') {
227 227
 			return substr($path, 1);
228
-		}else{
228
+		} else{
229 229
 			return $path;
230 230
 		}
231 231
 	}
Please login to merge, or discard this patch.
lib/private/Files/Cache/Wrapper/CacheJail.php 3 patches
Doc Comments   +3 added lines patch added patch discarded remove patch
@@ -194,6 +194,9 @@
 block discarded – undo
194 194
 		return $this->getCache()->getStatus($this->getSourcePath($file));
195 195
 	}
196 196
 
197
+	/**
198
+	 * @param ICacheEntry[] $results
199
+	 */
197 200
 	private function formatSearchResults($results) {
198 201
 		$results = array_filter($results, array($this, 'filterCacheEntry'));
199 202
 		$results = array_values($results);
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -51,7 +51,7 @@  discard block
 block discarded – undo
51 51
 		if ($path === '') {
52 52
 			return $this->root;
53 53
 		} else {
54
-			return $this->root . '/' . ltrim($path, '/');
54
+			return $this->root.'/'.ltrim($path, '/');
55 55
 		}
56 56
 	}
57 57
 
@@ -66,7 +66,7 @@  discard block
 block discarded – undo
66 66
 		$rootLength = strlen($this->root) + 1;
67 67
 		if ($path === $this->root) {
68 68
 			return '';
69
-		} else if (substr($path, 0, $rootLength) === $this->root . '/') {
69
+		} else if (substr($path, 0, $rootLength) === $this->root.'/') {
70 70
 			return substr($path, $rootLength);
71 71
 		} else {
72 72
 			return null;
@@ -86,7 +86,7 @@  discard block
 block discarded – undo
86 86
 
87 87
 	protected function filterCacheEntry($entry) {
88 88
 		$rootLength = strlen($this->root) + 1;
89
-		return ($entry['path'] === $this->root) or (substr($entry['path'], 0, $rootLength) === $this->root . '/');
89
+		return ($entry['path'] === $this->root) or (substr($entry['path'], 0, $rootLength) === $this->root.'/');
90 90
 	}
91 91
 
92 92
 	/**
Please login to merge, or discard this patch.
Indentation   +253 added lines, -253 removed lines patch added patch discarded remove patch
@@ -34,284 +34,284 @@
 block discarded – undo
34 34
  * Jail to a subdirectory of the wrapped cache
35 35
  */
36 36
 class CacheJail extends CacheWrapper {
37
-	/**
38
-	 * @var string
39
-	 */
40
-	protected $root;
37
+    /**
38
+     * @var string
39
+     */
40
+    protected $root;
41 41
 
42
-	/**
43
-	 * @param \OCP\Files\Cache\ICache $cache
44
-	 * @param string $root
45
-	 */
46
-	public function __construct($cache, $root) {
47
-		parent::__construct($cache);
48
-		$this->root = $root;
49
-	}
42
+    /**
43
+     * @param \OCP\Files\Cache\ICache $cache
44
+     * @param string $root
45
+     */
46
+    public function __construct($cache, $root) {
47
+        parent::__construct($cache);
48
+        $this->root = $root;
49
+    }
50 50
 
51
-	protected function getSourcePath($path) {
52
-		if ($path === '') {
53
-			return $this->root;
54
-		} else {
55
-			return $this->root . '/' . ltrim($path, '/');
56
-		}
57
-	}
51
+    protected function getSourcePath($path) {
52
+        if ($path === '') {
53
+            return $this->root;
54
+        } else {
55
+            return $this->root . '/' . ltrim($path, '/');
56
+        }
57
+    }
58 58
 
59
-	/**
60
-	 * @param string $path
61
-	 * @return null|string the jailed path or null if the path is outside the jail
62
-	 */
63
-	protected function getJailedPath($path) {
64
-		if ($this->root === '') {
65
-			return $path;
66
-		}
67
-		$rootLength = strlen($this->root) + 1;
68
-		if ($path === $this->root) {
69
-			return '';
70
-		} else if (substr($path, 0, $rootLength) === $this->root . '/') {
71
-			return substr($path, $rootLength);
72
-		} else {
73
-			return null;
74
-		}
75
-	}
59
+    /**
60
+     * @param string $path
61
+     * @return null|string the jailed path or null if the path is outside the jail
62
+     */
63
+    protected function getJailedPath($path) {
64
+        if ($this->root === '') {
65
+            return $path;
66
+        }
67
+        $rootLength = strlen($this->root) + 1;
68
+        if ($path === $this->root) {
69
+            return '';
70
+        } else if (substr($path, 0, $rootLength) === $this->root . '/') {
71
+            return substr($path, $rootLength);
72
+        } else {
73
+            return null;
74
+        }
75
+    }
76 76
 
77
-	/**
78
-	 * @param ICacheEntry|array $entry
79
-	 * @return array
80
-	 */
81
-	protected function formatCacheEntry($entry) {
82
-		if (isset($entry['path'])) {
83
-			$entry['path'] = $this->getJailedPath($entry['path']);
84
-		}
85
-		return $entry;
86
-	}
77
+    /**
78
+     * @param ICacheEntry|array $entry
79
+     * @return array
80
+     */
81
+    protected function formatCacheEntry($entry) {
82
+        if (isset($entry['path'])) {
83
+            $entry['path'] = $this->getJailedPath($entry['path']);
84
+        }
85
+        return $entry;
86
+    }
87 87
 
88
-	protected function filterCacheEntry($entry) {
89
-		$rootLength = strlen($this->root) + 1;
90
-		return ($entry['path'] === $this->root) or (substr($entry['path'], 0, $rootLength) === $this->root . '/');
91
-	}
88
+    protected function filterCacheEntry($entry) {
89
+        $rootLength = strlen($this->root) + 1;
90
+        return ($entry['path'] === $this->root) or (substr($entry['path'], 0, $rootLength) === $this->root . '/');
91
+    }
92 92
 
93
-	/**
94
-	 * get the stored metadata of a file or folder
95
-	 *
96
-	 * @param string /int $file
97
-	 * @return array|false
98
-	 */
99
-	public function get($file) {
100
-		if (is_string($file) or $file == '') {
101
-			$file = $this->getSourcePath($file);
102
-		}
103
-		return parent::get($file);
104
-	}
93
+    /**
94
+     * get the stored metadata of a file or folder
95
+     *
96
+     * @param string /int $file
97
+     * @return array|false
98
+     */
99
+    public function get($file) {
100
+        if (is_string($file) or $file == '') {
101
+            $file = $this->getSourcePath($file);
102
+        }
103
+        return parent::get($file);
104
+    }
105 105
 
106
-	/**
107
-	 * insert meta data for a new file or folder
108
-	 *
109
-	 * @param string $file
110
-	 * @param array $data
111
-	 *
112
-	 * @return int file id
113
-	 * @throws \RuntimeException
114
-	 */
115
-	public function insert($file, array $data) {
116
-		return $this->getCache()->insert($this->getSourcePath($file), $data);
117
-	}
106
+    /**
107
+     * insert meta data for a new file or folder
108
+     *
109
+     * @param string $file
110
+     * @param array $data
111
+     *
112
+     * @return int file id
113
+     * @throws \RuntimeException
114
+     */
115
+    public function insert($file, array $data) {
116
+        return $this->getCache()->insert($this->getSourcePath($file), $data);
117
+    }
118 118
 
119
-	/**
120
-	 * update the metadata in the cache
121
-	 *
122
-	 * @param int $id
123
-	 * @param array $data
124
-	 */
125
-	public function update($id, array $data) {
126
-		$this->getCache()->update($id, $data);
127
-	}
119
+    /**
120
+     * update the metadata in the cache
121
+     *
122
+     * @param int $id
123
+     * @param array $data
124
+     */
125
+    public function update($id, array $data) {
126
+        $this->getCache()->update($id, $data);
127
+    }
128 128
 
129
-	/**
130
-	 * get the file id for a file
131
-	 *
132
-	 * @param string $file
133
-	 * @return int
134
-	 */
135
-	public function getId($file) {
136
-		return $this->getCache()->getId($this->getSourcePath($file));
137
-	}
129
+    /**
130
+     * get the file id for a file
131
+     *
132
+     * @param string $file
133
+     * @return int
134
+     */
135
+    public function getId($file) {
136
+        return $this->getCache()->getId($this->getSourcePath($file));
137
+    }
138 138
 
139
-	/**
140
-	 * get the id of the parent folder of a file
141
-	 *
142
-	 * @param string $file
143
-	 * @return int
144
-	 */
145
-	public function getParentId($file) {
146
-		return $this->getCache()->getParentId($this->getSourcePath($file));
147
-	}
139
+    /**
140
+     * get the id of the parent folder of a file
141
+     *
142
+     * @param string $file
143
+     * @return int
144
+     */
145
+    public function getParentId($file) {
146
+        return $this->getCache()->getParentId($this->getSourcePath($file));
147
+    }
148 148
 
149
-	/**
150
-	 * check if a file is available in the cache
151
-	 *
152
-	 * @param string $file
153
-	 * @return bool
154
-	 */
155
-	public function inCache($file) {
156
-		return $this->getCache()->inCache($this->getSourcePath($file));
157
-	}
149
+    /**
150
+     * check if a file is available in the cache
151
+     *
152
+     * @param string $file
153
+     * @return bool
154
+     */
155
+    public function inCache($file) {
156
+        return $this->getCache()->inCache($this->getSourcePath($file));
157
+    }
158 158
 
159
-	/**
160
-	 * remove a file or folder from the cache
161
-	 *
162
-	 * @param string $file
163
-	 */
164
-	public function remove($file) {
165
-		$this->getCache()->remove($this->getSourcePath($file));
166
-	}
159
+    /**
160
+     * remove a file or folder from the cache
161
+     *
162
+     * @param string $file
163
+     */
164
+    public function remove($file) {
165
+        $this->getCache()->remove($this->getSourcePath($file));
166
+    }
167 167
 
168
-	/**
169
-	 * Move a file or folder in the cache
170
-	 *
171
-	 * @param string $source
172
-	 * @param string $target
173
-	 */
174
-	public function move($source, $target) {
175
-		$this->getCache()->move($this->getSourcePath($source), $this->getSourcePath($target));
176
-	}
168
+    /**
169
+     * Move a file or folder in the cache
170
+     *
171
+     * @param string $source
172
+     * @param string $target
173
+     */
174
+    public function move($source, $target) {
175
+        $this->getCache()->move($this->getSourcePath($source), $this->getSourcePath($target));
176
+    }
177 177
 
178
-	/**
179
-	 * remove all entries for files that are stored on the storage from the cache
180
-	 */
181
-	public function clear() {
182
-		$this->getCache()->remove($this->root);
183
-	}
178
+    /**
179
+     * remove all entries for files that are stored on the storage from the cache
180
+     */
181
+    public function clear() {
182
+        $this->getCache()->remove($this->root);
183
+    }
184 184
 
185
-	/**
186
-	 * @param string $file
187
-	 *
188
-	 * @return int Cache::NOT_FOUND, Cache::PARTIAL, Cache::SHALLOW or Cache::COMPLETE
189
-	 */
190
-	public function getStatus($file) {
191
-		return $this->getCache()->getStatus($this->getSourcePath($file));
192
-	}
185
+    /**
186
+     * @param string $file
187
+     *
188
+     * @return int Cache::NOT_FOUND, Cache::PARTIAL, Cache::SHALLOW or Cache::COMPLETE
189
+     */
190
+    public function getStatus($file) {
191
+        return $this->getCache()->getStatus($this->getSourcePath($file));
192
+    }
193 193
 
194
-	private function formatSearchResults($results) {
195
-		$results = array_filter($results, array($this, 'filterCacheEntry'));
196
-		$results = array_values($results);
197
-		return array_map(array($this, 'formatCacheEntry'), $results);
198
-	}
194
+    private function formatSearchResults($results) {
195
+        $results = array_filter($results, array($this, 'filterCacheEntry'));
196
+        $results = array_values($results);
197
+        return array_map(array($this, 'formatCacheEntry'), $results);
198
+    }
199 199
 
200
-	/**
201
-	 * search for files matching $pattern
202
-	 *
203
-	 * @param string $pattern
204
-	 * @return array an array of file data
205
-	 */
206
-	public function search($pattern) {
207
-		$results = $this->getCache()->search($pattern);
208
-		return $this->formatSearchResults($results);
209
-	}
200
+    /**
201
+     * search for files matching $pattern
202
+     *
203
+     * @param string $pattern
204
+     * @return array an array of file data
205
+     */
206
+    public function search($pattern) {
207
+        $results = $this->getCache()->search($pattern);
208
+        return $this->formatSearchResults($results);
209
+    }
210 210
 
211
-	/**
212
-	 * search for files by mimetype
213
-	 *
214
-	 * @param string $mimetype
215
-	 * @return array
216
-	 */
217
-	public function searchByMime($mimetype) {
218
-		$results = $this->getCache()->searchByMime($mimetype);
219
-		return $this->formatSearchResults($results);
220
-	}
211
+    /**
212
+     * search for files by mimetype
213
+     *
214
+     * @param string $mimetype
215
+     * @return array
216
+     */
217
+    public function searchByMime($mimetype) {
218
+        $results = $this->getCache()->searchByMime($mimetype);
219
+        return $this->formatSearchResults($results);
220
+    }
221 221
 
222
-	public function searchQuery(ISearchQuery $query) {
223
-		$results = $this->getCache()->searchQuery($query);
224
-		return $this->formatSearchResults($results);
225
-	}
222
+    public function searchQuery(ISearchQuery $query) {
223
+        $results = $this->getCache()->searchQuery($query);
224
+        return $this->formatSearchResults($results);
225
+    }
226 226
 
227
-	/**
228
-	 * search for files by mimetype
229
-	 *
230
-	 * @param string|int $tag name or tag id
231
-	 * @param string $userId owner of the tags
232
-	 * @return array
233
-	 */
234
-	public function searchByTag($tag, $userId) {
235
-		$results = $this->getCache()->searchByTag($tag, $userId);
236
-		return $this->formatSearchResults($results);
237
-	}
227
+    /**
228
+     * search for files by mimetype
229
+     *
230
+     * @param string|int $tag name or tag id
231
+     * @param string $userId owner of the tags
232
+     * @return array
233
+     */
234
+    public function searchByTag($tag, $userId) {
235
+        $results = $this->getCache()->searchByTag($tag, $userId);
236
+        return $this->formatSearchResults($results);
237
+    }
238 238
 
239
-	/**
240
-	 * update the folder size and the size of all parent folders
241
-	 *
242
-	 * @param string|boolean $path
243
-	 * @param array $data (optional) meta data of the folder
244
-	 */
245
-	public function correctFolderSize($path, $data = null) {
246
-		if ($this->getCache() instanceof Cache) {
247
-			$this->getCache()->correctFolderSize($this->getSourcePath($path), $data);
248
-		}
249
-	}
239
+    /**
240
+     * update the folder size and the size of all parent folders
241
+     *
242
+     * @param string|boolean $path
243
+     * @param array $data (optional) meta data of the folder
244
+     */
245
+    public function correctFolderSize($path, $data = null) {
246
+        if ($this->getCache() instanceof Cache) {
247
+            $this->getCache()->correctFolderSize($this->getSourcePath($path), $data);
248
+        }
249
+    }
250 250
 
251
-	/**
252
-	 * get the size of a folder and set it in the cache
253
-	 *
254
-	 * @param string $path
255
-	 * @param array $entry (optional) meta data of the folder
256
-	 * @return int
257
-	 */
258
-	public function calculateFolderSize($path, $entry = null) {
259
-		if ($this->getCache() instanceof Cache) {
260
-			return $this->getCache()->calculateFolderSize($this->getSourcePath($path), $entry);
261
-		} else {
262
-			return 0;
263
-		}
251
+    /**
252
+     * get the size of a folder and set it in the cache
253
+     *
254
+     * @param string $path
255
+     * @param array $entry (optional) meta data of the folder
256
+     * @return int
257
+     */
258
+    public function calculateFolderSize($path, $entry = null) {
259
+        if ($this->getCache() instanceof Cache) {
260
+            return $this->getCache()->calculateFolderSize($this->getSourcePath($path), $entry);
261
+        } else {
262
+            return 0;
263
+        }
264 264
 
265
-	}
265
+    }
266 266
 
267
-	/**
268
-	 * get all file ids on the files on the storage
269
-	 *
270
-	 * @return int[]
271
-	 */
272
-	public function getAll() {
273
-		// not supported
274
-		return array();
275
-	}
267
+    /**
268
+     * get all file ids on the files on the storage
269
+     *
270
+     * @return int[]
271
+     */
272
+    public function getAll() {
273
+        // not supported
274
+        return array();
275
+    }
276 276
 
277
-	/**
278
-	 * find a folder in the cache which has not been fully scanned
279
-	 *
280
-	 * If multiply incomplete folders are in the cache, the one with the highest id will be returned,
281
-	 * use the one with the highest id gives the best result with the background scanner, since that is most
282
-	 * likely the folder where we stopped scanning previously
283
-	 *
284
-	 * @return string|bool the path of the folder or false when no folder matched
285
-	 */
286
-	public function getIncomplete() {
287
-		// not supported
288
-		return false;
289
-	}
277
+    /**
278
+     * find a folder in the cache which has not been fully scanned
279
+     *
280
+     * If multiply incomplete folders are in the cache, the one with the highest id will be returned,
281
+     * use the one with the highest id gives the best result with the background scanner, since that is most
282
+     * likely the folder where we stopped scanning previously
283
+     *
284
+     * @return string|bool the path of the folder or false when no folder matched
285
+     */
286
+    public function getIncomplete() {
287
+        // not supported
288
+        return false;
289
+    }
290 290
 
291
-	/**
292
-	 * get the path of a file on this storage by it's id
293
-	 *
294
-	 * @param int $id
295
-	 * @return string|null
296
-	 */
297
-	public function getPathById($id) {
298
-		$path = $this->getCache()->getPathById($id);
299
-		return $this->getJailedPath($path);
300
-	}
291
+    /**
292
+     * get the path of a file on this storage by it's id
293
+     *
294
+     * @param int $id
295
+     * @return string|null
296
+     */
297
+    public function getPathById($id) {
298
+        $path = $this->getCache()->getPathById($id);
299
+        return $this->getJailedPath($path);
300
+    }
301 301
 
302
-	/**
303
-	 * Move a file or folder in the cache
304
-	 *
305
-	 * Note that this should make sure the entries are removed from the source cache
306
-	 *
307
-	 * @param \OCP\Files\Cache\ICache $sourceCache
308
-	 * @param string $sourcePath
309
-	 * @param string $targetPath
310
-	 */
311
-	public function moveFromCache(\OCP\Files\Cache\ICache $sourceCache, $sourcePath, $targetPath) {
312
-		if ($sourceCache === $this) {
313
-			return $this->move($sourcePath, $targetPath);
314
-		}
315
-		return $this->getCache()->moveFromCache($sourceCache, $sourcePath, $this->getSourcePath($targetPath));
316
-	}
302
+    /**
303
+     * Move a file or folder in the cache
304
+     *
305
+     * Note that this should make sure the entries are removed from the source cache
306
+     *
307
+     * @param \OCP\Files\Cache\ICache $sourceCache
308
+     * @param string $sourcePath
309
+     * @param string $targetPath
310
+     */
311
+    public function moveFromCache(\OCP\Files\Cache\ICache $sourceCache, $sourcePath, $targetPath) {
312
+        if ($sourceCache === $this) {
313
+            return $this->move($sourcePath, $targetPath);
314
+        }
315
+        return $this->getCache()->moveFromCache($sourceCache, $sourcePath, $this->getSourcePath($targetPath));
316
+    }
317 317
 }
Please login to merge, or discard this patch.
lib/private/Files/FileInfo.php 3 patches
Unused Use Statements   -1 removed lines patch added patch discarded remove patch
@@ -32,7 +32,6 @@
 block discarded – undo
32 32
 
33 33
 use OCP\Files\Cache\ICacheEntry;
34 34
 use OCP\Files\Mount\IMountPoint;
35
-use OCP\Files\Storage\IStorage;
36 35
 use OCP\Files\IHomeStorage;
37 36
 use OCP\IUser;
38 37
 
Please login to merge, or discard this patch.
Indentation   +352 added lines, -352 removed lines patch added patch discarded remove patch
@@ -37,356 +37,356 @@
 block discarded – undo
37 37
 use OCP\IUser;
38 38
 
39 39
 class FileInfo implements \OCP\Files\FileInfo, \ArrayAccess {
40
-	/**
41
-	 * @var array $data
42
-	 */
43
-	private $data;
44
-
45
-	/**
46
-	 * @var string $path
47
-	 */
48
-	private $path;
49
-
50
-	/**
51
-	 * @var \OC\Files\Storage\Storage $storage
52
-	 */
53
-	private $storage;
54
-
55
-	/**
56
-	 * @var string $internalPath
57
-	 */
58
-	private $internalPath;
59
-
60
-	/**
61
-	 * @var \OCP\Files\Mount\IMountPoint
62
-	 */
63
-	private $mount;
64
-
65
-	/**
66
-	 * @var IUser
67
-	 */
68
-	private $owner;
69
-
70
-	/**
71
-	 * @var string[]
72
-	 */
73
-	private $childEtags = [];
74
-
75
-	/**
76
-	 * @var IMountPoint[]
77
-	 */
78
-	private $subMounts = [];
79
-
80
-	private $subMountsUsed = false;
81
-
82
-	/**
83
-	 * @param string|boolean $path
84
-	 * @param Storage\Storage $storage
85
-	 * @param string $internalPath
86
-	 * @param array|ICacheEntry $data
87
-	 * @param \OCP\Files\Mount\IMountPoint $mount
88
-	 * @param \OCP\IUser|null $owner
89
-	 */
90
-	public function __construct($path, $storage, $internalPath, $data, $mount, $owner= null) {
91
-		$this->path = $path;
92
-		$this->storage = $storage;
93
-		$this->internalPath = $internalPath;
94
-		$this->data = $data;
95
-		$this->mount = $mount;
96
-		$this->owner = $owner;
97
-	}
98
-
99
-	public function offsetSet($offset, $value) {
100
-		$this->data[$offset] = $value;
101
-	}
102
-
103
-	public function offsetExists($offset) {
104
-		return isset($this->data[$offset]);
105
-	}
106
-
107
-	public function offsetUnset($offset) {
108
-		unset($this->data[$offset]);
109
-	}
110
-
111
-	public function offsetGet($offset) {
112
-		if ($offset === 'type') {
113
-			return $this->getType();
114
-		} else if ($offset === 'etag') {
115
-			return $this->getEtag();
116
-		} else if ($offset === 'size') {
117
-			return $this->getSize();
118
-		} else if ($offset === 'mtime') {
119
-			return $this->getMTime();
120
-		} elseif ($offset === 'permissions') {
121
-			return $this->getPermissions();
122
-		} elseif (isset($this->data[$offset])) {
123
-			return $this->data[$offset];
124
-		} else {
125
-			return null;
126
-		}
127
-	}
128
-
129
-	/**
130
-	 * @return string
131
-	 */
132
-	public function getPath() {
133
-		return $this->path;
134
-	}
135
-
136
-	/**
137
-	 * @return \OCP\Files\Storage
138
-	 */
139
-	public function getStorage() {
140
-		return $this->storage;
141
-	}
142
-
143
-	/**
144
-	 * @return string
145
-	 */
146
-	public function getInternalPath() {
147
-		return $this->internalPath;
148
-	}
149
-
150
-	/**
151
-	 * Get FileInfo ID or null in case of part file
152
-	 *
153
-	 * @return int|null
154
-	 */
155
-	public function getId() {
156
-		return isset($this->data['fileid']) ? (int)  $this->data['fileid'] : null;
157
-	}
158
-
159
-	/**
160
-	 * @return string
161
-	 */
162
-	public function getMimetype() {
163
-		return $this->data['mimetype'];
164
-	}
165
-
166
-	/**
167
-	 * @return string
168
-	 */
169
-	public function getMimePart() {
170
-		return $this->data['mimepart'];
171
-	}
172
-
173
-	/**
174
-	 * @return string
175
-	 */
176
-	public function getName() {
177
-		return basename($this->getPath());
178
-	}
179
-
180
-	/**
181
-	 * @return string
182
-	 */
183
-	public function getEtag() {
184
-		$this->updateEntryfromSubMounts();
185
-		if (count($this->childEtags) > 0) {
186
-			$combinedEtag = $this->data['etag'] . '::' . implode('::', $this->childEtags);
187
-			return md5($combinedEtag);
188
-		} else {
189
-			return $this->data['etag'];
190
-		}
191
-	}
192
-
193
-	/**
194
-	 * @return int
195
-	 */
196
-	public function getSize() {
197
-		$this->updateEntryfromSubMounts();
198
-		return isset($this->data['size']) ? (int) $this->data['size'] : 0;
199
-	}
200
-
201
-	/**
202
-	 * @return int
203
-	 */
204
-	public function getMTime() {
205
-		$this->updateEntryfromSubMounts();
206
-		return (int) $this->data['mtime'];
207
-	}
208
-
209
-	/**
210
-	 * @return bool
211
-	 */
212
-	public function isEncrypted() {
213
-		return $this->data['encrypted'];
214
-	}
215
-
216
-	/**
217
-	 * Return the currently version used for the HMAC in the encryption app
218
-	 *
219
-	 * @return int
220
-	 */
221
-	public function getEncryptedVersion() {
222
-		return isset($this->data['encryptedVersion']) ? (int) $this->data['encryptedVersion'] : 1;
223
-	}
224
-
225
-	/**
226
-	 * @return int
227
-	 */
228
-	public function getPermissions() {
229
-		$perms = (int) $this->data['permissions'];
230
-		if (\OCP\Util::isSharingDisabledForUser() || ($this->isShared() && !\OC\Share\Share::isResharingAllowed())) {
231
-			$perms = $perms & ~\OCP\Constants::PERMISSION_SHARE;
232
-		}
233
-		return (int) $perms;
234
-	}
235
-
236
-	/**
237
-	 * @return \OCP\Files\FileInfo::TYPE_FILE|\OCP\Files\FileInfo::TYPE_FOLDER
238
-	 */
239
-	public function getType() {
240
-		if (!isset($this->data['type'])) {
241
-			$this->data['type'] = ($this->getMimetype() === 'httpd/unix-directory') ? self::TYPE_FOLDER : self::TYPE_FILE;
242
-		}
243
-		return $this->data['type'];
244
-	}
245
-
246
-	public function getData() {
247
-		return $this->data;
248
-	}
249
-
250
-	/**
251
-	 * @param int $permissions
252
-	 * @return bool
253
-	 */
254
-	protected function checkPermissions($permissions) {
255
-		return ($this->getPermissions() & $permissions) === $permissions;
256
-	}
257
-
258
-	/**
259
-	 * @return bool
260
-	 */
261
-	public function isReadable() {
262
-		return $this->checkPermissions(\OCP\Constants::PERMISSION_READ);
263
-	}
264
-
265
-	/**
266
-	 * @return bool
267
-	 */
268
-	public function isUpdateable() {
269
-		return $this->checkPermissions(\OCP\Constants::PERMISSION_UPDATE);
270
-	}
271
-
272
-	/**
273
-	 * Check whether new files or folders can be created inside this folder
274
-	 *
275
-	 * @return bool
276
-	 */
277
-	public function isCreatable() {
278
-		return $this->checkPermissions(\OCP\Constants::PERMISSION_CREATE);
279
-	}
280
-
281
-	/**
282
-	 * @return bool
283
-	 */
284
-	public function isDeletable() {
285
-		return $this->checkPermissions(\OCP\Constants::PERMISSION_DELETE);
286
-	}
287
-
288
-	/**
289
-	 * @return bool
290
-	 */
291
-	public function isShareable() {
292
-		return $this->checkPermissions(\OCP\Constants::PERMISSION_SHARE);
293
-	}
294
-
295
-	/**
296
-	 * Check if a file or folder is shared
297
-	 *
298
-	 * @return bool
299
-	 */
300
-	public function isShared() {
301
-		$sid = $this->getStorage()->getId();
302
-		if (!is_null($sid)) {
303
-			$sid = explode(':', $sid);
304
-			return ($sid[0] === 'shared');
305
-		}
306
-
307
-		return false;
308
-	}
309
-
310
-	public function isMounted() {
311
-		$storage = $this->getStorage();
312
-		if ($storage->instanceOfStorage('\OCP\Files\IHomeStorage')) {
313
-			return false;
314
-		}
315
-		$sid = $storage->getId();
316
-		if (!is_null($sid)) {
317
-			$sid = explode(':', $sid);
318
-			return ($sid[0] !== 'home' and $sid[0] !== 'shared');
319
-		}
320
-
321
-		return false;
322
-	}
323
-
324
-	/**
325
-	 * Get the mountpoint the file belongs to
326
-	 *
327
-	 * @return \OCP\Files\Mount\IMountPoint
328
-	 */
329
-	public function getMountPoint() {
330
-		return $this->mount;
331
-	}
332
-
333
-	/**
334
-	 * Get the owner of the file
335
-	 *
336
-	 * @return \OCP\IUser
337
-	 */
338
-	public function getOwner() {
339
-		return $this->owner;
340
-	}
341
-
342
-	/**
343
-	 * @param IMountPoint[] $mounts
344
-	 */
345
-	public function setSubMounts(array $mounts) {
346
-		$this->subMounts = $mounts;
347
-	}
348
-
349
-	private function updateEntryfromSubMounts() {
350
-		if ($this->subMountsUsed) {
351
-			return;
352
-		}
353
-		$this->subMountsUsed = true;
354
-		foreach ($this->subMounts as $mount) {
355
-			$subStorage = $mount->getStorage();
356
-			if ($subStorage) {
357
-				$subCache = $subStorage->getCache('');
358
-				$rootEntry = $subCache->get('');
359
-				$this->addSubEntry($rootEntry, $mount->getMountPoint());
360
-			}
361
-		}
362
-	}
363
-
364
-	/**
365
-	 * Add a cache entry which is the child of this folder
366
-	 *
367
-	 * Sets the size, etag and size to for cross-storage childs
368
-	 *
369
-	 * @param array|ICacheEntry $data cache entry for the child
370
-	 * @param string $entryPath full path of the child entry
371
-	 */
372
-	public function addSubEntry($data, $entryPath) {
373
-		$this->data['size'] += isset($data['size']) ? $data['size'] : 0;
374
-		if (isset($data['mtime'])) {
375
-			$this->data['mtime'] = max($this->data['mtime'], $data['mtime']);
376
-		}
377
-		if (isset($data['etag'])) {
378
-			// prefix the etag with the relative path of the subentry to propagate etag on mount moves
379
-			$relativeEntryPath = substr($entryPath, strlen($this->getPath()));
380
-			// attach the permissions to propagate etag on permision changes of submounts
381
-			$permissions = isset($data['permissions']) ? $data['permissions'] : 0;
382
-			$this->childEtags[] = $relativeEntryPath . '/' . $data['etag'] . $permissions;
383
-		}
384
-	}
385
-
386
-	/**
387
-	 * @inheritdoc
388
-	 */
389
-	public function getChecksum() {
390
-		return $this->data['checksum'];
391
-	}
40
+    /**
41
+     * @var array $data
42
+     */
43
+    private $data;
44
+
45
+    /**
46
+     * @var string $path
47
+     */
48
+    private $path;
49
+
50
+    /**
51
+     * @var \OC\Files\Storage\Storage $storage
52
+     */
53
+    private $storage;
54
+
55
+    /**
56
+     * @var string $internalPath
57
+     */
58
+    private $internalPath;
59
+
60
+    /**
61
+     * @var \OCP\Files\Mount\IMountPoint
62
+     */
63
+    private $mount;
64
+
65
+    /**
66
+     * @var IUser
67
+     */
68
+    private $owner;
69
+
70
+    /**
71
+     * @var string[]
72
+     */
73
+    private $childEtags = [];
74
+
75
+    /**
76
+     * @var IMountPoint[]
77
+     */
78
+    private $subMounts = [];
79
+
80
+    private $subMountsUsed = false;
81
+
82
+    /**
83
+     * @param string|boolean $path
84
+     * @param Storage\Storage $storage
85
+     * @param string $internalPath
86
+     * @param array|ICacheEntry $data
87
+     * @param \OCP\Files\Mount\IMountPoint $mount
88
+     * @param \OCP\IUser|null $owner
89
+     */
90
+    public function __construct($path, $storage, $internalPath, $data, $mount, $owner= null) {
91
+        $this->path = $path;
92
+        $this->storage = $storage;
93
+        $this->internalPath = $internalPath;
94
+        $this->data = $data;
95
+        $this->mount = $mount;
96
+        $this->owner = $owner;
97
+    }
98
+
99
+    public function offsetSet($offset, $value) {
100
+        $this->data[$offset] = $value;
101
+    }
102
+
103
+    public function offsetExists($offset) {
104
+        return isset($this->data[$offset]);
105
+    }
106
+
107
+    public function offsetUnset($offset) {
108
+        unset($this->data[$offset]);
109
+    }
110
+
111
+    public function offsetGet($offset) {
112
+        if ($offset === 'type') {
113
+            return $this->getType();
114
+        } else if ($offset === 'etag') {
115
+            return $this->getEtag();
116
+        } else if ($offset === 'size') {
117
+            return $this->getSize();
118
+        } else if ($offset === 'mtime') {
119
+            return $this->getMTime();
120
+        } elseif ($offset === 'permissions') {
121
+            return $this->getPermissions();
122
+        } elseif (isset($this->data[$offset])) {
123
+            return $this->data[$offset];
124
+        } else {
125
+            return null;
126
+        }
127
+    }
128
+
129
+    /**
130
+     * @return string
131
+     */
132
+    public function getPath() {
133
+        return $this->path;
134
+    }
135
+
136
+    /**
137
+     * @return \OCP\Files\Storage
138
+     */
139
+    public function getStorage() {
140
+        return $this->storage;
141
+    }
142
+
143
+    /**
144
+     * @return string
145
+     */
146
+    public function getInternalPath() {
147
+        return $this->internalPath;
148
+    }
149
+
150
+    /**
151
+     * Get FileInfo ID or null in case of part file
152
+     *
153
+     * @return int|null
154
+     */
155
+    public function getId() {
156
+        return isset($this->data['fileid']) ? (int)  $this->data['fileid'] : null;
157
+    }
158
+
159
+    /**
160
+     * @return string
161
+     */
162
+    public function getMimetype() {
163
+        return $this->data['mimetype'];
164
+    }
165
+
166
+    /**
167
+     * @return string
168
+     */
169
+    public function getMimePart() {
170
+        return $this->data['mimepart'];
171
+    }
172
+
173
+    /**
174
+     * @return string
175
+     */
176
+    public function getName() {
177
+        return basename($this->getPath());
178
+    }
179
+
180
+    /**
181
+     * @return string
182
+     */
183
+    public function getEtag() {
184
+        $this->updateEntryfromSubMounts();
185
+        if (count($this->childEtags) > 0) {
186
+            $combinedEtag = $this->data['etag'] . '::' . implode('::', $this->childEtags);
187
+            return md5($combinedEtag);
188
+        } else {
189
+            return $this->data['etag'];
190
+        }
191
+    }
192
+
193
+    /**
194
+     * @return int
195
+     */
196
+    public function getSize() {
197
+        $this->updateEntryfromSubMounts();
198
+        return isset($this->data['size']) ? (int) $this->data['size'] : 0;
199
+    }
200
+
201
+    /**
202
+     * @return int
203
+     */
204
+    public function getMTime() {
205
+        $this->updateEntryfromSubMounts();
206
+        return (int) $this->data['mtime'];
207
+    }
208
+
209
+    /**
210
+     * @return bool
211
+     */
212
+    public function isEncrypted() {
213
+        return $this->data['encrypted'];
214
+    }
215
+
216
+    /**
217
+     * Return the currently version used for the HMAC in the encryption app
218
+     *
219
+     * @return int
220
+     */
221
+    public function getEncryptedVersion() {
222
+        return isset($this->data['encryptedVersion']) ? (int) $this->data['encryptedVersion'] : 1;
223
+    }
224
+
225
+    /**
226
+     * @return int
227
+     */
228
+    public function getPermissions() {
229
+        $perms = (int) $this->data['permissions'];
230
+        if (\OCP\Util::isSharingDisabledForUser() || ($this->isShared() && !\OC\Share\Share::isResharingAllowed())) {
231
+            $perms = $perms & ~\OCP\Constants::PERMISSION_SHARE;
232
+        }
233
+        return (int) $perms;
234
+    }
235
+
236
+    /**
237
+     * @return \OCP\Files\FileInfo::TYPE_FILE|\OCP\Files\FileInfo::TYPE_FOLDER
238
+     */
239
+    public function getType() {
240
+        if (!isset($this->data['type'])) {
241
+            $this->data['type'] = ($this->getMimetype() === 'httpd/unix-directory') ? self::TYPE_FOLDER : self::TYPE_FILE;
242
+        }
243
+        return $this->data['type'];
244
+    }
245
+
246
+    public function getData() {
247
+        return $this->data;
248
+    }
249
+
250
+    /**
251
+     * @param int $permissions
252
+     * @return bool
253
+     */
254
+    protected function checkPermissions($permissions) {
255
+        return ($this->getPermissions() & $permissions) === $permissions;
256
+    }
257
+
258
+    /**
259
+     * @return bool
260
+     */
261
+    public function isReadable() {
262
+        return $this->checkPermissions(\OCP\Constants::PERMISSION_READ);
263
+    }
264
+
265
+    /**
266
+     * @return bool
267
+     */
268
+    public function isUpdateable() {
269
+        return $this->checkPermissions(\OCP\Constants::PERMISSION_UPDATE);
270
+    }
271
+
272
+    /**
273
+     * Check whether new files or folders can be created inside this folder
274
+     *
275
+     * @return bool
276
+     */
277
+    public function isCreatable() {
278
+        return $this->checkPermissions(\OCP\Constants::PERMISSION_CREATE);
279
+    }
280
+
281
+    /**
282
+     * @return bool
283
+     */
284
+    public function isDeletable() {
285
+        return $this->checkPermissions(\OCP\Constants::PERMISSION_DELETE);
286
+    }
287
+
288
+    /**
289
+     * @return bool
290
+     */
291
+    public function isShareable() {
292
+        return $this->checkPermissions(\OCP\Constants::PERMISSION_SHARE);
293
+    }
294
+
295
+    /**
296
+     * Check if a file or folder is shared
297
+     *
298
+     * @return bool
299
+     */
300
+    public function isShared() {
301
+        $sid = $this->getStorage()->getId();
302
+        if (!is_null($sid)) {
303
+            $sid = explode(':', $sid);
304
+            return ($sid[0] === 'shared');
305
+        }
306
+
307
+        return false;
308
+    }
309
+
310
+    public function isMounted() {
311
+        $storage = $this->getStorage();
312
+        if ($storage->instanceOfStorage('\OCP\Files\IHomeStorage')) {
313
+            return false;
314
+        }
315
+        $sid = $storage->getId();
316
+        if (!is_null($sid)) {
317
+            $sid = explode(':', $sid);
318
+            return ($sid[0] !== 'home' and $sid[0] !== 'shared');
319
+        }
320
+
321
+        return false;
322
+    }
323
+
324
+    /**
325
+     * Get the mountpoint the file belongs to
326
+     *
327
+     * @return \OCP\Files\Mount\IMountPoint
328
+     */
329
+    public function getMountPoint() {
330
+        return $this->mount;
331
+    }
332
+
333
+    /**
334
+     * Get the owner of the file
335
+     *
336
+     * @return \OCP\IUser
337
+     */
338
+    public function getOwner() {
339
+        return $this->owner;
340
+    }
341
+
342
+    /**
343
+     * @param IMountPoint[] $mounts
344
+     */
345
+    public function setSubMounts(array $mounts) {
346
+        $this->subMounts = $mounts;
347
+    }
348
+
349
+    private function updateEntryfromSubMounts() {
350
+        if ($this->subMountsUsed) {
351
+            return;
352
+        }
353
+        $this->subMountsUsed = true;
354
+        foreach ($this->subMounts as $mount) {
355
+            $subStorage = $mount->getStorage();
356
+            if ($subStorage) {
357
+                $subCache = $subStorage->getCache('');
358
+                $rootEntry = $subCache->get('');
359
+                $this->addSubEntry($rootEntry, $mount->getMountPoint());
360
+            }
361
+        }
362
+    }
363
+
364
+    /**
365
+     * Add a cache entry which is the child of this folder
366
+     *
367
+     * Sets the size, etag and size to for cross-storage childs
368
+     *
369
+     * @param array|ICacheEntry $data cache entry for the child
370
+     * @param string $entryPath full path of the child entry
371
+     */
372
+    public function addSubEntry($data, $entryPath) {
373
+        $this->data['size'] += isset($data['size']) ? $data['size'] : 0;
374
+        if (isset($data['mtime'])) {
375
+            $this->data['mtime'] = max($this->data['mtime'], $data['mtime']);
376
+        }
377
+        if (isset($data['etag'])) {
378
+            // prefix the etag with the relative path of the subentry to propagate etag on mount moves
379
+            $relativeEntryPath = substr($entryPath, strlen($this->getPath()));
380
+            // attach the permissions to propagate etag on permision changes of submounts
381
+            $permissions = isset($data['permissions']) ? $data['permissions'] : 0;
382
+            $this->childEtags[] = $relativeEntryPath . '/' . $data['etag'] . $permissions;
383
+        }
384
+    }
385
+
386
+    /**
387
+     * @inheritdoc
388
+     */
389
+    public function getChecksum() {
390
+        return $this->data['checksum'];
391
+    }
392 392
 }
Please login to merge, or discard this patch.
Spacing   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -87,7 +87,7 @@  discard block
 block discarded – undo
87 87
 	 * @param \OCP\Files\Mount\IMountPoint $mount
88 88
 	 * @param \OCP\IUser|null $owner
89 89
 	 */
90
-	public function __construct($path, $storage, $internalPath, $data, $mount, $owner= null) {
90
+	public function __construct($path, $storage, $internalPath, $data, $mount, $owner = null) {
91 91
 		$this->path = $path;
92 92
 		$this->storage = $storage;
93 93
 		$this->internalPath = $internalPath;
@@ -153,7 +153,7 @@  discard block
 block discarded – undo
153 153
 	 * @return int|null
154 154
 	 */
155 155
 	public function getId() {
156
-		return isset($this->data['fileid']) ? (int)  $this->data['fileid'] : null;
156
+		return isset($this->data['fileid']) ? (int) $this->data['fileid'] : null;
157 157
 	}
158 158
 
159 159
 	/**
@@ -183,7 +183,7 @@  discard block
 block discarded – undo
183 183
 	public function getEtag() {
184 184
 		$this->updateEntryfromSubMounts();
185 185
 		if (count($this->childEtags) > 0) {
186
-			$combinedEtag = $this->data['etag'] . '::' . implode('::', $this->childEtags);
186
+			$combinedEtag = $this->data['etag'].'::'.implode('::', $this->childEtags);
187 187
 			return md5($combinedEtag);
188 188
 		} else {
189 189
 			return $this->data['etag'];
@@ -379,7 +379,7 @@  discard block
 block discarded – undo
379 379
 			$relativeEntryPath = substr($entryPath, strlen($this->getPath()));
380 380
 			// attach the permissions to propagate etag on permision changes of submounts
381 381
 			$permissions = isset($data['permissions']) ? $data['permissions'] : 0;
382
-			$this->childEtags[] = $relativeEntryPath . '/' . $data['etag'] . $permissions;
382
+			$this->childEtags[] = $relativeEntryPath.'/'.$data['etag'].$permissions;
383 383
 		}
384 384
 	}
385 385
 
Please login to merge, or discard this patch.
lib/private/Group/Manager.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -156,7 +156,7 @@
 block discarded – undo
156 156
 	/**
157 157
 	 * @param string $gid
158 158
 	 * @param string $displayName
159
-	 * @return \OCP\IGroup
159
+	 * @return null|Group
160 160
 	 */
161 161
 	protected function getGroupObject($gid, $displayName = null) {
162 162
 		$backends = array();
Please login to merge, or discard this patch.
Indentation   +318 added lines, -318 removed lines patch added patch discarded remove patch
@@ -58,323 +58,323 @@
 block discarded – undo
58 58
  * @package OC\Group
59 59
  */
60 60
 class Manager extends PublicEmitter implements IGroupManager {
61
-	/**
62
-	 * @var GroupInterface[] $backends
63
-	 */
64
-	private $backends = array();
65
-
66
-	/**
67
-	 * @var \OC\User\Manager $userManager
68
-	 */
69
-	private $userManager;
70
-
71
-	/**
72
-	 * @var \OC\Group\Group[]
73
-	 */
74
-	private $cachedGroups = array();
75
-
76
-	/**
77
-	 * @var \OC\Group\Group[]
78
-	 */
79
-	private $cachedUserGroups = array();
80
-
81
-	/** @var \OC\SubAdmin */
82
-	private $subAdmin = null;
83
-
84
-	/** @var ILogger */
85
-	private $logger;
86
-
87
-	/**
88
-	 * @param \OC\User\Manager $userManager
89
-	 * @param ILogger $logger
90
-	 */
91
-	public function __construct(\OC\User\Manager $userManager, ILogger $logger) {
92
-		$this->userManager = $userManager;
93
-		$this->logger = $logger;
94
-		$cachedGroups = & $this->cachedGroups;
95
-		$cachedUserGroups = & $this->cachedUserGroups;
96
-		$this->listen('\OC\Group', 'postDelete', function ($group) use (&$cachedGroups, &$cachedUserGroups) {
97
-			/**
98
-			 * @var \OC\Group\Group $group
99
-			 */
100
-			unset($cachedGroups[$group->getGID()]);
101
-			$cachedUserGroups = array();
102
-		});
103
-		$this->listen('\OC\Group', 'postAddUser', function ($group) use (&$cachedUserGroups) {
104
-			/**
105
-			 * @var \OC\Group\Group $group
106
-			 */
107
-			$cachedUserGroups = array();
108
-		});
109
-		$this->listen('\OC\Group', 'postRemoveUser', function ($group) use (&$cachedUserGroups) {
110
-			/**
111
-			 * @var \OC\Group\Group $group
112
-			 */
113
-			$cachedUserGroups = array();
114
-		});
115
-	}
116
-
117
-	/**
118
-	 * Checks whether a given backend is used
119
-	 *
120
-	 * @param string $backendClass Full classname including complete namespace
121
-	 * @return bool
122
-	 */
123
-	public function isBackendUsed($backendClass) {
124
-		$backendClass = strtolower(ltrim($backendClass, '\\'));
125
-
126
-		foreach ($this->backends as $backend) {
127
-			if (strtolower(get_class($backend)) === $backendClass) {
128
-				return true;
129
-			}
130
-		}
131
-
132
-		return false;
133
-	}
134
-
135
-	/**
136
-	 * @param \OCP\GroupInterface $backend
137
-	 */
138
-	public function addBackend($backend) {
139
-		$this->backends[] = $backend;
140
-		$this->clearCaches();
141
-	}
142
-
143
-	public function clearBackends() {
144
-		$this->backends = array();
145
-		$this->clearCaches();
146
-	}
61
+    /**
62
+     * @var GroupInterface[] $backends
63
+     */
64
+    private $backends = array();
65
+
66
+    /**
67
+     * @var \OC\User\Manager $userManager
68
+     */
69
+    private $userManager;
70
+
71
+    /**
72
+     * @var \OC\Group\Group[]
73
+     */
74
+    private $cachedGroups = array();
75
+
76
+    /**
77
+     * @var \OC\Group\Group[]
78
+     */
79
+    private $cachedUserGroups = array();
80
+
81
+    /** @var \OC\SubAdmin */
82
+    private $subAdmin = null;
83
+
84
+    /** @var ILogger */
85
+    private $logger;
86
+
87
+    /**
88
+     * @param \OC\User\Manager $userManager
89
+     * @param ILogger $logger
90
+     */
91
+    public function __construct(\OC\User\Manager $userManager, ILogger $logger) {
92
+        $this->userManager = $userManager;
93
+        $this->logger = $logger;
94
+        $cachedGroups = & $this->cachedGroups;
95
+        $cachedUserGroups = & $this->cachedUserGroups;
96
+        $this->listen('\OC\Group', 'postDelete', function ($group) use (&$cachedGroups, &$cachedUserGroups) {
97
+            /**
98
+             * @var \OC\Group\Group $group
99
+             */
100
+            unset($cachedGroups[$group->getGID()]);
101
+            $cachedUserGroups = array();
102
+        });
103
+        $this->listen('\OC\Group', 'postAddUser', function ($group) use (&$cachedUserGroups) {
104
+            /**
105
+             * @var \OC\Group\Group $group
106
+             */
107
+            $cachedUserGroups = array();
108
+        });
109
+        $this->listen('\OC\Group', 'postRemoveUser', function ($group) use (&$cachedUserGroups) {
110
+            /**
111
+             * @var \OC\Group\Group $group
112
+             */
113
+            $cachedUserGroups = array();
114
+        });
115
+    }
116
+
117
+    /**
118
+     * Checks whether a given backend is used
119
+     *
120
+     * @param string $backendClass Full classname including complete namespace
121
+     * @return bool
122
+     */
123
+    public function isBackendUsed($backendClass) {
124
+        $backendClass = strtolower(ltrim($backendClass, '\\'));
125
+
126
+        foreach ($this->backends as $backend) {
127
+            if (strtolower(get_class($backend)) === $backendClass) {
128
+                return true;
129
+            }
130
+        }
131
+
132
+        return false;
133
+    }
134
+
135
+    /**
136
+     * @param \OCP\GroupInterface $backend
137
+     */
138
+    public function addBackend($backend) {
139
+        $this->backends[] = $backend;
140
+        $this->clearCaches();
141
+    }
142
+
143
+    public function clearBackends() {
144
+        $this->backends = array();
145
+        $this->clearCaches();
146
+    }
147 147
 	
148
-	protected function clearCaches() {
149
-		$this->cachedGroups = array();
150
-		$this->cachedUserGroups = array();
151
-	}
152
-
153
-	/**
154
-	 * @param string $gid
155
-	 * @return \OC\Group\Group
156
-	 */
157
-	public function get($gid) {
158
-		if (isset($this->cachedGroups[$gid])) {
159
-			return $this->cachedGroups[$gid];
160
-		}
161
-		return $this->getGroupObject($gid);
162
-	}
163
-
164
-	/**
165
-	 * @param string $gid
166
-	 * @param string $displayName
167
-	 * @return \OCP\IGroup
168
-	 */
169
-	protected function getGroupObject($gid, $displayName = null) {
170
-		$backends = array();
171
-		foreach ($this->backends as $backend) {
172
-			if ($backend->implementsActions(\OC\Group\Backend::GROUP_DETAILS)) {
173
-				$groupData = $backend->getGroupDetails($gid);
174
-				if (is_array($groupData)) {
175
-					// take the display name from the first backend that has a non-null one
176
-					if (is_null($displayName) && isset($groupData['displayName'])) {
177
-						$displayName = $groupData['displayName'];
178
-					}
179
-					$backends[] = $backend;
180
-				}
181
-			} else if ($backend->groupExists($gid)) {
182
-				$backends[] = $backend;
183
-			}
184
-		}
185
-		if (count($backends) === 0) {
186
-			return null;
187
-		}
188
-		$this->cachedGroups[$gid] = new Group($gid, $backends, $this->userManager, $this, $displayName);
189
-		return $this->cachedGroups[$gid];
190
-	}
191
-
192
-	/**
193
-	 * @param string $gid
194
-	 * @return bool
195
-	 */
196
-	public function groupExists($gid) {
197
-		return $this->get($gid) instanceof IGroup;
198
-	}
199
-
200
-	/**
201
-	 * @param string $gid
202
-	 * @return \OC\Group\Group
203
-	 */
204
-	public function createGroup($gid) {
205
-		if ($gid === '' || $gid === null) {
206
-			return false;
207
-		} else if ($group = $this->get($gid)) {
208
-			return $group;
209
-		} else {
210
-			$this->emit('\OC\Group', 'preCreate', array($gid));
211
-			foreach ($this->backends as $backend) {
212
-				if ($backend->implementsActions(\OC\Group\Backend::CREATE_GROUP)) {
213
-					$backend->createGroup($gid);
214
-					$group = $this->getGroupObject($gid);
215
-					$this->emit('\OC\Group', 'postCreate', array($group));
216
-					return $group;
217
-				}
218
-			}
219
-			return null;
220
-		}
221
-	}
222
-
223
-	/**
224
-	 * @param string $search
225
-	 * @param int $limit
226
-	 * @param int $offset
227
-	 * @return \OC\Group\Group[]
228
-	 */
229
-	public function search($search, $limit = null, $offset = null) {
230
-		$groups = array();
231
-		foreach ($this->backends as $backend) {
232
-			$groupIds = $backend->getGroups($search, $limit, $offset);
233
-			foreach ($groupIds as $groupId) {
234
-				$aGroup = $this->get($groupId);
235
-				if ($aGroup instanceof IGroup) {
236
-					$groups[$groupId] = $aGroup;
237
-				} else {
238
-					$this->logger->debug('Group "' . $groupId . '" was returned by search but not found through direct access', ['app' => 'core']);
239
-				}
240
-			}
241
-			if (!is_null($limit) and $limit <= 0) {
242
-				return array_values($groups);
243
-			}
244
-		}
245
-		return array_values($groups);
246
-	}
247
-
248
-	/**
249
-	 * @param \OC\User\User|null $user
250
-	 * @return \OC\Group\Group[]
251
-	 */
252
-	public function getUserGroups($user) {
253
-		if (!$user instanceof IUser) {
254
-			return [];
255
-		}
256
-		return $this->getUserIdGroups($user->getUID());
257
-	}
258
-
259
-	/**
260
-	 * @param string $uid the user id
261
-	 * @return \OC\Group\Group[]
262
-	 */
263
-	public function getUserIdGroups($uid) {
264
-		if (isset($this->cachedUserGroups[$uid])) {
265
-			return $this->cachedUserGroups[$uid];
266
-		}
267
-		$groups = array();
268
-		foreach ($this->backends as $backend) {
269
-			$groupIds = $backend->getUserGroups($uid);
270
-			if (is_array($groupIds)) {
271
-				foreach ($groupIds as $groupId) {
272
-					$aGroup = $this->get($groupId);
273
-					if ($aGroup instanceof IGroup) {
274
-						$groups[$groupId] = $aGroup;
275
-					} else {
276
-						$this->logger->debug('User "' . $uid . '" belongs to deleted group: "' . $groupId . '"', ['app' => 'core']);
277
-					}
278
-				}
279
-			}
280
-		}
281
-		$this->cachedUserGroups[$uid] = $groups;
282
-		return $this->cachedUserGroups[$uid];
283
-	}
284
-
285
-	/**
286
-	 * Checks if a userId is in the admin group
287
-	 * @param string $userId
288
-	 * @return bool if admin
289
-	 */
290
-	public function isAdmin($userId) {
291
-		return $this->isInGroup($userId, 'admin');
292
-	}
293
-
294
-	/**
295
-	 * Checks if a userId is in a group
296
-	 * @param string $userId
297
-	 * @param string $group
298
-	 * @return bool if in group
299
-	 */
300
-	public function isInGroup($userId, $group) {
301
-		return array_key_exists($group, $this->getUserIdGroups($userId));
302
-	}
303
-
304
-	/**
305
-	 * get a list of group ids for a user
306
-	 * @param \OC\User\User $user
307
-	 * @return array with group ids
308
-	 */
309
-	public function getUserGroupIds($user) {
310
-		return array_map(function($value) {
311
-			return (string) $value;
312
-		}, array_keys($this->getUserGroups($user)));
313
-	}
314
-
315
-	/**
316
-	 * get a list of all display names in a group
317
-	 * @param string $gid
318
-	 * @param string $search
319
-	 * @param int $limit
320
-	 * @param int $offset
321
-	 * @return array an array of display names (value) and user ids (key)
322
-	 */
323
-	public function displayNamesInGroup($gid, $search = '', $limit = -1, $offset = 0) {
324
-		$group = $this->get($gid);
325
-		if(is_null($group)) {
326
-			return array();
327
-		}
328
-
329
-		$search = trim($search);
330
-		$groupUsers = array();
331
-
332
-		if(!empty($search)) {
333
-			// only user backends have the capability to do a complex search for users
334
-			$searchOffset = 0;
335
-			$searchLimit = $limit * 100;
336
-			if($limit === -1) {
337
-				$searchLimit = 500;
338
-			}
339
-
340
-			do {
341
-				$filteredUsers = $this->userManager->searchDisplayName($search, $searchLimit, $searchOffset);
342
-				foreach($filteredUsers as $filteredUser) {
343
-					if($group->inGroup($filteredUser)) {
344
-						$groupUsers[]= $filteredUser;
345
-					}
346
-				}
347
-				$searchOffset += $searchLimit;
348
-			} while(count($groupUsers) < $searchLimit+$offset && count($filteredUsers) >= $searchLimit);
349
-
350
-			if($limit === -1) {
351
-				$groupUsers = array_slice($groupUsers, $offset);
352
-			} else {
353
-				$groupUsers = array_slice($groupUsers, $offset, $limit);
354
-			}
355
-		} else {
356
-			$groupUsers = $group->searchUsers('', $limit, $offset);
357
-		}
358
-
359
-		$matchingUsers = array();
360
-		foreach($groupUsers as $groupUser) {
361
-			$matchingUsers[$groupUser->getUID()] = $groupUser->getDisplayName();
362
-		}
363
-		return $matchingUsers;
364
-	}
365
-
366
-	/**
367
-	 * @return \OC\SubAdmin
368
-	 */
369
-	public function getSubAdmin() {
370
-		if (!$this->subAdmin) {
371
-			$this->subAdmin = new \OC\SubAdmin(
372
-				$this->userManager,
373
-				$this,
374
-				\OC::$server->getDatabaseConnection()
375
-			);
376
-		}
377
-
378
-		return $this->subAdmin;
379
-	}
148
+    protected function clearCaches() {
149
+        $this->cachedGroups = array();
150
+        $this->cachedUserGroups = array();
151
+    }
152
+
153
+    /**
154
+     * @param string $gid
155
+     * @return \OC\Group\Group
156
+     */
157
+    public function get($gid) {
158
+        if (isset($this->cachedGroups[$gid])) {
159
+            return $this->cachedGroups[$gid];
160
+        }
161
+        return $this->getGroupObject($gid);
162
+    }
163
+
164
+    /**
165
+     * @param string $gid
166
+     * @param string $displayName
167
+     * @return \OCP\IGroup
168
+     */
169
+    protected function getGroupObject($gid, $displayName = null) {
170
+        $backends = array();
171
+        foreach ($this->backends as $backend) {
172
+            if ($backend->implementsActions(\OC\Group\Backend::GROUP_DETAILS)) {
173
+                $groupData = $backend->getGroupDetails($gid);
174
+                if (is_array($groupData)) {
175
+                    // take the display name from the first backend that has a non-null one
176
+                    if (is_null($displayName) && isset($groupData['displayName'])) {
177
+                        $displayName = $groupData['displayName'];
178
+                    }
179
+                    $backends[] = $backend;
180
+                }
181
+            } else if ($backend->groupExists($gid)) {
182
+                $backends[] = $backend;
183
+            }
184
+        }
185
+        if (count($backends) === 0) {
186
+            return null;
187
+        }
188
+        $this->cachedGroups[$gid] = new Group($gid, $backends, $this->userManager, $this, $displayName);
189
+        return $this->cachedGroups[$gid];
190
+    }
191
+
192
+    /**
193
+     * @param string $gid
194
+     * @return bool
195
+     */
196
+    public function groupExists($gid) {
197
+        return $this->get($gid) instanceof IGroup;
198
+    }
199
+
200
+    /**
201
+     * @param string $gid
202
+     * @return \OC\Group\Group
203
+     */
204
+    public function createGroup($gid) {
205
+        if ($gid === '' || $gid === null) {
206
+            return false;
207
+        } else if ($group = $this->get($gid)) {
208
+            return $group;
209
+        } else {
210
+            $this->emit('\OC\Group', 'preCreate', array($gid));
211
+            foreach ($this->backends as $backend) {
212
+                if ($backend->implementsActions(\OC\Group\Backend::CREATE_GROUP)) {
213
+                    $backend->createGroup($gid);
214
+                    $group = $this->getGroupObject($gid);
215
+                    $this->emit('\OC\Group', 'postCreate', array($group));
216
+                    return $group;
217
+                }
218
+            }
219
+            return null;
220
+        }
221
+    }
222
+
223
+    /**
224
+     * @param string $search
225
+     * @param int $limit
226
+     * @param int $offset
227
+     * @return \OC\Group\Group[]
228
+     */
229
+    public function search($search, $limit = null, $offset = null) {
230
+        $groups = array();
231
+        foreach ($this->backends as $backend) {
232
+            $groupIds = $backend->getGroups($search, $limit, $offset);
233
+            foreach ($groupIds as $groupId) {
234
+                $aGroup = $this->get($groupId);
235
+                if ($aGroup instanceof IGroup) {
236
+                    $groups[$groupId] = $aGroup;
237
+                } else {
238
+                    $this->logger->debug('Group "' . $groupId . '" was returned by search but not found through direct access', ['app' => 'core']);
239
+                }
240
+            }
241
+            if (!is_null($limit) and $limit <= 0) {
242
+                return array_values($groups);
243
+            }
244
+        }
245
+        return array_values($groups);
246
+    }
247
+
248
+    /**
249
+     * @param \OC\User\User|null $user
250
+     * @return \OC\Group\Group[]
251
+     */
252
+    public function getUserGroups($user) {
253
+        if (!$user instanceof IUser) {
254
+            return [];
255
+        }
256
+        return $this->getUserIdGroups($user->getUID());
257
+    }
258
+
259
+    /**
260
+     * @param string $uid the user id
261
+     * @return \OC\Group\Group[]
262
+     */
263
+    public function getUserIdGroups($uid) {
264
+        if (isset($this->cachedUserGroups[$uid])) {
265
+            return $this->cachedUserGroups[$uid];
266
+        }
267
+        $groups = array();
268
+        foreach ($this->backends as $backend) {
269
+            $groupIds = $backend->getUserGroups($uid);
270
+            if (is_array($groupIds)) {
271
+                foreach ($groupIds as $groupId) {
272
+                    $aGroup = $this->get($groupId);
273
+                    if ($aGroup instanceof IGroup) {
274
+                        $groups[$groupId] = $aGroup;
275
+                    } else {
276
+                        $this->logger->debug('User "' . $uid . '" belongs to deleted group: "' . $groupId . '"', ['app' => 'core']);
277
+                    }
278
+                }
279
+            }
280
+        }
281
+        $this->cachedUserGroups[$uid] = $groups;
282
+        return $this->cachedUserGroups[$uid];
283
+    }
284
+
285
+    /**
286
+     * Checks if a userId is in the admin group
287
+     * @param string $userId
288
+     * @return bool if admin
289
+     */
290
+    public function isAdmin($userId) {
291
+        return $this->isInGroup($userId, 'admin');
292
+    }
293
+
294
+    /**
295
+     * Checks if a userId is in a group
296
+     * @param string $userId
297
+     * @param string $group
298
+     * @return bool if in group
299
+     */
300
+    public function isInGroup($userId, $group) {
301
+        return array_key_exists($group, $this->getUserIdGroups($userId));
302
+    }
303
+
304
+    /**
305
+     * get a list of group ids for a user
306
+     * @param \OC\User\User $user
307
+     * @return array with group ids
308
+     */
309
+    public function getUserGroupIds($user) {
310
+        return array_map(function($value) {
311
+            return (string) $value;
312
+        }, array_keys($this->getUserGroups($user)));
313
+    }
314
+
315
+    /**
316
+     * get a list of all display names in a group
317
+     * @param string $gid
318
+     * @param string $search
319
+     * @param int $limit
320
+     * @param int $offset
321
+     * @return array an array of display names (value) and user ids (key)
322
+     */
323
+    public function displayNamesInGroup($gid, $search = '', $limit = -1, $offset = 0) {
324
+        $group = $this->get($gid);
325
+        if(is_null($group)) {
326
+            return array();
327
+        }
328
+
329
+        $search = trim($search);
330
+        $groupUsers = array();
331
+
332
+        if(!empty($search)) {
333
+            // only user backends have the capability to do a complex search for users
334
+            $searchOffset = 0;
335
+            $searchLimit = $limit * 100;
336
+            if($limit === -1) {
337
+                $searchLimit = 500;
338
+            }
339
+
340
+            do {
341
+                $filteredUsers = $this->userManager->searchDisplayName($search, $searchLimit, $searchOffset);
342
+                foreach($filteredUsers as $filteredUser) {
343
+                    if($group->inGroup($filteredUser)) {
344
+                        $groupUsers[]= $filteredUser;
345
+                    }
346
+                }
347
+                $searchOffset += $searchLimit;
348
+            } while(count($groupUsers) < $searchLimit+$offset && count($filteredUsers) >= $searchLimit);
349
+
350
+            if($limit === -1) {
351
+                $groupUsers = array_slice($groupUsers, $offset);
352
+            } else {
353
+                $groupUsers = array_slice($groupUsers, $offset, $limit);
354
+            }
355
+        } else {
356
+            $groupUsers = $group->searchUsers('', $limit, $offset);
357
+        }
358
+
359
+        $matchingUsers = array();
360
+        foreach($groupUsers as $groupUser) {
361
+            $matchingUsers[$groupUser->getUID()] = $groupUser->getDisplayName();
362
+        }
363
+        return $matchingUsers;
364
+    }
365
+
366
+    /**
367
+     * @return \OC\SubAdmin
368
+     */
369
+    public function getSubAdmin() {
370
+        if (!$this->subAdmin) {
371
+            $this->subAdmin = new \OC\SubAdmin(
372
+                $this->userManager,
373
+                $this,
374
+                \OC::$server->getDatabaseConnection()
375
+            );
376
+        }
377
+
378
+        return $this->subAdmin;
379
+    }
380 380
 }
Please login to merge, or discard this patch.
Spacing   +14 added lines, -14 removed lines patch added patch discarded remove patch
@@ -93,20 +93,20 @@  discard block
 block discarded – undo
93 93
 		$this->logger = $logger;
94 94
 		$cachedGroups = & $this->cachedGroups;
95 95
 		$cachedUserGroups = & $this->cachedUserGroups;
96
-		$this->listen('\OC\Group', 'postDelete', function ($group) use (&$cachedGroups, &$cachedUserGroups) {
96
+		$this->listen('\OC\Group', 'postDelete', function($group) use (&$cachedGroups, &$cachedUserGroups) {
97 97
 			/**
98 98
 			 * @var \OC\Group\Group $group
99 99
 			 */
100 100
 			unset($cachedGroups[$group->getGID()]);
101 101
 			$cachedUserGroups = array();
102 102
 		});
103
-		$this->listen('\OC\Group', 'postAddUser', function ($group) use (&$cachedUserGroups) {
103
+		$this->listen('\OC\Group', 'postAddUser', function($group) use (&$cachedUserGroups) {
104 104
 			/**
105 105
 			 * @var \OC\Group\Group $group
106 106
 			 */
107 107
 			$cachedUserGroups = array();
108 108
 		});
109
-		$this->listen('\OC\Group', 'postRemoveUser', function ($group) use (&$cachedUserGroups) {
109
+		$this->listen('\OC\Group', 'postRemoveUser', function($group) use (&$cachedUserGroups) {
110 110
 			/**
111 111
 			 * @var \OC\Group\Group $group
112 112
 			 */
@@ -235,7 +235,7 @@  discard block
 block discarded – undo
235 235
 				if ($aGroup instanceof IGroup) {
236 236
 					$groups[$groupId] = $aGroup;
237 237
 				} else {
238
-					$this->logger->debug('Group "' . $groupId . '" was returned by search but not found through direct access', ['app' => 'core']);
238
+					$this->logger->debug('Group "'.$groupId.'" was returned by search but not found through direct access', ['app' => 'core']);
239 239
 				}
240 240
 			}
241 241
 			if (!is_null($limit) and $limit <= 0) {
@@ -273,7 +273,7 @@  discard block
 block discarded – undo
273 273
 					if ($aGroup instanceof IGroup) {
274 274
 						$groups[$groupId] = $aGroup;
275 275
 					} else {
276
-						$this->logger->debug('User "' . $uid . '" belongs to deleted group: "' . $groupId . '"', ['app' => 'core']);
276
+						$this->logger->debug('User "'.$uid.'" belongs to deleted group: "'.$groupId.'"', ['app' => 'core']);
277 277
 					}
278 278
 				}
279 279
 			}
@@ -322,32 +322,32 @@  discard block
 block discarded – undo
322 322
 	 */
323 323
 	public function displayNamesInGroup($gid, $search = '', $limit = -1, $offset = 0) {
324 324
 		$group = $this->get($gid);
325
-		if(is_null($group)) {
325
+		if (is_null($group)) {
326 326
 			return array();
327 327
 		}
328 328
 
329 329
 		$search = trim($search);
330 330
 		$groupUsers = array();
331 331
 
332
-		if(!empty($search)) {
332
+		if (!empty($search)) {
333 333
 			// only user backends have the capability to do a complex search for users
334 334
 			$searchOffset = 0;
335 335
 			$searchLimit = $limit * 100;
336
-			if($limit === -1) {
336
+			if ($limit === -1) {
337 337
 				$searchLimit = 500;
338 338
 			}
339 339
 
340 340
 			do {
341 341
 				$filteredUsers = $this->userManager->searchDisplayName($search, $searchLimit, $searchOffset);
342
-				foreach($filteredUsers as $filteredUser) {
343
-					if($group->inGroup($filteredUser)) {
344
-						$groupUsers[]= $filteredUser;
342
+				foreach ($filteredUsers as $filteredUser) {
343
+					if ($group->inGroup($filteredUser)) {
344
+						$groupUsers[] = $filteredUser;
345 345
 					}
346 346
 				}
347 347
 				$searchOffset += $searchLimit;
348
-			} while(count($groupUsers) < $searchLimit+$offset && count($filteredUsers) >= $searchLimit);
348
+			} while (count($groupUsers) < $searchLimit + $offset && count($filteredUsers) >= $searchLimit);
349 349
 
350
-			if($limit === -1) {
350
+			if ($limit === -1) {
351 351
 				$groupUsers = array_slice($groupUsers, $offset);
352 352
 			} else {
353 353
 				$groupUsers = array_slice($groupUsers, $offset, $limit);
@@ -357,7 +357,7 @@  discard block
 block discarded – undo
357 357
 		}
358 358
 
359 359
 		$matchingUsers = array();
360
-		foreach($groupUsers as $groupUser) {
360
+		foreach ($groupUsers as $groupUser) {
361 361
 			$matchingUsers[$groupUser->getUID()] = $groupUser->getDisplayName();
362 362
 		}
363 363
 		return $matchingUsers;
Please login to merge, or discard this patch.