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