Completed
Pull Request — master (#7354)
by Morris
15:39
created
lib/base.php 2 patches
Indentation   +991 added lines, -991 removed lines patch added patch discarded remove patch
@@ -62,997 +62,997 @@
 block discarded – undo
62 62
  * OC_autoload!
63 63
  */
64 64
 class OC {
65
-	/**
66
-	 * Associative array for autoloading. classname => filename
67
-	 */
68
-	public static $CLASSPATH = array();
69
-	/**
70
-	 * The installation path for Nextcloud  on the server (e.g. /srv/http/nextcloud)
71
-	 */
72
-	public static $SERVERROOT = '';
73
-	/**
74
-	 * the current request path relative to the Nextcloud root (e.g. files/index.php)
75
-	 */
76
-	private static $SUBURI = '';
77
-	/**
78
-	 * the Nextcloud root path for http requests (e.g. nextcloud/)
79
-	 */
80
-	public static $WEBROOT = '';
81
-	/**
82
-	 * The installation path array of the apps folder on the server (e.g. /srv/http/nextcloud) 'path' and
83
-	 * web path in 'url'
84
-	 */
85
-	public static $APPSROOTS = array();
86
-
87
-	/**
88
-	 * @var string
89
-	 */
90
-	public static $configDir;
91
-
92
-	/**
93
-	 * requested app
94
-	 */
95
-	public static $REQUESTEDAPP = '';
96
-
97
-	/**
98
-	 * check if Nextcloud runs in cli mode
99
-	 */
100
-	public static $CLI = false;
101
-
102
-	/**
103
-	 * @var \OC\Autoloader $loader
104
-	 */
105
-	public static $loader = null;
106
-
107
-	/** @var \Composer\Autoload\ClassLoader $composerAutoloader */
108
-	public static $composerAutoloader = null;
109
-
110
-	/**
111
-	 * @var \OC\Server
112
-	 */
113
-	public static $server = null;
114
-
115
-	/**
116
-	 * @var \OC\Config
117
-	 */
118
-	private static $config = null;
119
-
120
-	/**
121
-	 * @throws \RuntimeException when the 3rdparty directory is missing or
122
-	 * the app path list is empty or contains an invalid path
123
-	 */
124
-	public static function initPaths() {
125
-		if(defined('PHPUNIT_CONFIG_DIR')) {
126
-			self::$configDir = OC::$SERVERROOT . '/' . PHPUNIT_CONFIG_DIR . '/';
127
-		} elseif(defined('PHPUNIT_RUN') and PHPUNIT_RUN and is_dir(OC::$SERVERROOT . '/tests/config/')) {
128
-			self::$configDir = OC::$SERVERROOT . '/tests/config/';
129
-		} elseif($dir = getenv('NEXTCLOUD_CONFIG_DIR')) {
130
-			self::$configDir = rtrim($dir, '/') . '/';
131
-		} else {
132
-			self::$configDir = OC::$SERVERROOT . '/config/';
133
-		}
134
-		self::$config = new \OC\Config(self::$configDir);
135
-
136
-		OC::$SUBURI = str_replace("\\", "/", substr(realpath($_SERVER["SCRIPT_FILENAME"]), strlen(OC::$SERVERROOT)));
137
-		/**
138
-		 * FIXME: The following lines are required because we can't yet instantiate
139
-		 *        \OC::$server->getRequest() since \OC::$server does not yet exist.
140
-		 */
141
-		$params = [
142
-			'server' => [
143
-				'SCRIPT_NAME' => $_SERVER['SCRIPT_NAME'],
144
-				'SCRIPT_FILENAME' => $_SERVER['SCRIPT_FILENAME'],
145
-			],
146
-		];
147
-		$fakeRequest = new \OC\AppFramework\Http\Request($params, null, new \OC\AllConfig(new \OC\SystemConfig(self::$config)));
148
-		$scriptName = $fakeRequest->getScriptName();
149
-		if (substr($scriptName, -1) == '/') {
150
-			$scriptName .= 'index.php';
151
-			//make sure suburi follows the same rules as scriptName
152
-			if (substr(OC::$SUBURI, -9) != 'index.php') {
153
-				if (substr(OC::$SUBURI, -1) != '/') {
154
-					OC::$SUBURI = OC::$SUBURI . '/';
155
-				}
156
-				OC::$SUBURI = OC::$SUBURI . 'index.php';
157
-			}
158
-		}
159
-
160
-
161
-		if (OC::$CLI) {
162
-			OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
163
-		} else {
164
-			if (substr($scriptName, 0 - strlen(OC::$SUBURI)) === OC::$SUBURI) {
165
-				OC::$WEBROOT = substr($scriptName, 0, 0 - strlen(OC::$SUBURI));
166
-
167
-				if (OC::$WEBROOT != '' && OC::$WEBROOT[0] !== '/') {
168
-					OC::$WEBROOT = '/' . OC::$WEBROOT;
169
-				}
170
-			} else {
171
-				// The scriptName is not ending with OC::$SUBURI
172
-				// This most likely means that we are calling from CLI.
173
-				// However some cron jobs still need to generate
174
-				// a web URL, so we use overwritewebroot as a fallback.
175
-				OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
176
-			}
177
-
178
-			// Resolve /nextcloud to /nextcloud/ to ensure to always have a trailing
179
-			// slash which is required by URL generation.
180
-			if (isset($_SERVER['REQUEST_URI']) && $_SERVER['REQUEST_URI'] === \OC::$WEBROOT &&
181
-					substr($_SERVER['REQUEST_URI'], -1) !== '/') {
182
-				header('Location: '.\OC::$WEBROOT.'/');
183
-				exit();
184
-			}
185
-		}
186
-
187
-		// search the apps folder
188
-		$config_paths = self::$config->getValue('apps_paths', array());
189
-		if (!empty($config_paths)) {
190
-			foreach ($config_paths as $paths) {
191
-				if (isset($paths['url']) && isset($paths['path'])) {
192
-					$paths['url'] = rtrim($paths['url'], '/');
193
-					$paths['path'] = rtrim($paths['path'], '/');
194
-					OC::$APPSROOTS[] = $paths;
195
-				}
196
-			}
197
-		} elseif (file_exists(OC::$SERVERROOT . '/apps')) {
198
-			OC::$APPSROOTS[] = array('path' => OC::$SERVERROOT . '/apps', 'url' => '/apps', 'writable' => true);
199
-		} elseif (file_exists(OC::$SERVERROOT . '/../apps')) {
200
-			OC::$APPSROOTS[] = array(
201
-				'path' => rtrim(dirname(OC::$SERVERROOT), '/') . '/apps',
202
-				'url' => '/apps',
203
-				'writable' => true
204
-			);
205
-		}
206
-
207
-		if (empty(OC::$APPSROOTS)) {
208
-			throw new \RuntimeException('apps directory not found! Please put the Nextcloud apps folder in the Nextcloud folder'
209
-				. ' or the folder above. You can also configure the location in the config.php file.');
210
-		}
211
-		$paths = array();
212
-		foreach (OC::$APPSROOTS as $path) {
213
-			$paths[] = $path['path'];
214
-			if (!is_dir($path['path'])) {
215
-				throw new \RuntimeException(sprintf('App directory "%s" not found! Please put the Nextcloud apps folder in the'
216
-					. ' Nextcloud folder or the folder above. You can also configure the location in the'
217
-					. ' config.php file.', $path['path']));
218
-			}
219
-		}
220
-
221
-		// set the right include path
222
-		set_include_path(
223
-			implode(PATH_SEPARATOR, $paths)
224
-		);
225
-	}
226
-
227
-	public static function checkConfig() {
228
-		$l = \OC::$server->getL10N('lib');
229
-
230
-		// Create config if it does not already exist
231
-		$configFilePath = self::$configDir .'/config.php';
232
-		if(!file_exists($configFilePath)) {
233
-			@touch($configFilePath);
234
-		}
235
-
236
-		// Check if config is writable
237
-		$configFileWritable = is_writable($configFilePath);
238
-		if (!$configFileWritable && !OC_Helper::isReadOnlyConfigEnabled()
239
-			|| !$configFileWritable && \OCP\Util::needUpgrade()) {
240
-
241
-			$urlGenerator = \OC::$server->getURLGenerator();
242
-
243
-			if (self::$CLI) {
244
-				echo $l->t('Cannot write into "config" directory!')."\n";
245
-				echo $l->t('This can usually be fixed by giving the webserver write access to the config directory')."\n";
246
-				echo "\n";
247
-				echo $l->t('See %s', [ $urlGenerator->linkToDocs('admin-dir_permissions') ])."\n";
248
-				exit;
249
-			} else {
250
-				OC_Template::printErrorPage(
251
-					$l->t('Cannot write into "config" directory!'),
252
-					$l->t('This can usually be fixed by giving the webserver write access to the config directory. See %s',
253
-					 [ $urlGenerator->linkToDocs('admin-dir_permissions') ])
254
-				);
255
-			}
256
-		}
257
-	}
258
-
259
-	public static function checkInstalled() {
260
-		if (defined('OC_CONSOLE')) {
261
-			return;
262
-		}
263
-		// Redirect to installer if not installed
264
-		if (!\OC::$server->getSystemConfig()->getValue('installed', false) && OC::$SUBURI !== '/index.php' && OC::$SUBURI !== '/status.php') {
265
-			if (OC::$CLI) {
266
-				throw new Exception('Not installed');
267
-			} else {
268
-				$url = OC::$WEBROOT . '/index.php';
269
-				header('Location: ' . $url);
270
-			}
271
-			exit();
272
-		}
273
-	}
274
-
275
-	public static function checkMaintenanceMode() {
276
-		// Allow ajax update script to execute without being stopped
277
-		if (\OC::$server->getSystemConfig()->getValue('maintenance', false) && OC::$SUBURI != '/core/ajax/update.php') {
278
-			// send http status 503
279
-			header('HTTP/1.1 503 Service Temporarily Unavailable');
280
-			header('Status: 503 Service Temporarily Unavailable');
281
-			header('Retry-After: 120');
282
-
283
-			// render error page
284
-			$template = new OC_Template('', 'update.user', 'guest');
285
-			OC_Util::addScript('maintenance-check');
286
-			OC_Util::addStyle('core', 'guest');
287
-			$template->printPage();
288
-			die();
289
-		}
290
-	}
291
-
292
-	/**
293
-	 * Prints the upgrade page
294
-	 *
295
-	 * @param \OC\SystemConfig $systemConfig
296
-	 */
297
-	private static function printUpgradePage(\OC\SystemConfig $systemConfig) {
298
-		$disableWebUpdater = $systemConfig->getValue('upgrade.disable-web', false);
299
-		$tooBig = false;
300
-		if (!$disableWebUpdater) {
301
-			$apps = \OC::$server->getAppManager();
302
-			if ($apps->isInstalled('user_ldap')) {
303
-				$qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
304
-
305
-				$result = $qb->selectAlias($qb->createFunction('COUNT(*)'), 'user_count')
306
-					->from('ldap_user_mapping')
307
-					->execute();
308
-				$row = $result->fetch();
309
-				$result->closeCursor();
310
-
311
-				$tooBig = ($row['user_count'] > 50);
312
-			}
313
-			if (!$tooBig && $apps->isInstalled('user_saml')) {
314
-				$qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
315
-
316
-				$result = $qb->selectAlias($qb->createFunction('COUNT(*)'), 'user_count')
317
-					->from('user_saml_users')
318
-					->execute();
319
-				$row = $result->fetch();
320
-				$result->closeCursor();
321
-
322
-				$tooBig = ($row['user_count'] > 50);
323
-			}
324
-			if (!$tooBig) {
325
-				// count users
326
-				$stats = \OC::$server->getUserManager()->countUsers();
327
-				$totalUsers = array_sum($stats);
328
-				$tooBig = ($totalUsers > 50);
329
-			}
330
-		}
331
-		$ignoreTooBigWarning = isset($_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup']) &&
332
-			$_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup'] === 'IAmSuperSureToDoThis';
333
-
334
-		if ($disableWebUpdater || ($tooBig && !$ignoreTooBigWarning)) {
335
-			// send http status 503
336
-			header('HTTP/1.1 503 Service Temporarily Unavailable');
337
-			header('Status: 503 Service Temporarily Unavailable');
338
-			header('Retry-After: 120');
339
-
340
-			// render error page
341
-			$template = new OC_Template('', 'update.use-cli', 'guest');
342
-			$template->assign('productName', 'nextcloud'); // for now
343
-			$template->assign('version', OC_Util::getVersionString());
344
-			$template->assign('tooBig', $tooBig);
345
-
346
-			$template->printPage();
347
-			die();
348
-		}
349
-
350
-		// check whether this is a core update or apps update
351
-		$installedVersion = $systemConfig->getValue('version', '0.0.0');
352
-		$currentVersion = implode('.', \OCP\Util::getVersion());
353
-
354
-		// if not a core upgrade, then it's apps upgrade
355
-		$isAppsOnlyUpgrade = (version_compare($currentVersion, $installedVersion, '='));
356
-
357
-		$oldTheme = $systemConfig->getValue('theme');
358
-		$systemConfig->setValue('theme', '');
359
-		OC_Util::addScript('config'); // needed for web root
360
-		OC_Util::addScript('update');
361
-
362
-		/** @var \OC\App\AppManager $appManager */
363
-		$appManager = \OC::$server->getAppManager();
364
-
365
-		$tmpl = new OC_Template('', 'update.admin', 'guest');
366
-		$tmpl->assign('version', OC_Util::getVersionString());
367
-		$tmpl->assign('isAppsOnlyUpgrade', $isAppsOnlyUpgrade);
368
-
369
-		// get third party apps
370
-		$ocVersion = \OCP\Util::getVersion();
371
-		$incompatibleApps = $appManager->getIncompatibleApps($ocVersion);
372
-		$incompatibleShippedApps = [];
373
-		foreach ($incompatibleApps as $appInfo) {
374
-			if ($appManager->isShipped($appInfo['id'])) {
375
-				$incompatibleShippedApps[] = $appInfo['name'] . ' (' . $appInfo['id'] . ')';
376
-			}
377
-		}
378
-
379
-		if (!empty($incompatibleShippedApps)) {
380
-			$l = \OC::$server->getL10N('core');
381
-			$hint = $l->t('The files of the app %$1s were not replaced correctly. Make sure it is a version compatible with the server.', [implode(', ', $incompatibleShippedApps)]);
382
-			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);
383
-		}
384
-
385
-		$tmpl->assign('appsToUpgrade', $appManager->getAppsNeedingUpgrade($ocVersion));
386
-		$tmpl->assign('incompatibleAppsList', $incompatibleApps);
387
-		$tmpl->assign('productName', 'Nextcloud'); // for now
388
-		$tmpl->assign('oldTheme', $oldTheme);
389
-		$tmpl->printPage();
390
-	}
391
-
392
-	public static function initSession() {
393
-		// prevents javascript from accessing php session cookies
394
-		ini_set('session.cookie_httponly', true);
395
-
396
-		// set the cookie path to the Nextcloud directory
397
-		$cookie_path = OC::$WEBROOT ? : '/';
398
-		ini_set('session.cookie_path', $cookie_path);
399
-
400
-		// Let the session name be changed in the initSession Hook
401
-		$sessionName = OC_Util::getInstanceId();
402
-
403
-		try {
404
-			// Allow session apps to create a custom session object
405
-			$useCustomSession = false;
406
-			$session = self::$server->getSession();
407
-			OC_Hook::emit('OC', 'initSession', array('session' => &$session, 'sessionName' => &$sessionName, 'useCustomSession' => &$useCustomSession));
408
-			if (!$useCustomSession) {
409
-				// set the session name to the instance id - which is unique
410
-				$session = new \OC\Session\Internal($sessionName);
411
-			}
412
-
413
-			$cryptoWrapper = \OC::$server->getSessionCryptoWrapper();
414
-			$session = $cryptoWrapper->wrapSession($session);
415
-			self::$server->setSession($session);
416
-
417
-			// if session can't be started break with http 500 error
418
-		} catch (Exception $e) {
419
-			\OCP\Util::logException('base', $e);
420
-			//show the user a detailed error page
421
-			OC_Response::setStatus(OC_Response::STATUS_INTERNAL_SERVER_ERROR);
422
-			OC_Template::printExceptionErrorPage($e);
423
-			die();
424
-		}
425
-
426
-		$sessionLifeTime = self::getSessionLifeTime();
427
-
428
-		// session timeout
429
-		if ($session->exists('LAST_ACTIVITY') && (time() - $session->get('LAST_ACTIVITY') > $sessionLifeTime)) {
430
-			if (isset($_COOKIE[session_name()])) {
431
-				setcookie(session_name(), null, -1, self::$WEBROOT ? : '/');
432
-			}
433
-			\OC::$server->getUserSession()->logout();
434
-		}
435
-
436
-		$session->set('LAST_ACTIVITY', time());
437
-	}
438
-
439
-	/**
440
-	 * @return string
441
-	 */
442
-	private static function getSessionLifeTime() {
443
-		return \OC::$server->getConfig()->getSystemValue('session_lifetime', 60 * 60 * 24);
444
-	}
445
-
446
-	public static function loadAppClassPaths() {
447
-		foreach (OC_App::getEnabledApps() as $app) {
448
-			$appPath = OC_App::getAppPath($app);
449
-			if ($appPath === false) {
450
-				continue;
451
-			}
452
-
453
-			$file = $appPath . '/appinfo/classpath.php';
454
-			if (file_exists($file)) {
455
-				require_once $file;
456
-			}
457
-		}
458
-	}
459
-
460
-	/**
461
-	 * Try to set some values to the required Nextcloud default
462
-	 */
463
-	public static function setRequiredIniValues() {
464
-		@ini_set('default_charset', 'UTF-8');
465
-		@ini_set('gd.jpeg_ignore_warning', 1);
466
-	}
467
-
468
-	/**
469
-	 * Send the same site cookies
470
-	 */
471
-	private static function sendSameSiteCookies() {
472
-		$cookieParams = session_get_cookie_params();
473
-		$secureCookie = ($cookieParams['secure'] === true) ? 'secure; ' : '';
474
-		$policies = [
475
-			'lax',
476
-			'strict',
477
-		];
478
-
479
-		// Append __Host to the cookie if it meets the requirements
480
-		$cookiePrefix = '';
481
-		if($cookieParams['secure'] === true && $cookieParams['path'] === '/') {
482
-			$cookiePrefix = '__Host-';
483
-		}
484
-
485
-		foreach($policies as $policy) {
486
-			header(
487
-				sprintf(
488
-					'Set-Cookie: %snc_sameSiteCookie%s=true; path=%s; httponly;' . $secureCookie . 'expires=Fri, 31-Dec-2100 23:59:59 GMT; SameSite=%s',
489
-					$cookiePrefix,
490
-					$policy,
491
-					$cookieParams['path'],
492
-					$policy
493
-				),
494
-				false
495
-			);
496
-		}
497
-	}
498
-
499
-	/**
500
-	 * Same Site cookie to further mitigate CSRF attacks. This cookie has to
501
-	 * be set in every request if cookies are sent to add a second level of
502
-	 * defense against CSRF.
503
-	 *
504
-	 * If the cookie is not sent this will set the cookie and reload the page.
505
-	 * We use an additional cookie since we want to protect logout CSRF and
506
-	 * also we can't directly interfere with PHP's session mechanism.
507
-	 */
508
-	private static function performSameSiteCookieProtection() {
509
-		$request = \OC::$server->getRequest();
510
-
511
-		// Some user agents are notorious and don't really properly follow HTTP
512
-		// specifications. For those, have an automated opt-out. Since the protection
513
-		// for remote.php is applied in base.php as starting point we need to opt out
514
-		// here.
515
-		$incompatibleUserAgents = [
516
-			// OS X Finder
517
-			'/^WebDAVFS/',
518
-		];
519
-		if($request->isUserAgent($incompatibleUserAgents)) {
520
-			return;
521
-		}
522
-
523
-		if(count($_COOKIE) > 0) {
524
-			$requestUri = $request->getScriptName();
525
-			$processingScript = explode('/', $requestUri);
526
-			$processingScript = $processingScript[count($processingScript)-1];
527
-
528
-			// index.php routes are handled in the middleware
529
-			if($processingScript === 'index.php') {
530
-				return;
531
-			}
532
-
533
-			// All other endpoints require the lax and the strict cookie
534
-			if(!$request->passesStrictCookieCheck()) {
535
-				self::sendSameSiteCookies();
536
-				// Debug mode gets access to the resources without strict cookie
537
-				// due to the fact that the SabreDAV browser also lives there.
538
-				if(!\OC::$server->getConfig()->getSystemValue('debug', false)) {
539
-					http_response_code(\OCP\AppFramework\Http::STATUS_SERVICE_UNAVAILABLE);
540
-					exit();
541
-				}
542
-			}
543
-		} elseif(!isset($_COOKIE['nc_sameSiteCookielax']) || !isset($_COOKIE['nc_sameSiteCookiestrict'])) {
544
-			self::sendSameSiteCookies();
545
-		}
546
-	}
547
-
548
-	public static function init() {
549
-		// calculate the root directories
550
-		OC::$SERVERROOT = str_replace("\\", '/', substr(__DIR__, 0, -4));
551
-
552
-		// register autoloader
553
-		$loaderStart = microtime(true);
554
-		require_once __DIR__ . '/autoloader.php';
555
-		self::$loader = new \OC\Autoloader([
556
-			OC::$SERVERROOT . '/lib/private/legacy',
557
-		]);
558
-		if (defined('PHPUNIT_RUN')) {
559
-			self::$loader->addValidRoot(OC::$SERVERROOT . '/tests');
560
-		}
561
-		spl_autoload_register(array(self::$loader, 'load'));
562
-		$loaderEnd = microtime(true);
563
-
564
-		self::$CLI = (php_sapi_name() == 'cli');
565
-
566
-		// Add default composer PSR-4 autoloader
567
-		self::$composerAutoloader = require_once OC::$SERVERROOT . '/lib/composer/autoload.php';
568
-
569
-		try {
570
-			self::initPaths();
571
-			// setup 3rdparty autoloader
572
-			$vendorAutoLoad = OC::$SERVERROOT. '/3rdparty/autoload.php';
573
-			if (!file_exists($vendorAutoLoad)) {
574
-				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".');
575
-			}
576
-			require_once $vendorAutoLoad;
577
-
578
-		} catch (\RuntimeException $e) {
579
-			if (!self::$CLI) {
580
-				$claimedProtocol = strtoupper($_SERVER['SERVER_PROTOCOL']);
581
-				$protocol = in_array($claimedProtocol, ['HTTP/1.0', 'HTTP/1.1', 'HTTP/2']) ? $claimedProtocol : 'HTTP/1.1';
582
-				header($protocol . ' ' . OC_Response::STATUS_SERVICE_UNAVAILABLE);
583
-			}
584
-			// we can't use the template error page here, because this needs the
585
-			// DI container which isn't available yet
586
-			print($e->getMessage());
587
-			exit();
588
-		}
589
-
590
-		// setup the basic server
591
-		self::$server = new \OC\Server(\OC::$WEBROOT, self::$config);
592
-		\OC::$server->getEventLogger()->log('autoloader', 'Autoloader', $loaderStart, $loaderEnd);
593
-		\OC::$server->getEventLogger()->start('boot', 'Initialize');
594
-
595
-		// Don't display errors and log them
596
-		error_reporting(E_ALL | E_STRICT);
597
-		@ini_set('display_errors', 0);
598
-		@ini_set('log_errors', 1);
599
-
600
-		if(!date_default_timezone_set('UTC')) {
601
-			throw new \RuntimeException('Could not set timezone to UTC');
602
-		};
603
-
604
-		//try to configure php to enable big file uploads.
605
-		//this doesn´t work always depending on the webserver and php configuration.
606
-		//Let´s try to overwrite some defaults anyway
607
-
608
-		//try to set the maximum execution time to 60min
609
-		if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
610
-			@set_time_limit(3600);
611
-		}
612
-		@ini_set('max_execution_time', 3600);
613
-		@ini_set('max_input_time', 3600);
614
-
615
-		//try to set the maximum filesize to 10G
616
-		@ini_set('upload_max_filesize', '10G');
617
-		@ini_set('post_max_size', '10G');
618
-		@ini_set('file_uploads', '50');
619
-
620
-		self::setRequiredIniValues();
621
-		self::handleAuthHeaders();
622
-		self::registerAutoloaderCache();
623
-
624
-		// initialize intl fallback is necessary
625
-		\Patchwork\Utf8\Bootup::initIntl();
626
-		OC_Util::isSetLocaleWorking();
627
-
628
-		if (!defined('PHPUNIT_RUN')) {
629
-			OC\Log\ErrorHandler::setLogger(\OC::$server->getLogger());
630
-			$debug = \OC::$server->getConfig()->getSystemValue('debug', false);
631
-			OC\Log\ErrorHandler::register($debug);
632
-		}
633
-
634
-		\OC::$server->getEventLogger()->start('init_session', 'Initialize session');
635
-		OC_App::loadApps(array('session'));
636
-		if (!self::$CLI) {
637
-			self::initSession();
638
-		}
639
-		\OC::$server->getEventLogger()->end('init_session');
640
-		self::checkConfig();
641
-		self::checkInstalled();
642
-
643
-		OC_Response::addSecurityHeaders();
644
-		if(self::$server->getRequest()->getServerProtocol() === 'https') {
645
-			ini_set('session.cookie_secure', true);
646
-		}
647
-
648
-		self::performSameSiteCookieProtection();
649
-
650
-		if (!defined('OC_CONSOLE')) {
651
-			$errors = OC_Util::checkServer(\OC::$server->getSystemConfig());
652
-			if (count($errors) > 0) {
653
-				if (self::$CLI) {
654
-					// Convert l10n string into regular string for usage in database
655
-					$staticErrors = [];
656
-					foreach ($errors as $error) {
657
-						echo $error['error'] . "\n";
658
-						echo $error['hint'] . "\n\n";
659
-						$staticErrors[] = [
660
-							'error' => (string)$error['error'],
661
-							'hint' => (string)$error['hint'],
662
-						];
663
-					}
664
-
665
-					try {
666
-						\OC::$server->getConfig()->setAppValue('core', 'cronErrors', json_encode($staticErrors));
667
-					} catch (\Exception $e) {
668
-						echo('Writing to database failed');
669
-					}
670
-					exit(1);
671
-				} else {
672
-					OC_Response::setStatus(OC_Response::STATUS_SERVICE_UNAVAILABLE);
673
-					OC_Util::addStyle('guest');
674
-					OC_Template::printGuestPage('', 'error', array('errors' => $errors));
675
-					exit;
676
-				}
677
-			} elseif (self::$CLI && \OC::$server->getConfig()->getSystemValue('installed', false)) {
678
-				\OC::$server->getConfig()->deleteAppValue('core', 'cronErrors');
679
-			}
680
-		}
681
-		//try to set the session lifetime
682
-		$sessionLifeTime = self::getSessionLifeTime();
683
-		@ini_set('gc_maxlifetime', (string)$sessionLifeTime);
684
-
685
-		$systemConfig = \OC::$server->getSystemConfig();
686
-
687
-		// User and Groups
688
-		if (!$systemConfig->getValue("installed", false)) {
689
-			self::$server->getSession()->set('user_id', '');
690
-		}
691
-
692
-		OC_User::useBackend(new \OC\User\Database());
693
-		\OC::$server->getGroupManager()->addBackend(new \OC\Group\Database());
694
-
695
-		// Subscribe to the hook
696
-		\OCP\Util::connectHook(
697
-			'\OCA\Files_Sharing\API\Server2Server',
698
-			'preLoginNameUsedAsUserName',
699
-			'\OC\User\Database',
700
-			'preLoginNameUsedAsUserName'
701
-		);
702
-
703
-		//setup extra user backends
704
-		if (!\OCP\Util::needUpgrade()) {
705
-			OC_User::setupBackends();
706
-		} else {
707
-			// Run upgrades in incognito mode
708
-			OC_User::setIncognitoMode(true);
709
-		}
710
-
711
-		self::registerCleanupHooks();
712
-		self::registerFilesystemHooks();
713
-		self::registerShareHooks();
714
-		self::registerEncryptionWrapper();
715
-		self::registerEncryptionHooks();
716
-		self::registerAccountHooks();
717
-		self::registerSettingsHooks();
718
-
719
-		$settings = new \OC\Settings\Application();
720
-		$settings->register();
721
-
722
-		//make sure temporary files are cleaned up
723
-		$tmpManager = \OC::$server->getTempManager();
724
-		register_shutdown_function(array($tmpManager, 'clean'));
725
-		$lockProvider = \OC::$server->getLockingProvider();
726
-		register_shutdown_function(array($lockProvider, 'releaseAll'));
727
-
728
-		// Check whether the sample configuration has been copied
729
-		if($systemConfig->getValue('copied_sample_config', false)) {
730
-			$l = \OC::$server->getL10N('lib');
731
-			header('HTTP/1.1 503 Service Temporarily Unavailable');
732
-			header('Status: 503 Service Temporarily Unavailable');
733
-			OC_Template::printErrorPage(
734
-				$l->t('Sample configuration detected'),
735
-				$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')
736
-			);
737
-			return;
738
-		}
739
-
740
-		$request = \OC::$server->getRequest();
741
-		$host = $request->getInsecureServerHost();
742
-		/**
743
-		 * if the host passed in headers isn't trusted
744
-		 * FIXME: Should not be in here at all :see_no_evil:
745
-		 */
746
-		if (!OC::$CLI
747
-			// overwritehost is always trusted, workaround to not have to make
748
-			// \OC\AppFramework\Http\Request::getOverwriteHost public
749
-			&& self::$server->getConfig()->getSystemValue('overwritehost') === ''
750
-			&& !\OC::$server->getTrustedDomainHelper()->isTrustedDomain($host)
751
-			&& self::$server->getConfig()->getSystemValue('installed', false)
752
-		) {
753
-			// Allow access to CSS resources
754
-			$isScssRequest = false;
755
-			if(strpos($request->getPathInfo(), '/css/') === 0) {
756
-				$isScssRequest = true;
757
-			}
758
-
759
-			if (!$isScssRequest) {
760
-				header('HTTP/1.1 400 Bad Request');
761
-				header('Status: 400 Bad Request');
762
-
763
-				\OC::$server->getLogger()->warning(
764
-					'Trusted domain error. "{remoteAddress}" tried to access using "{host}" as host.',
765
-					[
766
-						'app' => 'core',
767
-						'remoteAddress' => $request->getRemoteAddress(),
768
-						'host' => $host,
769
-					]
770
-				);
771
-
772
-				$tmpl = new OCP\Template('core', 'untrustedDomain', 'guest');
773
-				$tmpl->assign('domain', $host);
774
-				$tmpl->printPage();
775
-
776
-				exit();
777
-			}
778
-		}
779
-		\OC::$server->getEventLogger()->end('boot');
780
-	}
781
-
782
-	/**
783
-	 * register hooks for the cleanup of cache and bruteforce protection
784
-	 */
785
-	public static function registerCleanupHooks() {
786
-		//don't try to do this before we are properly setup
787
-		if (\OC::$server->getSystemConfig()->getValue('installed', false) && !\OCP\Util::needUpgrade()) {
788
-
789
-			// NOTE: This will be replaced to use OCP
790
-			$userSession = self::$server->getUserSession();
791
-			$userSession->listen('\OC\User', 'postLogin', function () use ($userSession) {
792
-				if (!defined('PHPUNIT_RUN')) {
793
-					// reset brute force delay for this IP address and username
794
-					$uid = \OC::$server->getUserSession()->getUser()->getUID();
795
-					$request = \OC::$server->getRequest();
796
-					$throttler = \OC::$server->getBruteForceThrottler();
797
-					$throttler->resetDelay($request->getRemoteAddress(), 'login', ['user' => $uid]);
798
-				}
799
-
800
-				try {
801
-					$cache = new \OC\Cache\File();
802
-					$cache->gc();
803
-				} catch (\OC\ServerNotAvailableException $e) {
804
-					// not a GC exception, pass it on
805
-					throw $e;
806
-				} catch (\OC\ForbiddenException $e) {
807
-					// filesystem blocked for this request, ignore
808
-				} catch (\Exception $e) {
809
-					// a GC exception should not prevent users from using OC,
810
-					// so log the exception
811
-					\OC::$server->getLogger()->warning('Exception when running cache gc: ' . $e->getMessage(), array('app' => 'core'));
812
-				}
813
-			});
814
-		}
815
-	}
816
-
817
-	public static function registerSettingsHooks() {
818
-		$dispatcher = \OC::$server->getEventDispatcher();
819
-		$dispatcher->addListener(OCP\App\ManagerEvent::EVENT_APP_DISABLE, function($event) {
820
-			/** @var \OCP\App\ManagerEvent $event */
821
-			\OC::$server->getSettingsManager()->onAppDisabled($event->getAppID());
822
-		});
823
-		$dispatcher->addListener(OCP\App\ManagerEvent::EVENT_APP_UPDATE, function($event) {
824
-			/** @var \OCP\App\ManagerEvent $event */
825
-			$jobList = \OC::$server->getJobList();
826
-			$job = 'OC\\Settings\\RemoveOrphaned';
827
-			if(!($jobList->has($job, null))) {
828
-				$jobList->add($job);
829
-			}
830
-		});
831
-	}
832
-
833
-	private static function registerEncryptionWrapper() {
834
-		$manager = self::$server->getEncryptionManager();
835
-		\OCP\Util::connectHook('OC_Filesystem', 'preSetup', $manager, 'setupStorage');
836
-	}
837
-
838
-	private static function registerEncryptionHooks() {
839
-		$enabled = self::$server->getEncryptionManager()->isEnabled();
840
-		if ($enabled) {
841
-			\OCP\Util::connectHook('OCP\Share', 'post_shared', 'OC\Encryption\HookManager', 'postShared');
842
-			\OCP\Util::connectHook('OCP\Share', 'post_unshare', 'OC\Encryption\HookManager', 'postUnshared');
843
-			\OCP\Util::connectHook('OC_Filesystem', 'post_rename', 'OC\Encryption\HookManager', 'postRename');
844
-			\OCP\Util::connectHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', 'OC\Encryption\HookManager', 'postRestore');
845
-		}
846
-	}
847
-
848
-	private static function registerAccountHooks() {
849
-		$hookHandler = new \OC\Accounts\Hooks(\OC::$server->getLogger());
850
-		\OCP\Util::connectHook('OC_User', 'changeUser', $hookHandler, 'changeUserHook');
851
-	}
852
-
853
-	/**
854
-	 * register hooks for the filesystem
855
-	 */
856
-	public static function registerFilesystemHooks() {
857
-		// Check for blacklisted files
858
-		OC_Hook::connect('OC_Filesystem', 'write', 'OC\Files\Filesystem', 'isBlacklisted');
859
-		OC_Hook::connect('OC_Filesystem', 'rename', 'OC\Files\Filesystem', 'isBlacklisted');
860
-	}
861
-
862
-	/**
863
-	 * register hooks for sharing
864
-	 */
865
-	public static function registerShareHooks() {
866
-		if (\OC::$server->getSystemConfig()->getValue('installed')) {
867
-			OC_Hook::connect('OC_User', 'post_deleteUser', 'OC\Share20\Hooks', 'post_deleteUser');
868
-			OC_Hook::connect('OC_User', 'post_removeFromGroup', 'OC\Share20\Hooks', 'post_removeFromGroup');
869
-			OC_Hook::connect('OC_User', 'post_deleteGroup', 'OC\Share20\Hooks', 'post_deleteGroup');
870
-		}
871
-	}
872
-
873
-	protected static function registerAutoloaderCache() {
874
-		// The class loader takes an optional low-latency cache, which MUST be
875
-		// namespaced. The instanceid is used for namespacing, but might be
876
-		// unavailable at this point. Furthermore, it might not be possible to
877
-		// generate an instanceid via \OC_Util::getInstanceId() because the
878
-		// config file may not be writable. As such, we only register a class
879
-		// loader cache if instanceid is available without trying to create one.
880
-		$instanceId = \OC::$server->getSystemConfig()->getValue('instanceid', null);
881
-		if ($instanceId) {
882
-			try {
883
-				$memcacheFactory = \OC::$server->getMemCacheFactory();
884
-				self::$loader->setMemoryCache($memcacheFactory->createLocal('Autoloader'));
885
-			} catch (\Exception $ex) {
886
-			}
887
-		}
888
-	}
889
-
890
-	/**
891
-	 * Handle the request
892
-	 */
893
-	public static function handleRequest() {
894
-
895
-		\OC::$server->getEventLogger()->start('handle_request', 'Handle request');
896
-		$systemConfig = \OC::$server->getSystemConfig();
897
-		// load all the classpaths from the enabled apps so they are available
898
-		// in the routing files of each app
899
-		OC::loadAppClassPaths();
900
-
901
-		// Check if Nextcloud is installed or in maintenance (update) mode
902
-		if (!$systemConfig->getValue('installed', false)) {
903
-			\OC::$server->getSession()->clear();
904
-			$setupHelper = new OC\Setup(
905
-				$systemConfig,
906
-				\OC::$server->getIniWrapper(),
907
-				\OC::$server->getL10N('lib'),
908
-				\OC::$server->query(\OCP\Defaults::class),
909
-				\OC::$server->getLogger(),
910
-				\OC::$server->getSecureRandom(),
911
-				\OC::$server->query(\OC\Installer::class)
912
-			);
913
-			$controller = new OC\Core\Controller\SetupController($setupHelper);
914
-			$controller->run($_POST);
915
-			exit();
916
-		}
917
-
918
-		$request = \OC::$server->getRequest();
919
-		$requestPath = $request->getRawPathInfo();
920
-		if ($requestPath === '/heartbeat') {
921
-			return;
922
-		}
923
-		if (substr($requestPath, -3) !== '.js') { // we need these files during the upgrade
924
-			self::checkMaintenanceMode();
925
-
926
-			if (\OCP\Util::needUpgrade()) {
927
-				if (function_exists('opcache_reset')) {
928
-					opcache_reset();
929
-				}
930
-				if (!$systemConfig->getValue('maintenance', false)) {
931
-					self::printUpgradePage($systemConfig);
932
-					exit();
933
-				}
934
-			}
935
-		}
936
-
937
-		// emergency app disabling
938
-		if ($requestPath === '/disableapp'
939
-			&& $request->getMethod() === 'POST'
940
-			&& ((array)$request->getParam('appid')) !== ''
941
-		) {
942
-			\OCP\JSON::callCheck();
943
-			\OCP\JSON::checkAdminUser();
944
-			$appIds = (array)$request->getParam('appid');
945
-			foreach($appIds as $appId) {
946
-				$appId = \OC_App::cleanAppId($appId);
947
-				\OC_App::disable($appId);
948
-			}
949
-			\OC_JSON::success();
950
-			exit();
951
-		}
952
-
953
-		// Always load authentication apps
954
-		OC_App::loadApps(['authentication']);
955
-
956
-		// Load minimum set of apps
957
-		if (!\OCP\Util::needUpgrade()
958
-			&& !$systemConfig->getValue('maintenance', false)) {
959
-			// For logged-in users: Load everything
960
-			if(\OC::$server->getUserSession()->isLoggedIn()) {
961
-				OC_App::loadApps();
962
-			} else {
963
-				// For guests: Load only filesystem and logging
964
-				OC_App::loadApps(array('filesystem', 'logging'));
965
-				self::handleLogin($request);
966
-			}
967
-		}
968
-
969
-		if (!self::$CLI) {
970
-			try {
971
-				if (!$systemConfig->getValue('maintenance', false) && !\OCP\Util::needUpgrade()) {
972
-					OC_App::loadApps(array('filesystem', 'logging'));
973
-					OC_App::loadApps();
974
-				}
975
-				OC_Util::setupFS();
976
-				OC::$server->getRouter()->match(\OC::$server->getRequest()->getRawPathInfo());
977
-				return;
978
-			} catch (Symfony\Component\Routing\Exception\ResourceNotFoundException $e) {
979
-				//header('HTTP/1.0 404 Not Found');
980
-			} catch (Symfony\Component\Routing\Exception\MethodNotAllowedException $e) {
981
-				OC_Response::setStatus(405);
982
-				return;
983
-			}
984
-		}
985
-
986
-		// Handle WebDAV
987
-		if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'PROPFIND') {
988
-			// not allowed any more to prevent people
989
-			// mounting this root directly.
990
-			// Users need to mount remote.php/webdav instead.
991
-			header('HTTP/1.1 405 Method Not Allowed');
992
-			header('Status: 405 Method Not Allowed');
993
-			return;
994
-		}
995
-
996
-		// Someone is logged in
997
-		if (\OC::$server->getUserSession()->isLoggedIn()) {
998
-			OC_App::loadApps();
999
-			OC_User::setupBackends();
1000
-			OC_Util::setupFS();
1001
-			// FIXME
1002
-			// Redirect to default application
1003
-			OC_Util::redirectToDefaultPage();
1004
-		} else {
1005
-			// Not handled and not logged in
1006
-			header('Location: '.\OC::$server->getURLGenerator()->linkToRouteAbsolute('core.login.showLoginForm'));
1007
-		}
1008
-	}
1009
-
1010
-	/**
1011
-	 * Check login: apache auth, auth token, basic auth
1012
-	 *
1013
-	 * @param OCP\IRequest $request
1014
-	 * @return boolean
1015
-	 */
1016
-	static function handleLogin(OCP\IRequest $request) {
1017
-		$userSession = self::$server->getUserSession();
1018
-		if (OC_User::handleApacheAuth()) {
1019
-			return true;
1020
-		}
1021
-		if ($userSession->tryTokenLogin($request)) {
1022
-			return true;
1023
-		}
1024
-		if (isset($_COOKIE['nc_username'])
1025
-			&& isset($_COOKIE['nc_token'])
1026
-			&& isset($_COOKIE['nc_session_id'])
1027
-			&& $userSession->loginWithCookie($_COOKIE['nc_username'], $_COOKIE['nc_token'], $_COOKIE['nc_session_id'])) {
1028
-			return true;
1029
-		}
1030
-		if ($userSession->tryBasicAuthLogin($request, \OC::$server->getBruteForceThrottler())) {
1031
-			return true;
1032
-		}
1033
-		return false;
1034
-	}
1035
-
1036
-	protected static function handleAuthHeaders() {
1037
-		//copy http auth headers for apache+php-fcgid work around
1038
-		if (isset($_SERVER['HTTP_XAUTHORIZATION']) && !isset($_SERVER['HTTP_AUTHORIZATION'])) {
1039
-			$_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['HTTP_XAUTHORIZATION'];
1040
-		}
1041
-
1042
-		// Extract PHP_AUTH_USER/PHP_AUTH_PW from other headers if necessary.
1043
-		$vars = array(
1044
-			'HTTP_AUTHORIZATION', // apache+php-cgi work around
1045
-			'REDIRECT_HTTP_AUTHORIZATION', // apache+php-cgi alternative
1046
-		);
1047
-		foreach ($vars as $var) {
1048
-			if (isset($_SERVER[$var]) && preg_match('/Basic\s+(.*)$/i', $_SERVER[$var], $matches)) {
1049
-				list($name, $password) = explode(':', base64_decode($matches[1]), 2);
1050
-				$_SERVER['PHP_AUTH_USER'] = $name;
1051
-				$_SERVER['PHP_AUTH_PW'] = $password;
1052
-				break;
1053
-			}
1054
-		}
1055
-	}
65
+    /**
66
+     * Associative array for autoloading. classname => filename
67
+     */
68
+    public static $CLASSPATH = array();
69
+    /**
70
+     * The installation path for Nextcloud  on the server (e.g. /srv/http/nextcloud)
71
+     */
72
+    public static $SERVERROOT = '';
73
+    /**
74
+     * the current request path relative to the Nextcloud root (e.g. files/index.php)
75
+     */
76
+    private static $SUBURI = '';
77
+    /**
78
+     * the Nextcloud root path for http requests (e.g. nextcloud/)
79
+     */
80
+    public static $WEBROOT = '';
81
+    /**
82
+     * The installation path array of the apps folder on the server (e.g. /srv/http/nextcloud) 'path' and
83
+     * web path in 'url'
84
+     */
85
+    public static $APPSROOTS = array();
86
+
87
+    /**
88
+     * @var string
89
+     */
90
+    public static $configDir;
91
+
92
+    /**
93
+     * requested app
94
+     */
95
+    public static $REQUESTEDAPP = '';
96
+
97
+    /**
98
+     * check if Nextcloud runs in cli mode
99
+     */
100
+    public static $CLI = false;
101
+
102
+    /**
103
+     * @var \OC\Autoloader $loader
104
+     */
105
+    public static $loader = null;
106
+
107
+    /** @var \Composer\Autoload\ClassLoader $composerAutoloader */
108
+    public static $composerAutoloader = null;
109
+
110
+    /**
111
+     * @var \OC\Server
112
+     */
113
+    public static $server = null;
114
+
115
+    /**
116
+     * @var \OC\Config
117
+     */
118
+    private static $config = null;
119
+
120
+    /**
121
+     * @throws \RuntimeException when the 3rdparty directory is missing or
122
+     * the app path list is empty or contains an invalid path
123
+     */
124
+    public static function initPaths() {
125
+        if(defined('PHPUNIT_CONFIG_DIR')) {
126
+            self::$configDir = OC::$SERVERROOT . '/' . PHPUNIT_CONFIG_DIR . '/';
127
+        } elseif(defined('PHPUNIT_RUN') and PHPUNIT_RUN and is_dir(OC::$SERVERROOT . '/tests/config/')) {
128
+            self::$configDir = OC::$SERVERROOT . '/tests/config/';
129
+        } elseif($dir = getenv('NEXTCLOUD_CONFIG_DIR')) {
130
+            self::$configDir = rtrim($dir, '/') . '/';
131
+        } else {
132
+            self::$configDir = OC::$SERVERROOT . '/config/';
133
+        }
134
+        self::$config = new \OC\Config(self::$configDir);
135
+
136
+        OC::$SUBURI = str_replace("\\", "/", substr(realpath($_SERVER["SCRIPT_FILENAME"]), strlen(OC::$SERVERROOT)));
137
+        /**
138
+         * FIXME: The following lines are required because we can't yet instantiate
139
+         *        \OC::$server->getRequest() since \OC::$server does not yet exist.
140
+         */
141
+        $params = [
142
+            'server' => [
143
+                'SCRIPT_NAME' => $_SERVER['SCRIPT_NAME'],
144
+                'SCRIPT_FILENAME' => $_SERVER['SCRIPT_FILENAME'],
145
+            ],
146
+        ];
147
+        $fakeRequest = new \OC\AppFramework\Http\Request($params, null, new \OC\AllConfig(new \OC\SystemConfig(self::$config)));
148
+        $scriptName = $fakeRequest->getScriptName();
149
+        if (substr($scriptName, -1) == '/') {
150
+            $scriptName .= 'index.php';
151
+            //make sure suburi follows the same rules as scriptName
152
+            if (substr(OC::$SUBURI, -9) != 'index.php') {
153
+                if (substr(OC::$SUBURI, -1) != '/') {
154
+                    OC::$SUBURI = OC::$SUBURI . '/';
155
+                }
156
+                OC::$SUBURI = OC::$SUBURI . 'index.php';
157
+            }
158
+        }
159
+
160
+
161
+        if (OC::$CLI) {
162
+            OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
163
+        } else {
164
+            if (substr($scriptName, 0 - strlen(OC::$SUBURI)) === OC::$SUBURI) {
165
+                OC::$WEBROOT = substr($scriptName, 0, 0 - strlen(OC::$SUBURI));
166
+
167
+                if (OC::$WEBROOT != '' && OC::$WEBROOT[0] !== '/') {
168
+                    OC::$WEBROOT = '/' . OC::$WEBROOT;
169
+                }
170
+            } else {
171
+                // The scriptName is not ending with OC::$SUBURI
172
+                // This most likely means that we are calling from CLI.
173
+                // However some cron jobs still need to generate
174
+                // a web URL, so we use overwritewebroot as a fallback.
175
+                OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
176
+            }
177
+
178
+            // Resolve /nextcloud to /nextcloud/ to ensure to always have a trailing
179
+            // slash which is required by URL generation.
180
+            if (isset($_SERVER['REQUEST_URI']) && $_SERVER['REQUEST_URI'] === \OC::$WEBROOT &&
181
+                    substr($_SERVER['REQUEST_URI'], -1) !== '/') {
182
+                header('Location: '.\OC::$WEBROOT.'/');
183
+                exit();
184
+            }
185
+        }
186
+
187
+        // search the apps folder
188
+        $config_paths = self::$config->getValue('apps_paths', array());
189
+        if (!empty($config_paths)) {
190
+            foreach ($config_paths as $paths) {
191
+                if (isset($paths['url']) && isset($paths['path'])) {
192
+                    $paths['url'] = rtrim($paths['url'], '/');
193
+                    $paths['path'] = rtrim($paths['path'], '/');
194
+                    OC::$APPSROOTS[] = $paths;
195
+                }
196
+            }
197
+        } elseif (file_exists(OC::$SERVERROOT . '/apps')) {
198
+            OC::$APPSROOTS[] = array('path' => OC::$SERVERROOT . '/apps', 'url' => '/apps', 'writable' => true);
199
+        } elseif (file_exists(OC::$SERVERROOT . '/../apps')) {
200
+            OC::$APPSROOTS[] = array(
201
+                'path' => rtrim(dirname(OC::$SERVERROOT), '/') . '/apps',
202
+                'url' => '/apps',
203
+                'writable' => true
204
+            );
205
+        }
206
+
207
+        if (empty(OC::$APPSROOTS)) {
208
+            throw new \RuntimeException('apps directory not found! Please put the Nextcloud apps folder in the Nextcloud folder'
209
+                . ' or the folder above. You can also configure the location in the config.php file.');
210
+        }
211
+        $paths = array();
212
+        foreach (OC::$APPSROOTS as $path) {
213
+            $paths[] = $path['path'];
214
+            if (!is_dir($path['path'])) {
215
+                throw new \RuntimeException(sprintf('App directory "%s" not found! Please put the Nextcloud apps folder in the'
216
+                    . ' Nextcloud folder or the folder above. You can also configure the location in the'
217
+                    . ' config.php file.', $path['path']));
218
+            }
219
+        }
220
+
221
+        // set the right include path
222
+        set_include_path(
223
+            implode(PATH_SEPARATOR, $paths)
224
+        );
225
+    }
226
+
227
+    public static function checkConfig() {
228
+        $l = \OC::$server->getL10N('lib');
229
+
230
+        // Create config if it does not already exist
231
+        $configFilePath = self::$configDir .'/config.php';
232
+        if(!file_exists($configFilePath)) {
233
+            @touch($configFilePath);
234
+        }
235
+
236
+        // Check if config is writable
237
+        $configFileWritable = is_writable($configFilePath);
238
+        if (!$configFileWritable && !OC_Helper::isReadOnlyConfigEnabled()
239
+            || !$configFileWritable && \OCP\Util::needUpgrade()) {
240
+
241
+            $urlGenerator = \OC::$server->getURLGenerator();
242
+
243
+            if (self::$CLI) {
244
+                echo $l->t('Cannot write into "config" directory!')."\n";
245
+                echo $l->t('This can usually be fixed by giving the webserver write access to the config directory')."\n";
246
+                echo "\n";
247
+                echo $l->t('See %s', [ $urlGenerator->linkToDocs('admin-dir_permissions') ])."\n";
248
+                exit;
249
+            } else {
250
+                OC_Template::printErrorPage(
251
+                    $l->t('Cannot write into "config" directory!'),
252
+                    $l->t('This can usually be fixed by giving the webserver write access to the config directory. See %s',
253
+                        [ $urlGenerator->linkToDocs('admin-dir_permissions') ])
254
+                );
255
+            }
256
+        }
257
+    }
258
+
259
+    public static function checkInstalled() {
260
+        if (defined('OC_CONSOLE')) {
261
+            return;
262
+        }
263
+        // Redirect to installer if not installed
264
+        if (!\OC::$server->getSystemConfig()->getValue('installed', false) && OC::$SUBURI !== '/index.php' && OC::$SUBURI !== '/status.php') {
265
+            if (OC::$CLI) {
266
+                throw new Exception('Not installed');
267
+            } else {
268
+                $url = OC::$WEBROOT . '/index.php';
269
+                header('Location: ' . $url);
270
+            }
271
+            exit();
272
+        }
273
+    }
274
+
275
+    public static function checkMaintenanceMode() {
276
+        // Allow ajax update script to execute without being stopped
277
+        if (\OC::$server->getSystemConfig()->getValue('maintenance', false) && OC::$SUBURI != '/core/ajax/update.php') {
278
+            // send http status 503
279
+            header('HTTP/1.1 503 Service Temporarily Unavailable');
280
+            header('Status: 503 Service Temporarily Unavailable');
281
+            header('Retry-After: 120');
282
+
283
+            // render error page
284
+            $template = new OC_Template('', 'update.user', 'guest');
285
+            OC_Util::addScript('maintenance-check');
286
+            OC_Util::addStyle('core', 'guest');
287
+            $template->printPage();
288
+            die();
289
+        }
290
+    }
291
+
292
+    /**
293
+     * Prints the upgrade page
294
+     *
295
+     * @param \OC\SystemConfig $systemConfig
296
+     */
297
+    private static function printUpgradePage(\OC\SystemConfig $systemConfig) {
298
+        $disableWebUpdater = $systemConfig->getValue('upgrade.disable-web', false);
299
+        $tooBig = false;
300
+        if (!$disableWebUpdater) {
301
+            $apps = \OC::$server->getAppManager();
302
+            if ($apps->isInstalled('user_ldap')) {
303
+                $qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
304
+
305
+                $result = $qb->selectAlias($qb->createFunction('COUNT(*)'), 'user_count')
306
+                    ->from('ldap_user_mapping')
307
+                    ->execute();
308
+                $row = $result->fetch();
309
+                $result->closeCursor();
310
+
311
+                $tooBig = ($row['user_count'] > 50);
312
+            }
313
+            if (!$tooBig && $apps->isInstalled('user_saml')) {
314
+                $qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
315
+
316
+                $result = $qb->selectAlias($qb->createFunction('COUNT(*)'), 'user_count')
317
+                    ->from('user_saml_users')
318
+                    ->execute();
319
+                $row = $result->fetch();
320
+                $result->closeCursor();
321
+
322
+                $tooBig = ($row['user_count'] > 50);
323
+            }
324
+            if (!$tooBig) {
325
+                // count users
326
+                $stats = \OC::$server->getUserManager()->countUsers();
327
+                $totalUsers = array_sum($stats);
328
+                $tooBig = ($totalUsers > 50);
329
+            }
330
+        }
331
+        $ignoreTooBigWarning = isset($_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup']) &&
332
+            $_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup'] === 'IAmSuperSureToDoThis';
333
+
334
+        if ($disableWebUpdater || ($tooBig && !$ignoreTooBigWarning)) {
335
+            // send http status 503
336
+            header('HTTP/1.1 503 Service Temporarily Unavailable');
337
+            header('Status: 503 Service Temporarily Unavailable');
338
+            header('Retry-After: 120');
339
+
340
+            // render error page
341
+            $template = new OC_Template('', 'update.use-cli', 'guest');
342
+            $template->assign('productName', 'nextcloud'); // for now
343
+            $template->assign('version', OC_Util::getVersionString());
344
+            $template->assign('tooBig', $tooBig);
345
+
346
+            $template->printPage();
347
+            die();
348
+        }
349
+
350
+        // check whether this is a core update or apps update
351
+        $installedVersion = $systemConfig->getValue('version', '0.0.0');
352
+        $currentVersion = implode('.', \OCP\Util::getVersion());
353
+
354
+        // if not a core upgrade, then it's apps upgrade
355
+        $isAppsOnlyUpgrade = (version_compare($currentVersion, $installedVersion, '='));
356
+
357
+        $oldTheme = $systemConfig->getValue('theme');
358
+        $systemConfig->setValue('theme', '');
359
+        OC_Util::addScript('config'); // needed for web root
360
+        OC_Util::addScript('update');
361
+
362
+        /** @var \OC\App\AppManager $appManager */
363
+        $appManager = \OC::$server->getAppManager();
364
+
365
+        $tmpl = new OC_Template('', 'update.admin', 'guest');
366
+        $tmpl->assign('version', OC_Util::getVersionString());
367
+        $tmpl->assign('isAppsOnlyUpgrade', $isAppsOnlyUpgrade);
368
+
369
+        // get third party apps
370
+        $ocVersion = \OCP\Util::getVersion();
371
+        $incompatibleApps = $appManager->getIncompatibleApps($ocVersion);
372
+        $incompatibleShippedApps = [];
373
+        foreach ($incompatibleApps as $appInfo) {
374
+            if ($appManager->isShipped($appInfo['id'])) {
375
+                $incompatibleShippedApps[] = $appInfo['name'] . ' (' . $appInfo['id'] . ')';
376
+            }
377
+        }
378
+
379
+        if (!empty($incompatibleShippedApps)) {
380
+            $l = \OC::$server->getL10N('core');
381
+            $hint = $l->t('The files of the app %$1s were not replaced correctly. Make sure it is a version compatible with the server.', [implode(', ', $incompatibleShippedApps)]);
382
+            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);
383
+        }
384
+
385
+        $tmpl->assign('appsToUpgrade', $appManager->getAppsNeedingUpgrade($ocVersion));
386
+        $tmpl->assign('incompatibleAppsList', $incompatibleApps);
387
+        $tmpl->assign('productName', 'Nextcloud'); // for now
388
+        $tmpl->assign('oldTheme', $oldTheme);
389
+        $tmpl->printPage();
390
+    }
391
+
392
+    public static function initSession() {
393
+        // prevents javascript from accessing php session cookies
394
+        ini_set('session.cookie_httponly', true);
395
+
396
+        // set the cookie path to the Nextcloud directory
397
+        $cookie_path = OC::$WEBROOT ? : '/';
398
+        ini_set('session.cookie_path', $cookie_path);
399
+
400
+        // Let the session name be changed in the initSession Hook
401
+        $sessionName = OC_Util::getInstanceId();
402
+
403
+        try {
404
+            // Allow session apps to create a custom session object
405
+            $useCustomSession = false;
406
+            $session = self::$server->getSession();
407
+            OC_Hook::emit('OC', 'initSession', array('session' => &$session, 'sessionName' => &$sessionName, 'useCustomSession' => &$useCustomSession));
408
+            if (!$useCustomSession) {
409
+                // set the session name to the instance id - which is unique
410
+                $session = new \OC\Session\Internal($sessionName);
411
+            }
412
+
413
+            $cryptoWrapper = \OC::$server->getSessionCryptoWrapper();
414
+            $session = $cryptoWrapper->wrapSession($session);
415
+            self::$server->setSession($session);
416
+
417
+            // if session can't be started break with http 500 error
418
+        } catch (Exception $e) {
419
+            \OCP\Util::logException('base', $e);
420
+            //show the user a detailed error page
421
+            OC_Response::setStatus(OC_Response::STATUS_INTERNAL_SERVER_ERROR);
422
+            OC_Template::printExceptionErrorPage($e);
423
+            die();
424
+        }
425
+
426
+        $sessionLifeTime = self::getSessionLifeTime();
427
+
428
+        // session timeout
429
+        if ($session->exists('LAST_ACTIVITY') && (time() - $session->get('LAST_ACTIVITY') > $sessionLifeTime)) {
430
+            if (isset($_COOKIE[session_name()])) {
431
+                setcookie(session_name(), null, -1, self::$WEBROOT ? : '/');
432
+            }
433
+            \OC::$server->getUserSession()->logout();
434
+        }
435
+
436
+        $session->set('LAST_ACTIVITY', time());
437
+    }
438
+
439
+    /**
440
+     * @return string
441
+     */
442
+    private static function getSessionLifeTime() {
443
+        return \OC::$server->getConfig()->getSystemValue('session_lifetime', 60 * 60 * 24);
444
+    }
445
+
446
+    public static function loadAppClassPaths() {
447
+        foreach (OC_App::getEnabledApps() as $app) {
448
+            $appPath = OC_App::getAppPath($app);
449
+            if ($appPath === false) {
450
+                continue;
451
+            }
452
+
453
+            $file = $appPath . '/appinfo/classpath.php';
454
+            if (file_exists($file)) {
455
+                require_once $file;
456
+            }
457
+        }
458
+    }
459
+
460
+    /**
461
+     * Try to set some values to the required Nextcloud default
462
+     */
463
+    public static function setRequiredIniValues() {
464
+        @ini_set('default_charset', 'UTF-8');
465
+        @ini_set('gd.jpeg_ignore_warning', 1);
466
+    }
467
+
468
+    /**
469
+     * Send the same site cookies
470
+     */
471
+    private static function sendSameSiteCookies() {
472
+        $cookieParams = session_get_cookie_params();
473
+        $secureCookie = ($cookieParams['secure'] === true) ? 'secure; ' : '';
474
+        $policies = [
475
+            'lax',
476
+            'strict',
477
+        ];
478
+
479
+        // Append __Host to the cookie if it meets the requirements
480
+        $cookiePrefix = '';
481
+        if($cookieParams['secure'] === true && $cookieParams['path'] === '/') {
482
+            $cookiePrefix = '__Host-';
483
+        }
484
+
485
+        foreach($policies as $policy) {
486
+            header(
487
+                sprintf(
488
+                    'Set-Cookie: %snc_sameSiteCookie%s=true; path=%s; httponly;' . $secureCookie . 'expires=Fri, 31-Dec-2100 23:59:59 GMT; SameSite=%s',
489
+                    $cookiePrefix,
490
+                    $policy,
491
+                    $cookieParams['path'],
492
+                    $policy
493
+                ),
494
+                false
495
+            );
496
+        }
497
+    }
498
+
499
+    /**
500
+     * Same Site cookie to further mitigate CSRF attacks. This cookie has to
501
+     * be set in every request if cookies are sent to add a second level of
502
+     * defense against CSRF.
503
+     *
504
+     * If the cookie is not sent this will set the cookie and reload the page.
505
+     * We use an additional cookie since we want to protect logout CSRF and
506
+     * also we can't directly interfere with PHP's session mechanism.
507
+     */
508
+    private static function performSameSiteCookieProtection() {
509
+        $request = \OC::$server->getRequest();
510
+
511
+        // Some user agents are notorious and don't really properly follow HTTP
512
+        // specifications. For those, have an automated opt-out. Since the protection
513
+        // for remote.php is applied in base.php as starting point we need to opt out
514
+        // here.
515
+        $incompatibleUserAgents = [
516
+            // OS X Finder
517
+            '/^WebDAVFS/',
518
+        ];
519
+        if($request->isUserAgent($incompatibleUserAgents)) {
520
+            return;
521
+        }
522
+
523
+        if(count($_COOKIE) > 0) {
524
+            $requestUri = $request->getScriptName();
525
+            $processingScript = explode('/', $requestUri);
526
+            $processingScript = $processingScript[count($processingScript)-1];
527
+
528
+            // index.php routes are handled in the middleware
529
+            if($processingScript === 'index.php') {
530
+                return;
531
+            }
532
+
533
+            // All other endpoints require the lax and the strict cookie
534
+            if(!$request->passesStrictCookieCheck()) {
535
+                self::sendSameSiteCookies();
536
+                // Debug mode gets access to the resources without strict cookie
537
+                // due to the fact that the SabreDAV browser also lives there.
538
+                if(!\OC::$server->getConfig()->getSystemValue('debug', false)) {
539
+                    http_response_code(\OCP\AppFramework\Http::STATUS_SERVICE_UNAVAILABLE);
540
+                    exit();
541
+                }
542
+            }
543
+        } elseif(!isset($_COOKIE['nc_sameSiteCookielax']) || !isset($_COOKIE['nc_sameSiteCookiestrict'])) {
544
+            self::sendSameSiteCookies();
545
+        }
546
+    }
547
+
548
+    public static function init() {
549
+        // calculate the root directories
550
+        OC::$SERVERROOT = str_replace("\\", '/', substr(__DIR__, 0, -4));
551
+
552
+        // register autoloader
553
+        $loaderStart = microtime(true);
554
+        require_once __DIR__ . '/autoloader.php';
555
+        self::$loader = new \OC\Autoloader([
556
+            OC::$SERVERROOT . '/lib/private/legacy',
557
+        ]);
558
+        if (defined('PHPUNIT_RUN')) {
559
+            self::$loader->addValidRoot(OC::$SERVERROOT . '/tests');
560
+        }
561
+        spl_autoload_register(array(self::$loader, 'load'));
562
+        $loaderEnd = microtime(true);
563
+
564
+        self::$CLI = (php_sapi_name() == 'cli');
565
+
566
+        // Add default composer PSR-4 autoloader
567
+        self::$composerAutoloader = require_once OC::$SERVERROOT . '/lib/composer/autoload.php';
568
+
569
+        try {
570
+            self::initPaths();
571
+            // setup 3rdparty autoloader
572
+            $vendorAutoLoad = OC::$SERVERROOT. '/3rdparty/autoload.php';
573
+            if (!file_exists($vendorAutoLoad)) {
574
+                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".');
575
+            }
576
+            require_once $vendorAutoLoad;
577
+
578
+        } catch (\RuntimeException $e) {
579
+            if (!self::$CLI) {
580
+                $claimedProtocol = strtoupper($_SERVER['SERVER_PROTOCOL']);
581
+                $protocol = in_array($claimedProtocol, ['HTTP/1.0', 'HTTP/1.1', 'HTTP/2']) ? $claimedProtocol : 'HTTP/1.1';
582
+                header($protocol . ' ' . OC_Response::STATUS_SERVICE_UNAVAILABLE);
583
+            }
584
+            // we can't use the template error page here, because this needs the
585
+            // DI container which isn't available yet
586
+            print($e->getMessage());
587
+            exit();
588
+        }
589
+
590
+        // setup the basic server
591
+        self::$server = new \OC\Server(\OC::$WEBROOT, self::$config);
592
+        \OC::$server->getEventLogger()->log('autoloader', 'Autoloader', $loaderStart, $loaderEnd);
593
+        \OC::$server->getEventLogger()->start('boot', 'Initialize');
594
+
595
+        // Don't display errors and log them
596
+        error_reporting(E_ALL | E_STRICT);
597
+        @ini_set('display_errors', 0);
598
+        @ini_set('log_errors', 1);
599
+
600
+        if(!date_default_timezone_set('UTC')) {
601
+            throw new \RuntimeException('Could not set timezone to UTC');
602
+        };
603
+
604
+        //try to configure php to enable big file uploads.
605
+        //this doesn´t work always depending on the webserver and php configuration.
606
+        //Let´s try to overwrite some defaults anyway
607
+
608
+        //try to set the maximum execution time to 60min
609
+        if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
610
+            @set_time_limit(3600);
611
+        }
612
+        @ini_set('max_execution_time', 3600);
613
+        @ini_set('max_input_time', 3600);
614
+
615
+        //try to set the maximum filesize to 10G
616
+        @ini_set('upload_max_filesize', '10G');
617
+        @ini_set('post_max_size', '10G');
618
+        @ini_set('file_uploads', '50');
619
+
620
+        self::setRequiredIniValues();
621
+        self::handleAuthHeaders();
622
+        self::registerAutoloaderCache();
623
+
624
+        // initialize intl fallback is necessary
625
+        \Patchwork\Utf8\Bootup::initIntl();
626
+        OC_Util::isSetLocaleWorking();
627
+
628
+        if (!defined('PHPUNIT_RUN')) {
629
+            OC\Log\ErrorHandler::setLogger(\OC::$server->getLogger());
630
+            $debug = \OC::$server->getConfig()->getSystemValue('debug', false);
631
+            OC\Log\ErrorHandler::register($debug);
632
+        }
633
+
634
+        \OC::$server->getEventLogger()->start('init_session', 'Initialize session');
635
+        OC_App::loadApps(array('session'));
636
+        if (!self::$CLI) {
637
+            self::initSession();
638
+        }
639
+        \OC::$server->getEventLogger()->end('init_session');
640
+        self::checkConfig();
641
+        self::checkInstalled();
642
+
643
+        OC_Response::addSecurityHeaders();
644
+        if(self::$server->getRequest()->getServerProtocol() === 'https') {
645
+            ini_set('session.cookie_secure', true);
646
+        }
647
+
648
+        self::performSameSiteCookieProtection();
649
+
650
+        if (!defined('OC_CONSOLE')) {
651
+            $errors = OC_Util::checkServer(\OC::$server->getSystemConfig());
652
+            if (count($errors) > 0) {
653
+                if (self::$CLI) {
654
+                    // Convert l10n string into regular string for usage in database
655
+                    $staticErrors = [];
656
+                    foreach ($errors as $error) {
657
+                        echo $error['error'] . "\n";
658
+                        echo $error['hint'] . "\n\n";
659
+                        $staticErrors[] = [
660
+                            'error' => (string)$error['error'],
661
+                            'hint' => (string)$error['hint'],
662
+                        ];
663
+                    }
664
+
665
+                    try {
666
+                        \OC::$server->getConfig()->setAppValue('core', 'cronErrors', json_encode($staticErrors));
667
+                    } catch (\Exception $e) {
668
+                        echo('Writing to database failed');
669
+                    }
670
+                    exit(1);
671
+                } else {
672
+                    OC_Response::setStatus(OC_Response::STATUS_SERVICE_UNAVAILABLE);
673
+                    OC_Util::addStyle('guest');
674
+                    OC_Template::printGuestPage('', 'error', array('errors' => $errors));
675
+                    exit;
676
+                }
677
+            } elseif (self::$CLI && \OC::$server->getConfig()->getSystemValue('installed', false)) {
678
+                \OC::$server->getConfig()->deleteAppValue('core', 'cronErrors');
679
+            }
680
+        }
681
+        //try to set the session lifetime
682
+        $sessionLifeTime = self::getSessionLifeTime();
683
+        @ini_set('gc_maxlifetime', (string)$sessionLifeTime);
684
+
685
+        $systemConfig = \OC::$server->getSystemConfig();
686
+
687
+        // User and Groups
688
+        if (!$systemConfig->getValue("installed", false)) {
689
+            self::$server->getSession()->set('user_id', '');
690
+        }
691
+
692
+        OC_User::useBackend(new \OC\User\Database());
693
+        \OC::$server->getGroupManager()->addBackend(new \OC\Group\Database());
694
+
695
+        // Subscribe to the hook
696
+        \OCP\Util::connectHook(
697
+            '\OCA\Files_Sharing\API\Server2Server',
698
+            'preLoginNameUsedAsUserName',
699
+            '\OC\User\Database',
700
+            'preLoginNameUsedAsUserName'
701
+        );
702
+
703
+        //setup extra user backends
704
+        if (!\OCP\Util::needUpgrade()) {
705
+            OC_User::setupBackends();
706
+        } else {
707
+            // Run upgrades in incognito mode
708
+            OC_User::setIncognitoMode(true);
709
+        }
710
+
711
+        self::registerCleanupHooks();
712
+        self::registerFilesystemHooks();
713
+        self::registerShareHooks();
714
+        self::registerEncryptionWrapper();
715
+        self::registerEncryptionHooks();
716
+        self::registerAccountHooks();
717
+        self::registerSettingsHooks();
718
+
719
+        $settings = new \OC\Settings\Application();
720
+        $settings->register();
721
+
722
+        //make sure temporary files are cleaned up
723
+        $tmpManager = \OC::$server->getTempManager();
724
+        register_shutdown_function(array($tmpManager, 'clean'));
725
+        $lockProvider = \OC::$server->getLockingProvider();
726
+        register_shutdown_function(array($lockProvider, 'releaseAll'));
727
+
728
+        // Check whether the sample configuration has been copied
729
+        if($systemConfig->getValue('copied_sample_config', false)) {
730
+            $l = \OC::$server->getL10N('lib');
731
+            header('HTTP/1.1 503 Service Temporarily Unavailable');
732
+            header('Status: 503 Service Temporarily Unavailable');
733
+            OC_Template::printErrorPage(
734
+                $l->t('Sample configuration detected'),
735
+                $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')
736
+            );
737
+            return;
738
+        }
739
+
740
+        $request = \OC::$server->getRequest();
741
+        $host = $request->getInsecureServerHost();
742
+        /**
743
+         * if the host passed in headers isn't trusted
744
+         * FIXME: Should not be in here at all :see_no_evil:
745
+         */
746
+        if (!OC::$CLI
747
+            // overwritehost is always trusted, workaround to not have to make
748
+            // \OC\AppFramework\Http\Request::getOverwriteHost public
749
+            && self::$server->getConfig()->getSystemValue('overwritehost') === ''
750
+            && !\OC::$server->getTrustedDomainHelper()->isTrustedDomain($host)
751
+            && self::$server->getConfig()->getSystemValue('installed', false)
752
+        ) {
753
+            // Allow access to CSS resources
754
+            $isScssRequest = false;
755
+            if(strpos($request->getPathInfo(), '/css/') === 0) {
756
+                $isScssRequest = true;
757
+            }
758
+
759
+            if (!$isScssRequest) {
760
+                header('HTTP/1.1 400 Bad Request');
761
+                header('Status: 400 Bad Request');
762
+
763
+                \OC::$server->getLogger()->warning(
764
+                    'Trusted domain error. "{remoteAddress}" tried to access using "{host}" as host.',
765
+                    [
766
+                        'app' => 'core',
767
+                        'remoteAddress' => $request->getRemoteAddress(),
768
+                        'host' => $host,
769
+                    ]
770
+                );
771
+
772
+                $tmpl = new OCP\Template('core', 'untrustedDomain', 'guest');
773
+                $tmpl->assign('domain', $host);
774
+                $tmpl->printPage();
775
+
776
+                exit();
777
+            }
778
+        }
779
+        \OC::$server->getEventLogger()->end('boot');
780
+    }
781
+
782
+    /**
783
+     * register hooks for the cleanup of cache and bruteforce protection
784
+     */
785
+    public static function registerCleanupHooks() {
786
+        //don't try to do this before we are properly setup
787
+        if (\OC::$server->getSystemConfig()->getValue('installed', false) && !\OCP\Util::needUpgrade()) {
788
+
789
+            // NOTE: This will be replaced to use OCP
790
+            $userSession = self::$server->getUserSession();
791
+            $userSession->listen('\OC\User', 'postLogin', function () use ($userSession) {
792
+                if (!defined('PHPUNIT_RUN')) {
793
+                    // reset brute force delay for this IP address and username
794
+                    $uid = \OC::$server->getUserSession()->getUser()->getUID();
795
+                    $request = \OC::$server->getRequest();
796
+                    $throttler = \OC::$server->getBruteForceThrottler();
797
+                    $throttler->resetDelay($request->getRemoteAddress(), 'login', ['user' => $uid]);
798
+                }
799
+
800
+                try {
801
+                    $cache = new \OC\Cache\File();
802
+                    $cache->gc();
803
+                } catch (\OC\ServerNotAvailableException $e) {
804
+                    // not a GC exception, pass it on
805
+                    throw $e;
806
+                } catch (\OC\ForbiddenException $e) {
807
+                    // filesystem blocked for this request, ignore
808
+                } catch (\Exception $e) {
809
+                    // a GC exception should not prevent users from using OC,
810
+                    // so log the exception
811
+                    \OC::$server->getLogger()->warning('Exception when running cache gc: ' . $e->getMessage(), array('app' => 'core'));
812
+                }
813
+            });
814
+        }
815
+    }
816
+
817
+    public static function registerSettingsHooks() {
818
+        $dispatcher = \OC::$server->getEventDispatcher();
819
+        $dispatcher->addListener(OCP\App\ManagerEvent::EVENT_APP_DISABLE, function($event) {
820
+            /** @var \OCP\App\ManagerEvent $event */
821
+            \OC::$server->getSettingsManager()->onAppDisabled($event->getAppID());
822
+        });
823
+        $dispatcher->addListener(OCP\App\ManagerEvent::EVENT_APP_UPDATE, function($event) {
824
+            /** @var \OCP\App\ManagerEvent $event */
825
+            $jobList = \OC::$server->getJobList();
826
+            $job = 'OC\\Settings\\RemoveOrphaned';
827
+            if(!($jobList->has($job, null))) {
828
+                $jobList->add($job);
829
+            }
830
+        });
831
+    }
832
+
833
+    private static function registerEncryptionWrapper() {
834
+        $manager = self::$server->getEncryptionManager();
835
+        \OCP\Util::connectHook('OC_Filesystem', 'preSetup', $manager, 'setupStorage');
836
+    }
837
+
838
+    private static function registerEncryptionHooks() {
839
+        $enabled = self::$server->getEncryptionManager()->isEnabled();
840
+        if ($enabled) {
841
+            \OCP\Util::connectHook('OCP\Share', 'post_shared', 'OC\Encryption\HookManager', 'postShared');
842
+            \OCP\Util::connectHook('OCP\Share', 'post_unshare', 'OC\Encryption\HookManager', 'postUnshared');
843
+            \OCP\Util::connectHook('OC_Filesystem', 'post_rename', 'OC\Encryption\HookManager', 'postRename');
844
+            \OCP\Util::connectHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', 'OC\Encryption\HookManager', 'postRestore');
845
+        }
846
+    }
847
+
848
+    private static function registerAccountHooks() {
849
+        $hookHandler = new \OC\Accounts\Hooks(\OC::$server->getLogger());
850
+        \OCP\Util::connectHook('OC_User', 'changeUser', $hookHandler, 'changeUserHook');
851
+    }
852
+
853
+    /**
854
+     * register hooks for the filesystem
855
+     */
856
+    public static function registerFilesystemHooks() {
857
+        // Check for blacklisted files
858
+        OC_Hook::connect('OC_Filesystem', 'write', 'OC\Files\Filesystem', 'isBlacklisted');
859
+        OC_Hook::connect('OC_Filesystem', 'rename', 'OC\Files\Filesystem', 'isBlacklisted');
860
+    }
861
+
862
+    /**
863
+     * register hooks for sharing
864
+     */
865
+    public static function registerShareHooks() {
866
+        if (\OC::$server->getSystemConfig()->getValue('installed')) {
867
+            OC_Hook::connect('OC_User', 'post_deleteUser', 'OC\Share20\Hooks', 'post_deleteUser');
868
+            OC_Hook::connect('OC_User', 'post_removeFromGroup', 'OC\Share20\Hooks', 'post_removeFromGroup');
869
+            OC_Hook::connect('OC_User', 'post_deleteGroup', 'OC\Share20\Hooks', 'post_deleteGroup');
870
+        }
871
+    }
872
+
873
+    protected static function registerAutoloaderCache() {
874
+        // The class loader takes an optional low-latency cache, which MUST be
875
+        // namespaced. The instanceid is used for namespacing, but might be
876
+        // unavailable at this point. Furthermore, it might not be possible to
877
+        // generate an instanceid via \OC_Util::getInstanceId() because the
878
+        // config file may not be writable. As such, we only register a class
879
+        // loader cache if instanceid is available without trying to create one.
880
+        $instanceId = \OC::$server->getSystemConfig()->getValue('instanceid', null);
881
+        if ($instanceId) {
882
+            try {
883
+                $memcacheFactory = \OC::$server->getMemCacheFactory();
884
+                self::$loader->setMemoryCache($memcacheFactory->createLocal('Autoloader'));
885
+            } catch (\Exception $ex) {
886
+            }
887
+        }
888
+    }
889
+
890
+    /**
891
+     * Handle the request
892
+     */
893
+    public static function handleRequest() {
894
+
895
+        \OC::$server->getEventLogger()->start('handle_request', 'Handle request');
896
+        $systemConfig = \OC::$server->getSystemConfig();
897
+        // load all the classpaths from the enabled apps so they are available
898
+        // in the routing files of each app
899
+        OC::loadAppClassPaths();
900
+
901
+        // Check if Nextcloud is installed or in maintenance (update) mode
902
+        if (!$systemConfig->getValue('installed', false)) {
903
+            \OC::$server->getSession()->clear();
904
+            $setupHelper = new OC\Setup(
905
+                $systemConfig,
906
+                \OC::$server->getIniWrapper(),
907
+                \OC::$server->getL10N('lib'),
908
+                \OC::$server->query(\OCP\Defaults::class),
909
+                \OC::$server->getLogger(),
910
+                \OC::$server->getSecureRandom(),
911
+                \OC::$server->query(\OC\Installer::class)
912
+            );
913
+            $controller = new OC\Core\Controller\SetupController($setupHelper);
914
+            $controller->run($_POST);
915
+            exit();
916
+        }
917
+
918
+        $request = \OC::$server->getRequest();
919
+        $requestPath = $request->getRawPathInfo();
920
+        if ($requestPath === '/heartbeat') {
921
+            return;
922
+        }
923
+        if (substr($requestPath, -3) !== '.js') { // we need these files during the upgrade
924
+            self::checkMaintenanceMode();
925
+
926
+            if (\OCP\Util::needUpgrade()) {
927
+                if (function_exists('opcache_reset')) {
928
+                    opcache_reset();
929
+                }
930
+                if (!$systemConfig->getValue('maintenance', false)) {
931
+                    self::printUpgradePage($systemConfig);
932
+                    exit();
933
+                }
934
+            }
935
+        }
936
+
937
+        // emergency app disabling
938
+        if ($requestPath === '/disableapp'
939
+            && $request->getMethod() === 'POST'
940
+            && ((array)$request->getParam('appid')) !== ''
941
+        ) {
942
+            \OCP\JSON::callCheck();
943
+            \OCP\JSON::checkAdminUser();
944
+            $appIds = (array)$request->getParam('appid');
945
+            foreach($appIds as $appId) {
946
+                $appId = \OC_App::cleanAppId($appId);
947
+                \OC_App::disable($appId);
948
+            }
949
+            \OC_JSON::success();
950
+            exit();
951
+        }
952
+
953
+        // Always load authentication apps
954
+        OC_App::loadApps(['authentication']);
955
+
956
+        // Load minimum set of apps
957
+        if (!\OCP\Util::needUpgrade()
958
+            && !$systemConfig->getValue('maintenance', false)) {
959
+            // For logged-in users: Load everything
960
+            if(\OC::$server->getUserSession()->isLoggedIn()) {
961
+                OC_App::loadApps();
962
+            } else {
963
+                // For guests: Load only filesystem and logging
964
+                OC_App::loadApps(array('filesystem', 'logging'));
965
+                self::handleLogin($request);
966
+            }
967
+        }
968
+
969
+        if (!self::$CLI) {
970
+            try {
971
+                if (!$systemConfig->getValue('maintenance', false) && !\OCP\Util::needUpgrade()) {
972
+                    OC_App::loadApps(array('filesystem', 'logging'));
973
+                    OC_App::loadApps();
974
+                }
975
+                OC_Util::setupFS();
976
+                OC::$server->getRouter()->match(\OC::$server->getRequest()->getRawPathInfo());
977
+                return;
978
+            } catch (Symfony\Component\Routing\Exception\ResourceNotFoundException $e) {
979
+                //header('HTTP/1.0 404 Not Found');
980
+            } catch (Symfony\Component\Routing\Exception\MethodNotAllowedException $e) {
981
+                OC_Response::setStatus(405);
982
+                return;
983
+            }
984
+        }
985
+
986
+        // Handle WebDAV
987
+        if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'PROPFIND') {
988
+            // not allowed any more to prevent people
989
+            // mounting this root directly.
990
+            // Users need to mount remote.php/webdav instead.
991
+            header('HTTP/1.1 405 Method Not Allowed');
992
+            header('Status: 405 Method Not Allowed');
993
+            return;
994
+        }
995
+
996
+        // Someone is logged in
997
+        if (\OC::$server->getUserSession()->isLoggedIn()) {
998
+            OC_App::loadApps();
999
+            OC_User::setupBackends();
1000
+            OC_Util::setupFS();
1001
+            // FIXME
1002
+            // Redirect to default application
1003
+            OC_Util::redirectToDefaultPage();
1004
+        } else {
1005
+            // Not handled and not logged in
1006
+            header('Location: '.\OC::$server->getURLGenerator()->linkToRouteAbsolute('core.login.showLoginForm'));
1007
+        }
1008
+    }
1009
+
1010
+    /**
1011
+     * Check login: apache auth, auth token, basic auth
1012
+     *
1013
+     * @param OCP\IRequest $request
1014
+     * @return boolean
1015
+     */
1016
+    static function handleLogin(OCP\IRequest $request) {
1017
+        $userSession = self::$server->getUserSession();
1018
+        if (OC_User::handleApacheAuth()) {
1019
+            return true;
1020
+        }
1021
+        if ($userSession->tryTokenLogin($request)) {
1022
+            return true;
1023
+        }
1024
+        if (isset($_COOKIE['nc_username'])
1025
+            && isset($_COOKIE['nc_token'])
1026
+            && isset($_COOKIE['nc_session_id'])
1027
+            && $userSession->loginWithCookie($_COOKIE['nc_username'], $_COOKIE['nc_token'], $_COOKIE['nc_session_id'])) {
1028
+            return true;
1029
+        }
1030
+        if ($userSession->tryBasicAuthLogin($request, \OC::$server->getBruteForceThrottler())) {
1031
+            return true;
1032
+        }
1033
+        return false;
1034
+    }
1035
+
1036
+    protected static function handleAuthHeaders() {
1037
+        //copy http auth headers for apache+php-fcgid work around
1038
+        if (isset($_SERVER['HTTP_XAUTHORIZATION']) && !isset($_SERVER['HTTP_AUTHORIZATION'])) {
1039
+            $_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['HTTP_XAUTHORIZATION'];
1040
+        }
1041
+
1042
+        // Extract PHP_AUTH_USER/PHP_AUTH_PW from other headers if necessary.
1043
+        $vars = array(
1044
+            'HTTP_AUTHORIZATION', // apache+php-cgi work around
1045
+            'REDIRECT_HTTP_AUTHORIZATION', // apache+php-cgi alternative
1046
+        );
1047
+        foreach ($vars as $var) {
1048
+            if (isset($_SERVER[$var]) && preg_match('/Basic\s+(.*)$/i', $_SERVER[$var], $matches)) {
1049
+                list($name, $password) = explode(':', base64_decode($matches[1]), 2);
1050
+                $_SERVER['PHP_AUTH_USER'] = $name;
1051
+                $_SERVER['PHP_AUTH_PW'] = $password;
1052
+                break;
1053
+            }
1054
+        }
1055
+    }
1056 1056
 }
