Passed
Push — master ( f77c3f...4a3fe2 )
by Morris
10:43
created
apps/files_sharing/lib/Controller/ShareController.php 1 patch
Indentation   +608 added lines, -609 removed lines patch added patch discarded remove patch
@@ -73,617 +73,616 @@
 block discarded – undo
73 73
  */
74 74
 class ShareController extends AuthPublicShareController {
75 75
 
76
-	/** @var IConfig */
77
-	protected $config;
78
-	/** @var IUserManager */
79
-	protected $userManager;
80
-	/** @var ILogger */
81
-	protected $logger;
82
-	/** @var \OCP\Activity\IManager */
83
-	protected $activityManager;
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
-	/** @var ShareManager */
97
-	protected $shareManager;
98
-
99
-	/** @var Share\IShare */
100
-	protected $share;
101
-
102
-	/**
103
-	 * @param string $appName
104
-	 * @param IRequest $request
105
-	 * @param IConfig $config
106
-	 * @param IURLGenerator $urlGenerator
107
-	 * @param IUserManager $userManager
108
-	 * @param ILogger $logger
109
-	 * @param \OCP\Activity\IManager $activityManager
110
-	 * @param \OCP\Share\IManager $shareManager
111
-	 * @param ISession $session
112
-	 * @param IPreview $previewManager
113
-	 * @param IRootFolder $rootFolder
114
-	 * @param FederatedShareProvider $federatedShareProvider
115
-	 * @param EventDispatcherInterface $eventDispatcher
116
-	 * @param IL10N $l10n
117
-	 * @param Defaults $defaults
118
-	 */
119
-	public function __construct(string $appName,
120
-								IRequest $request,
121
-								IConfig $config,
122
-								IURLGenerator $urlGenerator,
123
-								IUserManager $userManager,
124
-								ILogger $logger,
125
-								\OCP\Activity\IManager $activityManager,
126
-								ShareManager $shareManager,
127
-								ISession $session,
128
-								IPreview $previewManager,
129
-								IRootFolder $rootFolder,
130
-								FederatedShareProvider $federatedShareProvider,
131
-								EventDispatcherInterface $eventDispatcher,
132
-								IL10N $l10n,
133
-								Defaults $defaults) {
134
-		parent::__construct($appName, $request, $session, $urlGenerator);
135
-
136
-		$this->config = $config;
137
-		$this->userManager = $userManager;
138
-		$this->logger = $logger;
139
-		$this->activityManager = $activityManager;
140
-		$this->previewManager = $previewManager;
141
-		$this->rootFolder = $rootFolder;
142
-		$this->federatedShareProvider = $federatedShareProvider;
143
-		$this->eventDispatcher = $eventDispatcher;
144
-		$this->l10n = $l10n;
145
-		$this->defaults = $defaults;
146
-		$this->shareManager = $shareManager;
147
-	}
148
-
149
-	/**
150
-	 * @PublicPage
151
-	 * @NoCSRFRequired
152
-	 *
153
-	 * Show the authentication page
154
-	 * The form has to submit to the authenticate method route
155
-	 */
156
-	public function showAuthenticate(): TemplateResponse {
157
-		$templateParameters = ['share' => $this->share];
158
-
159
-		$event = new GenericEvent(null, $templateParameters);
160
-		$this->eventDispatcher->dispatch('OCA\Files_Sharing::loadAdditionalScripts::publicShareAuth', $event);
161
-
162
-		$response = new TemplateResponse('core', 'publicshareauth', $templateParameters, 'guest');
163
-		if ($this->share->getSendPasswordByTalk()) {
164
-			$csp = new ContentSecurityPolicy();
165
-			$csp->addAllowedConnectDomain('*');
166
-			$csp->addAllowedMediaDomain('blob:');
167
-			$csp->allowEvalScript(true);
168
-			$response->setContentSecurityPolicy($csp);
169
-		}
170
-
171
-		return $response;
172
-	}
173
-
174
-	/**
175
-	 * The template to show when authentication failed
176
-	 */
177
-	protected function showAuthFailed(): TemplateResponse {
178
-		$templateParameters = ['share' => $this->share, 'wrongpw' => true];
179
-
180
-		$event = new GenericEvent(null, $templateParameters);
181
-		$this->eventDispatcher->dispatch('OCA\Files_Sharing::loadAdditionalScripts::publicShareAuth', $event);
182
-
183
-		$response = new TemplateResponse('core', 'publicshareauth', $templateParameters, 'guest');
184
-		if ($this->share->getSendPasswordByTalk()) {
185
-			$csp = new ContentSecurityPolicy();
186
-			$csp->addAllowedConnectDomain('*');
187
-			$csp->addAllowedMediaDomain('blob:');
188
-			$csp->allowEvalScript(true);
189
-			$response->setContentSecurityPolicy($csp);
190
-		}
191
-
192
-		return $response;
193
-	}
194
-
195
-	protected function verifyPassword(string $password): bool {
196
-		return $this->shareManager->checkPassword($this->share, $password);
197
-	}
198
-
199
-	protected function getPasswordHash(): string {
200
-		return $this->share->getPassword();
201
-	}
202
-
203
-	public function isValidToken(): bool {
204
-		try {
205
-			$this->share = $this->shareManager->getShareByToken($this->getToken());
206
-		} catch (ShareNotFound $e) {
207
-			return false;
208
-		}
209
-
210
-		return true;
211
-	}
212
-
213
-	protected function isPasswordProtected(): bool {
214
-		return $this->share->getPassword() !== null;
215
-	}
216
-
217
-	protected function authSucceeded() {
218
-		// For share this was always set so it is still used in other apps
219
-		$this->session->set('public_link_authenticated', (string)$this->share->getId());
220
-	}
221
-
222
-	protected function authFailed() {
223
-		$this->emitAccessShareHook($this->share, 403, 'Wrong password');
224
-	}
225
-
226
-	/**
227
-	 * throws hooks when a share is attempted to be accessed
228
-	 *
229
-	 * @param \OCP\Share\IShare|string $share the Share instance if available,
230
-	 * otherwise token
231
-	 * @param int $errorCode
232
-	 * @param string $errorMessage
233
-	 * @throws \OC\HintException
234
-	 * @throws \OC\ServerNotAvailableException
235
-	 */
236
-	protected function emitAccessShareHook($share, $errorCode = 200, $errorMessage = '') {
237
-		$itemType = $itemSource = $uidOwner = '';
238
-		$token = $share;
239
-		$exception = null;
240
-		if($share instanceof \OCP\Share\IShare) {
241
-			try {
242
-				$token = $share->getToken();
243
-				$uidOwner = $share->getSharedBy();
244
-				$itemType = $share->getNodeType();
245
-				$itemSource = $share->getNodeId();
246
-			} catch (\Exception $e) {
247
-				// we log what we know and pass on the exception afterwards
248
-				$exception = $e;
249
-			}
250
-		}
251
-		\OC_Hook::emit(Share::class, 'share_link_access', [
252
-			'itemType' => $itemType,
253
-			'itemSource' => $itemSource,
254
-			'uidOwner' => $uidOwner,
255
-			'token' => $token,
256
-			'errorCode' => $errorCode,
257
-			'errorMessage' => $errorMessage,
258
-		]);
259
-		if(!is_null($exception)) {
260
-			throw $exception;
261
-		}
262
-	}
263
-
264
-	/**
265
-	 * Validate the permissions of the share
266
-	 *
267
-	 * @param Share\IShare $share
268
-	 * @return bool
269
-	 */
270
-	private function validateShare(\OCP\Share\IShare $share) {
271
-		return $share->getNode()->isReadable() && $share->getNode()->isShareable();
272
-	}
273
-
274
-	/**
275
-	 * @PublicPage
276
-	 * @NoCSRFRequired
277
-	 *
278
-
279
-	 * @param string $path
280
-	 * @return TemplateResponse
281
-	 * @throws NotFoundException
282
-	 * @throws \Exception
283
-	 */
284
-	public function showShare($path = ''): TemplateResponse {
285
-		\OC_User::setIncognitoMode(true);
286
-
287
-		// Check whether share exists
288
-		try {
289
-			$share = $this->shareManager->getShareByToken($this->getToken());
290
-		} catch (ShareNotFound $e) {
291
-			$this->emitAccessShareHook($this->getToken(), 404, 'Share not found');
292
-			throw new NotFoundException();
293
-		}
294
-
295
-		if (!$this->validateShare($share)) {
296
-			throw new NotFoundException();
297
-		}
298
-
299
-		$shareNode = $share->getNode();
300
-
301
-		// We can't get the path of a file share
302
-		try {
303
-			if ($shareNode 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'] = $shareNode->getName();
316
-		$shareTmpl['directory_path'] = $share->getTarget();
317
-		$shareTmpl['note'] = $share->getNote();
318
-		$shareTmpl['mimetype'] = $shareNode->getMimetype();
319
-		$shareTmpl['previewSupported'] = $this->previewManager->isMimeSupported($shareNode->getMimetype());
320
-		$shareTmpl['dirToken'] = $this->getToken();
321
-		$shareTmpl['sharingToken'] = $this->getToken();
322
-		$shareTmpl['server2serversharing'] = $this->federatedShareProvider->isOutgoingServer2serverShareEnabled();
323
-		$shareTmpl['protected'] = $share->getPassword() !== null ? 'true' : 'false';
324
-		$shareTmpl['dir'] = '';
325
-		$shareTmpl['nonHumanFileSize'] = $shareNode->getSize();
326
-		$shareTmpl['fileSize'] = \OCP\Util::humanFileSize($shareNode->getSize());
327
-		$shareTmpl['hideDownload'] = $share->getHideDownload();
328
-
329
-		$hideFileList = false;
330
-
331
-		if ($shareNode instanceof \OCP\Files\Folder) {
332
-
333
-			$shareIsFolder = true;
334
-
335
-			try {
336
-				$folderNode = $shareNode->get($path);
337
-			} catch (\OCP\Files\NotFoundException $e) {
338
-				$this->emitAccessShareHook($share, 404, 'Share not found');
339
-				throw new NotFoundException();
340
-			}
341
-
342
-			$shareTmpl['dir'] = $shareNode->getRelativePath($folderNode->getPath());
343
-
344
-			/*
76
+    /** @var IConfig */
77
+    protected $config;
78
+    /** @var IUserManager */
79
+    protected $userManager;
80
+    /** @var ILogger */
81
+    protected $logger;
82
+    /** @var \OCP\Activity\IManager */
83
+    protected $activityManager;
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
+    /** @var ShareManager */
97
+    protected $shareManager;
98
+
99
+    /** @var Share\IShare */
100
+    protected $share;
101
+
102
+    /**
103
+     * @param string $appName
104
+     * @param IRequest $request
105
+     * @param IConfig $config
106
+     * @param IURLGenerator $urlGenerator
107
+     * @param IUserManager $userManager
108
+     * @param ILogger $logger
109
+     * @param \OCP\Activity\IManager $activityManager
110
+     * @param \OCP\Share\IManager $shareManager
111
+     * @param ISession $session
112
+     * @param IPreview $previewManager
113
+     * @param IRootFolder $rootFolder
114
+     * @param FederatedShareProvider $federatedShareProvider
115
+     * @param EventDispatcherInterface $eventDispatcher
116
+     * @param IL10N $l10n
117
+     * @param Defaults $defaults
118
+     */
119
+    public function __construct(string $appName,
120
+                                IRequest $request,
121
+                                IConfig $config,
122
+                                IURLGenerator $urlGenerator,
123
+                                IUserManager $userManager,
124
+                                ILogger $logger,
125
+                                \OCP\Activity\IManager $activityManager,
126
+                                ShareManager $shareManager,
127
+                                ISession $session,
128
+                                IPreview $previewManager,
129
+                                IRootFolder $rootFolder,
130
+                                FederatedShareProvider $federatedShareProvider,
131
+                                EventDispatcherInterface $eventDispatcher,
132
+                                IL10N $l10n,
133
+                                Defaults $defaults) {
134
+        parent::__construct($appName, $request, $session, $urlGenerator);
135
+
136
+        $this->config = $config;
137
+        $this->userManager = $userManager;
138
+        $this->logger = $logger;
139
+        $this->activityManager = $activityManager;
140
+        $this->previewManager = $previewManager;
141
+        $this->rootFolder = $rootFolder;
142
+        $this->federatedShareProvider = $federatedShareProvider;
143
+        $this->eventDispatcher = $eventDispatcher;
144
+        $this->l10n = $l10n;
145
+        $this->defaults = $defaults;
146
+        $this->shareManager = $shareManager;
147
+    }
148
+
149
+    /**
150
+     * @PublicPage
151
+     * @NoCSRFRequired
152
+     *
153
+     * Show the authentication page
154
+     * The form has to submit to the authenticate method route
155
+     */
156
+    public function showAuthenticate(): TemplateResponse {
157
+        $templateParameters = ['share' => $this->share];
158
+
159
+        $event = new GenericEvent(null, $templateParameters);
160
+        $this->eventDispatcher->dispatch('OCA\Files_Sharing::loadAdditionalScripts::publicShareAuth', $event);
161
+
162
+        $response = new TemplateResponse('core', 'publicshareauth', $templateParameters, 'guest');
163
+        if ($this->share->getSendPasswordByTalk()) {
164
+            $csp = new ContentSecurityPolicy();
165
+            $csp->addAllowedConnectDomain('*');
166
+            $csp->addAllowedMediaDomain('blob:');
167
+            $csp->allowEvalScript(true);
168
+            $response->setContentSecurityPolicy($csp);
169
+        }
170
+
171
+        return $response;
172
+    }
173
+
174
+    /**
175
+     * The template to show when authentication failed
176
+     */
177
+    protected function showAuthFailed(): TemplateResponse {
178
+        $templateParameters = ['share' => $this->share, 'wrongpw' => true];
179
+
180
+        $event = new GenericEvent(null, $templateParameters);
181
+        $this->eventDispatcher->dispatch('OCA\Files_Sharing::loadAdditionalScripts::publicShareAuth', $event);
182
+
183
+        $response = new TemplateResponse('core', 'publicshareauth', $templateParameters, 'guest');
184
+        if ($this->share->getSendPasswordByTalk()) {
185
+            $csp = new ContentSecurityPolicy();
186
+            $csp->addAllowedConnectDomain('*');
187
+            $csp->addAllowedMediaDomain('blob:');
188
+            $csp->allowEvalScript(true);
189
+            $response->setContentSecurityPolicy($csp);
190
+        }
191
+
192
+        return $response;
193
+    }
194
+
195
+    protected function verifyPassword(string $password): bool {
196
+        return $this->shareManager->checkPassword($this->share, $password);
197
+    }
198
+
199
+    protected function getPasswordHash(): string {
200
+        return $this->share->getPassword();
201
+    }
202
+
203
+    public function isValidToken(): bool {
204
+        try {
205
+            $this->share = $this->shareManager->getShareByToken($this->getToken());
206
+        } catch (ShareNotFound $e) {
207
+            return false;
208
+        }
209
+
210
+        return true;
211
+    }
212
+
213
+    protected function isPasswordProtected(): bool {
214
+        return $this->share->getPassword() !== null;
215
+    }
216
+
217
+    protected function authSucceeded() {
218
+        // For share this was always set so it is still used in other apps
219
+        $this->session->set('public_link_authenticated', (string)$this->share->getId());
220
+    }
221
+
222
+    protected function authFailed() {
223
+        $this->emitAccessShareHook($this->share, 403, 'Wrong password');
224
+    }
225
+
226
+    /**
227
+     * throws hooks when a share is attempted to be accessed
228
+     *
229
+     * @param \OCP\Share\IShare|string $share the Share instance if available,
230
+     * otherwise token
231
+     * @param int $errorCode
232
+     * @param string $errorMessage
233
+     * @throws \OC\HintException
234
+     * @throws \OC\ServerNotAvailableException
235
+     */
236
+    protected function emitAccessShareHook($share, $errorCode = 200, $errorMessage = '') {
237
+        $itemType = $itemSource = $uidOwner = '';
238
+        $token = $share;
239
+        $exception = null;
240
+        if($share instanceof \OCP\Share\IShare) {
241
+            try {
242
+                $token = $share->getToken();
243
+                $uidOwner = $share->getSharedBy();
244
+                $itemType = $share->getNodeType();
245
+                $itemSource = $share->getNodeId();
246
+            } catch (\Exception $e) {
247
+                // we log what we know and pass on the exception afterwards
248
+                $exception = $e;
249
+            }
250
+        }
251
+        \OC_Hook::emit(Share::class, 'share_link_access', [
252
+            'itemType' => $itemType,
253
+            'itemSource' => $itemSource,
254
+            'uidOwner' => $uidOwner,
255
+            'token' => $token,
256
+            'errorCode' => $errorCode,
257
+            'errorMessage' => $errorMessage,
258
+        ]);
259
+        if(!is_null($exception)) {
260
+            throw $exception;
261
+        }
262
+    }
263
+
264
+    /**
265
+     * Validate the permissions of the share
266
+     *
267
+     * @param Share\IShare $share
268
+     * @return bool
269
+     */
270
+    private function validateShare(\OCP\Share\IShare $share) {
271
+        return $share->getNode()->isReadable() && $share->getNode()->isShareable();
272
+    }
273
+
274
+    /**
275
+     * @PublicPage
276
+     * @NoCSRFRequired
277
+     *
278
+     * @param string $path
279
+     * @return TemplateResponse
280
+     * @throws NotFoundException
281
+     * @throws \Exception
282
+     */
283
+    public function showShare($path = ''): TemplateResponse {
284
+        \OC_User::setIncognitoMode(true);
285
+
286
+        // Check whether share exists
287
+        try {
288
+            $share = $this->shareManager->getShareByToken($this->getToken());
289
+        } catch (ShareNotFound $e) {
290
+            $this->emitAccessShareHook($this->getToken(), 404, 'Share not found');
291
+            throw new NotFoundException();
292
+        }
293
+
294
+        if (!$this->validateShare($share)) {
295
+            throw new NotFoundException();
296
+        }
297
+
298
+        $shareNode = $share->getNode();
299
+
300
+        // We can't get the path of a file share
301
+        try {
302
+            if ($shareNode instanceof \OCP\Files\File && $path !== '') {
303
+                $this->emitAccessShareHook($share, 404, 'Share not found');
304
+                throw new NotFoundException();
305
+            }
306
+        } catch (\Exception $e) {
307
+            $this->emitAccessShareHook($share, 404, 'Share not found');
308
+            throw $e;
309
+        }
310
+
311
+        $shareTmpl = [];
312
+        $shareTmpl['displayName'] = $this->userManager->get($share->getShareOwner())->getDisplayName();
313
+        $shareTmpl['owner'] = $share->getShareOwner();
314
+        $shareTmpl['filename'] = $shareNode->getName();
315
+        $shareTmpl['directory_path'] = $share->getTarget();
316
+        $shareTmpl['note'] = $share->getNote();
317
+        $shareTmpl['mimetype'] = $shareNode->getMimetype();
318
+        $shareTmpl['previewSupported'] = $this->previewManager->isMimeSupported($shareNode->getMimetype());
319
+        $shareTmpl['dirToken'] = $this->getToken();
320
+        $shareTmpl['sharingToken'] = $this->getToken();
321
+        $shareTmpl['server2serversharing'] = $this->federatedShareProvider->isOutgoingServer2serverShareEnabled();
322
+        $shareTmpl['protected'] = $share->getPassword() !== null ? 'true' : 'false';
323
+        $shareTmpl['dir'] = '';
324
+        $shareTmpl['nonHumanFileSize'] = $shareNode->getSize();
325
+        $shareTmpl['fileSize'] = \OCP\Util::humanFileSize($shareNode->getSize());
326
+        $shareTmpl['hideDownload'] = $share->getHideDownload();
327
+
328
+        $hideFileList = false;
329
+
330
+        if ($shareNode instanceof \OCP\Files\Folder) {
331
+
332
+            $shareIsFolder = true;
333
+
334
+            try {
335
+                $folderNode = $shareNode->get($path);
336
+            } catch (\OCP\Files\NotFoundException $e) {
337
+                $this->emitAccessShareHook($share, 404, 'Share not found');
338
+                throw new NotFoundException();
339
+            }
340
+
341
+            $shareTmpl['dir'] = $shareNode->getRelativePath($folderNode->getPath());
342
+
343
+            /*
345 344
 			 * The OC_Util methods require a view. This just uses the node API
346 345
 			 */
347
-			$freeSpace = $share->getNode()->getStorage()->free_space($share->getNode()->getInternalPath());
348
-			if ($freeSpace < \OCP\Files\FileInfo::SPACE_UNLIMITED) {
349
-				$freeSpace = max($freeSpace, 0);
350
-			} else {
351
-				$freeSpace = (INF > 0) ? INF: PHP_INT_MAX; // work around https://bugs.php.net/bug.php?id=69188
352
-			}
353
-
354
-			$hideFileList = !($share->getPermissions() & \OCP\Constants::PERMISSION_READ);
355
-			$maxUploadFilesize = $freeSpace;
356
-
357
-			$folder = new Template('files', 'list', '');
358
-			$folder->assign('dir', $shareNode->getRelativePath($folderNode->getPath()));
359
-			$folder->assign('dirToken', $this->getToken());
360
-			$folder->assign('permissions', \OCP\Constants::PERMISSION_READ);
361
-			$folder->assign('isPublic', true);
362
-			$folder->assign('hideFileList', $hideFileList);
363
-			$folder->assign('publicUploadEnabled', 'no');
364
-			$folder->assign('showgridview', false);
365
-			$folder->assign('uploadMaxFilesize', $maxUploadFilesize);
366
-			$folder->assign('uploadMaxHumanFilesize', \OCP\Util::humanFileSize($maxUploadFilesize));
367
-			$folder->assign('freeSpace', $freeSpace);
368
-			$folder->assign('usedSpacePercent', 0);
369
-			$folder->assign('trash', false);
370
-			$shareTmpl['folder'] = $folder->fetchPage();
371
-		} else {
372
-			$shareIsFolder = false;
373
-		}
374
-
375
-		$shareTmpl['showgridview'] = false;
376
-
377
-		$shareTmpl['hideFileList'] = $hideFileList;
378
-		$shareTmpl['shareOwner'] = $this->userManager->get($share->getShareOwner())->getDisplayName();
379
-		$shareTmpl['downloadURL'] = $this->urlGenerator->linkToRouteAbsolute('files_sharing.sharecontroller.downloadShare', ['token' => $this->getToken()]);
380
-		$shareTmpl['shareUrl'] = $this->urlGenerator->linkToRouteAbsolute('files_sharing.sharecontroller.showShare', ['token' => $this->getToken()]);
381
-		$shareTmpl['maxSizeAnimateGif'] = $this->config->getSystemValue('max_filesize_animated_gifs_public_sharing', 10);
382
-		$shareTmpl['previewEnabled'] = $this->config->getSystemValue('enable_previews', true);
383
-		$shareTmpl['previewMaxX'] = $this->config->getSystemValue('preview_max_x', 1024);
384
-		$shareTmpl['previewMaxY'] = $this->config->getSystemValue('preview_max_y', 1024);
385
-		$shareTmpl['disclaimer'] = $this->config->getAppValue('core', 'shareapi_public_link_disclaimertext', null);
386
-		$shareTmpl['previewURL'] = $shareTmpl['downloadURL'];
387
-
388
-		if ($shareTmpl['previewSupported']) {
389
-			$shareTmpl['previewImage'] = $this->urlGenerator->linkToRouteAbsolute( 'files_sharing.PublicPreview.getPreview',
390
-				['x' => 200, 'y' => 200, 'file' => $shareTmpl['directory_path'], 'token' => $shareTmpl['dirToken']]);
391
-			$ogPreview = $shareTmpl['previewImage'];
392
-
393
-			// We just have direct previews for image files
394
-			if ($shareNode->getMimePart() === 'image') {
395
-				$shareTmpl['previewURL'] = $this->urlGenerator->linkToRouteAbsolute('files_sharing.publicpreview.directLink', ['token' => $this->getToken()]);
396
-
397
-				$ogPreview = $shareTmpl['previewURL'];
398
-
399
-				//Whatapp is kind of picky about their size requirements
400
-				if ($this->request->isUserAgent(['/^WhatsApp/'])) {
401
-					$ogPreview = $this->urlGenerator->linkToRouteAbsolute('files_sharing.PublicPreview.getPreview', [
402
-						'token' => $this->getToken(),
403
-						'x' => 256,
404
-						'y' => 256,
405
-						'a' => true,
406
-					]);
407
-				}
408
-			}
409
-		} else {
410
-			$shareTmpl['previewImage'] = $this->urlGenerator->getAbsoluteURL($this->urlGenerator->imagePath('core', 'favicon-fb.png'));
411
-			$ogPreview = $shareTmpl['previewImage'];
412
-		}
413
-
414
-		// Load files we need
415
-		\OCP\Util::addScript('files', 'file-upload');
416
-		\OCP\Util::addStyle('files_sharing', 'publicView');
417
-		\OCP\Util::addScript('files_sharing', 'public');
418
-		\OCP\Util::addScript('files_sharing', 'templates');
419
-		\OCP\Util::addScript('files', 'fileactions');
420
-		\OCP\Util::addScript('files', 'fileactionsmenu');
421
-		\OCP\Util::addScript('files', 'jquery.fileupload');
422
-		\OCP\Util::addScript('files_sharing', 'files_drop');
423
-
424
-		if (isset($shareTmpl['folder'])) {
425
-			// JS required for folders
426
-			\OCP\Util::addStyle('files', 'merged');
427
-			\OCP\Util::addScript('files', 'filesummary');
428
-			\OCP\Util::addScript('files', 'templates');
429
-			\OCP\Util::addScript('files', 'breadcrumb');
430
-			\OCP\Util::addScript('files', 'fileinfomodel');
431
-			\OCP\Util::addScript('files', 'newfilemenu');
432
-			\OCP\Util::addScript('files', 'files');
433
-			\OCP\Util::addScript('files', 'filemultiselectmenu');
434
-			\OCP\Util::addScript('files', 'filelist');
435
-			\OCP\Util::addScript('files', 'keyboardshortcuts');
436
-		}
437
-
438
-		// OpenGraph Support: http://ogp.me/
439
-		\OCP\Util::addHeader('meta', ['property' => "og:title", 'content' => $shareTmpl['filename']]);
440
-		\OCP\Util::addHeader('meta', ['property' => "og:description", 'content' => $this->defaults->getName() . ($this->defaults->getSlogan() !== '' ? ' - ' . $this->defaults->getSlogan() : '')]);
441
-		\OCP\Util::addHeader('meta', ['property' => "og:site_name", 'content' => $this->defaults->getName()]);
442
-		\OCP\Util::addHeader('meta', ['property' => "og:url", 'content' => $shareTmpl['shareUrl']]);
443
-		\OCP\Util::addHeader('meta', ['property' => "og:type", 'content' => "object"]);
444
-		\OCP\Util::addHeader('meta', ['property' => "og:image", 'content' => $ogPreview]);
445
-
446
-		$this->eventDispatcher->dispatch('OCA\Files_Sharing::loadAdditionalScripts');
447
-
448
-		$csp = new \OCP\AppFramework\Http\ContentSecurityPolicy();
449
-		$csp->addAllowedFrameDomain('\'self\'');
450
-
451
-		$response = new PublicTemplateResponse($this->appName, 'public', $shareTmpl);
452
-		$response->setHeaderTitle($shareTmpl['filename']);
453
-		$response->setHeaderDetails($this->l10n->t('shared by %s', [$shareTmpl['displayName']]));
454
-
455
-		$isNoneFileDropFolder = $shareIsFolder === false || $share->getPermissions() !== \OCP\Constants::PERMISSION_CREATE;
456
-
457
-		if ($isNoneFileDropFolder && !$share->getHideDownload()) {
458
-			\OCP\Util::addScript('files_sharing', 'public_note');
459
-
460
-			$downloadWhite = new SimpleMenuAction('download', $this->l10n->t('Download'), 'icon-download-white', $shareTmpl['downloadURL'], 0);
461
-			$downloadAllWhite = new SimpleMenuAction('download', $this->l10n->t('Download all files'), 'icon-download-white', $shareTmpl['downloadURL'], 0);
462
-			$download = new SimpleMenuAction('download', $this->l10n->t('Download'), 'icon-download', $shareTmpl['downloadURL'], 10, $shareTmpl['fileSize']);
463
-			$downloadAll = new SimpleMenuAction('download', $this->l10n->t('Download all files'), 'icon-download', $shareTmpl['downloadURL'], 10, $shareTmpl['fileSize']);
464
-			$directLink = new LinkMenuAction($this->l10n->t('Direct link'), 'icon-public', $shareTmpl['previewURL']);
465
-			$externalShare = new ExternalShareMenuAction($this->l10n->t('Add to your Nextcloud'), 'icon-external', $shareTmpl['owner'], $shareTmpl['displayName'], $shareTmpl['filename']);
466
-
467
-			$responseComposer = [];
468
-
469
-			if ($shareIsFolder) {
470
-				$responseComposer[] = $downloadAllWhite;
471
-				$responseComposer[] = $downloadAll;
472
-			} else {
473
-				$responseComposer[] = $downloadWhite;
474
-				$responseComposer[] = $download;
475
-			}
476
-			$responseComposer[] = $directLink;
477
-			if ($this->federatedShareProvider->isOutgoingServer2serverShareEnabled()) {
478
-				$responseComposer[] = $externalShare;
479
-			}
480
-
481
-			$response->setHeaderActions($responseComposer);
482
-		}
483
-
484
-		$response->setContentSecurityPolicy($csp);
485
-
486
-		$this->emitAccessShareHook($share);
487
-
488
-		return $response;
489
-	}
490
-
491
-	/**
492
-	 * @PublicPage
493
-	 * @NoCSRFRequired
494
-	 *
495
-	 * @param string $token
496
-	 * @param string $files
497
-	 * @param string $path
498
-	 * @param string $downloadStartSecret
499
-	 * @return void|\OCP\AppFramework\Http\Response
500
-	 * @throws NotFoundException
501
-	 */
502
-	public function downloadShare($token, $files = null, $path = '', $downloadStartSecret = '') {
503
-		\OC_User::setIncognitoMode(true);
504
-
505
-		$share = $this->shareManager->getShareByToken($token);
506
-
507
-		if(!($share->getPermissions() & \OCP\Constants::PERMISSION_READ)) {
508
-			return new \OCP\AppFramework\Http\DataResponse('Share is read-only');
509
-		}
510
-
511
-		$files_list = null;
512
-		if (!is_null($files)) { // download selected files
513
-			$files_list = json_decode($files);
514
-			// in case we get only a single file
515
-			if ($files_list === null) {
516
-				$files_list = [$files];
517
-			}
518
-			// Just in case $files is a single int like '1234'
519
-			if (!is_array($files_list)) {
520
-				$files_list = [$files_list];
521
-			}
522
-		}
523
-
524
-
525
-		if (!$this->validateShare($share)) {
526
-			throw new NotFoundException();
527
-		}
528
-
529
-		$userFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
530
-		$originalSharePath = $userFolder->getRelativePath($share->getNode()->getPath());
531
-
532
-
533
-		// Single file share
534
-		if ($share->getNode() instanceof \OCP\Files\File) {
535
-			// Single file download
536
-			$this->singleFileDownloaded($share, $share->getNode());
537
-		}
538
-		// Directory share
539
-		else {
540
-			/** @var \OCP\Files\Folder $node */
541
-			$node = $share->getNode();
542
-
543
-			// Try to get the path
544
-			if ($path !== '') {
545
-				try {
546
-					$node = $node->get($path);
547
-				} catch (NotFoundException $e) {
548
-					$this->emitAccessShareHook($share, 404, 'Share not found');
549
-					return new NotFoundResponse();
550
-				}
551
-			}
552
-
553
-			$originalSharePath = $userFolder->getRelativePath($node->getPath());
554
-
555
-			if ($node instanceof \OCP\Files\File) {
556
-				// Single file download
557
-				$this->singleFileDownloaded($share, $share->getNode());
558
-			} else if (!empty($files_list)) {
559
-				$this->fileListDownloaded($share, $files_list, $node);
560
-			} else {
561
-				// The folder is downloaded
562
-				$this->singleFileDownloaded($share, $share->getNode());
563
-			}
564
-		}
565
-
566
-		/* FIXME: We should do this all nicely in OCP */
567
-		OC_Util::tearDownFS();
568
-		OC_Util::setupFS($share->getShareOwner());
569
-
570
-		/**
571
-		 * this sets a cookie to be able to recognize the start of the download
572
-		 * the content must not be longer than 32 characters and must only contain
573
-		 * alphanumeric characters
574
-		 */
575
-		if (!empty($downloadStartSecret)
576
-			&& !isset($downloadStartSecret[32])
577
-			&& preg_match('!^[a-zA-Z0-9]+$!', $downloadStartSecret) === 1) {
578
-
579
-			// FIXME: set on the response once we use an actual app framework response
580
-			setcookie('ocDownloadStarted', $downloadStartSecret, time() + 20, '/');
581
-		}
582
-
583
-		$this->emitAccessShareHook($share);
584
-
585
-		$server_params = array( 'head' => $this->request->getMethod() === 'HEAD' );
586
-
587
-		/**
588
-		 * Http range requests support
589
-		 */
590
-		if (isset($_SERVER['HTTP_RANGE'])) {
591
-			$server_params['range'] = $this->request->getHeader('Range');
592
-		}
593
-
594
-		// download selected files
595
-		if (!is_null($files) && $files !== '') {
596
-			// FIXME: The exit is required here because otherwise the AppFramework is trying to add headers as well
597
-			// after dispatching the request which results in a "Cannot modify header information" notice.
598
-			OC_Files::get($originalSharePath, $files_list, $server_params);
599
-			exit();
600
-		} else {
601
-			// FIXME: The exit is required here because otherwise the AppFramework is trying to add headers as well
602
-			// after dispatching the request which results in a "Cannot modify header information" notice.
603
-			OC_Files::get(dirname($originalSharePath), basename($originalSharePath), $server_params);
604
-			exit();
605
-		}
606
-	}
607
-
608
-	/**
609
-	 * create activity for every downloaded file
610
-	 *
611
-	 * @param Share\IShare $share
612
-	 * @param array $files_list
613
-	 * @param \OCP\Files\Folder $node
614
-	 */
615
-	protected function fileListDownloaded(Share\IShare $share, array $files_list, \OCP\Files\Folder $node) {
616
-		foreach ($files_list as $file) {
617
-			$subNode = $node->get($file);
618
-			$this->singleFileDownloaded($share, $subNode);
619
-		}
620
-
621
-	}
622
-
623
-	/**
624
-	 * create activity if a single file was downloaded from a link share
625
-	 *
626
-	 * @param Share\IShare $share
627
-	 */
628
-	protected function singleFileDownloaded(Share\IShare $share, \OCP\Files\Node $node) {
629
-
630
-		$fileId = $node->getId();
631
-
632
-		$userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
633
-		$userNodeList = $userFolder->getById($fileId);
634
-		$userNode = $userNodeList[0];
635
-		$ownerFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
636
-		$userPath = $userFolder->getRelativePath($userNode->getPath());
637
-		$ownerPath = $ownerFolder->getRelativePath($node->getPath());
638
-
639
-		$parameters = [$userPath];
640
-
641
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
642
-			if ($node instanceof \OCP\Files\File) {
643
-				$subject = Downloads::SUBJECT_SHARED_FILE_BY_EMAIL_DOWNLOADED;
644
-			} else {
645
-				$subject = Downloads::SUBJECT_SHARED_FOLDER_BY_EMAIL_DOWNLOADED;
646
-			}
647
-			$parameters[] = $share->getSharedWith();
648
-		} else {
649
-			if ($node instanceof \OCP\Files\File) {
650
-				$subject = Downloads::SUBJECT_PUBLIC_SHARED_FILE_DOWNLOADED;
651
-			} else {
652
-				$subject = Downloads::SUBJECT_PUBLIC_SHARED_FOLDER_DOWNLOADED;
653
-			}
654
-		}
655
-
656
-		$this->publishActivity($subject, $parameters, $share->getSharedBy(), $fileId, $userPath);
657
-
658
-		if ($share->getShareOwner() !== $share->getSharedBy()) {
659
-			$parameters[0] = $ownerPath;
660
-			$this->publishActivity($subject, $parameters, $share->getShareOwner(), $fileId, $ownerPath);
661
-		}
662
-	}
663
-
664
-	/**
665
-	 * publish activity
666
-	 *
667
-	 * @param string $subject
668
-	 * @param array $parameters
669
-	 * @param string $affectedUser
670
-	 * @param int $fileId
671
-	 * @param string $filePath
672
-	 */
673
-	protected function publishActivity($subject,
674
-										array $parameters,
675
-										$affectedUser,
676
-										$fileId,
677
-										$filePath) {
678
-
679
-		$event = $this->activityManager->generateEvent();
680
-		$event->setApp('files_sharing')
681
-			->setType('public_links')
682
-			->setSubject($subject, $parameters)
683
-			->setAffectedUser($affectedUser)
684
-			->setObject('files', $fileId, $filePath);
685
-		$this->activityManager->publish($event);
686
-	}
346
+            $freeSpace = $share->getNode()->getStorage()->free_space($share->getNode()->getInternalPath());
347
+            if ($freeSpace < \OCP\Files\FileInfo::SPACE_UNLIMITED) {
348
+                $freeSpace = max($freeSpace, 0);
349
+            } else {
350
+                $freeSpace = (INF > 0) ? INF: PHP_INT_MAX; // work around https://bugs.php.net/bug.php?id=69188
351
+            }
352
+
353
+            $hideFileList = !($share->getPermissions() & \OCP\Constants::PERMISSION_READ);
354
+            $maxUploadFilesize = $freeSpace;
355
+
356
+            $folder = new Template('files', 'list', '');
357
+            $folder->assign('dir', $shareNode->getRelativePath($folderNode->getPath()));
358
+            $folder->assign('dirToken', $this->getToken());
359
+            $folder->assign('permissions', \OCP\Constants::PERMISSION_READ);
360
+            $folder->assign('isPublic', true);
361
+            $folder->assign('hideFileList', $hideFileList);
362
+            $folder->assign('publicUploadEnabled', 'no');
363
+            $folder->assign('showgridview', false);
364
+            $folder->assign('uploadMaxFilesize', $maxUploadFilesize);
365
+            $folder->assign('uploadMaxHumanFilesize', \OCP\Util::humanFileSize($maxUploadFilesize));
366
+            $folder->assign('freeSpace', $freeSpace);
367
+            $folder->assign('usedSpacePercent', 0);
368
+            $folder->assign('trash', false);
369
+            $shareTmpl['folder'] = $folder->fetchPage();
370
+        } else {
371
+            $shareIsFolder = false;
372
+        }
373
+
374
+        $shareTmpl['showgridview'] = false;
375
+
376
+        $shareTmpl['hideFileList'] = $hideFileList;
377
+        $shareTmpl['shareOwner'] = $this->userManager->get($share->getShareOwner())->getDisplayName();
378
+        $shareTmpl['downloadURL'] = $this->urlGenerator->linkToRouteAbsolute('files_sharing.sharecontroller.downloadShare', ['token' => $this->getToken()]);
379
+        $shareTmpl['shareUrl'] = $this->urlGenerator->linkToRouteAbsolute('files_sharing.sharecontroller.showShare', ['token' => $this->getToken()]);
380
+        $shareTmpl['maxSizeAnimateGif'] = $this->config->getSystemValue('max_filesize_animated_gifs_public_sharing', 10);
381
+        $shareTmpl['previewEnabled'] = $this->config->getSystemValue('enable_previews', true);
382
+        $shareTmpl['previewMaxX'] = $this->config->getSystemValue('preview_max_x', 1024);
383
+        $shareTmpl['previewMaxY'] = $this->config->getSystemValue('preview_max_y', 1024);
384
+        $shareTmpl['disclaimer'] = $this->config->getAppValue('core', 'shareapi_public_link_disclaimertext', null);
385
+        $shareTmpl['previewURL'] = $shareTmpl['downloadURL'];
386
+
387
+        if ($shareTmpl['previewSupported']) {
388
+            $shareTmpl['previewImage'] = $this->urlGenerator->linkToRouteAbsolute( 'files_sharing.PublicPreview.getPreview',
389
+                ['x' => 200, 'y' => 200, 'file' => $shareTmpl['directory_path'], 'token' => $shareTmpl['dirToken']]);
390
+            $ogPreview = $shareTmpl['previewImage'];
391
+
392
+            // We just have direct previews for image files
393
+            if ($shareNode->getMimePart() === 'image') {
394
+                $shareTmpl['previewURL'] = $this->urlGenerator->linkToRouteAbsolute('files_sharing.publicpreview.directLink', ['token' => $this->getToken()]);
395
+
396
+                $ogPreview = $shareTmpl['previewURL'];
397
+
398
+                //Whatapp is kind of picky about their size requirements
399
+                if ($this->request->isUserAgent(['/^WhatsApp/'])) {
400
+                    $ogPreview = $this->urlGenerator->linkToRouteAbsolute('files_sharing.PublicPreview.getPreview', [
401
+                        'token' => $this->getToken(),
402
+                        'x' => 256,
403
+                        'y' => 256,
404
+                        'a' => true,
405
+                    ]);
406
+                }
407
+            }
408
+        } else {
409
+            $shareTmpl['previewImage'] = $this->urlGenerator->getAbsoluteURL($this->urlGenerator->imagePath('core', 'favicon-fb.png'));
410
+            $ogPreview = $shareTmpl['previewImage'];
411
+        }
412
+
413
+        // Load files we need
414
+        \OCP\Util::addScript('files', 'file-upload');
415
+        \OCP\Util::addStyle('files_sharing', 'publicView');
416
+        \OCP\Util::addScript('files_sharing', 'public');
417
+        \OCP\Util::addScript('files_sharing', 'templates');
418
+        \OCP\Util::addScript('files', 'fileactions');
419
+        \OCP\Util::addScript('files', 'fileactionsmenu');
420
+        \OCP\Util::addScript('files', 'jquery.fileupload');
421
+        \OCP\Util::addScript('files_sharing', 'files_drop');
422
+
423
+        if (isset($shareTmpl['folder'])) {
424
+            // JS required for folders
425
+            \OCP\Util::addStyle('files', 'merged');
426
+            \OCP\Util::addScript('files', 'filesummary');
427
+            \OCP\Util::addScript('files', 'templates');
428
+            \OCP\Util::addScript('files', 'breadcrumb');
429
+            \OCP\Util::addScript('files', 'fileinfomodel');
430
+            \OCP\Util::addScript('files', 'newfilemenu');
431
+            \OCP\Util::addScript('files', 'files');
432
+            \OCP\Util::addScript('files', 'filemultiselectmenu');
433
+            \OCP\Util::addScript('files', 'filelist');
434
+            \OCP\Util::addScript('files', 'keyboardshortcuts');
435
+        }
436
+
437
+        // OpenGraph Support: http://ogp.me/
438
+        \OCP\Util::addHeader('meta', ['property' => "og:title", 'content' => $shareTmpl['filename']]);
439
+        \OCP\Util::addHeader('meta', ['property' => "og:description", 'content' => $this->defaults->getName() . ($this->defaults->getSlogan() !== '' ? ' - ' . $this->defaults->getSlogan() : '')]);
440
+        \OCP\Util::addHeader('meta', ['property' => "og:site_name", 'content' => $this->defaults->getName()]);
441
+        \OCP\Util::addHeader('meta', ['property' => "og:url", 'content' => $shareTmpl['shareUrl']]);
442
+        \OCP\Util::addHeader('meta', ['property' => "og:type", 'content' => "object"]);
443
+        \OCP\Util::addHeader('meta', ['property' => "og:image", 'content' => $ogPreview]);
444
+
445
+        $this->eventDispatcher->dispatch('OCA\Files_Sharing::loadAdditionalScripts');
446
+
447
+        $csp = new \OCP\AppFramework\Http\ContentSecurityPolicy();
448
+        $csp->addAllowedFrameDomain('\'self\'');
449
+
450
+        $response = new PublicTemplateResponse($this->appName, 'public', $shareTmpl);
451
+        $response->setHeaderTitle($shareTmpl['filename']);
452
+        $response->setHeaderDetails($this->l10n->t('shared by %s', [$shareTmpl['displayName']]));
453
+
454
+        $isNoneFileDropFolder = $shareIsFolder === false || $share->getPermissions() !== \OCP\Constants::PERMISSION_CREATE;
455
+
456
+        if ($isNoneFileDropFolder && !$share->getHideDownload()) {
457
+            \OCP\Util::addScript('files_sharing', 'public_note');
458
+
459
+            $downloadWhite = new SimpleMenuAction('download', $this->l10n->t('Download'), 'icon-download-white', $shareTmpl['downloadURL'], 0);
460
+            $downloadAllWhite = new SimpleMenuAction('download', $this->l10n->t('Download all files'), 'icon-download-white', $shareTmpl['downloadURL'], 0);
461
+            $download = new SimpleMenuAction('download', $this->l10n->t('Download'), 'icon-download', $shareTmpl['downloadURL'], 10, $shareTmpl['fileSize']);
462
+            $downloadAll = new SimpleMenuAction('download', $this->l10n->t('Download all files'), 'icon-download', $shareTmpl['downloadURL'], 10, $shareTmpl['fileSize']);
463
+            $directLink = new LinkMenuAction($this->l10n->t('Direct link'), 'icon-public', $shareTmpl['previewURL']);
464
+            $externalShare = new ExternalShareMenuAction($this->l10n->t('Add to your Nextcloud'), 'icon-external', $shareTmpl['owner'], $shareTmpl['displayName'], $shareTmpl['filename']);
465
+
466
+            $responseComposer = [];
467
+
468
+            if ($shareIsFolder) {
469
+                $responseComposer[] = $downloadAllWhite;
470
+                $responseComposer[] = $downloadAll;
471
+            } else {
472
+                $responseComposer[] = $downloadWhite;
473
+                $responseComposer[] = $download;
474
+            }
475
+            $responseComposer[] = $directLink;
476
+            if ($this->federatedShareProvider->isOutgoingServer2serverShareEnabled()) {
477
+                $responseComposer[] = $externalShare;
478
+            }
479
+
480
+            $response->setHeaderActions($responseComposer);
481
+        }
482
+
483
+        $response->setContentSecurityPolicy($csp);
484
+
485
+        $this->emitAccessShareHook($share);
486
+
487
+        return $response;
488
+    }
489
+
490
+    /**
491
+     * @PublicPage
492
+     * @NoCSRFRequired
493
+     *
494
+     * @param string $token
495
+     * @param string $files
496
+     * @param string $path
497
+     * @param string $downloadStartSecret
498
+     * @return void|\OCP\AppFramework\Http\Response
499
+     * @throws NotFoundException
500
+     */
501
+    public function downloadShare($token, $files = null, $path = '', $downloadStartSecret = '') {
502
+        \OC_User::setIncognitoMode(true);
503
+
504
+        $share = $this->shareManager->getShareByToken($token);
505
+
506
+        if(!($share->getPermissions() & \OCP\Constants::PERMISSION_READ)) {
507
+            return new \OCP\AppFramework\Http\DataResponse('Share is read-only');
508
+        }
509
+
510
+        $files_list = null;
511
+        if (!is_null($files)) { // download selected files
512
+            $files_list = json_decode($files);
513
+            // in case we get only a single file
514
+            if ($files_list === null) {
515
+                $files_list = [$files];
516
+            }
517
+            // Just in case $files is a single int like '1234'
518
+            if (!is_array($files_list)) {
519
+                $files_list = [$files_list];
520
+            }
521
+        }
522
+
523
+
524
+        if (!$this->validateShare($share)) {
525
+            throw new NotFoundException();
526
+        }
527
+
528
+        $userFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
529
+        $originalSharePath = $userFolder->getRelativePath($share->getNode()->getPath());
530
+
531
+
532
+        // Single file share
533
+        if ($share->getNode() instanceof \OCP\Files\File) {
534
+            // Single file download
535
+            $this->singleFileDownloaded($share, $share->getNode());
536
+        }
537
+        // Directory share
538
+        else {
539
+            /** @var \OCP\Files\Folder $node */
540
+            $node = $share->getNode();
541
+
542
+            // Try to get the path
543
+            if ($path !== '') {
544
+                try {
545
+                    $node = $node->get($path);
546
+                } catch (NotFoundException $e) {
547
+                    $this->emitAccessShareHook($share, 404, 'Share not found');
548
+                    return new NotFoundResponse();
549
+                }
550
+            }
551
+
552
+            $originalSharePath = $userFolder->getRelativePath($node->getPath());
553
+
554
+            if ($node instanceof \OCP\Files\File) {
555
+                // Single file download
556
+                $this->singleFileDownloaded($share, $share->getNode());
557
+            } else if (!empty($files_list)) {
558
+                $this->fileListDownloaded($share, $files_list, $node);
559
+            } else {
560
+                // The folder is downloaded
561
+                $this->singleFileDownloaded($share, $share->getNode());
562
+            }
563
+        }
564
+
565
+        /* FIXME: We should do this all nicely in OCP */
566
+        OC_Util::tearDownFS();
567
+        OC_Util::setupFS($share->getShareOwner());
568
+
569
+        /**
570
+         * this sets a cookie to be able to recognize the start of the download
571
+         * the content must not be longer than 32 characters and must only contain
572
+         * alphanumeric characters
573
+         */
574
+        if (!empty($downloadStartSecret)
575
+            && !isset($downloadStartSecret[32])
576
+            && preg_match('!^[a-zA-Z0-9]+$!', $downloadStartSecret) === 1) {
577
+
578
+            // FIXME: set on the response once we use an actual app framework response
579
+            setcookie('ocDownloadStarted', $downloadStartSecret, time() + 20, '/');
580
+        }
581
+
582
+        $this->emitAccessShareHook($share);
583
+
584
+        $server_params = array( 'head' => $this->request->getMethod() === 'HEAD' );
585
+
586
+        /**
587
+         * Http range requests support
588
+         */
589
+        if (isset($_SERVER['HTTP_RANGE'])) {
590
+            $server_params['range'] = $this->request->getHeader('Range');
591
+        }
592
+
593
+        // download selected files
594
+        if (!is_null($files) && $files !== '') {
595
+            // FIXME: The exit is required here because otherwise the AppFramework is trying to add headers as well
596
+            // after dispatching the request which results in a "Cannot modify header information" notice.
597
+            OC_Files::get($originalSharePath, $files_list, $server_params);
598
+            exit();
599
+        } else {
600
+            // FIXME: The exit is required here because otherwise the AppFramework is trying to add headers as well
601
+            // after dispatching the request which results in a "Cannot modify header information" notice.
602
+            OC_Files::get(dirname($originalSharePath), basename($originalSharePath), $server_params);
603
+            exit();
604
+        }
605
+    }
606
+
607
+    /**
608
+     * create activity for every downloaded file
609
+     *
610
+     * @param Share\IShare $share
611
+     * @param array $files_list
612
+     * @param \OCP\Files\Folder $node
613
+     */
614
+    protected function fileListDownloaded(Share\IShare $share, array $files_list, \OCP\Files\Folder $node) {
615
+        foreach ($files_list as $file) {
616
+            $subNode = $node->get($file);
617
+            $this->singleFileDownloaded($share, $subNode);
618
+        }
619
+
620
+    }
621
+
622
+    /**
623
+     * create activity if a single file was downloaded from a link share
624
+     *
625
+     * @param Share\IShare $share
626
+     */
627
+    protected function singleFileDownloaded(Share\IShare $share, \OCP\Files\Node $node) {
628
+
629
+        $fileId = $node->getId();
630
+
631
+        $userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
632
+        $userNodeList = $userFolder->getById($fileId);
633
+        $userNode = $userNodeList[0];
634
+        $ownerFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
635
+        $userPath = $userFolder->getRelativePath($userNode->getPath());
636
+        $ownerPath = $ownerFolder->getRelativePath($node->getPath());
637
+
638
+        $parameters = [$userPath];
639
+
640
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
641
+            if ($node instanceof \OCP\Files\File) {
642
+                $subject = Downloads::SUBJECT_SHARED_FILE_BY_EMAIL_DOWNLOADED;
643
+            } else {
644
+                $subject = Downloads::SUBJECT_SHARED_FOLDER_BY_EMAIL_DOWNLOADED;
645
+            }
646
+            $parameters[] = $share->getSharedWith();
647
+        } else {
648
+            if ($node instanceof \OCP\Files\File) {
649
+                $subject = Downloads::SUBJECT_PUBLIC_SHARED_FILE_DOWNLOADED;
650
+            } else {
651
+                $subject = Downloads::SUBJECT_PUBLIC_SHARED_FOLDER_DOWNLOADED;
652
+            }
653
+        }
654
+
655
+        $this->publishActivity($subject, $parameters, $share->getSharedBy(), $fileId, $userPath);
656
+
657
+        if ($share->getShareOwner() !== $share->getSharedBy()) {
658
+            $parameters[0] = $ownerPath;
659
+            $this->publishActivity($subject, $parameters, $share->getShareOwner(), $fileId, $ownerPath);
660
+        }
661
+    }
662
+
663
+    /**
664
+     * publish activity
665
+     *
666
+     * @param string $subject
667
+     * @param array $parameters
668
+     * @param string $affectedUser
669
+     * @param int $fileId
670
+     * @param string $filePath
671
+     */
672
+    protected function publishActivity($subject,
673
+                                        array $parameters,
674
+                                        $affectedUser,
675
+                                        $fileId,
676
+                                        $filePath) {
677
+
678
+        $event = $this->activityManager->generateEvent();
679
+        $event->setApp('files_sharing')
680
+            ->setType('public_links')
681
+            ->setSubject($subject, $parameters)
682
+            ->setAffectedUser($affectedUser)
683
+            ->setObject('files', $fileId, $filePath);
684
+        $this->activityManager->publish($event);
685
+    }
687 686
 
688 687
 
689 688
 }
Please login to merge, or discard this patch.