Passed
Push — master ( 62403d...0c3e2f )
by Joas
14:50 queued 14s
created
apps/files_sharing/lib/Controller/ShareController.php 1 patch
Indentation   +643 added lines, -644 removed lines patch added patch discarded remove patch
@@ -80,652 +80,651 @@
 block discarded – undo
80 80
  */
81 81
 class ShareController extends AuthPublicShareController {
82 82
 
83
-	/** @var IConfig */
84
-	protected $config;
85
-	/** @var IUserManager */
86
-	protected $userManager;
87
-	/** @var ILogger */
88
-	protected $logger;
89
-	/** @var \OCP\Activity\IManager */
90
-	protected $activityManager;
91
-	/** @var IPreview */
92
-	protected $previewManager;
93
-	/** @var IRootFolder */
94
-	protected $rootFolder;
95
-	/** @var FederatedShareProvider */
96
-	protected $federatedShareProvider;
97
-	/** @var EventDispatcherInterface */
98
-	protected $eventDispatcher;
99
-	/** @var IL10N */
100
-	protected $l10n;
101
-	/** @var Defaults */
102
-	protected $defaults;
103
-	/** @var ShareManager */
104
-	protected $shareManager;
105
-
106
-	/** @var Share\IShare */
107
-	protected $share;
108
-
109
-	/**
110
-	 * @param string $appName
111
-	 * @param IRequest $request
112
-	 * @param IConfig $config
113
-	 * @param IURLGenerator $urlGenerator
114
-	 * @param IUserManager $userManager
115
-	 * @param ILogger $logger
116
-	 * @param \OCP\Activity\IManager $activityManager
117
-	 * @param \OCP\Share\IManager $shareManager
118
-	 * @param ISession $session
119
-	 * @param IPreview $previewManager
120
-	 * @param IRootFolder $rootFolder
121
-	 * @param FederatedShareProvider $federatedShareProvider
122
-	 * @param EventDispatcherInterface $eventDispatcher
123
-	 * @param IL10N $l10n
124
-	 * @param Defaults $defaults
125
-	 */
126
-	public function __construct(string $appName,
127
-								IRequest $request,
128
-								IConfig $config,
129
-								IURLGenerator $urlGenerator,
130
-								IUserManager $userManager,
131
-								ILogger $logger,
132
-								\OCP\Activity\IManager $activityManager,
133
-								ShareManager $shareManager,
134
-								ISession $session,
135
-								IPreview $previewManager,
136
-								IRootFolder $rootFolder,
137
-								FederatedShareProvider $federatedShareProvider,
138
-								EventDispatcherInterface $eventDispatcher,
139
-								IL10N $l10n,
140
-								Defaults $defaults) {
141
-		parent::__construct($appName, $request, $session, $urlGenerator);
142
-
143
-		$this->config = $config;
144
-		$this->userManager = $userManager;
145
-		$this->logger = $logger;
146
-		$this->activityManager = $activityManager;
147
-		$this->previewManager = $previewManager;
148
-		$this->rootFolder = $rootFolder;
149
-		$this->federatedShareProvider = $federatedShareProvider;
150
-		$this->eventDispatcher = $eventDispatcher;
151
-		$this->l10n = $l10n;
152
-		$this->defaults = $defaults;
153
-		$this->shareManager = $shareManager;
154
-	}
155
-
156
-	/**
157
-	 * @PublicPage
158
-	 * @NoCSRFRequired
159
-	 *
160
-	 * Show the authentication page
161
-	 * The form has to submit to the authenticate method route
162
-	 */
163
-	public function showAuthenticate(): TemplateResponse {
164
-		$templateParameters = ['share' => $this->share];
165
-
166
-		$event = new GenericEvent(null, $templateParameters);
167
-		$this->eventDispatcher->dispatch('OCA\Files_Sharing::loadAdditionalScripts::publicShareAuth', $event);
168
-
169
-		$response = new TemplateResponse('core', 'publicshareauth', $templateParameters, 'guest');
170
-		if ($this->share->getSendPasswordByTalk()) {
171
-			$csp = new ContentSecurityPolicy();
172
-			$csp->addAllowedConnectDomain('*');
173
-			$csp->addAllowedMediaDomain('blob:');
174
-			$response->setContentSecurityPolicy($csp);
175
-		}
176
-
177
-		return $response;
178
-	}
179
-
180
-	/**
181
-	 * The template to show when authentication failed
182
-	 */
183
-	protected function showAuthFailed(): TemplateResponse {
184
-		$templateParameters = ['share' => $this->share, 'wrongpw' => true];
185
-
186
-		$event = new GenericEvent(null, $templateParameters);
187
-		$this->eventDispatcher->dispatch('OCA\Files_Sharing::loadAdditionalScripts::publicShareAuth', $event);
188
-
189
-		$response = new TemplateResponse('core', 'publicshareauth', $templateParameters, 'guest');
190
-		if ($this->share->getSendPasswordByTalk()) {
191
-			$csp = new ContentSecurityPolicy();
192
-			$csp->addAllowedConnectDomain('*');
193
-			$csp->addAllowedMediaDomain('blob:');
194
-			$response->setContentSecurityPolicy($csp);
195
-		}
196
-
197
-		return $response;
198
-	}
199
-
200
-	protected function verifyPassword(string $password): bool {
201
-		return $this->shareManager->checkPassword($this->share, $password);
202
-	}
203
-
204
-	protected function getPasswordHash(): string {
205
-		return $this->share->getPassword();
206
-	}
207
-
208
-	public function isValidToken(): bool {
209
-		try {
210
-			$this->share = $this->shareManager->getShareByToken($this->getToken());
211
-		} catch (ShareNotFound $e) {
212
-			return false;
213
-		}
214
-
215
-		return true;
216
-	}
217
-
218
-	protected function isPasswordProtected(): bool {
219
-		return $this->share->getPassword() !== null;
220
-	}
221
-
222
-	protected function authSucceeded() {
223
-		// For share this was always set so it is still used in other apps
224
-		$this->session->set('public_link_authenticated', (string)$this->share->getId());
225
-	}
226
-
227
-	protected function authFailed() {
228
-		$this->emitAccessShareHook($this->share, 403, 'Wrong password');
229
-	}
230
-
231
-	/**
232
-	 * throws hooks when a share is attempted to be accessed
233
-	 *
234
-	 * @param \OCP\Share\IShare|string $share the Share instance if available,
235
-	 * otherwise token
236
-	 * @param int $errorCode
237
-	 * @param string $errorMessage
238
-	 * @throws \OC\HintException
239
-	 * @throws \OC\ServerNotAvailableException
240
-	 */
241
-	protected function emitAccessShareHook($share, $errorCode = 200, $errorMessage = '') {
242
-		$itemType = $itemSource = $uidOwner = '';
243
-		$token = $share;
244
-		$exception = null;
245
-		if($share instanceof \OCP\Share\IShare) {
246
-			try {
247
-				$token = $share->getToken();
248
-				$uidOwner = $share->getSharedBy();
249
-				$itemType = $share->getNodeType();
250
-				$itemSource = $share->getNodeId();
251
-			} catch (\Exception $e) {
252
-				// we log what we know and pass on the exception afterwards
253
-				$exception = $e;
254
-			}
255
-		}
256
-		\OC_Hook::emit(Share::class, 'share_link_access', [
257
-			'itemType' => $itemType,
258
-			'itemSource' => $itemSource,
259
-			'uidOwner' => $uidOwner,
260
-			'token' => $token,
261
-			'errorCode' => $errorCode,
262
-			'errorMessage' => $errorMessage,
263
-		]);
264
-		if(!is_null($exception)) {
265
-			throw $exception;
266
-		}
267
-	}
268
-
269
-	/**
270
-	 * Validate the permissions of the share
271
-	 *
272
-	 * @param Share\IShare $share
273
-	 * @return bool
274
-	 */
275
-	private function validateShare(\OCP\Share\IShare $share) {
276
-		// If the owner is disabled no access to the linke is granted
277
-		$owner = $this->userManager->get($share->getShareOwner());
278
-		if ($owner === null || !$owner->isEnabled()) {
279
-			return false;
280
-		}
281
-
282
-		// If the initiator of the share is disabled no access is granted
283
-		$initiator = $this->userManager->get($share->getSharedBy());
284
-		if ($initiator === null || !$initiator->isEnabled()) {
285
-			return false;
286
-		}
287
-
288
-		return $share->getNode()->isReadable() && $share->getNode()->isShareable();
289
-	}
290
-
291
-	/**
292
-	 * @PublicPage
293
-	 * @NoCSRFRequired
294
-	 *
295
-
296
-	 * @param string $path
297
-	 * @return TemplateResponse
298
-	 * @throws NotFoundException
299
-	 * @throws \Exception
300
-	 */
301
-	public function showShare($path = ''): TemplateResponse {
302
-		\OC_User::setIncognitoMode(true);
303
-
304
-		// Check whether share exists
305
-		try {
306
-			$share = $this->shareManager->getShareByToken($this->getToken());
307
-		} catch (ShareNotFound $e) {
308
-			$this->emitAccessShareHook($this->getToken(), 404, 'Share not found');
309
-			throw new NotFoundException();
310
-		}
311
-
312
-		if (!$this->validateShare($share)) {
313
-			throw new NotFoundException();
314
-		}
315
-
316
-		$shareNode = $share->getNode();
317
-
318
-		// We can't get the path of a file share
319
-		try {
320
-			if ($shareNode instanceof \OCP\Files\File && $path !== '') {
321
-				$this->emitAccessShareHook($share, 404, 'Share not found');
322
-				throw new NotFoundException();
323
-			}
324
-		} catch (\Exception $e) {
325
-			$this->emitAccessShareHook($share, 404, 'Share not found');
326
-			throw $e;
327
-		}
328
-
329
-		$shareTmpl = [];
330
-		$shareTmpl['displayName'] = $this->userManager->get($share->getShareOwner())->getDisplayName();
331
-		$shareTmpl['owner'] = $share->getShareOwner();
332
-		$shareTmpl['filename'] = $shareNode->getName();
333
-		$shareTmpl['directory_path'] = $share->getTarget();
334
-		$shareTmpl['note'] = $share->getNote();
335
-		$shareTmpl['mimetype'] = $shareNode->getMimetype();
336
-		$shareTmpl['previewSupported'] = $this->previewManager->isMimeSupported($shareNode->getMimetype());
337
-		$shareTmpl['dirToken'] = $this->getToken();
338
-		$shareTmpl['sharingToken'] = $this->getToken();
339
-		$shareTmpl['server2serversharing'] = $this->federatedShareProvider->isOutgoingServer2serverShareEnabled();
340
-		$shareTmpl['protected'] = $share->getPassword() !== null ? 'true' : 'false';
341
-		$shareTmpl['dir'] = '';
342
-		$shareTmpl['nonHumanFileSize'] = $shareNode->getSize();
343
-		$shareTmpl['fileSize'] = \OCP\Util::humanFileSize($shareNode->getSize());
344
-		$shareTmpl['hideDownload'] = $share->getHideDownload();
345
-
346
-		$hideFileList = false;
347
-
348
-		if ($shareNode instanceof \OCP\Files\Folder) {
349
-
350
-			$shareIsFolder = true;
351
-
352
-			try {
353
-				$folderNode = $shareNode->get($path);
354
-			} catch (\OCP\Files\NotFoundException $e) {
355
-				$this->emitAccessShareHook($share, 404, 'Share not found');
356
-				throw new NotFoundException();
357
-			}
358
-
359
-			$shareTmpl['dir'] = $shareNode->getRelativePath($folderNode->getPath());
360
-
361
-			/*
83
+    /** @var IConfig */
84
+    protected $config;
85
+    /** @var IUserManager */
86
+    protected $userManager;
87
+    /** @var ILogger */
88
+    protected $logger;
89
+    /** @var \OCP\Activity\IManager */
90
+    protected $activityManager;
91
+    /** @var IPreview */
92
+    protected $previewManager;
93
+    /** @var IRootFolder */
94
+    protected $rootFolder;
95
+    /** @var FederatedShareProvider */
96
+    protected $federatedShareProvider;
97
+    /** @var EventDispatcherInterface */
98
+    protected $eventDispatcher;
99
+    /** @var IL10N */
100
+    protected $l10n;
101
+    /** @var Defaults */
102
+    protected $defaults;
103
+    /** @var ShareManager */
104
+    protected $shareManager;
105
+
106
+    /** @var Share\IShare */
107
+    protected $share;
108
+
109
+    /**
110
+     * @param string $appName
111
+     * @param IRequest $request
112
+     * @param IConfig $config
113
+     * @param IURLGenerator $urlGenerator
114
+     * @param IUserManager $userManager
115
+     * @param ILogger $logger
116
+     * @param \OCP\Activity\IManager $activityManager
117
+     * @param \OCP\Share\IManager $shareManager
118
+     * @param ISession $session
119
+     * @param IPreview $previewManager
120
+     * @param IRootFolder $rootFolder
121
+     * @param FederatedShareProvider $federatedShareProvider
122
+     * @param EventDispatcherInterface $eventDispatcher
123
+     * @param IL10N $l10n
124
+     * @param Defaults $defaults
125
+     */
126
+    public function __construct(string $appName,
127
+                                IRequest $request,
128
+                                IConfig $config,
129
+                                IURLGenerator $urlGenerator,
130
+                                IUserManager $userManager,
131
+                                ILogger $logger,
132
+                                \OCP\Activity\IManager $activityManager,
133
+                                ShareManager $shareManager,
134
+                                ISession $session,
135
+                                IPreview $previewManager,
136
+                                IRootFolder $rootFolder,
137
+                                FederatedShareProvider $federatedShareProvider,
138
+                                EventDispatcherInterface $eventDispatcher,
139
+                                IL10N $l10n,
140
+                                Defaults $defaults) {
141
+        parent::__construct($appName, $request, $session, $urlGenerator);
142
+
143
+        $this->config = $config;
144
+        $this->userManager = $userManager;
145
+        $this->logger = $logger;
146
+        $this->activityManager = $activityManager;
147
+        $this->previewManager = $previewManager;
148
+        $this->rootFolder = $rootFolder;
149
+        $this->federatedShareProvider = $federatedShareProvider;
150
+        $this->eventDispatcher = $eventDispatcher;
151
+        $this->l10n = $l10n;
152
+        $this->defaults = $defaults;
153
+        $this->shareManager = $shareManager;
154
+    }
155
+
156
+    /**
157
+     * @PublicPage
158
+     * @NoCSRFRequired
159
+     *
160
+     * Show the authentication page
161
+     * The form has to submit to the authenticate method route
162
+     */
163
+    public function showAuthenticate(): TemplateResponse {
164
+        $templateParameters = ['share' => $this->share];
165
+
166
+        $event = new GenericEvent(null, $templateParameters);
167
+        $this->eventDispatcher->dispatch('OCA\Files_Sharing::loadAdditionalScripts::publicShareAuth', $event);
168
+
169
+        $response = new TemplateResponse('core', 'publicshareauth', $templateParameters, 'guest');
170
+        if ($this->share->getSendPasswordByTalk()) {
171
+            $csp = new ContentSecurityPolicy();
172
+            $csp->addAllowedConnectDomain('*');
173
+            $csp->addAllowedMediaDomain('blob:');
174
+            $response->setContentSecurityPolicy($csp);
175
+        }
176
+
177
+        return $response;
178
+    }
179
+
180
+    /**
181
+     * The template to show when authentication failed
182
+     */
183
+    protected function showAuthFailed(): TemplateResponse {
184
+        $templateParameters = ['share' => $this->share, 'wrongpw' => true];
185
+
186
+        $event = new GenericEvent(null, $templateParameters);
187
+        $this->eventDispatcher->dispatch('OCA\Files_Sharing::loadAdditionalScripts::publicShareAuth', $event);
188
+
189
+        $response = new TemplateResponse('core', 'publicshareauth', $templateParameters, 'guest');
190
+        if ($this->share->getSendPasswordByTalk()) {
191
+            $csp = new ContentSecurityPolicy();
192
+            $csp->addAllowedConnectDomain('*');
193
+            $csp->addAllowedMediaDomain('blob:');
194
+            $response->setContentSecurityPolicy($csp);
195
+        }
196
+
197
+        return $response;
198
+    }
199
+
200
+    protected function verifyPassword(string $password): bool {
201
+        return $this->shareManager->checkPassword($this->share, $password);
202
+    }
203
+
204
+    protected function getPasswordHash(): string {
205
+        return $this->share->getPassword();
206
+    }
207
+
208
+    public function isValidToken(): bool {
209
+        try {
210
+            $this->share = $this->shareManager->getShareByToken($this->getToken());
211
+        } catch (ShareNotFound $e) {
212
+            return false;
213
+        }
214
+
215
+        return true;
216
+    }
217
+
218
+    protected function isPasswordProtected(): bool {
219
+        return $this->share->getPassword() !== null;
220
+    }
221
+
222
+    protected function authSucceeded() {
223
+        // For share this was always set so it is still used in other apps
224
+        $this->session->set('public_link_authenticated', (string)$this->share->getId());
225
+    }
226
+
227
+    protected function authFailed() {
228
+        $this->emitAccessShareHook($this->share, 403, 'Wrong password');
229
+    }
230
+
231
+    /**
232
+     * throws hooks when a share is attempted to be accessed
233
+     *
234
+     * @param \OCP\Share\IShare|string $share the Share instance if available,
235
+     * otherwise token
236
+     * @param int $errorCode
237
+     * @param string $errorMessage
238
+     * @throws \OC\HintException
239
+     * @throws \OC\ServerNotAvailableException
240
+     */
241
+    protected function emitAccessShareHook($share, $errorCode = 200, $errorMessage = '') {
242
+        $itemType = $itemSource = $uidOwner = '';
243
+        $token = $share;
244
+        $exception = null;
245
+        if($share instanceof \OCP\Share\IShare) {
246
+            try {
247
+                $token = $share->getToken();
248
+                $uidOwner = $share->getSharedBy();
249
+                $itemType = $share->getNodeType();
250
+                $itemSource = $share->getNodeId();
251
+            } catch (\Exception $e) {
252
+                // we log what we know and pass on the exception afterwards
253
+                $exception = $e;
254
+            }
255
+        }
256
+        \OC_Hook::emit(Share::class, 'share_link_access', [
257
+            'itemType' => $itemType,
258
+            'itemSource' => $itemSource,
259
+            'uidOwner' => $uidOwner,
260
+            'token' => $token,
261
+            'errorCode' => $errorCode,
262
+            'errorMessage' => $errorMessage,
263
+        ]);
264
+        if(!is_null($exception)) {
265
+            throw $exception;
266
+        }
267
+    }
268
+
269
+    /**
270
+     * Validate the permissions of the share
271
+     *
272
+     * @param Share\IShare $share
273
+     * @return bool
274
+     */
275
+    private function validateShare(\OCP\Share\IShare $share) {
276
+        // If the owner is disabled no access to the linke is granted
277
+        $owner = $this->userManager->get($share->getShareOwner());
278
+        if ($owner === null || !$owner->isEnabled()) {
279
+            return false;
280
+        }
281
+
282
+        // If the initiator of the share is disabled no access is granted
283
+        $initiator = $this->userManager->get($share->getSharedBy());
284
+        if ($initiator === null || !$initiator->isEnabled()) {
285
+            return false;
286
+        }
287
+
288
+        return $share->getNode()->isReadable() && $share->getNode()->isShareable();
289
+    }
290
+
291
+    /**
292
+     * @PublicPage
293
+     * @NoCSRFRequired
294
+     *
295
+     * @param string $path
296
+     * @return TemplateResponse
297
+     * @throws NotFoundException
298
+     * @throws \Exception
299
+     */
300
+    public function showShare($path = ''): TemplateResponse {
301
+        \OC_User::setIncognitoMode(true);
302
+
303
+        // Check whether share exists
304
+        try {
305
+            $share = $this->shareManager->getShareByToken($this->getToken());
306
+        } catch (ShareNotFound $e) {
307
+            $this->emitAccessShareHook($this->getToken(), 404, 'Share not found');
308
+            throw new NotFoundException();
309
+        }
310
+
311
+        if (!$this->validateShare($share)) {
312
+            throw new NotFoundException();
313
+        }
314
+
315
+        $shareNode = $share->getNode();
316
+
317
+        // We can't get the path of a file share
318
+        try {
319
+            if ($shareNode instanceof \OCP\Files\File && $path !== '') {
320
+                $this->emitAccessShareHook($share, 404, 'Share not found');
321
+                throw new NotFoundException();
322
+            }
323
+        } catch (\Exception $e) {
324
+            $this->emitAccessShareHook($share, 404, 'Share not found');
325
+            throw $e;
326
+        }
327
+
328
+        $shareTmpl = [];
329
+        $shareTmpl['displayName'] = $this->userManager->get($share->getShareOwner())->getDisplayName();
330
+        $shareTmpl['owner'] = $share->getShareOwner();
331
+        $shareTmpl['filename'] = $shareNode->getName();
332
+        $shareTmpl['directory_path'] = $share->getTarget();
333
+        $shareTmpl['note'] = $share->getNote();
334
+        $shareTmpl['mimetype'] = $shareNode->getMimetype();
335
+        $shareTmpl['previewSupported'] = $this->previewManager->isMimeSupported($shareNode->getMimetype());
336
+        $shareTmpl['dirToken'] = $this->getToken();
337
+        $shareTmpl['sharingToken'] = $this->getToken();
338
+        $shareTmpl['server2serversharing'] = $this->federatedShareProvider->isOutgoingServer2serverShareEnabled();
339
+        $shareTmpl['protected'] = $share->getPassword() !== null ? 'true' : 'false';
340
+        $shareTmpl['dir'] = '';
341
+        $shareTmpl['nonHumanFileSize'] = $shareNode->getSize();
342
+        $shareTmpl['fileSize'] = \OCP\Util::humanFileSize($shareNode->getSize());
343
+        $shareTmpl['hideDownload'] = $share->getHideDownload();
344
+
345
+        $hideFileList = false;
346
+
347
+        if ($shareNode instanceof \OCP\Files\Folder) {
348
+
349
+            $shareIsFolder = true;
350
+
351
+            try {
352
+                $folderNode = $shareNode->get($path);
353
+            } catch (\OCP\Files\NotFoundException $e) {
354
+                $this->emitAccessShareHook($share, 404, 'Share not found');
355
+                throw new NotFoundException();
356
+            }
357
+
358
+            $shareTmpl['dir'] = $shareNode->getRelativePath($folderNode->getPath());
359
+
360
+            /*
362 361
 			 * The OC_Util methods require a view. This just uses the node API
363 362
 			 */
364
-			$freeSpace = $share->getNode()->getStorage()->free_space($share->getNode()->getInternalPath());
365
-			if ($freeSpace < \OCP\Files\FileInfo::SPACE_UNLIMITED) {
366
-				$freeSpace = max($freeSpace, 0);
367
-			} else {
368
-				$freeSpace = (INF > 0) ? INF: PHP_INT_MAX; // work around https://bugs.php.net/bug.php?id=69188
369
-			}
370
-
371
-			$hideFileList = !($share->getPermissions() & \OCP\Constants::PERMISSION_READ);
372
-			$maxUploadFilesize = $freeSpace;
373
-
374
-			$folder = new Template('files', 'list', '');
375
-
376
-			$folder->assign('dir', $shareNode->getRelativePath($folderNode->getPath()));
377
-			$folder->assign('dirToken', $this->getToken());
378
-			$folder->assign('permissions', \OCP\Constants::PERMISSION_READ);
379
-			$folder->assign('isPublic', true);
380
-			$folder->assign('hideFileList', $hideFileList);
381
-			$folder->assign('publicUploadEnabled', 'no');
382
-			// default to list view
383
-			$folder->assign('showgridview', false);
384
-			$folder->assign('uploadMaxFilesize', $maxUploadFilesize);
385
-			$folder->assign('uploadMaxHumanFilesize', \OCP\Util::humanFileSize($maxUploadFilesize));
386
-			$folder->assign('freeSpace', $freeSpace);
387
-			$folder->assign('usedSpacePercent', 0);
388
-			$folder->assign('trash', false);
389
-			$shareTmpl['folder'] = $folder->fetchPage();
390
-		} else {
391
-			$shareIsFolder = false;
392
-		}
393
-
394
-		// default to list view
395
-		$shareTmpl['showgridview'] = false;
396
-
397
-		$shareTmpl['hideFileList'] = $hideFileList;
398
-		$shareTmpl['shareOwner'] = $this->userManager->get($share->getShareOwner())->getDisplayName();
399
-		$shareTmpl['downloadURL'] = $this->urlGenerator->linkToRouteAbsolute('files_sharing.sharecontroller.downloadShare', ['token' => $this->getToken()]);
400
-		$shareTmpl['shareUrl'] = $this->urlGenerator->linkToRouteAbsolute('files_sharing.sharecontroller.showShare', ['token' => $this->getToken()]);
401
-		$shareTmpl['maxSizeAnimateGif'] = $this->config->getSystemValue('max_filesize_animated_gifs_public_sharing', 10);
402
-		$shareTmpl['previewEnabled'] = $this->config->getSystemValue('enable_previews', true);
403
-		$shareTmpl['previewMaxX'] = $this->config->getSystemValue('preview_max_x', 1024);
404
-		$shareTmpl['previewMaxY'] = $this->config->getSystemValue('preview_max_y', 1024);
405
-		$shareTmpl['disclaimer'] = $this->config->getAppValue('core', 'shareapi_public_link_disclaimertext', null);
406
-		$shareTmpl['previewURL'] = $shareTmpl['downloadURL'];
407
-
408
-		if ($shareTmpl['previewSupported']) {
409
-			$shareTmpl['previewImage'] = $this->urlGenerator->linkToRouteAbsolute( 'files_sharing.PublicPreview.getPreview',
410
-				['x' => 200, 'y' => 200, 'file' => $shareTmpl['directory_path'], 'token' => $shareTmpl['dirToken']]);
411
-			$ogPreview = $shareTmpl['previewImage'];
412
-
413
-			// We just have direct previews for image files
414
-			if ($shareNode->getMimePart() === 'image') {
415
-				$shareTmpl['previewURL'] = $this->urlGenerator->linkToRouteAbsolute('files_sharing.publicpreview.directLink', ['token' => $this->getToken()]);
416
-
417
-				$ogPreview = $shareTmpl['previewURL'];
418
-
419
-				//Whatapp is kind of picky about their size requirements
420
-				if ($this->request->isUserAgent(['/^WhatsApp/'])) {
421
-					$ogPreview = $this->urlGenerator->linkToRouteAbsolute('files_sharing.PublicPreview.getPreview', [
422
-						'token' => $this->getToken(),
423
-						'x' => 256,
424
-						'y' => 256,
425
-						'a' => true,
426
-					]);
427
-				}
428
-			}
429
-		} else {
430
-			$shareTmpl['previewImage'] = $this->urlGenerator->getAbsoluteURL($this->urlGenerator->imagePath('core', 'favicon-fb.png'));
431
-			$ogPreview = $shareTmpl['previewImage'];
432
-		}
433
-
434
-		// Load files we need
435
-		\OCP\Util::addScript('files', 'semaphore');
436
-		\OCP\Util::addScript('files', 'file-upload');
437
-		\OCP\Util::addStyle('files_sharing', 'publicView');
438
-		\OCP\Util::addScript('files_sharing', 'public');
439
-		\OCP\Util::addScript('files_sharing', 'templates');
440
-		\OCP\Util::addScript('files', 'fileactions');
441
-		\OCP\Util::addScript('files', 'fileactionsmenu');
442
-		\OCP\Util::addScript('files', 'jquery.fileupload');
443
-		\OCP\Util::addScript('files_sharing', 'files_drop');
444
-
445
-		if (isset($shareTmpl['folder'])) {
446
-			// JS required for folders
447
-			\OCP\Util::addStyle('files', 'merged');
448
-			\OCP\Util::addScript('files', 'filesummary');
449
-			\OCP\Util::addScript('files', 'templates');
450
-			\OCP\Util::addScript('files', 'breadcrumb');
451
-			\OCP\Util::addScript('files', 'fileinfomodel');
452
-			\OCP\Util::addScript('files', 'newfilemenu');
453
-			\OCP\Util::addScript('files', 'files');
454
-			\OCP\Util::addScript('files', 'filemultiselectmenu');
455
-			\OCP\Util::addScript('files', 'filelist');
456
-			\OCP\Util::addScript('files', 'keyboardshortcuts');
457
-			\OCP\Util::addScript('files', 'operationprogressbar');
458
-
459
-			// Load Viewer scripts
460
-			if (class_exists(LoadViewer::class)) {
461
-				$this->eventDispatcher->dispatch(LoadViewer::class, new LoadViewer());
462
-			}
463
-		}
464
-
465
-		// OpenGraph Support: http://ogp.me/
466
-		\OCP\Util::addHeader('meta', ['property' => "og:title", 'content' => $shareTmpl['filename']]);
467
-		\OCP\Util::addHeader('meta', ['property' => "og:description", 'content' => $this->defaults->getName() . ($this->defaults->getSlogan() !== '' ? ' - ' . $this->defaults->getSlogan() : '')]);
468
-		\OCP\Util::addHeader('meta', ['property' => "og:site_name", 'content' => $this->defaults->getName()]);
469
-		\OCP\Util::addHeader('meta', ['property' => "og:url", 'content' => $shareTmpl['shareUrl']]);
470
-		\OCP\Util::addHeader('meta', ['property' => "og:type", 'content' => "object"]);
471
-		\OCP\Util::addHeader('meta', ['property' => "og:image", 'content' => $ogPreview]);
472
-
473
-		$event = new GenericEvent(null, ['share' => $share]);
474
-		$this->eventDispatcher->dispatch('OCA\Files_Sharing::loadAdditionalScripts', $event);
475
-
476
-		$csp = new \OCP\AppFramework\Http\ContentSecurityPolicy();
477
-		$csp->addAllowedFrameDomain('\'self\'');
478
-
479
-		$response = new PublicTemplateResponse($this->appName, 'public', $shareTmpl);
480
-		$response->setHeaderTitle($shareTmpl['filename']);
481
-		$response->setHeaderDetails($this->l10n->t('shared by %s', [$shareTmpl['displayName']]));
482
-
483
-		$isNoneFileDropFolder = $shareIsFolder === false || $share->getPermissions() !== \OCP\Constants::PERMISSION_CREATE;
484
-
485
-		if ($isNoneFileDropFolder && !$share->getHideDownload()) {
486
-			\OCP\Util::addScript('files_sharing', 'public_note');
487
-
488
-			$downloadWhite = new SimpleMenuAction('download', $this->l10n->t('Download'), 'icon-download-white', $shareTmpl['downloadURL'], 0);
489
-			$downloadAllWhite = new SimpleMenuAction('download', $this->l10n->t('Download all files'), 'icon-download-white', $shareTmpl['downloadURL'], 0);
490
-			$download = new SimpleMenuAction('download', $this->l10n->t('Download'), 'icon-download', $shareTmpl['downloadURL'], 10, $shareTmpl['fileSize']);
491
-			$downloadAll = new SimpleMenuAction('download', $this->l10n->t('Download all files'), 'icon-download', $shareTmpl['downloadURL'], 10, $shareTmpl['fileSize']);
492
-			$directLink = new LinkMenuAction($this->l10n->t('Direct link'), 'icon-public', $shareTmpl['previewURL']);
493
-			$externalShare = new ExternalShareMenuAction($this->l10n->t('Add to your Nextcloud'), 'icon-external', $shareTmpl['owner'], $shareTmpl['displayName'], $shareTmpl['filename']);
494
-
495
-			$responseComposer = [];
496
-
497
-			if ($shareIsFolder) {
498
-				$responseComposer[] = $downloadAllWhite;
499
-				$responseComposer[] = $downloadAll;
500
-			} else {
501
-				$responseComposer[] = $downloadWhite;
502
-				$responseComposer[] = $download;
503
-			}
504
-			$responseComposer[] = $directLink;
505
-			if ($this->federatedShareProvider->isOutgoingServer2serverShareEnabled()) {
506
-				$responseComposer[] = $externalShare;
507
-			}
508
-
509
-			$response->setHeaderActions($responseComposer);
510
-		}
511
-
512
-		$response->setContentSecurityPolicy($csp);
513
-
514
-		$this->emitAccessShareHook($share);
515
-
516
-		return $response;
517
-	}
518
-
519
-	/**
520
-	 * @PublicPage
521
-	 * @NoCSRFRequired
522
-	 *
523
-	 * @param string $token
524
-	 * @param string $files
525
-	 * @param string $path
526
-	 * @param string $downloadStartSecret
527
-	 * @return void|\OCP\AppFramework\Http\Response
528
-	 * @throws NotFoundException
529
-	 */
530
-	public function downloadShare($token, $files = null, $path = '', $downloadStartSecret = '') {
531
-		\OC_User::setIncognitoMode(true);
532
-
533
-		$share = $this->shareManager->getShareByToken($token);
534
-
535
-		if(!($share->getPermissions() & \OCP\Constants::PERMISSION_READ)) {
536
-			return new \OCP\AppFramework\Http\DataResponse('Share is read-only');
537
-		}
538
-
539
-		$files_list = null;
540
-		if (!is_null($files)) { // download selected files
541
-			$files_list = json_decode($files);
542
-			// in case we get only a single file
543
-			if ($files_list === null) {
544
-				$files_list = [$files];
545
-			}
546
-			// Just in case $files is a single int like '1234'
547
-			if (!is_array($files_list)) {
548
-				$files_list = [$files_list];
549
-			}
550
-		}
551
-
552
-		if (!$this->validateShare($share)) {
553
-			throw new NotFoundException();
554
-		}
555
-
556
-		$userFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
557
-		$originalSharePath = $userFolder->getRelativePath($share->getNode()->getPath());
558
-
559
-
560
-		// Single file share
561
-		if ($share->getNode() instanceof \OCP\Files\File) {
562
-			// Single file download
563
-			$this->singleFileDownloaded($share, $share->getNode());
564
-		}
565
-		// Directory share
566
-		else {
567
-			/** @var \OCP\Files\Folder $node */
568
-			$node = $share->getNode();
569
-
570
-			// Try to get the path
571
-			if ($path !== '') {
572
-				try {
573
-					$node = $node->get($path);
574
-				} catch (NotFoundException $e) {
575
-					$this->emitAccessShareHook($share, 404, 'Share not found');
576
-					return new NotFoundResponse();
577
-				}
578
-			}
579
-
580
-			$originalSharePath = $userFolder->getRelativePath($node->getPath());
581
-
582
-			if ($node instanceof \OCP\Files\File) {
583
-				// Single file download
584
-				$this->singleFileDownloaded($share, $share->getNode());
585
-			} else {
586
-				try {
587
-					if (!empty($files_list)) {
588
-						$this->fileListDownloaded($share, $files_list, $node);
589
-					} else {
590
-						// The folder is downloaded
591
-						$this->singleFileDownloaded($share, $share->getNode());
592
-					}
593
-				} catch (NotFoundException $e) {
594
-					return new NotFoundResponse();
595
-				}
596
-			}
597
-		}
598
-
599
-		/* FIXME: We should do this all nicely in OCP */
600
-		OC_Util::tearDownFS();
601
-		OC_Util::setupFS($share->getShareOwner());
602
-
603
-		/**
604
-		 * this sets a cookie to be able to recognize the start of the download
605
-		 * the content must not be longer than 32 characters and must only contain
606
-		 * alphanumeric characters
607
-		 */
608
-		if (!empty($downloadStartSecret)
609
-			&& !isset($downloadStartSecret[32])
610
-			&& preg_match('!^[a-zA-Z0-9]+$!', $downloadStartSecret) === 1) {
611
-
612
-			// FIXME: set on the response once we use an actual app framework response
613
-			setcookie('ocDownloadStarted', $downloadStartSecret, time() + 20, '/');
614
-		}
615
-
616
-		$this->emitAccessShareHook($share);
617
-
618
-		$server_params = [ 'head' => $this->request->getMethod() === 'HEAD' ];
619
-
620
-		/**
621
-		 * Http range requests support
622
-		 */
623
-		if (isset($_SERVER['HTTP_RANGE'])) {
624
-			$server_params['range'] = $this->request->getHeader('Range');
625
-		}
626
-
627
-		// download selected files
628
-		if (!is_null($files) && $files !== '') {
629
-			// FIXME: The exit is required here because otherwise the AppFramework is trying to add headers as well
630
-			// after dispatching the request which results in a "Cannot modify header information" notice.
631
-			OC_Files::get($originalSharePath, $files_list, $server_params);
632
-			exit();
633
-		} else {
634
-			// FIXME: The exit is required here because otherwise the AppFramework is trying to add headers as well
635
-			// after dispatching the request which results in a "Cannot modify header information" notice.
636
-			OC_Files::get(dirname($originalSharePath), basename($originalSharePath), $server_params);
637
-			exit();
638
-		}
639
-	}
640
-
641
-	/**
642
-	 * create activity for every downloaded file
643
-	 *
644
-	 * @param Share\IShare $share
645
-	 * @param array $files_list
646
-	 * @param \OCP\Files\Folder $node
647
-	 * @throws NotFoundException when trying to download a folder or multiple files of a "hide download" share
648
-	 */
649
-	protected function fileListDownloaded(Share\IShare $share, array $files_list, \OCP\Files\Folder $node) {
650
-		if ($share->getHideDownload() && count($files_list) > 1) {
651
-			throw new NotFoundException('Downloading more than 1 file');
652
-		}
653
-
654
-		foreach ($files_list as $file) {
655
-			$subNode = $node->get($file);
656
-			$this->singleFileDownloaded($share, $subNode);
657
-		}
658
-
659
-	}
660
-
661
-	/**
662
-	 * create activity if a single file was downloaded from a link share
663
-	 *
664
-	 * @param Share\IShare $share
665
-	 * @throws NotFoundException when trying to download a folder of a "hide download" share
666
-	 */
667
-	protected function singleFileDownloaded(Share\IShare $share, \OCP\Files\Node $node) {
668
-		if ($share->getHideDownload() && $node instanceof Folder) {
669
-			throw new NotFoundException('Downloading a folder');
670
-		}
671
-
672
-		$fileId = $node->getId();
673
-
674
-		$userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
675
-		$userNodeList = $userFolder->getById($fileId);
676
-		$userNode = $userNodeList[0];
677
-		$ownerFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
678
-		$userPath = $userFolder->getRelativePath($userNode->getPath());
679
-		$ownerPath = $ownerFolder->getRelativePath($node->getPath());
680
-
681
-		$parameters = [$userPath];
682
-
683
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
684
-			if ($node instanceof \OCP\Files\File) {
685
-				$subject = Downloads::SUBJECT_SHARED_FILE_BY_EMAIL_DOWNLOADED;
686
-			} else {
687
-				$subject = Downloads::SUBJECT_SHARED_FOLDER_BY_EMAIL_DOWNLOADED;
688
-			}
689
-			$parameters[] = $share->getSharedWith();
690
-		} else {
691
-			if ($node instanceof \OCP\Files\File) {
692
-				$subject = Downloads::SUBJECT_PUBLIC_SHARED_FILE_DOWNLOADED;
693
-			} else {
694
-				$subject = Downloads::SUBJECT_PUBLIC_SHARED_FOLDER_DOWNLOADED;
695
-			}
696
-		}
697
-
698
-		$this->publishActivity($subject, $parameters, $share->getSharedBy(), $fileId, $userPath);
699
-
700
-		if ($share->getShareOwner() !== $share->getSharedBy()) {
701
-			$parameters[0] = $ownerPath;
702
-			$this->publishActivity($subject, $parameters, $share->getShareOwner(), $fileId, $ownerPath);
703
-		}
704
-	}
705
-
706
-	/**
707
-	 * publish activity
708
-	 *
709
-	 * @param string $subject
710
-	 * @param array $parameters
711
-	 * @param string $affectedUser
712
-	 * @param int $fileId
713
-	 * @param string $filePath
714
-	 */
715
-	protected function publishActivity($subject,
716
-										array $parameters,
717
-										$affectedUser,
718
-										$fileId,
719
-										$filePath) {
720
-
721
-		$event = $this->activityManager->generateEvent();
722
-		$event->setApp('files_sharing')
723
-			->setType('public_links')
724
-			->setSubject($subject, $parameters)
725
-			->setAffectedUser($affectedUser)
726
-			->setObject('files', $fileId, $filePath);
727
-		$this->activityManager->publish($event);
728
-	}
363
+            $freeSpace = $share->getNode()->getStorage()->free_space($share->getNode()->getInternalPath());
364
+            if ($freeSpace < \OCP\Files\FileInfo::SPACE_UNLIMITED) {
365
+                $freeSpace = max($freeSpace, 0);
366
+            } else {
367
+                $freeSpace = (INF > 0) ? INF: PHP_INT_MAX; // work around https://bugs.php.net/bug.php?id=69188
368
+            }
369
+
370
+            $hideFileList = !($share->getPermissions() & \OCP\Constants::PERMISSION_READ);
371
+            $maxUploadFilesize = $freeSpace;
372
+
373
+            $folder = new Template('files', 'list', '');
374
+
375
+            $folder->assign('dir', $shareNode->getRelativePath($folderNode->getPath()));
376
+            $folder->assign('dirToken', $this->getToken());
377
+            $folder->assign('permissions', \OCP\Constants::PERMISSION_READ);
378
+            $folder->assign('isPublic', true);
379
+            $folder->assign('hideFileList', $hideFileList);
380
+            $folder->assign('publicUploadEnabled', 'no');
381
+            // default to list view
382
+            $folder->assign('showgridview', false);
383
+            $folder->assign('uploadMaxFilesize', $maxUploadFilesize);
384
+            $folder->assign('uploadMaxHumanFilesize', \OCP\Util::humanFileSize($maxUploadFilesize));
385
+            $folder->assign('freeSpace', $freeSpace);
386
+            $folder->assign('usedSpacePercent', 0);
387
+            $folder->assign('trash', false);
388
+            $shareTmpl['folder'] = $folder->fetchPage();
389
+        } else {
390
+            $shareIsFolder = false;
391
+        }
392
+
393
+        // default to list view
394
+        $shareTmpl['showgridview'] = false;
395
+
396
+        $shareTmpl['hideFileList'] = $hideFileList;
397
+        $shareTmpl['shareOwner'] = $this->userManager->get($share->getShareOwner())->getDisplayName();
398
+        $shareTmpl['downloadURL'] = $this->urlGenerator->linkToRouteAbsolute('files_sharing.sharecontroller.downloadShare', ['token' => $this->getToken()]);
399
+        $shareTmpl['shareUrl'] = $this->urlGenerator->linkToRouteAbsolute('files_sharing.sharecontroller.showShare', ['token' => $this->getToken()]);
400
+        $shareTmpl['maxSizeAnimateGif'] = $this->config->getSystemValue('max_filesize_animated_gifs_public_sharing', 10);
401
+        $shareTmpl['previewEnabled'] = $this->config->getSystemValue('enable_previews', true);
402
+        $shareTmpl['previewMaxX'] = $this->config->getSystemValue('preview_max_x', 1024);
403
+        $shareTmpl['previewMaxY'] = $this->config->getSystemValue('preview_max_y', 1024);
404
+        $shareTmpl['disclaimer'] = $this->config->getAppValue('core', 'shareapi_public_link_disclaimertext', null);
405
+        $shareTmpl['previewURL'] = $shareTmpl['downloadURL'];
406
+
407
+        if ($shareTmpl['previewSupported']) {
408
+            $shareTmpl['previewImage'] = $this->urlGenerator->linkToRouteAbsolute( 'files_sharing.PublicPreview.getPreview',
409
+                ['x' => 200, 'y' => 200, 'file' => $shareTmpl['directory_path'], 'token' => $shareTmpl['dirToken']]);
410
+            $ogPreview = $shareTmpl['previewImage'];
411
+
412
+            // We just have direct previews for image files
413
+            if ($shareNode->getMimePart() === 'image') {
414
+                $shareTmpl['previewURL'] = $this->urlGenerator->linkToRouteAbsolute('files_sharing.publicpreview.directLink', ['token' => $this->getToken()]);
415
+
416
+                $ogPreview = $shareTmpl['previewURL'];
417
+
418
+                //Whatapp is kind of picky about their size requirements
419
+                if ($this->request->isUserAgent(['/^WhatsApp/'])) {
420
+                    $ogPreview = $this->urlGenerator->linkToRouteAbsolute('files_sharing.PublicPreview.getPreview', [
421
+                        'token' => $this->getToken(),
422
+                        'x' => 256,
423
+                        'y' => 256,
424
+                        'a' => true,
425
+                    ]);
426
+                }
427
+            }
428
+        } else {
429
+            $shareTmpl['previewImage'] = $this->urlGenerator->getAbsoluteURL($this->urlGenerator->imagePath('core', 'favicon-fb.png'));
430
+            $ogPreview = $shareTmpl['previewImage'];
431
+        }
432
+
433
+        // Load files we need
434
+        \OCP\Util::addScript('files', 'semaphore');
435
+        \OCP\Util::addScript('files', 'file-upload');
436
+        \OCP\Util::addStyle('files_sharing', 'publicView');
437
+        \OCP\Util::addScript('files_sharing', 'public');
438
+        \OCP\Util::addScript('files_sharing', 'templates');
439
+        \OCP\Util::addScript('files', 'fileactions');
440
+        \OCP\Util::addScript('files', 'fileactionsmenu');
441
+        \OCP\Util::addScript('files', 'jquery.fileupload');
442
+        \OCP\Util::addScript('files_sharing', 'files_drop');
443
+
444
+        if (isset($shareTmpl['folder'])) {
445
+            // JS required for folders
446
+            \OCP\Util::addStyle('files', 'merged');
447
+            \OCP\Util::addScript('files', 'filesummary');
448
+            \OCP\Util::addScript('files', 'templates');
449
+            \OCP\Util::addScript('files', 'breadcrumb');
450
+            \OCP\Util::addScript('files', 'fileinfomodel');
451
+            \OCP\Util::addScript('files', 'newfilemenu');
452
+            \OCP\Util::addScript('files', 'files');
453
+            \OCP\Util::addScript('files', 'filemultiselectmenu');
454
+            \OCP\Util::addScript('files', 'filelist');
455
+            \OCP\Util::addScript('files', 'keyboardshortcuts');
456
+            \OCP\Util::addScript('files', 'operationprogressbar');
457
+
458
+            // Load Viewer scripts
459
+            if (class_exists(LoadViewer::class)) {
460
+                $this->eventDispatcher->dispatch(LoadViewer::class, new LoadViewer());
461
+            }
462
+        }
463
+
464
+        // OpenGraph Support: http://ogp.me/
465
+        \OCP\Util::addHeader('meta', ['property' => "og:title", 'content' => $shareTmpl['filename']]);
466
+        \OCP\Util::addHeader('meta', ['property' => "og:description", 'content' => $this->defaults->getName() . ($this->defaults->getSlogan() !== '' ? ' - ' . $this->defaults->getSlogan() : '')]);
467
+        \OCP\Util::addHeader('meta', ['property' => "og:site_name", 'content' => $this->defaults->getName()]);
468
+        \OCP\Util::addHeader('meta', ['property' => "og:url", 'content' => $shareTmpl['shareUrl']]);
469
+        \OCP\Util::addHeader('meta', ['property' => "og:type", 'content' => "object"]);
470
+        \OCP\Util::addHeader('meta', ['property' => "og:image", 'content' => $ogPreview]);
471
+
472
+        $event = new GenericEvent(null, ['share' => $share]);
473
+        $this->eventDispatcher->dispatch('OCA\Files_Sharing::loadAdditionalScripts', $event);
474
+
475
+        $csp = new \OCP\AppFramework\Http\ContentSecurityPolicy();
476
+        $csp->addAllowedFrameDomain('\'self\'');
477
+
478
+        $response = new PublicTemplateResponse($this->appName, 'public', $shareTmpl);
479
+        $response->setHeaderTitle($shareTmpl['filename']);
480
+        $response->setHeaderDetails($this->l10n->t('shared by %s', [$shareTmpl['displayName']]));
481
+
482
+        $isNoneFileDropFolder = $shareIsFolder === false || $share->getPermissions() !== \OCP\Constants::PERMISSION_CREATE;
483
+
484
+        if ($isNoneFileDropFolder && !$share->getHideDownload()) {
485
+            \OCP\Util::addScript('files_sharing', 'public_note');
486
+
487
+            $downloadWhite = new SimpleMenuAction('download', $this->l10n->t('Download'), 'icon-download-white', $shareTmpl['downloadURL'], 0);
488
+            $downloadAllWhite = new SimpleMenuAction('download', $this->l10n->t('Download all files'), 'icon-download-white', $shareTmpl['downloadURL'], 0);
489
+            $download = new SimpleMenuAction('download', $this->l10n->t('Download'), 'icon-download', $shareTmpl['downloadURL'], 10, $shareTmpl['fileSize']);
490
+            $downloadAll = new SimpleMenuAction('download', $this->l10n->t('Download all files'), 'icon-download', $shareTmpl['downloadURL'], 10, $shareTmpl['fileSize']);
491
+            $directLink = new LinkMenuAction($this->l10n->t('Direct link'), 'icon-public', $shareTmpl['previewURL']);
492
+            $externalShare = new ExternalShareMenuAction($this->l10n->t('Add to your Nextcloud'), 'icon-external', $shareTmpl['owner'], $shareTmpl['displayName'], $shareTmpl['filename']);
493
+
494
+            $responseComposer = [];
495
+
496
+            if ($shareIsFolder) {
497
+                $responseComposer[] = $downloadAllWhite;
498
+                $responseComposer[] = $downloadAll;
499
+            } else {
500
+                $responseComposer[] = $downloadWhite;
501
+                $responseComposer[] = $download;
502
+            }
503
+            $responseComposer[] = $directLink;
504
+            if ($this->federatedShareProvider->isOutgoingServer2serverShareEnabled()) {
505
+                $responseComposer[] = $externalShare;
506
+            }
507
+
508
+            $response->setHeaderActions($responseComposer);
509
+        }
510
+
511
+        $response->setContentSecurityPolicy($csp);
512
+
513
+        $this->emitAccessShareHook($share);
514
+
515
+        return $response;
516
+    }
517
+
518
+    /**
519
+     * @PublicPage
520
+     * @NoCSRFRequired
521
+     *
522
+     * @param string $token
523
+     * @param string $files
524
+     * @param string $path
525
+     * @param string $downloadStartSecret
526
+     * @return void|\OCP\AppFramework\Http\Response
527
+     * @throws NotFoundException
528
+     */
529
+    public function downloadShare($token, $files = null, $path = '', $downloadStartSecret = '') {
530
+        \OC_User::setIncognitoMode(true);
531
+
532
+        $share = $this->shareManager->getShareByToken($token);
533
+
534
+        if(!($share->getPermissions() & \OCP\Constants::PERMISSION_READ)) {
535
+            return new \OCP\AppFramework\Http\DataResponse('Share is read-only');
536
+        }
537
+
538
+        $files_list = null;
539
+        if (!is_null($files)) { // download selected files
540
+            $files_list = json_decode($files);
541
+            // in case we get only a single file
542
+            if ($files_list === null) {
543
+                $files_list = [$files];
544
+            }
545
+            // Just in case $files is a single int like '1234'
546
+            if (!is_array($files_list)) {
547
+                $files_list = [$files_list];
548
+            }
549
+        }
550
+
551
+        if (!$this->validateShare($share)) {
552
+            throw new NotFoundException();
553
+        }
554
+
555
+        $userFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
556
+        $originalSharePath = $userFolder->getRelativePath($share->getNode()->getPath());
557
+
558
+
559
+        // Single file share
560
+        if ($share->getNode() instanceof \OCP\Files\File) {
561
+            // Single file download
562
+            $this->singleFileDownloaded($share, $share->getNode());
563
+        }
564
+        // Directory share
565
+        else {
566
+            /** @var \OCP\Files\Folder $node */
567
+            $node = $share->getNode();
568
+
569
+            // Try to get the path
570
+            if ($path !== '') {
571
+                try {
572
+                    $node = $node->get($path);
573
+                } catch (NotFoundException $e) {
574
+                    $this->emitAccessShareHook($share, 404, 'Share not found');
575
+                    return new NotFoundResponse();
576
+                }
577
+            }
578
+
579
+            $originalSharePath = $userFolder->getRelativePath($node->getPath());
580
+
581
+            if ($node instanceof \OCP\Files\File) {
582
+                // Single file download
583
+                $this->singleFileDownloaded($share, $share->getNode());
584
+            } else {
585
+                try {
586
+                    if (!empty($files_list)) {
587
+                        $this->fileListDownloaded($share, $files_list, $node);
588
+                    } else {
589
+                        // The folder is downloaded
590
+                        $this->singleFileDownloaded($share, $share->getNode());
591
+                    }
592
+                } catch (NotFoundException $e) {
593
+                    return new NotFoundResponse();
594
+                }
595
+            }
596
+        }
597
+
598
+        /* FIXME: We should do this all nicely in OCP */
599
+        OC_Util::tearDownFS();
600
+        OC_Util::setupFS($share->getShareOwner());
601
+
602
+        /**
603
+         * this sets a cookie to be able to recognize the start of the download
604
+         * the content must not be longer than 32 characters and must only contain
605
+         * alphanumeric characters
606
+         */
607
+        if (!empty($downloadStartSecret)
608
+            && !isset($downloadStartSecret[32])
609
+            && preg_match('!^[a-zA-Z0-9]+$!', $downloadStartSecret) === 1) {
610
+
611
+            // FIXME: set on the response once we use an actual app framework response
612
+            setcookie('ocDownloadStarted', $downloadStartSecret, time() + 20, '/');
613
+        }
614
+
615
+        $this->emitAccessShareHook($share);
616
+
617
+        $server_params = [ 'head' => $this->request->getMethod() === 'HEAD' ];
618
+
619
+        /**
620
+         * Http range requests support
621
+         */
622
+        if (isset($_SERVER['HTTP_RANGE'])) {
623
+            $server_params['range'] = $this->request->getHeader('Range');
624
+        }
625
+
626
+        // download selected files
627
+        if (!is_null($files) && $files !== '') {
628
+            // FIXME: The exit is required here because otherwise the AppFramework is trying to add headers as well
629
+            // after dispatching the request which results in a "Cannot modify header information" notice.
630
+            OC_Files::get($originalSharePath, $files_list, $server_params);
631
+            exit();
632
+        } else {
633
+            // FIXME: The exit is required here because otherwise the AppFramework is trying to add headers as well
634
+            // after dispatching the request which results in a "Cannot modify header information" notice.
635
+            OC_Files::get(dirname($originalSharePath), basename($originalSharePath), $server_params);
636
+            exit();
637
+        }
638
+    }
639
+
640
+    /**
641
+     * create activity for every downloaded file
642
+     *
643
+     * @param Share\IShare $share
644
+     * @param array $files_list
645
+     * @param \OCP\Files\Folder $node
646
+     * @throws NotFoundException when trying to download a folder or multiple files of a "hide download" share
647
+     */
648
+    protected function fileListDownloaded(Share\IShare $share, array $files_list, \OCP\Files\Folder $node) {
649
+        if ($share->getHideDownload() && count($files_list) > 1) {
650
+            throw new NotFoundException('Downloading more than 1 file');
651
+        }
652
+
653
+        foreach ($files_list as $file) {
654
+            $subNode = $node->get($file);
655
+            $this->singleFileDownloaded($share, $subNode);
656
+        }
657
+
658
+    }
659
+
660
+    /**
661
+     * create activity if a single file was downloaded from a link share
662
+     *
663
+     * @param Share\IShare $share
664
+     * @throws NotFoundException when trying to download a folder of a "hide download" share
665
+     */
666
+    protected function singleFileDownloaded(Share\IShare $share, \OCP\Files\Node $node) {
667
+        if ($share->getHideDownload() && $node instanceof Folder) {
668
+            throw new NotFoundException('Downloading a folder');
669
+        }
670
+
671
+        $fileId = $node->getId();
672
+
673
+        $userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
674
+        $userNodeList = $userFolder->getById($fileId);
675
+        $userNode = $userNodeList[0];
676
+        $ownerFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
677
+        $userPath = $userFolder->getRelativePath($userNode->getPath());
678
+        $ownerPath = $ownerFolder->getRelativePath($node->getPath());
679
+
680
+        $parameters = [$userPath];
681
+
682
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
683
+            if ($node instanceof \OCP\Files\File) {
684
+                $subject = Downloads::SUBJECT_SHARED_FILE_BY_EMAIL_DOWNLOADED;
685
+            } else {
686
+                $subject = Downloads::SUBJECT_SHARED_FOLDER_BY_EMAIL_DOWNLOADED;
687
+            }
688
+            $parameters[] = $share->getSharedWith();
689
+        } else {
690
+            if ($node instanceof \OCP\Files\File) {
691
+                $subject = Downloads::SUBJECT_PUBLIC_SHARED_FILE_DOWNLOADED;
692
+            } else {
693
+                $subject = Downloads::SUBJECT_PUBLIC_SHARED_FOLDER_DOWNLOADED;
694
+            }
695
+        }
696
+
697
+        $this->publishActivity($subject, $parameters, $share->getSharedBy(), $fileId, $userPath);
698
+
699
+        if ($share->getShareOwner() !== $share->getSharedBy()) {
700
+            $parameters[0] = $ownerPath;
701
+            $this->publishActivity($subject, $parameters, $share->getShareOwner(), $fileId, $ownerPath);
702
+        }
703
+    }
704
+
705
+    /**
706
+     * publish activity
707
+     *
708
+     * @param string $subject
709
+     * @param array $parameters
710
+     * @param string $affectedUser
711
+     * @param int $fileId
712
+     * @param string $filePath
713
+     */
714
+    protected function publishActivity($subject,
715
+                                        array $parameters,
716
+                                        $affectedUser,
717
+                                        $fileId,
718
+                                        $filePath) {
719
+
720
+        $event = $this->activityManager->generateEvent();
721
+        $event->setApp('files_sharing')
722
+            ->setType('public_links')
723
+            ->setSubject($subject, $parameters)
724
+            ->setAffectedUser($affectedUser)
725
+            ->setObject('files', $fileId, $filePath);
726
+        $this->activityManager->publish($event);
727
+    }
729 728
 