1057 1057
 
1058 1058
 OC::init();
Please login to merge, or discard this patch.
Spacing   +57 added lines, -57 removed lines patch added patch discarded remove patch
@@ -122,14 +122,14 @@  discard block
 block discarded – undo
122 122
 	 * the app path list is empty or contains an invalid path
123 123
 	 */
124 124
 	public static function initPaths() {
125
-		if(defined('PHPUNIT_CONFIG_DIR')) {
126
-			self::$configDir = OC::$SERVERROOT . '/' . PHPUNIT_CONFIG_DIR . '/';
127
-		} elseif(defined('PHPUNIT_RUN') and PHPUNIT_RUN and is_dir(OC::$SERVERROOT . '/tests/config/')) {
128
-			self::$configDir = OC::$SERVERROOT . '/tests/config/';
129
-		} elseif($dir = getenv('NEXTCLOUD_CONFIG_DIR')) {
130
-			self::$configDir = rtrim($dir, '/') . '/';
125
+		if (defined('PHPUNIT_CONFIG_DIR')) {
126
+			self::$configDir = OC::$SERVERROOT.'/'.PHPUNIT_CONFIG_DIR.'/';
127
+		} elseif (defined('PHPUNIT_RUN') and PHPUNIT_RUN and is_dir(OC::$SERVERROOT.'/tests/config/')) {
128
+			self::$configDir = OC::$SERVERROOT.'/tests/config/';
129
+		} elseif ($dir = getenv('NEXTCLOUD_CONFIG_DIR')) {
130
+			self::$configDir = rtrim($dir, '/').'/';
131 131
 		} else {
132
-			self::$configDir = OC::$SERVERROOT . '/config/';
132
+			self::$configDir = OC::$SERVERROOT.'/config/';
133 133
 		}
134 134
 		self::$config = new \OC\Config(self::$configDir);
135 135
 
@@ -151,9 +151,9 @@  discard block
 block discarded – undo
151 151
 			//make sure suburi follows the same rules as scriptName
152 152
 			if (substr(OC::$SUBURI, -9) != 'index.php') {
153 153
 				if (substr(OC::$SUBURI, -1) != '/') {
154
-					OC::$SUBURI = OC::$SUBURI . '/';
154
+					OC::$SUBURI = OC::$SUBURI.'/';
155 155
 				}
156
-				OC::$SUBURI = OC::$SUBURI . 'index.php';
156
+				OC::$SUBURI = OC::$SUBURI.'index.php';
157 157
 			}
158 158
 		}
159 159
 
@@ -165,7 +165,7 @@  discard block
 block discarded – undo
165 165
 				OC::$WEBROOT = substr($scriptName, 0, 0 - strlen(OC::$SUBURI));
166 166
 
167 167
 				if (OC::$WEBROOT != '' && OC::$WEBROOT[0] !== '/') {
168
-					OC::$WEBROOT = '/' . OC::$WEBROOT;
168
+					OC::$WEBROOT = '/'.OC::$WEBROOT;
169 169
 				}
170 170
 			} else {
171 171
 				// The scriptName is not ending with OC::$SUBURI
@@ -194,11 +194,11 @@  discard block
 block discarded – undo
194 194
 					OC::$APPSROOTS[] = $paths;
195 195
 				}
