Completed
Push — stable13 ( 4e87d5...f6a732 )
by
unknown
25:04 queued 12:21
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.
Indentation   +576 added lines, -576 removed lines patch added patch discarded remove patch
@@ -67,584 +67,584 @@
 block discarded – undo
67 67
  */
68 68
 class ShareController extends Controller {
69 69
 
70
-	/** @var IConfig */
71
-	protected $config;
72
-	/** @var IURLGenerator */
73
-	protected $urlGenerator;
74
-	/** @var IUserManager */
75
-	protected $userManager;
76
-	/** @var ILogger */
77
-	protected $logger;
78
-	/** @var \OCP\Activity\IManager */
79
-	protected $activityManager;
80
-	/** @var \OCP\Share\IManager */
81
-	protected $shareManager;
82
-	/** @var ISession */
83
-	protected $session;
84
-	/** @var IPreview */
85
-	protected $previewManager;
86
-	/** @var IRootFolder */
87
-	protected $rootFolder;
88
-	/** @var FederatedShareProvider */
89
-	protected $federatedShareProvider;
90
-	/** @var EventDispatcherInterface */
91
-	protected $eventDispatcher;
92
-	/** @var IL10N */
93
-	protected $l10n;
94
-	/** @var Defaults */
95
-	protected $defaults;
96
-
97
-	/**
98
-	 * @param string $appName
99
-	 * @param IRequest $request
100
-	 * @param IConfig $config
101
-	 * @param IURLGenerator $urlGenerator
102
-	 * @param IUserManager $userManager
103
-	 * @param ILogger $logger
104
-	 * @param \OCP\Activity\IManager $activityManager
105
-	 * @param \OCP\Share\IManager $shareManager
106
-	 * @param ISession $session
107
-	 * @param IPreview $previewManager
108
-	 * @param IRootFolder $rootFolder
109
-	 * @param FederatedShareProvider $federatedShareProvider
110
-	 * @param EventDispatcherInterface $eventDispatcher
111
-	 * @param IL10N $l10n
112
-	 * @param Defaults $defaults
113
-	 */
114
-	public function __construct($appName,
115
-								IRequest $request,
116
-								IConfig $config,
117
-								IURLGenerator $urlGenerator,
118
-								IUserManager $userManager,
119
-								ILogger $logger,
120
-								\OCP\Activity\IManager $activityManager,
121
-								\OCP\Share\IManager $shareManager,
122
-								ISession $session,
123
-								IPreview $previewManager,
124
-								IRootFolder $rootFolder,
125
-								FederatedShareProvider $federatedShareProvider,
126
-								EventDispatcherInterface $eventDispatcher,
127
-								IL10N $l10n,
128
-								Defaults $defaults) {
129
-		parent::__construct($appName, $request);
130
-
131
-		$this->config = $config;
132
-		$this->urlGenerator = $urlGenerator;
133
-		$this->userManager = $userManager;
134
-		$this->logger = $logger;
135
-		$this->activityManager = $activityManager;
136
-		$this->shareManager = $shareManager;
137
-		$this->session = $session;
138
-		$this->previewManager = $previewManager;
139
-		$this->rootFolder = $rootFolder;
140
-		$this->federatedShareProvider = $federatedShareProvider;
141
-		$this->eventDispatcher = $eventDispatcher;
142
-		$this->l10n = $l10n;
143
-		$this->defaults = $defaults;
144
-	}
145
-
146
-	/**
147
-	 * @PublicPage
148
-	 * @NoCSRFRequired
149
-	 *
150
-	 * @param string $token
151
-	 * @return TemplateResponse|RedirectResponse
152
-	 */
153
-	public function showAuthenticate($token) {
154
-		$share = $this->shareManager->getShareByToken($token);
155
-
156
-		if($this->linkShareAuth($share)) {
157
-			return new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.showShare', array('token' => $token)));
158
-		}
159
-
160
-		return new TemplateResponse($this->appName, 'authenticate', array(), 'guest');
161
-	}
162
-
163
-	/**
164
-	 * @PublicPage
165
-	 * @UseSession
166
-	 * @BruteForceProtection(action=publicLinkAuth)
167
-	 *
168
-	 * Authenticates against password-protected shares
169
-	 * @param string $token
170
-	 * @param string $password
171
-	 * @return RedirectResponse|TemplateResponse|NotFoundResponse
172
-	 */
173
-	public function authenticate($token, $password = '') {
174
-
175
-		// Check whether share exists
176
-		try {
177
-			$share = $this->shareManager->getShareByToken($token);
178
-		} catch (ShareNotFound $e) {
179
-			return new NotFoundResponse();
180
-		}
181
-
182
-		$authenticate = $this->linkShareAuth($share, $password);
183
-
184
-		if($authenticate === true) {
185
-			return new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.showShare', array('token' => $token)));
186
-		}
187
-
188
-		$response = new TemplateResponse($this->appName, 'authenticate', array('wrongpw' => true), 'guest');
189
-		$response->throttle();
190
-		return $response;
191
-	}
192
-
193
-	/**
194
-	 * Authenticate a link item with the given password.
195
-	 * Or use the session if no password is provided.
196
-	 *
197
-	 * This is a modified version of Helper::authenticate
198
-	 * TODO: Try to merge back eventually with Helper::authenticate
199
-	 *
200
-	 * @param \OCP\Share\IShare $share
201
-	 * @param string|null $password
202
-	 * @return bool
203
-	 */
204
-	private function linkShareAuth(\OCP\Share\IShare $share, $password = null) {
205
-		if ($password !== null) {
206
-			if ($this->shareManager->checkPassword($share, $password)) {
207
-				$this->session->regenerateId(true, true);
208
-				$this->session->set('public_link_authenticated', (string)$share->getId());
209
-			} else {
210
-				$this->emitAccessShareHook($share, 403, 'Wrong password');
211
-				return false;
212
-			}
213
-		} else {
214
-			// not authenticated ?
215
-			if ( ! $this->session->exists('public_link_authenticated')
216
-				|| $this->session->get('public_link_authenticated') !== (string)$share->getId()) {
217
-				return false;
218
-			}
219
-		}
220
-		return true;
221
-	}
222
-
223
-	/**
224
-	 * throws hooks when a share is attempted to be accessed
225
-	 *
226
-	 * @param \OCP\Share\IShare|string $share the Share instance if available,
227
-	 * otherwise token
228
-	 * @param int $errorCode
229
-	 * @param string $errorMessage
230
-	 * @throws \OC\HintException
231
-	 * @throws \OC\ServerNotAvailableException
232
-	 */
233
-	protected function emitAccessShareHook($share, $errorCode = 200, $errorMessage = '') {
234
-		$itemType = $itemSource = $uidOwner = '';
235
-		$token = $share;
236
-		$exception = null;
237
-		if($share instanceof \OCP\Share\IShare) {
238
-			try {
239
-				$token = $share->getToken();
240
-				$uidOwner = $share->getSharedBy();
241
-				$itemType = $share->getNodeType();
242
-				$itemSource = $share->getNodeId();
243
-			} catch (\Exception $e) {
244
-				// we log what we know and pass on the exception afterwards
245
-				$exception = $e;
246
-			}
247
-		}
248
-		\OC_Hook::emit('OCP\Share', 'share_link_access', [
249
-			'itemType' => $itemType,
250
-			'itemSource' => $itemSource,
251
-			'uidOwner' => $uidOwner,
252
-			'token' => $token,
253
-			'errorCode' => $errorCode,
254
-			'errorMessage' => $errorMessage,
255
-		]);
256
-		if(!is_null($exception)) {
257
-			throw $exception;
258
-		}
259
-	}
260
-
261
-	/**
262
-	 * Validate the permissions of the share
263
-	 *
264
-	 * @param Share\IShare $share
265
-	 * @return bool
266
-	 */
267
-	private function validateShare(\OCP\Share\IShare $share) {
268
-		return $share->getNode()->isReadable() && $share->getNode()->isShareable();
269
-	}
270
-
271
-	/**
272
-	 * @PublicPage
273
-	 * @NoCSRFRequired
274
-	 *
275
-	 * @param string $token
276
-	 * @param string $path
277
-	 * @return TemplateResponse|RedirectResponse|NotFoundResponse
278
-	 * @throws NotFoundException
279
-	 * @throws \Exception
280
-	 */
281
-	public function showShare($token, $path = '') {
282
-		\OC_User::setIncognitoMode(true);
283
-
284
-		// Check whether share exists
285
-		try {
286
-			$share = $this->shareManager->getShareByToken($token);
287
-		} catch (ShareNotFound $e) {
288
-			$this->emitAccessShareHook($token, 404, 'Share not found');
289
-			return new NotFoundResponse();
290
-		}
291
-
292
-		// Share is password protected - check whether the user is permitted to access the share
293
-		if ($share->getPassword() !== null && !$this->linkShareAuth($share)) {
294
-			return new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.authenticate',
295
-				array('token' => $token)));
296
-		}
297
-
298
-		if (!$this->validateShare($share)) {
299
-			throw new NotFoundException();
300
-		}
301
-		// We can't get the path of a file share
302
-		try {
303
-			if ($share->getNode() instanceof \OCP\Files\File && $path !== '') {
304
-				$this->emitAccessShareHook($share, 404, 'Share not found');
305
-				throw new NotFoundException();
306
-			}
307
-		} catch (\Exception $e) {
308
-			$this->emitAccessShareHook($share, 404, 'Share not found');
309
-			throw $e;
310
-		}
311
-
312
-		$shareTmpl = [];
313
-		$shareTmpl['displayName'] = $this->userManager->get($share->getShareOwner())->getDisplayName();
314
-		$shareTmpl['owner'] = $share->getShareOwner();
315
-		$shareTmpl['filename'] = $share->getNode()->getName();
316
-		$shareTmpl['directory_path'] = $share->getTarget();
317
-		$shareTmpl['mimetype'] = $share->getNode()->getMimetype();
318
-		$shareTmpl['previewSupported'] = $this->previewManager->isMimeSupported($share->getNode()->getMimetype());
319
-		$shareTmpl['dirToken'] = $token;
320
-		$shareTmpl['sharingToken'] = $token;
321
-		$shareTmpl['server2serversharing'] = $this->federatedShareProvider->isOutgoingServer2serverShareEnabled();
322
-		$shareTmpl['protected'] = $share->getPassword() !== null ? 'true' : 'false';
323
-		$shareTmpl['dir'] = '';
324
-		$shareTmpl['nonHumanFileSize'] = $share->getNode()->getSize();
325
-		$shareTmpl['fileSize'] = \OCP\Util::humanFileSize($share->getNode()->getSize());
326
-
327
-		// Show file list
328
-		$hideFileList = false;
329
-		if ($share->getNode() instanceof \OCP\Files\Folder) {
330
-			/** @var \OCP\Files\Folder $rootFolder */
331
-			$rootFolder = $share->getNode();
332
-
333
-			try {
334
-				$folderNode = $rootFolder->get($path);
335
-			} catch (\OCP\Files\NotFoundException $e) {
336
-				$this->emitAccessShareHook($share, 404, 'Share not found');
337
-				throw new NotFoundException();
338
-			}
339
-
340
-			$shareTmpl['dir'] = $rootFolder->getRelativePath($folderNode->getPath());
341
-
342
-			/*
70
+    /** @var IConfig */
71
+    protected $config;
72
+    /** @var IURLGenerator */
73
+    protected $urlGenerator;
74
+    /** @var IUserManager */
75
+    protected $userManager;
76
+    /** @var ILogger */
77
+    protected $logger;
78
+    /** @var \OCP\Activity\IManager */
79
+    protected $activityManager;
80
+    /** @var \OCP\Share\IManager */
81
+    protected $shareManager;
82
+    /** @var ISession */
83
+    protected $session;
84
+    /** @var IPreview */
85
+    protected $previewManager;
86
+    /** @var IRootFolder */
87
+    protected $rootFolder;
88
+    /** @var FederatedShareProvider */
89
+    protected $federatedShareProvider;
90
+    /** @var EventDispatcherInterface */
91
+    protected $eventDispatcher;
92
+    /** @var IL10N */
93
+    protected $l10n;
94
+    /** @var Defaults */
95
+    protected $defaults;
96
+
97
+    /**
98
+     * @param string $appName
99
+     * @param IRequest $request
100
+     * @param IConfig $config
101
+     * @param IURLGenerator $urlGenerator
102
+     * @param IUserManager $userManager
103
+     * @param ILogger $logger
104
+     * @param \OCP\Activity\IManager $activityManager
105
+     * @param \OCP\Share\IManager $shareManager
106
+     * @param ISession $session
107
+     * @param IPreview $previewManager
108
+     * @param IRootFolder $rootFolder
109
+     * @param FederatedShareProvider $federatedShareProvider
110
+     * @param EventDispatcherInterface $eventDispatcher
111
+     * @param IL10N $l10n
112
+     * @param Defaults $defaults
113
+     */
114
+    public function __construct($appName,
115
+                                IRequest $request,
116
+                                IConfig $config,
117
+                                IURLGenerator $urlGenerator,
118
+                                IUserManager $userManager,
119
+                                ILogger $logger,
120
+                                \OCP\Activity\IManager $activityManager,
121
+                                \OCP\Share\IManager $shareManager,
122
+                                ISession $session,
123
+                                IPreview $previewManager,
124
+                                IRootFolder $rootFolder,
125
+                                FederatedShareProvider $federatedShareProvider,
126
+                                EventDispatcherInterface $eventDispatcher,
127
+                                IL10N $l10n,
128
+                                Defaults $defaults) {
129
+        parent::__construct($appName, $request);
130
+
131
+        $this->config = $config;
132
+        $this->urlGenerator = $urlGenerator;
133
+        $this->userManager = $userManager;
134
+        $this->logger = $logger;
135
+        $this->activityManager = $activityManager;
136
+        $this->shareManager = $shareManager;
137
+        $this->session = $session;
138
+        $this->previewManager = $previewManager;
139
+        $this->rootFolder = $rootFolder;
140
+        $this->federatedShareProvider = $federatedShareProvider;
141
+        $this->eventDispatcher = $eventDispatcher;
142
+        $this->l10n = $l10n;
143
+        $this->defaults = $defaults;
144
+    }
145
+
146
+    /**
147
+     * @PublicPage
148
+     * @NoCSRFRequired
149
+     *
150
+     * @param string $token
151
+     * @return TemplateResponse|RedirectResponse
152
+     */
153
+    public function showAuthenticate($token) {
154
+        $share = $this->shareManager->getShareByToken($token);
155
+
156
+        if($this->linkShareAuth($share)) {
157
+            return new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.showShare', array('token' => $token)));
158
+        }
159
+
160
+        return new TemplateResponse($this->appName, 'authenticate', array(), 'guest');
161
+    }
162
+
163
+    /**
164
+     * @PublicPage
165
+     * @UseSession
166
+     * @BruteForceProtection(action=publicLinkAuth)
167
+     *
168
+     * Authenticates against password-protected shares
169
+     * @param string $token
170
+     * @param string $password
171
+     * @return RedirectResponse|TemplateResponse|NotFoundResponse
172
+     */
173
+    public function authenticate($token, $password = '') {
174
+
175
+        // Check whether share exists
176
+        try {
177
+            $share = $this->shareManager->getShareByToken($token);
178
+        } catch (ShareNotFound $e) {
179
+            return new NotFoundResponse();
180
+        }
181
+
182
+        $authenticate = $this->linkShareAuth($share, $password);
183
+
184
+        if($authenticate === true) {
185
+            return new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.showShare', array('token' => $token)));
186
+        }
187
+
188
+        $response = new TemplateResponse($this->appName, 'authenticate', array('wrongpw' => true), 'guest');
189
+        $response->throttle();
190
+        return $response;
191
+    }
192
+
193
+    /**
194
+     * Authenticate a link item with the given password.
195
+     * Or use the session if no password is provided.
196
+     *
197
+     * This is a modified version of Helper::authenticate
198
+     * TODO: Try to merge back eventually with Helper::authenticate
199
+     *
200
+     * @param \OCP\Share\IShare $share
201
+     * @param string|null $password
202
+     * @return bool
203
+     */
204
+    private function linkShareAuth(\OCP\Share\IShare $share, $password = null) {
205
+        if ($password !== null) {
206
+            if ($this->shareManager->checkPassword($share, $password)) {
207
+                $this->session->regenerateId(true, true);
208
+                $this->session->set('public_link_authenticated', (string)$share->getId());
209
+            } else {
210
+                $this->emitAccessShareHook($share, 403, 'Wrong password');
211
+                return false;
212
+            }
213
+        } else {
214
+            // not authenticated ?
215
+            if ( ! $this->session->exists('public_link_authenticated')
216
+                || $this->session->get('public_link_authenticated') !== (string)$share->getId()) {
217
+                return false;
218
+            }
219
+        }
220
+        return true;
221
+    }
222
+
223
+    /**
224
+     * throws hooks when a share is attempted to be accessed
225
+     *
226
+     * @param \OCP\Share\IShare|string $share the Share instance if available,
227
+     * otherwise token
228
+     * @param int $errorCode
229
+     * @param string $errorMessage
230
+     * @throws \OC\HintException
231
+     * @throws \OC\ServerNotAvailableException
232
+     */
233
+    protected function emitAccessShareHook($share, $errorCode = 200, $errorMessage = '') {
234
+        $itemType = $itemSource = $uidOwner = '';
235
+        $token = $share;
236
+        $exception = null;
237
+        if($share instanceof \OCP\Share\IShare) {
238
+            try {
239
+                $token = $share->getToken();
240
+                $uidOwner = $share->getSharedBy();
241
+                $itemType = $share->getNodeType();
242
+                $itemSource = $share->getNodeId();
243
+            } catch (\Exception $e) {
244
+                // we log what we know and pass on the exception afterwards
245
+                $exception = $e;
246
+            }
247
+        }
248
+        \OC_Hook::emit('OCP\Share', 'share_link_access', [
249
+            'itemType' => $itemType,
250
+            'itemSource' => $itemSource,
251
+            'uidOwner' => $uidOwner,
252
+            'token' => $token,
253
+            'errorCode' => $errorCode,
254
+            'errorMessage' => $errorMessage,
255
+        ]);
256
+        if(!is_null($exception)) {
257
+            throw $exception;
258
+        }
259
+    }
260
+
261
+    /**
262
+     * Validate the permissions of the share
263
+     *
264
+     * @param Share\IShare $share
265
+     * @return bool
266
+     */
267
+    private function validateShare(\OCP\Share\IShare $share) {
268
+        return $share->getNode()->isReadable() && $share->getNode()->isShareable();
269
+    }
270
+
271
+    /**
272
+     * @PublicPage
273
+     * @NoCSRFRequired
274
+     *
275
+     * @param string $token
276
+     * @param string $path
277
+     * @return TemplateResponse|RedirectResponse|NotFoundResponse
278
+     * @throws NotFoundException
279
+     * @throws \Exception
280
+     */
281
+    public function showShare($token, $path = '') {
282
+        \OC_User::setIncognitoMode(true);
283
+
284
+        // Check whether share exists
285
+        try {
286
+            $share = $this->shareManager->getShareByToken($token);
287
+        } catch (ShareNotFound $e) {
288
+            $this->emitAccessShareHook($token, 404, 'Share not found');
289
+            return new NotFoundResponse();
290
+        }
291
+
292
+        // Share is password protected - check whether the user is permitted to access the share
293
+        if ($share->getPassword() !== null && !$this->linkShareAuth($share)) {
294
+            return new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.authenticate',
295
+                array('token' => $token)));
296
+        }
297
+
298
+        if (!$this->validateShare($share)) {
299
+            throw new NotFoundException();
300
+        }
301
+        // We can't get the path of a file share
302
+        try {
303
+            if ($share->getNode() instanceof \OCP\Files\File && $path !== '') {
304
+                $this->emitAccessShareHook($share, 404, 'Share not found');
305
+                throw new NotFoundException();
306
+            }
307
+        } catch (\Exception $e) {
308
+            $this->emitAccessShareHook($share, 404, 'Share not found');
309
+            throw $e;
310
+        }
311
+
312
+        $shareTmpl = [];
313
+        $shareTmpl['displayName'] = $this->userManager->get($share->getShareOwner())->getDisplayName();
314
+        $shareTmpl['owner'] = $share->getShareOwner();
315
+        $shareTmpl['filename'] = $share->getNode()->getName();
316
+        $shareTmpl['directory_path'] = $share->getTarget();
317
+        $shareTmpl['mimetype'] = $share->getNode()->getMimetype();
318
+        $shareTmpl['previewSupported'] = $this->previewManager->isMimeSupported($share->getNode()->getMimetype());
319
+        $shareTmpl['dirToken'] = $token;
320
+        $shareTmpl['sharingToken'] = $token;
321
+        $shareTmpl['server2serversharing'] = $this->federatedShareProvider->isOutgoingServer2serverShareEnabled();
322
+        $shareTmpl['protected'] = $share->getPassword() !== null ? 'true' : 'false';
323
+        $shareTmpl['dir'] = '';
324
+        $shareTmpl['nonHumanFileSize'] = $share->getNode()->getSize();
325
+        $shareTmpl['fileSize'] = \OCP\Util::humanFileSize($share->getNode()->getSize());
326
+
327
+        // Show file list
328
+        $hideFileList = false;
329
+        if ($share->getNode() instanceof \OCP\Files\Folder) {
330
+            /** @var \OCP\Files\Folder $rootFolder */
331
+            $rootFolder = $share->getNode();
332
+
333
+            try {
334
+                $folderNode = $rootFolder->get($path);
335
+            } catch (\OCP\Files\NotFoundException $e) {
336
+                $this->emitAccessShareHook($share, 404, 'Share not found');
337
+                throw new NotFoundException();
338
+            }
339
+
340
+            $shareTmpl['dir'] = $rootFolder->getRelativePath($folderNode->getPath());
341
+
342
+            /*
343 343
 			 * The OC_Util methods require a view. This just uses the node API
344 344
 			 */
345
-			$freeSpace = $share->getNode()->getStorage()->free_space($share->getNode()->getInternalPath());
346
-			if ($freeSpace < \OCP\Files\FileInfo::SPACE_UNLIMITED) {
347
-				$freeSpace = max($freeSpace, 0);
348
-			} else {
349
-				$freeSpace = (INF > 0) ? INF: PHP_INT_MAX; // work around https://bugs.php.net/bug.php?id=69188
350
-			}
351
-
352
-			$hideFileList = $share->getPermissions() & \OCP\Constants::PERMISSION_READ ? false : true;
353
-			$maxUploadFilesize = $freeSpace;
354
-
355
-			$folder = new Template('files', 'list', '');
356
-			$folder->assign('dir', $rootFolder->getRelativePath($folderNode->getPath()));
357
-			$folder->assign('dirToken', $token);
358
-			$folder->assign('permissions', \OCP\Constants::PERMISSION_READ);
359
-			$folder->assign('isPublic', true);
360
-			$folder->assign('hideFileList', $hideFileList);
361
-			$folder->assign('publicUploadEnabled', 'no');
362
-			$folder->assign('uploadMaxFilesize', $maxUploadFilesize);
363
-			$folder->assign('uploadMaxHumanFilesize', \OCP\Util::humanFileSize($maxUploadFilesize));
364
-			$folder->assign('freeSpace', $freeSpace);
365
-			$folder->assign('usedSpacePercent', 0);
366
-			$folder->assign('trash', false);
367
-			$shareTmpl['folder'] = $folder->fetchPage();
368
-		}
369
-
370
-		$shareTmpl['hideFileList'] = $hideFileList;
371
-		$shareTmpl['shareOwner'] = $this->userManager->get($share->getShareOwner())->getDisplayName();
372
-		$shareTmpl['downloadURL'] = $this->urlGenerator->linkToRouteAbsolute('files_sharing.sharecontroller.downloadShare', ['token' => $token]);
373
-		$shareTmpl['shareUrl'] = $this->urlGenerator->linkToRouteAbsolute('files_sharing.sharecontroller.showShare', ['token' => $token]);
374
-		$shareTmpl['maxSizeAnimateGif'] = $this->config->getSystemValue('max_filesize_animated_gifs_public_sharing', 10);
375
-		$shareTmpl['previewEnabled'] = $this->config->getSystemValue('enable_previews', true);
376
-		$shareTmpl['previewMaxX'] = $this->config->getSystemValue('preview_max_x', 1024);
377
-		$shareTmpl['previewMaxY'] = $this->config->getSystemValue('preview_max_y', 1024);
378
-		$shareTmpl['disclaimer'] = $this->config->getAppValue('core', 'shareapi_public_link_disclaimertext', null);
379
-		$shareTmpl['previewURL'] = $shareTmpl['downloadURL'];
380
-		$ogPreview = '';
381
-		if ($shareTmpl['previewSupported']) {
382
-			$shareTmpl['previewImage'] = $this->urlGenerator->linkToRouteAbsolute( 'files_sharing.PublicPreview.getPreview',
383
-				['x' => 200, 'y' => 200, 'file' => $shareTmpl['directory_path'], 't' => $shareTmpl['dirToken']]);
384
-			$ogPreview = $shareTmpl['previewImage'];
385
-
386
-			// We just have direct previews for image files
387
-			if ($share->getNode()->getMimePart() === 'image') {
388
-				$shareTmpl['previewURL'] = $this->urlGenerator->linkToRouteAbsolute('files_sharing.publicpreview.directLink', ['token' => $token]);
389
-
390
-				$ogPreview = $shareTmpl['previewURL'];
391
-
392
-				//Whatapp is kind of picky about their size requirements
393
-				if ($this->request->isUserAgent(['/^WhatsApp/'])) {
394
-					$ogPreview = $this->urlGenerator->linkToRouteAbsolute('files_sharing.PublicPreview.getPreview', [
395
-						't' => $token,
396
-						'x' => 256,
397
-						'y' => 256,
398
-						'a' => true,
399
-					]);
400
-				}
401
-			}
402
-		} else {
403
-			$shareTmpl['previewImage'] = $this->urlGenerator->getAbsoluteURL($this->urlGenerator->imagePath('core', 'favicon-fb.png'));
404
-			$ogPreview = $shareTmpl['previewImage'];
405
-		}
406
-
407
-		// Load files we need
408
-		\OCP\Util::addScript('files', 'file-upload');
409
-		\OCP\Util::addStyle('files_sharing', 'publicView');
410
-		\OCP\Util::addScript('files_sharing', 'public');
411
-		\OCP\Util::addScript('files', 'fileactions');
412
-		\OCP\Util::addScript('files', 'fileactionsmenu');
413
-		\OCP\Util::addScript('files', 'jquery.fileupload');
414
-		\OCP\Util::addScript('files_sharing', 'files_drop');
415
-
416
-		if (isset($shareTmpl['folder'])) {
417
-			// JS required for folders
418
-			\OCP\Util::addStyle('files', 'merged');
419
-			\OCP\Util::addScript('files', 'filesummary');
420
-			\OCP\Util::addScript('files', 'breadcrumb');
421
-			\OCP\Util::addScript('files', 'fileinfomodel');
422
-			\OCP\Util::addScript('files', 'newfilemenu');
423
-			\OCP\Util::addScript('files', 'files');
424
-			\OCP\Util::addScript('files', 'filelist');
425
-			\OCP\Util::addScript('files', 'keyboardshortcuts');
426
-		}
427
-
428
-		// OpenGraph Support: http://ogp.me/
429
-		\OCP\Util::addHeader('meta', ['property' => "og:title", 'content' => $shareTmpl['filename']]);
430
-		\OCP\Util::addHeader('meta', ['property' => "og:description", 'content' => $this->defaults->getName() . ($this->defaults->getSlogan() !== '' ? ' - ' . $this->defaults->getSlogan() : '')]);
431
-		\OCP\Util::addHeader('meta', ['property' => "og:site_name", 'content' => $this->defaults->getName()]);
432
-		\OCP\Util::addHeader('meta', ['property' => "og:url", 'content' => $shareTmpl['shareUrl']]);
433
-		\OCP\Util::addHeader('meta', ['property' => "og:type", 'content' => "object"]);
434
-		\OCP\Util::addHeader('meta', ['property' => "og:image", 'content' => $ogPreview]);
435
-
436
-		$this->eventDispatcher->dispatch('OCA\Files_Sharing::loadAdditionalScripts');
437
-
438
-		$csp = new \OCP\AppFramework\Http\ContentSecurityPolicy();
439
-		$csp->addAllowedFrameDomain('\'self\'');
440
-		$response = new TemplateResponse($this->appName, 'public', $shareTmpl, 'base');
441
-		$response->setContentSecurityPolicy($csp);
442
-
443
-		$this->emitAccessShareHook($share);
444
-
445
-		return $response;
446
-	}
447
-
448
-	/**
449
-	 * @PublicPage
450
-	 * @NoCSRFRequired
451
-	 *
452
-	 * @param string $token
453
-	 * @param string $files
454
-	 * @param string $path
455
-	 * @param string $downloadStartSecret
456
-	 * @return void|\OCP\AppFramework\Http\Response
457
-	 * @throws NotFoundException
458
-	 */
459
-	public function downloadShare($token, $files = null, $path = '', $downloadStartSecret = '') {
460
-		\OC_User::setIncognitoMode(true);
461
-
462
-		$share = $this->shareManager->getShareByToken($token);
463
-
464
-		if(!($share->getPermissions() & \OCP\Constants::PERMISSION_READ)) {
465
-			return new \OCP\AppFramework\Http\DataResponse('Share is read-only');
466
-		}
467
-
468
-		// Share is password protected - check whether the user is permitted to access the share
469
-		if ($share->getPassword() !== null && !$this->linkShareAuth($share)) {
470
-			return new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.authenticate',
471
-				['token' => $token]));
472
-		}
473
-
474
-		$files_list = null;
475
-		if (!is_null($files)) { // download selected files
476
-			$files_list = json_decode($files);
477
-			// in case we get only a single file
478
-			if ($files_list === null) {
479
-				$files_list = [$files];
480
-			}
481
-			// Just in case $files is a single int like '1234'
482
-			if (!is_array($files_list)) {
483
-				$files_list = [$files_list];
484
-			}
485
-		}
486
-
487
-		$userFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
488
-		$originalSharePath = $userFolder->getRelativePath($share->getNode()->getPath());
489
-
490
-		if (!$this->validateShare($share)) {
491
-			throw new NotFoundException();
492
-		}
493
-
494
-		// Single file share
495
-		if ($share->getNode() instanceof \OCP\Files\File) {
496
-			// Single file download
497
-			$this->singleFileDownloaded($share, $share->getNode());
498
-		}
499
-		// Directory share
500
-		else {
501
-			/** @var \OCP\Files\Folder $node */
502
-			$node = $share->getNode();
503
-
504
-			// Try to get the path
505
-			if ($path !== '') {
506
-				try {
507
-					$node = $node->get($path);
508
-				} catch (NotFoundException $e) {
509
-					$this->emitAccessShareHook($share, 404, 'Share not found');
510
-					return new NotFoundResponse();
511
-				}
512
-			}
513
-
514
-			$originalSharePath = $userFolder->getRelativePath($node->getPath());
515
-
516
-			if ($node instanceof \OCP\Files\File) {
517
-				// Single file download
518
-				$this->singleFileDownloaded($share, $share->getNode());
519
-			} else if (!empty($files_list)) {
520
-				$this->fileListDownloaded($share, $files_list, $node);
521
-			} else {
522
-				// The folder is downloaded
523
-				$this->singleFileDownloaded($share, $share->getNode());
524
-			}
525
-		}
526
-
527
-		/* FIXME: We should do this all nicely in OCP */
528
-		OC_Util::tearDownFS();
529
-		OC_Util::setupFS($share->getShareOwner());
530
-
531
-		/**
532
-		 * this sets a cookie to be able to recognize the start of the download
533
-		 * the content must not be longer than 32 characters and must only contain
534
-		 * alphanumeric characters
535
-		 */
536
-		if (!empty($downloadStartSecret)
537
-			&& !isset($downloadStartSecret[32])
538
-			&& preg_match('!^[a-zA-Z0-9]+$!', $downloadStartSecret) === 1) {
539
-
540
-			// FIXME: set on the response once we use an actual app framework response
541
-			setcookie('ocDownloadStarted', $downloadStartSecret, time() + 20, '/');
542
-		}
543
-
544
-		$this->emitAccessShareHook($share);
545
-
546
-		$server_params = array( 'head' => $this->request->getMethod() === 'HEAD' );
547
-
548
-		/**
549
-		 * Http range requests support
550
-		 */
551
-		if (isset($_SERVER['HTTP_RANGE'])) {
552
-			$server_params['range'] = $this->request->getHeader('Range');
553
-		}
554
-
555
-		// download selected files
556
-		if (!is_null($files) && $files !== '') {
557
-			// FIXME: The exit is required here because otherwise the AppFramework is trying to add headers as well
558
-			// after dispatching the request which results in a "Cannot modify header information" notice.
559
-			OC_Files::get($originalSharePath, $files_list, $server_params);
560
-			exit();
561
-		} else {
562
-			// FIXME: The exit is required here because otherwise the AppFramework is trying to add headers as well
563
-			// after dispatching the request which results in a "Cannot modify header information" notice.
564
-			OC_Files::get(dirname($originalSharePath), basename($originalSharePath), $server_params);
565
-			exit();
566
-		}
567
-	}
568
-
569
-	/**
570
-	 * create activity for every downloaded file
571
-	 *
572
-	 * @param Share\IShare $share
573
-	 * @param array $files_list
574
-	 * @param \OCP\Files\Folder $node
575
-	 */
576
-	protected function fileListDownloaded(Share\IShare $share, array $files_list, \OCP\Files\Folder $node) {
577
-		foreach ($files_list as $file) {
578
-			$subNode = $node->get($file);
579
-			$this->singleFileDownloaded($share, $subNode);
580
-		}
581
-
582
-	}
583
-
584
-	/**
585
-	 * create activity if a single file was downloaded from a link share
586
-	 *
587
-	 * @param Share\IShare $share
588
-	 */
589
-	protected function singleFileDownloaded(Share\IShare $share, \OCP\Files\Node $node) {
590
-
591
-		$fileId = $node->getId();
592
-
593
-		$userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
594
-		$userNodeList = $userFolder->getById($fileId);
595
-		$userNode = $userNodeList[0];
596
-		$ownerFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
597
-		$userPath = $userFolder->getRelativePath($userNode->getPath());
598
-		$ownerPath = $ownerFolder->getRelativePath($node->getPath());
599
-
600
-		$parameters = [$userPath];
601
-
602
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
603
-			if ($node instanceof \OCP\Files\File) {
604
-				$subject = Downloads::SUBJECT_SHARED_FILE_BY_EMAIL_DOWNLOADED;
605
-			} else {
606
-				$subject = Downloads::SUBJECT_SHARED_FOLDER_BY_EMAIL_DOWNLOADED;
607
-			}
608
-			$parameters[] = $share->getSharedWith();
609
-		} else {
610
-			if ($node instanceof \OCP\Files\File) {
611
-				$subject = Downloads::SUBJECT_PUBLIC_SHARED_FILE_DOWNLOADED;
612
-			} else {
613
-				$subject = Downloads::SUBJECT_PUBLIC_SHARED_FOLDER_DOWNLOADED;
614
-			}
615
-		}
616
-
617
-		$this->publishActivity($subject, $parameters, $share->getSharedBy(), $fileId, $userPath);
618
-
619
-		if ($share->getShareOwner() !== $share->getSharedBy()) {
620
-			$parameters[0] = $ownerPath;
621
-			$this->publishActivity($subject, $parameters, $share->getShareOwner(), $fileId, $ownerPath);
622
-		}
623
-	}
624
-
625
-	/**
626
-	 * publish activity
627
-	 *
628
-	 * @param string $subject
629
-	 * @param array $parameters
630
-	 * @param string $affectedUser
631
-	 * @param int $fileId
632
-	 * @param string $filePath
633
-	 */
634
-	protected function publishActivity($subject,
635
-										array $parameters,
636
-										$affectedUser,
637
-										$fileId,
638
-										$filePath) {
639
-
640
-		$event = $this->activityManager->generateEvent();
641
-		$event->setApp('files_sharing')
642
-			->setType('public_links')
643
-			->setSubject($subject, $parameters)
644
-			->setAffectedUser($affectedUser)
645
-			->setObject('files', $fileId, $filePath);
646
-		$this->activityManager->publish($event);
647
-	}
345
+            $freeSpace = $share->getNode()->getStorage()->free_space($share->getNode()->getInternalPath());
346
+            if ($freeSpace < \OCP\Files\FileInfo::SPACE_UNLIMITED) {
347
+                $freeSpace = max($freeSpace, 0);
348
+            } else {
349
+                $freeSpace = (INF > 0) ? INF: PHP_INT_MAX; // work around https://bugs.php.net/bug.php?id=69188
350
+            }
351
+
352
+            $hideFileList = $share->getPermissions() & \OCP\Constants::PERMISSION_READ ? false : true;
353
+            $maxUploadFilesize = $freeSpace;
354
+
355
+            $folder = new Template('files', 'list', '');
356
+            $folder->assign('dir', $rootFolder->getRelativePath($folderNode->getPath()));
357
+            $folder->assign('dirToken', $token);
358
+            $folder->assign('permissions', \OCP\Constants::PERMISSION_READ);
359
+            $folder->assign('isPublic', true);
360
+            $folder->assign('hideFileList', $hideFileList);
361
+            $folder->assign('publicUploadEnabled', 'no');
362
+            $folder->assign('uploadMaxFilesize', $maxUploadFilesize);
363
+            $folder->assign('uploadMaxHumanFilesize', \OCP\Util::humanFileSize($maxUploadFilesize));
364
+            $folder->assign('freeSpace', $freeSpace);
365
+            $folder->assign('usedSpacePercent', 0);
366
+            $folder->assign('trash', false);
367
+            $shareTmpl['folder'] = $folder->fetchPage();
368
+        }
369
+
370
+        $shareTmpl['hideFileList'] = $hideFileList;
371
+        $shareTmpl['shareOwner'] = $this->userManager->get($share->getShareOwner())->getDisplayName();
372
+        $shareTmpl['downloadURL'] = $this->urlGenerator->linkToRouteAbsolute('files_sharing.sharecontroller.downloadShare', ['token' => $token]);
373
+        $shareTmpl['shareUrl'] = $this->urlGenerator->linkToRouteAbsolute('files_sharing.sharecontroller.showShare', ['token' => $token]);
374
+        $shareTmpl['maxSizeAnimateGif'] = $this->config->getSystemValue('max_filesize_animated_gifs_public_sharing', 10);
375
+        $shareTmpl['previewEnabled'] = $this->config->getSystemValue('enable_previews', true);
376
+        $shareTmpl['previewMaxX'] = $this->config->getSystemValue('preview_max_x', 1024);
377
+        $shareTmpl['previewMaxY'] = $this->config->getSystemValue('preview_max_y', 1024);
378
+        $shareTmpl['disclaimer'] = $this->config->getAppValue('core', 'shareapi_public_link_disclaimertext', null);
379
+        $shareTmpl['previewURL'] = $shareTmpl['downloadURL'];
380
+        $ogPreview = '';
381
+        if ($shareTmpl['previewSupported']) {
382
+            $shareTmpl['previewImage'] = $this->urlGenerator->linkToRouteAbsolute( 'files_sharing.PublicPreview.getPreview',
383
+                ['x' => 200, 'y' => 200, 'file' => $shareTmpl['directory_path'], 't' => $shareTmpl['dirToken']]);
384
+            $ogPreview = $shareTmpl['previewImage'];
385
+
386
+            // We just have direct previews for image files
387
+            if ($share->getNode()->getMimePart() === 'image') {
388
+                $shareTmpl['previewURL'] = $this->urlGenerator->linkToRouteAbsolute('files_sharing.publicpreview.directLink', ['token' => $token]);
389
+
390
+                $ogPreview = $shareTmpl['previewURL'];
391
+
392
+                //Whatapp is kind of picky about their size requirements
393
+                if ($this->request->isUserAgent(['/^WhatsApp/'])) {
394
+                    $ogPreview = $this->urlGenerator->linkToRouteAbsolute('files_sharing.PublicPreview.getPreview', [
395
+                        't' => $token,
396
+                        'x' => 256,
397
+                        'y' => 256,
398
+                        'a' => true,
399
+                    ]);
400
+                }
401
+            }
402
+        } else {
403
+            $shareTmpl['previewImage'] = $this->urlGenerator->getAbsoluteURL($this->urlGenerator->imagePath('core', 'favicon-fb.png'));
404
+            $ogPreview = $shareTmpl['previewImage'];
405
+        }
406
+
407
+        // Load files we need
408
+        \OCP\Util::addScript('files', 'file-upload');
409
+        \OCP\Util::addStyle('files_sharing', 'publicView');
410
+        \OCP\Util::addScript('files_sharing', 'public');
411
+        \OCP\Util::addScript('files', 'fileactions');
412
+        \OCP\Util::addScript('files', 'fileactionsmenu');
413
+        \OCP\Util::addScript('files', 'jquery.fileupload');
414
+        \OCP\Util::addScript('files_sharing', 'files_drop');
415
+
416
+        if (isset($shareTmpl['folder'])) {
417
+            // JS required for folders
418
+            \OCP\Util::addStyle('files', 'merged');
419
+            \OCP\Util::addScript('files', 'filesummary');
420
+            \OCP\Util::addScript('files', 'breadcrumb');
421
+            \OCP\Util::addScript('files', 'fileinfomodel');
422
+            \OCP\Util::addScript('files', 'newfilemenu');
423
+            \OCP\Util::addScript('files', 'files');
424
+            \OCP\Util::addScript('files', 'filelist');
425
+            \OCP\Util::addScript('files', 'keyboardshortcuts');
426
+        }
427
+
428
+        // OpenGraph Support: http://ogp.me/
429
+        \OCP\Util::addHeader('meta', ['property' => "og:title", 'content' => $shareTmpl['filename']]);
430
+        \OCP\Util::addHeader('meta', ['property' => "og:description", 'content' => $this->defaults->getName() . ($this->defaults->getSlogan() !== '' ? ' - ' . $this->defaults->getSlogan() : '')]);
431
+        \OCP\Util::addHeader('meta', ['property' => "og:site_name", 'content' => $this->defaults->getName()]);
432
+        \OCP\Util::addHeader('meta', ['property' => "og:url", 'content' => $shareTmpl['shareUrl']]);
433
+        \OCP\Util::addHeader('meta', ['property' => "og:type", 'content' => "object"]);
434
+        \OCP\Util::addHeader('meta', ['property' => "og:image", 'content' => $ogPreview]);
435
+
436
+        $this->eventDispatcher->dispatch('OCA\Files_Sharing::loadAdditionalScripts');
437
+
438
+        $csp = new \OCP\AppFramework\Http\ContentSecurityPolicy();
439
+        $csp->addAllowedFrameDomain('\'self\'');
440
+        $response = new TemplateResponse($this->appName, 'public', $shareTmpl, 'base');
441
+        $response->setContentSecurityPolicy($csp);
442
+
443
+        $this->emitAccessShareHook($share);
444
+
445
+        return $response;
446
+    }
447
+
448
+    /**
449
+     * @PublicPage
450
+     * @NoCSRFRequired
451
+     *
452
+     * @param string $token
453
+     * @param string $files
454
+     * @param string $path
455
+     * @param string $downloadStartSecret
456
+     * @return void|\OCP\AppFramework\Http\Response
457
+     * @throws NotFoundException
458
+     */
459
+    public function downloadShare($token, $files = null, $path = '', $downloadStartSecret = '') {
460
+        \OC_User::setIncognitoMode(true);
461
+
462
+        $share = $this->shareManager->getShareByToken($token);
463
+
464
+        if(!($share->getPermissions() & \OCP\Constants::PERMISSION_READ)) {
465
+            return new \OCP\AppFramework\Http\DataResponse('Share is read-only');
466
+        }
467
+
468
+        // Share is password protected - check whether the user is permitted to access the share
469
+        if ($share->getPassword() !== null && !$this->linkShareAuth($share)) {
470
+            return new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.authenticate',
471
+                ['token' => $token]));
472
+        }
473
+
474
+        $files_list = null;
475
+        if (!is_null($files)) { // download selected files
476
+            $files_list = json_decode($files);
477
+            // in case we get only a single file
478
+            if ($files_list === null) {
479
+                $files_list = [$files];
480
+            }
481
+            // Just in case $files is a single int like '1234'
482
+            if (!is_array($files_list)) {
483
+                $files_list = [$files_list];
484
+            }
485
+        }
486
+
487
+        $userFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
488
+        $originalSharePath = $userFolder->getRelativePath($share->getNode()->getPath());
489
+
490
+        if (!$this->validateShare($share)) {
491
+            throw new NotFoundException();
492
+        }
493
+
494
+        // Single file share
495
+        if ($share->getNode() instanceof \OCP\Files\File) {
496
+            // Single file download
497
+            $this->singleFileDownloaded($share, $share->getNode());
498
+        }
499
+        // Directory share
500
+        else {
501
+            /** @var \OCP\Files\Folder $node */
502
+            $node = $share->getNode();
503
+
504
+            // Try to get the path
505
+            if ($path !== '') {
506
+                try {
507
+                    $node = $node->get($path);
508
+                } catch (NotFoundException $e) {
509
+                    $this->emitAccessShareHook($share, 404, 'Share not found');
510
+                    return new NotFoundResponse();
511
+                }
512
+            }
513
+
514
+            $originalSharePath = $userFolder->getRelativePath($node->getPath());
515
+
516
+            if ($node instanceof \OCP\Files\File) {
517
+                // Single file download
518
+                $this->singleFileDownloaded($share, $share->getNode());
519
+            } else if (!empty($files_list)) {
520
+                $this->fileListDownloaded($share, $files_list, $node);
521
+            } else {
522
+                // The folder is downloaded
523
+                $this->singleFileDownloaded($share, $share->getNode());
524
+            }
525
+        }
526
+
527
+        /* FIXME: We should do this all nicely in OCP */
528
+        OC_Util::tearDownFS();
529
+        OC_Util::setupFS($share->getShareOwner());
530
+
531
+        /**
532
+         * this sets a cookie to be able to recognize the start of the download
533
+         * the content must not be longer than 32 characters and must only contain
534
+         * alphanumeric characters
535
+         */
536
+        if (!empty($downloadStartSecret)
537
+            && !isset($downloadStartSecret[32])
538
+            && preg_match('!^[a-zA-Z0-9]+$!', $downloadStartSecret) === 1) {
539
+
540
+            // FIXME: set on the response once we use an actual app framework response
541
+            setcookie('ocDownloadStarted', $downloadStartSecret, time() + 20, '/');
542
+        }
543
+
544
+        $this->emitAccessShareHook($share);
545
+
546
+        $server_params = array( 'head' => $this->request->getMethod() === 'HEAD' );
547
+
548
+        /**
549
+         * Http range requests support
550
+         */
551
+        if (isset($_SERVER['HTTP_RANGE'])) {
552
+            $server_params['range'] = $this->request->getHeader('Range');
553
+        }
554
+
555
+        // download selected files
556
+        if (!is_null($files) && $files !== '') {
557
+            // FIXME: The exit is required here because otherwise the AppFramework is trying to add headers as well
558
+            // after dispatching the request which results in a "Cannot modify header information" notice.
559
+            OC_Files::get($originalSharePath, $files_list, $server_params);
560
+            exit();
561
+        } else {
562
+            // FIXME: The exit is required here because otherwise the AppFramework is trying to add headers as well
563
+            // after dispatching the request which results in a "Cannot modify header information" notice.
564
+            OC_Files::get(dirname($originalSharePath), basename($originalSharePath), $server_params);
565
+            exit();
566
+        }
567
+    }
568
+
569
+    /**
570
+     * create activity for every downloaded file
571
+     *
572
+     * @param Share\IShare $share
573
+     * @param array $files_list
574
+     * @param \OCP\Files\Folder $node
575
+     */
576
+    protected function fileListDownloaded(Share\IShare $share, array $files_list, \OCP\Files\Folder $node) {
577
+        foreach ($files_list as $file) {
578
+            $subNode = $node->get($file);
579
+            $this->singleFileDownloaded($share, $subNode);
580
+        }
581
+
582
+    }
583
+
584
+    /**
585
+     * create activity if a single file was downloaded from a link share
586
+     *
587
+     * @param Share\IShare $share
588
+     */
589
+    protected function singleFileDownloaded(Share\IShare $share, \OCP\Files\Node $node) {
590
+
591
+        $fileId = $node->getId();
592
+
593
+        $userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
594
+        $userNodeList = $userFolder->getById($fileId);
595
+        $userNode = $userNodeList[0];
596
+        $ownerFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
597
+        $userPath = $userFolder->getRelativePath($userNode->getPath());
598
+        $ownerPath = $ownerFolder->getRelativePath($node->getPath());
599
+
600
+        $parameters = [$userPath];
601
+
602
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
603
+            if ($node instanceof \OCP\Files\File) {
604
+                $subject = Downloads::SUBJECT_SHARED_FILE_BY_EMAIL_DOWNLOADED;
605
+            } else {
606
+                $subject = Downloads::SUBJECT_SHARED_FOLDER_BY_EMAIL_DOWNLOADED;
607
+            }
608
+            $parameters[] = $share->getSharedWith();
609
+        } else {
610
+            if ($node instanceof \OCP\Files\File) {
611
+                $subject = Downloads::SUBJECT_PUBLIC_SHARED_FILE_DOWNLOADED;
612
+            } else {
613
+                $subject = Downloads::SUBJECT_PUBLIC_SHARED_FOLDER_DOWNLOADED;
614
+            }
615
+        }
616
+
617
+        $this->publishActivity($subject, $parameters, $share->getSharedBy(), $fileId, $userPath);
618
+
619
+        if ($share->getShareOwner() !== $share->getSharedBy()) {
620
+            $parameters[0] = $ownerPath;
621
+            $this->publishActivity($subject, $parameters, $share->getShareOwner(), $fileId, $ownerPath);
622
+        }
623
+    }
624
+
625
+    /**
626
+     * publish activity
627
+     *
628
+     * @param string $subject
629
+     * @param array $parameters
630
+     * @param string $affectedUser
631
+     * @param int $fileId
632
+     * @param string $filePath
633
+     */
634
+    protected function publishActivity($subject,
635
+                                        array $parameters,
636
+                                        $affectedUser,
637
+                                        $fileId,
638
+                                        $filePath) {
639
+
640
+        $event = $this->activityManager->generateEvent();
641
+        $event->setApp('files_sharing')
642
+            ->setType('public_links')
643
+            ->setSubject($subject, $parameters)
644
+            ->setAffectedUser($affectedUser)
645
+            ->setObject('files', $fileId, $filePath);
646
+        $this->activityManager->publish($event);
647
+    }
648 648
 
