Passed
Push — master ( 820e13...09d56e )
by Joas
12:51 queued 14s
created
lib/base.php 2 patches
Indentation   +1015 added lines, -1015 removed lines patch added patch discarded remove patch
@@ -73,1021 +73,1021 @@
 block discarded – undo
73 73
  * OC_autoload!
74 74
  */
75 75
 class OC {
76
-	/**
77
-	 * Associative array for autoloading. classname => filename
78
-	 */
79
-	public static $CLASSPATH = [];
80
-	/**
81
-	 * The installation path for Nextcloud  on the server (e.g. /srv/http/nextcloud)
82
-	 */
83
-	public static $SERVERROOT = '';
84
-	/**
85
-	 * the current request path relative to the Nextcloud root (e.g. files/index.php)
86
-	 */
87
-	private static $SUBURI = '';
88
-	/**
89
-	 * the Nextcloud root path for http requests (e.g. nextcloud/)
90
-	 */
91
-	public static $WEBROOT = '';
92
-	/**
93
-	 * The installation path array of the apps folder on the server (e.g. /srv/http/nextcloud) 'path' and
94
-	 * web path in 'url'
95
-	 */
96
-	public static $APPSROOTS = [];
97
-
98
-	/**
99
-	 * @var string
100
-	 */
101
-	public static $configDir;
102
-
103
-	/**
104
-	 * requested app
105
-	 */
106
-	public static $REQUESTEDAPP = '';
107
-
108
-	/**
109
-	 * check if Nextcloud runs in cli mode
110
-	 */
111
-	public static $CLI = false;
112
-
113
-	/**
114
-	 * @var \OC\Autoloader $loader
115
-	 */
116
-	public static $loader = null;
117
-
118
-	/** @var \Composer\Autoload\ClassLoader $composerAutoloader */
119
-	public static $composerAutoloader = null;
120
-
121
-	/**
122
-	 * @var \OC\Server
123
-	 */
124
-	public static $server = null;
125
-
126
-	/**
127
-	 * @var \OC\Config
128
-	 */
129
-	private static $config = null;
130
-
131
-	/**
132
-	 * @throws \RuntimeException when the 3rdparty directory is missing or
133
-	 * the app path list is empty or contains an invalid path
134
-	 */
135
-	public static function initPaths() {
136
-		if(defined('PHPUNIT_CONFIG_DIR')) {
137
-			self::$configDir = OC::$SERVERROOT . '/' . PHPUNIT_CONFIG_DIR . '/';
138
-		} elseif(defined('PHPUNIT_RUN') and PHPUNIT_RUN and is_dir(OC::$SERVERROOT . '/tests/config/')) {
139
-			self::$configDir = OC::$SERVERROOT . '/tests/config/';
140
-		} elseif($dir = getenv('NEXTCLOUD_CONFIG_DIR')) {
141
-			self::$configDir = rtrim($dir, '/') . '/';
142
-		} else {
143
-			self::$configDir = OC::$SERVERROOT . '/config/';
144
-		}
145
-		self::$config = new \OC\Config(self::$configDir);
146
-
147
-		OC::$SUBURI = str_replace("\\", "/", substr(realpath($_SERVER["SCRIPT_FILENAME"]), strlen(OC::$SERVERROOT)));
148
-		/**
149
-		 * FIXME: The following lines are required because we can't yet instantiate
150
-		 *        \OC::$server->getRequest() since \OC::$server does not yet exist.
151
-		 */
152
-		$params = [
153
-			'server' => [
154
-				'SCRIPT_NAME' => $_SERVER['SCRIPT_NAME'],
155
-				'SCRIPT_FILENAME' => $_SERVER['SCRIPT_FILENAME'],
156
-			],
157
-		];
158
-		$fakeRequest = new \OC\AppFramework\Http\Request($params, null, new \OC\AllConfig(new \OC\SystemConfig(self::$config)));
159
-		$scriptName = $fakeRequest->getScriptName();
160
-		if (substr($scriptName, -1) == '/') {
161
-			$scriptName .= 'index.php';
162
-			//make sure suburi follows the same rules as scriptName
163
-			if (substr(OC::$SUBURI, -9) != 'index.php') {
164
-				if (substr(OC::$SUBURI, -1) != '/') {
165
-					OC::$SUBURI = OC::$SUBURI . '/';
166
-				}
167
-				OC::$SUBURI = OC::$SUBURI . 'index.php';
168
-			}
169
-		}
170
-
171
-
172
-		if (OC::$CLI) {
173
-			OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
174
-		} else {
175
-			if (substr($scriptName, 0 - strlen(OC::$SUBURI)) === OC::$SUBURI) {
176
-				OC::$WEBROOT = substr($scriptName, 0, 0 - strlen(OC::$SUBURI));
177
-
178
-				if (OC::$WEBROOT != '' && OC::$WEBROOT[0] !== '/') {
179
-					OC::$WEBROOT = '/' . OC::$WEBROOT;
180
-				}
181
-			} else {
182
-				// The scriptName is not ending with OC::$SUBURI
183
-				// This most likely means that we are calling from CLI.
184
-				// However some cron jobs still need to generate
185
-				// a web URL, so we use overwritewebroot as a fallback.
186
-				OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
187
-			}
188
-
189
-			// Resolve /nextcloud to /nextcloud/ to ensure to always have a trailing
190
-			// slash which is required by URL generation.
191
-			if (isset($_SERVER['REQUEST_URI']) && $_SERVER['REQUEST_URI'] === \OC::$WEBROOT &&
192
-					substr($_SERVER['REQUEST_URI'], -1) !== '/') {
193
-				header('Location: '.\OC::$WEBROOT.'/');
194
-				exit();
195
-			}
196
-		}
197
-
198
-		// search the apps folder
199
-		$config_paths = self::$config->getValue('apps_paths', []);
200
-		if (!empty($config_paths)) {
201
-			foreach ($config_paths as $paths) {
202
-				if (isset($paths['url']) && isset($paths['path'])) {
203
-					$paths['url'] = rtrim($paths['url'], '/');
204
-					$paths['path'] = rtrim($paths['path'], '/');
205
-					OC::$APPSROOTS[] = $paths;
206
-				}
207
-			}
208
-		} elseif (file_exists(OC::$SERVERROOT . '/apps')) {
209
-			OC::$APPSROOTS[] = ['path' => OC::$SERVERROOT . '/apps', 'url' => '/apps', 'writable' => true];
210
-		} elseif (file_exists(OC::$SERVERROOT . '/../apps')) {
211
-			OC::$APPSROOTS[] = [
212
-				'path' => rtrim(dirname(OC::$SERVERROOT), '/') . '/apps',
213
-				'url' => '/apps',
214
-				'writable' => true
215
-			];
216
-		}
217
-
218
-		if (empty(OC::$APPSROOTS)) {
219
-			throw new \RuntimeException('apps directory not found! Please put the Nextcloud apps folder in the Nextcloud folder'
220
-				. ' or the folder above. You can also configure the location in the config.php file.');
221
-		}
222
-		$paths = [];
223
-		foreach (OC::$APPSROOTS as $path) {
224
-			$paths[] = $path['path'];
225
-			if (!is_dir($path['path'])) {
226
-				throw new \RuntimeException(sprintf('App directory "%s" not found! Please put the Nextcloud apps folder in the'
227
-					. ' Nextcloud folder or the folder above. You can also configure the location in the'
228
-					. ' config.php file.', $path['path']));
229
-			}
230
-		}
231
-
232
-		// set the right include path
233
-		set_include_path(
234
-			implode(PATH_SEPARATOR, $paths)
235
-		);
236
-	}
237
-
238
-	public static function checkConfig() {
239
-		$l = \OC::$server->getL10N('lib');
240
-
241
-		// Create config if it does not already exist
242
-		$configFilePath = self::$configDir .'/config.php';
243
-		if(!file_exists($configFilePath)) {
244
-			@touch($configFilePath);
245
-		}
246
-
247
-		// Check if config is writable
248
-		$configFileWritable = is_writable($configFilePath);
249
-		if (!$configFileWritable && !OC_Helper::isReadOnlyConfigEnabled()
250
-			|| !$configFileWritable && \OCP\Util::needUpgrade()) {
251
-
252
-			$urlGenerator = \OC::$server->getURLGenerator();
253
-
254
-			if (self::$CLI) {
255
-				echo $l->t('Cannot write into "config" directory!')."\n";
256
-				echo $l->t('This can usually be fixed by giving the webserver write access to the config directory')."\n";
257
-				echo "\n";
258
-				echo $l->t('Or, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it.')."\n";
259
-				echo $l->t('See %s', [ $urlGenerator->linkToDocs('admin-config') ])."\n";
260
-				exit;
261
-			} else {
262
-				OC_Template::printErrorPage(
263
-					$l->t('Cannot write into "config" directory!'),
264
-					$l->t('This can usually be fixed by giving the webserver write access to the config directory.') . '. '
265
-					. $l->t('Or, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it. See %s',
266
-					[ $urlGenerator->linkToDocs('admin-config') ] ),
267
-					503
268
-				);
269
-			}
270
-		}
271
-	}
272
-
273
-	public static function checkInstalled() {
274
-		if (defined('OC_CONSOLE')) {
275
-			return;
276
-		}
277
-		// Redirect to installer if not installed
278
-		if (!\OC::$server->getSystemConfig()->getValue('installed', false) && OC::$SUBURI !== '/index.php' && OC::$SUBURI !== '/status.php') {
279
-			if (OC::$CLI) {
280
-				throw new Exception('Not installed');
281
-			} else {
282
-				$url = OC::$WEBROOT . '/index.php';
283
-				header('Location: ' . $url);
284
-			}
285
-			exit();
286
-		}
287
-	}
288
-
289
-	public static function checkMaintenanceMode() {
290
-		// Allow ajax update script to execute without being stopped
291
-		if (((bool) \OC::$server->getSystemConfig()->getValue('maintenance', false)) && OC::$SUBURI != '/core/ajax/update.php') {
292
-			// send http status 503
293
-			http_response_code(503);
294
-			header('Retry-After: 120');
295
-
296
-			// render error page
297
-			$template = new OC_Template('', 'update.user', 'guest');
298
-			OC_Util::addScript('dist/maintenance');
299
-			OC_Util::addStyle('core', 'guest');
300
-			$template->printPage();
301
-			die();
302
-		}
303
-	}
304
-
305
-	/**
306
-	 * Prints the upgrade page
307
-	 *
308
-	 * @param \OC\SystemConfig $systemConfig
309
-	 */
310
-	private static function printUpgradePage(\OC\SystemConfig $systemConfig) {
311
-		$disableWebUpdater = $systemConfig->getValue('upgrade.disable-web', false);
312
-		$tooBig = false;
313
-		if (!$disableWebUpdater) {
314
-			$apps = \OC::$server->getAppManager();
315
-			if ($apps->isInstalled('user_ldap')) {
316
-				$qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
317
-
318
-				$result = $qb->select($qb->func()->count('*', 'user_count'))
319
-					->from('ldap_user_mapping')
320
-					->execute();
321
-				$row = $result->fetch();
322
-				$result->closeCursor();
323
-
324
-				$tooBig = ($row['user_count'] > 50);
325
-			}
326
-			if (!$tooBig && $apps->isInstalled('user_saml')) {
327
-				$qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
328
-
329
-				$result = $qb->select($qb->func()->count('*', 'user_count'))
330
-					->from('user_saml_users')
331
-					->execute();
332
-				$row = $result->fetch();
333
-				$result->closeCursor();
334
-
335
-				$tooBig = ($row['user_count'] > 50);
336
-			}
337
-			if (!$tooBig) {
338
-				// count users
339
-				$stats = \OC::$server->getUserManager()->countUsers();
340
-				$totalUsers = array_sum($stats);
341
-				$tooBig = ($totalUsers > 50);
342
-			}
343
-		}
344
-		$ignoreTooBigWarning = isset($_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup']) &&
345
-			$_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup'] === 'IAmSuperSureToDoThis';
346
-
347
-		if ($disableWebUpdater || ($tooBig && !$ignoreTooBigWarning)) {
348
-			// send http status 503
349
-			http_response_code(503);
350
-			header('Retry-After: 120');
351
-
352
-			// render error page
353
-			$template = new OC_Template('', 'update.use-cli', 'guest');
354
-			$template->assign('productName', 'nextcloud'); // for now
355
-			$template->assign('version', OC_Util::getVersionString());
356
-			$template->assign('tooBig', $tooBig);
357
-
358
-			$template->printPage();
359
-			die();
360
-		}
361
-
362
-		// check whether this is a core update or apps update
363
-		$installedVersion = $systemConfig->getValue('version', '0.0.0');
364
-		$currentVersion = implode('.', \OCP\Util::getVersion());
365
-
366
-		// if not a core upgrade, then it's apps upgrade
367
-		$isAppsOnlyUpgrade = version_compare($currentVersion, $installedVersion, '=');
368
-
369
-		$oldTheme = $systemConfig->getValue('theme');
370
-		$systemConfig->setValue('theme', '');
371
-		OC_Util::addScript('config'); // needed for web root
372
-		OC_Util::addScript('update');
373
-
374
-		/** @var \OC\App\AppManager $appManager */
375
-		$appManager = \OC::$server->getAppManager();
376
-
377
-		$tmpl = new OC_Template('', 'update.admin', 'guest');
378
-		$tmpl->assign('version', OC_Util::getVersionString());
379
-		$tmpl->assign('isAppsOnlyUpgrade', $isAppsOnlyUpgrade);
380
-
381
-		// get third party apps
382
-		$ocVersion = \OCP\Util::getVersion();
383
-		$ocVersion = implode('.', $ocVersion);
384
-		$incompatibleApps = $appManager->getIncompatibleApps($ocVersion);
385
-		$incompatibleShippedApps = [];
386
-		foreach ($incompatibleApps as $appInfo) {
387
-			if ($appManager->isShipped($appInfo['id'])) {
388
-				$incompatibleShippedApps[] = $appInfo['name'] . ' (' . $appInfo['id'] . ')';
389
-			}
390
-		}
391
-
392
-		if (!empty($incompatibleShippedApps)) {
393
-			$l = \OC::$server->getL10N('core');
394
-			$hint = $l->t('The files of the app %1$s were not replaced correctly. Make sure it is a version compatible with the server.', [implode(', ', $incompatibleShippedApps)]);
395
-			throw new \OC\HintException('The files of the app ' . implode(', ', $incompatibleShippedApps) . ' were not replaced correctly. Make sure it is a version compatible with the server.', $hint);
396
-		}
397
-
398
-		$tmpl->assign('appsToUpgrade', $appManager->getAppsNeedingUpgrade($ocVersion));
399
-		$tmpl->assign('incompatibleAppsList', $incompatibleApps);
400
-		$tmpl->assign('productName', 'Nextcloud'); // for now
401
-		$tmpl->assign('oldTheme', $oldTheme);
402
-		$tmpl->printPage();
403
-	}
404
-
405
-	public static function initSession() {
406
-		if(self::$server->getRequest()->getServerProtocol() === 'https') {
407
-			ini_set('session.cookie_secure', true);
408
-		}
409
-
410
-		// prevents javascript from accessing php session cookies
411
-		ini_set('session.cookie_httponly', 'true');
412
-
413
-		// set the cookie path to the Nextcloud directory
414
-		$cookie_path = OC::$WEBROOT ? : '/';
415
-		ini_set('session.cookie_path', $cookie_path);
416
-
417
-		// Let the session name be changed in the initSession Hook
418
-		$sessionName = OC_Util::getInstanceId();
419
-
420
-		try {
421
-			// Allow session apps to create a custom session object
422
-			$useCustomSession = false;
423
-			$session = self::$server->getSession();
424
-			OC_Hook::emit('OC', 'initSession', ['session' => &$session, 'sessionName' => &$sessionName, 'useCustomSession' => &$useCustomSession]);
425
-			if (!$useCustomSession) {
426
-				// set the session name to the instance id - which is unique
427
-				$session = new \OC\Session\Internal($sessionName);
428
-			}
429
-
430
-			$cryptoWrapper = \OC::$server->getSessionCryptoWrapper();
431
-			$session = $cryptoWrapper->wrapSession($session);
432
-			self::$server->setSession($session);
433
-
434
-			// if session can't be started break with http 500 error
435
-		} catch (Exception $e) {
436
-			\OC::$server->getLogger()->logException($e, ['app' => 'base']);
437
-			//show the user a detailed error page
438
-			OC_Template::printExceptionErrorPage($e, 500);
439
-			die();
440
-		}
441
-
442
-		$sessionLifeTime = self::getSessionLifeTime();
443
-
444
-		// session timeout
445
-		if ($session->exists('LAST_ACTIVITY') && (time() - $session->get('LAST_ACTIVITY') > $sessionLifeTime)) {
446
-			if (isset($_COOKIE[session_name()])) {
447
-				setcookie(session_name(), '', -1, self::$WEBROOT ? : '/');
448
-			}
449
-			\OC::$server->getUserSession()->logout();
450
-		}
451
-
452
-		$session->set('LAST_ACTIVITY', time());
453
-	}
454
-
455
-	/**
456
-	 * @return string
457
-	 */
458
-	private static function getSessionLifeTime() {
459
-		return \OC::$server->getConfig()->getSystemValue('session_lifetime', 60 * 60 * 24);
460
-	}
461
-
462
-	/**
463
-	 * Try to set some values to the required Nextcloud default
464
-	 */
465
-	public static function setRequiredIniValues() {
466
-		@ini_set('default_charset', 'UTF-8');
467
-		@ini_set('gd.jpeg_ignore_warning', '1');
468
-	}
469
-
470
-	/**
471
-	 * Send the same site cookies
472
-	 */
473
-	private static function sendSameSiteCookies() {
474
-		$cookieParams = session_get_cookie_params();
475
-		$secureCookie = ($cookieParams['secure'] === true) ? 'secure; ' : '';
476
-		$policies = [
477
-			'lax',
478
-			'strict',
479
-		];
480
-
481
-		// Append __Host to the cookie if it meets the requirements
482
-		$cookiePrefix = '';
483
-		if($cookieParams['secure'] === true && $cookieParams['path'] === '/') {
484
-			$cookiePrefix = '__Host-';
485
-		}
486
-
487
-		foreach($policies as $policy) {
488
-			header(
489
-				sprintf(
490
-					'Set-Cookie: %snc_sameSiteCookie%s=true; path=%s; httponly;' . $secureCookie . 'expires=Fri, 31-Dec-2100 23:59:59 GMT; SameSite=%s',
491
-					$cookiePrefix,
492
-					$policy,
493
-					$cookieParams['path'],
494
-					$policy
495
-				),
496
-				false
497
-			);
498
-		}
499
-	}
500
-
501
-	/**
502
-	 * Same Site cookie to further mitigate CSRF attacks. This cookie has to
503
-	 * be set in every request if cookies are sent to add a second level of
504
-	 * defense against CSRF.
505
-	 *
506
-	 * If the cookie is not sent this will set the cookie and reload the page.
507
-	 * We use an additional cookie since we want to protect logout CSRF and
508
-	 * also we can't directly interfere with PHP's session mechanism.
509
-	 */
510
-	private static function performSameSiteCookieProtection() {
511
-		$request = \OC::$server->getRequest();
512
-
513
-		// Some user agents are notorious and don't really properly follow HTTP
514
-		// specifications. For those, have an automated opt-out. Since the protection
515
-		// for remote.php is applied in base.php as starting point we need to opt out
516
-		// here.
517
-		$incompatibleUserAgents = \OC::$server->getConfig()->getSystemValue('csrf.optout');
518
-
519
-		// Fallback, if csrf.optout is unset
520
-		if (!is_array($incompatibleUserAgents)) {
521
-			$incompatibleUserAgents = [
522
-				// OS X Finder
523
-				'/^WebDAVFS/',
524
-				// Windows webdav drive
525
-				'/^Microsoft-WebDAV-MiniRedir/',
526
-			];
527
-		}
528
-
529
-		if($request->isUserAgent($incompatibleUserAgents)) {
530
-			return;
531
-		}
532
-
533
-		if(count($_COOKIE) > 0) {
534
-			$requestUri = $request->getScriptName();
535
-			$processingScript = explode('/', $requestUri);
536
-			$processingScript = $processingScript[count($processingScript)-1];
537
-
538
-			// index.php routes are handled in the middleware
539
-			if($processingScript === 'index.php') {
540
-				return;
541
-			}
542
-
543
-			// All other endpoints require the lax and the strict cookie
544
-			if(!$request->passesStrictCookieCheck()) {
545
-				self::sendSameSiteCookies();
546
-				// Debug mode gets access to the resources without strict cookie
547
-				// due to the fact that the SabreDAV browser also lives there.
548
-				if(!\OC::$server->getConfig()->getSystemValue('debug', false)) {
549
-					http_response_code(\OCP\AppFramework\Http::STATUS_SERVICE_UNAVAILABLE);
550
-					exit();
551
-				}
552
-			}
553
-		} elseif(!isset($_COOKIE['nc_sameSiteCookielax']) || !isset($_COOKIE['nc_sameSiteCookiestrict'])) {
554
-			self::sendSameSiteCookies();
555
-		}
556
-	}
557
-
558
-	public static function init() {
559
-		// calculate the root directories
560
-		OC::$SERVERROOT = str_replace("\\", '/', substr(__DIR__, 0, -4));
561
-
562
-		// register autoloader
563
-		$loaderStart = microtime(true);
564
-		require_once __DIR__ . '/autoloader.php';
565
-		self::$loader = new \OC\Autoloader([
566
-			OC::$SERVERROOT . '/lib/private/legacy',
567
-		]);
568
-		if (defined('PHPUNIT_RUN')) {
569
-			self::$loader->addValidRoot(OC::$SERVERROOT . '/tests');
570
-		}
571
-		spl_autoload_register([self::$loader, 'load']);
572
-		$loaderEnd = microtime(true);
573
-
574
-		self::$CLI = (php_sapi_name() == 'cli');
575
-
576
-		// Add default composer PSR-4 autoloader
577
-		self::$composerAutoloader = require_once OC::$SERVERROOT . '/lib/composer/autoload.php';
578
-
579
-		try {
580
-			self::initPaths();
581
-			// setup 3rdparty autoloader
582
-			$vendorAutoLoad = OC::$SERVERROOT. '/3rdparty/autoload.php';
583
-			if (!file_exists($vendorAutoLoad)) {
584
-				throw new \RuntimeException('Composer autoloader not found, unable to continue. Check the folder "3rdparty". Running "git submodule update --init" will initialize the git submodule that handles the subfolder "3rdparty".');
585
-			}
586
-			require_once $vendorAutoLoad;
587
-
588
-		} catch (\RuntimeException $e) {
589
-			if (!self::$CLI) {
590
-				http_response_code(503);
591
-			}
592
-			// we can't use the template error page here, because this needs the
593
-			// DI container which isn't available yet
594
-			print($e->getMessage());
595
-			exit();
596
-		}
597
-
598
-		// setup the basic server
599
-		self::$server = new \OC\Server(\OC::$WEBROOT, self::$config);
600
-		\OC::$server->getEventLogger()->log('autoloader', 'Autoloader', $loaderStart, $loaderEnd);
601
-		\OC::$server->getEventLogger()->start('boot', 'Initialize');
602
-
603
-		// Override php.ini and log everything if we're troubleshooting
604
-		if (self::$config->getValue('loglevel') === ILogger::DEBUG) {
605
-			error_reporting(E_ALL);
606
-		}
607
-
608
-		// Don't display errors and log them
609
-		@ini_set('display_errors', '0');
610
-		@ini_set('log_errors', '1');
611
-
612
-		if(!date_default_timezone_set('UTC')) {
613
-			throw new \RuntimeException('Could not set timezone to UTC');
614
-		}
615
-
616
-		//try to configure php to enable big file uploads.
617
-		//this doesn´t work always depending on the webserver and php configuration.
618
-		//Let´s try to overwrite some defaults anyway
619
-
620
-		//try to set the maximum execution time to 60min
621
-		if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
622
-			@set_time_limit(3600);
623
-		}
624
-		@ini_set('max_execution_time', '3600');
625
-		@ini_set('max_input_time', '3600');
626
-
627
-		//try to set the maximum filesize to 10G
628
-		@ini_set('upload_max_filesize', '10G');
629
-		@ini_set('post_max_size', '10G');
630
-		@ini_set('file_uploads', '50');
631
-
632
-		self::setRequiredIniValues();
633
-		self::handleAuthHeaders();
634
-		self::registerAutoloaderCache();
635
-
636
-		// initialize intl fallback is necessary
637
-		\Patchwork\Utf8\Bootup::initIntl();
638
-		OC_Util::isSetLocaleWorking();
639
-
640
-		if (!defined('PHPUNIT_RUN')) {
641
-			OC\Log\ErrorHandler::setLogger(\OC::$server->getLogger());
642
-			$debug = \OC::$server->getConfig()->getSystemValue('debug', false);
643
-			OC\Log\ErrorHandler::register($debug);
644
-		}
645
-
646
-		\OC::$server->getEventLogger()->start('init_session', 'Initialize session');
647
-		OC_App::loadApps(['session']);
648
-		if (!self::$CLI) {
649
-			self::initSession();
650
-		}
651
-		\OC::$server->getEventLogger()->end('init_session');
652
-		self::checkConfig();
653
-		self::checkInstalled();
654
-
655
-		OC_Response::addSecurityHeaders();
656
-
657
-		self::performSameSiteCookieProtection();
658
-
659
-		if (!defined('OC_CONSOLE')) {
660
-			$errors = OC_Util::checkServer(\OC::$server->getSystemConfig());
661
-			if (count($errors) > 0) {
662
-				if (!self::$CLI) {
663
-					http_response_code(503);
664
-					OC_Util::addStyle('guest');
665
-					try {
666
-						OC_Template::printGuestPage('', 'error', ['errors' => $errors]);
667
-						exit;
668
-					} catch (\Exception $e) {
669
-						// In case any error happens when showing the error page, we simply fall back to posting the text.
670
-						// This might be the case when e.g. the data directory is broken and we can not load/write SCSS to/from it.
671
-					}
672
-				}
673
-
674
-				// Convert l10n string into regular string for usage in database
675
-				$staticErrors = [];
676
-				foreach ($errors as $error) {
677
-					echo $error['error'] . "\n";
678
-					echo $error['hint'] . "\n\n";
679
-					$staticErrors[] = [
680
-						'error' => (string)$error['error'],
681
-						'hint' => (string)$error['hint'],
682
-					];
683
-				}
684
-
685
-				try {
686
-					\OC::$server->getConfig()->setAppValue('core', 'cronErrors', json_encode($staticErrors));
687
-				} catch (\Exception $e) {
688
-					echo('Writing to database failed');
689
-				}
690
-				exit(1);
691
-			} elseif (self::$CLI && \OC::$server->getConfig()->getSystemValue('installed', false)) {
692
-				\OC::$server->getConfig()->deleteAppValue('core', 'cronErrors');
693
-			}
694
-		}
695
-		//try to set the session lifetime
696
-		$sessionLifeTime = self::getSessionLifeTime();
697
-		@ini_set('gc_maxlifetime', (string)$sessionLifeTime);
698
-
699
-		$systemConfig = \OC::$server->getSystemConfig();
700
-
701
-		// User and Groups
702
-		if (!$systemConfig->getValue("installed", false)) {
703
-			self::$server->getSession()->set('user_id', '');
704
-		}
705
-
706
-		OC_User::useBackend(new \OC\User\Database());
707
-		\OC::$server->getGroupManager()->addBackend(new \OC\Group\Database());
708
-
709
-		// Subscribe to the hook
710
-		\OCP\Util::connectHook(
711
-			'\OCA\Files_Sharing\API\Server2Server',
712
-			'preLoginNameUsedAsUserName',
713
-			'\OC\User\Database',
714
-			'preLoginNameUsedAsUserName'
715
-		);
716
-
717
-		//setup extra user backends
718
-		if (!\OCP\Util::needUpgrade()) {
719
-			OC_User::setupBackends();
720
-		} else {
721
-			// Run upgrades in incognito mode
722
-			OC_User::setIncognitoMode(true);
723
-		}
724
-
725
-		self::registerCleanupHooks();
726
-		self::registerFilesystemHooks();
727
-		self::registerShareHooks();
728
-		self::registerEncryptionWrapper();
729
-		self::registerEncryptionHooks();
730
-		self::registerAccountHooks();
731
-		self::registerResourceCollectionHooks();
732
-		self::registerAppRestrictionsHooks();
733
-
734
-		// Make sure that the application class is not loaded before the database is setup
735
-		if ($systemConfig->getValue("installed", false)) {
736
-			OC_App::loadApp('settings');
737
-			$settings = \OC::$server->query(\OCA\Settings\AppInfo\Application::class);
738
-			$settings->register();
739
-		}
740
-
741
-		//make sure temporary files are cleaned up
742
-		$tmpManager = \OC::$server->getTempManager();
743
-		register_shutdown_function([$tmpManager, 'clean']);
744
-		$lockProvider = \OC::$server->getLockingProvider();
745
-		register_shutdown_function([$lockProvider, 'releaseAll']);
746
-
747
-		// Check whether the sample configuration has been copied
748
-		if($systemConfig->getValue('copied_sample_config', false)) {
749
-			$l = \OC::$server->getL10N('lib');
750
-			OC_Template::printErrorPage(
751
-				$l->t('Sample configuration detected'),
752
-				$l->t('It has been detected that the sample configuration has been copied. This can break your installation and is unsupported. Please read the documentation before performing changes on config.php'),
753
-				503
754
-			);
755
-			return;
756
-		}
757
-
758
-		$request = \OC::$server->getRequest();
759
-		$host = $request->getInsecureServerHost();
760
-		/**
761
-		 * if the host passed in headers isn't trusted
762
-		 * FIXME: Should not be in here at all :see_no_evil:
763
-		 */
764
-		if (!OC::$CLI
765
-			&& !\OC::$server->getTrustedDomainHelper()->isTrustedDomain($host)
766
-			&& self::$server->getConfig()->getSystemValue('installed', false)
767
-		) {
768
-			// Allow access to CSS resources
769
-			$isScssRequest = false;
770
-			if(strpos($request->getPathInfo(), '/css/') === 0) {
771
-				$isScssRequest = true;
772
-			}
773
-
774
-			if(substr($request->getRequestUri(), -11) === '/status.php') {
775
-				http_response_code(400);
776
-				header('Content-Type: application/json');
777
-				echo '{"error": "Trusted domain error.", "code": 15}';
778
-				exit();
779
-			}
780
-
781
-			if (!$isScssRequest) {
782
-				http_response_code(400);
783
-
784
-				\OC::$server->getLogger()->info(
785
-					'Trusted domain error. "{remoteAddress}" tried to access using "{host}" as host.',
786
-					[
787
-						'app' => 'core',
788
-						'remoteAddress' => $request->getRemoteAddress(),
789
-						'host' => $host,
790
-					]
791
-				);
792
-
793
-				$tmpl = new OCP\Template('core', 'untrustedDomain', 'guest');
794
-				$tmpl->assign('docUrl', \OC::$server->getURLGenerator()->linkToDocs('admin-trusted-domains'));
795
-				$tmpl->printPage();
796
-
797
-				exit();
798
-			}
799
-		}
800
-		\OC::$server->getEventLogger()->end('boot');
801
-	}
802
-
803
-	/**
804
-	 * register hooks for the cleanup of cache and bruteforce protection
805
-	 */
806
-	public static function registerCleanupHooks() {
807
-		//don't try to do this before we are properly setup
808
-		if (\OC::$server->getSystemConfig()->getValue('installed', false) && !\OCP\Util::needUpgrade()) {
809
-
810
-			// NOTE: This will be replaced to use OCP
811
-			$userSession = self::$server->getUserSession();
812
-			$userSession->listen('\OC\User', 'postLogin', function () use ($userSession) {
813
-				if (!defined('PHPUNIT_RUN')) {
814
-					// reset brute force delay for this IP address and username
815
-					$uid = \OC::$server->getUserSession()->getUser()->getUID();
816
-					$request = \OC::$server->getRequest();
817
-					$throttler = \OC::$server->getBruteForceThrottler();
818
-					$throttler->resetDelay($request->getRemoteAddress(), 'login', ['user' => $uid]);
819
-				}
820
-
821
-				try {
822
-					$cache = new \OC\Cache\File();
823
-					$cache->gc();
824
-				} catch (\OC\ServerNotAvailableException $e) {
825
-					// not a GC exception, pass it on
826
-					throw $e;
827
-				} catch (\OC\ForbiddenException $e) {
828
-					// filesystem blocked for this request, ignore
829
-				} catch (\Exception $e) {
830
-					// a GC exception should not prevent users from using OC,
831
-					// so log the exception
832
-					\OC::$server->getLogger()->logException($e, [
833
-						'message' => 'Exception when running cache gc.',
834
-						'level' => ILogger::WARN,
835
-						'app' => 'core',
836
-					]);
837
-				}
838
-			});
839
-		}
840
-	}
841
-
842
-	private static function registerEncryptionWrapper() {
843
-		$manager = self::$server->getEncryptionManager();
844
-		\OCP\Util::connectHook('OC_Filesystem', 'preSetup', $manager, 'setupStorage');
845
-	}
846
-
847
-	private static function registerEncryptionHooks() {
848
-		$enabled = self::$server->getEncryptionManager()->isEnabled();
849
-		if ($enabled) {
850
-			\OCP\Util::connectHook(Share::class, 'post_shared', HookManager::class, 'postShared');
851
-			\OCP\Util::connectHook(Share::class, 'post_unshare', HookManager::class, 'postUnshared');
852
-			\OCP\Util::connectHook('OC_Filesystem', 'post_rename', HookManager::class, 'postRename');
853
-			\OCP\Util::connectHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', HookManager::class, 'postRestore');
854
-		}
855
-	}
856
-
857
-	private static function registerAccountHooks() {
858
-		$hookHandler = new \OC\Accounts\Hooks(\OC::$server->getLogger());
859
-		\OCP\Util::connectHook('OC_User', 'changeUser', $hookHandler, 'changeUserHook');
860
-	}
861
-
862
-	private static function registerAppRestrictionsHooks() {
863
-		$groupManager = self::$server->query(\OCP\IGroupManager::class);
864
-		$groupManager->listen ('\OC\Group', 'postDelete', function (\OCP\IGroup $group) {
865
-			$appManager = self::$server->getAppManager();
866
-			$apps = $appManager->getEnabledAppsForGroup($group);
867
-			foreach ($apps as $appId) {
868
-				$restrictions = $appManager->getAppRestriction($appId);
869
-				if (empty($restrictions)) {
870
-					continue;
871
-				}
872
-				$key = array_search($group->getGID(), $restrictions);
873
-				unset($restrictions[$key]);
874
-				$restrictions = array_values($restrictions);
875
-				if (empty($restrictions)) {
876
-					$appManager->disableApp($appId);
877
-				}
878
-				else{
879
-					$appManager->enableAppForGroups($appId, $restrictions);
880
-				}
881
-
882
-			}
883
-		});
884
-	}
885
-
886
-	private static function registerResourceCollectionHooks() {
887
-		\OC\Collaboration\Resources\Listener::register(\OC::$server->getEventDispatcher());
888
-	}
889
-
890
-	/**
891
-	 * register hooks for the filesystem
892
-	 */
893
-	public static function registerFilesystemHooks() {
894
-		// Check for blacklisted files
895
-		OC_Hook::connect('OC_Filesystem', 'write', Filesystem::class, 'isBlacklisted');
896
-		OC_Hook::connect('OC_Filesystem', 'rename', Filesystem::class, 'isBlacklisted');
897
-	}
898
-
899
-	/**
900
-	 * register hooks for sharing
901
-	 */
902
-	public static function registerShareHooks() {
903
-		if (\OC::$server->getSystemConfig()->getValue('installed')) {
904
-			OC_Hook::connect('OC_User', 'post_deleteUser', Hooks::class, 'post_deleteUser');
905
-			OC_Hook::connect('OC_User', 'post_removeFromGroup', Hooks::class, 'post_removeFromGroup');
906
-			OC_Hook::connect('OC_User', 'post_deleteGroup', Hooks::class, 'post_deleteGroup');
907
-		}
908
-	}
909
-
910
-	protected static function registerAutoloaderCache() {
911
-		// The class loader takes an optional low-latency cache, which MUST be
912
-		// namespaced. The instanceid is used for namespacing, but might be
913
-		// unavailable at this point. Furthermore, it might not be possible to
914
-		// generate an instanceid via \OC_Util::getInstanceId() because the
915
-		// config file may not be writable. As such, we only register a class
916
-		// loader cache if instanceid is available without trying to create one.
917
-		$instanceId = \OC::$server->getSystemConfig()->getValue('instanceid', null);
918
-		if ($instanceId) {
919
-			try {
920
-				$memcacheFactory = \OC::$server->getMemCacheFactory();
921
-				self::$loader->setMemoryCache($memcacheFactory->createLocal('Autoloader'));
922
-			} catch (\Exception $ex) {
923
-			}
924
-		}
925
-	}
926
-
927
-	/**
928
-	 * Handle the request
929
-	 */
930
-	public static function handleRequest() {
931
-
932
-		\OC::$server->getEventLogger()->start('handle_request', 'Handle request');
933
-		$systemConfig = \OC::$server->getSystemConfig();
934
-
935
-		// Check if Nextcloud is installed or in maintenance (update) mode
936
-		if (!$systemConfig->getValue('installed', false)) {
937
-			\OC::$server->getSession()->clear();
938
-			$setupHelper = new OC\Setup(
939
-				$systemConfig,
940
-				\OC::$server->getIniWrapper(),
941
-				\OC::$server->getL10N('lib'),
942
-				\OC::$server->query(\OCP\Defaults::class),
943
-				\OC::$server->getLogger(),
944
-				\OC::$server->getSecureRandom(),
945
-				\OC::$server->query(\OC\Installer::class)
946
-			);
947
-			$controller = new OC\Core\Controller\SetupController($setupHelper);
948
-			$controller->run($_POST);
949
-			exit();
950
-		}
951
-
952
-		$request = \OC::$server->getRequest();
953
-		$requestPath = $request->getRawPathInfo();
954
-		if ($requestPath === '/heartbeat') {
955
-			return;
956
-		}
957
-		if (substr($requestPath, -3) !== '.js') { // we need these files during the upgrade
958
-			self::checkMaintenanceMode();
959
-
960
-			if (\OCP\Util::needUpgrade()) {
961
-				if (function_exists('opcache_reset')) {
962
-					opcache_reset();
963
-				}
964
-				if (!((bool) $systemConfig->getValue('maintenance', false))) {
965
-					self::printUpgradePage($systemConfig);
966
-					exit();
967
-				}
968
-			}
969
-		}
970
-
971
-		// emergency app disabling
972
-		if ($requestPath === '/disableapp'
973
-			&& $request->getMethod() === 'POST'
974
-			&& ((array)$request->getParam('appid')) !== ''
975
-		) {
976
-			\OC_JSON::callCheck();
977
-			\OC_JSON::checkAdminUser();
978
-			$appIds = (array)$request->getParam('appid');
979
-			foreach($appIds as $appId) {
980
-				$appId = \OC_App::cleanAppId($appId);
981
-				\OC::$server->getAppManager()->disableApp($appId);
982
-			}
983
-			\OC_JSON::success();
984
-			exit();
985
-		}
986
-
987
-		// Always load authentication apps
988
-		OC_App::loadApps(['authentication']);
989
-
990
-		// Load minimum set of apps
991
-		if (!\OCP\Util::needUpgrade()
992
-			&& !((bool) $systemConfig->getValue('maintenance', false))) {
993
-			// For logged-in users: Load everything
994
-			if(\OC::$server->getUserSession()->isLoggedIn()) {
995
-				OC_App::loadApps();
996
-			} else {
997
-				// For guests: Load only filesystem and logging
998
-				OC_App::loadApps(['filesystem', 'logging']);
999
-				self::handleLogin($request);
1000
-			}
1001
-		}
1002
-
1003
-		if (!self::$CLI) {
1004
-			try {
1005
-				if (!((bool) $systemConfig->getValue('maintenance', false)) && !\OCP\Util::needUpgrade()) {
1006
-					OC_App::loadApps(['filesystem', 'logging']);
1007
-					OC_App::loadApps();
1008
-				}
1009
-				OC_Util::setupFS();
1010
-				OC::$server->getRouter()->match(\OC::$server->getRequest()->getRawPathInfo());
1011
-				return;
1012
-			} catch (Symfony\Component\Routing\Exception\ResourceNotFoundException $e) {
1013
-				//header('HTTP/1.0 404 Not Found');
1014
-			} catch (Symfony\Component\Routing\Exception\MethodNotAllowedException $e) {
1015
-				http_response_code(405);
1016
-				return;
1017
-			}
1018
-		}
1019
-
1020
-		// Handle WebDAV
1021
-		if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'PROPFIND') {
1022
-			// not allowed any more to prevent people
1023
-			// mounting this root directly.
1024
-			// Users need to mount remote.php/webdav instead.
1025
-			http_response_code(405);
1026
-			return;
1027
-		}
1028
-
1029
-		// Someone is logged in
1030
-		if (\OC::$server->getUserSession()->isLoggedIn()) {
1031
-			OC_App::loadApps();
1032
-			OC_User::setupBackends();
1033
-			OC_Util::setupFS();
1034
-			// FIXME
1035
-			// Redirect to default application
1036
-			OC_Util::redirectToDefaultPage();
1037
-		} else {
1038
-			// Not handled and not logged in
1039
-			header('Location: '.\OC::$server->getURLGenerator()->linkToRouteAbsolute('core.login.showLoginForm'));
1040
-		}
1041
-	}
1042
-
1043
-	/**
1044
-	 * Check login: apache auth, auth token, basic auth
1045
-	 *
1046
-	 * @param OCP\IRequest $request
1047
-	 * @return boolean
1048
-	 */
1049
-	static function handleLogin(OCP\IRequest $request) {
1050
-		$userSession = self::$server->getUserSession();
1051
-		if (OC_User::handleApacheAuth()) {
1052
-			return true;
1053
-		}
1054
-		if ($userSession->tryTokenLogin($request)) {
1055
-			return true;
1056
-		}
1057
-		if (isset($_COOKIE['nc_username'])
1058
-			&& isset($_COOKIE['nc_token'])
1059
-			&& isset($_COOKIE['nc_session_id'])
1060
-			&& $userSession->loginWithCookie($_COOKIE['nc_username'], $_COOKIE['nc_token'], $_COOKIE['nc_session_id'])) {
1061
-			return true;
1062
-		}
1063
-		if ($userSession->tryBasicAuthLogin($request, \OC::$server->getBruteForceThrottler())) {
1064
-			return true;
1065
-		}
1066
-		return false;
1067
-	}
1068
-
1069
-	protected static function handleAuthHeaders() {
1070
-		//copy http auth headers for apache+php-fcgid work around
1071
-		if (isset($_SERVER['HTTP_XAUTHORIZATION']) && !isset($_SERVER['HTTP_AUTHORIZATION'])) {
1072
-			$_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['HTTP_XAUTHORIZATION'];
1073
-		}
1074
-
1075
-		// Extract PHP_AUTH_USER/PHP_AUTH_PW from other headers if necessary.
1076
-		$vars = [
1077
-			'HTTP_AUTHORIZATION', // apache+php-cgi work around
1078
-			'REDIRECT_HTTP_AUTHORIZATION', // apache+php-cgi alternative
1079
-		];
1080
-		foreach ($vars as $var) {
1081
-			if (isset($_SERVER[$var]) && preg_match('/Basic\s+(.*)$/i', $_SERVER[$var], $matches)) {
1082
-				$credentials = explode(':', base64_decode($matches[1]), 2);
1083
-				if (count($credentials) === 2) {
1084
-					$_SERVER['PHP_AUTH_USER'] = $credentials[0];
1085
-					$_SERVER['PHP_AUTH_PW'] = $credentials[1];
1086
-					break;
1087
-				}
1088
-			}
1089
-		}
1090
-	}
76
+    /**
77
+     * Associative array for autoloading. classname => filename
78
+     */
79
+    public static $CLASSPATH = [];
80
+    /**
81
+     * The installation path for Nextcloud  on the server (e.g. /srv/http/nextcloud)
82
+     */
83
+    public static $SERVERROOT = '';
84
+    /**
85
+     * the current request path relative to the Nextcloud root (e.g. files/index.php)
86
+     */
87
+    private static $SUBURI = '';
88
+    /**
89
+     * the Nextcloud root path for http requests (e.g. nextcloud/)
90
+     */
91
+    public static $WEBROOT = '';
92
+    /**
93
+     * The installation path array of the apps folder on the server (e.g. /srv/http/nextcloud) 'path' and
94
+     * web path in 'url'
95
+     */
96
+    public static $APPSROOTS = [];
97
+
98
+    /**
99
+     * @var string
100
+     */
101
+    public static $configDir;
102
+
103
+    /**
104
+     * requested app
105
+     */
106
+    public static $REQUESTEDAPP = '';
107
+
108
+    /**
109
+     * check if Nextcloud runs in cli mode
110
+     */
111
+    public static $CLI = false;
112
+
113
+    /**
114
+     * @var \OC\Autoloader $loader
115
+     */
116
+    public static $loader = null;
117
+
118
+    /** @var \Composer\Autoload\ClassLoader $composerAutoloader */
119
+    public static $composerAutoloader = null;
120
+
121
+    /**
122
+     * @var \OC\Server
123
+     */
124
+    public static $server = null;
125
+
126
+    /**
127
+     * @var \OC\Config
128
+     */
129
+    private static $config = null;
130
+
131
+    /**
132
+     * @throws \RuntimeException when the 3rdparty directory is missing or
133
+     * the app path list is empty or contains an invalid path
134
+     */
135
+    public static function initPaths() {
136
+        if(defined('PHPUNIT_CONFIG_DIR')) {
137
+            self::$configDir = OC::$SERVERROOT . '/' . PHPUNIT_CONFIG_DIR . '/';
138
+        } elseif(defined('PHPUNIT_RUN') and PHPUNIT_RUN and is_dir(OC::$SERVERROOT . '/tests/config/')) {
139
+            self::$configDir = OC::$SERVERROOT . '/tests/config/';
140
+        } elseif($dir = getenv('NEXTCLOUD_CONFIG_DIR')) {
141
+            self::$configDir = rtrim($dir, '/') . '/';
142
+        } else {
143
+            self::$configDir = OC::$SERVERROOT . '/config/';
144
+        }
145
+        self::$config = new \OC\Config(self::$configDir);
146
+
147
+        OC::$SUBURI = str_replace("\\", "/", substr(realpath($_SERVER["SCRIPT_FILENAME"]), strlen(OC::$SERVERROOT)));
148
+        /**
149
+         * FIXME: The following lines are required because we can't yet instantiate
150
+         *        \OC::$server->getRequest() since \OC::$server does not yet exist.
151
+         */
152
+        $params = [
153
+            'server' => [
154
+                'SCRIPT_NAME' => $_SERVER['SCRIPT_NAME'],
155
+                'SCRIPT_FILENAME' => $_SERVER['SCRIPT_FILENAME'],
156
+            ],
157
+        ];
158
+        $fakeRequest = new \OC\AppFramework\Http\Request($params, null, new \OC\AllConfig(new \OC\SystemConfig(self::$config)));
159
+        $scriptName = $fakeRequest->getScriptName();
160
+        if (substr($scriptName, -1) == '/') {
161
+            $scriptName .= 'index.php';
162
+            //make sure suburi follows the same rules as scriptName
163
+            if (substr(OC::$SUBURI, -9) != 'index.php') {
164
+                if (substr(OC::$SUBURI, -1) != '/') {
165
+                    OC::$SUBURI = OC::$SUBURI . '/';
166
+                }
167
+                OC::$SUBURI = OC::$SUBURI . 'index.php';
168
+            }
169
+        }
170
+
171
+
172
+        if (OC::$CLI) {
173
+            OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
174
+        } else {
175
+            if (substr($scriptName, 0 - strlen(OC::$SUBURI)) === OC::$SUBURI) {
176
+                OC::$WEBROOT = substr($scriptName, 0, 0 - strlen(OC::$SUBURI));
177
+
178
+                if (OC::$WEBROOT != '' && OC::$WEBROOT[0] !== '/') {
179
+                    OC::$WEBROOT = '/' . OC::$WEBROOT;
180
+                }
181
+            } else {
182
+                // The scriptName is not ending with OC::$SUBURI
183
+                // This most likely means that we are calling from CLI.
184
+                // However some cron jobs still need to generate
185
+                // a web URL, so we use overwritewebroot as a fallback.
186
+                OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
187
+            }
188
+
189
+            // Resolve /nextcloud to /nextcloud/ to ensure to always have a trailing
190
+            // slash which is required by URL generation.
191
+            if (isset($_SERVER['REQUEST_URI']) && $_SERVER['REQUEST_URI'] === \OC::$WEBROOT &&
192
+                    substr($_SERVER['REQUEST_URI'], -1) !== '/') {
193
+                header('Location: '.\OC::$WEBROOT.'/');
194
+                exit();
195
+            }
196
+        }
197
+
198
+        // search the apps folder
199
+        $config_paths = self::$config->getValue('apps_paths', []);
200
+        if (!empty($config_paths)) {
201
+            foreach ($config_paths as $paths) {
202
+                if (isset($paths['url']) && isset($paths['path'])) {
203
+                    $paths['url'] = rtrim($paths['url'], '/');
204
+                    $paths['path'] = rtrim($paths['path'], '/');
205
+                    OC::$APPSROOTS[] = $paths;
206
+                }
207
+            }
208
+        } elseif (file_exists(OC::$SERVERROOT . '/apps')) {
209
+            OC::$APPSROOTS[] = ['path' => OC::$SERVERROOT . '/apps', 'url' => '/apps', 'writable' => true];
210
+        } elseif (file_exists(OC::$SERVERROOT . '/../apps')) {
211
+            OC::$APPSROOTS[] = [
212
+                'path' => rtrim(dirname(OC::$SERVERROOT), '/') . '/apps',
213
+                'url' => '/apps',
214
+                'writable' => true
215
+            ];
216
+        }
217
+
218
+        if (empty(OC::$APPSROOTS)) {
219
+            throw new \RuntimeException('apps directory not found! Please put the Nextcloud apps folder in the Nextcloud folder'
220
+                . ' or the folder above. You can also configure the location in the config.php file.');
221
+        }
222
+        $paths = [];
223
+        foreach (OC::$APPSROOTS as $path) {
224
+            $paths[] = $path['path'];
225
+            if (!is_dir($path['path'])) {
226
+                throw new \RuntimeException(sprintf('App directory "%s" not found! Please put the Nextcloud apps folder in the'
227
+                    . ' Nextcloud folder or the folder above. You can also configure the location in the'
228
+                    . ' config.php file.', $path['path']));
229
+            }
230
+        }
231
+
232
+        // set the right include path
233
+        set_include_path(
234
+            implode(PATH_SEPARATOR, $paths)
235
+        );
236
+    }
237
+
238
+    public static function checkConfig() {
239
+        $l = \OC::$server->getL10N('lib');
240
+
241
+        // Create config if it does not already exist
242
+        $configFilePath = self::$configDir .'/config.php';
243
+        if(!file_exists($configFilePath)) {
244
+            @touch($configFilePath);
245
+        }
246
+
247
+        // Check if config is writable
248
+        $configFileWritable = is_writable($configFilePath);
249
+        if (!$configFileWritable && !OC_Helper::isReadOnlyConfigEnabled()
250
+            || !$configFileWritable && \OCP\Util::needUpgrade()) {
251
+
252
+            $urlGenerator = \OC::$server->getURLGenerator();
253
+
254
+            if (self::$CLI) {
255
+                echo $l->t('Cannot write into "config" directory!')."\n";
256
+                echo $l->t('This can usually be fixed by giving the webserver write access to the config directory')."\n";
257
+                echo "\n";
258
+                echo $l->t('Or, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it.')."\n";
259
+                echo $l->t('See %s', [ $urlGenerator->linkToDocs('admin-config') ])."\n";
260
+                exit;
261
+            } else {
262
+                OC_Template::printErrorPage(
263
+                    $l->t('Cannot write into "config" directory!'),
264
+                    $l->t('This can usually be fixed by giving the webserver write access to the config directory.') . '. '
265
+                    . $l->t('Or, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it. See %s',
266
+                    [ $urlGenerator->linkToDocs('admin-config') ] ),
267
+                    503
268
+                );
269
+            }
270
+        }
271
+    }
272
+
273
+    public static function checkInstalled() {
274
+        if (defined('OC_CONSOLE')) {
275
+            return;
276
+        }
277
+        // Redirect to installer if not installed
278
+        if (!\OC::$server->getSystemConfig()->getValue('installed', false) && OC::$SUBURI !== '/index.php' && OC::$SUBURI !== '/status.php') {
279
+            if (OC::$CLI) {
280
+                throw new Exception('Not installed');
281
+            } else {
282
+                $url = OC::$WEBROOT . '/index.php';
283
+                header('Location: ' . $url);
284
+            }
285
+            exit();
286
+        }
287
+    }
288
+
289
+    public static function checkMaintenanceMode() {
290
+        // Allow ajax update script to execute without being stopped
291
+        if (((bool) \OC::$server->getSystemConfig()->getValue('maintenance', false)) && OC::$SUBURI != '/core/ajax/update.php') {
292
+            // send http status 503
293
+            http_response_code(503);
294
+            header('Retry-After: 120');
295
+
296
+            // render error page
297
+            $template = new OC_Template('', 'update.user', 'guest');
298
+            OC_Util::addScript('dist/maintenance');
299
+            OC_Util::addStyle('core', 'guest');
300
+            $template->printPage();
301
+            die();
302
+        }
303
+    }
304
+
305
+    /**
306
+     * Prints the upgrade page
307
+     *
308
+     * @param \OC\SystemConfig $systemConfig
309
+     */
310
+    private static function printUpgradePage(\OC\SystemConfig $systemConfig) {
311
+        $disableWebUpdater = $systemConfig->getValue('upgrade.disable-web', false);
312
+        $tooBig = false;
313
+        if (!$disableWebUpdater) {
314
+            $apps = \OC::$server->getAppManager();
315
+            if ($apps->isInstalled('user_ldap')) {
316
+                $qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
317
+
318
+                $result = $qb->select($qb->func()->count('*', 'user_count'))
319
+                    ->from('ldap_user_mapping')
320
+                    ->execute();
321
+                $row = $result->fetch();
322
+                $result->closeCursor();
323
+
324
+                $tooBig = ($row['user_count'] > 50);
325
+            }
326
+            if (!$tooBig && $apps->isInstalled('user_saml')) {
327
+                $qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
328
+
329
+                $result = $qb->select($qb->func()->count('*', 'user_count'))
330
+                    ->from('user_saml_users')
331
+                    ->execute();
332
+                $row = $result->fetch();
333
+                $result->closeCursor();
334
+
335
+                $tooBig = ($row['user_count'] > 50);
336
+            }
337
+            if (!$tooBig) {
338
+                // count users
339
+                $stats = \OC::$server->getUserManager()->countUsers();
340
+                $totalUsers = array_sum($stats);
341
+                $tooBig = ($totalUsers > 50);
342
+            }
343
+        }
344
+        $ignoreTooBigWarning = isset($_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup']) &&
345
+            $_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup'] === 'IAmSuperSureToDoThis';
346
+
347
+        if ($disableWebUpdater || ($tooBig && !$ignoreTooBigWarning)) {
348
+            // send http status 503
349
+            http_response_code(503);
350
+            header('Retry-After: 120');
351
+
352
+            // render error page
353
+            $template = new OC_Template('', 'update.use-cli', 'guest');
354
+            $template->assign('productName', 'nextcloud'); // for now
355
+            $template->assign('version', OC_Util::getVersionString());
356
+            $template->assign('tooBig', $tooBig);
357
+
358
+            $template->printPage();
359
+            die();
360
+        }
361
+
362
+        // check whether this is a core update or apps update
363
+        $installedVersion = $systemConfig->getValue('version', '0.0.0');
364
+        $currentVersion = implode('.', \OCP\Util::getVersion());
365
+
366
+        // if not a core upgrade, then it's apps upgrade
367
+        $isAppsOnlyUpgrade = version_compare($currentVersion, $installedVersion, '=');
368
+
369
+        $oldTheme = $systemConfig->getValue('theme');
370
+        $systemConfig->setValue('theme', '');
371
+        OC_Util::addScript('config'); // needed for web root
372
+        OC_Util::addScript('update');
373
+
374
+        /** @var \OC\App\AppManager $appManager */
375
+        $appManager = \OC::$server->getAppManager();
376
+
377
+        $tmpl = new OC_Template('', 'update.admin', 'guest');
378
+        $tmpl->assign('version', OC_Util::getVersionString());
379
+        $tmpl->assign('isAppsOnlyUpgrade', $isAppsOnlyUpgrade);
380
+
381
+        // get third party apps
382
+        $ocVersion = \OCP\Util::getVersion();
383
+        $ocVersion = implode('.', $ocVersion);
384
+        $incompatibleApps = $appManager->getIncompatibleApps($ocVersion);
385
+        $incompatibleShippedApps = [];
386
+        foreach ($incompatibleApps as $appInfo) {
387
+            if ($appManager->isShipped($appInfo['id'])) {
388
+                $incompatibleShippedApps[] = $appInfo['name'] . ' (' . $appInfo['id'] . ')';
389
+            }
390
+        }
391
+
392
+        if (!empty($incompatibleShippedApps)) {
393
+            $l = \OC::$server->getL10N('core');
394
+            $hint = $l->t('The files of the app %1$s were not replaced correctly. Make sure it is a version compatible with the server.', [implode(', ', $incompatibleShippedApps)]);
395
+            throw new \OC\HintException('The files of the app ' . implode(', ', $incompatibleShippedApps) . ' were not replaced correctly. Make sure it is a version compatible with the server.', $hint);
396
+        }
397
+
398
+        $tmpl->assign('appsToUpgrade', $appManager->getAppsNeedingUpgrade($ocVersion));
399
+        $tmpl->assign('incompatibleAppsList', $incompatibleApps);
400
+        $tmpl->assign('productName', 'Nextcloud'); // for now
401
+        $tmpl->assign('oldTheme', $oldTheme);
402
+        $tmpl->printPage();
403
+    }
404
+
405
+    public static function initSession() {
406
+        if(self::$server->getRequest()->getServerProtocol() === 'https') {
407
+            ini_set('session.cookie_secure', true);
408
+        }
409
+
410
+        // prevents javascript from accessing php session cookies
411
+        ini_set('session.cookie_httponly', 'true');
412
+
413
+        // set the cookie path to the Nextcloud directory
414
+        $cookie_path = OC::$WEBROOT ? : '/';
415
+        ini_set('session.cookie_path', $cookie_path);
416
+
417
+        // Let the session name be changed in the initSession Hook
418
+        $sessionName = OC_Util::getInstanceId();
419
+
420
+        try {
421
+            // Allow session apps to create a custom session object
422
+            $useCustomSession = false;
423
+            $session = self::$server->getSession();
424
+            OC_Hook::emit('OC', 'initSession', ['session' => &$session, 'sessionName' => &$sessionName, 'useCustomSession' => &$useCustomSession]);
425
+            if (!$useCustomSession) {
426
+                // set the session name to the instance id - which is unique
427
+                $session = new \OC\Session\Internal($sessionName);
428
+            }
429
+
430
+            $cryptoWrapper = \OC::$server->getSessionCryptoWrapper();
431
+            $session = $cryptoWrapper->wrapSession($session);
432
+            self::$server->setSession($session);
433
+
434
+            // if session can't be started break with http 500 error
435
+        } catch (Exception $e) {
436
+            \OC::$server->getLogger()->logException($e, ['app' => 'base']);
437
+            //show the user a detailed error page
438
+            OC_Template::printExceptionErrorPage($e, 500);
439
+            die();
440
+        }
441
+
442
+        $sessionLifeTime = self::getSessionLifeTime();
443
+
444
+        // session timeout
445
+        if ($session->exists('LAST_ACTIVITY') && (time() - $session->get('LAST_ACTIVITY') > $sessionLifeTime)) {
446
+            if (isset($_COOKIE[session_name()])) {
447
+                setcookie(session_name(), '', -1, self::$WEBROOT ? : '/');
448
+            }
449
+            \OC::$server->getUserSession()->logout();
450
+        }
451
+
452
+        $session->set('LAST_ACTIVITY', time());
453
+    }
454
+
455
+    /**
456
+     * @return string
457
+     */
458
+    private static function getSessionLifeTime() {
459
+        return \OC::$server->getConfig()->getSystemValue('session_lifetime', 60 * 60 * 24);
460
+    }
461
+
462
+    /**
463
+     * Try to set some values to the required Nextcloud default
464
+     */
465
+    public static function setRequiredIniValues() {
466
+        @ini_set('default_charset', 'UTF-8');
467
+        @ini_set('gd.jpeg_ignore_warning', '1');
468
+    }
469
+
470
+    /**
471
+     * Send the same site cookies
472
+     */
473
+    private static function sendSameSiteCookies() {
474
+        $cookieParams = session_get_cookie_params();
475
+        $secureCookie = ($cookieParams['secure'] === true) ? 'secure; ' : '';
476
+        $policies = [
477
+            'lax',
478
+            'strict',
479
+        ];
480
+
481
+        // Append __Host to the cookie if it meets the requirements
482
+        $cookiePrefix = '';
483
+        if($cookieParams['secure'] === true && $cookieParams['path'] === '/') {
484
+            $cookiePrefix = '__Host-';
485
+        }
486
+
487
+        foreach($policies as $policy) {
488
+            header(
489
+                sprintf(
490
+                    'Set-Cookie: %snc_sameSiteCookie%s=true; path=%s; httponly;' . $secureCookie . 'expires=Fri, 31-Dec-2100 23:59:59 GMT; SameSite=%s',
491
+                    $cookiePrefix,
492
+                    $policy,
493
+                    $cookieParams['path'],
494
+                    $policy
495
+                ),
496
+                false
497
+            );
498
+        }
499
+    }
500
+
501
+    /**
502
+     * Same Site cookie to further mitigate CSRF attacks. This cookie has to
503
+     * be set in every request if cookies are sent to add a second level of
504
+     * defense against CSRF.
505
+     *
506
+     * If the cookie is not sent this will set the cookie and reload the page.
507
+     * We use an additional cookie since we want to protect logout CSRF and
508
+     * also we can't directly interfere with PHP's session mechanism.
509
+     */
510
+    private static function performSameSiteCookieProtection() {
511
+        $request = \OC::$server->getRequest();
512
+
513
+        // Some user agents are notorious and don't really properly follow HTTP
514
+        // specifications. For those, have an automated opt-out. Since the protection
515
+        // for remote.php is applied in base.php as starting point we need to opt out
516
+        // here.
517
+        $incompatibleUserAgents = \OC::$server->getConfig()->getSystemValue('csrf.optout');
518
+
519
+        // Fallback, if csrf.optout is unset
520
+        if (!is_array($incompatibleUserAgents)) {
521
+            $incompatibleUserAgents = [
522
+                // OS X Finder
523
+                '/^WebDAVFS/',
524
+                // Windows webdav drive
525
+                '/^Microsoft-WebDAV-MiniRedir/',
526
+            ];
527
+        }
528
+
529
+        if($request->isUserAgent($incompatibleUserAgents)) {
530
+            return;
531
+        }
532
+
533
+        if(count($_COOKIE) > 0) {
534
+            $requestUri = $request->getScriptName();
535
+            $processingScript = explode('/', $requestUri);
536
+            $processingScript = $processingScript[count($processingScript)-1];
537
+
538
+            // index.php routes are handled in the middleware
539
+            if($processingScript === 'index.php') {
540
+                return;
541
+            }
542
+
543
+            // All other endpoints require the lax and the strict cookie
544
+            if(!$request->passesStrictCookieCheck()) {
545
+                self::sendSameSiteCookies();
546
+                // Debug mode gets access to the resources without strict cookie
547
+                // due to the fact that the SabreDAV browser also lives there.
548
+                if(!\OC::$server->getConfig()->getSystemValue('debug', false)) {
549
+                    http_response_code(\OCP\AppFramework\Http::STATUS_SERVICE_UNAVAILABLE);
550
+                    exit();
551
+                }
552
+            }
553
+        } elseif(!isset($_COOKIE['nc_sameSiteCookielax']) || !isset($_COOKIE['nc_sameSiteCookiestrict'])) {
554
+            self::sendSameSiteCookies();
555
+        }
556
+    }
557
+
558
+    public static function init() {
559
+        // calculate the root directories
560
+        OC::$SERVERROOT = str_replace("\\", '/', substr(__DIR__, 0, -4));
561
+
562
+        // register autoloader
563
+        $loaderStart = microtime(true);
564
+        require_once __DIR__ . '/autoloader.php';
565
+        self::$loader = new \OC\Autoloader([
566
+            OC::$SERVERROOT . '/lib/private/legacy',
567
+        ]);
568
+        if (defined('PHPUNIT_RUN')) {
569
+            self::$loader->addValidRoot(OC::$SERVERROOT . '/tests');
570
+        }
571
+        spl_autoload_register([self::$loader, 'load']);
572
+        $loaderEnd = microtime(true);
573
+
574
+        self::$CLI = (php_sapi_name() == 'cli');
575
+
576
+        // Add default composer PSR-4 autoloader
577
+        self::$composerAutoloader = require_once OC::$SERVERROOT . '/lib/composer/autoload.php';
578
+
579
+        try {
580
+            self::initPaths();
581
+            // setup 3rdparty autoloader
582
+            $vendorAutoLoad = OC::$SERVERROOT. '/3rdparty/autoload.php';
583
+            if (!file_exists($vendorAutoLoad)) {
584
+                throw new \RuntimeException('Composer autoloader not found, unable to continue. Check the folder "3rdparty". Running "git submodule update --init" will initialize the git submodule that handles the subfolder "3rdparty".');
585
+            }
586
+            require_once $vendorAutoLoad;
587
+
588
+        } catch (\RuntimeException $e) {
589
+            if (!self::$CLI) {
590
+                http_response_code(503);
591
+            }
592
+            // we can't use the template error page here, because this needs the
593
+            // DI container which isn't available yet
594
+            print($e->getMessage());
595
+            exit();
596
+        }
597
+
598
+        // setup the basic server
599
+        self::$server = new \OC\Server(\OC::$WEBROOT, self::$config);
600
+        \OC::$server->getEventLogger()->log('autoloader', 'Autoloader', $loaderStart, $loaderEnd);
601
+        \OC::$server->getEventLogger()->start('boot', 'Initialize');
602
+
603
+        // Override php.ini and log everything if we're troubleshooting
604
+        if (self::$config->getValue('loglevel') === ILogger::DEBUG) {
605
+            error_reporting(E_ALL);
606
+        }
607
+
608
+        // Don't display errors and log them
609
+        @ini_set('display_errors', '0');
610
+        @ini_set('log_errors', '1');
611
+
612
+        if(!date_default_timezone_set('UTC')) {
613
+            throw new \RuntimeException('Could not set timezone to UTC');
614
+        }
615
+
616
+        //try to configure php to enable big file uploads.
617
+        //this doesn´t work always depending on the webserver and php configuration.
618
+        //Let´s try to overwrite some defaults anyway
619
+
620
+        //try to set the maximum execution time to 60min
621
+        if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
622
+            @set_time_limit(3600);
623
+        }
624
+        @ini_set('max_execution_time', '3600');
625
+        @ini_set('max_input_time', '3600');
626
+
627
+        //try to set the maximum filesize to 10G
628
+        @ini_set('upload_max_filesize', '10G');
629
+        @ini_set('post_max_size', '10G');
630
+        @ini_set('file_uploads', '50');
631
+
632
+        self::setRequiredIniValues();
633
+        self::handleAuthHeaders();
634
+        self::registerAutoloaderCache();
635
+
636
+        // initialize intl fallback is necessary
637
+        \Patchwork\Utf8\Bootup::initIntl();
638
+        OC_Util::isSetLocaleWorking();
639
+
640
+        if (!defined('PHPUNIT_RUN')) {
641
+            OC\Log\ErrorHandler::setLogger(\OC::$server->getLogger());
642
+            $debug = \OC::$server->getConfig()->getSystemValue('debug', false);
643
+            OC\Log\ErrorHandler::register($debug);
644
+        }
645
+
646
+        \OC::$server->getEventLogger()->start('init_session', 'Initialize session');
647
+        OC_App::loadApps(['session']);
648
+        if (!self::$CLI) {
649
+            self::initSession();
650
+        }
651
+        \OC::$server->getEventLogger()->end('init_session');
652
+        self::checkConfig();
653
+        self::checkInstalled();
654
+
655
+        OC_Response::addSecurityHeaders();
656
+
657
+        self::performSameSiteCookieProtection();
658
+
659
+        if (!defined('OC_CONSOLE')) {
660
+            $errors = OC_Util::checkServer(\OC::$server->getSystemConfig());
661
+            if (count($errors) > 0) {
662
+                if (!self::$CLI) {
663
+                    http_response_code(503);
664
+                    OC_Util::addStyle('guest');
665
+                    try {
666
+                        OC_Template::printGuestPage('', 'error', ['errors' => $errors]);
667
+                        exit;
668
+                    } catch (\Exception $e) {
669
+                        // In case any error happens when showing the error page, we simply fall back to posting the text.
670
+                        // This might be the case when e.g. the data directory is broken and we can not load/write SCSS to/from it.
671
+                    }
672
+                }
673
+
674
+                // Convert l10n string into regular string for usage in database
675
+                $staticErrors = [];
676
+                foreach ($errors as $error) {
677
+                    echo $error['error'] . "\n";
678
+                    echo $error['hint'] . "\n\n";
679
+                    $staticErrors[] = [
680
+                        'error' => (string)$error['error'],
681
+                        'hint' => (string)$error['hint'],
682
+                    ];
683
+                }
684
+
685
+                try {
686
+                    \OC::$server->getConfig()->setAppValue('core', 'cronErrors', json_encode($staticErrors));
687
+                } catch (\Exception $e) {
688
+                    echo('Writing to database failed');
689
+                }
690
+                exit(1);
691
+            } elseif (self::$CLI && \OC::$server->getConfig()->getSystemValue('installed', false)) {
692
+                \OC::$server->getConfig()->deleteAppValue('core', 'cronErrors');
693
+            }
694
+        }
695
+        //try to set the session lifetime
696
+        $sessionLifeTime = self::getSessionLifeTime();
697
+        @ini_set('gc_maxlifetime', (string)$sessionLifeTime);
698
+
699
+        $systemConfig = \OC::$server->getSystemConfig();
700
+
701
+        // User and Groups
702
+        if (!$systemConfig->getValue("installed", false)) {
703
+            self::$server->getSession()->set('user_id', '');
704
+        }
705
+
706
+        OC_User::useBackend(new \OC\User\Database());
707
+        \OC::$server->getGroupManager()->addBackend(new \OC\Group\Database());
708
+
709
+        // Subscribe to the hook
710
+        \OCP\Util::connectHook(
711
+            '\OCA\Files_Sharing\API\Server2Server',
712
+            'preLoginNameUsedAsUserName',
713
+            '\OC\User\Database',
714
+            'preLoginNameUsedAsUserName'
715
+        );
716
+
717
+        //setup extra user backends
718
+        if (!\OCP\Util::needUpgrade()) {
719
+            OC_User::setupBackends();
720
+        } else {
721
+            // Run upgrades in incognito mode
722
+            OC_User::setIncognitoMode(true);
723
+        }
724
+
725
+        self::registerCleanupHooks();
726
+        self::registerFilesystemHooks();
727
+        self::registerShareHooks();
728
+        self::registerEncryptionWrapper();
729
+        self::registerEncryptionHooks();
730
+        self::registerAccountHooks();
731
+        self::registerResourceCollectionHooks();
732
+        self::registerAppRestrictionsHooks();
733
+
734
+        // Make sure that the application class is not loaded before the database is setup
735
+        if ($systemConfig->getValue("installed", false)) {
736
+            OC_App::loadApp('settings');
737
+            $settings = \OC::$server->query(\OCA\Settings\AppInfo\Application::class);
738
+            $settings->register();
739
+        }
740
+
741
+        //make sure temporary files are cleaned up
742
+        $tmpManager = \OC::$server->getTempManager();
743
+        register_shutdown_function([$tmpManager, 'clean']);
744
+        $lockProvider = \OC::$server->getLockingProvider();
745
+        register_shutdown_function([$lockProvider, 'releaseAll']);
746
+
747
+        // Check whether the sample configuration has been copied
748
+        if($systemConfig->getValue('copied_sample_config', false)) {
749
+            $l = \OC::$server->getL10N('lib');
750
+            OC_Template::printErrorPage(
751
+                $l->t('Sample configuration detected'),
752
+                $l->t('It has been detected that the sample configuration has been copied. This can break your installation and is unsupported. Please read the documentation before performing changes on config.php'),
753
+                503
754
+            );
755
+            return;
756
+        }
757
+
758
+        $request = \OC::$server->getRequest();
759
+        $host = $request->getInsecureServerHost();
760
+        /**
761
+         * if the host passed in headers isn't trusted
762
+         * FIXME: Should not be in here at all :see_no_evil:
763
+         */
764
+        if (!OC::$CLI
765
+            && !\OC::$server->getTrustedDomainHelper()->isTrustedDomain($host)
766
+            && self::$server->getConfig()->getSystemValue('installed', false)
767
+        ) {
768
+            // Allow access to CSS resources
769
+            $isScssRequest = false;
770
+            if(strpos($request->getPathInfo(), '/css/') === 0) {
771
+                $isScssRequest = true;
772
+            }
773
+
774
+            if(substr($request->getRequestUri(), -11) === '/status.php') {
775
+                http_response_code(400);
776
+                header('Content-Type: application/json');
777
+                echo '{"error": "Trusted domain error.", "code": 15}';
778
+                exit();
779
+            }
780
+
781
+            if (!$isScssRequest) {
782
+                http_response_code(400);
783
+
784
+                \OC::$server->getLogger()->info(
785
+                    'Trusted domain error. "{remoteAddress}" tried to access using "{host}" as host.',
786
+                    [
787
+                        'app' => 'core',
788
+                        'remoteAddress' => $request->getRemoteAddress(),
789
+                        'host' => $host,
790
+                    ]
791
+                );
792
+
793
+                $tmpl = new OCP\Template('core', 'untrustedDomain', 'guest');
794
+                $tmpl->assign('docUrl', \OC::$server->getURLGenerator()->linkToDocs('admin-trusted-domains'));
795
+                $tmpl->printPage();
796
+
797
+                exit();
798
+            }
799
+        }
800
+        \OC::$server->getEventLogger()->end('boot');
801
+    }
802
+
803
+    /**
804
+     * register hooks for the cleanup of cache and bruteforce protection
805
+     */
806
+    public static function registerCleanupHooks() {
807
+        //don't try to do this before we are properly setup
808
+        if (\OC::$server->getSystemConfig()->getValue('installed', false) && !\OCP\Util::needUpgrade()) {
809
+
810
+            // NOTE: This will be replaced to use OCP
811
+            $userSession = self::$server->getUserSession();
812
+            $userSession->listen('\OC\User', 'postLogin', function () use ($userSession) {
813
+                if (!defined('PHPUNIT_RUN')) {
814
+                    // reset brute force delay for this IP address and username
815
+                    $uid = \OC::$server->getUserSession()->getUser()->getUID();
816
+                    $request = \OC::$server->getRequest();
817
+                    $throttler = \OC::$server->getBruteForceThrottler();
818
+                    $throttler->resetDelay($request->getRemoteAddress(), 'login', ['user' => $uid]);
819
+                }
820
+
821
+                try {
822
+                    $cache = new \OC\Cache\File();
823
+                    $cache->gc();
824
+                } catch (\OC\ServerNotAvailableException $e) {
825
+                    // not a GC exception, pass it on
826
+                    throw $e;
827
+                } catch (\OC\ForbiddenException $e) {
828
+                    // filesystem blocked for this request, ignore
829
+                } catch (\Exception $e) {
830
+                    // a GC exception should not prevent users from using OC,
831
+                    // so log the exception
832
+                    \OC::$server->getLogger()->logException($e, [
833
+                        'message' => 'Exception when running cache gc.',
834
+                        'level' => ILogger::WARN,
835
+                        'app' => 'core',
836
+                    ]);
837
+                }
838
+            });
839
+        }
840
+    }
841
+
842
+    private static function registerEncryptionWrapper() {
843
+        $manager = self::$server->getEncryptionManager();
844
+        \OCP\Util::connectHook('OC_Filesystem', 'preSetup', $manager, 'setupStorage');
845
+    }
846
+
847
+    private static function registerEncryptionHooks() {
848
+        $enabled = self::$server->getEncryptionManager()->isEnabled();
849
+        if ($enabled) {
850
+            \OCP\Util::connectHook(Share::class, 'post_shared', HookManager::class, 'postShared');
851
+            \OCP\Util::connectHook(Share::class, 'post_unshare', HookManager::class, 'postUnshared');
852
+            \OCP\Util::connectHook('OC_Filesystem', 'post_rename', HookManager::class, 'postRename');
853
+            \OCP\Util::connectHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', HookManager::class, 'postRestore');
854
+        }
855
+    }
856
+
857
+    private static function registerAccountHooks() {
858
+        $hookHandler = new \OC\Accounts\Hooks(\OC::$server->getLogger());
859
+        \OCP\Util::connectHook('OC_User', 'changeUser', $hookHandler, 'changeUserHook');
860
+    }
861
+
862
+    private static function registerAppRestrictionsHooks() {
863
+        $groupManager = self::$server->query(\OCP\IGroupManager::class);
864
+        $groupManager->listen ('\OC\Group', 'postDelete', function (\OCP\IGroup $group) {
865
+            $appManager = self::$server->getAppManager();
866
+            $apps = $appManager->getEnabledAppsForGroup($group);
867
+            foreach ($apps as $appId) {
868
+                $restrictions = $appManager->getAppRestriction($appId);
869
+                if (empty($restrictions)) {
870
+                    continue;
871
+                }
872
+                $key = array_search($group->getGID(), $restrictions);
873
+                unset($restrictions[$key]);
874
+                $restrictions = array_values($restrictions);
875
+                if (empty($restrictions)) {
876
+                    $appManager->disableApp($appId);
877
+                }
878
+                else{
879
+                    $appManager->enableAppForGroups($appId, $restrictions);
880
+                }
881
+
882
+            }
883
+        });
884
+    }
885
+
886
+    private static function registerResourceCollectionHooks() {
887
+        \OC\Collaboration\Resources\Listener::register(\OC::$server->getEventDispatcher());
888
+    }
889
+
890
+    /**
891
+     * register hooks for the filesystem
892
+     */
893
+    public static function registerFilesystemHooks() {
894
+        // Check for blacklisted files
895
+        OC_Hook::connect('OC_Filesystem', 'write', Filesystem::class, 'isBlacklisted');
896
+        OC_Hook::connect('OC_Filesystem', 'rename', Filesystem::class, 'isBlacklisted');
897
+    }
898
+
899
+    /**
900
+     * register hooks for sharing
901
+     */
902
+    public static function registerShareHooks() {
903
+        if (\OC::$server->getSystemConfig()->getValue('installed')) {
904
+            OC_Hook::connect('OC_User', 'post_deleteUser', Hooks::class, 'post_deleteUser');
905
+            OC_Hook::connect('OC_User', 'post_removeFromGroup', Hooks::class, 'post_removeFromGroup');
906
+            OC_Hook::connect('OC_User', 'post_deleteGroup', Hooks::class, 'post_deleteGroup');
907
+        }
908
+    }
909
+
910
+    protected static function registerAutoloaderCache() {
911
+        // The class loader takes an optional low-latency cache, which MUST be
912
+        // namespaced. The instanceid is used for namespacing, but might be
913
+        // unavailable at this point. Furthermore, it might not be possible to
914
+        // generate an instanceid via \OC_Util::getInstanceId() because the
915
+        // config file may not be writable. As such, we only register a class
916
+        // loader cache if instanceid is available without trying to create one.
917
+        $instanceId = \OC::$server->getSystemConfig()->getValue('instanceid', null);
918
+        if ($instanceId) {
919
+            try {
920
+                $memcacheFactory = \OC::$server->getMemCacheFactory();
921
+                self::$loader->setMemoryCache($memcacheFactory->createLocal('Autoloader'));
922
+            } catch (\Exception $ex) {
923
+            }
924
+        }
925
+    }
926
+
927
+    /**
928
+     * Handle the request
929
+     */
930
+    public static function handleRequest() {
931
+
932
+        \OC::$server->getEventLogger()->start('handle_request', 'Handle request');
933
+        $systemConfig = \OC::$server->getSystemConfig();
934
+
935
+        // Check if Nextcloud is installed or in maintenance (update) mode
936
+        if (!$systemConfig->getValue('installed', false)) {
937
+            \OC::$server->getSession()->clear();
938
+            $setupHelper = new OC\Setup(
939
+                $systemConfig,
940
+                \OC::$server->getIniWrapper(),
941
+                \OC::$server->getL10N('lib'),
942
+                \OC::$server->query(\OCP\Defaults::class),
943
+                \OC::$server->getLogger(),
944
+                \OC::$server->getSecureRandom(),
945
+                \OC::$server->query(\OC\Installer::class)
946
+            );
947
+            $controller = new OC\Core\Controller\SetupController($setupHelper);
948
+            $controller->run($_POST);
949
+            exit();
950
+        }
951
+
952
+        $request = \OC::$server->getRequest();
953
+        $requestPath = $request->getRawPathInfo();
954
+        if ($requestPath === '/heartbeat') {
955
+            return;
956
+        }
957
+        if (substr($requestPath, -3) !== '.js') { // we need these files during the upgrade
958
+            self::checkMaintenanceMode();
959
+
960
+            if (\OCP\Util::needUpgrade()) {
961
+                if (function_exists('opcache_reset')) {
962
+                    opcache_reset();
963
+                }
964
+                if (!((bool) $systemConfig->getValue('maintenance', false))) {
965
+                    self::printUpgradePage($systemConfig);
966
+                    exit();
967
+                }
968
+            }
969
+        }
970
+
971
+        // emergency app disabling
972
+        if ($requestPath === '/disableapp'
973
+            && $request->getMethod() === 'POST'
974
+            && ((array)$request->getParam('appid')) !== ''
975
+        ) {
976
+            \OC_JSON::callCheck();
977
+            \OC_JSON::checkAdminUser();
978
+            $appIds = (array)$request->getParam('appid');
979
+            foreach($appIds as $appId) {
980
+                $appId = \OC_App::cleanAppId($appId);
981
+                \OC::$server->getAppManager()->disableApp($appId);
982
+            }
983
+            \OC_JSON::success();
984
+            exit();
985
+        }
986
+
987
+        // Always load authentication apps
988
+        OC_App::loadApps(['authentication']);
989
+
990
+        // Load minimum set of apps
991
+        if (!\OCP\Util::needUpgrade()
992
+            && !((bool) $systemConfig->getValue('maintenance', false))) {
993
+            // For logged-in users: Load everything
994
+            if(\OC::$server->getUserSession()->isLoggedIn()) {
995
+                OC_App::loadApps();
996
+            } else {
997
+                // For guests: Load only filesystem and logging
998
+                OC_App::loadApps(['filesystem', 'logging']);
999
+                self::handleLogin($request);
1000
+            }
1001
+        }
1002
+
1003
+        if (!self::$CLI) {
1004
+            try {
1005
+                if (!((bool) $systemConfig->getValue('maintenance', false)) && !\OCP\Util::needUpgrade()) {
1006
+                    OC_App::loadApps(['filesystem', 'logging']);
1007
+                    OC_App::loadApps();
1008
+                }
1009
+                OC_Util::setupFS();
1010
+                OC::$server->getRouter()->match(\OC::$server->getRequest()->getRawPathInfo());
1011
+                return;
1012
+            } catch (Symfony\Component\Routing\Exception\ResourceNotFoundException $e) {
1013
+                //header('HTTP/1.0 404 Not Found');
1014
+            } catch (Symfony\Component\Routing\Exception\MethodNotAllowedException $e) {
1015
+                http_response_code(405);
1016
+                return;
1017
+            }
1018
+        }
1019
+
1020
+        // Handle WebDAV
1021
+        if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'PROPFIND') {
1022
+            // not allowed any more to prevent people
1023
+            // mounting this root directly.
1024
+            // Users need to mount remote.php/webdav instead.
1025
+            http_response_code(405);
1026
+            return;
1027
+        }
1028
+
1029
+        // Someone is logged in
1030
+        if (\OC::$server->getUserSession()->isLoggedIn()) {
1031
+            OC_App::loadApps();
1032
+            OC_User::setupBackends();
1033
+            OC_Util::setupFS();
1034
+            // FIXME
1035
+            // Redirect to default application
1036
+            OC_Util::redirectToDefaultPage();
1037
+        } else {
1038
+            // Not handled and not logged in
1039
+            header('Location: '.\OC::$server->getURLGenerator()->linkToRouteAbsolute('core.login.showLoginForm'));
1040
+        }
1041
+    }
1042
+
1043
+    /**
1044
+     * Check login: apache auth, auth token, basic auth
1045
+     *
1046
+     * @param OCP\IRequest $request
1047
+     * @return boolean
1048
+     */
1049
+    static function handleLogin(OCP\IRequest $request) {
1050
+        $userSession = self::$server->getUserSession();
1051
+        if (OC_User::handleApacheAuth()) {
1052
+            return true;
1053
+        }
1054
+        if ($userSession->tryTokenLogin($request)) {
1055
+            return true;
1056
+        }
1057
+        if (isset($_COOKIE['nc_username'])
1058
+            && isset($_COOKIE['nc_token'])
1059
+            && isset($_COOKIE['nc_session_id'])
1060
+            && $userSession->loginWithCookie($_COOKIE['nc_username'], $_COOKIE['nc_token'], $_COOKIE['nc_session_id'])) {
1061
+            return true;
1062
+        }
1063
+        if ($userSession->tryBasicAuthLogin($request, \OC::$server->getBruteForceThrottler())) {
1064
+            return true;
1065
+        }
1066
+        return false;
1067
+    }
1068
+
1069
+    protected static function handleAuthHeaders() {
1070
+        //copy http auth headers for apache+php-fcgid work around
1071
+        if (isset($_SERVER['HTTP_XAUTHORIZATION']) && !isset($_SERVER['HTTP_AUTHORIZATION'])) {
1072
+            $_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['HTTP_XAUTHORIZATION'];
1073
+        }
1074
+
1075
+        // Extract PHP_AUTH_USER/PHP_AUTH_PW from other headers if necessary.
1076
+        $vars = [
1077
+            'HTTP_AUTHORIZATION', // apache+php-cgi work around
1078
+            'REDIRECT_HTTP_AUTHORIZATION', // apache+php-cgi alternative
1079
+        ];
1080
+        foreach ($vars as $var) {
1081
+            if (isset($_SERVER[$var]) && preg_match('/Basic\s+(.*)$/i', $_SERVER[$var], $matches)) {
1082
+                $credentials = explode(':', base64_decode($matches[1]), 2);
1083
+                if (count($credentials) === 2) {
1084
+                    $_SERVER['PHP_AUTH_USER'] = $credentials[0];
1085
+                    $_SERVER['PHP_AUTH_PW'] = $credentials[1];
1086
+                    break;
1087
+                }
1088
+            }
1089
+        }
1090
+    }
1091 1091
 }