196 196
 			}
197
-		} elseif (file_exists(OC::$SERVERROOT . '/apps')) {
198
-			OC::$APPSROOTS[] = array('path' => OC::$SERVERROOT . '/apps', 'url' => '/apps', 'writable' => true);
199
-		} elseif (file_exists(OC::$SERVERROOT . '/../apps')) {
197
+		} elseif (file_exists(OC::$SERVERROOT.'/apps')) {
198
+			OC::$APPSROOTS[] = array('path' => OC::$SERVERROOT.'/apps', 'url' => '/apps', 'writable' => true);
199
+		} elseif (file_exists(OC::$SERVERROOT.'/../apps')) {
200 200
 			OC::$APPSROOTS[] = array(
201
-				'path' => rtrim(dirname(OC::$SERVERROOT), '/') . '/apps',
201
+				'path' => rtrim(dirname(OC::$SERVERROOT), '/').'/apps',
202 202
 				'url' => '/apps',
203 203
 				'writable' => true
204 204
 			);
@@ -228,8 +228,8 @@  discard block
 block discarded – undo
228 228
 		$l = \OC::$server->getL10N('lib');
229 229
 
230 230
 		// Create config if it does not already exist
231
-		$configFilePath = self::$configDir .'/config.php';
232
-		if(!file_exists($configFilePath)) {
231
+		$configFilePath = self::$configDir.'/config.php';
232
+		if (!file_exists($configFilePath)) {
233 233
 			@touch($configFilePath);
234 234
 		}
235 235
 
@@ -244,13 +244,13 @@  discard block
 block discarded – undo
244 244
 				echo $l->t('Cannot write into "config" directory!')."\n";
245 245
 				echo $l->t('This can usually be fixed by giving the webserver write access to the config directory')."\n";
246 246
 				echo "\n";
247
-				echo $l->t('See %s', [ $urlGenerator->linkToDocs('admin-dir_permissions') ])."\n";
247
+				echo $l->t('See %s', [$urlGenerator->linkToDocs('admin-dir_permissions')])."\n";
248 248
 				exit;
249 249
 			} else {
250 250
 				OC_Template::printErrorPage(
251 251
 					$l->t('Cannot write into "config" directory!'),
252 252
 					$l->t('This can usually be fixed by giving the webserver write access to the config directory. See %s',
253
-					 [ $urlGenerator->linkToDocs('admin-dir_permissions') ])
253
+					 [$urlGenerator->linkToDocs('admin-dir_permissions')])
254 254
 				);
255 255
 			}