730 729
 
731 730
 }
Please login to merge, or discard this patch.
apps/user_ldap/ajax/deleteConfiguration.php 1 patch
Indentation   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -33,8 +33,8 @@
 block discarded – undo
33 33
 $prefix = (string)$_POST['ldap_serverconfig_chooser'];
34 34
 $helper = new \OCA\User_LDAP\Helper(\OC::$server->getConfig());
35 35
 if($helper->deleteServerConfiguration($prefix)) {
36
-	\OC_JSON::success();
36
+    \OC_JSON::success();
37 37
 } else {
38
-	$l = \OC::$server->getL10N('user_ldap');
39
-	\OC_JSON::error(['message' => $l->t('Failed to delete the server configuration')]);
38
+    $l = \OC::$server->getL10N('user_ldap');
39
+    \OC_JSON::error(['message' => $l->t('Failed to delete the server configuration')]);
40 40
 }
Please login to merge, or discard this patch.
apps/user_ldap/ajax/wizard.php 1 patch
Indentation   +85 added lines, -85 removed lines patch added patch discarded remove patch
@@ -36,13 +36,13 @@  discard block
 block discarded – undo
36 36
 $l = \OC::$server->getL10N('user_ldap');
37 37
 
38 38
 if(!isset($_POST['action'])) {
39
-	\OC_JSON::error(['message' => $l->t('No action specified')]);
39
+    \OC_JSON::error(['message' => $l->t('No action specified')]);
40 40
 }