1092 1092
 
1093 1093
 OC::init();
Please login to merge, or discard this patch.
Spacing   +57 added lines, -57 removed lines patch added patch discarded remove patch
@@ -133,14 +133,14 @@  discard block
 block discarded – undo
133 133
 	 * the app path list is empty or contains an invalid path
134 134
 	 */
135 135
 	public static function initPaths() {
136
-		if(defined('PHPUNIT_CONFIG_DIR')) {
137
-			self::$configDir = OC::$SERVERROOT . '/' . PHPUNIT_CONFIG_DIR . '/';
138
-		} elseif(defined('PHPUNIT_RUN') and PHPUNIT_RUN and is_dir(OC::$SERVERROOT . '/tests/config/')) {
139
-			self::$configDir = OC::$SERVERROOT . '/tests/config/';
140
-		} elseif($dir = getenv('NEXTCLOUD_CONFIG_DIR')) {
141
-			self::$configDir = rtrim($dir, '/') . '/';
136
+		if (defined('PHPUNIT_CONFIG_DIR')) {
137
+			self::$configDir = OC::$SERVERROOT.'/'.PHPUNIT_CONFIG_DIR.'/';
138
+		} elseif (defined('PHPUNIT_RUN') and PHPUNIT_RUN and is_dir(OC::$SERVERROOT.'/tests/config/')) {
139
+			self::$configDir = OC::$SERVERROOT.'/tests/config/';
140
+		} elseif ($dir = getenv('NEXTCLOUD_CONFIG_DIR')) {
141
+			self::$configDir = rtrim($dir, '/').'/';
142 142
 		} else {
143
-			self::$configDir = OC::$SERVERROOT . '/config/';
143
+			self::$configDir = OC::$SERVERROOT.'/config/';
144 144
 		}
145 145
 		self::$config = new \OC\Config(self::$configDir);
146 146
 
@@ -162,9 +162,9 @@  discard block
 block discarded – undo
162 162
 			//make sure suburi follows the same rules as scriptName
163 163
 			if (substr(OC::$SUBURI, -9) != 'index.php') {
164 164
 				if (substr(OC::$SUBURI, -1) != '/') {
165
-					OC::$SUBURI = OC::$SUBURI . '/';
165
+					OC::$SUBURI = OC::$SUBURI.'/';
166 166
 				}
167
-				OC::$SUBURI = OC::$SUBURI . 'index.php';
167
+				OC::$SUBURI = OC::$SUBURI.'index.php';
168 168
 			}
169 169
 		}
170 170
 
@@ -176,7 +176,7 @@  discard block
 block discarded – undo
176 176
 				OC::$WEBROOT = substr($scriptName, 0, 0 - strlen(OC::$SUBURI));
177 177
 
178 178
 				if (OC::$WEBROOT != '' && OC::$WEBROOT[0] !== '/') {
179
-					OC::$WEBROOT = '/' . OC::$WEBROOT;
179
+					OC::$WEBROOT = '/'.OC::$WEBROOT;
180 180
 				}
181 181
 			} else {
182 182
 				// The scriptName is not ending with OC::$SUBURI
@@ -205,11 +205,11 @@  discard block
 block discarded – undo
205 205
 					OC::$APPSROOTS[] = $paths;
206 206
 				}