256 256
 		}
@@ -265,8 +265,8 @@  discard block
 block discarded – undo
265 265
 			if (OC::$CLI) {
266 266
 				throw new Exception('Not installed');
267 267
 			} else {
268
-				$url = OC::$WEBROOT . '/index.php';
269
-				header('Location: ' . $url);
268
+				$url = OC::$WEBROOT.'/index.php';
269
+				header('Location: '.$url);
270 270
 			}
271 271
 			exit();
272 272
 		}
@@ -372,14 +372,14 @@  discard block
 block discarded – undo
372 372
 		$incompatibleShippedApps = [];
373 373
 		foreach ($incompatibleApps as $appInfo) {
374 374
 			if ($appManager->isShipped($appInfo['id'])) {
375
-				$incompatibleShippedApps[] = $appInfo['name'] . ' (' . $appInfo['id'] . ')';
375
+				$incompatibleShippedApps[] = $appInfo['name'].' ('.$appInfo['id'].')';
376 376
 			}
377 377
 		}
378 378
 
379 379
 		if (!empty($incompatibleShippedApps)) {
380 380
 			$l = \OC::$server->getL10N('core');
381 381
 			$hint = $l->t('The files of the app %$1s were not replaced correctly. Make sure it is a version compatible with the server.', [implode(', ', $incompatibleShippedApps)]);
382
-			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);
382
+			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);
383 383
 		}