41 41
 $action = (string)$_POST['action'];
42 42
 
43 43
 
44 44
 if(!isset($_POST['ldap_serverconfig_chooser'])) {
45
-	\OC_JSON::error(['message' => $l->t('No configuration specified')]);
45
+    \OC_JSON::error(['message' => $l->t('No configuration specified')]);
46 46
 }
47 47
 $prefix = (string)$_POST['ldap_serverconfig_chooser'];
48 48
 
@@ -55,96 +55,96 @@  discard block
 block discarded – undo
55 55
 $con->setIgnoreValidation(true);
56 56
 
57 57
 $userManager = new \OCA\User_LDAP\User\Manager(
58
-	\OC::$server->getConfig(),
59
-	new \OCA\User_LDAP\FilesystemHelper(),
60
-	new \OCA\User_LDAP\LogWrapper(),
61
-	\OC::$server->getAvatarManager(),
62
-	new \OCP\Image(),
63
-	\OC::$server->getDatabaseConnection(),
64
-	\OC::$server->getUserManager(),
65
-	\OC::$server->getNotificationManager());
58
+    \OC::$server->getConfig(),
59
+    new \OCA\User_LDAP\FilesystemHelper(),
60
+    new \OCA\User_LDAP\LogWrapper(),
61
+    \OC::$server->getAvatarManager(),
62
+    new \OCP\Image(),
63
+    \OC::$server->getDatabaseConnection(),
64
+    \OC::$server->getUserManager(),
65
+    \OC::$server->getNotificationManager());
66 66
 