649 649
 
650 650
 }
Please login to merge, or discard this patch.
Spacing   +11 added lines, -11 removed lines patch added patch discarded remove patch
@@ -153,7 +153,7 @@  discard block
 block discarded – undo
153 153
 	public function showAuthenticate($token) {
154 154
 		$share = $this->shareManager->getShareByToken($token);
155 155
 
156
-		if($this->linkShareAuth($share)) {
156
+		if ($this->linkShareAuth($share)) {
157 157
 			return new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.showShare', array('token' => $token)));
158 158
 		}
159 159
 
@@ -181,7 +181,7 @@  discard block
 block discarded – undo
181 181
 
182 182
 		$authenticate = $this->linkShareAuth($share, $password);
183 183
 
184
-		if($authenticate === true) {
184
+		if ($authenticate === true) {
185 185
 			return new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.showShare', array('token' => $token)));
186 186
 		}
187 187
 
@@ -205,15 +205,15 @@  discard block
 block discarded – undo
205 205
 		if ($password !== null) {
206 206
 			if ($this->shareManager->checkPassword($share, $password)) {
207 207
 				$this->session->regenerateId(true, true);
208
-				$this->session->set('public_link_authenticated', (string)$share->getId());
208
+				$this->session->set('public_link_authenticated', (string) $share->getId());
209 209
 			} else {
210 210
 				$this->emitAccessShareHook($share, 403, 'Wrong password');
211 211
 				return false;
212 212
 			}
213 213
 		} else {
214 214
 			// not authenticated ?
215
-			if ( ! $this->session->exists('public_link_authenticated')
216
-				|| $this->session->get('public_link_authenticated') !== (string)$share->getId()) {
215
+			if (!$this->session->exists('public_link_authenticated')
216
+				|| $this->session->get('public_link_authenticated') !== (string) $share->getId()) {
217 217
 				return false;
218 218
 			}
219 219
 		}
@@ -234,7 +234,7 @@  discard block
 block discarded – undo
234 234
 		$itemType = $itemSource = $uidOwner = '';
235 235
 		$token = $share;
236 236
 		$exception = null;
237
-		if($share instanceof \OCP\Share\IShare) {
237
+		if ($share instanceof \OCP\Share\IShare) {
238 238
 			try {
239 239
 				$token = $share->getToken();
240 240
 				$uidOwner = $share->getSharedBy();
@@ -253,7 +253,7 @@  discard block
 block discarded – undo
253 253
 			'errorCode' => $errorCode,
254 254
 			'errorMessage' => $errorMessage,
255 255
 		]);
256
-		if(!is_null($exception)) {
256
+		if (!is_null($exception)) {
257 257
 			throw $exception;
258 258
 		}
259 259
 	}
@@ -379,7 +379,7 @@  discard block
 block discarded – undo
379 379
 		$shareTmpl['previewURL'] = $shareTmpl['downloadURL'];
380 380
 		$ogPreview = '';
381 381
 		if ($shareTmpl['previewSupported']) {
382
-			$shareTmpl['previewImage'] = $this->urlGenerator->linkToRouteAbsolute( 'files_sharing.PublicPreview.getPreview',
382
+			$shareTmpl['previewImage'] = $this->urlGenerator->linkToRouteAbsolute('files_sharing.PublicPreview.getPreview',
383 383
 				['x' => 200, 'y' => 200, 'file' => $shareTmpl['directory_path'], 't' => $shareTmpl['dirToken']]);
384 384
 			$ogPreview = $shareTmpl['previewImage'];
385 385
 
@@ -427,7 +427,7 @@  discard block
 block discarded – undo
427 427
 
428 428
 		// OpenGraph Support: http://ogp.me/
429 429
 		\OCP\Util::addHeader('meta', ['property' => "og:title", 'content' => $shareTmpl['filename']]);
430
-		\OCP\Util::addHeader('meta', ['property' => "og:description", 'content' => $this->defaults->getName() . ($this->defaults->getSlogan() !== '' ? ' - ' . $this->defaults->getSlogan() : '')]);
430
+		\OCP\Util::addHeader('meta', ['property' => "og:description", 'content' => $this->defaults->getName().($this->defaults->getSlogan() !== '' ? ' - '.$this->defaults->getSlogan() : '')]);
431 431
 		\OCP\Util::addHeader('meta', ['property' => "og:site_name", 'content' => $this->defaults->getName()]);
432 432
 		\OCP\Util::addHeader('meta', ['property' => "og:url", 'content' => $shareTmpl['shareUrl']]);
433 433
 		\OCP\Util::addHeader('meta', ['property' => "og:type", 'content' => "object"]);
@@ -461,7 +461,7 @@  discard block
 block discarded – undo
461 461
 
462 462
 		$share = $this->shareManager->getShareByToken($token);
463 463
 
464
-		if(!($share->getPermissions() & \OCP\Constants::PERMISSION_READ)) {
464
+		if (!($share->getPermissions() & \OCP\Constants::PERMISSION_READ)) {
465 465
 			return new \OCP\AppFramework\Http\DataResponse('Share is read-only');
466 466
 		}
467 467
 
@@ -543,7 +543,7 @@  discard block
 block discarded – undo
543 543
 
544 544
 		$this->emitAccessShareHook($share);
545 545
 
546
-		$server_params = array( 'head' => $this->request->getMethod() === 'HEAD' );
546
+		$server_params = array('head' => $this->request->getMethod() === 'HEAD');
547 547
 
548 548
 		/**
549 549
 		 * Http range requests support
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   +789 added lines, -789 removed lines patch added patch discarded remove patch
@@ -51,793 +51,793 @@
 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 IAppManager */
59
-	private $appManager;
60
-	/** @var IGroupManager|\OC\Group\Manager */ // FIXME Requires a method that is not on the interface
61
-	private $groupManager;
62
-	/** @var IUserSession */
63
-	private $userSession;
64
-	/** @var AccountManager */
65
-	private $accountManager;
66
-	/** @var ILogger */
67
-	private $logger;
68
-	/** @var IFactory */
69
-	private $l10nFactory;
70
-	/** @var NewUserMailHelper */
71
-	private $newUserMailHelper;
72
-
73
-	/**
74
-	 * @param string $appName
75
-	 * @param IRequest $request
76
-	 * @param IUserManager $userManager
77
-	 * @param IConfig $config
78
-	 * @param IAppManager $appManager
79
-	 * @param IGroupManager $groupManager
80
-	 * @param IUserSession $userSession
81
-	 * @param AccountManager $accountManager
82
-	 * @param ILogger $logger
83
-	 * @param IFactory $l10nFactory
84
-	 * @param NewUserMailHelper $newUserMailHelper
85
-	 */
86
-	public function __construct($appName,
87
-								IRequest $request,
88
-								IUserManager $userManager,
89
-								IConfig $config,
90
-								IAppManager $appManager,
91
-								IGroupManager $groupManager,
92
-								IUserSession $userSession,
93
-								AccountManager $accountManager,
94
-								ILogger $logger,
95
-								IFactory $l10nFactory,
96
-								NewUserMailHelper $newUserMailHelper) {
97
-		parent::__construct($appName, $request);
98
-
99
-		$this->userManager = $userManager;
100
-		$this->config = $config;
101
-		$this->appManager = $appManager;
102
-		$this->groupManager = $groupManager;
103
-		$this->userSession = $userSession;
104
-		$this->accountManager = $accountManager;
105
-		$this->logger = $logger;
106
-		$this->l10nFactory = $l10nFactory;
107
-		$this->newUserMailHelper = $newUserMailHelper;
108
-	}
109
-
110
-	/**
111
-	 * @NoAdminRequired
112
-	 *
113
-	 * returns a list of users
114
-	 *
115
-	 * @param string $search
116
-	 * @param int $limit
117
-	 * @param int $offset
118
-	 * @return DataResponse
119
-	 */
120
-	public function getUsers($search = '', $limit = null, $offset = null) {
121
-		$user = $this->userSession->getUser();
122
-		$users = [];
123
-
124
-		// Admin? Or SubAdmin?
125
-		$uid = $user->getUID();
126
-		$subAdminManager = $this->groupManager->getSubAdmin();
127
-		if($this->groupManager->isAdmin($uid)){
128
-			$users = $this->userManager->search($search, $limit, $offset);
129
-		} else if ($subAdminManager->isSubAdmin($user)) {
130
-			$subAdminOfGroups = $subAdminManager->getSubAdminsGroups($user);
131
-			foreach ($subAdminOfGroups as $key => $group) {
132
-				$subAdminOfGroups[$key] = $group->getGID();
133
-			}
134
-
135
-			if($offset === null) {
136
-				$offset = 0;
137
-			}
138
-
139
-			$users = [];
140
-			foreach ($subAdminOfGroups as $group) {
141
-				$users = array_merge($users, $this->groupManager->displayNamesInGroup($group, $search));
142
-			}
143
-
144
-			$users = array_slice($users, $offset, $limit);
145
-		}
146
-
147
-		$users = array_keys($users);
148
-
149
-		return new DataResponse([
150
-			'users' => $users
151
-		]);
152
-	}
153
-
154
-	/**
155
-	 * @PasswordConfirmationRequired
156
-	 * @NoAdminRequired
157
-	 *
158
-	 * @param string $userid
159
-	 * @param string $password
160
-	 * @param array $groups
161
-	 * @return DataResponse
162
-	 * @throws OCSException
163
-	 */
164
-	public function addUser($userid, $password, $groups = null) {
165
-		$user = $this->userSession->getUser();
166
-		$isAdmin = $this->groupManager->isAdmin($user->getUID());
167
-		$subAdminManager = $this->groupManager->getSubAdmin();
168
-
169
-		if($this->userManager->userExists($userid)) {
170
-			$this->logger->error('Failed addUser attempt: User already exists.', ['app' => 'ocs_api']);
171
-			throw new OCSException('User already exists', 102);
172
-		}
173
-
174
-		if(is_array($groups)) {
175
-			foreach ($groups as $group) {
176
-				if(!$this->groupManager->groupExists($group)) {
177
-					throw new OCSException('group '.$group.' does not exist', 104);
178
-				}
179
-				if(!$isAdmin && !$subAdminManager->isSubAdminofGroup($user, $this->groupManager->get($group))) {
180
-					throw new OCSException('insufficient privileges for group '. $group, 105);
181
-				}
182
-			}
183
-		} else {
184
-			if(!$isAdmin) {
185
-				throw new OCSException('no group specified (required for subadmins)', 106);
186
-			}
187
-		}
188
-
189
-		try {
190
-			$newUser = $this->userManager->createUser($userid, $password);
191
-			$this->logger->info('Successful addUser call with userid: ' . $userid, ['app' => 'ocs_api']);
192
-
193
-			if (is_array($groups)) {
194
-				foreach ($groups as $group) {
195
-					$this->groupManager->get($group)->addUser($newUser);
196
-					$this->logger->info('Added userid ' . $userid . ' to group ' . $group, ['app' => 'ocs_api']);
197
-				}
198
-			}
199
-			return new DataResponse();
200
-		} catch (HintException $e ) {
201
-			$this->logger->logException($e, [
202
-				'message' => 'Failed addUser attempt with hint exception.',
203
-				'level' => \OCP\Util::WARN,
204
-				'app' => 'ocs_api',
205
-			]);
206
-			throw new OCSException($e->getHint(), 107);
207
-		} catch (\Exception $e) {
208
-			$this->logger->error('Failed addUser attempt with exception: '.$e->getMessage(), ['app' => 'ocs_api']);
209
-			throw new OCSException('Bad request', 101);
210
-		}
211
-	}
212
-
213
-	/**
214
-	 * @NoAdminRequired
215
-	 * @NoSubAdminRequired
216
-	 *
217
-	 * gets user info
218
-	 *
219
-	 * @param string $userId
220
-	 * @return DataResponse
221
-	 * @throws OCSException
222
-	 */
223
-	public function getUser($userId) {
224
-		$data = $this->getUserData($userId);
225
-		return new DataResponse($data);
226
-	}
227
-
228
-	/**
229
-	 * @NoAdminRequired
230
-	 * @NoSubAdminRequired
231
-	 *
232
-	 * gets user info from the currently logged in user
233
-	 *
234
-	 * @return DataResponse
235
-	 * @throws OCSException
236
-	 */
237
-	public function getCurrentUser() {
238
-		$user = $this->userSession->getUser();
239
-		if ($user) {
240
-			$data =  $this->getUserData($user->getUID());
241
-			// rename "displayname" to "display-name" only for this call to keep
242
-			// the API stable.
243
-			$data['display-name'] = $data['displayname'];
244
-			unset($data['displayname']);
245
-			return new DataResponse($data);
246
-
247
-		}
248
-
249
-		throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
250
-	}
251
-
252
-	/**
253
-	 * creates a array with all user data
254
-	 *
255
-	 * @param $userId
256
-	 * @return array
257
-	 * @throws OCSException
258
-	 */
259
-	protected function getUserData($userId) {
260
-		$currentLoggedInUser = $this->userSession->getUser();
261
-
262
-		$data = [];
263
-
264
-		// Check if the target user exists
265
-		$targetUserObject = $this->userManager->get($userId);
266
-		if($targetUserObject === null) {
267
-			throw new OCSException('The requested user could not be found', \OCP\API::RESPOND_NOT_FOUND);
268
-		}
269
-
270
-		// Admin? Or SubAdmin?
271
-		if($this->groupManager->isAdmin($currentLoggedInUser->getUID())
272
-			|| $this->groupManager->getSubAdmin()->isUserAccessible($currentLoggedInUser, $targetUserObject)) {
273
-			$data['enabled'] = $this->config->getUserValue($targetUserObject->getUID(), 'core', 'enabled', 'true');
274
-		} else {
275
-			// Check they are looking up themselves
276
-			if($currentLoggedInUser->getUID() !== $targetUserObject->getUID()) {
277
-				throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
278
-			}
279
-		}
280
-
281
-		$userAccount = $this->accountManager->getUser($targetUserObject);
282
-		$groups = $this->groupManager->getUserGroups($targetUserObject);
283
-		$gids = [];
284
-		foreach ($groups as $group) {
285
-			$gids[] = $group->getDisplayName();
286
-		}
287
-
288
-		// Find the data
289
-		$data['id'] = $targetUserObject->getUID();
290
-		$data['quota'] = $this->fillStorageInfo($targetUserObject->getUID());
291
-		$data[AccountManager::PROPERTY_EMAIL] = $targetUserObject->getEMailAddress();
292
-		$data[AccountManager::PROPERTY_DISPLAYNAME] = $targetUserObject->getDisplayName();
293
-		$data[AccountManager::PROPERTY_PHONE] = $userAccount[AccountManager::PROPERTY_PHONE]['value'];
294
-		$data[AccountManager::PROPERTY_ADDRESS] = $userAccount[AccountManager::PROPERTY_ADDRESS]['value'];
295
-		$data[AccountManager::PROPERTY_WEBSITE] = $userAccount[AccountManager::PROPERTY_WEBSITE]['value'];
296
-		$data[AccountManager::PROPERTY_TWITTER] = $userAccount[AccountManager::PROPERTY_TWITTER]['value'];
297
-		$data['groups'] = $gids;
298
-		$data['language'] = $this->config->getUserValue($targetUserObject->getUID(), 'core', 'lang');
299
-
300
-		return $data;
301
-	}
302
-
303
-	/**
304
-	 * @NoAdminRequired
305
-	 * @NoSubAdminRequired
306
-	 * @PasswordConfirmationRequired
307
-	 *
308
-	 * edit users
309
-	 *
310
-	 * @param string $userId
311
-	 * @param string $key
312
-	 * @param string $value
313
-	 * @return DataResponse
314
-	 * @throws OCSException
315
-	 * @throws OCSForbiddenException
316
-	 */
317
-	public function editUser($userId, $key, $value) {
318
-		$currentLoggedInUser = $this->userSession->getUser();
319
-
320
-		$targetUser = $this->userManager->get($userId);
321
-		if($targetUser === null) {
322
-			throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
323
-		}
324
-
325
-		$permittedFields = [];
326
-		if($targetUser->getUID() === $currentLoggedInUser->getUID()) {
327
-			// Editing self (display, email)
328
-			if ($this->config->getSystemValue('allow_user_to_change_display_name', true) !== false) {
329
-				$permittedFields[] = 'display';
330
-				$permittedFields[] = AccountManager::PROPERTY_DISPLAYNAME;
331
-				$permittedFields[] = AccountManager::PROPERTY_EMAIL;
332
-			}
333
-
334
-			$permittedFields[] = 'password';
335
-			if ($this->config->getSystemValue('force_language', false) === false ||
336
-				$this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
337
-				$permittedFields[] = 'language';
338
-			}
339
-
340
-			if ($this->appManager->isEnabledForUser('federatedfilesharing')) {
341
-				$federatedFileSharing = new \OCA\FederatedFileSharing\AppInfo\Application();
342
-				$shareProvider = $federatedFileSharing->getFederatedShareProvider();
343
-				if ($shareProvider->isLookupServerUploadEnabled()) {
344
-					$permittedFields[] = AccountManager::PROPERTY_PHONE;
345
-					$permittedFields[] = AccountManager::PROPERTY_ADDRESS;
346
-					$permittedFields[] = AccountManager::PROPERTY_WEBSITE;
347
-					$permittedFields[] = AccountManager::PROPERTY_TWITTER;
348
-				}
349
-			}
350
-
351
-			// If admin they can edit their own quota
352
-			if($this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
353
-				$permittedFields[] = 'quota';
354
-			}
355
-		} else {
356
-			// Check if admin / subadmin
357
-			$subAdminManager = $this->groupManager->getSubAdmin();
358
-			if($subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)
359
-			|| $this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
360
-				// They have permissions over the user
361
-				$permittedFields[] = 'display';
362
-				$permittedFields[] = AccountManager::PROPERTY_DISPLAYNAME;
363
-				$permittedFields[] = AccountManager::PROPERTY_EMAIL;
364
-				$permittedFields[] = 'password';
365
-				$permittedFields[] = 'language';
366
-				$permittedFields[] = AccountManager::PROPERTY_PHONE;
367
-				$permittedFields[] = AccountManager::PROPERTY_ADDRESS;
368
-				$permittedFields[] = AccountManager::PROPERTY_WEBSITE;
369
-				$permittedFields[] = AccountManager::PROPERTY_TWITTER;
370
-				$permittedFields[] = 'quota';
371
-			} else {
372
-				// No rights
373
-				throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
374
-			}
375
-		}
376
-		// Check if permitted to edit this field
377
-		if(!in_array($key, $permittedFields)) {
378
-			throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
379
-		}
380
-		// Process the edit
381
-		switch($key) {
382
-			case 'display':
383
-			case AccountManager::PROPERTY_DISPLAYNAME:
384
-				$targetUser->setDisplayName($value);
385
-				break;
386
-			case 'quota':
387
-				$quota = $value;
388
-				if($quota !== 'none' && $quota !== 'default') {
389
-					if (is_numeric($quota)) {
390
-						$quota = (float) $quota;
391
-					} else {
392
-						$quota = \OCP\Util::computerFileSize($quota);
393
-					}
394
-					if ($quota === false) {
395
-						throw new OCSException('Invalid quota value '.$value, 103);
396
-					}
397
-					if($quota === 0) {
398
-						$quota = 'default';
399
-					}else if($quota === -1) {
400
-						$quota = 'none';
401
-					} else {
402
-						$quota = \OCP\Util::humanFileSize($quota);
403
-					}
404
-				}
405
-				$targetUser->setQuota($quota);
406
-				break;
407
-			case 'password':
408
-				$targetUser->setPassword($value);
409
-				break;
410
-			case 'language':
411
-				$languagesCodes = $this->l10nFactory->findAvailableLanguages();
412
-				if (!in_array($value, $languagesCodes, true) && $value !== 'en') {
413
-					throw new OCSException('Invalid language', 102);
414
-				}
415
-				$this->config->setUserValue($targetUser->getUID(), 'core', 'lang', $value);
416
-				break;
417
-			case AccountManager::PROPERTY_EMAIL:
418
-				if(filter_var($value, FILTER_VALIDATE_EMAIL)) {
419
-					$targetUser->setEMailAddress($value);
420
-				} else {
421
-					throw new OCSException('', 102);
422
-				}
423
-				break;
424
-			case AccountManager::PROPERTY_PHONE:
425
-			case AccountManager::PROPERTY_ADDRESS:
426
-			case AccountManager::PROPERTY_WEBSITE:
427
-			case AccountManager::PROPERTY_TWITTER:
428
-				$userAccount = $this->accountManager->getUser($targetUser);
429
-				if ($userAccount[$key]['value'] !== $value) {
430
-					$userAccount[$key]['value'] = $value;
431
-					$this->accountManager->updateUser($targetUser, $userAccount);
432
-				}
433
-				break;
434
-			default:
435
-				throw new OCSException('', 103);
436
-		}
437
-		return new DataResponse();
438
-	}
439
-
440
-	/**
441
-	 * @PasswordConfirmationRequired
442
-	 * @NoAdminRequired
443
-	 *
444
-	 * @param string $userId
445
-	 * @return DataResponse
446
-	 * @throws OCSException
447
-	 * @throws OCSForbiddenException
448
-	 */
449
-	public function deleteUser($userId) {
450
-		$currentLoggedInUser = $this->userSession->getUser();
451
-
452
-		$targetUser = $this->userManager->get($userId);
453
-
454
-		if($targetUser === null || $targetUser->getUID() === $currentLoggedInUser->getUID()) {
455
-			throw new OCSException('', 101);
456
-		}
457
-
458
-		// If not permitted
459
-		$subAdminManager = $this->groupManager->getSubAdmin();
460
-		if(!$this->groupManager->isAdmin($currentLoggedInUser->getUID()) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) {
461
-			throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
462
-		}
463
-
464
-		// Go ahead with the delete
465
-		if($targetUser->delete()) {
466
-			return new DataResponse();
467
-		} else {
468
-			throw new OCSException('', 101);
469
-		}
470
-	}
471
-
472
-	/**
473
-	 * @PasswordConfirmationRequired
474
-	 * @NoAdminRequired
475
-	 *
476
-	 * @param string $userId
477
-	 * @return DataResponse
478
-	 * @throws OCSException
479
-	 * @throws OCSForbiddenException
480
-	 */
481
-	public function disableUser($userId) {
482
-		return $this->setEnabled($userId, false);
483
-	}
484
-
485
-	/**
486
-	 * @PasswordConfirmationRequired
487
-	 * @NoAdminRequired
488
-	 *
489
-	 * @param string $userId
490
-	 * @return DataResponse
491
-	 * @throws OCSException
492
-	 * @throws OCSForbiddenException
493
-	 */
494
-	public function enableUser($userId) {
495
-		return $this->setEnabled($userId, true);
496
-	}
497
-
498
-	/**
499
-	 * @param string $userId
500
-	 * @param bool $value
501
-	 * @return DataResponse
502
-	 * @throws OCSException
503
-	 * @throws OCSForbiddenException
504
-	 */
505
-	private function setEnabled($userId, $value) {
506
-		$currentLoggedInUser = $this->userSession->getUser();
507
-
508
-		$targetUser = $this->userManager->get($userId);
509
-		if($targetUser === null || $targetUser->getUID() === $currentLoggedInUser->getUID()) {
510
-			throw new OCSException('', 101);
511
-		}
512
-
513
-		// If not permitted
514
-		$subAdminManager = $this->groupManager->getSubAdmin();
515
-		if(!$this->groupManager->isAdmin($currentLoggedInUser->getUID()) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) {
516
-			throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
517
-		}
518
-
519
-		// enable/disable the user now
520
-		$targetUser->setEnabled($value);
521
-		return new DataResponse();
522
-	}
523
-
524
-	/**
525
-	 * @NoAdminRequired
526
-	 * @NoSubAdminRequired
527
-	 *
528
-	 * @param string $userId
529
-	 * @return DataResponse
530
-	 * @throws OCSException
531
-	 */
532
-	public function getUsersGroups($userId) {
533
-		$loggedInUser = $this->userSession->getUser();
534
-
535
-		$targetUser = $this->userManager->get($userId);
536
-		if($targetUser === null) {
537
-			throw new OCSException('', \OCP\API::RESPOND_NOT_FOUND);
538
-		}
539
-
540
-		if($targetUser->getUID() === $loggedInUser->getUID() || $this->groupManager->isAdmin($loggedInUser->getUID())) {
541
-			// Self lookup or admin lookup
542
-			return new DataResponse([
543
-				'groups' => $this->groupManager->getUserGroupIds($targetUser)
544
-			]);
545
-		} else {
546
-			$subAdminManager = $this->groupManager->getSubAdmin();
547
-
548
-			// Looking up someone else
549
-			if($subAdminManager->isUserAccessible($loggedInUser, $targetUser)) {
550
-				// Return the group that the method caller is subadmin of for the user in question
551
-				/** @var IGroup[] $getSubAdminsGroups */
552
-				$getSubAdminsGroups = $subAdminManager->getSubAdminsGroups($loggedInUser);
553
-				foreach ($getSubAdminsGroups as $key => $group) {
554
-					$getSubAdminsGroups[$key] = $group->getGID();
555
-				}
556
-				$groups = array_intersect(
557
-					$getSubAdminsGroups,
558
-					$this->groupManager->getUserGroupIds($targetUser)
559
-				);
560
-				return new DataResponse(['groups' => $groups]);
561
-			} else {
562
-				// Not permitted
563
-				throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
564
-			}
565
-		}
566
-
567
-	}
568
-
569
-	/**
570
-	 * @PasswordConfirmationRequired
571
-	 * @NoAdminRequired
572
-	 *
573
-	 * @param string $userId
574
-	 * @param string $groupid
575
-	 * @return DataResponse
576
-	 * @throws OCSException
577
-	 */
578
-	public function addToGroup($userId, $groupid = '') {
579
-		if($groupid === '') {
580
-			throw new OCSException('', 101);
581
-		}
582
-
583
-		$group = $this->groupManager->get($groupid);
584
-		$targetUser = $this->userManager->get($userId);
585
-		if($group === null) {
586
-			throw new OCSException('', 102);
587
-		}
588
-		if($targetUser === null) {
589
-			throw new OCSException('', 103);
590
-		}
591
-
592
-		// If they're not an admin, check they are a subadmin of the group in question
593
-		$loggedInUser = $this->userSession->getUser();
594
-		$subAdminManager = $this->groupManager->getSubAdmin();
595
-		if (!$this->groupManager->isAdmin($loggedInUser->getUID()) && !$subAdminManager->isSubAdminOfGroup($loggedInUser, $group)) {
596
-			throw new OCSException('', 104);
597
-		}
598
-
599
-		// Add user to group
600
-		$group->addUser($targetUser);
601
-		return new DataResponse();
602
-	}
603
-
604
-	/**
605
-	 * @PasswordConfirmationRequired
606
-	 * @NoAdminRequired
607
-	 *
608
-	 * @param string $userId
609
-	 * @param string $groupid
610
-	 * @return DataResponse
611
-	 * @throws OCSException
612
-	 */
613
-	public function removeFromGroup($userId, $groupid) {
614
-		$loggedInUser = $this->userSession->getUser();
615
-
616
-		if($groupid === null || trim($groupid) === '') {
617
-			throw new OCSException('', 101);
618
-		}
619
-
620
-		$group = $this->groupManager->get($groupid);
621
-		if($group === null) {
622
-			throw new OCSException('', 102);
623
-		}
624
-
625
-		$targetUser = $this->userManager->get($userId);
626
-		if($targetUser === null) {
627
-			throw new OCSException('', 103);
628
-		}
629
-
630
-		// If they're not an admin, check they are a subadmin of the group in question
631
-		$subAdminManager = $this->groupManager->getSubAdmin();
632
-		if (!$this->groupManager->isAdmin($loggedInUser->getUID()) && !$subAdminManager->isSubAdminOfGroup($loggedInUser, $group)) {
633
-			throw new OCSException('', 104);
634
-		}
635
-
636
-		// Check they aren't removing themselves from 'admin' or their 'subadmin; group
637
-		if ($targetUser->getUID() === $loggedInUser->getUID()) {
638
-			if ($this->groupManager->isAdmin($loggedInUser->getUID())) {
639
-				if ($group->getGID() === 'admin') {
640
-					throw new OCSException('Cannot remove yourself from the admin group', 105);
641
-				}
642
-			} else {
643
-				// Not an admin, so the user must be a subadmin of this group, but that is not allowed.
644
-				throw new OCSException('Cannot remove yourself from this group as you are a SubAdmin', 105);
645
-			}
646
-
647
-		} else if (!$this->groupManager->isAdmin($loggedInUser->getUID())) {
648
-			/** @var IGroup[] $subAdminGroups */
649
-			$subAdminGroups = $subAdminManager->getSubAdminsGroups($loggedInUser);
650
-			$subAdminGroups = array_map(function (IGroup $subAdminGroup) {
651
-				return $subAdminGroup->getGID();
652
-			}, $subAdminGroups);
653
-			$userGroups = $this->groupManager->getUserGroupIds($targetUser);
654
-			$userSubAdminGroups = array_intersect($subAdminGroups, $userGroups);
655
-
656
-			if (count($userSubAdminGroups) <= 1) {
657
-				// Subadmin must not be able to remove a user from all their subadmin groups.
658
-				throw new OCSException('Cannot remove user from this group as this is the only remaining group you are a SubAdmin of', 105);
659
-			}
660
-		}
661
-
662
-		// Remove user from group
663
-		$group->removeUser($targetUser);
664
-		return new DataResponse();
665
-	}
666
-
667
-	/**
668
-	 * Creates a subadmin
669
-	 *
670
-	 * @PasswordConfirmationRequired
671
-	 *
672
-	 * @param string $userId
673
-	 * @param string $groupid
674
-	 * @return DataResponse
675
-	 * @throws OCSException
676
-	 */
677
-	public function addSubAdmin($userId, $groupid) {
678
-		$group = $this->groupManager->get($groupid);
679
-		$user = $this->userManager->get($userId);
680
-
681
-		// Check if the user exists
682
-		if($user === null) {
683
-			throw new OCSException('User does not exist', 101);
684
-		}
685
-		// Check if group exists
686
-		if($group === null) {
687
-			throw new OCSException('Group does not exist',  102);
688
-		}
689
-		// Check if trying to make subadmin of admin group
690
-		if($group->getGID() === 'admin') {
691
-			throw new OCSException('Cannot create subadmins for admin group', 103);
692
-		}
693
-
694
-		$subAdminManager = $this->groupManager->getSubAdmin();
695
-
696
-		// We cannot be subadmin twice
697
-		if ($subAdminManager->isSubAdminofGroup($user, $group)) {
698
-			return new DataResponse();
699
-		}
700
-		// Go
701
-		if($subAdminManager->createSubAdmin($user, $group)) {
702
-			return new DataResponse();
703
-		} else {
704
-			throw new OCSException('Unknown error occurred', 103);
705
-		}
706
-	}
707
-
708
-	/**
709
-	 * Removes a subadmin from a group
710
-	 *
711
-	 * @PasswordConfirmationRequired
712
-	 *
713
-	 * @param string $userId
714
-	 * @param string $groupid
715
-	 * @return DataResponse
716
-	 * @throws OCSException
717
-	 */
718
-	public function removeSubAdmin($userId, $groupid) {
719
-		$group = $this->groupManager->get($groupid);
720
-		$user = $this->userManager->get($userId);
721
-		$subAdminManager = $this->groupManager->getSubAdmin();
722
-
723
-		// Check if the user exists
724
-		if($user === null) {
725
-			throw new OCSException('User does not exist', 101);
726
-		}
727
-		// Check if the group exists
728
-		if($group === null) {
729
-			throw new OCSException('Group does not exist', 101);
730
-		}
731
-		// Check if they are a subadmin of this said group
732
-		if(!$subAdminManager->isSubAdminOfGroup($user, $group)) {
733
-			throw new OCSException('User is not a subadmin of this group', 102);
734
-		}
735
-
736
-		// Go
737
-		if($subAdminManager->deleteSubAdmin($user, $group)) {
738
-			return new DataResponse();
739
-		} else {
740
-			throw new OCSException('Unknown error occurred', 103);
741
-		}
742
-	}
743
-
744
-	/**
745
-	 * Get the groups a user is a subadmin of
746
-	 *
747
-	 * @param string $userId
748
-	 * @return DataResponse
749
-	 * @throws OCSException
750
-	 */
751
-	public function getUserSubAdminGroups($userId) {
752
-		$user = $this->userManager->get($userId);
753
-		// Check if the user exists
754
-		if($user === null) {
755
-			throw new OCSException('User does not exist', 101);
756
-		}
757
-
758
-		// Get the subadmin groups
759
-		$groups = $this->groupManager->getSubAdmin()->getSubAdminsGroups($user);
760
-		foreach ($groups as $key => $group) {
761
-			$groups[$key] = $group->getGID();
762
-		}
763
-
764
-		if(!$groups) {
765
-			throw new OCSException('Unknown error occurred', 102);
766
-		} else {
767
-			return new DataResponse($groups);
768
-		}
769
-	}
770
-
771
-	/**
772
-	 * @param string $userId
773
-	 * @return array
774
-	 * @throws \OCP\Files\NotFoundException
775
-	 */
776
-	protected function fillStorageInfo($userId) {
777
-		try {
778
-			\OC_Util::tearDownFS();
779
-			\OC_Util::setupFS($userId);
780
-			$storage = OC_Helper::getStorageInfo('/');
781
-			$data = [
782
-				'free' => $storage['free'],
783
-				'used' => $storage['used'],
784
-				'total' => $storage['total'],
785
-				'relative' => $storage['relative'],
786
-				'quota' => $storage['quota'],
787
-			];
788
-		} catch (NotFoundException $ex) {
789
-			$data = [];
790
-		}
791
-		return $data;
792
-	}
793
-
794
-	/**
795
-	 * @NoAdminRequired
796
-	 * @PasswordConfirmationRequired
797
-	 *
798
-	 * resend welcome message
799
-	 *
800
-	 * @param string $userId
801
-	 * @return DataResponse
802
-	 * @throws OCSException
803
-	 */
804
-	public function resendWelcomeMessage($userId) {
805
-		$currentLoggedInUser = $this->userSession->getUser();
806
-
807
-		$targetUser = $this->userManager->get($userId);
808
-		if($targetUser === null) {
809
-			throw new OCSException('', \OCP\API::RESPOND_NOT_FOUND);
810
-		}
811
-
812
-		// Check if admin / subadmin
813
-		$subAdminManager = $this->groupManager->getSubAdmin();
814
-		if(!$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)
815
-			&& !$this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
816
-			// No rights
817
-			throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
818
-		}
819
-
820
-		$email = $targetUser->getEMailAddress();
821
-		if ($email === '' || $email === null) {
822
-			throw new OCSException('Email address not available', 101);
823
-		}
824
-		$username = $targetUser->getUID();
825
-		$lang = $this->config->getUserValue($username, 'core', 'lang', 'en');
826
-		if (!$this->l10nFactory->languageExists('settings', $lang)) {
827
-			$lang = 'en';
828
-		}
829
-
830
-		$l10n = $this->l10nFactory->get('settings', $lang);
831
-
832
-		try {
833
-			$this->newUserMailHelper->setL10N($l10n);
834
-			$emailTemplate = $this->newUserMailHelper->generateTemplate($targetUser, false);
835
-			$this->newUserMailHelper->sendMail($targetUser, $emailTemplate);
836
-		} catch(\Exception $e) {
837
-			$this->logger->error("Can't send new user mail to $email: " . $e->getMessage(), array('app' => 'settings'));
838
-			throw new OCSException('Sending email failed', 102);
839
-		}
840
-
841
-		return new DataResponse();
842
-	}
54
+    /** @var IUserManager */
55
+    private $userManager;
56
+    /** @var IConfig */
57
+    private $config;
58
+    /** @var IAppManager */
59
+    private $appManager;
60
+    /** @var IGroupManager|\OC\Group\Manager */ // FIXME Requires a method that is not on the interface
61
+    private $groupManager;
62
+    /** @var IUserSession */
63
+    private $userSession;
64
+    /** @var AccountManager */
65
+    private $accountManager;
66
+    /** @var ILogger */
67
+    private $logger;
68
+    /** @var IFactory */
69
+    private $l10nFactory;
70
+    /** @var NewUserMailHelper */
71
+    private $newUserMailHelper;
72
+
73
+    /**
74
+     * @param string $appName
75
+     * @param IRequest $request
76
+     * @param IUserManager $userManager
77
+     * @param IConfig $config
78
+     * @param IAppManager $appManager
79
+     * @param IGroupManager $groupManager
80
+     * @param IUserSession $userSession
81
+     * @param AccountManager $accountManager
82
+     * @param ILogger $logger
83
+     * @param IFactory $l10nFactory
84
+     * @param NewUserMailHelper $newUserMailHelper
85
+     */
86
+    public function __construct($appName,
87
+                                IRequest $request,
88
+                                IUserManager $userManager,
89
+                                IConfig $config,
90
+                                IAppManager $appManager,
91
+                                IGroupManager $groupManager,
92
+                                IUserSession $userSession,
93
+                                AccountManager $accountManager,
94
+                                ILogger $logger,
95
+                                IFactory $l10nFactory,
96
+                                NewUserMailHelper $newUserMailHelper) {
97
+        parent::__construct($appName, $request);
98
+
99
+        $this->userManager = $userManager;
100
+        $this->config = $config;
101
+        $this->appManager = $appManager;
102
+        $this->groupManager = $groupManager;
103
+        $this->userSession = $userSession;
104
+        $this->accountManager = $accountManager;
105
+        $this->logger = $logger;
106
+        $this->l10nFactory = $l10nFactory;
107
+        $this->newUserMailHelper = $newUserMailHelper;
108
+    }
109
+
110
+    /**
111
+     * @NoAdminRequired
112
+     *
113
+     * returns a list of users
114
+     *
115
+     * @param string $search
116
+     * @param int $limit
117
+     * @param int $offset
118
+     * @return DataResponse
119
+     */
120
+    public function getUsers($search = '', $limit = null, $offset = null) {
121
+        $user = $this->userSession->getUser();
122
+        $users = [];
123
+
124
+        // Admin? Or SubAdmin?
125
+        $uid = $user->getUID();
126
+        $subAdminManager = $this->groupManager->getSubAdmin();
127
+        if($this->groupManager->isAdmin($uid)){
128
+            $users = $this->userManager->search($search, $limit, $offset);
129
+        } else if ($subAdminManager->isSubAdmin($user)) {
130
+            $subAdminOfGroups = $subAdminManager->getSubAdminsGroups($user);
131
+            foreach ($subAdminOfGroups as $key => $group) {
132
+                $subAdminOfGroups[$key] = $group->getGID();
133
+            }
134
+
135
+            if($offset === null) {
136
+                $offset = 0;
137
+            }
138
+
139
+            $users = [];
140
+            foreach ($subAdminOfGroups as $group) {
141
+                $users = array_merge($users, $this->groupManager->displayNamesInGroup($group, $search));
142
+            }
143
+
144
+            $users = array_slice($users, $offset, $limit);
145
+        }
146
+
147
+        $users = array_keys($users);
148
+
149
+        return new DataResponse([
150
+            'users' => $users
151
+        ]);
152
+    }
153
+
154
+    /**
155
+     * @PasswordConfirmationRequired
156
+     * @NoAdminRequired
157
+     *
158
+     * @param string $userid
159
+     * @param string $password
160
+     * @param array $groups
161
+     * @return DataResponse
162
+     * @throws OCSException
163
+     */
164
+    public function addUser($userid, $password, $groups = null) {
165
+        $user = $this->userSession->getUser();
166
+        $isAdmin = $this->groupManager->isAdmin($user->getUID());
167
+        $subAdminManager = $this->groupManager->getSubAdmin();
168
+
169
+        if($this->userManager->userExists($userid)) {
170
+            $this->logger->error('Failed addUser attempt: User already exists.', ['app' => 'ocs_api']);
171
+            throw new OCSException('User already exists', 102);
172
+        }
173
+
174
+        if(is_array($groups)) {
175
+            foreach ($groups as $group) {
176
+                if(!$this->groupManager->groupExists($group)) {
177
+                    throw new OCSException('group '.$group.' does not exist', 104);
178
+                }
179
+                if(!$isAdmin && !$subAdminManager->isSubAdminofGroup($user, $this->groupManager->get($group))) {
180
+                    throw new OCSException('insufficient privileges for group '. $group, 105);
181
+                }
182
+            }
183
+        } else {
184
+            if(!$isAdmin) {
185
+                throw new OCSException('no group specified (required for subadmins)', 106);
186
+            }
187
+        }
188
+
189
+        try {
190
+            $newUser = $this->userManager->createUser($userid, $password);
191
+            $this->logger->info('Successful addUser call with userid: ' . $userid, ['app' => 'ocs_api']);
192
+
193
+            if (is_array($groups)) {
194
+                foreach ($groups as $group) {
195
+                    $this->groupManager->get($group)->addUser($newUser);
196
+                    $this->logger->info('Added userid ' . $userid . ' to group ' . $group, ['app' => 'ocs_api']);
197
+                }
198
+            }
199
+            return new DataResponse();
200
+        } catch (HintException $e ) {
201
+            $this->logger->logException($e, [
202
+                'message' => 'Failed addUser attempt with hint exception.',
203
+                'level' => \OCP\Util::WARN,
204
+                'app' => 'ocs_api',
205
+            ]);
206
+            throw new OCSException($e->getHint(), 107);
207
+        } catch (\Exception $e) {
208
+            $this->logger->error('Failed addUser attempt with exception: '.$e->getMessage(), ['app' => 'ocs_api']);
209
+            throw new OCSException('Bad request', 101);
210
+        }
211
+    }
212
+
213
+    /**
214
+     * @NoAdminRequired
215
+     * @NoSubAdminRequired
216
+     *
217
+     * gets user info
218
+     *
219
+     * @param string $userId
220
+     * @return DataResponse
221
+     * @throws OCSException
222
+     */
223
+    public function getUser($userId) {
224
+        $data = $this->getUserData($userId);
225
+        return new DataResponse($data);
226
+    }
227
+
228
+    /**
229
+     * @NoAdminRequired
230
+     * @NoSubAdminRequired
231
+     *
232
+     * gets user info from the currently logged in user
233
+     *
234
+     * @return DataResponse
235
+     * @throws OCSException
236
+     */
237
+    public function getCurrentUser() {
238
+        $user = $this->userSession->getUser();
239
+        if ($user) {
240
+            $data =  $this->getUserData($user->getUID());
241
+            // rename "displayname" to "display-name" only for this call to keep
242
+            // the API stable.
243
+            $data['display-name'] = $data['displayname'];
244
+            unset($data['displayname']);
245
+            return new DataResponse($data);
246
+
247
+        }
248
+
249
+        throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
250
+    }
251
+
252
+    /**
253
+     * creates a array with all user data
254
+     *
255
+     * @param $userId
256
+     * @return array
257
+     * @throws OCSException
258
+     */
259
+    protected function getUserData($userId) {
260
+        $currentLoggedInUser = $this->userSession->getUser();
261
+
262
+        $data = [];
263
+
264
+        // Check if the target user exists
265
+        $targetUserObject = $this->userManager->get($userId);
266
+        if($targetUserObject === null) {
267
+            throw new OCSException('The requested user could not be found', \OCP\API::RESPOND_NOT_FOUND);
268
+        }
269
+
270
+        // Admin? Or SubAdmin?
271
+        if($this->groupManager->isAdmin($currentLoggedInUser->getUID())
272
+            || $this->groupManager->getSubAdmin()->isUserAccessible($currentLoggedInUser, $targetUserObject)) {
273
+            $data['enabled'] = $this->config->getUserValue($targetUserObject->getUID(), 'core', 'enabled', 'true');
274
+        } else {
275
+            // Check they are looking up themselves
276
+            if($currentLoggedInUser->getUID() !== $targetUserObject->getUID()) {
277
+                throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
278
+            }
279
+        }
280
+
281
+        $userAccount = $this->accountManager->getUser($targetUserObject);
282
+        $groups = $this->groupManager->getUserGroups($targetUserObject);
283
+        $gids = [];
284
+        foreach ($groups as $group) {
285
+            $gids[] = $group->getDisplayName();
286
+        }
287
+
288
+        // Find the data
289
+        $data['id'] = $targetUserObject->getUID();
290
+        $data['quota'] = $this->fillStorageInfo($targetUserObject->getUID());
291
+        $data[AccountManager::PROPERTY_EMAIL] = $targetUserObject->getEMailAddress();
292
+        $data[AccountManager::PROPERTY_DISPLAYNAME] = $targetUserObject->getDisplayName();
293
+        $data[AccountManager::PROPERTY_PHONE] = $userAccount[AccountManager::PROPERTY_PHONE]['value'];
294
+        $data[AccountManager::PROPERTY_ADDRESS] = $userAccount[AccountManager::PROPERTY_ADDRESS]['value'];
295
+        $data[AccountManager::PROPERTY_WEBSITE] = $userAccount[AccountManager::PROPERTY_WEBSITE]['value'];
296
+        $data[AccountManager::PROPERTY_TWITTER] = $userAccount[AccountManager::PROPERTY_TWITTER]['value'];
297
+        $data['groups'] = $gids;
298
+        $data['language'] = $this->config->getUserValue($targetUserObject->getUID(), 'core', 'lang');
299
+
300
+        return $data;
301
+    }
302
+
303
+    /**
304
+     * @NoAdminRequired
305
+     * @NoSubAdminRequired
306
+     * @PasswordConfirmationRequired
307
+     *
308
+     * edit users
309
+     *
310
+     * @param string $userId
311
+     * @param string $key
312
+     * @param string $value
313
+     * @return DataResponse
314
+     * @throws OCSException
315
+     * @throws OCSForbiddenException
316
+     */
317
+    public function editUser($userId, $key, $value) {
318
+        $currentLoggedInUser = $this->userSession->getUser();
319
+
320
+        $targetUser = $this->userManager->get($userId);
321
+        if($targetUser === null) {
322
+            throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
323
+        }
324
+
325
+        $permittedFields = [];
326
+        if($targetUser->getUID() === $currentLoggedInUser->getUID()) {
327
+            // Editing self (display, email)
328
+            if ($this->config->getSystemValue('allow_user_to_change_display_name', true) !== false) {
329
+                $permittedFields[] = 'display';
330
+                $permittedFields[] = AccountManager::PROPERTY_DISPLAYNAME;
331
+                $permittedFields[] = AccountManager::PROPERTY_EMAIL;
332
+            }
333
+
334
+            $permittedFields[] = 'password';
335
+            if ($this->config->getSystemValue('force_language', false) === false ||
336
+                $this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
337
+                $permittedFields[] = 'language';
338
+            }
339
+
340
+            if ($this->appManager->isEnabledForUser('federatedfilesharing')) {
341
+                $federatedFileSharing = new \OCA\FederatedFileSharing\AppInfo\Application();
342
+                $shareProvider = $federatedFileSharing->getFederatedShareProvider();
343
+                if ($shareProvider->isLookupServerUploadEnabled()) {
344
+                    $permittedFields[] = AccountManager::PROPERTY_PHONE;
345
+                    $permittedFields[] = AccountManager::PROPERTY_ADDRESS;
346
+                    $permittedFields[] = AccountManager::PROPERTY_WEBSITE;
347
+                    $permittedFields[] = AccountManager::PROPERTY_TWITTER;
348
+                }
349
+            }
350
+
351
+            // If admin they can edit their own quota
352
+            if($this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
353
+                $permittedFields[] = 'quota';
354
+            }
355
+        } else {
356
+            // Check if admin / subadmin
357
+            $subAdminManager = $this->groupManager->getSubAdmin();
358
+            if($subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)
359
+            || $this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
360
+                // They have permissions over the user
361
+                $permittedFields[] = 'display';
362
+                $permittedFields[] = AccountManager::PROPERTY_DISPLAYNAME;
363
+                $permittedFields[] = AccountManager::PROPERTY_EMAIL;
364
+                $permittedFields[] = 'password';
365
+                $permittedFields[] = 'language';
366
+                $permittedFields[] = AccountManager::PROPERTY_PHONE;
367
+                $permittedFields[] = AccountManager::PROPERTY_ADDRESS;
368
+                $permittedFields[] = AccountManager::PROPERTY_WEBSITE;
369
+                $permittedFields[] = AccountManager::PROPERTY_TWITTER;
370
+                $permittedFields[] = 'quota';
371
+            } else {
372
+                // No rights
373
+                throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
374
+            }
375
+        }
376
+        // Check if permitted to edit this field
377
+        if(!in_array($key, $permittedFields)) {
378
+            throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
379
+        }
380
+        // Process the edit
381
+        switch($key) {
382
+            case 'display':
383
+            case AccountManager::PROPERTY_DISPLAYNAME:
384
+                $targetUser->setDisplayName($value);
385
+                break;
386
+            case 'quota':
387
+                $quota = $value;
388
+                if($quota !== 'none' && $quota !== 'default') {
389
+                    if (is_numeric($quota)) {
390
+                        $quota = (float) $quota;
391
+                    } else {
392
+                        $quota = \OCP\Util::computerFileSize($quota);
393
+                    }
394
+                    if ($quota === false) {
395
+                        throw new OCSException('Invalid quota value '.$value, 103);
396
+                    }
397
+                    if($quota === 0) {
398
+                        $quota = 'default';
399
+                    }else if($quota === -1) {
400
+                        $quota = 'none';
401
+                    } else {
402
+                        $quota = \OCP\Util::humanFileSize($quota);
403
+                    }
404
+                }
405
+                $targetUser->setQuota($quota);
406
+                break;
407
+            case 'password':
408
+                $targetUser->setPassword($value);
409
+                break;
410
+            case 'language':
411
+                $languagesCodes = $this->l10nFactory->findAvailableLanguages();
412
+                if (!in_array($value, $languagesCodes, true) && $value !== 'en') {
413
+                    throw new OCSException('Invalid language', 102);
414
+                }
415
+                $this->config->setUserValue($targetUser->getUID(), 'core', 'lang', $value);
416
+                break;
417
+            case AccountManager::PROPERTY_EMAIL:
418
+                if(filter_var($value, FILTER_VALIDATE_EMAIL)) {
419
+                    $targetUser->setEMailAddress($value);
420
+                } else {
421
+                    throw new OCSException('', 102);
422
+                }
423
+                break;
424
+            case AccountManager::PROPERTY_PHONE:
425
+            case AccountManager::PROPERTY_ADDRESS:
426
+            case AccountManager::PROPERTY_WEBSITE:
427
+            case AccountManager::PROPERTY_TWITTER:
428
+                $userAccount = $this->accountManager->getUser($targetUser);
429
+                if ($userAccount[$key]['value'] !== $value) {
430
+                    $userAccount[$key]['value'] = $value;
431
+                    $this->accountManager->updateUser($targetUser, $userAccount);
432
+                }
433
+                break;
434
+            default:
435
+                throw new OCSException('', 103);
436
+        }
437
+        return new DataResponse();
438
+    }
439
+
440
+    /**
441
+     * @PasswordConfirmationRequired
442
+     * @NoAdminRequired
443
+     *
444
+     * @param string $userId
445
+     * @return DataResponse
446
+     * @throws OCSException
447
+     * @throws OCSForbiddenException
448
+     */
449
+    public function deleteUser($userId) {
450
+        $currentLoggedInUser = $this->userSession->getUser();
451
+
452
+        $targetUser = $this->userManager->get($userId);
453
+
454
+        if($targetUser === null || $targetUser->getUID() === $currentLoggedInUser->getUID()) {
455
+            throw new OCSException('', 101);
456
+        }
457
+
458
+        // If not permitted
459
+        $subAdminManager = $this->groupManager->getSubAdmin();
460
+        if(!$this->groupManager->isAdmin($currentLoggedInUser->getUID()) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) {
461
+            throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
462
+        }
463
+
464
+        // Go ahead with the delete
465
+        if($targetUser->delete()) {
466
+            return new DataResponse();
467
+        } else {
468
+            throw new OCSException('', 101);
469
+        }
470
+    }
471
+
472
+    /**
473
+     * @PasswordConfirmationRequired
474
+     * @NoAdminRequired
475
+     *
476
+     * @param string $userId
477
+     * @return DataResponse
478
+     * @throws OCSException
479
+     * @throws OCSForbiddenException
480
+     */
481
+    public function disableUser($userId) {
482
+        return $this->setEnabled($userId, false);
483
+    }
484
+
485
+    /**
486
+     * @PasswordConfirmationRequired
487
+     * @NoAdminRequired
488
+     *
489
+     * @param string $userId
490
+     * @return DataResponse
491
+     * @throws OCSException
492
+     * @throws OCSForbiddenException
493
+     */
494
+    public function enableUser($userId) {
495
+        return $this->setEnabled($userId, true);
496
+    }
497
+
498
+    /**
499
+     * @param string $userId
500
+     * @param bool $value
501
+     * @return DataResponse
502
+     * @throws OCSException
503
+     * @throws OCSForbiddenException
504
+     */
505
+    private function setEnabled($userId, $value) {
506
+        $currentLoggedInUser = $this->userSession->getUser();
507
+
508
+        $targetUser = $this->userManager->get($userId);
509
+        if($targetUser === null || $targetUser->getUID() === $currentLoggedInUser->getUID()) {
510
+            throw new OCSException('', 101);
511
+        }
512
+
513
+        // If not permitted
514
+        $subAdminManager = $this->groupManager->getSubAdmin();
515
+        if(!$this->groupManager->isAdmin($currentLoggedInUser->getUID()) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) {
516
+            throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
517
+        }
518
+
519
+        // enable/disable the user now
520
+        $targetUser->setEnabled($value);
521
+        return new DataResponse();
522
+    }
523
+
524
+    /**
525
+     * @NoAdminRequired
526
+     * @NoSubAdminRequired
527
+     *
528
+     * @param string $userId
529
+     * @return DataResponse
530
+     * @throws OCSException
531
+     */
532
+    public function getUsersGroups($userId) {
533
+        $loggedInUser = $this->userSession->getUser();
534
+
535
+        $targetUser = $this->userManager->get($userId);
536
+        if($targetUser === null) {
537
+            throw new OCSException('', \OCP\API::RESPOND_NOT_FOUND);
538
+        }
539
+
540
+        if($targetUser->getUID() === $loggedInUser->getUID() || $this->groupManager->isAdmin($loggedInUser->getUID())) {
541
+            // Self lookup or admin lookup
542
+            return new DataResponse([
543
+                'groups' => $this->groupManager->getUserGroupIds($targetUser)
544
+            ]);
545
+        } else {
546
+            $subAdminManager = $this->groupManager->getSubAdmin();
547
+
548
+            // Looking up someone else
549
+            if($subAdminManager->isUserAccessible($loggedInUser, $targetUser)) {
550
+                // Return the group that the method caller is subadmin of for the user in question
551
+                /** @var IGroup[] $getSubAdminsGroups */
552
+                $getSubAdminsGroups = $subAdminManager->getSubAdminsGroups($loggedInUser);
553
+                foreach ($getSubAdminsGroups as $key => $group) {
554
+                    $getSubAdminsGroups[$key] = $group->getGID();
555
+                }
556
+                $groups = array_intersect(
557
+                    $getSubAdminsGroups,
558
+                    $this->groupManager->getUserGroupIds($targetUser)
559
+                );
560
+                return new DataResponse(['groups' => $groups]);
561
+            } else {
562
+                // Not permitted
563
+                throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
564
+            }
565
+        }
566
+
567
+    }
568
+
569
+    /**
570
+     * @PasswordConfirmationRequired
571
+     * @NoAdminRequired
572
+     *
573
+     * @param string $userId
574
+     * @param string $groupid
575
+     * @return DataResponse
576
+     * @throws OCSException
577
+     */
578
+    public function addToGroup($userId, $groupid = '') {
579
+        if($groupid === '') {
580
+            throw new OCSException('', 101);
581
+        }
582
+
583
+        $group = $this->groupManager->get($groupid);
584
+        $targetUser = $this->userManager->get($userId);
585
+        if($group === null) {
586
+            throw new OCSException('', 102);
587
+        }
588
+        if($targetUser === null) {
589
+            throw new OCSException('', 103);
590
+        }
591
+
592
+        // If they're not an admin, check they are a subadmin of the group in question
593
+        $loggedInUser = $this->userSession->getUser();
594
+        $subAdminManager = $this->groupManager->getSubAdmin();
595
+        if (!$this->groupManager->isAdmin($loggedInUser->getUID()) && !$subAdminManager->isSubAdminOfGroup($loggedInUser, $group)) {
596
+            throw new OCSException('', 104);
597
+        }
598
+
599
+        // Add user to group
600
+        $group->addUser($targetUser);
601
+        return new DataResponse();
602
+    }
603
+
604
+    /**
605
+     * @PasswordConfirmationRequired
606
+     * @NoAdminRequired
607
+     *
608
+     * @param string $userId
609
+     * @param string $groupid
610
+     * @return DataResponse
611
+     * @throws OCSException
612
+     */
613
+    public function removeFromGroup($userId, $groupid) {
614
+        $loggedInUser = $this->userSession->getUser();
615
+
616
+        if($groupid === null || trim($groupid) === '') {
617
+            throw new OCSException('', 101);
618
+        }
619
+
620
+        $group = $this->groupManager->get($groupid);
621
+        if($group === null) {
622
+            throw new OCSException('', 102);
623
+        }
624
+
625
+        $targetUser = $this->userManager->get($userId);
626
+        if($targetUser === null) {
627
+            throw new OCSException('', 103);
628
+        }
629
+
630
+        // If they're not an admin, check they are a subadmin of the group in question
631
+        $subAdminManager = $this->groupManager->getSubAdmin();
632
+        if (!$this->groupManager->isAdmin($loggedInUser->getUID()) && !$subAdminManager->isSubAdminOfGroup($loggedInUser, $group)) {
633
+            throw new OCSException('', 104);
634
+        }
635
+
636
+        // Check they aren't removing themselves from 'admin' or their 'subadmin; group
637
+        if ($targetUser->getUID() === $loggedInUser->getUID()) {
638
+            if ($this->groupManager->isAdmin($loggedInUser->getUID())) {
639
+                if ($group->getGID() === 'admin') {
640
+                    throw new OCSException('Cannot remove yourself from the admin group', 105);
641
+                }
642
+            } else {
643
+                // Not an admin, so the user must be a subadmin of this group, but that is not allowed.
644
+                throw new OCSException('Cannot remove yourself from this group as you are a SubAdmin', 105);
645
+            }
646
+
647
+        } else if (!$this->groupManager->isAdmin($loggedInUser->getUID())) {
648
+            /** @var IGroup[] $subAdminGroups */
649
+            $subAdminGroups = $subAdminManager->getSubAdminsGroups($loggedInUser);
650
+            $subAdminGroups = array_map(function (IGroup $subAdminGroup) {
651
+                return $subAdminGroup->getGID();
652
+            }, $subAdminGroups);
653
+            $userGroups = $this->groupManager->getUserGroupIds($targetUser);
654
+            $userSubAdminGroups = array_intersect($subAdminGroups, $userGroups);
655
+
656
+            if (count($userSubAdminGroups) <= 1) {
657
+                // Subadmin must not be able to remove a user from all their subadmin groups.
658
+                throw new OCSException('Cannot remove user from this group as this is the only remaining group you are a SubAdmin of', 105);
659
+            }
660
+        }
661
+
662
+        // Remove user from group
663
+        $group->removeUser($targetUser);
664
+        return new DataResponse();
665
+    }
666
+
667
+    /**
668
+     * Creates a subadmin
669
+     *
670
+     * @PasswordConfirmationRequired
671
+     *
672
+     * @param string $userId
673
+     * @param string $groupid
674
+     * @return DataResponse
675
+     * @throws OCSException
676
+     */
677
+    public function addSubAdmin($userId, $groupid) {
678
+        $group = $this->groupManager->get($groupid);
679
+        $user = $this->userManager->get($userId);
680
+
681
+        // Check if the user exists
682
+        if($user === null) {
683
+            throw new OCSException('User does not exist', 101);
684
+        }
685
+        // Check if group exists
686
+        if($group === null) {
687
+            throw new OCSException('Group does not exist',  102);
688
+        }
689
+        // Check if trying to make subadmin of admin group
690
+        if($group->getGID() === 'admin') {
691
+            throw new OCSException('Cannot create subadmins for admin group', 103);
692
+        }
693
+
694
+        $subAdminManager = $this->groupManager->getSubAdmin();
695
+
696
+        // We cannot be subadmin twice
697
+        if ($subAdminManager->isSubAdminofGroup($user, $group)) {
698
+            return new DataResponse();
699
+        }
700
+        // Go
701
+        if($subAdminManager->createSubAdmin($user, $group)) {
702
+            return new DataResponse();
703
+        } else {
704
+            throw new OCSException('Unknown error occurred', 103);
705
+        }
706
+    }
707
+
708
+    /**
709
+     * Removes a subadmin from a group
710
+     *
711
+     * @PasswordConfirmationRequired
712
+     *
713
+     * @param string $userId
714
+     * @param string $groupid
715
+     * @return DataResponse
716
+     * @throws OCSException
717
+     */
718
+    public function removeSubAdmin($userId, $groupid) {
719
+        $group = $this->groupManager->get($groupid);
720
+        $user = $this->userManager->get($userId);
721
+        $subAdminManager = $this->groupManager->getSubAdmin();
722
+
723
+        // Check if the user exists
724
+        if($user === null) {
725
+            throw new OCSException('User does not exist', 101);
726
+        }
727
+        // Check if the group exists
728
+        if($group === null) {
729
+            throw new OCSException('Group does not exist', 101);
730
+        }
731
+        // Check if they are a subadmin of this said group
732
+        if(!$subAdminManager->isSubAdminOfGroup($user, $group)) {
733
+            throw new OCSException('User is not a subadmin of this group', 102);
734
+        }
735
+
736
+        // Go
737
+        if($subAdminManager->deleteSubAdmin($user, $group)) {
738
+            return new DataResponse();
739
+        } else {
740
+            throw new OCSException('Unknown error occurred', 103);
741
+        }
742
+    }
743
+
744
+    /**
745
+     * Get the groups a user is a subadmin of
746
+     *
747
+     * @param string $userId
748
+     * @return DataResponse
749
+     * @throws OCSException
750
+     */
751
+    public function getUserSubAdminGroups($userId) {
752
+        $user = $this->userManager->get($userId);
753
+        // Check if the user exists
754
+        if($user === null) {
755
+            throw new OCSException('User does not exist', 101);
756
+        }
757
+
758
+        // Get the subadmin groups
759
+        $groups = $this->groupManager->getSubAdmin()->getSubAdminsGroups($user);
760
+        foreach ($groups as $key => $group) {
761
+            $groups[$key] = $group->getGID();
762
+        }
763
+
764
+        if(!$groups) {
765
+            throw new OCSException('Unknown error occurred', 102);
766
+        } else {
767
+            return new DataResponse($groups);
768
+        }
769
+    }
770
+
771
+    /**
772
+     * @param string $userId
773
+     * @return array
774
+     * @throws \OCP\Files\NotFoundException
775
+     */
776
+    protected function fillStorageInfo($userId) {
777
+        try {
778
+            \OC_Util::tearDownFS();
779
+            \OC_Util::setupFS($userId);
780
+            $storage = OC_Helper::getStorageInfo('/');
781
+            $data = [
782
+                'free' => $storage['free'],
783
+                'used' => $storage['used'],
784
+                'total' => $storage['total'],
785
+                'relative' => $storage['relative'],
786
+                'quota' => $storage['quota'],
787
+            ];
788
+        } catch (NotFoundException $ex) {
789
+            $data = [];
790
+        }
791
+        return $data;
792
+    }
793
+
794
+    /**
795
+     * @NoAdminRequired
796
+     * @PasswordConfirmationRequired
797
+     *
798
+     * resend welcome message
799
+     *
800
+     * @param string $userId
801
+     * @return DataResponse
802
+     * @throws OCSException
803
+     */
804
+    public function resendWelcomeMessage($userId) {
805
+        $currentLoggedInUser = $this->userSession->getUser();
806
+
807
+        $targetUser = $this->userManager->get($userId);
808
+        if($targetUser === null) {
809
+            throw new OCSException('', \OCP\API::RESPOND_NOT_FOUND);
810
+        }
811
+
812
+        // Check if admin / subadmin
813
+        $subAdminManager = $this->groupManager->getSubAdmin();
814
+        if(!$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)
815
+            && !$this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
816
+            // No rights
817
+            throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
818
+        }
819
+
820
+        $email = $targetUser->getEMailAddress();
821
+        if ($email === '' || $email === null) {
822
+            throw new OCSException('Email address not available', 101);
823
+        }
824
+        $username = $targetUser->getUID();
825
+        $lang = $this->config->getUserValue($username, 'core', 'lang', 'en');
826
+        if (!$this->l10nFactory->languageExists('settings', $lang)) {
827
+            $lang = 'en';
828
+        }
829
+
830
+        $l10n = $this->l10nFactory->get('settings', $lang);
831
+
832
+        try {
833
+            $this->newUserMailHelper->setL10N($l10n);
834
+            $emailTemplate = $this->newUserMailHelper->generateTemplate($targetUser, false);
835
+            $this->newUserMailHelper->sendMail($targetUser, $emailTemplate);
836
+        } catch(\Exception $e) {
837
+            $this->logger->error("Can't send new user mail to $email: " . $e->getMessage(), array('app' => 'settings'));
838
+            throw new OCSException('Sending email failed', 102);
839
+        }
840
+
841
+        return new DataResponse();
842
+    }
843 843
 }
Please login to merge, or discard this patch.
Spacing   +55 added lines, -55 removed lines patch added patch discarded remove patch
@@ -124,7 +124,7 @@  discard block
 block discarded – undo
124 124
 		// Admin? Or SubAdmin?
125 125
 		$uid = $user->getUID();
126 126
 		$subAdminManager = $this->groupManager->getSubAdmin();
127
-		if($this->groupManager->isAdmin($uid)){
127
+		if ($this->groupManager->isAdmin($uid)) {
128 128
 			$users = $this->userManager->search($search, $limit, $offset);
129 129
 		} else if ($subAdminManager->isSubAdmin($user)) {
130 130
 			$subAdminOfGroups = $subAdminManager->getSubAdminsGroups($user);
@@ -132,7 +132,7 @@  discard block
 block discarded – undo
132 132
 				$subAdminOfGroups[$key] = $group->getGID();
133 133
 			}
134 134
 
135
-			if($offset === null) {
135
+			if ($offset === null) {
136 136
 				$offset = 0;
137 137
 			}
138 138
 
@@ -166,38 +166,38 @@  discard block
 block discarded – undo
166 166
 		$isAdmin = $this->groupManager->isAdmin($user->getUID());
167 167
 		$subAdminManager = $this->groupManager->getSubAdmin();
168 168
 
169
-		if($this->userManager->userExists($userid)) {
169
+		if ($this->userManager->userExists($userid)) {
170 170
 			$this->logger->error('Failed addUser attempt: User already exists.', ['app' => 'ocs_api']);
171 171
 			throw new OCSException('User already exists', 102);
172 172
 		}
173 173
 
174
-		if(is_array($groups)) {
174
+		if (is_array($groups)) {
175 175
 			foreach ($groups as $group) {
176
-				if(!$this->groupManager->groupExists($group)) {
176
+				if (!$this->groupManager->groupExists($group)) {
177 177
 					throw new OCSException('group '.$group.' does not exist', 104);
178 178
 				}
179
-				if(!$isAdmin && !$subAdminManager->isSubAdminofGroup($user, $this->groupManager->get($group))) {
180
-					throw new OCSException('insufficient privileges for group '. $group, 105);
179
+				if (!$isAdmin && !$subAdminManager->isSubAdminofGroup($user, $this->groupManager->get($group))) {
180
+					throw new OCSException('insufficient privileges for group '.$group, 105);
181 181
 				}
182 182
 			}
183 183
 		} else {
184
-			if(!$isAdmin) {
184
+			if (!$isAdmin) {
185 185
 				throw new OCSException('no group specified (required for subadmins)', 106);
186 186
 			}
187 187
 		}
188 188
 
189 189
 		try {
190 190
 			$newUser = $this->userManager->createUser($userid, $password);
191
-			$this->logger->info('Successful addUser call with userid: ' . $userid, ['app' => 'ocs_api']);
191
+			$this->logger->info('Successful addUser call with userid: '.$userid, ['app' => 'ocs_api']);
192 192
 
193 193
 			if (is_array($groups)) {
194 194
 				foreach ($groups as $group) {
195 195
 					$this->groupManager->get($group)->addUser($newUser);
196
-					$this->logger->info('Added userid ' . $userid . ' to group ' . $group, ['app' => 'ocs_api']);
196
+					$this->logger->info('Added userid '.$userid.' to group '.$group, ['app' => 'ocs_api']);
197 197
 				}
198 198
 			}
199 199
 			return new DataResponse();
200
-		} catch (HintException $e ) {
200
+		} catch (HintException $e) {
201 201
 			$this->logger->logException($e, [
202 202
 				'message' => 'Failed addUser attempt with hint exception.',
203 203
 				'level' => \OCP\Util::WARN,
@@ -237,7 +237,7 @@  discard block
 block discarded – undo
237 237
 	public function getCurrentUser() {
238 238
 		$user = $this->userSession->getUser();
239 239
 		if ($user) {
240
-			$data =  $this->getUserData($user->getUID());
240
+			$data = $this->getUserData($user->getUID());
241 241
 			// rename "displayname" to "display-name" only for this call to keep
242 242
 			// the API stable.
243 243
 			$data['display-name'] = $data['displayname'];
@@ -263,17 +263,17 @@  discard block
 block discarded – undo
263 263
 
264 264
 		// Check if the target user exists
265 265
 		$targetUserObject = $this->userManager->get($userId);
266
-		if($targetUserObject === null) {
266
+		if ($targetUserObject === null) {
267 267
 			throw new OCSException('The requested user could not be found', \OCP\API::RESPOND_NOT_FOUND);
268 268
 		}
269 269
 
270 270
 		// Admin? Or SubAdmin?
271
-		if($this->groupManager->isAdmin($currentLoggedInUser->getUID())
271
+		if ($this->groupManager->isAdmin($currentLoggedInUser->getUID())
272 272
 			|| $this->groupManager->getSubAdmin()->isUserAccessible($currentLoggedInUser, $targetUserObject)) {
273 273
 			$data['enabled'] = $this->config->getUserValue($targetUserObject->getUID(), 'core', 'enabled', 'true');
274 274
 		} else {
275 275
 			// Check they are looking up themselves
276
-			if($currentLoggedInUser->getUID() !== $targetUserObject->getUID()) {
276
+			if ($currentLoggedInUser->getUID() !== $targetUserObject->getUID()) {
277 277
 				throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
278 278
 			}
279 279
 		}
@@ -318,12 +318,12 @@  discard block
 block discarded – undo
318 318
 		$currentLoggedInUser = $this->userSession->getUser();
319 319
 
320 320
 		$targetUser = $this->userManager->get($userId);
321
-		if($targetUser === null) {
321
+		if ($targetUser === null) {
322 322
 			throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
323 323
 		}
324 324
 
325 325
 		$permittedFields = [];
326
-		if($targetUser->getUID() === $currentLoggedInUser->getUID()) {
326
+		if ($targetUser->getUID() === $currentLoggedInUser->getUID()) {
327 327
 			// Editing self (display, email)
328 328
 			if ($this->config->getSystemValue('allow_user_to_change_display_name', true) !== false) {
329 329
 				$permittedFields[] = 'display';
@@ -349,13 +349,13 @@  discard block
 block discarded – undo
349 349
 			}
350 350
 
351 351
 			// If admin they can edit their own quota
352
-			if($this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
352
+			if ($this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
353 353
 				$permittedFields[] = 'quota';
354 354
 			}
355 355
 		} else {
356 356
 			// Check if admin / subadmin
357 357
 			$subAdminManager = $this->groupManager->getSubAdmin();
358
-			if($subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)
358
+			if ($subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)
359 359
 			|| $this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
360 360
 				// They have permissions over the user
361 361
 				$permittedFields[] = 'display';
@@ -374,18 +374,18 @@  discard block
 block discarded – undo
374 374
 			}
375 375
 		}
376 376
 		// Check if permitted to edit this field
377
-		if(!in_array($key, $permittedFields)) {
377
+		if (!in_array($key, $permittedFields)) {
378 378
 			throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
379 379
 		}
380 380
 		// Process the edit
381
-		switch($key) {
381
+		switch ($key) {
382 382
 			case 'display':
383 383
 			case AccountManager::PROPERTY_DISPLAYNAME:
384 384
 				$targetUser->setDisplayName($value);
385 385
 				break;
386 386
 			case 'quota':
387 387
 				$quota = $value;
388
-				if($quota !== 'none' && $quota !== 'default') {
388
+				if ($quota !== 'none' && $quota !== 'default') {
389 389
 					if (is_numeric($quota)) {
390 390
 						$quota = (float) $quota;
391 391
 					} else {
@@ -394,9 +394,9 @@  discard block
 block discarded – undo
394 394
 					if ($quota === false) {
395 395
 						throw new OCSException('Invalid quota value '.$value, 103);
396 396
 					}
397
-					if($quota === 0) {
397
+					if ($quota === 0) {
398 398
 						$quota = 'default';
399
-					}else if($quota === -1) {
399
+					} else if ($quota === -1) {
400 400
 						$quota = 'none';
401 401
 					} else {
402 402
 						$quota = \OCP\Util::humanFileSize($quota);
@@ -415,7 +415,7 @@  discard block
 block discarded – undo
415 415
 				$this->config->setUserValue($targetUser->getUID(), 'core', 'lang', $value);
416 416
 				break;
417 417
 			case AccountManager::PROPERTY_EMAIL:
418
-				if(filter_var($value, FILTER_VALIDATE_EMAIL)) {
418
+				if (filter_var($value, FILTER_VALIDATE_EMAIL)) {
419 419
 					$targetUser->setEMailAddress($value);
420 420
 				} else {
421 421
 					throw new OCSException('', 102);
@@ -451,18 +451,18 @@  discard block
 block discarded – undo
451 451
 
452 452
 		$targetUser = $this->userManager->get($userId);
453 453
 
454
-		if($targetUser === null || $targetUser->getUID() === $currentLoggedInUser->getUID()) {
454
+		if ($targetUser === null || $targetUser->getUID() === $currentLoggedInUser->getUID()) {
455 455
 			throw new OCSException('', 101);
456 456
 		}
457 457
 
458 458
 		// If not permitted
459 459
 		$subAdminManager = $this->groupManager->getSubAdmin();
460
-		if(!$this->groupManager->isAdmin($currentLoggedInUser->getUID()) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) {
460
+		if (!$this->groupManager->isAdmin($currentLoggedInUser->getUID()) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) {
461 461
 			throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
462 462
 		}
463 463
 
464 464
 		// Go ahead with the delete
465
-		if($targetUser->delete()) {
465
+		if ($targetUser->delete()) {
466 466
 			return new DataResponse();
467 467
 		} else {
468 468
 			throw new OCSException('', 101);
@@ -506,13 +506,13 @@  discard block
 block discarded – undo
506 506
 		$currentLoggedInUser = $this->userSession->getUser();
507 507
 
508 508
 		$targetUser = $this->userManager->get($userId);
509
-		if($targetUser === null || $targetUser->getUID() === $currentLoggedInUser->getUID()) {
509
+		if ($targetUser === null || $targetUser->getUID() === $currentLoggedInUser->getUID()) {
510 510
 			throw new OCSException('', 101);
511 511
 		}
512 512
 
513 513
 		// If not permitted
514 514
 		$subAdminManager = $this->groupManager->getSubAdmin();
515
-		if(!$this->groupManager->isAdmin($currentLoggedInUser->getUID()) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) {
515
+		if (!$this->groupManager->isAdmin($currentLoggedInUser->getUID()) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) {
516 516
 			throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
517 517
 		}
518 518
 
@@ -533,11 +533,11 @@  discard block
 block discarded – undo
533 533
 		$loggedInUser = $this->userSession->getUser();
534 534
 
535 535
 		$targetUser = $this->userManager->get($userId);
536
-		if($targetUser === null) {
536
+		if ($targetUser === null) {
537 537
 			throw new OCSException('', \OCP\API::RESPOND_NOT_FOUND);
538 538
 		}
539 539
 
540
-		if($targetUser->getUID() === $loggedInUser->getUID() || $this->groupManager->isAdmin($loggedInUser->getUID())) {
540
+		if ($targetUser->getUID() === $loggedInUser->getUID() || $this->groupManager->isAdmin($loggedInUser->getUID())) {
541 541
 			// Self lookup or admin lookup
542 542
 			return new DataResponse([
543 543
 				'groups' => $this->groupManager->getUserGroupIds($targetUser)
@@ -546,7 +546,7 @@  discard block
 block discarded – undo
546 546
 			$subAdminManager = $this->groupManager->getSubAdmin();
547 547
 
548 548
 			// Looking up someone else
549
-			if($subAdminManager->isUserAccessible($loggedInUser, $targetUser)) {
549
+			if ($subAdminManager->isUserAccessible($loggedInUser, $targetUser)) {
550 550
 				// Return the group that the method caller is subadmin of for the user in question
551 551
 				/** @var IGroup[] $getSubAdminsGroups */
552 552
 				$getSubAdminsGroups = $subAdminManager->getSubAdminsGroups($loggedInUser);
@@ -576,16 +576,16 @@  discard block
 block discarded – undo
576 576
 	 * @throws OCSException
577 577
 	 */
578 578
 	public function addToGroup($userId, $groupid = '') {
579
-		if($groupid === '') {
579
+		if ($groupid === '') {
580 580
 			throw new OCSException('', 101);
581 581
 		}
582 582
 
583 583
 		$group = $this->groupManager->get($groupid);
584 584
 		$targetUser = $this->userManager->get($userId);
585
-		if($group === null) {
585
+		if ($group === null) {
586 586
 			throw new OCSException('', 102);
587 587
 		}
588
-		if($targetUser === null) {
588
+		if ($targetUser === null) {
589 589
 			throw new OCSException('', 103);
590 590
 		}
591 591
 
@@ -613,17 +613,17 @@  discard block
 block discarded – undo
613 613
 	public function removeFromGroup($userId, $groupid) {
614 614
 		$loggedInUser = $this->userSession->getUser();
615 615
 
616
-		if($groupid === null || trim($groupid) === '') {
616
+		if ($groupid === null || trim($groupid) === '') {
617 617
 			throw new OCSException('', 101);
618 618
 		}
619 619
 
620 620
 		$group = $this->groupManager->get($groupid);
621
-		if($group === null) {
621
+		if ($group === null) {
622 622
 			throw new OCSException('', 102);
623 623
 		}
624 624
 
625 625
 		$targetUser = $this->userManager->get($userId);
626
-		if($targetUser === null) {
626
+		if ($targetUser === null) {
627 627
 			throw new OCSException('', 103);
628 628
 		}
629 629
 
@@ -647,7 +647,7 @@  discard block
 block discarded – undo
647 647
 		} else if (!$this->groupManager->isAdmin($loggedInUser->getUID())) {
648 648
 			/** @var IGroup[] $subAdminGroups */
649 649
 			$subAdminGroups = $subAdminManager->getSubAdminsGroups($loggedInUser);
650
-			$subAdminGroups = array_map(function (IGroup $subAdminGroup) {
650
+			$subAdminGroups = array_map(function(IGroup $subAdminGroup) {
651 651
 				return $subAdminGroup->getGID();
652 652
 			}, $subAdminGroups);
653 653
 			$userGroups = $this->groupManager->getUserGroupIds($targetUser);
@@ -679,15 +679,15 @@  discard block
 block discarded – undo
679 679
 		$user = $this->userManager->get($userId);
680 680
 
681 681
 		// Check if the user exists
682
-		if($user === null) {
682
+		if ($user === null) {
683 683
 			throw new OCSException('User does not exist', 101);
684 684
 		}
685 685
 		// Check if group exists
686
-		if($group === null) {
687
-			throw new OCSException('Group does not exist',  102);
686
+		if ($group === null) {
687
+			throw new OCSException('Group does not exist', 102);
688 688
 		}
689 689
 		// Check if trying to make subadmin of admin group
690
-		if($group->getGID() === 'admin') {
690
+		if ($group->getGID() === 'admin') {
691 691
 			throw new OCSException('Cannot create subadmins for admin group', 103);
692 692
 		}
693 693
 
@@ -698,7 +698,7 @@  discard block
 block discarded – undo
698 698
 			return new DataResponse();
699 699
 		}
700 700
 		// Go
701
-		if($subAdminManager->createSubAdmin($user, $group)) {
701
+		if ($subAdminManager->createSubAdmin($user, $group)) {
702 702
 			return new DataResponse();
703 703
 		} else {
704 704
 			throw new OCSException('Unknown error occurred', 103);
@@ -721,20 +721,20 @@  discard block
 block discarded – undo
721 721
 		$subAdminManager = $this->groupManager->getSubAdmin();
722 722
 
723 723
 		// Check if the user exists
724
-		if($user === null) {
724
+		if ($user === null) {
725 725
 			throw new OCSException('User does not exist', 101);
726 726
 		}
727 727
 		// Check if the group exists
728
-		if($group === null) {
728
+		if ($group === null) {
729 729
 			throw new OCSException('Group does not exist', 101);
730 730
 		}
731 731
 		// Check if they are a subadmin of this said group
732
-		if(!$subAdminManager->isSubAdminOfGroup($user, $group)) {
732
+		if (!$subAdminManager->isSubAdminOfGroup($user, $group)) {
733 733
 			throw new OCSException('User is not a subadmin of this group', 102);
734 734
 		}
735 735
 
736 736
 		// Go
737
-		if($subAdminManager->deleteSubAdmin($user, $group)) {
737
+		if ($subAdminManager->deleteSubAdmin($user, $group)) {
738 738
 			return new DataResponse();
739 739
 		} else {
740 740
 			throw new OCSException('Unknown error occurred', 103);
@@ -751,7 +751,7 @@  discard block
 block discarded – undo
751 751
 	public function getUserSubAdminGroups($userId) {
752 752
 		$user = $this->userManager->get($userId);
753 753
 		// Check if the user exists
754
-		if($user === null) {
754
+		if ($user === null) {
755 755
 			throw new OCSException('User does not exist', 101);
756 756
 		}
757 757
 
@@ -761,7 +761,7 @@  discard block
 block discarded – undo
761 761
 			$groups[$key] = $group->getGID();
762 762
 		}
763 763
 
764
-		if(!$groups) {
764
+		if (!$groups) {
765 765
 			throw new OCSException('Unknown error occurred', 102);
766 766
 		} else {
767 767
 			return new DataResponse($groups);
@@ -805,13 +805,13 @@  discard block
 block discarded – undo
805 805
 		$currentLoggedInUser = $this->userSession->getUser();
806 806
 
807 807
 		$targetUser = $this->userManager->get($userId);
808
-		if($targetUser === null) {
808
+		if ($targetUser === null) {
809 809
 			throw new OCSException('', \OCP\API::RESPOND_NOT_FOUND);
810 810
 		}
811 811
 
812 812
 		// Check if admin / subadmin
813 813
 		$subAdminManager = $this->groupManager->getSubAdmin();
814
-		if(!$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)
814
+		if (!$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)
815 815
 			&& !$this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
816 816
 			// No rights
817 817
 			throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
@@ -833,8 +833,8 @@  discard block
 block discarded – undo
833 833
 			$this->newUserMailHelper->setL10N($l10n);
834 834
 			$emailTemplate = $this->newUserMailHelper->generateTemplate($targetUser, false);
835 835
 			$this->newUserMailHelper->sendMail($targetUser, $emailTemplate);
836
-		} catch(\Exception $e) {
837
-			$this->logger->error("Can't send new user mail to $email: " . $e->getMessage(), array('app' => 'settings'));
836
+		} catch (\Exception $e) {
837
+			$this->logger->error("Can't send new user mail to $email: ".$e->getMessage(), array('app' => 'settings'));
838 838
 			throw new OCSException('Sending email failed', 102);
839 839
 		}
840 840
 
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.
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
 
@@ -298,11 +298,11 @@  discard block
 block discarded – undo
298 298
 		$userSession = \OC::$server->getUserSession();
299 299
 		$userPluginManager = \OC::$server->query('LDAPUserPluginManager');
300 300
 
301
-		$userBackend  = new User_Proxy(
301
+		$userBackend = new User_Proxy(
302 302
 			$configPrefixes, $ldapWrapper, $ocConfig, $notificationManager, $userSession, $userPluginManager
303 303
 		);
304
-		$uid = $userBackend->loginName2UserName($param['uid'] );
305
-		if($uid !== false) {
304
+		$uid = $userBackend->loginName2UserName($param['uid']);
305
+		if ($uid !== false) {
306 306
 			$param['uid'] = $uid;
307 307
 		}
308 308
 	}
Please login to merge, or discard this patch.
Indentation   +262 added lines, -262 removed lines patch added patch discarded remove patch
@@ -37,126 +37,126 @@  discard block
 block discarded – undo
37 37
 
38 38
 class Helper {
39 39
 
40
-	/** @var IConfig */
41
-	private $config;
42
-
43
-	/**
44
-	 * Helper constructor.
45
-	 *
46
-	 * @param IConfig $config
47
-	 */
48
-	public function __construct(IConfig $config) {
49
-		$this->config = $config;
50
-	}
51
-
52
-	/**
53
-	 * returns prefixes for each saved LDAP/AD server configuration.
54
-	 * @param bool $activeConfigurations optional, whether only active configuration shall be
55
-	 * retrieved, defaults to false
56
-	 * @return array with a list of the available prefixes
57
-	 *
58
-	 * Configuration prefixes are used to set up configurations for n LDAP or
59
-	 * AD servers. Since configuration is stored in the database, table
60
-	 * appconfig under appid user_ldap, the common identifiers in column
61
-	 * 'configkey' have a prefix. The prefix for the very first server
62
-	 * configuration is empty.
63
-	 * Configkey Examples:
64
-	 * Server 1: ldap_login_filter
65
-	 * Server 2: s1_ldap_login_filter
66
-	 * Server 3: s2_ldap_login_filter
67
-	 *
68
-	 * The prefix needs to be passed to the constructor of Connection class,
69
-	 * except the default (first) server shall be connected to.
70
-	 *
71
-	 */
72
-	public function getServerConfigurationPrefixes($activeConfigurations = false) {
73
-		$referenceConfigkey = 'ldap_configuration_active';
74
-
75
-		$keys = $this->getServersConfig($referenceConfigkey);
76
-
77
-		$prefixes = [];
78
-		foreach ($keys as $key) {
79
-			if ($activeConfigurations && $this->config->getAppValue('user_ldap', $key, '0') !== '1') {
80
-				continue;
81
-			}
82
-
83
-			$len = strlen($key) - strlen($referenceConfigkey);
84
-			$prefixes[] = substr($key, 0, $len);
85
-		}
86
-
87
-		return $prefixes;
88
-	}
89
-
90
-	/**
91
-	 *
92
-	 * determines the host for every configured connection
93
-	 * @return array an array with configprefix as keys
94
-	 *
95
-	 */
96
-	public function getServerConfigurationHosts() {
97
-		$referenceConfigkey = 'ldap_host';
98
-
99
-		$keys = $this->getServersConfig($referenceConfigkey);
100
-
101
-		$result = array();
102
-		foreach($keys as $key) {
103
-			$len = strlen($key) - strlen($referenceConfigkey);
104
-			$prefix = substr($key, 0, $len);
105
-			$result[$prefix] = $this->config->getAppValue('user_ldap', $key);
106
-		}
107
-
108
-		return $result;
109
-	}
110
-
111
-	/**
112
-	 * return the next available configuration prefix
113
-	 *
114
-	 * @return string
115
-	 */
116
-	public function getNextServerConfigurationPrefix() {
117
-		$serverConnections = $this->getServerConfigurationPrefixes();
118
-
119
-		if(count($serverConnections) === 0) {
120
-			return 's01';
121
-		}
122
-
123
-		sort($serverConnections);
124
-		$lastKey = array_pop($serverConnections);
125
-		$lastNumber = intval(str_replace('s', '', $lastKey));
126
-		$nextPrefix = 's' . str_pad($lastNumber + 1, 2, '0', STR_PAD_LEFT);
127
-		return $nextPrefix;
128
-	}
129
-
130
-	private function getServersConfig($value) {
131
-		$regex = '/' . $value . '$/S';
132
-
133
-		$keys = $this->config->getAppKeys('user_ldap');
134
-		$result = [];
135
-		foreach ($keys as $key) {
136
-			if (preg_match($regex, $key) === 1) {
137
-				$result[] = $key;
138
-			}
139
-		}
140
-
141
-		return $result;
142
-	}
143
-
144
-	/**
145
-	 * deletes a given saved LDAP/AD server configuration.
146
-	 * @param string $prefix the configuration prefix of the config to delete
147
-	 * @return bool true on success, false otherwise
148
-	 */
149
-	public function deleteServerConfiguration($prefix) {
150
-		if(!in_array($prefix, self::getServerConfigurationPrefixes())) {
151
-			return false;
152
-		}
153
-
154
-		$saveOtherConfigurations = '';
155
-		if(empty($prefix)) {
156
-			$saveOtherConfigurations = 'AND `configkey` NOT LIKE \'s%\'';
157
-		}
158
-
159
-		$query = \OCP\DB::prepare('
40
+    /** @var IConfig */
41
+    private $config;
42
+
43
+    /**
44
+     * Helper constructor.
45
+     *
46
+     * @param IConfig $config
47
+     */
48
+    public function __construct(IConfig $config) {
49
+        $this->config = $config;
50
+    }
51
+
52
+    /**
53
+     * returns prefixes for each saved LDAP/AD server configuration.
54
+     * @param bool $activeConfigurations optional, whether only active configuration shall be
55
+     * retrieved, defaults to false
56
+     * @return array with a list of the available prefixes
57
+     *
58
+     * Configuration prefixes are used to set up configurations for n LDAP or
59
+     * AD servers. Since configuration is stored in the database, table
60
+     * appconfig under appid user_ldap, the common identifiers in column
61
+     * 'configkey' have a prefix. The prefix for the very first server
62
+     * configuration is empty.
63
+     * Configkey Examples:
64
+     * Server 1: ldap_login_filter
65
+     * Server 2: s1_ldap_login_filter
66
+     * Server 3: s2_ldap_login_filter
67
+     *
68
+     * The prefix needs to be passed to the constructor of Connection class,
69
+     * except the default (first) server shall be connected to.
70
+     *
71
+     */
72
+    public function getServerConfigurationPrefixes($activeConfigurations = false) {
73
+        $referenceConfigkey = 'ldap_configuration_active';
74
+
75
+        $keys = $this->getServersConfig($referenceConfigkey);
76
+
77
+        $prefixes = [];
78
+        foreach ($keys as $key) {
79
+            if ($activeConfigurations && $this->config->getAppValue('user_ldap', $key, '0') !== '1') {
80
+                continue;
81
+            }
82
+
83
+            $len = strlen($key) - strlen($referenceConfigkey);
84
+            $prefixes[] = substr($key, 0, $len);
85
+        }
86
+
87
+        return $prefixes;
88
+    }
89
+
90
+    /**
91
+     *
92
+     * determines the host for every configured connection
93
+     * @return array an array with configprefix as keys
94
+     *
95
+     */
96
+    public function getServerConfigurationHosts() {
97
+        $referenceConfigkey = 'ldap_host';
98
+
99
+        $keys = $this->getServersConfig($referenceConfigkey);
100
+
101
+        $result = array();
102
+        foreach($keys as $key) {
103
+            $len = strlen($key) - strlen($referenceConfigkey);
104
+            $prefix = substr($key, 0, $len);
105
+            $result[$prefix] = $this->config->getAppValue('user_ldap', $key);
106
+        }
107
+
108
+        return $result;
109
+    }
110
+
111
+    /**
112
+     * return the next available configuration prefix
113
+     *
114
+     * @return string
115
+     */
116
+    public function getNextServerConfigurationPrefix() {
117
+        $serverConnections = $this->getServerConfigurationPrefixes();
118
+
119
+        if(count($serverConnections) === 0) {
120
+            return 's01';
121
+        }
122
+
123
+        sort($serverConnections);
124
+        $lastKey = array_pop($serverConnections);
125
+        $lastNumber = intval(str_replace('s', '', $lastKey));
126
+        $nextPrefix = 's' . str_pad($lastNumber + 1, 2, '0', STR_PAD_LEFT);
127
+        return $nextPrefix;
128
+    }
129
+
130
+    private function getServersConfig($value) {
131
+        $regex = '/' . $value . '$/S';
132
+
133
+        $keys = $this->config->getAppKeys('user_ldap');
134
+        $result = [];
135
+        foreach ($keys as $key) {
136
+            if (preg_match($regex, $key) === 1) {
137
+                $result[] = $key;
138
+            }
139
+        }
140
+
141
+        return $result;
142
+    }
143
+
144
+    /**
145
+     * deletes a given saved LDAP/AD server configuration.
146
+     * @param string $prefix the configuration prefix of the config to delete
147
+     * @return bool true on success, false otherwise
148
+     */
149
+    public function deleteServerConfiguration($prefix) {
150
+        if(!in_array($prefix, self::getServerConfigurationPrefixes())) {
151
+            return false;
152
+        }
153
+
154
+        $saveOtherConfigurations = '';
155
+        if(empty($prefix)) {
156
+            $saveOtherConfigurations = 'AND `configkey` NOT LIKE \'s%\'';
157
+        }
158
+
159
+        $query = \OCP\DB::prepare('
160 160
 			DELETE
161 161
 			FROM `*PREFIX*appconfig`
162 162
 			WHERE `configkey` LIKE ?
@@ -164,149 +164,149 @@  discard block
 block discarded – undo
164 164
 				AND `appid` = \'user_ldap\'
165 165
 				AND `configkey` NOT IN (\'enabled\', \'installed_version\', \'types\', \'bgjUpdateGroupsLastRun\')
166 166
 		');
167
-		$delRows = $query->execute(array($prefix.'%'));
168
-
169
-		if(\OCP\DB::isError($delRows)) {
170
-			return false;
171
-		}
172
-
173
-		if($delRows === 0) {
174
-			return false;
175
-		}
176
-
177
-		return true;
178
-	}
179
-
180
-	/**
181
-	 * checks whether there is one or more disabled LDAP configurations
182
-	 * @throws \Exception
183
-	 * @return bool
184
-	 */
185
-	public function haveDisabledConfigurations() {
186
-		$all = $this->getServerConfigurationPrefixes(false);
187
-		$active = $this->getServerConfigurationPrefixes(true);
188
-
189
-		if(!is_array($all) || !is_array($active)) {
190
-			throw new \Exception('Unexpected Return Value');
191
-		}
192
-
193
-		return count($all) !== count($active) || count($all) === 0;
194
-	}
195
-
196
-	/**
197
-	 * extracts the domain from a given URL
198
-	 * @param string $url the URL
199
-	 * @return string|false domain as string on success, false otherwise
200
-	 */
201
-	public function getDomainFromURL($url) {
202
-		$uinfo = parse_url($url);
203
-		if(!is_array($uinfo)) {
204
-			return false;
205
-		}
206
-
207
-		$domain = false;
208
-		if(isset($uinfo['host'])) {
209
-			$domain = $uinfo['host'];
210
-		} else if(isset($uinfo['path'])) {
211
-			$domain = $uinfo['path'];
212
-		}
213
-
214
-		return $domain;
215
-	}
167
+        $delRows = $query->execute(array($prefix.'%'));
168
+
169
+        if(\OCP\DB::isError($delRows)) {
170
+            return false;
171
+        }
172
+
173
+        if($delRows === 0) {
174
+            return false;
175
+        }
176
+
177
+        return true;
178
+    }
179
+
180
+    /**
181
+     * checks whether there is one or more disabled LDAP configurations
182
+     * @throws \Exception
183
+     * @return bool
184
+     */
185
+    public function haveDisabledConfigurations() {
186
+        $all = $this->getServerConfigurationPrefixes(false);
187
+        $active = $this->getServerConfigurationPrefixes(true);
188
+
189
+        if(!is_array($all) || !is_array($active)) {
190
+            throw new \Exception('Unexpected Return Value');
191
+        }
192
+
193
+        return count($all) !== count($active) || count($all) === 0;
194
+    }
195
+
196
+    /**
197
+     * extracts the domain from a given URL
198
+     * @param string $url the URL
199
+     * @return string|false domain as string on success, false otherwise
200
+     */
201
+    public function getDomainFromURL($url) {
202
+        $uinfo = parse_url($url);
203
+        if(!is_array($uinfo)) {
204
+            return false;
205
+        }
206
+
207
+        $domain = false;
208
+        if(isset($uinfo['host'])) {
209
+            $domain = $uinfo['host'];
210
+        } else if(isset($uinfo['path'])) {
211
+            $domain = $uinfo['path'];
212
+        }
213
+
214
+        return $domain;
215
+    }
216 216
 	
217
-	/**
218
-	 *
219
-	 * Set the LDAPProvider in the config
220
-	 *
221
-	 */
222
-	public function setLDAPProvider() {
223
-		$current = \OC::$server->getConfig()->getSystemValue('ldapProviderFactory', null);
224
-		if(is_null($current)) {
225
-			\OC::$server->getConfig()->setSystemValue('ldapProviderFactory', '\\OCA\\User_LDAP\\LDAPProviderFactory');
226
-		}
227
-	}
217
+    /**
218
+     *
219
+     * Set the LDAPProvider in the config
220
+     *
221
+     */
222
+    public function setLDAPProvider() {
223
+        $current = \OC::$server->getConfig()->getSystemValue('ldapProviderFactory', null);
224
+        if(is_null($current)) {
225
+            \OC::$server->getConfig()->setSystemValue('ldapProviderFactory', '\\OCA\\User_LDAP\\LDAPProviderFactory');
226
+        }
227
+    }
228 228
 	
229
-	/**
230
-	 * sanitizes a DN received from the LDAP server
231
-	 * @param array $dn the DN in question
232
-	 * @return array|string the sanitized DN
233
-	 */
234
-	public function sanitizeDN($dn) {
235
-		//treating multiple base DNs
236
-		if(is_array($dn)) {
237
-			$result = array();
238
-			foreach($dn as $singleDN) {
239
-				$result[] = $this->sanitizeDN($singleDN);
240
-			}
241
-			return $result;
242
-		}
243
-
244
-		//OID sometimes gives back DNs with whitespace after the comma
245
-		// a la "uid=foo, cn=bar, dn=..." We need to tackle this!
246
-		$dn = preg_replace('/([^\\\]),(\s+)/u', '\1,', $dn);
247
-
248
-		//make comparisons and everything work
249
-		$dn = mb_strtolower($dn, 'UTF-8');
250
-
251
-		//escape DN values according to RFC 2253 – this is already done by ldap_explode_dn
252
-		//to use the DN in search filters, \ needs to be escaped to \5c additionally
253
-		//to use them in bases, we convert them back to simple backslashes in readAttribute()
254
-		$replacements = array(
255
-			'\,' => '\5c2C',
256
-			'\=' => '\5c3D',
257
-			'\+' => '\5c2B',
258
-			'\<' => '\5c3C',
259
-			'\>' => '\5c3E',
260
-			'\;' => '\5c3B',
261
-			'\"' => '\5c22',
262
-			'\#' => '\5c23',
263
-			'('  => '\28',
264
-			')'  => '\29',
265
-			'*'  => '\2A',
266
-		);
267
-		$dn = str_replace(array_keys($replacements), array_values($replacements), $dn);
268
-
269
-		return $dn;
270
-	}
229
+    /**
230
+     * sanitizes a DN received from the LDAP server
231
+     * @param array $dn the DN in question
232
+     * @return array|string the sanitized DN
233
+     */
234
+    public function sanitizeDN($dn) {
235
+        //treating multiple base DNs
236
+        if(is_array($dn)) {
237
+            $result = array();
238
+            foreach($dn as $singleDN) {
239
+                $result[] = $this->sanitizeDN($singleDN);
240
+            }
241
+            return $result;
242
+        }
243
+
244
+        //OID sometimes gives back DNs with whitespace after the comma
245
+        // a la "uid=foo, cn=bar, dn=..." We need to tackle this!
246
+        $dn = preg_replace('/([^\\\]),(\s+)/u', '\1,', $dn);
247
+
248
+        //make comparisons and everything work
249
+        $dn = mb_strtolower($dn, 'UTF-8');
250
+
251
+        //escape DN values according to RFC 2253 – this is already done by ldap_explode_dn
252
+        //to use the DN in search filters, \ needs to be escaped to \5c additionally
253
+        //to use them in bases, we convert them back to simple backslashes in readAttribute()
254
+        $replacements = array(
255
+            '\,' => '\5c2C',
256
+            '\=' => '\5c3D',
257
+            '\+' => '\5c2B',
258
+            '\<' => '\5c3C',
259
+            '\>' => '\5c3E',
260
+            '\;' => '\5c3B',
261
+            '\"' => '\5c22',
262
+            '\#' => '\5c23',
263
+            '('  => '\28',
264
+            ')'  => '\29',
265
+            '*'  => '\2A',
266
+        );
267
+        $dn = str_replace(array_keys($replacements), array_values($replacements), $dn);
268
+
269
+        return $dn;
270
+    }
271 271
 	
272
-	/**
273
-	 * converts a stored DN so it can be used as base parameter for LDAP queries, internally we store them for usage in LDAP filters
274
-	 * @param string $dn the DN
275
-	 * @return string
276
-	 */
277
-	public function DNasBaseParameter($dn) {
278
-		return str_ireplace('\\5c', '\\', $dn);
279
-	}
280
-
281
-	/**
282
-	 * listens to a hook thrown by server2server sharing and replaces the given
283
-	 * login name by a username, if it matches an LDAP user.
284
-	 *
285
-	 * @param array $param
286
-	 * @throws \Exception
287
-	 */
288
-	public static function loginName2UserName($param) {
289
-		if(!isset($param['uid'])) {
290
-			throw new \Exception('key uid is expected to be set in $param');
291
-		}
292
-
293
-		//ain't it ironic?
294
-		$helper = new Helper(\OC::$server->getConfig());
295
-
296
-		$configPrefixes = $helper->getServerConfigurationPrefixes(true);
297
-		$ldapWrapper = new LDAP();
298
-		$ocConfig = \OC::$server->getConfig();
299
-		$notificationManager = \OC::$server->getNotificationManager();
300
-
301
-		$userSession = \OC::$server->getUserSession();
302
-		$userPluginManager = \OC::$server->query('LDAPUserPluginManager');
303
-
304
-		$userBackend  = new User_Proxy(
305
-			$configPrefixes, $ldapWrapper, $ocConfig, $notificationManager, $userSession, $userPluginManager
306
-		);
307
-		$uid = $userBackend->loginName2UserName($param['uid'] );
308
-		if($uid !== false) {
309
-			$param['uid'] = $uid;
310
-		}
311
-	}
272
+    /**
273
+     * converts a stored DN so it can be used as base parameter for LDAP queries, internally we store them for usage in LDAP filters
274
+     * @param string $dn the DN
275
+     * @return string
276
+     */
277
+    public function DNasBaseParameter($dn) {
278
+        return str_ireplace('\\5c', '\\', $dn);
279
+    }
280
+
281
+    /**
282
+     * listens to a hook thrown by server2server sharing and replaces the given
283
+     * login name by a username, if it matches an LDAP user.
284
+     *
285
+     * @param array $param
286
+     * @throws \Exception
287
+     */
288
+    public static function loginName2UserName($param) {
289
+        if(!isset($param['uid'])) {
290
+            throw new \Exception('key uid is expected to be set in $param');
291
+        }
292
+
293
+        //ain't it ironic?
294
+        $helper = new Helper(\OC::$server->getConfig());
295
+
296
+        $configPrefixes = $helper->getServerConfigurationPrefixes(true);
297
+        $ldapWrapper = new LDAP();
298
+        $ocConfig = \OC::$server->getConfig();
299
+        $notificationManager = \OC::$server->getNotificationManager();
300
+
301
+        $userSession = \OC::$server->getUserSession();
302
+        $userPluginManager = \OC::$server->query('LDAPUserPluginManager');
303
+
304
+        $userBackend  = new User_Proxy(
305
+            $configPrefixes, $ldapWrapper, $ocConfig, $notificationManager, $userSession, $userPluginManager
306
+        );
307
+        $uid = $userBackend->loginName2UserName($param['uid'] );
308
+        if($uid !== false) {
309
+            $param['uid'] = $uid;
310
+        }
311
+    }
312 312
 }
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
@@ -59,7 +59,7 @@  discard block
 block discarded – undo
59 59
 		if ($path === '') {
60 60
 			return $this->getRoot();
61 61
 		} else {
62
-			return $this->getRoot() . '/' . ltrim($path, '/');
62
+			return $this->getRoot().'/'.ltrim($path, '/');
63 63
 		}
64 64
 	}
65 65
 
@@ -74,7 +74,7 @@  discard block
 block discarded – undo
74 74
 		$rootLength = strlen($this->getRoot()) + 1;
75 75
 		if ($path === $this->getRoot()) {
76 76
 			return '';
77
-		} else if (substr($path, 0, $rootLength) === $this->getRoot() . '/') {
77
+		} else if (substr($path, 0, $rootLength) === $this->getRoot().'/') {
78 78
 			return substr($path, $rootLength);
79 79
 		} else {
80 80
 			return null;
@@ -94,7 +94,7 @@  discard block
 block discarded – undo
94 94
 
95 95
 	protected function filterCacheEntry($entry) {
96 96
 		$rootLength = strlen($this->getRoot()) + 1;
97
-		return $rootLength === 1 || ($entry['path'] === $this->getRoot()) || (substr($entry['path'], 0, $rootLength) === $this->getRoot() . '/');
97
+		return $rootLength === 1 || ($entry['path'] === $this->getRoot()) || (substr($entry['path'], 0, $rootLength) === $this->getRoot().'/');
98 98
 	}
99 99
 
100 100
 	/**
Please login to merge, or discard this patch.
Indentation   +298 added lines, -298 removed lines patch added patch discarded remove patch
@@ -36,302 +36,302 @@
 block discarded – undo
36 36
  * Jail to a subdirectory of the wrapped cache
37 37
  */
38 38
 class CacheJail extends CacheWrapper {
39
-	/**
40
-	 * @var string
41
-	 */
42
-	protected $root;
43
-
44
-	/**
45
-	 * @param \OCP\Files\Cache\ICache $cache
46
-	 * @param string $root
47
-	 */
48
-	public function __construct($cache, $root) {
49
-		parent::__construct($cache);
50
-		$this->root = $root;
51
-	}
52
-
53
-	protected function getRoot() {
54
-		return $this->root;
55
-	}
56
-
57
-	protected function getSourcePath($path) {
58
-		if ($path === '') {
59
-			return $this->getRoot();
60
-		} else {
61
-			return $this->getRoot() . '/' . ltrim($path, '/');
62
-		}
63
-	}
64
-
65
-	/**
66
-	 * @param string $path
67
-	 * @return null|string the jailed path or null if the path is outside the jail
68
-	 */
69
-	protected function getJailedPath($path) {
70
-		if ($this->getRoot() === '') {
71
-			return $path;
72
-		}
73
-		$rootLength = strlen($this->getRoot()) + 1;
74
-		if ($path === $this->getRoot()) {
75
-			return '';
76
-		} else if (substr($path, 0, $rootLength) === $this->getRoot() . '/') {
77
-			return substr($path, $rootLength);
78
-		} else {
79
-			return null;
80
-		}
81
-	}
82
-
83
-	/**
84
-	 * @param ICacheEntry|array $entry
85
-	 * @return array
86
-	 */
87
-	protected function formatCacheEntry($entry) {
88
-		if (isset($entry['path'])) {
89
-			$entry['path'] = $this->getJailedPath($entry['path']);
90
-		}
91
-		return $entry;
92
-	}
93
-
94
-	protected function filterCacheEntry($entry) {
95
-		$rootLength = strlen($this->getRoot()) + 1;
96
-		return $rootLength === 1 || ($entry['path'] === $this->getRoot()) || (substr($entry['path'], 0, $rootLength) === $this->getRoot() . '/');
97
-	}
98
-
99
-	/**
100
-	 * get the stored metadata of a file or folder
101
-	 *
102
-	 * @param string /int $file
103
-	 * @return ICacheEntry|false
104
-	 */
105
-	public function get($file) {
106
-		if (is_string($file) or $file == '') {
107
-			$file = $this->getSourcePath($file);
108
-		}
109
-		return parent::get($file);
110
-	}
111
-
112
-	/**
113
-	 * insert meta data for a new file or folder
114
-	 *
115
-	 * @param string $file
116
-	 * @param array $data
117
-	 *
118
-	 * @return int file id
119
-	 * @throws \RuntimeException
120
-	 */
121
-	public function insert($file, array $data) {
122
-		return $this->getCache()->insert($this->getSourcePath($file), $data);
123
-	}
124
-
125
-	/**
126
-	 * update the metadata in the cache
127
-	 *
128
-	 * @param int $id
129
-	 * @param array $data
130
-	 */
131
-	public function update($id, array $data) {
132
-		$this->getCache()->update($id, $data);
133
-	}
134
-
135
-	/**
136
-	 * get the file id for a file
137
-	 *
138
-	 * @param string $file
139
-	 * @return int
140
-	 */
141
-	public function getId($file) {
142
-		return $this->getCache()->getId($this->getSourcePath($file));
143
-	}
144
-
145
-	/**
146
-	 * get the id of the parent folder of a file
147
-	 *
148
-	 * @param string $file
149
-	 * @return int
150
-	 */
151
-	public function getParentId($file) {
152
-		return $this->getCache()->getParentId($this->getSourcePath($file));
153
-	}
154
-
155
-	/**
156
-	 * check if a file is available in the cache
157
-	 *
158
-	 * @param string $file
159
-	 * @return bool
160
-	 */
161
-	public function inCache($file) {
162
-		return $this->getCache()->inCache($this->getSourcePath($file));
163
-	}
164
-
165
-	/**
166
-	 * remove a file or folder from the cache
167
-	 *
168
-	 * @param string $file
169
-	 */
170
-	public function remove($file) {
171
-		$this->getCache()->remove($this->getSourcePath($file));
172
-	}
173
-
174
-	/**
175
-	 * Move a file or folder in the cache
176
-	 *
177
-	 * @param string $source
178
-	 * @param string $target
179
-	 */
180
-	public function move($source, $target) {
181
-		$this->getCache()->move($this->getSourcePath($source), $this->getSourcePath($target));
182
-	}
183
-
184
-	/**
185
-	 * Get the storage id and path needed for a move
186
-	 *
187
-	 * @param string $path
188
-	 * @return array [$storageId, $internalPath]
189
-	 */
190
-	protected function getMoveInfo($path) {
191
-		return [$this->getNumericStorageId(), $this->getSourcePath($path)];
192
-	}
193
-
194
-	/**
195
-	 * remove all entries for files that are stored on the storage from the cache
196
-	 */
197
-	public function clear() {
198
-		$this->getCache()->remove($this->getRoot());
199
-	}
200
-
201
-	/**
202
-	 * @param string $file
203
-	 *
204
-	 * @return int Cache::NOT_FOUND, Cache::PARTIAL, Cache::SHALLOW or Cache::COMPLETE
205
-	 */
206
-	public function getStatus($file) {
207
-		return $this->getCache()->getStatus($this->getSourcePath($file));
208
-	}
209
-
210
-	private function formatSearchResults($results) {
211
-		$results = array_filter($results, array($this, 'filterCacheEntry'));
212
-		$results = array_values($results);
213
-		return array_map(array($this, 'formatCacheEntry'), $results);
214
-	}
215
-
216
-	/**
217
-	 * search for files matching $pattern
218
-	 *
219
-	 * @param string $pattern
220
-	 * @return array an array of file data
221
-	 */
222
-	public function search($pattern) {
223
-		$results = $this->getCache()->search($pattern);
224
-		return $this->formatSearchResults($results);
225
-	}
226
-
227
-	/**
228
-	 * search for files by mimetype
229
-	 *
230
-	 * @param string $mimetype
231
-	 * @return array
232
-	 */
233
-	public function searchByMime($mimetype) {
234
-		$results = $this->getCache()->searchByMime($mimetype);
235
-		return $this->formatSearchResults($results);
236
-	}
237
-
238
-	public function searchQuery(ISearchQuery $query) {
239
-		$results = $this->getCache()->searchQuery($query);
240
-		return $this->formatSearchResults($results);
241
-	}
242
-
243
-	/**
244
-	 * search for files by mimetype
245
-	 *
246
-	 * @param string|int $tag name or tag id
247
-	 * @param string $userId owner of the tags
248
-	 * @return array
249
-	 */
250
-	public function searchByTag($tag, $userId) {
251
-		$results = $this->getCache()->searchByTag($tag, $userId);
252
-		return $this->formatSearchResults($results);
253
-	}
254
-
255
-	/**
256
-	 * update the folder size and the size of all parent folders
257
-	 *
258
-	 * @param string|boolean $path
259
-	 * @param array $data (optional) meta data of the folder
260
-	 */
261
-	public function correctFolderSize($path, $data = null) {
262
-		if ($this->getCache() instanceof Cache) {
263
-			$this->getCache()->correctFolderSize($this->getSourcePath($path), $data);
264
-		}
265
-	}
266
-
267
-	/**
268
-	 * get the size of a folder and set it in the cache
269
-	 *
270
-	 * @param string $path
271
-	 * @param array $entry (optional) meta data of the folder
272
-	 * @return int
273
-	 */
274
-	public function calculateFolderSize($path, $entry = null) {
275
-		if ($this->getCache() instanceof Cache) {
276
-			return $this->getCache()->calculateFolderSize($this->getSourcePath($path), $entry);
277
-		} else {
278
-			return 0;
279
-		}
280
-
281
-	}
282
-
283
-	/**
284
-	 * get all file ids on the files on the storage
285
-	 *
286
-	 * @return int[]
287
-	 */
288
-	public function getAll() {
289
-		// not supported
290
-		return array();
291
-	}
292
-
293
-	/**
294
-	 * find a folder in the cache which has not been fully scanned
295
-	 *
296
-	 * If multiply incomplete folders are in the cache, the one with the highest id will be returned,
297
-	 * use the one with the highest id gives the best result with the background scanner, since that is most
298
-	 * likely the folder where we stopped scanning previously
299
-	 *
300
-	 * @return string|bool the path of the folder or false when no folder matched
301
-	 */
302
-	public function getIncomplete() {
303
-		// not supported
304
-		return false;
305
-	}
306
-
307
-	/**
308
-	 * get the path of a file on this storage by it's id
309
-	 *
310
-	 * @param int $id
311
-	 * @return string|null
312
-	 */
313
-	public function getPathById($id) {
314
-		$path = $this->getCache()->getPathById($id);
315
-		if ($path === null) {
316
-			return null;
317
-		}
318
-
319
-		return $this->getJailedPath($path);
320
-	}
321
-
322
-	/**
323
-	 * Move a file or folder in the cache
324
-	 *
325
-	 * Note that this should make sure the entries are removed from the source cache
326
-	 *
327
-	 * @param \OCP\Files\Cache\ICache $sourceCache
328
-	 * @param string $sourcePath
329
-	 * @param string $targetPath
330
-	 */
331
-	public function moveFromCache(\OCP\Files\Cache\ICache $sourceCache, $sourcePath, $targetPath) {
332
-		if ($sourceCache === $this) {
333
-			return $this->move($sourcePath, $targetPath);
334
-		}
335
-		return $this->getCache()->moveFromCache($sourceCache, $sourcePath, $this->getSourcePath($targetPath));
336
-	}
39
+    /**
40
+     * @var string
41
+     */
42
+    protected $root;
43
+
44
+    /**
45
+     * @param \OCP\Files\Cache\ICache $cache
46
+     * @param string $root
47
+     */
48
+    public function __construct($cache, $root) {
49
+        parent::__construct($cache);
50
+        $this->root = $root;
51
+    }
52
+
53
+    protected function getRoot() {
54
+        return $this->root;
55
+    }
56
+
57
+    protected function getSourcePath($path) {
58
+        if ($path === '') {
59
+            return $this->getRoot();
60
+        } else {
61
+            return $this->getRoot() . '/' . ltrim($path, '/');
62
+        }
63
+    }
64
+
65
+    /**
66
+     * @param string $path
67
+     * @return null|string the jailed path or null if the path is outside the jail
68
+     */
69
+    protected function getJailedPath($path) {
70
+        if ($this->getRoot() === '') {
71
+            return $path;
72
+        }
73
+        $rootLength = strlen($this->getRoot()) + 1;
74
+        if ($path === $this->getRoot()) {
75
+            return '';
76
+        } else if (substr($path, 0, $rootLength) === $this->getRoot() . '/') {
77
+            return substr($path, $rootLength);
78
+        } else {
79
+            return null;
80
+        }
81
+    }
82
+
83
+    /**
84
+     * @param ICacheEntry|array $entry
85
+     * @return array
86
+     */
87
+    protected function formatCacheEntry($entry) {
88
+        if (isset($entry['path'])) {
89
+            $entry['path'] = $this->getJailedPath($entry['path']);
90
+        }
91
+        return $entry;
92
+    }
93
+
94
+    protected function filterCacheEntry($entry) {
95
+        $rootLength = strlen($this->getRoot()) + 1;
96
+        return $rootLength === 1 || ($entry['path'] === $this->getRoot()) || (substr($entry['path'], 0, $rootLength) === $this->getRoot() . '/');
97
+    }
98
+
99
+    /**
100
+     * get the stored metadata of a file or folder
101
+     *
102
+     * @param string /int $file
103
+     * @return ICacheEntry|false
104
+     */
105
+    public function get($file) {
106
+        if (is_string($file) or $file == '') {
107
+            $file = $this->getSourcePath($file);
108
+        }
109
+        return parent::get($file);
110
+    }
111
+
112
+    /**
113
+     * insert meta data for a new file or folder
114
+     *
115
+     * @param string $file
116
+     * @param array $data
117
+     *
118
+     * @return int file id
119
+     * @throws \RuntimeException
120
+     */
121
+    public function insert($file, array $data) {
122
+        return $this->getCache()->insert($this->getSourcePath($file), $data);
123
+    }
124
+
125
+    /**
126
+     * update the metadata in the cache
127
+     *
128
+     * @param int $id
129
+     * @param array $data
130
+     */
131
+    public function update($id, array $data) {
132
+        $this->getCache()->update($id, $data);
133
+    }
134
+
135
+    /**
136
+     * get the file id for a file
137
+     *
138
+     * @param string $file
139
+     * @return int
140
+     */
141
+    public function getId($file) {
142
+        return $this->getCache()->getId($this->getSourcePath($file));
143
+    }
144
+
145
+    /**
146
+     * get the id of the parent folder of a file
147
+     *
148
+     * @param string $file
149
+     * @return int
150
+     */
151
+    public function getParentId($file) {
152
+        return $this->getCache()->getParentId($this->getSourcePath($file));
153
+    }
154
+
155
+    /**
156
+     * check if a file is available in the cache
157
+     *
158
+     * @param string $file
159
+     * @return bool
160
+     */
161
+    public function inCache($file) {
162
+        return $this->getCache()->inCache($this->getSourcePath($file));
163
+    }
164
+
165
+    /**
166
+     * remove a file or folder from the cache
167
+     *
168
+     * @param string $file
169
+     */
170
+    public function remove($file) {
171
+        $this->getCache()->remove($this->getSourcePath($file));
172
+    }
173
+
174
+    /**
175
+     * Move a file or folder in the cache
176
+     *
177
+     * @param string $source
178
+     * @param string $target
179
+     */
180
+    public function move($source, $target) {
181
+        $this->getCache()->move($this->getSourcePath($source), $this->getSourcePath($target));
182
+    }
183
+
184
+    /**
185
+     * Get the storage id and path needed for a move
186
+     *
187
+     * @param string $path
188
+     * @return array [$storageId, $internalPath]
189
+     */
190
+    protected function getMoveInfo($path) {
191
+        return [$this->getNumericStorageId(), $this->getSourcePath($path)];
192
+    }
193
+
194
+    /**
195
+     * remove all entries for files that are stored on the storage from the cache
196
+     */
197
+    public function clear() {
198
+        $this->getCache()->remove($this->getRoot());
199
+    }
200
+
201
+    /**
202
+     * @param string $file
203
+     *
204
+     * @return int Cache::NOT_FOUND, Cache::PARTIAL, Cache::SHALLOW or Cache::COMPLETE
205
+     */
206
+    public function getStatus($file) {
207
+        return $this->getCache()->getStatus($this->getSourcePath($file));
208
+    }
209
+
210
+    private function formatSearchResults($results) {
211
+        $results = array_filter($results, array($this, 'filterCacheEntry'));
212
+        $results = array_values($results);
213
+        return array_map(array($this, 'formatCacheEntry'), $results);
214
+    }
215
+
216
+    /**
217
+     * search for files matching $pattern
218
+     *
219
+     * @param string $pattern
220
+     * @return array an array of file data
221
+     */
222
+    public function search($pattern) {
223
+        $results = $this->getCache()->search($pattern);
224
+        return $this->formatSearchResults($results);
225
+    }
226
+
227
+    /**
228
+     * search for files by mimetype
229
+     *
230
+     * @param string $mimetype
231
+     * @return array
232
+     */
233
+    public function searchByMime($mimetype) {
234
+        $results = $this->getCache()->searchByMime($mimetype);
235
+        return $this->formatSearchResults($results);
236
+    }
237
+
238
+    public function searchQuery(ISearchQuery $query) {
239
+        $results = $this->getCache()->searchQuery($query);
240
+        return $this->formatSearchResults($results);
241
+    }
242
+
243
+    /**
244
+     * search for files by mimetype
245
+     *
246
+     * @param string|int $tag name or tag id
247
+     * @param string $userId owner of the tags
248
+     * @return array
249
+     */
250
+    public function searchByTag($tag, $userId) {
251
+        $results = $this->getCache()->searchByTag($tag, $userId);
252
+        return $this->formatSearchResults($results);
253
+    }
254
+
255
+    /**
256
+     * update the folder size and the size of all parent folders
257
+     *
258
+     * @param string|boolean $path
259
+     * @param array $data (optional) meta data of the folder
260
+     */
261
+    public function correctFolderSize($path, $data = null) {
262
+        if ($this->getCache() instanceof Cache) {
263
+            $this->getCache()->correctFolderSize($this->getSourcePath($path), $data);
264
+        }
265
+    }
266
+
267
+    /**
268
+     * get the size of a folder and set it in the cache
269
+     *
270
+     * @param string $path
271
+     * @param array $entry (optional) meta data of the folder
272
+     * @return int
273
+     */
274
+    public function calculateFolderSize($path, $entry = null) {
275
+        if ($this->getCache() instanceof Cache) {
276
+            return $this->getCache()->calculateFolderSize($this->getSourcePath($path), $entry);
277
+        } else {
278
+            return 0;
279
+        }
280
+
281
+    }
282
+
283
+    /**
284
+     * get all file ids on the files on the storage
285
+     *
286
+     * @return int[]
287
+     */
288
+    public function getAll() {
289
+        // not supported
290
+        return array();
291
+    }
292
+
293
+    /**
294
+     * find a folder in the cache which has not been fully scanned
295
+     *
296
+     * If multiply incomplete folders are in the cache, the one with the highest id will be returned,
297
+     * use the one with the highest id gives the best result with the background scanner, since that is most
298
+     * likely the folder where we stopped scanning previously
299
+     *
300
+     * @return string|bool the path of the folder or false when no folder matched
301
+     */
302
+    public function getIncomplete() {
303
+        // not supported
304
+        return false;
305
+    }
306
+
307
+    /**
308
+     * get the path of a file on this storage by it's id
309
+     *
310
+     * @param int $id
311
+     * @return string|null
312
+     */
313
+    public function getPathById($id) {
314
+        $path = $this->getCache()->getPathById($id);
315
+        if ($path === null) {
316
+            return null;
317
+        }
318
+
319
+        return $this->getJailedPath($path);
320
+    }
321
+
322
+    /**
323
+     * Move a file or folder in the cache
324
+     *
325
+     * Note that this should make sure the entries are removed from the source cache
326
+     *
327
+     * @param \OCP\Files\Cache\ICache $sourceCache
328
+     * @param string $sourcePath
329
+     * @param string $targetPath
330
+     */
331
+    public function moveFromCache(\OCP\Files\Cache\ICache $sourceCache, $sourcePath, $targetPath) {
332
+        if ($sourceCache === $this) {
333
+            return $this->move($sourcePath, $targetPath);
334
+        }
335
+        return $this->getCache()->moveFromCache($sourceCache, $sourcePath, $this->getSourcePath($targetPath));
336
+    }
337 337
 }
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.
Spacing   +15 added lines, -15 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) {
@@ -249,7 +249,7 @@  discard block
 block discarded – undo
249 249
 	 * @param IUser|null $user
250 250
 	 * @return \OC\Group\Group[]
251 251
 	 */
252
-	public function getUserGroups(IUser $user= null) {
252
+	public function getUserGroups(IUser $user = null) {
253 253
 		if (!$user instanceof IUser) {
254 254
 			return [];
255 255
 		}
@@ -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.
Indentation   +333 added lines, -333 removed lines patch added patch discarded remove patch
@@ -58,337 +58,337 @@
 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
-	}
147
-
148
-	/**
149
-	 * Get the active backends
150
-	 * @return \OCP\GroupInterface[]
151
-	 */
152
-	public function getBackends() {
153
-		return $this->backends;
154
-	}
155
-
156
-
157
-	protected function clearCaches() {
158
-		$this->cachedGroups = array();
159
-		$this->cachedUserGroups = array();
160
-	}
161
-
162
-	/**
163
-	 * @param string $gid
164
-	 * @return \OC\Group\Group
165
-	 */
166
-	public function get($gid) {
167
-		if (isset($this->cachedGroups[$gid])) {
168
-			return $this->cachedGroups[$gid];
169
-		}
170
-		return $this->getGroupObject($gid);
171
-	}
172
-
173
-	/**
174
-	 * @param string $gid
175
-	 * @param string $displayName
176
-	 * @return \OCP\IGroup
177
-	 */
178
-	protected function getGroupObject($gid, $displayName = null) {
179
-		$backends = array();
180
-		foreach ($this->backends as $backend) {
181
-			if ($backend->implementsActions(\OC\Group\Backend::GROUP_DETAILS)) {
182
-				$groupData = $backend->getGroupDetails($gid);
183
-				if (is_array($groupData)) {
184
-					// take the display name from the first backend that has a non-null one
185
-					if (is_null($displayName) && isset($groupData['displayName'])) {
186
-						$displayName = $groupData['displayName'];
187
-					}
188
-					$backends[] = $backend;
189
-				}
190
-			} else if ($backend->groupExists($gid)) {
191
-				$backends[] = $backend;
192
-			}
193
-		}
194
-		if (count($backends) === 0) {
195
-			return null;
196
-		}
197
-		$this->cachedGroups[$gid] = new Group($gid, $backends, $this->userManager, $this, $displayName);
198
-		return $this->cachedGroups[$gid];
199
-	}
200
-
201
-	/**
202
-	 * @param string $gid
203
-	 * @return bool
204
-	 */
205
-	public function groupExists($gid) {
206
-		return $this->get($gid) instanceof IGroup;
207
-	}
208
-
209
-	/**
210
-	 * @param string $gid
211
-	 * @return \OC\Group\Group
212
-	 */
213
-	public function createGroup($gid) {
214
-		if ($gid === '' || $gid === null) {
215
-			return false;
216
-		} else if ($group = $this->get($gid)) {
217
-			return $group;
218
-		} else {
219
-			$this->emit('\OC\Group', 'preCreate', array($gid));
220
-			foreach ($this->backends as $backend) {
221
-				if ($backend->implementsActions(\OC\Group\Backend::CREATE_GROUP)) {
222
-					$backend->createGroup($gid);
223
-					$group = $this->getGroupObject($gid);
224
-					$this->emit('\OC\Group', 'postCreate', array($group));
225
-					return $group;
226
-				}
227
-			}
228
-			return null;
229
-		}
230
-	}
231
-
232
-	/**
233
-	 * @param string $search
234
-	 * @param int $limit
235
-	 * @param int $offset
236
-	 * @return \OC\Group\Group[]
237
-	 */
238
-	public function search($search, $limit = null, $offset = null) {
239
-		$groups = array();
240
-		foreach ($this->backends as $backend) {
241
-			$groupIds = $backend->getGroups($search, $limit, $offset);
242
-			foreach ($groupIds as $groupId) {
243
-				$aGroup = $this->get($groupId);
244
-				if ($aGroup instanceof IGroup) {
245
-					$groups[$groupId] = $aGroup;
246
-				} else {
247
-					$this->logger->debug('Group "' . $groupId . '" was returned by search but not found through direct access', ['app' => 'core']);
248
-				}
249
-			}
250
-			if (!is_null($limit) and $limit <= 0) {
251
-				return array_values($groups);
252
-			}
253
-		}
254
-		return array_values($groups);
255
-	}
256
-
257
-	/**
258
-	 * @param IUser|null $user
259
-	 * @return \OC\Group\Group[]
260
-	 */
261
-	public function getUserGroups(IUser $user= null) {
262
-		if (!$user instanceof IUser) {
263
-			return [];
264
-		}
265
-		return $this->getUserIdGroups($user->getUID());
266
-	}
267
-
268
-	/**
269
-	 * @param string $uid the user id
270
-	 * @return \OC\Group\Group[]
271
-	 */
272
-	public function getUserIdGroups($uid) {
273
-		if (isset($this->cachedUserGroups[$uid])) {
274
-			return $this->cachedUserGroups[$uid];
275
-		}
276
-		$groups = array();
277
-		foreach ($this->backends as $backend) {
278
-			$groupIds = $backend->getUserGroups($uid);
279
-			if (is_array($groupIds)) {
280
-				foreach ($groupIds as $groupId) {
281
-					$aGroup = $this->get($groupId);
282
-					if ($aGroup instanceof IGroup) {
283
-						$groups[$groupId] = $aGroup;
284
-					} else {
285
-						$this->logger->debug('User "' . $uid . '" belongs to deleted group: "' . $groupId . '"', ['app' => 'core']);
286
-					}
287
-				}
288
-			}
289
-		}
290
-		$this->cachedUserGroups[$uid] = $groups;
291
-		return $this->cachedUserGroups[$uid];
292
-	}
293
-
294
-	/**
295
-	 * Checks if a userId is in the admin group
296
-	 * @param string $userId
297
-	 * @return bool if admin
298
-	 */
299
-	public function isAdmin($userId) {
300
-		foreach ($this->backends as $backend) {
301
-			if ($backend->implementsActions(\OC\Group\Backend::IS_ADMIN) && $backend->isAdmin($userId)) {
302
-				return true;
303
-			}
304
-		}
305
-		return $this->isInGroup($userId, 'admin');
306
-	}
307
-
308
-	/**
309
-	 * Checks if a userId is in a group
310
-	 * @param string $userId
311
-	 * @param string $group
312
-	 * @return bool if in group
313
-	 */
314
-	public function isInGroup($userId, $group) {
315
-		return array_key_exists($group, $this->getUserIdGroups($userId));
316
-	}
317
-
318
-	/**
319
-	 * get a list of group ids for a user
320
-	 * @param IUser $user
321
-	 * @return array with group ids
322
-	 */
323
-	public function getUserGroupIds(IUser $user) {
324
-		return array_map(function($value) {
325
-			return (string) $value;
326
-		}, array_keys($this->getUserGroups($user)));
327
-	}
328
-
329
-	/**
330
-	 * get a list of all display names in a group
331
-	 * @param string $gid
332
-	 * @param string $search
333
-	 * @param int $limit
334
-	 * @param int $offset
335
-	 * @return array an array of display names (value) and user ids (key)
336
-	 */
337
-	public function displayNamesInGroup($gid, $search = '', $limit = -1, $offset = 0) {
338
-		$group = $this->get($gid);
339
-		if(is_null($group)) {
340
-			return array();
341
-		}
342
-
343
-		$search = trim($search);
344
-		$groupUsers = array();
345
-
346
-		if(!empty($search)) {
347
-			// only user backends have the capability to do a complex search for users
348
-			$searchOffset = 0;
349
-			$searchLimit = $limit * 100;
350
-			if($limit === -1) {
351
-				$searchLimit = 500;
352
-			}
353
-
354
-			do {
355
-				$filteredUsers = $this->userManager->searchDisplayName($search, $searchLimit, $searchOffset);
356
-				foreach($filteredUsers as $filteredUser) {
357
-					if($group->inGroup($filteredUser)) {
358
-						$groupUsers[]= $filteredUser;
359
-					}
360
-				}
361
-				$searchOffset += $searchLimit;
362
-			} while(count($groupUsers) < $searchLimit+$offset && count($filteredUsers) >= $searchLimit);
363
-
364
-			if($limit === -1) {
365
-				$groupUsers = array_slice($groupUsers, $offset);
366
-			} else {
367
-				$groupUsers = array_slice($groupUsers, $offset, $limit);
368
-			}
369
-		} else {
370
-			$groupUsers = $group->searchUsers('', $limit, $offset);
371
-		}
372
-
373
-		$matchingUsers = array();
374
-		foreach($groupUsers as $groupUser) {
375
-			$matchingUsers[$groupUser->getUID()] = $groupUser->getDisplayName();
376
-		}
377
-		return $matchingUsers;
378
-	}
379
-
380
-	/**
381
-	 * @return \OC\SubAdmin
382
-	 */
383
-	public function getSubAdmin() {
384
-		if (!$this->subAdmin) {
385
-			$this->subAdmin = new \OC\SubAdmin(
386
-				$this->userManager,
387
-				$this,
388
-				\OC::$server->getDatabaseConnection()
389
-			);
390
-		}
391
-
392
-		return $this->subAdmin;
393
-	}
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
+
148
+    /**
149
+     * Get the active backends
150
+     * @return \OCP\GroupInterface[]
151
+     */
152
+    public function getBackends() {
153
+        return $this->backends;
154
+    }
155
+
156
+
157
+    protected function clearCaches() {
158
+        $this->cachedGroups = array();
159
+        $this->cachedUserGroups = array();
160
+    }
161
+
162
+    /**
163
+     * @param string $gid
164
+     * @return \OC\Group\Group
165
+     */
166
+    public function get($gid) {
167
+        if (isset($this->cachedGroups[$gid])) {
168
+            return $this->cachedGroups[$gid];
169
+        }
170
+        return $this->getGroupObject($gid);
171
+    }
172
+
173
+    /**
174
+     * @param string $gid
175
+     * @param string $displayName
176
+     * @return \OCP\IGroup
177
+     */
178
+    protected function getGroupObject($gid, $displayName = null) {
179
+        $backends = array();
180
+        foreach ($this->backends as $backend) {
181
+            if ($backend->implementsActions(\OC\Group\Backend::GROUP_DETAILS)) {
182
+                $groupData = $backend->getGroupDetails($gid);
183
+                if (is_array($groupData)) {
184
+                    // take the display name from the first backend that has a non-null one
185
+                    if (is_null($displayName) && isset($groupData['displayName'])) {
186
+                        $displayName = $groupData['displayName'];
187
+                    }
188
+                    $backends[] = $backend;
189
+                }
190
+            } else if ($backend->groupExists($gid)) {
191
+                $backends[] = $backend;
192
+            }
193
+        }
194
+        if (count($backends) === 0) {
195
+            return null;
196
+        }
197
+        $this->cachedGroups[$gid] = new Group($gid, $backends, $this->userManager, $this, $displayName);
198
+        return $this->cachedGroups[$gid];
199
+    }
200
+
201
+    /**
202
+     * @param string $gid
203
+     * @return bool
204
+     */
205
+    public function groupExists($gid) {
206
+        return $this->get($gid) instanceof IGroup;
207
+    }
208
+
209
+    /**
210
+     * @param string $gid
211
+     * @return \OC\Group\Group
212
+     */
213
+    public function createGroup($gid) {
214
+        if ($gid === '' || $gid === null) {
215
+            return false;
216
+        } else if ($group = $this->get($gid)) {
217
+            return $group;
218
+        } else {
219
+            $this->emit('\OC\Group', 'preCreate', array($gid));
220
+            foreach ($this->backends as $backend) {
221
+                if ($backend->implementsActions(\OC\Group\Backend::CREATE_GROUP)) {
222
+                    $backend->createGroup($gid);
223
+                    $group = $this->getGroupObject($gid);
224
+                    $this->emit('\OC\Group', 'postCreate', array($group));
225
+                    return $group;
226
+                }
227
+            }
228
+            return null;
229
+        }
230
+    }
231
+
232
+    /**
233
+     * @param string $search
234
+     * @param int $limit
235
+     * @param int $offset
236
+     * @return \OC\Group\Group[]
237
+     */
238
+    public function search($search, $limit = null, $offset = null) {
239
+        $groups = array();
240
+        foreach ($this->backends as $backend) {
241
+            $groupIds = $backend->getGroups($search, $limit, $offset);
242
+            foreach ($groupIds as $groupId) {
243
+                $aGroup = $this->get($groupId);
244
+                if ($aGroup instanceof IGroup) {
245
+                    $groups[$groupId] = $aGroup;
246
+                } else {
247
+                    $this->logger->debug('Group "' . $groupId . '" was returned by search but not found through direct access', ['app' => 'core']);
248
+                }
249
+            }
250
+            if (!is_null($limit) and $limit <= 0) {
251
+                return array_values($groups);
252
+            }
253
+        }
254
+        return array_values($groups);
255
+    }
256
+
257
+    /**
258
+     * @param IUser|null $user
259
+     * @return \OC\Group\Group[]
260
+     */
261
+    public function getUserGroups(IUser $user= null) {
262
+        if (!$user instanceof IUser) {
263
+            return [];
264
+        }
265
+        return $this->getUserIdGroups($user->getUID());
266
+    }
267
+
268
+    /**
269
+     * @param string $uid the user id
270
+     * @return \OC\Group\Group[]
271
+     */
272
+    public function getUserIdGroups($uid) {
273
+        if (isset($this->cachedUserGroups[$uid])) {
274
+            return $this->cachedUserGroups[$uid];
275
+        }
276
+        $groups = array();
277
+        foreach ($this->backends as $backend) {
278
+            $groupIds = $backend->getUserGroups($uid);
279
+            if (is_array($groupIds)) {
280
+                foreach ($groupIds as $groupId) {
281
+                    $aGroup = $this->get($groupId);
282
+                    if ($aGroup instanceof IGroup) {
283
+                        $groups[$groupId] = $aGroup;
284
+                    } else {
285
+                        $this->logger->debug('User "' . $uid . '" belongs to deleted group: "' . $groupId . '"', ['app' => 'core']);
286
+                    }
287
+                }
288
+            }
289
+        }
290
+        $this->cachedUserGroups[$uid] = $groups;
291
+        return $this->cachedUserGroups[$uid];
292
+    }
293
+
294
+    /**
295
+     * Checks if a userId is in the admin group
296
+     * @param string $userId
297
+     * @return bool if admin
298
+     */
299
+    public function isAdmin($userId) {
300
+        foreach ($this->backends as $backend) {
301
+            if ($backend->implementsActions(\OC\Group\Backend::IS_ADMIN) && $backend->isAdmin($userId)) {
302
+                return true;
303
+            }
304
+        }
305
+        return $this->isInGroup($userId, 'admin');
306
+    }
307
+
308
+    /**
309
+     * Checks if a userId is in a group
310
+     * @param string $userId
311
+     * @param string $group
312
+     * @return bool if in group
313
+     */
314
+    public function isInGroup($userId, $group) {
315
+        return array_key_exists($group, $this->getUserIdGroups($userId));
316
+    }
317
+
318
+    /**
319
+     * get a list of group ids for a user
320
+     * @param IUser $user
321
+     * @return array with group ids
322
+     */
323
+    public function getUserGroupIds(IUser $user) {
324
+        return array_map(function($value) {
325
+            return (string) $value;
326
+        }, array_keys($this->getUserGroups($user)));
327
+    }
328
+
329
+    /**
330
+     * get a list of all display names in a group
331
+     * @param string $gid
332
+     * @param string $search
333
+     * @param int $limit
334
+     * @param int $offset
335
+     * @return array an array of display names (value) and user ids (key)
336
+     */
337
+    public function displayNamesInGroup($gid, $search = '', $limit = -1, $offset = 0) {
338
+        $group = $this->get($gid);
339
+        if(is_null($group)) {
340
+            return array();
341
+        }
342
+
343
+        $search = trim($search);
344
+        $groupUsers = array();
345
+
346
+        if(!empty($search)) {
347
+            // only user backends have the capability to do a complex search for users
348
+            $searchOffset = 0;
349
+            $searchLimit = $limit * 100;
350
+            if($limit === -1) {
351
+                $searchLimit = 500;
352
+            }
353
+
354
+            do {
355
+                $filteredUsers = $this->userManager->searchDisplayName($search, $searchLimit, $searchOffset);
356
+                foreach($filteredUsers as $filteredUser) {
357
+                    if($group->inGroup($filteredUser)) {
358
+                        $groupUsers[]= $filteredUser;
359
+                    }
360
+                }
361
+                $searchOffset += $searchLimit;
362
+            } while(count($groupUsers) < $searchLimit+$offset && count($filteredUsers) >= $searchLimit);
363
+
364
+            if($limit === -1) {
365
+                $groupUsers = array_slice($groupUsers, $offset);
366
+            } else {
367
+                $groupUsers = array_slice($groupUsers, $offset, $limit);
368
+            }
369
+        } else {
370
+            $groupUsers = $group->searchUsers('', $limit, $offset);
371
+        }
372
+
373
+        $matchingUsers = array();
374
+        foreach($groupUsers as $groupUser) {
375
+            $matchingUsers[$groupUser->getUID()] = $groupUser->getDisplayName();
376
+        }
377
+        return $matchingUsers;
378
+    }
379
+
380
+    /**
381
+     * @return \OC\SubAdmin
382
+     */
383
+    public function getSubAdmin() {
384
+        if (!$this->subAdmin) {
385
+            $this->subAdmin = new \OC\SubAdmin(
386
+                $this->userManager,
387
+                $this,
388
+                \OC::$server->getDatabaseConnection()
389
+            );
390
+        }
391
+
392
+        return $this->subAdmin;
393
+    }
394 394
 }
Please login to merge, or discard this patch.
lib/private/Memcache/APCu.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -65,7 +65,7 @@
 block discarded – undo
65 65
 	 * Set a value in the cache if it's not already stored
66 66
 	 *
67 67
 	 * @param string $key
68
-	 * @param mixed $value
68
+	 * @param integer $value
69 69
 	 * @param int $ttl Time To Live in seconds. Defaults to 60*60*24
70 70
 	 * @return bool
71 71
 	 */
Please login to merge, or discard this patch.
Indentation   +125 added lines, -125 removed lines patch added patch discarded remove patch
@@ -30,140 +30,140 @@
 block discarded – undo
30 30
 use OCP\IMemcache;
31 31
 
32 32
 class APCu extends Cache implements IMemcache {
33
-	use CASTrait {
34
-		cas as casEmulated;
35
-	}
33
+    use CASTrait {
34
+        cas as casEmulated;
35
+    }
36 36
 
37
-	use CADTrait;
37
+    use CADTrait;
38 38
 
39
-	public function get($key) {
40
-		$result = apcu_fetch($this->getPrefix() . $key, $success);
41
-		if (!$success) {
42
-			return null;
43
-		}
44
-		return $result;
45
-	}
39
+    public function get($key) {
40
+        $result = apcu_fetch($this->getPrefix() . $key, $success);
41
+        if (!$success) {
42
+            return null;
43
+        }
44
+        return $result;
45
+    }
46 46
 
47
-	public function set($key, $value, $ttl = 0) {
48
-		return apcu_store($this->getPrefix() . $key, $value, $ttl);
49
-	}
47
+    public function set($key, $value, $ttl = 0) {
48
+        return apcu_store($this->getPrefix() . $key, $value, $ttl);
49
+    }
50 50
 
51
-	public function hasKey($key) {
52
-		return apcu_exists($this->getPrefix() . $key);
53
-	}
51
+    public function hasKey($key) {
52
+        return apcu_exists($this->getPrefix() . $key);
53
+    }
54 54
 
55
-	public function remove($key) {
56
-		return apcu_delete($this->getPrefix() . $key);
57
-	}
55
+    public function remove($key) {
56
+        return apcu_delete($this->getPrefix() . $key);
57
+    }
58 58
 
59
-	public function clear($prefix = '') {
60
-		$ns = $this->getPrefix() . $prefix;
61
-		$ns = preg_quote($ns, '/');
62
-		if(class_exists('\APCIterator')) {
63
-			$iter = new \APCIterator('user', '/^' . $ns . '/', APC_ITER_KEY);
64
-		} else {
65
-			$iter = new \APCUIterator('/^' . $ns . '/', APC_ITER_KEY);
66
-		}
67
-		return apcu_delete($iter);
68
-	}
59
+    public function clear($prefix = '') {
60
+        $ns = $this->getPrefix() . $prefix;
61
+        $ns = preg_quote($ns, '/');
62
+        if(class_exists('\APCIterator')) {
63
+            $iter = new \APCIterator('user', '/^' . $ns . '/', APC_ITER_KEY);
64
+        } else {
65
+            $iter = new \APCUIterator('/^' . $ns . '/', APC_ITER_KEY);
66
+        }
67
+        return apcu_delete($iter);
68
+    }
69 69
 
70
-	/**
71
-	 * Set a value in the cache if it's not already stored
72
-	 *
73
-	 * @param string $key
74
-	 * @param mixed $value
75
-	 * @param int $ttl Time To Live in seconds. Defaults to 60*60*24
76
-	 * @return bool
77
-	 */
78
-	public function add($key, $value, $ttl = 0) {
79
-		return apcu_add($this->getPrefix() . $key, $value, $ttl);
80
-	}
70
+    /**
71
+     * Set a value in the cache if it's not already stored
72
+     *
73
+     * @param string $key
74
+     * @param mixed $value
75
+     * @param int $ttl Time To Live in seconds. Defaults to 60*60*24
76
+     * @return bool
77
+     */
78
+    public function add($key, $value, $ttl = 0) {
79
+        return apcu_add($this->getPrefix() . $key, $value, $ttl);
80
+    }
81 81
 
82
-	/**
83
-	 * Increase a stored number
84
-	 *
85
-	 * @param string $key
86
-	 * @param int $step
87
-	 * @return int | bool
88
-	 */
89
-	public function inc($key, $step = 1) {
90
-		$this->add($key, 0);
91
-		/**
92
-		 * TODO - hack around a PHP 7 specific issue in APCu
93
-		 *
94
-		 * on PHP 7 the apcu_inc method on a non-existing object will increment
95
-		 * "0" and result in "1" as value - therefore we check for existence
96
-		 * first
97
-		 *
98
-		 * on PHP 5.6 this is not the case
99
-		 *
100
-		 * see https://github.com/krakjoe/apcu/issues/183#issuecomment-244038221
101
-		 * for details
102
-		 */
103
-		return apcu_exists($this->getPrefix() . $key)
104
-			? apcu_inc($this->getPrefix() . $key, $step)
105
-			: false;
106
-	}
82
+    /**
83
+     * Increase a stored number
84
+     *
85
+     * @param string $key
86
+     * @param int $step
87
+     * @return int | bool
88
+     */
89
+    public function inc($key, $step = 1) {
90
+        $this->add($key, 0);
91
+        /**
92
+         * TODO - hack around a PHP 7 specific issue in APCu
93
+         *
94
+         * on PHP 7 the apcu_inc method on a non-existing object will increment
95
+         * "0" and result in "1" as value - therefore we check for existence
96
+         * first
97
+         *
98
+         * on PHP 5.6 this is not the case
99
+         *
100
+         * see https://github.com/krakjoe/apcu/issues/183#issuecomment-244038221
101
+         * for details
102
+         */
103
+        return apcu_exists($this->getPrefix() . $key)
104
+            ? apcu_inc($this->getPrefix() . $key, $step)
105
+            : false;
106
+    }
107 107
 
108
-	/**
109
-	 * Decrease a stored number
110
-	 *
111
-	 * @param string $key
112
-	 * @param int $step
113
-	 * @return int | bool
114
-	 */
115
-	public function dec($key, $step = 1) {
116
-		/**
117
-		 * TODO - hack around a PHP 7 specific issue in APCu
118
-		 *
119
-		 * on PHP 7 the apcu_dec method on a non-existing object will decrement
120
-		 * "0" and result in "-1" as value - therefore we check for existence
121
-		 * first
122
-		 *
123
-		 * on PHP 5.6 this is not the case
124
-		 *
125
-		 * see https://github.com/krakjoe/apcu/issues/183#issuecomment-244038221
126
-		 * for details
127
-		 */
128
-		return apcu_exists($this->getPrefix() . $key)
129
-			? apcu_dec($this->getPrefix() . $key, $step)
130
-			: false;
131
-	}
108
+    /**
109
+     * Decrease a stored number
110
+     *
111
+     * @param string $key
112
+     * @param int $step
113
+     * @return int | bool
114
+     */
115
+    public function dec($key, $step = 1) {
116
+        /**
117
+         * TODO - hack around a PHP 7 specific issue in APCu
118
+         *
119
+         * on PHP 7 the apcu_dec method on a non-existing object will decrement
120
+         * "0" and result in "-1" as value - therefore we check for existence
121
+         * first
122
+         *
123
+         * on PHP 5.6 this is not the case
124
+         *
125
+         * see https://github.com/krakjoe/apcu/issues/183#issuecomment-244038221
126
+         * for details
127
+         */
128
+        return apcu_exists($this->getPrefix() . $key)
129
+            ? apcu_dec($this->getPrefix() . $key, $step)
130
+            : false;
131
+    }
132 132
 
133
-	/**
134
-	 * Compare and set
135
-	 *
136
-	 * @param string $key
137
-	 * @param mixed $old
138
-	 * @param mixed $new
139
-	 * @return bool
140
-	 */
141
-	public function cas($key, $old, $new) {
142
-		// apc only does cas for ints
143
-		if (is_int($old) and is_int($new)) {
144
-			return apcu_cas($this->getPrefix() . $key, $old, $new);
145
-		} else {
146
-			return $this->casEmulated($key, $old, $new);
147
-		}
148
-	}
133
+    /**
134
+     * Compare and set
135
+     *
136
+     * @param string $key
137
+     * @param mixed $old
138
+     * @param mixed $new
139
+     * @return bool
140
+     */
141
+    public function cas($key, $old, $new) {
142
+        // apc only does cas for ints
143
+        if (is_int($old) and is_int($new)) {
144
+            return apcu_cas($this->getPrefix() . $key, $old, $new);
145
+        } else {
146
+            return $this->casEmulated($key, $old, $new);
147
+        }
148
+    }
149 149
 
150
-	/**
151
-	 * @return bool
152
-	 */
153
-	static public function isAvailable() {
154
-		if (!extension_loaded('apcu')) {
155
-			return false;
156
-		} elseif (!\OC::$server->getIniWrapper()->getBool('apc.enabled')) {
157
-			return false;
158
-		} elseif (!\OC::$server->getIniWrapper()->getBool('apc.enable_cli') && \OC::$CLI) {
159
-			return false;
160
-		} elseif (
161
-				version_compare(phpversion('apc'), '4.0.6') === -1 &&
162
-				version_compare(phpversion('apcu'), '5.1.0') === -1
163
-		) {
164
-			return false;
165
-		} else {
166
-			return true;
167
-		}
168
-	}
150
+    /**
151
+     * @return bool
152
+     */
153
+    static public function isAvailable() {
154
+        if (!extension_loaded('apcu')) {
155
+            return false;
156
+        } elseif (!\OC::$server->getIniWrapper()->getBool('apc.enabled')) {
157
+            return false;
158
+        } elseif (!\OC::$server->getIniWrapper()->getBool('apc.enable_cli') && \OC::$CLI) {
159
+            return false;
160
+        } elseif (
161
+                version_compare(phpversion('apc'), '4.0.6') === -1 &&
162
+                version_compare(phpversion('apcu'), '5.1.0') === -1
163
+        ) {
164
+            return false;
165
+        } else {
166
+            return true;
167
+        }
168
+    }
169 169
 }
Please login to merge, or discard this patch.
Spacing   +14 added lines, -14 removed lines patch added patch discarded remove patch
@@ -37,7 +37,7 @@  discard block
 block discarded – undo
37 37
 	use CADTrait;
38 38
 
39 39
 	public function get($key) {
40
-		$result = apcu_fetch($this->getPrefix() . $key, $success);
40
+		$result = apcu_fetch($this->getPrefix().$key, $success);
41 41
 		if (!$success) {
42 42
 			return null;
43 43
 		}
@@ -45,24 +45,24 @@  discard block
 block discarded – undo
45 45
 	}
46 46
 
47 47
 	public function set($key, $value, $ttl = 0) {
48
-		return apcu_store($this->getPrefix() . $key, $value, $ttl);
48
+		return apcu_store($this->getPrefix().$key, $value, $ttl);
49 49
 	}
50 50
 
51 51
 	public function hasKey($key) {
52
-		return apcu_exists($this->getPrefix() . $key);
52
+		return apcu_exists($this->getPrefix().$key);
53 53
 	}
54 54
 
55 55
 	public function remove($key) {
56
-		return apcu_delete($this->getPrefix() . $key);
56
+		return apcu_delete($this->getPrefix().$key);
57 57
 	}
58 58
 
59 59
 	public function clear($prefix = '') {
60
-		$ns = $this->getPrefix() . $prefix;
60
+		$ns = $this->getPrefix().$prefix;
61 61
 		$ns = preg_quote($ns, '/');
62
-		if(class_exists('\APCIterator')) {
63
-			$iter = new \APCIterator('user', '/^' . $ns . '/', APC_ITER_KEY);
62
+		if (class_exists('\APCIterator')) {
63
+			$iter = new \APCIterator('user', '/^'.$ns.'/', APC_ITER_KEY);
64 64
 		} else {
65
-			$iter = new \APCUIterator('/^' . $ns . '/', APC_ITER_KEY);
65
+			$iter = new \APCUIterator('/^'.$ns.'/', APC_ITER_KEY);
66 66
 		}
67 67
 		return apcu_delete($iter);
68 68
 	}
@@ -76,7 +76,7 @@  discard block
 block discarded – undo
76 76
 	 * @return bool
77 77
 	 */
78 78
 	public function add($key, $value, $ttl = 0) {
79
-		return apcu_add($this->getPrefix() . $key, $value, $ttl);
79
+		return apcu_add($this->getPrefix().$key, $value, $ttl);
80 80
 	}
81 81
 
82 82
 	/**
@@ -100,8 +100,8 @@  discard block
 block discarded – undo
100 100
 		 * see https://github.com/krakjoe/apcu/issues/183#issuecomment-244038221
101 101
 		 * for details
102 102
 		 */
103
-		return apcu_exists($this->getPrefix() . $key)
104
-			? apcu_inc($this->getPrefix() . $key, $step)
103
+		return apcu_exists($this->getPrefix().$key)
104
+			? apcu_inc($this->getPrefix().$key, $step)
105 105
 			: false;
106 106
 	}
107 107
 
@@ -125,8 +125,8 @@  discard block
 block discarded – undo
125 125
 		 * see https://github.com/krakjoe/apcu/issues/183#issuecomment-244038221
126 126
 		 * for details
127 127
 		 */
128
-		return apcu_exists($this->getPrefix() . $key)
129
-			? apcu_dec($this->getPrefix() . $key, $step)
128
+		return apcu_exists($this->getPrefix().$key)
129
+			? apcu_dec($this->getPrefix().$key, $step)
130 130
 			: false;
131 131
 	}
132 132
 
@@ -141,7 +141,7 @@  discard block
 block discarded – undo
141 141
 	public function cas($key, $old, $new) {
142 142
 		// apc only does cas for ints
143 143
 		if (is_int($old) and is_int($new)) {
144
-			return apcu_cas($this->getPrefix() . $key, $old, $new);
144
+			return apcu_cas($this->getPrefix().$key, $old, $new);
145 145
 		} else {
146 146
 			return $this->casEmulated($key, $old, $new);
147 147
 		}
Please login to merge, or discard this patch.
lib/private/Memcache/ArrayCache.php 2 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -65,7 +65,7 @@
 block discarded – undo
65 65
 	 * Set a value in the cache if it's not already stored
66 66
 	 *
67 67
 	 * @param string $key
68
-	 * @param mixed $value
68
+	 * @param integer $value
69 69
 	 * @param int $ttl Time To Live in seconds. Defaults to 60*60*24
70 70
 	 * @return bool
71 71
 	 */
Please login to merge, or discard this patch.
Indentation   +117 added lines, -117 removed lines patch added patch discarded remove patch
@@ -27,133 +27,133 @@
 block discarded – undo
27 27
 use OCP\IMemcache;
28 28
 
29 29
 class ArrayCache extends Cache implements IMemcache {
30
-	/** @var array Array with the cached data */
31
-	protected $cachedData = array();
30
+    /** @var array Array with the cached data */
31
+    protected $cachedData = array();
32 32
 
33
-	use CADTrait;
33
+    use CADTrait;
34 34
 
35
-	/**
36
-	 * {@inheritDoc}
37
-	 */
38
-	public function get($key) {
39
-		if ($this->hasKey($key)) {
40
-			return $this->cachedData[$key];
41
-		}
42
-		return null;
43
-	}
35
+    /**
36
+     * {@inheritDoc}
37
+     */
38
+    public function get($key) {
39
+        if ($this->hasKey($key)) {
40
+            return $this->cachedData[$key];
41
+        }
42
+        return null;
43
+    }
44 44
 
45
-	/**
46
-	 * {@inheritDoc}
47
-	 */
48
-	public function set($key, $value, $ttl = 0) {
49
-		$this->cachedData[$key] = $value;
50
-		return true;
51
-	}
45
+    /**
46
+     * {@inheritDoc}
47
+     */
48
+    public function set($key, $value, $ttl = 0) {
49
+        $this->cachedData[$key] = $value;
50
+        return true;
51
+    }
52 52
 
53
-	/**
54
-	 * {@inheritDoc}
55
-	 */
56
-	public function hasKey($key) {
57
-		return isset($this->cachedData[$key]);
58
-	}
53
+    /**
54
+     * {@inheritDoc}
55
+     */
56
+    public function hasKey($key) {
57
+        return isset($this->cachedData[$key]);
58
+    }
59 59
 
60
-	/**
61
-	 * {@inheritDoc}
62
-	 */
63
-	public function remove($key) {
64
-		unset($this->cachedData[$key]);
65
-		return true;
66
-	}
60
+    /**
61
+     * {@inheritDoc}
62
+     */
63
+    public function remove($key) {
64
+        unset($this->cachedData[$key]);
65
+        return true;
66
+    }
67 67
 
68
-	/**
69
-	 * {@inheritDoc}
70
-	 */
71
-	public function clear($prefix = '') {
72
-		if ($prefix === '') {
73
-			$this->cachedData = [];
74
-			return true;
75
-		}
68
+    /**
69
+     * {@inheritDoc}
70
+     */
71
+    public function clear($prefix = '') {
72
+        if ($prefix === '') {
73
+            $this->cachedData = [];
74
+            return true;
75
+        }
76 76
 
77
-		foreach ($this->cachedData as $key => $value) {
78
-			if (strpos($key, $prefix) === 0) {
79
-				$this->remove($key);
80
-			}
81
-		}
82
-		return true;
83
-	}
77
+        foreach ($this->cachedData as $key => $value) {
78
+            if (strpos($key, $prefix) === 0) {
79
+                $this->remove($key);
80
+            }
81
+        }
82
+        return true;
83
+    }
84 84
 
85
-	/**
86
-	 * Set a value in the cache if it's not already stored
87
-	 *
88
-	 * @param string $key
89
-	 * @param mixed $value
90
-	 * @param int $ttl Time To Live in seconds. Defaults to 60*60*24
91
-	 * @return bool
92
-	 */
93
-	public function add($key, $value, $ttl = 0) {
94
-		// since this cache is not shared race conditions aren't an issue
95
-		if ($this->hasKey($key)) {
96
-			return false;
97
-		} else {
98
-			return $this->set($key, $value, $ttl);
99
-		}
100
-	}
85
+    /**
86
+     * Set a value in the cache if it's not already stored
87
+     *
88
+     * @param string $key
89
+     * @param mixed $value
90
+     * @param int $ttl Time To Live in seconds. Defaults to 60*60*24
91
+     * @return bool
92
+     */
93
+    public function add($key, $value, $ttl = 0) {
94
+        // since this cache is not shared race conditions aren't an issue
95
+        if ($this->hasKey($key)) {
96
+            return false;
97
+        } else {
98
+            return $this->set($key, $value, $ttl);
99
+        }
100
+    }
101 101
 
102
-	/**
103
-	 * Increase a stored number
104
-	 *
105
-	 * @param string $key
106
-	 * @param int $step
107
-	 * @return int | bool
108
-	 */
109
-	public function inc($key, $step = 1) {
110
-		$oldValue = $this->get($key);
111
-		if (is_int($oldValue)) {
112
-			$this->set($key, $oldValue + $step);
113
-			return $oldValue + $step;
114
-		} else {
115
-			$success = $this->add($key, $step);
116
-			return ($success) ? $step : false;
117
-		}
118
-	}
102
+    /**
103
+     * Increase a stored number
104
+     *
105
+     * @param string $key
106
+     * @param int $step
107
+     * @return int | bool
108
+     */
109
+    public function inc($key, $step = 1) {
110
+        $oldValue = $this->get($key);
111
+        if (is_int($oldValue)) {
112
+            $this->set($key, $oldValue + $step);
113
+            return $oldValue + $step;
114
+        } else {
115
+            $success = $this->add($key, $step);
116
+            return ($success) ? $step : false;
117
+        }
118
+    }
119 119
 
120
-	/**
121
-	 * Decrease a stored number
122
-	 *
123
-	 * @param string $key
124
-	 * @param int $step
125
-	 * @return int | bool
126
-	 */
127
-	public function dec($key, $step = 1) {
128
-		$oldValue = $this->get($key);
129
-		if (is_int($oldValue)) {
130
-			$this->set($key, $oldValue - $step);
131
-			return $oldValue - $step;
132
-		} else {
133
-			return false;
134
-		}
135
-	}
120
+    /**
121
+     * Decrease a stored number
122
+     *
123
+     * @param string $key
124
+     * @param int $step
125
+     * @return int | bool
126
+     */
127
+    public function dec($key, $step = 1) {
128
+        $oldValue = $this->get($key);
129
+        if (is_int($oldValue)) {
130
+            $this->set($key, $oldValue - $step);
131
+            return $oldValue - $step;
132
+        } else {
133
+            return false;
134
+        }
135
+    }
136 136
 
137
-	/**
138
-	 * Compare and set
139
-	 *
140
-	 * @param string $key
141
-	 * @param mixed $old
142
-	 * @param mixed $new
143
-	 * @return bool
144
-	 */
145
-	public function cas($key, $old, $new) {
146
-		if ($this->get($key) === $old) {
147
-			return $this->set($key, $new);
148
-		} else {
149
-			return false;
150
-		}
151
-	}
137
+    /**
138
+     * Compare and set
139
+     *
140
+     * @param string $key
141
+     * @param mixed $old
142
+     * @param mixed $new
143
+     * @return bool
144
+     */
145
+    public function cas($key, $old, $new) {
146
+        if ($this->get($key) === $old) {
147
+            return $this->set($key, $new);
148
+        } else {
149
+            return false;
150
+        }
151
+    }
152 152
 
153
-	/**
154
-	 * {@inheritDoc}
155
-	 */
156
-	static public function isAvailable() {
157
-		return true;
158
-	}
153
+    /**
154
+     * {@inheritDoc}
155
+     */
156
+    static public function isAvailable() {
157
+        return true;
158
+    }
159 159
 }
Please login to merge, or discard this patch.
apps/files_external/lib/Lib/Storage/SMB.php 3 patches
Doc Comments   +3 added lines patch added patch discarded remove patch
@@ -498,6 +498,9 @@
 block discarded – undo
498 498
 		});
499 499
 	}
500 500
 
501
+	/**
502
+	 * @param string $path
503
+	 */
501 504
 	public function notify($path) {
502 505
 		$path = '/' . ltrim($path, '/');
503 506
 		$shareNotifyHandler = $this->share->notify($this->buildPath($path));
Please login to merge, or discard this patch.
Spacing   +15 added lines, -15 removed lines patch added patch discarded remove patch
@@ -88,7 +88,7 @@  discard block
 block discarded – undo
88 88
 
89 89
 			$this->root = isset($params['root']) ? $params['root'] : '/';
90 90
 			if (!$this->root || $this->root[0] !== '/') {
91
-				$this->root = '/' . $this->root;
91
+				$this->root = '/'.$this->root;
92 92
 			}
93 93
 			if (substr($this->root, -1, 1) !== '/') {
94 94
 				$this->root .= '/';
@@ -107,7 +107,7 @@  discard block
 block discarded – undo
107 107
 		// FIXME: double slash to keep compatible with the old storage ids,
108 108
 		// failure to do so will lead to creation of a new storage id and
109 109
 		// loss of shares from the storage
110
-		return 'smb::' . $this->server->getUser() . '@' . $this->server->getHost() . '//' . $this->share->getName() . '/' . $this->root;
110
+		return 'smb::'.$this->server->getUser().'@'.$this->server->getHost().'//'.$this->share->getName().'/'.$this->root;
111 111
 	}
112 112
 
113 113
 	/**
@@ -115,7 +115,7 @@  discard block
 block discarded – undo
115 115
 	 * @return string
116 116
 	 */
117 117
 	protected function buildPath($path) {
118
-		return Filesystem::normalizePath($this->root . '/' . $path, true, false, true);
118
+		return Filesystem::normalizePath($this->root.'/'.$path, true, false, true);
119 119
 	}
120 120
 
121 121
 	protected function relativePath($fullPath) {
@@ -156,19 +156,19 @@  discard block
 block discarded – undo
156 156
 			$path = $this->buildPath($path);
157 157
 			$files = $this->share->dir($path);
158 158
 			foreach ($files as $file) {
159
-				$this->statCache[$path . '/' . $file->getName()] = $file;
159
+				$this->statCache[$path.'/'.$file->getName()] = $file;
160 160
 			}
161
-			return array_filter($files, function (IFileInfo $file) {
161
+			return array_filter($files, function(IFileInfo $file) {
162 162
 				try {
163 163
 					if ($file->isHidden()) {
164
-						\OC::$server->getLogger()->debug('hiding hidden file ' . $file->getName());
164
+						\OC::$server->getLogger()->debug('hiding hidden file '.$file->getName());
165 165
 					}
166 166
 					return !$file->isHidden();
167 167
 				} catch (ForbiddenException $e) {
168
-					\OC::$server->getLogger()->logException($e, ['level' => Util::DEBUG, 'message' => 'Hiding forbidden entry ' . $file->getName()]);
168
+					\OC::$server->getLogger()->logException($e, ['level' => Util::DEBUG, 'message' => 'Hiding forbidden entry '.$file->getName()]);
169 169
 					return false;
170 170
 				} catch (NotFoundException $e) {
171
-					\OC::$server->getLogger()->logException($e, ['level' => Util::DEBUG, 'message' => 'Hiding not found entry ' . $file->getName()]);
171
+					\OC::$server->getLogger()->logException($e, ['level' => Util::DEBUG, 'message' => 'Hiding not found entry '.$file->getName()]);
172 172
 					return false;
173 173
 				}
174 174
 			});
@@ -352,7 +352,7 @@  discard block
 block discarded – undo
352 352
 				case 'w':
353 353
 				case 'wb':
354 354
 					$source = $this->share->write($fullPath);
355
-					return CallBackWrapper::wrap($source, null, null, function () use ($fullPath) {
355
+					return CallBackWrapper::wrap($source, null, null, function() use ($fullPath) {
356 356
 						unset($this->statCache[$fullPath]);
357 357
 					});
358 358
 				case 'a':
@@ -384,7 +384,7 @@  discard block
 block discarded – undo
384 384
 					}
385 385
 					$source = fopen($tmpFile, $mode);
386 386
 					$share = $this->share;
387
-					return CallbackWrapper::wrap($source, null, null, function () use ($tmpFile, $fullPath, $share) {
387
+					return CallbackWrapper::wrap($source, null, null, function() use ($tmpFile, $fullPath, $share) {
388 388
 						unset($this->statCache[$fullPath]);
389 389
 						$share->put($tmpFile, $fullPath);
390 390
 						unlink($tmpFile);
@@ -411,7 +411,7 @@  discard block
 block discarded – undo
411 411
 			$content = $this->share->dir($this->buildPath($path));
412 412
 			foreach ($content as $file) {
413 413
 				if ($file->isDirectory()) {
414
-					$this->rmdir($path . '/' . $file->getName());
414
+					$this->rmdir($path.'/'.$file->getName());
415 415
 				} else {
416 416
 					$this->share->del($file->getPath());
417 417
 				}
@@ -450,7 +450,7 @@  discard block
 block discarded – undo
450 450
 		} catch (ForbiddenException $e) {
451 451
 			return false;
452 452
 		}
453
-		$names = array_map(function ($info) {
453
+		$names = array_map(function($info) {
454 454
 			/** @var \Icewind\SMB\IFileInfo $info */
455 455
 			return $info->getName();
456 456
 		}, $files);
@@ -533,7 +533,7 @@  discard block
 block discarded – undo
533 533
 	 */
534 534
 	public static function checkDependencies() {
535 535
 		return (
536
-			(bool)\OC_Helper::findBinaryPath('smbclient')
536
+			(bool) \OC_Helper::findBinaryPath('smbclient')
537 537
 			|| Server::NativeAvailable()
538 538
 		) ? true : ['smbclient'];
539 539
 	}
@@ -553,7 +553,7 @@  discard block
 block discarded – undo
553 553
 	}
554 554
 
555 555
 	public function listen($path, callable $callback) {
556
-		$this->notify($path)->listen(function (IChange $change) use ($callback) {
556
+		$this->notify($path)->listen(function(IChange $change) use ($callback) {
557 557
 			if ($change instanceof IRenameChange) {
558 558
 				return $callback($change->getType(), $change->getPath(), $change->getTargetPath());
559 559
 			} else {
@@ -563,7 +563,7 @@  discard block
 block discarded – undo
563 563
 	}
564 564
 
565 565
 	public function notify($path) {
566
-		$path = '/' . ltrim($path, '/');
566
+		$path = '/'.ltrim($path, '/');
567 567
 		$shareNotifyHandler = $this->share->notify($this->buildPath($path));
568 568
 		return new SMBNotifyHandler($shareNotifyHandler, $this->root);
569 569
 	}
Please login to merge, or discard this patch.
Indentation   +516 added lines, -516 removed lines patch added patch discarded remove patch
@@ -58,520 +58,520 @@
 block discarded – undo
58 58
 use OCP\Util;
59 59
 
60 60
 class SMB extends Common implements INotifyStorage {
61
-	/**
62
-	 * @var \Icewind\SMB\Server
63
-	 */
64
-	protected $server;
65
-
66
-	/**
67
-	 * @var \Icewind\SMB\Share
68
-	 */
69
-	protected $share;
70
-
71
-	/**
72
-	 * @var string
73
-	 */
74
-	protected $root;
75
-
76
-	/**
77
-	 * @var \Icewind\SMB\FileInfo[]
78
-	 */
79
-	protected $statCache;
80
-
81
-	public function __construct($params) {
82
-		if (isset($params['host']) && isset($params['user']) && isset($params['password']) && isset($params['share'])) {
83
-			if (Server::NativeAvailable()) {
84
-				$this->server = new NativeServer($params['host'], $params['user'], $params['password']);
85
-			} else {
86
-				$this->server = new Server($params['host'], $params['user'], $params['password']);
87
-			}
88
-			$this->share = $this->server->getShare(trim($params['share'], '/'));
89
-
90
-			$this->root = isset($params['root']) ? $params['root'] : '/';
91
-			if (!$this->root || $this->root[0] !== '/') {
92
-				$this->root = '/' . $this->root;
93
-			}
94
-			if (substr($this->root, -1, 1) !== '/') {
95
-				$this->root .= '/';
96
-			}
97
-		} else {
98
-			throw new \Exception('Invalid configuration');
99
-		}
100
-		$this->statCache = new CappedMemoryCache();
101
-		parent::__construct($params);
102
-	}
103
-
104
-	/**
105
-	 * @return string
106
-	 */
107
-	public function getId() {
108
-		// FIXME: double slash to keep compatible with the old storage ids,
109
-		// failure to do so will lead to creation of a new storage id and
110
-		// loss of shares from the storage
111
-		return 'smb::' . $this->server->getUser() . '@' . $this->server->getHost() . '//' . $this->share->getName() . '/' . $this->root;
112
-	}
113
-
114
-	/**
115
-	 * @param string $path
116
-	 * @return string
117
-	 */
118
-	protected function buildPath($path) {
119
-		return Filesystem::normalizePath($this->root . '/' . $path, true, false, true);
120
-	}
121
-
122
-	protected function relativePath($fullPath) {
123
-		if ($fullPath === $this->root) {
124
-			return '';
125
-		} else if (substr($fullPath, 0, strlen($this->root)) === $this->root) {
126
-			return substr($fullPath, strlen($this->root));
127
-		} else {
128
-			return null;
129
-		}
130
-	}
131
-
132
-	/**
133
-	 * @param string $path
134
-	 * @return \Icewind\SMB\IFileInfo
135
-	 * @throws StorageNotAvailableException
136
-	 */
137
-	protected function getFileInfo($path) {
138
-		try {
139
-			$path = $this->buildPath($path);
140
-			if (!isset($this->statCache[$path])) {
141
-				$this->statCache[$path] = $this->share->stat($path);
142
-			}
143
-			return $this->statCache[$path];
144
-		} catch (ConnectException $e) {
145
-			\OC::$server->getLogger()->logException($e, ['message' => 'Error while getting file info']);
146
-			throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
147
-		}
148
-	}
149
-
150
-	/**
151
-	 * @param string $path
152
-	 * @return \Icewind\SMB\IFileInfo[]
153
-	 * @throws StorageNotAvailableException
154
-	 */
155
-	protected function getFolderContents($path) {
156
-		try {
157
-			$path = $this->buildPath($path);
158
-			$files = $this->share->dir($path);
159
-			foreach ($files as $file) {
160
-				$this->statCache[$path . '/' . $file->getName()] = $file;
161
-			}
162
-			return array_filter($files, function (IFileInfo $file) {
163
-				try {
164
-					if ($file->isHidden()) {
165
-						\OC::$server->getLogger()->debug('hiding hidden file ' . $file->getName());
166
-					}
167
-					return !$file->isHidden();
168
-				} catch (ForbiddenException $e) {
169
-					\OC::$server->getLogger()->logException($e, ['level' => Util::DEBUG, 'message' => 'Hiding forbidden entry ' . $file->getName()]);
170
-					return false;
171
-				} catch (NotFoundException $e) {
172
-					\OC::$server->getLogger()->logException($e, ['level' => Util::DEBUG, 'message' => 'Hiding not found entry ' . $file->getName()]);
173
-					return false;
174
-				}
175
-			});
176
-		} catch (ConnectException $e) {
177
-			\OC::$server->getLogger()->logException($e, ['message' => 'Error while getting folder content']);
178
-			throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
179
-		}
180
-	}
181
-
182
-	/**
183
-	 * @param \Icewind\SMB\IFileInfo $info
184
-	 * @return array
185
-	 */
186
-	protected function formatInfo($info) {
187
-		$result = [
188
-			'size' => $info->getSize(),
189
-			'mtime' => $info->getMTime(),
190
-		];
191
-		if ($info->isDirectory()) {
192
-			$result['type'] = 'dir';
193
-		} else {
194
-			$result['type'] = 'file';
195
-		}
196
-		return $result;
197
-	}
198
-
199
-	/**
200
-	 * Rename the files. If the source or the target is the root, the rename won't happen.
201
-	 *
202
-	 * @param string $source the old name of the path
203
-	 * @param string $target the new name of the path
204
-	 * @return bool true if the rename is successful, false otherwise
205
-	 */
206
-	public function rename($source, $target, $retry = true) {
207
-		if ($this->isRootDir($source) || $this->isRootDir($target)) {
208
-			return false;
209
-		}
210
-
211
-		$absoluteSource = $this->buildPath($source);
212
-		$absoluteTarget = $this->buildPath($target);
213
-		try {
214
-			$result = $this->share->rename($absoluteSource, $absoluteTarget);
215
-		} catch (AlreadyExistsException $e) {
216
-			if ($retry) {
217
-				$this->remove($target);
218
-				$result = $this->share->rename($absoluteSource, $absoluteTarget, false);
219
-			} else {
220
-				\OC::$server->getLogger()->logException($e, ['level' => ILogger::WARN]);
221
-				return false;
222
-			}
223
-		} catch (InvalidArgumentException $e) {
224
-			if ($retry) {
225
-				$this->remove($target);
226
-				$result = $this->share->rename($absoluteSource, $absoluteTarget, false);
227
-			} else {
228
-				\OC::$server->getLogger()->logException($e, ['level' => ILogger::WARN]);
229
-				return false;
230
-			}
231
-		} catch (\Exception $e) {
232
-			\OC::$server->getLogger()->logException($e, ['level' => Util::WARN]);
233
-			return false;
234
-		}
235
-		unset($this->statCache[$absoluteSource], $this->statCache[$absoluteTarget]);
236
-		return $result;
237
-	}
238
-
239
-	public function stat($path, $retry = true) {
240
-		try {
241
-			$result = $this->formatInfo($this->getFileInfo($path));
242
-		} catch (ForbiddenException $e) {
243
-			return false;
244
-		} catch (NotFoundException $e) {
245
-			return false;
246
-		} catch (TimedOutException $e) {
247
-			if ($retry) {
248
-				return $this->stat($path, false);
249
-			} else {
250
-				throw $e;
251
-			}
252
-		}
253
-		if ($this->remoteIsShare() && $this->isRootDir($path)) {
254
-			$result['mtime'] = $this->shareMTime();
255
-		}
256
-		return $result;
257
-	}
258
-
259
-	/**
260
-	 * get the best guess for the modification time of the share
261
-	 *
262
-	 * @return int
263
-	 */
264
-	private function shareMTime() {
265
-		$highestMTime = 0;
266
-		$files = $this->share->dir($this->root);
267
-		foreach ($files as $fileInfo) {
268
-			try {
269
-				if ($fileInfo->getMTime() > $highestMTime) {
270
-					$highestMTime = $fileInfo->getMTime();
271
-				}
272
-			} catch (NotFoundException $e) {
273
-				// Ignore this, can happen on unavailable DFS shares
274
-			}
275
-		}
276
-		return $highestMTime;
277
-	}
278
-
279
-	/**
280
-	 * Check if the path is our root dir (not the smb one)
281
-	 *
282
-	 * @param string $path the path
283
-	 * @return bool
284
-	 */
285
-	private function isRootDir($path) {
286
-		return $path === '' || $path === '/' || $path === '.';
287
-	}
288
-
289
-	/**
290
-	 * Check if our root points to a smb share
291
-	 *
292
-	 * @return bool true if our root points to a share false otherwise
293
-	 */
294
-	private function remoteIsShare() {
295
-		return $this->share->getName() && (!$this->root || $this->root === '/');
296
-	}
297
-
298
-	/**
299
-	 * @param string $path
300
-	 * @return bool
301
-	 */
302
-	public function unlink($path) {
303
-		if ($this->isRootDir($path)) {
304
-			return false;
305
-		}
306
-
307
-		try {
308
-			if ($this->is_dir($path)) {
309
-				return $this->rmdir($path);
310
-			} else {
311
-				$path = $this->buildPath($path);
312
-				unset($this->statCache[$path]);
313
-				$this->share->del($path);
314
-				return true;
315
-			}
316
-		} catch (NotFoundException $e) {
317
-			return false;
318
-		} catch (ForbiddenException $e) {
319
-			return false;
320
-		} catch (ConnectException $e) {
321
-			\OC::$server->getLogger()->logException($e, ['message' => 'Error while deleting file']);
322
-			throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
323
-		}
324
-	}
325
-
326
-	/**
327
-	 * check if a file or folder has been updated since $time
328
-	 *
329
-	 * @param string $path
330
-	 * @param int $time
331
-	 * @return bool
332
-	 */
333
-	public function hasUpdated($path, $time) {
334
-		if (!$path and $this->root === '/') {
335
-			// mtime doesn't work for shares, but giving the nature of the backend,
336
-			// doing a full update is still just fast enough
337
-			return true;
338
-		} else {
339
-			$actualTime = $this->filemtime($path);
340
-			return $actualTime > $time;
341
-		}
342
-	}
343
-
344
-	/**
345
-	 * @param string $path
346
-	 * @param string $mode
347
-	 * @return resource|false
348
-	 */
349
-	public function fopen($path, $mode) {
350
-		$fullPath = $this->buildPath($path);
351
-		try {
352
-			switch ($mode) {
353
-				case 'r':
354
-				case 'rb':
355
-					if (!$this->file_exists($path)) {
356
-						return false;
357
-					}
358
-					return $this->share->read($fullPath);
359
-				case 'w':
360
-				case 'wb':
361
-					$source = $this->share->write($fullPath);
362
-					return CallBackWrapper::wrap($source, null, null, function () use ($fullPath) {
363
-						unset($this->statCache[$fullPath]);
364
-					});
365
-				case 'a':
366
-				case 'ab':
367
-				case 'r+':
368
-				case 'w+':
369
-				case 'wb+':
370
-				case 'a+':
371
-				case 'x':
372
-				case 'x+':
373
-				case 'c':
374
-				case 'c+':
375
-					//emulate these
376
-					if (strrpos($path, '.') !== false) {
377
-						$ext = substr($path, strrpos($path, '.'));
378
-					} else {
379
-						$ext = '';
380
-					}
381
-					if ($this->file_exists($path)) {
382
-						if (!$this->isUpdatable($path)) {
383
-							return false;
384
-						}
385
-						$tmpFile = $this->getCachedFile($path);
386
-					} else {
387
-						if (!$this->isCreatable(dirname($path))) {
388
-							return false;
389
-						}
390
-						$tmpFile = \OCP\Files::tmpFile($ext);
391
-					}
392
-					$source = fopen($tmpFile, $mode);
393
-					$share = $this->share;
394
-					return CallbackWrapper::wrap($source, null, null, function () use ($tmpFile, $fullPath, $share) {
395
-						unset($this->statCache[$fullPath]);
396
-						$share->put($tmpFile, $fullPath);
397
-						unlink($tmpFile);
398
-					});
399
-			}
400
-			return false;
401
-		} catch (NotFoundException $e) {
402
-			return false;
403
-		} catch (ForbiddenException $e) {
404
-			return false;
405
-		} catch (ConnectException $e) {
406
-			\OC::$server->getLogger()->logException($e, ['message' => 'Error while opening file']);
407
-			throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
408
-		}
409
-	}
410
-
411
-	public function rmdir($path) {
412
-		if ($this->isRootDir($path)) {
413
-			return false;
414
-		}
415
-
416
-		try {
417
-			$this->statCache = array();
418
-			$content = $this->share->dir($this->buildPath($path));
419
-			foreach ($content as $file) {
420
-				if ($file->isDirectory()) {
421
-					$this->rmdir($path . '/' . $file->getName());
422
-				} else {
423
-					$this->share->del($file->getPath());
424
-				}
425
-			}
426
-			$this->share->rmdir($this->buildPath($path));
427
-			return true;
428
-		} catch (NotFoundException $e) {
429
-			return false;
430
-		} catch (ForbiddenException $e) {
431
-			return false;
432
-		} catch (ConnectException $e) {
433
-			\OC::$server->getLogger()->logException($e, ['message' => 'Error while removing folder']);
434
-			throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
435
-		}
436
-	}
437
-
438
-	public function touch($path, $time = null) {
439
-		try {
440
-			if (!$this->file_exists($path)) {
441
-				$fh = $this->share->write($this->buildPath($path));
442
-				fclose($fh);
443
-				return true;
444
-			}
445
-			return false;
446
-		} catch (ConnectException $e) {
447
-			\OC::$server->getLogger()->logException($e, ['message' => 'Error while creating file']);
448
-			throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
449
-		}
450
-	}
451
-
452
-	public function opendir($path) {
453
-		try {
454
-			$files = $this->getFolderContents($path);
455
-		} catch (NotFoundException $e) {
456
-			return false;
457
-		} catch (ForbiddenException $e) {
458
-			return false;
459
-		}
460
-		$names = array_map(function ($info) {
461
-			/** @var \Icewind\SMB\IFileInfo $info */
462
-			return $info->getName();
463
-		}, $files);
464
-		return IteratorDirectory::wrap($names);
465
-	}
466
-
467
-	public function filetype($path) {
468
-		try {
469
-			return $this->getFileInfo($path)->isDirectory() ? 'dir' : 'file';
470
-		} catch (NotFoundException $e) {
471
-			return false;
472
-		} catch (ForbiddenException $e) {
473
-			return false;
474
-		}
475
-	}
476
-
477
-	public function mkdir($path) {
478
-		$path = $this->buildPath($path);
479
-		try {
480
-			$this->share->mkdir($path);
481
-			return true;
482
-		} catch (ConnectException $e) {
483
-			\OC::$server->getLogger()->logException($e, ['message' => 'Error while creating folder']);
484
-			throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
485
-		} catch (Exception $e) {
486
-			return false;
487
-		}
488
-	}
489
-
490
-	public function file_exists($path) {
491
-		try {
492
-			$this->getFileInfo($path);
493
-			return true;
494
-		} catch (NotFoundException $e) {
495
-			return false;
496
-		} catch (ForbiddenException $e) {
497
-			return false;
498
-		} catch (ConnectException $e) {
499
-			throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
500
-		}
501
-	}
502
-
503
-	public function isReadable($path) {
504
-		try {
505
-			$info = $this->getFileInfo($path);
506
-			return !$info->isHidden();
507
-		} catch (NotFoundException $e) {
508
-			return false;
509
-		} catch (ForbiddenException $e) {
510
-			return false;
511
-		}
512
-	}
513
-
514
-	public function isUpdatable($path) {
515
-		try {
516
-			$info = $this->getFileInfo($path);
517
-			// following windows behaviour for read-only folders: they can be written into
518
-			// (https://support.microsoft.com/en-us/kb/326549 - "cause" section)
519
-			return !$info->isHidden() && (!$info->isReadOnly() || $this->is_dir($path));
520
-		} catch (NotFoundException $e) {
521
-			return false;
522
-		} catch (ForbiddenException $e) {
523
-			return false;
524
-		}
525
-	}
526
-
527
-	public function isDeletable($path) {
528
-		try {
529
-			$info = $this->getFileInfo($path);
530
-			return !$info->isHidden() && !$info->isReadOnly();
531
-		} catch (NotFoundException $e) {
532
-			return false;
533
-		} catch (ForbiddenException $e) {
534
-			return false;
535
-		}
536
-	}
537
-
538
-	/**
539
-	 * check if smbclient is installed
540
-	 */
541
-	public static function checkDependencies() {
542
-		return (
543
-			(bool)\OC_Helper::findBinaryPath('smbclient')
544
-			|| Server::NativeAvailable()
545
-		) ? true : ['smbclient'];
546
-	}
547
-
548
-	/**
549
-	 * Test a storage for availability
550
-	 *
551
-	 * @return bool
552
-	 */
553
-	public function test() {
554
-		try {
555
-			return parent::test();
556
-		} catch (Exception $e) {
557
-			\OC::$server->getLogger()->logException($e);
558
-			return false;
559
-		}
560
-	}
561
-
562
-	public function listen($path, callable $callback) {
563
-		$this->notify($path)->listen(function (IChange $change) use ($callback) {
564
-			if ($change instanceof IRenameChange) {
565
-				return $callback($change->getType(), $change->getPath(), $change->getTargetPath());
566
-			} else {
567
-				return $callback($change->getType(), $change->getPath());
568
-			}
569
-		});
570
-	}
571
-
572
-	public function notify($path) {
573
-		$path = '/' . ltrim($path, '/');
574
-		$shareNotifyHandler = $this->share->notify($this->buildPath($path));
575
-		return new SMBNotifyHandler($shareNotifyHandler, $this->root);
576
-	}
61
+    /**
62
+     * @var \Icewind\SMB\Server
63
+     */
64
+    protected $server;
65
+
66
+    /**
67
+     * @var \Icewind\SMB\Share
68
+     */
69
+    protected $share;
70
+
71
+    /**
72
+     * @var string
73
+     */
74
+    protected $root;
75
+
76
+    /**
77
+     * @var \Icewind\SMB\FileInfo[]
78
+     */
79
+    protected $statCache;
80
+
81
+    public function __construct($params) {
82
+        if (isset($params['host']) && isset($params['user']) && isset($params['password']) && isset($params['share'])) {
83
+            if (Server::NativeAvailable()) {
84
+                $this->server = new NativeServer($params['host'], $params['user'], $params['password']);
85
+            } else {
86
+                $this->server = new Server($params['host'], $params['user'], $params['password']);
87
+            }
88
+            $this->share = $this->server->getShare(trim($params['share'], '/'));
89
+
90
+            $this->root = isset($params['root']) ? $params['root'] : '/';
91
+            if (!$this->root || $this->root[0] !== '/') {
92
+                $this->root = '/' . $this->root;
93
+            }
94
+            if (substr($this->root, -1, 1) !== '/') {
95
+                $this->root .= '/';
96
+            }
97
+        } else {
98
+            throw new \Exception('Invalid configuration');
99
+        }
100
+        $this->statCache = new CappedMemoryCache();
101
+        parent::__construct($params);
102
+    }
103
+
104
+    /**
105
+     * @return string
106
+     */
107
+    public function getId() {
108
+        // FIXME: double slash to keep compatible with the old storage ids,
109
+        // failure to do so will lead to creation of a new storage id and
110
+        // loss of shares from the storage
111
+        return 'smb::' . $this->server->getUser() . '@' . $this->server->getHost() . '//' . $this->share->getName() . '/' . $this->root;
112
+    }
113
+
114
+    /**
115
+     * @param string $path
116
+     * @return string
117
+     */
118
+    protected function buildPath($path) {
119
+        return Filesystem::normalizePath($this->root . '/' . $path, true, false, true);
120
+    }
121
+
122
+    protected function relativePath($fullPath) {
123
+        if ($fullPath === $this->root) {
124
+            return '';
125
+        } else if (substr($fullPath, 0, strlen($this->root)) === $this->root) {
126
+            return substr($fullPath, strlen($this->root));
127
+        } else {
128
+            return null;
129
+        }
130
+    }
131
+
132
+    /**
133
+     * @param string $path
134
+     * @return \Icewind\SMB\IFileInfo
135
+     * @throws StorageNotAvailableException
136
+     */
137
+    protected function getFileInfo($path) {
138
+        try {
139
+            $path = $this->buildPath($path);
140
+            if (!isset($this->statCache[$path])) {
141
+                $this->statCache[$path] = $this->share->stat($path);
142
+            }
143
+            return $this->statCache[$path];
144
+        } catch (ConnectException $e) {
145
+            \OC::$server->getLogger()->logException($e, ['message' => 'Error while getting file info']);
146
+            throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
147
+        }
148
+    }
149
+
150
+    /**
151
+     * @param string $path
152
+     * @return \Icewind\SMB\IFileInfo[]
153
+     * @throws StorageNotAvailableException
154
+     */
155
+    protected function getFolderContents($path) {
156
+        try {
157
+            $path = $this->buildPath($path);
158
+            $files = $this->share->dir($path);
159
+            foreach ($files as $file) {
160
+                $this->statCache[$path . '/' . $file->getName()] = $file;
161
+            }
162
+            return array_filter($files, function (IFileInfo $file) {
163
+                try {
164
+                    if ($file->isHidden()) {
165
+                        \OC::$server->getLogger()->debug('hiding hidden file ' . $file->getName());
166
+                    }
167
+                    return !$file->isHidden();
168
+                } catch (ForbiddenException $e) {
169
+                    \OC::$server->getLogger()->logException($e, ['level' => Util::DEBUG, 'message' => 'Hiding forbidden entry ' . $file->getName()]);
170
+                    return false;
171
+                } catch (NotFoundException $e) {
172
+                    \OC::$server->getLogger()->logException($e, ['level' => Util::DEBUG, 'message' => 'Hiding not found entry ' . $file->getName()]);
173
+                    return false;
174
+                }
175
+            });
176
+        } catch (ConnectException $e) {
177
+            \OC::$server->getLogger()->logException($e, ['message' => 'Error while getting folder content']);
178
+            throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
179
+        }
180
+    }
181
+
182
+    /**
183
+     * @param \Icewind\SMB\IFileInfo $info
184
+     * @return array
185
+     */
186
+    protected function formatInfo($info) {
187
+        $result = [
188
+            'size' => $info->getSize(),
189
+            'mtime' => $info->getMTime(),
190
+        ];
191
+        if ($info->isDirectory()) {
192
+            $result['type'] = 'dir';
193
+        } else {
194
+            $result['type'] = 'file';
195
+        }
196
+        return $result;
197
+    }
198
+
199
+    /**
200
+     * Rename the files. If the source or the target is the root, the rename won't happen.
201
+     *
202
+     * @param string $source the old name of the path
203
+     * @param string $target the new name of the path
204
+     * @return bool true if the rename is successful, false otherwise
205
+     */
206
+    public function rename($source, $target, $retry = true) {
207
+        if ($this->isRootDir($source) || $this->isRootDir($target)) {
208
+            return false;
209
+        }
210
+
211
+        $absoluteSource = $this->buildPath($source);
212
+        $absoluteTarget = $this->buildPath($target);
213
+        try {
214
+            $result = $this->share->rename($absoluteSource, $absoluteTarget);
215
+        } catch (AlreadyExistsException $e) {
216
+            if ($retry) {
217
+                $this->remove($target);
218
+                $result = $this->share->rename($absoluteSource, $absoluteTarget, false);
219
+            } else {
220
+                \OC::$server->getLogger()->logException($e, ['level' => ILogger::WARN]);
221
+                return false;
222
+            }
223
+        } catch (InvalidArgumentException $e) {
224
+            if ($retry) {
225
+                $this->remove($target);
226
+                $result = $this->share->rename($absoluteSource, $absoluteTarget, false);
227
+            } else {
228
+                \OC::$server->getLogger()->logException($e, ['level' => ILogger::WARN]);
229
+                return false;
230
+            }
231
+        } catch (\Exception $e) {
232
+            \OC::$server->getLogger()->logException($e, ['level' => Util::WARN]);
233
+            return false;
234
+        }
235
+        unset($this->statCache[$absoluteSource], $this->statCache[$absoluteTarget]);
236
+        return $result;
237
+    }
238
+
239
+    public function stat($path, $retry = true) {
240
+        try {
241
+            $result = $this->formatInfo($this->getFileInfo($path));
242
+        } catch (ForbiddenException $e) {
243
+            return false;
244
+        } catch (NotFoundException $e) {
245
+            return false;
246
+        } catch (TimedOutException $e) {
247
+            if ($retry) {
248
+                return $this->stat($path, false);
249
+            } else {
250
+                throw $e;
251
+            }
252
+        }
253
+        if ($this->remoteIsShare() && $this->isRootDir($path)) {
254
+            $result['mtime'] = $this->shareMTime();
255
+        }
256
+        return $result;
257
+    }
258
+
259
+    /**
260
+     * get the best guess for the modification time of the share
261
+     *
262
+     * @return int
263
+     */
264
+    private function shareMTime() {
265
+        $highestMTime = 0;
266
+        $files = $this->share->dir($this->root);
267
+        foreach ($files as $fileInfo) {
268
+            try {
269
+                if ($fileInfo->getMTime() > $highestMTime) {
270
+                    $highestMTime = $fileInfo->getMTime();
271
+                }
272
+            } catch (NotFoundException $e) {
273
+                // Ignore this, can happen on unavailable DFS shares
274
+            }
275
+        }
276
+        return $highestMTime;
277
+    }
278
+
279
+    /**
280
+     * Check if the path is our root dir (not the smb one)
281
+     *
282
+     * @param string $path the path
283
+     * @return bool
284
+     */
285
+    private function isRootDir($path) {
286
+        return $path === '' || $path === '/' || $path === '.';
287
+    }
288
+
289
+    /**
290
+     * Check if our root points to a smb share
291
+     *
292
+     * @return bool true if our root points to a share false otherwise
293
+     */
294
+    private function remoteIsShare() {
295
+        return $this->share->getName() && (!$this->root || $this->root === '/');
296
+    }
297
+
298
+    /**
299
+     * @param string $path
300
+     * @return bool
301
+     */
302
+    public function unlink($path) {
303
+        if ($this->isRootDir($path)) {
304
+            return false;
305
+        }
306
+
307
+        try {
308
+            if ($this->is_dir($path)) {
309
+                return $this->rmdir($path);
310
+            } else {
311
+                $path = $this->buildPath($path);
312
+                unset($this->statCache[$path]);
313
+                $this->share->del($path);
314
+                return true;
315
+            }
316
+        } catch (NotFoundException $e) {
317
+            return false;
318
+        } catch (ForbiddenException $e) {
319
+            return false;
320
+        } catch (ConnectException $e) {
321
+            \OC::$server->getLogger()->logException($e, ['message' => 'Error while deleting file']);
322
+            throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
323
+        }
324
+    }
325
+
326
+    /**
327
+     * check if a file or folder has been updated since $time
328
+     *
329
+     * @param string $path
330
+     * @param int $time
331
+     * @return bool
332
+     */
333
+    public function hasUpdated($path, $time) {
334
+        if (!$path and $this->root === '/') {
335
+            // mtime doesn't work for shares, but giving the nature of the backend,
336
+            // doing a full update is still just fast enough
337
+            return true;
338
+        } else {
339
+            $actualTime = $this->filemtime($path);
340
+            return $actualTime > $time;
341
+        }
342
+    }
343
+
344
+    /**
345
+     * @param string $path
346
+     * @param string $mode
347
+     * @return resource|false
348
+     */
349
+    public function fopen($path, $mode) {
350
+        $fullPath = $this->buildPath($path);
351
+        try {
352
+            switch ($mode) {
353
+                case 'r':
354
+                case 'rb':
355
+                    if (!$this->file_exists($path)) {
356
+                        return false;
357
+                    }
358
+                    return $this->share->read($fullPath);
359
+                case 'w':
360
+                case 'wb':
361
+                    $source = $this->share->write($fullPath);
362
+                    return CallBackWrapper::wrap($source, null, null, function () use ($fullPath) {
363
+                        unset($this->statCache[$fullPath]);
364
+                    });
365
+                case 'a':
366
+                case 'ab':
367
+                case 'r+':
368
+                case 'w+':
369
+                case 'wb+':
370
+                case 'a+':
371
+                case 'x':
372
+                case 'x+':
373
+                case 'c':
374
+                case 'c+':
375
+                    //emulate these
376
+                    if (strrpos($path, '.') !== false) {
377
+                        $ext = substr($path, strrpos($path, '.'));
378
+                    } else {
379
+                        $ext = '';
380
+                    }
381
+                    if ($this->file_exists($path)) {
382
+                        if (!$this->isUpdatable($path)) {
383
+                            return false;
384
+                        }
385
+                        $tmpFile = $this->getCachedFile($path);
386
+                    } else {
387
+                        if (!$this->isCreatable(dirname($path))) {
388
+                            return false;
389
+                        }
390
+                        $tmpFile = \OCP\Files::tmpFile($ext);
391
+                    }
392
+                    $source = fopen($tmpFile, $mode);
393
+                    $share = $this->share;
394
+                    return CallbackWrapper::wrap($source, null, null, function () use ($tmpFile, $fullPath, $share) {
395
+                        unset($this->statCache[$fullPath]);
396
+                        $share->put($tmpFile, $fullPath);
397
+                        unlink($tmpFile);
398
+                    });
399
+            }
400
+            return false;
401
+        } catch (NotFoundException $e) {
402
+            return false;
403
+        } catch (ForbiddenException $e) {
404
+            return false;
405
+        } catch (ConnectException $e) {
406
+            \OC::$server->getLogger()->logException($e, ['message' => 'Error while opening file']);
407
+            throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
408
+        }
409
+    }
410
+
411
+    public function rmdir($path) {
412
+        if ($this->isRootDir($path)) {
413
+            return false;
414
+        }
415
+
416
+        try {
417
+            $this->statCache = array();
418
+            $content = $this->share->dir($this->buildPath($path));
419
+            foreach ($content as $file) {
420
+                if ($file->isDirectory()) {
421
+                    $this->rmdir($path . '/' . $file->getName());
422
+                } else {
423
+                    $this->share->del($file->getPath());
424
+                }
425
+            }
426
+            $this->share->rmdir($this->buildPath($path));
427
+            return true;
428
+        } catch (NotFoundException $e) {
429
+            return false;
430
+        } catch (ForbiddenException $e) {
431
+            return false;
432
+        } catch (ConnectException $e) {
433
+            \OC::$server->getLogger()->logException($e, ['message' => 'Error while removing folder']);
434
+            throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
435
+        }
436
+    }
437
+
438
+    public function touch($path, $time = null) {
439
+        try {
440
+            if (!$this->file_exists($path)) {
441
+                $fh = $this->share->write($this->buildPath($path));
442
+                fclose($fh);
443
+                return true;
444
+            }
445
+            return false;
446
+        } catch (ConnectException $e) {
447
+            \OC::$server->getLogger()->logException($e, ['message' => 'Error while creating file']);
448
+            throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
449
+        }
450
+    }
451
+
452
+    public function opendir($path) {
453
+        try {
454
+            $files = $this->getFolderContents($path);
455
+        } catch (NotFoundException $e) {
456
+            return false;
457
+        } catch (ForbiddenException $e) {
458
+            return false;
459
+        }
460
+        $names = array_map(function ($info) {
461
+            /** @var \Icewind\SMB\IFileInfo $info */
462
+            return $info->getName();
463
+        }, $files);
464
+        return IteratorDirectory::wrap($names);
465
+    }
466
+
467
+    public function filetype($path) {
468
+        try {
469
+            return $this->getFileInfo($path)->isDirectory() ? 'dir' : 'file';
470
+        } catch (NotFoundException $e) {
471
+            return false;
472
+        } catch (ForbiddenException $e) {
473
+            return false;
474
+        }
475
+    }
476
+
477
+    public function mkdir($path) {
478
+        $path = $this->buildPath($path);
479
+        try {
480
+            $this->share->mkdir($path);
481
+            return true;
482
+        } catch (ConnectException $e) {
483
+            \OC::$server->getLogger()->logException($e, ['message' => 'Error while creating folder']);
484
+            throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
485
+        } catch (Exception $e) {
486
+            return false;
487
+        }
488
+    }
489
+
490
+    public function file_exists($path) {
491
+        try {
492
+            $this->getFileInfo($path);
493
+            return true;
494
+        } catch (NotFoundException $e) {
495
+            return false;
496
+        } catch (ForbiddenException $e) {
497
+            return false;
498
+        } catch (ConnectException $e) {
499
+            throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
500
+        }
501
+    }
502
+
503
+    public function isReadable($path) {
504
+        try {
505
+            $info = $this->getFileInfo($path);
506
+            return !$info->isHidden();
507
+        } catch (NotFoundException $e) {
508
+            return false;
509
+        } catch (ForbiddenException $e) {
510
+            return false;
511
+        }
512
+    }
513
+
514
+    public function isUpdatable($path) {
515
+        try {
516
+            $info = $this->getFileInfo($path);
517
+            // following windows behaviour for read-only folders: they can be written into
518
+            // (https://support.microsoft.com/en-us/kb/326549 - "cause" section)
519
+            return !$info->isHidden() && (!$info->isReadOnly() || $this->is_dir($path));
520
+        } catch (NotFoundException $e) {
521
+            return false;
522
+        } catch (ForbiddenException $e) {
523
+            return false;
524
+        }
525
+    }
526
+
527
+    public function isDeletable($path) {
528
+        try {
529
+            $info = $this->getFileInfo($path);
530
+            return !$info->isHidden() && !$info->isReadOnly();
531
+        } catch (NotFoundException $e) {
532
+            return false;
533
+        } catch (ForbiddenException $e) {
534
+            return false;
535
+        }
536
+    }
537
+
538
+    /**
539
+     * check if smbclient is installed
540
+     */
541
+    public static function checkDependencies() {
542
+        return (
543
+            (bool)\OC_Helper::findBinaryPath('smbclient')
544
+            || Server::NativeAvailable()
545
+        ) ? true : ['smbclient'];
546
+    }
547
+
548
+    /**
549
+     * Test a storage for availability
550
+     *
551
+     * @return bool
552
+     */
553
+    public function test() {
554
+        try {
555
+            return parent::test();
556
+        } catch (Exception $e) {
557
+            \OC::$server->getLogger()->logException($e);
558
+            return false;
559
+        }
560
+    }
561
+
562
+    public function listen($path, callable $callback) {
563
+        $this->notify($path)->listen(function (IChange $change) use ($callback) {
564
+            if ($change instanceof IRenameChange) {
565
+                return $callback($change->getType(), $change->getPath(), $change->getTargetPath());
566
+            } else {
567
+                return $callback($change->getType(), $change->getPath());
568
+            }
569
+        });
570
+    }
571
+
572
+    public function notify($path) {
573
+        $path = '/' . ltrim($path, '/');
574
+        $shareNotifyHandler = $this->share->notify($this->buildPath($path));
575
+        return new SMBNotifyHandler($shareNotifyHandler, $this->root);
576
+    }
577 577
 }
Please login to merge, or discard this patch.
apps/user_ldap/lib/Controller/RenewPasswordController.php 3 patches
Unused Use Statements   -1 removed lines patch added patch discarded remove patch
@@ -23,7 +23,6 @@
 block discarded – undo
23 23
 namespace OCA\User_LDAP\Controller;
24 24
 
25 25
 use OC\HintException;
26
-use OC_Util;
27 26
 use OCP\AppFramework\Controller;
28 27
 use OCP\AppFramework\Http\RedirectResponse;
29 28
 use OCP\AppFramework\Http\TemplateResponse;
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -85,7 +85,7 @@  discard block
 block discarded – undo
85 85
 	 * @return TemplateResponse|RedirectResponse
86 86
 	 */
87 87
 	public function showRenewPasswordForm($user) {
88
-		if($this->config->getUserValue($user, 'user_ldap', 'needsPasswordReset') !== 'true') {
88
+		if ($this->config->getUserValue($user, 'user_ldap', 'needsPasswordReset') !== 'true') {
89 89
 			return new RedirectResponse($this->urlGenerator->linkToRouteAbsolute('core.login.showLoginForm'));
90 90
 		}
91 91
 		$parameters = [];
@@ -129,7 +129,7 @@  discard block
 block discarded – undo
129 129
 	 * @return RedirectResponse
130 130
 	 */
131 131
 	public function tryRenewPassword($user, $oldPassword, $newPassword) {
132
-		if($this->config->getUserValue($user, 'user_ldap', 'needsPasswordReset') !== 'true') {
132
+		if ($this->config->getUserValue($user, 'user_ldap', 'needsPasswordReset') !== 'true') {
133 133
 			return new RedirectResponse($this->urlGenerator->linkToRouteAbsolute('core.login.showLoginForm'));
134 134
 		}
135 135
 		$args = !is_null($user) ? ['user' => $user] : [];
Please login to merge, or discard this patch.
Indentation   +129 added lines, -129 removed lines patch added patch discarded remove patch
@@ -37,144 +37,144 @@
 block discarded – undo
37 37
 use OCP\IUserManager;
38 38
 
39 39
 class RenewPasswordController extends Controller {
40
-	/** @var IUserManager */
41
-	private $userManager;
42
-	/** @var IConfig */
43
-	private $config;
44
-	/** @var IL10N */
45
-	protected $l10n;
46
-	/** @var ISession */
47
-	private $session;
48
-	/** @var IURLGenerator */
49
-	private $urlGenerator;
40
+    /** @var IUserManager */
41
+    private $userManager;
42
+    /** @var IConfig */
43
+    private $config;
44
+    /** @var IL10N */
45
+    protected $l10n;
46
+    /** @var ISession */
47
+    private $session;
48
+    /** @var IURLGenerator */
49
+    private $urlGenerator;
50 50
 
51
-	/**
52
-	 * @param string $appName
53
-	 * @param IRequest $request
54
-	 * @param IUserManager $userManager
55
-	 * @param IConfig $config
56
-	 * @param IURLGenerator $urlGenerator
57
-	 */
58
-	function __construct($appName, IRequest $request, IUserManager $userManager, 
59
-		IConfig $config, IL10N $l10n, ISession $session, IURLGenerator $urlGenerator) {
60
-		parent::__construct($appName, $request);
61
-		$this->userManager = $userManager;
62
-		$this->config = $config;
63
-		$this->l10n = $l10n;
64
-		$this->session = $session;
65
-		$this->urlGenerator = $urlGenerator;
66
-	}
51
+    /**
52
+     * @param string $appName
53
+     * @param IRequest $request
54
+     * @param IUserManager $userManager
55
+     * @param IConfig $config
56
+     * @param IURLGenerator $urlGenerator
57
+     */
58
+    function __construct($appName, IRequest $request, IUserManager $userManager, 
59
+        IConfig $config, IL10N $l10n, ISession $session, IURLGenerator $urlGenerator) {
60
+        parent::__construct($appName, $request);
61
+        $this->userManager = $userManager;
62
+        $this->config = $config;
63
+        $this->l10n = $l10n;
64
+        $this->session = $session;
65
+        $this->urlGenerator = $urlGenerator;
66
+    }
67 67
 
68
-	/**
69
-	 * @PublicPage
70
-	 * @NoCSRFRequired
71
-	 *
72
-	 * @return RedirectResponse
73
-	 */
74
-	public function cancel() {
75
-		return new RedirectResponse($this->urlGenerator->linkToRouteAbsolute('core.login.showLoginForm'));
76
-	}
68
+    /**
69
+     * @PublicPage
70
+     * @NoCSRFRequired
71
+     *
72
+     * @return RedirectResponse
73
+     */
74
+    public function cancel() {
75
+        return new RedirectResponse($this->urlGenerator->linkToRouteAbsolute('core.login.showLoginForm'));
76
+    }
77 77
 
78
-	/**
79
-	 * @PublicPage
80
-	 * @NoCSRFRequired
81
-	 * @UseSession
82
-	 *
83
-	 * @param string $user
84
-	 *
85
-	 * @return TemplateResponse|RedirectResponse
86
-	 */
87
-	public function showRenewPasswordForm($user) {
88
-		if($this->config->getUserValue($user, 'user_ldap', 'needsPasswordReset') !== 'true') {
89
-			return new RedirectResponse($this->urlGenerator->linkToRouteAbsolute('core.login.showLoginForm'));
90
-		}
91
-		$parameters = [];
92
-		$renewPasswordMessages = $this->session->get('renewPasswordMessages');
93
-		$errors = [];
94
-		$messages = [];
95
-		if (is_array($renewPasswordMessages)) {
96
-			list($errors, $messages) = $renewPasswordMessages;
97
-		}
98
-		$this->session->remove('renewPasswordMessages');
99
-		foreach ($errors as $value) {
100
-			$parameters[$value] = true;
101
-		}
78
+    /**
79
+     * @PublicPage
80
+     * @NoCSRFRequired
81
+     * @UseSession
82
+     *
83
+     * @param string $user
84
+     *
85
+     * @return TemplateResponse|RedirectResponse
86
+     */
87
+    public function showRenewPasswordForm($user) {
88
+        if($this->config->getUserValue($user, 'user_ldap', 'needsPasswordReset') !== 'true') {
89
+            return new RedirectResponse($this->urlGenerator->linkToRouteAbsolute('core.login.showLoginForm'));
90
+        }
91
+        $parameters = [];
92
+        $renewPasswordMessages = $this->session->get('renewPasswordMessages');
93
+        $errors = [];
94
+        $messages = [];
95
+        if (is_array($renewPasswordMessages)) {
96
+            list($errors, $messages) = $renewPasswordMessages;
97
+        }
98
+        $this->session->remove('renewPasswordMessages');
99
+        foreach ($errors as $value) {
100
+            $parameters[$value] = true;
101
+        }
102 102
 
103
-		$parameters['messages'] = $messages;
104
-		$parameters['user'] = $user;
103
+        $parameters['messages'] = $messages;
104
+        $parameters['user'] = $user;
105 105
 
106
-		$parameters['canResetPassword'] = true;
107
-		$parameters['resetPasswordLink'] = $this->config->getSystemValue('lost_password_link', '');
108
-		if (!$parameters['resetPasswordLink']) {
109
-			$userObj = $this->userManager->get($user);
110
-			if ($userObj instanceof IUser) {
111
-				$parameters['canResetPassword'] = $userObj->canChangePassword();
112
-			}
113
-		}
114
-		$parameters['cancelLink'] = $this->urlGenerator->linkToRouteAbsolute('core.login.showLoginForm');
106
+        $parameters['canResetPassword'] = true;
107
+        $parameters['resetPasswordLink'] = $this->config->getSystemValue('lost_password_link', '');
108
+        if (!$parameters['resetPasswordLink']) {
109
+            $userObj = $this->userManager->get($user);
110
+            if ($userObj instanceof IUser) {
111
+                $parameters['canResetPassword'] = $userObj->canChangePassword();
112
+            }
113
+        }
114
+        $parameters['cancelLink'] = $this->urlGenerator->linkToRouteAbsolute('core.login.showLoginForm');
115 115
 
116
-		return new TemplateResponse(
117
-			$this->appName, 'renewpassword', $parameters, 'guest'
118
-		);
119
-	}
116
+        return new TemplateResponse(
117
+            $this->appName, 'renewpassword', $parameters, 'guest'
118
+        );
119
+    }
120 120
 
121
-	/**
122
-	 * @PublicPage
123
-	 * @UseSession
124
-	 *
125
-	 * @param string $user
126
-	 * @param string $oldPassword
127
-	 * @param string $newPassword
128
-	 *
129
-	 * @return RedirectResponse
130
-	 */
131
-	public function tryRenewPassword($user, $oldPassword, $newPassword) {
132
-		if($this->config->getUserValue($user, 'user_ldap', 'needsPasswordReset') !== 'true') {
133
-			return new RedirectResponse($this->urlGenerator->linkToRouteAbsolute('core.login.showLoginForm'));
134
-		}
135
-		$args = !is_null($user) ? ['user' => $user] : [];
136
-		$loginResult = $this->userManager->checkPassword($user, $oldPassword);
137
-		if ($loginResult === false) {
138
-			$this->session->set('renewPasswordMessages', [
139
-				['invalidpassword'], []
140
-			]);
141
-			return new RedirectResponse($this->urlGenerator->linkToRoute('user_ldap.renewPassword.showRenewPasswordForm', $args));
142
-		}
121
+    /**
122
+     * @PublicPage
123
+     * @UseSession
124
+     *
125
+     * @param string $user
126
+     * @param string $oldPassword
127
+     * @param string $newPassword
128
+     *
129
+     * @return RedirectResponse
130
+     */
131
+    public function tryRenewPassword($user, $oldPassword, $newPassword) {
132
+        if($this->config->getUserValue($user, 'user_ldap', 'needsPasswordReset') !== 'true') {
133
+            return new RedirectResponse($this->urlGenerator->linkToRouteAbsolute('core.login.showLoginForm'));
134
+        }
135
+        $args = !is_null($user) ? ['user' => $user] : [];
136
+        $loginResult = $this->userManager->checkPassword($user, $oldPassword);
137
+        if ($loginResult === false) {
138
+            $this->session->set('renewPasswordMessages', [
139
+                ['invalidpassword'], []
140
+            ]);
141
+            return new RedirectResponse($this->urlGenerator->linkToRoute('user_ldap.renewPassword.showRenewPasswordForm', $args));
142
+        }
143 143
 		
144
-		try {
145
-			if (!is_null($newPassword) && \OC_User::setPassword($user, $newPassword)) {
146
-				$this->session->set('loginMessages', [
147
-					[], [$this->l10n->t("Please login with the new password")]
148
-				]);
149
-				$this->config->setUserValue($user, 'user_ldap', 'needsPasswordReset', 'false');
150
-				return new RedirectResponse($this->urlGenerator->linkToRoute('core.login.showLoginForm', $args));
151
-			} else {
152
-				$this->session->set('renewPasswordMessages', [
153
-					['internalexception'], []
154
-				]);
155
-			}
156
-		} catch (HintException $e) {
157
-			$this->session->set('renewPasswordMessages', [
158
-				[], [$e->getHint()]
159
-			]);
160
-		}
144
+        try {
145
+            if (!is_null($newPassword) && \OC_User::setPassword($user, $newPassword)) {
146
+                $this->session->set('loginMessages', [
147
+                    [], [$this->l10n->t("Please login with the new password")]
148
+                ]);
149
+                $this->config->setUserValue($user, 'user_ldap', 'needsPasswordReset', 'false');
150
+                return new RedirectResponse($this->urlGenerator->linkToRoute('core.login.showLoginForm', $args));
151
+            } else {
152
+                $this->session->set('renewPasswordMessages', [
153
+                    ['internalexception'], []
154
+                ]);
155
+            }
156
+        } catch (HintException $e) {
157
+            $this->session->set('renewPasswordMessages', [
158
+                [], [$e->getHint()]
159
+            ]);
160
+        }
161 161
 
162
-		return new RedirectResponse($this->urlGenerator->linkToRoute('user_ldap.renewPassword.showRenewPasswordForm', $args));
163
-	}
162
+        return new RedirectResponse($this->urlGenerator->linkToRoute('user_ldap.renewPassword.showRenewPasswordForm', $args));
163
+    }
164 164
 
165
-	/**
166
-	 * @PublicPage
167
-	 * @NoCSRFRequired
168
-	 * @UseSession
169
-	 *
170
-	 * @return RedirectResponse
171
-	 */
172
-	public function showLoginFormInvalidPassword($user) {
173
-		$args = !is_null($user) ? ['user' => $user] : [];
174
-		$this->session->set('loginMessages', [
175
-			['invalidpassword'], []
176
-		]);
177
-		return new RedirectResponse($this->urlGenerator->linkToRoute('core.login.showLoginForm', $args));
178
-	}
165
+    /**
166
+     * @PublicPage
167
+     * @NoCSRFRequired
168
+     * @UseSession
169
+     *
170
+     * @return RedirectResponse
171
+     */
172
+    public function showLoginFormInvalidPassword($user) {
173
+        $args = !is_null($user) ? ['user' => $user] : [];
174
+        $this->session->set('loginMessages', [
175
+            ['invalidpassword'], []
176
+        ]);
177
+        return new RedirectResponse($this->urlGenerator->linkToRoute('core.login.showLoginForm', $args));
178
+    }
179 179
 
180 180
 }
Please login to merge, or discard this patch.