207 207
 			}
208
-		} elseif (file_exists(OC::$SERVERROOT . '/apps')) {
209
-			OC::$APPSROOTS[] = ['path' => OC::$SERVERROOT . '/apps', 'url' => '/apps', 'writable' => true];
210
-		} elseif (file_exists(OC::$SERVERROOT . '/../apps')) {
208
+		} elseif (file_exists(OC::$SERVERROOT.'/apps')) {
209
+			OC::$APPSROOTS[] = ['path' => OC::$SERVERROOT.'/apps', 'url' => '/apps', 'writable' => true];
210
+		} elseif (file_exists(OC::$SERVERROOT.'/../apps')) {
211 211
 			OC::$APPSROOTS[] = [
212
-				'path' => rtrim(dirname(OC::$SERVERROOT), '/') . '/apps',
212
+				'path' => rtrim(dirname(OC::$SERVERROOT), '/').'/apps',
213 213
 				'url' => '/apps',
214 214
 				'writable' => true
215 215
 			];
@@ -239,8 +239,8 @@  discard block
 block discarded – undo
239 239
 		$l = \OC::$server->getL10N('lib');
240 240
 
241 241
 		// Create config if it does not already exist
242
-		$configFilePath = self::$configDir .'/config.php';
243
-		if(!file_exists($configFilePath)) {
242
+		$configFilePath = self::$configDir.'/config.php';
243
+		if (!file_exists($configFilePath)) {
244 244
 			@touch($configFilePath);
245 245
 		}
246 246
 
@@ -256,14 +256,14 @@  discard block
 block discarded – undo
256 256
 				echo $l->t('This can usually be fixed by giving the webserver write access to the config directory')."\n";
257 257
 				echo "\n";
258 258
 				echo $l->t('Or, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it.')."\n";
259
-				echo $l->t('See %s', [ $urlGenerator->linkToDocs('admin-config') ])."\n";
259
+				echo $l->t('See %s', [$urlGenerator->linkToDocs('admin-config')])."\n";
260 260
 				exit;
261 261
 			} else {
262 262
 				OC_Template::printErrorPage(
263 263
 					$l->t('Cannot write into "config" directory!'),
264
-					$l->t('This can usually be fixed by giving the webserver write access to the config directory.') . '. '
264
+					$l->t('This can usually be fixed by giving the webserver write access to the config directory.').'. '
265 265
 					. $l->t('Or, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it. See %s',
266
-					[ $urlGenerator->linkToDocs('admin-config') ] ),
266
+					[$urlGenerator->linkToDocs('admin-config')]),
267 267
 					503
268 268
 				);
269 269
 			}