67 67
 $access = new \OCA\User_LDAP\Access(
68
-	$con,
69
-	$ldapWrapper,
70
-	$userManager,
71
-	new \OCA\User_LDAP\Helper(\OC::$server->getConfig()),
72
-	\OC::$server->getConfig(),
73
-	\OC::$server->getUserManager()
68
+    $con,
69
+    $ldapWrapper,
70
+    $userManager,
71
+    new \OCA\User_LDAP\Helper(\OC::$server->getConfig()),
72
+    \OC::$server->getConfig(),
73
+    \OC::$server->getUserManager()
74 74
 );
75 75
 
76 76
 $wizard = new \OCA\User_LDAP\Wizard($configuration, $ldapWrapper, $access);
77 77
 
78 78
 switch($action) {
79
-	case 'guessPortAndTLS':
80
-	case 'guessBaseDN':
81
-	case 'detectEmailAttribute':
82
-	case 'detectUserDisplayNameAttribute':
83
-	case 'determineGroupMemberAssoc':
84
-	case 'determineUserObjectClasses':
85
-	case 'determineGroupObjectClasses':
86
-	case 'determineGroupsForUsers':
87
-	case 'determineGroupsForGroups':
88
-	case 'determineAttributes':
89
-	case 'getUserListFilter':
90
-	case 'getUserLoginFilter':
91
-	case 'getGroupFilter':
92
-	case 'countUsers':
93
-	case 'countGroups':
94
-	case 'countInBaseDN':
95
-		try {
96
-			$result = $wizard->$action();
97
-			if($result !== false) {
98
-				\OC_JSON::success($result->getResultArray());
99
-				exit;
100
-			}
101
-		} catch (\Exception $e) {
102
-			\OC_JSON::error(['message' => $e->getMessage(), 'code' => $e->getCode()]);
103
-			exit;
104
-		}
105
-		\OC_JSON::error();
106
-		exit;
107
-		break;
79
+    case 'guessPortAndTLS':
80
+    case 'guessBaseDN':
81
+    case 'detectEmailAttribute':
82
+    case 'detectUserDisplayNameAttribute':
83
+    case 'determineGroupMemberAssoc':
84
+    case 'determineUserObjectClasses':
85
+    case 'determineGroupObjectClasses':
86
+    case 'determineGroupsForUsers':
87
+    case 'determineGroupsForGroups':
88
+    case 'determineAttributes':
89
+    case 'getUserListFilter':
90
+    case 'getUserLoginFilter':
91
+    case 'getGroupFilter':
92
+    case 'countUsers':
93
+    case 'countGroups':
94
+    case 'countInBaseDN':
95
+        try {
96
+            $result = $wizard->$action();
97
+            if($result !== false) {
98
+                \OC_JSON::success($result->getResultArray());
99
+                exit;
100
+            }
101
+        } catch (\Exception $e) {
102
+            \OC_JSON::error(['message' => $e->getMessage(), 'code' => $e->getCode()]);
103
+            exit;
104
+        }
105
+        \OC_JSON::error();
106
+        exit;
107
+        break;
108 108
 
109
-	case 'testLoginName': {
110
-		try {
111
-			$loginName = $_POST['ldap_test_loginname'];
112
-			$result = $wizard->$action($loginName);
113
-			if($result !== false) {
114
-				\OC_JSON::success($result->getResultArray());
115
-				exit;
116
-			}
117
-		} catch (\Exception $e) {
118
-			\OC_JSON::error(['message' => $e->getMessage()]);
119
-			exit;
120
-		}
121
-		\OC_JSON::error();
122
-		exit;
123
-		break;
124
-	}
109
+    case 'testLoginName': {
110
+        try {
111
+            $loginName = $_POST['ldap_test_loginname'];
112
+            $result = $wizard->$action($loginName);
113
+            if($result !== false) {
114
+                \OC_JSON::success($result->getResultArray());
115
+                exit;
116
+            }
117
+        } catch (\Exception $e) {
118
+            \OC_JSON::error(['message' => $e->getMessage()]);
119
+            exit;
120
+        }
121
+        \OC_JSON::error();
122
+        exit;
123
+        break;
124
+    }
125 125
 
126
-	case 'save':
127
-		$key = isset($_POST['cfgkey']) ? $_POST['cfgkey'] : false;
128
-		$val = isset($_POST['cfgval']) ? $_POST['cfgval'] : null;
129
-		if($key === false || is_null($val)) {
130
-			\OC_JSON::error(['message' => $l->t('No data specified')]);
131
-			exit;
132
-		}
133
-		$cfg = [$key => $val];
134
-		$setParameters = [];
135
-		$configuration->setConfiguration($cfg, $setParameters);
136
-		if(!in_array($key, $setParameters)) {
137
-			\OC_JSON::error(['message' => $l->t($key.
138
-				' Could not set configuration %s', $setParameters[0])]);
139
-			exit;
140
-		}
141
-		$configuration->saveConfiguration();
142
-		//clear the cache on save
143
-		$connection = new \OCA\User_LDAP\Connection($ldapWrapper, $prefix);
144
-		$connection->clearCache();
145
-		\OC_JSON::success();
146
-		break;
147
-	default:
148
-		\OC_JSON::error(['message' => $l->t('Action does not exist')]);
149
-		break;
126
+    case 'save':
127
+        $key = isset($_POST['cfgkey']) ? $_POST['cfgkey'] : false;
128
+        $val = isset($_POST['cfgval']) ? $_POST['cfgval'] : null;
129
+        if($key === false || is_null($val)) {
130
+            \OC_JSON::error(['message' => $l->t('No data specified')]);
131
+            exit;
132
+        }
133
+        $cfg = [$key => $val];
134
+        $setParameters = [];
135
+        $configuration->setConfiguration($cfg, $setParameters);
136
+        if(!in_array($key, $setParameters)) {
137
+            \OC_JSON::error(['message' => $l->t($key.
138
+                ' Could not set configuration %s', $setParameters[0])]);
139
+            exit;
140
+        }
141
+        $configuration->saveConfiguration();
142
+        //clear the cache on save
143
+        $connection = new \OCA\User_LDAP\Connection($ldapWrapper, $prefix);
144
+        $connection->clearCache();
145
+        \OC_JSON::success();
146
+        break;
147
+    default:
148
+        \OC_JSON::error(['message' => $l->t('Action does not exist')]);
149
+        break;
150 150
 }