384 384
 
385 385
 		$tmpl->assign('appsToUpgrade', $appManager->getAppsNeedingUpgrade($ocVersion));
@@ -394,7 +394,7 @@  discard block
 block discarded – undo
394 394
 		ini_set('session.cookie_httponly', true);
395 395
 
396 396
 		// set the cookie path to the Nextcloud directory
397
-		$cookie_path = OC::$WEBROOT ? : '/';
397
+		$cookie_path = OC::$WEBROOT ?: '/';
398 398
 		ini_set('session.cookie_path', $cookie_path);
399 399
 
400 400
 		// Let the session name be changed in the initSession Hook
@@ -428,7 +428,7 @@  discard block
 block discarded – undo
428 428
 		// session timeout
429 429
 		if ($session->exists('LAST_ACTIVITY') && (time() - $session->get('LAST_ACTIVITY') > $sessionLifeTime)) {
430 430
 			if (isset($_COOKIE[session_name()])) {
431
-				setcookie(session_name(), null, -1, self::$WEBROOT ? : '/');
431
+				setcookie(session_name(), null, -1, self::$WEBROOT ?: '/');
432 432
 			}
433 433
 			\OC::$server->getUserSession()->logout();
434 434
 		}
@@ -450,7 +450,7 @@  discard block
 block discarded – undo
450 450
 				continue;
451 451
 			}
452 452
 
453
-			$file = $appPath . '/appinfo/classpath.php';
453
+			$file = $appPath.'/appinfo/classpath.php';
454 454
 			if (file_exists($file)) {
455 455
 				require_once $file;
456 456
 			}
@@ -478,14 +478,14 @@  discard block
 block discarded – undo
478 478
 
479 479
 		// Append __Host to the cookie if it meets the requirements
480 480
 		$cookiePrefix = '';
