Passed
Push — master ( f1fefd...f56e5b )
by Morris
14:52 queued 11s
created
lib/private/TemplateLayout.php 1 patch
Indentation   +323 added lines, -323 removed lines patch added patch discarded remove patch
@@ -57,327 +57,327 @@
 block discarded – undo
57 57
 use OCP\Util;
58 58
 
59 59
 class TemplateLayout extends \OC_Template {
60
-	private static $versionHash = '';
61
-
62
-	/** @var IConfig */
63
-	private $config;
64
-
65
-	/** @var IInitialStateService */
66
-	private $initialState;
67
-
68
-	/** @var INavigationManager */
69
-	private $navigationManager;
70
-
71
-	/**
72
-	 * @param string $renderAs
73
-	 * @param string $appId application id
74
-	 */
75
-	public function __construct($renderAs, $appId = '') {
76
-
77
-		/** @var IConfig */
78
-		$this->config = \OC::$server->get(IConfig::class);
79
-
80
-		/** @var IInitialStateService */
81
-		$this->initialState = \OC::$server->get(IInitialStateService::class);
82
-
83
-		if (\OC_Util::isIe()) {
84
-			Util::addStyle('ie');
85
-		}
86
-
87
-		// Decide which page we show
88
-		if ($renderAs === TemplateResponse::RENDER_AS_USER) {
89
-			/** @var INavigationManager */
90
-			$this->navigationManager = \OC::$server->get(INavigationManager::class);
91
-
92
-			parent::__construct('core', 'layout.user');
93
-			if (in_array(\OC_App::getCurrentApp(), ['settings','admin', 'help']) !== false) {
94
-				$this->assign('bodyid', 'body-settings');
95
-			} else {
96
-				$this->assign('bodyid', 'body-user');
97
-			}
98
-
99
-			$this->initialState->provideInitialState('core', 'active-app', $this->navigationManager->getActiveEntry());
100
-			$this->initialState->provideInitialState('unified-search', 'limit-default', SearchQuery::LIMIT_DEFAULT);
101
-			Util::addScript('dist/unified-search', null, true);
102
-
103
-			// Add navigation entry
104
-			$this->assign('application', '');
105
-			$this->assign('appid', $appId);
106
-
107
-			$navigation = $this->navigationManager->getAll();
108
-			$this->assign('navigation', $navigation);
109
-			$settingsNavigation = $this->navigationManager->getAll('settings');
110
-			$this->assign('settingsnavigation', $settingsNavigation);
111
-
112
-			foreach ($navigation as $entry) {
113
-				if ($entry['active']) {
114
-					$this->assign('application', $entry['name']);
115
-					break;
116
-				}
117
-			}
118
-
119
-			foreach ($settingsNavigation as $entry) {
120
-				if ($entry['active']) {
121
-					$this->assign('application', $entry['name']);
122
-					break;
123
-				}
124
-			}
125
-			$userDisplayName = \OC_User::getDisplayName();
126
-			$this->assign('user_displayname', $userDisplayName);
127
-			$this->assign('user_uid', \OC_User::getUser());
128
-
129
-			if (\OC_User::getUser() === false) {
130
-				$this->assign('userAvatarSet', false);
131
-			} else {
132
-				$this->assign('userAvatarSet', true);
133
-				$this->assign('userAvatarVersion', $this->config->getUserValue(\OC_User::getUser(), 'avatar', 'version', 0));
134
-			}
135
-
136
-			// check if app menu icons should be inverted
137
-			try {
138
-				/** @var \OCA\Theming\Util $util */
139
-				$util = \OC::$server->query(\OCA\Theming\Util::class);
140
-				$this->assign('themingInvertMenu', $util->invertTextColor(\OC::$server->getThemingDefaults()->getColorPrimary()));
141
-			} catch (\OCP\AppFramework\QueryException $e) {
142
-				$this->assign('themingInvertMenu', false);
143
-			} catch (\OCP\AutoloadNotAllowedException $e) {
144
-				$this->assign('themingInvertMenu', false);
145
-			}
146
-		} elseif ($renderAs === TemplateResponse::RENDER_AS_ERROR) {
147
-			parent::__construct('core', 'layout.guest', '', false);
148
-			$this->assign('bodyid', 'body-login');
149
-			$this->assign('user_displayname', '');
150
-			$this->assign('user_uid', '');
151
-		} elseif ($renderAs === TemplateResponse::RENDER_AS_GUEST) {
152
-			parent::__construct('core', 'layout.guest');
153
-			\OC_Util::addStyle('guest');
154
-			$this->assign('bodyid', 'body-login');
155
-
156
-			$userDisplayName = \OC_User::getDisplayName();
157
-			$this->assign('user_displayname', $userDisplayName);
158
-			$this->assign('user_uid', \OC_User::getUser());
159
-		} elseif ($renderAs === TemplateResponse::RENDER_AS_PUBLIC) {
160
-			parent::__construct('core', 'layout.public');
161
-			$this->assign('appid', $appId);
162
-			$this->assign('bodyid', 'body-public');
163
-
164
-			/** @var IRegistry $subscription */
165
-			$subscription = \OC::$server->query(IRegistry::class);
166
-			$showSimpleSignup = $this->config->getSystemValueBool('simpleSignUpLink.shown', true);
167
-			if ($showSimpleSignup && $subscription->delegateHasValidSubscription()) {
168
-				$showSimpleSignup = false;
169
-			}
170
-			$this->assign('showSimpleSignUpLink', $showSimpleSignup);
171
-		} else {
172
-			parent::__construct('core', 'layout.base');
173
-		}
174
-		// Send the language and the locale to our layouts
175
-		$lang = \OC::$server->getL10NFactory()->findLanguage();
176
-		$locale = \OC::$server->getL10NFactory()->findLocale($lang);
177
-
178
-		$lang = str_replace('_', '-', $lang);
179
-		$this->assign('language', $lang);
180
-		$this->assign('locale', $locale);
181
-
182
-		if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
183
-			if (empty(self::$versionHash)) {
184
-				$v = \OC_App::getAppVersions();
185
-				$v['core'] = implode('.', \OCP\Util::getVersion());
186
-				self::$versionHash = substr(md5(implode(',', $v)), 0, 8);
187
-			}
188
-		} else {
189
-			self::$versionHash = md5('not installed');
190
-		}
191
-
192
-		// Add the js files
193
-		$jsFiles = self::findJavascriptFiles(\OC_Util::$scripts);
194
-		$this->assign('jsfiles', []);
195
-		if ($this->config->getSystemValue('installed', false) && $renderAs != TemplateResponse::RENDER_AS_ERROR) {
196
-			// this is on purpose outside of the if statement below so that the initial state is prefilled (done in the getConfig() call)
197
-			// see https://github.com/nextcloud/server/pull/22636 for details
198
-			$jsConfigHelper = new JSConfigHelper(
199
-				\OC::$server->getL10N('lib'),
200
-				\OC::$server->query(Defaults::class),
201
-				\OC::$server->getAppManager(),
202
-				\OC::$server->getSession(),
203
-				\OC::$server->getUserSession()->getUser(),
204
-				$this->config,
205
-				\OC::$server->getGroupManager(),
206
-				\OC::$server->get(IniGetWrapper::class),
207
-				\OC::$server->getURLGenerator(),
208
-				\OC::$server->getCapabilitiesManager(),
209
-				\OC::$server->query(IInitialStateService::class)
210
-			);
211
-			$config = $jsConfigHelper->getConfig();
212
-			if (\OC::$server->getContentSecurityPolicyNonceManager()->browserSupportsCspV3()) {
213
-				$this->assign('inline_ocjs', $config);
214
-			} else {
215
-				$this->append('jsfiles', \OC::$server->getURLGenerator()->linkToRoute('core.OCJS.getConfig', ['v' => self::$versionHash]));
216
-			}
217
-		}
218
-		foreach ($jsFiles as $info) {
219
-			$web = $info[1];
220
-			$file = $info[2];
221
-			$this->append('jsfiles', $web.'/'.$file . $this->getVersionHashSuffix());
222
-		}
223
-
224
-		try {
225
-			$pathInfo = \OC::$server->getRequest()->getPathInfo();
226
-		} catch (\Exception $e) {
227
-			$pathInfo = '';
228
-		}
229
-
230
-		// Do not initialise scss appdata until we have a fully installed instance
231
-		// Do not load scss for update, errors, installation or login page
232
-		if (\OC::$server->getSystemConfig()->getValue('installed', false)
233
-			&& !\OCP\Util::needUpgrade()
234
-			&& $pathInfo !== ''
235
-			&& !preg_match('/^\/login/', $pathInfo)
236
-			&& $renderAs !== TemplateResponse::RENDER_AS_ERROR
237
-		) {
238
-			$cssFiles = self::findStylesheetFiles(\OC_Util::$styles);
239
-		} else {
240
-			// If we ignore the scss compiler,
241
-			// we need to load the guest css fallback
242
-			\OC_Util::addStyle('guest');
243
-			$cssFiles = self::findStylesheetFiles(\OC_Util::$styles, false);
244
-		}
245
-
246
-		$this->assign('cssfiles', []);
247
-		$this->assign('printcssfiles', []);
248
-		$this->assign('versionHash', self::$versionHash);
249
-		foreach ($cssFiles as $info) {
250
-			$web = $info[1];
251
-			$file = $info[2];
252
-
253
-			if (substr($file, -strlen('print.css')) === 'print.css') {
254
-				$this->append('printcssfiles', $web.'/'.$file . $this->getVersionHashSuffix());
255
-			} else {
256
-				$suffix = $this->getVersionHashSuffix($web, $file);
257
-
258
-				if (strpos($file, '?v=') == false) {
259
-					$this->append('cssfiles', $web.'/'.$file . $suffix);
260
-				} else {
261
-					$this->append('cssfiles', $web.'/'.$file . '-' . substr($suffix, 3));
262
-				}
263
-			}
264
-		}
265
-
266
-		$this->assign('initialStates', $this->initialState->getInitialStates());
267
-	}
268
-
269
-	/**
270
-	 * @param string $path
271
-	 * @param string $file
272
-	 * @return string
273
-	 */
274
-	protected function getVersionHashSuffix($path = false, $file = false) {
275
-		if ($this->config->getSystemValue('debug', false)) {
276
-			// allows chrome workspace mapping in debug mode
277
-			return "";
278
-		}
279
-		$themingSuffix = '';
280
-		$v = [];
281
-
282
-		if ($this->config->getSystemValue('installed', false)) {
283
-			if (\OC::$server->getAppManager()->isInstalled('theming')) {
284
-				$themingSuffix = '-' . $this->config->getAppValue('theming', 'cachebuster', '0');
285
-			}
286
-			$v = \OC_App::getAppVersions();
287
-		}
288
-
289
-		// Try the webroot path for a match
290
-		if ($path !== false && $path !== '') {
291
-			$appName = $this->getAppNamefromPath($path);
292
-			if (array_key_exists($appName, $v)) {
293
-				$appVersion = $v[$appName];
294
-				return '?v=' . substr(md5($appVersion), 0, 8) . $themingSuffix;
295
-			}
296
-		}
297
-		// fallback to the file path instead
298
-		if ($file !== false && $file !== '') {
299
-			$appName = $this->getAppNamefromPath($file);
300
-			if (array_key_exists($appName, $v)) {
301
-				$appVersion = $v[$appName];
302
-				return '?v=' . substr(md5($appVersion), 0, 8) . $themingSuffix;
303
-			}
304
-		}
305
-
306
-		return '?v=' . self::$versionHash . $themingSuffix;
307
-	}
308
-
309
-	/**
310
-	 * @param array $styles
311
-	 * @return array
312
-	 */
313
-	public static function findStylesheetFiles($styles, $compileScss = true) {
314
-		// Read the selected theme from the config file
315
-		$theme = \OC_Util::getTheme();
316
-
317
-		if ($compileScss) {
318
-			$SCSSCacher = \OC::$server->query(SCSSCacher::class);
319
-		} else {
320
-			$SCSSCacher = null;
321
-		}
322
-
323
-		$locator = new \OC\Template\CSSResourceLocator(
324
-			\OC::$server->getLogger(),
325
-			$theme,
326
-			[ \OC::$SERVERROOT => \OC::$WEBROOT ],
327
-			[ \OC::$SERVERROOT => \OC::$WEBROOT ],
328
-			$SCSSCacher
329
-		);
330
-		$locator->find($styles);
331
-		return $locator->getResources();
332
-	}
333
-
334
-	/**
335
-	 * @param string $path
336
-	 * @return string|boolean
337
-	 */
338
-	public function getAppNamefromPath($path) {
339
-		if ($path !== '' && is_string($path)) {
340
-			$pathParts = explode('/', $path);
341
-			if ($pathParts[0] === 'css') {
342
-				// This is a scss request
343
-				return $pathParts[1];
344
-			}
345
-			return end($pathParts);
346
-		}
347
-		return false;
348
-	}
349
-
350
-	/**
351
-	 * @param array $scripts
352
-	 * @return array
353
-	 */
354
-	public static function findJavascriptFiles($scripts) {
355
-		// Read the selected theme from the config file
356
-		$theme = \OC_Util::getTheme();
357
-
358
-		$locator = new \OC\Template\JSResourceLocator(
359
-			\OC::$server->getLogger(),
360
-			$theme,
361
-			[ \OC::$SERVERROOT => \OC::$WEBROOT ],
362
-			[ \OC::$SERVERROOT => \OC::$WEBROOT ],
363
-			\OC::$server->query(JSCombiner::class)
364
-			);
365
-		$locator->find($scripts);
366
-		return $locator->getResources();
367
-	}
368
-
369
-	/**
370
-	 * Converts the absolute file path to a relative path from \OC::$SERVERROOT
371
-	 * @param string $filePath Absolute path
372
-	 * @return string Relative path
373
-	 * @throws \Exception If $filePath is not under \OC::$SERVERROOT
374
-	 */
375
-	public static function convertToRelativePath($filePath) {
376
-		$relativePath = explode(\OC::$SERVERROOT, $filePath);
377
-		if (count($relativePath) !== 2) {
378
-			throw new \Exception('$filePath is not under the \OC::$SERVERROOT');
379
-		}
380
-
381
-		return $relativePath[1];
382
-	}
60
+    private static $versionHash = '';
61
+
62
+    /** @var IConfig */
63
+    private $config;
64
+
65
+    /** @var IInitialStateService */
66
+    private $initialState;
67
+
68
+    /** @var INavigationManager */
69
+    private $navigationManager;
70
+
71
+    /**
72
+     * @param string $renderAs
73
+     * @param string $appId application id
74
+     */
75
+    public function __construct($renderAs, $appId = '') {
76
+
77
+        /** @var IConfig */
78
+        $this->config = \OC::$server->get(IConfig::class);
79
+
80
+        /** @var IInitialStateService */
81
+        $this->initialState = \OC::$server->get(IInitialStateService::class);
82
+
83
+        if (\OC_Util::isIe()) {
84
+            Util::addStyle('ie');
85
+        }
86
+
87
+        // Decide which page we show
88
+        if ($renderAs === TemplateResponse::RENDER_AS_USER) {
89
+            /** @var INavigationManager */
90
+            $this->navigationManager = \OC::$server->get(INavigationManager::class);
91
+
92
+            parent::__construct('core', 'layout.user');
93
+            if (in_array(\OC_App::getCurrentApp(), ['settings','admin', 'help']) !== false) {
94
+                $this->assign('bodyid', 'body-settings');
95
+            } else {
96
+                $this->assign('bodyid', 'body-user');
97
+            }
98
+
99
+            $this->initialState->provideInitialState('core', 'active-app', $this->navigationManager->getActiveEntry());
100
+            $this->initialState->provideInitialState('unified-search', 'limit-default', SearchQuery::LIMIT_DEFAULT);
101
+            Util::addScript('dist/unified-search', null, true);
102
+
103
+            // Add navigation entry
104
+            $this->assign('application', '');
105
+            $this->assign('appid', $appId);
106
+
107
+            $navigation = $this->navigationManager->getAll();
108
+            $this->assign('navigation', $navigation);
109
+            $settingsNavigation = $this->navigationManager->getAll('settings');
110
+            $this->assign('settingsnavigation', $settingsNavigation);
111
+
112
+            foreach ($navigation as $entry) {
113
+                if ($entry['active']) {
114
+                    $this->assign('application', $entry['name']);
115
+                    break;
116
+                }
117
+            }
118
+
119
+            foreach ($settingsNavigation as $entry) {
120
+                if ($entry['active']) {
121
+                    $this->assign('application', $entry['name']);
122
+                    break;
123
+                }
124
+            }
125
+            $userDisplayName = \OC_User::getDisplayName();
126
+            $this->assign('user_displayname', $userDisplayName);
127
+            $this->assign('user_uid', \OC_User::getUser());
128
+
129
+            if (\OC_User::getUser() === false) {
130
+                $this->assign('userAvatarSet', false);
131
+            } else {
132
+                $this->assign('userAvatarSet', true);
133
+                $this->assign('userAvatarVersion', $this->config->getUserValue(\OC_User::getUser(), 'avatar', 'version', 0));
134
+            }
135
+
136
+            // check if app menu icons should be inverted
137
+            try {
138
+                /** @var \OCA\Theming\Util $util */
139
+                $util = \OC::$server->query(\OCA\Theming\Util::class);
140
+                $this->assign('themingInvertMenu', $util->invertTextColor(\OC::$server->getThemingDefaults()->getColorPrimary()));
141
+            } catch (\OCP\AppFramework\QueryException $e) {
142
+                $this->assign('themingInvertMenu', false);
143
+            } catch (\OCP\AutoloadNotAllowedException $e) {
144
+                $this->assign('themingInvertMenu', false);
145
+            }
146
+        } elseif ($renderAs === TemplateResponse::RENDER_AS_ERROR) {
147
+            parent::__construct('core', 'layout.guest', '', false);
148
+            $this->assign('bodyid', 'body-login');
149
+            $this->assign('user_displayname', '');
150
+            $this->assign('user_uid', '');
151
+        } elseif ($renderAs === TemplateResponse::RENDER_AS_GUEST) {
152
+            parent::__construct('core', 'layout.guest');
153
+            \OC_Util::addStyle('guest');
154
+            $this->assign('bodyid', 'body-login');
155
+
156
+            $userDisplayName = \OC_User::getDisplayName();
157
+            $this->assign('user_displayname', $userDisplayName);
158
+            $this->assign('user_uid', \OC_User::getUser());
159
+        } elseif ($renderAs === TemplateResponse::RENDER_AS_PUBLIC) {
160
+            parent::__construct('core', 'layout.public');
161
+            $this->assign('appid', $appId);
162
+            $this->assign('bodyid', 'body-public');
163
+
164
+            /** @var IRegistry $subscription */
165
+            $subscription = \OC::$server->query(IRegistry::class);
166
+            $showSimpleSignup = $this->config->getSystemValueBool('simpleSignUpLink.shown', true);
167
+            if ($showSimpleSignup && $subscription->delegateHasValidSubscription()) {
168
+                $showSimpleSignup = false;
169
+            }
170
+            $this->assign('showSimpleSignUpLink', $showSimpleSignup);
171
+        } else {
172
+            parent::__construct('core', 'layout.base');
173
+        }
174
+        // Send the language and the locale to our layouts
175
+        $lang = \OC::$server->getL10NFactory()->findLanguage();
176
+        $locale = \OC::$server->getL10NFactory()->findLocale($lang);
177
+
178
+        $lang = str_replace('_', '-', $lang);
179
+        $this->assign('language', $lang);
180
+        $this->assign('locale', $locale);
181
+
182
+        if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
183
+            if (empty(self::$versionHash)) {
184
+                $v = \OC_App::getAppVersions();
185
+                $v['core'] = implode('.', \OCP\Util::getVersion());
186
+                self::$versionHash = substr(md5(implode(',', $v)), 0, 8);
187
+            }
188
+        } else {
189
+            self::$versionHash = md5('not installed');
190
+        }
191
+
192
+        // Add the js files
193
+        $jsFiles = self::findJavascriptFiles(\OC_Util::$scripts);
194
+        $this->assign('jsfiles', []);
195
+        if ($this->config->getSystemValue('installed', false) && $renderAs != TemplateResponse::RENDER_AS_ERROR) {
196
+            // this is on purpose outside of the if statement below so that the initial state is prefilled (done in the getConfig() call)
197
+            // see https://github.com/nextcloud/server/pull/22636 for details
198
+            $jsConfigHelper = new JSConfigHelper(
199
+                \OC::$server->getL10N('lib'),
200
+                \OC::$server->query(Defaults::class),
201
+                \OC::$server->getAppManager(),
202
+                \OC::$server->getSession(),
203
+                \OC::$server->getUserSession()->getUser(),
204
+                $this->config,
205
+                \OC::$server->getGroupManager(),
206
+                \OC::$server->get(IniGetWrapper::class),
207
+                \OC::$server->getURLGenerator(),
208
+                \OC::$server->getCapabilitiesManager(),
209
+                \OC::$server->query(IInitialStateService::class)
210
+            );
211
+            $config = $jsConfigHelper->getConfig();
212
+            if (\OC::$server->getContentSecurityPolicyNonceManager()->browserSupportsCspV3()) {
213
+                $this->assign('inline_ocjs', $config);
214
+            } else {
215
+                $this->append('jsfiles', \OC::$server->getURLGenerator()->linkToRoute('core.OCJS.getConfig', ['v' => self::$versionHash]));
216
+            }
217
+        }
218
+        foreach ($jsFiles as $info) {
219
+            $web = $info[1];
220
+            $file = $info[2];
221
+            $this->append('jsfiles', $web.'/'.$file . $this->getVersionHashSuffix());
222
+        }
223
+
224
+        try {
225
+            $pathInfo = \OC::$server->getRequest()->getPathInfo();
226
+        } catch (\Exception $e) {
227
+            $pathInfo = '';
228
+        }
229
+
230
+        // Do not initialise scss appdata until we have a fully installed instance
231
+        // Do not load scss for update, errors, installation or login page
232
+        if (\OC::$server->getSystemConfig()->getValue('installed', false)
233
+            && !\OCP\Util::needUpgrade()
234
+            && $pathInfo !== ''
235
+            && !preg_match('/^\/login/', $pathInfo)
236
+            && $renderAs !== TemplateResponse::RENDER_AS_ERROR
237
+        ) {
238
+            $cssFiles = self::findStylesheetFiles(\OC_Util::$styles);
239
+        } else {
240
+            // If we ignore the scss compiler,
241
+            // we need to load the guest css fallback
242
+            \OC_Util::addStyle('guest');
243
+            $cssFiles = self::findStylesheetFiles(\OC_Util::$styles, false);
244
+        }
245
+
246
+        $this->assign('cssfiles', []);
247
+        $this->assign('printcssfiles', []);
248
+        $this->assign('versionHash', self::$versionHash);
249
+        foreach ($cssFiles as $info) {
250
+            $web = $info[1];
251
+            $file = $info[2];
252
+
253
+            if (substr($file, -strlen('print.css')) === 'print.css') {
254
+                $this->append('printcssfiles', $web.'/'.$file . $this->getVersionHashSuffix());
255
+            } else {
256
+                $suffix = $this->getVersionHashSuffix($web, $file);
257
+
258
+                if (strpos($file, '?v=') == false) {
259
+                    $this->append('cssfiles', $web.'/'.$file . $suffix);
260
+                } else {
261
+                    $this->append('cssfiles', $web.'/'.$file . '-' . substr($suffix, 3));
262
+                }
263
+            }
264
+        }
265
+
266
+        $this->assign('initialStates', $this->initialState->getInitialStates());
267
+    }
268
+
269
+    /**
270
+     * @param string $path
271
+     * @param string $file
272
+     * @return string
273
+     */
274
+    protected function getVersionHashSuffix($path = false, $file = false) {
275
+        if ($this->config->getSystemValue('debug', false)) {
276
+            // allows chrome workspace mapping in debug mode
277
+            return "";
278
+        }
279
+        $themingSuffix = '';
280
+        $v = [];
281
+
282
+        if ($this->config->getSystemValue('installed', false)) {
283
+            if (\OC::$server->getAppManager()->isInstalled('theming')) {
284
+                $themingSuffix = '-' . $this->config->getAppValue('theming', 'cachebuster', '0');
285
+            }
286
+            $v = \OC_App::getAppVersions();
287
+        }
288
+
289
+        // Try the webroot path for a match
290
+        if ($path !== false && $path !== '') {
291
+            $appName = $this->getAppNamefromPath($path);
292
+            if (array_key_exists($appName, $v)) {
293
+                $appVersion = $v[$appName];
294
+                return '?v=' . substr(md5($appVersion), 0, 8) . $themingSuffix;
295
+            }
296
+        }
297
+        // fallback to the file path instead
298
+        if ($file !== false && $file !== '') {
299
+            $appName = $this->getAppNamefromPath($file);
300
+            if (array_key_exists($appName, $v)) {
301
+                $appVersion = $v[$appName];
302
+                return '?v=' . substr(md5($appVersion), 0, 8) . $themingSuffix;
303
+            }
304
+        }
305
+
306
+        return '?v=' . self::$versionHash . $themingSuffix;
307
+    }
308
+
309
+    /**
310
+     * @param array $styles
311
+     * @return array
312
+     */
313
+    public static function findStylesheetFiles($styles, $compileScss = true) {
314
+        // Read the selected theme from the config file
315
+        $theme = \OC_Util::getTheme();
316
+
317
+        if ($compileScss) {
318
+            $SCSSCacher = \OC::$server->query(SCSSCacher::class);
319
+        } else {
320
+            $SCSSCacher = null;
321
+        }
322
+
323
+        $locator = new \OC\Template\CSSResourceLocator(
324
+            \OC::$server->getLogger(),
325
+            $theme,
326
+            [ \OC::$SERVERROOT => \OC::$WEBROOT ],
327
+            [ \OC::$SERVERROOT => \OC::$WEBROOT ],
328
+            $SCSSCacher
329
+        );
330
+        $locator->find($styles);
331
+        return $locator->getResources();
332
+    }
333
+
334
+    /**
335
+     * @param string $path
336
+     * @return string|boolean
337
+     */
338
+    public function getAppNamefromPath($path) {
339
+        if ($path !== '' && is_string($path)) {
340
+            $pathParts = explode('/', $path);
341
+            if ($pathParts[0] === 'css') {
342
+                // This is a scss request
343
+                return $pathParts[1];
344
+            }
345
+            return end($pathParts);
346
+        }
347
+        return false;
348
+    }
349
+
350
+    /**
351
+     * @param array $scripts
352
+     * @return array
353
+     */
354
+    public static function findJavascriptFiles($scripts) {
355
+        // Read the selected theme from the config file
356
+        $theme = \OC_Util::getTheme();
357
+
358
+        $locator = new \OC\Template\JSResourceLocator(
359
+            \OC::$server->getLogger(),
360
+            $theme,
361
+            [ \OC::$SERVERROOT => \OC::$WEBROOT ],
362
+            [ \OC::$SERVERROOT => \OC::$WEBROOT ],
363
+            \OC::$server->query(JSCombiner::class)
364
+            );
365
+        $locator->find($scripts);
366
+        return $locator->getResources();
367
+    }
368
+
369
+    /**
370
+     * Converts the absolute file path to a relative path from \OC::$SERVERROOT
371
+     * @param string $filePath Absolute path
372
+     * @return string Relative path
373
+     * @throws \Exception If $filePath is not under \OC::$SERVERROOT
374
+     */
375
+    public static function convertToRelativePath($filePath) {
376
+        $relativePath = explode(\OC::$SERVERROOT, $filePath);
377
+        if (count($relativePath) !== 2) {
378
+            throw new \Exception('$filePath is not under the \OC::$SERVERROOT');
379
+        }
380
+
381
+        return $relativePath[1];
382
+    }
383 383
 }