Please login to merge, or discard this patch.
apps/user_ldap/ajax/getConfiguration.php 1 patch
Indentation   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -35,7 +35,7 @@
 block discarded – undo
35 35
 $connection = new \OCA\User_LDAP\Connection($ldapWrapper, $prefix);
36 36
 $configuration = $connection->getConfiguration();
37 37
 if (isset($configuration['ldap_agent_password']) && $configuration['ldap_agent_password'] !== '') {
38
-	// hide password
39
-	$configuration['ldap_agent_password'] = '**PASSWORD SET**';
38
+    // hide password
39
+    $configuration['ldap_agent_password'] = '**PASSWORD SET**';
40 40
 }
41 41
 \OC_JSON::success(['configuration' => $configuration]);
Please login to merge, or discard this patch.
apps/user_ldap/ajax/testConfiguration.php 1 patch
Indentation   +32 added lines, -32 removed lines patch added patch discarded remove patch
@@ -39,24 +39,24 @@  discard block
 block discarded – undo
39 39
 
40 40
 
41 41
 try {
42
-	$configurationOk = true;
43
-	$conf = $connection->getConfiguration();
44
-	if ($conf['ldap_configuration_active'] === '0') {
45
-		//needs to be true, otherwise it will also fail with an irritating message
46
-		$conf['ldap_configuration_active'] = '1';
47
-		$configurationOk = $connection->setConfiguration($conf);
48
-	}
49
-	if ($configurationOk) {
50
-		//Configuration is okay
51
-		/*
42
+    $configurationOk = true;
43
+    $conf = $connection->getConfiguration();
44
+    if ($conf['ldap_configuration_active'] === '0') {
45
+        //needs to be true, otherwise it will also fail with an irritating message
46
+        $conf['ldap_configuration_active'] = '1';
47
+        $configurationOk = $connection->setConfiguration($conf);
48
+    }
49
+    if ($configurationOk) {
50
+        //Configuration is okay
51
+        /*
52 52
 		 * Clossing the session since it won't be used from this point on. There might be a potential
53 53
 		 * race condition if a second request is made: either this request or the other might not
54 54
 		 * contact the LDAP backup server the first time when it should, but there shouldn't be any
55 55
 		 * problem with that other than the extra connection.
56 56
 		 */
57
-		\OC::$server->getSession()->close();
58
-		if ($connection->bind()) {
59
-			/*
57
+        \OC::$server->getSession()->close();
58
+        if ($connection->bind()) {
59
+            /*
60 60
 			 * This shiny if block is an ugly hack to find out whether anonymous
61 61
 			 * bind is possible on AD or not. Because AD happily and constantly
62 62
 			 * replies with success to any anonymous bind request, we need to
@@ -65,24 +65,24 @@  discard block
 block discarded – undo
65 65
 			 * exception by the LDAP wrapper. We catch this. Other cases may
66 66
 			 * pass (like e.g. expected syntax error).
67 67
 			 */
68
-			try {
69
-				$ldapWrapper->read($connection->getConnectionResource(), '', 'objectClass=*', ['dn']);
70
-			} catch (\Exception $e) {
71
-				if($e->getCode() === 1) {
72
-					\OC_JSON::error(['message' => $l->t('Invalid configuration: Anonymous binding is not allowed.')]);
73
-					exit;
74
-				}
75
-			}
76
-			\OC_JSON::success(['message'
77
-			=> $l->t('Valid configuration, connection established!')]);
78
-		} else {
79
-			\OC_JSON::error(['message'
80
-			=> $l->t('Valid configuration, but binding failed. Please check the server settings and credentials.')]);
81
-		}
82
-	} else {
83
-		\OC_JSON::error(['message'
84
-		=> $l->t('Invalid configuration. Please have a look at the logs for further details.')]);
85
-	}
68
+            try {
69
+                $ldapWrapper->read($connection->getConnectionResource(), '', 'objectClass=*', ['dn']);
70
+            } catch (\Exception $e) {
71
+                if($e->getCode() === 1) {
72
+                    \OC_JSON::error(['message' => $l->t('Invalid configuration: Anonymous binding is not allowed.')]);
73
+                    exit;
74
+                }
75
+            }
76
+            \OC_JSON::success(['message'
77
+            => $l->t('Valid configuration, connection established!')]);
78
+        } else {
79
+            \OC_JSON::error(['message'
80
+            => $l->t('Valid configuration, but binding failed. Please check the server settings and credentials.')]);
81
+        }
82
+    } else {
83
+        \OC_JSON::error(['message'
84
+        => $l->t('Invalid configuration. Please have a look at the logs for further details.')]);
85
+    }
86 86
 } catch (\Exception $e) {
87
-	\OC_JSON::error(['message' => $e->getMessage()]);
87
+    \OC_JSON::error(['message' => $e->getMessage()]);
88 88
 }
