Passed
Push — master ( d9cd8b...e0946a )
by Julius
16:26 queued 13s
created
apps/files/lib/Controller/ViewController.php 1 patch
Indentation   +342 added lines, -342 removed lines patch added patch discarded remove patch
@@ -67,346 +67,346 @@
 block discarded – undo
67 67
  * @package OCA\Files\Controller
68 68
  */
69 69
 class ViewController extends Controller {
70
-	private IURLGenerator $urlGenerator;
71
-	private IL10N $l10n;
72
-	private IConfig $config;
73
-	private IEventDispatcher $eventDispatcher;
74
-	private IUserSession $userSession;
75
-	private IAppManager $appManager;
76
-	private IRootFolder $rootFolder;
77
-	private Helper $activityHelper;
78
-	private IInitialState $initialState;
79
-	private ITemplateManager $templateManager;
80
-	private IManager $shareManager;
81
-	private UserConfig $userConfig;
82
-
83
-	public function __construct(string $appName,
84
-		IRequest $request,
85
-		IURLGenerator $urlGenerator,
86
-		IL10N $l10n,
87
-		IConfig $config,
88
-		IEventDispatcher $eventDispatcher,
89
-		IUserSession $userSession,
90
-		IAppManager $appManager,
91
-		IRootFolder $rootFolder,
92
-		Helper $activityHelper,
93
-		IInitialState $initialState,
94
-		ITemplateManager $templateManager,
95
-		IManager $shareManager,
96
-		UserConfig $userConfig
97
-	) {
98
-		parent::__construct($appName, $request);
99
-		$this->urlGenerator = $urlGenerator;
100
-		$this->l10n = $l10n;
101
-		$this->config = $config;
102
-		$this->eventDispatcher = $eventDispatcher;
103
-		$this->userSession = $userSession;
104
-		$this->appManager = $appManager;
105
-		$this->rootFolder = $rootFolder;
106
-		$this->activityHelper = $activityHelper;
107
-		$this->initialState = $initialState;
108
-		$this->templateManager = $templateManager;
109
-		$this->shareManager = $shareManager;
110
-		$this->userConfig = $userConfig;
111
-	}
112
-
113
-	/**
114
-	 * @param string $appName
115
-	 * @param string $scriptName
116
-	 * @return string
117
-	 */
118
-	protected function renderScript($appName, $scriptName) {
119
-		$content = '';
120
-		$appPath = \OC_App::getAppPath($appName);
121
-		$scriptPath = $appPath . '/' . $scriptName;
122
-		if (file_exists($scriptPath)) {
123
-			// TODO: sanitize path / script name ?
124
-			ob_start();
125
-			include $scriptPath;
126
-			$content = ob_get_contents();
127
-			@ob_end_clean();
128
-		}
129
-
130
-		return $content;
131
-	}
132
-
133
-	/**
134
-	 * FIXME: Replace with non static code
135
-	 *
136
-	 * @return array
137
-	 * @throws \OCP\Files\NotFoundException
138
-	 */
139
-	protected function getStorageInfo(string $dir = '/') {
140
-		$rootInfo = \OC\Files\Filesystem::getFileInfo('/', false);
141
-
142
-		return \OC_Helper::getStorageInfo($dir, $rootInfo ?: null);
143
-	}
144
-
145
-	/**
146
-	 * @NoCSRFRequired
147
-	 * @NoAdminRequired
148
-	 *
149
-	 * @param string $fileid
150
-	 * @return TemplateResponse|RedirectResponse
151
-	 * @throws NotFoundException
152
-	 */
153
-	public function showFile(string $fileid = null, int $openfile = 1): Response {
154
-		// This is the entry point from the `/f/{fileid}` URL which is hardcoded in the server.
155
-		try {
156
-			return $this->redirectToFile($fileid, $openfile !== 0);
157
-		} catch (NotFoundException $e) {
158
-			return new RedirectResponse($this->urlGenerator->linkToRoute('files.view.index', ['fileNotFound' => true]));
159
-		}
160
-	}
161
-
162
-	/**
163
-	 * @NoCSRFRequired
164
-	 * @NoAdminRequired
165
-	 * @UseSession
166
-	 *
167
-	 * @param string $dir
168
-	 * @param string $view
169
-	 * @param string $fileid
170
-	 * @param bool $fileNotFound
171
-	 * @param string $openfile - the openfile URL parameter if it was present in the initial request
172
-	 * @return TemplateResponse|RedirectResponse
173
-	 * @throws NotFoundException
174
-	 */
175
-	public function index($dir = '', $view = '', $fileid = null, $fileNotFound = false, $openfile = null) {
176
-
177
-		if ($fileid !== null && $dir === '') {
178
-			try {
179
-				return $this->redirectToFile($fileid);
180
-			} catch (NotFoundException $e) {
181
-				return new RedirectResponse($this->urlGenerator->linkToRoute('files.view.index', ['fileNotFound' => true]));
182
-			}
183
-		}
184
-
185
-		$nav = new \OCP\Template('files', 'appnavigation', '');
186
-
187
-		// Load the files we need
188
-		\OCP\Util::addStyle('files', 'merged');
189
-		\OCP\Util::addScript('files', 'merged-index', 'files');
190
-		\OCP\Util::addScript('files', 'main');
191
-
192
-		$userId = $this->userSession->getUser()->getUID();
193
-
194
-		// Get all the user favorites to create a submenu
195
-		try {
196
-			$favElements = $this->activityHelper->getFavoriteFilePaths($userId);
197
-		} catch (\RuntimeException $e) {
198
-			$favElements['folders'] = [];
199
-		}
200
-
201
-		$collapseClasses = '';
202
-		if (count($favElements['folders']) > 0) {
203
-			$collapseClasses = 'collapsible';
204
-		}
205
-
206
-		$favoritesSublistArray = [];
207
-
208
-		$navBarPositionPosition = 6;
209
-		foreach ($favElements['folders'] as $favElement) {
210
-			$element = [
211
-				'id' => str_replace('/', '-', $favElement),
212
-				'dir' => $favElement,
213
-				'order' => $navBarPositionPosition,
214
-				'name' => basename($favElement),
215
-				'icon' => 'folder',
216
-				'params' => [
217
-					'view' => 'files',
218
-					'dir' => $favElement,
219
-				],
220
-			];
221
-
222
-			array_push($favoritesSublistArray, $element);
223
-			$navBarPositionPosition++;
224
-		}
225
-
226
-		$navItems = \OCA\Files\App::getNavigationManager()->getAll();
227
-
228
-		// add the favorites entry in menu
229
-		$navItems['favorites']['sublist'] = $favoritesSublistArray;
230
-		$navItems['favorites']['classes'] = $collapseClasses;
231
-
232
-		// parse every menu and add the expanded user value
233
-		foreach ($navItems as $key => $item) {
234
-			$navItems[$key]['expanded'] = $this->config->getUserValue($userId, 'files', 'show_' . $item['id'], '0') === '1';
235
-		}
236
-
237
-		$nav->assign('navigationItems', $navItems);
238
-
239
-		$contentItems = [];
240
-
241
-		try {
242
-			// If view is files, we use the directory, otherwise we use the root storage
243
-			$storageInfo =  $this->getStorageInfo(($view === 'files' && $dir) ? $dir : '/');
244
-		} catch(\Exception $e) {
245
-			$storageInfo = $this->getStorageInfo();
246
-		}
247
-
248
-		$this->initialState->provideInitialState('storageStats', $storageInfo);
249
-		$this->initialState->provideInitialState('navigation', $navItems);
250
-		$this->initialState->provideInitialState('config', $this->userConfig->getConfigs());
251
-
252
-		// render the container content for every navigation item
253
-		foreach ($navItems as $item) {
254
-			$content = '';
255
-			if (isset($item['script'])) {
256
-				$content = $this->renderScript($item['appname'], $item['script']);
257
-			}
258
-			// parse submenus
259
-			if (isset($item['sublist'])) {
260
-				foreach ($item['sublist'] as $subitem) {
261
-					$subcontent = '';
262
-					if (isset($subitem['script'])) {
263
-						$subcontent = $this->renderScript($subitem['appname'], $subitem['script']);
264
-					}
265
-					$contentItems[$subitem['id']] = [
266
-						'id' => $subitem['id'],
267
-						'content' => $subcontent
268
-					];
269
-				}
270
-			}
271
-			$contentItems[$item['id']] = [
272
-				'id' => $item['id'],
273
-				'content' => $content
274
-			];
275
-		}
276
-
277
-		$this->eventDispatcher->dispatchTyped(new ResourcesLoadAdditionalScriptsEvent());
278
-		$event = new LoadAdditionalScriptsEvent();
279
-		$this->eventDispatcher->dispatchTyped($event);
280
-		$this->eventDispatcher->dispatchTyped(new LoadSidebar());
281
-		// Load Viewer scripts
282
-		if (class_exists(LoadViewer::class)) {
283
-			$this->eventDispatcher->dispatchTyped(new LoadViewer());
284
-		}
285
-
286
-		$this->initialState->provideInitialState('templates_path', $this->templateManager->hasTemplateDirectory() ? $this->templateManager->getTemplatePath() : false);
287
-		$this->initialState->provideInitialState('templates', $this->templateManager->listCreators());
288
-
289
-		$params = [];
290
-		$params['usedSpacePercent'] = (int) $storageInfo['relative'];
291
-		$params['owner'] = $storageInfo['owner'] ?? '';
292
-		$params['ownerDisplayName'] = $storageInfo['ownerDisplayName'] ?? '';
293
-		$params['isPublic'] = false;
294
-		$params['allowShareWithLink'] = $this->shareManager->shareApiAllowLinks() ? 'yes' : 'no';
295
-		$params['defaultFileSorting'] = $this->config->getUserValue($userId, 'files', 'file_sorting', 'name');
296
-		$params['defaultFileSortingDirection'] = $this->config->getUserValue($userId, 'files', 'file_sorting_direction', 'asc');
297
-		$params['showgridview'] = $this->config->getUserValue($userId, 'files', 'show_grid', false);
298
-		$showHidden = (bool) $this->config->getUserValue($userId, 'files', 'show_hidden', false);
299
-		$params['showHiddenFiles'] = $showHidden ? 1 : 0;
300
-		$cropImagePreviews = (bool) $this->config->getUserValue($userId, 'files', 'crop_image_previews', true);
301
-		$params['cropImagePreviews'] = $cropImagePreviews ? 1 : 0;
302
-		$params['fileNotFound'] = $fileNotFound ? 1 : 0;
303
-		$params['appNavigation'] = $nav;
304
-		$params['appContents'] = $contentItems;
305
-		$params['hiddenFields'] = $event->getHiddenFields();
306
-
307
-		$response = new TemplateResponse(
308
-			Application::APP_ID,
309
-			'index',
310
-			$params
311
-		);
312
-		$policy = new ContentSecurityPolicy();
313
-		$policy->addAllowedFrameDomain('\'self\'');
314
-		$response->setContentSecurityPolicy($policy);
315
-
316
-		$this->provideInitialState($dir, $openfile);
317
-
318
-		return $response;
319
-	}
320
-
321
-	/**
322
-	 * Add openFileInfo in initialState if $openfile is set.
323
-	 * @param string $dir - the ?dir= URL param
324
-	 * @param string $openfile - the ?openfile= URL param
325
-	 * @return void
326
-	 */
327
-	private function provideInitialState(string $dir, ?string $openfile): void {
328
-		if ($openfile === null) {
329
-			return;
330
-		}
331
-
332
-		$user = $this->userSession->getUser();
333
-
334
-		if ($user === null) {
335
-			return;
336
-		}
337
-
338
-		$uid = $user->getUID();
339
-		$userFolder = $this->rootFolder->getUserFolder($uid);
340
-		$nodes = $userFolder->getById((int) $openfile);
341
-		$node = array_shift($nodes);
342
-
343
-		if ($node === null) {
344
-			return;
345
-		}
346
-
347
-		// properly format full path and make sure
348
-		// we're relative to the user home folder
349
-		$isRoot = $node === $userFolder;
350
-		$path = $userFolder->getRelativePath($node->getPath());
351
-		$directory = $userFolder->getRelativePath($node->getParent()->getPath());
352
-
353
-		// Prevent opening a file from another folder.
354
-		if ($dir !== $directory) {
355
-			return;
356
-		}
357
-
358
-		$this->initialState->provideInitialState(
359
-			'openFileInfo', [
360
-				'id' => $node->getId(),
361
-				'name' => $isRoot ? '' : $node->getName(),
362
-				'path' => $path,
363
-				'directory' => $directory,
364
-				'mime' => $node->getMimetype(),
365
-				'type' => $node->getType(),
366
-				'permissions' => $node->getPermissions(),
367
-			]
368
-		);
369
-	}
370
-
371
-	/**
372
-	 * Redirects to the file list and highlight the given file id
373
-	 *
374
-	 * @param string $fileId file id to show
375
-	 * @param bool $setOpenfile - whether or not to set the openfile URL parameter
376
-	 * @return RedirectResponse redirect response or not found response
377
-	 * @throws \OCP\Files\NotFoundException
378
-	 */
379
-	private function redirectToFile($fileId, bool $setOpenfile = false) {
380
-		$uid = $this->userSession->getUser()->getUID();
381
-		$baseFolder = $this->rootFolder->getUserFolder($uid);
382
-		$files = $baseFolder->getById($fileId);
383
-		$params = [];
384
-
385
-		if (empty($files) && $this->appManager->isEnabledForUser('files_trashbin')) {
386
-			$baseFolder = $this->rootFolder->get($uid . '/files_trashbin/files/');
387
-			$files = $baseFolder->getById($fileId);
388
-			$params['view'] = 'trashbin';
389
-		}
390
-
391
-		if (!empty($files)) {
392
-			$file = current($files);
393
-			if ($file instanceof Folder) {
394
-				// set the full path to enter the folder
395
-				$params['dir'] = $baseFolder->getRelativePath($file->getPath());
396
-			} else {
397
-				// set parent path as dir
398
-				$params['dir'] = $baseFolder->getRelativePath($file->getParent()->getPath());
399
-				// and scroll to the entry
400
-				$params['scrollto'] = $file->getName();
401
-
402
-				if ($setOpenfile) {
403
-					// forward the openfile URL parameter.
404
-					$params['openfile'] = $fileId;
405
-				}
406
-			}
407
-
408
-			return new RedirectResponse($this->urlGenerator->linkToRoute('files.view.index', $params));
409
-		}
410
-		throw new \OCP\Files\NotFoundException();
411
-	}
70
+    private IURLGenerator $urlGenerator;
71
+    private IL10N $l10n;
72
+    private IConfig $config;
73
+    private IEventDispatcher $eventDispatcher;
74
+    private IUserSession $userSession;
75
+    private IAppManager $appManager;
76
+    private IRootFolder $rootFolder;
77
+    private Helper $activityHelper;
78
+    private IInitialState $initialState;
79
+    private ITemplateManager $templateManager;
80
+    private IManager $shareManager;
81
+    private UserConfig $userConfig;
82
+
83
+    public function __construct(string $appName,
84
+        IRequest $request,
85
+        IURLGenerator $urlGenerator,
86
+        IL10N $l10n,
87
+        IConfig $config,
88
+        IEventDispatcher $eventDispatcher,
89
+        IUserSession $userSession,
90
+        IAppManager $appManager,
91
+        IRootFolder $rootFolder,
92
+        Helper $activityHelper,
93
+        IInitialState $initialState,
94
+        ITemplateManager $templateManager,
95
+        IManager $shareManager,
96
+        UserConfig $userConfig
97
+    ) {
98
+        parent::__construct($appName, $request);
99
+        $this->urlGenerator = $urlGenerator;
100
+        $this->l10n = $l10n;
101
+        $this->config = $config;
102
+        $this->eventDispatcher = $eventDispatcher;
103
+        $this->userSession = $userSession;
104
+        $this->appManager = $appManager;
105
+        $this->rootFolder = $rootFolder;
106
+        $this->activityHelper = $activityHelper;
107
+        $this->initialState = $initialState;
108
+        $this->templateManager = $templateManager;
109
+        $this->shareManager = $shareManager;
110
+        $this->userConfig = $userConfig;
111
+    }
112
+
113
+    /**
114
+     * @param string $appName
115
+     * @param string $scriptName
116
+     * @return string
117
+     */
118
+    protected function renderScript($appName, $scriptName) {
119
+        $content = '';
120
+        $appPath = \OC_App::getAppPath($appName);
121
+        $scriptPath = $appPath . '/' . $scriptName;
122
+        if (file_exists($scriptPath)) {
123
+            // TODO: sanitize path / script name ?
124
+            ob_start();
125
+            include $scriptPath;
126
+            $content = ob_get_contents();
127
+            @ob_end_clean();
128
+        }
129
+
130
+        return $content;
131
+    }
132
+
133
+    /**
134
+     * FIXME: Replace with non static code
135
+     *
136
+     * @return array
137
+     * @throws \OCP\Files\NotFoundException
138
+     */
139
+    protected function getStorageInfo(string $dir = '/') {
140
+        $rootInfo = \OC\Files\Filesystem::getFileInfo('/', false);
141
+
142
+        return \OC_Helper::getStorageInfo($dir, $rootInfo ?: null);
143
+    }
144
+
145
+    /**
146
+     * @NoCSRFRequired
147
+     * @NoAdminRequired
148
+     *
149
+     * @param string $fileid
150
+     * @return TemplateResponse|RedirectResponse
151
+     * @throws NotFoundException
152
+     */
153
+    public function showFile(string $fileid = null, int $openfile = 1): Response {
154
+        // This is the entry point from the `/f/{fileid}` URL which is hardcoded in the server.
155
+        try {
156
+            return $this->redirectToFile($fileid, $openfile !== 0);
157
+        } catch (NotFoundException $e) {
158
+            return new RedirectResponse($this->urlGenerator->linkToRoute('files.view.index', ['fileNotFound' => true]));
159
+        }
160
+    }
161
+
162
+    /**
163
+     * @NoCSRFRequired
164
+     * @NoAdminRequired
165
+     * @UseSession
166
+     *
167
+     * @param string $dir
168
+     * @param string $view
169
+     * @param string $fileid
170
+     * @param bool $fileNotFound
171
+     * @param string $openfile - the openfile URL parameter if it was present in the initial request
172
+     * @return TemplateResponse|RedirectResponse
173
+     * @throws NotFoundException
174
+     */
175
+    public function index($dir = '', $view = '', $fileid = null, $fileNotFound = false, $openfile = null) {
176
+
177
+        if ($fileid !== null && $dir === '') {
178
+            try {
179
+                return $this->redirectToFile($fileid);
180
+            } catch (NotFoundException $e) {
181
+                return new RedirectResponse($this->urlGenerator->linkToRoute('files.view.index', ['fileNotFound' => true]));
182
+            }
183
+        }
184
+
185
+        $nav = new \OCP\Template('files', 'appnavigation', '');
186
+
187
+        // Load the files we need
188
+        \OCP\Util::addStyle('files', 'merged');
189
+        \OCP\Util::addScript('files', 'merged-index', 'files');
190
+        \OCP\Util::addScript('files', 'main');
191
+
192
+        $userId = $this->userSession->getUser()->getUID();
193
+
194
+        // Get all the user favorites to create a submenu
195
+        try {
196
+            $favElements = $this->activityHelper->getFavoriteFilePaths($userId);
197
+        } catch (\RuntimeException $e) {
198
+            $favElements['folders'] = [];
199
+        }
200
+
201
+        $collapseClasses = '';
202
+        if (count($favElements['folders']) > 0) {
203
+            $collapseClasses = 'collapsible';
204
+        }
205
+
206
+        $favoritesSublistArray = [];
207
+
208
+        $navBarPositionPosition = 6;
209
+        foreach ($favElements['folders'] as $favElement) {
210
+            $element = [
211
+                'id' => str_replace('/', '-', $favElement),
212
+                'dir' => $favElement,
213
+                'order' => $navBarPositionPosition,
214
+                'name' => basename($favElement),
215
+                'icon' => 'folder',
216
+                'params' => [
217
+                    'view' => 'files',
218
+                    'dir' => $favElement,
219
+                ],
220
+            ];
221
+
222
+            array_push($favoritesSublistArray, $element);
223
+            $navBarPositionPosition++;
224
+        }
225
+
226
+        $navItems = \OCA\Files\App::getNavigationManager()->getAll();
227
+
228
+        // add the favorites entry in menu
229
+        $navItems['favorites']['sublist'] = $favoritesSublistArray;
230
+        $navItems['favorites']['classes'] = $collapseClasses;
231
+
232
+        // parse every menu and add the expanded user value
233
+        foreach ($navItems as $key => $item) {
234
+            $navItems[$key]['expanded'] = $this->config->getUserValue($userId, 'files', 'show_' . $item['id'], '0') === '1';
235
+        }
236
+
237
+        $nav->assign('navigationItems', $navItems);
238
+
239
+        $contentItems = [];
240
+
241
+        try {
242
+            // If view is files, we use the directory, otherwise we use the root storage
243
+            $storageInfo =  $this->getStorageInfo(($view === 'files' && $dir) ? $dir : '/');
244
+        } catch(\Exception $e) {
245
+            $storageInfo = $this->getStorageInfo();
246
+        }
247
+
248
+        $this->initialState->provideInitialState('storageStats', $storageInfo);
249
+        $this->initialState->provideInitialState('navigation', $navItems);
250
+        $this->initialState->provideInitialState('config', $this->userConfig->getConfigs());
251
+
252
+        // render the container content for every navigation item
253
+        foreach ($navItems as $item) {
254
+            $content = '';
255
+            if (isset($item['script'])) {
256
+                $content = $this->renderScript($item['appname'], $item['script']);
257
+            }
258
+            // parse submenus
259
+            if (isset($item['sublist'])) {
260
+                foreach ($item['sublist'] as $subitem) {
261
+                    $subcontent = '';
262
+                    if (isset($subitem['script'])) {
263
+                        $subcontent = $this->renderScript($subitem['appname'], $subitem['script']);
264
+                    }
265
+                    $contentItems[$subitem['id']] = [
266
+                        'id' => $subitem['id'],
267
+                        'content' => $subcontent
268
+                    ];
269
+                }
270
+            }
271
+            $contentItems[$item['id']] = [
272
+                'id' => $item['id'],
273
+                'content' => $content
274
+            ];
275
+        }
276
+
277
+        $this->eventDispatcher->dispatchTyped(new ResourcesLoadAdditionalScriptsEvent());
278
+        $event = new LoadAdditionalScriptsEvent();
279
+        $this->eventDispatcher->dispatchTyped($event);
280
+        $this->eventDispatcher->dispatchTyped(new LoadSidebar());
281
+        // Load Viewer scripts
282
+        if (class_exists(LoadViewer::class)) {
283
+            $this->eventDispatcher->dispatchTyped(new LoadViewer());
284
+        }
285
+
286
+        $this->initialState->provideInitialState('templates_path', $this->templateManager->hasTemplateDirectory() ? $this->templateManager->getTemplatePath() : false);
287
+        $this->initialState->provideInitialState('templates', $this->templateManager->listCreators());
288
+
289
+        $params = [];
290
+        $params['usedSpacePercent'] = (int) $storageInfo['relative'];
291
+        $params['owner'] = $storageInfo['owner'] ?? '';
292
+        $params['ownerDisplayName'] = $storageInfo['ownerDisplayName'] ?? '';
293
+        $params['isPublic'] = false;
294
+        $params['allowShareWithLink'] = $this->shareManager->shareApiAllowLinks() ? 'yes' : 'no';
295
+        $params['defaultFileSorting'] = $this->config->getUserValue($userId, 'files', 'file_sorting', 'name');
296
+        $params['defaultFileSortingDirection'] = $this->config->getUserValue($userId, 'files', 'file_sorting_direction', 'asc');
297
+        $params['showgridview'] = $this->config->getUserValue($userId, 'files', 'show_grid', false);
298
+        $showHidden = (bool) $this->config->getUserValue($userId, 'files', 'show_hidden', false);
299
+        $params['showHiddenFiles'] = $showHidden ? 1 : 0;
300
+        $cropImagePreviews = (bool) $this->config->getUserValue($userId, 'files', 'crop_image_previews', true);
301
+        $params['cropImagePreviews'] = $cropImagePreviews ? 1 : 0;
302
+        $params['fileNotFound'] = $fileNotFound ? 1 : 0;
303
+        $params['appNavigation'] = $nav;
304
+        $params['appContents'] = $contentItems;
305
+        $params['hiddenFields'] = $event->getHiddenFields();
306
+
307
+        $response = new TemplateResponse(
308
+            Application::APP_ID,
309
+            'index',
310
+            $params
311
+        );
312
+        $policy = new ContentSecurityPolicy();
313
+        $policy->addAllowedFrameDomain('\'self\'');
314
+        $response->setContentSecurityPolicy($policy);
315
+
316
+        $this->provideInitialState($dir, $openfile);
317
+
318
+        return $response;
319
+    }
320
+
321
+    /**
322
+     * Add openFileInfo in initialState if $openfile is set.
323
+     * @param string $dir - the ?dir= URL param
324
+     * @param string $openfile - the ?openfile= URL param
325
+     * @return void
326
+     */
327
+    private function provideInitialState(string $dir, ?string $openfile): void {
328
+        if ($openfile === null) {
329
+            return;
330
+        }
331
+
332
+        $user = $this->userSession->getUser();
333
+
334
+        if ($user === null) {
335
+            return;
336
+        }
337
+
338
+        $uid = $user->getUID();
339
+        $userFolder = $this->rootFolder->getUserFolder($uid);
340
+        $nodes = $userFolder->getById((int) $openfile);
341
+        $node = array_shift($nodes);
342
+
343
+        if ($node === null) {
344
+            return;
345
+        }
346
+
347
+        // properly format full path and make sure
348
+        // we're relative to the user home folder
349
+        $isRoot = $node === $userFolder;
350
+        $path = $userFolder->getRelativePath($node->getPath());
351
+        $directory = $userFolder->getRelativePath($node->getParent()->getPath());
352
+
353
+        // Prevent opening a file from another folder.
354
+        if ($dir !== $directory) {
355
+            return;
356
+        }
357
+
358
+        $this->initialState->provideInitialState(
359
+            'openFileInfo', [
360
+                'id' => $node->getId(),
361
+                'name' => $isRoot ? '' : $node->getName(),
362
+                'path' => $path,
363
+                'directory' => $directory,
364
+                'mime' => $node->getMimetype(),
365
+                'type' => $node->getType(),
366
+                'permissions' => $node->getPermissions(),
367
+            ]
368
+        );
369
+    }
370
+
371
+    /**
372
+     * Redirects to the file list and highlight the given file id
373
+     *
374
+     * @param string $fileId file id to show
375
+     * @param bool $setOpenfile - whether or not to set the openfile URL parameter
376
+     * @return RedirectResponse redirect response or not found response
377
+     * @throws \OCP\Files\NotFoundException
378
+     */
379
+    private function redirectToFile($fileId, bool $setOpenfile = false) {
380
+        $uid = $this->userSession->getUser()->getUID();
381
+        $baseFolder = $this->rootFolder->getUserFolder($uid);
382
+        $files = $baseFolder->getById($fileId);
383
+        $params = [];
384
+
385
+        if (empty($files) && $this->appManager->isEnabledForUser('files_trashbin')) {
386
+            $baseFolder = $this->rootFolder->get($uid . '/files_trashbin/files/');
387
+            $files = $baseFolder->getById($fileId);
388
+            $params['view'] = 'trashbin';
389
+        }
390
+
391
+        if (!empty($files)) {
392
+            $file = current($files);
393
+            if ($file instanceof Folder) {
394
+                // set the full path to enter the folder
395
+                $params['dir'] = $baseFolder->getRelativePath($file->getPath());
396
+            } else {
397
+                // set parent path as dir
398
+                $params['dir'] = $baseFolder->getRelativePath($file->getParent()->getPath());
399
+                // and scroll to the entry
400
+                $params['scrollto'] = $file->getName();
401
+
402
+                if ($setOpenfile) {
403
+                    // forward the openfile URL parameter.
404
+                    $params['openfile'] = $fileId;
405
+                }
406
+            }
407
+
408
+            return new RedirectResponse($this->urlGenerator->linkToRoute('files.view.index', $params));
409
+        }
410
+        throw new \OCP\Files\NotFoundException();
411
+    }
412 412
 }
Please login to merge, or discard this patch.