Please login to merge, or discard this patch.
lib/public/Util.php 1 patch
Indentation   +462 added lines, -462 removed lines patch added patch discarded remove patch
@@ -59,466 +59,466 @@
 block discarded – undo
59 59
  * @since 4.0.0
60 60
  */
61 61
 class Util {
62
-	/**
63
-	 * @deprecated 14.0.0 use \OCP\ILogger::DEBUG
64
-	 */
65
-	public const DEBUG = 0;
66
-	/**
67
-	 * @deprecated 14.0.0 use \OCP\ILogger::INFO
68
-	 */
69
-	public const INFO = 1;
70
-	/**
71
-	 * @deprecated 14.0.0 use \OCP\ILogger::WARN
72
-	 */
73
-	public const WARN = 2;
74
-	/**
75
-	 * @deprecated 14.0.0 use \OCP\ILogger::ERROR
76
-	 */
77
-	public const ERROR = 3;
78
-	/**
79
-	 * @deprecated 14.0.0 use \OCP\ILogger::FATAL
80
-	 */
81
-	public const FATAL = 4;
82
-
83
-	/** \OCP\Share\IManager */
84
-	private static $shareManager;
85
-
86
-	/**
87
-	 * get the current installed version of Nextcloud
88
-	 * @return array
89
-	 * @since 4.0.0
90
-	 */
91
-	public static function getVersion() {
92
-		return \OC_Util::getVersion();
93
-	}
94
-
95
-	/**
96
-	 * @since 17.0.0
97
-	 */
98
-	public static function hasExtendedSupport(): bool {
99
-		try {
100
-			/** @var \OCP\Support\Subscription\IRegistry */
101
-			$subscriptionRegistry = \OC::$server->query(\OCP\Support\Subscription\IRegistry::class);
102
-			return $subscriptionRegistry->delegateHasExtendedSupport();
103
-		} catch (AppFramework\QueryException $e) {
104
-		}
105
-		return \OC::$server->getConfig()->getSystemValueBool('extendedSupport', false);
106
-	}
107
-
108
-	/**
109
-	 * Set current update channel
110
-	 * @param string $channel
111
-	 * @since 8.1.0
112
-	 */
113
-	public static function setChannel($channel) {
114
-		\OC::$server->getConfig()->setSystemValue('updater.release.channel', $channel);
115
-	}
116
-
117
-	/**
118
-	 * Get current update channel
119
-	 * @return string
120
-	 * @since 8.1.0
121
-	 */
122
-	public static function getChannel() {
123
-		return \OC_Util::getChannel();
124
-	}
125
-
126
-	/**
127
-	 * write a message in the log
128
-	 * @param string $app
129
-	 * @param string $message
130
-	 * @param int $level
131
-	 * @since 4.0.0
132
-	 * @deprecated 13.0.0 use log of \OCP\ILogger
133
-	 */
134
-	public static function writeLog($app, $message, $level) {
135
-		$context = ['app' => $app];
136
-		\OC::$server->getLogger()->log($level, $message, $context);
137
-	}
138
-
139
-	/**
140
-	 * check if sharing is disabled for the current user
141
-	 *
142
-	 * @return boolean
143
-	 * @since 7.0.0
144
-	 * @deprecated 9.1.0 Use \OC::$server->getShareManager()->sharingDisabledForUser
145
-	 */
146
-	public static function isSharingDisabledForUser() {
147
-		if (self::$shareManager === null) {
148
-			self::$shareManager = \OC::$server->getShareManager();
149
-		}
150
-
151
-		$user = \OC::$server->getUserSession()->getUser();
152
-		if ($user !== null) {
153
-			$user = $user->getUID();
154
-		}
155
-
156
-		return self::$shareManager->sharingDisabledForUser($user);
157
-	}
158
-
159
-	/**
160
-	 * get l10n object
161
-	 * @param string $application
162
-	 * @param string|null $language
163
-	 * @return \OCP\IL10N
164
-	 * @since 6.0.0 - parameter $language was added in 8.0.0
165
-	 */
166
-	public static function getL10N($application, $language = null) {
167
-		return \OC::$server->getL10N($application, $language);
168
-	}
169
-
170
-	/**
171
-	 * add a css file
172
-	 * @param string $application
173
-	 * @param string $file
174
-	 * @since 4.0.0
175
-	 */
176
-	public static function addStyle($application, $file = null) {
177
-		\OC_Util::addStyle($application, $file);
178
-	}
179
-
180
-	/**
181
-	 * add a javascript file
182
-	 * @param string $application
183
-	 * @param string $file
184
-	 * @since 4.0.0
185
-	 */
186
-	public static function addScript($application, $file = null) {
187
-		\OC_Util::addScript($application, $file);
188
-	}
189
-
190
-	/**
191
-	 * Add a translation JS file
192
-	 * @param string $application application id
193
-	 * @param string $languageCode language code, defaults to the current locale
194
-	 * @since 8.0.0
195
-	 */
196
-	public static function addTranslations($application, $languageCode = null) {
197
-		\OC_Util::addTranslations($application, $languageCode);
198
-	}
199
-
200
-	/**
201
-	 * Add a custom element to the header
202
-	 * If $text is null then the element will be written as empty element.
203
-	 * So use "" to get a closing tag.
204
-	 * @param string $tag tag name of the element
205
-	 * @param array $attributes array of attributes for the element
206
-	 * @param string $text the text content for the element
207
-	 * @since 4.0.0
208
-	 */
209
-	public static function addHeader($tag, $attributes, $text = null) {
210
-		\OC_Util::addHeader($tag, $attributes, $text);
211
-	}
212
-
213
-	/**
214
-	 * Creates an absolute url to the given app and file.
215
-	 * @param string $app app
216
-	 * @param string $file file
217
-	 * @param array $args array with param=>value, will be appended to the returned url
218
-	 * 	The value of $args will be urlencoded
219
-	 * @return string the url
220
-	 * @since 4.0.0 - parameter $args was added in 4.5.0
221
-	 */
222
-	public static function linkToAbsolute($app, $file, $args = []) {
223
-		$urlGenerator = \OC::$server->getURLGenerator();
224
-		return $urlGenerator->getAbsoluteURL(
225
-			$urlGenerator->linkTo($app, $file, $args)
226
-		);
227
-	}
228
-
229
-	/**
230
-	 * Creates an absolute url for remote use.
231
-	 * @param string $service id
232
-	 * @return string the url
233
-	 * @since 4.0.0
234
-	 */
235
-	public static function linkToRemote($service) {
236
-		$urlGenerator = \OC::$server->getURLGenerator();
237
-		$remoteBase = $urlGenerator->linkTo('', 'remote.php') . '/' . $service;
238
-		return $urlGenerator->getAbsoluteURL(
239
-			$remoteBase . (($service[strlen($service) - 1] != '/') ? '/' : '')
240
-		);
241
-	}
242
-
243
-	/**
244
-	 * Creates an absolute url for public use
245
-	 * @param string $service id
246
-	 * @return string the url
247
-	 * @since 4.5.0
248
-	 * @deprecated 15.0.0 - use OCP\IURLGenerator
249
-	 */
250
-	public static function linkToPublic($service) {
251
-		$urlGenerator = \OC::$server->getURLGenerator();
252
-		if ($service === 'files') {
253
-			return $urlGenerator->getAbsoluteURL('/s');
254
-		}
255
-		return $urlGenerator->getAbsoluteURL($urlGenerator->linkTo('', 'public.php').'?service='.$service);
256
-	}
257
-
258
-	/**
259
-	 * Returns the server host name without an eventual port number
260
-	 * @return string the server hostname
261
-	 * @since 5.0.0
262
-	 */
263
-	public static function getServerHostName() {
264
-		$host_name = \OC::$server->getRequest()->getServerHost();
265
-		// strip away port number (if existing)
266
-		$colon_pos = strpos($host_name, ':');
267
-		if ($colon_pos != false) {
268
-			$host_name = substr($host_name, 0, $colon_pos);
269
-		}
270
-		return $host_name;
271
-	}
272
-
273
-	/**
274
-	 * Returns the default email address
275
-	 * @param string $user_part the user part of the address
276
-	 * @return string the default email address
277
-	 *
278
-	 * Assembles a default email address (using the server hostname
279
-	 * and the given user part, and returns it
280
-	 * Example: when given lostpassword-noreply as $user_part param,
281
-	 *     and is currently accessed via http(s)://example.com/,
282
-	 *     it would return '[email protected]'
283
-	 *
284
-	 * If the configuration value 'mail_from_address' is set in
285
-	 * config.php, this value will override the $user_part that
286
-	 * is passed to this function
287
-	 * @since 5.0.0
288
-	 */
289
-	public static function getDefaultEmailAddress($user_part) {
290
-		$config = \OC::$server->getConfig();
291
-		$user_part = $config->getSystemValue('mail_from_address', $user_part);
292
-		$host_name = self::getServerHostName();
293
-		$host_name = $config->getSystemValue('mail_domain', $host_name);
294
-		$defaultEmailAddress = $user_part.'@'.$host_name;
295
-
296
-		$mailer = \OC::$server->getMailer();
297
-		if ($mailer->validateMailAddress($defaultEmailAddress)) {
298
-			return $defaultEmailAddress;
299
-		}
300
-
301
-		// in case we cannot build a valid email address from the hostname let's fallback to 'localhost.localdomain'
302
-		return $user_part.'@localhost.localdomain';
303
-	}
304
-
305
-	/**
306
-	 * Make a human file size (2048 to 2 kB)
307
-	 * @param int $bytes file size in bytes
308
-	 * @return string a human readable file size
309
-	 * @since 4.0.0
310
-	 */
311
-	public static function humanFileSize($bytes) {
312
-		return \OC_Helper::humanFileSize($bytes);
313
-	}
314
-
315
-	/**
316
-	 * Make a computer file size (2 kB to 2048)
317
-	 * @param string $str file size in a fancy format
318
-	 * @return float a file size in bytes
319
-	 *
320
-	 * Inspired by: https://www.php.net/manual/en/function.filesize.php#92418
321
-	 * @since 4.0.0
322
-	 */
323
-	public static function computerFileSize($str) {
324
-		return \OC_Helper::computerFileSize($str);
325
-	}
326
-
327
-	/**
328
-	 * connects a function to a hook
329
-	 *
330
-	 * @param string $signalClass class name of emitter
331
-	 * @param string $signalName name of signal
332
-	 * @param string|object $slotClass class name of slot
333
-	 * @param string $slotName name of slot
334
-	 * @return bool
335
-	 *
336
-	 * This function makes it very easy to connect to use hooks.
337
-	 *
338
-	 * TODO: write example
339
-	 * @since 4.0.0
340
-	 * @deprecated 21.0.0 use \OCP\EventDispatcher\IEventDispatcher::addListener
341
-	 */
342
-	public static function connectHook($signalClass, $signalName, $slotClass, $slotName) {
343
-		return \OC_Hook::connect($signalClass, $signalName, $slotClass, $slotName);
344
-	}
345
-
346
-	/**
347
-	 * Emits a signal. To get data from the slot use references!
348
-	 * @param string $signalclass class name of emitter
349
-	 * @param string $signalname name of signal
350
-	 * @param array $params default: array() array with additional data
351
-	 * @return bool true if slots exists or false if not
352
-	 *
353
-	 * TODO: write example
354
-	 * @since 4.0.0
355
-	 * @deprecated 21.0.0 use \OCP\EventDispatcher\IEventDispatcher::dispatchTypedEvent
356
-	 */
357
-	public static function emitHook($signalclass, $signalname, $params = []) {
358
-		return \OC_Hook::emit($signalclass, $signalname, $params);
359
-	}
360
-
361
-	/**
362
-	 * Cached encrypted CSRF token. Some static unit-tests of ownCloud compare
363
-	 * multiple OC_Template elements which invoke `callRegister`. If the value
364
-	 * would not be cached these unit-tests would fail.
365
-	 * @var string
366
-	 */
367
-	private static $token = '';
368
-
369
-	/**
370
-	 * Register an get/post call. This is important to prevent CSRF attacks
371
-	 * @since 4.5.0
372
-	 */
373
-	public static function callRegister() {
374
-		if (self::$token === '') {
375
-			self::$token = \OC::$server->getCsrfTokenManager()->getToken()->getEncryptedValue();
376
-		}
377
-		return self::$token;
378
-	}
379
-
380
-	/**
381
-	 * Used to sanitize HTML
382
-	 *
383
-	 * This function is used to sanitize HTML and should be applied on any
384
-	 * string or array of strings before displaying it on a web page.
385
-	 *
386
-	 * @param string|array $value
387
-	 * @return string|array an array of sanitized strings or a single sanitized string, depends on the input parameter.
388
-	 * @since 4.5.0
389
-	 */
390
-	public static function sanitizeHTML($value) {
391
-		return \OC_Util::sanitizeHTML($value);
392
-	}
393
-
394
-	/**
395
-	 * Public function to encode url parameters
396
-	 *
397
-	 * This function is used to encode path to file before output.
398
-	 * Encoding is done according to RFC 3986 with one exception:
399
-	 * Character '/' is preserved as is.
400
-	 *
401
-	 * @param string $component part of URI to encode
402
-	 * @return string
403
-	 * @since 6.0.0
404
-	 */
405
-	public static function encodePath($component) {
406
-		return \OC_Util::encodePath($component);
407
-	}
408
-
409
-	/**
410
-	 * Returns an array with all keys from input lowercased or uppercased. Numbered indices are left as is.
411
-	 *
412
-	 * @param array $input The array to work on
413
-	 * @param int $case Either MB_CASE_UPPER or MB_CASE_LOWER (default)
414
-	 * @param string $encoding The encoding parameter is the character encoding. Defaults to UTF-8
415
-	 * @return array
416
-	 * @since 4.5.0
417
-	 */
418
-	public static function mb_array_change_key_case($input, $case = MB_CASE_LOWER, $encoding = 'UTF-8') {
419
-		return \OC_Helper::mb_array_change_key_case($input, $case, $encoding);
420
-	}
421
-
422
-	/**
423
-	 * performs a search in a nested array
424
-	 *
425
-	 * @param array $haystack the array to be searched
426
-	 * @param string $needle the search string
427
-	 * @param mixed $index optional, only search this key name
428
-	 * @return mixed the key of the matching field, otherwise false
429
-	 * @since 4.5.0
430
-	 * @deprecated 15.0.0
431
-	 */
432
-	public static function recursiveArraySearch($haystack, $needle, $index = null) {
433
-		return \OC_Helper::recursiveArraySearch($haystack, $needle, $index);
434
-	}
435
-
436
-	/**
437
-	 * calculates the maximum upload size respecting system settings, free space and user quota
438
-	 *
439
-	 * @param string $dir the current folder where the user currently operates
440
-	 * @param int $free the number of bytes free on the storage holding $dir, if not set this will be received from the storage directly
441
-	 * @return int number of bytes representing
442
-	 * @since 5.0.0
443
-	 */
444
-	public static function maxUploadFilesize($dir, $free = null) {
445
-		return \OC_Helper::maxUploadFilesize($dir, $free);
446
-	}
447
-
448
-	/**
449
-	 * Calculate free space left within user quota
450
-	 * @param string $dir the current folder where the user currently operates
451
-	 * @return int number of bytes representing
452
-	 * @since 7.0.0
453
-	 */
454
-	public static function freeSpace($dir) {
455
-		return \OC_Helper::freeSpace($dir);
456
-	}
457
-
458
-	/**
459
-	 * Calculate PHP upload limit
460
-	 *
461
-	 * @return int number of bytes representing
462
-	 * @since 7.0.0
463
-	 */
464
-	public static function uploadLimit() {
465
-		return \OC_Helper::uploadLimit();
466
-	}
467
-
468
-	/**
469
-	 * Returns whether the given file name is valid
470
-	 * @param string $file file name to check
471
-	 * @return bool true if the file name is valid, false otherwise
472
-	 * @deprecated 8.1.0 use \OC\Files\View::verifyPath()
473
-	 * @since 7.0.0
474
-	 * @suppress PhanDeprecatedFunction
475
-	 */
476
-	public static function isValidFileName($file) {
477
-		return \OC_Util::isValidFileName($file);
478
-	}
479
-
480
-	/**
481
-	 * Compare two strings to provide a natural sort
482
-	 * @param string $a first string to compare
483
-	 * @param string $b second string to compare
484
-	 * @return int -1 if $b comes before $a, 1 if $a comes before $b
485
-	 * or 0 if the strings are identical
486
-	 * @since 7.0.0
487
-	 */
488
-	public static function naturalSortCompare($a, $b) {
489
-		return \OC\NaturalSort::getInstance()->compare($a, $b);
490
-	}
491
-
492
-	/**
493
-	 * check if a password is required for each public link
494
-	 * @return boolean
495
-	 * @since 7.0.0
496
-	 */
497
-	public static function isPublicLinkPasswordRequired() {
498
-		return \OC_Util::isPublicLinkPasswordRequired();
499
-	}
500
-
501
-	/**
502
-	 * check if share API enforces a default expire date
503
-	 * @return boolean
504
-	 * @since 8.0.0
505
-	 */
506
-	public static function isDefaultExpireDateEnforced() {
507
-		return \OC_Util::isDefaultExpireDateEnforced();
508
-	}
509
-
510
-	protected static $needUpgradeCache = null;
511
-
512
-	/**
513
-	 * Checks whether the current version needs upgrade.
514
-	 *
515
-	 * @return bool true if upgrade is needed, false otherwise
516
-	 * @since 7.0.0
517
-	 */
518
-	public static function needUpgrade() {
519
-		if (!isset(self::$needUpgradeCache)) {
520
-			self::$needUpgradeCache = \OC_Util::needUpgrade(\OC::$server->getSystemConfig());
521
-		}
522
-		return self::$needUpgradeCache;
523
-	}
62
+    /**
63
+     * @deprecated 14.0.0 use \OCP\ILogger::DEBUG
64
+     */
65
+    public const DEBUG = 0;
66
+    /**
67
+     * @deprecated 14.0.0 use \OCP\ILogger::INFO
68
+     */
69
+    public const INFO = 1;
70
+    /**
71
+     * @deprecated 14.0.0 use \OCP\ILogger::WARN
72
+     */
73
+    public const WARN = 2;
74
+    /**
75
+     * @deprecated 14.0.0 use \OCP\ILogger::ERROR
76
+     */
77
+    public const ERROR = 3;
78
+    /**
79
+     * @deprecated 14.0.0 use \OCP\ILogger::FATAL
80
+     */
81
+    public const FATAL = 4;
82
+
83
+    /** \OCP\Share\IManager */
84
+    private static $shareManager;
85
+
86
+    /**
87
+     * get the current installed version of Nextcloud
88
+     * @return array
89
+     * @since 4.0.0
90
+     */
91
+    public static function getVersion() {
92
+        return \OC_Util::getVersion();
93
+    }
94
+
95
+    /**
96
+     * @since 17.0.0
97
+     */
98
+    public static function hasExtendedSupport(): bool {
99
+        try {
100
+            /** @var \OCP\Support\Subscription\IRegistry */
101
+            $subscriptionRegistry = \OC::$server->query(\OCP\Support\Subscription\IRegistry::class);
102
+            return $subscriptionRegistry->delegateHasExtendedSupport();
103
+        } catch (AppFramework\QueryException $e) {
104
+        }
105
+        return \OC::$server->getConfig()->getSystemValueBool('extendedSupport', false);
106
+    }
107
+
108
+    /**
109
+     * Set current update channel
110
+     * @param string $channel
111
+     * @since 8.1.0
112
+     */
113
+    public static function setChannel($channel) {
114
+        \OC::$server->getConfig()->setSystemValue('updater.release.channel', $channel);
115
+    }
116
+
117
+    /**
118
+     * Get current update channel
119
+     * @return string
120
+     * @since 8.1.0
121
+     */
122
+    public static function getChannel() {
123
+        return \OC_Util::getChannel();
124
+    }
125
+
126
+    /**
127
+     * write a message in the log
128
+     * @param string $app
129
+     * @param string $message
130
+     * @param int $level
131
+     * @since 4.0.0
132
+     * @deprecated 13.0.0 use log of \OCP\ILogger
133
+     */
134
+    public static function writeLog($app, $message, $level) {
135
+        $context = ['app' => $app];
136
+        \OC::$server->getLogger()->log($level, $message, $context);
137
+    }
138
+
139
+    /**
140
+     * check if sharing is disabled for the current user
141
+     *
142
+     * @return boolean
143
+     * @since 7.0.0
144
+     * @deprecated 9.1.0 Use \OC::$server->getShareManager()->sharingDisabledForUser
145
+     */
146
+    public static function isSharingDisabledForUser() {
147
+        if (self::$shareManager === null) {
148
+            self::$shareManager = \OC::$server->getShareManager();
149
+        }
150
+
151
+        $user = \OC::$server->getUserSession()->getUser();
152
+        if ($user !== null) {
153
+            $user = $user->getUID();
154
+        }
155
+
156
+        return self::$shareManager->sharingDisabledForUser($user);
157
+    }
158
+
159
+    /**
160
+     * get l10n object
161
+     * @param string $application
162
+     * @param string|null $language
163
+     * @return \OCP\IL10N
164
+     * @since 6.0.0 - parameter $language was added in 8.0.0
165
+     */
166
+    public static function getL10N($application, $language = null) {
167
+        return \OC::$server->getL10N($application, $language);
168
+    }
169
+
170
+    /**
171
+     * add a css file
172
+     * @param string $application
173
+     * @param string $file
174
+     * @since 4.0.0
175
+     */
176
+    public static function addStyle($application, $file = null) {
177
+        \OC_Util::addStyle($application, $file);
178
+    }
179
+
180
+    /**
181
+     * add a javascript file
182
+     * @param string $application
183
+     * @param string $file
184
+     * @since 4.0.0
185
+     */
186
+    public static function addScript($application, $file = null) {
187
+        \OC_Util::addScript($application, $file);
188
+    }
189
+
190
+    /**
191
+     * Add a translation JS file
192
+     * @param string $application application id
193
+     * @param string $languageCode language code, defaults to the current locale
194
+     * @since 8.0.0
195
+     */
196
+    public static function addTranslations($application, $languageCode = null) {
197
+        \OC_Util::addTranslations($application, $languageCode);
198
+    }
199
+
200
+    /**
201
+     * Add a custom element to the header
202
+     * If $text is null then the element will be written as empty element.
203
+     * So use "" to get a closing tag.
204
+     * @param string $tag tag name of the element
205
+     * @param array $attributes array of attributes for the element
206
+     * @param string $text the text content for the element
207
+     * @since 4.0.0
208
+     */
209
+    public static function addHeader($tag, $attributes, $text = null) {
210
+        \OC_Util::addHeader($tag, $attributes, $text);
211
+    }
212
+
213
+    /**
214
+     * Creates an absolute url to the given app and file.
215
+     * @param string $app app
216
+     * @param string $file file
217
+     * @param array $args array with param=>value, will be appended to the returned url
218
+     * 	The value of $args will be urlencoded
219
+     * @return string the url
220
+     * @since 4.0.0 - parameter $args was added in 4.5.0
221
+     */
222
+    public static function linkToAbsolute($app, $file, $args = []) {
223
+        $urlGenerator = \OC::$server->getURLGenerator();
224
+        return $urlGenerator->getAbsoluteURL(
225
+            $urlGenerator->linkTo($app, $file, $args)
226
+        );
227
+    }
228
+
229
+    /**
230
+     * Creates an absolute url for remote use.
231
+     * @param string $service id
232
+     * @return string the url
233
+     * @since 4.0.0
234
+     */
235
+    public static function linkToRemote($service) {
236
+        $urlGenerator = \OC::$server->getURLGenerator();
237
+        $remoteBase = $urlGenerator->linkTo('', 'remote.php') . '/' . $service;
238
+        return $urlGenerator->getAbsoluteURL(
239
+            $remoteBase . (($service[strlen($service) - 1] != '/') ? '/' : '')
240
+        );
241
+    }
242
+
243
+    /**
244
+     * Creates an absolute url for public use
245
+     * @param string $service id
246
+     * @return string the url
247
+     * @since 4.5.0
248
+     * @deprecated 15.0.0 - use OCP\IURLGenerator
249
+     */
250
+    public static function linkToPublic($service) {
251
+        $urlGenerator = \OC::$server->getURLGenerator();
252
+        if ($service === 'files') {
253
+            return $urlGenerator->getAbsoluteURL('/s');
254
+        }
255
+        return $urlGenerator->getAbsoluteURL($urlGenerator->linkTo('', 'public.php').'?service='.$service);
256
+    }
257
+
258
+    /**
259
+     * Returns the server host name without an eventual port number
260
+     * @return string the server hostname
261
+     * @since 5.0.0
262
+     */
263
+    public static function getServerHostName() {
264
+        $host_name = \OC::$server->getRequest()->getServerHost();
265
+        // strip away port number (if existing)
266
+        $colon_pos = strpos($host_name, ':');
267
+        if ($colon_pos != false) {
268
+            $host_name = substr($host_name, 0, $colon_pos);
269
+        }
270
+        return $host_name;
271
+    }
272
+
273
+    /**
274
+     * Returns the default email address
275
+     * @param string $user_part the user part of the address
276
+     * @return string the default email address
277
+     *
278
+     * Assembles a default email address (using the server hostname
279
+     * and the given user part, and returns it
280
+     * Example: when given lostpassword-noreply as $user_part param,
281
+     *     and is currently accessed via http(s)://example.com/,
282
+     *     it would return '[email protected]'
283
+     *
284
+     * If the configuration value 'mail_from_address' is set in
285
+     * config.php, this value will override the $user_part that
286
+     * is passed to this function
287
+     * @since 5.0.0
288
+     */
289
+    public static function getDefaultEmailAddress($user_part) {
290
+        $config = \OC::$server->getConfig();
291
+        $user_part = $config->getSystemValue('mail_from_address', $user_part);
292
+        $host_name = self::getServerHostName();
293
+        $host_name = $config->getSystemValue('mail_domain', $host_name);
294
+        $defaultEmailAddress = $user_part.'@'.$host_name;
295
+
296
+        $mailer = \OC::$server->getMailer();
297
+        if ($mailer->validateMailAddress($defaultEmailAddress)) {
298
+            return $defaultEmailAddress;
299
+        }
300
+
301
+        // in case we cannot build a valid email address from the hostname let's fallback to 'localhost.localdomain'
302
+        return $user_part.'@localhost.localdomain';
303
+    }
304
+
305
+    /**
306
+     * Make a human file size (2048 to 2 kB)
307
+     * @param int $bytes file size in bytes
308
+     * @return string a human readable file size
309
+     * @since 4.0.0
310
+     */
311
+    public static function humanFileSize($bytes) {
312
+        return \OC_Helper::humanFileSize($bytes);
313
+    }
314
+
315
+    /**
316
+     * Make a computer file size (2 kB to 2048)
317
+     * @param string $str file size in a fancy format
318
+     * @return float a file size in bytes
319
+     *
320
+     * Inspired by: https://www.php.net/manual/en/function.filesize.php#92418
321
+     * @since 4.0.0
322
+     */
323
+    public static function computerFileSize($str) {
324
+        return \OC_Helper::computerFileSize($str);
325
+    }
326
+
327
+    /**
328
+     * connects a function to a hook
329
+     *
330
+     * @param string $signalClass class name of emitter
331
+     * @param string $signalName name of signal
332
+     * @param string|object $slotClass class name of slot
333
+     * @param string $slotName name of slot
334
+     * @return bool
335
+     *
336
+     * This function makes it very easy to connect to use hooks.
337
+     *
338
+     * TODO: write example
339
+     * @since 4.0.0
340
+     * @deprecated 21.0.0 use \OCP\EventDispatcher\IEventDispatcher::addListener
341
+     */
342
+    public static function connectHook($signalClass, $signalName, $slotClass, $slotName) {
343
+        return \OC_Hook::connect($signalClass, $signalName, $slotClass, $slotName);
344
+    }
345
+
346
+    /**
347
+     * Emits a signal. To get data from the slot use references!
348
+     * @param string $signalclass class name of emitter
349
+     * @param string $signalname name of signal
350
+     * @param array $params default: array() array with additional data
351
+     * @return bool true if slots exists or false if not
352
+     *
353
+     * TODO: write example
354
+     * @since 4.0.0
355
+     * @deprecated 21.0.0 use \OCP\EventDispatcher\IEventDispatcher::dispatchTypedEvent
356
+     */
357
+    public static function emitHook($signalclass, $signalname, $params = []) {
358
+        return \OC_Hook::emit($signalclass, $signalname, $params);
359
+    }
360
+
361
+    /**
362
+     * Cached encrypted CSRF token. Some static unit-tests of ownCloud compare
363
+     * multiple OC_Template elements which invoke `callRegister`. If the value
364
+     * would not be cached these unit-tests would fail.
365
+     * @var string
366
+     */
367
+    private static $token = '';
368
+
369
+    /**
370
+     * Register an get/post call. This is important to prevent CSRF attacks
371
+     * @since 4.5.0
372
+     */
373
+    public static function callRegister() {
374
+        if (self::$token === '') {
375
+            self::$token = \OC::$server->getCsrfTokenManager()->getToken()->getEncryptedValue();
376
+        }
377
+        return self::$token;
378
+    }
379
+
380
+    /**
381
+     * Used to sanitize HTML
382
+     *
383
+     * This function is used to sanitize HTML and should be applied on any
384
+     * string or array of strings before displaying it on a web page.
385
+     *
386
+     * @param string|array $value
387
+     * @return string|array an array of sanitized strings or a single sanitized string, depends on the input parameter.
388
+     * @since 4.5.0
389
+     */
390
+    public static function sanitizeHTML($value) {
391
+        return \OC_Util::sanitizeHTML($value);
392
+    }
393
+
394
+    /**
395
+     * Public function to encode url parameters
396
+     *
397
+     * This function is used to encode path to file before output.
398
+     * Encoding is done according to RFC 3986 with one exception:
399
+     * Character '/' is preserved as is.
400
+     *
401
+     * @param string $component part of URI to encode
402
+     * @return string
403
+     * @since 6.0.0
404
+     */
405
+    public static function encodePath($component) {
406
+        return \OC_Util::encodePath($component);
407
+    }
408
+
409
+    /**
410
+     * Returns an array with all keys from input lowercased or uppercased. Numbered indices are left as is.
411
+     *
412
+     * @param array $input The array to work on
413
+     * @param int $case Either MB_CASE_UPPER or MB_CASE_LOWER (default)
414
+     * @param string $encoding The encoding parameter is the character encoding. Defaults to UTF-8
415
+     * @return array
416
+     * @since 4.5.0
417
+     */
418
+    public static function mb_array_change_key_case($input, $case = MB_CASE_LOWER, $encoding = 'UTF-8') {
419
+        return \OC_Helper::mb_array_change_key_case($input, $case, $encoding);
420
+    }
421
+
422
+    /**
423
+     * performs a search in a nested array
424
+     *
425
+     * @param array $haystack the array to be searched
426
+     * @param string $needle the search string
427
+     * @param mixed $index optional, only search this key name
428
+     * @return mixed the key of the matching field, otherwise false
429
+     * @since 4.5.0
430
+     * @deprecated 15.0.0
431
+     */
432
+    public static function recursiveArraySearch($haystack, $needle, $index = null) {
433
+        return \OC_Helper::recursiveArraySearch($haystack, $needle, $index);
434
+    }
435
+
436
+    /**
437
+     * calculates the maximum upload size respecting system settings, free space and user quota
438
+     *
439
+     * @param string $dir the current folder where the user currently operates
440
+     * @param int $free the number of bytes free on the storage holding $dir, if not set this will be received from the storage directly
441
+     * @return int number of bytes representing
442
+     * @since 5.0.0
443
+     */
444
+    public static function maxUploadFilesize($dir, $free = null) {
445
+        return \OC_Helper::maxUploadFilesize($dir, $free);
446
+    }
447
+
448
+    /**
449
+     * Calculate free space left within user quota
450
+     * @param string $dir the current folder where the user currently operates
451
+     * @return int number of bytes representing
452
+     * @since 7.0.0
453
+     */
454
+    public static function freeSpace($dir) {
455
+        return \OC_Helper::freeSpace($dir);
456
+    }
457
+
458
+    /**
459
+     * Calculate PHP upload limit
460
+     *
461
+     * @return int number of bytes representing
462
+     * @since 7.0.0
463
+     */
464
+    public static function uploadLimit() {
465
+        return \OC_Helper::uploadLimit();
466
+    }
467
+
468
+    /**
469
+     * Returns whether the given file name is valid
470
+     * @param string $file file name to check
471
+     * @return bool true if the file name is valid, false otherwise
472
+     * @deprecated 8.1.0 use \OC\Files\View::verifyPath()
473
+     * @since 7.0.0
474
+     * @suppress PhanDeprecatedFunction
475
+     */
476
+    public static function isValidFileName($file) {
477
+        return \OC_Util::isValidFileName($file);
478
+    }
479
+
480
+    /**
481
+     * Compare two strings to provide a natural sort
482
+     * @param string $a first string to compare
483
+     * @param string $b second string to compare
484
+     * @return int -1 if $b comes before $a, 1 if $a comes before $b
485
+     * or 0 if the strings are identical
486
+     * @since 7.0.0
487
+     */
488
+    public static function naturalSortCompare($a, $b) {
489
+        return \OC\NaturalSort::getInstance()->compare($a, $b);
490
+    }
491
+
492
+    /**
493
+     * check if a password is required for each public link
494
+     * @return boolean
495
+     * @since 7.0.0
496
+     */
497
+    public static function isPublicLinkPasswordRequired() {
498
+        return \OC_Util::isPublicLinkPasswordRequired();
499
+    }
500
+
501
+    /**
502
+     * check if share API enforces a default expire date
503
+     * @return boolean
504
+     * @since 8.0.0
505
+     */
506
+    public static function isDefaultExpireDateEnforced() {
507
+        return \OC_Util::isDefaultExpireDateEnforced();
508
+    }
509
+
510
+    protected static $needUpgradeCache = null;
511
+
512
+    /**
513
+     * Checks whether the current version needs upgrade.
514
+     *
515
+     * @return bool true if upgrade is needed, false otherwise
516
+     * @since 7.0.0
517
+     */
518
+    public static function needUpgrade() {
519
+        if (!isset(self::$needUpgradeCache)) {
520
+            self::$needUpgradeCache = \OC_Util::needUpgrade(\OC::$server->getSystemConfig());
521
+        }
522
+        return self::$needUpgradeCache;
523
+    }
524 524
 }