Please login to merge, or discard this patch.
apps/user_ldap/ajax/setConfiguration.php 1 patch
Indentation   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -36,11 +36,11 @@
 block discarded – undo
36 36
 // only legacy checkboxes (Advanced and Expert tab) need to be handled here,
37 37
 // the Wizard-like tabs handle it on their own
38 38
 $chkboxes = ['ldap_configuration_active', 'ldap_override_main_server',
39
-				  'ldap_turn_off_cert_check'];
39
+                    'ldap_turn_off_cert_check'];
40 40
 foreach($chkboxes as $boxid) {
41
-	if(!isset($_POST[$boxid])) {
42
-		$_POST[$boxid] = 0;
43
-	}
41
+    if(!isset($_POST[$boxid])) {
42
+        $_POST[$boxid] = 0;
43
+    }
44 44
 }
45 45
 
46 46
 $ldapWrapper = new OCA\User_LDAP\LDAP();
Please login to merge, or discard this patch.
apps/user_ldap/ajax/clearMappings.php 1 patch
Indentation   +20 added lines, -20 removed lines patch added patch discarded remove patch
@@ -35,26 +35,26 @@
 block discarded – undo
35 35
 $subject = (string)$_POST['ldap_clear_mapping'];
36 36
 $mapping = null;
37 37
 try {
38
-	if($subject === 'user') {
39
-		$mapping = new UserMapping(\OC::$server->getDatabaseConnection());
40
-		$result = $mapping->clearCb(
41
-			function ($uid) {
42
-				\OC::$server->getUserManager()->emit('\OC\User', 'preUnassignedUserId', [$uid]);
43
-			},
44
-			function ($uid) {
45
-				\OC::$server->getUserManager()->emit('\OC\User', 'postUnassignedUserId', [$uid]);
46
-			}
47
-		);
48
-	} else if($subject === 'group') {
49
-		$mapping = new GroupMapping(\OC::$server->getDatabaseConnection());
50
-		$result = $mapping->clear();
51
-	}
38
+    if($subject === 'user') {
39
+        $mapping = new UserMapping(\OC::$server->getDatabaseConnection());
40
+        $result = $mapping->clearCb(
41
+            function ($uid) {
42
+                \OC::$server->getUserManager()->emit('\OC\User', 'preUnassignedUserId', [$uid]);
43
+            },
44
+            function ($uid) {
45
+                \OC::$server->getUserManager()->emit('\OC\User', 'postUnassignedUserId', [$uid]);
46
+            }
47
+        );
48
+    } else if($subject === 'group') {
49
+        $mapping = new GroupMapping(\OC::$server->getDatabaseConnection());
50
+        $result = $mapping->clear();
51
+    }
52 52
 
53
-	if($mapping === null || !$result) {
54
-		$l = \OC::$server->getL10N('user_ldap');
55
-		throw new \Exception($l->t('Failed to clear the mappings.'));
56
-	}
57
-	\OC_JSON::success();
53
+    if($mapping === null || !$result) {
54
+        $l = \OC::$server->getL10N('user_ldap');
55
+        throw new \Exception($l->t('Failed to clear the mappings.'));
56
+    }
57
+    \OC_JSON::success();
58 58
 } catch (\Exception $e) {
59
-	\OC_JSON::error(['message' => $e->getMessage()]);
59
+    \OC_JSON::error(['message' => $e->getMessage()]);
60 60
 }