@@ -279,8 +279,8 @@  discard block
 block discarded – undo
279 279
 			if (OC::$CLI) {
280 280
 				throw new Exception('Not installed');
281 281
 			} else {
282
-				$url = OC::$WEBROOT . '/index.php';
283
-				header('Location: ' . $url);
282
+				$url = OC::$WEBROOT.'/index.php';
283
+				header('Location: '.$url);
284 284
 			}
285 285
 			exit();
286 286
 		}
@@ -385,14 +385,14 @@  discard block
 block discarded – undo
385 385
 		$incompatibleShippedApps = [];
386 386
 		foreach ($incompatibleApps as $appInfo) {
387 387
 			if ($appManager->isShipped($appInfo['id'])) {
388
-				$incompatibleShippedApps[] = $appInfo['name'] . ' (' . $appInfo['id'] . ')';
388
+				$incompatibleShippedApps[] = $appInfo['name'].' ('.$appInfo['id'].')';
389 389
 			}
390 390
 		}
391 391
 
392 392
 		if (!empty($incompatibleShippedApps)) {
393 393
 			$l = \OC::$server->getL10N('core');
394 394
 			$hint = $l->t('The files of the app %1$s were not replaced correctly. Make sure it is a version compatible with the server.', [implode(', ', $incompatibleShippedApps)]);
395
-			throw new \OC\HintException('The files of the app ' . implode(', ', $incompatibleShippedApps) . ' were not replaced correctly. Make sure it is a version compatible with the server.', $hint);
395
+			throw new \OC\HintException('The files of the app '.implode(', ', $incompatibleShippedApps).' were not replaced correctly. Make sure it is a version compatible with the server.', $hint);
396 396
 		}
397 397
 
398 398
 		$tmpl->assign('appsToUpgrade', $appManager->getAppsNeedingUpgrade($ocVersion));
@@ -403,7 +403,7 @@  discard block
 block discarded – undo
403 403
 	}
404 404
 