481
-		if($cookieParams['secure'] === true && $cookieParams['path'] === '/') {
481
+		if ($cookieParams['secure'] === true && $cookieParams['path'] === '/') {
482 482
 			$cookiePrefix = '__Host-';
483 483
 		}
484 484
 
485
-		foreach($policies as $policy) {
485
+		foreach ($policies as $policy) {
486 486
 			header(
487 487
 				sprintf(
488
-					'Set-Cookie: %snc_sameSiteCookie%s=true; path=%s; httponly;' . $secureCookie . 'expires=Fri, 31-Dec-2100 23:59:59 GMT; SameSite=%s',
488
+					'Set-Cookie: %snc_sameSiteCookie%s=true; path=%s; httponly;'.$secureCookie.'expires=Fri, 31-Dec-2100 23:59:59 GMT; SameSite=%s',
489 489
 					$cookiePrefix,
490 490
 					$policy,
491 491
 					$cookieParams['path'],
@@ -516,31 +516,31 @@  discard block
 block discarded – undo
516 516
 			// OS X Finder
517 517
 			'/^WebDAVFS/',
518 518
 		];
519
-		if($request->isUserAgent($incompatibleUserAgents)) {
519
+		if ($request->isUserAgent($incompatibleUserAgents)) {
520 520
 			return;
521 521
 		}
522 522
 
523
-		if(count($_COOKIE) > 0) {
523
+		if (count($_COOKIE) > 0) {
524 524
 			$requestUri = $request->getScriptName();
525 525
 			$processingScript = explode('/', $requestUri);
526
-			$processingScript = $processingScript[count($processingScript)-1];
526
+			$processingScript = $processingScript[count($processingScript) - 1];
527 527
 
528 528
 			// index.php routes are handled in the middleware
529
-			if($processingScript === 'index.php') {
529
+			if ($processingScript === 'index.php') {
530 530
 				return;
531 531
 			}
532 532
 
533 533
 			// All other endpoints require the lax and the strict cookie
534
-			if(!$request->passesStrictCookieCheck()) {
534
+			if (!$request->passesStrictCookieCheck()) {
535 535
 				self::sendSameSiteCookies();
536 536
 				// Debug mode gets access to the resources without strict cookie
537 537
 				// due to the fact that the SabreDAV browser also lives there.
538
-				if(!\OC::$server->getConfig()->getSystemValue('debug', false)) {
538
+				if (!\OC::$server->getConfig()->getSystemValue('debug', false)) {
539 539
 					http_response_code(\OCP\AppFramework\Http::STATUS_SERVICE_UNAVAILABLE);
540 540
 					exit();
541 541
 				}
542 542
 			}
543
-		} elseif(!isset($_COOKIE['nc_sameSiteCookielax']) || !isset($_COOKIE['nc_sameSiteCookiestrict'])) {
543
+		} elseif (!isset($_COOKIE['nc_sameSiteCookielax']) || !isset($_COOKIE['nc_sameSiteCookiestrict'])) {
544 544
 			self::sendSameSiteCookies();
545 545
 		}
546 546
 	}
@@ -551,12 +551,12 @@  discard block
 block discarded – undo
551 551
 
552 552
 		// register autoloader
553 553
 		$loaderStart = microtime(true);
554
-		require_once __DIR__ . '/autoloader.php';
554
+		require_once __DIR__.'/autoloader.php';
555 555
 		self::$loader = new \OC\Autoloader([
556
-			OC::$SERVERROOT . '/lib/private/legacy',
556
+			OC::$SERVERROOT.'/lib/private/legacy',
557 557
 		]);
558 558
 		if (defined('PHPUNIT_RUN')) {
559
-			self::$loader->addValidRoot(OC::$SERVERROOT . '/tests');
559
+			self::$loader->addValidRoot(OC::$SERVERROOT.'/tests');
560 560
 		}
561 561
 		spl_autoload_register(array(self::$loader, 'load'));
562 562
 		$loaderEnd = microtime(true);
@@ -564,12 +564,12 @@  discard block
 block discarded – undo
564 564
 		self::$CLI = (php_sapi_name() == 'cli');
565 565
 
566 566
 		// Add default composer PSR-4 autoloader
567
-		self::$composerAutoloader = require_once OC::$SERVERROOT . '/lib/composer/autoload.php';
567
+		self::$composerAutoloader = require_once OC::$SERVERROOT.'/lib/composer/autoload.php';
568 568
 
569 569
 		try {
570 570
 			self::initPaths();
571 571
 			// setup 3rdparty autoloader
572
-			$vendorAutoLoad = OC::$SERVERROOT. '/3rdparty/autoload.php';
572
+			$vendorAutoLoad = OC::$SERVERROOT.'/3rdparty/autoload.php';
573 573
 			if (!file_exists($vendorAutoLoad)) {
574 574
 				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".');
575 575
 			}
@@ -579,7 +579,7 @@  discard block
 block discarded – undo
579 579
 			if (!self::$CLI) {
580 580
 				$claimedProtocol = strtoupper($_SERVER['SERVER_PROTOCOL']);
581 581
 				$protocol = in_array($claimedProtocol, ['HTTP/1.0', 'HTTP/1.1', 'HTTP/2']) ? $claimedProtocol : 'HTTP/1.1';
582
-				header($protocol . ' ' . OC_Response::STATUS_SERVICE_UNAVAILABLE);
582
+				header($protocol.' '.OC_Response::STATUS_SERVICE_UNAVAILABLE);
583 583
 			}
584 584
 			// we can't use the template error page here, because this needs the
585 585
 			// DI container which isn't available yet
@@ -597,7 +597,7 @@  discard block
 block discarded – undo
597 597
 		@ini_set('display_errors', 0);
598 598
 		@ini_set('log_errors', 1);
599 599
 
600
-		if(!date_default_timezone_set('UTC')) {
600
+		if (!date_default_timezone_set('UTC')) {
601 601
 			throw new \RuntimeException('Could not set timezone to UTC');
602 602
 		};
603 603
 
@@ -641,7 +641,7 @@  discard block
 block discarded – undo
641 641
 		self::checkInstalled();
642 642
 
643 643
 		OC_Response::addSecurityHeaders();
644
-		if(self::$server->getRequest()->getServerProtocol() === 'https') {
644
+		if (self::$server->getRequest()->getServerProtocol() === 'https') {
645 645
 			ini_set('session.cookie_secure', true);
646 646
 		}
647 647
 
@@ -654,11 +654,11 @@  discard block
 block discarded – undo
654 654
 					// Convert l10n string into regular string for usage in database
655 655
 					$staticErrors = [];
656 656
 					foreach ($errors as $error) {
657
-						echo $error['error'] . "\n";
658
-						echo $error['hint'] . "\n\n";
657
+						echo $error['error']."\n";
658
+						echo $error['hint']."\n\n";
659 659
 						$staticErrors[] = [
660
-							'error' => (string)$error['error'],
661
-							'hint' => (string)$error['hint'],
660
+							'error' => (string) $error['error'],
661
+							'hint' => (string) $error['hint'],
662 662
 						];
663 663
 					}
664 664
 
@@ -680,7 +680,7 @@  discard block
 block discarded – undo
680 680
 		}
681 681
 		//try to set the session lifetime
682 682
 		$sessionLifeTime = self::getSessionLifeTime();
683
-		@ini_set('gc_maxlifetime', (string)$sessionLifeTime);
683
+		@ini_set('gc_maxlifetime', (string) $sessionLifeTime);
684 684
 
685 685
 		$systemConfig = \OC::$server->getSystemConfig();
686 686
 
@@ -726,7 +726,7 @@  discard block
 block discarded – undo
726 726
 		register_shutdown_function(array($lockProvider, 'releaseAll'));
727 727
 
728 728
 		// Check whether the sample configuration has been copied
729
-		if($systemConfig->getValue('copied_sample_config', false)) {
729
+		if ($systemConfig->getValue('copied_sample_config', false)) {
730 730
 			$l = \OC::$server->getL10N('lib');
731 731
 			header('HTTP/1.1 503 Service Temporarily Unavailable');
732 732
 			header('Status: 503 Service Temporarily Unavailable');
@@ -752,7 +752,7 @@  discard block
 block discarded – undo
752 752
 		) {
753 753
 			// Allow access to CSS resources
754 754
 			$isScssRequest = false;
755
-			if(strpos($request->getPathInfo(), '/css/') === 0) {
755
+			if (strpos($request->getPathInfo(), '/css/') === 0) {
756 756
 				$isScssRequest = true;
757 757
 			}
758 758
 
@@ -788,7 +788,7 @@  discard block
 block discarded – undo
788 788
 
789 789
 			// NOTE: This will be replaced to use OCP
790 790
 			$userSession = self::$server->getUserSession();
791
-			$userSession->listen('\OC\User', 'postLogin', function () use ($userSession) {
791
+			$userSession->listen('\OC\User', 'postLogin', function() use ($userSession) {
792 792
 				if (!defined('PHPUNIT_RUN')) {
793 793
 					// reset brute force delay for this IP address and username
794 794
 					$uid = \OC::$server->getUserSession()->getUser()->getUID();
@@ -808,7 +808,7 @@  discard block
 block discarded – undo
808 808
 				} catch (\Exception $e) {
809 809
 					// a GC exception should not prevent users from using OC,
810 810
 					// so log the exception
811
-					\OC::$server->getLogger()->warning('Exception when running cache gc: ' . $e->getMessage(), array('app' => 'core'));
811
+					\OC::$server->getLogger()->warning('Exception when running cache gc: '.$e->getMessage(), array('app' => 'core'));
812 812
 				}
813 813
 			});
814 814
 		}
@@ -824,7 +824,7 @@  discard block
 block discarded – undo
824 824
 			/** @var \OCP\App\ManagerEvent $event */
825 825
 			$jobList = \OC::$server->getJobList();
826 826
 			$job = 'OC\\Settings\\RemoveOrphaned';
827
-			if(!($jobList->has($job, null))) {
827
+			if (!($jobList->has($job, null))) {
828 828
 				$jobList->add($job);
829 829
 			}
830 830
 		});
@@ -937,12 +937,12 @@  discard block
 block discarded – undo
937 937
 		// emergency app disabling
938 938
 		if ($requestPath === '/disableapp'
939 939
 			&& $request->getMethod() === 'POST'
940
-			&& ((array)$request->getParam('appid')) !== ''
940
+			&& ((array) $request->getParam('appid')) !== ''
941 941
 		) {
942 942
 			\OCP\JSON::callCheck();
943 943
 			\OCP\JSON::checkAdminUser();
944
-			$appIds = (array)$request->getParam('appid');
945
-			foreach($appIds as $appId) {
944
+			$appIds = (array) $request->getParam('appid');
945
+			foreach ($appIds as $appId) {
946 946
 				$appId = \OC_App::cleanAppId($appId);
947 947
 				\OC_App::disable($appId);
948 948
 			}
@@ -957,7 +957,7 @@  discard block
 block discarded – undo
957 957
 		if (!\OCP\Util::needUpgrade()
958 958
 			&& !$systemConfig->getValue('maintenance', false)) {
959 959
 			// For logged-in users: Load everything
960
-			if(\OC::$server->getUserSession()->isLoggedIn()) {
960
+			if (\OC::$server->getUserSession()->isLoggedIn()) {
961 961
 				OC_App::loadApps();
962 962
 			} else {
963 963
 				// For guests: Load only filesystem and logging
Please login to merge, or discard this patch.
apps/dav/lib/Connector/Sabre/MaintenancePlugin.php 1 patch
Indentation   +48 added lines, -48 removed lines patch added patch discarded remove patch
@@ -33,58 +33,58 @@
 block discarded – undo
33 33
 
34 34
 class MaintenancePlugin extends ServerPlugin {
35 35
 
36
-	/** @var IConfig */
37
-	private $config;
36
+    /** @var IConfig */
37
+    private $config;
38 38
 
39
-	/**
40
-	 * Reference to main server object
41
-	 *
42
-	 * @var Server
43
-	 */
44
-	private $server;
39
+    /**
40
+     * Reference to main server object
41
+     *
42
+     * @var Server
43
+     */
44
+    private $server;
45 45
 
46
-	/**
47
-	 * @param IConfig $config
48
-	 */
49
-	public function __construct(IConfig $config = null) {
50
-		$this->config = $config;
51
-		if (is_null($config)) {
52
-			$this->config = \OC::$server->getConfig();
53
-		}
54
-	}
46
+    /**
47
+     * @param IConfig $config
48
+     */
49
+    public function __construct(IConfig $config = null) {
50
+        $this->config = $config;
51
+        if (is_null($config)) {
52
+            $this->config = \OC::$server->getConfig();
53
+        }
54
+    }
55 55
 
56 56
 
57
-	/**
58
-	 * This initializes the plugin.
59
-	 *
60
-	 * This function is called by \Sabre\DAV\Server, after
61
-	 * addPlugin is called.
62
-	 *
63
-	 * This method should set up the required event subscriptions.
64
-	 *
65
-	 * @param \Sabre\DAV\Server $server
66
-	 * @return void
67
-	 */
68
-	public function initialize(\Sabre\DAV\Server $server) {
69
-		$this->server = $server;
70
-		$this->server->on('beforeMethod', array($this, 'checkMaintenanceMode'), 1);
71
-	}
57
+    /**
58
+     * This initializes the plugin.
59
+     *
60
+     * This function is called by \Sabre\DAV\Server, after
61
+     * addPlugin is called.
62
+     *
63
+     * This method should set up the required event subscriptions.
64
+     *
65
+     * @param \Sabre\DAV\Server $server
66
+     * @return void
67
+     */
68
+    public function initialize(\Sabre\DAV\Server $server) {
69
+        $this->server = $server;
70
+        $this->server->on('beforeMethod', array($this, 'checkMaintenanceMode'), 1);
71
+    }
72 72
 
73
-	/**
74
-	 * This method is called before any HTTP method and returns http status code 503
75
-	 * in case the system is in maintenance mode.
76
-	 *
77
-	 * @throws ServiceUnavailable
78
-	 * @return bool
79
-	 */
80
-	public function checkMaintenanceMode() {
81
-		if ($this->config->getSystemValue('maintenance', false)) {
82
-			throw new ServiceUnavailable('System in maintenance mode.');
83
-		}
84
-		if (Util::needUpgrade()) {
85
-			throw new ServiceUnavailable('Upgrade needed');
86
-		}
73
+    /**
74
+     * This method is called before any HTTP method and returns http status code 503
75
+     * in case the system is in maintenance mode.
76
+     *
77
+     * @throws ServiceUnavailable
78
+     * @return bool
79
+     */
80
+    public function checkMaintenanceMode() {
81
+        if ($this->config->getSystemValue('maintenance', false)) {
82
+            throw new ServiceUnavailable('System in maintenance mode.');
83
+        }
84
+        if (Util::needUpgrade()) {
85
+            throw new ServiceUnavailable('Upgrade needed');
86
+        }
87 87
 
88
-		return true;
89
-	}
88
+        return true;
89
+    }
90 90
 }
Please login to merge, or discard this patch.
core/ajax/update.php 1 patch
Indentation   +181 added lines, -181 removed lines patch added patch discarded remove patch
@@ -31,7 +31,7 @@  discard block
 block discarded – undo
31 31
 use Symfony\Component\EventDispatcher\GenericEvent;
32 32
 
33 33
 if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
34
-	@set_time_limit(0);
34
+    @set_time_limit(0);
35 35
 }
36 36
 
37 37
 require_once '../../lib/base.php';
@@ -45,191 +45,191 @@  discard block
 block discarded – undo
45 45
 $eventSource->send('success', (string)$l->t('Preparing update'));
46 46
 
47 47
 class FeedBackHandler {
48
-	/** @var integer */
49
-	private $progressStateMax = 100;
50
-	/** @var integer */
51
-	private $progressStateStep = 0;
52
-	/** @var string */
53
-	private $currentStep;
54
-	/** @var \OCP\IEventSource */
55
-	private $eventSource;
56
-	/** @var \OCP\IL10N */
57
-	private $l10n;
58
-
59
-	public function __construct(\OCP\IEventSource $eventSource, \OCP\IL10N $l10n) {
60
-		$this->eventSource = $eventSource;
61
-		$this->l10n = $l10n;
62
-	}
63
-
64
-	public function handleRepairFeedback($event) {
65
-		if (!$event instanceof GenericEvent) {
66
-			return;
67
-		}
68
-
69
-		switch ($event->getSubject()) {
70
-			case '\OC\Repair::startProgress':
71
-				$this->progressStateMax = $event->getArgument(0);
72
-				$this->progressStateStep = 0;
73
-				$this->currentStep = $event->getArgument(1);
74
-				break;
75
-			case '\OC\Repair::advance':
76
-				$this->progressStateStep += $event->getArgument(0);
77
-				$desc = $event->getArgument(1);
78
-				if (empty($desc)) {
79
-					$desc = $this->currentStep;
80
-				}
81
-				$this->eventSource->send('success', (string)$this->l10n->t('[%d / %d]: %s', [$this->progressStateStep, $this->progressStateMax, $desc]));
82
-				break;
83
-			case '\OC\Repair::finishProgress':
84
-				$this->progressStateMax = $this->progressStateStep;
85
-				$this->eventSource->send('success', (string)$this->l10n->t('[%d / %d]: %s', [$this->progressStateStep, $this->progressStateMax, $this->currentStep]));
86
-				break;
87
-			case '\OC\Repair::step':
88
-				break;
89
-			case '\OC\Repair::info':
90
-				break;
91
-			case '\OC\Repair::warning':
92
-				$this->eventSource->send('notice', (string)$this->l10n->t('Repair warning: ') . $event->getArgument(0));
93
-				break;
94
-			case '\OC\Repair::error':
95
-				$this->eventSource->send('notice', (string)$this->l10n->t('Repair error: ') . $event->getArgument(0));
96
-				break;
97
-		}
98
-	}
48
+    /** @var integer */
49
+    private $progressStateMax = 100;
50
+    /** @var integer */
51
+    private $progressStateStep = 0;
52
+    /** @var string */
53
+    private $currentStep;
54
+    /** @var \OCP\IEventSource */
55
+    private $eventSource;
56
+    /** @var \OCP\IL10N */
57
+    private $l10n;
58
+
59
+    public function __construct(\OCP\IEventSource $eventSource, \OCP\IL10N $l10n) {
60
+        $this->eventSource = $eventSource;
61
+        $this->l10n = $l10n;
62
+    }
63
+
64
+    public function handleRepairFeedback($event) {
65
+        if (!$event instanceof GenericEvent) {
66
+            return;
67
+        }
68
+
69
+        switch ($event->getSubject()) {
70
+            case '\OC\Repair::startProgress':
71
+                $this->progressStateMax = $event->getArgument(0);
72
+                $this->progressStateStep = 0;
73
+                $this->currentStep = $event->getArgument(1);
74
+                break;
75
+            case '\OC\Repair::advance':
76
+                $this->progressStateStep += $event->getArgument(0);
77
+                $desc = $event->getArgument(1);
78
+                if (empty($desc)) {
79
+                    $desc = $this->currentStep;
80
+                }
81
+                $this->eventSource->send('success', (string)$this->l10n->t('[%d / %d]: %s', [$this->progressStateStep, $this->progressStateMax, $desc]));
82
+                break;
83
+            case '\OC\Repair::finishProgress':
84
+                $this->progressStateMax = $this->progressStateStep;
85
+                $this->eventSource->send('success', (string)$this->l10n->t('[%d / %d]: %s', [$this->progressStateStep, $this->progressStateMax, $this->currentStep]));
86
+                break;
87
+            case '\OC\Repair::step':
88
+                break;
89
+            case '\OC\Repair::info':
90
+                break;
91
+            case '\OC\Repair::warning':
92
+                $this->eventSource->send('notice', (string)$this->l10n->t('Repair warning: ') . $event->getArgument(0));
93
+                break;
94
+            case '\OC\Repair::error':
95
+                $this->eventSource->send('notice', (string)$this->l10n->t('Repair error: ') . $event->getArgument(0));
96
+                break;
97
+        }
98
+    }
99 99
 }
100 100
 
101 101
 if (\OCP\Util::needUpgrade()) {
102 102
 
103
-	$config = \OC::$server->getSystemConfig();
104
-	if ($config->getValue('upgrade.disable-web', false)) {
105
-		$eventSource->send('failure', (string)$l->t('Please use the command line updater because automatic updating is disabled in the config.php.'));
106
-		$eventSource->close();
107
-		exit();
108
-	}
109
-
110
-	// if a user is currently logged in, their session must be ignored to
111
-	// avoid side effects
112
-	\OC_User::setIncognitoMode(true);
113
-
114
-	$logger = \OC::$server->getLogger();
115
-	$config = \OC::$server->getConfig();
116
-	$updater = new \OC\Updater(
117
-			$config,
118
-			\OC::$server->getIntegrityCodeChecker(),
119
-			$logger,
120
-			\OC::$server->query(\OC\Installer::class)
121
-	);
122
-	$incompatibleApps = [];
123
-	$disabledThirdPartyApps = [];
124
-
125
-	$dispatcher = \OC::$server->getEventDispatcher();
126
-	$dispatcher->addListener('\OC\DB\Migrator::executeSql', function($event) use ($eventSource, $l) {
127
-		if ($event instanceof GenericEvent) {
128
-			$eventSource->send('success', (string)$l->t('[%d / %d]: %s', [$event[0], $event[1], $event->getSubject()]));
129
-		}
130
-	});
131
-	$dispatcher->addListener('\OC\DB\Migrator::checkTable', function($event) use ($eventSource, $l) {
132
-		if ($event instanceof GenericEvent) {
133
-			$eventSource->send('success', (string)$l->t('[%d / %d]: Checking table %s', [$event[0], $event[1], $event->getSubject()]));
134
-		}
135
-	});
136
-	$feedBack = new FeedBackHandler($eventSource, $l);
137
-	$dispatcher->addListener('\OC\Repair::startProgress', [$feedBack, 'handleRepairFeedback']);
138
-	$dispatcher->addListener('\OC\Repair::advance', [$feedBack, 'handleRepairFeedback']);
139
-	$dispatcher->addListener('\OC\Repair::finishProgress', [$feedBack, 'handleRepairFeedback']);
140
-	$dispatcher->addListener('\OC\Repair::step', [$feedBack, 'handleRepairFeedback']);
141
-	$dispatcher->addListener('\OC\Repair::info', [$feedBack, 'handleRepairFeedback']);
142
-	$dispatcher->addListener('\OC\Repair::warning', [$feedBack, 'handleRepairFeedback']);
143
-	$dispatcher->addListener('\OC\Repair::error', [$feedBack, 'handleRepairFeedback']);
144
-
145
-	$updater->listen('\OC\Updater', 'maintenanceEnabled', function () use ($eventSource, $l) {
146
-		$eventSource->send('success', (string)$l->t('Turned on maintenance mode'));
147
-	});
148
-	$updater->listen('\OC\Updater', 'maintenanceDisabled', function () use ($eventSource, $l) {
149
-		$eventSource->send('success', (string)$l->t('Turned off maintenance mode'));
150
-	});
151
-	$updater->listen('\OC\Updater', 'maintenanceActive', function () use ($eventSource, $l) {
152
-		$eventSource->send('success', (string)$l->t('Maintenance mode is kept active'));
153
-	});
154
-	$updater->listen('\OC\Updater', 'dbUpgradeBefore', function () use($eventSource, $l) {
155
-		$eventSource->send('success', (string)$l->t('Updating database schema'));
156
-	});
157
-	$updater->listen('\OC\Updater', 'dbUpgrade', function () use ($eventSource, $l) {
158
-		$eventSource->send('success', (string)$l->t('Updated database'));
159
-	});
160
-	$updater->listen('\OC\Updater', 'dbSimulateUpgradeBefore', function () use($eventSource, $l) {
161
-		$eventSource->send('success', (string)$l->t('Checking whether the database schema can be updated (this can take a long time depending on the database size)'));
162
-	});
163
-	$updater->listen('\OC\Updater', 'dbSimulateUpgrade', function () use ($eventSource, $l) {
164
-		$eventSource->send('success', (string)$l->t('Checked database schema update'));
165
-	});
166
-	$updater->listen('\OC\Updater', 'appUpgradeCheckBefore', function () use ($eventSource, $l) {
167
-		$eventSource->send('success', (string)$l->t('Checking updates of apps'));
168
-	});
169
-	$updater->listen('\OC\Updater', 'checkAppStoreAppBefore', function ($app) use ($eventSource, $l) {
170
-		$eventSource->send('success', (string)$l->t('Checking for update of app "%s" in appstore', [$app]));
171
-	});
172
-	$updater->listen('\OC\Updater', 'upgradeAppStoreApp', function ($app) use ($eventSource, $l) {
173
-		$eventSource->send('success', (string)$l->t('Update app "%s" from appstore', [$app]));
174
-	});
175
-	$updater->listen('\OC\Updater', 'checkAppStoreApp', function ($app) use ($eventSource, $l) {
176
-		$eventSource->send('success', (string)$l->t('Checked for update of app "%s" in appstore', [$app]));
177
-	});
178
-	$updater->listen('\OC\Updater', 'appSimulateUpdate', function ($app) use ($eventSource, $l) {
179
-		$eventSource->send('success', (string)$l->t('Checking whether the database schema for %s can be updated (this can take a long time depending on the database size)', [$app]));
180
-	});
181
-	$updater->listen('\OC\Updater', 'appUpgradeCheck', function () use ($eventSource, $l) {
182
-		$eventSource->send('success', (string)$l->t('Checked database schema update for apps'));
183
-	});
184
-	$updater->listen('\OC\Updater', 'appUpgrade', function ($app, $version) use ($eventSource, $l) {
185
-		$eventSource->send('success', (string)$l->t('Updated "%s" to %s', array($app, $version)));
186
-	});
187
-	$updater->listen('\OC\Updater', 'incompatibleAppDisabled', function ($app) use (&$incompatibleApps) {
188
-		$incompatibleApps[]= $app;
189
-	});
190
-	$updater->listen('\OC\Updater', 'thirdPartyAppDisabled', function ($app) use (&$disabledThirdPartyApps) {
191
-		$disabledThirdPartyApps[]= $app;
192
-	});
193
-	$updater->listen('\OC\Updater', 'failure', function ($message) use ($eventSource, $config) {
194
-		$eventSource->send('failure', $message);
195
-		$eventSource->close();
196
-		$config->setSystemValue('maintenance', false);
197
-	});
198
-	$updater->listen('\OC\Updater', 'setDebugLogLevel', function ($logLevel, $logLevelName) use($eventSource, $l) {
199
-		$eventSource->send('success', (string)$l->t('Set log level to debug'));
200
-	});
201
-	$updater->listen('\OC\Updater', 'resetLogLevel', function ($logLevel, $logLevelName) use($eventSource, $l) {
202
-		$eventSource->send('success', (string)$l->t('Reset log level'));
203
-	});
204
-	$updater->listen('\OC\Updater', 'startCheckCodeIntegrity', function () use($eventSource, $l) {
205
-		$eventSource->send('success', (string)$l->t('Starting code integrity check'));
206
-	});
207
-	$updater->listen('\OC\Updater', 'finishedCheckCodeIntegrity', function () use($eventSource, $l) {
208
-		$eventSource->send('success', (string)$l->t('Finished code integrity check'));
209
-	});
210
-
211
-	try {
212
-		$updater->upgrade();
213
-	} catch (\Exception $e) {
214
-		$eventSource->send('failure', get_class($e) . ': ' . $e->getMessage());
215
-		$eventSource->close();
216
-		exit();
217
-	}
218
-
219
-	$disabledApps = [];
220
-	foreach ($disabledThirdPartyApps as $app) {
221
-		$disabledApps[$app] = (string) $l->t('%s (3rdparty)', [$app]);
222
-	}
223
-	foreach ($incompatibleApps as $app) {
224
-		$disabledApps[$app] = (string) $l->t('%s (incompatible)', [$app]);
225
-	}
226
-
227
-	if (!empty($disabledApps)) {
228
-		$eventSource->send('notice',
229
-			(string)$l->t('Following apps have been disabled: %s', [implode(', ', $disabledApps)]));
230
-	}
103
+    $config = \OC::$server->getSystemConfig();
104
+    if ($config->getValue('upgrade.disable-web', false)) {
105
+        $eventSource->send('failure', (string)$l->t('Please use the command line updater because automatic updating is disabled in the config.php.'));
106
+        $eventSource->close();
107
+        exit();
108
+    }
109
+
110
+    // if a user is currently logged in, their session must be ignored to
111
+    // avoid side effects
112
+    \OC_User::setIncognitoMode(true);
113
+
114
+    $logger = \OC::$server->getLogger();
115
+    $config = \OC::$server->getConfig();
116
+    $updater = new \OC\Updater(
117
+            $config,
118
+            \OC::$server->getIntegrityCodeChecker(),
119
+            $logger,
120
+            \OC::$server->query(\OC\Installer::class)
121
+    );
122
+    $incompatibleApps = [];
123
+    $disabledThirdPartyApps = [];
124
+
125
+    $dispatcher = \OC::$server->getEventDispatcher();
126
+    $dispatcher->addListener('\OC\DB\Migrator::executeSql', function($event) use ($eventSource, $l) {
127
+        if ($event instanceof GenericEvent) {
128
+            $eventSource->send('success', (string)$l->t('[%d / %d]: %s', [$event[0], $event[1], $event->getSubject()]));
129
+        }
130
+    });
131
+    $dispatcher->addListener('\OC\DB\Migrator::checkTable', function($event) use ($eventSource, $l) {
132
+        if ($event instanceof GenericEvent) {
133
+            $eventSource->send('success', (string)$l->t('[%d / %d]: Checking table %s', [$event[0], $event[1], $event->getSubject()]));
134
+        }
135
+    });
136
+    $feedBack = new FeedBackHandler($eventSource, $l);
137
+    $dispatcher->addListener('\OC\Repair::startProgress', [$feedBack, 'handleRepairFeedback']);
138
+    $dispatcher->addListener('\OC\Repair::advance', [$feedBack, 'handleRepairFeedback']);
139
+    $dispatcher->addListener('\OC\Repair::finishProgress', [$feedBack, 'handleRepairFeedback']);
140
+    $dispatcher->addListener('\OC\Repair::step', [$feedBack, 'handleRepairFeedback']);
141
+    $dispatcher->addListener('\OC\Repair::info', [$feedBack, 'handleRepairFeedback']);
142
+    $dispatcher->addListener('\OC\Repair::warning', [$feedBack, 'handleRepairFeedback']);
143
+    $dispatcher->addListener('\OC\Repair::error', [$feedBack, 'handleRepairFeedback']);
144
+
145
+    $updater->listen('\OC\Updater', 'maintenanceEnabled', function () use ($eventSource, $l) {
146
+        $eventSource->send('success', (string)$l->t('Turned on maintenance mode'));
147
+    });
148
+    $updater->listen('\OC\Updater', 'maintenanceDisabled', function () use ($eventSource, $l) {
149
+        $eventSource->send('success', (string)$l->t('Turned off maintenance mode'));
150
+    });
151
+    $updater->listen('\OC\Updater', 'maintenanceActive', function () use ($eventSource, $l) {
152
+        $eventSource->send('success', (string)$l->t('Maintenance mode is kept active'));
153
+    });
154
+    $updater->listen('\OC\Updater', 'dbUpgradeBefore', function () use($eventSource, $l) {
155
+        $eventSource->send('success', (string)$l->t('Updating database schema'));
156
+    });
157
+    $updater->listen('\OC\Updater', 'dbUpgrade', function () use ($eventSource, $l) {
158
+        $eventSource->send('success', (string)$l->t('Updated database'));
159
+    });
160
+    $updater->listen('\OC\Updater', 'dbSimulateUpgradeBefore', function () use($eventSource, $l) {
161
+        $eventSource->send('success', (string)$l->t('Checking whether the database schema can be updated (this can take a long time depending on the database size)'));
162
+    });
163
+    $updater->listen('\OC\Updater', 'dbSimulateUpgrade', function () use ($eventSource, $l) {
164
+        $eventSource->send('success', (string)$l->t('Checked database schema update'));
165
+    });
166
+    $updater->listen('\OC\Updater', 'appUpgradeCheckBefore', function () use ($eventSource, $l) {
167
+        $eventSource->send('success', (string)$l->t('Checking updates of apps'));
168
+    });
169
+    $updater->listen('\OC\Updater', 'checkAppStoreAppBefore', function ($app) use ($eventSource, $l) {
170
+        $eventSource->send('success', (string)$l->t('Checking for update of app "%s" in appstore', [$app]));
171
+    });
172
+    $updater->listen('\OC\Updater', 'upgradeAppStoreApp', function ($app) use ($eventSource, $l) {
173
+        $eventSource->send('success', (string)$l->t('Update app "%s" from appstore', [$app]));
174
+    });
175
+    $updater->listen('\OC\Updater', 'checkAppStoreApp', function ($app) use ($eventSource, $l) {
176
+        $eventSource->send('success', (string)$l->t('Checked for update of app "%s" in appstore', [$app]));
177
+    });
178
+    $updater->listen('\OC\Updater', 'appSimulateUpdate', function ($app) use ($eventSource, $l) {
179
+        $eventSource->send('success', (string)$l->t('Checking whether the database schema for %s can be updated (this can take a long time depending on the database size)', [$app]));
180
+    });
181
+    $updater->listen('\OC\Updater', 'appUpgradeCheck', function () use ($eventSource, $l) {
182
+        $eventSource->send('success', (string)$l->t('Checked database schema update for apps'));
183
+    });
184
+    $updater->listen('\OC\Updater', 'appUpgrade', function ($app, $version) use ($eventSource, $l) {
185
+        $eventSource->send('success', (string)$l->t('Updated "%s" to %s', array($app, $version)));
186
+    });
187
+    $updater->listen('\OC\Updater', 'incompatibleAppDisabled', function ($app) use (&$incompatibleApps) {
188
+        $incompatibleApps[]= $app;
189
+    });
190
+    $updater->listen('\OC\Updater', 'thirdPartyAppDisabled', function ($app) use (&$disabledThirdPartyApps) {
191
+        $disabledThirdPartyApps[]= $app;
192
+    });
193
+    $updater->listen('\OC\Updater', 'failure', function ($message) use ($eventSource, $config) {
194
+        $eventSource->send('failure', $message);
195
+        $eventSource->close();
196
+        $config->setSystemValue('maintenance', false);
197
+    });
198
+    $updater->listen('\OC\Updater', 'setDebugLogLevel', function ($logLevel, $logLevelName) use($eventSource, $l) {
199
+        $eventSource->send('success', (string)$l->t('Set log level to debug'));
200
+    });
201
+    $updater->listen('\OC\Updater', 'resetLogLevel', function ($logLevel, $logLevelName) use($eventSource, $l) {
202
+        $eventSource->send('success', (string)$l->t('Reset log level'));
203
+    });
204
+    $updater->listen('\OC\Updater', 'startCheckCodeIntegrity', function () use($eventSource, $l) {
205
+        $eventSource->send('success', (string)$l->t('Starting code integrity check'));
206
+    });
207
+    $updater->listen('\OC\Updater', 'finishedCheckCodeIntegrity', function () use($eventSource, $l) {
208
+        $eventSource->send('success', (string)$l->t('Finished code integrity check'));
209
+    });
210
+
211
+    try {
212
+        $updater->upgrade();
213
+    } catch (\Exception $e) {
214
+        $eventSource->send('failure', get_class($e) . ': ' . $e->getMessage());
215
+        $eventSource->close();
216
+        exit();
217
+    }
218
+
219
+    $disabledApps = [];
220
+    foreach ($disabledThirdPartyApps as $app) {
221
+        $disabledApps[$app] = (string) $l->t('%s (3rdparty)', [$app]);
222
+    }
223
+    foreach ($incompatibleApps as $app) {
224
+        $disabledApps[$app] = (string) $l->t('%s (incompatible)', [$app]);
225
+    }
226
+
227
+    if (!empty($disabledApps)) {
228
+        $eventSource->send('notice',
229
+            (string)$l->t('Following apps have been disabled: %s', [implode(', ', $disabledApps)]));
230
+    }
231 231
 } else {
232
-	$eventSource->send('notice', (string)$l->t('Already up to date'));
232
+    $eventSource->send('notice', (string)$l->t('Already up to date'));
233 233
 }
234 234
 
235 235
 $eventSource->send('done', '');
Please login to merge, or discard this patch.
core/Command/Upgrade.php 2 patches
Indentation   +242 added lines, -242 removed lines patch added patch discarded remove patch
@@ -49,263 +49,263 @@
 block discarded – undo
49 49
 
50 50
 class Upgrade extends Command {
51 51
 
52
-	const ERROR_SUCCESS = 0;
53
-	const ERROR_NOT_INSTALLED = 1;
54
-	const ERROR_MAINTENANCE_MODE = 2;
55
-	const ERROR_UP_TO_DATE = 0;
56
-	const ERROR_INVALID_ARGUMENTS = 4;
57
-	const ERROR_FAILURE = 5;
52
+    const ERROR_SUCCESS = 0;
53
+    const ERROR_NOT_INSTALLED = 1;
54
+    const ERROR_MAINTENANCE_MODE = 2;
55
+    const ERROR_UP_TO_DATE = 0;
56
+    const ERROR_INVALID_ARGUMENTS = 4;
57
+    const ERROR_FAILURE = 5;
58 58
 
59
-	/** @var IConfig */
60
-	private $config;
59
+    /** @var IConfig */
60
+    private $config;
61 61
 
62
-	/** @var ILogger */
63
-	private $logger;
62
+    /** @var ILogger */
63
+    private $logger;
64 64
 
65
-	/**
66
-	 * @param IConfig $config
67
-	 * @param ILogger $logger
68
-	 * @param Installer $installer
69
-	 */
70
-	public function __construct(IConfig $config, ILogger $logger, Installer $installer) {
71
-		parent::__construct();
72
-		$this->config = $config;
73
-		$this->logger = $logger;
74
-		$this->installer = $installer;
75
-	}
65
+    /**
66
+     * @param IConfig $config
67
+     * @param ILogger $logger
68
+     * @param Installer $installer
69
+     */
70
+    public function __construct(IConfig $config, ILogger $logger, Installer $installer) {
71
+        parent::__construct();
72
+        $this->config = $config;
73
+        $this->logger = $logger;
74
+        $this->installer = $installer;
75
+    }
76 76
 
77
-	protected function configure() {
78
-		$this
79
-			->setName('upgrade')
80
-			->setDescription('run upgrade routines after installation of a new release. The release has to be installed before.')
81
-			->addOption(
82
-				'--no-app-disable',
83
-				null,
84
-				InputOption::VALUE_NONE,
85
-				'skips the disable of third party apps'
86
-			);
87
-	}
77
+    protected function configure() {
78
+        $this
79
+            ->setName('upgrade')
80
+            ->setDescription('run upgrade routines after installation of a new release. The release has to be installed before.')
81
+            ->addOption(
82
+                '--no-app-disable',
83
+                null,
84
+                InputOption::VALUE_NONE,
85
+                'skips the disable of third party apps'
86
+            );
87
+    }
88 88
 
89
-	/**
90
-	 * Execute the upgrade command
91
-	 *
92
-	 * @param InputInterface $input input interface
93
-	 * @param OutputInterface $output output interface
94
-	 */
95
-	protected function execute(InputInterface $input, OutputInterface $output) {
89
+    /**
90
+     * Execute the upgrade command
91
+     *
92
+     * @param InputInterface $input input interface
93
+     * @param OutputInterface $output output interface
94
+     */
95
+    protected function execute(InputInterface $input, OutputInterface $output) {
96 96
 
97
-		if(Util::needUpgrade()) {
98
-			if (OutputInterface::VERBOSITY_NORMAL < $output->getVerbosity()) {
99
-				// Prepend each line with a little timestamp
100
-				$timestampFormatter = new TimestampFormatter($this->config, $output->getFormatter());
101
-				$output->setFormatter($timestampFormatter);
102
-			}
97
+        if(Util::needUpgrade()) {
98
+            if (OutputInterface::VERBOSITY_NORMAL < $output->getVerbosity()) {
99
+                // Prepend each line with a little timestamp
100
+                $timestampFormatter = new TimestampFormatter($this->config, $output->getFormatter());
101
+                $output->setFormatter($timestampFormatter);
102
+            }
103 103
 
104
-			$self = $this;
105
-			$updater = new Updater(
106
-					$this->config,
107
-					\OC::$server->getIntegrityCodeChecker(),
108
-					$this->logger,
109
-					$this->installer
110
-			);
104
+            $self = $this;
105
+            $updater = new Updater(
106
+                    $this->config,
107
+                    \OC::$server->getIntegrityCodeChecker(),
108
+                    $this->logger,
109
+                    $this->installer
110
+            );
111 111
 
112
-			if ($input->getOption('no-app-disable')) {
113
-				$updater->setSkip3rdPartyAppsDisable(true);
114
-			}
115
-			$dispatcher = \OC::$server->getEventDispatcher();
116
-			$progress = new ProgressBar($output);
117
-			$progress->setFormat(" %message%\n %current%/%max% [%bar%] %percent:3s%%");
118
-			$listener = function($event) use ($progress, $output) {
119
-				if ($event instanceof GenericEvent) {
120
-					$message = $event->getSubject();
121
-					if (OutputInterface::VERBOSITY_NORMAL < $output->getVerbosity()) {
122
-						$output->writeln(' Checking table ' . $message);
123
-					} else {
124
-						if (strlen($message) > 60) {
125
-							$message = substr($message, 0, 57) . '...';
126
-						}
127
-						$progress->setMessage($message);
128
-						if ($event[0] === 1) {
129
-							$output->writeln('');
130
-							$progress->start($event[1]);
131
-						}
132
-						$progress->setProgress($event[0]);
133
-						if ($event[0] === $event[1]) {
134
-							$progress->setMessage('Done');
135
-							$progress->finish();
136
-							$output->writeln('');
137
-						}
138
-					}
139
-				}
140
-			};
141
-			$repairListener = function($event) use ($progress, $output) {
142
-				if (!$event instanceof GenericEvent) {
143
-					return;
144
-				}
145
-				switch ($event->getSubject()) {
146
-					case '\OC\Repair::startProgress':
147
-						$progress->setMessage('Starting ...');
148
-						$output->writeln($event->getArgument(1));
149
-						$output->writeln('');
150
-						$progress->start($event->getArgument(0));
151
-						break;
152
-					case '\OC\Repair::advance':
153
-						$desc = $event->getArgument(1);
154
-						if (!empty($desc)) {
155
-							$progress->setMessage($desc);
156
-						}
157
-						$progress->advance($event->getArgument(0));
112
+            if ($input->getOption('no-app-disable')) {
113
+                $updater->setSkip3rdPartyAppsDisable(true);
114
+            }
115
+            $dispatcher = \OC::$server->getEventDispatcher();
116
+            $progress = new ProgressBar($output);
117
+            $progress->setFormat(" %message%\n %current%/%max% [%bar%] %percent:3s%%");
118
+            $listener = function($event) use ($progress, $output) {
119
+                if ($event instanceof GenericEvent) {
120
+                    $message = $event->getSubject();
121
+                    if (OutputInterface::VERBOSITY_NORMAL < $output->getVerbosity()) {
122
+                        $output->writeln(' Checking table ' . $message);
123
+                    } else {
124
+                        if (strlen($message) > 60) {
125
+                            $message = substr($message, 0, 57) . '...';
126
+                        }
127
+                        $progress->setMessage($message);
128
+                        if ($event[0] === 1) {
129
+                            $output->writeln('');
130
+                            $progress->start($event[1]);
131
+                        }
132
+                        $progress->setProgress($event[0]);
133
+                        if ($event[0] === $event[1]) {
134
+                            $progress->setMessage('Done');
135
+                            $progress->finish();
136
+                            $output->writeln('');
137
+                        }
138
+                    }
139
+                }
140
+            };
141
+            $repairListener = function($event) use ($progress, $output) {
142
+                if (!$event instanceof GenericEvent) {
143
+                    return;
144
+                }
145
+                switch ($event->getSubject()) {
146
+                    case '\OC\Repair::startProgress':
147
+                        $progress->setMessage('Starting ...');
148
+                        $output->writeln($event->getArgument(1));
149
+                        $output->writeln('');
150
+                        $progress->start($event->getArgument(0));
151
+                        break;
152
+                    case '\OC\Repair::advance':
153
+                        $desc = $event->getArgument(1);
154
+                        if (!empty($desc)) {
155
+                            $progress->setMessage($desc);
156
+                        }
157
+                        $progress->advance($event->getArgument(0));
158 158
 
159
-						break;
160
-					case '\OC\Repair::finishProgress':
161
-						$progress->setMessage('Done');
162
-						$progress->finish();
163
-						$output->writeln('');
164
-						break;
165
-					case '\OC\Repair::step':
166
-						if(OutputInterface::VERBOSITY_NORMAL < $output->getVerbosity()) {
167
-							$output->writeln('<info>Repair step: ' . $event->getArgument(0) . '</info>');
168
-						}
169
-						break;
170
-					case '\OC\Repair::info':
171
-						if(OutputInterface::VERBOSITY_NORMAL < $output->getVerbosity()) {
172
-							$output->writeln('<info>Repair info: ' . $event->getArgument(0) . '</info>');
173
-						}
174
-						break;
175
-					case '\OC\Repair::warning':
176
-						$output->writeln('<error>Repair warning: ' . $event->getArgument(0) . '</error>');
177
-						break;
178
-					case '\OC\Repair::error':
179
-						$output->writeln('<error>Repair error: ' . $event->getArgument(0) . '</error>');
180
-						break;
181
-				}
182
-			};
159
+                        break;
160
+                    case '\OC\Repair::finishProgress':
161
+                        $progress->setMessage('Done');
162
+                        $progress->finish();
163
+                        $output->writeln('');
164
+                        break;
165
+                    case '\OC\Repair::step':
166
+                        if(OutputInterface::VERBOSITY_NORMAL < $output->getVerbosity()) {
167
+                            $output->writeln('<info>Repair step: ' . $event->getArgument(0) . '</info>');
168
+                        }
169
+                        break;
170
+                    case '\OC\Repair::info':
171
+                        if(OutputInterface::VERBOSITY_NORMAL < $output->getVerbosity()) {
172
+                            $output->writeln('<info>Repair info: ' . $event->getArgument(0) . '</info>');
173
+                        }
174
+                        break;
175
+                    case '\OC\Repair::warning':
176
+                        $output->writeln('<error>Repair warning: ' . $event->getArgument(0) . '</error>');
177
+                        break;
178
+                    case '\OC\Repair::error':
179
+                        $output->writeln('<error>Repair error: ' . $event->getArgument(0) . '</error>');
180
+                        break;
181
+                }
182
+            };
183 183
 
184
-			$dispatcher->addListener('\OC\DB\Migrator::executeSql', $listener);
185
-			$dispatcher->addListener('\OC\DB\Migrator::checkTable', $listener);
186
-			$dispatcher->addListener('\OC\Repair::startProgress', $repairListener);
187
-			$dispatcher->addListener('\OC\Repair::advance', $repairListener);
188
-			$dispatcher->addListener('\OC\Repair::finishProgress', $repairListener);
189
-			$dispatcher->addListener('\OC\Repair::step', $repairListener);
190
-			$dispatcher->addListener('\OC\Repair::info', $repairListener);
191
-			$dispatcher->addListener('\OC\Repair::warning', $repairListener);
192
-			$dispatcher->addListener('\OC\Repair::error', $repairListener);
184
+            $dispatcher->addListener('\OC\DB\Migrator::executeSql', $listener);
185
+            $dispatcher->addListener('\OC\DB\Migrator::checkTable', $listener);
186
+            $dispatcher->addListener('\OC\Repair::startProgress', $repairListener);
187
+            $dispatcher->addListener('\OC\Repair::advance', $repairListener);
188
+            $dispatcher->addListener('\OC\Repair::finishProgress', $repairListener);
189
+            $dispatcher->addListener('\OC\Repair::step', $repairListener);
190
+            $dispatcher->addListener('\OC\Repair::info', $repairListener);
191
+            $dispatcher->addListener('\OC\Repair::warning', $repairListener);
192
+            $dispatcher->addListener('\OC\Repair::error', $repairListener);
193 193
 			
194 194
 
195
-			$updater->listen('\OC\Updater', 'maintenanceEnabled', function () use($output) {
196
-				$output->writeln('<info>Turned on maintenance mode</info>');
197
-			});
198
-			$updater->listen('\OC\Updater', 'maintenanceDisabled', function () use($output) {
199
-				$output->writeln('<info>Turned off maintenance mode</info>');
200
-			});
201
-			$updater->listen('\OC\Updater', 'maintenanceActive', function () use($output) {
202
-				$output->writeln('<info>Maintenance mode is kept active</info>');
203
-			});
204
-			$updater->listen('\OC\Updater', 'updateEnd',
205
-				function ($success) use($output, $self) {
206
-					if ($success) {
207
-						$message = "<info>Update successful</info>";
208
-					} else {
209
-						$message = "<error>Update failed</error>";
210
-					}
211
-					$output->writeln($message);
212
-				});
213
-			$updater->listen('\OC\Updater', 'dbUpgradeBefore', function () use($output) {
214
-				$output->writeln('<info>Updating database schema</info>');
215
-			});
216
-			$updater->listen('\OC\Updater', 'dbUpgrade', function () use($output) {
217
-				$output->writeln('<info>Updated database</info>');
218
-			});
219
-			$updater->listen('\OC\Updater', 'dbSimulateUpgradeBefore', function () use($output) {
220
-				$output->writeln('<info>Checking whether the database schema can be updated (this can take a long time depending on the database size)</info>');
221
-			});
222
-			$updater->listen('\OC\Updater', 'dbSimulateUpgrade', function () use($output) {
223
-				$output->writeln('<info>Checked database schema update</info>');
224
-			});
225
-			$updater->listen('\OC\Updater', 'incompatibleAppDisabled', function ($app) use($output) {
226
-				$output->writeln('<comment>Disabled incompatible app: ' . $app . '</comment>');
227
-			});
228
-			$updater->listen('\OC\Updater', 'thirdPartyAppDisabled', function ($app) use ($output) {
229
-				$output->writeln('<comment>Disabled 3rd-party app: ' . $app . '</comment>');
230
-			});
231
-			$updater->listen('\OC\Updater', 'checkAppStoreAppBefore', function ($app) use($output) {
232
-				$output->writeln('<info>Checking for update of app ' . $app . ' in appstore</info>');
233
-			});
234
-			$updater->listen('\OC\Updater', 'upgradeAppStoreApp', function ($app) use($output) {
235
-				$output->writeln('<info>Update app ' . $app . ' from appstore</info>');
236
-			});
237
-			$updater->listen('\OC\Updater', 'checkAppStoreApp', function ($app) use($output) {
238
-				$output->writeln('<info>Checked for update of app "' . $app . '" in appstore </info>');
239
-			});
240
-			$updater->listen('\OC\Updater', 'appUpgradeCheckBefore', function () use ($output) {
241
-				$output->writeln('<info>Checking updates of apps</info>');
242
-			});
243
-			$updater->listen('\OC\Updater', 'appSimulateUpdate', function ($app) use ($output) {
244
-				$output->writeln("<info>Checking whether the database schema for <$app> can be updated (this can take a long time depending on the database size)</info>");
245
-			});
246
-			$updater->listen('\OC\Updater', 'appUpgradeCheck', function () use ($output) {
247
-				$output->writeln('<info>Checked database schema update for apps</info>');
248
-			});
249
-			$updater->listen('\OC\Updater', 'appUpgradeStarted', function ($app, $version) use ($output) {
250
-				$output->writeln("<info>Updating <$app> ...</info>");
251
-			});
252
-			$updater->listen('\OC\Updater', 'appUpgrade', function ($app, $version) use ($output) {
253
-				$output->writeln("<info>Updated <$app> to $version</info>");
254
-			});
255
-			$updater->listen('\OC\Updater', 'failure', function ($message) use($output, $self) {
256
-				$output->writeln("<error>$message</error>");
257
-			});
258
-			$updater->listen('\OC\Updater', 'setDebugLogLevel', function ($logLevel, $logLevelName) use($output) {
259
-				$output->writeln("<info>Set log level to debug</info>");
260
-			});
261
-			$updater->listen('\OC\Updater', 'resetLogLevel', function ($logLevel, $logLevelName) use($output) {
262
-				$output->writeln("<info>Reset log level</info>");
263
-			});
264
-			$updater->listen('\OC\Updater', 'startCheckCodeIntegrity', function () use($output) {
265
-				$output->writeln("<info>Starting code integrity check...</info>");
266
-			});
267
-			$updater->listen('\OC\Updater', 'finishedCheckCodeIntegrity', function () use($output) {
268
-				$output->writeln("<info>Finished code integrity check</info>");
269
-			});
195
+            $updater->listen('\OC\Updater', 'maintenanceEnabled', function () use($output) {
196
+                $output->writeln('<info>Turned on maintenance mode</info>');
197
+            });
198
+            $updater->listen('\OC\Updater', 'maintenanceDisabled', function () use($output) {
199
+                $output->writeln('<info>Turned off maintenance mode</info>');
200
+            });
201
+            $updater->listen('\OC\Updater', 'maintenanceActive', function () use($output) {
202
+                $output->writeln('<info>Maintenance mode is kept active</info>');
203
+            });
204
+            $updater->listen('\OC\Updater', 'updateEnd',
205
+                function ($success) use($output, $self) {
206
+                    if ($success) {
207
+                        $message = "<info>Update successful</info>";
208
+                    } else {
209
+                        $message = "<error>Update failed</error>";
210
+                    }
211
+                    $output->writeln($message);
212
+                });
213
+            $updater->listen('\OC\Updater', 'dbUpgradeBefore', function () use($output) {
214
+                $output->writeln('<info>Updating database schema</info>');
215
+            });
216
+            $updater->listen('\OC\Updater', 'dbUpgrade', function () use($output) {
217
+                $output->writeln('<info>Updated database</info>');
218
+            });
219
+            $updater->listen('\OC\Updater', 'dbSimulateUpgradeBefore', function () use($output) {
220
+                $output->writeln('<info>Checking whether the database schema can be updated (this can take a long time depending on the database size)</info>');
221
+            });
222
+            $updater->listen('\OC\Updater', 'dbSimulateUpgrade', function () use($output) {
223
+                $output->writeln('<info>Checked database schema update</info>');
224
+            });
225
+            $updater->listen('\OC\Updater', 'incompatibleAppDisabled', function ($app) use($output) {
226
+                $output->writeln('<comment>Disabled incompatible app: ' . $app . '</comment>');
227
+            });
228
+            $updater->listen('\OC\Updater', 'thirdPartyAppDisabled', function ($app) use ($output) {
229
+                $output->writeln('<comment>Disabled 3rd-party app: ' . $app . '</comment>');
230
+            });
231
+            $updater->listen('\OC\Updater', 'checkAppStoreAppBefore', function ($app) use($output) {
232
+                $output->writeln('<info>Checking for update of app ' . $app . ' in appstore</info>');
233
+            });
234
+            $updater->listen('\OC\Updater', 'upgradeAppStoreApp', function ($app) use($output) {
235
+                $output->writeln('<info>Update app ' . $app . ' from appstore</info>');
236
+            });
237
+            $updater->listen('\OC\Updater', 'checkAppStoreApp', function ($app) use($output) {
238
+                $output->writeln('<info>Checked for update of app "' . $app . '" in appstore </info>');
239
+            });
240
+            $updater->listen('\OC\Updater', 'appUpgradeCheckBefore', function () use ($output) {
241
+                $output->writeln('<info>Checking updates of apps</info>');
242
+            });
243
+            $updater->listen('\OC\Updater', 'appSimulateUpdate', function ($app) use ($output) {
244
+                $output->writeln("<info>Checking whether the database schema for <$app> can be updated (this can take a long time depending on the database size)</info>");
245
+            });
246
+            $updater->listen('\OC\Updater', 'appUpgradeCheck', function () use ($output) {
247
+                $output->writeln('<info>Checked database schema update for apps</info>');
248
+            });
249
+            $updater->listen('\OC\Updater', 'appUpgradeStarted', function ($app, $version) use ($output) {
250
+                $output->writeln("<info>Updating <$app> ...</info>");
251
+            });
252
+            $updater->listen('\OC\Updater', 'appUpgrade', function ($app, $version) use ($output) {
253
+                $output->writeln("<info>Updated <$app> to $version</info>");
254
+            });
255
+            $updater->listen('\OC\Updater', 'failure', function ($message) use($output, $self) {
256
+                $output->writeln("<error>$message</error>");
257
+            });
258
+            $updater->listen('\OC\Updater', 'setDebugLogLevel', function ($logLevel, $logLevelName) use($output) {
259
+                $output->writeln("<info>Set log level to debug</info>");
260
+            });
261
+            $updater->listen('\OC\Updater', 'resetLogLevel', function ($logLevel, $logLevelName) use($output) {
262
+                $output->writeln("<info>Reset log level</info>");
263
+            });
264
+            $updater->listen('\OC\Updater', 'startCheckCodeIntegrity', function () use($output) {
265
+                $output->writeln("<info>Starting code integrity check...</info>");
266
+            });
267
+            $updater->listen('\OC\Updater', 'finishedCheckCodeIntegrity', function () use($output) {
268
+                $output->writeln("<info>Finished code integrity check</info>");
269
+            });
270 270
 
271
-			$success = $updater->upgrade();
271
+            $success = $updater->upgrade();
272 272
 
273
-			$this->postUpgradeCheck($input, $output);
273
+            $this->postUpgradeCheck($input, $output);
274 274
 
275
-			if(!$success) {
276
-				return self::ERROR_FAILURE;
277
-			}
275
+            if(!$success) {
276
+                return self::ERROR_FAILURE;
277
+            }
278 278
 
279
-			return self::ERROR_SUCCESS;
280
-		} else if($this->config->getSystemValue('maintenance', false)) {
281
-			//Possible scenario: Nextcloud core is updated but an app failed
282
-			$output->writeln('<warning>Nextcloud is in maintenance mode</warning>');
283
-			$output->write('<comment>Maybe an upgrade is already in process. Please check the '
284
-				. 'logfile (data/nextcloud.log). If you want to re-run the '
285
-				. 'upgrade procedure, remove the "maintenance mode" from '
286
-				. 'config.php and call this script again.</comment>'
287
-				, true);
288
-			return self::ERROR_MAINTENANCE_MODE;
289
-		} else {
290
-			$output->writeln('<info>Nextcloud is already latest version</info>');
291
-			return self::ERROR_UP_TO_DATE;
292
-		}
293
-	}
279
+            return self::ERROR_SUCCESS;
280
+        } else if($this->config->getSystemValue('maintenance', false)) {
281
+            //Possible scenario: Nextcloud core is updated but an app failed
282
+            $output->writeln('<warning>Nextcloud is in maintenance mode</warning>');
283
+            $output->write('<comment>Maybe an upgrade is already in process. Please check the '
284
+                . 'logfile (data/nextcloud.log). If you want to re-run the '
285
+                . 'upgrade procedure, remove the "maintenance mode" from '
286
+                . 'config.php and call this script again.</comment>'
287
+                , true);
288
+            return self::ERROR_MAINTENANCE_MODE;
289
+        } else {
290
+            $output->writeln('<info>Nextcloud is already latest version</info>');
291
+            return self::ERROR_UP_TO_DATE;
292
+        }
293
+    }
294 294
 
295
-	/**
296
-	 * Perform a post upgrade check (specific to the command line tool)
297
-	 *
298
-	 * @param InputInterface $input input interface
299
-	 * @param OutputInterface $output output interface
300
-	 */
301
-	protected function postUpgradeCheck(InputInterface $input, OutputInterface $output) {
302
-		$trustedDomains = $this->config->getSystemValue('trusted_domains', array());
303
-		if (empty($trustedDomains)) {
304
-			$output->write(
305
-				'<warning>The setting "trusted_domains" could not be ' .
306
-				'set automatically by the upgrade script, ' .
307
-				'please set it manually</warning>'
308
-			);
309
-		}
310
-	}
295
+    /**
296
+     * Perform a post upgrade check (specific to the command line tool)
297
+     *
298
+     * @param InputInterface $input input interface
299
+     * @param OutputInterface $output output interface
300
+     */
301
+    protected function postUpgradeCheck(InputInterface $input, OutputInterface $output) {
302
+        $trustedDomains = $this->config->getSystemValue('trusted_domains', array());
303
+        if (empty($trustedDomains)) {
304
+            $output->write(
305
+                '<warning>The setting "trusted_domains" could not be ' .
306
+                'set automatically by the upgrade script, ' .
307
+                'please set it manually</warning>'
308
+            );
309
+        }
310
+    }
311 311
 }
Please login to merge, or discard this patch.
Spacing   +41 added lines, -41 removed lines patch added patch discarded remove patch
@@ -94,7 +94,7 @@  discard block
 block discarded – undo
94 94
 	 */
95 95
 	protected function execute(InputInterface $input, OutputInterface $output) {
96 96
 
97
-		if(Util::needUpgrade()) {
97
+		if (Util::needUpgrade()) {
98 98
 			if (OutputInterface::VERBOSITY_NORMAL < $output->getVerbosity()) {
99 99
 				// Prepend each line with a little timestamp
100 100
 				$timestampFormatter = new TimestampFormatter($this->config, $output->getFormatter());
@@ -119,10 +119,10 @@  discard block
 block discarded – undo
119 119
 				if ($event instanceof GenericEvent) {
120 120
 					$message = $event->getSubject();
121 121
 					if (OutputInterface::VERBOSITY_NORMAL < $output->getVerbosity()) {
122
-						$output->writeln(' Checking table ' . $message);
122
+						$output->writeln(' Checking table '.$message);
123 123
 					} else {
124 124
 						if (strlen($message) > 60) {
125
-							$message = substr($message, 0, 57) . '...';
125
+							$message = substr($message, 0, 57).'...';
126 126
 						}
127 127
 						$progress->setMessage($message);
128 128
 						if ($event[0] === 1) {
@@ -163,20 +163,20 @@  discard block
 block discarded – undo
163 163
 						$output->writeln('');
164 164
 						break;
165 165
 					case '\OC\Repair::step':
166
-						if(OutputInterface::VERBOSITY_NORMAL < $output->getVerbosity()) {
167
-							$output->writeln('<info>Repair step: ' . $event->getArgument(0) . '</info>');
166
+						if (OutputInterface::VERBOSITY_NORMAL < $output->getVerbosity()) {
167
+							$output->writeln('<info>Repair step: '.$event->getArgument(0).'</info>');
168 168
 						}
169 169
 						break;
170 170
 					case '\OC\Repair::info':
171
-						if(OutputInterface::VERBOSITY_NORMAL < $output->getVerbosity()) {
172
-							$output->writeln('<info>Repair info: ' . $event->getArgument(0) . '</info>');
171
+						if (OutputInterface::VERBOSITY_NORMAL < $output->getVerbosity()) {
172
+							$output->writeln('<info>Repair info: '.$event->getArgument(0).'</info>');
173 173
 						}
174 174
 						break;
175 175
 					case '\OC\Repair::warning':
176
-						$output->writeln('<error>Repair warning: ' . $event->getArgument(0) . '</error>');
176
+						$output->writeln('<error>Repair warning: '.$event->getArgument(0).'</error>');
177 177
 						break;
178 178
 					case '\OC\Repair::error':
179
-						$output->writeln('<error>Repair error: ' . $event->getArgument(0) . '</error>');
179
+						$output->writeln('<error>Repair error: '.$event->getArgument(0).'</error>');
180 180
 						break;
181 181
 				}
182 182
 			};
@@ -192,17 +192,17 @@  discard block
 block discarded – undo
192 192
 			$dispatcher->addListener('\OC\Repair::error', $repairListener);
193 193
 			
194 194
 
195
-			$updater->listen('\OC\Updater', 'maintenanceEnabled', function () use($output) {
195
+			$updater->listen('\OC\Updater', 'maintenanceEnabled', function() use($output) {
196 196
 				$output->writeln('<info>Turned on maintenance mode</info>');
197 197
 			});
198
-			$updater->listen('\OC\Updater', 'maintenanceDisabled', function () use($output) {
198
+			$updater->listen('\OC\Updater', 'maintenanceDisabled', function() use($output) {
199 199
 				$output->writeln('<info>Turned off maintenance mode</info>');
200 200
 			});
201
-			$updater->listen('\OC\Updater', 'maintenanceActive', function () use($output) {
201
+			$updater->listen('\OC\Updater', 'maintenanceActive', function() use($output) {
202 202
 				$output->writeln('<info>Maintenance mode is kept active</info>');
203 203
 			});
204 204
 			$updater->listen('\OC\Updater', 'updateEnd',
205
-				function ($success) use($output, $self) {
205
+				function($success) use($output, $self) {
206 206
 					if ($success) {
207 207
 						$message = "<info>Update successful</info>";
208 208
 					} else {
@@ -210,61 +210,61 @@  discard block
 block discarded – undo
210 210
 					}
211 211
 					$output->writeln($message);
212 212
 				});
213
-			$updater->listen('\OC\Updater', 'dbUpgradeBefore', function () use($output) {
213
+			$updater->listen('\OC\Updater', 'dbUpgradeBefore', function() use($output) {
214 214
 				$output->writeln('<info>Updating database schema</info>');
215 215
 			});
216
-			$updater->listen('\OC\Updater', 'dbUpgrade', function () use($output) {
216
+			$updater->listen('\OC\Updater', 'dbUpgrade', function() use($output) {
217 217
 				$output->writeln('<info>Updated database</info>');
218 218
 			});
219
-			$updater->listen('\OC\Updater', 'dbSimulateUpgradeBefore', function () use($output) {
219
+			$updater->listen('\OC\Updater', 'dbSimulateUpgradeBefore', function() use($output) {
220 220
 				$output->writeln('<info>Checking whether the database schema can be updated (this can take a long time depending on the database size)</info>');
221 221
 			});
222
-			$updater->listen('\OC\Updater', 'dbSimulateUpgrade', function () use($output) {
222
+			$updater->listen('\OC\Updater', 'dbSimulateUpgrade', function() use($output) {
223 223
 				$output->writeln('<info>Checked database schema update</info>');
224 224
 			});
225
-			$updater->listen('\OC\Updater', 'incompatibleAppDisabled', function ($app) use($output) {
226
-				$output->writeln('<comment>Disabled incompatible app: ' . $app . '</comment>');
225
+			$updater->listen('\OC\Updater', 'incompatibleAppDisabled', function($app) use($output) {
226
+				$output->writeln('<comment>Disabled incompatible app: '.$app.'</comment>');
227 227
 			});
228
-			$updater->listen('\OC\Updater', 'thirdPartyAppDisabled', function ($app) use ($output) {
229
-				$output->writeln('<comment>Disabled 3rd-party app: ' . $app . '</comment>');
228
+			$updater->listen('\OC\Updater', 'thirdPartyAppDisabled', function($app) use ($output) {
229
+				$output->writeln('<comment>Disabled 3rd-party app: '.$app.'</comment>');
230 230
 			});
231
-			$updater->listen('\OC\Updater', 'checkAppStoreAppBefore', function ($app) use($output) {
232
-				$output->writeln('<info>Checking for update of app ' . $app . ' in appstore</info>');
231
+			$updater->listen('\OC\Updater', 'checkAppStoreAppBefore', function($app) use($output) {
232
+				$output->writeln('<info>Checking for update of app '.$app.' in appstore</info>');
233 233
 			});
234
-			$updater->listen('\OC\Updater', 'upgradeAppStoreApp', function ($app) use($output) {
235
-				$output->writeln('<info>Update app ' . $app . ' from appstore</info>');
234
+			$updater->listen('\OC\Updater', 'upgradeAppStoreApp', function($app) use($output) {
235
+				$output->writeln('<info>Update app '.$app.' from appstore</info>');
236 236
 			});
237
-			$updater->listen('\OC\Updater', 'checkAppStoreApp', function ($app) use($output) {
238
-				$output->writeln('<info>Checked for update of app "' . $app . '" in appstore </info>');
237
+			$updater->listen('\OC\Updater', 'checkAppStoreApp', function($app) use($output) {
238
+				$output->writeln('<info>Checked for update of app "'.$app.'" in appstore </info>');
239 239
 			});
240
-			$updater->listen('\OC\Updater', 'appUpgradeCheckBefore', function () use ($output) {
240
+			$updater->listen('\OC\Updater', 'appUpgradeCheckBefore', function() use ($output) {
241 241
 				$output->writeln('<info>Checking updates of apps</info>');
242 242
 			});
243
-			$updater->listen('\OC\Updater', 'appSimulateUpdate', function ($app) use ($output) {
243
+			$updater->listen('\OC\Updater', 'appSimulateUpdate', function($app) use ($output) {
244 244
 				$output->writeln("<info>Checking whether the database schema for <$app> can be updated (this can take a long time depending on the database size)</info>");
245 245
 			});
246
-			$updater->listen('\OC\Updater', 'appUpgradeCheck', function () use ($output) {
246
+			$updater->listen('\OC\Updater', 'appUpgradeCheck', function() use ($output) {
247 247
 				$output->writeln('<info>Checked database schema update for apps</info>');
248 248
 			});
249
-			$updater->listen('\OC\Updater', 'appUpgradeStarted', function ($app, $version) use ($output) {
249
+			$updater->listen('\OC\Updater', 'appUpgradeStarted', function($app, $version) use ($output) {
250 250
 				$output->writeln("<info>Updating <$app> ...</info>");
251 251
 			});
252
-			$updater->listen('\OC\Updater', 'appUpgrade', function ($app, $version) use ($output) {
252
+			$updater->listen('\OC\Updater', 'appUpgrade', function($app, $version) use ($output) {
253 253
 				$output->writeln("<info>Updated <$app> to $version</info>");
254 254
 			});
255
-			$updater->listen('\OC\Updater', 'failure', function ($message) use($output, $self) {
255
+			$updater->listen('\OC\Updater', 'failure', function($message) use($output, $self) {
256 256
 				$output->writeln("<error>$message</error>");
257 257
 			});
258
-			$updater->listen('\OC\Updater', 'setDebugLogLevel', function ($logLevel, $logLevelName) use($output) {
258
+			$updater->listen('\OC\Updater', 'setDebugLogLevel', function($logLevel, $logLevelName) use($output) {
259 259
 				$output->writeln("<info>Set log level to debug</info>");
260 260
 			});
261
-			$updater->listen('\OC\Updater', 'resetLogLevel', function ($logLevel, $logLevelName) use($output) {
261
+			$updater->listen('\OC\Updater', 'resetLogLevel', function($logLevel, $logLevelName) use($output) {
262 262
 				$output->writeln("<info>Reset log level</info>");
263 263
 			});
264
-			$updater->listen('\OC\Updater', 'startCheckCodeIntegrity', function () use($output) {
264
+			$updater->listen('\OC\Updater', 'startCheckCodeIntegrity', function() use($output) {
265 265
 				$output->writeln("<info>Starting code integrity check...</info>");
266 266
 			});
267
-			$updater->listen('\OC\Updater', 'finishedCheckCodeIntegrity', function () use($output) {
267
+			$updater->listen('\OC\Updater', 'finishedCheckCodeIntegrity', function() use($output) {
268 268
 				$output->writeln("<info>Finished code integrity check</info>");
269 269
 			});
270 270
 
@@ -272,12 +272,12 @@  discard block
 block discarded – undo
272 272
 
273 273
 			$this->postUpgradeCheck($input, $output);
274 274
 
275
-			if(!$success) {
275
+			if (!$success) {
276 276
 				return self::ERROR_FAILURE;
277 277
 			}
278 278
 
279 279
 			return self::ERROR_SUCCESS;
280
-		} else if($this->config->getSystemValue('maintenance', false)) {
280
+		} else if ($this->config->getSystemValue('maintenance', false)) {
281 281
 			//Possible scenario: Nextcloud core is updated but an app failed
282 282
 			$output->writeln('<warning>Nextcloud is in maintenance mode</warning>');
283 283
 			$output->write('<comment>Maybe an upgrade is already in process. Please check the '
@@ -302,8 +302,8 @@  discard block
 block discarded – undo
302 302
 		$trustedDomains = $this->config->getSystemValue('trusted_domains', array());
303 303
 		if (empty($trustedDomains)) {
304 304
 			$output->write(
305
-				'<warning>The setting "trusted_domains" could not be ' .
306
-				'set automatically by the upgrade script, ' .
305
+				'<warning>The setting "trusted_domains" could not be '.
306
+				'set automatically by the upgrade script, '.
307 307
 				'please set it manually</warning>'
308 308
 			);
309 309
 		}
Please login to merge, or discard this patch.