Please login to merge, or discard this patch.
apps/user_ldap/templates/part.wizard-server.php 1 patch
Indentation   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -2,14 +2,14 @@
 block discarded – undo
2 2
 		<p>
3 3
 		<select id="ldap_serverconfig_chooser" name="ldap_serverconfig_chooser">
4 4
 		<?php
5
-		$i = 1;
6
-		$sel = ' selected';
7
-		foreach($_['serverConfigurationPrefixes'] as $prefix) {
8
-			?>
5
+        $i = 1;
6
+        $sel = ' selected';
7
+        foreach($_['serverConfigurationPrefixes'] as $prefix) {
8
+            ?>
9 9
 			<option value="<?php p($prefix); ?>"<?php p($sel); $sel = ''; ?>><?php p($l->t('%s. Server:', [$i++]));?> <?php p(' '.$_['serverConfigurationHosts'][$prefix]); ?></option>
10 10
 			<?php
11
-		}
12
-		?>
11
+        }
12
+        ?>
13 13
 		</select>
14 14
 		<button type="button" id="ldap_action_add_configuration"
15 15
 			name="ldap_action_add_configuration" class="icon-add icon-default-style"
Please login to merge, or discard this patch.
apps/user_ldap/lib/Group_Proxy.php 1 patch
Indentation   +223 added lines, -223 removed lines patch added patch discarded remove patch
@@ -30,251 +30,251 @@
 block discarded – undo
30 30
 use OCP\Group\Backend\IGetDisplayNameBackend;
31 31
 