405 405
 	public static function initSession() {
406
-		if(self::$server->getRequest()->getServerProtocol() === 'https') {
406
+		if (self::$server->getRequest()->getServerProtocol() === 'https') {
407 407
 			ini_set('session.cookie_secure', true);
408 408
 		}
409 409
 
@@ -411,7 +411,7 @@  discard block
 block discarded – undo
411 411
 		ini_set('session.cookie_httponly', 'true');
412 412
 
413 413
 		// set the cookie path to the Nextcloud directory
414
-		$cookie_path = OC::$WEBROOT ? : '/';
414
+		$cookie_path = OC::$WEBROOT ?: '/';
415 415
 		ini_set('session.cookie_path', $cookie_path);
416 416
 
417 417
 		// Let the session name be changed in the initSession Hook
@@ -444,7 +444,7 @@  discard block
 block discarded – undo
444 444
 		// session timeout
445 445
 		if ($session->exists('LAST_ACTIVITY') && (time() - $session->get('LAST_ACTIVITY') > $sessionLifeTime)) {
446 446
 			if (isset($_COOKIE[session_name()])) {
447
-				setcookie(session_name(), '', -1, self::$WEBROOT ? : '/');
447
+				setcookie(session_name(), '', -1, self::$WEBROOT ?: '/');
448 448
 			}
449 449
 			\OC::$server->getUserSession()->logout();
450 450
 		}
@@ -480,14 +480,14 @@  discard block
 block discarded – undo
480 480
 
481 481
 		// Append __Host to the cookie if it meets the requirements
482 482
 		$cookiePrefix = '';
483
-		if($cookieParams['secure'] === true && $cookieParams['path'] === '/') {
483
+		if ($cookieParams['secure'] === true && $cookieParams['path'] === '/') {
484 484
 			$cookiePrefix = '__Host-';
485 485
 		}
486 486
 
487
-		foreach($policies as $policy) {
487
+		foreach ($policies as $policy) {
488 488
 			header(
489 489
 				sprintf(
490
-					'Set-Cookie: %snc_sameSiteCookie%s=true; path=%s; httponly;' . $secureCookie . 'expires=Fri, 31-Dec-2100 23:59:59 GMT; SameSite=%s',
490
+					'Set-Cookie: %snc_sameSiteCookie%s=true; path=%s; httponly;'.$secureCookie.'expires=Fri, 31-Dec-2100 23:59:59 GMT; SameSite=%s',
491 491
 					$cookiePrefix,
492 492
 					$policy,
493 493
 					$cookieParams['path'],
@@ -526,31 +526,31 @@  discard block
 block discarded – undo
526 526
 			];
527 527
 		}
528 528
 
529
-		if($request->isUserAgent($incompatibleUserAgents)) {
529
+		if ($request->isUserAgent($incompatibleUserAgents)) {
530 530
 			return;
531 531
 		}
532 532
 
533
-		if(count($_COOKIE) > 0) {
533
+		if (count($_COOKIE) > 0) {
534 534
 			$requestUri = $request->getScriptName();
535 535
 			$processingScript = explode('/', $requestUri);
536
-			$processingScript = $processingScript[count($processingScript)-1];
536
+			$processingScript = $processingScript[count($processingScript) - 1];
537 537
 
538 538
 			// index.php routes are handled in the middleware
539
-			if($processingScript === 'index.php') {
539
+			if ($processingScript === 'index.php') {
540 540
 				return;
541 541
 			}
542 542
 
543 543
 			// All other endpoints require the lax and the strict cookie
544
-			if(!$request->passesStrictCookieCheck()) {
544
+			if (!$request->passesStrictCookieCheck()) {
545 545
 				self::sendSameSiteCookies();
546 546
 				// Debug mode gets access to the resources without strict cookie
547 547
 				// due to the fact that the SabreDAV browser also lives there.
548
-				if(!\OC::$server->getConfig()->getSystemValue('debug', false)) {
548
+				if (!\OC::$server->getConfig()->getSystemValue('debug', false)) {
549 549
 					http_response_code(\OCP\AppFramework\Http::STATUS_SERVICE_UNAVAILABLE);
550 550
 					exit();
551 551
 				}
552 552
 			}
553
-		} elseif(!isset($_COOKIE['nc_sameSiteCookielax']) || !isset($_COOKIE['nc_sameSiteCookiestrict'])) {
553
+		} elseif (!isset($_COOKIE['nc_sameSiteCookielax']) || !isset($_COOKIE['nc_sameSiteCookiestrict'])) {
554 554
 			self::sendSameSiteCookies();
555 555
 		}
556 556
 	}
@@ -561,12 +561,12 @@  discard block
 block discarded – undo
561 561
 
562 562
 		// register autoloader
563 563
 		$loaderStart = microtime(true);
564
-		require_once __DIR__ . '/autoloader.php';
564
+		require_once __DIR__.'/autoloader.php';
565 565
 		self::$loader = new \OC\Autoloader([
566
-			OC::$SERVERROOT . '/lib/private/legacy',
566
+			OC::$SERVERROOT.'/lib/private/legacy',
567 567
 		]);
568 568
 		if (defined('PHPUNIT_RUN')) {
569
-			self::$loader->addValidRoot(OC::$SERVERROOT . '/tests');
569
+			self::$loader->addValidRoot(OC::$SERVERROOT.'/tests');
570 570
 		}
571 571
 		spl_autoload_register([self::$loader, 'load']);
572 572
 		$loaderEnd = microtime(true);
@@ -574,12 +574,12 @@  discard block
 block discarded – undo
574 574
 		self::$CLI = (php_sapi_name() == 'cli');
575 575
 
576 576
 		// Add default composer PSR-4 autoloader
577
-		self::$composerAutoloader = require_once OC::$SERVERROOT . '/lib/composer/autoload.php';
577
+		self::$composerAutoloader = require_once OC::$SERVERROOT.'/lib/composer/autoload.php';
578 578
 
579 579
 		try {
580 580
 			self::initPaths();
581 581
 			// setup 3rdparty autoloader
582
-			$vendorAutoLoad = OC::$SERVERROOT. '/3rdparty/autoload.php';
582
+			$vendorAutoLoad = OC::$SERVERROOT.'/3rdparty/autoload.php';
583 583
 			if (!file_exists($vendorAutoLoad)) {
584 584
 				throw new \RuntimeException('Composer autoloader not found, unable to continue. Check the folder "3rdparty". Running "git submodule update --init" will initialize the git submodule that handles the subfolder "3rdparty".');
585 585
 			}
@@ -609,7 +609,7 @@  discard block
 block discarded – undo
609 609
 		@ini_set('display_errors', '0');
610 610
 		@ini_set('log_errors', '1');
611 611
 
612
-		if(!date_default_timezone_set('UTC')) {
612
+		if (!date_default_timezone_set('UTC')) {
613 613
 			throw new \RuntimeException('Could not set timezone to UTC');
614 614
 		}
615 615
 
@@ -674,11 +674,11 @@  discard block
 block discarded – undo
674 674
 				// Convert l10n string into regular string for usage in database
675 675
 				$staticErrors = [];
676 676
 				foreach ($errors as $error) {
677
-					echo $error['error'] . "\n";
678
-					echo $error['hint'] . "\n\n";
677
+					echo $error['error']."\n";
678
+					echo $error['hint']."\n\n";
679 679
 					$staticErrors[] = [
680
-						'error' => (string)$error['error'],
681
-						'hint' => (string)$error['hint'],
680
+						'error' => (string) $error['error'],
681
+						'hint' => (string) $error['hint'],
682 682
 					];
683 683
 				}
684 684
 
@@ -694,7 +694,7 @@  discard block
 block discarded – undo
694 694
 		}
695 695
 		//try to set the session lifetime
696 696
 		$sessionLifeTime = self::getSessionLifeTime();
697
-		@ini_set('gc_maxlifetime', (string)$sessionLifeTime);
697
+		@ini_set('gc_maxlifetime', (string) $sessionLifeTime);
698 698
 
699 699
 		$systemConfig = \OC::$server->getSystemConfig();
700 700
 
@@ -745,7 +745,7 @@  discard block
 block discarded – undo
745 745
 		register_shutdown_function([$lockProvider, 'releaseAll']);
746 746
 
747 747
 		// Check whether the sample configuration has been copied
748
-		if($systemConfig->getValue('copied_sample_config', false)) {
748
+		if ($systemConfig->getValue('copied_sample_config', false)) {
749 749
 			$l = \OC::$server->getL10N('lib');
750 750
 			OC_Template::printErrorPage(
751 751
 				$l->t('Sample configuration detected'),
@@ -767,11 +767,11 @@  discard block
 block discarded – undo
767 767
 		) {
768 768
 			// Allow access to CSS resources
769 769
 			$isScssRequest = false;
770
-			if(strpos($request->getPathInfo(), '/css/') === 0) {
770
+			if (strpos($request->getPathInfo(), '/css/') === 0) {
771 771
 				$isScssRequest = true;
772 772
 			}
773 773
 
774
-			if(substr($request->getRequestUri(), -11) === '/status.php') {
774
+			if (substr($request->getRequestUri(), -11) === '/status.php') {
775 775
 				http_response_code(400);
776 776
 				header('Content-Type: application/json');
777 777
 				echo '{"error": "Trusted domain error.", "code": 15}';
@@ -809,7 +809,7 @@  discard block
 block discarded – undo
809 809
 
810 810
 			// NOTE: This will be replaced to use OCP
811 811
 			$userSession = self::$server->getUserSession();
812
-			$userSession->listen('\OC\User', 'postLogin', function () use ($userSession) {
812
+			$userSession->listen('\OC\User', 'postLogin', function() use ($userSession) {
813 813
 				if (!defined('PHPUNIT_RUN')) {
814 814
 					// reset brute force delay for this IP address and username
815 815
 					$uid = \OC::$server->getUserSession()->getUser()->getUID();
@@ -861,7 +861,7 @@  discard block
 block discarded – undo
861 861
 
862 862
 	private static function registerAppRestrictionsHooks() {
863 863
 		$groupManager = self::$server->query(\OCP\IGroupManager::class);
864
-		$groupManager->listen ('\OC\Group', 'postDelete', function (\OCP\IGroup $group) {
864
+		$groupManager->listen('\OC\Group', 'postDelete', function(\OCP\IGroup $group) {
865 865
 			$appManager = self::$server->getAppManager();
866 866
 			$apps = $appManager->getEnabledAppsForGroup($group);
867 867
 			foreach ($apps as $appId) {
@@ -875,7 +875,7 @@  discard block
 block discarded – undo
875 875
 				if (empty($restrictions)) {
876 876
 					$appManager->disableApp($appId);
877 877
 				}
878
-				else{
878
+				else {
879 879
 					$appManager->enableAppForGroups($appId, $restrictions);
880 880
 				}
881 881
 
@@ -971,12 +971,12 @@  discard block
 block discarded – undo
971 971
 		// emergency app disabling
972 972
 		if ($requestPath === '/disableapp'
973 973
 			&& $request->getMethod() === 'POST'
974
-			&& ((array)$request->getParam('appid')) !== ''
974
+			&& ((array) $request->getParam('appid')) !== ''
975 975
 		) {
976 976
 			\OC_JSON::callCheck();
977 977
 			\OC_JSON::checkAdminUser();
978
-			$appIds = (array)$request->getParam('appid');
979
-			foreach($appIds as $appId) {
978
+			$appIds = (array) $request->getParam('appid');
979
+			foreach ($appIds as $appId) {
980 980
 				$appId = \OC_App::cleanAppId($appId);
981 981
 				\OC::$server->getAppManager()->disableApp($appId);
982 982
 			}
@@ -991,7 +991,7 @@  discard block
 block discarded – undo
991 991
 		if (!\OCP\Util::needUpgrade()
992 992
 			&& !((bool) $systemConfig->getValue('maintenance', false))) {
993 993
 			// For logged-in users: Load everything
994
-			if(\OC::$server->getUserSession()->isLoggedIn()) {
994
+			if (\OC::$server->getUserSession()->isLoggedIn()) {
995 995
 				OC_App::loadApps();
996 996
 			} else {
997 997
 				// For guests: Load only filesystem and logging
Please login to merge, or discard this patch.
lib/private/Config.php 2 patches
Indentation   +199 added lines, -199 removed lines patch added patch discarded remove patch
@@ -42,229 +42,229 @@
 block discarded – undo
42 42
  */
43 43
 class Config {
44 44
 
45
-	const ENV_PREFIX = 'NC_';
45
+    const ENV_PREFIX = 'NC_';
46 46
 
47
-	/** @var array Associative array ($key => $value) */
48
-	protected $cache = [];
49
-	/** @var string */
50
-	protected $configDir;
51
-	/** @var string */
52
-	protected $configFilePath;
53
-	/** @var string */
54
-	protected $configFileName;
47
+    /** @var array Associative array ($key => $value) */
48
+    protected $cache = [];
49
+    /** @var string */
50
+    protected $configDir;
51
+    /** @var string */
52
+    protected $configFilePath;
53
+    /** @var string */
54
+    protected $configFileName;
55 55
 
56
-	/**
57
-	 * @param string $configDir Path to the config dir, needs to end with '/'
58
-	 * @param string $fileName (Optional) Name of the config file. Defaults to config.php
59
-	 */
60
-	public function __construct($configDir, $fileName = 'config.php') {
61
-		$this->configDir = $configDir;
62
-		$this->configFilePath = $this->configDir.$fileName;
63
-		$this->configFileName = $fileName;
64
-		$this->readData();
65
-	}
56
+    /**
57
+     * @param string $configDir Path to the config dir, needs to end with '/'
58
+     * @param string $fileName (Optional) Name of the config file. Defaults to config.php
59
+     */
60
+    public function __construct($configDir, $fileName = 'config.php') {
61
+        $this->configDir = $configDir;
62
+        $this->configFilePath = $this->configDir.$fileName;
63
+        $this->configFileName = $fileName;
64
+        $this->readData();
65
+    }
66 66
 
67
-	/**
68
-	 * Lists all available config keys
69
-	 *
70
-	 * Please note that it does not return the values.
71
-	 *
72
-	 * @return array an array of key names
73
-	 */
74
-	public function getKeys() {
75
-		return array_keys($this->cache);
76
-	}
67
+    /**
68
+     * Lists all available config keys
69
+     *
70
+     * Please note that it does not return the values.
71
+     *
72
+     * @return array an array of key names
73
+     */
74
+    public function getKeys() {
75
+        return array_keys($this->cache);
76
+    }
77 77
 
78
-	/**
79
-	 * Returns a config value
80
-	 *
81
-	 * gets its value from an `NC_` prefixed environment variable
82
-	 * if it doesn't exist from config.php
83
-	 * if this doesn't exist either, it will return the given `$default`
84
-	 *
85
-	 * @param string $key key
86
-	 * @param mixed $default = null default value
87
-	 * @return mixed the value or $default
88
-	 */
89
-	public function getValue($key, $default = null) {
90
-		$envValue = getenv(self::ENV_PREFIX . $key);
91
-		if ($envValue !== false) {
92
-			return $envValue;
93
-		}
78
+    /**
79
+     * Returns a config value
80
+     *
81
+     * gets its value from an `NC_` prefixed environment variable
82
+     * if it doesn't exist from config.php
83
+     * if this doesn't exist either, it will return the given `$default`
84
+     *
85
+     * @param string $key key
86
+     * @param mixed $default = null default value
87
+     * @return mixed the value or $default
88
+     */
89
+    public function getValue($key, $default = null) {
90
+        $envValue = getenv(self::ENV_PREFIX . $key);
91
+        if ($envValue !== false) {
92
+            return $envValue;
93
+        }
94 94
 
95
-		if (isset($this->cache[$key])) {
96
-			return $this->cache[$key];
97
-		}
95
+        if (isset($this->cache[$key])) {
96
+            return $this->cache[$key];
97
+        }
98 98
 
99
-		return $default;
100
-	}
99
+        return $default;
100
+    }
101 101
 
102
-	/**
103
-	 * Sets and deletes values and writes the config.php
104
-	 *
105
-	 * @param array $configs Associative array with `key => value` pairs
106
-	 *                       If value is null, the config key will be deleted
107
-	 */
108
-	public function setValues(array $configs) {
109
-		$needsUpdate = false;
110
-		foreach ($configs as $key => $value) {
111
-			if ($value !== null) {
112
-				$needsUpdate |= $this->set($key, $value);
113
-			} else {
114
-				$needsUpdate |= $this->delete($key);
115
-			}
116
-		}
102
+    /**
103
+     * Sets and deletes values and writes the config.php
104
+     *
105
+     * @param array $configs Associative array with `key => value` pairs
106
+     *                       If value is null, the config key will be deleted
107
+     */
108
+    public function setValues(array $configs) {
109
+        $needsUpdate = false;
110
+        foreach ($configs as $key => $value) {
111
+            if ($value !== null) {
112
+                $needsUpdate |= $this->set($key, $value);
113
+            } else {
114
+                $needsUpdate |= $this->delete($key);
115
+            }
116
+        }
117 117
 
118
-		if ($needsUpdate) {
119
-			// Write changes
120
-			$this->writeData();
121
-		}
122
-	}
118
+        if ($needsUpdate) {
119
+            // Write changes
120
+            $this->writeData();
121
+        }
122
+    }
123 123
 
124
-	/**
125
-	 * Sets the value and writes it to config.php if required
126
-	 *
127
-	 * @param string $key key
128
-	 * @param mixed $value value
129
-	 */
130
-	public function setValue($key, $value) {
131
-		if ($this->set($key, $value)) {
132
-			// Write changes
133
-			$this->writeData();
134
-		}
135
-	}
124
+    /**
125
+     * Sets the value and writes it to config.php if required
126
+     *
127
+     * @param string $key key
128
+     * @param mixed $value value
129
+     */
130
+    public function setValue($key, $value) {
131
+        if ($this->set($key, $value)) {
132
+            // Write changes
133
+            $this->writeData();
134
+        }
135
+    }
136 136
 
137
-	/**
138
-	 * This function sets the value
139
-	 *
140
-	 * @param string $key key
141
-	 * @param mixed $value value
142
-	 * @return bool True if the file needs to be updated, false otherwise
143
-	 */
144
-	protected function set($key, $value) {
145
-		if (!isset($this->cache[$key]) || $this->cache[$key] !== $value) {
146
-			// Add change
147
-			$this->cache[$key] = $value;
148
-			return true;
149
-		}
137
+    /**
138
+     * This function sets the value
139
+     *
140
+     * @param string $key key
141
+     * @param mixed $value value
142
+     * @return bool True if the file needs to be updated, false otherwise
143
+     */
144
+    protected function set($key, $value) {
145
+        if (!isset($this->cache[$key]) || $this->cache[$key] !== $value) {
146
+            // Add change
147
+            $this->cache[$key] = $value;
148
+            return true;
149
+        }
150 150
 
151
-		return false;
152
-	}
151
+        return false;
152
+    }
153 153
 
154
-	/**
155
-	 * Removes a key from the config and removes it from config.php if required
156
-	 * @param string $key
157
-	 */
158
-	public function deleteKey($key) {
159
-		if ($this->delete($key)) {
160
-			// Write changes
161
-			$this->writeData();
162
-		}
163
-	}
154
+    /**
155
+     * Removes a key from the config and removes it from config.php if required
156
+     * @param string $key
157
+     */
158
+    public function deleteKey($key) {
159
+        if ($this->delete($key)) {
160
+            // Write changes
161
+            $this->writeData();
162
+        }
163
+    }
164 164
 
165
-	/**
166
-	 * This function removes a key from the config
167
-	 *
168
-	 * @param string $key
169
-	 * @return bool True if the file needs to be updated, false otherwise
170
-	 */
171
-	protected function delete($key) {
172
-		if (isset($this->cache[$key])) {
173
-			// Delete key from cache
174
-			unset($this->cache[$key]);
175
-			return true;
176
-		}
177
-		return false;
178
-	}
165
+    /**
166
+     * This function removes a key from the config
167
+     *
168
+     * @param string $key
169
+     * @return bool True if the file needs to be updated, false otherwise
170
+     */
171
+    protected function delete($key) {
172
+        if (isset($this->cache[$key])) {
173
+            // Delete key from cache
174
+            unset($this->cache[$key]);
175
+            return true;
176
+        }
177
+        return false;
178
+    }
179 179
 
180
-	/**
181
-	 * Loads the config file
182
-	 *
183
-	 * Reads the config file and saves it to the cache
184
-	 *
185
-	 * @throws \Exception If no lock could be acquired or the config file has not been found
186
-	 */
187
-	private function readData() {
188
-		// Default config should always get loaded
189
-		$configFiles = [$this->configFilePath];
180
+    /**
181
+     * Loads the config file
182
+     *
183
+     * Reads the config file and saves it to the cache
184
+     *
185
+     * @throws \Exception If no lock could be acquired or the config file has not been found
186
+     */
187
+    private function readData() {
188
+        // Default config should always get loaded
189
+        $configFiles = [$this->configFilePath];
190 190
 
191
-		// Add all files in the config dir ending with the same file name
192
-		$extra = glob($this->configDir.'*.'.$this->configFileName);
193
-		if (is_array($extra)) {
194
-			natsort($extra);
195
-			$configFiles = array_merge($configFiles, $extra);
196
-		}
191
+        // Add all files in the config dir ending with the same file name
192
+        $extra = glob($this->configDir.'*.'.$this->configFileName);
193
+        if (is_array($extra)) {
194
+            natsort($extra);
195
+            $configFiles = array_merge($configFiles, $extra);
196
+        }
197 197
 
198
-		// Include file and merge config
199
-		foreach ($configFiles as $file) {
200
-			$fileExistsAndIsReadable = file_exists($file) && is_readable($file);
201
-			$filePointer = $fileExistsAndIsReadable ? fopen($file, 'r') : false;
202
-			if($file === $this->configFilePath &&
203
-				$filePointer === false) {
204
-				// Opening the main config might not be possible, e.g. if the wrong
205
-				// permissions are set (likely on a new installation)
206
-				continue;
207
-			}
198
+        // Include file and merge config
199
+        foreach ($configFiles as $file) {
200
+            $fileExistsAndIsReadable = file_exists($file) && is_readable($file);
201
+            $filePointer = $fileExistsAndIsReadable ? fopen($file, 'r') : false;
202
+            if($file === $this->configFilePath &&
203
+                $filePointer === false) {
204
+                // Opening the main config might not be possible, e.g. if the wrong
205
+                // permissions are set (likely on a new installation)
206
+                continue;
207
+            }
208 208
 
209
-			// Try to acquire a file lock
210
-			if(!flock($filePointer, LOCK_SH)) {
211
-				throw new \Exception(sprintf('Could not acquire a shared lock on the config file %s', $file));
212
-			}
209
+            // Try to acquire a file lock
210
+            if(!flock($filePointer, LOCK_SH)) {
211
+                throw new \Exception(sprintf('Could not acquire a shared lock on the config file %s', $file));
212
+            }
213 213
 
214
-			unset($CONFIG);
215
-			include $file;
216
-			if(isset($CONFIG) && is_array($CONFIG)) {
217
-				$this->cache = array_merge($this->cache, $CONFIG);
218
-			}
214
+            unset($CONFIG);
215
+            include $file;
216
+            if(isset($CONFIG) && is_array($CONFIG)) {
217
+                $this->cache = array_merge($this->cache, $CONFIG);
218
+            }
219 219
 
220
-			// Close the file pointer and release the lock
221
-			flock($filePointer, LOCK_UN);
222
-			fclose($filePointer);
223
-		}
224
-	}
220
+            // Close the file pointer and release the lock
221
+            flock($filePointer, LOCK_UN);
222
+            fclose($filePointer);
223
+        }
224
+    }
225 225
 
226
-	/**
227
-	 * Writes the config file
228
-	 *
229
-	 * Saves the config to the config file.
230
-	 *
231
-	 * @throws HintException If the config file cannot be written to
232
-	 * @throws \Exception If no file lock can be acquired
233
-	 */
234
-	private function writeData() {
235
-		// Create a php file ...
236
-		$content = "<?php\n";
237
-		$content .= '$CONFIG = ';
238
-		$content .= var_export($this->cache, true);
239
-		$content .= ";\n";
226
+    /**
227
+     * Writes the config file
228
+     *
229
+     * Saves the config to the config file.
230
+     *
231
+     * @throws HintException If the config file cannot be written to
232
+     * @throws \Exception If no file lock can be acquired
233
+     */
234
+    private function writeData() {
235
+        // Create a php file ...
236
+        $content = "<?php\n";
237
+        $content .= '$CONFIG = ';
238
+        $content .= var_export($this->cache, true);
239
+        $content .= ";\n";
240 240
 
241
-		touch ($this->configFilePath);
242
-		$filePointer = fopen($this->configFilePath, 'r+');
241
+        touch ($this->configFilePath);
242
+        $filePointer = fopen($this->configFilePath, 'r+');
243 243
 
244
-		// Prevent others not to read the config
245
-		chmod($this->configFilePath, 0640);
244
+        // Prevent others not to read the config
245
+        chmod($this->configFilePath, 0640);
246 246
 
247
-		// File does not exist, this can happen when doing a fresh install
248
-		if(!is_resource ($filePointer)) {
249
-			throw new HintException(
250
-				"Can't write into config directory!",
251
-				'This can usually be fixed by giving the webserver write access to the config directory.');
252
-		}
247
+        // File does not exist, this can happen when doing a fresh install
248
+        if(!is_resource ($filePointer)) {
249
+            throw new HintException(
250
+                "Can't write into config directory!",
251
+                'This can usually be fixed by giving the webserver write access to the config directory.');
252
+        }
253 253
 
254
-		// Try to acquire a file lock
255
-		if(!flock($filePointer, LOCK_EX)) {
256
-			throw new \Exception(sprintf('Could not acquire an exclusive lock on the config file %s', $this->configFilePath));
257
-		}
254
+        // Try to acquire a file lock
255
+        if(!flock($filePointer, LOCK_EX)) {
256
+            throw new \Exception(sprintf('Could not acquire an exclusive lock on the config file %s', $this->configFilePath));
257
+        }
258 258
 
259
-		// Write the config and release the lock
260
-		ftruncate ($filePointer, 0);
261
-		fwrite($filePointer, $content);
262
-		fflush($filePointer);
263
-		flock($filePointer, LOCK_UN);
264
-		fclose($filePointer);
259
+        // Write the config and release the lock
260
+        ftruncate ($filePointer, 0);
261
+        fwrite($filePointer, $content);
262
+        fflush($filePointer);
263
+        flock($filePointer, LOCK_UN);
264
+        fclose($filePointer);
265 265
 
266
-		if (function_exists('opcache_invalidate')) {
267
-			@opcache_invalidate($this->configFilePath, true);
268
-		}
269
-	}
266
+        if (function_exists('opcache_invalidate')) {
267
+            @opcache_invalidate($this->configFilePath, true);
268
+        }
269
+    }
270 270
 }
Please login to merge, or discard this patch.
Spacing   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -87,7 +87,7 @@  discard block
 block discarded – undo
87 87
 	 * @return mixed the value or $default
88 88
 	 */
89 89
 	public function getValue($key, $default = null) {
90
-		$envValue = getenv(self::ENV_PREFIX . $key);
90
+		$envValue = getenv(self::ENV_PREFIX.$key);
91 91
 		if ($envValue !== false) {
92 92
 			return $envValue;
93 93
 		}
@@ -199,7 +199,7 @@  discard block
 block discarded – undo
199 199
 		foreach ($configFiles as $file) {
200 200
 			$fileExistsAndIsReadable = file_exists($file) && is_readable($file);
201 201
 			$filePointer = $fileExistsAndIsReadable ? fopen($file, 'r') : false;
202
-			if($file === $this->configFilePath &&
202
+			if ($file === $this->configFilePath &&
203 203
 				$filePointer === false) {
204 204
 				// Opening the main config might not be possible, e.g. if the wrong
205 205
 				// permissions are set (likely on a new installation)
@@ -207,13 +207,13 @@  discard block
 block discarded – undo
207 207
 			}
208 208
 
209 209
 			// Try to acquire a file lock
210
-			if(!flock($filePointer, LOCK_SH)) {
210
+			if (!flock($filePointer, LOCK_SH)) {
211 211
 				throw new \Exception(sprintf('Could not acquire a shared lock on the config file %s', $file));
212 212
 			}
213 213
 
214 214
 			unset($CONFIG);
215 215
 			include $file;
216
-			if(isset($CONFIG) && is_array($CONFIG)) {
216
+			if (isset($CONFIG) && is_array($CONFIG)) {
217 217
 				$this->cache = array_merge($this->cache, $CONFIG);
218 218
 			}
219 219
 
@@ -238,26 +238,26 @@  discard block
 block discarded – undo
238 238
 		$content .= var_export($this->cache, true);
239 239
 		$content .= ";\n";
240 240
 
241
-		touch ($this->configFilePath);
241
+		touch($this->configFilePath);
242 242
 		$filePointer = fopen($this->configFilePath, 'r+');
243 243
 
244 244
 		// Prevent others not to read the config
245 245
 		chmod($this->configFilePath, 0640);
246 246
 
247 247
 		// File does not exist, this can happen when doing a fresh install
248
-		if(!is_resource ($filePointer)) {
248
+		if (!is_resource($filePointer)) {
249 249
 			throw new HintException(
250 250
 				"Can't write into config directory!",
251 251
 				'This can usually be fixed by giving the webserver write access to the config directory.');
252 252
 		}
253 253
 
254 254
 		// Try to acquire a file lock
255
-		if(!flock($filePointer, LOCK_EX)) {
255
+		if (!flock($filePointer, LOCK_EX)) {
256 256
 			throw new \Exception(sprintf('Could not acquire an exclusive lock on the config file %s', $this->configFilePath));
257 257
 		}
258 258
 
259 259
 		// Write the config and release the lock
260
-		ftruncate ($filePointer, 0);
260
+		ftruncate($filePointer, 0);
261 261
 		fwrite($filePointer, $content);
262 262
 		fflush($filePointer);
263 263
 		flock($filePointer, LOCK_UN);
Please login to merge, or discard this patch.
lib/private/legacy/util.php 1 patch
Indentation   +1394 added lines, -1394 removed lines patch added patch discarded remove patch
@@ -69,1404 +69,1404 @@
 block discarded – undo
69 69
 use OCP\IUser;
70 70
 
71 71
 class OC_Util {
72
-	public static $scripts = [];
73
-	public static $styles = [];
74
-	public static $headers = [];
75
-	private static $rootMounted = false;
76
-	private static $fsSetup = false;
77
-
78
-	/** @var array Local cache of version.php */
79
-	private static $versionCache = null;
80
-
81
-	protected static function getAppManager() {
82
-		return \OC::$server->getAppManager();
83
-	}
84
-
85
-	private static function initLocalStorageRootFS() {
86
-		// mount local file backend as root
87
-		$configDataDirectory = \OC::$server->getSystemConfig()->getValue("datadirectory", OC::$SERVERROOT . "/data");
88
-		//first set up the local "root" storage
89
-		\OC\Files\Filesystem::initMountManager();
90
-		if (!self::$rootMounted) {
91
-			\OC\Files\Filesystem::mount('\OC\Files\Storage\Local', ['datadir' => $configDataDirectory], '/');
92
-			self::$rootMounted = true;
93
-		}
94
-	}
95
-
96
-	/**
97
-	 * mounting an object storage as the root fs will in essence remove the
98
-	 * necessity of a data folder being present.
99
-	 * TODO make home storage aware of this and use the object storage instead of local disk access
100
-	 *
101
-	 * @param array $config containing 'class' and optional 'arguments'
102
-	 * @suppress PhanDeprecatedFunction
103
-	 */
104
-	private static function initObjectStoreRootFS($config) {
105
-		// check misconfiguration
106
-		if (empty($config['class'])) {
107
-			\OCP\Util::writeLog('files', 'No class given for objectstore', ILogger::ERROR);
108
-		}
109
-		if (!isset($config['arguments'])) {
110
-			$config['arguments'] = [];
111
-		}
112
-
113
-		// instantiate object store implementation
114
-		$name = $config['class'];
115
-		if (strpos($name, 'OCA\\') === 0 && substr_count($name, '\\') >= 2) {
116
-			$segments = explode('\\', $name);
117
-			OC_App::loadApp(strtolower($segments[1]));
118
-		}
119
-		$config['arguments']['objectstore'] = new $config['class']($config['arguments']);
120
-		// mount with plain / root object store implementation
121
-		$config['class'] = '\OC\Files\ObjectStore\ObjectStoreStorage';
122
-
123
-		// mount object storage as root
124
-		\OC\Files\Filesystem::initMountManager();
125
-		if (!self::$rootMounted) {
126
-			\OC\Files\Filesystem::mount($config['class'], $config['arguments'], '/');
127
-			self::$rootMounted = true;
128
-		}
129
-	}
130
-
131
-	/**
132
-	 * mounting an object storage as the root fs will in essence remove the
133
-	 * necessity of a data folder being present.
134
-	 *
135
-	 * @param array $config containing 'class' and optional 'arguments'
136
-	 * @suppress PhanDeprecatedFunction
137
-	 */
138
-	private static function initObjectStoreMultibucketRootFS($config) {
139
-		// check misconfiguration
140
-		if (empty($config['class'])) {
141
-			\OCP\Util::writeLog('files', 'No class given for objectstore', ILogger::ERROR);
142
-		}
143
-		if (!isset($config['arguments'])) {
144
-			$config['arguments'] = [];
145
-		}
146
-
147
-		// instantiate object store implementation
148
-		$name = $config['class'];
149
-		if (strpos($name, 'OCA\\') === 0 && substr_count($name, '\\') >= 2) {
150
-			$segments = explode('\\', $name);
151
-			OC_App::loadApp(strtolower($segments[1]));
152
-		}
153
-
154
-		if (!isset($config['arguments']['bucket'])) {
155
-			$config['arguments']['bucket'] = '';
156
-		}
157
-		// put the root FS always in first bucket for multibucket configuration
158
-		$config['arguments']['bucket'] .= '0';
159
-
160
-		$config['arguments']['objectstore'] = new $config['class']($config['arguments']);
161
-		// mount with plain / root object store implementation
162
-		$config['class'] = '\OC\Files\ObjectStore\ObjectStoreStorage';
163
-
164
-		// mount object storage as root
165
-		\OC\Files\Filesystem::initMountManager();
166
-		if (!self::$rootMounted) {
167
-			\OC\Files\Filesystem::mount($config['class'], $config['arguments'], '/');
168
-			self::$rootMounted = true;
169
-		}
170
-	}
171
-
172
-	/**
173
-	 * Can be set up
174
-	 *
175
-	 * @param string $user
176
-	 * @return boolean
177
-	 * @description configure the initial filesystem based on the configuration
178
-	 * @suppress PhanDeprecatedFunction
179
-	 * @suppress PhanAccessMethodInternal
180
-	 */
181
-	public static function setupFS($user = '') {
182
-		//setting up the filesystem twice can only lead to trouble
183
-		if (self::$fsSetup) {
184
-			return false;
185
-		}
186
-
187
-		\OC::$server->getEventLogger()->start('setup_fs', 'Setup filesystem');
188
-
189
-		// If we are not forced to load a specific user we load the one that is logged in
190
-		if ($user === null) {
191
-			$user = '';
192
-		} else if ($user == "" && \OC::$server->getUserSession()->isLoggedIn()) {
193
-			$user = OC_User::getUser();
194
-		}
195
-
196
-		// load all filesystem apps before, so no setup-hook gets lost
197
-		OC_App::loadApps(['filesystem']);
198
-
199
-		// the filesystem will finish when $user is not empty,
200
-		// mark fs setup here to avoid doing the setup from loading
201
-		// OC_Filesystem
202
-		if ($user != '') {
203
-			self::$fsSetup = true;
204
-		}
205
-
206
-		\OC\Files\Filesystem::initMountManager();
207
-
208
-		$prevLogging = \OC\Files\Filesystem::logWarningWhenAddingStorageWrapper(false);
209
-		\OC\Files\Filesystem::addStorageWrapper('mount_options', function ($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) {
210
-			if ($storage->instanceOfStorage('\OC\Files\Storage\Common')) {
211
-				/** @var \OC\Files\Storage\Common $storage */
212
-				$storage->setMountOptions($mount->getOptions());
213
-			}
214
-			return $storage;
215
-		});
216
-
217
-		\OC\Files\Filesystem::addStorageWrapper('enable_sharing', function ($mountPoint, \OCP\Files\Storage\IStorage $storage, \OCP\Files\Mount\IMountPoint $mount) {
218
-			if (!$mount->getOption('enable_sharing', true)) {
219
-				return new \OC\Files\Storage\Wrapper\PermissionsMask([
220
-					'storage' => $storage,
221
-					'mask' => \OCP\Constants::PERMISSION_ALL - \OCP\Constants::PERMISSION_SHARE
222
-				]);
223
-			}
224
-			return $storage;
225
-		});
226
-
227
-		// install storage availability wrapper, before most other wrappers
228
-		\OC\Files\Filesystem::addStorageWrapper('oc_availability', function ($mountPoint, \OCP\Files\Storage\IStorage $storage) {
229
-			if (!$storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage') && !$storage->isLocal()) {
230
-				return new \OC\Files\Storage\Wrapper\Availability(['storage' => $storage]);
231
-			}
232
-			return $storage;
233
-		});
234
-
235
-		\OC\Files\Filesystem::addStorageWrapper('oc_encoding', function ($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) {
236
-			if ($mount->getOption('encoding_compatibility', false) && !$storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage') && !$storage->isLocal()) {
237
-				return new \OC\Files\Storage\Wrapper\Encoding(['storage' => $storage]);
238
-			}
239
-			return $storage;
240
-		});
241
-
242
-		\OC\Files\Filesystem::addStorageWrapper('oc_quota', function ($mountPoint, $storage) {
243
-			// set up quota for home storages, even for other users
244
-			// which can happen when using sharing
245
-
246
-			/**
247
-			 * @var \OC\Files\Storage\Storage $storage
248
-			 */
249
-			if ($storage->instanceOfStorage('\OC\Files\Storage\Home')
250
-				|| $storage->instanceOfStorage('\OC\Files\ObjectStore\HomeObjectStoreStorage')
251
-			) {
252
-				/** @var \OC\Files\Storage\Home $storage */
253
-				if (is_object($storage->getUser())) {
254
-					$user = $storage->getUser()->getUID();
255
-					$quota = OC_Util::getUserQuota($user);
256
-					if ($quota !== \OCP\Files\FileInfo::SPACE_UNLIMITED) {
257
-						return new \OC\Files\Storage\Wrapper\Quota(['storage' => $storage, 'quota' => $quota, 'root' => 'files']);
258
-					}
259
-				}
260
-			}
261
-
262
-			return $storage;
263
-		});
264
-
265
-		\OC\Files\Filesystem::addStorageWrapper('readonly', function ($mountPoint, \OCP\Files\Storage\IStorage $storage, \OCP\Files\Mount\IMountPoint $mount) {
266
-			/*
72
+    public static $scripts = [];
73
+    public static $styles = [];
74
+    public static $headers = [];
75
+    private static $rootMounted = false;
76
+    private static $fsSetup = false;
77
+
78
+    /** @var array Local cache of version.php */
79
+    private static $versionCache = null;
80
+
81
+    protected static function getAppManager() {
82
+        return \OC::$server->getAppManager();
83
+    }
84
+
85
+    private static function initLocalStorageRootFS() {
86
+        // mount local file backend as root
87
+        $configDataDirectory = \OC::$server->getSystemConfig()->getValue("datadirectory", OC::$SERVERROOT . "/data");
88
+        //first set up the local "root" storage
89
+        \OC\Files\Filesystem::initMountManager();
90
+        if (!self::$rootMounted) {
91
+            \OC\Files\Filesystem::mount('\OC\Files\Storage\Local', ['datadir' => $configDataDirectory], '/');
92
+            self::$rootMounted = true;
93
+        }
94
+    }
95
+
96
+    /**
97
+     * mounting an object storage as the root fs will in essence remove the
98
+     * necessity of a data folder being present.
99
+     * TODO make home storage aware of this and use the object storage instead of local disk access
100
+     *
101
+     * @param array $config containing 'class' and optional 'arguments'
102
+     * @suppress PhanDeprecatedFunction
103
+     */
104
+    private static function initObjectStoreRootFS($config) {
105
+        // check misconfiguration
106
+        if (empty($config['class'])) {
107
+            \OCP\Util::writeLog('files', 'No class given for objectstore', ILogger::ERROR);
108
+        }
109
+        if (!isset($config['arguments'])) {
110
+            $config['arguments'] = [];
111
+        }
112
+
113
+        // instantiate object store implementation
114
+        $name = $config['class'];
115
+        if (strpos($name, 'OCA\\') === 0 && substr_count($name, '\\') >= 2) {
116
+            $segments = explode('\\', $name);
117
+            OC_App::loadApp(strtolower($segments[1]));
118
+        }
119
+        $config['arguments']['objectstore'] = new $config['class']($config['arguments']);
120
+        // mount with plain / root object store implementation
121
+        $config['class'] = '\OC\Files\ObjectStore\ObjectStoreStorage';
122
+
123
+        // mount object storage as root
124
+        \OC\Files\Filesystem::initMountManager();
125
+        if (!self::$rootMounted) {
126
+            \OC\Files\Filesystem::mount($config['class'], $config['arguments'], '/');
127
+            self::$rootMounted = true;
128
+        }
129
+    }
130
+
131
+    /**
132
+     * mounting an object storage as the root fs will in essence remove the
133
+     * necessity of a data folder being present.
134
+     *
135
+     * @param array $config containing 'class' and optional 'arguments'
136
+     * @suppress PhanDeprecatedFunction
137
+     */
138
+    private static function initObjectStoreMultibucketRootFS($config) {
139
+        // check misconfiguration
140
+        if (empty($config['class'])) {
141
+            \OCP\Util::writeLog('files', 'No class given for objectstore', ILogger::ERROR);
142
+        }
143
+        if (!isset($config['arguments'])) {
144
+            $config['arguments'] = [];
145
+        }
146
+
147
+        // instantiate object store implementation
148
+        $name = $config['class'];
149
+        if (strpos($name, 'OCA\\') === 0 && substr_count($name, '\\') >= 2) {
150
+            $segments = explode('\\', $name);
151
+            OC_App::loadApp(strtolower($segments[1]));
152
+        }
153
+
154
+        if (!isset($config['arguments']['bucket'])) {
155
+            $config['arguments']['bucket'] = '';
156
+        }
157
+        // put the root FS always in first bucket for multibucket configuration
158
+        $config['arguments']['bucket'] .= '0';
159
+
160
+        $config['arguments']['objectstore'] = new $config['class']($config['arguments']);
161
+        // mount with plain / root object store implementation
162
+        $config['class'] = '\OC\Files\ObjectStore\ObjectStoreStorage';
163
+
164
+        // mount object storage as root
165
+        \OC\Files\Filesystem::initMountManager();
166
+        if (!self::$rootMounted) {
167
+            \OC\Files\Filesystem::mount($config['class'], $config['arguments'], '/');
168
+            self::$rootMounted = true;
169
+        }
170
+    }
171
+
172
+    /**
173
+     * Can be set up
174
+     *
175
+     * @param string $user
176
+     * @return boolean
177
+     * @description configure the initial filesystem based on the configuration
178
+     * @suppress PhanDeprecatedFunction
179
+     * @suppress PhanAccessMethodInternal
180
+     */
181
+    public static function setupFS($user = '') {
182
+        //setting up the filesystem twice can only lead to trouble
183
+        if (self::$fsSetup) {
184
+            return false;
185
+        }
186
+
187
+        \OC::$server->getEventLogger()->start('setup_fs', 'Setup filesystem');
188
+
189
+        // If we are not forced to load a specific user we load the one that is logged in
190
+        if ($user === null) {
191
+            $user = '';
192
+        } else if ($user == "" && \OC::$server->getUserSession()->isLoggedIn()) {
193
+            $user = OC_User::getUser();
194
+        }
195
+
196
+        // load all filesystem apps before, so no setup-hook gets lost
197
+        OC_App::loadApps(['filesystem']);
198
+
199
+        // the filesystem will finish when $user is not empty,
200
+        // mark fs setup here to avoid doing the setup from loading
201
+        // OC_Filesystem
202
+        if ($user != '') {
203
+            self::$fsSetup = true;
204
+        }
205
+
206
+        \OC\Files\Filesystem::initMountManager();
207
+
208
+        $prevLogging = \OC\Files\Filesystem::logWarningWhenAddingStorageWrapper(false);
209
+        \OC\Files\Filesystem::addStorageWrapper('mount_options', function ($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) {
210
+            if ($storage->instanceOfStorage('\OC\Files\Storage\Common')) {
211
+                /** @var \OC\Files\Storage\Common $storage */
212
+                $storage->setMountOptions($mount->getOptions());
213
+            }
214
+            return $storage;
215
+        });
216
+
217
+        \OC\Files\Filesystem::addStorageWrapper('enable_sharing', function ($mountPoint, \OCP\Files\Storage\IStorage $storage, \OCP\Files\Mount\IMountPoint $mount) {
218
+            if (!$mount->getOption('enable_sharing', true)) {
219
+                return new \OC\Files\Storage\Wrapper\PermissionsMask([
220
+                    'storage' => $storage,
221
+                    'mask' => \OCP\Constants::PERMISSION_ALL - \OCP\Constants::PERMISSION_SHARE
222
+                ]);
223
+            }
224
+            return $storage;
225
+        });
226
+
227
+        // install storage availability wrapper, before most other wrappers
228
+        \OC\Files\Filesystem::addStorageWrapper('oc_availability', function ($mountPoint, \OCP\Files\Storage\IStorage $storage) {
229
+            if (!$storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage') && !$storage->isLocal()) {
230
+                return new \OC\Files\Storage\Wrapper\Availability(['storage' => $storage]);
231
+            }
232
+            return $storage;
233
+        });
234
+
235
+        \OC\Files\Filesystem::addStorageWrapper('oc_encoding', function ($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) {
236
+            if ($mount->getOption('encoding_compatibility', false) && !$storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage') && !$storage->isLocal()) {
237
+                return new \OC\Files\Storage\Wrapper\Encoding(['storage' => $storage]);
238
+            }
239
+            return $storage;
240
+        });
241
+
242
+        \OC\Files\Filesystem::addStorageWrapper('oc_quota', function ($mountPoint, $storage) {
243
+            // set up quota for home storages, even for other users
244
+            // which can happen when using sharing
245
+
246
+            /**
247
+             * @var \OC\Files\Storage\Storage $storage
248
+             */
249
+            if ($storage->instanceOfStorage('\OC\Files\Storage\Home')
250
+                || $storage->instanceOfStorage('\OC\Files\ObjectStore\HomeObjectStoreStorage')
251
+            ) {
252
+                /** @var \OC\Files\Storage\Home $storage */
253
+                if (is_object($storage->getUser())) {
254
+                    $user = $storage->getUser()->getUID();
255
+                    $quota = OC_Util::getUserQuota($user);
256
+                    if ($quota !== \OCP\Files\FileInfo::SPACE_UNLIMITED) {
257
+                        return new \OC\Files\Storage\Wrapper\Quota(['storage' => $storage, 'quota' => $quota, 'root' => 'files']);
258
+                    }
259
+                }
260
+            }
261
+
262
+            return $storage;
263
+        });
264
+
265
+        \OC\Files\Filesystem::addStorageWrapper('readonly', function ($mountPoint, \OCP\Files\Storage\IStorage $storage, \OCP\Files\Mount\IMountPoint $mount) {
266
+            /*
267 267
 			 * Do not allow any operations that modify the storage
268 268
 			 */
269
-			if ($mount->getOption('readonly', false)) {
270
-				return new \OC\Files\Storage\Wrapper\PermissionsMask([
271
-					'storage' => $storage,
272
-					'mask' => \OCP\Constants::PERMISSION_ALL & ~(
273
-						\OCP\Constants::PERMISSION_UPDATE |
274
-						\OCP\Constants::PERMISSION_CREATE |
275
-						\OCP\Constants::PERMISSION_DELETE
276
-					),
277
-				]);
278
-			}
279
-			return $storage;
280
-		});
281
-
282
-		OC_Hook::emit('OC_Filesystem', 'preSetup', ['user' => $user]);
283
-
284
-		\OC\Files\Filesystem::logWarningWhenAddingStorageWrapper($prevLogging);
285
-
286
-		//check if we are using an object storage
287
-		$objectStore = \OC::$server->getSystemConfig()->getValue('objectstore', null);
288
-		$objectStoreMultibucket = \OC::$server->getSystemConfig()->getValue('objectstore_multibucket', null);
289
-
290
-		// use the same order as in ObjectHomeMountProvider
291
-		if (isset($objectStoreMultibucket)) {
292
-			self::initObjectStoreMultibucketRootFS($objectStoreMultibucket);
293
-		} elseif (isset($objectStore)) {
294
-			self::initObjectStoreRootFS($objectStore);
295
-		} else {
296
-			self::initLocalStorageRootFS();
297
-		}
298
-
299
-		if ($user != '' && !\OC::$server->getUserManager()->userExists($user)) {
300
-			\OC::$server->getEventLogger()->end('setup_fs');
301
-			return false;
302
-		}
303
-
304
-		//if we aren't logged in, there is no use to set up the filesystem
305
-		if ($user != "") {
306
-
307
-			$userDir = '/' . $user . '/files';
308
-
309
-			//jail the user into his "home" directory
310
-			\OC\Files\Filesystem::init($user, $userDir);
311
-
312
-			OC_Hook::emit('OC_Filesystem', 'setup', ['user' => $user, 'user_dir' => $userDir]);
313
-		}
314
-		\OC::$server->getEventLogger()->end('setup_fs');
315
-		return true;
316
-	}
317
-
318
-	/**
319
-	 * check if a password is required for each public link
320
-	 *
321
-	 * @return boolean
322
-	 * @suppress PhanDeprecatedFunction
323
-	 */
324
-	public static function isPublicLinkPasswordRequired() {
325
-		$enforcePassword = \OC::$server->getConfig()->getAppValue('core', 'shareapi_enforce_links_password', 'no');
326
-		return $enforcePassword === 'yes';
327
-	}
328
-
329
-	/**
330
-	 * check if sharing is disabled for the current user
331
-	 * @param IConfig $config
332
-	 * @param IGroupManager $groupManager
333
-	 * @param IUser|null $user
334
-	 * @return bool
335
-	 */
336
-	public static function isSharingDisabledForUser(IConfig $config, IGroupManager $groupManager, $user) {
337
-		if ($config->getAppValue('core', 'shareapi_exclude_groups', 'no') === 'yes') {
338
-			$groupsList = $config->getAppValue('core', 'shareapi_exclude_groups_list', '');
339
-			$excludedGroups = json_decode($groupsList);
340
-			if (is_null($excludedGroups)) {
341
-				$excludedGroups = explode(',', $groupsList);
342
-				$newValue = json_encode($excludedGroups);
343
-				$config->setAppValue('core', 'shareapi_exclude_groups_list', $newValue);
344
-			}
345
-			$usersGroups = $groupManager->getUserGroupIds($user);
346
-			if (!empty($usersGroups)) {
347
-				$remainingGroups = array_diff($usersGroups, $excludedGroups);
348
-				// if the user is only in groups which are disabled for sharing then
349
-				// sharing is also disabled for the user
350
-				if (empty($remainingGroups)) {
351
-					return true;
352
-				}
353
-			}
354
-		}
355
-		return false;
356
-	}
357
-
358
-	/**
359
-	 * check if share API enforces a default expire date
360
-	 *
361
-	 * @return boolean
362
-	 * @suppress PhanDeprecatedFunction
363
-	 */
364
-	public static function isDefaultExpireDateEnforced() {
365
-		$isDefaultExpireDateEnabled = \OC::$server->getConfig()->getAppValue('core', 'shareapi_default_expire_date', 'no');
366
-		$enforceDefaultExpireDate = false;
367
-		if ($isDefaultExpireDateEnabled === 'yes') {
368
-			$value = \OC::$server->getConfig()->getAppValue('core', 'shareapi_enforce_expire_date', 'no');
369
-			$enforceDefaultExpireDate = $value === 'yes';
370
-		}
371
-
372
-		return $enforceDefaultExpireDate;
373
-	}
374
-
375
-	/**
376
-	 * Get the quota of a user
377
-	 *
378
-	 * @param string $userId
379
-	 * @return float Quota bytes
380
-	 */
381
-	public static function getUserQuota($userId) {
382
-		$user = \OC::$server->getUserManager()->get($userId);
383
-		if (is_null($user)) {
384
-			return \OCP\Files\FileInfo::SPACE_UNLIMITED;
385
-		}
386
-		$userQuota = $user->getQuota();
387
-		if($userQuota === 'none') {
388
-			return \OCP\Files\FileInfo::SPACE_UNLIMITED;
389
-		}
390
-		return OC_Helper::computerFileSize($userQuota);
391
-	}
392
-
393
-	/**
394
-	 * copies the skeleton to the users /files
395
-	 *
396
-	 * @param string $userId
397
-	 * @param \OCP\Files\Folder $userDirectory
398
-	 * @throws \OCP\Files\NotFoundException
399
-	 * @throws \OCP\Files\NotPermittedException
400
-	 * @suppress PhanDeprecatedFunction
401
-	 */
402
-	public static function copySkeleton($userId, \OCP\Files\Folder $userDirectory) {
403
-
404
-		$plainSkeletonDirectory = \OC::$server->getConfig()->getSystemValue('skeletondirectory', \OC::$SERVERROOT . '/core/skeleton');
405
-		$userLang = \OC::$server->getL10NFactory()->findLanguage();
406
-		$skeletonDirectory = str_replace('{lang}', $userLang, $plainSkeletonDirectory);
407
-
408
-		if (!file_exists($skeletonDirectory)) {
409
-			$dialectStart = strpos($userLang, '_');
410
-			if ($dialectStart !== false) {
411
-				$skeletonDirectory = str_replace('{lang}', substr($userLang, 0, $dialectStart), $plainSkeletonDirectory);
412
-			}
413
-			if ($dialectStart === false || !file_exists($skeletonDirectory)) {
414
-				$skeletonDirectory = str_replace('{lang}', 'default', $plainSkeletonDirectory);
415
-			}
416
-			if (!file_exists($skeletonDirectory)) {
417
-				$skeletonDirectory = '';
418
-			}
419
-		}
420
-
421
-		$instanceId = \OC::$server->getConfig()->getSystemValue('instanceid', '');
422
-
423
-		if ($instanceId === null) {
424
-			throw new \RuntimeException('no instance id!');
425
-		}
426
-		$appdata = 'appdata_' . $instanceId;
427
-		if ($userId === $appdata) {
428
-			throw new \RuntimeException('username is reserved name: ' . $appdata);
429
-		}
430
-
431
-		if (!empty($skeletonDirectory)) {
432
-			\OCP\Util::writeLog(
433
-				'files_skeleton',
434
-				'copying skeleton for '.$userId.' from '.$skeletonDirectory.' to '.$userDirectory->getFullPath('/'),
435
-				ILogger::DEBUG
436
-			);
437
-			self::copyr($skeletonDirectory, $userDirectory);
438
-			// update the file cache
439
-			$userDirectory->getStorage()->getScanner()->scan('', \OC\Files\Cache\Scanner::SCAN_RECURSIVE);
440
-		}
441
-	}
442
-
443
-	/**
444
-	 * copies a directory recursively by using streams
445
-	 *
446
-	 * @param string $source
447
-	 * @param \OCP\Files\Folder $target
448
-	 * @return void
449
-	 */
450
-	public static function copyr($source, \OCP\Files\Folder $target) {
451
-		$logger = \OC::$server->getLogger();
452
-
453
-		// Verify if folder exists
454
-		$dir = opendir($source);
455
-		if($dir === false) {
456
-			$logger->error(sprintf('Could not opendir "%s"', $source), ['app' => 'core']);
457
-			return;
458
-		}
459
-
460
-		// Copy the files
461
-		while (false !== ($file = readdir($dir))) {
462
-			if (!\OC\Files\Filesystem::isIgnoredDir($file)) {
463
-				if (is_dir($source . '/' . $file)) {
464
-					$child = $target->newFolder($file);
465
-					self::copyr($source . '/' . $file, $child);
466
-				} else {
467
-					$child = $target->newFile($file);
468
-					$sourceStream = fopen($source . '/' . $file, 'r');
469
-					if($sourceStream === false) {
470
-						$logger->error(sprintf('Could not fopen "%s"', $source . '/' . $file), ['app' => 'core']);
471
-						closedir($dir);
472
-						return;
473
-					}
474
-					stream_copy_to_stream($sourceStream, $child->fopen('w'));
475
-				}
476
-			}
477
-		}
478
-		closedir($dir);
479
-	}
480
-
481
-	/**
482
-	 * @return void
483
-	 * @suppress PhanUndeclaredMethod
484
-	 */
485
-	public static function tearDownFS() {
486
-		\OC\Files\Filesystem::tearDown();
487
-		\OC::$server->getRootFolder()->clearCache();
488
-		self::$fsSetup = false;
489
-		self::$rootMounted = false;
490
-	}
491
-
492
-	/**
493
-	 * get the current installed version of ownCloud
494
-	 *
495
-	 * @return array
496
-	 */
497
-	public static function getVersion() {
498
-		OC_Util::loadVersion();
499
-		return self::$versionCache['OC_Version'];
500
-	}
501
-
502
-	/**
503
-	 * get the current installed version string of ownCloud
504
-	 *
505
-	 * @return string
506
-	 */
507
-	public static function getVersionString() {
508
-		OC_Util::loadVersion();
509
-		return self::$versionCache['OC_VersionString'];
510
-	}
511
-
512
-	/**
513
-	 * @deprecated the value is of no use anymore
514
-	 * @return string
515
-	 */
516
-	public static function getEditionString() {
517
-		return '';
518
-	}
519
-
520
-	/**
521
-	 * @description get the update channel of the current installed of ownCloud.
522
-	 * @return string
523
-	 */
524
-	public static function getChannel() {
525
-		OC_Util::loadVersion();
526
-		return \OC::$server->getConfig()->getSystemValue('updater.release.channel', self::$versionCache['OC_Channel']);
527
-	}
528
-
529
-	/**
530
-	 * @description get the build number of the current installed of ownCloud.
531
-	 * @return string
532
-	 */
533
-	public static function getBuild() {
534
-		OC_Util::loadVersion();
535
-		return self::$versionCache['OC_Build'];
536
-	}
537
-
538
-	/**
539
-	 * @description load the version.php into the session as cache
540
-	 * @suppress PhanUndeclaredVariable
541
-	 */
542
-	private static function loadVersion() {
543
-		if (self::$versionCache !== null) {
544
-			return;
545
-		}
546
-
547
-		$timestamp = filemtime(OC::$SERVERROOT . '/version.php');
548
-		require OC::$SERVERROOT . '/version.php';
549
-		/** @var $timestamp int */
550
-		self::$versionCache['OC_Version_Timestamp'] = $timestamp;
551
-		/** @var $OC_Version string */
552
-		self::$versionCache['OC_Version'] = $OC_Version;
553
-		/** @var $OC_VersionString string */
554
-		self::$versionCache['OC_VersionString'] = $OC_VersionString;
555
-		/** @var $OC_Build string */
556
-		self::$versionCache['OC_Build'] = $OC_Build;
557
-
558
-		/** @var $OC_Channel string */
559
-		self::$versionCache['OC_Channel'] = $OC_Channel;
560
-	}
561
-
562
-	/**
563
-	 * generates a path for JS/CSS files. If no application is provided it will create the path for core.
564
-	 *
565
-	 * @param string $application application to get the files from
566
-	 * @param string $directory directory within this application (css, js, vendor, etc)
567
-	 * @param string $file the file inside of the above folder
568
-	 * @return string the path
569
-	 */
570
-	private static function generatePath($application, $directory, $file) {
571
-		if (is_null($file)) {
572
-			$file = $application;
573
-			$application = "";
574
-		}
575
-		if (!empty($application)) {
576
-			return "$application/$directory/$file";
577
-		} else {
578
-			return "$directory/$file";
579
-		}
580
-	}
581
-
582
-	/**
583
-	 * add a javascript file
584
-	 *
585
-	 * @param string $application application id
586
-	 * @param string|null $file filename
587
-	 * @param bool $prepend prepend the Script to the beginning of the list
588
-	 * @return void
589
-	 */
590
-	public static function addScript($application, $file = null, $prepend = false) {
591
-		$path = OC_Util::generatePath($application, 'js', $file);
592
-
593
-		// core js files need separate handling
594
-		if ($application !== 'core' && $file !== null) {
595
-			self::addTranslations ( $application );
596
-		}
597
-		self::addExternalResource($application, $prepend, $path, "script");
598
-	}
599
-
600
-	/**
601
-	 * add a javascript file from the vendor sub folder
602
-	 *
603
-	 * @param string $application application id
604
-	 * @param string|null $file filename
605
-	 * @param bool $prepend prepend the Script to the beginning of the list
606
-	 * @return void
607
-	 */
608
-	public static function addVendorScript($application, $file = null, $prepend = false) {
609
-		$path = OC_Util::generatePath($application, 'vendor', $file);
610
-		self::addExternalResource($application, $prepend, $path, "script");
611
-	}
612
-
613
-	/**
614
-	 * add a translation JS file
615
-	 *
616
-	 * @param string $application application id
617
-	 * @param string|null $languageCode language code, defaults to the current language
618
-	 * @param bool|null $prepend prepend the Script to the beginning of the list
619
-	 */
620
-	public static function addTranslations($application, $languageCode = null, $prepend = false) {
621
-		if (is_null($languageCode)) {
622
-			$languageCode = \OC::$server->getL10NFactory()->findLanguage($application);
623
-		}
624
-		if (!empty($application)) {
625
-			$path = "$application/l10n/$languageCode";
626
-		} else {
627
-			$path = "l10n/$languageCode";
628
-		}
629
-		self::addExternalResource($application, $prepend, $path, "script");
630
-	}
631
-
632
-	/**
633
-	 * add a css file
634
-	 *
635
-	 * @param string $application application id
636
-	 * @param string|null $file filename
637
-	 * @param bool $prepend prepend the Style to the beginning of the list
638
-	 * @return void
639
-	 */
640
-	public static function addStyle($application, $file = null, $prepend = false) {
641
-		$path = OC_Util::generatePath($application, 'css', $file);
642
-		self::addExternalResource($application, $prepend, $path, "style");
643
-	}
644
-
645
-	/**
646
-	 * add a css file from the vendor sub folder
647
-	 *
648
-	 * @param string $application application id
649
-	 * @param string|null $file filename
650
-	 * @param bool $prepend prepend the Style to the beginning of the list
651
-	 * @return void
652
-	 */
653
-	public static function addVendorStyle($application, $file = null, $prepend = false) {
654
-		$path = OC_Util::generatePath($application, 'vendor', $file);
655
-		self::addExternalResource($application, $prepend, $path, "style");
656
-	}
657
-
658
-	/**
659
-	 * add an external resource css/js file
660
-	 *
661
-	 * @param string $application application id
662
-	 * @param bool $prepend prepend the file to the beginning of the list
663
-	 * @param string $path
664
-	 * @param string $type (script or style)
665
-	 * @return void
666
-	 */
667
-	private static function addExternalResource($application, $prepend, $path, $type = "script") {
668
-
669
-		if ($type === "style") {
670
-			if (!in_array($path, self::$styles)) {
671
-				if ($prepend === true) {
672
-					array_unshift ( self::$styles, $path );
673
-				} else {
674
-					self::$styles[] = $path;
675
-				}
676
-			}
677
-		} elseif ($type === "script") {
678
-			if (!in_array($path, self::$scripts)) {
679
-				if ($prepend === true) {
680
-					array_unshift ( self::$scripts, $path );
681
-				} else {
682
-					self::$scripts [] = $path;
683
-				}
684
-			}
685
-		}
686
-	}
687
-
688
-	/**
689
-	 * Add a custom element to the header
690
-	 * If $text is null then the element will be written as empty element.
691
-	 * So use "" to get a closing tag.
692
-	 * @param string $tag tag name of the element
693
-	 * @param array $attributes array of attributes for the element
694
-	 * @param string $text the text content for the element
695
-	 * @param bool $prepend prepend the header to the beginning of the list
696
-	 */
697
-	public static function addHeader($tag, $attributes, $text = null, $prepend = false) {
698
-		$header = [
699
-			'tag' => $tag,
700
-			'attributes' => $attributes,
701
-			'text' => $text
702
-		];
703
-		if ($prepend === true) {
704
-			array_unshift (self::$headers, $header);
705
-
706
-		} else {
707
-			self::$headers[] = $header;
708
-		}
709
-	}
710
-
711
-	/**
712
-	 * check if the current server configuration is suitable for ownCloud
713
-	 *
714
-	 * @param \OC\SystemConfig $config
715
-	 * @return array arrays with error messages and hints
716
-	 */
717
-	public static function checkServer(\OC\SystemConfig $config) {
718
-		$l = \OC::$server->getL10N('lib');
719
-		$errors = [];
720
-		$CONFIG_DATADIRECTORY = $config->getValue('datadirectory', OC::$SERVERROOT . '/data');
721
-
722
-		if (!self::needUpgrade($config) && $config->getValue('installed', false)) {
723
-			// this check needs to be done every time
724
-			$errors = self::checkDataDirectoryValidity($CONFIG_DATADIRECTORY);
725
-		}
726
-
727
-		// Assume that if checkServer() succeeded before in this session, then all is fine.
728
-		if (\OC::$server->getSession()->exists('checkServer_succeeded') && \OC::$server->getSession()->get('checkServer_succeeded')) {
729
-			return $errors;
730
-		}
731
-
732
-		$webServerRestart = false;
733
-		$setup = new \OC\Setup(
734
-			$config,
735
-			\OC::$server->getIniWrapper(),
736
-			\OC::$server->getL10N('lib'),
737
-			\OC::$server->query(\OCP\Defaults::class),
738
-			\OC::$server->getLogger(),
739
-			\OC::$server->getSecureRandom(),
740
-			\OC::$server->query(\OC\Installer::class)
741
-		);
742
-
743
-		$urlGenerator = \OC::$server->getURLGenerator();
744
-
745
-		$availableDatabases = $setup->getSupportedDatabases();
746
-		if (empty($availableDatabases)) {
747
-			$errors[] = [
748
-				'error' => $l->t('No database drivers (sqlite, mysql, or postgresql) installed.'),
749
-				'hint' => '' //TODO: sane hint
750
-			];
751
-			$webServerRestart = true;
752
-		}
753
-
754
-		// Check if config folder is writable.
755
-		if(!OC_Helper::isReadOnlyConfigEnabled()) {
756
-			if (!is_writable(OC::$configDir) or !is_readable(OC::$configDir)) {
757
-				$errors[] = [
758
-					'error' => $l->t('Cannot write into "config" directory'),
759
-					'hint' => $l->t('This can usually be fixed by giving the webserver write access to the config directory. See %s',
760
-						[ $urlGenerator->linkToDocs('admin-dir_permissions') ]) . '. '
761
-						. $l->t('Or, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it. See %s',
762
-						[ $urlGenerator->linkToDocs('admin-config') ] )
763
-				];
764
-			}
765
-		}
766
-
767
-		// Check if there is a writable install folder.
768
-		if ($config->getValue('appstoreenabled', true)) {
769
-			if (OC_App::getInstallPath() === null
770
-				|| !is_writable(OC_App::getInstallPath())
771
-				|| !is_readable(OC_App::getInstallPath())
772
-			) {
773
-				$errors[] = [
774
-					'error' => $l->t('Cannot write into "apps" directory'),
775
-					'hint' => $l->t('This can usually be fixed by giving the webserver write access to the apps directory'
776
-						. ' or disabling the appstore in the config file.')
777
-				];
778
-			}
779
-		}
780
-		// Create root dir.
781
-		if ($config->getValue('installed', false)) {
782
-			if (!is_dir($CONFIG_DATADIRECTORY)) {
783
-				$success = @mkdir($CONFIG_DATADIRECTORY);
784
-				if ($success) {
785
-					$errors = array_merge($errors, self::checkDataDirectoryPermissions($CONFIG_DATADIRECTORY));
786
-				} else {
787
-					$errors[] = [
788
-						'error' => $l->t('Cannot create "data" directory'),
789
-						'hint' => $l->t('This can usually be fixed by giving the webserver write access to the root directory. See %s',
790
-							[$urlGenerator->linkToDocs('admin-dir_permissions')])
791
-					];
792
-				}
793
-			} else if (!is_writable($CONFIG_DATADIRECTORY) or !is_readable($CONFIG_DATADIRECTORY)) {
794
-				// is_writable doesn't work for NFS mounts, so try to write a file and check if it exists.
795
-				$testFile = sprintf('%s/%s.tmp', $CONFIG_DATADIRECTORY, uniqid('data_dir_writability_test_'));
796
-				$handle = fopen($testFile, 'w');
797
-				if (!$handle || fwrite($handle, 'Test write operation') === false) {
798
-					$permissionsHint = $l->t('Permissions can usually be fixed by giving the webserver write access to the root directory. See %s.',
799
-						[$urlGenerator->linkToDocs('admin-dir_permissions')]);
800
-					$errors[] = [
801
-						'error' => 'Your data directory is not writable',
802
-						'hint' => $permissionsHint
803
-					];
804
-				} else {
805
-					fclose($handle);
806
-					unlink($testFile);
807
-				}
808
-			} else {
809
-				$errors = array_merge($errors, self::checkDataDirectoryPermissions($CONFIG_DATADIRECTORY));
810
-			}
811
-		}
812
-
813
-		if (!OC_Util::isSetLocaleWorking()) {
814
-			$errors[] = [
815
-				'error' => $l->t('Setting locale to %s failed',
816
-					['en_US.UTF-8/fr_FR.UTF-8/es_ES.UTF-8/de_DE.UTF-8/ru_RU.UTF-8/'
817
-						. 'pt_BR.UTF-8/it_IT.UTF-8/ja_JP.UTF-8/zh_CN.UTF-8']),
818
-				'hint' => $l->t('Please install one of these locales on your system and restart your webserver.')
819
-			];
820
-		}
821
-
822
-		// Contains the dependencies that should be checked against
823
-		// classes = class_exists
824
-		// functions = function_exists
825
-		// defined = defined
826
-		// ini = ini_get
827
-		// If the dependency is not found the missing module name is shown to the EndUser
828
-		// When adding new checks always verify that they pass on Travis as well
829
-		// for ini settings, see https://github.com/owncloud/administration/blob/master/travis-ci/custom.ini
830
-		$dependencies = [
831
-			'classes' => [
832
-				'ZipArchive' => 'zip',
833
-				'DOMDocument' => 'dom',
834
-				'XMLWriter' => 'XMLWriter',
835
-				'XMLReader' => 'XMLReader',
836
-			],
837
-			'functions' => [
838
-				'xml_parser_create' => 'libxml',
839
-				'mb_strcut' => 'mbstring',
840
-				'ctype_digit' => 'ctype',
841
-				'json_encode' => 'JSON',
842
-				'gd_info' => 'GD',
843
-				'gzencode' => 'zlib',
844
-				'iconv' => 'iconv',
845
-				'simplexml_load_string' => 'SimpleXML',
846
-				'hash' => 'HASH Message Digest Framework',
847
-				'curl_init' => 'cURL',
848
-				'openssl_verify' => 'OpenSSL',
849
-			],
850
-			'defined' => [
851
-				'PDO::ATTR_DRIVER_NAME' => 'PDO'
852
-			],
853
-			'ini' => [
854
-				'default_charset' => 'UTF-8',
855
-			],
856
-		];
857
-		$missingDependencies = [];
858
-		$invalidIniSettings = [];
859
-		$moduleHint = $l->t('Please ask your server administrator to install the module.');
860
-
861
-		$iniWrapper = \OC::$server->getIniWrapper();
862
-		foreach ($dependencies['classes'] as $class => $module) {
863
-			if (!class_exists($class)) {
864
-				$missingDependencies[] = $module;
865
-			}
866
-		}
867
-		foreach ($dependencies['functions'] as $function => $module) {
868
-			if (!function_exists($function)) {
869
-				$missingDependencies[] = $module;
870
-			}
871
-		}
872
-		foreach ($dependencies['defined'] as $defined => $module) {
873
-			if (!defined($defined)) {
874
-				$missingDependencies[] = $module;
875
-			}
876
-		}
877
-		foreach ($dependencies['ini'] as $setting => $expected) {
878
-			if (is_bool($expected)) {
879
-				if ($iniWrapper->getBool($setting) !== $expected) {
880
-					$invalidIniSettings[] = [$setting, $expected];
881
-				}
882
-			}
883
-			if (is_int($expected)) {
884
-				if ($iniWrapper->getNumeric($setting) !== $expected) {
885
-					$invalidIniSettings[] = [$setting, $expected];
886
-				}
887
-			}
888
-			if (is_string($expected)) {
889
-				if (strtolower($iniWrapper->getString($setting)) !== strtolower($expected)) {
890
-					$invalidIniSettings[] = [$setting, $expected];
891
-				}
892
-			}
893
-		}
894
-
895
-		foreach($missingDependencies as $missingDependency) {
896
-			$errors[] = [
897
-				'error' => $l->t('PHP module %s not installed.', [$missingDependency]),
898
-				'hint' => $moduleHint
899
-			];
900
-			$webServerRestart = true;
901
-		}
902
-		foreach($invalidIniSettings as $setting) {
903
-			if(is_bool($setting[1])) {
904
-				$setting[1] = $setting[1] ? 'on' : 'off';
905
-			}
906
-			$errors[] = [
907
-				'error' => $l->t('PHP setting "%s" is not set to "%s".', [$setting[0], var_export($setting[1], true)]),
908
-				'hint' =>  $l->t('Adjusting this setting in php.ini will make Nextcloud run again')
909
-			];
910
-			$webServerRestart = true;
911
-		}
912
-
913
-		/**
914
-		 * The mbstring.func_overload check can only be performed if the mbstring
915
-		 * module is installed as it will return null if the checking setting is
916
-		 * not available and thus a check on the boolean value fails.
917
-		 *
918
-		 * TODO: Should probably be implemented in the above generic dependency
919
-		 *       check somehow in the long-term.
920
-		 */
921
-		if($iniWrapper->getBool('mbstring.func_overload') !== null &&
922
-			$iniWrapper->getBool('mbstring.func_overload') === true) {
923
-			$errors[] = [
924
-				'error' => $l->t('mbstring.func_overload is set to "%s" instead of the expected value "0"', [$iniWrapper->getString('mbstring.func_overload')]),
925
-				'hint' => $l->t('To fix this issue set <code>mbstring.func_overload</code> to <code>0</code> in your php.ini')
926
-			];
927
-		}
928
-
929
-		if(function_exists('xml_parser_create') &&
930
-			LIBXML_LOADED_VERSION < 20700 ) {
931
-			$version = LIBXML_LOADED_VERSION;
932
-			$major = floor($version/10000);
933
-			$version -= ($major * 10000);
934
-			$minor = floor($version/100);
935
-			$version -= ($minor * 100);
936
-			$patch = $version;
937
-			$errors[] = [
938
-				'error' => $l->t('libxml2 2.7.0 is at least required. Currently %s is installed.', [$major . '.' . $minor . '.' . $patch]),
939
-				'hint' => $l->t('To fix this issue update your libxml2 version and restart your web server.')
940
-			];
941
-		}
942
-
943
-		if (!self::isAnnotationsWorking()) {
944
-			$errors[] = [
945
-				'error' => $l->t('PHP is apparently set up to strip inline doc blocks. This will make several core apps inaccessible.'),
946
-				'hint' => $l->t('This is probably caused by a cache/accelerator such as Zend OPcache or eAccelerator.')
947
-			];
948
-		}
949
-
950
-		if (!\OC::$CLI && $webServerRestart) {
951
-			$errors[] = [
952
-				'error' => $l->t('PHP modules have been installed, but they are still listed as missing?'),
953
-				'hint' => $l->t('Please ask your server administrator to restart the web server.')
954
-			];
955
-		}
956
-
957
-		$errors = array_merge($errors, self::checkDatabaseVersion());
958
-
959
-		// Cache the result of this function
960
-		\OC::$server->getSession()->set('checkServer_succeeded', count($errors) == 0);
961
-
962
-		return $errors;
963
-	}
964
-
965
-	/**
966
-	 * Check the database version
967
-	 *
968
-	 * @return array errors array
969
-	 */
970
-	public static function checkDatabaseVersion() {
971
-		$l = \OC::$server->getL10N('lib');
972
-		$errors = [];
973
-		$dbType = \OC::$server->getSystemConfig()->getValue('dbtype', 'sqlite');
974
-		if ($dbType === 'pgsql') {
975
-			// check PostgreSQL version
976
-			try {
977
-				$result = \OC_DB::executeAudited('SHOW SERVER_VERSION');
978
-				$data = $result->fetchRow();
979
-				if (isset($data['server_version'])) {
980
-					$version = $data['server_version'];
981
-					if (version_compare($version, '9.0.0', '<')) {
982
-						$errors[] = [
983
-							'error' => $l->t('PostgreSQL >= 9 required'),
984
-							'hint' => $l->t('Please upgrade your database version')
985
-						];
986
-					}
987
-				}
988
-			} catch (\Doctrine\DBAL\DBALException $e) {
989
-				$logger = \OC::$server->getLogger();
990
-				$logger->warning('Error occurred while checking PostgreSQL version, assuming >= 9');
991
-				$logger->logException($e);
992
-			}
993
-		}
994
-		return $errors;
995
-	}
996
-
997
-	/**
998
-	 * Check for correct file permissions of data directory
999
-	 *
1000
-	 * @param string $dataDirectory
1001
-	 * @return array arrays with error messages and hints
1002
-	 */
1003
-	public static function checkDataDirectoryPermissions($dataDirectory) {
1004
-		if(\OC::$server->getConfig()->getSystemValue('check_data_directory_permissions', true) === false) {
1005
-			return  [];
1006
-		}
1007
-		$l = \OC::$server->getL10N('lib');
1008
-		$errors = [];
1009
-		$permissionsModHint = $l->t('Please change the permissions to 0770 so that the directory'
1010
-			. ' cannot be listed by other users.');
1011
-		$perms = substr(decoct(@fileperms($dataDirectory)), -3);
1012
-		if (substr($perms, -1) !== '0') {
1013
-			chmod($dataDirectory, 0770);
1014
-			clearstatcache();
1015
-			$perms = substr(decoct(@fileperms($dataDirectory)), -3);
1016
-			if ($perms[2] !== '0') {
1017
-				$errors[] = [
1018
-					'error' => $l->t('Your data directory is readable by other users'),
1019
-					'hint' => $permissionsModHint
1020
-				];
1021
-			}
1022
-		}
1023
-		return $errors;
1024
-	}
1025
-
1026
-	/**
1027
-	 * Check that the data directory exists and is valid by
1028
-	 * checking the existence of the ".ocdata" file.
1029
-	 *
1030
-	 * @param string $dataDirectory data directory path
1031
-	 * @return array errors found
1032
-	 */
1033
-	public static function checkDataDirectoryValidity($dataDirectory) {
1034
-		$l = \OC::$server->getL10N('lib');
1035
-		$errors = [];
1036
-		if ($dataDirectory[0] !== '/') {
1037
-			$errors[] = [
1038
-				'error' => $l->t('Your data directory must be an absolute path'),
1039
-				'hint' => $l->t('Check the value of "datadirectory" in your configuration')
1040
-			];
1041
-		}
1042
-		if (!file_exists($dataDirectory . '/.ocdata')) {
1043
-			$errors[] = [
1044
-				'error' => $l->t('Your data directory is invalid'),
1045
-				'hint' => $l->t('Ensure there is a file called ".ocdata"' .
1046
-					' in the root of the data directory.')
1047
-			];
1048
-		}
1049
-		return $errors;
1050
-	}
1051
-
1052
-	/**
1053
-	 * Check if the user is logged in, redirects to home if not. With
1054
-	 * redirect URL parameter to the request URI.
1055
-	 *
1056
-	 * @return void
1057
-	 */
1058
-	public static function checkLoggedIn() {
1059
-		// Check if we are a user
1060
-		if (!\OC::$server->getUserSession()->isLoggedIn()) {
1061
-			header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute(
1062
-						'core.login.showLoginForm',
1063
-						[
1064
-							'redirect_url' => \OC::$server->getRequest()->getRequestUri(),
1065
-						]
1066
-					)
1067
-			);
1068
-			exit();
1069
-		}
1070
-		// Redirect to 2FA challenge selection if 2FA challenge was not solved yet
1071
-		if (\OC::$server->getTwoFactorAuthManager()->needsSecondFactor(\OC::$server->getUserSession()->getUser())) {
1072
-			header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute('core.TwoFactorChallenge.selectChallenge'));
1073
-			exit();
1074
-		}
1075
-	}
1076
-
1077
-	/**
1078
-	 * Check if the user is a admin, redirects to home if not
1079
-	 *
1080
-	 * @return void
1081
-	 */
1082
-	public static function checkAdminUser() {
1083
-		OC_Util::checkLoggedIn();
1084
-		if (!OC_User::isAdminUser(OC_User::getUser())) {
1085
-			header('Location: ' . \OCP\Util::linkToAbsolute('', 'index.php'));
1086
-			exit();
1087
-		}
1088
-	}
1089
-
1090
-	/**
1091
-	 * Returns the URL of the default page
1092
-	 * based on the system configuration and
1093
-	 * the apps visible for the current user
1094
-	 *
1095
-	 * @return string URL
1096
-	 * @suppress PhanDeprecatedFunction
1097
-	 */
1098
-	public static function getDefaultPageUrl() {
1099
-		$urlGenerator = \OC::$server->getURLGenerator();
1100
-		// Deny the redirect if the URL contains a @
1101
-		// This prevents unvalidated redirects like ?redirect_url=:[email protected]
1102
-		if (isset($_REQUEST['redirect_url']) && strpos($_REQUEST['redirect_url'], '@') === false) {
1103
-			$location = $urlGenerator->getAbsoluteURL(urldecode($_REQUEST['redirect_url']));
1104
-		} else {
1105
-			$defaultPage = \OC::$server->getConfig()->getAppValue('core', 'defaultpage');
1106
-			if ($defaultPage) {
1107
-				$location = $urlGenerator->getAbsoluteURL($defaultPage);
1108
-			} else {
1109
-				$appId = 'files';
1110
-				$config = \OC::$server->getConfig();
1111
-				$defaultApps = explode(',', $config->getSystemValue('defaultapp', 'files'));
1112
-				// find the first app that is enabled for the current user
1113
-				foreach ($defaultApps as $defaultApp) {
1114
-					$defaultApp = OC_App::cleanAppId(strip_tags($defaultApp));
1115
-					if (static::getAppManager()->isEnabledForUser($defaultApp)) {
1116
-						$appId = $defaultApp;
1117
-						break;
1118
-					}
1119
-				}
1120
-
1121
-				if($config->getSystemValue('htaccess.IgnoreFrontController', false) === true || getenv('front_controller_active') === 'true') {
1122
-					$location = $urlGenerator->getAbsoluteURL('/apps/' . $appId . '/');
1123
-				} else {
1124
-					$location = $urlGenerator->getAbsoluteURL('/index.php/apps/' . $appId . '/');
1125
-				}
1126
-			}
1127
-		}
1128
-		return $location;
1129
-	}
1130
-
1131
-	/**
1132
-	 * Redirect to the user default page
1133
-	 *
1134
-	 * @return void
1135
-	 */
1136
-	public static function redirectToDefaultPage() {
1137
-		$location = self::getDefaultPageUrl();
1138
-		header('Location: ' . $location);
1139
-		exit();
1140
-	}
1141
-
1142
-	/**
1143
-	 * get an id unique for this instance
1144
-	 *
1145
-	 * @return string
1146
-	 */
1147
-	public static function getInstanceId() {
1148
-		$id = \OC::$server->getSystemConfig()->getValue('instanceid', null);
1149
-		if (is_null($id)) {
1150
-			// We need to guarantee at least one letter in instanceid so it can be used as the session_name
1151
-			$id = 'oc' . \OC::$server->getSecureRandom()->generate(10, \OCP\Security\ISecureRandom::CHAR_LOWER.\OCP\Security\ISecureRandom::CHAR_DIGITS);
1152
-			\OC::$server->getSystemConfig()->setValue('instanceid', $id);
1153
-		}
1154
-		return $id;
1155
-	}
1156
-
1157
-	/**
1158
-	 * Public function to sanitize HTML
1159
-	 *
1160
-	 * This function is used to sanitize HTML and should be applied on any
1161
-	 * string or array of strings before displaying it on a web page.
1162
-	 *
1163
-	 * @param string|array $value
1164
-	 * @return string|array an array of sanitized strings or a single sanitized string, depends on the input parameter.
1165
-	 */
1166
-	public static function sanitizeHTML($value) {
1167
-		if (is_array($value)) {
1168
-			$value = array_map(function($value) {
1169
-				return self::sanitizeHTML($value);
1170
-			}, $value);
1171
-		} else {
1172
-			// Specify encoding for PHP<5.4
1173
-			$value = htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
1174
-		}
1175
-		return $value;
1176
-	}
1177
-
1178
-	/**
1179
-	 * Public function to encode url parameters
1180
-	 *
1181
-	 * This function is used to encode path to file before output.
1182
-	 * Encoding is done according to RFC 3986 with one exception:
1183
-	 * Character '/' is preserved as is.
1184
-	 *
1185
-	 * @param string $component part of URI to encode
1186
-	 * @return string
1187
-	 */
1188
-	public static function encodePath($component) {
1189
-		$encoded = rawurlencode($component);
1190
-		$encoded = str_replace('%2F', '/', $encoded);
1191
-		return $encoded;
1192
-	}
1193
-
1194
-
1195
-	public function createHtaccessTestFile(\OCP\IConfig $config) {
1196
-		// php dev server does not support htaccess
1197
-		if (php_sapi_name() === 'cli-server') {
1198
-			return false;
1199
-		}
1200
-
1201
-		// testdata
1202
-		$fileName = '/htaccesstest.txt';
1203
-		$testContent = 'This is used for testing whether htaccess is properly enabled to disallow access from the outside. This file can be safely removed.';
1204
-
1205
-		// creating a test file
1206
-		$testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
1207
-
1208
-		if (file_exists($testFile)) {// already running this test, possible recursive call
1209
-			return false;
1210
-		}
1211
-
1212
-		$fp = @fopen($testFile, 'w');
1213
-		if (!$fp) {
1214
-			throw new OC\HintException('Can\'t create test file to check for working .htaccess file.',
1215
-				'Make sure it is possible for the webserver to write to ' . $testFile);
1216
-		}
1217
-		fwrite($fp, $testContent);
1218
-		fclose($fp);
1219
-
1220
-		return $testContent;
1221
-	}
1222
-
1223
-	/**
1224
-	 * Check if the .htaccess file is working
1225
-	 * @param \OCP\IConfig $config
1226
-	 * @return bool
1227
-	 * @throws Exception
1228
-	 * @throws \OC\HintException If the test file can't get written.
1229
-	 */
1230
-	public function isHtaccessWorking(\OCP\IConfig $config) {
1231
-
1232
-		if (\OC::$CLI || !$config->getSystemValue('check_for_working_htaccess', true)) {
1233
-			return true;
1234
-		}
1235
-
1236
-		$testContent = $this->createHtaccessTestFile($config);
1237
-		if ($testContent === false) {
1238
-			return false;
1239
-		}
1240
-
1241
-		$fileName = '/htaccesstest.txt';
1242
-		$testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
1243
-
1244
-		// accessing the file via http
1245
-		$url = \OC::$server->getURLGenerator()->getAbsoluteURL(OC::$WEBROOT . '/data' . $fileName);
1246
-		try {
1247
-			$content = \OC::$server->getHTTPClientService()->newClient()->get($url)->getBody();
1248
-		} catch (\Exception $e) {
1249
-			$content = false;
1250
-		}
1251
-
1252
-		if (strpos($url, 'https:') === 0) {
1253
-			$url = 'http:' . substr($url, 6);
1254
-		} else {
1255
-			$url = 'https:' . substr($url, 5);
1256
-		}
1257
-
1258
-		try {
1259
-			$fallbackContent = \OC::$server->getHTTPClientService()->newClient()->get($url)->getBody();
1260
-		} catch (\Exception $e) {
1261
-			$fallbackContent = false;
1262
-		}
1263
-
1264
-		// cleanup
1265
-		@unlink($testFile);
1266
-
1267
-		/*
269
+            if ($mount->getOption('readonly', false)) {
270
+                return new \OC\Files\Storage\Wrapper\PermissionsMask([
271
+                    'storage' => $storage,
272
+                    'mask' => \OCP\Constants::PERMISSION_ALL & ~(
273
+                        \OCP\Constants::PERMISSION_UPDATE |
274
+                        \OCP\Constants::PERMISSION_CREATE |
275
+                        \OCP\Constants::PERMISSION_DELETE
276
+                    ),
277
+                ]);
278
+            }
279
+            return $storage;
280
+        });
281
+
282
+        OC_Hook::emit('OC_Filesystem', 'preSetup', ['user' => $user]);
283
+
284
+        \OC\Files\Filesystem::logWarningWhenAddingStorageWrapper($prevLogging);
285
+
286
+        //check if we are using an object storage
287
+        $objectStore = \OC::$server->getSystemConfig()->getValue('objectstore', null);
288
+        $objectStoreMultibucket = \OC::$server->getSystemConfig()->getValue('objectstore_multibucket', null);
289
+
290
+        // use the same order as in ObjectHomeMountProvider
291
+        if (isset($objectStoreMultibucket)) {
292
+            self::initObjectStoreMultibucketRootFS($objectStoreMultibucket);
293
+        } elseif (isset($objectStore)) {
294
+            self::initObjectStoreRootFS($objectStore);
295
+        } else {
296
+            self::initLocalStorageRootFS();
297
+        }
298
+
299
+        if ($user != '' && !\OC::$server->getUserManager()->userExists($user)) {
300
+            \OC::$server->getEventLogger()->end('setup_fs');
301
+            return false;
302
+        }
303
+
304
+        //if we aren't logged in, there is no use to set up the filesystem
305
+        if ($user != "") {
306
+
307
+            $userDir = '/' . $user . '/files';
308
+
309
+            //jail the user into his "home" directory
310
+            \OC\Files\Filesystem::init($user, $userDir);
311
+
312
+            OC_Hook::emit('OC_Filesystem', 'setup', ['user' => $user, 'user_dir' => $userDir]);
313
+        }
314
+        \OC::$server->getEventLogger()->end('setup_fs');
315
+        return true;
316
+    }
317
+
318
+    /**
319
+     * check if a password is required for each public link
320
+     *
321
+     * @return boolean
322
+     * @suppress PhanDeprecatedFunction
323
+     */
324
+    public static function isPublicLinkPasswordRequired() {
325
+        $enforcePassword = \OC::$server->getConfig()->getAppValue('core', 'shareapi_enforce_links_password', 'no');
326
+        return $enforcePassword === 'yes';
327
+    }
328
+
329
+    /**
330
+     * check if sharing is disabled for the current user
331
+     * @param IConfig $config
332
+     * @param IGroupManager $groupManager
333
+     * @param IUser|null $user
334
+     * @return bool
335
+     */
336
+    public static function isSharingDisabledForUser(IConfig $config, IGroupManager $groupManager, $user) {
337
+        if ($config->getAppValue('core', 'shareapi_exclude_groups', 'no') === 'yes') {
338
+            $groupsList = $config->getAppValue('core', 'shareapi_exclude_groups_list', '');
339
+            $excludedGroups = json_decode($groupsList);
340
+            if (is_null($excludedGroups)) {
341
+                $excludedGroups = explode(',', $groupsList);
342
+                $newValue = json_encode($excludedGroups);
343
+                $config->setAppValue('core', 'shareapi_exclude_groups_list', $newValue);
344
+            }
345
+            $usersGroups = $groupManager->getUserGroupIds($user);
346
+            if (!empty($usersGroups)) {
347
+                $remainingGroups = array_diff($usersGroups, $excludedGroups);
348
+                // if the user is only in groups which are disabled for sharing then
349
+                // sharing is also disabled for the user
350
+                if (empty($remainingGroups)) {
351
+                    return true;
352
+                }
353
+            }
354
+        }
355
+        return false;
356
+    }
357
+
358
+    /**
359
+     * check if share API enforces a default expire date
360
+     *
361
+     * @return boolean
362
+     * @suppress PhanDeprecatedFunction
363
+     */
364
+    public static function isDefaultExpireDateEnforced() {
365
+        $isDefaultExpireDateEnabled = \OC::$server->getConfig()->getAppValue('core', 'shareapi_default_expire_date', 'no');
366
+        $enforceDefaultExpireDate = false;
367
+        if ($isDefaultExpireDateEnabled === 'yes') {
368
+            $value = \OC::$server->getConfig()->getAppValue('core', 'shareapi_enforce_expire_date', 'no');
369
+            $enforceDefaultExpireDate = $value === 'yes';
370
+        }
371
+
372
+        return $enforceDefaultExpireDate;
373
+    }
374
+
375
+    /**
376
+     * Get the quota of a user
377
+     *
378
+     * @param string $userId
379
+     * @return float Quota bytes
380
+     */
381
+    public static function getUserQuota($userId) {
382
+        $user = \OC::$server->getUserManager()->get($userId);
383
+        if (is_null($user)) {
384
+            return \OCP\Files\FileInfo::SPACE_UNLIMITED;
385
+        }
386
+        $userQuota = $user->getQuota();
387
+        if($userQuota === 'none') {
388
+            return \OCP\Files\FileInfo::SPACE_UNLIMITED;
389
+        }
390
+        return OC_Helper::computerFileSize($userQuota);
391
+    }
392
+
393
+    /**
394
+     * copies the skeleton to the users /files
395
+     *
396
+     * @param string $userId
397
+     * @param \OCP\Files\Folder $userDirectory
398
+     * @throws \OCP\Files\NotFoundException
399
+     * @throws \OCP\Files\NotPermittedException
400
+     * @suppress PhanDeprecatedFunction
401
+     */
402
+    public static function copySkeleton($userId, \OCP\Files\Folder $userDirectory) {
403
+
404
+        $plainSkeletonDirectory = \OC::$server->getConfig()->getSystemValue('skeletondirectory', \OC::$SERVERROOT . '/core/skeleton');
405
+        $userLang = \OC::$server->getL10NFactory()->findLanguage();
406
+        $skeletonDirectory = str_replace('{lang}', $userLang, $plainSkeletonDirectory);
407
+
408
+        if (!file_exists($skeletonDirectory)) {
409
+            $dialectStart = strpos($userLang, '_');
410
+            if ($dialectStart !== false) {
411
+                $skeletonDirectory = str_replace('{lang}', substr($userLang, 0, $dialectStart), $plainSkeletonDirectory);
412
+            }
413
+            if ($dialectStart === false || !file_exists($skeletonDirectory)) {
414
+                $skeletonDirectory = str_replace('{lang}', 'default', $plainSkeletonDirectory);
415
+            }
416
+            if (!file_exists($skeletonDirectory)) {
417
+                $skeletonDirectory = '';
418
+            }
419
+        }
420
+
421
+        $instanceId = \OC::$server->getConfig()->getSystemValue('instanceid', '');
422
+
423
+        if ($instanceId === null) {
424
+            throw new \RuntimeException('no instance id!');
425
+        }
426
+        $appdata = 'appdata_' . $instanceId;
427
+        if ($userId === $appdata) {
428
+            throw new \RuntimeException('username is reserved name: ' . $appdata);
429
+        }
430
+
431
+        if (!empty($skeletonDirectory)) {
432
+            \OCP\Util::writeLog(
433
+                'files_skeleton',
434
+                'copying skeleton for '.$userId.' from '.$skeletonDirectory.' to '.$userDirectory->getFullPath('/'),
435
+                ILogger::DEBUG
436
+            );
437
+            self::copyr($skeletonDirectory, $userDirectory);
438
+            // update the file cache
439
+            $userDirectory->getStorage()->getScanner()->scan('', \OC\Files\Cache\Scanner::SCAN_RECURSIVE);
440
+        }
441
+    }
442
+
443
+    /**
444
+     * copies a directory recursively by using streams
445
+     *
446
+     * @param string $source
447
+     * @param \OCP\Files\Folder $target
448
+     * @return void
449
+     */
450
+    public static function copyr($source, \OCP\Files\Folder $target) {
451
+        $logger = \OC::$server->getLogger();
452
+
453
+        // Verify if folder exists
454
+        $dir = opendir($source);
455
+        if($dir === false) {
456
+            $logger->error(sprintf('Could not opendir "%s"', $source), ['app' => 'core']);
457
+            return;
458
+        }
459
+
460
+        // Copy the files
461
+        while (false !== ($file = readdir($dir))) {
462
+            if (!\OC\Files\Filesystem::isIgnoredDir($file)) {
463
+                if (is_dir($source . '/' . $file)) {
464
+                    $child = $target->newFolder($file);
465
+                    self::copyr($source . '/' . $file, $child);
466
+                } else {
467
+                    $child = $target->newFile($file);
468
+                    $sourceStream = fopen($source . '/' . $file, 'r');
469
+                    if($sourceStream === false) {
470
+                        $logger->error(sprintf('Could not fopen "%s"', $source . '/' . $file), ['app' => 'core']);
471
+                        closedir($dir);
472
+                        return;
473
+                    }
474
+                    stream_copy_to_stream($sourceStream, $child->fopen('w'));
475
+                }
476
+            }
477
+        }
478
+        closedir($dir);
479
+    }
480
+
481
+    /**
482
+     * @return void
483
+     * @suppress PhanUndeclaredMethod
484
+     */
485
+    public static function tearDownFS() {
486
+        \OC\Files\Filesystem::tearDown();
487
+        \OC::$server->getRootFolder()->clearCache();
488
+        self::$fsSetup = false;
489
+        self::$rootMounted = false;
490
+    }
491
+
492
+    /**
493
+     * get the current installed version of ownCloud
494
+     *
495
+     * @return array
496
+     */
497
+    public static function getVersion() {
498
+        OC_Util::loadVersion();
499
+        return self::$versionCache['OC_Version'];
500
+    }
501
+
502
+    /**
503
+     * get the current installed version string of ownCloud
504
+     *
505
+     * @return string
506
+     */
507
+    public static function getVersionString() {
508
+        OC_Util::loadVersion();
509
+        return self::$versionCache['OC_VersionString'];
510
+    }
511
+
512
+    /**
513
+     * @deprecated the value is of no use anymore
514
+     * @return string
515
+     */
516
+    public static function getEditionString() {
517
+        return '';
518
+    }
519
+
520
+    /**
521
+     * @description get the update channel of the current installed of ownCloud.
522
+     * @return string
523
+     */
524
+    public static function getChannel() {
525
+        OC_Util::loadVersion();
526
+        return \OC::$server->getConfig()->getSystemValue('updater.release.channel', self::$versionCache['OC_Channel']);
527
+    }
528
+
529
+    /**
530
+     * @description get the build number of the current installed of ownCloud.
531
+     * @return string
532
+     */
533
+    public static function getBuild() {
534
+        OC_Util::loadVersion();
535
+        return self::$versionCache['OC_Build'];
536
+    }
537
+
538
+    /**
539
+     * @description load the version.php into the session as cache
540
+     * @suppress PhanUndeclaredVariable
541
+     */
542
+    private static function loadVersion() {
543
+        if (self::$versionCache !== null) {
544
+            return;
545
+        }
546
+
547
+        $timestamp = filemtime(OC::$SERVERROOT . '/version.php');
548
+        require OC::$SERVERROOT . '/version.php';
549
+        /** @var $timestamp int */
550
+        self::$versionCache['OC_Version_Timestamp'] = $timestamp;
551
+        /** @var $OC_Version string */
552
+        self::$versionCache['OC_Version'] = $OC_Version;
553
+        /** @var $OC_VersionString string */
554
+        self::$versionCache['OC_VersionString'] = $OC_VersionString;
555
+        /** @var $OC_Build string */
556
+        self::$versionCache['OC_Build'] = $OC_Build;
557
+
558
+        /** @var $OC_Channel string */
559
+        self::$versionCache['OC_Channel'] = $OC_Channel;
560
+    }
561
+
562
+    /**
563
+     * generates a path for JS/CSS files. If no application is provided it will create the path for core.
564
+     *
565
+     * @param string $application application to get the files from
566
+     * @param string $directory directory within this application (css, js, vendor, etc)
567
+     * @param string $file the file inside of the above folder
568
+     * @return string the path
569
+     */
570
+    private static function generatePath($application, $directory, $file) {
571
+        if (is_null($file)) {
572
+            $file = $application;
573
+            $application = "";
574
+        }
575
+        if (!empty($application)) {
576
+            return "$application/$directory/$file";
577
+        } else {
578
+            return "$directory/$file";
579
+        }
580
+    }
581
+
582
+    /**
583
+     * add a javascript file
584
+     *
585
+     * @param string $application application id
586
+     * @param string|null $file filename
587
+     * @param bool $prepend prepend the Script to the beginning of the list
588
+     * @return void
589
+     */
590
+    public static function addScript($application, $file = null, $prepend = false) {
591
+        $path = OC_Util::generatePath($application, 'js', $file);
592
+
593
+        // core js files need separate handling
594
+        if ($application !== 'core' && $file !== null) {
595
+            self::addTranslations ( $application );
596
+        }
597
+        self::addExternalResource($application, $prepend, $path, "script");
598
+    }
599
+
600
+    /**
601
+     * add a javascript file from the vendor sub folder
602
+     *
603
+     * @param string $application application id
604
+     * @param string|null $file filename
605
+     * @param bool $prepend prepend the Script to the beginning of the list
606
+     * @return void
607
+     */
608
+    public static function addVendorScript($application, $file = null, $prepend = false) {
609
+        $path = OC_Util::generatePath($application, 'vendor', $file);
610
+        self::addExternalResource($application, $prepend, $path, "script");
611
+    }
612
+
613
+    /**
614
+     * add a translation JS file
615
+     *
616
+     * @param string $application application id
617
+     * @param string|null $languageCode language code, defaults to the current language
618
+     * @param bool|null $prepend prepend the Script to the beginning of the list
619
+     */
620
+    public static function addTranslations($application, $languageCode = null, $prepend = false) {
621
+        if (is_null($languageCode)) {
622
+            $languageCode = \OC::$server->getL10NFactory()->findLanguage($application);
623
+        }
624
+        if (!empty($application)) {
625
+            $path = "$application/l10n/$languageCode";
626
+        } else {
627
+            $path = "l10n/$languageCode";
628
+        }
629
+        self::addExternalResource($application, $prepend, $path, "script");
630
+    }
631
+
632
+    /**
633
+     * add a css file
634
+     *
635
+     * @param string $application application id
636
+     * @param string|null $file filename
637
+     * @param bool $prepend prepend the Style to the beginning of the list
638
+     * @return void
639
+     */
640
+    public static function addStyle($application, $file = null, $prepend = false) {
641
+        $path = OC_Util::generatePath($application, 'css', $file);
642
+        self::addExternalResource($application, $prepend, $path, "style");
643
+    }
644
+
645
+    /**
646
+     * add a css file from the vendor sub folder
647
+     *
648
+     * @param string $application application id
649
+     * @param string|null $file filename
650
+     * @param bool $prepend prepend the Style to the beginning of the list
651
+     * @return void
652
+     */
653
+    public static function addVendorStyle($application, $file = null, $prepend = false) {
654
+        $path = OC_Util::generatePath($application, 'vendor', $file);
655
+        self::addExternalResource($application, $prepend, $path, "style");
656
+    }
657
+
658
+    /**
659
+     * add an external resource css/js file
660
+     *
661
+     * @param string $application application id
662
+     * @param bool $prepend prepend the file to the beginning of the list
663
+     * @param string $path
664
+     * @param string $type (script or style)
665
+     * @return void
666
+     */
667
+    private static function addExternalResource($application, $prepend, $path, $type = "script") {
668
+
669
+        if ($type === "style") {
670
+            if (!in_array($path, self::$styles)) {
671
+                if ($prepend === true) {
672
+                    array_unshift ( self::$styles, $path );
673
+                } else {
674
+                    self::$styles[] = $path;
675
+                }
676
+            }
677
+        } elseif ($type === "script") {
678
+            if (!in_array($path, self::$scripts)) {
679
+                if ($prepend === true) {
680
+                    array_unshift ( self::$scripts, $path );
681
+                } else {
682
+                    self::$scripts [] = $path;
683
+                }
684
+            }
685
+        }
686
+    }
687
+
688
+    /**
689
+     * Add a custom element to the header
690
+     * If $text is null then the element will be written as empty element.
691
+     * So use "" to get a closing tag.
692
+     * @param string $tag tag name of the element
693
+     * @param array $attributes array of attributes for the element
694
+     * @param string $text the text content for the element
695
+     * @param bool $prepend prepend the header to the beginning of the list
696
+     */
697
+    public static function addHeader($tag, $attributes, $text = null, $prepend = false) {
698
+        $header = [
699
+            'tag' => $tag,
700
+            'attributes' => $attributes,
701
+            'text' => $text
702
+        ];
703
+        if ($prepend === true) {
704
+            array_unshift (self::$headers, $header);
705
+
706
+        } else {
707
+            self::$headers[] = $header;
708
+        }
709
+    }
710
+
711
+    /**
712
+     * check if the current server configuration is suitable for ownCloud
713
+     *
714
+     * @param \OC\SystemConfig $config
715
+     * @return array arrays with error messages and hints
716
+     */
717
+    public static function checkServer(\OC\SystemConfig $config) {
718
+        $l = \OC::$server->getL10N('lib');
719
+        $errors = [];
720
+        $CONFIG_DATADIRECTORY = $config->getValue('datadirectory', OC::$SERVERROOT . '/data');
721
+
722
+        if (!self::needUpgrade($config) && $config->getValue('installed', false)) {
723
+            // this check needs to be done every time
724
+            $errors = self::checkDataDirectoryValidity($CONFIG_DATADIRECTORY);
725
+        }
726
+
727
+        // Assume that if checkServer() succeeded before in this session, then all is fine.
728
+        if (\OC::$server->getSession()->exists('checkServer_succeeded') && \OC::$server->getSession()->get('checkServer_succeeded')) {
729
+            return $errors;
730
+        }
731
+
732
+        $webServerRestart = false;
733
+        $setup = new \OC\Setup(
734
+            $config,
735
+            \OC::$server->getIniWrapper(),
736
+            \OC::$server->getL10N('lib'),
737
+            \OC::$server->query(\OCP\Defaults::class),
738
+            \OC::$server->getLogger(),
739
+            \OC::$server->getSecureRandom(),
740
+            \OC::$server->query(\OC\Installer::class)
741
+        );
742
+
743
+        $urlGenerator = \OC::$server->getURLGenerator();
744
+
745
+        $availableDatabases = $setup->getSupportedDatabases();
746
+        if (empty($availableDatabases)) {
747
+            $errors[] = [
748
+                'error' => $l->t('No database drivers (sqlite, mysql, or postgresql) installed.'),
749
+                'hint' => '' //TODO: sane hint
750
+            ];
751
+            $webServerRestart = true;
752
+        }
753
+
754
+        // Check if config folder is writable.
755
+        if(!OC_Helper::isReadOnlyConfigEnabled()) {
756
+            if (!is_writable(OC::$configDir) or !is_readable(OC::$configDir)) {
757
+                $errors[] = [
758
+                    'error' => $l->t('Cannot write into "config" directory'),
759
+                    'hint' => $l->t('This can usually be fixed by giving the webserver write access to the config directory. See %s',
760
+                        [ $urlGenerator->linkToDocs('admin-dir_permissions') ]) . '. '
761
+                        . $l->t('Or, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it. See %s',
762
+                        [ $urlGenerator->linkToDocs('admin-config') ] )
763
+                ];
764
+            }
765
+        }
766
+
767
+        // Check if there is a writable install folder.
768
+        if ($config->getValue('appstoreenabled', true)) {
769
+            if (OC_App::getInstallPath() === null
770
+                || !is_writable(OC_App::getInstallPath())
771
+                || !is_readable(OC_App::getInstallPath())
772
+            ) {
773
+                $errors[] = [
774
+                    'error' => $l->t('Cannot write into "apps" directory'),
775
+                    'hint' => $l->t('This can usually be fixed by giving the webserver write access to the apps directory'
776
+                        . ' or disabling the appstore in the config file.')
777
+                ];
778
+            }
779
+        }
780
+        // Create root dir.
781
+        if ($config->getValue('installed', false)) {
782
+            if (!is_dir($CONFIG_DATADIRECTORY)) {
783
+                $success = @mkdir($CONFIG_DATADIRECTORY);
784
+                if ($success) {
785
+                    $errors = array_merge($errors, self::checkDataDirectoryPermissions($CONFIG_DATADIRECTORY));
786
+                } else {
787
+                    $errors[] = [
788
+                        'error' => $l->t('Cannot create "data" directory'),
789
+                        'hint' => $l->t('This can usually be fixed by giving the webserver write access to the root directory. See %s',
790
+                            [$urlGenerator->linkToDocs('admin-dir_permissions')])
791
+                    ];
792
+                }
793
+            } else if (!is_writable($CONFIG_DATADIRECTORY) or !is_readable($CONFIG_DATADIRECTORY)) {
794
+                // is_writable doesn't work for NFS mounts, so try to write a file and check if it exists.
795
+                $testFile = sprintf('%s/%s.tmp', $CONFIG_DATADIRECTORY, uniqid('data_dir_writability_test_'));
796
+                $handle = fopen($testFile, 'w');
797
+                if (!$handle || fwrite($handle, 'Test write operation') === false) {
798
+                    $permissionsHint = $l->t('Permissions can usually be fixed by giving the webserver write access to the root directory. See %s.',
799
+                        [$urlGenerator->linkToDocs('admin-dir_permissions')]);
800
+                    $errors[] = [
801
+                        'error' => 'Your data directory is not writable',
802
+                        'hint' => $permissionsHint
803
+                    ];
804
+                } else {
805
+                    fclose($handle);
806
+                    unlink($testFile);
807
+                }
808
+            } else {
809
+                $errors = array_merge($errors, self::checkDataDirectoryPermissions($CONFIG_DATADIRECTORY));
810
+            }
811
+        }
812
+
813
+        if (!OC_Util::isSetLocaleWorking()) {
814
+            $errors[] = [
815
+                'error' => $l->t('Setting locale to %s failed',
816
+                    ['en_US.UTF-8/fr_FR.UTF-8/es_ES.UTF-8/de_DE.UTF-8/ru_RU.UTF-8/'
817
+                        . 'pt_BR.UTF-8/it_IT.UTF-8/ja_JP.UTF-8/zh_CN.UTF-8']),
818
+                'hint' => $l->t('Please install one of these locales on your system and restart your webserver.')
819
+            ];
820
+        }
821
+
822
+        // Contains the dependencies that should be checked against
823
+        // classes = class_exists
824
+        // functions = function_exists
825
+        // defined = defined
826
+        // ini = ini_get
827
+        // If the dependency is not found the missing module name is shown to the EndUser
828
+        // When adding new checks always verify that they pass on Travis as well
829
+        // for ini settings, see https://github.com/owncloud/administration/blob/master/travis-ci/custom.ini
830
+        $dependencies = [
831
+            'classes' => [
832
+                'ZipArchive' => 'zip',
833
+                'DOMDocument' => 'dom',
834
+                'XMLWriter' => 'XMLWriter',
835
+                'XMLReader' => 'XMLReader',
836
+            ],
837
+            'functions' => [
838
+                'xml_parser_create' => 'libxml',
839
+                'mb_strcut' => 'mbstring',
840
+                'ctype_digit' => 'ctype',
841
+                'json_encode' => 'JSON',
842
+                'gd_info' => 'GD',
843
+                'gzencode' => 'zlib',
844
+                'iconv' => 'iconv',
845
+                'simplexml_load_string' => 'SimpleXML',
846
+                'hash' => 'HASH Message Digest Framework',
847
+                'curl_init' => 'cURL',
848
+                'openssl_verify' => 'OpenSSL',
849
+            ],
850
+            'defined' => [
851
+                'PDO::ATTR_DRIVER_NAME' => 'PDO'
852
+            ],
853
+            'ini' => [
854
+                'default_charset' => 'UTF-8',
855
+            ],
856
+        ];
857
+        $missingDependencies = [];
858
+        $invalidIniSettings = [];
859
+        $moduleHint = $l->t('Please ask your server administrator to install the module.');
860
+
861
+        $iniWrapper = \OC::$server->getIniWrapper();
862
+        foreach ($dependencies['classes'] as $class => $module) {
863
+            if (!class_exists($class)) {
864
+                $missingDependencies[] = $module;
865
+            }
866
+        }
867
+        foreach ($dependencies['functions'] as $function => $module) {
868
+            if (!function_exists($function)) {
869
+                $missingDependencies[] = $module;
870
+            }
871
+        }
872
+        foreach ($dependencies['defined'] as $defined => $module) {
873
+            if (!defined($defined)) {
874
+                $missingDependencies[] = $module;
875
+            }
876
+        }
877
+        foreach ($dependencies['ini'] as $setting => $expected) {
878
+            if (is_bool($expected)) {
879
+                if ($iniWrapper->getBool($setting) !== $expected) {
880
+                    $invalidIniSettings[] = [$setting, $expected];
881
+                }
882
+            }
883
+            if (is_int($expected)) {
884
+                if ($iniWrapper->getNumeric($setting) !== $expected) {
885
+                    $invalidIniSettings[] = [$setting, $expected];
886
+                }
887
+            }
888
+            if (is_string($expected)) {
889
+                if (strtolower($iniWrapper->getString($setting)) !== strtolower($expected)) {
890
+                    $invalidIniSettings[] = [$setting, $expected];
891
+                }
892
+            }
893
+        }
894
+
895
+        foreach($missingDependencies as $missingDependency) {
896
+            $errors[] = [
897
+                'error' => $l->t('PHP module %s not installed.', [$missingDependency]),
898
+                'hint' => $moduleHint
899
+            ];
900
+            $webServerRestart = true;
901
+        }
902
+        foreach($invalidIniSettings as $setting) {
903
+            if(is_bool($setting[1])) {
904
+                $setting[1] = $setting[1] ? 'on' : 'off';
905
+            }
906
+            $errors[] = [
907
+                'error' => $l->t('PHP setting "%s" is not set to "%s".', [$setting[0], var_export($setting[1], true)]),
908
+                'hint' =>  $l->t('Adjusting this setting in php.ini will make Nextcloud run again')
909
+            ];
910
+            $webServerRestart = true;
911
+        }
912
+
913
+        /**
914
+         * The mbstring.func_overload check can only be performed if the mbstring
915
+         * module is installed as it will return null if the checking setting is
916
+         * not available and thus a check on the boolean value fails.
917
+         *
918
+         * TODO: Should probably be implemented in the above generic dependency
919
+         *       check somehow in the long-term.
920
+         */
921
+        if($iniWrapper->getBool('mbstring.func_overload') !== null &&
922
+            $iniWrapper->getBool('mbstring.func_overload') === true) {
923
+            $errors[] = [
924
+                'error' => $l->t('mbstring.func_overload is set to "%s" instead of the expected value "0"', [$iniWrapper->getString('mbstring.func_overload')]),
925
+                'hint' => $l->t('To fix this issue set <code>mbstring.func_overload</code> to <code>0</code> in your php.ini')
926
+            ];
927
+        }
928
+
929
+        if(function_exists('xml_parser_create') &&
930
+            LIBXML_LOADED_VERSION < 20700 ) {
931
+            $version = LIBXML_LOADED_VERSION;
932
+            $major = floor($version/10000);
933
+            $version -= ($major * 10000);
934
+            $minor = floor($version/100);
935
+            $version -= ($minor * 100);
936
+            $patch = $version;
937
+            $errors[] = [
938
+                'error' => $l->t('libxml2 2.7.0 is at least required. Currently %s is installed.', [$major . '.' . $minor . '.' . $patch]),
939
+                'hint' => $l->t('To fix this issue update your libxml2 version and restart your web server.')
940
+            ];
941
+        }
942
+
943
+        if (!self::isAnnotationsWorking()) {
944
+            $errors[] = [
945
+                'error' => $l->t('PHP is apparently set up to strip inline doc blocks. This will make several core apps inaccessible.'),
946
+                'hint' => $l->t('This is probably caused by a cache/accelerator such as Zend OPcache or eAccelerator.')
947
+            ];
948
+        }
949
+
950
+        if (!\OC::$CLI && $webServerRestart) {
951
+            $errors[] = [
952
+                'error' => $l->t('PHP modules have been installed, but they are still listed as missing?'),
953
+                'hint' => $l->t('Please ask your server administrator to restart the web server.')
954
+            ];
955
+        }
956
+
957
+        $errors = array_merge($errors, self::checkDatabaseVersion());
958
+
959
+        // Cache the result of this function
960
+        \OC::$server->getSession()->set('checkServer_succeeded', count($errors) == 0);
961
+
962
+        return $errors;
963
+    }
964
+
965
+    /**
966
+     * Check the database version
967
+     *
968
+     * @return array errors array
969
+     */
970
+    public static function checkDatabaseVersion() {
971
+        $l = \OC::$server->getL10N('lib');
972
+        $errors = [];
973
+        $dbType = \OC::$server->getSystemConfig()->getValue('dbtype', 'sqlite');
974
+        if ($dbType === 'pgsql') {
975
+            // check PostgreSQL version
976
+            try {
977
+                $result = \OC_DB::executeAudited('SHOW SERVER_VERSION');
978
+                $data = $result->fetchRow();
979
+                if (isset($data['server_version'])) {
980
+                    $version = $data['server_version'];
981
+                    if (version_compare($version, '9.0.0', '<')) {
982
+                        $errors[] = [
983
+                            'error' => $l->t('PostgreSQL >= 9 required'),
984
+                            'hint' => $l->t('Please upgrade your database version')
985
+                        ];
986
+                    }
987
+                }
988
+            } catch (\Doctrine\DBAL\DBALException $e) {
989
+                $logger = \OC::$server->getLogger();
990
+                $logger->warning('Error occurred while checking PostgreSQL version, assuming >= 9');
991
+                $logger->logException($e);
992
+            }
993
+        }
994
+        return $errors;
995
+    }
996
+
997
+    /**
998
+     * Check for correct file permissions of data directory
999
+     *
1000
+     * @param string $dataDirectory
1001
+     * @return array arrays with error messages and hints
1002
+     */
1003
+    public static function checkDataDirectoryPermissions($dataDirectory) {
1004
+        if(\OC::$server->getConfig()->getSystemValue('check_data_directory_permissions', true) === false) {
1005
+            return  [];
1006
+        }
1007
+        $l = \OC::$server->getL10N('lib');
1008
+        $errors = [];
1009
+        $permissionsModHint = $l->t('Please change the permissions to 0770 so that the directory'
1010
+            . ' cannot be listed by other users.');
1011
+        $perms = substr(decoct(@fileperms($dataDirectory)), -3);
1012
+        if (substr($perms, -1) !== '0') {
1013
+            chmod($dataDirectory, 0770);
1014
+            clearstatcache();
1015
+            $perms = substr(decoct(@fileperms($dataDirectory)), -3);
1016
+            if ($perms[2] !== '0') {
1017
+                $errors[] = [
1018
+                    'error' => $l->t('Your data directory is readable by other users'),
1019
+                    'hint' => $permissionsModHint
1020
+                ];
1021
+            }
1022
+        }
1023
+        return $errors;
1024
+    }
1025
+
1026
+    /**
1027
+     * Check that the data directory exists and is valid by
1028
+     * checking the existence of the ".ocdata" file.
1029
+     *
1030
+     * @param string $dataDirectory data directory path
1031
+     * @return array errors found
1032
+     */
1033
+    public static function checkDataDirectoryValidity($dataDirectory) {
1034
+        $l = \OC::$server->getL10N('lib');
1035
+        $errors = [];
1036
+        if ($dataDirectory[0] !== '/') {
1037
+            $errors[] = [
1038
+                'error' => $l->t('Your data directory must be an absolute path'),
1039
+                'hint' => $l->t('Check the value of "datadirectory" in your configuration')
1040
+            ];
1041
+        }
1042
+        if (!file_exists($dataDirectory . '/.ocdata')) {
1043
+            $errors[] = [
1044
+                'error' => $l->t('Your data directory is invalid'),
1045
+                'hint' => $l->t('Ensure there is a file called ".ocdata"' .
1046
+                    ' in the root of the data directory.')
1047
+            ];
1048
+        }
1049
+        return $errors;
1050
+    }
1051
+
1052
+    /**
1053
+     * Check if the user is logged in, redirects to home if not. With
1054
+     * redirect URL parameter to the request URI.
1055
+     *
1056
+     * @return void
1057
+     */
1058
+    public static function checkLoggedIn() {
1059
+        // Check if we are a user
1060
+        if (!\OC::$server->getUserSession()->isLoggedIn()) {
1061
+            header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute(
1062
+                        'core.login.showLoginForm',
1063
+                        [
1064
+                            'redirect_url' => \OC::$server->getRequest()->getRequestUri(),
1065
+                        ]
1066
+                    )
1067
+            );
1068
+            exit();
1069
+        }
1070
+        // Redirect to 2FA challenge selection if 2FA challenge was not solved yet
1071
+        if (\OC::$server->getTwoFactorAuthManager()->needsSecondFactor(\OC::$server->getUserSession()->getUser())) {
1072
+            header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute('core.TwoFactorChallenge.selectChallenge'));
1073
+            exit();
1074
+        }
1075
+    }
1076
+
1077
+    /**
1078
+     * Check if the user is a admin, redirects to home if not
1079
+     *
1080
+     * @return void
1081
+     */
1082
+    public static function checkAdminUser() {
1083
+        OC_Util::checkLoggedIn();
1084
+        if (!OC_User::isAdminUser(OC_User::getUser())) {
1085
+            header('Location: ' . \OCP\Util::linkToAbsolute('', 'index.php'));
1086
+            exit();
1087
+        }
1088
+    }
1089
+
1090
+    /**
1091
+     * Returns the URL of the default page
1092
+     * based on the system configuration and
1093
+     * the apps visible for the current user
1094
+     *
1095
+     * @return string URL
1096
+     * @suppress PhanDeprecatedFunction
1097
+     */
1098
+    public static function getDefaultPageUrl() {
1099
+        $urlGenerator = \OC::$server->getURLGenerator();
1100
+        // Deny the redirect if the URL contains a @
1101
+        // This prevents unvalidated redirects like ?redirect_url=:[email protected]
1102
+        if (isset($_REQUEST['redirect_url']) && strpos($_REQUEST['redirect_url'], '@') === false) {
1103
+            $location = $urlGenerator->getAbsoluteURL(urldecode($_REQUEST['redirect_url']));
1104
+        } else {
1105
+            $defaultPage = \OC::$server->getConfig()->getAppValue('core', 'defaultpage');
1106
+            if ($defaultPage) {
1107
+                $location = $urlGenerator->getAbsoluteURL($defaultPage);
1108
+            } else {
1109
+                $appId = 'files';
1110
+                $config = \OC::$server->getConfig();
1111
+                $defaultApps = explode(',', $config->getSystemValue('defaultapp', 'files'));
1112
+                // find the first app that is enabled for the current user
1113
+                foreach ($defaultApps as $defaultApp) {
1114
+                    $defaultApp = OC_App::cleanAppId(strip_tags($defaultApp));
1115
+                    if (static::getAppManager()->isEnabledForUser($defaultApp)) {
1116
+                        $appId = $defaultApp;
1117
+                        break;
1118
+                    }
1119
+                }
1120
+
1121
+                if($config->getSystemValue('htaccess.IgnoreFrontController', false) === true || getenv('front_controller_active') === 'true') {
1122
+                    $location = $urlGenerator->getAbsoluteURL('/apps/' . $appId . '/');
1123
+                } else {
1124
+                    $location = $urlGenerator->getAbsoluteURL('/index.php/apps/' . $appId . '/');
1125
+                }
1126
+            }
1127
+        }
1128
+        return $location;
1129
+    }
1130
+
1131
+    /**
1132
+     * Redirect to the user default page
1133
+     *
1134
+     * @return void
1135
+     */
1136
+    public static function redirectToDefaultPage() {
1137
+        $location = self::getDefaultPageUrl();
1138
+        header('Location: ' . $location);
1139
+        exit();
1140
+    }
1141
+
1142
+    /**
1143
+     * get an id unique for this instance
1144
+     *
1145
+     * @return string
1146
+     */
1147
+    public static function getInstanceId() {
1148
+        $id = \OC::$server->getSystemConfig()->getValue('instanceid', null);
1149
+        if (is_null($id)) {
1150
+            // We need to guarantee at least one letter in instanceid so it can be used as the session_name
1151
+            $id = 'oc' . \OC::$server->getSecureRandom()->generate(10, \OCP\Security\ISecureRandom::CHAR_LOWER.\OCP\Security\ISecureRandom::CHAR_DIGITS);
1152
+            \OC::$server->getSystemConfig()->setValue('instanceid', $id);
1153
+        }
1154
+        return $id;
1155
+    }
1156
+
1157
+    /**
1158
+     * Public function to sanitize HTML
1159
+     *
1160
+     * This function is used to sanitize HTML and should be applied on any
1161
+     * string or array of strings before displaying it on a web page.
1162
+     *
1163
+     * @param string|array $value
1164
+     * @return string|array an array of sanitized strings or a single sanitized string, depends on the input parameter.
1165
+     */
1166
+    public static function sanitizeHTML($value) {
1167
+        if (is_array($value)) {
1168
+            $value = array_map(function($value) {
1169
+                return self::sanitizeHTML($value);
1170
+            }, $value);
1171
+        } else {
1172
+            // Specify encoding for PHP<5.4
1173
+            $value = htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
1174
+        }
1175
+        return $value;
1176
+    }
1177
+
1178
+    /**
1179
+     * Public function to encode url parameters
1180
+     *
1181
+     * This function is used to encode path to file before output.
1182
+     * Encoding is done according to RFC 3986 with one exception:
1183
+     * Character '/' is preserved as is.
1184
+     *
1185
+     * @param string $component part of URI to encode
1186
+     * @return string
1187
+     */
1188
+    public static function encodePath($component) {
1189
+        $encoded = rawurlencode($component);
1190
+        $encoded = str_replace('%2F', '/', $encoded);
1191
+        return $encoded;
1192
+    }
1193
+
1194
+
1195
+    public function createHtaccessTestFile(\OCP\IConfig $config) {
1196
+        // php dev server does not support htaccess
1197
+        if (php_sapi_name() === 'cli-server') {
1198
+            return false;
1199
+        }
1200
+
1201
+        // testdata
1202
+        $fileName = '/htaccesstest.txt';
1203
+        $testContent = 'This is used for testing whether htaccess is properly enabled to disallow access from the outside. This file can be safely removed.';
1204
+
1205
+        // creating a test file
1206
+        $testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
1207
+
1208
+        if (file_exists($testFile)) {// already running this test, possible recursive call
1209
+            return false;
1210
+        }
1211
+
1212
+        $fp = @fopen($testFile, 'w');
1213
+        if (!$fp) {
1214
+            throw new OC\HintException('Can\'t create test file to check for working .htaccess file.',
1215
+                'Make sure it is possible for the webserver to write to ' . $testFile);
1216
+        }
1217
+        fwrite($fp, $testContent);
1218
+        fclose($fp);
1219
+
1220
+        return $testContent;
1221
+    }
1222
+
1223
+    /**
1224
+     * Check if the .htaccess file is working
1225
+     * @param \OCP\IConfig $config
1226
+     * @return bool
1227
+     * @throws Exception
1228
+     * @throws \OC\HintException If the test file can't get written.
1229
+     */
1230
+    public function isHtaccessWorking(\OCP\IConfig $config) {
1231
+
1232
+        if (\OC::$CLI || !$config->getSystemValue('check_for_working_htaccess', true)) {
1233
+            return true;
1234
+        }
1235
+
1236
+        $testContent = $this->createHtaccessTestFile($config);
1237
+        if ($testContent === false) {
1238
+            return false;
1239
+        }
1240
+
1241
+        $fileName = '/htaccesstest.txt';
1242
+        $testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
1243
+
1244
+        // accessing the file via http
1245
+        $url = \OC::$server->getURLGenerator()->getAbsoluteURL(OC::$WEBROOT . '/data' . $fileName);
1246
+        try {
1247
+            $content = \OC::$server->getHTTPClientService()->newClient()->get($url)->getBody();
1248
+        } catch (\Exception $e) {
1249
+            $content = false;
1250
+        }
1251
+
1252
+        if (strpos($url, 'https:') === 0) {
1253
+            $url = 'http:' . substr($url, 6);
1254
+        } else {
1255
+            $url = 'https:' . substr($url, 5);
1256
+        }
1257
+
1258
+        try {
1259
+            $fallbackContent = \OC::$server->getHTTPClientService()->newClient()->get($url)->getBody();
1260
+        } catch (\Exception $e) {
1261
+            $fallbackContent = false;
1262
+        }
1263
+
1264
+        // cleanup
1265
+        @unlink($testFile);
1266
+
1267
+        /*
1268 1268
 		 * If the content is not equal to test content our .htaccess
1269 1269
 		 * is working as required
1270 1270
 		 */
1271
-		return $content !== $testContent && $fallbackContent !== $testContent;
1272
-	}
1273
-
1274
-	/**
1275
-	 * Check if the setlocal call does not work. This can happen if the right
1276
-	 * local packages are not available on the server.
1277
-	 *
1278
-	 * @return bool
1279
-	 */
1280
-	public static function isSetLocaleWorking() {
1281
-		\Patchwork\Utf8\Bootup::initLocale();
1282
-		if ('' === basename('§')) {
1283
-			return false;
1284
-		}
1285
-		return true;
1286
-	}
1287
-
1288
-	/**
1289
-	 * Check if it's possible to get the inline annotations
1290
-	 *
1291
-	 * @return bool
1292
-	 */
1293
-	public static function isAnnotationsWorking() {
1294
-		$reflection = new \ReflectionMethod(__METHOD__);
1295
-		$docs = $reflection->getDocComment();
1296
-
1297
-		return (is_string($docs) && strlen($docs) > 50);
1298
-	}
1299
-
1300
-	/**
1301
-	 * Check if the PHP module fileinfo is loaded.
1302
-	 *
1303
-	 * @return bool
1304
-	 */
1305
-	public static function fileInfoLoaded() {
1306
-		return function_exists('finfo_open');
1307
-	}
1308
-
1309
-	/**
1310
-	 * clear all levels of output buffering
1311
-	 *
1312
-	 * @return void
1313
-	 */
1314
-	public static function obEnd() {
1315
-		while (ob_get_level()) {
1316
-			ob_end_clean();
1317
-		}
1318
-	}
1319
-
1320
-	/**
1321
-	 * Checks whether the server is running on Mac OS X
1322
-	 *
1323
-	 * @return bool true if running on Mac OS X, false otherwise
1324
-	 */
1325
-	public static function runningOnMac() {
1326
-		return (strtoupper(substr(PHP_OS, 0, 6)) === 'DARWIN');
1327
-	}
1328
-
1329
-	/**
1330
-	 * Handles the case that there may not be a theme, then check if a "default"
1331
-	 * theme exists and take that one
1332
-	 *
1333
-	 * @return string the theme
1334
-	 */
1335
-	public static function getTheme() {
1336
-		$theme = \OC::$server->getSystemConfig()->getValue("theme", '');
1337
-
1338
-		if ($theme === '') {
1339
-			if (is_dir(OC::$SERVERROOT . '/themes/default')) {
1340
-				$theme = 'default';
1341
-			}
1342
-		}
1343
-
1344
-		return $theme;
1345
-	}
1346
-
1347
-	/**
1348
-	 * Normalize a unicode string
1349
-	 *
1350
-	 * @param string $value a not normalized string
1351
-	 * @return bool|string
1352
-	 */
1353
-	public static function normalizeUnicode($value) {
1354
-		if(Normalizer::isNormalized($value)) {
1355
-			return $value;
1356
-		}
1357
-
1358
-		$normalizedValue = Normalizer::normalize($value);
1359
-		if ($normalizedValue === null || $normalizedValue === false) {
1360
-			\OC::$server->getLogger()->warning('normalizing failed for "' . $value . '"', ['app' => 'core']);
1361
-			return $value;
1362
-		}
1363
-
1364
-		return $normalizedValue;
1365
-	}
1366
-
1367
-	/**
1368
-	 * A human readable string is generated based on version and build number
1369
-	 *
1370
-	 * @return string
1371
-	 */
1372
-	public static function getHumanVersion() {
1373
-		$version = OC_Util::getVersionString();
1374
-		$build = OC_Util::getBuild();
1375
-		if (!empty($build) and OC_Util::getChannel() === 'daily') {
1376
-			$version .= ' Build:' . $build;
1377
-		}
1378
-		return $version;
1379
-	}
1380
-
1381
-	/**
1382
-	 * Returns whether the given file name is valid
1383
-	 *
1384
-	 * @param string $file file name to check
1385
-	 * @return bool true if the file name is valid, false otherwise
1386
-	 * @deprecated use \OC\Files\View::verifyPath()
1387
-	 */
1388
-	public static function isValidFileName($file) {
1389
-		$trimmed = trim($file);
1390
-		if ($trimmed === '') {
1391
-			return false;
1392
-		}
1393
-		if (\OC\Files\Filesystem::isIgnoredDir($trimmed)) {
1394
-			return false;
1395
-		}
1396
-
1397
-		// detect part files
1398
-		if (preg_match('/' . \OCP\Files\FileInfo::BLACKLIST_FILES_REGEX . '/', $trimmed) !== 0) {
1399
-			return false;
1400
-		}
1401
-
1402
-		foreach (str_split($trimmed) as $char) {
1403
-			if (strpos(\OCP\Constants::FILENAME_INVALID_CHARS, $char) !== false) {
1404
-				return false;
1405
-			}
1406
-		}
1407
-		return true;
1408
-	}
1409
-
1410
-	/**
1411
-	 * Check whether the instance needs to perform an upgrade,
1412
-	 * either when the core version is higher or any app requires
1413
-	 * an upgrade.
1414
-	 *
1415
-	 * @param \OC\SystemConfig $config
1416
-	 * @return bool whether the core or any app needs an upgrade
1417
-	 * @throws \OC\HintException When the upgrade from the given version is not allowed
1418
-	 */
1419
-	public static function needUpgrade(\OC\SystemConfig $config) {
1420
-		if ($config->getValue('installed', false)) {
1421
-			$installedVersion = $config->getValue('version', '0.0.0');
1422
-			$currentVersion = implode('.', \OCP\Util::getVersion());
1423
-			$versionDiff = version_compare($currentVersion, $installedVersion);
1424
-			if ($versionDiff > 0) {
1425
-				return true;
1426
-			} else if ($config->getValue('debug', false) && $versionDiff < 0) {
1427
-				// downgrade with debug
1428
-				$installedMajor = explode('.', $installedVersion);
1429
-				$installedMajor = $installedMajor[0] . '.' . $installedMajor[1];
1430
-				$currentMajor = explode('.', $currentVersion);
1431
-				$currentMajor = $currentMajor[0] . '.' . $currentMajor[1];
1432
-				if ($installedMajor === $currentMajor) {
1433
-					// Same major, allow downgrade for developers
1434
-					return true;
1435
-				} else {
1436
-					// downgrade attempt, throw exception
1437
-					throw new \OC\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
1438
-				}
1439
-			} else if ($versionDiff < 0) {
1440
-				// downgrade attempt, throw exception
1441
-				throw new \OC\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
1442
-			}
1443
-
1444
-			// also check for upgrades for apps (independently from the user)
1445
-			$apps = \OC_App::getEnabledApps(false, true);
1446
-			$shouldUpgrade = false;
1447
-			foreach ($apps as $app) {
1448
-				if (\OC_App::shouldUpgrade($app)) {
1449
-					$shouldUpgrade = true;
1450
-					break;
1451
-				}
1452
-			}
1453
-			return $shouldUpgrade;
1454
-		} else {
1455
-			return false;
1456
-		}
1457
-	}
1458
-
1459
-	/**
1460
-	 * is this Internet explorer ?
1461
-	 *
1462
-	 * @return boolean
1463
-	 */
1464
-	public static function isIe() {
1465
-		if (!isset($_SERVER['HTTP_USER_AGENT'])) {
1466
-			return false;
1467
-		}
1468
-
1469
-		return preg_match(Request::USER_AGENT_IE, $_SERVER['HTTP_USER_AGENT']) === 1;
1470
-	}
1271
+        return $content !== $testContent && $fallbackContent !== $testContent;
1272
+    }
1273
+
1274
+    /**
1275
+     * Check if the setlocal call does not work. This can happen if the right
1276
+     * local packages are not available on the server.
1277
+     *
1278
+     * @return bool
1279
+     */
1280
+    public static function isSetLocaleWorking() {
1281
+        \Patchwork\Utf8\Bootup::initLocale();
1282
+        if ('' === basename('§')) {
1283
+            return false;
1284
+        }
1285
+        return true;
1286
+    }
1287
+
1288
+    /**
1289
+     * Check if it's possible to get the inline annotations
1290
+     *
1291
+     * @return bool
1292
+     */
1293
+    public static function isAnnotationsWorking() {
1294
+        $reflection = new \ReflectionMethod(__METHOD__);
1295
+        $docs = $reflection->getDocComment();
1296
+
1297
+        return (is_string($docs) && strlen($docs) > 50);
1298
+    }
1299
+
1300
+    /**
1301
+     * Check if the PHP module fileinfo is loaded.
1302
+     *
1303
+     * @return bool
1304
+     */
1305
+    public static function fileInfoLoaded() {
1306
+        return function_exists('finfo_open');
1307
+    }
1308
+
1309
+    /**
1310
+     * clear all levels of output buffering
1311
+     *
1312
+     * @return void
1313
+     */
1314
+    public static function obEnd() {
1315
+        while (ob_get_level()) {
1316
+            ob_end_clean();
1317
+        }
1318
+    }
1319
+
1320
+    /**
1321
+     * Checks whether the server is running on Mac OS X
1322
+     *
1323
+     * @return bool true if running on Mac OS X, false otherwise
1324
+     */
1325
+    public static function runningOnMac() {
1326
+        return (strtoupper(substr(PHP_OS, 0, 6)) === 'DARWIN');
1327
+    }
1328
+
1329
+    /**
1330
+     * Handles the case that there may not be a theme, then check if a "default"
1331
+     * theme exists and take that one
1332
+     *
1333
+     * @return string the theme
1334
+     */
1335
+    public static function getTheme() {
1336
+        $theme = \OC::$server->getSystemConfig()->getValue("theme", '');
1337
+
1338
+        if ($theme === '') {
1339
+            if (is_dir(OC::$SERVERROOT . '/themes/default')) {
1340
+                $theme = 'default';
1341
+            }
1342
+        }
1343
+
1344
+        return $theme;
1345
+    }
1346
+
1347
+    /**
1348
+     * Normalize a unicode string
1349
+     *
1350
+     * @param string $value a not normalized string
1351
+     * @return bool|string
1352
+     */
1353
+    public static function normalizeUnicode($value) {
1354
+        if(Normalizer::isNormalized($value)) {
1355
+            return $value;
1356
+        }
1357
+
1358
+        $normalizedValue = Normalizer::normalize($value);
1359
+        if ($normalizedValue === null || $normalizedValue === false) {
1360
+            \OC::$server->getLogger()->warning('normalizing failed for "' . $value . '"', ['app' => 'core']);
1361
+            return $value;
1362
+        }
1363
+
1364
+        return $normalizedValue;
1365
+    }
1366
+
1367
+    /**
1368
+     * A human readable string is generated based on version and build number
1369
+     *
1370
+     * @return string
1371
+     */
1372
+    public static function getHumanVersion() {
1373
+        $version = OC_Util::getVersionString();
1374
+        $build = OC_Util::getBuild();
1375
+        if (!empty($build) and OC_Util::getChannel() === 'daily') {
1376
+            $version .= ' Build:' . $build;
1377
+        }
1378
+        return $version;
1379
+    }
1380
+
1381
+    /**
1382
+     * Returns whether the given file name is valid
1383
+     *
1384
+     * @param string $file file name to check
1385
+     * @return bool true if the file name is valid, false otherwise
1386
+     * @deprecated use \OC\Files\View::verifyPath()
1387
+     */
1388
+    public static function isValidFileName($file) {
1389
+        $trimmed = trim($file);
1390
+        if ($trimmed === '') {
1391
+            return false;
1392
+        }
1393
+        if (\OC\Files\Filesystem::isIgnoredDir($trimmed)) {
1394
+            return false;
1395
+        }
1396
+
1397
+        // detect part files
1398
+        if (preg_match('/' . \OCP\Files\FileInfo::BLACKLIST_FILES_REGEX . '/', $trimmed) !== 0) {
1399
+            return false;
1400
+        }
1401
+
1402
+        foreach (str_split($trimmed) as $char) {
1403
+            if (strpos(\OCP\Constants::FILENAME_INVALID_CHARS, $char) !== false) {
1404
+                return false;
1405
+            }
1406
+        }
1407
+        return true;
1408
+    }
1409
+
1410
+    /**
1411
+     * Check whether the instance needs to perform an upgrade,
1412
+     * either when the core version is higher or any app requires
1413
+     * an upgrade.
1414
+     *
1415
+     * @param \OC\SystemConfig $config
1416
+     * @return bool whether the core or any app needs an upgrade
1417
+     * @throws \OC\HintException When the upgrade from the given version is not allowed
1418
+     */
1419
+    public static function needUpgrade(\OC\SystemConfig $config) {
1420
+        if ($config->getValue('installed', false)) {
1421
+            $installedVersion = $config->getValue('version', '0.0.0');
1422
+            $currentVersion = implode('.', \OCP\Util::getVersion());
1423
+            $versionDiff = version_compare($currentVersion, $installedVersion);
1424
+            if ($versionDiff > 0) {
1425
+                return true;
1426
+            } else if ($config->getValue('debug', false) && $versionDiff < 0) {
1427
+                // downgrade with debug
1428
+                $installedMajor = explode('.', $installedVersion);
1429
+                $installedMajor = $installedMajor[0] . '.' . $installedMajor[1];
1430
+                $currentMajor = explode('.', $currentVersion);
1431
+                $currentMajor = $currentMajor[0] . '.' . $currentMajor[1];
1432
+                if ($installedMajor === $currentMajor) {
1433
+                    // Same major, allow downgrade for developers
1434
+                    return true;
1435
+                } else {
1436
+                    // downgrade attempt, throw exception
1437
+                    throw new \OC\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
1438
+                }
1439
+            } else if ($versionDiff < 0) {
1440
+                // downgrade attempt, throw exception
1441
+                throw new \OC\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
1442
+            }
1443
+
1444
+            // also check for upgrades for apps (independently from the user)
1445
+            $apps = \OC_App::getEnabledApps(false, true);
1446
+            $shouldUpgrade = false;
1447
+            foreach ($apps as $app) {
1448
+                if (\OC_App::shouldUpgrade($app)) {
1449
+                    $shouldUpgrade = true;
1450
+                    break;
1451
+                }
1452
+            }
1453
+            return $shouldUpgrade;
1454
+        } else {
1455
+            return false;
1456
+        }
1457
+    }
1458
+
1459
+    /**
1460
+     * is this Internet explorer ?
1461
+     *
1462
+     * @return boolean
1463
+     */
1464
+    public static function isIe() {
1465
+        if (!isset($_SERVER['HTTP_USER_AGENT'])) {
1466
+            return false;
1467
+        }
1468
+
1469
+        return preg_match(Request::USER_AGENT_IE, $_SERVER['HTTP_USER_AGENT']) === 1;
1470
+    }
1471 1471
 
1472 1472
 }
Please login to merge, or discard this patch.