Passed
Push — master ( ffb623...eaabe9 )
by Morris
10:27
created
apps/files/lib/Controller/ViewController.php 1 patch
Indentation   +281 added lines, -281 removed lines patch added patch discarded remove patch
@@ -53,285 +53,285 @@
 block discarded – undo
53 53
  * @package OCA\Files\Controller
54 54
  */
55 55
 class ViewController extends Controller {
56
-	/** @var string */
57
-	protected $appName;
58
-	/** @var IRequest */
59
-	protected $request;
60
-	/** @var IURLGenerator */
61
-	protected $urlGenerator;
62
-	/** @var IL10N */
63
-	protected $l10n;
64
-	/** @var IConfig */
65
-	protected $config;
66
-	/** @var EventDispatcherInterface */
67
-	protected $eventDispatcher;
68
-	/** @var IUserSession */
69
-	protected $userSession;
70
-	/** @var IAppManager */
71
-	protected $appManager;
72
-	/** @var IRootFolder */
73
-	protected $rootFolder;
74
-	/** @var Helper */
75
-	protected $activityHelper;
76
-
77
-	public function __construct(string $appName,
78
-		IRequest $request,
79
-		IURLGenerator $urlGenerator,
80
-		IL10N $l10n,
81
-		IConfig $config,
82
-		EventDispatcherInterface $eventDispatcherInterface,
83
-		IUserSession $userSession,
84
-		IAppManager $appManager,
85
-		IRootFolder $rootFolder,
86
-		Helper $activityHelper
87
-	) {
88
-		parent::__construct($appName, $request);
89
-		$this->appName         = $appName;
90
-		$this->request         = $request;
91
-		$this->urlGenerator    = $urlGenerator;
92
-		$this->l10n            = $l10n;
93
-		$this->config          = $config;
94
-		$this->eventDispatcher = $eventDispatcherInterface;
95
-		$this->userSession     = $userSession;
96
-		$this->appManager      = $appManager;
97
-		$this->rootFolder      = $rootFolder;
98
-		$this->activityHelper  = $activityHelper;
99
-	}
100
-
101
-	/**
102
-	 * @param string $appName
103
-	 * @param string $scriptName
104
-	 * @return string
105
-	 */
106
-	protected function renderScript($appName, $scriptName) {
107
-		$content    = '';
108
-		$appPath    = \OC_App::getAppPath($appName);
109
-		$scriptPath = $appPath . '/' . $scriptName;
110
-		if (file_exists($scriptPath)) {
111
-			// TODO: sanitize path / script name ?
112
-			ob_start();
113
-			include $scriptPath;
114
-			$content = ob_get_contents();
115
-			@ob_end_clean();
116
-		}
117
-
118
-		return $content;
119
-	}
120
-
121
-	/**
122
-	 * FIXME: Replace with non static code
123
-	 *
124
-	 * @return array
125
-	 * @throws \OCP\Files\NotFoundException
126
-	 */
127
-	protected function getStorageInfo() {
128
-		$dirInfo = \OC\Files\Filesystem::getFileInfo('/', false);
129
-
130
-		return \OC_Helper::getStorageInfo('/', $dirInfo);
131
-	}
132
-
133
-	/**
134
-	 * @NoCSRFRequired
135
-	 * @NoAdminRequired
136
-	 *
137
-	 * @param string $fileid
138
-	 * @return TemplateResponse|RedirectResponse
139
-	 * @throws NotFoundException
140
-	 */
141
-	public function showFile(string $fileid = null): Response {
142
-		// This is the entry point from the `/f/{fileid}` URL which is hardcoded in the server.
143
-		try {
144
-			return $this->redirectToFile($fileid);
145
-		} catch (NotFoundException $e) {
146
-			return new RedirectResponse($this->urlGenerator->linkToRoute('files.view.index', ['fileNotFound' => true]));
147
-		}
148
-	}
149
-
150
-	/**
151
-	 * @NoCSRFRequired
152
-	 * @NoAdminRequired
153
-	 *
154
-	 * @param string $dir
155
-	 * @param string $view
156
-	 * @param string $fileid
157
-	 * @param bool $fileNotFound
158
-	 * @return TemplateResponse|RedirectResponse
159
-	 * @throws NotFoundException
160
-	 */
161
-	public function index($dir = '', $view = '', $fileid = null, $fileNotFound = false) {
162
-		if ($fileid !== null) {
163
-			try {
164
-				return $this->redirectToFile($fileid);
165
-			} catch (NotFoundException $e) {
166
-				return new RedirectResponse($this->urlGenerator->linkToRoute('files.view.index', ['fileNotFound' => true]));
167
-			}
168
-		}
169
-
170
-		$nav = new \OCP\Template('files', 'appnavigation', '');
171
-
172
-		// Load the files we need
173
-		\OCP\Util::addStyle('files', 'merged');
174
-		\OCP\Util::addScript('files', 'merged-index');
175
-
176
-		// mostly for the home storage's free space
177
-		// FIXME: Make non static
178
-		$storageInfo = $this->getStorageInfo();
179
-
180
-		$user = $this->userSession->getUser()->getUID();
181
-
182
-		// Get all the user favorites to create a submenu
183
-		try {
184
-			$favElements = $this->activityHelper->getFavoriteFilePaths($this->userSession->getUser()->getUID());
185
-		} catch (\RuntimeException $e) {
186
-			$favElements['folders'] = [];
187
-		}
188
-
189
-		$collapseClasses = '';
190
-		if (count($favElements['folders']) > 0) {
191
-			$collapseClasses = 'collapsible';
192
-		}
193
-
194
-		$favoritesSublistArray = Array();
195
-
196
-		$navBarPositionPosition = 6;
197
-		$currentCount           = 0;
198
-		foreach ($favElements['folders'] as $dir) {
199
-
200
-			$link         = $this->urlGenerator->linkToRoute('files.view.index', ['dir' => $dir, 'view' => 'files']);
201
-			$sortingValue = ++$currentCount;
202
-			$element      = [
203
-				'id'                 => str_replace('/', '-', $dir),
204
-				'view'               => 'files',
205
-				'href'               => $link,
206
-				'dir'                => $dir,
207
-				'order'              => $navBarPositionPosition,
208
-				'folderPosition'     => $sortingValue,
209
-				'name'               => basename($dir),
210
-				'icon'               => 'files',
211
-				'quickaccesselement' => 'true'
212
-			];
213
-
214
-			array_push($favoritesSublistArray, $element);
215
-			$navBarPositionPosition++;
216
-		}
217
-
218
-		$navItems = \OCA\Files\App::getNavigationManager()->getAll();
219
-
220
-		// add the favorites entry in menu
221
-		$navItems['favorites']['sublist'] = $favoritesSublistArray;
222
-		$navItems['favorites']['classes'] = $collapseClasses;
223
-
224
-		// parse every menu and add the expandedState user value
225
-		foreach ($navItems as $key => $item) {
226
-			if (isset($item['expandedState'])) {
227
-				$navItems[$key]['defaultExpandedState'] = $this->config->getUserValue($this->userSession->getUser()->getUID(), 'files', $item['expandedState'], '0') === '1';
228
-			}
229
-		}
230
-
231
-		$nav->assign('navigationItems', $navItems);
232
-
233
-		$nav->assign('usage', \OC_Helper::humanFileSize($storageInfo['used']));
234
-		if ($storageInfo['quota'] === \OCP\Files\FileInfo::SPACE_UNLIMITED) {
235
-			$totalSpace = $this->l10n->t('Unlimited');
236
-		} else {
237
-			$totalSpace = \OC_Helper::humanFileSize($storageInfo['total']);
238
-		}
239
-		$nav->assign('total_space', $totalSpace);
240
-		$nav->assign('quota', $storageInfo['quota']);
241
-		$nav->assign('usage_relative', $storageInfo['relative']);
242
-
243
-		$contentItems = [];
244
-
245
-		// render the container content for every navigation item
246
-		foreach ($navItems as $item) {
247
-			$content = '';
248
-			if (isset($item['script'])) {
249
-				$content = $this->renderScript($item['appname'], $item['script']);
250
-			}
251
-			// parse submenus
252
-			if (isset($item['sublist'])) {
253
-				foreach ($item['sublist'] as $subitem) {
254
-					$subcontent = '';
255
-					if (isset($subitem['script'])) {
256
-						$subcontent = $this->renderScript($subitem['appname'], $subitem['script']);
257
-					}
258
-					$contentItems[$subitem['id']] = [
259
-						'id'      => $subitem['id'],
260
-						'content' => $subcontent
261
-					];
262
-				}
263
-			}
264
-			$contentItems[$item['id']] = [
265
-				'id'      => $item['id'],
266
-				'content' => $content
267
-			];
268
-		}
269
-
270
-		$event = new GenericEvent(null, ['hiddenFields' => []]);
271
-		$this->eventDispatcher->dispatch('OCA\Files::loadAdditionalScripts', $event);
272
-
273
-		$params                                = [];
274
-		$params['usedSpacePercent']            = (int) $storageInfo['relative'];
275
-		$params['owner']                       = $storageInfo['owner'];
276
-		$params['ownerDisplayName']            = $storageInfo['ownerDisplayName'];
277
-		$params['isPublic']                    = false;
278
-		$params['allowShareWithLink']          = $this->config->getAppValue('core', 'shareapi_allow_links', 'yes');
279
-		$params['defaultFileSorting']          = $this->config->getUserValue($user, 'files', 'file_sorting', 'name');
280
-		$params['defaultFileSortingDirection'] = $this->config->getUserValue($user, 'files', 'file_sorting_direction', 'asc');
281
-		$params['showgridview']				   = $this->config->getUserValue($user, 'files', 'show_grid', false);
282
-		$params['isIE']						   = \OCP\Util::isIE();
283
-		$showHidden                            = (bool) $this->config->getUserValue($this->userSession->getUser()->getUID(), 'files', 'show_hidden', false);
284
-		$params['showHiddenFiles']             = $showHidden ? 1 : 0;
285
-		$params['fileNotFound']                = $fileNotFound ? 1 : 0;
286
-		$params['appNavigation']               = $nav;
287
-		$params['appContents']                 = $contentItems;
288
-		$params['hiddenFields']                = $event->getArgument('hiddenFields');
289
-
290
-		$response = new TemplateResponse(
291
-			$this->appName,
292
-			'index',
293
-			$params
294
-		);
295
-		$policy = new ContentSecurityPolicy();
296
-		$policy->addAllowedFrameDomain('\'self\'');
297
-		$response->setContentSecurityPolicy($policy);
298
-
299
-		return $response;
300
-	}
301
-
302
-	/**
303
-	 * Redirects to the file list and highlight the given file id
304
-	 *
305
-	 * @param string $fileId file id to show
306
-	 * @return RedirectResponse redirect response or not found response
307
-	 * @throws \OCP\Files\NotFoundException
308
-	 */
309
-	private function redirectToFile($fileId) {
310
-		$uid        = $this->userSession->getUser()->getUID();
311
-		$baseFolder = $this->rootFolder->getUserFolder($uid);
312
-		$files      = $baseFolder->getById($fileId);
313
-		$params     = [];
314
-
315
-		if (empty($files) && $this->appManager->isEnabledForUser('files_trashbin')) {
316
-			$baseFolder     = $this->rootFolder->get($uid . '/files_trashbin/files/');
317
-			$files          = $baseFolder->getById($fileId);
318
-			$params['view'] = 'trashbin';
319
-		}
320
-
321
-		if (!empty($files)) {
322
-			$file = current($files);
323
-			if ($file instanceof Folder) {
324
-				// set the full path to enter the folder
325
-				$params['dir'] = $baseFolder->getRelativePath($file->getPath());
326
-			} else {
327
-				// set parent path as dir
328
-				$params['dir'] = $baseFolder->getRelativePath($file->getParent()->getPath());
329
-				// and scroll to the entry
330
-				$params['scrollto'] = $file->getName();
331
-			}
332
-
333
-			return new RedirectResponse($this->urlGenerator->linkToRoute('files.view.index', $params));
334
-		}
335
-		throw new \OCP\Files\NotFoundException();
336
-	}
56
+    /** @var string */
57
+    protected $appName;
58
+    /** @var IRequest */
59
+    protected $request;
60
+    /** @var IURLGenerator */
61
+    protected $urlGenerator;
62
+    /** @var IL10N */
63
+    protected $l10n;
64
+    /** @var IConfig */
65
+    protected $config;
66
+    /** @var EventDispatcherInterface */
67
+    protected $eventDispatcher;
68
+    /** @var IUserSession */
69
+    protected $userSession;
70
+    /** @var IAppManager */
71
+    protected $appManager;
72
+    /** @var IRootFolder */
73
+    protected $rootFolder;
74
+    /** @var Helper */
75
+    protected $activityHelper;
76
+
77
+    public function __construct(string $appName,
78
+        IRequest $request,
79
+        IURLGenerator $urlGenerator,
80
+        IL10N $l10n,
81
+        IConfig $config,
82
+        EventDispatcherInterface $eventDispatcherInterface,
83
+        IUserSession $userSession,
84
+        IAppManager $appManager,
85
+        IRootFolder $rootFolder,
86
+        Helper $activityHelper
87
+    ) {
88
+        parent::__construct($appName, $request);
89
+        $this->appName         = $appName;
90
+        $this->request         = $request;
91
+        $this->urlGenerator    = $urlGenerator;
92
+        $this->l10n            = $l10n;
93
+        $this->config          = $config;
94
+        $this->eventDispatcher = $eventDispatcherInterface;
95
+        $this->userSession     = $userSession;
96
+        $this->appManager      = $appManager;
97
+        $this->rootFolder      = $rootFolder;
98
+        $this->activityHelper  = $activityHelper;
99
+    }
100
+
101
+    /**
102
+     * @param string $appName
103
+     * @param string $scriptName
104
+     * @return string
105
+     */
106
+    protected function renderScript($appName, $scriptName) {
107
+        $content    = '';
108
+        $appPath    = \OC_App::getAppPath($appName);
109
+        $scriptPath = $appPath . '/' . $scriptName;
110
+        if (file_exists($scriptPath)) {
111
+            // TODO: sanitize path / script name ?
112
+            ob_start();
113
+            include $scriptPath;
114
+            $content = ob_get_contents();
115
+            @ob_end_clean();
116
+        }
117
+
118
+        return $content;
119
+    }
120
+
121
+    /**
122
+     * FIXME: Replace with non static code
123
+     *
124
+     * @return array
125
+     * @throws \OCP\Files\NotFoundException
126
+     */
127
+    protected function getStorageInfo() {
128
+        $dirInfo = \OC\Files\Filesystem::getFileInfo('/', false);
129
+
130
+        return \OC_Helper::getStorageInfo('/', $dirInfo);
131
+    }
132
+
133
+    /**
134
+     * @NoCSRFRequired
135
+     * @NoAdminRequired
136
+     *
137
+     * @param string $fileid
138
+     * @return TemplateResponse|RedirectResponse
139
+     * @throws NotFoundException
140
+     */
141
+    public function showFile(string $fileid = null): Response {
142
+        // This is the entry point from the `/f/{fileid}` URL which is hardcoded in the server.
143
+        try {
144
+            return $this->redirectToFile($fileid);
145
+        } catch (NotFoundException $e) {
146
+            return new RedirectResponse($this->urlGenerator->linkToRoute('files.view.index', ['fileNotFound' => true]));
147
+        }
148
+    }
149
+
150
+    /**
151
+     * @NoCSRFRequired
152
+     * @NoAdminRequired
153
+     *
154
+     * @param string $dir
155
+     * @param string $view
156
+     * @param string $fileid
157
+     * @param bool $fileNotFound
158
+     * @return TemplateResponse|RedirectResponse
159
+     * @throws NotFoundException
160
+     */
161
+    public function index($dir = '', $view = '', $fileid = null, $fileNotFound = false) {
162
+        if ($fileid !== null) {
163
+            try {
164
+                return $this->redirectToFile($fileid);
165
+            } catch (NotFoundException $e) {
166
+                return new RedirectResponse($this->urlGenerator->linkToRoute('files.view.index', ['fileNotFound' => true]));
167
+            }
168
+        }
169
+
170
+        $nav = new \OCP\Template('files', 'appnavigation', '');
171
+
172
+        // Load the files we need
173
+        \OCP\Util::addStyle('files', 'merged');
174
+        \OCP\Util::addScript('files', 'merged-index');
175
+
176
+        // mostly for the home storage's free space
177
+        // FIXME: Make non static
178
+        $storageInfo = $this->getStorageInfo();
179
+
180
+        $user = $this->userSession->getUser()->getUID();
181
+
182
+        // Get all the user favorites to create a submenu
183
+        try {
184
+            $favElements = $this->activityHelper->getFavoriteFilePaths($this->userSession->getUser()->getUID());
185
+        } catch (\RuntimeException $e) {
186
+            $favElements['folders'] = [];
187
+        }
188
+
189
+        $collapseClasses = '';
190
+        if (count($favElements['folders']) > 0) {
191
+            $collapseClasses = 'collapsible';
192
+        }
193
+
194
+        $favoritesSublistArray = Array();
195
+
196
+        $navBarPositionPosition = 6;
197
+        $currentCount           = 0;
198
+        foreach ($favElements['folders'] as $dir) {
199
+
200
+            $link         = $this->urlGenerator->linkToRoute('files.view.index', ['dir' => $dir, 'view' => 'files']);
201
+            $sortingValue = ++$currentCount;
202
+            $element      = [
203
+                'id'                 => str_replace('/', '-', $dir),
204
+                'view'               => 'files',
205
+                'href'               => $link,
206
+                'dir'                => $dir,
207
+                'order'              => $navBarPositionPosition,
208
+                'folderPosition'     => $sortingValue,
209
+                'name'               => basename($dir),
210
+                'icon'               => 'files',
211
+                'quickaccesselement' => 'true'
212
+            ];
213
+
214
+            array_push($favoritesSublistArray, $element);
215
+            $navBarPositionPosition++;
216
+        }
217
+
218
+        $navItems = \OCA\Files\App::getNavigationManager()->getAll();
219
+
220
+        // add the favorites entry in menu
221
+        $navItems['favorites']['sublist'] = $favoritesSublistArray;
222
+        $navItems['favorites']['classes'] = $collapseClasses;
223
+
224
+        // parse every menu and add the expandedState user value
225
+        foreach ($navItems as $key => $item) {
226
+            if (isset($item['expandedState'])) {
227
+                $navItems[$key]['defaultExpandedState'] = $this->config->getUserValue($this->userSession->getUser()->getUID(), 'files', $item['expandedState'], '0') === '1';
228
+            }
229
+        }
230
+
231
+        $nav->assign('navigationItems', $navItems);
232
+
233
+        $nav->assign('usage', \OC_Helper::humanFileSize($storageInfo['used']));
234
+        if ($storageInfo['quota'] === \OCP\Files\FileInfo::SPACE_UNLIMITED) {
235
+            $totalSpace = $this->l10n->t('Unlimited');
236
+        } else {
237
+            $totalSpace = \OC_Helper::humanFileSize($storageInfo['total']);
238
+        }
239
+        $nav->assign('total_space', $totalSpace);
240
+        $nav->assign('quota', $storageInfo['quota']);
241
+        $nav->assign('usage_relative', $storageInfo['relative']);
242
+
243
+        $contentItems = [];
244
+
245
+        // render the container content for every navigation item
246
+        foreach ($navItems as $item) {
247
+            $content = '';
248
+            if (isset($item['script'])) {
249
+                $content = $this->renderScript($item['appname'], $item['script']);
250
+            }
251
+            // parse submenus
252
+            if (isset($item['sublist'])) {
253
+                foreach ($item['sublist'] as $subitem) {
254
+                    $subcontent = '';
255
+                    if (isset($subitem['script'])) {
256
+                        $subcontent = $this->renderScript($subitem['appname'], $subitem['script']);
257
+                    }
258
+                    $contentItems[$subitem['id']] = [
259
+                        'id'      => $subitem['id'],
260
+                        'content' => $subcontent
261
+                    ];
262
+                }
263
+            }
264
+            $contentItems[$item['id']] = [
265
+                'id'      => $item['id'],
266
+                'content' => $content
267
+            ];
268
+        }
269
+
270
+        $event = new GenericEvent(null, ['hiddenFields' => []]);
271
+        $this->eventDispatcher->dispatch('OCA\Files::loadAdditionalScripts', $event);
272
+
273
+        $params                                = [];
274
+        $params['usedSpacePercent']            = (int) $storageInfo['relative'];
275
+        $params['owner']                       = $storageInfo['owner'];
276
+        $params['ownerDisplayName']            = $storageInfo['ownerDisplayName'];
277
+        $params['isPublic']                    = false;
278
+        $params['allowShareWithLink']          = $this->config->getAppValue('core', 'shareapi_allow_links', 'yes');
279
+        $params['defaultFileSorting']          = $this->config->getUserValue($user, 'files', 'file_sorting', 'name');
280
+        $params['defaultFileSortingDirection'] = $this->config->getUserValue($user, 'files', 'file_sorting_direction', 'asc');
281
+        $params['showgridview']				   = $this->config->getUserValue($user, 'files', 'show_grid', false);
282
+        $params['isIE']						   = \OCP\Util::isIE();
283
+        $showHidden                            = (bool) $this->config->getUserValue($this->userSession->getUser()->getUID(), 'files', 'show_hidden', false);
284
+        $params['showHiddenFiles']             = $showHidden ? 1 : 0;
285
+        $params['fileNotFound']                = $fileNotFound ? 1 : 0;
286
+        $params['appNavigation']               = $nav;
287
+        $params['appContents']                 = $contentItems;
288
+        $params['hiddenFields']                = $event->getArgument('hiddenFields');
289
+
290
+        $response = new TemplateResponse(
291
+            $this->appName,
292
+            'index',
293
+            $params
294
+        );
295
+        $policy = new ContentSecurityPolicy();
296
+        $policy->addAllowedFrameDomain('\'self\'');
297
+        $response->setContentSecurityPolicy($policy);
298
+
299
+        return $response;
300
+    }
301
+
302
+    /**
303
+     * Redirects to the file list and highlight the given file id
304
+     *
305
+     * @param string $fileId file id to show
306
+     * @return RedirectResponse redirect response or not found response
307
+     * @throws \OCP\Files\NotFoundException
308
+     */
309
+    private function redirectToFile($fileId) {
310
+        $uid        = $this->userSession->getUser()->getUID();
311
+        $baseFolder = $this->rootFolder->getUserFolder($uid);
312
+        $files      = $baseFolder->getById($fileId);
313
+        $params     = [];
314
+
315
+        if (empty($files) && $this->appManager->isEnabledForUser('files_trashbin')) {
316
+            $baseFolder     = $this->rootFolder->get($uid . '/files_trashbin/files/');
317
+            $files          = $baseFolder->getById($fileId);
318
+            $params['view'] = 'trashbin';
319
+        }
320
+
321
+        if (!empty($files)) {
322
+            $file = current($files);
323
+            if ($file instanceof Folder) {
324
+                // set the full path to enter the folder
325
+                $params['dir'] = $baseFolder->getRelativePath($file->getPath());
326
+            } else {
327
+                // set parent path as dir
328
+                $params['dir'] = $baseFolder->getRelativePath($file->getParent()->getPath());
329
+                // and scroll to the entry
330
+                $params['scrollto'] = $file->getName();
331
+            }
332
+
333
+            return new RedirectResponse($this->urlGenerator->linkToRoute('files.view.index', $params));
334
+        }
335
+        throw new \OCP\Files\NotFoundException();
336
+    }
337 337
 }
Please login to merge, or discard this patch.