32 32
 class Group_Proxy extends Proxy implements \OCP\GroupInterface, IGroupLDAP, IGetDisplayNameBackend {
33
-	private $backends = [];
34
-	private $refBackend = null;
33
+    private $backends = [];
34
+    private $refBackend = null;
35 35
 
36
-	/**
37
-	 * Constructor
38
-	 * @param string[] $serverConfigPrefixes array containing the config Prefixes
39
-	 */
40
-	public function __construct($serverConfigPrefixes, ILDAPWrapper $ldap, GroupPluginManager $groupPluginManager) {
41
-		parent::__construct($ldap);
42
-		foreach($serverConfigPrefixes as $configPrefix) {
43
-			$this->backends[$configPrefix] =
44
-				new \OCA\User_LDAP\Group_LDAP($this->getAccess($configPrefix), $groupPluginManager);
45
-			if(is_null($this->refBackend)) {
46
-				$this->refBackend = &$this->backends[$configPrefix];
47
-			}
48
-		}
49
-	}
36
+    /**
37
+     * Constructor
38
+     * @param string[] $serverConfigPrefixes array containing the config Prefixes
39
+     */
40
+    public function __construct($serverConfigPrefixes, ILDAPWrapper $ldap, GroupPluginManager $groupPluginManager) {
41
+        parent::__construct($ldap);
42
+        foreach($serverConfigPrefixes as $configPrefix) {
43
+            $this->backends[$configPrefix] =
44
+                new \OCA\User_LDAP\Group_LDAP($this->getAccess($configPrefix), $groupPluginManager);
45
+            if(is_null($this->refBackend)) {
46
+                $this->refBackend = &$this->backends[$configPrefix];
47
+            }
48
+        }
49
+    }
50 50
 
51
-	/**
52
-	 * Tries the backends one after the other until a positive result is returned from the specified method
53
-	 * @param string $gid the gid connected to the request
54
-	 * @param string $method the method of the group backend that shall be called
55
-	 * @param array $parameters an array of parameters to be passed
56
-	 * @return mixed, the result of the method or false
57
-	 */
58
-	protected function walkBackends($gid, $method, $parameters) {
59
-		$cacheKey = $this->getGroupCacheKey($gid);
60
-		foreach($this->backends as $configPrefix => $backend) {
61
-			if($result = call_user_func_array([$backend, $method], $parameters)) {
62
-				$this->writeToCache($cacheKey, $configPrefix);
63
-				return $result;
64
-			}
65
-		}
66
-		return false;
67
-	}
51
+    /**
52
+     * Tries the backends one after the other until a positive result is returned from the specified method
53
+     * @param string $gid the gid connected to the request
54
+     * @param string $method the method of the group backend that shall be called
55
+     * @param array $parameters an array of parameters to be passed
56
+     * @return mixed, the result of the method or false
57
+     */
58
+    protected function walkBackends($gid, $method, $parameters) {
59
+        $cacheKey = $this->getGroupCacheKey($gid);
60
+        foreach($this->backends as $configPrefix => $backend) {
61
+            if($result = call_user_func_array([$backend, $method], $parameters)) {
62
+                $this->writeToCache($cacheKey, $configPrefix);
63
+                return $result;
64
+            }
65
+        }
66
+        return false;
67
+    }
68 68
 
69
-	/**
70
-	 * Asks the backend connected to the server that supposely takes care of the gid from the request.
71
-	 * @param string $gid the gid connected to the request
72
-	 * @param string $method the method of the group backend that shall be called
73
-	 * @param array $parameters an array of parameters to be passed
74
-	 * @param mixed $passOnWhen the result matches this variable
75
-	 * @return mixed, the result of the method or false
76
-	 */
77
-	protected function callOnLastSeenOn($gid, $method, $parameters, $passOnWhen) {
78
-		$cacheKey = $this->getGroupCacheKey($gid);
79
-		$prefix = $this->getFromCache($cacheKey);
80
-		//in case the uid has been found in the past, try this stored connection first
81
-		if(!is_null($prefix)) {
82
-			if(isset($this->backends[$prefix])) {
83
-				$result = call_user_func_array([$this->backends[$prefix], $method], $parameters);
84
-				if($result === $passOnWhen) {
85
-					//not found here, reset cache to null if group vanished
86
-					//because sometimes methods return false with a reason
87
-					$groupExists = call_user_func_array(
88
-						[$this->backends[$prefix], 'groupExists'],
89
-						[$gid]
90
-					);
91
-					if(!$groupExists) {
92
-						$this->writeToCache($cacheKey, null);
93
-					}
94
-				}
95
-				return $result;
96
-			}
97
-		}
98
-		return false;
99
-	}
69
+    /**
70
+     * Asks the backend connected to the server that supposely takes care of the gid from the request.
71
+     * @param string $gid the gid connected to the request
72
+     * @param string $method the method of the group backend that shall be called
73
+     * @param array $parameters an array of parameters to be passed
74
+     * @param mixed $passOnWhen the result matches this variable
75
+     * @return mixed, the result of the method or false
76
+     */
77
+    protected function callOnLastSeenOn($gid, $method, $parameters, $passOnWhen) {
78
+        $cacheKey = $this->getGroupCacheKey($gid);
79
+        $prefix = $this->getFromCache($cacheKey);
80
+        //in case the uid has been found in the past, try this stored connection first
81
+        if(!is_null($prefix)) {
82
+            if(isset($this->backends[$prefix])) {
83
+                $result = call_user_func_array([$this->backends[$prefix], $method], $parameters);
84
+                if($result === $passOnWhen) {
85
+                    //not found here, reset cache to null if group vanished
86
+                    //because sometimes methods return false with a reason
87
+                    $groupExists = call_user_func_array(
88
+                        [$this->backends[$prefix], 'groupExists'],
89
+                        [$gid]
90
+                    );
91
+                    if(!$groupExists) {
92
+                        $this->writeToCache($cacheKey, null);
93
+                    }
94
+                }
95
+                return $result;
96
+            }
97
+        }
98
+        return false;
99
+    }
100 100
 
101
-	/**
102
-	 * is user in group?
103
-	 * @param string $uid uid of the user
104
-	 * @param string $gid gid of the group
105
-	 * @return bool
106
-	 *
107
-	 * Checks whether the user is member of a group or not.
108
-	 */
109
-	public function inGroup($uid, $gid) {
110
-		return $this->handleRequest($gid, 'inGroup', [$uid, $gid]);
111
-	}
101
+    /**
102
+     * is user in group?
103
+     * @param string $uid uid of the user
104
+     * @param string $gid gid of the group
105
+     * @return bool
106
+     *
107
+     * Checks whether the user is member of a group or not.
108
+     */
109
+    public function inGroup($uid, $gid) {
110
+        return $this->handleRequest($gid, 'inGroup', [$uid, $gid]);
111
+    }
112 112
 
113
-	/**
114
-	 * Get all groups a user belongs to
115
-	 * @param string $uid Name of the user
116
-	 * @return string[] with group names
117
-	 *
118
-	 * This function fetches all groups a user belongs to. It does not check
119
-	 * if the user exists at all.
120
-	 */
121
-	public function getUserGroups($uid) {
122
-		$groups = [];
113
+    /**
114
+     * Get all groups a user belongs to
115
+     * @param string $uid Name of the user
116
+     * @return string[] with group names
117
+     *
118
+     * This function fetches all groups a user belongs to. It does not check
119
+     * if the user exists at all.
120
+     */
121
+    public function getUserGroups($uid) {
122
+        $groups = [];
123 123
 
124
-		foreach($this->backends as $backend) {
125
-			$backendGroups = $backend->getUserGroups($uid);
126
-			if (is_array($backendGroups)) {
127
-				$groups = array_merge($groups, $backendGroups);
128
-			}
129
-		}
124
+        foreach($this->backends as $backend) {
125
+            $backendGroups = $backend->getUserGroups($uid);
126
+            if (is_array($backendGroups)) {
127
+                $groups = array_merge($groups, $backendGroups);
128
+            }
129
+        }
130 130
 
131
-		return $groups;
132
-	}
131
+        return $groups;
132
+    }
133 133
 
134
-	/**
135
-	 * get a list of all users in a group
136
-	 * @return string[] with user ids
137
-	 */
138
-	public function usersInGroup($gid, $search = '', $limit = -1, $offset = 0) {
139
-		$users = [];
134
+    /**
135
+     * get a list of all users in a group
136
+     * @return string[] with user ids
137
+     */
138
+    public function usersInGroup($gid, $search = '', $limit = -1, $offset = 0) {
139
+        $users = [];
140 140
 
141
-		foreach($this->backends as $backend) {
142
-			$backendUsers = $backend->usersInGroup($gid, $search, $limit, $offset);
143
-			if (is_array($backendUsers)) {
144
-				$users = array_merge($users, $backendUsers);
145
-			}
146
-		}
141
+        foreach($this->backends as $backend) {
142
+            $backendUsers = $backend->usersInGroup($gid, $search, $limit, $offset);
143
+            if (is_array($backendUsers)) {
144
+                $users = array_merge($users, $backendUsers);
145
+            }
146
+        }
147 147
 
148
-		return $users;
149
-	}
148
+        return $users;
149
+    }
150 150
 
151
-	/**
152
-	 * @param string $gid
153
-	 * @return bool
154
-	 */
155
-	public function createGroup($gid) {
156
-		return $this->handleRequest(
157
-			$gid, 'createGroup', [$gid]);
158
-	}
151
+    /**
152
+     * @param string $gid
153
+     * @return bool
154
+     */
155
+    public function createGroup($gid) {
156
+        return $this->handleRequest(
157
+            $gid, 'createGroup', [$gid]);
158
+    }
159 159
 
160
-	/**
161
-	 * delete a group
162
-	 * @param string $gid gid of the group to delete
163
-	 * @return bool
164
-	 */
165
-	public function deleteGroup($gid) {
166
-		return $this->handleRequest(
167
-			$gid, 'deleteGroup', [$gid]);
168
-	}
160
+    /**
161
+     * delete a group
162
+     * @param string $gid gid of the group to delete
163
+     * @return bool
164
+     */
165
+    public function deleteGroup($gid) {
166
+        return $this->handleRequest(
167
+            $gid, 'deleteGroup', [$gid]);
168
+    }
169 169
 
170
-	/**
171
-	 * Add a user to a group
172
-	 * @param string $uid Name of the user to add to group
173
-	 * @param string $gid Name of the group in which add the user
174
-	 * @return bool
175
-	 *
176
-	 * Adds a user to a group.
177
-	 */
178
-	public function addToGroup($uid, $gid) {
179
-		return $this->handleRequest(
180
-			$gid, 'addToGroup', [$uid, $gid]);
181
-	}
170
+    /**
171
+     * Add a user to a group
172
+     * @param string $uid Name of the user to add to group
173
+     * @param string $gid Name of the group in which add the user
174
+     * @return bool
175
+     *
176
+     * Adds a user to a group.
177
+     */
178
+    public function addToGroup($uid, $gid) {
179
+        return $this->handleRequest(
180
+            $gid, 'addToGroup', [$uid, $gid]);
181
+    }
182 182
 
183
-	/**
184
-	 * Removes a user from a group
185
-	 * @param string $uid Name of the user to remove from group
186
-	 * @param string $gid Name of the group from which remove the user
187
-	 * @return bool
188
-	 *
189
-	 * removes the user from a group.
190
-	 */
191
-	public function removeFromGroup($uid, $gid) {
192
-		return $this->handleRequest(
193
-			$gid, 'removeFromGroup', [$uid, $gid]);
194
-	}
183
+    /**
184
+     * Removes a user from a group
185
+     * @param string $uid Name of the user to remove from group
186
+     * @param string $gid Name of the group from which remove the user
187
+     * @return bool
188
+     *
189
+     * removes the user from a group.
190
+     */
191
+    public function removeFromGroup($uid, $gid) {
192
+        return $this->handleRequest(
193
+            $gid, 'removeFromGroup', [$uid, $gid]);
194
+    }
195 195
 
196
-	/**
197
-	 * returns the number of users in a group, who match the search term
198
-	 * @param string $gid the internal group name
199
-	 * @param string $search optional, a search string
200
-	 * @return int|bool
201
-	 */
202
-	public function countUsersInGroup($gid, $search = '') {
203
-		return $this->handleRequest(
204
-			$gid, 'countUsersInGroup', [$gid, $search]);
205
-	}
196
+    /**
197
+     * returns the number of users in a group, who match the search term
198
+     * @param string $gid the internal group name
199
+     * @param string $search optional, a search string
200
+     * @return int|bool
201
+     */
202
+    public function countUsersInGroup($gid, $search = '') {
203
+        return $this->handleRequest(
204
+            $gid, 'countUsersInGroup', [$gid, $search]);
205
+    }
206 206
 
207
-	/**
208
-	 * get an array with group details
209
-	 * @param string $gid
210
-	 * @return array|false
211
-	 */
212
-	public function getGroupDetails($gid) {
213
-		return $this->handleRequest(
214
-			$gid, 'getGroupDetails', [$gid]);
215
-	}
207
+    /**
208
+     * get an array with group details
209
+     * @param string $gid
210
+     * @return array|false
211
+     */
212
+    public function getGroupDetails($gid) {
213
+        return $this->handleRequest(
214
+            $gid, 'getGroupDetails', [$gid]);
215
+    }
216 216
 
217
-	/**
218
-	 * get a list of all groups
219
-	 * @return string[] with group names
220
-	 *
221
-	 * Returns a list with all groups
222
-	 */
223
-	public function getGroups($search = '', $limit = -1, $offset = 0) {
224
-		$groups = [];
217
+    /**
218
+     * get a list of all groups
219
+     * @return string[] with group names
220
+     *
221
+     * Returns a list with all groups
222
+     */
223
+    public function getGroups($search = '', $limit = -1, $offset = 0) {
224
+        $groups = [];
225 225
 
226
-		foreach($this->backends as $backend) {
227
-			$backendGroups = $backend->getGroups($search, $limit, $offset);
228
-			if (is_array($backendGroups)) {
229
-				$groups = array_merge($groups, $backendGroups);
230
-			}
231
-		}
226
+        foreach($this->backends as $backend) {
227
+            $backendGroups = $backend->getGroups($search, $limit, $offset);
228
+            if (is_array($backendGroups)) {
229
+                $groups = array_merge($groups, $backendGroups);
230
+            }
231
+        }
232 232
 
233
-		return $groups;
234
-	}
233
+        return $groups;
234
+    }
235 235
 
236
-	/**
237
-	 * check if a group exists
238
-	 * @param string $gid
239
-	 * @return bool
240
-	 */
241
-	public function groupExists($gid) {
242
-		return $this->handleRequest($gid, 'groupExists', [$gid]);
243
-	}
236
+    /**
237
+     * check if a group exists
238
+     * @param string $gid
239
+     * @return bool
240
+     */
241
+    public function groupExists($gid) {
242
+        return $this->handleRequest($gid, 'groupExists', [$gid]);
243
+    }
244 244
 
245
-	/**
246
-	 * Check if backend implements actions
247
-	 * @param int $actions bitwise-or'ed actions
248
-	 * @return boolean
249
-	 *
250
-	 * Returns the supported actions as int to be
251
-	 * compared with \OCP\GroupInterface::CREATE_GROUP etc.
252
-	 */
253
-	public function implementsActions($actions) {
254
-		//it's the same across all our user backends obviously
255
-		return $this->refBackend->implementsActions($actions);
256
-	}
245
+    /**
246
+     * Check if backend implements actions
247
+     * @param int $actions bitwise-or'ed actions
248
+     * @return boolean
249
+     *
250
+     * Returns the supported actions as int to be
251
+     * compared with \OCP\GroupInterface::CREATE_GROUP etc.
252
+     */
253
+    public function implementsActions($actions) {
254
+        //it's the same across all our user backends obviously
255
+        return $this->refBackend->implementsActions($actions);
256
+    }
257 257
 
258
-	/**
259
-	 * Return access for LDAP interaction.
260
-	 * @param string $gid
261
-	 * @return Access instance of Access for LDAP interaction
262
-	 */
263
-	public function getLDAPAccess($gid) {
264
-		return $this->handleRequest($gid, 'getLDAPAccess', [$gid]);
265
-	}
258
+    /**
259
+     * Return access for LDAP interaction.
260
+     * @param string $gid
261
+     * @return Access instance of Access for LDAP interaction
262
+     */
263
+    public function getLDAPAccess($gid) {
264
+        return $this->handleRequest($gid, 'getLDAPAccess', [$gid]);
265
+    }
266 266
 
267
-	/**
268
-	 * Return a new LDAP connection for the specified group.
269
-	 * The connection needs to be closed manually.
270
-	 * @param string $gid
271
-	 * @return resource of the LDAP connection
272
-	 */
273
-	public function getNewLDAPConnection($gid) {
274
-		return $this->handleRequest($gid, 'getNewLDAPConnection', [$gid]);
275
-	}
267
+    /**
268
+     * Return a new LDAP connection for the specified group.
269
+     * The connection needs to be closed manually.
270
+     * @param string $gid
271
+     * @return resource of the LDAP connection
272
+     */
273
+    public function getNewLDAPConnection($gid) {
274
+        return $this->handleRequest($gid, 'getNewLDAPConnection', [$gid]);
275
+    }
276 276
 
277
-	public function getDisplayName(string $gid): string {
278
-		return $this->handleRequest($gid, 'getDisplayName', [$gid]);
279
-	}
277
+    public function getDisplayName(string $gid): string {
278
+        return $this->handleRequest($gid, 'getDisplayName', [$gid]);
279
+    }
280 280
 }
Please login to merge, or discard this patch.