Please login to merge, or discard this patch.
apps/files/lib/Controller/ViewController.php 1 patch
Indentation   +301 added lines, -301 removed lines patch added patch discarded remove patch
@@ -62,305 +62,305 @@
 block discarded – undo
62 62
  * @package OCA\Files\Controller
63 63
  */
64 64
 class ViewController extends Controller {
65
-	/** @var string */
66
-	protected $appName;
67
-	/** @var IRequest */
68
-	protected $request;
69
-	/** @var IURLGenerator */
70
-	protected $urlGenerator;
71
-	/** @var IL10N */
72
-	protected $l10n;
73
-	/** @var IConfig */
74
-	protected $config;
75
-	/** @var IEventDispatcher */
76
-	protected $eventDispatcher;
77
-	/** @var IUserSession */
78
-	protected $userSession;
79
-	/** @var IAppManager */
80
-	protected $appManager;
81
-	/** @var IRootFolder */
82
-	protected $rootFolder;
83
-	/** @var Helper */
84
-	protected $activityHelper;
85
-	/** @var IInitialState */
86
-	private $initialState;
87
-	/** @var ITemplateManager */
88
-	private $templateManager;
89
-
90
-	public function __construct(string $appName,
91
-		IRequest $request,
92
-		IURLGenerator $urlGenerator,
93
-		IL10N $l10n,
94
-		IConfig $config,
95
-		IEventDispatcher $eventDispatcher,
96
-		IUserSession $userSession,
97
-		IAppManager $appManager,
98
-		IRootFolder $rootFolder,
99
-		Helper $activityHelper,
100
-		IInitialState $initialState,
101
-		ITemplateManager $templateManager
102
-	) {
103
-		parent::__construct($appName, $request);
104
-		$this->appName = $appName;
105
-		$this->request = $request;
106
-		$this->urlGenerator = $urlGenerator;
107
-		$this->l10n = $l10n;
108
-		$this->config = $config;
109
-		$this->eventDispatcher = $eventDispatcher;
110
-		$this->userSession = $userSession;
111
-		$this->appManager = $appManager;
112
-		$this->rootFolder = $rootFolder;
113
-		$this->activityHelper = $activityHelper;
114
-		$this->initialState = $initialState;
115
-		$this->templateManager = $templateManager;
116
-	}
117
-
118
-	/**
119
-	 * @param string $appName
120
-	 * @param string $scriptName
121
-	 * @return string
122
-	 */
123
-	protected function renderScript($appName, $scriptName) {
124
-		$content = '';
125
-		$appPath = \OC_App::getAppPath($appName);
126
-		$scriptPath = $appPath . '/' . $scriptName;
127
-		if (file_exists($scriptPath)) {
128
-			// TODO: sanitize path / script name ?
129
-			ob_start();
130
-			include $scriptPath;
131
-			$content = ob_get_contents();
132
-			@ob_end_clean();
133
-		}
134
-
135
-		return $content;
136
-	}
137
-
138
-	/**
139
-	 * FIXME: Replace with non static code
140
-	 *
141
-	 * @return array
142
-	 * @throws \OCP\Files\NotFoundException
143
-	 */
144
-	protected function getStorageInfo() {
145
-		\OC_Util::setupFS();
146
-		$dirInfo = \OC\Files\Filesystem::getFileInfo('/', false);
147
-
148
-		return \OC_Helper::getStorageInfo('/', $dirInfo);
149
-	}
150
-
151
-	/**
152
-	 * @NoCSRFRequired
153
-	 * @NoAdminRequired
154
-	 *
155
-	 * @param string $fileid
156
-	 * @return TemplateResponse|RedirectResponse
157
-	 * @throws NotFoundException
158
-	 */
159
-	public function showFile(string $fileid = null): Response {
160
-		// This is the entry point from the `/f/{fileid}` URL which is hardcoded in the server.
161
-		try {
162
-			return $this->redirectToFile($fileid);
163
-		} catch (NotFoundException $e) {
164
-			return new RedirectResponse($this->urlGenerator->linkToRoute('files.view.index', ['fileNotFound' => true]));
165
-		}
166
-	}
167
-
168
-	/**
169
-	 * @NoCSRFRequired
170
-	 * @NoAdminRequired
171
-	 *
172
-	 * @param string $dir
173
-	 * @param string $view
174
-	 * @param string $fileid
175
-	 * @param bool $fileNotFound
176
-	 * @return TemplateResponse|RedirectResponse
177
-	 * @throws NotFoundException
178
-	 */
179
-	public function index($dir = '', $view = '', $fileid = null, $fileNotFound = false) {
180
-		if ($fileid !== null) {
181
-			try {
182
-				return $this->redirectToFile($fileid);
183
-			} catch (NotFoundException $e) {
184
-				return new RedirectResponse($this->urlGenerator->linkToRoute('files.view.index', ['fileNotFound' => true]));
185
-			}
186
-		}
187
-
188
-		$nav = new \OCP\Template('files', 'appnavigation', '');
189
-
190
-		// Load the files we need
191
-		\OCP\Util::addStyle('files', 'merged');
192
-		\OCP\Util::addScript('files', 'merged-index');
193
-		\OCP\Util::addScript('files', 'dist/templates');
194
-
195
-		// mostly for the home storage's free space
196
-		// FIXME: Make non static
197
-		$storageInfo = $this->getStorageInfo();
198
-
199
-		$user = $this->userSession->getUser()->getUID();
200
-
201
-		// Get all the user favorites to create a submenu
202
-		try {
203
-			$favElements = $this->activityHelper->getFavoriteFilePaths($this->userSession->getUser()->getUID());
204
-		} catch (\RuntimeException $e) {
205
-			$favElements['folders'] = [];
206
-		}
207
-
208
-		$collapseClasses = '';
209
-		if (count($favElements['folders']) > 0) {
210
-			$collapseClasses = 'collapsible';
211
-		}
212
-
213
-		$favoritesSublistArray = [];
214
-
215
-		$navBarPositionPosition = 6;
216
-		$currentCount = 0;
217
-		foreach ($favElements['folders'] as $dir) {
218
-			$link = $this->urlGenerator->linkToRoute('files.view.index', ['dir' => $dir, 'view' => 'files']);
219
-			$sortingValue = ++$currentCount;
220
-			$element = [
221
-				'id' => str_replace('/', '-', $dir),
222
-				'view' => 'files',
223
-				'href' => $link,
224
-				'dir' => $dir,
225
-				'order' => $navBarPositionPosition,
226
-				'folderPosition' => $sortingValue,
227
-				'name' => basename($dir),
228
-				'icon' => 'files',
229
-				'quickaccesselement' => 'true'
230
-			];
231
-
232
-			array_push($favoritesSublistArray, $element);
233
-			$navBarPositionPosition++;
234
-		}
235
-
236
-		$navItems = \OCA\Files\App::getNavigationManager()->getAll();
237
-
238
-		// add the favorites entry in menu
239
-		$navItems['favorites']['sublist'] = $favoritesSublistArray;
240
-		$navItems['favorites']['classes'] = $collapseClasses;
241
-
242
-		// parse every menu and add the expandedState user value
243
-		foreach ($navItems as $key => $item) {
244
-			if (isset($item['expandedState'])) {
245
-				$navItems[$key]['defaultExpandedState'] = $this->config->getUserValue($this->userSession->getUser()->getUID(), 'files', $item['expandedState'], '0') === '1';
246
-			}
247
-		}
248
-
249
-		$nav->assign('navigationItems', $navItems);
250
-
251
-		$nav->assign('usage', \OC_Helper::humanFileSize($storageInfo['used']));
252
-		if ($storageInfo['quota'] === \OCP\Files\FileInfo::SPACE_UNLIMITED) {
253
-			$totalSpace = $this->l10n->t('Unlimited');
254
-		} else {
255
-			$totalSpace = \OC_Helper::humanFileSize($storageInfo['total']);
256
-		}
257
-		$nav->assign('total_space', $totalSpace);
258
-		$nav->assign('quota', $storageInfo['quota']);
259
-		$nav->assign('usage_relative', $storageInfo['relative']);
260
-
261
-		$nav->assign('webdav_url', \OCP\Util::linkToRemote('dav/files/' . $user));
262
-
263
-		$contentItems = [];
264
-
265
-		// render the container content for every navigation item
266
-		foreach ($navItems as $item) {
267
-			$content = '';
268
-			if (isset($item['script'])) {
269
-				$content = $this->renderScript($item['appname'], $item['script']);
270
-			}
271
-			// parse submenus
272
-			if (isset($item['sublist'])) {
273
-				foreach ($item['sublist'] as $subitem) {
274
-					$subcontent = '';
275
-					if (isset($subitem['script'])) {
276
-						$subcontent = $this->renderScript($subitem['appname'], $subitem['script']);
277
-					}
278
-					$contentItems[$subitem['id']] = [
279
-						'id' => $subitem['id'],
280
-						'content' => $subcontent
281
-					];
282
-				}
283
-			}
284
-			$contentItems[$item['id']] = [
285
-				'id' => $item['id'],
286
-				'content' => $content
287
-			];
288
-		}
289
-
290
-		$event = new LoadAdditionalScriptsEvent();
291
-		$this->eventDispatcher->dispatchTyped($event);
292
-		$this->eventDispatcher->dispatchTyped(new LoadSidebar());
293
-		// Load Viewer scripts
294
-		if (class_exists(LoadViewer::class)) {
295
-			$this->eventDispatcher->dispatchTyped(new LoadViewer());
296
-		}
297
-		$this->initialState->provideInitialState('templates_path', $this->templateManager->hasTemplateDirectory() ? $this->templateManager->getTemplatePath() : false);
298
-		$this->initialState->provideInitialState('templates', $this->templateManager->listCreators());
299
-
300
-		$params = [];
301
-		$params['usedSpacePercent'] = (int) $storageInfo['relative'];
302
-		$params['owner'] = $storageInfo['owner'] ?? '';
303
-		$params['ownerDisplayName'] = $storageInfo['ownerDisplayName'] ?? '';
304
-		$params['isPublic'] = false;
305
-		$params['allowShareWithLink'] = $this->config->getAppValue('core', 'shareapi_allow_links', 'yes');
306
-		$params['defaultFileSorting'] = $this->config->getUserValue($user, 'files', 'file_sorting', 'name');
307
-		$params['defaultFileSortingDirection'] = $this->config->getUserValue($user, 'files', 'file_sorting_direction', 'asc');
308
-		$params['showgridview'] = $this->config->getUserValue($user, 'files', 'show_grid', false);
309
-		$params['isIE'] = \OC_Util::isIe();
310
-		$showHidden = (bool) $this->config->getUserValue($this->userSession->getUser()->getUID(), 'files', 'show_hidden', false);
311
-		$params['showHiddenFiles'] = $showHidden ? 1 : 0;
312
-		$cropImagePreviews = (bool) $this->config->getUserValue($this->userSession->getUser()->getUID(), 'files', 'crop_image_previews', true);
313
-		$params['cropImagePreviews'] = $cropImagePreviews ? 1 : 0;
314
-		$params['fileNotFound'] = $fileNotFound ? 1 : 0;
315
-		$params['appNavigation'] = $nav;
316
-		$params['appContents'] = $contentItems;
317
-		$params['hiddenFields'] = $event->getHiddenFields();
318
-
319
-		$response = new TemplateResponse(
320
-			$this->appName,
321
-			'index',
322
-			$params
323
-		);
324
-		$policy = new ContentSecurityPolicy();
325
-		$policy->addAllowedFrameDomain('\'self\'');
326
-		$response->setContentSecurityPolicy($policy);
327
-
328
-		return $response;
329
-	}
330
-
331
-	/**
332
-	 * Redirects to the file list and highlight the given file id
333
-	 *
334
-	 * @param string $fileId file id to show
335
-	 * @return RedirectResponse redirect response or not found response
336
-	 * @throws \OCP\Files\NotFoundException
337
-	 */
338
-	private function redirectToFile($fileId) {
339
-		$uid = $this->userSession->getUser()->getUID();
340
-		$baseFolder = $this->rootFolder->getUserFolder($uid);
341
-		$files = $baseFolder->getById($fileId);
342
-		$params = [];
343
-
344
-		if (empty($files) && $this->appManager->isEnabledForUser('files_trashbin')) {
345
-			$baseFolder = $this->rootFolder->get($uid . '/files_trashbin/files/');
346
-			$files = $baseFolder->getById($fileId);
347
-			$params['view'] = 'trashbin';
348
-		}
349
-
350
-		if (!empty($files)) {
351
-			$file = current($files);
352
-			if ($file instanceof Folder) {
353
-				// set the full path to enter the folder
354
-				$params['dir'] = $baseFolder->getRelativePath($file->getPath());
355
-			} else {
356
-				// set parent path as dir
357
-				$params['dir'] = $baseFolder->getRelativePath($file->getParent()->getPath());
358
-				// and scroll to the entry
359
-				$params['scrollto'] = $file->getName();
360
-			}
361
-
362
-			return new RedirectResponse($this->urlGenerator->linkToRoute('files.view.index', $params));
363
-		}
364
-		throw new \OCP\Files\NotFoundException();
365
-	}
65
+    /** @var string */
66
+    protected $appName;
67
+    /** @var IRequest */
68
+    protected $request;
69
+    /** @var IURLGenerator */
70
+    protected $urlGenerator;
71
+    /** @var IL10N */
72
+    protected $l10n;
73
+    /** @var IConfig */
74
+    protected $config;
75
+    /** @var IEventDispatcher */
76
+    protected $eventDispatcher;
77
+    /** @var IUserSession */
78
+    protected $userSession;
79
+    /** @var IAppManager */
80
+    protected $appManager;
81
+    /** @var IRootFolder */
82
+    protected $rootFolder;
83
+    /** @var Helper */
84
+    protected $activityHelper;
85
+    /** @var IInitialState */
86
+    private $initialState;
87
+    /** @var ITemplateManager */
88
+    private $templateManager;
89
+
90
+    public function __construct(string $appName,
91
+        IRequest $request,
92
+        IURLGenerator $urlGenerator,
93
+        IL10N $l10n,
94
+        IConfig $config,
95
+        IEventDispatcher $eventDispatcher,
96
+        IUserSession $userSession,
97
+        IAppManager $appManager,
98
+        IRootFolder $rootFolder,
99
+        Helper $activityHelper,
100
+        IInitialState $initialState,
101
+        ITemplateManager $templateManager
102
+    ) {
103
+        parent::__construct($appName, $request);
104
+        $this->appName = $appName;
105
+        $this->request = $request;
106
+        $this->urlGenerator = $urlGenerator;
107
+        $this->l10n = $l10n;
108
+        $this->config = $config;
109
+        $this->eventDispatcher = $eventDispatcher;
110
+        $this->userSession = $userSession;
111
+        $this->appManager = $appManager;
112
+        $this->rootFolder = $rootFolder;
113
+        $this->activityHelper = $activityHelper;
114
+        $this->initialState = $initialState;
115
+        $this->templateManager = $templateManager;
116
+    }
117
+
118
+    /**
119
+     * @param string $appName
120
+     * @param string $scriptName
121
+     * @return string
122
+     */
123
+    protected function renderScript($appName, $scriptName) {
124
+        $content = '';
125
+        $appPath = \OC_App::getAppPath($appName);
126
+        $scriptPath = $appPath . '/' . $scriptName;
127
+        if (file_exists($scriptPath)) {
128
+            // TODO: sanitize path / script name ?
129
+            ob_start();
130
+            include $scriptPath;
131
+            $content = ob_get_contents();
132
+            @ob_end_clean();
133
+        }
134
+
135
+        return $content;
136
+    }
137
+
138
+    /**
139
+     * FIXME: Replace with non static code
140
+     *
141
+     * @return array
142
+     * @throws \OCP\Files\NotFoundException
143
+     */
144
+    protected function getStorageInfo() {
145
+        \OC_Util::setupFS();
146
+        $dirInfo = \OC\Files\Filesystem::getFileInfo('/', false);
147
+
148
+        return \OC_Helper::getStorageInfo('/', $dirInfo);
149
+    }
150
+
151
+    /**
152
+     * @NoCSRFRequired
153
+     * @NoAdminRequired
154
+     *
155
+     * @param string $fileid
156
+     * @return TemplateResponse|RedirectResponse
157
+     * @throws NotFoundException
158
+     */
159
+    public function showFile(string $fileid = null): Response {
160
+        // This is the entry point from the `/f/{fileid}` URL which is hardcoded in the server.
161
+        try {
162
+            return $this->redirectToFile($fileid);
163
+        } catch (NotFoundException $e) {
164
+            return new RedirectResponse($this->urlGenerator->linkToRoute('files.view.index', ['fileNotFound' => true]));
165
+        }
166
+    }
167
+
168
+    /**
169
+     * @NoCSRFRequired
170
+     * @NoAdminRequired
171
+     *
172
+     * @param string $dir
173
+     * @param string $view
174
+     * @param string $fileid
175
+     * @param bool $fileNotFound
176
+     * @return TemplateResponse|RedirectResponse
177
+     * @throws NotFoundException
178
+     */
179
+    public function index($dir = '', $view = '', $fileid = null, $fileNotFound = false) {
180
+        if ($fileid !== null) {
181
+            try {
182
+                return $this->redirectToFile($fileid);
183
+            } catch (NotFoundException $e) {
184
+                return new RedirectResponse($this->urlGenerator->linkToRoute('files.view.index', ['fileNotFound' => true]));
185
+            }
186
+        }
187
+
188
+        $nav = new \OCP\Template('files', 'appnavigation', '');
189
+
190
+        // Load the files we need
191
+        \OCP\Util::addStyle('files', 'merged');
192
+        \OCP\Util::addScript('files', 'merged-index');
193
+        \OCP\Util::addScript('files', 'dist/templates');
194
+
195
+        // mostly for the home storage's free space
196
+        // FIXME: Make non static
197
+        $storageInfo = $this->getStorageInfo();
198
+
199
+        $user = $this->userSession->getUser()->getUID();
200
+
201
+        // Get all the user favorites to create a submenu
202
+        try {
203
+            $favElements = $this->activityHelper->getFavoriteFilePaths($this->userSession->getUser()->getUID());
204
+        } catch (\RuntimeException $e) {
205
+            $favElements['folders'] = [];
206
+        }
207
+
208
+        $collapseClasses = '';
209
+        if (count($favElements['folders']) > 0) {
210
+            $collapseClasses = 'collapsible';
211
+        }
212
+
213
+        $favoritesSublistArray = [];
214
+
215
+        $navBarPositionPosition = 6;
216
+        $currentCount = 0;
217
+        foreach ($favElements['folders'] as $dir) {
218
+            $link = $this->urlGenerator->linkToRoute('files.view.index', ['dir' => $dir, 'view' => 'files']);
219
+            $sortingValue = ++$currentCount;
220
+            $element = [
221
+                'id' => str_replace('/', '-', $dir),
222
+                'view' => 'files',
223
+                'href' => $link,
224
+                'dir' => $dir,
225
+                'order' => $navBarPositionPosition,
226
+                'folderPosition' => $sortingValue,
227
+                'name' => basename($dir),
228
+                'icon' => 'files',
229
+                'quickaccesselement' => 'true'
230
+            ];
231
+
232
+            array_push($favoritesSublistArray, $element);
233
+            $navBarPositionPosition++;
234
+        }
235
+
236
+        $navItems = \OCA\Files\App::getNavigationManager()->getAll();
237
+
238
+        // add the favorites entry in menu
239
+        $navItems['favorites']['sublist'] = $favoritesSublistArray;
240
+        $navItems['favorites']['classes'] = $collapseClasses;
241
+
242
+        // parse every menu and add the expandedState user value
243
+        foreach ($navItems as $key => $item) {
244
+            if (isset($item['expandedState'])) {
245
+                $navItems[$key]['defaultExpandedState'] = $this->config->getUserValue($this->userSession->getUser()->getUID(), 'files', $item['expandedState'], '0') === '1';
246
+            }
247
+        }
248
+
249
+        $nav->assign('navigationItems', $navItems);
250
+
251
+        $nav->assign('usage', \OC_Helper::humanFileSize($storageInfo['used']));
252
+        if ($storageInfo['quota'] === \OCP\Files\FileInfo::SPACE_UNLIMITED) {
253
+            $totalSpace = $this->l10n->t('Unlimited');
254
+        } else {
255
+            $totalSpace = \OC_Helper::humanFileSize($storageInfo['total']);
256
+        }
257
+        $nav->assign('total_space', $totalSpace);
258
+        $nav->assign('quota', $storageInfo['quota']);
259
+        $nav->assign('usage_relative', $storageInfo['relative']);
260
+
261
+        $nav->assign('webdav_url', \OCP\Util::linkToRemote('dav/files/' . $user));
262
+
263
+        $contentItems = [];
264
+
265
+        // render the container content for every navigation item
266
+        foreach ($navItems as $item) {
267
+            $content = '';
268
+            if (isset($item['script'])) {
269
+                $content = $this->renderScript($item['appname'], $item['script']);
270
+            }
271
+            // parse submenus
272
+            if (isset($item['sublist'])) {
273
+                foreach ($item['sublist'] as $subitem) {
274
+                    $subcontent = '';
275
+                    if (isset($subitem['script'])) {
276
+                        $subcontent = $this->renderScript($subitem['appname'], $subitem['script']);
277
+                    }
278
+                    $contentItems[$subitem['id']] = [
279
+                        'id' => $subitem['id'],
280
+                        'content' => $subcontent
281
+                    ];
282
+                }
283
+            }
284
+            $contentItems[$item['id']] = [
285
+                'id' => $item['id'],
286
+                'content' => $content
287
+            ];
288
+        }
289
+
290
+        $event = new LoadAdditionalScriptsEvent();
291
+        $this->eventDispatcher->dispatchTyped($event);
292
+        $this->eventDispatcher->dispatchTyped(new LoadSidebar());
293
+        // Load Viewer scripts
294
+        if (class_exists(LoadViewer::class)) {
295
+            $this->eventDispatcher->dispatchTyped(new LoadViewer());
296
+        }
297
+        $this->initialState->provideInitialState('templates_path', $this->templateManager->hasTemplateDirectory() ? $this->templateManager->getTemplatePath() : false);
298
+        $this->initialState->provideInitialState('templates', $this->templateManager->listCreators());
299
+
300
+        $params = [];
301
+        $params['usedSpacePercent'] = (int) $storageInfo['relative'];
302
+        $params['owner'] = $storageInfo['owner'] ?? '';
303
+        $params['ownerDisplayName'] = $storageInfo['ownerDisplayName'] ?? '';
304
+        $params['isPublic'] = false;
305
+        $params['allowShareWithLink'] = $this->config->getAppValue('core', 'shareapi_allow_links', 'yes');
306
+        $params['defaultFileSorting'] = $this->config->getUserValue($user, 'files', 'file_sorting', 'name');
307
+        $params['defaultFileSortingDirection'] = $this->config->getUserValue($user, 'files', 'file_sorting_direction', 'asc');
308
+        $params['showgridview'] = $this->config->getUserValue($user, 'files', 'show_grid', false);
309
+        $params['isIE'] = \OC_Util::isIe();
310
+        $showHidden = (bool) $this->config->getUserValue($this->userSession->getUser()->getUID(), 'files', 'show_hidden', false);
311
+        $params['showHiddenFiles'] = $showHidden ? 1 : 0;
312
+        $cropImagePreviews = (bool) $this->config->getUserValue($this->userSession->getUser()->getUID(), 'files', 'crop_image_previews', true);
313
+        $params['cropImagePreviews'] = $cropImagePreviews ? 1 : 0;
314
+        $params['fileNotFound'] = $fileNotFound ? 1 : 0;
315
+        $params['appNavigation'] = $nav;
316
+        $params['appContents'] = $contentItems;
317
+        $params['hiddenFields'] = $event->getHiddenFields();
318
+
319
+        $response = new TemplateResponse(
320
+            $this->appName,
321
+            'index',
322
+            $params
323
+        );
324
+        $policy = new ContentSecurityPolicy();
325
+        $policy->addAllowedFrameDomain('\'self\'');
326
+        $response->setContentSecurityPolicy($policy);
327
+
328
+        return $response;
329
+    }
330
+
331
+    /**
332
+     * Redirects to the file list and highlight the given file id
333
+     *
334
+     * @param string $fileId file id to show
335
+     * @return RedirectResponse redirect response or not found response
336
+     * @throws \OCP\Files\NotFoundException
337
+     */
338
+    private function redirectToFile($fileId) {
339
+        $uid = $this->userSession->getUser()->getUID();
340
+        $baseFolder = $this->rootFolder->getUserFolder($uid);
341
+        $files = $baseFolder->getById($fileId);
342
+        $params = [];
343
+
344
+        if (empty($files) && $this->appManager->isEnabledForUser('files_trashbin')) {
345
+            $baseFolder = $this->rootFolder->get($uid . '/files_trashbin/files/');
346
+            $files = $baseFolder->getById($fileId);
347
+            $params['view'] = 'trashbin';
348
+        }
349
+
350
+        if (!empty($files)) {
351
+            $file = current($files);
352
+            if ($file instanceof Folder) {
353
+                // set the full path to enter the folder
354
+                $params['dir'] = $baseFolder->getRelativePath($file->getPath());
355
+            } else {
356
+                // set parent path as dir
357
+                $params['dir'] = $baseFolder->getRelativePath($file->getParent()->getPath());
358
+                // and scroll to the entry
359
+                $params['scrollto'] = $file->getName();
360
+            }
361
+
362
+            return new RedirectResponse($this->urlGenerator->linkToRoute('files.view.index', $params));
363
+        }
364
+        throw new \OCP\Files\NotFoundException();
365
+    }
366 366
 }
Please login to merge, or discard this patch.