Passed
Push — master ( ed1f89...987f62 )
by Roeland
12:51
created
lib/base.php 1 patch
Indentation   +1010 added lines, -1010 removed lines patch added patch discarded remove patch
@@ -77,1016 +77,1016 @@
 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 = new \OC\Accounts\Hooks(\OC::$server->getLogger());
858
-		\OCP\Util::connectHook('OC_User', 'changeUser', $hookHandler, 'changeUserHook');
859
-	}
860
-
861
-	private static function registerAppRestrictionsHooks() {
862
-		$groupManager = self::$server->query(\OCP\IGroupManager::class);
863
-		$groupManager->listen('\OC\Group', 'postDelete', function (\OCP\IGroup $group) {
864
-			$appManager = self::$server->getAppManager();
865
-			$apps = $appManager->getEnabledAppsForGroup($group);
866
-			foreach ($apps as $appId) {
867
-				$restrictions = $appManager->getAppRestriction($appId);
868
-				if (empty($restrictions)) {
869
-					continue;
870
-				}
871
-				$key = array_search($group->getGID(), $restrictions);
872
-				unset($restrictions[$key]);
873
-				$restrictions = array_values($restrictions);
874
-				if (empty($restrictions)) {
875
-					$appManager->disableApp($appId);
876
-				} else {
877
-					$appManager->enableAppForGroups($appId, $restrictions);
878
-				}
879
-			}
880
-		});
881
-	}
882
-
883
-	private static function registerResourceCollectionHooks() {
884
-		\OC\Collaboration\Resources\Listener::register(\OC::$server->getEventDispatcher());
885
-	}
886
-
887
-	/**
888
-	 * register hooks for the filesystem
889
-	 */
890
-	public static function registerFilesystemHooks() {
891
-		// Check for blacklisted files
892
-		OC_Hook::connect('OC_Filesystem', 'write', Filesystem::class, 'isBlacklisted');
893
-		OC_Hook::connect('OC_Filesystem', 'rename', Filesystem::class, 'isBlacklisted');
894
-	}
895
-
896
-	/**
897
-	 * register hooks for sharing
898
-	 */
899
-	public static function registerShareHooks() {
900
-		if (\OC::$server->getSystemConfig()->getValue('installed')) {
901
-			OC_Hook::connect('OC_User', 'post_deleteUser', Hooks::class, 'post_deleteUser');
902
-			OC_Hook::connect('OC_User', 'post_deleteGroup', Hooks::class, 'post_deleteGroup');
903
-
904
-			/** @var IEventDispatcher $dispatcher */
905
-			$dispatcher = \OC::$server->get(IEventDispatcher::class);
906
-			$dispatcher->addServiceListener(UserRemovedEvent::class, \OC\Share20\UserRemovedListener::class);
907
-		}
908
-	}
909
-
910
-	protected static function registerAutoloaderCache() {
911
-		// The class loader takes an optional low-latency cache, which MUST be
912
-		// namespaced. The instanceid is used for namespacing, but might be
913
-		// unavailable at this point. Furthermore, it might not be possible to
914
-		// generate an instanceid via \OC_Util::getInstanceId() because the
915
-		// config file may not be writable. As such, we only register a class
916
-		// loader cache if instanceid is available without trying to create one.
917
-		$instanceId = \OC::$server->getSystemConfig()->getValue('instanceid', null);
918
-		if ($instanceId) {
919
-			try {
920
-				$memcacheFactory = \OC::$server->getMemCacheFactory();
921
-				self::$loader->setMemoryCache($memcacheFactory->createLocal('Autoloader'));
922
-			} catch (\Exception $ex) {
923
-			}
924
-		}
925
-	}
926
-
927
-	/**
928
-	 * Handle the request
929
-	 */
930
-	public static function handleRequest() {
931
-		\OC::$server->getEventLogger()->start('handle_request', 'Handle request');
932
-		$systemConfig = \OC::$server->getSystemConfig();
933
-
934
-		// Check if Nextcloud is installed or in maintenance (update) mode
935
-		if (!$systemConfig->getValue('installed', false)) {
936
-			\OC::$server->getSession()->clear();
937
-			$setupHelper = new OC\Setup(
938
-				$systemConfig,
939
-				\OC::$server->get(\bantu\IniGetWrapper\IniGetWrapper::class),
940
-				\OC::$server->getL10N('lib'),
941
-				\OC::$server->query(\OCP\Defaults::class),
942
-				\OC::$server->getLogger(),
943
-				\OC::$server->getSecureRandom(),
944
-				\OC::$server->query(\OC\Installer::class)
945
-			);
946
-			$controller = new OC\Core\Controller\SetupController($setupHelper);
947
-			$controller->run($_POST);
948
-			exit();
949
-		}
950
-
951
-		$request = \OC::$server->getRequest();
952
-		$requestPath = $request->getRawPathInfo();
953
-		if ($requestPath === '/heartbeat') {
954
-			return;
955
-		}
956
-		if (substr($requestPath, -3) !== '.js') { // we need these files during the upgrade
957
-			self::checkMaintenanceMode();
958
-
959
-			if (\OCP\Util::needUpgrade()) {
960
-				if (function_exists('opcache_reset')) {
961
-					opcache_reset();
962
-				}
963
-				if (!((bool) $systemConfig->getValue('maintenance', false))) {
964
-					self::printUpgradePage($systemConfig);
965
-					exit();
966
-				}
967
-			}
968
-		}
969
-
970
-		// emergency app disabling
971
-		if ($requestPath === '/disableapp'
972
-			&& $request->getMethod() === 'POST'
973
-			&& ((array)$request->getParam('appid')) !== ''
974
-		) {
975
-			\OC_JSON::callCheck();
976
-			\OC_JSON::checkAdminUser();
977
-			$appIds = (array)$request->getParam('appid');
978
-			foreach ($appIds as $appId) {
979
-				$appId = \OC_App::cleanAppId($appId);
980
-				\OC::$server->getAppManager()->disableApp($appId);
981
-			}
982
-			\OC_JSON::success();
983
-			exit();
984
-		}
985
-
986
-		// Always load authentication apps
987
-		OC_App::loadApps(['authentication']);
988
-
989
-		// Load minimum set of apps
990
-		if (!\OCP\Util::needUpgrade()
991
-			&& !((bool) $systemConfig->getValue('maintenance', false))) {
992
-			// For logged-in users: Load everything
993
-			if (\OC::$server->getUserSession()->isLoggedIn()) {
994
-				OC_App::loadApps();
995
-			} else {
996
-				// For guests: Load only filesystem and logging
997
-				OC_App::loadApps(['filesystem', 'logging']);
998
-				self::handleLogin($request);
999
-			}
1000
-		}
1001
-
1002
-		if (!self::$CLI) {
1003
-			try {
1004
-				if (!((bool) $systemConfig->getValue('maintenance', false)) && !\OCP\Util::needUpgrade()) {
1005
-					OC_App::loadApps(['filesystem', 'logging']);
1006
-					OC_App::loadApps();
1007
-				}
1008
-				OC_Util::setupFS();
1009
-				OC::$server->getRouter()->match(\OC::$server->getRequest()->getRawPathInfo());
1010
-				return;
1011
-			} catch (Symfony\Component\Routing\Exception\ResourceNotFoundException $e) {
1012
-				//header('HTTP/1.0 404 Not Found');
1013
-			} catch (Symfony\Component\Routing\Exception\MethodNotAllowedException $e) {
1014
-				http_response_code(405);
1015
-				return;
1016
-			}
1017
-		}
1018
-
1019
-		// Handle WebDAV
1020
-		if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'PROPFIND') {
1021
-			// not allowed any more to prevent people
1022
-			// mounting this root directly.
1023
-			// Users need to mount remote.php/webdav instead.
1024
-			http_response_code(405);
1025
-			return;
1026
-		}
1027
-
1028
-		// Someone is logged in
1029
-		if (\OC::$server->getUserSession()->isLoggedIn()) {
1030
-			OC_App::loadApps();
1031
-			OC_User::setupBackends();
1032
-			OC_Util::setupFS();
1033
-			// FIXME
1034
-			// Redirect to default application
1035
-			OC_Util::redirectToDefaultPage();
1036
-		} else {
1037
-			// Not handled and not logged in
1038
-			header('Location: '.\OC::$server->getURLGenerator()->linkToRouteAbsolute('core.login.showLoginForm'));
1039
-		}
1040
-	}
1041
-
1042
-	/**
1043
-	 * Check login: apache auth, auth token, basic auth
1044
-	 *
1045
-	 * @param OCP\IRequest $request
1046
-	 * @return boolean
1047
-	 */
1048
-	public static function handleLogin(OCP\IRequest $request) {
1049
-		$userSession = self::$server->getUserSession();
1050
-		if (OC_User::handleApacheAuth()) {
1051
-			return true;
1052
-		}
1053
-		if ($userSession->tryTokenLogin($request)) {
1054
-			return true;
1055
-		}
1056
-		if (isset($_COOKIE['nc_username'])
1057
-			&& isset($_COOKIE['nc_token'])
1058
-			&& isset($_COOKIE['nc_session_id'])
1059
-			&& $userSession->loginWithCookie($_COOKIE['nc_username'], $_COOKIE['nc_token'], $_COOKIE['nc_session_id'])) {
1060
-			return true;
1061
-		}
1062
-		if ($userSession->tryBasicAuthLogin($request, \OC::$server->getBruteForceThrottler())) {
1063
-			return true;
1064
-		}
1065
-		return false;
1066
-	}
1067
-
1068
-	protected static function handleAuthHeaders() {
1069
-		//copy http auth headers for apache+php-fcgid work around
1070
-		if (isset($_SERVER['HTTP_XAUTHORIZATION']) && !isset($_SERVER['HTTP_AUTHORIZATION'])) {
1071
-			$_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['HTTP_XAUTHORIZATION'];
1072
-		}
1073
-
1074
-		// Extract PHP_AUTH_USER/PHP_AUTH_PW from other headers if necessary.
1075
-		$vars = [
1076
-			'HTTP_AUTHORIZATION', // apache+php-cgi work around
1077
-			'REDIRECT_HTTP_AUTHORIZATION', // apache+php-cgi alternative
1078
-		];
1079
-		foreach ($vars as $var) {
1080
-			if (isset($_SERVER[$var]) && preg_match('/Basic\s+(.*)$/i', $_SERVER[$var], $matches)) {
1081
-				$credentials = explode(':', base64_decode($matches[1]), 2);
1082
-				if (count($credentials) === 2) {
1083
-					$_SERVER['PHP_AUTH_USER'] = $credentials[0];
1084
-					$_SERVER['PHP_AUTH_PW'] = $credentials[1];
1085
-					break;
1086
-				}
1087
-			}
1088
-		}
1089
-	}
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 = new \OC\Accounts\Hooks(\OC::$server->getLogger());
858
+        \OCP\Util::connectHook('OC_User', 'changeUser', $hookHandler, 'changeUserHook');
859
+    }
860
+
861
+    private static function registerAppRestrictionsHooks() {
862
+        $groupManager = self::$server->query(\OCP\IGroupManager::class);
863
+        $groupManager->listen('\OC\Group', 'postDelete', function (\OCP\IGroup $group) {
864
+            $appManager = self::$server->getAppManager();
865
+            $apps = $appManager->getEnabledAppsForGroup($group);
866
+            foreach ($apps as $appId) {
867
+                $restrictions = $appManager->getAppRestriction($appId);
868
+                if (empty($restrictions)) {
869
+                    continue;
870
+                }
871
+                $key = array_search($group->getGID(), $restrictions);
872
+                unset($restrictions[$key]);
873
+                $restrictions = array_values($restrictions);
874
+                if (empty($restrictions)) {
875
+                    $appManager->disableApp($appId);
876
+                } else {
877
+                    $appManager->enableAppForGroups($appId, $restrictions);
878
+                }
879
+            }
880
+        });
881
+    }
882
+
883
+    private static function registerResourceCollectionHooks() {
884
+        \OC\Collaboration\Resources\Listener::register(\OC::$server->getEventDispatcher());
885
+    }
886
+
887
+    /**
888
+     * register hooks for the filesystem
889
+     */
890
+    public static function registerFilesystemHooks() {
891
+        // Check for blacklisted files
892
+        OC_Hook::connect('OC_Filesystem', 'write', Filesystem::class, 'isBlacklisted');
893
+        OC_Hook::connect('OC_Filesystem', 'rename', Filesystem::class, 'isBlacklisted');
894
+    }
895
+
896
+    /**
897
+     * register hooks for sharing
898
+     */
899
+    public static function registerShareHooks() {
900
+        if (\OC::$server->getSystemConfig()->getValue('installed')) {
901
+            OC_Hook::connect('OC_User', 'post_deleteUser', Hooks::class, 'post_deleteUser');
902
+            OC_Hook::connect('OC_User', 'post_deleteGroup', Hooks::class, 'post_deleteGroup');
903
+
904
+            /** @var IEventDispatcher $dispatcher */
905
+            $dispatcher = \OC::$server->get(IEventDispatcher::class);
906
+            $dispatcher->addServiceListener(UserRemovedEvent::class, \OC\Share20\UserRemovedListener::class);
907
+        }
908
+    }
909
+
910
+    protected static function registerAutoloaderCache() {
911
+        // The class loader takes an optional low-latency cache, which MUST be
912
+        // namespaced. The instanceid is used for namespacing, but might be
913
+        // unavailable at this point. Furthermore, it might not be possible to
914
+        // generate an instanceid via \OC_Util::getInstanceId() because the
915
+        // config file may not be writable. As such, we only register a class
916
+        // loader cache if instanceid is available without trying to create one.
917
+        $instanceId = \OC::$server->getSystemConfig()->getValue('instanceid', null);
918
+        if ($instanceId) {
919
+            try {
920
+                $memcacheFactory = \OC::$server->getMemCacheFactory();
921
+                self::$loader->setMemoryCache($memcacheFactory->createLocal('Autoloader'));
922
+            } catch (\Exception $ex) {
923
+            }
924
+        }
925
+    }
926
+
927
+    /**
928
+     * Handle the request
929
+     */
930
+    public static function handleRequest() {
931
+        \OC::$server->getEventLogger()->start('handle_request', 'Handle request');
932
+        $systemConfig = \OC::$server->getSystemConfig();
933
+
934
+        // Check if Nextcloud is installed or in maintenance (update) mode
935
+        if (!$systemConfig->getValue('installed', false)) {
936
+            \OC::$server->getSession()->clear();
937
+            $setupHelper = new OC\Setup(
938
+                $systemConfig,
939
+                \OC::$server->get(\bantu\IniGetWrapper\IniGetWrapper::class),
940
+                \OC::$server->getL10N('lib'),
941
+                \OC::$server->query(\OCP\Defaults::class),
942
+                \OC::$server->getLogger(),
943
+                \OC::$server->getSecureRandom(),
944
+                \OC::$server->query(\OC\Installer::class)
945
+            );
946
+            $controller = new OC\Core\Controller\SetupController($setupHelper);
947
+            $controller->run($_POST);
948
+            exit();
949
+        }
950
+
951
+        $request = \OC::$server->getRequest();
952
+        $requestPath = $request->getRawPathInfo();
953
+        if ($requestPath === '/heartbeat') {
954
+            return;
955
+        }
956
+        if (substr($requestPath, -3) !== '.js') { // we need these files during the upgrade
957
+            self::checkMaintenanceMode();
958
+
959
+            if (\OCP\Util::needUpgrade()) {
960
+                if (function_exists('opcache_reset')) {
961
+                    opcache_reset();
962
+                }
963
+                if (!((bool) $systemConfig->getValue('maintenance', false))) {
964
+                    self::printUpgradePage($systemConfig);
965
+                    exit();
966
+                }
967
+            }
968
+        }
969
+
970
+        // emergency app disabling
971
+        if ($requestPath === '/disableapp'
972
+            && $request->getMethod() === 'POST'
973
+            && ((array)$request->getParam('appid')) !== ''
974
+        ) {
975
+            \OC_JSON::callCheck();
976
+            \OC_JSON::checkAdminUser();
977
+            $appIds = (array)$request->getParam('appid');
978
+            foreach ($appIds as $appId) {
979
+                $appId = \OC_App::cleanAppId($appId);
980
+                \OC::$server->getAppManager()->disableApp($appId);
981
+            }
982
+            \OC_JSON::success();
983
+            exit();
984
+        }
985
+
986
+        // Always load authentication apps
987
+        OC_App::loadApps(['authentication']);
988
+
989
+        // Load minimum set of apps
990
+        if (!\OCP\Util::needUpgrade()
991
+            && !((bool) $systemConfig->getValue('maintenance', false))) {
992
+            // For logged-in users: Load everything
993
+            if (\OC::$server->getUserSession()->isLoggedIn()) {
994
+                OC_App::loadApps();
995
+            } else {
996
+                // For guests: Load only filesystem and logging
997
+                OC_App::loadApps(['filesystem', 'logging']);
998
+                self::handleLogin($request);
999
+            }
1000
+        }
1001
+
1002
+        if (!self::$CLI) {
1003
+            try {
1004
+                if (!((bool) $systemConfig->getValue('maintenance', false)) && !\OCP\Util::needUpgrade()) {
1005
+                    OC_App::loadApps(['filesystem', 'logging']);
1006
+                    OC_App::loadApps();
1007
+                }
1008
+                OC_Util::setupFS();
1009
+                OC::$server->getRouter()->match(\OC::$server->getRequest()->getRawPathInfo());
1010
+                return;
1011
+            } catch (Symfony\Component\Routing\Exception\ResourceNotFoundException $e) {
1012
+                //header('HTTP/1.0 404 Not Found');
1013
+            } catch (Symfony\Component\Routing\Exception\MethodNotAllowedException $e) {
1014
+                http_response_code(405);
1015
+                return;
1016
+            }
1017
+        }
1018
+
1019
+        // Handle WebDAV
1020
+        if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'PROPFIND') {
1021
+            // not allowed any more to prevent people
1022
+            // mounting this root directly.
1023
+            // Users need to mount remote.php/webdav instead.
1024
+            http_response_code(405);
1025
+            return;
1026
+        }
1027
+
1028
+        // Someone is logged in
1029
+        if (\OC::$server->getUserSession()->isLoggedIn()) {
1030
+            OC_App::loadApps();
1031
+            OC_User::setupBackends();
1032
+            OC_Util::setupFS();
1033
+            // FIXME
1034
+            // Redirect to default application
1035
+            OC_Util::redirectToDefaultPage();
1036
+        } else {
1037
+            // Not handled and not logged in
1038
+            header('Location: '.\OC::$server->getURLGenerator()->linkToRouteAbsolute('core.login.showLoginForm'));
1039
+        }
1040
+    }
1041
+
1042
+    /**
1043
+     * Check login: apache auth, auth token, basic auth
1044
+     *
1045
+     * @param OCP\IRequest $request
1046
+     * @return boolean
1047
+     */
1048
+    public static function handleLogin(OCP\IRequest $request) {
1049
+        $userSession = self::$server->getUserSession();
1050
+        if (OC_User::handleApacheAuth()) {
1051
+            return true;
1052
+        }
1053
+        if ($userSession->tryTokenLogin($request)) {
1054
+            return true;
1055
+        }
1056
+        if (isset($_COOKIE['nc_username'])
1057
+            && isset($_COOKIE['nc_token'])
1058
+            && isset($_COOKIE['nc_session_id'])
1059
+            && $userSession->loginWithCookie($_COOKIE['nc_username'], $_COOKIE['nc_token'], $_COOKIE['nc_session_id'])) {
1060
+            return true;
1061
+        }
1062
+        if ($userSession->tryBasicAuthLogin($request, \OC::$server->getBruteForceThrottler())) {
1063
+            return true;
1064
+        }
1065
+        return false;
1066
+    }
1067
+
1068
+    protected static function handleAuthHeaders() {
1069
+        //copy http auth headers for apache+php-fcgid work around
1070
+        if (isset($_SERVER['HTTP_XAUTHORIZATION']) && !isset($_SERVER['HTTP_AUTHORIZATION'])) {
1071
+            $_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['HTTP_XAUTHORIZATION'];
1072
+        }
1073
+
1074
+        // Extract PHP_AUTH_USER/PHP_AUTH_PW from other headers if necessary.
1075
+        $vars = [
1076
+            'HTTP_AUTHORIZATION', // apache+php-cgi work around
1077
+            'REDIRECT_HTTP_AUTHORIZATION', // apache+php-cgi alternative
1078
+        ];
1079
+        foreach ($vars as $var) {
1080
+            if (isset($_SERVER[$var]) && preg_match('/Basic\s+(.*)$/i', $_SERVER[$var], $matches)) {
1081
+                $credentials = explode(':', base64_decode($matches[1]), 2);
1082
+                if (count($credentials) === 2) {
1083
+                    $_SERVER['PHP_AUTH_USER'] = $credentials[0];
1084
+                    $_SERVER['PHP_AUTH_PW'] = $credentials[1];
1085
+                    break;
1086
+                }
1087
+            }
1088
+        }
1089
+    }
1090 1090
 }
1091 1091
 
1092 1092
 OC::init();
Please login to merge, or discard this patch.
lib/private/LargeFileHelper.php 1 patch
Indentation   +165 added lines, -165 removed lines patch added patch discarded remove patch
@@ -35,178 +35,178 @@
 block discarded – undo
35 35
  * Helper class for large files on 32-bit platforms.
36 36
  */
37 37
 class LargeFileHelper {
38
-	/**
39
-	 * pow(2, 53) as a base-10 string.
40
-	 * @var string
41
-	 */
42
-	public const POW_2_53 = '9007199254740992';
38
+    /**
39
+     * pow(2, 53) as a base-10 string.
40
+     * @var string
41
+     */
42
+    public const POW_2_53 = '9007199254740992';
43 43
 
44
-	/**
45
-	 * pow(2, 53) - 1 as a base-10 string.
46
-	 * @var string
47
-	 */
48
-	public const POW_2_53_MINUS_1 = '9007199254740991';
44
+    /**
45
+     * pow(2, 53) - 1 as a base-10 string.
46
+     * @var string
47
+     */
48
+    public const POW_2_53_MINUS_1 = '9007199254740991';
49 49
 
50
-	/**
51
-	 * @brief Checks whether our assumptions hold on the PHP platform we are on.
52
-	 *
53
-	 * @throws \RunTimeException if our assumptions do not hold on the current
54
-	 *                           PHP platform.
55
-	 */
56
-	public function __construct() {
57
-		$pow_2_53 = (float)self::POW_2_53_MINUS_1 + 1.0;
58
-		if ($this->formatUnsignedInteger($pow_2_53) !== self::POW_2_53) {
59
-			throw new \RuntimeException(
60
-				'This class assumes floats to be double precision or "better".'
61
-			);
62
-		}
63
-	}
50
+    /**
51
+     * @brief Checks whether our assumptions hold on the PHP platform we are on.
52
+     *
53
+     * @throws \RunTimeException if our assumptions do not hold on the current
54
+     *                           PHP platform.
55
+     */
56
+    public function __construct() {
57
+        $pow_2_53 = (float)self::POW_2_53_MINUS_1 + 1.0;
58
+        if ($this->formatUnsignedInteger($pow_2_53) !== self::POW_2_53) {
59
+            throw new \RuntimeException(
60
+                'This class assumes floats to be double precision or "better".'
61
+            );
62
+        }
63
+    }
64 64
 
65
-	/**
66
-	 * @brief Formats a signed integer or float as an unsigned integer base-10
67
-	 *        string. Passed strings will be checked for being base-10.
68
-	 *
69
-	 * @param int|float|string $number Number containing unsigned integer data
70
-	 *
71
-	 * @throws \UnexpectedValueException if $number is not a float, not an int
72
-	 *                                   and not a base-10 string.
73
-	 *
74
-	 * @return string Unsigned integer base-10 string
75
-	 */
76
-	public function formatUnsignedInteger($number) {
77
-		if (is_float($number)) {
78
-			// Undo the effect of the php.ini setting 'precision'.
79
-			return number_format($number, 0, '', '');
80
-		} elseif (is_string($number) && ctype_digit($number)) {
81
-			return $number;
82
-		} elseif (is_int($number)) {
83
-			// Interpret signed integer as unsigned integer.
84
-			return sprintf('%u', $number);
85
-		} else {
86
-			throw new \UnexpectedValueException(
87
-				'Expected int, float or base-10 string'
88
-			);
89
-		}
90
-	}
65
+    /**
66
+     * @brief Formats a signed integer or float as an unsigned integer base-10
67
+     *        string. Passed strings will be checked for being base-10.
68
+     *
69
+     * @param int|float|string $number Number containing unsigned integer data
70
+     *
71
+     * @throws \UnexpectedValueException if $number is not a float, not an int
72
+     *                                   and not a base-10 string.
73
+     *
74
+     * @return string Unsigned integer base-10 string
75
+     */
76
+    public function formatUnsignedInteger($number) {
77
+        if (is_float($number)) {
78
+            // Undo the effect of the php.ini setting 'precision'.
79
+            return number_format($number, 0, '', '');
80
+        } elseif (is_string($number) && ctype_digit($number)) {
81
+            return $number;
82
+        } elseif (is_int($number)) {
83
+            // Interpret signed integer as unsigned integer.
84
+            return sprintf('%u', $number);
85
+        } else {
86
+            throw new \UnexpectedValueException(
87
+                'Expected int, float or base-10 string'
88
+            );
89
+        }
90
+    }
91 91
 
92
-	/**
93
-	 * @brief Tries to get the size of a file via various workarounds that
94
-	 *        even work for large files on 32-bit platforms.
95
-	 *
96
-	 * @param string $filename Path to the file.
97
-	 *
98
-	 * @return null|int|float Number of bytes as number (float or int) or
99
-	 *                        null on failure.
100
-	 */
101
-	public function getFileSize($filename) {
102
-		$fileSize = $this->getFileSizeViaCurl($filename);
103
-		if (!is_null($fileSize)) {
104
-			return $fileSize;
105
-		}
106
-		$fileSize = $this->getFileSizeViaExec($filename);
107
-		if (!is_null($fileSize)) {
108
-			return $fileSize;
109
-		}
110
-		return $this->getFileSizeNative($filename);
111
-	}
92
+    /**
93
+     * @brief Tries to get the size of a file via various workarounds that
94
+     *        even work for large files on 32-bit platforms.
95
+     *
96
+     * @param string $filename Path to the file.
97
+     *
98
+     * @return null|int|float Number of bytes as number (float or int) or
99
+     *                        null on failure.
100
+     */
101
+    public function getFileSize($filename) {
102
+        $fileSize = $this->getFileSizeViaCurl($filename);
103
+        if (!is_null($fileSize)) {
104
+            return $fileSize;
105
+        }
106
+        $fileSize = $this->getFileSizeViaExec($filename);
107
+        if (!is_null($fileSize)) {
108
+            return $fileSize;
109
+        }
110
+        return $this->getFileSizeNative($filename);
111
+    }
112 112
 
113
-	/**
114
-	 * @brief Tries to get the size of a file via a CURL HEAD request.
115
-	 *
116
-	 * @param string $fileName Path to the file.
117
-	 *
118
-	 * @return null|int|float Number of bytes as number (float or int) or
119
-	 *                        null on failure.
120
-	 */
121
-	public function getFileSizeViaCurl($fileName) {
122
-		if (\OC::$server->get(IniGetWrapper::class)->getString('open_basedir') === '') {
123
-			$encodedFileName = rawurlencode($fileName);
124
-			$ch = curl_init("file:///$encodedFileName");
125
-			curl_setopt($ch, CURLOPT_NOBODY, true);
126
-			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
127
-			curl_setopt($ch, CURLOPT_HEADER, true);
128
-			$data = curl_exec($ch);
129
-			curl_close($ch);
130
-			if ($data !== false) {
131
-				$matches = [];
132
-				preg_match('/Content-Length: (\d+)/', $data, $matches);
133
-				if (isset($matches[1])) {
134
-					return 0 + $matches[1];
135
-				}
136
-			}
137
-		}
138
-		return null;
139
-	}
113
+    /**
114
+     * @brief Tries to get the size of a file via a CURL HEAD request.
115
+     *
116
+     * @param string $fileName Path to the file.
117
+     *
118
+     * @return null|int|float Number of bytes as number (float or int) or
119
+     *                        null on failure.
120
+     */
121
+    public function getFileSizeViaCurl($fileName) {
122
+        if (\OC::$server->get(IniGetWrapper::class)->getString('open_basedir') === '') {
123
+            $encodedFileName = rawurlencode($fileName);
124
+            $ch = curl_init("file:///$encodedFileName");
125
+            curl_setopt($ch, CURLOPT_NOBODY, true);
126
+            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
127
+            curl_setopt($ch, CURLOPT_HEADER, true);
128
+            $data = curl_exec($ch);
129
+            curl_close($ch);
130
+            if ($data !== false) {
131
+                $matches = [];
132
+                preg_match('/Content-Length: (\d+)/', $data, $matches);
133
+                if (isset($matches[1])) {
134
+                    return 0 + $matches[1];
135
+                }
136
+            }
137
+        }
138
+        return null;
139
+    }
140 140
 
141
-	/**
142
-	 * @brief Tries to get the size of a file via an exec() call.
143
-	 *
144
-	 * @param string $filename Path to the file.
145
-	 *
146
-	 * @return null|int|float Number of bytes as number (float or int) or
147
-	 *                        null on failure.
148
-	 */
149
-	public function getFileSizeViaExec($filename) {
150
-		if (\OC_Helper::is_function_enabled('exec')) {
151
-			$os = strtolower(php_uname('s'));
152
-			$arg = escapeshellarg($filename);
153
-			$result = null;
154
-			if (strpos($os, 'linux') !== false) {
155
-				$result = $this->exec("stat -c %s $arg");
156
-			} elseif (strpos($os, 'bsd') !== false || strpos($os, 'darwin') !== false) {
157
-				$result = $this->exec("stat -f %z $arg");
158
-			}
159
-			return $result;
160
-		}
161
-		return null;
162
-	}
141
+    /**
142
+     * @brief Tries to get the size of a file via an exec() call.
143
+     *
144
+     * @param string $filename Path to the file.
145
+     *
146
+     * @return null|int|float Number of bytes as number (float or int) or
147
+     *                        null on failure.
148
+     */
149
+    public function getFileSizeViaExec($filename) {
150
+        if (\OC_Helper::is_function_enabled('exec')) {
151
+            $os = strtolower(php_uname('s'));
152
+            $arg = escapeshellarg($filename);
153
+            $result = null;
154
+            if (strpos($os, 'linux') !== false) {
155
+                $result = $this->exec("stat -c %s $arg");
156
+            } elseif (strpos($os, 'bsd') !== false || strpos($os, 'darwin') !== false) {
157
+                $result = $this->exec("stat -f %z $arg");
158
+            }
159
+            return $result;
160
+        }
161
+        return null;
162
+    }
163 163
 
164
-	/**
165
-	 * @brief Gets the size of a file via a filesize() call and converts
166
-	 *        negative signed int to positive float. As the result of filesize()
167
-	 *        will wrap around after a file size of 2^32 bytes = 4 GiB, this
168
-	 *        should only be used as a last resort.
169
-	 *
170
-	 * @param string $filename Path to the file.
171
-	 *
172
-	 * @return int|float Number of bytes as number (float or int).
173
-	 */
174
-	public function getFileSizeNative($filename) {
175
-		$result = filesize($filename);
176
-		if ($result < 0) {
177
-			// For file sizes between 2 GiB and 4 GiB, filesize() will return a
178
-			// negative int, as the PHP data type int is signed. Interpret the
179
-			// returned int as an unsigned integer and put it into a float.
180
-			return (float) sprintf('%u', $result);
181
-		}
182
-		return $result;
183
-	}
164
+    /**
165
+     * @brief Gets the size of a file via a filesize() call and converts
166
+     *        negative signed int to positive float. As the result of filesize()
167
+     *        will wrap around after a file size of 2^32 bytes = 4 GiB, this
168
+     *        should only be used as a last resort.
169
+     *
170
+     * @param string $filename Path to the file.
171
+     *
172
+     * @return int|float Number of bytes as number (float or int).
173
+     */
174
+    public function getFileSizeNative($filename) {
175
+        $result = filesize($filename);
176
+        if ($result < 0) {
177
+            // For file sizes between 2 GiB and 4 GiB, filesize() will return a
178
+            // negative int, as the PHP data type int is signed. Interpret the
179
+            // returned int as an unsigned integer and put it into a float.
180
+            return (float) sprintf('%u', $result);
181
+        }
182
+        return $result;
183
+    }
184 184
 
185
-	/**
186
-	 * Returns the current mtime for $fullPath
187
-	 *
188
-	 * @param string $fullPath
189
-	 * @return int
190
-	 */
191
-	public function getFileMtime($fullPath) {
192
-		try {
193
-			$result = filemtime($fullPath);
194
-		} catch (\Exception $e) {
195
-			$result =- 1;
196
-		}
197
-		if ($result < 0) {
198
-			if (\OC_Helper::is_function_enabled('exec')) {
199
-				$os = strtolower(php_uname('s'));
200
-				if (strpos($os, 'linux') !== false) {
201
-					return $this->exec('stat -c %Y ' . escapeshellarg($fullPath));
202
-				}
203
-			}
204
-		}
205
-		return $result;
206
-	}
185
+    /**
186
+     * Returns the current mtime for $fullPath
187
+     *
188
+     * @param string $fullPath
189
+     * @return int
190
+     */
191
+    public function getFileMtime($fullPath) {
192
+        try {
193
+            $result = filemtime($fullPath);
194
+        } catch (\Exception $e) {
195
+            $result =- 1;
196
+        }
197
+        if ($result < 0) {
198
+            if (\OC_Helper::is_function_enabled('exec')) {
199
+                $os = strtolower(php_uname('s'));
200
+                if (strpos($os, 'linux') !== false) {
201
+                    return $this->exec('stat -c %Y ' . escapeshellarg($fullPath));
202
+                }
203
+            }
204
+        }
205
+        return $result;
206
+    }
207 207
 
208
-	protected function exec($cmd) {
209
-		$result = trim(exec($cmd));
210
-		return ctype_digit($result) ? 0 + $result : null;
211
-	}
208
+    protected function exec($cmd) {
209
+        $result = trim(exec($cmd));
210
+        return ctype_digit($result) ? 0 + $result : null;
211
+    }
212 212
 }
Please login to merge, or discard this patch.
lib/private/Server.php 2 patches
Indentation   +2049 added lines, -2049 removed lines patch added patch discarded remove patch
@@ -243,2058 +243,2058 @@
 block discarded – undo
243 243
  */
244 244
 class Server extends ServerContainer implements IServerContainer {
245 245
 
246
-	/** @var string */
247
-	private $webRoot;
248
-
249
-	/**
250
-	 * @param string $webRoot
251
-	 * @param \OC\Config $config
252
-	 */
253
-	public function __construct($webRoot, \OC\Config $config) {
254
-		parent::__construct();
255
-		$this->webRoot = $webRoot;
256
-
257
-		// To find out if we are running from CLI or not
258
-		$this->registerParameter('isCLI', \OC::$CLI);
259
-		$this->registerParameter('serverRoot', \OC::$SERVERROOT);
260
-
261
-		$this->registerService(ContainerInterface::class, function (ContainerInterface $c) {
262
-			return $c;
263
-		});
264
-		$this->registerService(\OCP\IServerContainer::class, function (ContainerInterface $c) {
265
-			return $c;
266
-		});
267
-
268
-		$this->registerAlias(\OCP\Calendar\IManager::class, \OC\Calendar\Manager::class);
269
-		/** @deprecated 19.0.0 */
270
-		$this->registerDeprecatedAlias('CalendarManager', \OC\Calendar\Manager::class);
271
-
272
-		$this->registerAlias(\OCP\Calendar\Resource\IManager::class, \OC\Calendar\Resource\Manager::class);
273
-		/** @deprecated 19.0.0 */
274
-		$this->registerDeprecatedAlias('CalendarResourceBackendManager', \OC\Calendar\Resource\Manager::class);
275
-
276
-		$this->registerAlias(\OCP\Calendar\Room\IManager::class, \OC\Calendar\Room\Manager::class);
277
-		/** @deprecated 19.0.0 */
278
-		$this->registerDeprecatedAlias('CalendarRoomBackendManager', \OC\Calendar\Room\Manager::class);
279
-
280
-		$this->registerAlias(\OCP\Contacts\IManager::class, \OC\ContactsManager::class);
281
-		/** @deprecated 19.0.0 */
282
-		$this->registerDeprecatedAlias('ContactsManager', \OCP\Contacts\IManager::class);
283
-
284
-		$this->registerAlias(\OCP\DirectEditing\IManager::class, \OC\DirectEditing\Manager::class);
285
-
286
-		$this->registerAlias(IActionFactory::class, ActionFactory::class);
287
-
288
-
289
-		$this->registerService(IPreview::class, function (Server $c) {
290
-			return new PreviewManager(
291
-				$c->getConfig(),
292
-				$c->getRootFolder(),
293
-				new \OC\Preview\Storage\Root($c->getRootFolder(), $c->getSystemConfig()),
294
-				$c->getEventDispatcher(),
295
-				$c->getGeneratorHelper(),
296
-				$c->getSession()->get('user_id')
297
-			);
298
-		});
299
-		/** @deprecated 19.0.0 */
300
-		$this->registerDeprecatedAlias('PreviewManager', IPreview::class);
301
-
302
-		$this->registerService(\OC\Preview\Watcher::class, function (Server $c) {
303
-			return new \OC\Preview\Watcher(
304
-				new \OC\Preview\Storage\Root($c->getRootFolder(), $c->getSystemConfig())
305
-			);
306
-		});
307
-
308
-		$this->registerService(\OCP\Encryption\IManager::class, function (Server $c) {
309
-			$view = new View();
310
-			$util = new Encryption\Util(
311
-				$view,
312
-				$c->getUserManager(),
313
-				$c->getGroupManager(),
314
-				$c->getConfig()
315
-			);
316
-			return new Encryption\Manager(
317
-				$c->getConfig(),
318
-				$c->getLogger(),
319
-				$c->getL10N('core'),
320
-				new View(),
321
-				$util,
322
-				new ArrayCache()
323
-			);
324
-		});
325
-		/** @deprecated 19.0.0 */
326
-		$this->registerDeprecatedAlias('EncryptionManager', \OCP\Encryption\IManager::class);
327
-
328
-		$this->registerService('EncryptionFileHelper', function (Server $c) {
329
-			$util = new Encryption\Util(
330
-				new View(),
331
-				$c->getUserManager(),
332
-				$c->getGroupManager(),
333
-				$c->getConfig()
334
-			);
335
-			return new Encryption\File(
336
-				$util,
337
-				$c->getRootFolder(),
338
-				$c->getShareManager()
339
-			);
340
-		});
341
-
342
-		$this->registerService('EncryptionKeyStorage', function (Server $c) {
343
-			$view = new View();
344
-			$util = new Encryption\Util(
345
-				$view,
346
-				$c->getUserManager(),
347
-				$c->getGroupManager(),
348
-				$c->getConfig()
349
-			);
350
-
351
-			return new Encryption\Keys\Storage($view, $util, $c->getCrypto(), $c->getConfig());
352
-		});
353
-		/** @deprecated 20.0.0 */
354
-		$this->registerDeprecatedAlias('TagMapper', TagMapper::class);
355
-
356
-		$this->registerAlias(\OCP\ITagManager::class, TagManager::class);
357
-		/** @deprecated 19.0.0 */
358
-		$this->registerDeprecatedAlias('TagManager', \OCP\ITagManager::class);
359
-
360
-		$this->registerService('SystemTagManagerFactory', function (Server $c) {
361
-			$config = $c->getConfig();
362
-			$factoryClass = $config->getSystemValue('systemtags.managerFactory', SystemTagManagerFactory::class);
363
-			return new $factoryClass($this);
364
-		});
365
-		$this->registerService(ISystemTagManager::class, function (Server $c) {
366
-			return $c->query('SystemTagManagerFactory')->getManager();
367
-		});
368
-		/** @deprecated 19.0.0 */
369
-		$this->registerDeprecatedAlias('SystemTagManager', ISystemTagManager::class);
370
-
371
-		$this->registerService(ISystemTagObjectMapper::class, function (Server $c) {
372
-			return $c->query('SystemTagManagerFactory')->getObjectMapper();
373
-		});
374
-		$this->registerService('RootFolder', function (Server $c) {
375
-			$manager = \OC\Files\Filesystem::getMountManager(null);
376
-			$view = new View();
377
-			$root = new Root(
378
-				$manager,
379
-				$view,
380
-				null,
381
-				$c->getUserMountCache(),
382
-				$this->getLogger(),
383
-				$this->getUserManager()
384
-			);
385
-
386
-			$previewConnector = new \OC\Preview\WatcherConnector($root, $c->getSystemConfig());
387
-			$previewConnector->connectWatcher();
388
-
389
-			return $root;
390
-		});
391
-		$this->registerService(HookConnector::class, function (Server $c) {
392
-			return new HookConnector(
393
-				$c->query(IRootFolder::class),
394
-				new View(),
395
-				$c->query(\OC\EventDispatcher\SymfonyAdapter::class),
396
-				$c->query(IEventDispatcher::class)
397
-			);
398
-		});
399
-
400
-		/** @deprecated 19.0.0 */
401
-		$this->registerDeprecatedAlias('SystemTagObjectMapper', ISystemTagObjectMapper::class);
402
-
403
-		$this->registerService(IRootFolder::class, function (Server $c) {
404
-			return new LazyRoot(function () use ($c) {
405
-				return $c->query('RootFolder');
406
-			});
407
-		});
408
-		/** @deprecated 19.0.0 */
409
-		$this->registerDeprecatedAlias('LazyRootFolder', IRootFolder::class);
410
-
411
-		/** @deprecated 19.0.0 */
412
-		$this->registerDeprecatedAlias('UserManager', \OC\User\Manager::class);
413
-		$this->registerAlias(\OCP\IUserManager::class, \OC\User\Manager::class);
414
-
415
-		$this->registerService(\OCP\IGroupManager::class, function (Server $c) {
416
-			$groupManager = new \OC\Group\Manager($this->getUserManager(), $c->getEventDispatcher(), $this->getLogger());
417
-			$groupManager->listen('\OC\Group', 'preCreate', function ($gid) {
418
-				\OC_Hook::emit('OC_Group', 'pre_createGroup', ['run' => true, 'gid' => $gid]);
419
-
420
-				/** @var IEventDispatcher $dispatcher */
421
-				$dispatcher = $this->query(IEventDispatcher::class);
422
-				$dispatcher->dispatchTyped(new BeforeGroupCreatedEvent($gid));
423
-			});
424
-			$groupManager->listen('\OC\Group', 'postCreate', function (\OC\Group\Group $group) {
425
-				\OC_Hook::emit('OC_User', 'post_createGroup', ['gid' => $group->getGID()]);
426
-
427
-				/** @var IEventDispatcher $dispatcher */
428
-				$dispatcher = $this->query(IEventDispatcher::class);
429
-				$dispatcher->dispatchTyped(new GroupCreatedEvent($group));
430
-			});
431
-			$groupManager->listen('\OC\Group', 'preDelete', function (\OC\Group\Group $group) {
432
-				\OC_Hook::emit('OC_Group', 'pre_deleteGroup', ['run' => true, 'gid' => $group->getGID()]);
433
-
434
-				/** @var IEventDispatcher $dispatcher */
435
-				$dispatcher = $this->query(IEventDispatcher::class);
436
-				$dispatcher->dispatchTyped(new BeforeGroupDeletedEvent($group));
437
-			});
438
-			$groupManager->listen('\OC\Group', 'postDelete', function (\OC\Group\Group $group) {
439
-				\OC_Hook::emit('OC_User', 'post_deleteGroup', ['gid' => $group->getGID()]);
440
-
441
-				/** @var IEventDispatcher $dispatcher */
442
-				$dispatcher = $this->query(IEventDispatcher::class);
443
-				$dispatcher->dispatchTyped(new GroupDeletedEvent($group));
444
-			});
445
-			$groupManager->listen('\OC\Group', 'preAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
446
-				\OC_Hook::emit('OC_Group', 'pre_addToGroup', ['run' => true, 'uid' => $user->getUID(), 'gid' => $group->getGID()]);
447
-
448
-				/** @var IEventDispatcher $dispatcher */
449
-				$dispatcher = $this->query(IEventDispatcher::class);
450
-				$dispatcher->dispatchTyped(new BeforeUserAddedEvent($group, $user));
451
-			});
452
-			$groupManager->listen('\OC\Group', 'postAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
453
-				\OC_Hook::emit('OC_Group', 'post_addToGroup', ['uid' => $user->getUID(), 'gid' => $group->getGID()]);
454
-				//Minimal fix to keep it backward compatible TODO: clean up all the GroupManager hooks
455
-				\OC_Hook::emit('OC_User', 'post_addToGroup', ['uid' => $user->getUID(), 'gid' => $group->getGID()]);
456
-
457
-				/** @var IEventDispatcher $dispatcher */
458
-				$dispatcher = $this->query(IEventDispatcher::class);
459
-				$dispatcher->dispatchTyped(new UserAddedEvent($group, $user));
460
-			});
461
-			$groupManager->listen('\OC\Group', 'preRemoveUser', function (\OC\Group\Group $group, \OC\User\User $user) {
462
-				/** @var IEventDispatcher $dispatcher */
463
-				$dispatcher = $this->query(IEventDispatcher::class);
464
-				$dispatcher->dispatchTyped(new BeforeUserRemovedEvent($group, $user));
465
-			});
466
-			$groupManager->listen('\OC\Group', 'postRemoveUser', function (\OC\Group\Group $group, \OC\User\User $user) {
467
-				/** @var IEventDispatcher $dispatcher */
468
-				$dispatcher = $this->query(IEventDispatcher::class);
469
-				$dispatcher->dispatchTyped(new UserRemovedEvent($group, $user));
470
-			});
471
-			return $groupManager;
472
-		});
473
-		/** @deprecated 19.0.0 */
474
-		$this->registerDeprecatedAlias('GroupManager', \OCP\IGroupManager::class);
475
-
476
-		$this->registerService(Store::class, function (Server $c) {
477
-			$session = $c->getSession();
478
-			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
479
-				$tokenProvider = $c->query(IProvider::class);
480
-			} else {
481
-				$tokenProvider = null;
482
-			}
483
-			$logger = $c->getLogger();
484
-			return new Store($session, $logger, $tokenProvider);
485
-		});
486
-		$this->registerAlias(IStore::class, Store::class);
487
-		$this->registerAlias(IProvider::class, Authentication\Token\Manager::class);
488
-
489
-		$this->registerService(\OC\User\Session::class, function (Server $c) {
490
-			$manager = $c->getUserManager();
491
-			$session = new \OC\Session\Memory('');
492
-			$timeFactory = new TimeFactory();
493
-			// Token providers might require a working database. This code
494
-			// might however be called when ownCloud is not yet setup.
495
-			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
496
-				$defaultTokenProvider = $c->query(IProvider::class);
497
-			} else {
498
-				$defaultTokenProvider = null;
499
-			}
500
-
501
-			$legacyDispatcher = $c->getEventDispatcher();
502
-
503
-			$userSession = new \OC\User\Session(
504
-				$manager,
505
-				$session,
506
-				$timeFactory,
507
-				$defaultTokenProvider,
508
-				$c->getConfig(),
509
-				$c->getSecureRandom(),
510
-				$c->getLockdownManager(),
511
-				$c->getLogger(),
512
-				$c->query(IEventDispatcher::class)
513
-			);
514
-			$userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
515
-				\OC_Hook::emit('OC_User', 'pre_createUser', ['run' => true, 'uid' => $uid, 'password' => $password]);
516
-
517
-				/** @var IEventDispatcher $dispatcher */
518
-				$dispatcher = $this->query(IEventDispatcher::class);
519
-				$dispatcher->dispatchTyped(new BeforeUserCreatedEvent($uid, $password));
520
-			});
521
-			$userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
522
-				/** @var \OC\User\User $user */
523
-				\OC_Hook::emit('OC_User', 'post_createUser', ['uid' => $user->getUID(), 'password' => $password]);
524
-
525
-				/** @var IEventDispatcher $dispatcher */
526
-				$dispatcher = $this->query(IEventDispatcher::class);
527
-				$dispatcher->dispatchTyped(new UserCreatedEvent($user, $password));
528
-			});
529
-			$userSession->listen('\OC\User', 'preDelete', function ($user) use ($legacyDispatcher) {
530
-				/** @var \OC\User\User $user */
531
-				\OC_Hook::emit('OC_User', 'pre_deleteUser', ['run' => true, 'uid' => $user->getUID()]);
532
-				$legacyDispatcher->dispatch('OCP\IUser::preDelete', new GenericEvent($user));
533
-
534
-				/** @var IEventDispatcher $dispatcher */
535
-				$dispatcher = $this->query(IEventDispatcher::class);
536
-				$dispatcher->dispatchTyped(new BeforeUserDeletedEvent($user));
537
-			});
538
-			$userSession->listen('\OC\User', 'postDelete', function ($user) {
539
-				/** @var \OC\User\User $user */
540
-				\OC_Hook::emit('OC_User', 'post_deleteUser', ['uid' => $user->getUID()]);
541
-
542
-				/** @var IEventDispatcher $dispatcher */
543
-				$dispatcher = $this->query(IEventDispatcher::class);
544
-				$dispatcher->dispatchTyped(new UserDeletedEvent($user));
545
-			});
546
-			$userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
547
-				/** @var \OC\User\User $user */
548
-				\OC_Hook::emit('OC_User', 'pre_setPassword', ['run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword]);
549
-
550
-				/** @var IEventDispatcher $dispatcher */
551
-				$dispatcher = $this->query(IEventDispatcher::class);
552
-				$dispatcher->dispatchTyped(new BeforePasswordUpdatedEvent($user, $password, $recoveryPassword));
553
-			});
554
-			$userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
555
-				/** @var \OC\User\User $user */
556
-				\OC_Hook::emit('OC_User', 'post_setPassword', ['run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword]);
557
-
558
-				/** @var IEventDispatcher $dispatcher */
559
-				$dispatcher = $this->query(IEventDispatcher::class);
560
-				$dispatcher->dispatchTyped(new PasswordUpdatedEvent($user, $password, $recoveryPassword));
561
-			});
562
-			$userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
563
-				\OC_Hook::emit('OC_User', 'pre_login', ['run' => true, 'uid' => $uid, 'password' => $password]);
564
-
565
-				/** @var IEventDispatcher $dispatcher */
566
-				$dispatcher = $this->query(IEventDispatcher::class);
567
-				$dispatcher->dispatchTyped(new BeforeUserLoggedInEvent($uid, $password));
568
-			});
569
-			$userSession->listen('\OC\User', 'postLogin', function ($user, $password, $isTokenLogin) {
570
-				/** @var \OC\User\User $user */
571
-				\OC_Hook::emit('OC_User', 'post_login', ['run' => true, 'uid' => $user->getUID(), 'password' => $password, 'isTokenLogin' => $isTokenLogin]);
572
-
573
-				/** @var IEventDispatcher $dispatcher */
574
-				$dispatcher = $this->query(IEventDispatcher::class);
575
-				$dispatcher->dispatchTyped(new UserLoggedInEvent($user, $password, $isTokenLogin));
576
-			});
577
-			$userSession->listen('\OC\User', 'preRememberedLogin', function ($uid) {
578
-				/** @var IEventDispatcher $dispatcher */
579
-				$dispatcher = $this->query(IEventDispatcher::class);
580
-				$dispatcher->dispatchTyped(new BeforeUserLoggedInWithCookieEvent($uid));
581
-			});
582
-			$userSession->listen('\OC\User', 'postRememberedLogin', function ($user, $password) {
583
-				/** @var \OC\User\User $user */
584
-				\OC_Hook::emit('OC_User', 'post_login', ['run' => true, 'uid' => $user->getUID(), 'password' => $password]);
585
-
586
-				/** @var IEventDispatcher $dispatcher */
587
-				$dispatcher = $this->query(IEventDispatcher::class);
588
-				$dispatcher->dispatchTyped(new UserLoggedInWithCookieEvent($user, $password));
589
-			});
590
-			$userSession->listen('\OC\User', 'logout', function ($user) {
591
-				\OC_Hook::emit('OC_User', 'logout', []);
592
-
593
-				/** @var IEventDispatcher $dispatcher */
594
-				$dispatcher = $this->query(IEventDispatcher::class);
595
-				$dispatcher->dispatchTyped(new BeforeUserLoggedOutEvent($user));
596
-			});
597
-			$userSession->listen('\OC\User', 'postLogout', function ($user) {
598
-				/** @var IEventDispatcher $dispatcher */
599
-				$dispatcher = $this->query(IEventDispatcher::class);
600
-				$dispatcher->dispatchTyped(new UserLoggedOutEvent($user));
601
-			});
602
-			$userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value, $oldValue) {
603
-				/** @var \OC\User\User $user */
604
-				\OC_Hook::emit('OC_User', 'changeUser', ['run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value, 'old_value' => $oldValue]);
605
-
606
-				/** @var IEventDispatcher $dispatcher */
607
-				$dispatcher = $this->query(IEventDispatcher::class);
608
-				$dispatcher->dispatchTyped(new UserChangedEvent($user, $feature, $value, $oldValue));
609
-			});
610
-			return $userSession;
611
-		});
612
-		$this->registerAlias(\OCP\IUserSession::class, \OC\User\Session::class);
613
-		/** @deprecated 19.0.0 */
614
-		$this->registerDeprecatedAlias('UserSession', \OC\User\Session::class);
615
-
616
-		$this->registerAlias(\OCP\Authentication\TwoFactorAuth\IRegistry::class, \OC\Authentication\TwoFactorAuth\Registry::class);
617
-
618
-		$this->registerAlias(INavigationManager::class, \OC\NavigationManager::class);
619
-		/** @deprecated 19.0.0 */
620
-		$this->registerDeprecatedAlias('NavigationManager', INavigationManager::class);
621
-
622
-		/** @deprecated 19.0.0 */
623
-		$this->registerDeprecatedAlias('AllConfig', \OC\AllConfig::class);
624
-		$this->registerAlias(\OCP\IConfig::class, \OC\AllConfig::class);
625
-
626
-		$this->registerService(\OC\SystemConfig::class, function ($c) use ($config) {
627
-			return new \OC\SystemConfig($config);
628
-		});
629
-		/** @deprecated 19.0.0 */
630
-		$this->registerDeprecatedAlias('SystemConfig', \OC\SystemConfig::class);
631
-
632
-		/** @deprecated 19.0.0 */
633
-		$this->registerDeprecatedAlias('AppConfig', \OC\AppConfig::class);
634
-		$this->registerAlias(IAppConfig::class, \OC\AppConfig::class);
635
-
636
-		$this->registerService(IFactory::class, function (Server $c) {
637
-			return new \OC\L10N\Factory(
638
-				$c->getConfig(),
639
-				$c->getRequest(),
640
-				$c->getUserSession(),
641
-				\OC::$SERVERROOT
642
-			);
643
-		});
644
-		/** @deprecated 19.0.0 */
645
-		$this->registerDeprecatedAlias('L10NFactory', IFactory::class);
646
-
647
-		$this->registerAlias(IURLGenerator::class, URLGenerator::class);
648
-		/** @deprecated 19.0.0 */
649
-		$this->registerDeprecatedAlias('URLGenerator', IURLGenerator::class);
650
-
651
-		/** @deprecated 19.0.0 */
652
-		$this->registerDeprecatedAlias('AppFetcher', AppFetcher::class);
653
-		/** @deprecated 19.0.0 */
654
-		$this->registerDeprecatedAlias('CategoryFetcher', CategoryFetcher::class);
655
-
656
-		$this->registerService(ICache::class, function ($c) {
657
-			return new Cache\File();
658
-		});
659
-		/** @deprecated 19.0.0 */
660
-		$this->registerDeprecatedAlias('UserCache', ICache::class);
661
-
662
-		$this->registerService(Factory::class, function (Server $c) {
663
-			$arrayCacheFactory = new \OC\Memcache\Factory('', $c->getLogger(),
664
-				ArrayCache::class,
665
-				ArrayCache::class,
666
-				ArrayCache::class
667
-			);
668
-			$config = $c->getConfig();
669
-
670
-			if ($config->getSystemValue('installed', false) && !(defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
671
-				$v = \OC_App::getAppVersions();
672
-				$v['core'] = implode(',', \OC_Util::getVersion());
673
-				$version = implode(',', $v);
674
-				$instanceId = \OC_Util::getInstanceId();
675
-				$path = \OC::$SERVERROOT;
676
-				$prefix = md5($instanceId . '-' . $version . '-' . $path);
677
-				return new \OC\Memcache\Factory($prefix, $c->getLogger(),
678
-					$config->getSystemValue('memcache.local', null),
679
-					$config->getSystemValue('memcache.distributed', null),
680
-					$config->getSystemValue('memcache.locking', null)
681
-				);
682
-			}
683
-			return $arrayCacheFactory;
684
-		});
685
-		/** @deprecated 19.0.0 */
686
-		$this->registerDeprecatedAlias('MemCacheFactory', Factory::class);
687
-		$this->registerAlias(ICacheFactory::class, Factory::class);
688
-
689
-		$this->registerService('RedisFactory', function (Server $c) {
690
-			$systemConfig = $c->getSystemConfig();
691
-			return new RedisFactory($systemConfig);
692
-		});
693
-
694
-		$this->registerService(\OCP\Activity\IManager::class, function (Server $c) {
695
-			$l10n = $this->get(IFactory::class)->get('activity');
696
-			return new \OC\Activity\Manager(
697
-				$c->getRequest(),
698
-				$c->getUserSession(),
699
-				$c->getConfig(),
700
-				$c->query(IValidator::class),
701
-				$l10n
702
-			);
703
-		});
704
-		/** @deprecated 19.0.0 */
705
-		$this->registerDeprecatedAlias('ActivityManager', \OCP\Activity\IManager::class);
706
-
707
-		$this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
708
-			return new \OC\Activity\EventMerger(
709
-				$c->getL10N('lib')
710
-			);
711
-		});
712
-		$this->registerAlias(IValidator::class, Validator::class);
713
-
714
-		$this->registerService(AvatarManager::class, function (Server $c) {
715
-			return new AvatarManager(
716
-				$c->query(\OC\User\Manager::class),
717
-				$c->getAppDataDir('avatar'),
718
-				$c->getL10N('lib'),
719
-				$c->getLogger(),
720
-				$c->getConfig()
721
-			);
722
-		});
723
-		$this->registerAlias(IAvatarManager::class, AvatarManager::class);
724
-		/** @deprecated 19.0.0 */
725
-		$this->registerDeprecatedAlias('AvatarManager', AvatarManager::class);
726
-
727
-		$this->registerAlias(\OCP\Support\CrashReport\IRegistry::class, \OC\Support\CrashReport\Registry::class);
728
-		$this->registerAlias(\OCP\Support\Subscription\IRegistry::class, \OC\Support\Subscription\Registry::class);
729
-
730
-		$this->registerService(\OC\Log::class, function (Server $c) {
731
-			$logType = $c->query(AllConfig::class)->getSystemValue('log_type', 'file');
732
-			$factory = new LogFactory($c, $this->getSystemConfig());
733
-			$logger = $factory->get($logType);
734
-			$registry = $c->query(\OCP\Support\CrashReport\IRegistry::class);
735
-
736
-			return new Log($logger, $this->getSystemConfig(), null, $registry);
737
-		});
738
-		$this->registerAlias(ILogger::class, \OC\Log::class);
739
-		/** @deprecated 19.0.0 */
740
-		$this->registerDeprecatedAlias('Logger', \OC\Log::class);
741
-		// PSR-3 logger
742
-		$this->registerAlias(LoggerInterface::class, PsrLoggerAdapter::class);
743
-
744
-		$this->registerService(ILogFactory::class, function (Server $c) {
745
-			return new LogFactory($c, $this->getSystemConfig());
746
-		});
747
-
748
-		$this->registerAlias(IJobList::class, \OC\BackgroundJob\JobList::class);
749
-		/** @deprecated 19.0.0 */
750
-		$this->registerDeprecatedAlias('JobList', IJobList::class);
751
-
752
-		$this->registerService(IRouter::class, function (Server $c) {
753
-			$cacheFactory = $c->getMemCacheFactory();
754
-			$logger = $c->getLogger();
755
-			if ($cacheFactory->isLocalCacheAvailable()) {
756
-				$router = new \OC\Route\CachingRouter($cacheFactory->createLocal('route'), $logger);
757
-			} else {
758
-				$router = new \OC\Route\Router($logger);
759
-			}
760
-			return $router;
761
-		});
762
-		/** @deprecated 19.0.0 */
763
-		$this->registerDeprecatedAlias('Router', IRouter::class);
764
-
765
-		$this->registerAlias(ISearch::class, Search::class);
766
-		/** @deprecated 19.0.0 */
767
-		$this->registerDeprecatedAlias('Search', ISearch::class);
768
-
769
-		$this->registerService(\OC\Security\RateLimiting\Backend\IBackend::class, function ($c) {
770
-			return new \OC\Security\RateLimiting\Backend\MemoryCache(
771
-				$this->getMemCacheFactory(),
772
-				new \OC\AppFramework\Utility\TimeFactory()
773
-			);
774
-		});
775
-
776
-		$this->registerAlias(\OCP\Security\ISecureRandom::class, SecureRandom::class);
777
-		/** @deprecated 19.0.0 */
778
-		$this->registerDeprecatedAlias('SecureRandom', \OCP\Security\ISecureRandom::class);
779
-
780
-		$this->registerAlias(ICrypto::class, Crypto::class);
781
-		/** @deprecated 19.0.0 */
782
-		$this->registerDeprecatedAlias('Crypto', ICrypto::class);
783
-
784
-		$this->registerAlias(IHasher::class, Hasher::class);
785
-		/** @deprecated 19.0.0 */
786
-		$this->registerDeprecatedAlias('Hasher', IHasher::class);
787
-
788
-		$this->registerAlias(ICredentialsManager::class, CredentialsManager::class);
789
-		/** @deprecated 19.0.0 */
790
-		$this->registerDeprecatedAlias('CredentialsManager', ICredentialsManager::class);
791
-
792
-		$this->registerService(IDBConnection::class, function (Server $c) {
793
-			$systemConfig = $c->getSystemConfig();
794
-			$factory = new \OC\DB\ConnectionFactory($systemConfig);
795
-			$type = $systemConfig->getValue('dbtype', 'sqlite');
796
-			if (!$factory->isValidType($type)) {
797
-				throw new \OC\DatabaseException('Invalid database type');
798
-			}
799
-			$connectionParams = $factory->createConnectionParams();
800
-			$connection = $factory->getConnection($type, $connectionParams);
801
-			$connection->getConfiguration()->setSQLLogger($c->getQueryLogger());
802
-			return $connection;
803
-		});
804
-		/** @deprecated 19.0.0 */
805
-		$this->registerDeprecatedAlias('DatabaseConnection', IDBConnection::class);
806
-
807
-
808
-		$this->registerService(IClientService::class, function (Server $c) {
809
-			$user = \OC_User::getUser();
810
-			$uid = $user ? $user : null;
811
-			return new ClientService(
812
-				$c->getConfig(),
813
-				$c->getLogger(),
814
-				new \OC\Security\CertificateManager(
815
-					$uid,
816
-					new View(),
817
-					$c->getConfig(),
818
-					$c->getLogger(),
819
-					$c->getSecureRandom()
820
-				)
821
-			);
822
-		});
823
-		/** @deprecated 19.0.0 */
824
-		$this->registerDeprecatedAlias('HttpClientService', IClientService::class);
825
-		$this->registerService(IEventLogger::class, function (Server $c) {
826
-			$eventLogger = new EventLogger();
827
-			if ($c->getSystemConfig()->getValue('debug', false)) {
828
-				// In debug mode, module is being activated by default
829
-				$eventLogger->activate();
830
-			}
831
-			return $eventLogger;
832
-		});
833
-		/** @deprecated 19.0.0 */
834
-		$this->registerDeprecatedAlias('EventLogger', IEventLogger::class);
835
-
836
-		$this->registerService(IQueryLogger::class, function (Server $c) {
837
-			$queryLogger = new QueryLogger();
838
-			if ($c->getSystemConfig()->getValue('debug', false)) {
839
-				// In debug mode, module is being activated by default
840
-				$queryLogger->activate();
841
-			}
842
-			return $queryLogger;
843
-		});
844
-		/** @deprecated 19.0.0 */
845
-		$this->registerDeprecatedAlias('QueryLogger', IQueryLogger::class);
846
-
847
-		/** @deprecated 19.0.0 */
848
-		$this->registerDeprecatedAlias('TempManager', TempManager::class);
849
-		$this->registerAlias(ITempManager::class, TempManager::class);
850
-
851
-		$this->registerService(AppManager::class, function (Server $c) {
852
-			return new \OC\App\AppManager(
853
-				$c->getUserSession(),
854
-				$c->getConfig(),
855
-				$c->query(\OC\AppConfig::class),
856
-				$c->getGroupManager(),
857
-				$c->getMemCacheFactory(),
858
-				$c->getEventDispatcher(),
859
-				$c->getLogger()
860
-			);
861
-		});
862
-		/** @deprecated 19.0.0 */
863
-		$this->registerDeprecatedAlias('AppManager', AppManager::class);
864
-		$this->registerAlias(IAppManager::class, AppManager::class);
865
-
866
-		$this->registerAlias(IDateTimeZone::class, DateTimeZone::class);
867
-		/** @deprecated 19.0.0 */
868
-		$this->registerDeprecatedAlias('DateTimeZone', IDateTimeZone::class);
869
-
870
-		$this->registerService(IDateTimeFormatter::class, function (Server $c) {
871
-			$language = $c->getConfig()->getUserValue($c->getSession()->get('user_id'), 'core', 'lang', null);
872
-
873
-			return new DateTimeFormatter(
874
-				$c->getDateTimeZone()->getTimeZone(),
875
-				$c->getL10N('lib', $language)
876
-			);
877
-		});
878
-		/** @deprecated 19.0.0 */
879
-		$this->registerDeprecatedAlias('DateTimeFormatter', IDateTimeFormatter::class);
880
-
881
-		$this->registerService(IUserMountCache::class, function (Server $c) {
882
-			$mountCache = new UserMountCache($c->getDatabaseConnection(), $c->getUserManager(), $c->getLogger());
883
-			$listener = new UserMountCacheListener($mountCache);
884
-			$listener->listen($c->getUserManager());
885
-			return $mountCache;
886
-		});
887
-		/** @deprecated 19.0.0 */
888
-		$this->registerDeprecatedAlias('UserMountCache', IUserMountCache::class);
889
-
890
-		$this->registerService(IMountProviderCollection::class, function (Server $c) {
891
-			$loader = \OC\Files\Filesystem::getLoader();
892
-			$mountCache = $c->query(IUserMountCache::class);
893
-			$manager = new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
894
-
895
-			// builtin providers
896
-
897
-			$config = $c->getConfig();
898
-			$logger = $c->getLogger();
899
-			$manager->registerProvider(new CacheMountProvider($config));
900
-			$manager->registerHomeProvider(new LocalHomeMountProvider());
901
-			$manager->registerHomeProvider(new ObjectHomeMountProvider($config));
902
-			$manager->registerRootProvider(new ObjectStorePreviewCacheMountProvider($logger, $config));
903
-
904
-			return $manager;
905
-		});
906
-		/** @deprecated 19.0.0 */
907
-		$this->registerDeprecatedAlias('MountConfigManager', IMountProviderCollection::class);
908
-
909
-		/** @deprecated 20.0.0 */
910
-		$this->registerDeprecatedAlias('IniWrapper', IniGetWrapper::class);
911
-		$this->registerService('AsyncCommandBus', function (Server $c) {
912
-			$busClass = $c->getConfig()->getSystemValue('commandbus');
913
-			if ($busClass) {
914
-				[$app, $class] = explode('::', $busClass, 2);
915
-				if ($c->getAppManager()->isInstalled($app)) {
916
-					\OC_App::loadApp($app);
917
-					return $c->query($class);
918
-				} else {
919
-					throw new ServiceUnavailableException("The app providing the command bus ($app) is not enabled");
920
-				}
921
-			} else {
922
-				$jobList = $c->getJobList();
923
-				return new CronBus($jobList);
924
-			}
925
-		});
926
-		$this->registerAlias(IBus::class, 'AsyncCommandBus');
927
-		/** @deprecated 20.0.0 */
928
-		$this->registerDeprecatedAlias('TrustedDomainHelper', TrustedDomainHelper::class);
929
-		/** @deprecated 19.0.0 */
930
-		$this->registerDeprecatedAlias('Throttler', Throttler::class);
931
-		$this->registerService('IntegrityCodeChecker', function (Server $c) {
932
-			// IConfig and IAppManager requires a working database. This code
933
-			// might however be called when ownCloud is not yet setup.
934
-			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
935
-				$config = $c->getConfig();
936
-				$appManager = $c->getAppManager();
937
-			} else {
938
-				$config = null;
939
-				$appManager = null;
940
-			}
941
-
942
-			return new Checker(
943
-				new EnvironmentHelper(),
944
-				new FileAccessHelper(),
945
-				new AppLocator(),
946
-				$config,
947
-				$c->getMemCacheFactory(),
948
-				$appManager,
949
-				$c->getTempManager(),
950
-				$c->getMimeTypeDetector()
951
-			);
952
-		});
953
-		$this->registerService(\OCP\IRequest::class, function ($c) {
954
-			if (isset($this['urlParams'])) {
955
-				$urlParams = $this['urlParams'];
956
-			} else {
957
-				$urlParams = [];
958
-			}
959
-
960
-			if (defined('PHPUNIT_RUN') && PHPUNIT_RUN
961
-				&& in_array('fakeinput', stream_get_wrappers())
962
-			) {
963
-				$stream = 'fakeinput://data';
964
-			} else {
965
-				$stream = 'php://input';
966
-			}
967
-
968
-			return new Request(
969
-				[
970
-					'get' => $_GET,
971
-					'post' => $_POST,
972
-					'files' => $_FILES,
973
-					'server' => $_SERVER,
974
-					'env' => $_ENV,
975
-					'cookies' => $_COOKIE,
976
-					'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
977
-						? $_SERVER['REQUEST_METHOD']
978
-						: '',
979
-					'urlParams' => $urlParams,
980
-				],
981
-				$this->getSecureRandom(),
982
-				$this->getConfig(),
983
-				$this->getCsrfTokenManager(),
984
-				$stream
985
-			);
986
-		});
987
-		/** @deprecated 19.0.0 */
988
-		$this->registerDeprecatedAlias('Request', \OCP\IRequest::class);
989
-
990
-		$this->registerService(IMailer::class, function (Server $c) {
991
-			return new Mailer(
992
-				$c->getConfig(),
993
-				$c->getLogger(),
994
-				$c->query(Defaults::class),
995
-				$c->getURLGenerator(),
996
-				$c->getL10N('lib'),
997
-				$c->query(IEventDispatcher::class),
998
-				$c->getL10NFactory()
999
-			);
1000
-		});
1001
-		/** @deprecated 19.0.0 */
1002
-		$this->registerDeprecatedAlias('Mailer', IMailer::class);
1003
-
1004
-		$this->registerService('LDAPProvider', function (Server $c) {
1005
-			$config = $c->getConfig();
1006
-			$factoryClass = $config->getSystemValue('ldapProviderFactory', null);
1007
-			if (is_null($factoryClass)) {
1008
-				throw new \Exception('ldapProviderFactory not set');
1009
-			}
1010
-			/** @var \OCP\LDAP\ILDAPProviderFactory $factory */
1011
-			$factory = new $factoryClass($this);
1012
-			return $factory->getLDAPProvider();
1013
-		});
1014
-		$this->registerService(ILockingProvider::class, function (Server $c) {
1015
-			$ini = $c->get(IniGetWrapper::class);
1016
-			$config = $c->getConfig();
1017
-			$ttl = $config->getSystemValue('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
1018
-			if ($config->getSystemValue('filelocking.enabled', true) or (defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
1019
-				/** @var \OC\Memcache\Factory $memcacheFactory */
1020
-				$memcacheFactory = $c->getMemCacheFactory();
1021
-				$memcache = $memcacheFactory->createLocking('lock');
1022
-				if (!($memcache instanceof \OC\Memcache\NullCache)) {
1023
-					return new MemcacheLockingProvider($memcache, $ttl);
1024
-				}
1025
-				return new DBLockingProvider(
1026
-					$c->getDatabaseConnection(),
1027
-					$c->getLogger(),
1028
-					new TimeFactory(),
1029
-					$ttl,
1030
-					!\OC::$CLI
1031
-				);
1032
-			}
1033
-			return new NoopLockingProvider();
1034
-		});
1035
-		/** @deprecated 19.0.0 */
1036
-		$this->registerDeprecatedAlias('LockingProvider', ILockingProvider::class);
1037
-
1038
-		$this->registerAlias(IMountManager::class, \OC\Files\Mount\Manager::class);
1039
-		/** @deprecated 19.0.0 */
1040
-		$this->registerDeprecatedAlias('MountManager', IMountManager::class);
1041
-
1042
-		$this->registerService(IMimeTypeDetector::class, function (Server $c) {
1043
-			return new \OC\Files\Type\Detection(
1044
-				$c->getURLGenerator(),
1045
-				$c->getLogger(),
1046
-				\OC::$configDir,
1047
-				\OC::$SERVERROOT . '/resources/config/'
1048
-			);
1049
-		});
1050
-		/** @deprecated 19.0.0 */
1051
-		$this->registerDeprecatedAlias('MimeTypeDetector', IMimeTypeDetector::class);
1052
-
1053
-		$this->registerAlias(IMimeTypeLoader::class, Loader::class);
1054
-		/** @deprecated 19.0.0 */
1055
-		$this->registerDeprecatedAlias('MimeTypeLoader', IMimeTypeLoader::class);
1056
-		$this->registerService(BundleFetcher::class, function () {
1057
-			return new BundleFetcher($this->getL10N('lib'));
1058
-		});
1059
-		$this->registerAlias(\OCP\Notification\IManager::class, Manager::class);
1060
-		/** @deprecated 19.0.0 */
1061
-		$this->registerDeprecatedAlias('NotificationManager', \OCP\Notification\IManager::class);
1062
-
1063
-		$this->registerService(CapabilitiesManager::class, function (Server $c) {
1064
-			$manager = new CapabilitiesManager($c->getLogger());
1065
-			$manager->registerCapability(function () use ($c) {
1066
-				return new \OC\OCS\CoreCapabilities($c->getConfig());
1067
-			});
1068
-			$manager->registerCapability(function () use ($c) {
1069
-				return $c->query(\OC\Security\Bruteforce\Capabilities::class);
1070
-			});
1071
-			return $manager;
1072
-		});
1073
-		/** @deprecated 19.0.0 */
1074
-		$this->registerDeprecatedAlias('CapabilitiesManager', CapabilitiesManager::class);
1075
-
1076
-		$this->registerService(ICommentsManager::class, function (Server $c) {
1077
-			$config = $c->getConfig();
1078
-			$factoryClass = $config->getSystemValue('comments.managerFactory', CommentsManagerFactory::class);
1079
-			/** @var \OCP\Comments\ICommentsManagerFactory $factory */
1080
-			$factory = new $factoryClass($this);
1081
-			$manager = $factory->getManager();
1082
-
1083
-			$manager->registerDisplayNameResolver('user', function ($id) use ($c) {
1084
-				$manager = $c->getUserManager();
1085
-				$user = $manager->get($id);
1086
-				if (is_null($user)) {
1087
-					$l = $c->getL10N('core');
1088
-					$displayName = $l->t('Unknown user');
1089
-				} else {
1090
-					$displayName = $user->getDisplayName();
1091
-				}
1092
-				return $displayName;
1093
-			});
1094
-
1095
-			return $manager;
1096
-		});
1097
-		/** @deprecated 19.0.0 */
1098
-		$this->registerDeprecatedAlias('CommentsManager', ICommentsManager::class);
1099
-
1100
-		$this->registerAlias(\OC_Defaults::class, 'ThemingDefaults');
1101
-		$this->registerService('ThemingDefaults', function (Server $c) {
1102
-			/*
246
+    /** @var string */
247
+    private $webRoot;
248
+
249
+    /**
250
+     * @param string $webRoot
251
+     * @param \OC\Config $config
252
+     */
253
+    public function __construct($webRoot, \OC\Config $config) {
254
+        parent::__construct();
255
+        $this->webRoot = $webRoot;
256
+
257
+        // To find out if we are running from CLI or not
258
+        $this->registerParameter('isCLI', \OC::$CLI);
259
+        $this->registerParameter('serverRoot', \OC::$SERVERROOT);
260
+
261
+        $this->registerService(ContainerInterface::class, function (ContainerInterface $c) {
262
+            return $c;
263
+        });
264
+        $this->registerService(\OCP\IServerContainer::class, function (ContainerInterface $c) {
265
+            return $c;
266
+        });
267
+
268
+        $this->registerAlias(\OCP\Calendar\IManager::class, \OC\Calendar\Manager::class);
269
+        /** @deprecated 19.0.0 */
270
+        $this->registerDeprecatedAlias('CalendarManager', \OC\Calendar\Manager::class);
271
+
272
+        $this->registerAlias(\OCP\Calendar\Resource\IManager::class, \OC\Calendar\Resource\Manager::class);
273
+        /** @deprecated 19.0.0 */
274
+        $this->registerDeprecatedAlias('CalendarResourceBackendManager', \OC\Calendar\Resource\Manager::class);
275
+
276
+        $this->registerAlias(\OCP\Calendar\Room\IManager::class, \OC\Calendar\Room\Manager::class);
277
+        /** @deprecated 19.0.0 */
278
+        $this->registerDeprecatedAlias('CalendarRoomBackendManager', \OC\Calendar\Room\Manager::class);
279
+
280
+        $this->registerAlias(\OCP\Contacts\IManager::class, \OC\ContactsManager::class);
281
+        /** @deprecated 19.0.0 */
282
+        $this->registerDeprecatedAlias('ContactsManager', \OCP\Contacts\IManager::class);
283
+
284
+        $this->registerAlias(\OCP\DirectEditing\IManager::class, \OC\DirectEditing\Manager::class);
285
+
286
+        $this->registerAlias(IActionFactory::class, ActionFactory::class);
287
+
288
+
289
+        $this->registerService(IPreview::class, function (Server $c) {
290
+            return new PreviewManager(
291
+                $c->getConfig(),
292
+                $c->getRootFolder(),
293
+                new \OC\Preview\Storage\Root($c->getRootFolder(), $c->getSystemConfig()),
294
+                $c->getEventDispatcher(),
295
+                $c->getGeneratorHelper(),
296
+                $c->getSession()->get('user_id')
297
+            );
298
+        });
299
+        /** @deprecated 19.0.0 */
300
+        $this->registerDeprecatedAlias('PreviewManager', IPreview::class);
301
+
302
+        $this->registerService(\OC\Preview\Watcher::class, function (Server $c) {
303
+            return new \OC\Preview\Watcher(
304
+                new \OC\Preview\Storage\Root($c->getRootFolder(), $c->getSystemConfig())
305
+            );
306
+        });
307
+
308
+        $this->registerService(\OCP\Encryption\IManager::class, function (Server $c) {
309
+            $view = new View();
310
+            $util = new Encryption\Util(
311
+                $view,
312
+                $c->getUserManager(),
313
+                $c->getGroupManager(),
314
+                $c->getConfig()
315
+            );
316
+            return new Encryption\Manager(
317
+                $c->getConfig(),
318
+                $c->getLogger(),
319
+                $c->getL10N('core'),
320
+                new View(),
321
+                $util,
322
+                new ArrayCache()
323
+            );
324
+        });
325
+        /** @deprecated 19.0.0 */
326
+        $this->registerDeprecatedAlias('EncryptionManager', \OCP\Encryption\IManager::class);
327
+
328
+        $this->registerService('EncryptionFileHelper', function (Server $c) {
329
+            $util = new Encryption\Util(
330
+                new View(),
331
+                $c->getUserManager(),
332
+                $c->getGroupManager(),
333
+                $c->getConfig()
334
+            );
335
+            return new Encryption\File(
336
+                $util,
337
+                $c->getRootFolder(),
338
+                $c->getShareManager()
339
+            );
340
+        });
341
+
342
+        $this->registerService('EncryptionKeyStorage', function (Server $c) {
343
+            $view = new View();
344
+            $util = new Encryption\Util(
345
+                $view,
346
+                $c->getUserManager(),
347
+                $c->getGroupManager(),
348
+                $c->getConfig()
349
+            );
350
+
351
+            return new Encryption\Keys\Storage($view, $util, $c->getCrypto(), $c->getConfig());
352
+        });
353
+        /** @deprecated 20.0.0 */
354
+        $this->registerDeprecatedAlias('TagMapper', TagMapper::class);
355
+
356
+        $this->registerAlias(\OCP\ITagManager::class, TagManager::class);
357
+        /** @deprecated 19.0.0 */
358
+        $this->registerDeprecatedAlias('TagManager', \OCP\ITagManager::class);
359
+
360
+        $this->registerService('SystemTagManagerFactory', function (Server $c) {
361
+            $config = $c->getConfig();
362
+            $factoryClass = $config->getSystemValue('systemtags.managerFactory', SystemTagManagerFactory::class);
363
+            return new $factoryClass($this);
364
+        });
365
+        $this->registerService(ISystemTagManager::class, function (Server $c) {
366
+            return $c->query('SystemTagManagerFactory')->getManager();
367
+        });
368
+        /** @deprecated 19.0.0 */
369
+        $this->registerDeprecatedAlias('SystemTagManager', ISystemTagManager::class);
370
+
371
+        $this->registerService(ISystemTagObjectMapper::class, function (Server $c) {
372
+            return $c->query('SystemTagManagerFactory')->getObjectMapper();
373
+        });
374
+        $this->registerService('RootFolder', function (Server $c) {
375
+            $manager = \OC\Files\Filesystem::getMountManager(null);
376
+            $view = new View();
377
+            $root = new Root(
378
+                $manager,
379
+                $view,
380
+                null,
381
+                $c->getUserMountCache(),
382
+                $this->getLogger(),
383
+                $this->getUserManager()
384
+            );
385
+
386
+            $previewConnector = new \OC\Preview\WatcherConnector($root, $c->getSystemConfig());
387
+            $previewConnector->connectWatcher();
388
+
389
+            return $root;
390
+        });
391
+        $this->registerService(HookConnector::class, function (Server $c) {
392
+            return new HookConnector(
393
+                $c->query(IRootFolder::class),
394
+                new View(),
395
+                $c->query(\OC\EventDispatcher\SymfonyAdapter::class),
396
+                $c->query(IEventDispatcher::class)
397
+            );
398
+        });
399
+
400
+        /** @deprecated 19.0.0 */
401
+        $this->registerDeprecatedAlias('SystemTagObjectMapper', ISystemTagObjectMapper::class);
402
+
403
+        $this->registerService(IRootFolder::class, function (Server $c) {
404
+            return new LazyRoot(function () use ($c) {
405
+                return $c->query('RootFolder');
406
+            });
407
+        });
408
+        /** @deprecated 19.0.0 */
409
+        $this->registerDeprecatedAlias('LazyRootFolder', IRootFolder::class);
410
+
411
+        /** @deprecated 19.0.0 */
412
+        $this->registerDeprecatedAlias('UserManager', \OC\User\Manager::class);
413
+        $this->registerAlias(\OCP\IUserManager::class, \OC\User\Manager::class);
414
+
415
+        $this->registerService(\OCP\IGroupManager::class, function (Server $c) {
416
+            $groupManager = new \OC\Group\Manager($this->getUserManager(), $c->getEventDispatcher(), $this->getLogger());
417
+            $groupManager->listen('\OC\Group', 'preCreate', function ($gid) {
418
+                \OC_Hook::emit('OC_Group', 'pre_createGroup', ['run' => true, 'gid' => $gid]);
419
+
420
+                /** @var IEventDispatcher $dispatcher */
421
+                $dispatcher = $this->query(IEventDispatcher::class);
422
+                $dispatcher->dispatchTyped(new BeforeGroupCreatedEvent($gid));
423
+            });
424
+            $groupManager->listen('\OC\Group', 'postCreate', function (\OC\Group\Group $group) {
425
+                \OC_Hook::emit('OC_User', 'post_createGroup', ['gid' => $group->getGID()]);
426
+
427
+                /** @var IEventDispatcher $dispatcher */
428
+                $dispatcher = $this->query(IEventDispatcher::class);
429
+                $dispatcher->dispatchTyped(new GroupCreatedEvent($group));
430
+            });
431
+            $groupManager->listen('\OC\Group', 'preDelete', function (\OC\Group\Group $group) {
432
+                \OC_Hook::emit('OC_Group', 'pre_deleteGroup', ['run' => true, 'gid' => $group->getGID()]);
433
+
434
+                /** @var IEventDispatcher $dispatcher */
435
+                $dispatcher = $this->query(IEventDispatcher::class);
436
+                $dispatcher->dispatchTyped(new BeforeGroupDeletedEvent($group));
437
+            });
438
+            $groupManager->listen('\OC\Group', 'postDelete', function (\OC\Group\Group $group) {
439
+                \OC_Hook::emit('OC_User', 'post_deleteGroup', ['gid' => $group->getGID()]);
440
+
441
+                /** @var IEventDispatcher $dispatcher */
442
+                $dispatcher = $this->query(IEventDispatcher::class);
443
+                $dispatcher->dispatchTyped(new GroupDeletedEvent($group));
444
+            });
445
+            $groupManager->listen('\OC\Group', 'preAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
446
+                \OC_Hook::emit('OC_Group', 'pre_addToGroup', ['run' => true, 'uid' => $user->getUID(), 'gid' => $group->getGID()]);
447
+
448
+                /** @var IEventDispatcher $dispatcher */
449
+                $dispatcher = $this->query(IEventDispatcher::class);
450
+                $dispatcher->dispatchTyped(new BeforeUserAddedEvent($group, $user));
451
+            });
452
+            $groupManager->listen('\OC\Group', 'postAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
453
+                \OC_Hook::emit('OC_Group', 'post_addToGroup', ['uid' => $user->getUID(), 'gid' => $group->getGID()]);
454
+                //Minimal fix to keep it backward compatible TODO: clean up all the GroupManager hooks
455
+                \OC_Hook::emit('OC_User', 'post_addToGroup', ['uid' => $user->getUID(), 'gid' => $group->getGID()]);
456
+
457
+                /** @var IEventDispatcher $dispatcher */
458
+                $dispatcher = $this->query(IEventDispatcher::class);
459
+                $dispatcher->dispatchTyped(new UserAddedEvent($group, $user));
460
+            });
461
+            $groupManager->listen('\OC\Group', 'preRemoveUser', function (\OC\Group\Group $group, \OC\User\User $user) {
462
+                /** @var IEventDispatcher $dispatcher */
463
+                $dispatcher = $this->query(IEventDispatcher::class);
464
+                $dispatcher->dispatchTyped(new BeforeUserRemovedEvent($group, $user));
465
+            });
466
+            $groupManager->listen('\OC\Group', 'postRemoveUser', function (\OC\Group\Group $group, \OC\User\User $user) {
467
+                /** @var IEventDispatcher $dispatcher */
468
+                $dispatcher = $this->query(IEventDispatcher::class);
469
+                $dispatcher->dispatchTyped(new UserRemovedEvent($group, $user));
470
+            });
471
+            return $groupManager;
472
+        });
473
+        /** @deprecated 19.0.0 */
474
+        $this->registerDeprecatedAlias('GroupManager', \OCP\IGroupManager::class);
475
+
476
+        $this->registerService(Store::class, function (Server $c) {
477
+            $session = $c->getSession();
478
+            if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
479
+                $tokenProvider = $c->query(IProvider::class);
480
+            } else {
481
+                $tokenProvider = null;
482
+            }
483
+            $logger = $c->getLogger();
484
+            return new Store($session, $logger, $tokenProvider);
485
+        });
486
+        $this->registerAlias(IStore::class, Store::class);
487
+        $this->registerAlias(IProvider::class, Authentication\Token\Manager::class);
488
+
489
+        $this->registerService(\OC\User\Session::class, function (Server $c) {
490
+            $manager = $c->getUserManager();
491
+            $session = new \OC\Session\Memory('');
492
+            $timeFactory = new TimeFactory();
493
+            // Token providers might require a working database. This code
494
+            // might however be called when ownCloud is not yet setup.
495
+            if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
496
+                $defaultTokenProvider = $c->query(IProvider::class);
497
+            } else {
498
+                $defaultTokenProvider = null;
499
+            }
500
+
501
+            $legacyDispatcher = $c->getEventDispatcher();
502
+
503
+            $userSession = new \OC\User\Session(
504
+                $manager,
505
+                $session,
506
+                $timeFactory,
507
+                $defaultTokenProvider,
508
+                $c->getConfig(),
509
+                $c->getSecureRandom(),
510
+                $c->getLockdownManager(),
511
+                $c->getLogger(),
512
+                $c->query(IEventDispatcher::class)
513
+            );
514
+            $userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
515
+                \OC_Hook::emit('OC_User', 'pre_createUser', ['run' => true, 'uid' => $uid, 'password' => $password]);
516
+
517
+                /** @var IEventDispatcher $dispatcher */
518
+                $dispatcher = $this->query(IEventDispatcher::class);
519
+                $dispatcher->dispatchTyped(new BeforeUserCreatedEvent($uid, $password));
520
+            });
521
+            $userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
522
+                /** @var \OC\User\User $user */
523
+                \OC_Hook::emit('OC_User', 'post_createUser', ['uid' => $user->getUID(), 'password' => $password]);
524
+
525
+                /** @var IEventDispatcher $dispatcher */
526
+                $dispatcher = $this->query(IEventDispatcher::class);
527
+                $dispatcher->dispatchTyped(new UserCreatedEvent($user, $password));
528
+            });
529
+            $userSession->listen('\OC\User', 'preDelete', function ($user) use ($legacyDispatcher) {
530
+                /** @var \OC\User\User $user */
531
+                \OC_Hook::emit('OC_User', 'pre_deleteUser', ['run' => true, 'uid' => $user->getUID()]);
532
+                $legacyDispatcher->dispatch('OCP\IUser::preDelete', new GenericEvent($user));
533
+
534
+                /** @var IEventDispatcher $dispatcher */
535
+                $dispatcher = $this->query(IEventDispatcher::class);
536
+                $dispatcher->dispatchTyped(new BeforeUserDeletedEvent($user));
537
+            });
538
+            $userSession->listen('\OC\User', 'postDelete', function ($user) {
539
+                /** @var \OC\User\User $user */
540
+                \OC_Hook::emit('OC_User', 'post_deleteUser', ['uid' => $user->getUID()]);
541
+
542
+                /** @var IEventDispatcher $dispatcher */
543
+                $dispatcher = $this->query(IEventDispatcher::class);
544
+                $dispatcher->dispatchTyped(new UserDeletedEvent($user));
545
+            });
546
+            $userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
547
+                /** @var \OC\User\User $user */
548
+                \OC_Hook::emit('OC_User', 'pre_setPassword', ['run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword]);
549
+
550
+                /** @var IEventDispatcher $dispatcher */
551
+                $dispatcher = $this->query(IEventDispatcher::class);
552
+                $dispatcher->dispatchTyped(new BeforePasswordUpdatedEvent($user, $password, $recoveryPassword));
553
+            });
554
+            $userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
555
+                /** @var \OC\User\User $user */
556
+                \OC_Hook::emit('OC_User', 'post_setPassword', ['run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword]);
557
+
558
+                /** @var IEventDispatcher $dispatcher */
559
+                $dispatcher = $this->query(IEventDispatcher::class);
560
+                $dispatcher->dispatchTyped(new PasswordUpdatedEvent($user, $password, $recoveryPassword));
561
+            });
562
+            $userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
563
+                \OC_Hook::emit('OC_User', 'pre_login', ['run' => true, 'uid' => $uid, 'password' => $password]);
564
+
565
+                /** @var IEventDispatcher $dispatcher */
566
+                $dispatcher = $this->query(IEventDispatcher::class);
567
+                $dispatcher->dispatchTyped(new BeforeUserLoggedInEvent($uid, $password));
568
+            });
569
+            $userSession->listen('\OC\User', 'postLogin', function ($user, $password, $isTokenLogin) {
570
+                /** @var \OC\User\User $user */
571
+                \OC_Hook::emit('OC_User', 'post_login', ['run' => true, 'uid' => $user->getUID(), 'password' => $password, 'isTokenLogin' => $isTokenLogin]);
572
+
573
+                /** @var IEventDispatcher $dispatcher */
574
+                $dispatcher = $this->query(IEventDispatcher::class);
575
+                $dispatcher->dispatchTyped(new UserLoggedInEvent($user, $password, $isTokenLogin));
576
+            });
577
+            $userSession->listen('\OC\User', 'preRememberedLogin', function ($uid) {
578
+                /** @var IEventDispatcher $dispatcher */
579
+                $dispatcher = $this->query(IEventDispatcher::class);
580
+                $dispatcher->dispatchTyped(new BeforeUserLoggedInWithCookieEvent($uid));
581
+            });
582
+            $userSession->listen('\OC\User', 'postRememberedLogin', function ($user, $password) {
583
+                /** @var \OC\User\User $user */
584
+                \OC_Hook::emit('OC_User', 'post_login', ['run' => true, 'uid' => $user->getUID(), 'password' => $password]);
585
+
586
+                /** @var IEventDispatcher $dispatcher */
587
+                $dispatcher = $this->query(IEventDispatcher::class);
588
+                $dispatcher->dispatchTyped(new UserLoggedInWithCookieEvent($user, $password));
589
+            });
590
+            $userSession->listen('\OC\User', 'logout', function ($user) {
591
+                \OC_Hook::emit('OC_User', 'logout', []);
592
+
593
+                /** @var IEventDispatcher $dispatcher */
594
+                $dispatcher = $this->query(IEventDispatcher::class);
595
+                $dispatcher->dispatchTyped(new BeforeUserLoggedOutEvent($user));
596
+            });
597
+            $userSession->listen('\OC\User', 'postLogout', function ($user) {
598
+                /** @var IEventDispatcher $dispatcher */
599
+                $dispatcher = $this->query(IEventDispatcher::class);
600
+                $dispatcher->dispatchTyped(new UserLoggedOutEvent($user));
601
+            });
602
+            $userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value, $oldValue) {
603
+                /** @var \OC\User\User $user */
604
+                \OC_Hook::emit('OC_User', 'changeUser', ['run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value, 'old_value' => $oldValue]);
605
+
606
+                /** @var IEventDispatcher $dispatcher */
607
+                $dispatcher = $this->query(IEventDispatcher::class);
608
+                $dispatcher->dispatchTyped(new UserChangedEvent($user, $feature, $value, $oldValue));
609
+            });
610
+            return $userSession;
611
+        });
612
+        $this->registerAlias(\OCP\IUserSession::class, \OC\User\Session::class);
613
+        /** @deprecated 19.0.0 */
614
+        $this->registerDeprecatedAlias('UserSession', \OC\User\Session::class);
615
+
616
+        $this->registerAlias(\OCP\Authentication\TwoFactorAuth\IRegistry::class, \OC\Authentication\TwoFactorAuth\Registry::class);
617
+
618
+        $this->registerAlias(INavigationManager::class, \OC\NavigationManager::class);
619
+        /** @deprecated 19.0.0 */
620
+        $this->registerDeprecatedAlias('NavigationManager', INavigationManager::class);
621
+
622
+        /** @deprecated 19.0.0 */
623
+        $this->registerDeprecatedAlias('AllConfig', \OC\AllConfig::class);
624
+        $this->registerAlias(\OCP\IConfig::class, \OC\AllConfig::class);
625
+
626
+        $this->registerService(\OC\SystemConfig::class, function ($c) use ($config) {
627
+            return new \OC\SystemConfig($config);
628
+        });
629
+        /** @deprecated 19.0.0 */
630
+        $this->registerDeprecatedAlias('SystemConfig', \OC\SystemConfig::class);
631
+
632
+        /** @deprecated 19.0.0 */
633
+        $this->registerDeprecatedAlias('AppConfig', \OC\AppConfig::class);
634
+        $this->registerAlias(IAppConfig::class, \OC\AppConfig::class);
635
+
636
+        $this->registerService(IFactory::class, function (Server $c) {
637
+            return new \OC\L10N\Factory(
638
+                $c->getConfig(),
639
+                $c->getRequest(),
640
+                $c->getUserSession(),
641
+                \OC::$SERVERROOT
642
+            );
643
+        });
644
+        /** @deprecated 19.0.0 */
645
+        $this->registerDeprecatedAlias('L10NFactory', IFactory::class);
646
+
647
+        $this->registerAlias(IURLGenerator::class, URLGenerator::class);
648
+        /** @deprecated 19.0.0 */
649
+        $this->registerDeprecatedAlias('URLGenerator', IURLGenerator::class);
650
+
651
+        /** @deprecated 19.0.0 */
652
+        $this->registerDeprecatedAlias('AppFetcher', AppFetcher::class);
653
+        /** @deprecated 19.0.0 */
654
+        $this->registerDeprecatedAlias('CategoryFetcher', CategoryFetcher::class);
655
+
656
+        $this->registerService(ICache::class, function ($c) {
657
+            return new Cache\File();
658
+        });
659
+        /** @deprecated 19.0.0 */
660
+        $this->registerDeprecatedAlias('UserCache', ICache::class);
661
+
662
+        $this->registerService(Factory::class, function (Server $c) {
663
+            $arrayCacheFactory = new \OC\Memcache\Factory('', $c->getLogger(),
664
+                ArrayCache::class,
665
+                ArrayCache::class,
666
+                ArrayCache::class
667
+            );
668
+            $config = $c->getConfig();
669
+
670
+            if ($config->getSystemValue('installed', false) && !(defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
671
+                $v = \OC_App::getAppVersions();
672
+                $v['core'] = implode(',', \OC_Util::getVersion());
673
+                $version = implode(',', $v);
674
+                $instanceId = \OC_Util::getInstanceId();
675
+                $path = \OC::$SERVERROOT;
676
+                $prefix = md5($instanceId . '-' . $version . '-' . $path);
677
+                return new \OC\Memcache\Factory($prefix, $c->getLogger(),
678
+                    $config->getSystemValue('memcache.local', null),
679
+                    $config->getSystemValue('memcache.distributed', null),
680
+                    $config->getSystemValue('memcache.locking', null)
681
+                );
682
+            }
683
+            return $arrayCacheFactory;
684
+        });
685
+        /** @deprecated 19.0.0 */
686
+        $this->registerDeprecatedAlias('MemCacheFactory', Factory::class);
687
+        $this->registerAlias(ICacheFactory::class, Factory::class);
688
+
689
+        $this->registerService('RedisFactory', function (Server $c) {
690
+            $systemConfig = $c->getSystemConfig();
691
+            return new RedisFactory($systemConfig);
692
+        });
693
+
694
+        $this->registerService(\OCP\Activity\IManager::class, function (Server $c) {
695
+            $l10n = $this->get(IFactory::class)->get('activity');
696
+            return new \OC\Activity\Manager(
697
+                $c->getRequest(),
698
+                $c->getUserSession(),
699
+                $c->getConfig(),
700
+                $c->query(IValidator::class),
701
+                $l10n
702
+            );
703
+        });
704
+        /** @deprecated 19.0.0 */
705
+        $this->registerDeprecatedAlias('ActivityManager', \OCP\Activity\IManager::class);
706
+
707
+        $this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
708
+            return new \OC\Activity\EventMerger(
709
+                $c->getL10N('lib')
710
+            );
711
+        });
712
+        $this->registerAlias(IValidator::class, Validator::class);
713
+
714
+        $this->registerService(AvatarManager::class, function (Server $c) {
715
+            return new AvatarManager(
716
+                $c->query(\OC\User\Manager::class),
717
+                $c->getAppDataDir('avatar'),
718
+                $c->getL10N('lib'),
719
+                $c->getLogger(),
720
+                $c->getConfig()
721
+            );
722
+        });
723
+        $this->registerAlias(IAvatarManager::class, AvatarManager::class);
724
+        /** @deprecated 19.0.0 */
725
+        $this->registerDeprecatedAlias('AvatarManager', AvatarManager::class);
726
+
727
+        $this->registerAlias(\OCP\Support\CrashReport\IRegistry::class, \OC\Support\CrashReport\Registry::class);
728
+        $this->registerAlias(\OCP\Support\Subscription\IRegistry::class, \OC\Support\Subscription\Registry::class);
729
+
730
+        $this->registerService(\OC\Log::class, function (Server $c) {
731
+            $logType = $c->query(AllConfig::class)->getSystemValue('log_type', 'file');
732
+            $factory = new LogFactory($c, $this->getSystemConfig());
733
+            $logger = $factory->get($logType);
734
+            $registry = $c->query(\OCP\Support\CrashReport\IRegistry::class);
735
+
736
+            return new Log($logger, $this->getSystemConfig(), null, $registry);
737
+        });
738
+        $this->registerAlias(ILogger::class, \OC\Log::class);
739
+        /** @deprecated 19.0.0 */
740
+        $this->registerDeprecatedAlias('Logger', \OC\Log::class);
741
+        // PSR-3 logger
742
+        $this->registerAlias(LoggerInterface::class, PsrLoggerAdapter::class);
743
+
744
+        $this->registerService(ILogFactory::class, function (Server $c) {
745
+            return new LogFactory($c, $this->getSystemConfig());
746
+        });
747
+
748
+        $this->registerAlias(IJobList::class, \OC\BackgroundJob\JobList::class);
749
+        /** @deprecated 19.0.0 */
750
+        $this->registerDeprecatedAlias('JobList', IJobList::class);
751
+
752
+        $this->registerService(IRouter::class, function (Server $c) {
753
+            $cacheFactory = $c->getMemCacheFactory();
754
+            $logger = $c->getLogger();
755
+            if ($cacheFactory->isLocalCacheAvailable()) {
756
+                $router = new \OC\Route\CachingRouter($cacheFactory->createLocal('route'), $logger);
757
+            } else {
758
+                $router = new \OC\Route\Router($logger);
759
+            }
760
+            return $router;
761
+        });
762
+        /** @deprecated 19.0.0 */
763
+        $this->registerDeprecatedAlias('Router', IRouter::class);
764
+
765
+        $this->registerAlias(ISearch::class, Search::class);
766
+        /** @deprecated 19.0.0 */
767
+        $this->registerDeprecatedAlias('Search', ISearch::class);
768
+
769
+        $this->registerService(\OC\Security\RateLimiting\Backend\IBackend::class, function ($c) {
770
+            return new \OC\Security\RateLimiting\Backend\MemoryCache(
771
+                $this->getMemCacheFactory(),
772
+                new \OC\AppFramework\Utility\TimeFactory()
773
+            );
774
+        });
775
+
776
+        $this->registerAlias(\OCP\Security\ISecureRandom::class, SecureRandom::class);
777
+        /** @deprecated 19.0.0 */
778
+        $this->registerDeprecatedAlias('SecureRandom', \OCP\Security\ISecureRandom::class);
779
+
780
+        $this->registerAlias(ICrypto::class, Crypto::class);
781
+        /** @deprecated 19.0.0 */
782
+        $this->registerDeprecatedAlias('Crypto', ICrypto::class);
783
+
784
+        $this->registerAlias(IHasher::class, Hasher::class);
785
+        /** @deprecated 19.0.0 */
786
+        $this->registerDeprecatedAlias('Hasher', IHasher::class);
787
+
788
+        $this->registerAlias(ICredentialsManager::class, CredentialsManager::class);
789
+        /** @deprecated 19.0.0 */
790
+        $this->registerDeprecatedAlias('CredentialsManager', ICredentialsManager::class);
791
+
792
+        $this->registerService(IDBConnection::class, function (Server $c) {
793
+            $systemConfig = $c->getSystemConfig();
794
+            $factory = new \OC\DB\ConnectionFactory($systemConfig);
795
+            $type = $systemConfig->getValue('dbtype', 'sqlite');
796
+            if (!$factory->isValidType($type)) {
797
+                throw new \OC\DatabaseException('Invalid database type');
798
+            }
799
+            $connectionParams = $factory->createConnectionParams();
800
+            $connection = $factory->getConnection($type, $connectionParams);
801
+            $connection->getConfiguration()->setSQLLogger($c->getQueryLogger());
802
+            return $connection;
803
+        });
804
+        /** @deprecated 19.0.0 */
805
+        $this->registerDeprecatedAlias('DatabaseConnection', IDBConnection::class);
806
+
807
+
808
+        $this->registerService(IClientService::class, function (Server $c) {
809
+            $user = \OC_User::getUser();
810
+            $uid = $user ? $user : null;
811
+            return new ClientService(
812
+                $c->getConfig(),
813
+                $c->getLogger(),
814
+                new \OC\Security\CertificateManager(
815
+                    $uid,
816
+                    new View(),
817
+                    $c->getConfig(),
818
+                    $c->getLogger(),
819
+                    $c->getSecureRandom()
820
+                )
821
+            );
822
+        });
823
+        /** @deprecated 19.0.0 */
824
+        $this->registerDeprecatedAlias('HttpClientService', IClientService::class);
825
+        $this->registerService(IEventLogger::class, function (Server $c) {
826
+            $eventLogger = new EventLogger();
827
+            if ($c->getSystemConfig()->getValue('debug', false)) {
828
+                // In debug mode, module is being activated by default
829
+                $eventLogger->activate();
830
+            }
831
+            return $eventLogger;
832
+        });
833
+        /** @deprecated 19.0.0 */
834
+        $this->registerDeprecatedAlias('EventLogger', IEventLogger::class);
835
+
836
+        $this->registerService(IQueryLogger::class, function (Server $c) {
837
+            $queryLogger = new QueryLogger();
838
+            if ($c->getSystemConfig()->getValue('debug', false)) {
839
+                // In debug mode, module is being activated by default
840
+                $queryLogger->activate();
841
+            }
842
+            return $queryLogger;
843
+        });
844
+        /** @deprecated 19.0.0 */
845
+        $this->registerDeprecatedAlias('QueryLogger', IQueryLogger::class);
846
+
847
+        /** @deprecated 19.0.0 */
848
+        $this->registerDeprecatedAlias('TempManager', TempManager::class);
849
+        $this->registerAlias(ITempManager::class, TempManager::class);
850
+
851
+        $this->registerService(AppManager::class, function (Server $c) {
852
+            return new \OC\App\AppManager(
853
+                $c->getUserSession(),
854
+                $c->getConfig(),
855
+                $c->query(\OC\AppConfig::class),
856
+                $c->getGroupManager(),
857
+                $c->getMemCacheFactory(),
858
+                $c->getEventDispatcher(),
859
+                $c->getLogger()
860
+            );
861
+        });
862
+        /** @deprecated 19.0.0 */
863
+        $this->registerDeprecatedAlias('AppManager', AppManager::class);
864
+        $this->registerAlias(IAppManager::class, AppManager::class);
865
+
866
+        $this->registerAlias(IDateTimeZone::class, DateTimeZone::class);
867
+        /** @deprecated 19.0.0 */
868
+        $this->registerDeprecatedAlias('DateTimeZone', IDateTimeZone::class);
869
+
870
+        $this->registerService(IDateTimeFormatter::class, function (Server $c) {
871
+            $language = $c->getConfig()->getUserValue($c->getSession()->get('user_id'), 'core', 'lang', null);
872
+
873
+            return new DateTimeFormatter(
874
+                $c->getDateTimeZone()->getTimeZone(),
875
+                $c->getL10N('lib', $language)
876
+            );
877
+        });
878
+        /** @deprecated 19.0.0 */
879
+        $this->registerDeprecatedAlias('DateTimeFormatter', IDateTimeFormatter::class);
880
+
881
+        $this->registerService(IUserMountCache::class, function (Server $c) {
882
+            $mountCache = new UserMountCache($c->getDatabaseConnection(), $c->getUserManager(), $c->getLogger());
883
+            $listener = new UserMountCacheListener($mountCache);
884
+            $listener->listen($c->getUserManager());
885
+            return $mountCache;
886
+        });
887
+        /** @deprecated 19.0.0 */
888
+        $this->registerDeprecatedAlias('UserMountCache', IUserMountCache::class);
889
+
890
+        $this->registerService(IMountProviderCollection::class, function (Server $c) {
891
+            $loader = \OC\Files\Filesystem::getLoader();
892
+            $mountCache = $c->query(IUserMountCache::class);
893
+            $manager = new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
894
+
895
+            // builtin providers
896
+
897
+            $config = $c->getConfig();
898
+            $logger = $c->getLogger();
899
+            $manager->registerProvider(new CacheMountProvider($config));
900
+            $manager->registerHomeProvider(new LocalHomeMountProvider());
901
+            $manager->registerHomeProvider(new ObjectHomeMountProvider($config));
902
+            $manager->registerRootProvider(new ObjectStorePreviewCacheMountProvider($logger, $config));
903
+
904
+            return $manager;
905
+        });
906
+        /** @deprecated 19.0.0 */
907
+        $this->registerDeprecatedAlias('MountConfigManager', IMountProviderCollection::class);
908
+
909
+        /** @deprecated 20.0.0 */
910
+        $this->registerDeprecatedAlias('IniWrapper', IniGetWrapper::class);
911
+        $this->registerService('AsyncCommandBus', function (Server $c) {
912
+            $busClass = $c->getConfig()->getSystemValue('commandbus');
913
+            if ($busClass) {
914
+                [$app, $class] = explode('::', $busClass, 2);
915
+                if ($c->getAppManager()->isInstalled($app)) {
916
+                    \OC_App::loadApp($app);
917
+                    return $c->query($class);
918
+                } else {
919
+                    throw new ServiceUnavailableException("The app providing the command bus ($app) is not enabled");
920
+                }
921
+            } else {
922
+                $jobList = $c->getJobList();
923
+                return new CronBus($jobList);
924
+            }
925
+        });
926
+        $this->registerAlias(IBus::class, 'AsyncCommandBus');
927
+        /** @deprecated 20.0.0 */
928
+        $this->registerDeprecatedAlias('TrustedDomainHelper', TrustedDomainHelper::class);
929
+        /** @deprecated 19.0.0 */
930
+        $this->registerDeprecatedAlias('Throttler', Throttler::class);
931
+        $this->registerService('IntegrityCodeChecker', function (Server $c) {
932
+            // IConfig and IAppManager requires a working database. This code
933
+            // might however be called when ownCloud is not yet setup.
934
+            if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
935
+                $config = $c->getConfig();
936
+                $appManager = $c->getAppManager();
937
+            } else {
938
+                $config = null;
939
+                $appManager = null;
940
+            }
941
+
942
+            return new Checker(
943
+                new EnvironmentHelper(),
944
+                new FileAccessHelper(),
945
+                new AppLocator(),
946
+                $config,
947
+                $c->getMemCacheFactory(),
948
+                $appManager,
949
+                $c->getTempManager(),
950
+                $c->getMimeTypeDetector()
951
+            );
952
+        });
953
+        $this->registerService(\OCP\IRequest::class, function ($c) {
954
+            if (isset($this['urlParams'])) {
955
+                $urlParams = $this['urlParams'];
956
+            } else {
957
+                $urlParams = [];
958
+            }
959
+
960
+            if (defined('PHPUNIT_RUN') && PHPUNIT_RUN
961
+                && in_array('fakeinput', stream_get_wrappers())
962
+            ) {
963
+                $stream = 'fakeinput://data';
964
+            } else {
965
+                $stream = 'php://input';
966
+            }
967
+
968
+            return new Request(
969
+                [
970
+                    'get' => $_GET,
971
+                    'post' => $_POST,
972
+                    'files' => $_FILES,
973
+                    'server' => $_SERVER,
974
+                    'env' => $_ENV,
975
+                    'cookies' => $_COOKIE,
976
+                    'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
977
+                        ? $_SERVER['REQUEST_METHOD']
978
+                        : '',
979
+                    'urlParams' => $urlParams,
980
+                ],
981
+                $this->getSecureRandom(),
982
+                $this->getConfig(),
983
+                $this->getCsrfTokenManager(),
984
+                $stream
985
+            );
986
+        });
987
+        /** @deprecated 19.0.0 */
988
+        $this->registerDeprecatedAlias('Request', \OCP\IRequest::class);
989
+
990
+        $this->registerService(IMailer::class, function (Server $c) {
991
+            return new Mailer(
992
+                $c->getConfig(),
993
+                $c->getLogger(),
994
+                $c->query(Defaults::class),
995
+                $c->getURLGenerator(),
996
+                $c->getL10N('lib'),
997
+                $c->query(IEventDispatcher::class),
998
+                $c->getL10NFactory()
999
+            );
1000
+        });
1001
+        /** @deprecated 19.0.0 */
1002
+        $this->registerDeprecatedAlias('Mailer', IMailer::class);
1003
+
1004
+        $this->registerService('LDAPProvider', function (Server $c) {
1005
+            $config = $c->getConfig();
1006
+            $factoryClass = $config->getSystemValue('ldapProviderFactory', null);
1007
+            if (is_null($factoryClass)) {
1008
+                throw new \Exception('ldapProviderFactory not set');
1009
+            }
1010
+            /** @var \OCP\LDAP\ILDAPProviderFactory $factory */
1011
+            $factory = new $factoryClass($this);
1012
+            return $factory->getLDAPProvider();
1013
+        });
1014
+        $this->registerService(ILockingProvider::class, function (Server $c) {
1015
+            $ini = $c->get(IniGetWrapper::class);
1016
+            $config = $c->getConfig();
1017
+            $ttl = $config->getSystemValue('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
1018
+            if ($config->getSystemValue('filelocking.enabled', true) or (defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
1019
+                /** @var \OC\Memcache\Factory $memcacheFactory */
1020
+                $memcacheFactory = $c->getMemCacheFactory();
1021
+                $memcache = $memcacheFactory->createLocking('lock');
1022
+                if (!($memcache instanceof \OC\Memcache\NullCache)) {
1023
+                    return new MemcacheLockingProvider($memcache, $ttl);
1024
+                }
1025
+                return new DBLockingProvider(
1026
+                    $c->getDatabaseConnection(),
1027
+                    $c->getLogger(),
1028
+                    new TimeFactory(),
1029
+                    $ttl,
1030
+                    !\OC::$CLI
1031
+                );
1032
+            }
1033
+            return new NoopLockingProvider();
1034
+        });
1035
+        /** @deprecated 19.0.0 */
1036
+        $this->registerDeprecatedAlias('LockingProvider', ILockingProvider::class);
1037
+
1038
+        $this->registerAlias(IMountManager::class, \OC\Files\Mount\Manager::class);
1039
+        /** @deprecated 19.0.0 */
1040
+        $this->registerDeprecatedAlias('MountManager', IMountManager::class);
1041
+
1042
+        $this->registerService(IMimeTypeDetector::class, function (Server $c) {
1043
+            return new \OC\Files\Type\Detection(
1044
+                $c->getURLGenerator(),
1045
+                $c->getLogger(),
1046
+                \OC::$configDir,
1047
+                \OC::$SERVERROOT . '/resources/config/'
1048
+            );
1049
+        });
1050
+        /** @deprecated 19.0.0 */
1051
+        $this->registerDeprecatedAlias('MimeTypeDetector', IMimeTypeDetector::class);
1052
+
1053
+        $this->registerAlias(IMimeTypeLoader::class, Loader::class);
1054
+        /** @deprecated 19.0.0 */
1055
+        $this->registerDeprecatedAlias('MimeTypeLoader', IMimeTypeLoader::class);
1056
+        $this->registerService(BundleFetcher::class, function () {
1057
+            return new BundleFetcher($this->getL10N('lib'));
1058
+        });
1059
+        $this->registerAlias(\OCP\Notification\IManager::class, Manager::class);
1060
+        /** @deprecated 19.0.0 */
1061
+        $this->registerDeprecatedAlias('NotificationManager', \OCP\Notification\IManager::class);
1062
+
1063
+        $this->registerService(CapabilitiesManager::class, function (Server $c) {
1064
+            $manager = new CapabilitiesManager($c->getLogger());
1065
+            $manager->registerCapability(function () use ($c) {
1066
+                return new \OC\OCS\CoreCapabilities($c->getConfig());
1067
+            });
1068
+            $manager->registerCapability(function () use ($c) {
1069
+                return $c->query(\OC\Security\Bruteforce\Capabilities::class);
1070
+            });
1071
+            return $manager;
1072
+        });
1073
+        /** @deprecated 19.0.0 */
1074
+        $this->registerDeprecatedAlias('CapabilitiesManager', CapabilitiesManager::class);
1075
+
1076
+        $this->registerService(ICommentsManager::class, function (Server $c) {
1077
+            $config = $c->getConfig();
1078
+            $factoryClass = $config->getSystemValue('comments.managerFactory', CommentsManagerFactory::class);
1079
+            /** @var \OCP\Comments\ICommentsManagerFactory $factory */
1080
+            $factory = new $factoryClass($this);
1081
+            $manager = $factory->getManager();
1082
+
1083
+            $manager->registerDisplayNameResolver('user', function ($id) use ($c) {
1084
+                $manager = $c->getUserManager();
1085
+                $user = $manager->get($id);
1086
+                if (is_null($user)) {
1087
+                    $l = $c->getL10N('core');
1088
+                    $displayName = $l->t('Unknown user');
1089
+                } else {
1090
+                    $displayName = $user->getDisplayName();
1091
+                }
1092
+                return $displayName;
1093
+            });
1094
+
1095
+            return $manager;
1096
+        });
1097
+        /** @deprecated 19.0.0 */
1098
+        $this->registerDeprecatedAlias('CommentsManager', ICommentsManager::class);
1099
+
1100
+        $this->registerAlias(\OC_Defaults::class, 'ThemingDefaults');
1101
+        $this->registerService('ThemingDefaults', function (Server $c) {
1102
+            /*
1103 1103
 			 * Dark magic for autoloader.
1104 1104
 			 * If we do a class_exists it will try to load the class which will
1105 1105
 			 * make composer cache the result. Resulting in errors when enabling
1106 1106
 			 * the theming app.
1107 1107
 			 */
1108
-			$prefixes = \OC::$composerAutoloader->getPrefixesPsr4();
1109
-			if (isset($prefixes['OCA\\Theming\\'])) {
1110
-				$classExists = true;
1111
-			} else {
1112
-				$classExists = false;
1113
-			}
1114
-
1115
-			if ($classExists && $c->getConfig()->getSystemValue('installed', false) && $c->getAppManager()->isInstalled('theming') && $c->getTrustedDomainHelper()->isTrustedDomain($c->getRequest()->getInsecureServerHost())) {
1116
-				return new ThemingDefaults(
1117
-					$c->getConfig(),
1118
-					$c->getL10N('theming'),
1119
-					$c->getURLGenerator(),
1120
-					$c->getMemCacheFactory(),
1121
-					new Util($c->getConfig(), $this->getAppManager(), $c->getAppDataDir('theming')),
1122
-					new ImageManager($c->getConfig(), $c->getAppDataDir('theming'), $c->getURLGenerator(), $this->getMemCacheFactory(), $this->getLogger()),
1123
-					$c->getAppManager(),
1124
-					$c->getNavigationManager()
1125
-				);
1126
-			}
1127
-			return new \OC_Defaults();
1128
-		});
1129
-		$this->registerService(JSCombiner::class, function (Server $c) {
1130
-			return new JSCombiner(
1131
-				$c->getAppDataDir('js'),
1132
-				$c->getURLGenerator(),
1133
-				$this->getMemCacheFactory(),
1134
-				$c->getSystemConfig(),
1135
-				$c->getLogger()
1136
-			);
1137
-		});
1138
-		$this->registerAlias(\OCP\EventDispatcher\IEventDispatcher::class, \OC\EventDispatcher\EventDispatcher::class);
1139
-		/** @deprecated 19.0.0 */
1140
-		$this->registerDeprecatedAlias('EventDispatcher', \OC\EventDispatcher\SymfonyAdapter::class);
1141
-		$this->registerAlias(EventDispatcherInterface::class, \OC\EventDispatcher\SymfonyAdapter::class);
1142
-
1143
-		$this->registerService('CryptoWrapper', function (Server $c) {
1144
-			// FIXME: Instantiiated here due to cyclic dependency
1145
-			$request = new Request(
1146
-				[
1147
-					'get' => $_GET,
1148
-					'post' => $_POST,
1149
-					'files' => $_FILES,
1150
-					'server' => $_SERVER,
1151
-					'env' => $_ENV,
1152
-					'cookies' => $_COOKIE,
1153
-					'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
1154
-						? $_SERVER['REQUEST_METHOD']
1155
-						: null,
1156
-				],
1157
-				$c->getSecureRandom(),
1158
-				$c->getConfig()
1159
-			);
1160
-
1161
-			return new CryptoWrapper(
1162
-				$c->getConfig(),
1163
-				$c->getCrypto(),
1164
-				$c->getSecureRandom(),
1165
-				$request
1166
-			);
1167
-		});
1168
-		/** @deprecated 19.0.0 */
1169
-		$this->registerDeprecatedAlias('CsrfTokenManager', CsrfTokenManager::class);
1170
-		$this->registerService(SessionStorage::class, function (Server $c) {
1171
-			return new SessionStorage($c->getSession());
1172
-		});
1173
-		$this->registerAlias(\OCP\Security\IContentSecurityPolicyManager::class, ContentSecurityPolicyManager::class);
1174
-		/** @deprecated 19.0.0 */
1175
-		$this->registerDeprecatedAlias('ContentSecurityPolicyManager', ContentSecurityPolicyManager::class);
1176
-
1177
-		$this->registerService(\OCP\Share\IManager::class, function (Server $c) {
1178
-			$config = $c->getConfig();
1179
-			$factoryClass = $config->getSystemValue('sharing.managerFactory', ProviderFactory::class);
1180
-			/** @var \OCP\Share\IProviderFactory $factory */
1181
-			$factory = new $factoryClass($this);
1182
-
1183
-			$manager = new \OC\Share20\Manager(
1184
-				$c->getLogger(),
1185
-				$c->getConfig(),
1186
-				$c->getSecureRandom(),
1187
-				$c->getHasher(),
1188
-				$c->getMountManager(),
1189
-				$c->getGroupManager(),
1190
-				$c->getL10N('lib'),
1191
-				$c->getL10NFactory(),
1192
-				$factory,
1193
-				$c->getUserManager(),
1194
-				$c->getLazyRootFolder(),
1195
-				$c->getEventDispatcher(),
1196
-				$c->getMailer(),
1197
-				$c->getURLGenerator(),
1198
-				$c->getThemingDefaults(),
1199
-				$c->query(IEventDispatcher::class)
1200
-			);
1201
-
1202
-			return $manager;
1203
-		});
1204
-		/** @deprecated 19.0.0 */
1205
-		$this->registerDeprecatedAlias('ShareManager', \OCP\Share\IManager::class);
1206
-
1207
-		$this->registerService(\OCP\Collaboration\Collaborators\ISearch::class, function (Server $c) {
1208
-			$instance = new Collaboration\Collaborators\Search($c);
1209
-
1210
-			// register default plugins
1211
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_USER', 'class' => UserPlugin::class]);
1212
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_GROUP', 'class' => GroupPlugin::class]);
1213
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_EMAIL', 'class' => MailPlugin::class]);
1214
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_REMOTE', 'class' => RemotePlugin::class]);
1215
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_REMOTE_GROUP', 'class' => RemoteGroupPlugin::class]);
1216
-
1217
-			return $instance;
1218
-		});
1219
-		/** @deprecated 19.0.0 */
1220
-		$this->registerDeprecatedAlias('CollaboratorSearch', \OCP\Collaboration\Collaborators\ISearch::class);
1221
-		$this->registerAlias(\OCP\Collaboration\Collaborators\ISearchResult::class, \OC\Collaboration\Collaborators\SearchResult::class);
1222
-
1223
-		$this->registerAlias(\OCP\Collaboration\AutoComplete\IManager::class, \OC\Collaboration\AutoComplete\Manager::class);
1224
-
1225
-		$this->registerAlias(\OCP\Collaboration\Resources\IProviderManager::class, \OC\Collaboration\Resources\ProviderManager::class);
1226
-		$this->registerAlias(\OCP\Collaboration\Resources\IManager::class, \OC\Collaboration\Resources\Manager::class);
1227
-
1228
-		$this->registerService('SettingsManager', function (Server $c) {
1229
-			$manager = new \OC\Settings\Manager(
1230
-				$c->getLogger(),
1231
-				$c->getL10NFactory(),
1232
-				$c->getURLGenerator(),
1233
-				$c
1234
-			);
1235
-			return $manager;
1236
-		});
1237
-		$this->registerService(\OC\Files\AppData\Factory::class, function (Server $c) {
1238
-			return new \OC\Files\AppData\Factory(
1239
-				$c->getRootFolder(),
1240
-				$c->getSystemConfig()
1241
-			);
1242
-		});
1243
-
1244
-		$this->registerService('LockdownManager', function (Server $c) {
1245
-			return new LockdownManager(function () use ($c) {
1246
-				return $c->getSession();
1247
-			});
1248
-		});
1249
-
1250
-		$this->registerService(\OCP\OCS\IDiscoveryService::class, function (Server $c) {
1251
-			return new DiscoveryService($c->getMemCacheFactory(), $c->getHTTPClientService());
1252
-		});
1253
-
1254
-		$this->registerService(ICloudIdManager::class, function (Server $c) {
1255
-			return new CloudIdManager();
1256
-		});
1257
-
1258
-		$this->registerAlias(\OCP\GlobalScale\IConfig::class, \OC\GlobalScale\Config::class);
1259
-
1260
-		$this->registerService(ICloudFederationProviderManager::class, function (Server $c) {
1261
-			return new CloudFederationProviderManager($c->getAppManager(), $c->getHTTPClientService(), $c->getCloudIdManager(), $c->getLogger());
1262
-		});
1263
-
1264
-		$this->registerService(ICloudFederationFactory::class, function (Server $c) {
1265
-			return new CloudFederationFactory();
1266
-		});
1267
-
1268
-		$this->registerAlias(\OCP\AppFramework\Utility\IControllerMethodReflector::class, \OC\AppFramework\Utility\ControllerMethodReflector::class);
1269
-		/** @deprecated 19.0.0 */
1270
-		$this->registerDeprecatedAlias('ControllerMethodReflector', \OCP\AppFramework\Utility\IControllerMethodReflector::class);
1271
-
1272
-		$this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
1273
-		/** @deprecated 19.0.0 */
1274
-		$this->registerDeprecatedAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
1275
-
1276
-		$this->registerService(Defaults::class, function (Server $c) {
1277
-			return new Defaults(
1278
-				$c->getThemingDefaults()
1279
-			);
1280
-		});
1281
-		/** @deprecated 19.0.0 */
1282
-		$this->registerDeprecatedAlias('Defaults', \OCP\Defaults::class);
1283
-
1284
-		$this->registerService(\OCP\ISession::class, function (SimpleContainer $c) {
1285
-			return $c->query(\OCP\IUserSession::class)->getSession();
1286
-		});
1287
-
1288
-		$this->registerService(IShareHelper::class, function (Server $c) {
1289
-			return new ShareHelper(
1290
-				$c->query(\OCP\Share\IManager::class)
1291
-			);
1292
-		});
1293
-
1294
-		$this->registerService(Installer::class, function (Server $c) {
1295
-			return new Installer(
1296
-				$c->getAppFetcher(),
1297
-				$c->getHTTPClientService(),
1298
-				$c->getTempManager(),
1299
-				$c->getLogger(),
1300
-				$c->getConfig(),
1301
-				\OC::$CLI
1302
-			);
1303
-		});
1304
-
1305
-		$this->registerService(IApiFactory::class, function (Server $c) {
1306
-			return new ApiFactory($c->getHTTPClientService());
1307
-		});
1308
-
1309
-		$this->registerService(IInstanceFactory::class, function (Server $c) {
1310
-			$memcacheFactory = $c->getMemCacheFactory();
1311
-			return new InstanceFactory($memcacheFactory->createLocal('remoteinstance.'), $c->getHTTPClientService());
1312
-		});
1313
-
1314
-		$this->registerAlias(IContactsStore::class, ContactsStore::class);
1315
-		$this->registerAlias(IAccountManager::class, AccountManager::class);
1316
-
1317
-		$this->registerAlias(IStorageFactory::class, StorageFactory::class);
1318
-
1319
-		$this->registerAlias(IDashboardManager::class, DashboardManager::class);
1320
-		$this->registerAlias(\OCP\Dashboard\IManager::class, \OC\Dashboard\Manager::class);
1321
-		$this->registerAlias(IFullTextSearchManager::class, FullTextSearchManager::class);
1322
-
1323
-		$this->registerAlias(ISubAdmin::class, SubAdmin::class);
1324
-
1325
-		$this->registerAlias(IInitialStateService::class, InitialStateService::class);
1326
-
1327
-		$this->registerAlias(\OCP\UserStatus\IManager::class, \OC\UserStatus\Manager::class);
1328
-
1329
-		$this->connectDispatcher();
1330
-	}
1331
-
1332
-	public function boot() {
1333
-		/** @var HookConnector $hookConnector */
1334
-		$hookConnector = $this->query(HookConnector::class);
1335
-		$hookConnector->viewToNode();
1336
-	}
1337
-
1338
-	/**
1339
-	 * @return \OCP\Calendar\IManager
1340
-	 * @deprecated
1341
-	 */
1342
-	public function getCalendarManager() {
1343
-		return $this->query(\OC\Calendar\Manager::class);
1344
-	}
1345
-
1346
-	/**
1347
-	 * @return \OCP\Calendar\Resource\IManager
1348
-	 * @deprecated
1349
-	 */
1350
-	public function getCalendarResourceBackendManager() {
1351
-		return $this->query(\OC\Calendar\Resource\Manager::class);
1352
-	}
1353
-
1354
-	/**
1355
-	 * @return \OCP\Calendar\Room\IManager
1356
-	 * @deprecated
1357
-	 */
1358
-	public function getCalendarRoomBackendManager() {
1359
-		return $this->query(\OC\Calendar\Room\Manager::class);
1360
-	}
1361
-
1362
-	private function connectDispatcher() {
1363
-		$dispatcher = $this->getEventDispatcher();
1364
-
1365
-		// Delete avatar on user deletion
1366
-		$dispatcher->addListener('OCP\IUser::preDelete', function (GenericEvent $e) {
1367
-			$logger = $this->getLogger();
1368
-			$manager = $this->getAvatarManager();
1369
-			/** @var IUser $user */
1370
-			$user = $e->getSubject();
1371
-
1372
-			try {
1373
-				$avatar = $manager->getAvatar($user->getUID());
1374
-				$avatar->remove();
1375
-			} catch (NotFoundException $e) {
1376
-				// no avatar to remove
1377
-			} catch (\Exception $e) {
1378
-				// Ignore exceptions
1379
-				$logger->info('Could not cleanup avatar of ' . $user->getUID());
1380
-			}
1381
-		});
1382
-
1383
-		$dispatcher->addListener('OCP\IUser::changeUser', function (GenericEvent $e) {
1384
-			$manager = $this->getAvatarManager();
1385
-			/** @var IUser $user */
1386
-			$user = $e->getSubject();
1387
-			$feature = $e->getArgument('feature');
1388
-			$oldValue = $e->getArgument('oldValue');
1389
-			$value = $e->getArgument('value');
1390
-
1391
-			// We only change the avatar on display name changes
1392
-			if ($feature !== 'displayName') {
1393
-				return;
1394
-			}
1395
-
1396
-			try {
1397
-				$avatar = $manager->getAvatar($user->getUID());
1398
-				$avatar->userChanged($feature, $oldValue, $value);
1399
-			} catch (NotFoundException $e) {
1400
-				// no avatar to remove
1401
-			}
1402
-		});
1403
-
1404
-		/** @var IEventDispatcher $eventDispatched */
1405
-		$eventDispatched = $this->query(IEventDispatcher::class);
1406
-		$eventDispatched->addServiceListener(LoginFailed::class, LoginFailedListener::class);
1407
-	}
1408
-
1409
-	/**
1410
-	 * @return \OCP\Contacts\IManager
1411
-	 * @deprecated
1412
-	 */
1413
-	public function getContactsManager() {
1414
-		return $this->query(\OCP\Contacts\IManager::class);
1415
-	}
1416
-
1417
-	/**
1418
-	 * @return \OC\Encryption\Manager
1419
-	 * @deprecated
1420
-	 */
1421
-	public function getEncryptionManager() {
1422
-		return $this->query(\OCP\Encryption\IManager::class);
1423
-	}
1424
-
1425
-	/**
1426
-	 * @return \OC\Encryption\File
1427
-	 * @deprecated
1428
-	 */
1429
-	public function getEncryptionFilesHelper() {
1430
-		return $this->query('EncryptionFileHelper');
1431
-	}
1432
-
1433
-	/**
1434
-	 * @return \OCP\Encryption\Keys\IStorage
1435
-	 * @deprecated
1436
-	 */
1437
-	public function getEncryptionKeyStorage() {
1438
-		return $this->query('EncryptionKeyStorage');
1439
-	}
1440
-
1441
-	/**
1442
-	 * The current request object holding all information about the request
1443
-	 * currently being processed is returned from this method.
1444
-	 * In case the current execution was not initiated by a web request null is returned
1445
-	 *
1446
-	 * @return \OCP\IRequest
1447
-	 * @deprecated
1448
-	 */
1449
-	public function getRequest() {
1450
-		return $this->query(IRequest::class);
1451
-	}
1452
-
1453
-	/**
1454
-	 * Returns the preview manager which can create preview images for a given file
1455
-	 *
1456
-	 * @return IPreview
1457
-	 * @deprecated
1458
-	 */
1459
-	public function getPreviewManager() {
1460
-		return $this->query(IPreview::class);
1461
-	}
1462
-
1463
-	/**
1464
-	 * Returns the tag manager which can get and set tags for different object types
1465
-	 *
1466
-	 * @see \OCP\ITagManager::load()
1467
-	 * @return ITagManager
1468
-	 * @deprecated
1469
-	 */
1470
-	public function getTagManager() {
1471
-		return $this->query(ITagManager::class);
1472
-	}
1473
-
1474
-	/**
1475
-	 * Returns the system-tag manager
1476
-	 *
1477
-	 * @return ISystemTagManager
1478
-	 *
1479
-	 * @since 9.0.0
1480
-	 * @deprecated
1481
-	 */
1482
-	public function getSystemTagManager() {
1483
-		return $this->query(ISystemTagManager::class);
1484
-	}
1485
-
1486
-	/**
1487
-	 * Returns the system-tag object mapper
1488
-	 *
1489
-	 * @return ISystemTagObjectMapper
1490
-	 *
1491
-	 * @since 9.0.0
1492
-	 * @deprecated
1493
-	 */
1494
-	public function getSystemTagObjectMapper() {
1495
-		return $this->query(ISystemTagObjectMapper::class);
1496
-	}
1497
-
1498
-	/**
1499
-	 * Returns the avatar manager, used for avatar functionality
1500
-	 *
1501
-	 * @return IAvatarManager
1502
-	 * @deprecated
1503
-	 */
1504
-	public function getAvatarManager() {
1505
-		return $this->query(IAvatarManager::class);
1506
-	}
1507
-
1508
-	/**
1509
-	 * Returns the root folder of ownCloud's data directory
1510
-	 *
1511
-	 * @return IRootFolder
1512
-	 * @deprecated
1513
-	 */
1514
-	public function getRootFolder() {
1515
-		return $this->query(IRootFolder::class);
1516
-	}
1517
-
1518
-	/**
1519
-	 * Returns the root folder of ownCloud's data directory
1520
-	 * This is the lazy variant so this gets only initialized once it
1521
-	 * is actually used.
1522
-	 *
1523
-	 * @return IRootFolder
1524
-	 */
1525
-	public function getLazyRootFolder() {
1526
-		return $this->query(IRootFolder::class);
1527
-	}
1528
-
1529
-	/**
1530
-	 * Returns a view to ownCloud's files folder
1531
-	 *
1532
-	 * @param string $userId user ID
1533
-	 * @return \OCP\Files\Folder|null
1534
-	 * @deprecated
1535
-	 */
1536
-	public function getUserFolder($userId = null) {
1537
-		if ($userId === null) {
1538
-			$user = $this->getUserSession()->getUser();
1539
-			if (!$user) {
1540
-				return null;
1541
-			}
1542
-			$userId = $user->getUID();
1543
-		}
1544
-		$root = $this->getRootFolder();
1545
-		return $root->getUserFolder($userId);
1546
-	}
1547
-
1548
-	/**
1549
-	 * @return \OC\User\Manager
1550
-	 * @deprecated
1551
-	 */
1552
-	public function getUserManager() {
1553
-		return $this->query(IUserManager::class);
1554
-	}
1555
-
1556
-	/**
1557
-	 * @return \OC\Group\Manager
1558
-	 * @deprecated
1559
-	 */
1560
-	public function getGroupManager() {
1561
-		return $this->query(IGroupManager::class);
1562
-	}
1563
-
1564
-	/**
1565
-	 * @return \OC\User\Session
1566
-	 * @deprecated
1567
-	 */
1568
-	public function getUserSession() {
1569
-		return $this->query(IUserSession::class);
1570
-	}
1571
-
1572
-	/**
1573
-	 * @return \OCP\ISession
1574
-	 * @deprecated
1575
-	 */
1576
-	public function getSession() {
1577
-		return $this->getUserSession()->getSession();
1578
-	}
1579
-
1580
-	/**
1581
-	 * @param \OCP\ISession $session
1582
-	 */
1583
-	public function setSession(\OCP\ISession $session) {
1584
-		$this->query(SessionStorage::class)->setSession($session);
1585
-		$this->getUserSession()->setSession($session);
1586
-		$this->query(Store::class)->setSession($session);
1587
-	}
1588
-
1589
-	/**
1590
-	 * @return \OC\Authentication\TwoFactorAuth\Manager
1591
-	 * @deprecated
1592
-	 */
1593
-	public function getTwoFactorAuthManager() {
1594
-		return $this->query(\OC\Authentication\TwoFactorAuth\Manager::class);
1595
-	}
1596
-
1597
-	/**
1598
-	 * @return \OC\NavigationManager
1599
-	 * @deprecated
1600
-	 */
1601
-	public function getNavigationManager() {
1602
-		return $this->query(INavigationManager::class);
1603
-	}
1604
-
1605
-	/**
1606
-	 * @return \OCP\IConfig
1607
-	 * @deprecated
1608
-	 */
1609
-	public function getConfig() {
1610
-		return $this->query(AllConfig::class);
1611
-	}
1612
-
1613
-	/**
1614
-	 * @return \OC\SystemConfig
1615
-	 * @deprecated
1616
-	 */
1617
-	public function getSystemConfig() {
1618
-		return $this->query(SystemConfig::class);
1619
-	}
1620
-
1621
-	/**
1622
-	 * Returns the app config manager
1623
-	 *
1624
-	 * @return IAppConfig
1625
-	 * @deprecated
1626
-	 */
1627
-	public function getAppConfig() {
1628
-		return $this->query(IAppConfig::class);
1629
-	}
1630
-
1631
-	/**
1632
-	 * @return IFactory
1633
-	 * @deprecated
1634
-	 */
1635
-	public function getL10NFactory() {
1636
-		return $this->query(IFactory::class);
1637
-	}
1638
-
1639
-	/**
1640
-	 * get an L10N instance
1641
-	 *
1642
-	 * @param string $app appid
1643
-	 * @param string $lang
1644
-	 * @return IL10N
1645
-	 * @deprecated
1646
-	 */
1647
-	public function getL10N($app, $lang = null) {
1648
-		return $this->getL10NFactory()->get($app, $lang);
1649
-	}
1650
-
1651
-	/**
1652
-	 * @return IURLGenerator
1653
-	 * @deprecated
1654
-	 */
1655
-	public function getURLGenerator() {
1656
-		return $this->query(IURLGenerator::class);
1657
-	}
1658
-
1659
-	/**
1660
-	 * @return AppFetcher
1661
-	 * @deprecated
1662
-	 */
1663
-	public function getAppFetcher() {
1664
-		return $this->query(AppFetcher::class);
1665
-	}
1666
-
1667
-	/**
1668
-	 * Returns an ICache instance. Since 8.1.0 it returns a fake cache. Use
1669
-	 * getMemCacheFactory() instead.
1670
-	 *
1671
-	 * @return ICache
1672
-	 * @deprecated 8.1.0 use getMemCacheFactory to obtain a proper cache
1673
-	 */
1674
-	public function getCache() {
1675
-		return $this->query(ICache::class);
1676
-	}
1677
-
1678
-	/**
1679
-	 * Returns an \OCP\CacheFactory instance
1680
-	 *
1681
-	 * @return \OCP\ICacheFactory
1682
-	 * @deprecated
1683
-	 */
1684
-	public function getMemCacheFactory() {
1685
-		return $this->query(Factory::class);
1686
-	}
1687
-
1688
-	/**
1689
-	 * Returns an \OC\RedisFactory instance
1690
-	 *
1691
-	 * @return \OC\RedisFactory
1692
-	 * @deprecated
1693
-	 */
1694
-	public function getGetRedisFactory() {
1695
-		return $this->query('RedisFactory');
1696
-	}
1697
-
1698
-
1699
-	/**
1700
-	 * Returns the current session
1701
-	 *
1702
-	 * @return \OCP\IDBConnection
1703
-	 * @deprecated
1704
-	 */
1705
-	public function getDatabaseConnection() {
1706
-		return $this->query(IDBConnection::class);
1707
-	}
1708
-
1709
-	/**
1710
-	 * Returns the activity manager
1711
-	 *
1712
-	 * @return \OCP\Activity\IManager
1713
-	 * @deprecated
1714
-	 */
1715
-	public function getActivityManager() {
1716
-		return $this->query(\OCP\Activity\IManager::class);
1717
-	}
1718
-
1719
-	/**
1720
-	 * Returns an job list for controlling background jobs
1721
-	 *
1722
-	 * @return IJobList
1723
-	 * @deprecated
1724
-	 */
1725
-	public function getJobList() {
1726
-		return $this->query(IJobList::class);
1727
-	}
1728
-
1729
-	/**
1730
-	 * Returns a logger instance
1731
-	 *
1732
-	 * @return ILogger
1733
-	 * @deprecated
1734
-	 */
1735
-	public function getLogger() {
1736
-		return $this->query(ILogger::class);
1737
-	}
1738
-
1739
-	/**
1740
-	 * @return ILogFactory
1741
-	 * @throws \OCP\AppFramework\QueryException
1742
-	 * @deprecated
1743
-	 */
1744
-	public function getLogFactory() {
1745
-		return $this->query(ILogFactory::class);
1746
-	}
1747
-
1748
-	/**
1749
-	 * Returns a router for generating and matching urls
1750
-	 *
1751
-	 * @return IRouter
1752
-	 * @deprecated
1753
-	 */
1754
-	public function getRouter() {
1755
-		return $this->query(IRouter::class);
1756
-	}
1757
-
1758
-	/**
1759
-	 * Returns a search instance
1760
-	 *
1761
-	 * @return ISearch
1762
-	 * @deprecated
1763
-	 */
1764
-	public function getSearch() {
1765
-		return $this->query(ISearch::class);
1766
-	}
1767
-
1768
-	/**
1769
-	 * Returns a SecureRandom instance
1770
-	 *
1771
-	 * @return \OCP\Security\ISecureRandom
1772
-	 * @deprecated
1773
-	 */
1774
-	public function getSecureRandom() {
1775
-		return $this->query(ISecureRandom::class);
1776
-	}
1777
-
1778
-	/**
1779
-	 * Returns a Crypto instance
1780
-	 *
1781
-	 * @return ICrypto
1782
-	 * @deprecated
1783
-	 */
1784
-	public function getCrypto() {
1785
-		return $this->query(ICrypto::class);
1786
-	}
1787
-
1788
-	/**
1789
-	 * Returns a Hasher instance
1790
-	 *
1791
-	 * @return IHasher
1792
-	 * @deprecated
1793
-	 */
1794
-	public function getHasher() {
1795
-		return $this->query(IHasher::class);
1796
-	}
1797
-
1798
-	/**
1799
-	 * Returns a CredentialsManager instance
1800
-	 *
1801
-	 * @return ICredentialsManager
1802
-	 * @deprecated
1803
-	 */
1804
-	public function getCredentialsManager() {
1805
-		return $this->query(ICredentialsManager::class);
1806
-	}
1807
-
1808
-	/**
1809
-	 * Get the certificate manager for the user
1810
-	 *
1811
-	 * @param string $userId (optional) if not specified the current loggedin user is used, use null to get the system certificate manager
1812
-	 * @return \OCP\ICertificateManager | null if $uid is null and no user is logged in
1813
-	 * @deprecated
1814
-	 */
1815
-	public function getCertificateManager($userId = '') {
1816
-		if ($userId === '') {
1817
-			$userSession = $this->getUserSession();
1818
-			$user = $userSession->getUser();
1819
-			if (is_null($user)) {
1820
-				return null;
1821
-			}
1822
-			$userId = $user->getUID();
1823
-		}
1824
-		return new CertificateManager(
1825
-			$userId,
1826
-			new View(),
1827
-			$this->getConfig(),
1828
-			$this->getLogger(),
1829
-			$this->getSecureRandom()
1830
-		);
1831
-	}
1832
-
1833
-	/**
1834
-	 * Returns an instance of the HTTP client service
1835
-	 *
1836
-	 * @return IClientService
1837
-	 * @deprecated
1838
-	 */
1839
-	public function getHTTPClientService() {
1840
-		return $this->query(IClientService::class);
1841
-	}
1842
-
1843
-	/**
1844
-	 * Create a new event source
1845
-	 *
1846
-	 * @return \OCP\IEventSource
1847
-	 * @deprecated
1848
-	 */
1849
-	public function createEventSource() {
1850
-		return new \OC_EventSource();
1851
-	}
1852
-
1853
-	/**
1854
-	 * Get the active event logger
1855
-	 *
1856
-	 * The returned logger only logs data when debug mode is enabled
1857
-	 *
1858
-	 * @return IEventLogger
1859
-	 * @deprecated
1860
-	 */
1861
-	public function getEventLogger() {
1862
-		return $this->query(IEventLogger::class);
1863
-	}
1864
-
1865
-	/**
1866
-	 * Get the active query logger
1867
-	 *
1868
-	 * The returned logger only logs data when debug mode is enabled
1869
-	 *
1870
-	 * @return IQueryLogger
1871
-	 * @deprecated
1872
-	 */
1873
-	public function getQueryLogger() {
1874
-		return $this->query(IQueryLogger::class);
1875
-	}
1876
-
1877
-	/**
1878
-	 * Get the manager for temporary files and folders
1879
-	 *
1880
-	 * @return \OCP\ITempManager
1881
-	 * @deprecated
1882
-	 */
1883
-	public function getTempManager() {
1884
-		return $this->query(ITempManager::class);
1885
-	}
1886
-
1887
-	/**
1888
-	 * Get the app manager
1889
-	 *
1890
-	 * @return \OCP\App\IAppManager
1891
-	 * @deprecated
1892
-	 */
1893
-	public function getAppManager() {
1894
-		return $this->query(IAppManager::class);
1895
-	}
1896
-
1897
-	/**
1898
-	 * Creates a new mailer
1899
-	 *
1900
-	 * @return IMailer
1901
-	 * @deprecated
1902
-	 */
1903
-	public function getMailer() {
1904
-		return $this->query(IMailer::class);
1905
-	}
1906
-
1907
-	/**
1908
-	 * Get the webroot
1909
-	 *
1910
-	 * @return string
1911
-	 * @deprecated
1912
-	 */
1913
-	public function getWebRoot() {
1914
-		return $this->webRoot;
1915
-	}
1916
-
1917
-	/**
1918
-	 * @return \OC\OCSClient
1919
-	 * @deprecated
1920
-	 */
1921
-	public function getOcsClient() {
1922
-		return $this->query('OcsClient');
1923
-	}
1924
-
1925
-	/**
1926
-	 * @return IDateTimeZone
1927
-	 * @deprecated
1928
-	 */
1929
-	public function getDateTimeZone() {
1930
-		return $this->query(IDateTimeZone::class);
1931
-	}
1932
-
1933
-	/**
1934
-	 * @return IDateTimeFormatter
1935
-	 * @deprecated
1936
-	 */
1937
-	public function getDateTimeFormatter() {
1938
-		return $this->query(IDateTimeFormatter::class);
1939
-	}
1940
-
1941
-	/**
1942
-	 * @return IMountProviderCollection
1943
-	 * @deprecated
1944
-	 */
1945
-	public function getMountProviderCollection() {
1946
-		return $this->query(IMountProviderCollection::class);
1947
-	}
1948
-
1949
-	/**
1950
-	 * Get the IniWrapper
1951
-	 *
1952
-	 * @return IniGetWrapper
1953
-	 * @deprecated
1954
-	 */
1955
-	public function getIniWrapper() {
1956
-		return $this->query(IniGetWrapper::class);
1957
-	}
1958
-
1959
-	/**
1960
-	 * @return \OCP\Command\IBus
1961
-	 * @deprecated
1962
-	 */
1963
-	public function getCommandBus() {
1964
-		return $this->query('AsyncCommandBus');
1965
-	}
1966
-
1967
-	/**
1968
-	 * Get the trusted domain helper
1969
-	 *
1970
-	 * @return TrustedDomainHelper
1971
-	 * @deprecated
1972
-	 */
1973
-	public function getTrustedDomainHelper() {
1974
-		return $this->query('TrustedDomainHelper');
1975
-	}
1976
-
1977
-	/**
1978
-	 * Get the locking provider
1979
-	 *
1980
-	 * @return ILockingProvider
1981
-	 * @since 8.1.0
1982
-	 * @deprecated
1983
-	 */
1984
-	public function getLockingProvider() {
1985
-		return $this->query(ILockingProvider::class);
1986
-	}
1987
-
1988
-	/**
1989
-	 * @return IMountManager
1990
-	 * @deprecated
1991
-	 **/
1992
-	public function getMountManager() {
1993
-		return $this->query(IMountManager::class);
1994
-	}
1995
-
1996
-	/**
1997
-	 * @return IUserMountCache
1998
-	 * @deprecated
1999
-	 */
2000
-	public function getUserMountCache() {
2001
-		return $this->query(IUserMountCache::class);
2002
-	}
2003
-
2004
-	/**
2005
-	 * Get the MimeTypeDetector
2006
-	 *
2007
-	 * @return IMimeTypeDetector
2008
-	 * @deprecated
2009
-	 */
2010
-	public function getMimeTypeDetector() {
2011
-		return $this->query(IMimeTypeDetector::class);
2012
-	}
2013
-
2014
-	/**
2015
-	 * Get the MimeTypeLoader
2016
-	 *
2017
-	 * @return IMimeTypeLoader
2018
-	 * @deprecated
2019
-	 */
2020
-	public function getMimeTypeLoader() {
2021
-		return $this->query(IMimeTypeLoader::class);
2022
-	}
2023
-
2024
-	/**
2025
-	 * Get the manager of all the capabilities
2026
-	 *
2027
-	 * @return CapabilitiesManager
2028
-	 * @deprecated
2029
-	 */
2030
-	public function getCapabilitiesManager() {
2031
-		return $this->query(CapabilitiesManager::class);
2032
-	}
2033
-
2034
-	/**
2035
-	 * Get the EventDispatcher
2036
-	 *
2037
-	 * @return EventDispatcherInterface
2038
-	 * @since 8.2.0
2039
-	 * @deprecated 18.0.0 use \OCP\EventDispatcher\IEventDispatcher
2040
-	 */
2041
-	public function getEventDispatcher() {
2042
-		return $this->query(\OC\EventDispatcher\SymfonyAdapter::class);
2043
-	}
2044
-
2045
-	/**
2046
-	 * Get the Notification Manager
2047
-	 *
2048
-	 * @return \OCP\Notification\IManager
2049
-	 * @since 8.2.0
2050
-	 * @deprecated
2051
-	 */
2052
-	public function getNotificationManager() {
2053
-		return $this->query(\OCP\Notification\IManager::class);
2054
-	}
2055
-
2056
-	/**
2057
-	 * @return ICommentsManager
2058
-	 * @deprecated
2059
-	 */
2060
-	public function getCommentsManager() {
2061
-		return $this->query(ICommentsManager::class);
2062
-	}
2063
-
2064
-	/**
2065
-	 * @return \OCA\Theming\ThemingDefaults
2066
-	 * @deprecated
2067
-	 */
2068
-	public function getThemingDefaults() {
2069
-		return $this->query('ThemingDefaults');
2070
-	}
2071
-
2072
-	/**
2073
-	 * @return \OC\IntegrityCheck\Checker
2074
-	 * @deprecated
2075
-	 */
2076
-	public function getIntegrityCodeChecker() {
2077
-		return $this->query('IntegrityCodeChecker');
2078
-	}
2079
-
2080
-	/**
2081
-	 * @return \OC\Session\CryptoWrapper
2082
-	 * @deprecated
2083
-	 */
2084
-	public function getSessionCryptoWrapper() {
2085
-		return $this->query('CryptoWrapper');
2086
-	}
2087
-
2088
-	/**
2089
-	 * @return CsrfTokenManager
2090
-	 * @deprecated
2091
-	 */
2092
-	public function getCsrfTokenManager() {
2093
-		return $this->query(CsrfTokenManager::class);
2094
-	}
2095
-
2096
-	/**
2097
-	 * @return Throttler
2098
-	 * @deprecated
2099
-	 */
2100
-	public function getBruteForceThrottler() {
2101
-		return $this->query(Throttler::class);
2102
-	}
2103
-
2104
-	/**
2105
-	 * @return IContentSecurityPolicyManager
2106
-	 * @deprecated
2107
-	 */
2108
-	public function getContentSecurityPolicyManager() {
2109
-		return $this->query(ContentSecurityPolicyManager::class);
2110
-	}
2111
-
2112
-	/**
2113
-	 * @return ContentSecurityPolicyNonceManager
2114
-	 * @deprecated
2115
-	 */
2116
-	public function getContentSecurityPolicyNonceManager() {
2117
-		return $this->query(ContentSecurityPolicyNonceManager::class);
2118
-	}
2119
-
2120
-	/**
2121
-	 * Not a public API as of 8.2, wait for 9.0
2122
-	 *
2123
-	 * @return \OCA\Files_External\Service\BackendService
2124
-	 * @deprecated
2125
-	 */
2126
-	public function getStoragesBackendService() {
2127
-		return $this->query(BackendService::class);
2128
-	}
2129
-
2130
-	/**
2131
-	 * Not a public API as of 8.2, wait for 9.0
2132
-	 *
2133
-	 * @return \OCA\Files_External\Service\GlobalStoragesService
2134
-	 * @deprecated
2135
-	 */
2136
-	public function getGlobalStoragesService() {
2137
-		return $this->query(GlobalStoragesService::class);
2138
-	}
2139
-
2140
-	/**
2141
-	 * Not a public API as of 8.2, wait for 9.0
2142
-	 *
2143
-	 * @return \OCA\Files_External\Service\UserGlobalStoragesService
2144
-	 * @deprecated
2145
-	 */
2146
-	public function getUserGlobalStoragesService() {
2147
-		return $this->query(UserGlobalStoragesService::class);
2148
-	}
2149
-
2150
-	/**
2151
-	 * Not a public API as of 8.2, wait for 9.0
2152
-	 *
2153
-	 * @return \OCA\Files_External\Service\UserStoragesService
2154
-	 * @deprecated
2155
-	 */
2156
-	public function getUserStoragesService() {
2157
-		return $this->query(UserStoragesService::class);
2158
-	}
2159
-
2160
-	/**
2161
-	 * @return \OCP\Share\IManager
2162
-	 * @deprecated
2163
-	 */
2164
-	public function getShareManager() {
2165
-		return $this->query(\OCP\Share\IManager::class);
2166
-	}
2167
-
2168
-	/**
2169
-	 * @return \OCP\Collaboration\Collaborators\ISearch
2170
-	 * @deprecated
2171
-	 */
2172
-	public function getCollaboratorSearch() {
2173
-		return $this->query(\OCP\Collaboration\Collaborators\ISearch::class);
2174
-	}
2175
-
2176
-	/**
2177
-	 * @return \OCP\Collaboration\AutoComplete\IManager
2178
-	 * @deprecated
2179
-	 */
2180
-	public function getAutoCompleteManager() {
2181
-		return $this->query(IManager::class);
2182
-	}
2183
-
2184
-	/**
2185
-	 * Returns the LDAP Provider
2186
-	 *
2187
-	 * @return \OCP\LDAP\ILDAPProvider
2188
-	 * @deprecated
2189
-	 */
2190
-	public function getLDAPProvider() {
2191
-		return $this->query('LDAPProvider');
2192
-	}
2193
-
2194
-	/**
2195
-	 * @return \OCP\Settings\IManager
2196
-	 * @deprecated
2197
-	 */
2198
-	public function getSettingsManager() {
2199
-		return $this->query('SettingsManager');
2200
-	}
2201
-
2202
-	/**
2203
-	 * @return \OCP\Files\IAppData
2204
-	 * @deprecated
2205
-	 */
2206
-	public function getAppDataDir($app) {
2207
-		/** @var \OC\Files\AppData\Factory $factory */
2208
-		$factory = $this->query(\OC\Files\AppData\Factory::class);
2209
-		return $factory->get($app);
2210
-	}
2211
-
2212
-	/**
2213
-	 * @return \OCP\Lockdown\ILockdownManager
2214
-	 * @deprecated
2215
-	 */
2216
-	public function getLockdownManager() {
2217
-		return $this->query('LockdownManager');
2218
-	}
2219
-
2220
-	/**
2221
-	 * @return \OCP\Federation\ICloudIdManager
2222
-	 * @deprecated
2223
-	 */
2224
-	public function getCloudIdManager() {
2225
-		return $this->query(ICloudIdManager::class);
2226
-	}
2227
-
2228
-	/**
2229
-	 * @return \OCP\GlobalScale\IConfig
2230
-	 * @deprecated
2231
-	 */
2232
-	public function getGlobalScaleConfig() {
2233
-		return $this->query(IConfig::class);
2234
-	}
2235
-
2236
-	/**
2237
-	 * @return \OCP\Federation\ICloudFederationProviderManager
2238
-	 * @deprecated
2239
-	 */
2240
-	public function getCloudFederationProviderManager() {
2241
-		return $this->query(ICloudFederationProviderManager::class);
2242
-	}
2243
-
2244
-	/**
2245
-	 * @return \OCP\Remote\Api\IApiFactory
2246
-	 * @deprecated
2247
-	 */
2248
-	public function getRemoteApiFactory() {
2249
-		return $this->query(IApiFactory::class);
2250
-	}
2251
-
2252
-	/**
2253
-	 * @return \OCP\Federation\ICloudFederationFactory
2254
-	 * @deprecated
2255
-	 */
2256
-	public function getCloudFederationFactory() {
2257
-		return $this->query(ICloudFederationFactory::class);
2258
-	}
2259
-
2260
-	/**
2261
-	 * @return \OCP\Remote\IInstanceFactory
2262
-	 * @deprecated
2263
-	 */
2264
-	public function getRemoteInstanceFactory() {
2265
-		return $this->query(IInstanceFactory::class);
2266
-	}
2267
-
2268
-	/**
2269
-	 * @return IStorageFactory
2270
-	 * @deprecated
2271
-	 */
2272
-	public function getStorageFactory() {
2273
-		return $this->query(IStorageFactory::class);
2274
-	}
2275
-
2276
-	/**
2277
-	 * Get the Preview GeneratorHelper
2278
-	 *
2279
-	 * @return GeneratorHelper
2280
-	 * @since 17.0.0
2281
-	 * @deprecated
2282
-	 */
2283
-	public function getGeneratorHelper() {
2284
-		return $this->query(\OC\Preview\GeneratorHelper::class);
2285
-	}
2286
-
2287
-	private function registerDeprecatedAlias(string $alias, string $target) {
2288
-		$this->registerService($alias, function (ContainerInterface $container) use ($target, $alias) {
2289
-			try {
2290
-				/** @var ILogger $logger */
2291
-				$logger = $container->get(ILogger::class);
2292
-				$logger->debug('The requested alias "' . $alias . '" is depreacted. Please request "' . $target . '" directly. This alias will be removed in a future Nextcloud version.', ['app' => 'serverDI']);
2293
-			} catch (ContainerExceptionInterface $e) {
2294
-				// Could not get logger. Continue
2295
-			}
2296
-
2297
-			return $container->get($target);
2298
-		}, false);
2299
-	}
1108
+            $prefixes = \OC::$composerAutoloader->getPrefixesPsr4();
1109
+            if (isset($prefixes['OCA\\Theming\\'])) {
1110
+                $classExists = true;
1111
+            } else {
1112
+                $classExists = false;
1113
+            }
1114
+
1115
+            if ($classExists && $c->getConfig()->getSystemValue('installed', false) && $c->getAppManager()->isInstalled('theming') && $c->getTrustedDomainHelper()->isTrustedDomain($c->getRequest()->getInsecureServerHost())) {
1116
+                return new ThemingDefaults(
1117
+                    $c->getConfig(),
1118
+                    $c->getL10N('theming'),
1119
+                    $c->getURLGenerator(),
1120
+                    $c->getMemCacheFactory(),
1121
+                    new Util($c->getConfig(), $this->getAppManager(), $c->getAppDataDir('theming')),
1122
+                    new ImageManager($c->getConfig(), $c->getAppDataDir('theming'), $c->getURLGenerator(), $this->getMemCacheFactory(), $this->getLogger()),
1123
+                    $c->getAppManager(),
1124
+                    $c->getNavigationManager()
1125
+                );
1126
+            }
1127
+            return new \OC_Defaults();
1128
+        });
1129
+        $this->registerService(JSCombiner::class, function (Server $c) {
1130
+            return new JSCombiner(
1131
+                $c->getAppDataDir('js'),
1132
+                $c->getURLGenerator(),
1133
+                $this->getMemCacheFactory(),
1134
+                $c->getSystemConfig(),
1135
+                $c->getLogger()
1136
+            );
1137
+        });
1138
+        $this->registerAlias(\OCP\EventDispatcher\IEventDispatcher::class, \OC\EventDispatcher\EventDispatcher::class);
1139
+        /** @deprecated 19.0.0 */
1140
+        $this->registerDeprecatedAlias('EventDispatcher', \OC\EventDispatcher\SymfonyAdapter::class);
1141
+        $this->registerAlias(EventDispatcherInterface::class, \OC\EventDispatcher\SymfonyAdapter::class);
1142
+
1143
+        $this->registerService('CryptoWrapper', function (Server $c) {
1144
+            // FIXME: Instantiiated here due to cyclic dependency
1145
+            $request = new Request(
1146
+                [
1147
+                    'get' => $_GET,
1148
+                    'post' => $_POST,
1149
+                    'files' => $_FILES,
1150
+                    'server' => $_SERVER,
1151
+                    'env' => $_ENV,
1152
+                    'cookies' => $_COOKIE,
1153
+                    'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
1154
+                        ? $_SERVER['REQUEST_METHOD']
1155
+                        : null,
1156
+                ],
1157
+                $c->getSecureRandom(),
1158
+                $c->getConfig()
1159
+            );
1160
+
1161
+            return new CryptoWrapper(
1162
+                $c->getConfig(),
1163
+                $c->getCrypto(),
1164
+                $c->getSecureRandom(),
1165
+                $request
1166
+            );
1167
+        });
1168
+        /** @deprecated 19.0.0 */
1169
+        $this->registerDeprecatedAlias('CsrfTokenManager', CsrfTokenManager::class);
1170
+        $this->registerService(SessionStorage::class, function (Server $c) {
1171
+            return new SessionStorage($c->getSession());
1172
+        });
1173
+        $this->registerAlias(\OCP\Security\IContentSecurityPolicyManager::class, ContentSecurityPolicyManager::class);
1174
+        /** @deprecated 19.0.0 */
1175
+        $this->registerDeprecatedAlias('ContentSecurityPolicyManager', ContentSecurityPolicyManager::class);
1176
+
1177
+        $this->registerService(\OCP\Share\IManager::class, function (Server $c) {
1178
+            $config = $c->getConfig();
1179
+            $factoryClass = $config->getSystemValue('sharing.managerFactory', ProviderFactory::class);
1180
+            /** @var \OCP\Share\IProviderFactory $factory */
1181
+            $factory = new $factoryClass($this);
1182
+
1183
+            $manager = new \OC\Share20\Manager(
1184
+                $c->getLogger(),
1185
+                $c->getConfig(),
1186
+                $c->getSecureRandom(),
1187
+                $c->getHasher(),
1188
+                $c->getMountManager(),
1189
+                $c->getGroupManager(),
1190
+                $c->getL10N('lib'),
1191
+                $c->getL10NFactory(),
1192
+                $factory,
1193
+                $c->getUserManager(),
1194
+                $c->getLazyRootFolder(),
1195
+                $c->getEventDispatcher(),
1196
+                $c->getMailer(),
1197
+                $c->getURLGenerator(),
1198
+                $c->getThemingDefaults(),
1199
+                $c->query(IEventDispatcher::class)
1200
+            );
1201
+
1202
+            return $manager;
1203
+        });
1204
+        /** @deprecated 19.0.0 */
1205
+        $this->registerDeprecatedAlias('ShareManager', \OCP\Share\IManager::class);
1206
+
1207
+        $this->registerService(\OCP\Collaboration\Collaborators\ISearch::class, function (Server $c) {
1208
+            $instance = new Collaboration\Collaborators\Search($c);
1209
+
1210
+            // register default plugins
1211
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_USER', 'class' => UserPlugin::class]);
1212
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_GROUP', 'class' => GroupPlugin::class]);
1213
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_EMAIL', 'class' => MailPlugin::class]);
1214
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_REMOTE', 'class' => RemotePlugin::class]);
1215
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_REMOTE_GROUP', 'class' => RemoteGroupPlugin::class]);
1216
+
1217
+            return $instance;
1218
+        });
1219
+        /** @deprecated 19.0.0 */
1220
+        $this->registerDeprecatedAlias('CollaboratorSearch', \OCP\Collaboration\Collaborators\ISearch::class);
1221
+        $this->registerAlias(\OCP\Collaboration\Collaborators\ISearchResult::class, \OC\Collaboration\Collaborators\SearchResult::class);
1222
+
1223
+        $this->registerAlias(\OCP\Collaboration\AutoComplete\IManager::class, \OC\Collaboration\AutoComplete\Manager::class);
1224
+
1225
+        $this->registerAlias(\OCP\Collaboration\Resources\IProviderManager::class, \OC\Collaboration\Resources\ProviderManager::class);
1226
+        $this->registerAlias(\OCP\Collaboration\Resources\IManager::class, \OC\Collaboration\Resources\Manager::class);
1227
+
1228
+        $this->registerService('SettingsManager', function (Server $c) {
1229
+            $manager = new \OC\Settings\Manager(
1230
+                $c->getLogger(),
1231
+                $c->getL10NFactory(),
1232
+                $c->getURLGenerator(),
1233
+                $c
1234
+            );
1235
+            return $manager;
1236
+        });
1237
+        $this->registerService(\OC\Files\AppData\Factory::class, function (Server $c) {
1238
+            return new \OC\Files\AppData\Factory(
1239
+                $c->getRootFolder(),
1240
+                $c->getSystemConfig()
1241
+            );
1242
+        });
1243
+
1244
+        $this->registerService('LockdownManager', function (Server $c) {
1245
+            return new LockdownManager(function () use ($c) {
1246
+                return $c->getSession();
1247
+            });
1248
+        });
1249
+
1250
+        $this->registerService(\OCP\OCS\IDiscoveryService::class, function (Server $c) {
1251
+            return new DiscoveryService($c->getMemCacheFactory(), $c->getHTTPClientService());
1252
+        });
1253
+
1254
+        $this->registerService(ICloudIdManager::class, function (Server $c) {
1255
+            return new CloudIdManager();
1256
+        });
1257
+
1258
+        $this->registerAlias(\OCP\GlobalScale\IConfig::class, \OC\GlobalScale\Config::class);
1259
+
1260
+        $this->registerService(ICloudFederationProviderManager::class, function (Server $c) {
1261
+            return new CloudFederationProviderManager($c->getAppManager(), $c->getHTTPClientService(), $c->getCloudIdManager(), $c->getLogger());
1262
+        });
1263
+
1264
+        $this->registerService(ICloudFederationFactory::class, function (Server $c) {
1265
+            return new CloudFederationFactory();
1266
+        });
1267
+
1268
+        $this->registerAlias(\OCP\AppFramework\Utility\IControllerMethodReflector::class, \OC\AppFramework\Utility\ControllerMethodReflector::class);
1269
+        /** @deprecated 19.0.0 */
1270
+        $this->registerDeprecatedAlias('ControllerMethodReflector', \OCP\AppFramework\Utility\IControllerMethodReflector::class);
1271
+
1272
+        $this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
1273
+        /** @deprecated 19.0.0 */
1274
+        $this->registerDeprecatedAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
1275
+
1276
+        $this->registerService(Defaults::class, function (Server $c) {
1277
+            return new Defaults(
1278
+                $c->getThemingDefaults()
1279
+            );
1280
+        });
1281
+        /** @deprecated 19.0.0 */
1282
+        $this->registerDeprecatedAlias('Defaults', \OCP\Defaults::class);
1283
+
1284
+        $this->registerService(\OCP\ISession::class, function (SimpleContainer $c) {
1285
+            return $c->query(\OCP\IUserSession::class)->getSession();
1286
+        });
1287
+
1288
+        $this->registerService(IShareHelper::class, function (Server $c) {
1289
+            return new ShareHelper(
1290
+                $c->query(\OCP\Share\IManager::class)
1291
+            );
1292
+        });
1293
+
1294
+        $this->registerService(Installer::class, function (Server $c) {
1295
+            return new Installer(
1296
+                $c->getAppFetcher(),
1297
+                $c->getHTTPClientService(),
1298
+                $c->getTempManager(),
1299
+                $c->getLogger(),
1300
+                $c->getConfig(),
1301
+                \OC::$CLI
1302
+            );
1303
+        });
1304
+
1305
+        $this->registerService(IApiFactory::class, function (Server $c) {
1306
+            return new ApiFactory($c->getHTTPClientService());
1307
+        });
1308
+
1309
+        $this->registerService(IInstanceFactory::class, function (Server $c) {
1310
+            $memcacheFactory = $c->getMemCacheFactory();
1311
+            return new InstanceFactory($memcacheFactory->createLocal('remoteinstance.'), $c->getHTTPClientService());
1312
+        });
1313
+
1314
+        $this->registerAlias(IContactsStore::class, ContactsStore::class);
1315
+        $this->registerAlias(IAccountManager::class, AccountManager::class);
1316
+
1317
+        $this->registerAlias(IStorageFactory::class, StorageFactory::class);
1318
+
1319
+        $this->registerAlias(IDashboardManager::class, DashboardManager::class);
1320
+        $this->registerAlias(\OCP\Dashboard\IManager::class, \OC\Dashboard\Manager::class);
1321
+        $this->registerAlias(IFullTextSearchManager::class, FullTextSearchManager::class);
1322
+
1323
+        $this->registerAlias(ISubAdmin::class, SubAdmin::class);
1324
+
1325
+        $this->registerAlias(IInitialStateService::class, InitialStateService::class);
1326
+
1327
+        $this->registerAlias(\OCP\UserStatus\IManager::class, \OC\UserStatus\Manager::class);
1328
+
1329
+        $this->connectDispatcher();
1330
+    }
1331
+
1332
+    public function boot() {
1333
+        /** @var HookConnector $hookConnector */
1334
+        $hookConnector = $this->query(HookConnector::class);
1335
+        $hookConnector->viewToNode();
1336
+    }
1337
+
1338
+    /**
1339
+     * @return \OCP\Calendar\IManager
1340
+     * @deprecated
1341
+     */
1342
+    public function getCalendarManager() {
1343
+        return $this->query(\OC\Calendar\Manager::class);
1344
+    }
1345
+
1346
+    /**
1347
+     * @return \OCP\Calendar\Resource\IManager
1348
+     * @deprecated
1349
+     */
1350
+    public function getCalendarResourceBackendManager() {
1351
+        return $this->query(\OC\Calendar\Resource\Manager::class);
1352
+    }
1353
+
1354
+    /**
1355
+     * @return \OCP\Calendar\Room\IManager
1356
+     * @deprecated
1357
+     */
1358
+    public function getCalendarRoomBackendManager() {
1359
+        return $this->query(\OC\Calendar\Room\Manager::class);
1360
+    }
1361
+
1362
+    private function connectDispatcher() {
1363
+        $dispatcher = $this->getEventDispatcher();
1364
+
1365
+        // Delete avatar on user deletion
1366
+        $dispatcher->addListener('OCP\IUser::preDelete', function (GenericEvent $e) {
1367
+            $logger = $this->getLogger();
1368
+            $manager = $this->getAvatarManager();
1369
+            /** @var IUser $user */
1370
+            $user = $e->getSubject();
1371
+
1372
+            try {
1373
+                $avatar = $manager->getAvatar($user->getUID());
1374
+                $avatar->remove();
1375
+            } catch (NotFoundException $e) {
1376
+                // no avatar to remove
1377
+            } catch (\Exception $e) {
1378
+                // Ignore exceptions
1379
+                $logger->info('Could not cleanup avatar of ' . $user->getUID());
1380
+            }
1381
+        });
1382
+
1383
+        $dispatcher->addListener('OCP\IUser::changeUser', function (GenericEvent $e) {
1384
+            $manager = $this->getAvatarManager();
1385
+            /** @var IUser $user */
1386
+            $user = $e->getSubject();
1387
+            $feature = $e->getArgument('feature');
1388
+            $oldValue = $e->getArgument('oldValue');
1389
+            $value = $e->getArgument('value');
1390
+
1391
+            // We only change the avatar on display name changes
1392
+            if ($feature !== 'displayName') {
1393
+                return;
1394
+            }
1395
+
1396
+            try {
1397
+                $avatar = $manager->getAvatar($user->getUID());
1398
+                $avatar->userChanged($feature, $oldValue, $value);
1399
+            } catch (NotFoundException $e) {
1400
+                // no avatar to remove
1401
+            }
1402
+        });
1403
+
1404
+        /** @var IEventDispatcher $eventDispatched */
1405
+        $eventDispatched = $this->query(IEventDispatcher::class);
1406
+        $eventDispatched->addServiceListener(LoginFailed::class, LoginFailedListener::class);
1407
+    }
1408
+
1409
+    /**
1410
+     * @return \OCP\Contacts\IManager
1411
+     * @deprecated
1412
+     */
1413
+    public function getContactsManager() {
1414
+        return $this->query(\OCP\Contacts\IManager::class);
1415
+    }
1416
+
1417
+    /**
1418
+     * @return \OC\Encryption\Manager
1419
+     * @deprecated
1420
+     */
1421
+    public function getEncryptionManager() {
1422
+        return $this->query(\OCP\Encryption\IManager::class);
1423
+    }
1424
+
1425
+    /**
1426
+     * @return \OC\Encryption\File
1427
+     * @deprecated
1428
+     */
1429
+    public function getEncryptionFilesHelper() {
1430
+        return $this->query('EncryptionFileHelper');
1431
+    }
1432
+
1433
+    /**
1434
+     * @return \OCP\Encryption\Keys\IStorage
1435
+     * @deprecated
1436
+     */
1437
+    public function getEncryptionKeyStorage() {
1438
+        return $this->query('EncryptionKeyStorage');
1439
+    }
1440
+
1441
+    /**
1442
+     * The current request object holding all information about the request
1443
+     * currently being processed is returned from this method.
1444
+     * In case the current execution was not initiated by a web request null is returned
1445
+     *
1446
+     * @return \OCP\IRequest
1447
+     * @deprecated
1448
+     */
1449
+    public function getRequest() {
1450
+        return $this->query(IRequest::class);
1451
+    }
1452
+
1453
+    /**
1454
+     * Returns the preview manager which can create preview images for a given file
1455
+     *
1456
+     * @return IPreview
1457
+     * @deprecated
1458
+     */
1459
+    public function getPreviewManager() {
1460
+        return $this->query(IPreview::class);
1461
+    }
1462
+
1463
+    /**
1464
+     * Returns the tag manager which can get and set tags for different object types
1465
+     *
1466
+     * @see \OCP\ITagManager::load()
1467
+     * @return ITagManager
1468
+     * @deprecated
1469
+     */
1470
+    public function getTagManager() {
1471
+        return $this->query(ITagManager::class);
1472
+    }
1473
+
1474
+    /**
1475
+     * Returns the system-tag manager
1476
+     *
1477
+     * @return ISystemTagManager
1478
+     *
1479
+     * @since 9.0.0
1480
+     * @deprecated
1481
+     */
1482
+    public function getSystemTagManager() {
1483
+        return $this->query(ISystemTagManager::class);
1484
+    }
1485
+
1486
+    /**
1487
+     * Returns the system-tag object mapper
1488
+     *
1489
+     * @return ISystemTagObjectMapper
1490
+     *
1491
+     * @since 9.0.0
1492
+     * @deprecated
1493
+     */
1494
+    public function getSystemTagObjectMapper() {
1495
+        return $this->query(ISystemTagObjectMapper::class);
1496
+    }
1497
+
1498
+    /**
1499
+     * Returns the avatar manager, used for avatar functionality
1500
+     *
1501
+     * @return IAvatarManager
1502
+     * @deprecated
1503
+     */
1504
+    public function getAvatarManager() {
1505
+        return $this->query(IAvatarManager::class);
1506
+    }
1507
+
1508
+    /**
1509
+     * Returns the root folder of ownCloud's data directory
1510
+     *
1511
+     * @return IRootFolder
1512
+     * @deprecated
1513
+     */
1514
+    public function getRootFolder() {
1515
+        return $this->query(IRootFolder::class);
1516
+    }
1517
+
1518
+    /**
1519
+     * Returns the root folder of ownCloud's data directory
1520
+     * This is the lazy variant so this gets only initialized once it
1521
+     * is actually used.
1522
+     *
1523
+     * @return IRootFolder
1524
+     */
1525
+    public function getLazyRootFolder() {
1526
+        return $this->query(IRootFolder::class);
1527
+    }
1528
+
1529
+    /**
1530
+     * Returns a view to ownCloud's files folder
1531
+     *
1532
+     * @param string $userId user ID
1533
+     * @return \OCP\Files\Folder|null
1534
+     * @deprecated
1535
+     */
1536
+    public function getUserFolder($userId = null) {
1537
+        if ($userId === null) {
1538
+            $user = $this->getUserSession()->getUser();
1539
+            if (!$user) {
1540
+                return null;
1541
+            }
1542
+            $userId = $user->getUID();
1543
+        }
1544
+        $root = $this->getRootFolder();
1545
+        return $root->getUserFolder($userId);
1546
+    }
1547
+
1548
+    /**
1549
+     * @return \OC\User\Manager
1550
+     * @deprecated
1551
+     */
1552
+    public function getUserManager() {
1553
+        return $this->query(IUserManager::class);
1554
+    }
1555
+
1556
+    /**
1557
+     * @return \OC\Group\Manager
1558
+     * @deprecated
1559
+     */
1560
+    public function getGroupManager() {
1561
+        return $this->query(IGroupManager::class);
1562
+    }
1563
+
1564
+    /**
1565
+     * @return \OC\User\Session
1566
+     * @deprecated
1567
+     */
1568
+    public function getUserSession() {
1569
+        return $this->query(IUserSession::class);
1570
+    }
1571
+
1572
+    /**
1573
+     * @return \OCP\ISession
1574
+     * @deprecated
1575
+     */
1576
+    public function getSession() {
1577
+        return $this->getUserSession()->getSession();
1578
+    }
1579
+
1580
+    /**
1581
+     * @param \OCP\ISession $session
1582
+     */
1583
+    public function setSession(\OCP\ISession $session) {
1584
+        $this->query(SessionStorage::class)->setSession($session);
1585
+        $this->getUserSession()->setSession($session);
1586
+        $this->query(Store::class)->setSession($session);
1587
+    }
1588
+
1589
+    /**
1590
+     * @return \OC\Authentication\TwoFactorAuth\Manager
1591
+     * @deprecated
1592
+     */
1593
+    public function getTwoFactorAuthManager() {
1594
+        return $this->query(\OC\Authentication\TwoFactorAuth\Manager::class);
1595
+    }
1596
+
1597
+    /**
1598
+     * @return \OC\NavigationManager
1599
+     * @deprecated
1600
+     */
1601
+    public function getNavigationManager() {
1602
+        return $this->query(INavigationManager::class);
1603
+    }
1604
+
1605
+    /**
1606
+     * @return \OCP\IConfig
1607
+     * @deprecated
1608
+     */
1609
+    public function getConfig() {
1610
+        return $this->query(AllConfig::class);
1611
+    }
1612
+
1613
+    /**
1614
+     * @return \OC\SystemConfig
1615
+     * @deprecated
1616
+     */
1617
+    public function getSystemConfig() {
1618
+        return $this->query(SystemConfig::class);
1619
+    }
1620
+
1621
+    /**
1622
+     * Returns the app config manager
1623
+     *
1624
+     * @return IAppConfig
1625
+     * @deprecated
1626
+     */
1627
+    public function getAppConfig() {
1628
+        return $this->query(IAppConfig::class);
1629
+    }
1630
+
1631
+    /**
1632
+     * @return IFactory
1633
+     * @deprecated
1634
+     */
1635
+    public function getL10NFactory() {
1636
+        return $this->query(IFactory::class);
1637
+    }
1638
+
1639
+    /**
1640
+     * get an L10N instance
1641
+     *
1642
+     * @param string $app appid
1643
+     * @param string $lang
1644
+     * @return IL10N
1645
+     * @deprecated
1646
+     */
1647
+    public function getL10N($app, $lang = null) {
1648
+        return $this->getL10NFactory()->get($app, $lang);
1649
+    }
1650
+
1651
+    /**
1652
+     * @return IURLGenerator
1653
+     * @deprecated
1654
+     */
1655
+    public function getURLGenerator() {
1656
+        return $this->query(IURLGenerator::class);
1657
+    }
1658
+
1659
+    /**
1660
+     * @return AppFetcher
1661
+     * @deprecated
1662
+     */
1663
+    public function getAppFetcher() {
1664
+        return $this->query(AppFetcher::class);
1665
+    }
1666
+
1667
+    /**
1668
+     * Returns an ICache instance. Since 8.1.0 it returns a fake cache. Use
1669
+     * getMemCacheFactory() instead.
1670
+     *
1671
+     * @return ICache
1672
+     * @deprecated 8.1.0 use getMemCacheFactory to obtain a proper cache
1673
+     */
1674
+    public function getCache() {
1675
+        return $this->query(ICache::class);
1676
+    }
1677
+
1678
+    /**
1679
+     * Returns an \OCP\CacheFactory instance
1680
+     *
1681
+     * @return \OCP\ICacheFactory
1682
+     * @deprecated
1683
+     */
1684
+    public function getMemCacheFactory() {
1685
+        return $this->query(Factory::class);
1686
+    }
1687
+
1688
+    /**
1689
+     * Returns an \OC\RedisFactory instance
1690
+     *
1691
+     * @return \OC\RedisFactory
1692
+     * @deprecated
1693
+     */
1694
+    public function getGetRedisFactory() {
1695
+        return $this->query('RedisFactory');
1696
+    }
1697
+
1698
+
1699
+    /**
1700
+     * Returns the current session
1701
+     *
1702
+     * @return \OCP\IDBConnection
1703
+     * @deprecated
1704
+     */
1705
+    public function getDatabaseConnection() {
1706
+        return $this->query(IDBConnection::class);
1707
+    }
1708
+
1709
+    /**
1710
+     * Returns the activity manager
1711
+     *
1712
+     * @return \OCP\Activity\IManager
1713
+     * @deprecated
1714
+     */
1715
+    public function getActivityManager() {
1716
+        return $this->query(\OCP\Activity\IManager::class);
1717
+    }
1718
+
1719
+    /**
1720
+     * Returns an job list for controlling background jobs
1721
+     *
1722
+     * @return IJobList
1723
+     * @deprecated
1724
+     */
1725
+    public function getJobList() {
1726
+        return $this->query(IJobList::class);
1727
+    }
1728
+
1729
+    /**
1730
+     * Returns a logger instance
1731
+     *
1732
+     * @return ILogger
1733
+     * @deprecated
1734
+     */
1735
+    public function getLogger() {
1736
+        return $this->query(ILogger::class);
1737
+    }
1738
+
1739
+    /**
1740
+     * @return ILogFactory
1741
+     * @throws \OCP\AppFramework\QueryException
1742
+     * @deprecated
1743
+     */
1744
+    public function getLogFactory() {
1745
+        return $this->query(ILogFactory::class);
1746
+    }
1747
+
1748
+    /**
1749
+     * Returns a router for generating and matching urls
1750
+     *
1751
+     * @return IRouter
1752
+     * @deprecated
1753
+     */
1754
+    public function getRouter() {
1755
+        return $this->query(IRouter::class);
1756
+    }
1757
+
1758
+    /**
1759
+     * Returns a search instance
1760
+     *
1761
+     * @return ISearch
1762
+     * @deprecated
1763
+     */
1764
+    public function getSearch() {
1765
+        return $this->query(ISearch::class);
1766
+    }
1767
+
1768
+    /**
1769
+     * Returns a SecureRandom instance
1770
+     *
1771
+     * @return \OCP\Security\ISecureRandom
1772
+     * @deprecated
1773
+     */
1774
+    public function getSecureRandom() {
1775
+        return $this->query(ISecureRandom::class);
1776
+    }
1777
+
1778
+    /**
1779
+     * Returns a Crypto instance
1780
+     *
1781
+     * @return ICrypto
1782
+     * @deprecated
1783
+     */
1784
+    public function getCrypto() {
1785
+        return $this->query(ICrypto::class);
1786
+    }
1787
+
1788
+    /**
1789
+     * Returns a Hasher instance
1790
+     *
1791
+     * @return IHasher
1792
+     * @deprecated
1793
+     */
1794
+    public function getHasher() {
1795
+        return $this->query(IHasher::class);
1796
+    }
1797
+
1798
+    /**
1799
+     * Returns a CredentialsManager instance
1800
+     *
1801
+     * @return ICredentialsManager
1802
+     * @deprecated
1803
+     */
1804
+    public function getCredentialsManager() {
1805
+        return $this->query(ICredentialsManager::class);
1806
+    }
1807
+
1808
+    /**
1809
+     * Get the certificate manager for the user
1810
+     *
1811
+     * @param string $userId (optional) if not specified the current loggedin user is used, use null to get the system certificate manager
1812
+     * @return \OCP\ICertificateManager | null if $uid is null and no user is logged in
1813
+     * @deprecated
1814
+     */
1815
+    public function getCertificateManager($userId = '') {
1816
+        if ($userId === '') {
1817
+            $userSession = $this->getUserSession();
1818
+            $user = $userSession->getUser();
1819
+            if (is_null($user)) {
1820
+                return null;
1821
+            }
1822
+            $userId = $user->getUID();
1823
+        }
1824
+        return new CertificateManager(
1825
+            $userId,
1826
+            new View(),
1827
+            $this->getConfig(),
1828
+            $this->getLogger(),
1829
+            $this->getSecureRandom()
1830
+        );
1831
+    }
1832
+
1833
+    /**
1834
+     * Returns an instance of the HTTP client service
1835
+     *
1836
+     * @return IClientService
1837
+     * @deprecated
1838
+     */
1839
+    public function getHTTPClientService() {
1840
+        return $this->query(IClientService::class);
1841
+    }
1842
+
1843
+    /**
1844
+     * Create a new event source
1845
+     *
1846
+     * @return \OCP\IEventSource
1847
+     * @deprecated
1848
+     */
1849
+    public function createEventSource() {
1850
+        return new \OC_EventSource();
1851
+    }
1852
+
1853
+    /**
1854
+     * Get the active event logger
1855
+     *
1856
+     * The returned logger only logs data when debug mode is enabled
1857
+     *
1858
+     * @return IEventLogger
1859
+     * @deprecated
1860
+     */
1861
+    public function getEventLogger() {
1862
+        return $this->query(IEventLogger::class);
1863
+    }
1864
+
1865
+    /**
1866
+     * Get the active query logger
1867
+     *
1868
+     * The returned logger only logs data when debug mode is enabled
1869
+     *
1870
+     * @return IQueryLogger
1871
+     * @deprecated
1872
+     */
1873
+    public function getQueryLogger() {
1874
+        return $this->query(IQueryLogger::class);
1875
+    }
1876
+
1877
+    /**
1878
+     * Get the manager for temporary files and folders
1879
+     *
1880
+     * @return \OCP\ITempManager
1881
+     * @deprecated
1882
+     */
1883
+    public function getTempManager() {
1884
+        return $this->query(ITempManager::class);
1885
+    }
1886
+
1887
+    /**
1888
+     * Get the app manager
1889
+     *
1890
+     * @return \OCP\App\IAppManager
1891
+     * @deprecated
1892
+     */
1893
+    public function getAppManager() {
1894
+        return $this->query(IAppManager::class);
1895
+    }
1896
+
1897
+    /**
1898
+     * Creates a new mailer
1899
+     *
1900
+     * @return IMailer
1901
+     * @deprecated
1902
+     */
1903
+    public function getMailer() {
1904
+        return $this->query(IMailer::class);
1905
+    }
1906
+
1907
+    /**
1908
+     * Get the webroot
1909
+     *
1910
+     * @return string
1911
+     * @deprecated
1912
+     */
1913
+    public function getWebRoot() {
1914
+        return $this->webRoot;
1915
+    }
1916
+
1917
+    /**
1918
+     * @return \OC\OCSClient
1919
+     * @deprecated
1920
+     */
1921
+    public function getOcsClient() {
1922
+        return $this->query('OcsClient');
1923
+    }
1924
+
1925
+    /**
1926
+     * @return IDateTimeZone
1927
+     * @deprecated
1928
+     */
1929
+    public function getDateTimeZone() {
1930
+        return $this->query(IDateTimeZone::class);
1931
+    }
1932
+
1933
+    /**
1934
+     * @return IDateTimeFormatter
1935
+     * @deprecated
1936
+     */
1937
+    public function getDateTimeFormatter() {
1938
+        return $this->query(IDateTimeFormatter::class);
1939
+    }
1940
+
1941
+    /**
1942
+     * @return IMountProviderCollection
1943
+     * @deprecated
1944
+     */
1945
+    public function getMountProviderCollection() {
1946
+        return $this->query(IMountProviderCollection::class);
1947
+    }
1948
+
1949
+    /**
1950
+     * Get the IniWrapper
1951
+     *
1952
+     * @return IniGetWrapper
1953
+     * @deprecated
1954
+     */
1955
+    public function getIniWrapper() {
1956
+        return $this->query(IniGetWrapper::class);
1957
+    }
1958
+
1959
+    /**
1960
+     * @return \OCP\Command\IBus
1961
+     * @deprecated
1962
+     */
1963
+    public function getCommandBus() {
1964
+        return $this->query('AsyncCommandBus');
1965
+    }
1966
+
1967
+    /**
1968
+     * Get the trusted domain helper
1969
+     *
1970
+     * @return TrustedDomainHelper
1971
+     * @deprecated
1972
+     */
1973
+    public function getTrustedDomainHelper() {
1974
+        return $this->query('TrustedDomainHelper');
1975
+    }
1976
+
1977
+    /**
1978
+     * Get the locking provider
1979
+     *
1980
+     * @return ILockingProvider
1981
+     * @since 8.1.0
1982
+     * @deprecated
1983
+     */
1984
+    public function getLockingProvider() {
1985
+        return $this->query(ILockingProvider::class);
1986
+    }
1987
+
1988
+    /**
1989
+     * @return IMountManager
1990
+     * @deprecated
1991
+     **/
1992
+    public function getMountManager() {
1993
+        return $this->query(IMountManager::class);
1994
+    }
1995
+
1996
+    /**
1997
+     * @return IUserMountCache
1998
+     * @deprecated
1999
+     */
2000
+    public function getUserMountCache() {
2001
+        return $this->query(IUserMountCache::class);
2002
+    }
2003
+
2004
+    /**
2005
+     * Get the MimeTypeDetector
2006
+     *
2007
+     * @return IMimeTypeDetector
2008
+     * @deprecated
2009
+     */
2010
+    public function getMimeTypeDetector() {
2011
+        return $this->query(IMimeTypeDetector::class);
2012
+    }
2013
+
2014
+    /**
2015
+     * Get the MimeTypeLoader
2016
+     *
2017
+     * @return IMimeTypeLoader
2018
+     * @deprecated
2019
+     */
2020
+    public function getMimeTypeLoader() {
2021
+        return $this->query(IMimeTypeLoader::class);
2022
+    }
2023
+
2024
+    /**
2025
+     * Get the manager of all the capabilities
2026
+     *
2027
+     * @return CapabilitiesManager
2028
+     * @deprecated
2029
+     */
2030
+    public function getCapabilitiesManager() {
2031
+        return $this->query(CapabilitiesManager::class);
2032
+    }
2033
+
2034
+    /**
2035
+     * Get the EventDispatcher
2036
+     *
2037
+     * @return EventDispatcherInterface
2038
+     * @since 8.2.0
2039
+     * @deprecated 18.0.0 use \OCP\EventDispatcher\IEventDispatcher
2040
+     */
2041
+    public function getEventDispatcher() {
2042
+        return $this->query(\OC\EventDispatcher\SymfonyAdapter::class);
2043
+    }
2044
+
2045
+    /**
2046
+     * Get the Notification Manager
2047
+     *
2048
+     * @return \OCP\Notification\IManager
2049
+     * @since 8.2.0
2050
+     * @deprecated
2051
+     */
2052
+    public function getNotificationManager() {
2053
+        return $this->query(\OCP\Notification\IManager::class);
2054
+    }
2055
+
2056
+    /**
2057
+     * @return ICommentsManager
2058
+     * @deprecated
2059
+     */
2060
+    public function getCommentsManager() {
2061
+        return $this->query(ICommentsManager::class);
2062
+    }
2063
+
2064
+    /**
2065
+     * @return \OCA\Theming\ThemingDefaults
2066
+     * @deprecated
2067
+     */
2068
+    public function getThemingDefaults() {
2069
+        return $this->query('ThemingDefaults');
2070
+    }
2071
+
2072
+    /**
2073
+     * @return \OC\IntegrityCheck\Checker
2074
+     * @deprecated
2075
+     */
2076
+    public function getIntegrityCodeChecker() {
2077
+        return $this->query('IntegrityCodeChecker');
2078
+    }
2079
+
2080
+    /**
2081
+     * @return \OC\Session\CryptoWrapper
2082
+     * @deprecated
2083
+     */
2084
+    public function getSessionCryptoWrapper() {
2085
+        return $this->query('CryptoWrapper');
2086
+    }
2087
+
2088
+    /**
2089
+     * @return CsrfTokenManager
2090
+     * @deprecated
2091
+     */
2092
+    public function getCsrfTokenManager() {
2093
+        return $this->query(CsrfTokenManager::class);
2094
+    }
2095
+
2096
+    /**
2097
+     * @return Throttler
2098
+     * @deprecated
2099
+     */
2100
+    public function getBruteForceThrottler() {
2101
+        return $this->query(Throttler::class);
2102
+    }
2103
+
2104
+    /**
2105
+     * @return IContentSecurityPolicyManager
2106
+     * @deprecated
2107
+     */
2108
+    public function getContentSecurityPolicyManager() {
2109
+        return $this->query(ContentSecurityPolicyManager::class);
2110
+    }
2111
+
2112
+    /**
2113
+     * @return ContentSecurityPolicyNonceManager
2114
+     * @deprecated
2115
+     */
2116
+    public function getContentSecurityPolicyNonceManager() {
2117
+        return $this->query(ContentSecurityPolicyNonceManager::class);
2118
+    }
2119
+
2120
+    /**
2121
+     * Not a public API as of 8.2, wait for 9.0
2122
+     *
2123
+     * @return \OCA\Files_External\Service\BackendService
2124
+     * @deprecated
2125
+     */
2126
+    public function getStoragesBackendService() {
2127
+        return $this->query(BackendService::class);
2128
+    }
2129
+
2130
+    /**
2131
+     * Not a public API as of 8.2, wait for 9.0
2132
+     *
2133
+     * @return \OCA\Files_External\Service\GlobalStoragesService
2134
+     * @deprecated
2135
+     */
2136
+    public function getGlobalStoragesService() {
2137
+        return $this->query(GlobalStoragesService::class);
2138
+    }
2139
+
2140
+    /**
2141
+     * Not a public API as of 8.2, wait for 9.0
2142
+     *
2143
+     * @return \OCA\Files_External\Service\UserGlobalStoragesService
2144
+     * @deprecated
2145
+     */
2146
+    public function getUserGlobalStoragesService() {
2147
+        return $this->query(UserGlobalStoragesService::class);
2148
+    }
2149
+
2150
+    /**
2151
+     * Not a public API as of 8.2, wait for 9.0
2152
+     *
2153
+     * @return \OCA\Files_External\Service\UserStoragesService
2154
+     * @deprecated
2155
+     */
2156
+    public function getUserStoragesService() {
2157
+        return $this->query(UserStoragesService::class);
2158
+    }
2159
+
2160
+    /**
2161
+     * @return \OCP\Share\IManager
2162
+     * @deprecated
2163
+     */
2164
+    public function getShareManager() {
2165
+        return $this->query(\OCP\Share\IManager::class);
2166
+    }
2167
+
2168
+    /**
2169
+     * @return \OCP\Collaboration\Collaborators\ISearch
2170
+     * @deprecated
2171
+     */
2172
+    public function getCollaboratorSearch() {
2173
+        return $this->query(\OCP\Collaboration\Collaborators\ISearch::class);
2174
+    }
2175
+
2176
+    /**
2177
+     * @return \OCP\Collaboration\AutoComplete\IManager
2178
+     * @deprecated
2179
+     */
2180
+    public function getAutoCompleteManager() {
2181
+        return $this->query(IManager::class);
2182
+    }
2183
+
2184
+    /**
2185
+     * Returns the LDAP Provider
2186
+     *
2187
+     * @return \OCP\LDAP\ILDAPProvider
2188
+     * @deprecated
2189
+     */
2190
+    public function getLDAPProvider() {
2191
+        return $this->query('LDAPProvider');
2192
+    }
2193
+
2194
+    /**
2195
+     * @return \OCP\Settings\IManager
2196
+     * @deprecated
2197
+     */
2198
+    public function getSettingsManager() {
2199
+        return $this->query('SettingsManager');
2200
+    }
2201
+
2202
+    /**
2203
+     * @return \OCP\Files\IAppData
2204
+     * @deprecated
2205
+     */
2206
+    public function getAppDataDir($app) {
2207
+        /** @var \OC\Files\AppData\Factory $factory */
2208
+        $factory = $this->query(\OC\Files\AppData\Factory::class);
2209
+        return $factory->get($app);
2210
+    }
2211
+
2212
+    /**
2213
+     * @return \OCP\Lockdown\ILockdownManager
2214
+     * @deprecated
2215
+     */
2216
+    public function getLockdownManager() {
2217
+        return $this->query('LockdownManager');
2218
+    }
2219
+
2220
+    /**
2221
+     * @return \OCP\Federation\ICloudIdManager
2222
+     * @deprecated
2223
+     */
2224
+    public function getCloudIdManager() {
2225
+        return $this->query(ICloudIdManager::class);
2226
+    }
2227
+
2228
+    /**
2229
+     * @return \OCP\GlobalScale\IConfig
2230
+     * @deprecated
2231
+     */
2232
+    public function getGlobalScaleConfig() {
2233
+        return $this->query(IConfig::class);
2234
+    }
2235
+
2236
+    /**
2237
+     * @return \OCP\Federation\ICloudFederationProviderManager
2238
+     * @deprecated
2239
+     */
2240
+    public function getCloudFederationProviderManager() {
2241
+        return $this->query(ICloudFederationProviderManager::class);
2242
+    }
2243
+
2244
+    /**
2245
+     * @return \OCP\Remote\Api\IApiFactory
2246
+     * @deprecated
2247
+     */
2248
+    public function getRemoteApiFactory() {
2249
+        return $this->query(IApiFactory::class);
2250
+    }
2251
+
2252
+    /**
2253
+     * @return \OCP\Federation\ICloudFederationFactory
2254
+     * @deprecated
2255
+     */
2256
+    public function getCloudFederationFactory() {
2257
+        return $this->query(ICloudFederationFactory::class);
2258
+    }
2259
+
2260
+    /**
2261
+     * @return \OCP\Remote\IInstanceFactory
2262
+     * @deprecated
2263
+     */
2264
+    public function getRemoteInstanceFactory() {
2265
+        return $this->query(IInstanceFactory::class);
2266
+    }
2267
+
2268
+    /**
2269
+     * @return IStorageFactory
2270
+     * @deprecated
2271
+     */
2272
+    public function getStorageFactory() {
2273
+        return $this->query(IStorageFactory::class);
2274
+    }
2275
+
2276
+    /**
2277
+     * Get the Preview GeneratorHelper
2278
+     *
2279
+     * @return GeneratorHelper
2280
+     * @since 17.0.0
2281
+     * @deprecated
2282
+     */
2283
+    public function getGeneratorHelper() {
2284
+        return $this->query(\OC\Preview\GeneratorHelper::class);
2285
+    }
2286
+
2287
+    private function registerDeprecatedAlias(string $alias, string $target) {
2288
+        $this->registerService($alias, function (ContainerInterface $container) use ($target, $alias) {
2289
+            try {
2290
+                /** @var ILogger $logger */
2291
+                $logger = $container->get(ILogger::class);
2292
+                $logger->debug('The requested alias "' . $alias . '" is depreacted. Please request "' . $target . '" directly. This alias will be removed in a future Nextcloud version.', ['app' => 'serverDI']);
2293
+            } catch (ContainerExceptionInterface $e) {
2294
+                // Could not get logger. Continue
2295
+            }
2296
+
2297
+            return $container->get($target);
2298
+        }, false);
2299
+    }
2300 2300
 }
Please login to merge, or discard this patch.
Spacing   +98 added lines, -98 removed lines patch added patch discarded remove patch
@@ -258,10 +258,10 @@  discard block
 block discarded – undo
258 258
 		$this->registerParameter('isCLI', \OC::$CLI);
259 259
 		$this->registerParameter('serverRoot', \OC::$SERVERROOT);
260 260
 
261
-		$this->registerService(ContainerInterface::class, function (ContainerInterface $c) {
261
+		$this->registerService(ContainerInterface::class, function(ContainerInterface $c) {
262 262
 			return $c;
263 263
 		});
264
-		$this->registerService(\OCP\IServerContainer::class, function (ContainerInterface $c) {
264
+		$this->registerService(\OCP\IServerContainer::class, function(ContainerInterface $c) {
265 265
 			return $c;
266 266
 		});
267 267
 
@@ -286,7 +286,7 @@  discard block
 block discarded – undo
286 286
 		$this->registerAlias(IActionFactory::class, ActionFactory::class);
287 287
 
288 288
 
289
-		$this->registerService(IPreview::class, function (Server $c) {
289
+		$this->registerService(IPreview::class, function(Server $c) {
290 290
 			return new PreviewManager(
291 291
 				$c->getConfig(),
292 292
 				$c->getRootFolder(),
@@ -299,13 +299,13 @@  discard block
 block discarded – undo
299 299
 		/** @deprecated 19.0.0 */
300 300
 		$this->registerDeprecatedAlias('PreviewManager', IPreview::class);
301 301
 
302
-		$this->registerService(\OC\Preview\Watcher::class, function (Server $c) {
302
+		$this->registerService(\OC\Preview\Watcher::class, function(Server $c) {
303 303
 			return new \OC\Preview\Watcher(
304 304
 				new \OC\Preview\Storage\Root($c->getRootFolder(), $c->getSystemConfig())
305 305
 			);
306 306
 		});
307 307
 
308
-		$this->registerService(\OCP\Encryption\IManager::class, function (Server $c) {
308
+		$this->registerService(\OCP\Encryption\IManager::class, function(Server $c) {
309 309
 			$view = new View();
310 310
 			$util = new Encryption\Util(
311 311
 				$view,
@@ -325,7 +325,7 @@  discard block
 block discarded – undo
325 325
 		/** @deprecated 19.0.0 */
326 326
 		$this->registerDeprecatedAlias('EncryptionManager', \OCP\Encryption\IManager::class);
327 327
 
328
-		$this->registerService('EncryptionFileHelper', function (Server $c) {
328
+		$this->registerService('EncryptionFileHelper', function(Server $c) {
329 329
 			$util = new Encryption\Util(
330 330
 				new View(),
331 331
 				$c->getUserManager(),
@@ -339,7 +339,7 @@  discard block
 block discarded – undo
339 339
 			);
340 340
 		});
341 341
 
342
-		$this->registerService('EncryptionKeyStorage', function (Server $c) {
342
+		$this->registerService('EncryptionKeyStorage', function(Server $c) {
343 343
 			$view = new View();
344 344
 			$util = new Encryption\Util(
345 345
 				$view,
@@ -357,21 +357,21 @@  discard block
 block discarded – undo
357 357
 		/** @deprecated 19.0.0 */
358 358
 		$this->registerDeprecatedAlias('TagManager', \OCP\ITagManager::class);
359 359
 
360
-		$this->registerService('SystemTagManagerFactory', function (Server $c) {
360
+		$this->registerService('SystemTagManagerFactory', function(Server $c) {
361 361
 			$config = $c->getConfig();
362 362
 			$factoryClass = $config->getSystemValue('systemtags.managerFactory', SystemTagManagerFactory::class);
363 363
 			return new $factoryClass($this);
364 364
 		});
365
-		$this->registerService(ISystemTagManager::class, function (Server $c) {
365
+		$this->registerService(ISystemTagManager::class, function(Server $c) {
366 366
 			return $c->query('SystemTagManagerFactory')->getManager();
367 367
 		});
368 368
 		/** @deprecated 19.0.0 */
369 369
 		$this->registerDeprecatedAlias('SystemTagManager', ISystemTagManager::class);
370 370
 
371
-		$this->registerService(ISystemTagObjectMapper::class, function (Server $c) {
371
+		$this->registerService(ISystemTagObjectMapper::class, function(Server $c) {
372 372
 			return $c->query('SystemTagManagerFactory')->getObjectMapper();
373 373
 		});
374
-		$this->registerService('RootFolder', function (Server $c) {
374
+		$this->registerService('RootFolder', function(Server $c) {
375 375
 			$manager = \OC\Files\Filesystem::getMountManager(null);
376 376
 			$view = new View();
377 377
 			$root = new Root(
@@ -388,7 +388,7 @@  discard block
 block discarded – undo
388 388
 
389 389
 			return $root;
390 390
 		});
391
-		$this->registerService(HookConnector::class, function (Server $c) {
391
+		$this->registerService(HookConnector::class, function(Server $c) {
392 392
 			return new HookConnector(
393 393
 				$c->query(IRootFolder::class),
394 394
 				new View(),
@@ -400,8 +400,8 @@  discard block
 block discarded – undo
400 400
 		/** @deprecated 19.0.0 */
401 401
 		$this->registerDeprecatedAlias('SystemTagObjectMapper', ISystemTagObjectMapper::class);
402 402
 
403
-		$this->registerService(IRootFolder::class, function (Server $c) {
404
-			return new LazyRoot(function () use ($c) {
403
+		$this->registerService(IRootFolder::class, function(Server $c) {
404
+			return new LazyRoot(function() use ($c) {
405 405
 				return $c->query('RootFolder');
406 406
 			});
407 407
 		});
@@ -412,44 +412,44 @@  discard block
 block discarded – undo
412 412
 		$this->registerDeprecatedAlias('UserManager', \OC\User\Manager::class);
413 413
 		$this->registerAlias(\OCP\IUserManager::class, \OC\User\Manager::class);
414 414
 
415
-		$this->registerService(\OCP\IGroupManager::class, function (Server $c) {
415
+		$this->registerService(\OCP\IGroupManager::class, function(Server $c) {
416 416
 			$groupManager = new \OC\Group\Manager($this->getUserManager(), $c->getEventDispatcher(), $this->getLogger());
417
-			$groupManager->listen('\OC\Group', 'preCreate', function ($gid) {
417
+			$groupManager->listen('\OC\Group', 'preCreate', function($gid) {
418 418
 				\OC_Hook::emit('OC_Group', 'pre_createGroup', ['run' => true, 'gid' => $gid]);
419 419
 
420 420
 				/** @var IEventDispatcher $dispatcher */
421 421
 				$dispatcher = $this->query(IEventDispatcher::class);
422 422
 				$dispatcher->dispatchTyped(new BeforeGroupCreatedEvent($gid));
423 423
 			});
424
-			$groupManager->listen('\OC\Group', 'postCreate', function (\OC\Group\Group $group) {
424
+			$groupManager->listen('\OC\Group', 'postCreate', function(\OC\Group\Group $group) {
425 425
 				\OC_Hook::emit('OC_User', 'post_createGroup', ['gid' => $group->getGID()]);
426 426
 
427 427
 				/** @var IEventDispatcher $dispatcher */
428 428
 				$dispatcher = $this->query(IEventDispatcher::class);
429 429
 				$dispatcher->dispatchTyped(new GroupCreatedEvent($group));
430 430
 			});
431
-			$groupManager->listen('\OC\Group', 'preDelete', function (\OC\Group\Group $group) {
431
+			$groupManager->listen('\OC\Group', 'preDelete', function(\OC\Group\Group $group) {
432 432
 				\OC_Hook::emit('OC_Group', 'pre_deleteGroup', ['run' => true, 'gid' => $group->getGID()]);
433 433
 
434 434
 				/** @var IEventDispatcher $dispatcher */
435 435
 				$dispatcher = $this->query(IEventDispatcher::class);
436 436
 				$dispatcher->dispatchTyped(new BeforeGroupDeletedEvent($group));
437 437
 			});
438
-			$groupManager->listen('\OC\Group', 'postDelete', function (\OC\Group\Group $group) {
438
+			$groupManager->listen('\OC\Group', 'postDelete', function(\OC\Group\Group $group) {
439 439
 				\OC_Hook::emit('OC_User', 'post_deleteGroup', ['gid' => $group->getGID()]);
440 440
 
441 441
 				/** @var IEventDispatcher $dispatcher */
442 442
 				$dispatcher = $this->query(IEventDispatcher::class);
443 443
 				$dispatcher->dispatchTyped(new GroupDeletedEvent($group));
444 444
 			});
445
-			$groupManager->listen('\OC\Group', 'preAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
445
+			$groupManager->listen('\OC\Group', 'preAddUser', function(\OC\Group\Group $group, \OC\User\User $user) {
446 446
 				\OC_Hook::emit('OC_Group', 'pre_addToGroup', ['run' => true, 'uid' => $user->getUID(), 'gid' => $group->getGID()]);
447 447
 
448 448
 				/** @var IEventDispatcher $dispatcher */
449 449
 				$dispatcher = $this->query(IEventDispatcher::class);
450 450
 				$dispatcher->dispatchTyped(new BeforeUserAddedEvent($group, $user));
451 451
 			});
452
-			$groupManager->listen('\OC\Group', 'postAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
452
+			$groupManager->listen('\OC\Group', 'postAddUser', function(\OC\Group\Group $group, \OC\User\User $user) {
453 453
 				\OC_Hook::emit('OC_Group', 'post_addToGroup', ['uid' => $user->getUID(), 'gid' => $group->getGID()]);
454 454
 				//Minimal fix to keep it backward compatible TODO: clean up all the GroupManager hooks
455 455
 				\OC_Hook::emit('OC_User', 'post_addToGroup', ['uid' => $user->getUID(), 'gid' => $group->getGID()]);
@@ -458,12 +458,12 @@  discard block
 block discarded – undo
458 458
 				$dispatcher = $this->query(IEventDispatcher::class);
459 459
 				$dispatcher->dispatchTyped(new UserAddedEvent($group, $user));
460 460
 			});
461
-			$groupManager->listen('\OC\Group', 'preRemoveUser', function (\OC\Group\Group $group, \OC\User\User $user) {
461
+			$groupManager->listen('\OC\Group', 'preRemoveUser', function(\OC\Group\Group $group, \OC\User\User $user) {
462 462
 				/** @var IEventDispatcher $dispatcher */
463 463
 				$dispatcher = $this->query(IEventDispatcher::class);
464 464
 				$dispatcher->dispatchTyped(new BeforeUserRemovedEvent($group, $user));
465 465
 			});
466
-			$groupManager->listen('\OC\Group', 'postRemoveUser', function (\OC\Group\Group $group, \OC\User\User $user) {
466
+			$groupManager->listen('\OC\Group', 'postRemoveUser', function(\OC\Group\Group $group, \OC\User\User $user) {
467 467
 				/** @var IEventDispatcher $dispatcher */
468 468
 				$dispatcher = $this->query(IEventDispatcher::class);
469 469
 				$dispatcher->dispatchTyped(new UserRemovedEvent($group, $user));
@@ -473,7 +473,7 @@  discard block
 block discarded – undo
473 473
 		/** @deprecated 19.0.0 */
474 474
 		$this->registerDeprecatedAlias('GroupManager', \OCP\IGroupManager::class);
475 475
 
476
-		$this->registerService(Store::class, function (Server $c) {
476
+		$this->registerService(Store::class, function(Server $c) {
477 477
 			$session = $c->getSession();
478 478
 			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
479 479
 				$tokenProvider = $c->query(IProvider::class);
@@ -486,7 +486,7 @@  discard block
 block discarded – undo
486 486
 		$this->registerAlias(IStore::class, Store::class);
487 487
 		$this->registerAlias(IProvider::class, Authentication\Token\Manager::class);
488 488
 
489
-		$this->registerService(\OC\User\Session::class, function (Server $c) {
489
+		$this->registerService(\OC\User\Session::class, function(Server $c) {
490 490
 			$manager = $c->getUserManager();
491 491
 			$session = new \OC\Session\Memory('');
492 492
 			$timeFactory = new TimeFactory();
@@ -511,14 +511,14 @@  discard block
 block discarded – undo
511 511
 				$c->getLogger(),
512 512
 				$c->query(IEventDispatcher::class)
513 513
 			);
514
-			$userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
514
+			$userSession->listen('\OC\User', 'preCreateUser', function($uid, $password) {
515 515
 				\OC_Hook::emit('OC_User', 'pre_createUser', ['run' => true, 'uid' => $uid, 'password' => $password]);
516 516
 
517 517
 				/** @var IEventDispatcher $dispatcher */
518 518
 				$dispatcher = $this->query(IEventDispatcher::class);
519 519
 				$dispatcher->dispatchTyped(new BeforeUserCreatedEvent($uid, $password));
520 520
 			});
521
-			$userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
521
+			$userSession->listen('\OC\User', 'postCreateUser', function($user, $password) {
522 522
 				/** @var \OC\User\User $user */
523 523
 				\OC_Hook::emit('OC_User', 'post_createUser', ['uid' => $user->getUID(), 'password' => $password]);
524 524
 
@@ -526,7 +526,7 @@  discard block
 block discarded – undo
526 526
 				$dispatcher = $this->query(IEventDispatcher::class);
527 527
 				$dispatcher->dispatchTyped(new UserCreatedEvent($user, $password));
528 528
 			});
529
-			$userSession->listen('\OC\User', 'preDelete', function ($user) use ($legacyDispatcher) {
529
+			$userSession->listen('\OC\User', 'preDelete', function($user) use ($legacyDispatcher) {
530 530
 				/** @var \OC\User\User $user */
531 531
 				\OC_Hook::emit('OC_User', 'pre_deleteUser', ['run' => true, 'uid' => $user->getUID()]);
532 532
 				$legacyDispatcher->dispatch('OCP\IUser::preDelete', new GenericEvent($user));
@@ -535,7 +535,7 @@  discard block
 block discarded – undo
535 535
 				$dispatcher = $this->query(IEventDispatcher::class);
536 536
 				$dispatcher->dispatchTyped(new BeforeUserDeletedEvent($user));
537 537
 			});
538
-			$userSession->listen('\OC\User', 'postDelete', function ($user) {
538
+			$userSession->listen('\OC\User', 'postDelete', function($user) {
539 539
 				/** @var \OC\User\User $user */
540 540
 				\OC_Hook::emit('OC_User', 'post_deleteUser', ['uid' => $user->getUID()]);
541 541
 
@@ -543,7 +543,7 @@  discard block
 block discarded – undo
543 543
 				$dispatcher = $this->query(IEventDispatcher::class);
544 544
 				$dispatcher->dispatchTyped(new UserDeletedEvent($user));
545 545
 			});
546
-			$userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
546
+			$userSession->listen('\OC\User', 'preSetPassword', function($user, $password, $recoveryPassword) {
547 547
 				/** @var \OC\User\User $user */
548 548
 				\OC_Hook::emit('OC_User', 'pre_setPassword', ['run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword]);
549 549
 
@@ -551,7 +551,7 @@  discard block
 block discarded – undo
551 551
 				$dispatcher = $this->query(IEventDispatcher::class);
552 552
 				$dispatcher->dispatchTyped(new BeforePasswordUpdatedEvent($user, $password, $recoveryPassword));
553 553
 			});
554
-			$userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
554
+			$userSession->listen('\OC\User', 'postSetPassword', function($user, $password, $recoveryPassword) {
555 555
 				/** @var \OC\User\User $user */
556 556
 				\OC_Hook::emit('OC_User', 'post_setPassword', ['run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword]);
557 557
 
@@ -559,14 +559,14 @@  discard block
 block discarded – undo
559 559
 				$dispatcher = $this->query(IEventDispatcher::class);
560 560
 				$dispatcher->dispatchTyped(new PasswordUpdatedEvent($user, $password, $recoveryPassword));
561 561
 			});
562
-			$userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
562
+			$userSession->listen('\OC\User', 'preLogin', function($uid, $password) {
563 563
 				\OC_Hook::emit('OC_User', 'pre_login', ['run' => true, 'uid' => $uid, 'password' => $password]);
564 564
 
565 565
 				/** @var IEventDispatcher $dispatcher */
566 566
 				$dispatcher = $this->query(IEventDispatcher::class);
567 567
 				$dispatcher->dispatchTyped(new BeforeUserLoggedInEvent($uid, $password));
568 568
 			});
569
-			$userSession->listen('\OC\User', 'postLogin', function ($user, $password, $isTokenLogin) {
569
+			$userSession->listen('\OC\User', 'postLogin', function($user, $password, $isTokenLogin) {
570 570
 				/** @var \OC\User\User $user */
571 571
 				\OC_Hook::emit('OC_User', 'post_login', ['run' => true, 'uid' => $user->getUID(), 'password' => $password, 'isTokenLogin' => $isTokenLogin]);
572 572
 
@@ -574,12 +574,12 @@  discard block
 block discarded – undo
574 574
 				$dispatcher = $this->query(IEventDispatcher::class);
575 575
 				$dispatcher->dispatchTyped(new UserLoggedInEvent($user, $password, $isTokenLogin));
576 576
 			});
577
-			$userSession->listen('\OC\User', 'preRememberedLogin', function ($uid) {
577
+			$userSession->listen('\OC\User', 'preRememberedLogin', function($uid) {
578 578
 				/** @var IEventDispatcher $dispatcher */
579 579
 				$dispatcher = $this->query(IEventDispatcher::class);
580 580
 				$dispatcher->dispatchTyped(new BeforeUserLoggedInWithCookieEvent($uid));
581 581
 			});
582
-			$userSession->listen('\OC\User', 'postRememberedLogin', function ($user, $password) {
582
+			$userSession->listen('\OC\User', 'postRememberedLogin', function($user, $password) {
583 583
 				/** @var \OC\User\User $user */
584 584
 				\OC_Hook::emit('OC_User', 'post_login', ['run' => true, 'uid' => $user->getUID(), 'password' => $password]);
585 585
 
@@ -587,19 +587,19 @@  discard block
 block discarded – undo
587 587
 				$dispatcher = $this->query(IEventDispatcher::class);
588 588
 				$dispatcher->dispatchTyped(new UserLoggedInWithCookieEvent($user, $password));
589 589
 			});
590
-			$userSession->listen('\OC\User', 'logout', function ($user) {
590
+			$userSession->listen('\OC\User', 'logout', function($user) {
591 591
 				\OC_Hook::emit('OC_User', 'logout', []);
592 592
 
593 593
 				/** @var IEventDispatcher $dispatcher */
594 594
 				$dispatcher = $this->query(IEventDispatcher::class);
595 595
 				$dispatcher->dispatchTyped(new BeforeUserLoggedOutEvent($user));
596 596
 			});
597
-			$userSession->listen('\OC\User', 'postLogout', function ($user) {
597
+			$userSession->listen('\OC\User', 'postLogout', function($user) {
598 598
 				/** @var IEventDispatcher $dispatcher */
599 599
 				$dispatcher = $this->query(IEventDispatcher::class);
600 600
 				$dispatcher->dispatchTyped(new UserLoggedOutEvent($user));
601 601
 			});
602
-			$userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value, $oldValue) {
602
+			$userSession->listen('\OC\User', 'changeUser', function($user, $feature, $value, $oldValue) {
603 603
 				/** @var \OC\User\User $user */
604 604
 				\OC_Hook::emit('OC_User', 'changeUser', ['run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value, 'old_value' => $oldValue]);
605 605
 
@@ -623,7 +623,7 @@  discard block
 block discarded – undo
623 623
 		$this->registerDeprecatedAlias('AllConfig', \OC\AllConfig::class);
624 624
 		$this->registerAlias(\OCP\IConfig::class, \OC\AllConfig::class);
625 625
 
626
-		$this->registerService(\OC\SystemConfig::class, function ($c) use ($config) {
626
+		$this->registerService(\OC\SystemConfig::class, function($c) use ($config) {
627 627
 			return new \OC\SystemConfig($config);
628 628
 		});
629 629
 		/** @deprecated 19.0.0 */
@@ -633,7 +633,7 @@  discard block
 block discarded – undo
633 633
 		$this->registerDeprecatedAlias('AppConfig', \OC\AppConfig::class);
634 634
 		$this->registerAlias(IAppConfig::class, \OC\AppConfig::class);
635 635
 
636
-		$this->registerService(IFactory::class, function (Server $c) {
636
+		$this->registerService(IFactory::class, function(Server $c) {
637 637
 			return new \OC\L10N\Factory(
638 638
 				$c->getConfig(),
639 639
 				$c->getRequest(),
@@ -653,13 +653,13 @@  discard block
 block discarded – undo
653 653
 		/** @deprecated 19.0.0 */
654 654
 		$this->registerDeprecatedAlias('CategoryFetcher', CategoryFetcher::class);
655 655
 
656
-		$this->registerService(ICache::class, function ($c) {
656
+		$this->registerService(ICache::class, function($c) {
657 657
 			return new Cache\File();
658 658
 		});
659 659
 		/** @deprecated 19.0.0 */
660 660
 		$this->registerDeprecatedAlias('UserCache', ICache::class);
661 661
 
662
-		$this->registerService(Factory::class, function (Server $c) {
662
+		$this->registerService(Factory::class, function(Server $c) {
663 663
 			$arrayCacheFactory = new \OC\Memcache\Factory('', $c->getLogger(),
664 664
 				ArrayCache::class,
665 665
 				ArrayCache::class,
@@ -673,7 +673,7 @@  discard block
 block discarded – undo
673 673
 				$version = implode(',', $v);
674 674
 				$instanceId = \OC_Util::getInstanceId();
675 675
 				$path = \OC::$SERVERROOT;
676
-				$prefix = md5($instanceId . '-' . $version . '-' . $path);
676
+				$prefix = md5($instanceId.'-'.$version.'-'.$path);
677 677
 				return new \OC\Memcache\Factory($prefix, $c->getLogger(),
678 678
 					$config->getSystemValue('memcache.local', null),
679 679
 					$config->getSystemValue('memcache.distributed', null),
@@ -686,12 +686,12 @@  discard block
 block discarded – undo
686 686
 		$this->registerDeprecatedAlias('MemCacheFactory', Factory::class);
687 687
 		$this->registerAlias(ICacheFactory::class, Factory::class);
688 688
 
689
-		$this->registerService('RedisFactory', function (Server $c) {
689
+		$this->registerService('RedisFactory', function(Server $c) {
690 690
 			$systemConfig = $c->getSystemConfig();
691 691
 			return new RedisFactory($systemConfig);
692 692
 		});
693 693
 
694
-		$this->registerService(\OCP\Activity\IManager::class, function (Server $c) {
694
+		$this->registerService(\OCP\Activity\IManager::class, function(Server $c) {
695 695
 			$l10n = $this->get(IFactory::class)->get('activity');
696 696
 			return new \OC\Activity\Manager(
697 697
 				$c->getRequest(),
@@ -704,14 +704,14 @@  discard block
 block discarded – undo
704 704
 		/** @deprecated 19.0.0 */
705 705
 		$this->registerDeprecatedAlias('ActivityManager', \OCP\Activity\IManager::class);
706 706
 
707
-		$this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
707
+		$this->registerService(\OCP\Activity\IEventMerger::class, function(Server $c) {
708 708
 			return new \OC\Activity\EventMerger(
709 709
 				$c->getL10N('lib')
710 710
 			);
711 711
 		});
712 712
 		$this->registerAlias(IValidator::class, Validator::class);
713 713
 
714
-		$this->registerService(AvatarManager::class, function (Server $c) {
714
+		$this->registerService(AvatarManager::class, function(Server $c) {
715 715
 			return new AvatarManager(
716 716
 				$c->query(\OC\User\Manager::class),
717 717
 				$c->getAppDataDir('avatar'),
@@ -727,7 +727,7 @@  discard block
 block discarded – undo
727 727
 		$this->registerAlias(\OCP\Support\CrashReport\IRegistry::class, \OC\Support\CrashReport\Registry::class);
728 728
 		$this->registerAlias(\OCP\Support\Subscription\IRegistry::class, \OC\Support\Subscription\Registry::class);
729 729
 
730
-		$this->registerService(\OC\Log::class, function (Server $c) {
730
+		$this->registerService(\OC\Log::class, function(Server $c) {
731 731
 			$logType = $c->query(AllConfig::class)->getSystemValue('log_type', 'file');
732 732
 			$factory = new LogFactory($c, $this->getSystemConfig());
733 733
 			$logger = $factory->get($logType);
@@ -741,7 +741,7 @@  discard block
 block discarded – undo
741 741
 		// PSR-3 logger
742 742
 		$this->registerAlias(LoggerInterface::class, PsrLoggerAdapter::class);
743 743
 
744
-		$this->registerService(ILogFactory::class, function (Server $c) {
744
+		$this->registerService(ILogFactory::class, function(Server $c) {
745 745
 			return new LogFactory($c, $this->getSystemConfig());
746 746
 		});
747 747
 
@@ -749,7 +749,7 @@  discard block
 block discarded – undo
749 749
 		/** @deprecated 19.0.0 */
750 750
 		$this->registerDeprecatedAlias('JobList', IJobList::class);
751 751
 
752
-		$this->registerService(IRouter::class, function (Server $c) {
752
+		$this->registerService(IRouter::class, function(Server $c) {
753 753
 			$cacheFactory = $c->getMemCacheFactory();
754 754
 			$logger = $c->getLogger();
755 755
 			if ($cacheFactory->isLocalCacheAvailable()) {
@@ -766,7 +766,7 @@  discard block
 block discarded – undo
766 766
 		/** @deprecated 19.0.0 */
767 767
 		$this->registerDeprecatedAlias('Search', ISearch::class);
768 768
 
769
-		$this->registerService(\OC\Security\RateLimiting\Backend\IBackend::class, function ($c) {
769
+		$this->registerService(\OC\Security\RateLimiting\Backend\IBackend::class, function($c) {
770 770
 			return new \OC\Security\RateLimiting\Backend\MemoryCache(
771 771
 				$this->getMemCacheFactory(),
772 772
 				new \OC\AppFramework\Utility\TimeFactory()
@@ -789,7 +789,7 @@  discard block
 block discarded – undo
789 789
 		/** @deprecated 19.0.0 */
790 790
 		$this->registerDeprecatedAlias('CredentialsManager', ICredentialsManager::class);
791 791
 
792
-		$this->registerService(IDBConnection::class, function (Server $c) {
792
+		$this->registerService(IDBConnection::class, function(Server $c) {
793 793
 			$systemConfig = $c->getSystemConfig();
794 794
 			$factory = new \OC\DB\ConnectionFactory($systemConfig);
795 795
 			$type = $systemConfig->getValue('dbtype', 'sqlite');
@@ -805,7 +805,7 @@  discard block
 block discarded – undo
805 805
 		$this->registerDeprecatedAlias('DatabaseConnection', IDBConnection::class);
806 806
 
807 807
 
808
-		$this->registerService(IClientService::class, function (Server $c) {
808
+		$this->registerService(IClientService::class, function(Server $c) {
809 809
 			$user = \OC_User::getUser();
810 810
 			$uid = $user ? $user : null;
811 811
 			return new ClientService(
@@ -822,7 +822,7 @@  discard block
 block discarded – undo
822 822
 		});
823 823
 		/** @deprecated 19.0.0 */
824 824
 		$this->registerDeprecatedAlias('HttpClientService', IClientService::class);
825
-		$this->registerService(IEventLogger::class, function (Server $c) {
825
+		$this->registerService(IEventLogger::class, function(Server $c) {
826 826
 			$eventLogger = new EventLogger();
827 827
 			if ($c->getSystemConfig()->getValue('debug', false)) {
828 828
 				// In debug mode, module is being activated by default
@@ -833,7 +833,7 @@  discard block
 block discarded – undo
833 833
 		/** @deprecated 19.0.0 */
834 834
 		$this->registerDeprecatedAlias('EventLogger', IEventLogger::class);
835 835
 
836
-		$this->registerService(IQueryLogger::class, function (Server $c) {
836
+		$this->registerService(IQueryLogger::class, function(Server $c) {
837 837
 			$queryLogger = new QueryLogger();
838 838
 			if ($c->getSystemConfig()->getValue('debug', false)) {
839 839
 				// In debug mode, module is being activated by default
@@ -848,7 +848,7 @@  discard block
 block discarded – undo
848 848
 		$this->registerDeprecatedAlias('TempManager', TempManager::class);
849 849
 		$this->registerAlias(ITempManager::class, TempManager::class);
850 850
 
851
-		$this->registerService(AppManager::class, function (Server $c) {
851
+		$this->registerService(AppManager::class, function(Server $c) {
852 852
 			return new \OC\App\AppManager(
853 853
 				$c->getUserSession(),
854 854
 				$c->getConfig(),
@@ -867,7 +867,7 @@  discard block
 block discarded – undo
867 867
 		/** @deprecated 19.0.0 */
868 868
 		$this->registerDeprecatedAlias('DateTimeZone', IDateTimeZone::class);
869 869
 
870
-		$this->registerService(IDateTimeFormatter::class, function (Server $c) {
870
+		$this->registerService(IDateTimeFormatter::class, function(Server $c) {
871 871
 			$language = $c->getConfig()->getUserValue($c->getSession()->get('user_id'), 'core', 'lang', null);
872 872
 
873 873
 			return new DateTimeFormatter(
@@ -878,7 +878,7 @@  discard block
 block discarded – undo
878 878
 		/** @deprecated 19.0.0 */
879 879
 		$this->registerDeprecatedAlias('DateTimeFormatter', IDateTimeFormatter::class);
880 880
 
881
-		$this->registerService(IUserMountCache::class, function (Server $c) {
881
+		$this->registerService(IUserMountCache::class, function(Server $c) {
882 882
 			$mountCache = new UserMountCache($c->getDatabaseConnection(), $c->getUserManager(), $c->getLogger());
883 883
 			$listener = new UserMountCacheListener($mountCache);
884 884
 			$listener->listen($c->getUserManager());
@@ -887,7 +887,7 @@  discard block
 block discarded – undo
887 887
 		/** @deprecated 19.0.0 */
888 888
 		$this->registerDeprecatedAlias('UserMountCache', IUserMountCache::class);
889 889
 
890
-		$this->registerService(IMountProviderCollection::class, function (Server $c) {
890
+		$this->registerService(IMountProviderCollection::class, function(Server $c) {
891 891
 			$loader = \OC\Files\Filesystem::getLoader();
892 892
 			$mountCache = $c->query(IUserMountCache::class);
893 893
 			$manager = new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
@@ -908,7 +908,7 @@  discard block
 block discarded – undo
908 908
 
909 909
 		/** @deprecated 20.0.0 */
910 910
 		$this->registerDeprecatedAlias('IniWrapper', IniGetWrapper::class);
911
-		$this->registerService('AsyncCommandBus', function (Server $c) {
911
+		$this->registerService('AsyncCommandBus', function(Server $c) {
912 912
 			$busClass = $c->getConfig()->getSystemValue('commandbus');
913 913
 			if ($busClass) {
914 914
 				[$app, $class] = explode('::', $busClass, 2);
@@ -928,7 +928,7 @@  discard block
 block discarded – undo
928 928
 		$this->registerDeprecatedAlias('TrustedDomainHelper', TrustedDomainHelper::class);
929 929
 		/** @deprecated 19.0.0 */
930 930
 		$this->registerDeprecatedAlias('Throttler', Throttler::class);
931
-		$this->registerService('IntegrityCodeChecker', function (Server $c) {
931
+		$this->registerService('IntegrityCodeChecker', function(Server $c) {
932 932
 			// IConfig and IAppManager requires a working database. This code
933 933
 			// might however be called when ownCloud is not yet setup.
934 934
 			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
@@ -950,7 +950,7 @@  discard block
 block discarded – undo
950 950
 				$c->getMimeTypeDetector()
951 951
 			);
952 952
 		});
953
-		$this->registerService(\OCP\IRequest::class, function ($c) {
953
+		$this->registerService(\OCP\IRequest::class, function($c) {
954 954
 			if (isset($this['urlParams'])) {
955 955
 				$urlParams = $this['urlParams'];
956 956
 			} else {
@@ -987,7 +987,7 @@  discard block
 block discarded – undo
987 987
 		/** @deprecated 19.0.0 */
988 988
 		$this->registerDeprecatedAlias('Request', \OCP\IRequest::class);
989 989
 
990
-		$this->registerService(IMailer::class, function (Server $c) {
990
+		$this->registerService(IMailer::class, function(Server $c) {
991 991
 			return new Mailer(
992 992
 				$c->getConfig(),
993 993
 				$c->getLogger(),
@@ -1001,7 +1001,7 @@  discard block
 block discarded – undo
1001 1001
 		/** @deprecated 19.0.0 */
1002 1002
 		$this->registerDeprecatedAlias('Mailer', IMailer::class);
1003 1003
 
1004
-		$this->registerService('LDAPProvider', function (Server $c) {
1004
+		$this->registerService('LDAPProvider', function(Server $c) {
1005 1005
 			$config = $c->getConfig();
1006 1006
 			$factoryClass = $config->getSystemValue('ldapProviderFactory', null);
1007 1007
 			if (is_null($factoryClass)) {
@@ -1011,7 +1011,7 @@  discard block
 block discarded – undo
1011 1011
 			$factory = new $factoryClass($this);
1012 1012
 			return $factory->getLDAPProvider();
1013 1013
 		});
1014
-		$this->registerService(ILockingProvider::class, function (Server $c) {
1014
+		$this->registerService(ILockingProvider::class, function(Server $c) {
1015 1015
 			$ini = $c->get(IniGetWrapper::class);
1016 1016
 			$config = $c->getConfig();
1017 1017
 			$ttl = $config->getSystemValue('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
@@ -1039,12 +1039,12 @@  discard block
 block discarded – undo
1039 1039
 		/** @deprecated 19.0.0 */
1040 1040
 		$this->registerDeprecatedAlias('MountManager', IMountManager::class);
1041 1041
 
1042
-		$this->registerService(IMimeTypeDetector::class, function (Server $c) {
1042
+		$this->registerService(IMimeTypeDetector::class, function(Server $c) {
1043 1043
 			return new \OC\Files\Type\Detection(
1044 1044
 				$c->getURLGenerator(),
1045 1045
 				$c->getLogger(),
1046 1046
 				\OC::$configDir,
1047
-				\OC::$SERVERROOT . '/resources/config/'
1047
+				\OC::$SERVERROOT.'/resources/config/'
1048 1048
 			);
1049 1049
 		});
1050 1050
 		/** @deprecated 19.0.0 */
@@ -1053,19 +1053,19 @@  discard block
 block discarded – undo
1053 1053
 		$this->registerAlias(IMimeTypeLoader::class, Loader::class);
1054 1054
 		/** @deprecated 19.0.0 */
1055 1055
 		$this->registerDeprecatedAlias('MimeTypeLoader', IMimeTypeLoader::class);
1056
-		$this->registerService(BundleFetcher::class, function () {
1056
+		$this->registerService(BundleFetcher::class, function() {
1057 1057
 			return new BundleFetcher($this->getL10N('lib'));
1058 1058
 		});
1059 1059
 		$this->registerAlias(\OCP\Notification\IManager::class, Manager::class);
1060 1060
 		/** @deprecated 19.0.0 */
1061 1061
 		$this->registerDeprecatedAlias('NotificationManager', \OCP\Notification\IManager::class);
1062 1062
 
1063
-		$this->registerService(CapabilitiesManager::class, function (Server $c) {
1063
+		$this->registerService(CapabilitiesManager::class, function(Server $c) {
1064 1064
 			$manager = new CapabilitiesManager($c->getLogger());
1065
-			$manager->registerCapability(function () use ($c) {
1065
+			$manager->registerCapability(function() use ($c) {
1066 1066
 				return new \OC\OCS\CoreCapabilities($c->getConfig());
1067 1067
 			});
1068
-			$manager->registerCapability(function () use ($c) {
1068
+			$manager->registerCapability(function() use ($c) {
1069 1069
 				return $c->query(\OC\Security\Bruteforce\Capabilities::class);
1070 1070
 			});
1071 1071
 			return $manager;
@@ -1073,14 +1073,14 @@  discard block
 block discarded – undo
1073 1073
 		/** @deprecated 19.0.0 */
1074 1074
 		$this->registerDeprecatedAlias('CapabilitiesManager', CapabilitiesManager::class);
1075 1075
 
1076
-		$this->registerService(ICommentsManager::class, function (Server $c) {
1076
+		$this->registerService(ICommentsManager::class, function(Server $c) {
1077 1077
 			$config = $c->getConfig();
1078 1078
 			$factoryClass = $config->getSystemValue('comments.managerFactory', CommentsManagerFactory::class);
1079 1079
 			/** @var \OCP\Comments\ICommentsManagerFactory $factory */
1080 1080
 			$factory = new $factoryClass($this);
1081 1081
 			$manager = $factory->getManager();
1082 1082
 
1083
-			$manager->registerDisplayNameResolver('user', function ($id) use ($c) {
1083
+			$manager->registerDisplayNameResolver('user', function($id) use ($c) {
1084 1084
 				$manager = $c->getUserManager();
1085 1085
 				$user = $manager->get($id);
1086 1086
 				if (is_null($user)) {
@@ -1098,7 +1098,7 @@  discard block
 block discarded – undo
1098 1098
 		$this->registerDeprecatedAlias('CommentsManager', ICommentsManager::class);
1099 1099
 
1100 1100
 		$this->registerAlias(\OC_Defaults::class, 'ThemingDefaults');
1101
-		$this->registerService('ThemingDefaults', function (Server $c) {
1101
+		$this->registerService('ThemingDefaults', function(Server $c) {
1102 1102
 			/*
1103 1103
 			 * Dark magic for autoloader.
1104 1104
 			 * If we do a class_exists it will try to load the class which will
@@ -1126,7 +1126,7 @@  discard block
 block discarded – undo
1126 1126
 			}
1127 1127
 			return new \OC_Defaults();
1128 1128
 		});
1129
-		$this->registerService(JSCombiner::class, function (Server $c) {
1129
+		$this->registerService(JSCombiner::class, function(Server $c) {
1130 1130
 			return new JSCombiner(
1131 1131
 				$c->getAppDataDir('js'),
1132 1132
 				$c->getURLGenerator(),
@@ -1140,7 +1140,7 @@  discard block
 block discarded – undo
1140 1140
 		$this->registerDeprecatedAlias('EventDispatcher', \OC\EventDispatcher\SymfonyAdapter::class);
1141 1141
 		$this->registerAlias(EventDispatcherInterface::class, \OC\EventDispatcher\SymfonyAdapter::class);
1142 1142
 
1143
-		$this->registerService('CryptoWrapper', function (Server $c) {
1143
+		$this->registerService('CryptoWrapper', function(Server $c) {
1144 1144
 			// FIXME: Instantiiated here due to cyclic dependency
1145 1145
 			$request = new Request(
1146 1146
 				[
@@ -1167,14 +1167,14 @@  discard block
 block discarded – undo
1167 1167
 		});
1168 1168
 		/** @deprecated 19.0.0 */
1169 1169
 		$this->registerDeprecatedAlias('CsrfTokenManager', CsrfTokenManager::class);
1170
-		$this->registerService(SessionStorage::class, function (Server $c) {
1170
+		$this->registerService(SessionStorage::class, function(Server $c) {
1171 1171
 			return new SessionStorage($c->getSession());
1172 1172
 		});
1173 1173
 		$this->registerAlias(\OCP\Security\IContentSecurityPolicyManager::class, ContentSecurityPolicyManager::class);
1174 1174
 		/** @deprecated 19.0.0 */
1175 1175
 		$this->registerDeprecatedAlias('ContentSecurityPolicyManager', ContentSecurityPolicyManager::class);
1176 1176
 
1177
-		$this->registerService(\OCP\Share\IManager::class, function (Server $c) {
1177
+		$this->registerService(\OCP\Share\IManager::class, function(Server $c) {
1178 1178
 			$config = $c->getConfig();
1179 1179
 			$factoryClass = $config->getSystemValue('sharing.managerFactory', ProviderFactory::class);
1180 1180
 			/** @var \OCP\Share\IProviderFactory $factory */
@@ -1204,7 +1204,7 @@  discard block
 block discarded – undo
1204 1204
 		/** @deprecated 19.0.0 */
1205 1205
 		$this->registerDeprecatedAlias('ShareManager', \OCP\Share\IManager::class);
1206 1206
 
1207
-		$this->registerService(\OCP\Collaboration\Collaborators\ISearch::class, function (Server $c) {
1207
+		$this->registerService(\OCP\Collaboration\Collaborators\ISearch::class, function(Server $c) {
1208 1208
 			$instance = new Collaboration\Collaborators\Search($c);
1209 1209
 
1210 1210
 			// register default plugins
@@ -1225,7 +1225,7 @@  discard block
 block discarded – undo
1225 1225
 		$this->registerAlias(\OCP\Collaboration\Resources\IProviderManager::class, \OC\Collaboration\Resources\ProviderManager::class);
1226 1226
 		$this->registerAlias(\OCP\Collaboration\Resources\IManager::class, \OC\Collaboration\Resources\Manager::class);
1227 1227
 
1228
-		$this->registerService('SettingsManager', function (Server $c) {
1228
+		$this->registerService('SettingsManager', function(Server $c) {
1229 1229
 			$manager = new \OC\Settings\Manager(
1230 1230
 				$c->getLogger(),
1231 1231
 				$c->getL10NFactory(),
@@ -1234,34 +1234,34 @@  discard block
 block discarded – undo
1234 1234
 			);
1235 1235
 			return $manager;
1236 1236
 		});
1237
-		$this->registerService(\OC\Files\AppData\Factory::class, function (Server $c) {
1237
+		$this->registerService(\OC\Files\AppData\Factory::class, function(Server $c) {
1238 1238
 			return new \OC\Files\AppData\Factory(
1239 1239
 				$c->getRootFolder(),
1240 1240
 				$c->getSystemConfig()
1241 1241
 			);
1242 1242
 		});
1243 1243
 
1244
-		$this->registerService('LockdownManager', function (Server $c) {
1245
-			return new LockdownManager(function () use ($c) {
1244
+		$this->registerService('LockdownManager', function(Server $c) {
1245
+			return new LockdownManager(function() use ($c) {
1246 1246
 				return $c->getSession();
1247 1247
 			});
1248 1248
 		});
1249 1249
 
1250
-		$this->registerService(\OCP\OCS\IDiscoveryService::class, function (Server $c) {
1250
+		$this->registerService(\OCP\OCS\IDiscoveryService::class, function(Server $c) {
1251 1251
 			return new DiscoveryService($c->getMemCacheFactory(), $c->getHTTPClientService());
1252 1252
 		});
1253 1253
 
1254
-		$this->registerService(ICloudIdManager::class, function (Server $c) {
1254
+		$this->registerService(ICloudIdManager::class, function(Server $c) {
1255 1255
 			return new CloudIdManager();
1256 1256
 		});
1257 1257
 
1258 1258
 		$this->registerAlias(\OCP\GlobalScale\IConfig::class, \OC\GlobalScale\Config::class);
1259 1259
 
1260
-		$this->registerService(ICloudFederationProviderManager::class, function (Server $c) {
1260
+		$this->registerService(ICloudFederationProviderManager::class, function(Server $c) {
1261 1261
 			return new CloudFederationProviderManager($c->getAppManager(), $c->getHTTPClientService(), $c->getCloudIdManager(), $c->getLogger());
1262 1262
 		});
1263 1263
 
1264
-		$this->registerService(ICloudFederationFactory::class, function (Server $c) {
1264
+		$this->registerService(ICloudFederationFactory::class, function(Server $c) {
1265 1265
 			return new CloudFederationFactory();
1266 1266
 		});
1267 1267
 
@@ -1273,7 +1273,7 @@  discard block
 block discarded – undo
1273 1273
 		/** @deprecated 19.0.0 */
1274 1274
 		$this->registerDeprecatedAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
1275 1275
 
1276
-		$this->registerService(Defaults::class, function (Server $c) {
1276
+		$this->registerService(Defaults::class, function(Server $c) {
1277 1277
 			return new Defaults(
1278 1278
 				$c->getThemingDefaults()
1279 1279
 			);
@@ -1281,17 +1281,17 @@  discard block
 block discarded – undo
1281 1281
 		/** @deprecated 19.0.0 */
1282 1282
 		$this->registerDeprecatedAlias('Defaults', \OCP\Defaults::class);
1283 1283
 
1284
-		$this->registerService(\OCP\ISession::class, function (SimpleContainer $c) {
1284
+		$this->registerService(\OCP\ISession::class, function(SimpleContainer $c) {
1285 1285
 			return $c->query(\OCP\IUserSession::class)->getSession();
1286 1286
 		});
1287 1287
 
1288
-		$this->registerService(IShareHelper::class, function (Server $c) {
1288
+		$this->registerService(IShareHelper::class, function(Server $c) {
1289 1289
 			return new ShareHelper(
1290 1290
 				$c->query(\OCP\Share\IManager::class)
1291 1291
 			);
1292 1292
 		});
1293 1293
 
1294
-		$this->registerService(Installer::class, function (Server $c) {
1294
+		$this->registerService(Installer::class, function(Server $c) {
1295 1295
 			return new Installer(
1296 1296
 				$c->getAppFetcher(),
1297 1297
 				$c->getHTTPClientService(),
@@ -1302,11 +1302,11 @@  discard block
 block discarded – undo
1302 1302
 			);
1303 1303
 		});
1304 1304
 
1305
-		$this->registerService(IApiFactory::class, function (Server $c) {
1305
+		$this->registerService(IApiFactory::class, function(Server $c) {
1306 1306
 			return new ApiFactory($c->getHTTPClientService());
1307 1307
 		});
1308 1308
 
1309
-		$this->registerService(IInstanceFactory::class, function (Server $c) {
1309
+		$this->registerService(IInstanceFactory::class, function(Server $c) {
1310 1310
 			$memcacheFactory = $c->getMemCacheFactory();
1311 1311
 			return new InstanceFactory($memcacheFactory->createLocal('remoteinstance.'), $c->getHTTPClientService());
1312 1312
 		});
@@ -1363,7 +1363,7 @@  discard block
 block discarded – undo
1363 1363
 		$dispatcher = $this->getEventDispatcher();
1364 1364
 
1365 1365
 		// Delete avatar on user deletion
1366
-		$dispatcher->addListener('OCP\IUser::preDelete', function (GenericEvent $e) {
1366
+		$dispatcher->addListener('OCP\IUser::preDelete', function(GenericEvent $e) {
1367 1367
 			$logger = $this->getLogger();
1368 1368
 			$manager = $this->getAvatarManager();
1369 1369
 			/** @var IUser $user */
@@ -1376,11 +1376,11 @@  discard block
 block discarded – undo
1376 1376
 				// no avatar to remove
1377 1377
 			} catch (\Exception $e) {
1378 1378
 				// Ignore exceptions
1379
-				$logger->info('Could not cleanup avatar of ' . $user->getUID());
1379
+				$logger->info('Could not cleanup avatar of '.$user->getUID());
1380 1380
 			}
1381 1381
 		});
1382 1382
 
1383
-		$dispatcher->addListener('OCP\IUser::changeUser', function (GenericEvent $e) {
1383
+		$dispatcher->addListener('OCP\IUser::changeUser', function(GenericEvent $e) {
1384 1384
 			$manager = $this->getAvatarManager();
1385 1385
 			/** @var IUser $user */
1386 1386
 			$user = $e->getSubject();
@@ -2285,11 +2285,11 @@  discard block
 block discarded – undo
2285 2285
 	}
2286 2286
 
2287 2287
 	private function registerDeprecatedAlias(string $alias, string $target) {
2288
-		$this->registerService($alias, function (ContainerInterface $container) use ($target, $alias) {
2288
+		$this->registerService($alias, function(ContainerInterface $container) use ($target, $alias) {
2289 2289
 			try {
2290 2290
 				/** @var ILogger $logger */
2291 2291
 				$logger = $container->get(ILogger::class);
2292
-				$logger->debug('The requested alias "' . $alias . '" is depreacted. Please request "' . $target . '" directly. This alias will be removed in a future Nextcloud version.', ['app' => 'serverDI']);
2292
+				$logger->debug('The requested alias "'.$alias.'" is depreacted. Please request "'.$target.'" directly. This alias will be removed in a future Nextcloud version.', ['app' => 'serverDI']);
2293 2293
 			} catch (ContainerExceptionInterface $e) {
2294 2294
 				// Could not get logger. Continue
2295 2295
 			}
Please login to merge, or discard this patch.
lib/private/legacy/OC_Helper.php 2 patches
Indentation   +548 added lines, -548 removed lines patch added patch discarded remove patch
@@ -51,552 +51,552 @@
 block discarded – undo
51 51
  * Collection of useful functions
52 52
  */
53 53
 class OC_Helper {
54
-	private static $templateManager;
55
-
56
-	/**
57
-	 * Make a human file size
58
-	 * @param int $bytes file size in bytes
59
-	 * @return string a human readable file size
60
-	 *
61
-	 * Makes 2048 to 2 kB.
62
-	 */
63
-	public static function humanFileSize($bytes) {
64
-		if ($bytes < 0) {
65
-			return "?";
66
-		}
67
-		if ($bytes < 1024) {
68
-			return "$bytes B";
69
-		}
70
-		$bytes = round($bytes / 1024, 0);
71
-		if ($bytes < 1024) {
72
-			return "$bytes KB";
73
-		}
74
-		$bytes = round($bytes / 1024, 1);
75
-		if ($bytes < 1024) {
76
-			return "$bytes MB";
77
-		}
78
-		$bytes = round($bytes / 1024, 1);
79
-		if ($bytes < 1024) {
80
-			return "$bytes GB";
81
-		}
82
-		$bytes = round($bytes / 1024, 1);
83
-		if ($bytes < 1024) {
84
-			return "$bytes TB";
85
-		}
86
-
87
-		$bytes = round($bytes / 1024, 1);
88
-		return "$bytes PB";
89
-	}
90
-
91
-	/**
92
-	 * Make a computer file size
93
-	 * @param string $str file size in human readable format
94
-	 * @return float|bool a file size in bytes
95
-	 *
96
-	 * Makes 2kB to 2048.
97
-	 *
98
-	 * Inspired by: http://www.php.net/manual/en/function.filesize.php#92418
99
-	 */
100
-	public static function computerFileSize($str) {
101
-		$str = strtolower($str);
102
-		if (is_numeric($str)) {
103
-			return (float)$str;
104
-		}
105
-
106
-		$bytes_array = [
107
-			'b' => 1,
108
-			'k' => 1024,
109
-			'kb' => 1024,
110
-			'mb' => 1024 * 1024,
111
-			'm' => 1024 * 1024,
112
-			'gb' => 1024 * 1024 * 1024,
113
-			'g' => 1024 * 1024 * 1024,
114
-			'tb' => 1024 * 1024 * 1024 * 1024,
115
-			't' => 1024 * 1024 * 1024 * 1024,
116
-			'pb' => 1024 * 1024 * 1024 * 1024 * 1024,
117
-			'p' => 1024 * 1024 * 1024 * 1024 * 1024,
118
-		];
119
-
120
-		$bytes = (float)$str;
121
-
122
-		if (preg_match('#([kmgtp]?b?)$#si', $str, $matches) && !empty($bytes_array[$matches[1]])) {
123
-			$bytes *= $bytes_array[$matches[1]];
124
-		} else {
125
-			return false;
126
-		}
127
-
128
-		$bytes = round($bytes);
129
-
130
-		return $bytes;
131
-	}
132
-
133
-	/**
134
-	 * Recursive copying of folders
135
-	 * @param string $src source folder
136
-	 * @param string $dest target folder
137
-	 *
138
-	 */
139
-	public static function copyr($src, $dest) {
140
-		if (is_dir($src)) {
141
-			if (!is_dir($dest)) {
142
-				mkdir($dest);
143
-			}
144
-			$files = scandir($src);
145
-			foreach ($files as $file) {
146
-				if ($file != "." && $file != "..") {
147
-					self::copyr("$src/$file", "$dest/$file");
148
-				}
149
-			}
150
-		} elseif (file_exists($src) && !\OC\Files\Filesystem::isFileBlacklisted($src)) {
151
-			copy($src, $dest);
152
-		}
153
-	}
154
-
155
-	/**
156
-	 * Recursive deletion of folders
157
-	 * @param string $dir path to the folder
158
-	 * @param bool $deleteSelf if set to false only the content of the folder will be deleted
159
-	 * @return bool
160
-	 */
161
-	public static function rmdirr($dir, $deleteSelf = true) {
162
-		if (is_dir($dir)) {
163
-			$files = new RecursiveIteratorIterator(
164
-				new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS),
165
-				RecursiveIteratorIterator::CHILD_FIRST
166
-			);
167
-
168
-			foreach ($files as $fileInfo) {
169
-				/** @var SplFileInfo $fileInfo */
170
-				if ($fileInfo->isLink()) {
171
-					unlink($fileInfo->getPathname());
172
-				} elseif ($fileInfo->isDir()) {
173
-					rmdir($fileInfo->getRealPath());
174
-				} else {
175
-					unlink($fileInfo->getRealPath());
176
-				}
177
-			}
178
-			if ($deleteSelf) {
179
-				rmdir($dir);
180
-			}
181
-		} elseif (file_exists($dir)) {
182
-			if ($deleteSelf) {
183
-				unlink($dir);
184
-			}
185
-		}
186
-		if (!$deleteSelf) {
187
-			return true;
188
-		}
189
-
190
-		return !file_exists($dir);
191
-	}
192
-
193
-	/**
194
-	 * @deprecated 18.0.0
195
-	 * @return \OC\Files\Type\TemplateManager
196
-	 */
197
-	public static function getFileTemplateManager() {
198
-		if (!self::$templateManager) {
199
-			self::$templateManager = new \OC\Files\Type\TemplateManager();
200
-		}
201
-		return self::$templateManager;
202
-	}
203
-
204
-	/**
205
-	 * detect if a given program is found in the search PATH
206
-	 *
207
-	 * @param string $name
208
-	 * @param bool $path
209
-	 * @internal param string $program name
210
-	 * @internal param string $optional search path, defaults to $PATH
211
-	 * @return bool    true if executable program found in path
212
-	 */
213
-	public static function canExecute($name, $path = false) {
214
-		// path defaults to PATH from environment if not set
215
-		if ($path === false) {
216
-			$path = getenv("PATH");
217
-		}
218
-		// we look for an executable file of that name
219
-		$exts = [""];
220
-		$check_fn = "is_executable";
221
-		// Default check will be done with $path directories :
222
-		$dirs = explode(PATH_SEPARATOR, $path);
223
-		// WARNING : We have to check if open_basedir is enabled :
224
-		$obd = OC::$server->get(IniGetWrapper::class)->getString('open_basedir');
225
-		if ($obd != "none") {
226
-			$obd_values = explode(PATH_SEPARATOR, $obd);
227
-			if (count($obd_values) > 0 and $obd_values[0]) {
228
-				// open_basedir is in effect !
229
-				// We need to check if the program is in one of these dirs :
230
-				$dirs = $obd_values;
231
-			}
232
-		}
233
-		foreach ($dirs as $dir) {
234
-			foreach ($exts as $ext) {
235
-				if ($check_fn("$dir/$name" . $ext)) {
236
-					return true;
237
-				}
238
-			}
239
-		}
240
-		return false;
241
-	}
242
-
243
-	/**
244
-	 * copy the contents of one stream to another
245
-	 *
246
-	 * @param resource $source
247
-	 * @param resource $target
248
-	 * @return array the number of bytes copied and result
249
-	 */
250
-	public static function streamCopy($source, $target) {
251
-		if (!$source or !$target) {
252
-			return [0, false];
253
-		}
254
-		$bufSize = 8192;
255
-		$result = true;
256
-		$count = 0;
257
-		while (!feof($source)) {
258
-			$buf = fread($source, $bufSize);
259
-			$bytesWritten = fwrite($target, $buf);
260
-			if ($bytesWritten !== false) {
261
-				$count += $bytesWritten;
262
-			}
263
-			// note: strlen is expensive so only use it when necessary,
264
-			// on the last block
265
-			if ($bytesWritten === false
266
-				|| ($bytesWritten < $bufSize && $bytesWritten < strlen($buf))
267
-			) {
268
-				// write error, could be disk full ?
269
-				$result = false;
270
-				break;
271
-			}
272
-		}
273
-		return [$count, $result];
274
-	}
275
-
276
-	/**
277
-	 * Adds a suffix to the name in case the file exists
278
-	 *
279
-	 * @param string $path
280
-	 * @param string $filename
281
-	 * @return string
282
-	 */
283
-	public static function buildNotExistingFileName($path, $filename) {
284
-		$view = \OC\Files\Filesystem::getView();
285
-		return self::buildNotExistingFileNameForView($path, $filename, $view);
286
-	}
287
-
288
-	/**
289
-	 * Adds a suffix to the name in case the file exists
290
-	 *
291
-	 * @param string $path
292
-	 * @param string $filename
293
-	 * @return string
294
-	 */
295
-	public static function buildNotExistingFileNameForView($path, $filename, \OC\Files\View $view) {
296
-		if ($path === '/') {
297
-			$path = '';
298
-		}
299
-		if ($pos = strrpos($filename, '.')) {
300
-			$name = substr($filename, 0, $pos);
301
-			$ext = substr($filename, $pos);
302
-		} else {
303
-			$name = $filename;
304
-			$ext = '';
305
-		}
306
-
307
-		$newpath = $path . '/' . $filename;
308
-		if ($view->file_exists($newpath)) {
309
-			if (preg_match_all('/\((\d+)\)/', $name, $matches, PREG_OFFSET_CAPTURE)) {
310
-				//Replace the last "(number)" with "(number+1)"
311
-				$last_match = count($matches[0]) - 1;
312
-				$counter = $matches[1][$last_match][0] + 1;
313
-				$offset = $matches[0][$last_match][1];
314
-				$match_length = strlen($matches[0][$last_match][0]);
315
-			} else {
316
-				$counter = 2;
317
-				$match_length = 0;
318
-				$offset = false;
319
-			}
320
-			do {
321
-				if ($offset) {
322
-					//Replace the last "(number)" with "(number+1)"
323
-					$newname = substr_replace($name, '(' . $counter . ')', $offset, $match_length);
324
-				} else {
325
-					$newname = $name . ' (' . $counter . ')';
326
-				}
327
-				$newpath = $path . '/' . $newname . $ext;
328
-				$counter++;
329
-			} while ($view->file_exists($newpath));
330
-		}
331
-
332
-		return $newpath;
333
-	}
334
-
335
-	/**
336
-	 * Returns an array with all keys from input lowercased or uppercased. Numbered indices are left as is.
337
-	 *
338
-	 * @param array $input The array to work on
339
-	 * @param int $case Either MB_CASE_UPPER or MB_CASE_LOWER (default)
340
-	 * @param string $encoding The encoding parameter is the character encoding. Defaults to UTF-8
341
-	 * @return array
342
-	 *
343
-	 * Returns an array with all keys from input lowercased or uppercased. Numbered indices are left as is.
344
-	 * based on http://www.php.net/manual/en/function.array-change-key-case.php#107715
345
-	 *
346
-	 */
347
-	public static function mb_array_change_key_case($input, $case = MB_CASE_LOWER, $encoding = 'UTF-8') {
348
-		$case = ($case != MB_CASE_UPPER) ? MB_CASE_LOWER : MB_CASE_UPPER;
349
-		$ret = [];
350
-		foreach ($input as $k => $v) {
351
-			$ret[mb_convert_case($k, $case, $encoding)] = $v;
352
-		}
353
-		return $ret;
354
-	}
355
-
356
-	/**
357
-	 * performs a search in a nested array
358
-	 * @param array $haystack the array to be searched
359
-	 * @param string $needle the search string
360
-	 * @param mixed $index optional, only search this key name
361
-	 * @return mixed the key of the matching field, otherwise false
362
-	 *
363
-	 * performs a search in a nested array
364
-	 *
365
-	 * taken from http://www.php.net/manual/en/function.array-search.php#97645
366
-	 */
367
-	public static function recursiveArraySearch($haystack, $needle, $index = null) {
368
-		$aIt = new RecursiveArrayIterator($haystack);
369
-		$it = new RecursiveIteratorIterator($aIt);
370
-
371
-		while ($it->valid()) {
372
-			if (((isset($index) and ($it->key() == $index)) or !isset($index)) and ($it->current() == $needle)) {
373
-				return $aIt->key();
374
-			}
375
-
376
-			$it->next();
377
-		}
378
-
379
-		return false;
380
-	}
381
-
382
-	/**
383
-	 * calculates the maximum upload size respecting system settings, free space and user quota
384
-	 *
385
-	 * @param string $dir the current folder where the user currently operates
386
-	 * @param int $freeSpace the number of bytes free on the storage holding $dir, if not set this will be received from the storage directly
387
-	 * @return int number of bytes representing
388
-	 */
389
-	public static function maxUploadFilesize($dir, $freeSpace = null) {
390
-		if (is_null($freeSpace) || $freeSpace < 0) {
391
-			$freeSpace = self::freeSpace($dir);
392
-		}
393
-		return min($freeSpace, self::uploadLimit());
394
-	}
395
-
396
-	/**
397
-	 * Calculate free space left within user quota
398
-	 *
399
-	 * @param string $dir the current folder where the user currently operates
400
-	 * @return int number of bytes representing
401
-	 */
402
-	public static function freeSpace($dir) {
403
-		$freeSpace = \OC\Files\Filesystem::free_space($dir);
404
-		if ($freeSpace < \OCP\Files\FileInfo::SPACE_UNLIMITED) {
405
-			$freeSpace = max($freeSpace, 0);
406
-			return $freeSpace;
407
-		} else {
408
-			return (INF > 0)? INF: PHP_INT_MAX; // work around https://bugs.php.net/bug.php?id=69188
409
-		}
410
-	}
411
-
412
-	/**
413
-	 * Calculate PHP upload limit
414
-	 *
415
-	 * @return int PHP upload file size limit
416
-	 */
417
-	public static function uploadLimit() {
418
-		$ini = \OC::$server->get(IniGetWrapper::class);
419
-		$upload_max_filesize = OCP\Util::computerFileSize($ini->get('upload_max_filesize'));
420
-		$post_max_size = OCP\Util::computerFileSize($ini->get('post_max_size'));
421
-		if ((int)$upload_max_filesize === 0 and (int)$post_max_size === 0) {
422
-			return INF;
423
-		} elseif ((int)$upload_max_filesize === 0 or (int)$post_max_size === 0) {
424
-			return max($upload_max_filesize, $post_max_size); //only the non 0 value counts
425
-		} else {
426
-			return min($upload_max_filesize, $post_max_size);
427
-		}
428
-	}
429
-
430
-	/**
431
-	 * Checks if a function is available
432
-	 *
433
-	 * @param string $function_name
434
-	 * @return bool
435
-	 */
436
-	public static function is_function_enabled($function_name) {
437
-		if (!function_exists($function_name)) {
438
-			return false;
439
-		}
440
-		$ini = \OC::$server->get(IniGetWrapper::class);
441
-		$disabled = explode(',', $ini->get('disable_functions') ?: '');
442
-		$disabled = array_map('trim', $disabled);
443
-		if (in_array($function_name, $disabled)) {
444
-			return false;
445
-		}
446
-		$disabled = explode(',', $ini->get('suhosin.executor.func.blacklist') ?: '');
447
-		$disabled = array_map('trim', $disabled);
448
-		if (in_array($function_name, $disabled)) {
449
-			return false;
450
-		}
451
-		return true;
452
-	}
453
-
454
-	/**
455
-	 * Try to find a program
456
-	 *
457
-	 * @param string $program
458
-	 * @return null|string
459
-	 */
460
-	public static function findBinaryPath($program) {
461
-		$memcache = \OC::$server->getMemCacheFactory()->createDistributed('findBinaryPath');
462
-		if ($memcache->hasKey($program)) {
463
-			return $memcache->get($program);
464
-		}
465
-		$result = null;
466
-		if (self::is_function_enabled('exec')) {
467
-			$exeSniffer = new ExecutableFinder();
468
-			// Returns null if nothing is found
469
-			$result = $exeSniffer->find($program, null, ['/usr/local/sbin', '/usr/local/bin', '/usr/sbin', '/usr/bin', '/sbin', '/bin', '/opt/bin']);
470
-		}
471
-		// store the value for 5 minutes
472
-		$memcache->set($program, $result, 300);
473
-		return $result;
474
-	}
475
-
476
-	/**
477
-	 * Calculate the disc space for the given path
478
-	 *
479
-	 * @param string $path
480
-	 * @param \OCP\Files\FileInfo $rootInfo (optional)
481
-	 * @return array
482
-	 * @throws \OCP\Files\NotFoundException
483
-	 */
484
-	public static function getStorageInfo($path, $rootInfo = null) {
485
-		// return storage info without adding mount points
486
-		$includeExtStorage = \OC::$server->getSystemConfig()->getValue('quota_include_external_storage', false);
487
-
488
-		if (!$rootInfo) {
489
-			$rootInfo = \OC\Files\Filesystem::getFileInfo($path, $includeExtStorage ? 'ext' : false);
490
-		}
491
-		if (!$rootInfo instanceof \OCP\Files\FileInfo) {
492
-			throw new \OCP\Files\NotFoundException();
493
-		}
494
-		$used = $rootInfo->getSize();
495
-		if ($used < 0) {
496
-			$used = 0;
497
-		}
498
-		$quota = \OCP\Files\FileInfo::SPACE_UNLIMITED;
499
-		$storage = $rootInfo->getStorage();
500
-		$sourceStorage = $storage;
501
-		if ($storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage')) {
502
-			$includeExtStorage = false;
503
-			$sourceStorage = $storage->getSourceStorage();
504
-		}
505
-		if ($includeExtStorage) {
506
-			if ($storage->instanceOfStorage('\OC\Files\Storage\Home')
507
-				|| $storage->instanceOfStorage('\OC\Files\ObjectStore\HomeObjectStoreStorage')
508
-			) {
509
-				/** @var \OC\Files\Storage\Home $storage */
510
-				$user = $storage->getUser();
511
-			} else {
512
-				$user = \OC::$server->getUserSession()->getUser();
513
-			}
514
-			$quota = OC_Util::getUserQuota($user);
515
-			if ($quota !== \OCP\Files\FileInfo::SPACE_UNLIMITED) {
516
-				// always get free space / total space from root + mount points
517
-				return self::getGlobalStorageInfo($quota);
518
-			}
519
-		}
520
-
521
-		// TODO: need a better way to get total space from storage
522
-		if ($sourceStorage->instanceOfStorage('\OC\Files\Storage\Wrapper\Quota')) {
523
-			/** @var \OC\Files\Storage\Wrapper\Quota $storage */
524
-			$quota = $sourceStorage->getQuota();
525
-		}
526
-		$free = $sourceStorage->free_space($rootInfo->getInternalPath());
527
-		if ($free >= 0) {
528
-			$total = $free + $used;
529
-		} else {
530
-			$total = $free; //either unknown or unlimited
531
-		}
532
-		if ($total > 0) {
533
-			if ($quota > 0 && $total > $quota) {
534
-				$total = $quota;
535
-			}
536
-			// prevent division by zero or error codes (negative values)
537
-			$relative = round(($used / $total) * 10000) / 100;
538
-		} else {
539
-			$relative = 0;
540
-		}
541
-
542
-		$ownerId = $storage->getOwner($path);
543
-		$ownerDisplayName = '';
544
-		$owner = \OC::$server->getUserManager()->get($ownerId);
545
-		if ($owner) {
546
-			$ownerDisplayName = $owner->getDisplayName();
547
-		}
548
-
549
-		return [
550
-			'free' => $free,
551
-			'used' => $used,
552
-			'quota' => $quota,
553
-			'total' => $total,
554
-			'relative' => $relative,
555
-			'owner' => $ownerId,
556
-			'ownerDisplayName' => $ownerDisplayName,
557
-		];
558
-	}
559
-
560
-	/**
561
-	 * Get storage info including all mount points and quota
562
-	 *
563
-	 * @param int $quota
564
-	 * @return array
565
-	 */
566
-	private static function getGlobalStorageInfo($quota) {
567
-		$rootInfo = \OC\Files\Filesystem::getFileInfo('', 'ext');
568
-		$used = $rootInfo['size'];
569
-		if ($used < 0) {
570
-			$used = 0;
571
-		}
572
-
573
-		$total = $quota;
574
-		$free = $quota - $used;
575
-
576
-		if ($total > 0) {
577
-			if ($quota > 0 && $total > $quota) {
578
-				$total = $quota;
579
-			}
580
-			// prevent division by zero or error codes (negative values)
581
-			$relative = round(($used / $total) * 10000) / 100;
582
-		} else {
583
-			$relative = 0;
584
-		}
585
-
586
-		return [
587
-			'free' => $free,
588
-			'used' => $used,
589
-			'total' => $total,
590
-			'relative' => $relative,
591
-			'quota' => $quota
592
-		];
593
-	}
594
-
595
-	/**
596
-	 * Returns whether the config file is set manually to read-only
597
-	 * @return bool
598
-	 */
599
-	public static function isReadOnlyConfigEnabled() {
600
-		return \OC::$server->getConfig()->getSystemValue('config_is_read_only', false);
601
-	}
54
+    private static $templateManager;
55
+
56
+    /**
57
+     * Make a human file size
58
+     * @param int $bytes file size in bytes
59
+     * @return string a human readable file size
60
+     *
61
+     * Makes 2048 to 2 kB.
62
+     */
63
+    public static function humanFileSize($bytes) {
64
+        if ($bytes < 0) {
65
+            return "?";
66
+        }
67
+        if ($bytes < 1024) {
68
+            return "$bytes B";
69
+        }
70
+        $bytes = round($bytes / 1024, 0);
71
+        if ($bytes < 1024) {
72
+            return "$bytes KB";
73
+        }
74
+        $bytes = round($bytes / 1024, 1);
75
+        if ($bytes < 1024) {
76
+            return "$bytes MB";
77
+        }
78
+        $bytes = round($bytes / 1024, 1);
79
+        if ($bytes < 1024) {
80
+            return "$bytes GB";
81
+        }
82
+        $bytes = round($bytes / 1024, 1);
83
+        if ($bytes < 1024) {
84
+            return "$bytes TB";
85
+        }
86
+
87
+        $bytes = round($bytes / 1024, 1);
88
+        return "$bytes PB";
89
+    }
90
+
91
+    /**
92
+     * Make a computer file size
93
+     * @param string $str file size in human readable format
94
+     * @return float|bool a file size in bytes
95
+     *
96
+     * Makes 2kB to 2048.
97
+     *
98
+     * Inspired by: http://www.php.net/manual/en/function.filesize.php#92418
99
+     */
100
+    public static function computerFileSize($str) {
101
+        $str = strtolower($str);
102
+        if (is_numeric($str)) {
103
+            return (float)$str;
104
+        }
105
+
106
+        $bytes_array = [
107
+            'b' => 1,
108
+            'k' => 1024,
109
+            'kb' => 1024,
110
+            'mb' => 1024 * 1024,
111
+            'm' => 1024 * 1024,
112
+            'gb' => 1024 * 1024 * 1024,
113
+            'g' => 1024 * 1024 * 1024,
114
+            'tb' => 1024 * 1024 * 1024 * 1024,
115
+            't' => 1024 * 1024 * 1024 * 1024,
116
+            'pb' => 1024 * 1024 * 1024 * 1024 * 1024,
117
+            'p' => 1024 * 1024 * 1024 * 1024 * 1024,
118
+        ];
119
+
120
+        $bytes = (float)$str;
121
+
122
+        if (preg_match('#([kmgtp]?b?)$#si', $str, $matches) && !empty($bytes_array[$matches[1]])) {
123
+            $bytes *= $bytes_array[$matches[1]];
124
+        } else {
125
+            return false;
126
+        }
127
+
128
+        $bytes = round($bytes);
129
+
130
+        return $bytes;
131
+    }
132
+
133
+    /**
134
+     * Recursive copying of folders
135
+     * @param string $src source folder
136
+     * @param string $dest target folder
137
+     *
138
+     */
139
+    public static function copyr($src, $dest) {
140
+        if (is_dir($src)) {
141
+            if (!is_dir($dest)) {
142
+                mkdir($dest);
143
+            }
144
+            $files = scandir($src);
145
+            foreach ($files as $file) {
146
+                if ($file != "." && $file != "..") {
147
+                    self::copyr("$src/$file", "$dest/$file");
148
+                }
149
+            }
150
+        } elseif (file_exists($src) && !\OC\Files\Filesystem::isFileBlacklisted($src)) {
151
+            copy($src, $dest);
152
+        }
153
+    }
154
+
155
+    /**
156
+     * Recursive deletion of folders
157
+     * @param string $dir path to the folder
158
+     * @param bool $deleteSelf if set to false only the content of the folder will be deleted
159
+     * @return bool
160
+     */
161
+    public static function rmdirr($dir, $deleteSelf = true) {
162
+        if (is_dir($dir)) {
163
+            $files = new RecursiveIteratorIterator(
164
+                new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS),
165
+                RecursiveIteratorIterator::CHILD_FIRST
166
+            );
167
+
168
+            foreach ($files as $fileInfo) {
169
+                /** @var SplFileInfo $fileInfo */
170
+                if ($fileInfo->isLink()) {
171
+                    unlink($fileInfo->getPathname());
172
+                } elseif ($fileInfo->isDir()) {
173
+                    rmdir($fileInfo->getRealPath());
174
+                } else {
175
+                    unlink($fileInfo->getRealPath());
176
+                }
177
+            }
178
+            if ($deleteSelf) {
179
+                rmdir($dir);
180
+            }
181
+        } elseif (file_exists($dir)) {
182
+            if ($deleteSelf) {
183
+                unlink($dir);
184
+            }
185
+        }
186
+        if (!$deleteSelf) {
187
+            return true;
188
+        }
189
+
190
+        return !file_exists($dir);
191
+    }
192
+
193
+    /**
194
+     * @deprecated 18.0.0
195
+     * @return \OC\Files\Type\TemplateManager
196
+     */
197
+    public static function getFileTemplateManager() {
198
+        if (!self::$templateManager) {
199
+            self::$templateManager = new \OC\Files\Type\TemplateManager();
200
+        }
201
+        return self::$templateManager;
202
+    }
203
+
204
+    /**
205
+     * detect if a given program is found in the search PATH
206
+     *
207
+     * @param string $name
208
+     * @param bool $path
209
+     * @internal param string $program name
210
+     * @internal param string $optional search path, defaults to $PATH
211
+     * @return bool    true if executable program found in path
212
+     */
213
+    public static function canExecute($name, $path = false) {
214
+        // path defaults to PATH from environment if not set
215
+        if ($path === false) {
216
+            $path = getenv("PATH");
217
+        }
218
+        // we look for an executable file of that name
219
+        $exts = [""];
220
+        $check_fn = "is_executable";
221
+        // Default check will be done with $path directories :
222
+        $dirs = explode(PATH_SEPARATOR, $path);
223
+        // WARNING : We have to check if open_basedir is enabled :
224
+        $obd = OC::$server->get(IniGetWrapper::class)->getString('open_basedir');
225
+        if ($obd != "none") {
226
+            $obd_values = explode(PATH_SEPARATOR, $obd);
227
+            if (count($obd_values) > 0 and $obd_values[0]) {
228
+                // open_basedir is in effect !
229
+                // We need to check if the program is in one of these dirs :
230
+                $dirs = $obd_values;
231
+            }
232
+        }
233
+        foreach ($dirs as $dir) {
234
+            foreach ($exts as $ext) {
235
+                if ($check_fn("$dir/$name" . $ext)) {
236
+                    return true;
237
+                }
238
+            }
239
+        }
240
+        return false;
241
+    }
242
+
243
+    /**
244
+     * copy the contents of one stream to another
245
+     *
246
+     * @param resource $source
247
+     * @param resource $target
248
+     * @return array the number of bytes copied and result
249
+     */
250
+    public static function streamCopy($source, $target) {
251
+        if (!$source or !$target) {
252
+            return [0, false];
253
+        }
254
+        $bufSize = 8192;
255
+        $result = true;
256
+        $count = 0;
257
+        while (!feof($source)) {
258
+            $buf = fread($source, $bufSize);
259
+            $bytesWritten = fwrite($target, $buf);
260
+            if ($bytesWritten !== false) {
261
+                $count += $bytesWritten;
262
+            }
263
+            // note: strlen is expensive so only use it when necessary,
264
+            // on the last block
265
+            if ($bytesWritten === false
266
+                || ($bytesWritten < $bufSize && $bytesWritten < strlen($buf))
267
+            ) {
268
+                // write error, could be disk full ?
269
+                $result = false;
270
+                break;
271
+            }
272
+        }
273
+        return [$count, $result];
274
+    }
275
+
276
+    /**
277
+     * Adds a suffix to the name in case the file exists
278
+     *
279
+     * @param string $path
280
+     * @param string $filename
281
+     * @return string
282
+     */
283
+    public static function buildNotExistingFileName($path, $filename) {
284
+        $view = \OC\Files\Filesystem::getView();
285
+        return self::buildNotExistingFileNameForView($path, $filename, $view);
286
+    }
287
+
288
+    /**
289
+     * Adds a suffix to the name in case the file exists
290
+     *
291
+     * @param string $path
292
+     * @param string $filename
293
+     * @return string
294
+     */
295
+    public static function buildNotExistingFileNameForView($path, $filename, \OC\Files\View $view) {
296
+        if ($path === '/') {
297
+            $path = '';
298
+        }
299
+        if ($pos = strrpos($filename, '.')) {
300
+            $name = substr($filename, 0, $pos);
301
+            $ext = substr($filename, $pos);
302
+        } else {
303
+            $name = $filename;
304
+            $ext = '';
305
+        }
306
+
307
+        $newpath = $path . '/' . $filename;
308
+        if ($view->file_exists($newpath)) {
309
+            if (preg_match_all('/\((\d+)\)/', $name, $matches, PREG_OFFSET_CAPTURE)) {
310
+                //Replace the last "(number)" with "(number+1)"
311
+                $last_match = count($matches[0]) - 1;
312
+                $counter = $matches[1][$last_match][0] + 1;
313
+                $offset = $matches[0][$last_match][1];
314
+                $match_length = strlen($matches[0][$last_match][0]);
315
+            } else {
316
+                $counter = 2;
317
+                $match_length = 0;
318
+                $offset = false;
319
+            }
320
+            do {
321
+                if ($offset) {
322
+                    //Replace the last "(number)" with "(number+1)"
323
+                    $newname = substr_replace($name, '(' . $counter . ')', $offset, $match_length);
324
+                } else {
325
+                    $newname = $name . ' (' . $counter . ')';
326
+                }
327
+                $newpath = $path . '/' . $newname . $ext;
328
+                $counter++;
329
+            } while ($view->file_exists($newpath));
330
+        }
331
+
332
+        return $newpath;
333
+    }
334
+
335
+    /**
336
+     * Returns an array with all keys from input lowercased or uppercased. Numbered indices are left as is.
337
+     *
338
+     * @param array $input The array to work on
339
+     * @param int $case Either MB_CASE_UPPER or MB_CASE_LOWER (default)
340
+     * @param string $encoding The encoding parameter is the character encoding. Defaults to UTF-8
341
+     * @return array
342
+     *
343
+     * Returns an array with all keys from input lowercased or uppercased. Numbered indices are left as is.
344
+     * based on http://www.php.net/manual/en/function.array-change-key-case.php#107715
345
+     *
346
+     */
347
+    public static function mb_array_change_key_case($input, $case = MB_CASE_LOWER, $encoding = 'UTF-8') {
348
+        $case = ($case != MB_CASE_UPPER) ? MB_CASE_LOWER : MB_CASE_UPPER;
349
+        $ret = [];
350
+        foreach ($input as $k => $v) {
351
+            $ret[mb_convert_case($k, $case, $encoding)] = $v;
352
+        }
353
+        return $ret;
354
+    }
355
+
356
+    /**
357
+     * performs a search in a nested array
358
+     * @param array $haystack the array to be searched
359
+     * @param string $needle the search string
360
+     * @param mixed $index optional, only search this key name
361
+     * @return mixed the key of the matching field, otherwise false
362
+     *
363
+     * performs a search in a nested array
364
+     *
365
+     * taken from http://www.php.net/manual/en/function.array-search.php#97645
366
+     */
367
+    public static function recursiveArraySearch($haystack, $needle, $index = null) {
368
+        $aIt = new RecursiveArrayIterator($haystack);
369
+        $it = new RecursiveIteratorIterator($aIt);
370
+
371
+        while ($it->valid()) {
372
+            if (((isset($index) and ($it->key() == $index)) or !isset($index)) and ($it->current() == $needle)) {
373
+                return $aIt->key();
374
+            }
375
+
376
+            $it->next();
377
+        }
378
+
379
+        return false;
380
+    }
381
+
382
+    /**
383
+     * calculates the maximum upload size respecting system settings, free space and user quota
384
+     *
385
+     * @param string $dir the current folder where the user currently operates
386
+     * @param int $freeSpace the number of bytes free on the storage holding $dir, if not set this will be received from the storage directly
387
+     * @return int number of bytes representing
388
+     */
389
+    public static function maxUploadFilesize($dir, $freeSpace = null) {
390
+        if (is_null($freeSpace) || $freeSpace < 0) {
391
+            $freeSpace = self::freeSpace($dir);
392
+        }
393
+        return min($freeSpace, self::uploadLimit());
394
+    }
395
+
396
+    /**
397
+     * Calculate free space left within user quota
398
+     *
399
+     * @param string $dir the current folder where the user currently operates
400
+     * @return int number of bytes representing
401
+     */
402
+    public static function freeSpace($dir) {
403
+        $freeSpace = \OC\Files\Filesystem::free_space($dir);
404
+        if ($freeSpace < \OCP\Files\FileInfo::SPACE_UNLIMITED) {
405
+            $freeSpace = max($freeSpace, 0);
406
+            return $freeSpace;
407
+        } else {
408
+            return (INF > 0)? INF: PHP_INT_MAX; // work around https://bugs.php.net/bug.php?id=69188
409
+        }
410
+    }
411
+
412
+    /**
413
+     * Calculate PHP upload limit
414
+     *
415
+     * @return int PHP upload file size limit
416
+     */
417
+    public static function uploadLimit() {
418
+        $ini = \OC::$server->get(IniGetWrapper::class);
419
+        $upload_max_filesize = OCP\Util::computerFileSize($ini->get('upload_max_filesize'));
420
+        $post_max_size = OCP\Util::computerFileSize($ini->get('post_max_size'));
421
+        if ((int)$upload_max_filesize === 0 and (int)$post_max_size === 0) {
422
+            return INF;
423
+        } elseif ((int)$upload_max_filesize === 0 or (int)$post_max_size === 0) {
424
+            return max($upload_max_filesize, $post_max_size); //only the non 0 value counts
425
+        } else {
426
+            return min($upload_max_filesize, $post_max_size);
427
+        }
428
+    }
429
+
430
+    /**
431
+     * Checks if a function is available
432
+     *
433
+     * @param string $function_name
434
+     * @return bool
435
+     */
436
+    public static function is_function_enabled($function_name) {
437
+        if (!function_exists($function_name)) {
438
+            return false;
439
+        }
440
+        $ini = \OC::$server->get(IniGetWrapper::class);
441
+        $disabled = explode(',', $ini->get('disable_functions') ?: '');
442
+        $disabled = array_map('trim', $disabled);
443
+        if (in_array($function_name, $disabled)) {
444
+            return false;
445
+        }
446
+        $disabled = explode(',', $ini->get('suhosin.executor.func.blacklist') ?: '');
447
+        $disabled = array_map('trim', $disabled);
448
+        if (in_array($function_name, $disabled)) {
449
+            return false;
450
+        }
451
+        return true;
452
+    }
453
+
454
+    /**
455
+     * Try to find a program
456
+     *
457
+     * @param string $program
458
+     * @return null|string
459
+     */
460
+    public static function findBinaryPath($program) {
461
+        $memcache = \OC::$server->getMemCacheFactory()->createDistributed('findBinaryPath');
462
+        if ($memcache->hasKey($program)) {
463
+            return $memcache->get($program);
464
+        }
465
+        $result = null;
466
+        if (self::is_function_enabled('exec')) {
467
+            $exeSniffer = new ExecutableFinder();
468
+            // Returns null if nothing is found
469
+            $result = $exeSniffer->find($program, null, ['/usr/local/sbin', '/usr/local/bin', '/usr/sbin', '/usr/bin', '/sbin', '/bin', '/opt/bin']);
470
+        }
471
+        // store the value for 5 minutes
472
+        $memcache->set($program, $result, 300);
473
+        return $result;
474
+    }
475
+
476
+    /**
477
+     * Calculate the disc space for the given path
478
+     *
479
+     * @param string $path
480
+     * @param \OCP\Files\FileInfo $rootInfo (optional)
481
+     * @return array
482
+     * @throws \OCP\Files\NotFoundException
483
+     */
484
+    public static function getStorageInfo($path, $rootInfo = null) {
485
+        // return storage info without adding mount points
486
+        $includeExtStorage = \OC::$server->getSystemConfig()->getValue('quota_include_external_storage', false);
487
+
488
+        if (!$rootInfo) {
489
+            $rootInfo = \OC\Files\Filesystem::getFileInfo($path, $includeExtStorage ? 'ext' : false);
490
+        }
491
+        if (!$rootInfo instanceof \OCP\Files\FileInfo) {
492
+            throw new \OCP\Files\NotFoundException();
493
+        }
494
+        $used = $rootInfo->getSize();
495
+        if ($used < 0) {
496
+            $used = 0;
497
+        }
498
+        $quota = \OCP\Files\FileInfo::SPACE_UNLIMITED;
499
+        $storage = $rootInfo->getStorage();
500
+        $sourceStorage = $storage;
501
+        if ($storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage')) {
502
+            $includeExtStorage = false;
503
+            $sourceStorage = $storage->getSourceStorage();
504
+        }
505
+        if ($includeExtStorage) {
506
+            if ($storage->instanceOfStorage('\OC\Files\Storage\Home')
507
+                || $storage->instanceOfStorage('\OC\Files\ObjectStore\HomeObjectStoreStorage')
508
+            ) {
509
+                /** @var \OC\Files\Storage\Home $storage */
510
+                $user = $storage->getUser();
511
+            } else {
512
+                $user = \OC::$server->getUserSession()->getUser();
513
+            }
514
+            $quota = OC_Util::getUserQuota($user);
515
+            if ($quota !== \OCP\Files\FileInfo::SPACE_UNLIMITED) {
516
+                // always get free space / total space from root + mount points
517
+                return self::getGlobalStorageInfo($quota);
518
+            }
519
+        }
520
+
521
+        // TODO: need a better way to get total space from storage
522
+        if ($sourceStorage->instanceOfStorage('\OC\Files\Storage\Wrapper\Quota')) {
523
+            /** @var \OC\Files\Storage\Wrapper\Quota $storage */
524
+            $quota = $sourceStorage->getQuota();
525
+        }
526
+        $free = $sourceStorage->free_space($rootInfo->getInternalPath());
527
+        if ($free >= 0) {
528
+            $total = $free + $used;
529
+        } else {
530
+            $total = $free; //either unknown or unlimited
531
+        }
532
+        if ($total > 0) {
533
+            if ($quota > 0 && $total > $quota) {
534
+                $total = $quota;
535
+            }
536
+            // prevent division by zero or error codes (negative values)
537
+            $relative = round(($used / $total) * 10000) / 100;
538
+        } else {
539
+            $relative = 0;
540
+        }
541
+
542
+        $ownerId = $storage->getOwner($path);
543
+        $ownerDisplayName = '';
544
+        $owner = \OC::$server->getUserManager()->get($ownerId);
545
+        if ($owner) {
546
+            $ownerDisplayName = $owner->getDisplayName();
547
+        }
548
+
549
+        return [
550
+            'free' => $free,
551
+            'used' => $used,
552
+            'quota' => $quota,
553
+            'total' => $total,
554
+            'relative' => $relative,
555
+            'owner' => $ownerId,
556
+            'ownerDisplayName' => $ownerDisplayName,
557
+        ];
558
+    }
559
+
560
+    /**
561
+     * Get storage info including all mount points and quota
562
+     *
563
+     * @param int $quota
564
+     * @return array
565
+     */
566
+    private static function getGlobalStorageInfo($quota) {
567
+        $rootInfo = \OC\Files\Filesystem::getFileInfo('', 'ext');
568
+        $used = $rootInfo['size'];
569
+        if ($used < 0) {
570
+            $used = 0;
571
+        }
572
+
573
+        $total = $quota;
574
+        $free = $quota - $used;
575
+
576
+        if ($total > 0) {
577
+            if ($quota > 0 && $total > $quota) {
578
+                $total = $quota;
579
+            }
580
+            // prevent division by zero or error codes (negative values)
581
+            $relative = round(($used / $total) * 10000) / 100;
582
+        } else {
583
+            $relative = 0;
584
+        }
585
+
586
+        return [
587
+            'free' => $free,
588
+            'used' => $used,
589
+            'total' => $total,
590
+            'relative' => $relative,
591
+            'quota' => $quota
592
+        ];
593
+    }
594
+
595
+    /**
596
+     * Returns whether the config file is set manually to read-only
597
+     * @return bool
598
+     */
599
+    public static function isReadOnlyConfigEnabled() {
600
+        return \OC::$server->getConfig()->getSystemValue('config_is_read_only', false);
601
+    }
602 602
 }
Please login to merge, or discard this patch.
Spacing   +10 added lines, -10 removed lines patch added patch discarded remove patch
@@ -100,7 +100,7 @@  discard block
 block discarded – undo
100 100
 	public static function computerFileSize($str) {
101 101
 		$str = strtolower($str);
102 102
 		if (is_numeric($str)) {
103
-			return (float)$str;
103
+			return (float) $str;
104 104
 		}
105 105
 
106 106
 		$bytes_array = [
@@ -117,7 +117,7 @@  discard block
 block discarded – undo
117 117
 			'p' => 1024 * 1024 * 1024 * 1024 * 1024,
118 118
 		];
119 119
 
120
-		$bytes = (float)$str;
120
+		$bytes = (float) $str;
121 121
 
122 122
 		if (preg_match('#([kmgtp]?b?)$#si', $str, $matches) && !empty($bytes_array[$matches[1]])) {
123 123
 			$bytes *= $bytes_array[$matches[1]];
@@ -232,7 +232,7 @@  discard block
 block discarded – undo
232 232
 		}
233 233
 		foreach ($dirs as $dir) {
234 234
 			foreach ($exts as $ext) {
235
-				if ($check_fn("$dir/$name" . $ext)) {
235
+				if ($check_fn("$dir/$name".$ext)) {
236 236
 					return true;
237 237
 				}
238 238
 			}
@@ -304,7 +304,7 @@  discard block
 block discarded – undo
304 304
 			$ext = '';
305 305
 		}
306 306
 
307
-		$newpath = $path . '/' . $filename;
307
+		$newpath = $path.'/'.$filename;
308 308
 		if ($view->file_exists($newpath)) {
309 309
 			if (preg_match_all('/\((\d+)\)/', $name, $matches, PREG_OFFSET_CAPTURE)) {
310 310
 				//Replace the last "(number)" with "(number+1)"
@@ -320,11 +320,11 @@  discard block
 block discarded – undo
320 320
 			do {
321 321
 				if ($offset) {
322 322
 					//Replace the last "(number)" with "(number+1)"
323
-					$newname = substr_replace($name, '(' . $counter . ')', $offset, $match_length);
323
+					$newname = substr_replace($name, '('.$counter.')', $offset, $match_length);
324 324
 				} else {
325
-					$newname = $name . ' (' . $counter . ')';
325
+					$newname = $name.' ('.$counter.')';
326 326
 				}
327
-				$newpath = $path . '/' . $newname . $ext;
327
+				$newpath = $path.'/'.$newname.$ext;
328 328
 				$counter++;
329 329
 			} while ($view->file_exists($newpath));
330 330
 		}
@@ -405,7 +405,7 @@  discard block
 block discarded – undo
405 405
 			$freeSpace = max($freeSpace, 0);
406 406
 			return $freeSpace;
407 407
 		} else {
408
-			return (INF > 0)? INF: PHP_INT_MAX; // work around https://bugs.php.net/bug.php?id=69188
408
+			return (INF > 0) ? INF: PHP_INT_MAX; // work around https://bugs.php.net/bug.php?id=69188
409 409
 		}
410 410
 	}
411 411
 
@@ -418,9 +418,9 @@  discard block
 block discarded – undo
418 418
 		$ini = \OC::$server->get(IniGetWrapper::class);
419 419
 		$upload_max_filesize = OCP\Util::computerFileSize($ini->get('upload_max_filesize'));
420 420
 		$post_max_size = OCP\Util::computerFileSize($ini->get('post_max_size'));
421
-		if ((int)$upload_max_filesize === 0 and (int)$post_max_size === 0) {
421
+		if ((int) $upload_max_filesize === 0 and (int) $post_max_size === 0) {
422 422
 			return INF;
423
-		} elseif ((int)$upload_max_filesize === 0 or (int)$post_max_size === 0) {
423
+		} elseif ((int) $upload_max_filesize === 0 or (int) $post_max_size === 0) {
424 424
 			return max($upload_max_filesize, $post_max_size); //only the non 0 value counts
425 425
 		} else {
426 426
 			return min($upload_max_filesize, $post_max_size);
Please login to merge, or discard this patch.
lib/private/legacy/OC_Files.php 2 patches
Indentation   +372 added lines, -372 removed lines patch added patch discarded remove patch
@@ -51,376 +51,376 @@
 block discarded – undo
51 51
  *
52 52
  */
53 53
 class OC_Files {
54
-	public const FILE = 1;
55
-	public const ZIP_FILES = 2;
56
-	public const ZIP_DIR = 3;
57
-
58
-	public const UPLOAD_MIN_LIMIT_BYTES = 1048576; // 1 MiB
59
-
60
-
61
-	private static $multipartBoundary = '';
62
-
63
-	/**
64
-	 * @return string
65
-	 */
66
-	private static function getBoundary() {
67
-		if (empty(self::$multipartBoundary)) {
68
-			self::$multipartBoundary = md5(mt_rand());
69
-		}
70
-		return self::$multipartBoundary;
71
-	}
72
-
73
-	/**
74
-	 * @param string $filename
75
-	 * @param string $name
76
-	 * @param array $rangeArray ('from'=>int,'to'=>int), ...
77
-	 */
78
-	private static function sendHeaders($filename, $name, array $rangeArray) {
79
-		OC_Response::setContentDispositionHeader($name, 'attachment');
80
-		header('Content-Transfer-Encoding: binary', true);
81
-		header('Pragma: public');// enable caching in IE
82
-		header('Expires: 0');
83
-		header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
84
-		$fileSize = \OC\Files\Filesystem::filesize($filename);
85
-		$type = \OC::$server->getMimeTypeDetector()->getSecureMimeType(\OC\Files\Filesystem::getMimeType($filename));
86
-		if ($fileSize > -1) {
87
-			if (!empty($rangeArray)) {
88
-				http_response_code(206);
89
-				header('Accept-Ranges: bytes', true);
90
-				if (count($rangeArray) > 1) {
91
-					$type = 'multipart/byteranges; boundary='.self::getBoundary();
92
-				// no Content-Length header here
93
-				} else {
94
-					header(sprintf('Content-Range: bytes %d-%d/%d', $rangeArray[0]['from'], $rangeArray[0]['to'], $fileSize), true);
95
-					OC_Response::setContentLengthHeader($rangeArray[0]['to'] - $rangeArray[0]['from'] + 1);
96
-				}
97
-			} else {
98
-				OC_Response::setContentLengthHeader($fileSize);
99
-			}
100
-		}
101
-		header('Content-Type: '.$type, true);
102
-	}
103
-
104
-	/**
105
-	 * return the content of a file or return a zip file containing multiple files
106
-	 *
107
-	 * @param string $dir
108
-	 * @param string $files ; separated list of files to download
109
-	 * @param array $params ; 'head' boolean to only send header of the request ; 'range' http range header
110
-	 */
111
-	public static function get($dir, $files, $params = null) {
112
-		$view = \OC\Files\Filesystem::getView();
113
-		$getType = self::FILE;
114
-		$filename = $dir;
115
-		try {
116
-			if (is_array($files) && count($files) === 1) {
117
-				$files = $files[0];
118
-			}
119
-
120
-			if (!is_array($files)) {
121
-				$filename = $dir . '/' . $files;
122
-				if (!$view->is_dir($filename)) {
123
-					self::getSingleFile($view, $dir, $files, is_null($params) ? [] : $params);
124
-					return;
125
-				}
126
-			}
127
-
128
-			$name = 'download';
129
-			if (is_array($files)) {
130
-				$getType = self::ZIP_FILES;
131
-				$basename = basename($dir);
132
-				if ($basename) {
133
-					$name = $basename;
134
-				}
135
-
136
-				$filename = $dir . '/' . $name;
137
-			} else {
138
-				$filename = $dir . '/' . $files;
139
-				$getType = self::ZIP_DIR;
140
-				// downloading root ?
141
-				if ($files !== '') {
142
-					$name = $files;
143
-				}
144
-			}
145
-
146
-			self::lockFiles($view, $dir, $files);
147
-
148
-			/* Calculate filesize and number of files */
149
-			if ($getType === self::ZIP_FILES) {
150
-				$fileInfos = [];
151
-				$fileSize = 0;
152
-				foreach ($files as $file) {
153
-					$fileInfo = \OC\Files\Filesystem::getFileInfo($dir . '/' . $file);
154
-					$fileSize += $fileInfo->getSize();
155
-					$fileInfos[] = $fileInfo;
156
-				}
157
-				$numberOfFiles = self::getNumberOfFiles($fileInfos);
158
-			} elseif ($getType === self::ZIP_DIR) {
159
-				$fileInfo = \OC\Files\Filesystem::getFileInfo($dir . '/' . $files);
160
-				$fileSize = $fileInfo->getSize();
161
-				$numberOfFiles = self::getNumberOfFiles([$fileInfo]);
162
-			}
163
-
164
-			$streamer = new Streamer(\OC::$server->getRequest(), $fileSize, $numberOfFiles);
165
-			OC_Util::obEnd();
166
-
167
-			$streamer->sendHeaders($name);
168
-			$executionTime = (int)OC::$server->get(IniGetWrapper::class)->getNumeric('max_execution_time');
169
-			if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
170
-				@set_time_limit(0);
171
-			}
172
-			ignore_user_abort(true);
173
-
174
-			if ($getType === self::ZIP_FILES) {
175
-				foreach ($files as $file) {
176
-					$file = $dir . '/' . $file;
177
-					if (\OC\Files\Filesystem::is_file($file)) {
178
-						$userFolder = \OC::$server->getRootFolder()->get(\OC\Files\Filesystem::getRoot());
179
-						$file = $userFolder->get($file);
180
-						if ($file instanceof \OC\Files\Node\File) {
181
-							try {
182
-								$fh = $file->fopen('r');
183
-							} catch (\OCP\Files\NotPermittedException $e) {
184
-								continue;
185
-							}
186
-							$fileSize = $file->getSize();
187
-							$fileTime = $file->getMTime();
188
-						} else {
189
-							// File is not a file? …
190
-							\OC::$server->getLogger()->debug(
191
-								'File given, but no Node available. Name {file}',
192
-								[ 'app' => 'files', 'file' => $file ]
193
-							);
194
-							continue;
195
-						}
196
-						$streamer->addFileFromStream($fh, $file->getName(), $fileSize, $fileTime);
197
-						fclose($fh);
198
-					} elseif (\OC\Files\Filesystem::is_dir($file)) {
199
-						$streamer->addDirRecursive($file);
200
-					}
201
-				}
202
-			} elseif ($getType === self::ZIP_DIR) {
203
-				$file = $dir . '/' . $files;
204
-				$streamer->addDirRecursive($file);
205
-			}
206
-			$streamer->finalize();
207
-			set_time_limit($executionTime);
208
-			self::unlockAllTheFiles($dir, $files, $getType, $view, $filename);
209
-		} catch (\OCP\Lock\LockedException $ex) {
210
-			self::unlockAllTheFiles($dir, $files, $getType, $view, $filename);
211
-			OC::$server->getLogger()->logException($ex);
212
-			$l = \OC::$server->getL10N('core');
213
-			$hint = method_exists($ex, 'getHint') ? $ex->getHint() : '';
214
-			\OC_Template::printErrorPage($l->t('File is currently busy, please try again later'), $hint, 200);
215
-		} catch (\OCP\Files\ForbiddenException $ex) {
216
-			self::unlockAllTheFiles($dir, $files, $getType, $view, $filename);
217
-			OC::$server->getLogger()->logException($ex);
218
-			$l = \OC::$server->getL10N('core');
219
-			\OC_Template::printErrorPage($l->t('Can\'t read file'), $ex->getMessage(), 200);
220
-		} catch (\Exception $ex) {
221
-			self::unlockAllTheFiles($dir, $files, $getType, $view, $filename);
222
-			OC::$server->getLogger()->logException($ex);
223
-			$l = \OC::$server->getL10N('core');
224
-			$hint = method_exists($ex, 'getHint') ? $ex->getHint() : '';
225
-			\OC_Template::printErrorPage($l->t('Can\'t read file'), $hint, 200);
226
-		}
227
-	}
228
-
229
-	/**
230
-	 * @param string $rangeHeaderPos
231
-	 * @param int $fileSize
232
-	 * @return array $rangeArray ('from'=>int,'to'=>int), ...
233
-	 */
234
-	private static function parseHttpRangeHeader($rangeHeaderPos, $fileSize) {
235
-		$rArray=explode(',', $rangeHeaderPos);
236
-		$minOffset = 0;
237
-		$ind = 0;
238
-
239
-		$rangeArray = [];
240
-
241
-		foreach ($rArray as $value) {
242
-			$ranges = explode('-', $value);
243
-			if (is_numeric($ranges[0])) {
244
-				if ($ranges[0] < $minOffset) { // case: bytes=500-700,601-999
245
-					$ranges[0] = $minOffset;
246
-				}
247
-				if ($ind > 0 && $rangeArray[$ind-1]['to']+1 == $ranges[0]) { // case: bytes=500-600,601-999
248
-					$ind--;
249
-					$ranges[0] = $rangeArray[$ind]['from'];
250
-				}
251
-			}
252
-
253
-			if (is_numeric($ranges[0]) && is_numeric($ranges[1]) && $ranges[0] < $fileSize && $ranges[0] <= $ranges[1]) {
254
-				// case: x-x
255
-				if ($ranges[1] >= $fileSize) {
256
-					$ranges[1] = $fileSize-1;
257
-				}
258
-				$rangeArray[$ind++] = [ 'from' => $ranges[0], 'to' => $ranges[1], 'size' => $fileSize ];
259
-				$minOffset = $ranges[1] + 1;
260
-				if ($minOffset >= $fileSize) {
261
-					break;
262
-				}
263
-			} elseif (is_numeric($ranges[0]) && $ranges[0] < $fileSize) {
264
-				// case: x-
265
-				$rangeArray[$ind++] = [ 'from' => $ranges[0], 'to' => $fileSize-1, 'size' => $fileSize ];
266
-				break;
267
-			} elseif (is_numeric($ranges[1])) {
268
-				// case: -x
269
-				if ($ranges[1] > $fileSize) {
270
-					$ranges[1] = $fileSize;
271
-				}
272
-				$rangeArray[$ind++] = [ 'from' => $fileSize-$ranges[1], 'to' => $fileSize-1, 'size' => $fileSize ];
273
-				break;
274
-			}
275
-		}
276
-		return $rangeArray;
277
-	}
278
-
279
-	/**
280
-	 * @param View $view
281
-	 * @param string $name
282
-	 * @param string $dir
283
-	 * @param array $params ; 'head' boolean to only send header of the request ; 'range' http range header
284
-	 */
285
-	private static function getSingleFile($view, $dir, $name, $params) {
286
-		$filename = $dir . '/' . $name;
287
-		$file = null;
288
-
289
-		try {
290
-			$userFolder = \OC::$server->getRootFolder()->get(\OC\Files\Filesystem::getRoot());
291
-			$file = $userFolder->get($filename);
292
-			if (!$file instanceof \OC\Files\Node\File || !$file->isReadable()) {
293
-				http_response_code(403);
294
-				die('403 Forbidden');
295
-			}
296
-			$fileSize = $file->getSize();
297
-		} catch (\OCP\Files\NotPermittedException $e) {
298
-			http_response_code(403);
299
-			die('403 Forbidden');
300
-		} catch (\OCP\Files\InvalidPathException $e) {
301
-			http_response_code(403);
302
-			die('403 Forbidden');
303
-		} catch (\OCP\Files\NotFoundException $e) {
304
-			http_response_code(404);
305
-			$tmpl = new OC_Template('', '404', 'guest');
306
-			$tmpl->printPage();
307
-			exit();
308
-		}
309
-
310
-		OC_Util::obEnd();
311
-		$view->lockFile($filename, ILockingProvider::LOCK_SHARED);
312
-
313
-		$rangeArray = [];
314
-
315
-		if (isset($params['range']) && substr($params['range'], 0, 6) === 'bytes=') {
316
-			$rangeArray = self::parseHttpRangeHeader(substr($params['range'], 6), $fileSize);
317
-		}
318
-
319
-		self::sendHeaders($filename, $name, $rangeArray);
320
-
321
-		if (isset($params['head']) && $params['head']) {
322
-			return;
323
-		}
324
-
325
-		if (!empty($rangeArray)) {
326
-			try {
327
-				if (count($rangeArray) == 1) {
328
-					$view->readfilePart($filename, $rangeArray[0]['from'], $rangeArray[0]['to']);
329
-				} else {
330
-					// check if file is seekable (if not throw UnseekableException)
331
-					// we have to check it before body contents
332
-					$view->readfilePart($filename, $rangeArray[0]['size'], $rangeArray[0]['size']);
333
-
334
-					$type = \OC::$server->getMimeTypeDetector()->getSecureMimeType(\OC\Files\Filesystem::getMimeType($filename));
335
-
336
-					foreach ($rangeArray as $range) {
337
-						echo "\r\n--".self::getBoundary()."\r\n".
338
-						 "Content-type: ".$type."\r\n".
339
-						 "Content-range: bytes ".$range['from']."-".$range['to']."/".$range['size']."\r\n\r\n";
340
-						$view->readfilePart($filename, $range['from'], $range['to']);
341
-					}
342
-					echo "\r\n--".self::getBoundary()."--\r\n";
343
-				}
344
-			} catch (\OCP\Files\UnseekableException $ex) {
345
-				// file is unseekable
346
-				header_remove('Accept-Ranges');
347
-				header_remove('Content-Range');
348
-				http_response_code(200);
349
-				self::sendHeaders($filename, $name, []);
350
-				$view->readfile($filename);
351
-			}
352
-		} else {
353
-			$view->readfile($filename);
354
-		}
355
-	}
356
-
357
-	/**
358
-	 * Returns the total (recursive) number of files and folders in the given
359
-	 * FileInfos.
360
-	 *
361
-	 * @param \OCP\Files\FileInfo[] $fileInfos the FileInfos to count
362
-	 * @return int the total number of files and folders
363
-	 */
364
-	private static function getNumberOfFiles($fileInfos) {
365
-		$numberOfFiles = 0;
366
-
367
-		$view = new View();
368
-
369
-		while ($fileInfo = array_pop($fileInfos)) {
370
-			$numberOfFiles++;
371
-
372
-			if ($fileInfo->getType() === \OCP\Files\FileInfo::TYPE_FOLDER) {
373
-				$fileInfos = array_merge($fileInfos, $view->getDirectoryContent($fileInfo->getPath()));
374
-			}
375
-		}
376
-
377
-		return $numberOfFiles;
378
-	}
379
-
380
-	/**
381
-	 * @param View $view
382
-	 * @param string $dir
383
-	 * @param string[]|string $files
384
-	 */
385
-	public static function lockFiles($view, $dir, $files) {
386
-		if (!is_array($files)) {
387
-			$file = $dir . '/' . $files;
388
-			$files = [$file];
389
-		}
390
-		foreach ($files as $file) {
391
-			$file = $dir . '/' . $file;
392
-			$view->lockFile($file, ILockingProvider::LOCK_SHARED);
393
-			if ($view->is_dir($file)) {
394
-				$contents = $view->getDirectoryContent($file);
395
-				$contents = array_map(function ($fileInfo) use ($file) {
396
-					/** @var \OCP\Files\FileInfo $fileInfo */
397
-					return $file . '/' . $fileInfo->getName();
398
-				}, $contents);
399
-				self::lockFiles($view, $dir, $contents);
400
-			}
401
-		}
402
-	}
403
-
404
-	/**
405
-	 * @param string $dir
406
-	 * @param $files
407
-	 * @param integer $getType
408
-	 * @param View $view
409
-	 * @param string $filename
410
-	 */
411
-	private static function unlockAllTheFiles($dir, $files, $getType, $view, $filename) {
412
-		if ($getType === self::FILE) {
413
-			$view->unlockFile($filename, ILockingProvider::LOCK_SHARED);
414
-		}
415
-		if ($getType === self::ZIP_FILES) {
416
-			foreach ($files as $file) {
417
-				$file = $dir . '/' . $file;
418
-				$view->unlockFile($file, ILockingProvider::LOCK_SHARED);
419
-			}
420
-		}
421
-		if ($getType === self::ZIP_DIR) {
422
-			$file = $dir . '/' . $files;
423
-			$view->unlockFile($file, ILockingProvider::LOCK_SHARED);
424
-		}
425
-	}
54
+    public const FILE = 1;
55
+    public const ZIP_FILES = 2;
56
+    public const ZIP_DIR = 3;
57
+
58
+    public const UPLOAD_MIN_LIMIT_BYTES = 1048576; // 1 MiB
59
+
60
+
61
+    private static $multipartBoundary = '';
62
+
63
+    /**
64
+     * @return string
65
+     */
66
+    private static function getBoundary() {
67
+        if (empty(self::$multipartBoundary)) {
68
+            self::$multipartBoundary = md5(mt_rand());
69
+        }
70
+        return self::$multipartBoundary;
71
+    }
72
+
73
+    /**
74
+     * @param string $filename
75
+     * @param string $name
76
+     * @param array $rangeArray ('from'=>int,'to'=>int), ...
77
+     */
78
+    private static function sendHeaders($filename, $name, array $rangeArray) {
79
+        OC_Response::setContentDispositionHeader($name, 'attachment');
80
+        header('Content-Transfer-Encoding: binary', true);
81
+        header('Pragma: public');// enable caching in IE
82
+        header('Expires: 0');
83
+        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
84
+        $fileSize = \OC\Files\Filesystem::filesize($filename);
85
+        $type = \OC::$server->getMimeTypeDetector()->getSecureMimeType(\OC\Files\Filesystem::getMimeType($filename));
86
+        if ($fileSize > -1) {
87
+            if (!empty($rangeArray)) {
88
+                http_response_code(206);
89
+                header('Accept-Ranges: bytes', true);
90
+                if (count($rangeArray) > 1) {
91
+                    $type = 'multipart/byteranges; boundary='.self::getBoundary();
92
+                // no Content-Length header here
93
+                } else {
94
+                    header(sprintf('Content-Range: bytes %d-%d/%d', $rangeArray[0]['from'], $rangeArray[0]['to'], $fileSize), true);
95
+                    OC_Response::setContentLengthHeader($rangeArray[0]['to'] - $rangeArray[0]['from'] + 1);
96
+                }
97
+            } else {
98
+                OC_Response::setContentLengthHeader($fileSize);
99
+            }
100
+        }
101
+        header('Content-Type: '.$type, true);
102
+    }
103
+
104
+    /**
105
+     * return the content of a file or return a zip file containing multiple files
106
+     *
107
+     * @param string $dir
108
+     * @param string $files ; separated list of files to download
109
+     * @param array $params ; 'head' boolean to only send header of the request ; 'range' http range header
110
+     */
111
+    public static function get($dir, $files, $params = null) {
112
+        $view = \OC\Files\Filesystem::getView();
113
+        $getType = self::FILE;
114
+        $filename = $dir;
115
+        try {
116
+            if (is_array($files) && count($files) === 1) {
117
+                $files = $files[0];
118
+            }
119
+
120
+            if (!is_array($files)) {
121
+                $filename = $dir . '/' . $files;
122
+                if (!$view->is_dir($filename)) {
123
+                    self::getSingleFile($view, $dir, $files, is_null($params) ? [] : $params);
124
+                    return;
125
+                }
126
+            }
127
+
128
+            $name = 'download';
129
+            if (is_array($files)) {
130
+                $getType = self::ZIP_FILES;
131
+                $basename = basename($dir);
132
+                if ($basename) {
133
+                    $name = $basename;
134
+                }
135
+
136
+                $filename = $dir . '/' . $name;
137
+            } else {
138
+                $filename = $dir . '/' . $files;
139
+                $getType = self::ZIP_DIR;
140
+                // downloading root ?
141
+                if ($files !== '') {
142
+                    $name = $files;
143
+                }
144
+            }
145
+
146
+            self::lockFiles($view, $dir, $files);
147
+
148
+            /* Calculate filesize and number of files */
149
+            if ($getType === self::ZIP_FILES) {
150
+                $fileInfos = [];
151
+                $fileSize = 0;
152
+                foreach ($files as $file) {
153
+                    $fileInfo = \OC\Files\Filesystem::getFileInfo($dir . '/' . $file);
154
+                    $fileSize += $fileInfo->getSize();
155
+                    $fileInfos[] = $fileInfo;
156
+                }
157
+                $numberOfFiles = self::getNumberOfFiles($fileInfos);
158
+            } elseif ($getType === self::ZIP_DIR) {
159
+                $fileInfo = \OC\Files\Filesystem::getFileInfo($dir . '/' . $files);
160
+                $fileSize = $fileInfo->getSize();
161
+                $numberOfFiles = self::getNumberOfFiles([$fileInfo]);
162
+            }
163
+
164
+            $streamer = new Streamer(\OC::$server->getRequest(), $fileSize, $numberOfFiles);
165
+            OC_Util::obEnd();
166
+
167
+            $streamer->sendHeaders($name);
168
+            $executionTime = (int)OC::$server->get(IniGetWrapper::class)->getNumeric('max_execution_time');
169
+            if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
170
+                @set_time_limit(0);
171
+            }
172
+            ignore_user_abort(true);
173
+
174
+            if ($getType === self::ZIP_FILES) {
175
+                foreach ($files as $file) {
176
+                    $file = $dir . '/' . $file;
177
+                    if (\OC\Files\Filesystem::is_file($file)) {
178
+                        $userFolder = \OC::$server->getRootFolder()->get(\OC\Files\Filesystem::getRoot());
179
+                        $file = $userFolder->get($file);
180
+                        if ($file instanceof \OC\Files\Node\File) {
181
+                            try {
182
+                                $fh = $file->fopen('r');
183
+                            } catch (\OCP\Files\NotPermittedException $e) {
184
+                                continue;
185
+                            }
186
+                            $fileSize = $file->getSize();
187
+                            $fileTime = $file->getMTime();
188
+                        } else {
189
+                            // File is not a file? …
190
+                            \OC::$server->getLogger()->debug(
191
+                                'File given, but no Node available. Name {file}',
192
+                                [ 'app' => 'files', 'file' => $file ]
193
+                            );
194
+                            continue;
195
+                        }
196
+                        $streamer->addFileFromStream($fh, $file->getName(), $fileSize, $fileTime);
197
+                        fclose($fh);
198
+                    } elseif (\OC\Files\Filesystem::is_dir($file)) {
199
+                        $streamer->addDirRecursive($file);
200
+                    }
201
+                }
202
+            } elseif ($getType === self::ZIP_DIR) {
203
+                $file = $dir . '/' . $files;
204
+                $streamer->addDirRecursive($file);
205
+            }
206
+            $streamer->finalize();
207
+            set_time_limit($executionTime);
208
+            self::unlockAllTheFiles($dir, $files, $getType, $view, $filename);
209
+        } catch (\OCP\Lock\LockedException $ex) {
210
+            self::unlockAllTheFiles($dir, $files, $getType, $view, $filename);
211
+            OC::$server->getLogger()->logException($ex);
212
+            $l = \OC::$server->getL10N('core');
213
+            $hint = method_exists($ex, 'getHint') ? $ex->getHint() : '';
214
+            \OC_Template::printErrorPage($l->t('File is currently busy, please try again later'), $hint, 200);
215
+        } catch (\OCP\Files\ForbiddenException $ex) {
216
+            self::unlockAllTheFiles($dir, $files, $getType, $view, $filename);
217
+            OC::$server->getLogger()->logException($ex);
218
+            $l = \OC::$server->getL10N('core');
219
+            \OC_Template::printErrorPage($l->t('Can\'t read file'), $ex->getMessage(), 200);
220
+        } catch (\Exception $ex) {
221
+            self::unlockAllTheFiles($dir, $files, $getType, $view, $filename);
222
+            OC::$server->getLogger()->logException($ex);
223
+            $l = \OC::$server->getL10N('core');
224
+            $hint = method_exists($ex, 'getHint') ? $ex->getHint() : '';
225
+            \OC_Template::printErrorPage($l->t('Can\'t read file'), $hint, 200);
226
+        }
227
+    }
228
+
229
+    /**
230
+     * @param string $rangeHeaderPos
231
+     * @param int $fileSize
232
+     * @return array $rangeArray ('from'=>int,'to'=>int), ...
233
+     */
234
+    private static function parseHttpRangeHeader($rangeHeaderPos, $fileSize) {
235
+        $rArray=explode(',', $rangeHeaderPos);
236
+        $minOffset = 0;
237
+        $ind = 0;
238
+
239
+        $rangeArray = [];
240
+
241
+        foreach ($rArray as $value) {
242
+            $ranges = explode('-', $value);
243
+            if (is_numeric($ranges[0])) {
244
+                if ($ranges[0] < $minOffset) { // case: bytes=500-700,601-999
245
+                    $ranges[0] = $minOffset;
246
+                }
247
+                if ($ind > 0 && $rangeArray[$ind-1]['to']+1 == $ranges[0]) { // case: bytes=500-600,601-999
248
+                    $ind--;
249
+                    $ranges[0] = $rangeArray[$ind]['from'];
250
+                }
251
+            }
252
+
253
+            if (is_numeric($ranges[0]) && is_numeric($ranges[1]) && $ranges[0] < $fileSize && $ranges[0] <= $ranges[1]) {
254
+                // case: x-x
255
+                if ($ranges[1] >= $fileSize) {
256
+                    $ranges[1] = $fileSize-1;
257
+                }
258
+                $rangeArray[$ind++] = [ 'from' => $ranges[0], 'to' => $ranges[1], 'size' => $fileSize ];
259
+                $minOffset = $ranges[1] + 1;
260
+                if ($minOffset >= $fileSize) {
261
+                    break;
262
+                }
263
+            } elseif (is_numeric($ranges[0]) && $ranges[0] < $fileSize) {
264
+                // case: x-
265
+                $rangeArray[$ind++] = [ 'from' => $ranges[0], 'to' => $fileSize-1, 'size' => $fileSize ];
266
+                break;
267
+            } elseif (is_numeric($ranges[1])) {
268
+                // case: -x
269
+                if ($ranges[1] > $fileSize) {
270
+                    $ranges[1] = $fileSize;
271
+                }
272
+                $rangeArray[$ind++] = [ 'from' => $fileSize-$ranges[1], 'to' => $fileSize-1, 'size' => $fileSize ];
273
+                break;
274
+            }
275
+        }
276
+        return $rangeArray;
277
+    }
278
+
279
+    /**
280
+     * @param View $view
281
+     * @param string $name
282
+     * @param string $dir
283
+     * @param array $params ; 'head' boolean to only send header of the request ; 'range' http range header
284
+     */
285
+    private static function getSingleFile($view, $dir, $name, $params) {
286
+        $filename = $dir . '/' . $name;
287
+        $file = null;
288
+
289
+        try {
290
+            $userFolder = \OC::$server->getRootFolder()->get(\OC\Files\Filesystem::getRoot());
291
+            $file = $userFolder->get($filename);
292
+            if (!$file instanceof \OC\Files\Node\File || !$file->isReadable()) {
293
+                http_response_code(403);
294
+                die('403 Forbidden');
295
+            }
296
+            $fileSize = $file->getSize();
297
+        } catch (\OCP\Files\NotPermittedException $e) {
298
+            http_response_code(403);
299
+            die('403 Forbidden');
300
+        } catch (\OCP\Files\InvalidPathException $e) {
301
+            http_response_code(403);
302
+            die('403 Forbidden');
303
+        } catch (\OCP\Files\NotFoundException $e) {
304
+            http_response_code(404);
305
+            $tmpl = new OC_Template('', '404', 'guest');
306
+            $tmpl->printPage();
307
+            exit();
308
+        }
309
+
310
+        OC_Util::obEnd();
311
+        $view->lockFile($filename, ILockingProvider::LOCK_SHARED);
312
+
313
+        $rangeArray = [];
314
+
315
+        if (isset($params['range']) && substr($params['range'], 0, 6) === 'bytes=') {
316
+            $rangeArray = self::parseHttpRangeHeader(substr($params['range'], 6), $fileSize);
317
+        }
318
+
319
+        self::sendHeaders($filename, $name, $rangeArray);
320
+
321
+        if (isset($params['head']) && $params['head']) {
322
+            return;
323
+        }
324
+
325
+        if (!empty($rangeArray)) {
326
+            try {
327
+                if (count($rangeArray) == 1) {
328
+                    $view->readfilePart($filename, $rangeArray[0]['from'], $rangeArray[0]['to']);
329
+                } else {
330
+                    // check if file is seekable (if not throw UnseekableException)
331
+                    // we have to check it before body contents
332
+                    $view->readfilePart($filename, $rangeArray[0]['size'], $rangeArray[0]['size']);
333
+
334
+                    $type = \OC::$server->getMimeTypeDetector()->getSecureMimeType(\OC\Files\Filesystem::getMimeType($filename));
335
+
336
+                    foreach ($rangeArray as $range) {
337
+                        echo "\r\n--".self::getBoundary()."\r\n".
338
+                            "Content-type: ".$type."\r\n".
339
+                            "Content-range: bytes ".$range['from']."-".$range['to']."/".$range['size']."\r\n\r\n";
340
+                        $view->readfilePart($filename, $range['from'], $range['to']);
341
+                    }
342
+                    echo "\r\n--".self::getBoundary()."--\r\n";
343
+                }
344
+            } catch (\OCP\Files\UnseekableException $ex) {
345
+                // file is unseekable
346
+                header_remove('Accept-Ranges');
347
+                header_remove('Content-Range');
348
+                http_response_code(200);
349
+                self::sendHeaders($filename, $name, []);
350
+                $view->readfile($filename);
351
+            }
352
+        } else {
353
+            $view->readfile($filename);
354
+        }
355
+    }
356
+
357
+    /**
358
+     * Returns the total (recursive) number of files and folders in the given
359
+     * FileInfos.
360
+     *
361
+     * @param \OCP\Files\FileInfo[] $fileInfos the FileInfos to count
362
+     * @return int the total number of files and folders
363
+     */
364
+    private static function getNumberOfFiles($fileInfos) {
365
+        $numberOfFiles = 0;
366
+
367
+        $view = new View();
368
+
369
+        while ($fileInfo = array_pop($fileInfos)) {
370
+            $numberOfFiles++;
371
+
372
+            if ($fileInfo->getType() === \OCP\Files\FileInfo::TYPE_FOLDER) {
373
+                $fileInfos = array_merge($fileInfos, $view->getDirectoryContent($fileInfo->getPath()));
374
+            }
375
+        }
376
+
377
+        return $numberOfFiles;
378
+    }
379
+
380
+    /**
381
+     * @param View $view
382
+     * @param string $dir
383
+     * @param string[]|string $files
384
+     */
385
+    public static function lockFiles($view, $dir, $files) {
386
+        if (!is_array($files)) {
387
+            $file = $dir . '/' . $files;
388
+            $files = [$file];
389
+        }
390
+        foreach ($files as $file) {
391
+            $file = $dir . '/' . $file;
392
+            $view->lockFile($file, ILockingProvider::LOCK_SHARED);
393
+            if ($view->is_dir($file)) {
394
+                $contents = $view->getDirectoryContent($file);
395
+                $contents = array_map(function ($fileInfo) use ($file) {
396
+                    /** @var \OCP\Files\FileInfo $fileInfo */
397
+                    return $file . '/' . $fileInfo->getName();
398
+                }, $contents);
399
+                self::lockFiles($view, $dir, $contents);
400
+            }
401
+        }
402
+    }
403
+
404
+    /**
405
+     * @param string $dir
406
+     * @param $files
407
+     * @param integer $getType
408
+     * @param View $view
409
+     * @param string $filename
410
+     */
411
+    private static function unlockAllTheFiles($dir, $files, $getType, $view, $filename) {
412
+        if ($getType === self::FILE) {
413
+            $view->unlockFile($filename, ILockingProvider::LOCK_SHARED);
414
+        }
415
+        if ($getType === self::ZIP_FILES) {
416
+            foreach ($files as $file) {
417
+                $file = $dir . '/' . $file;
418
+                $view->unlockFile($file, ILockingProvider::LOCK_SHARED);
419
+            }
420
+        }
421
+        if ($getType === self::ZIP_DIR) {
422
+            $file = $dir . '/' . $files;
423
+            $view->unlockFile($file, ILockingProvider::LOCK_SHARED);
424
+        }
425
+    }
426 426
 }
Please login to merge, or discard this patch.
Spacing   +23 added lines, -23 removed lines patch added patch discarded remove patch
@@ -78,7 +78,7 @@  discard block
 block discarded – undo
78 78
 	private static function sendHeaders($filename, $name, array $rangeArray) {
79 79
 		OC_Response::setContentDispositionHeader($name, 'attachment');
80 80
 		header('Content-Transfer-Encoding: binary', true);
81
-		header('Pragma: public');// enable caching in IE
81
+		header('Pragma: public'); // enable caching in IE
82 82
 		header('Expires: 0');
83 83
 		header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
84 84
 		$fileSize = \OC\Files\Filesystem::filesize($filename);
@@ -118,7 +118,7 @@  discard block
 block discarded – undo
118 118
 			}
119 119
 
120 120
 			if (!is_array($files)) {
121
-				$filename = $dir . '/' . $files;
121
+				$filename = $dir.'/'.$files;
122 122
 				if (!$view->is_dir($filename)) {
123 123
 					self::getSingleFile($view, $dir, $files, is_null($params) ? [] : $params);
124 124
 					return;
@@ -133,9 +133,9 @@  discard block
 block discarded – undo
133 133
 					$name = $basename;
134 134
 				}
135 135
 
136
-				$filename = $dir . '/' . $name;
136
+				$filename = $dir.'/'.$name;
137 137
 			} else {
138
-				$filename = $dir . '/' . $files;
138
+				$filename = $dir.'/'.$files;
139 139
 				$getType = self::ZIP_DIR;
140 140
 				// downloading root ?
141 141
 				if ($files !== '') {
@@ -150,13 +150,13 @@  discard block
 block discarded – undo
150 150
 				$fileInfos = [];
151 151
 				$fileSize = 0;
152 152
 				foreach ($files as $file) {
153
-					$fileInfo = \OC\Files\Filesystem::getFileInfo($dir . '/' . $file);
153
+					$fileInfo = \OC\Files\Filesystem::getFileInfo($dir.'/'.$file);
154 154
 					$fileSize += $fileInfo->getSize();
155 155
 					$fileInfos[] = $fileInfo;
156 156
 				}
157 157
 				$numberOfFiles = self::getNumberOfFiles($fileInfos);
158 158
 			} elseif ($getType === self::ZIP_DIR) {
159
-				$fileInfo = \OC\Files\Filesystem::getFileInfo($dir . '/' . $files);
159
+				$fileInfo = \OC\Files\Filesystem::getFileInfo($dir.'/'.$files);
160 160
 				$fileSize = $fileInfo->getSize();
161 161
 				$numberOfFiles = self::getNumberOfFiles([$fileInfo]);
162 162
 			}
@@ -165,7 +165,7 @@  discard block
 block discarded – undo
165 165
 			OC_Util::obEnd();
166 166
 
167 167
 			$streamer->sendHeaders($name);
168
-			$executionTime = (int)OC::$server->get(IniGetWrapper::class)->getNumeric('max_execution_time');
168
+			$executionTime = (int) OC::$server->get(IniGetWrapper::class)->getNumeric('max_execution_time');
169 169
 			if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
170 170
 				@set_time_limit(0);
171 171
 			}
@@ -173,7 +173,7 @@  discard block
 block discarded – undo
173 173
 
174 174
 			if ($getType === self::ZIP_FILES) {
175 175
 				foreach ($files as $file) {
176
-					$file = $dir . '/' . $file;
176
+					$file = $dir.'/'.$file;
177 177
 					if (\OC\Files\Filesystem::is_file($file)) {
178 178
 						$userFolder = \OC::$server->getRootFolder()->get(\OC\Files\Filesystem::getRoot());
179 179
 						$file = $userFolder->get($file);
@@ -189,7 +189,7 @@  discard block
 block discarded – undo
189 189
 							// File is not a file? …
190 190
 							\OC::$server->getLogger()->debug(
191 191
 								'File given, but no Node available. Name {file}',
192
-								[ 'app' => 'files', 'file' => $file ]
192
+								['app' => 'files', 'file' => $file]
193 193
 							);
194 194
 							continue;
195 195
 						}
@@ -200,7 +200,7 @@  discard block
 block discarded – undo
200 200
 					}
201 201
 				}
202 202
 			} elseif ($getType === self::ZIP_DIR) {
203
-				$file = $dir . '/' . $files;
203
+				$file = $dir.'/'.$files;
204 204
 				$streamer->addDirRecursive($file);
205 205
 			}
206 206
 			$streamer->finalize();
@@ -232,7 +232,7 @@  discard block
 block discarded – undo
232 232
 	 * @return array $rangeArray ('from'=>int,'to'=>int), ...
233 233
 	 */
234 234
 	private static function parseHttpRangeHeader($rangeHeaderPos, $fileSize) {
235
-		$rArray=explode(',', $rangeHeaderPos);
235
+		$rArray = explode(',', $rangeHeaderPos);
236 236
 		$minOffset = 0;
237 237
 		$ind = 0;
238 238
 
@@ -244,7 +244,7 @@  discard block
 block discarded – undo
244 244
 				if ($ranges[0] < $minOffset) { // case: bytes=500-700,601-999
245 245
 					$ranges[0] = $minOffset;
246 246
 				}
247
-				if ($ind > 0 && $rangeArray[$ind-1]['to']+1 == $ranges[0]) { // case: bytes=500-600,601-999
247
+				if ($ind > 0 && $rangeArray[$ind - 1]['to'] + 1 == $ranges[0]) { // case: bytes=500-600,601-999
248 248
 					$ind--;
249 249
 					$ranges[0] = $rangeArray[$ind]['from'];
250 250
 				}
@@ -253,23 +253,23 @@  discard block
 block discarded – undo
253 253
 			if (is_numeric($ranges[0]) && is_numeric($ranges[1]) && $ranges[0] < $fileSize && $ranges[0] <= $ranges[1]) {
254 254
 				// case: x-x
255 255
 				if ($ranges[1] >= $fileSize) {
256
-					$ranges[1] = $fileSize-1;
256
+					$ranges[1] = $fileSize - 1;
257 257
 				}
258
-				$rangeArray[$ind++] = [ 'from' => $ranges[0], 'to' => $ranges[1], 'size' => $fileSize ];
258
+				$rangeArray[$ind++] = ['from' => $ranges[0], 'to' => $ranges[1], 'size' => $fileSize];
259 259
 				$minOffset = $ranges[1] + 1;
260 260
 				if ($minOffset >= $fileSize) {
261 261
 					break;
262 262
 				}
263 263
 			} elseif (is_numeric($ranges[0]) && $ranges[0] < $fileSize) {
264 264
 				// case: x-
265
-				$rangeArray[$ind++] = [ 'from' => $ranges[0], 'to' => $fileSize-1, 'size' => $fileSize ];
265
+				$rangeArray[$ind++] = ['from' => $ranges[0], 'to' => $fileSize - 1, 'size' => $fileSize];
266 266
 				break;
267 267
 			} elseif (is_numeric($ranges[1])) {
268 268
 				// case: -x
269 269
 				if ($ranges[1] > $fileSize) {
270 270
 					$ranges[1] = $fileSize;
271 271
 				}
272
-				$rangeArray[$ind++] = [ 'from' => $fileSize-$ranges[1], 'to' => $fileSize-1, 'size' => $fileSize ];
272
+				$rangeArray[$ind++] = ['from' => $fileSize - $ranges[1], 'to' => $fileSize - 1, 'size' => $fileSize];
273 273
 				break;
274 274
 			}
275 275
 		}
@@ -283,7 +283,7 @@  discard block
 block discarded – undo
283 283
 	 * @param array $params ; 'head' boolean to only send header of the request ; 'range' http range header
284 284
 	 */
285 285
 	private static function getSingleFile($view, $dir, $name, $params) {
286
-		$filename = $dir . '/' . $name;
286
+		$filename = $dir.'/'.$name;
287 287
 		$file = null;
288 288
 
289 289
 		try {
@@ -384,17 +384,17 @@  discard block
 block discarded – undo
384 384
 	 */
385 385
 	public static function lockFiles($view, $dir, $files) {
386 386
 		if (!is_array($files)) {
387
-			$file = $dir . '/' . $files;
387
+			$file = $dir.'/'.$files;
388 388
 			$files = [$file];
389 389
 		}
390 390
 		foreach ($files as $file) {
391
-			$file = $dir . '/' . $file;
391
+			$file = $dir.'/'.$file;
392 392
 			$view->lockFile($file, ILockingProvider::LOCK_SHARED);
393 393
 			if ($view->is_dir($file)) {
394 394
 				$contents = $view->getDirectoryContent($file);
395
-				$contents = array_map(function ($fileInfo) use ($file) {
395
+				$contents = array_map(function($fileInfo) use ($file) {
396 396
 					/** @var \OCP\Files\FileInfo $fileInfo */
397
-					return $file . '/' . $fileInfo->getName();
397
+					return $file.'/'.$fileInfo->getName();
398 398
 				}, $contents);
399 399
 				self::lockFiles($view, $dir, $contents);
400 400
 			}
@@ -414,12 +414,12 @@  discard block
 block discarded – undo
414 414
 		}
415 415
 		if ($getType === self::ZIP_FILES) {
416 416
 			foreach ($files as $file) {
417
-				$file = $dir . '/' . $file;
417
+				$file = $dir.'/'.$file;
418 418
 				$view->unlockFile($file, ILockingProvider::LOCK_SHARED);
419 419
 			}
420 420
 		}
421 421
 		if ($getType === self::ZIP_DIR) {
422
-			$file = $dir . '/' . $files;
422
+			$file = $dir.'/'.$files;
423 423
 			$view->unlockFile($file, ILockingProvider::LOCK_SHARED);
424 424
 		}
425 425
 	}
Please login to merge, or discard this patch.
lib/private/legacy/OC_Util.php 1 patch
Indentation   +1404 added lines, -1404 removed lines patch added patch discarded remove patch
@@ -72,1413 +72,1413 @@
 block discarded – undo
72 72
 use OCP\IUserSession;
73 73
 
74 74
 class OC_Util {
75
-	public static $scripts = [];
76
-	public static $styles = [];
77
-	public static $headers = [];
78
-	private static $rootMounted = false;
79
-	private static $fsSetup = false;
80
-
81
-	/** @var array Local cache of version.php */
82
-	private static $versionCache = null;
83
-
84
-	protected static function getAppManager() {
85
-		return \OC::$server->getAppManager();
86
-	}
87
-
88
-	private static function initLocalStorageRootFS() {
89
-		// mount local file backend as root
90
-		$configDataDirectory = \OC::$server->getSystemConfig()->getValue("datadirectory", OC::$SERVERROOT . "/data");
91
-		//first set up the local "root" storage
92
-		\OC\Files\Filesystem::initMountManager();
93
-		if (!self::$rootMounted) {
94
-			\OC\Files\Filesystem::mount(LocalRootStorage::class, ['datadir' => $configDataDirectory], '/');
95
-			self::$rootMounted = true;
96
-		}
97
-	}
98
-
99
-	/**
100
-	 * mounting an object storage as the root fs will in essence remove the
101
-	 * necessity of a data folder being present.
102
-	 * TODO make home storage aware of this and use the object storage instead of local disk access
103
-	 *
104
-	 * @param array $config containing 'class' and optional 'arguments'
105
-	 * @suppress PhanDeprecatedFunction
106
-	 */
107
-	private static function initObjectStoreRootFS($config) {
108
-		// check misconfiguration
109
-		if (empty($config['class'])) {
110
-			\OCP\Util::writeLog('files', 'No class given for objectstore', ILogger::ERROR);
111
-		}
112
-		if (!isset($config['arguments'])) {
113
-			$config['arguments'] = [];
114
-		}
115
-
116
-		// instantiate object store implementation
117
-		$name = $config['class'];
118
-		if (strpos($name, 'OCA\\') === 0 && substr_count($name, '\\') >= 2) {
119
-			$segments = explode('\\', $name);
120
-			OC_App::loadApp(strtolower($segments[1]));
121
-		}
122
-		$config['arguments']['objectstore'] = new $config['class']($config['arguments']);
123
-		// mount with plain / root object store implementation
124
-		$config['class'] = '\OC\Files\ObjectStore\ObjectStoreStorage';
125
-
126
-		// mount object storage as root
127
-		\OC\Files\Filesystem::initMountManager();
128
-		if (!self::$rootMounted) {
129
-			\OC\Files\Filesystem::mount($config['class'], $config['arguments'], '/');
130
-			self::$rootMounted = true;
131
-		}
132
-	}
133
-
134
-	/**
135
-	 * mounting an object storage as the root fs will in essence remove the
136
-	 * necessity of a data folder being present.
137
-	 *
138
-	 * @param array $config containing 'class' and optional 'arguments'
139
-	 * @suppress PhanDeprecatedFunction
140
-	 */
141
-	private static function initObjectStoreMultibucketRootFS($config) {
142
-		// check misconfiguration
143
-		if (empty($config['class'])) {
144
-			\OCP\Util::writeLog('files', 'No class given for objectstore', ILogger::ERROR);
145
-		}
146
-		if (!isset($config['arguments'])) {
147
-			$config['arguments'] = [];
148
-		}
149
-
150
-		// instantiate object store implementation
151
-		$name = $config['class'];
152
-		if (strpos($name, 'OCA\\') === 0 && substr_count($name, '\\') >= 2) {
153
-			$segments = explode('\\', $name);
154
-			OC_App::loadApp(strtolower($segments[1]));
155
-		}
156
-
157
-		if (!isset($config['arguments']['bucket'])) {
158
-			$config['arguments']['bucket'] = '';
159
-		}
160
-		// put the root FS always in first bucket for multibucket configuration
161
-		$config['arguments']['bucket'] .= '0';
162
-
163
-		$config['arguments']['objectstore'] = new $config['class']($config['arguments']);
164
-		// mount with plain / root object store implementation
165
-		$config['class'] = '\OC\Files\ObjectStore\ObjectStoreStorage';
166
-
167
-		// mount object storage as root
168
-		\OC\Files\Filesystem::initMountManager();
169
-		if (!self::$rootMounted) {
170
-			\OC\Files\Filesystem::mount($config['class'], $config['arguments'], '/');
171
-			self::$rootMounted = true;
172
-		}
173
-	}
174
-
175
-	/**
176
-	 * Can be set up
177
-	 *
178
-	 * @param string $user
179
-	 * @return boolean
180
-	 * @description configure the initial filesystem based on the configuration
181
-	 * @suppress PhanDeprecatedFunction
182
-	 * @suppress PhanAccessMethodInternal
183
-	 */
184
-	public static function setupFS($user = '') {
185
-		//setting up the filesystem twice can only lead to trouble
186
-		if (self::$fsSetup) {
187
-			return false;
188
-		}
189
-
190
-		\OC::$server->getEventLogger()->start('setup_fs', 'Setup filesystem');
191
-
192
-		// If we are not forced to load a specific user we load the one that is logged in
193
-		if ($user === null) {
194
-			$user = '';
195
-		} elseif ($user == "" && \OC::$server->getUserSession()->isLoggedIn()) {
196
-			$user = OC_User::getUser();
197
-		}
198
-
199
-		// load all filesystem apps before, so no setup-hook gets lost
200
-		OC_App::loadApps(['filesystem']);
201
-
202
-		// the filesystem will finish when $user is not empty,
203
-		// mark fs setup here to avoid doing the setup from loading
204
-		// OC_Filesystem
205
-		if ($user != '') {
206
-			self::$fsSetup = true;
207
-		}
208
-
209
-		\OC\Files\Filesystem::initMountManager();
210
-
211
-		$prevLogging = \OC\Files\Filesystem::logWarningWhenAddingStorageWrapper(false);
212
-		\OC\Files\Filesystem::addStorageWrapper('mount_options', function ($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) {
213
-			if ($storage->instanceOfStorage('\OC\Files\Storage\Common')) {
214
-				/** @var \OC\Files\Storage\Common $storage */
215
-				$storage->setMountOptions($mount->getOptions());
216
-			}
217
-			return $storage;
218
-		});
219
-
220
-		\OC\Files\Filesystem::addStorageWrapper('enable_sharing', function ($mountPoint, \OCP\Files\Storage\IStorage $storage, \OCP\Files\Mount\IMountPoint $mount) {
221
-			if (!$mount->getOption('enable_sharing', true)) {
222
-				return new \OC\Files\Storage\Wrapper\PermissionsMask([
223
-					'storage' => $storage,
224
-					'mask' => \OCP\Constants::PERMISSION_ALL - \OCP\Constants::PERMISSION_SHARE
225
-				]);
226
-			}
227
-			return $storage;
228
-		});
229
-
230
-		// install storage availability wrapper, before most other wrappers
231
-		\OC\Files\Filesystem::addStorageWrapper('oc_availability', function ($mountPoint, \OCP\Files\Storage\IStorage $storage) {
232
-			if (!$storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage') && !$storage->isLocal()) {
233
-				return new \OC\Files\Storage\Wrapper\Availability(['storage' => $storage]);
234
-			}
235
-			return $storage;
236
-		});
237
-
238
-		\OC\Files\Filesystem::addStorageWrapper('oc_encoding', function ($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) {
239
-			if ($mount->getOption('encoding_compatibility', false) && !$storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage') && !$storage->isLocal()) {
240
-				return new \OC\Files\Storage\Wrapper\Encoding(['storage' => $storage]);
241
-			}
242
-			return $storage;
243
-		});
244
-
245
-		\OC\Files\Filesystem::addStorageWrapper('oc_quota', function ($mountPoint, $storage) {
246
-			// set up quota for home storages, even for other users
247
-			// which can happen when using sharing
248
-
249
-			/**
250
-			 * @var \OC\Files\Storage\Storage $storage
251
-			 */
252
-			if ($storage->instanceOfStorage('\OC\Files\Storage\Home')
253
-				|| $storage->instanceOfStorage('\OC\Files\ObjectStore\HomeObjectStoreStorage')
254
-			) {
255
-				/** @var \OC\Files\Storage\Home $storage */
256
-				if (is_object($storage->getUser())) {
257
-					$quota = OC_Util::getUserQuota($storage->getUser());
258
-					if ($quota !== \OCP\Files\FileInfo::SPACE_UNLIMITED) {
259
-						return new \OC\Files\Storage\Wrapper\Quota(['storage' => $storage, 'quota' => $quota, 'root' => 'files']);
260
-					}
261
-				}
262
-			}
263
-
264
-			return $storage;
265
-		});
266
-
267
-		\OC\Files\Filesystem::addStorageWrapper('readonly', function ($mountPoint, \OCP\Files\Storage\IStorage $storage, \OCP\Files\Mount\IMountPoint $mount) {
268
-			/*
75
+    public static $scripts = [];
76
+    public static $styles = [];
77
+    public static $headers = [];
78
+    private static $rootMounted = false;
79
+    private static $fsSetup = false;
80
+
81
+    /** @var array Local cache of version.php */
82
+    private static $versionCache = null;
83
+
84
+    protected static function getAppManager() {
85
+        return \OC::$server->getAppManager();
86
+    }
87
+
88
+    private static function initLocalStorageRootFS() {
89
+        // mount local file backend as root
90
+        $configDataDirectory = \OC::$server->getSystemConfig()->getValue("datadirectory", OC::$SERVERROOT . "/data");
91
+        //first set up the local "root" storage
92
+        \OC\Files\Filesystem::initMountManager();
93
+        if (!self::$rootMounted) {
94
+            \OC\Files\Filesystem::mount(LocalRootStorage::class, ['datadir' => $configDataDirectory], '/');
95
+            self::$rootMounted = true;
96
+        }
97
+    }
98
+
99
+    /**
100
+     * mounting an object storage as the root fs will in essence remove the
101
+     * necessity of a data folder being present.
102
+     * TODO make home storage aware of this and use the object storage instead of local disk access
103
+     *
104
+     * @param array $config containing 'class' and optional 'arguments'
105
+     * @suppress PhanDeprecatedFunction
106
+     */
107
+    private static function initObjectStoreRootFS($config) {
108
+        // check misconfiguration
109
+        if (empty($config['class'])) {
110
+            \OCP\Util::writeLog('files', 'No class given for objectstore', ILogger::ERROR);
111
+        }
112
+        if (!isset($config['arguments'])) {
113
+            $config['arguments'] = [];
114
+        }
115
+
116
+        // instantiate object store implementation
117
+        $name = $config['class'];
118
+        if (strpos($name, 'OCA\\') === 0 && substr_count($name, '\\') >= 2) {
119
+            $segments = explode('\\', $name);
120
+            OC_App::loadApp(strtolower($segments[1]));
121
+        }
122
+        $config['arguments']['objectstore'] = new $config['class']($config['arguments']);
123
+        // mount with plain / root object store implementation
124
+        $config['class'] = '\OC\Files\ObjectStore\ObjectStoreStorage';
125
+
126
+        // mount object storage as root
127
+        \OC\Files\Filesystem::initMountManager();
128
+        if (!self::$rootMounted) {
129
+            \OC\Files\Filesystem::mount($config['class'], $config['arguments'], '/');
130
+            self::$rootMounted = true;
131
+        }
132
+    }
133
+
134
+    /**
135
+     * mounting an object storage as the root fs will in essence remove the
136
+     * necessity of a data folder being present.
137
+     *
138
+     * @param array $config containing 'class' and optional 'arguments'
139
+     * @suppress PhanDeprecatedFunction
140
+     */
141
+    private static function initObjectStoreMultibucketRootFS($config) {
142
+        // check misconfiguration
143
+        if (empty($config['class'])) {
144
+            \OCP\Util::writeLog('files', 'No class given for objectstore', ILogger::ERROR);
145
+        }
146
+        if (!isset($config['arguments'])) {
147
+            $config['arguments'] = [];
148
+        }
149
+
150
+        // instantiate object store implementation
151
+        $name = $config['class'];
152
+        if (strpos($name, 'OCA\\') === 0 && substr_count($name, '\\') >= 2) {
153
+            $segments = explode('\\', $name);
154
+            OC_App::loadApp(strtolower($segments[1]));
155
+        }
156
+
157
+        if (!isset($config['arguments']['bucket'])) {
158
+            $config['arguments']['bucket'] = '';
159
+        }
160
+        // put the root FS always in first bucket for multibucket configuration
161
+        $config['arguments']['bucket'] .= '0';
162
+
163
+        $config['arguments']['objectstore'] = new $config['class']($config['arguments']);
164
+        // mount with plain / root object store implementation
165
+        $config['class'] = '\OC\Files\ObjectStore\ObjectStoreStorage';
166
+
167
+        // mount object storage as root
168
+        \OC\Files\Filesystem::initMountManager();
169
+        if (!self::$rootMounted) {
170
+            \OC\Files\Filesystem::mount($config['class'], $config['arguments'], '/');
171
+            self::$rootMounted = true;
172
+        }
173
+    }
174
+
175
+    /**
176
+     * Can be set up
177
+     *
178
+     * @param string $user
179
+     * @return boolean
180
+     * @description configure the initial filesystem based on the configuration
181
+     * @suppress PhanDeprecatedFunction
182
+     * @suppress PhanAccessMethodInternal
183
+     */
184
+    public static function setupFS($user = '') {
185
+        //setting up the filesystem twice can only lead to trouble
186
+        if (self::$fsSetup) {
187
+            return false;
188
+        }
189
+
190
+        \OC::$server->getEventLogger()->start('setup_fs', 'Setup filesystem');
191
+
192
+        // If we are not forced to load a specific user we load the one that is logged in
193
+        if ($user === null) {
194
+            $user = '';
195
+        } elseif ($user == "" && \OC::$server->getUserSession()->isLoggedIn()) {
196
+            $user = OC_User::getUser();
197
+        }
198
+
199
+        // load all filesystem apps before, so no setup-hook gets lost
200
+        OC_App::loadApps(['filesystem']);
201
+
202
+        // the filesystem will finish when $user is not empty,
203
+        // mark fs setup here to avoid doing the setup from loading
204
+        // OC_Filesystem
205
+        if ($user != '') {
206
+            self::$fsSetup = true;
207
+        }
208
+
209
+        \OC\Files\Filesystem::initMountManager();
210
+
211
+        $prevLogging = \OC\Files\Filesystem::logWarningWhenAddingStorageWrapper(false);
212
+        \OC\Files\Filesystem::addStorageWrapper('mount_options', function ($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) {
213
+            if ($storage->instanceOfStorage('\OC\Files\Storage\Common')) {
214
+                /** @var \OC\Files\Storage\Common $storage */
215
+                $storage->setMountOptions($mount->getOptions());
216
+            }
217
+            return $storage;
218
+        });
219
+
220
+        \OC\Files\Filesystem::addStorageWrapper('enable_sharing', function ($mountPoint, \OCP\Files\Storage\IStorage $storage, \OCP\Files\Mount\IMountPoint $mount) {
221
+            if (!$mount->getOption('enable_sharing', true)) {
222
+                return new \OC\Files\Storage\Wrapper\PermissionsMask([
223
+                    'storage' => $storage,
224
+                    'mask' => \OCP\Constants::PERMISSION_ALL - \OCP\Constants::PERMISSION_SHARE
225
+                ]);
226
+            }
227
+            return $storage;
228
+        });
229
+
230
+        // install storage availability wrapper, before most other wrappers
231
+        \OC\Files\Filesystem::addStorageWrapper('oc_availability', function ($mountPoint, \OCP\Files\Storage\IStorage $storage) {
232
+            if (!$storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage') && !$storage->isLocal()) {
233
+                return new \OC\Files\Storage\Wrapper\Availability(['storage' => $storage]);
234
+            }
235
+            return $storage;
236
+        });
237
+
238
+        \OC\Files\Filesystem::addStorageWrapper('oc_encoding', function ($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) {
239
+            if ($mount->getOption('encoding_compatibility', false) && !$storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage') && !$storage->isLocal()) {
240
+                return new \OC\Files\Storage\Wrapper\Encoding(['storage' => $storage]);
241
+            }
242
+            return $storage;
243
+        });
244
+
245
+        \OC\Files\Filesystem::addStorageWrapper('oc_quota', function ($mountPoint, $storage) {
246
+            // set up quota for home storages, even for other users
247
+            // which can happen when using sharing
248
+
249
+            /**
250
+             * @var \OC\Files\Storage\Storage $storage
251
+             */
252
+            if ($storage->instanceOfStorage('\OC\Files\Storage\Home')
253
+                || $storage->instanceOfStorage('\OC\Files\ObjectStore\HomeObjectStoreStorage')
254
+            ) {
255
+                /** @var \OC\Files\Storage\Home $storage */
256
+                if (is_object($storage->getUser())) {
257
+                    $quota = OC_Util::getUserQuota($storage->getUser());
258
+                    if ($quota !== \OCP\Files\FileInfo::SPACE_UNLIMITED) {
259
+                        return new \OC\Files\Storage\Wrapper\Quota(['storage' => $storage, 'quota' => $quota, 'root' => 'files']);
260
+                    }
261
+                }
262
+            }
263
+
264
+            return $storage;
265
+        });
266
+
267
+        \OC\Files\Filesystem::addStorageWrapper('readonly', function ($mountPoint, \OCP\Files\Storage\IStorage $storage, \OCP\Files\Mount\IMountPoint $mount) {
268
+            /*
269 269
 			 * Do not allow any operations that modify the storage
270 270
 			 */
271
-			if ($mount->getOption('readonly', false)) {
272
-				return new \OC\Files\Storage\Wrapper\PermissionsMask([
273
-					'storage' => $storage,
274
-					'mask' => \OCP\Constants::PERMISSION_ALL & ~(
275
-						\OCP\Constants::PERMISSION_UPDATE |
276
-						\OCP\Constants::PERMISSION_CREATE |
277
-						\OCP\Constants::PERMISSION_DELETE
278
-					),
279
-				]);
280
-			}
281
-			return $storage;
282
-		});
283
-
284
-		OC_Hook::emit('OC_Filesystem', 'preSetup', ['user' => $user]);
285
-
286
-		\OC\Files\Filesystem::logWarningWhenAddingStorageWrapper($prevLogging);
287
-
288
-		//check if we are using an object storage
289
-		$objectStore = \OC::$server->getSystemConfig()->getValue('objectstore', null);
290
-		$objectStoreMultibucket = \OC::$server->getSystemConfig()->getValue('objectstore_multibucket', null);
291
-
292
-		// use the same order as in ObjectHomeMountProvider
293
-		if (isset($objectStoreMultibucket)) {
294
-			self::initObjectStoreMultibucketRootFS($objectStoreMultibucket);
295
-		} elseif (isset($objectStore)) {
296
-			self::initObjectStoreRootFS($objectStore);
297
-		} else {
298
-			self::initLocalStorageRootFS();
299
-		}
300
-
301
-		/** @var \OCP\Files\Config\IMountProviderCollection $mountProviderCollection */
302
-		$mountProviderCollection = \OC::$server->query(\OCP\Files\Config\IMountProviderCollection::class);
303
-		$rootMountProviders = $mountProviderCollection->getRootMounts();
304
-
305
-		/** @var \OC\Files\Mount\Manager $mountManager */
306
-		$mountManager = \OC\Files\Filesystem::getMountManager();
307
-		foreach ($rootMountProviders as $rootMountProvider) {
308
-			$mountManager->addMount($rootMountProvider);
309
-		}
310
-
311
-		if ($user != '' && !\OC::$server->getUserManager()->userExists($user)) {
312
-			\OC::$server->getEventLogger()->end('setup_fs');
313
-			return false;
314
-		}
315
-
316
-		//if we aren't logged in, there is no use to set up the filesystem
317
-		if ($user != "") {
318
-			$userDir = '/' . $user . '/files';
319
-
320
-			//jail the user into his "home" directory
321
-			\OC\Files\Filesystem::init($user, $userDir);
322
-
323
-			OC_Hook::emit('OC_Filesystem', 'setup', ['user' => $user, 'user_dir' => $userDir]);
324
-		}
325
-		\OC::$server->getEventLogger()->end('setup_fs');
326
-		return true;
327
-	}
328
-
329
-	/**
330
-	 * check if a password is required for each public link
331
-	 *
332
-	 * @return boolean
333
-	 * @suppress PhanDeprecatedFunction
334
-	 */
335
-	public static function isPublicLinkPasswordRequired() {
336
-		$enforcePassword = \OC::$server->getConfig()->getAppValue('core', 'shareapi_enforce_links_password', 'no');
337
-		return $enforcePassword === 'yes';
338
-	}
339
-
340
-	/**
341
-	 * check if sharing is disabled for the current user
342
-	 * @param IConfig $config
343
-	 * @param IGroupManager $groupManager
344
-	 * @param IUser|null $user
345
-	 * @return bool
346
-	 */
347
-	public static function isSharingDisabledForUser(IConfig $config, IGroupManager $groupManager, $user) {
348
-		if ($config->getAppValue('core', 'shareapi_exclude_groups', 'no') === 'yes') {
349
-			$groupsList = $config->getAppValue('core', 'shareapi_exclude_groups_list', '');
350
-			$excludedGroups = json_decode($groupsList);
351
-			if (is_null($excludedGroups)) {
352
-				$excludedGroups = explode(',', $groupsList);
353
-				$newValue = json_encode($excludedGroups);
354
-				$config->setAppValue('core', 'shareapi_exclude_groups_list', $newValue);
355
-			}
356
-			$usersGroups = $groupManager->getUserGroupIds($user);
357
-			if (!empty($usersGroups)) {
358
-				$remainingGroups = array_diff($usersGroups, $excludedGroups);
359
-				// if the user is only in groups which are disabled for sharing then
360
-				// sharing is also disabled for the user
361
-				if (empty($remainingGroups)) {
362
-					return true;
363
-				}
364
-			}
365
-		}
366
-		return false;
367
-	}
368
-
369
-	/**
370
-	 * check if share API enforces a default expire date
371
-	 *
372
-	 * @return boolean
373
-	 * @suppress PhanDeprecatedFunction
374
-	 */
375
-	public static function isDefaultExpireDateEnforced() {
376
-		$isDefaultExpireDateEnabled = \OC::$server->getConfig()->getAppValue('core', 'shareapi_default_expire_date', 'no');
377
-		$enforceDefaultExpireDate = false;
378
-		if ($isDefaultExpireDateEnabled === 'yes') {
379
-			$value = \OC::$server->getConfig()->getAppValue('core', 'shareapi_enforce_expire_date', 'no');
380
-			$enforceDefaultExpireDate = $value === 'yes';
381
-		}
382
-
383
-		return $enforceDefaultExpireDate;
384
-	}
385
-
386
-	/**
387
-	 * Get the quota of a user
388
-	 *
389
-	 * @param IUser|null $user
390
-	 * @return float Quota bytes
391
-	 */
392
-	public static function getUserQuota(?IUser $user) {
393
-		if (is_null($user)) {
394
-			return \OCP\Files\FileInfo::SPACE_UNLIMITED;
395
-		}
396
-		$userQuota = $user->getQuota();
397
-		if ($userQuota === 'none') {
398
-			return \OCP\Files\FileInfo::SPACE_UNLIMITED;
399
-		}
400
-		return OC_Helper::computerFileSize($userQuota);
401
-	}
402
-
403
-	/**
404
-	 * copies the skeleton to the users /files
405
-	 *
406
-	 * @param string $userId
407
-	 * @param \OCP\Files\Folder $userDirectory
408
-	 * @throws \OCP\Files\NotFoundException
409
-	 * @throws \OCP\Files\NotPermittedException
410
-	 * @suppress PhanDeprecatedFunction
411
-	 */
412
-	public static function copySkeleton($userId, \OCP\Files\Folder $userDirectory) {
413
-		$plainSkeletonDirectory = \OC::$server->getConfig()->getSystemValue('skeletondirectory', \OC::$SERVERROOT . '/core/skeleton');
414
-		$userLang = \OC::$server->getL10NFactory()->findLanguage();
415
-		$skeletonDirectory = str_replace('{lang}', $userLang, $plainSkeletonDirectory);
416
-
417
-		if (!file_exists($skeletonDirectory)) {
418
-			$dialectStart = strpos($userLang, '_');
419
-			if ($dialectStart !== false) {
420
-				$skeletonDirectory = str_replace('{lang}', substr($userLang, 0, $dialectStart), $plainSkeletonDirectory);
421
-			}
422
-			if ($dialectStart === false || !file_exists($skeletonDirectory)) {
423
-				$skeletonDirectory = str_replace('{lang}', 'default', $plainSkeletonDirectory);
424
-			}
425
-			if (!file_exists($skeletonDirectory)) {
426
-				$skeletonDirectory = '';
427
-			}
428
-		}
429
-
430
-		$instanceId = \OC::$server->getConfig()->getSystemValue('instanceid', '');
431
-
432
-		if ($instanceId === null) {
433
-			throw new \RuntimeException('no instance id!');
434
-		}
435
-		$appdata = 'appdata_' . $instanceId;
436
-		if ($userId === $appdata) {
437
-			throw new \RuntimeException('username is reserved name: ' . $appdata);
438
-		}
439
-
440
-		if (!empty($skeletonDirectory)) {
441
-			\OCP\Util::writeLog(
442
-				'files_skeleton',
443
-				'copying skeleton for '.$userId.' from '.$skeletonDirectory.' to '.$userDirectory->getFullPath('/'),
444
-				ILogger::DEBUG
445
-			);
446
-			self::copyr($skeletonDirectory, $userDirectory);
447
-			// update the file cache
448
-			$userDirectory->getStorage()->getScanner()->scan('', \OC\Files\Cache\Scanner::SCAN_RECURSIVE);
449
-		}
450
-	}
451
-
452
-	/**
453
-	 * copies a directory recursively by using streams
454
-	 *
455
-	 * @param string $source
456
-	 * @param \OCP\Files\Folder $target
457
-	 * @return void
458
-	 */
459
-	public static function copyr($source, \OCP\Files\Folder $target) {
460
-		$logger = \OC::$server->getLogger();
461
-
462
-		// Verify if folder exists
463
-		$dir = opendir($source);
464
-		if ($dir === false) {
465
-			$logger->error(sprintf('Could not opendir "%s"', $source), ['app' => 'core']);
466
-			return;
467
-		}
468
-
469
-		// Copy the files
470
-		while (false !== ($file = readdir($dir))) {
471
-			if (!\OC\Files\Filesystem::isIgnoredDir($file)) {
472
-				if (is_dir($source . '/' . $file)) {
473
-					$child = $target->newFolder($file);
474
-					self::copyr($source . '/' . $file, $child);
475
-				} else {
476
-					$child = $target->newFile($file);
477
-					$sourceStream = fopen($source . '/' . $file, 'r');
478
-					if ($sourceStream === false) {
479
-						$logger->error(sprintf('Could not fopen "%s"', $source . '/' . $file), ['app' => 'core']);
480
-						closedir($dir);
481
-						return;
482
-					}
483
-					stream_copy_to_stream($sourceStream, $child->fopen('w'));
484
-				}
485
-			}
486
-		}
487
-		closedir($dir);
488
-	}
489
-
490
-	/**
491
-	 * @return void
492
-	 * @suppress PhanUndeclaredMethod
493
-	 */
494
-	public static function tearDownFS() {
495
-		\OC\Files\Filesystem::tearDown();
496
-		\OC::$server->getRootFolder()->clearCache();
497
-		self::$fsSetup = false;
498
-		self::$rootMounted = false;
499
-	}
500
-
501
-	/**
502
-	 * get the current installed version of ownCloud
503
-	 *
504
-	 * @return array
505
-	 */
506
-	public static function getVersion() {
507
-		OC_Util::loadVersion();
508
-		return self::$versionCache['OC_Version'];
509
-	}
510
-
511
-	/**
512
-	 * get the current installed version string of ownCloud
513
-	 *
514
-	 * @return string
515
-	 */
516
-	public static function getVersionString() {
517
-		OC_Util::loadVersion();
518
-		return self::$versionCache['OC_VersionString'];
519
-	}
520
-
521
-	/**
522
-	 * @deprecated the value is of no use anymore
523
-	 * @return string
524
-	 */
525
-	public static function getEditionString() {
526
-		return '';
527
-	}
528
-
529
-	/**
530
-	 * @description get the update channel of the current installed of ownCloud.
531
-	 * @return string
532
-	 */
533
-	public static function getChannel() {
534
-		OC_Util::loadVersion();
535
-		return \OC::$server->getConfig()->getSystemValue('updater.release.channel', self::$versionCache['OC_Channel']);
536
-	}
537
-
538
-	/**
539
-	 * @description get the build number of the current installed of ownCloud.
540
-	 * @return string
541
-	 */
542
-	public static function getBuild() {
543
-		OC_Util::loadVersion();
544
-		return self::$versionCache['OC_Build'];
545
-	}
546
-
547
-	/**
548
-	 * @description load the version.php into the session as cache
549
-	 * @suppress PhanUndeclaredVariable
550
-	 */
551
-	private static function loadVersion() {
552
-		if (self::$versionCache !== null) {
553
-			return;
554
-		}
555
-
556
-		$timestamp = filemtime(OC::$SERVERROOT . '/version.php');
557
-		require OC::$SERVERROOT . '/version.php';
558
-		/** @var int $timestamp */
559
-		self::$versionCache['OC_Version_Timestamp'] = $timestamp;
560
-		/** @var string $OC_Version */
561
-		self::$versionCache['OC_Version'] = $OC_Version;
562
-		/** @var string $OC_VersionString */
563
-		self::$versionCache['OC_VersionString'] = $OC_VersionString;
564
-		/** @var string $OC_Build */
565
-		self::$versionCache['OC_Build'] = $OC_Build;
566
-
567
-		/** @var string $OC_Channel */
568
-		self::$versionCache['OC_Channel'] = $OC_Channel;
569
-	}
570
-
571
-	/**
572
-	 * generates a path for JS/CSS files. If no application is provided it will create the path for core.
573
-	 *
574
-	 * @param string $application application to get the files from
575
-	 * @param string $directory directory within this application (css, js, vendor, etc)
576
-	 * @param string $file the file inside of the above folder
577
-	 * @return string the path
578
-	 */
579
-	private static function generatePath($application, $directory, $file) {
580
-		if (is_null($file)) {
581
-			$file = $application;
582
-			$application = "";
583
-		}
584
-		if (!empty($application)) {
585
-			return "$application/$directory/$file";
586
-		} else {
587
-			return "$directory/$file";
588
-		}
589
-	}
590
-
591
-	/**
592
-	 * add a javascript file
593
-	 *
594
-	 * @param string $application application id
595
-	 * @param string|null $file filename
596
-	 * @param bool $prepend prepend the Script to the beginning of the list
597
-	 * @return void
598
-	 */
599
-	public static function addScript($application, $file = null, $prepend = false) {
600
-		$path = OC_Util::generatePath($application, 'js', $file);
601
-
602
-		// core js files need separate handling
603
-		if ($application !== 'core' && $file !== null) {
604
-			self::addTranslations($application);
605
-		}
606
-		self::addExternalResource($application, $prepend, $path, "script");
607
-	}
608
-
609
-	/**
610
-	 * add a javascript file from the vendor sub folder
611
-	 *
612
-	 * @param string $application application id
613
-	 * @param string|null $file filename
614
-	 * @param bool $prepend prepend the Script to the beginning of the list
615
-	 * @return void
616
-	 */
617
-	public static function addVendorScript($application, $file = null, $prepend = false) {
618
-		$path = OC_Util::generatePath($application, 'vendor', $file);
619
-		self::addExternalResource($application, $prepend, $path, "script");
620
-	}
621
-
622
-	/**
623
-	 * add a translation JS file
624
-	 *
625
-	 * @param string $application application id
626
-	 * @param string|null $languageCode language code, defaults to the current language
627
-	 * @param bool|null $prepend prepend the Script to the beginning of the list
628
-	 */
629
-	public static function addTranslations($application, $languageCode = null, $prepend = false) {
630
-		if (is_null($languageCode)) {
631
-			$languageCode = \OC::$server->getL10NFactory()->findLanguage($application);
632
-		}
633
-		if (!empty($application)) {
634
-			$path = "$application/l10n/$languageCode";
635
-		} else {
636
-			$path = "l10n/$languageCode";
637
-		}
638
-		self::addExternalResource($application, $prepend, $path, "script");
639
-	}
640
-
641
-	/**
642
-	 * add a css file
643
-	 *
644
-	 * @param string $application application id
645
-	 * @param string|null $file filename
646
-	 * @param bool $prepend prepend the Style to the beginning of the list
647
-	 * @return void
648
-	 */
649
-	public static function addStyle($application, $file = null, $prepend = false) {
650
-		$path = OC_Util::generatePath($application, 'css', $file);
651
-		self::addExternalResource($application, $prepend, $path, "style");
652
-	}
653
-
654
-	/**
655
-	 * add a css file from the vendor sub folder
656
-	 *
657
-	 * @param string $application application id
658
-	 * @param string|null $file filename
659
-	 * @param bool $prepend prepend the Style to the beginning of the list
660
-	 * @return void
661
-	 */
662
-	public static function addVendorStyle($application, $file = null, $prepend = false) {
663
-		$path = OC_Util::generatePath($application, 'vendor', $file);
664
-		self::addExternalResource($application, $prepend, $path, "style");
665
-	}
666
-
667
-	/**
668
-	 * add an external resource css/js file
669
-	 *
670
-	 * @param string $application application id
671
-	 * @param bool $prepend prepend the file to the beginning of the list
672
-	 * @param string $path
673
-	 * @param string $type (script or style)
674
-	 * @return void
675
-	 */
676
-	private static function addExternalResource($application, $prepend, $path, $type = "script") {
677
-		if ($type === "style") {
678
-			if (!in_array($path, self::$styles)) {
679
-				if ($prepend === true) {
680
-					array_unshift(self::$styles, $path);
681
-				} else {
682
-					self::$styles[] = $path;
683
-				}
684
-			}
685
-		} elseif ($type === "script") {
686
-			if (!in_array($path, self::$scripts)) {
687
-				if ($prepend === true) {
688
-					array_unshift(self::$scripts, $path);
689
-				} else {
690
-					self::$scripts [] = $path;
691
-				}
692
-			}
693
-		}
694
-	}
695
-
696
-	/**
697
-	 * Add a custom element to the header
698
-	 * If $text is null then the element will be written as empty element.
699
-	 * So use "" to get a closing tag.
700
-	 * @param string $tag tag name of the element
701
-	 * @param array $attributes array of attributes for the element
702
-	 * @param string $text the text content for the element
703
-	 * @param bool $prepend prepend the header to the beginning of the list
704
-	 */
705
-	public static function addHeader($tag, $attributes, $text = null, $prepend = false) {
706
-		$header = [
707
-			'tag' => $tag,
708
-			'attributes' => $attributes,
709
-			'text' => $text
710
-		];
711
-		if ($prepend === true) {
712
-			array_unshift(self::$headers, $header);
713
-		} else {
714
-			self::$headers[] = $header;
715
-		}
716
-	}
717
-
718
-	/**
719
-	 * check if the current server configuration is suitable for ownCloud
720
-	 *
721
-	 * @param \OC\SystemConfig $config
722
-	 * @return array arrays with error messages and hints
723
-	 */
724
-	public static function checkServer(\OC\SystemConfig $config) {
725
-		$l = \OC::$server->getL10N('lib');
726
-		$errors = [];
727
-		$CONFIG_DATADIRECTORY = $config->getValue('datadirectory', OC::$SERVERROOT . '/data');
728
-
729
-		if (!self::needUpgrade($config) && $config->getValue('installed', false)) {
730
-			// this check needs to be done every time
731
-			$errors = self::checkDataDirectoryValidity($CONFIG_DATADIRECTORY);
732
-		}
733
-
734
-		// Assume that if checkServer() succeeded before in this session, then all is fine.
735
-		if (\OC::$server->getSession()->exists('checkServer_succeeded') && \OC::$server->getSession()->get('checkServer_succeeded')) {
736
-			return $errors;
737
-		}
738
-
739
-		$webServerRestart = false;
740
-		$setup = new \OC\Setup(
741
-			$config,
742
-			\OC::$server->get(IniGetWrapper::class),
743
-			\OC::$server->getL10N('lib'),
744
-			\OC::$server->query(\OCP\Defaults::class),
745
-			\OC::$server->getLogger(),
746
-			\OC::$server->getSecureRandom(),
747
-			\OC::$server->query(\OC\Installer::class)
748
-		);
749
-
750
-		$urlGenerator = \OC::$server->getURLGenerator();
751
-
752
-		$availableDatabases = $setup->getSupportedDatabases();
753
-		if (empty($availableDatabases)) {
754
-			$errors[] = [
755
-				'error' => $l->t('No database drivers (sqlite, mysql, or postgresql) installed.'),
756
-				'hint' => '' //TODO: sane hint
757
-			];
758
-			$webServerRestart = true;
759
-		}
760
-
761
-		// Check if config folder is writable.
762
-		if (!OC_Helper::isReadOnlyConfigEnabled()) {
763
-			if (!is_writable(OC::$configDir) or !is_readable(OC::$configDir)) {
764
-				$errors[] = [
765
-					'error' => $l->t('Cannot write into "config" directory'),
766
-					'hint' => $l->t('This can usually be fixed by giving the webserver write access to the config directory. See %s',
767
-						[ $urlGenerator->linkToDocs('admin-dir_permissions') ]) . '. '
768
-						. $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',
769
-						[ $urlGenerator->linkToDocs('admin-config') ])
770
-				];
771
-			}
772
-		}
773
-
774
-		// Check if there is a writable install folder.
775
-		if ($config->getValue('appstoreenabled', true)) {
776
-			if (OC_App::getInstallPath() === null
777
-				|| !is_writable(OC_App::getInstallPath())
778
-				|| !is_readable(OC_App::getInstallPath())
779
-			) {
780
-				$errors[] = [
781
-					'error' => $l->t('Cannot write into "apps" directory'),
782
-					'hint' => $l->t('This can usually be fixed by giving the webserver write access to the apps directory'
783
-						. ' or disabling the appstore in the config file.')
784
-				];
785
-			}
786
-		}
787
-		// Create root dir.
788
-		if ($config->getValue('installed', false)) {
789
-			if (!is_dir($CONFIG_DATADIRECTORY)) {
790
-				$success = @mkdir($CONFIG_DATADIRECTORY);
791
-				if ($success) {
792
-					$errors = array_merge($errors, self::checkDataDirectoryPermissions($CONFIG_DATADIRECTORY));
793
-				} else {
794
-					$errors[] = [
795
-						'error' => $l->t('Cannot create "data" directory'),
796
-						'hint' => $l->t('This can usually be fixed by giving the webserver write access to the root directory. See %s',
797
-							[$urlGenerator->linkToDocs('admin-dir_permissions')])
798
-					];
799
-				}
800
-			} elseif (!is_writable($CONFIG_DATADIRECTORY) or !is_readable($CONFIG_DATADIRECTORY)) {
801
-				// is_writable doesn't work for NFS mounts, so try to write a file and check if it exists.
802
-				$testFile = sprintf('%s/%s.tmp', $CONFIG_DATADIRECTORY, uniqid('data_dir_writability_test_'));
803
-				$handle = fopen($testFile, 'w');
804
-				if (!$handle || fwrite($handle, 'Test write operation') === false) {
805
-					$permissionsHint = $l->t('Permissions can usually be fixed by giving the webserver write access to the root directory. See %s.',
806
-						[$urlGenerator->linkToDocs('admin-dir_permissions')]);
807
-					$errors[] = [
808
-						'error' => 'Your data directory is not writable',
809
-						'hint' => $permissionsHint
810
-					];
811
-				} else {
812
-					fclose($handle);
813
-					unlink($testFile);
814
-				}
815
-			} else {
816
-				$errors = array_merge($errors, self::checkDataDirectoryPermissions($CONFIG_DATADIRECTORY));
817
-			}
818
-		}
819
-
820
-		if (!OC_Util::isSetLocaleWorking()) {
821
-			$errors[] = [
822
-				'error' => $l->t('Setting locale to %s failed',
823
-					['en_US.UTF-8/fr_FR.UTF-8/es_ES.UTF-8/de_DE.UTF-8/ru_RU.UTF-8/'
824
-						. 'pt_BR.UTF-8/it_IT.UTF-8/ja_JP.UTF-8/zh_CN.UTF-8']),
825
-				'hint' => $l->t('Please install one of these locales on your system and restart your webserver.')
826
-			];
827
-		}
828
-
829
-		// Contains the dependencies that should be checked against
830
-		// classes = class_exists
831
-		// functions = function_exists
832
-		// defined = defined
833
-		// ini = ini_get
834
-		// If the dependency is not found the missing module name is shown to the EndUser
835
-		// When adding new checks always verify that they pass on Travis as well
836
-		// for ini settings, see https://github.com/owncloud/administration/blob/master/travis-ci/custom.ini
837
-		$dependencies = [
838
-			'classes' => [
839
-				'ZipArchive' => 'zip',
840
-				'DOMDocument' => 'dom',
841
-				'XMLWriter' => 'XMLWriter',
842
-				'XMLReader' => 'XMLReader',
843
-			],
844
-			'functions' => [
845
-				'xml_parser_create' => 'libxml',
846
-				'mb_strcut' => 'mbstring',
847
-				'ctype_digit' => 'ctype',
848
-				'json_encode' => 'JSON',
849
-				'gd_info' => 'GD',
850
-				'gzencode' => 'zlib',
851
-				'iconv' => 'iconv',
852
-				'simplexml_load_string' => 'SimpleXML',
853
-				'hash' => 'HASH Message Digest Framework',
854
-				'curl_init' => 'cURL',
855
-				'openssl_verify' => 'OpenSSL',
856
-			],
857
-			'defined' => [
858
-				'PDO::ATTR_DRIVER_NAME' => 'PDO'
859
-			],
860
-			'ini' => [
861
-				'default_charset' => 'UTF-8',
862
-			],
863
-		];
864
-		$missingDependencies = [];
865
-		$invalidIniSettings = [];
866
-
867
-		$iniWrapper = \OC::$server->get(IniGetWrapper::class);
868
-		foreach ($dependencies['classes'] as $class => $module) {
869
-			if (!class_exists($class)) {
870
-				$missingDependencies[] = $module;
871
-			}
872
-		}
873
-		foreach ($dependencies['functions'] as $function => $module) {
874
-			if (!function_exists($function)) {
875
-				$missingDependencies[] = $module;
876
-			}
877
-		}
878
-		foreach ($dependencies['defined'] as $defined => $module) {
879
-			if (!defined($defined)) {
880
-				$missingDependencies[] = $module;
881
-			}
882
-		}
883
-		foreach ($dependencies['ini'] as $setting => $expected) {
884
-			if (is_bool($expected)) {
885
-				if ($iniWrapper->getBool($setting) !== $expected) {
886
-					$invalidIniSettings[] = [$setting, $expected];
887
-				}
888
-			}
889
-			if (is_int($expected)) {
890
-				if ($iniWrapper->getNumeric($setting) !== $expected) {
891
-					$invalidIniSettings[] = [$setting, $expected];
892
-				}
893
-			}
894
-			if (is_string($expected)) {
895
-				if (strtolower($iniWrapper->getString($setting)) !== strtolower($expected)) {
896
-					$invalidIniSettings[] = [$setting, $expected];
897
-				}
898
-			}
899
-		}
900
-
901
-		foreach ($missingDependencies as $missingDependency) {
902
-			$errors[] = [
903
-				'error' => $l->t('PHP module %s not installed.', [$missingDependency]),
904
-				'hint' => $l->t('Please ask your server administrator to install the module.'),
905
-			];
906
-			$webServerRestart = true;
907
-		}
908
-		foreach ($invalidIniSettings as $setting) {
909
-			if (is_bool($setting[1])) {
910
-				$setting[1] = $setting[1] ? 'on' : 'off';
911
-			}
912
-			$errors[] = [
913
-				'error' => $l->t('PHP setting "%s" is not set to "%s".', [$setting[0], var_export($setting[1], true)]),
914
-				'hint' =>  $l->t('Adjusting this setting in php.ini will make Nextcloud run again')
915
-			];
916
-			$webServerRestart = true;
917
-		}
918
-
919
-		/**
920
-		 * The mbstring.func_overload check can only be performed if the mbstring
921
-		 * module is installed as it will return null if the checking setting is
922
-		 * not available and thus a check on the boolean value fails.
923
-		 *
924
-		 * TODO: Should probably be implemented in the above generic dependency
925
-		 *       check somehow in the long-term.
926
-		 */
927
-		if ($iniWrapper->getBool('mbstring.func_overload') !== null &&
928
-			$iniWrapper->getBool('mbstring.func_overload') === true) {
929
-			$errors[] = [
930
-				'error' => $l->t('mbstring.func_overload is set to "%s" instead of the expected value "0"', [$iniWrapper->getString('mbstring.func_overload')]),
931
-				'hint' => $l->t('To fix this issue set <code>mbstring.func_overload</code> to <code>0</code> in your php.ini')
932
-			];
933
-		}
934
-
935
-		if (function_exists('xml_parser_create') &&
936
-			LIBXML_LOADED_VERSION < 20700) {
937
-			$version = LIBXML_LOADED_VERSION;
938
-			$major = floor($version/10000);
939
-			$version -= ($major * 10000);
940
-			$minor = floor($version/100);
941
-			$version -= ($minor * 100);
942
-			$patch = $version;
943
-			$errors[] = [
944
-				'error' => $l->t('libxml2 2.7.0 is at least required. Currently %s is installed.', [$major . '.' . $minor . '.' . $patch]),
945
-				'hint' => $l->t('To fix this issue update your libxml2 version and restart your web server.')
946
-			];
947
-		}
948
-
949
-		if (!self::isAnnotationsWorking()) {
950
-			$errors[] = [
951
-				'error' => $l->t('PHP is apparently set up to strip inline doc blocks. This will make several core apps inaccessible.'),
952
-				'hint' => $l->t('This is probably caused by a cache/accelerator such as Zend OPcache or eAccelerator.')
953
-			];
954
-		}
955
-
956
-		if (!\OC::$CLI && $webServerRestart) {
957
-			$errors[] = [
958
-				'error' => $l->t('PHP modules have been installed, but they are still listed as missing?'),
959
-				'hint' => $l->t('Please ask your server administrator to restart the web server.')
960
-			];
961
-		}
962
-
963
-		$errors = array_merge($errors, self::checkDatabaseVersion());
964
-
965
-		// Cache the result of this function
966
-		\OC::$server->getSession()->set('checkServer_succeeded', count($errors) == 0);
967
-
968
-		return $errors;
969
-	}
970
-
971
-	/**
972
-	 * Check the database version
973
-	 *
974
-	 * @return array errors array
975
-	 */
976
-	public static function checkDatabaseVersion() {
977
-		$l = \OC::$server->getL10N('lib');
978
-		$errors = [];
979
-		$dbType = \OC::$server->getSystemConfig()->getValue('dbtype', 'sqlite');
980
-		if ($dbType === 'pgsql') {
981
-			// check PostgreSQL version
982
-			try {
983
-				$result = \OC_DB::executeAudited('SHOW SERVER_VERSION');
984
-				$data = $result->fetchRow();
985
-				if (isset($data['server_version'])) {
986
-					$version = $data['server_version'];
987
-					if (version_compare($version, '9.0.0', '<')) {
988
-						$errors[] = [
989
-							'error' => $l->t('PostgreSQL >= 9 required'),
990
-							'hint' => $l->t('Please upgrade your database version')
991
-						];
992
-					}
993
-				}
994
-			} catch (\Doctrine\DBAL\DBALException $e) {
995
-				$logger = \OC::$server->getLogger();
996
-				$logger->warning('Error occurred while checking PostgreSQL version, assuming >= 9');
997
-				$logger->logException($e);
998
-			}
999
-		}
1000
-		return $errors;
1001
-	}
1002
-
1003
-	/**
1004
-	 * Check for correct file permissions of data directory
1005
-	 *
1006
-	 * @param string $dataDirectory
1007
-	 * @return array arrays with error messages and hints
1008
-	 */
1009
-	public static function checkDataDirectoryPermissions($dataDirectory) {
1010
-		if (\OC::$server->getConfig()->getSystemValue('check_data_directory_permissions', true) === false) {
1011
-			return  [];
1012
-		}
1013
-
1014
-		$perms = substr(decoct(@fileperms($dataDirectory)), -3);
1015
-		if (substr($perms, -1) !== '0') {
1016
-			chmod($dataDirectory, 0770);
1017
-			clearstatcache();
1018
-			$perms = substr(decoct(@fileperms($dataDirectory)), -3);
1019
-			if ($perms[2] !== '0') {
1020
-				$l = \OC::$server->getL10N('lib');
1021
-				return [[
1022
-					'error' => $l->t('Your data directory is readable by other users'),
1023
-					'hint' => $l->t('Please change the permissions to 0770 so that the directory cannot be listed by other users.'),
1024
-				]];
1025
-			}
1026
-		}
1027
-		return [];
1028
-	}
1029
-
1030
-	/**
1031
-	 * Check that the data directory exists and is valid by
1032
-	 * checking the existence of the ".ocdata" file.
1033
-	 *
1034
-	 * @param string $dataDirectory data directory path
1035
-	 * @return array errors found
1036
-	 */
1037
-	public static function checkDataDirectoryValidity($dataDirectory) {
1038
-		$l = \OC::$server->getL10N('lib');
1039
-		$errors = [];
1040
-		if ($dataDirectory[0] !== '/') {
1041
-			$errors[] = [
1042
-				'error' => $l->t('Your data directory must be an absolute path'),
1043
-				'hint' => $l->t('Check the value of "datadirectory" in your configuration')
1044
-			];
1045
-		}
1046
-		if (!file_exists($dataDirectory . '/.ocdata')) {
1047
-			$errors[] = [
1048
-				'error' => $l->t('Your data directory is invalid'),
1049
-				'hint' => $l->t('Ensure there is a file called ".ocdata"' .
1050
-					' in the root of the data directory.')
1051
-			];
1052
-		}
1053
-		return $errors;
1054
-	}
1055
-
1056
-	/**
1057
-	 * Check if the user is logged in, redirects to home if not. With
1058
-	 * redirect URL parameter to the request URI.
1059
-	 *
1060
-	 * @return void
1061
-	 */
1062
-	public static function checkLoggedIn() {
1063
-		// Check if we are a user
1064
-		if (!\OC::$server->getUserSession()->isLoggedIn()) {
1065
-			header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute(
1066
-						'core.login.showLoginForm',
1067
-						[
1068
-							'redirect_url' => \OC::$server->getRequest()->getRequestUri(),
1069
-						]
1070
-					)
1071
-			);
1072
-			exit();
1073
-		}
1074
-		// Redirect to 2FA challenge selection if 2FA challenge was not solved yet
1075
-		if (\OC::$server->getTwoFactorAuthManager()->needsSecondFactor(\OC::$server->getUserSession()->getUser())) {
1076
-			header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute('core.TwoFactorChallenge.selectChallenge'));
1077
-			exit();
1078
-		}
1079
-	}
1080
-
1081
-	/**
1082
-	 * Check if the user is a admin, redirects to home if not
1083
-	 *
1084
-	 * @return void
1085
-	 */
1086
-	public static function checkAdminUser() {
1087
-		OC_Util::checkLoggedIn();
1088
-		if (!OC_User::isAdminUser(OC_User::getUser())) {
1089
-			header('Location: ' . \OCP\Util::linkToAbsolute('', 'index.php'));
1090
-			exit();
1091
-		}
1092
-	}
1093
-
1094
-	/**
1095
-	 * Returns the URL of the default page
1096
-	 * based on the system configuration and
1097
-	 * the apps visible for the current user
1098
-	 *
1099
-	 * @return string URL
1100
-	 * @suppress PhanDeprecatedFunction
1101
-	 */
1102
-	public static function getDefaultPageUrl() {
1103
-		/** @var IConfig $config */
1104
-		$config = \OC::$server->get(IConfig::class);
1105
-		$urlGenerator = \OC::$server->getURLGenerator();
1106
-		// Deny the redirect if the URL contains a @
1107
-		// This prevents unvalidated redirects like ?redirect_url=:[email protected]
1108
-		if (isset($_REQUEST['redirect_url']) && strpos($_REQUEST['redirect_url'], '@') === false) {
1109
-			$location = $urlGenerator->getAbsoluteURL(urldecode($_REQUEST['redirect_url']));
1110
-		} else {
1111
-			$defaultPage = \OC::$server->getConfig()->getAppValue('core', 'defaultpage');
1112
-			if ($defaultPage) {
1113
-				$location = $urlGenerator->getAbsoluteURL($defaultPage);
1114
-			} else {
1115
-				$appId = 'files';
1116
-				$defaultApps = explode(',', $config->getSystemValue('defaultapp', 'dashboard,files'));
1117
-
1118
-				/** @var IUserSession $userSession */
1119
-				$userSession = \OC::$server->get(IUserSession::class);
1120
-				$user = $userSession->getUser();
1121
-				if ($user) {
1122
-					$userDefaultApps = explode(',', $config->getUserValue($user->getUID(), 'core', 'defaultapp'));
1123
-					$defaultApps = array_filter(array_merge($userDefaultApps, $defaultApps));
1124
-				}
1125
-
1126
-				// find the first app that is enabled for the current user
1127
-				foreach ($defaultApps as $defaultApp) {
1128
-					$defaultApp = OC_App::cleanAppId(strip_tags($defaultApp));
1129
-					if (static::getAppManager()->isEnabledForUser($defaultApp)) {
1130
-						$appId = $defaultApp;
1131
-						break;
1132
-					}
1133
-				}
1134
-
1135
-				if ($config->getSystemValue('htaccess.IgnoreFrontController', false) === true || getenv('front_controller_active') === 'true') {
1136
-					$location = $urlGenerator->getAbsoluteURL('/apps/' . $appId . '/');
1137
-				} else {
1138
-					$location = $urlGenerator->getAbsoluteURL('/index.php/apps/' . $appId . '/');
1139
-				}
1140
-			}
1141
-		}
1142
-		return $location;
1143
-	}
1144
-
1145
-	/**
1146
-	 * Redirect to the user default page
1147
-	 *
1148
-	 * @return void
1149
-	 */
1150
-	public static function redirectToDefaultPage() {
1151
-		$location = self::getDefaultPageUrl();
1152
-		header('Location: ' . $location);
1153
-		exit();
1154
-	}
1155
-
1156
-	/**
1157
-	 * get an id unique for this instance
1158
-	 *
1159
-	 * @return string
1160
-	 */
1161
-	public static function getInstanceId() {
1162
-		$id = \OC::$server->getSystemConfig()->getValue('instanceid', null);
1163
-		if (is_null($id)) {
1164
-			// We need to guarantee at least one letter in instanceid so it can be used as the session_name
1165
-			$id = 'oc' . \OC::$server->getSecureRandom()->generate(10, \OCP\Security\ISecureRandom::CHAR_LOWER.\OCP\Security\ISecureRandom::CHAR_DIGITS);
1166
-			\OC::$server->getSystemConfig()->setValue('instanceid', $id);
1167
-		}
1168
-		return $id;
1169
-	}
1170
-
1171
-	/**
1172
-	 * Public function to sanitize HTML
1173
-	 *
1174
-	 * This function is used to sanitize HTML and should be applied on any
1175
-	 * string or array of strings before displaying it on a web page.
1176
-	 *
1177
-	 * @param string|array $value
1178
-	 * @return string|array an array of sanitized strings or a single sanitized string, depends on the input parameter.
1179
-	 */
1180
-	public static function sanitizeHTML($value) {
1181
-		if (is_array($value)) {
1182
-			$value = array_map(function ($value) {
1183
-				return self::sanitizeHTML($value);
1184
-			}, $value);
1185
-		} else {
1186
-			// Specify encoding for PHP<5.4
1187
-			$value = htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
1188
-		}
1189
-		return $value;
1190
-	}
1191
-
1192
-	/**
1193
-	 * Public function to encode url parameters
1194
-	 *
1195
-	 * This function is used to encode path to file before output.
1196
-	 * Encoding is done according to RFC 3986 with one exception:
1197
-	 * Character '/' is preserved as is.
1198
-	 *
1199
-	 * @param string $component part of URI to encode
1200
-	 * @return string
1201
-	 */
1202
-	public static function encodePath($component) {
1203
-		$encoded = rawurlencode($component);
1204
-		$encoded = str_replace('%2F', '/', $encoded);
1205
-		return $encoded;
1206
-	}
1207
-
1208
-
1209
-	public function createHtaccessTestFile(\OCP\IConfig $config) {
1210
-		// php dev server does not support htaccess
1211
-		if (php_sapi_name() === 'cli-server') {
1212
-			return false;
1213
-		}
1214
-
1215
-		// testdata
1216
-		$fileName = '/htaccesstest.txt';
1217
-		$testContent = 'This is used for testing whether htaccess is properly enabled to disallow access from the outside. This file can be safely removed.';
1218
-
1219
-		// creating a test file
1220
-		$testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
1221
-
1222
-		if (file_exists($testFile)) {// already running this test, possible recursive call
1223
-			return false;
1224
-		}
1225
-
1226
-		$fp = @fopen($testFile, 'w');
1227
-		if (!$fp) {
1228
-			throw new OC\HintException('Can\'t create test file to check for working .htaccess file.',
1229
-				'Make sure it is possible for the webserver to write to ' . $testFile);
1230
-		}
1231
-		fwrite($fp, $testContent);
1232
-		fclose($fp);
1233
-
1234
-		return $testContent;
1235
-	}
1236
-
1237
-	/**
1238
-	 * Check if the .htaccess file is working
1239
-	 * @param \OCP\IConfig $config
1240
-	 * @return bool
1241
-	 * @throws Exception
1242
-	 * @throws \OC\HintException If the test file can't get written.
1243
-	 */
1244
-	public function isHtaccessWorking(\OCP\IConfig $config) {
1245
-		if (\OC::$CLI || !$config->getSystemValue('check_for_working_htaccess', true)) {
1246
-			return true;
1247
-		}
1248
-
1249
-		$testContent = $this->createHtaccessTestFile($config);
1250
-		if ($testContent === false) {
1251
-			return false;
1252
-		}
1253
-
1254
-		$fileName = '/htaccesstest.txt';
1255
-		$testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
1256
-
1257
-		// accessing the file via http
1258
-		$url = \OC::$server->getURLGenerator()->getAbsoluteURL(OC::$WEBROOT . '/data' . $fileName);
1259
-		try {
1260
-			$content = \OC::$server->getHTTPClientService()->newClient()->get($url)->getBody();
1261
-		} catch (\Exception $e) {
1262
-			$content = false;
1263
-		}
1264
-
1265
-		if (strpos($url, 'https:') === 0) {
1266
-			$url = 'http:' . substr($url, 6);
1267
-		} else {
1268
-			$url = 'https:' . substr($url, 5);
1269
-		}
1270
-
1271
-		try {
1272
-			$fallbackContent = \OC::$server->getHTTPClientService()->newClient()->get($url)->getBody();
1273
-		} catch (\Exception $e) {
1274
-			$fallbackContent = false;
1275
-		}
1276
-
1277
-		// cleanup
1278
-		@unlink($testFile);
1279
-
1280
-		/*
271
+            if ($mount->getOption('readonly', false)) {
272
+                return new \OC\Files\Storage\Wrapper\PermissionsMask([
273
+                    'storage' => $storage,
274
+                    'mask' => \OCP\Constants::PERMISSION_ALL & ~(
275
+                        \OCP\Constants::PERMISSION_UPDATE |
276
+                        \OCP\Constants::PERMISSION_CREATE |
277
+                        \OCP\Constants::PERMISSION_DELETE
278
+                    ),
279
+                ]);
280
+            }
281
+            return $storage;
282
+        });
283
+
284
+        OC_Hook::emit('OC_Filesystem', 'preSetup', ['user' => $user]);
285
+
286
+        \OC\Files\Filesystem::logWarningWhenAddingStorageWrapper($prevLogging);
287
+
288
+        //check if we are using an object storage
289
+        $objectStore = \OC::$server->getSystemConfig()->getValue('objectstore', null);
290
+        $objectStoreMultibucket = \OC::$server->getSystemConfig()->getValue('objectstore_multibucket', null);
291
+
292
+        // use the same order as in ObjectHomeMountProvider
293
+        if (isset($objectStoreMultibucket)) {
294
+            self::initObjectStoreMultibucketRootFS($objectStoreMultibucket);
295
+        } elseif (isset($objectStore)) {
296
+            self::initObjectStoreRootFS($objectStore);
297
+        } else {
298
+            self::initLocalStorageRootFS();
299
+        }
300
+
301
+        /** @var \OCP\Files\Config\IMountProviderCollection $mountProviderCollection */
302
+        $mountProviderCollection = \OC::$server->query(\OCP\Files\Config\IMountProviderCollection::class);
303
+        $rootMountProviders = $mountProviderCollection->getRootMounts();
304
+
305
+        /** @var \OC\Files\Mount\Manager $mountManager */
306
+        $mountManager = \OC\Files\Filesystem::getMountManager();
307
+        foreach ($rootMountProviders as $rootMountProvider) {
308
+            $mountManager->addMount($rootMountProvider);
309
+        }
310
+
311
+        if ($user != '' && !\OC::$server->getUserManager()->userExists($user)) {
312
+            \OC::$server->getEventLogger()->end('setup_fs');
313
+            return false;
314
+        }
315
+
316
+        //if we aren't logged in, there is no use to set up the filesystem
317
+        if ($user != "") {
318
+            $userDir = '/' . $user . '/files';
319
+
320
+            //jail the user into his "home" directory
321
+            \OC\Files\Filesystem::init($user, $userDir);
322
+
323
+            OC_Hook::emit('OC_Filesystem', 'setup', ['user' => $user, 'user_dir' => $userDir]);
324
+        }
325
+        \OC::$server->getEventLogger()->end('setup_fs');
326
+        return true;
327
+    }
328
+
329
+    /**
330
+     * check if a password is required for each public link
331
+     *
332
+     * @return boolean
333
+     * @suppress PhanDeprecatedFunction
334
+     */
335
+    public static function isPublicLinkPasswordRequired() {
336
+        $enforcePassword = \OC::$server->getConfig()->getAppValue('core', 'shareapi_enforce_links_password', 'no');
337
+        return $enforcePassword === 'yes';
338
+    }
339
+
340
+    /**
341
+     * check if sharing is disabled for the current user
342
+     * @param IConfig $config
343
+     * @param IGroupManager $groupManager
344
+     * @param IUser|null $user
345
+     * @return bool
346
+     */
347
+    public static function isSharingDisabledForUser(IConfig $config, IGroupManager $groupManager, $user) {
348
+        if ($config->getAppValue('core', 'shareapi_exclude_groups', 'no') === 'yes') {
349
+            $groupsList = $config->getAppValue('core', 'shareapi_exclude_groups_list', '');
350
+            $excludedGroups = json_decode($groupsList);
351
+            if (is_null($excludedGroups)) {
352
+                $excludedGroups = explode(',', $groupsList);
353
+                $newValue = json_encode($excludedGroups);
354
+                $config->setAppValue('core', 'shareapi_exclude_groups_list', $newValue);
355
+            }
356
+            $usersGroups = $groupManager->getUserGroupIds($user);
357
+            if (!empty($usersGroups)) {
358
+                $remainingGroups = array_diff($usersGroups, $excludedGroups);
359
+                // if the user is only in groups which are disabled for sharing then
360
+                // sharing is also disabled for the user
361
+                if (empty($remainingGroups)) {
362
+                    return true;
363
+                }
364
+            }
365
+        }
366
+        return false;
367
+    }
368
+
369
+    /**
370
+     * check if share API enforces a default expire date
371
+     *
372
+     * @return boolean
373
+     * @suppress PhanDeprecatedFunction
374
+     */
375
+    public static function isDefaultExpireDateEnforced() {
376
+        $isDefaultExpireDateEnabled = \OC::$server->getConfig()->getAppValue('core', 'shareapi_default_expire_date', 'no');
377
+        $enforceDefaultExpireDate = false;
378
+        if ($isDefaultExpireDateEnabled === 'yes') {
379
+            $value = \OC::$server->getConfig()->getAppValue('core', 'shareapi_enforce_expire_date', 'no');
380
+            $enforceDefaultExpireDate = $value === 'yes';
381
+        }
382
+
383
+        return $enforceDefaultExpireDate;
384
+    }
385
+
386
+    /**
387
+     * Get the quota of a user
388
+     *
389
+     * @param IUser|null $user
390
+     * @return float Quota bytes
391
+     */
392
+    public static function getUserQuota(?IUser $user) {
393
+        if (is_null($user)) {
394
+            return \OCP\Files\FileInfo::SPACE_UNLIMITED;
395
+        }
396
+        $userQuota = $user->getQuota();
397
+        if ($userQuota === 'none') {
398
+            return \OCP\Files\FileInfo::SPACE_UNLIMITED;
399
+        }
400
+        return OC_Helper::computerFileSize($userQuota);
401
+    }
402
+
403
+    /**
404
+     * copies the skeleton to the users /files
405
+     *
406
+     * @param string $userId
407
+     * @param \OCP\Files\Folder $userDirectory
408
+     * @throws \OCP\Files\NotFoundException
409
+     * @throws \OCP\Files\NotPermittedException
410
+     * @suppress PhanDeprecatedFunction
411
+     */
412
+    public static function copySkeleton($userId, \OCP\Files\Folder $userDirectory) {
413
+        $plainSkeletonDirectory = \OC::$server->getConfig()->getSystemValue('skeletondirectory', \OC::$SERVERROOT . '/core/skeleton');
414
+        $userLang = \OC::$server->getL10NFactory()->findLanguage();
415
+        $skeletonDirectory = str_replace('{lang}', $userLang, $plainSkeletonDirectory);
416
+
417
+        if (!file_exists($skeletonDirectory)) {
418
+            $dialectStart = strpos($userLang, '_');
419
+            if ($dialectStart !== false) {
420
+                $skeletonDirectory = str_replace('{lang}', substr($userLang, 0, $dialectStart), $plainSkeletonDirectory);
421
+            }
422
+            if ($dialectStart === false || !file_exists($skeletonDirectory)) {
423
+                $skeletonDirectory = str_replace('{lang}', 'default', $plainSkeletonDirectory);
424
+            }
425
+            if (!file_exists($skeletonDirectory)) {
426
+                $skeletonDirectory = '';
427
+            }
428
+        }
429
+
430
+        $instanceId = \OC::$server->getConfig()->getSystemValue('instanceid', '');
431
+
432
+        if ($instanceId === null) {
433
+            throw new \RuntimeException('no instance id!');
434
+        }
435
+        $appdata = 'appdata_' . $instanceId;
436
+        if ($userId === $appdata) {
437
+            throw new \RuntimeException('username is reserved name: ' . $appdata);
438
+        }
439
+
440
+        if (!empty($skeletonDirectory)) {
441
+            \OCP\Util::writeLog(
442
+                'files_skeleton',
443
+                'copying skeleton for '.$userId.' from '.$skeletonDirectory.' to '.$userDirectory->getFullPath('/'),
444
+                ILogger::DEBUG
445
+            );
446
+            self::copyr($skeletonDirectory, $userDirectory);
447
+            // update the file cache
448
+            $userDirectory->getStorage()->getScanner()->scan('', \OC\Files\Cache\Scanner::SCAN_RECURSIVE);
449
+        }
450
+    }
451
+
452
+    /**
453
+     * copies a directory recursively by using streams
454
+     *
455
+     * @param string $source
456
+     * @param \OCP\Files\Folder $target
457
+     * @return void
458
+     */
459
+    public static function copyr($source, \OCP\Files\Folder $target) {
460
+        $logger = \OC::$server->getLogger();
461
+
462
+        // Verify if folder exists
463
+        $dir = opendir($source);
464
+        if ($dir === false) {
465
+            $logger->error(sprintf('Could not opendir "%s"', $source), ['app' => 'core']);
466
+            return;
467
+        }
468
+
469
+        // Copy the files
470
+        while (false !== ($file = readdir($dir))) {
471
+            if (!\OC\Files\Filesystem::isIgnoredDir($file)) {
472
+                if (is_dir($source . '/' . $file)) {
473
+                    $child = $target->newFolder($file);
474
+                    self::copyr($source . '/' . $file, $child);
475
+                } else {
476
+                    $child = $target->newFile($file);
477
+                    $sourceStream = fopen($source . '/' . $file, 'r');
478
+                    if ($sourceStream === false) {
479
+                        $logger->error(sprintf('Could not fopen "%s"', $source . '/' . $file), ['app' => 'core']);
480
+                        closedir($dir);
481
+                        return;
482
+                    }
483
+                    stream_copy_to_stream($sourceStream, $child->fopen('w'));
484
+                }
485
+            }
486
+        }
487
+        closedir($dir);
488
+    }
489
+
490
+    /**
491
+     * @return void
492
+     * @suppress PhanUndeclaredMethod
493
+     */
494
+    public static function tearDownFS() {
495
+        \OC\Files\Filesystem::tearDown();
496
+        \OC::$server->getRootFolder()->clearCache();
497
+        self::$fsSetup = false;
498
+        self::$rootMounted = false;
499
+    }
500
+
501
+    /**
502
+     * get the current installed version of ownCloud
503
+     *
504
+     * @return array
505
+     */
506
+    public static function getVersion() {
507
+        OC_Util::loadVersion();
508
+        return self::$versionCache['OC_Version'];
509
+    }
510
+
511
+    /**
512
+     * get the current installed version string of ownCloud
513
+     *
514
+     * @return string
515
+     */
516
+    public static function getVersionString() {
517
+        OC_Util::loadVersion();
518
+        return self::$versionCache['OC_VersionString'];
519
+    }
520
+
521
+    /**
522
+     * @deprecated the value is of no use anymore
523
+     * @return string
524
+     */
525
+    public static function getEditionString() {
526
+        return '';
527
+    }
528
+
529
+    /**
530
+     * @description get the update channel of the current installed of ownCloud.
531
+     * @return string
532
+     */
533
+    public static function getChannel() {
534
+        OC_Util::loadVersion();
535
+        return \OC::$server->getConfig()->getSystemValue('updater.release.channel', self::$versionCache['OC_Channel']);
536
+    }
537
+
538
+    /**
539
+     * @description get the build number of the current installed of ownCloud.
540
+     * @return string
541
+     */
542
+    public static function getBuild() {
543
+        OC_Util::loadVersion();
544
+        return self::$versionCache['OC_Build'];
545
+    }
546
+
547
+    /**
548
+     * @description load the version.php into the session as cache
549
+     * @suppress PhanUndeclaredVariable
550
+     */
551
+    private static function loadVersion() {
552
+        if (self::$versionCache !== null) {
553
+            return;
554
+        }
555
+
556
+        $timestamp = filemtime(OC::$SERVERROOT . '/version.php');
557
+        require OC::$SERVERROOT . '/version.php';
558
+        /** @var int $timestamp */
559
+        self::$versionCache['OC_Version_Timestamp'] = $timestamp;
560
+        /** @var string $OC_Version */
561
+        self::$versionCache['OC_Version'] = $OC_Version;
562
+        /** @var string $OC_VersionString */
563
+        self::$versionCache['OC_VersionString'] = $OC_VersionString;
564
+        /** @var string $OC_Build */
565
+        self::$versionCache['OC_Build'] = $OC_Build;
566
+
567
+        /** @var string $OC_Channel */
568
+        self::$versionCache['OC_Channel'] = $OC_Channel;
569
+    }
570
+
571
+    /**
572
+     * generates a path for JS/CSS files. If no application is provided it will create the path for core.
573
+     *
574
+     * @param string $application application to get the files from
575
+     * @param string $directory directory within this application (css, js, vendor, etc)
576
+     * @param string $file the file inside of the above folder
577
+     * @return string the path
578
+     */
579
+    private static function generatePath($application, $directory, $file) {
580
+        if (is_null($file)) {
581
+            $file = $application;
582
+            $application = "";
583
+        }
584
+        if (!empty($application)) {
585
+            return "$application/$directory/$file";
586
+        } else {
587
+            return "$directory/$file";
588
+        }
589
+    }
590
+
591
+    /**
592
+     * add a javascript file
593
+     *
594
+     * @param string $application application id
595
+     * @param string|null $file filename
596
+     * @param bool $prepend prepend the Script to the beginning of the list
597
+     * @return void
598
+     */
599
+    public static function addScript($application, $file = null, $prepend = false) {
600
+        $path = OC_Util::generatePath($application, 'js', $file);
601
+
602
+        // core js files need separate handling
603
+        if ($application !== 'core' && $file !== null) {
604
+            self::addTranslations($application);
605
+        }
606
+        self::addExternalResource($application, $prepend, $path, "script");
607
+    }
608
+
609
+    /**
610
+     * add a javascript file from the vendor sub folder
611
+     *
612
+     * @param string $application application id
613
+     * @param string|null $file filename
614
+     * @param bool $prepend prepend the Script to the beginning of the list
615
+     * @return void
616
+     */
617
+    public static function addVendorScript($application, $file = null, $prepend = false) {
618
+        $path = OC_Util::generatePath($application, 'vendor', $file);
619
+        self::addExternalResource($application, $prepend, $path, "script");
620
+    }
621
+
622
+    /**
623
+     * add a translation JS file
624
+     *
625
+     * @param string $application application id
626
+     * @param string|null $languageCode language code, defaults to the current language
627
+     * @param bool|null $prepend prepend the Script to the beginning of the list
628
+     */
629
+    public static function addTranslations($application, $languageCode = null, $prepend = false) {
630
+        if (is_null($languageCode)) {
631
+            $languageCode = \OC::$server->getL10NFactory()->findLanguage($application);
632
+        }
633
+        if (!empty($application)) {
634
+            $path = "$application/l10n/$languageCode";
635
+        } else {
636
+            $path = "l10n/$languageCode";
637
+        }
638
+        self::addExternalResource($application, $prepend, $path, "script");
639
+    }
640
+
641
+    /**
642
+     * add a css file
643
+     *
644
+     * @param string $application application id
645
+     * @param string|null $file filename
646
+     * @param bool $prepend prepend the Style to the beginning of the list
647
+     * @return void
648
+     */
649
+    public static function addStyle($application, $file = null, $prepend = false) {
650
+        $path = OC_Util::generatePath($application, 'css', $file);
651
+        self::addExternalResource($application, $prepend, $path, "style");
652
+    }
653
+
654
+    /**
655
+     * add a css file from the vendor sub folder
656
+     *
657
+     * @param string $application application id
658
+     * @param string|null $file filename
659
+     * @param bool $prepend prepend the Style to the beginning of the list
660
+     * @return void
661
+     */
662
+    public static function addVendorStyle($application, $file = null, $prepend = false) {
663
+        $path = OC_Util::generatePath($application, 'vendor', $file);
664
+        self::addExternalResource($application, $prepend, $path, "style");
665
+    }
666
+
667
+    /**
668
+     * add an external resource css/js file
669
+     *
670
+     * @param string $application application id
671
+     * @param bool $prepend prepend the file to the beginning of the list
672
+     * @param string $path
673
+     * @param string $type (script or style)
674
+     * @return void
675
+     */
676
+    private static function addExternalResource($application, $prepend, $path, $type = "script") {
677
+        if ($type === "style") {
678
+            if (!in_array($path, self::$styles)) {
679
+                if ($prepend === true) {
680
+                    array_unshift(self::$styles, $path);
681
+                } else {
682
+                    self::$styles[] = $path;
683
+                }
684
+            }
685
+        } elseif ($type === "script") {
686
+            if (!in_array($path, self::$scripts)) {
687
+                if ($prepend === true) {
688
+                    array_unshift(self::$scripts, $path);
689
+                } else {
690
+                    self::$scripts [] = $path;
691
+                }
692
+            }
693
+        }
694
+    }
695
+
696
+    /**
697
+     * Add a custom element to the header
698
+     * If $text is null then the element will be written as empty element.
699
+     * So use "" to get a closing tag.
700
+     * @param string $tag tag name of the element
701
+     * @param array $attributes array of attributes for the element
702
+     * @param string $text the text content for the element
703
+     * @param bool $prepend prepend the header to the beginning of the list
704
+     */
705
+    public static function addHeader($tag, $attributes, $text = null, $prepend = false) {
706
+        $header = [
707
+            'tag' => $tag,
708
+            'attributes' => $attributes,
709
+            'text' => $text
710
+        ];
711
+        if ($prepend === true) {
712
+            array_unshift(self::$headers, $header);
713
+        } else {
714
+            self::$headers[] = $header;
715
+        }
716
+    }
717
+
718
+    /**
719
+     * check if the current server configuration is suitable for ownCloud
720
+     *
721
+     * @param \OC\SystemConfig $config
722
+     * @return array arrays with error messages and hints
723
+     */
724
+    public static function checkServer(\OC\SystemConfig $config) {
725
+        $l = \OC::$server->getL10N('lib');
726
+        $errors = [];
727
+        $CONFIG_DATADIRECTORY = $config->getValue('datadirectory', OC::$SERVERROOT . '/data');
728
+
729
+        if (!self::needUpgrade($config) && $config->getValue('installed', false)) {
730
+            // this check needs to be done every time
731
+            $errors = self::checkDataDirectoryValidity($CONFIG_DATADIRECTORY);
732
+        }
733
+
734
+        // Assume that if checkServer() succeeded before in this session, then all is fine.
735
+        if (\OC::$server->getSession()->exists('checkServer_succeeded') && \OC::$server->getSession()->get('checkServer_succeeded')) {
736
+            return $errors;
737
+        }
738
+
739
+        $webServerRestart = false;
740
+        $setup = new \OC\Setup(
741
+            $config,
742
+            \OC::$server->get(IniGetWrapper::class),
743
+            \OC::$server->getL10N('lib'),
744
+            \OC::$server->query(\OCP\Defaults::class),
745
+            \OC::$server->getLogger(),
746
+            \OC::$server->getSecureRandom(),
747
+            \OC::$server->query(\OC\Installer::class)
748
+        );
749
+
750
+        $urlGenerator = \OC::$server->getURLGenerator();
751
+
752
+        $availableDatabases = $setup->getSupportedDatabases();
753
+        if (empty($availableDatabases)) {
754
+            $errors[] = [
755
+                'error' => $l->t('No database drivers (sqlite, mysql, or postgresql) installed.'),
756
+                'hint' => '' //TODO: sane hint
757
+            ];
758
+            $webServerRestart = true;
759
+        }
760
+
761
+        // Check if config folder is writable.
762
+        if (!OC_Helper::isReadOnlyConfigEnabled()) {
763
+            if (!is_writable(OC::$configDir) or !is_readable(OC::$configDir)) {
764
+                $errors[] = [
765
+                    'error' => $l->t('Cannot write into "config" directory'),
766
+                    'hint' => $l->t('This can usually be fixed by giving the webserver write access to the config directory. See %s',
767
+                        [ $urlGenerator->linkToDocs('admin-dir_permissions') ]) . '. '
768
+                        . $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',
769
+                        [ $urlGenerator->linkToDocs('admin-config') ])
770
+                ];
771
+            }
772
+        }
773
+
774
+        // Check if there is a writable install folder.
775
+        if ($config->getValue('appstoreenabled', true)) {
776
+            if (OC_App::getInstallPath() === null
777
+                || !is_writable(OC_App::getInstallPath())
778
+                || !is_readable(OC_App::getInstallPath())
779
+            ) {
780
+                $errors[] = [
781
+                    'error' => $l->t('Cannot write into "apps" directory'),
782
+                    'hint' => $l->t('This can usually be fixed by giving the webserver write access to the apps directory'
783
+                        . ' or disabling the appstore in the config file.')
784
+                ];
785
+            }
786
+        }
787
+        // Create root dir.
788
+        if ($config->getValue('installed', false)) {
789
+            if (!is_dir($CONFIG_DATADIRECTORY)) {
790
+                $success = @mkdir($CONFIG_DATADIRECTORY);
791
+                if ($success) {
792
+                    $errors = array_merge($errors, self::checkDataDirectoryPermissions($CONFIG_DATADIRECTORY));
793
+                } else {
794
+                    $errors[] = [
795
+                        'error' => $l->t('Cannot create "data" directory'),
796
+                        'hint' => $l->t('This can usually be fixed by giving the webserver write access to the root directory. See %s',
797
+                            [$urlGenerator->linkToDocs('admin-dir_permissions')])
798
+                    ];
799
+                }
800
+            } elseif (!is_writable($CONFIG_DATADIRECTORY) or !is_readable($CONFIG_DATADIRECTORY)) {
801
+                // is_writable doesn't work for NFS mounts, so try to write a file and check if it exists.
802
+                $testFile = sprintf('%s/%s.tmp', $CONFIG_DATADIRECTORY, uniqid('data_dir_writability_test_'));
803
+                $handle = fopen($testFile, 'w');
804
+                if (!$handle || fwrite($handle, 'Test write operation') === false) {
805
+                    $permissionsHint = $l->t('Permissions can usually be fixed by giving the webserver write access to the root directory. See %s.',
806
+                        [$urlGenerator->linkToDocs('admin-dir_permissions')]);
807
+                    $errors[] = [
808
+                        'error' => 'Your data directory is not writable',
809
+                        'hint' => $permissionsHint
810
+                    ];
811
+                } else {
812
+                    fclose($handle);
813
+                    unlink($testFile);
814
+                }
815
+            } else {
816
+                $errors = array_merge($errors, self::checkDataDirectoryPermissions($CONFIG_DATADIRECTORY));
817
+            }
818
+        }
819
+
820
+        if (!OC_Util::isSetLocaleWorking()) {
821
+            $errors[] = [
822
+                'error' => $l->t('Setting locale to %s failed',
823
+                    ['en_US.UTF-8/fr_FR.UTF-8/es_ES.UTF-8/de_DE.UTF-8/ru_RU.UTF-8/'
824
+                        . 'pt_BR.UTF-8/it_IT.UTF-8/ja_JP.UTF-8/zh_CN.UTF-8']),
825
+                'hint' => $l->t('Please install one of these locales on your system and restart your webserver.')
826
+            ];
827
+        }
828
+
829
+        // Contains the dependencies that should be checked against
830
+        // classes = class_exists
831
+        // functions = function_exists
832
+        // defined = defined
833
+        // ini = ini_get
834
+        // If the dependency is not found the missing module name is shown to the EndUser
835
+        // When adding new checks always verify that they pass on Travis as well
836
+        // for ini settings, see https://github.com/owncloud/administration/blob/master/travis-ci/custom.ini
837
+        $dependencies = [
838
+            'classes' => [
839
+                'ZipArchive' => 'zip',
840
+                'DOMDocument' => 'dom',
841
+                'XMLWriter' => 'XMLWriter',
842
+                'XMLReader' => 'XMLReader',
843
+            ],
844
+            'functions' => [
845
+                'xml_parser_create' => 'libxml',
846
+                'mb_strcut' => 'mbstring',
847
+                'ctype_digit' => 'ctype',
848
+                'json_encode' => 'JSON',
849
+                'gd_info' => 'GD',
850
+                'gzencode' => 'zlib',
851
+                'iconv' => 'iconv',
852
+                'simplexml_load_string' => 'SimpleXML',
853
+                'hash' => 'HASH Message Digest Framework',
854
+                'curl_init' => 'cURL',
855
+                'openssl_verify' => 'OpenSSL',
856
+            ],
857
+            'defined' => [
858
+                'PDO::ATTR_DRIVER_NAME' => 'PDO'
859
+            ],
860
+            'ini' => [
861
+                'default_charset' => 'UTF-8',
862
+            ],
863
+        ];
864
+        $missingDependencies = [];
865
+        $invalidIniSettings = [];
866
+
867
+        $iniWrapper = \OC::$server->get(IniGetWrapper::class);
868
+        foreach ($dependencies['classes'] as $class => $module) {
869
+            if (!class_exists($class)) {
870
+                $missingDependencies[] = $module;
871
+            }
872
+        }
873
+        foreach ($dependencies['functions'] as $function => $module) {
874
+            if (!function_exists($function)) {
875
+                $missingDependencies[] = $module;
876
+            }
877
+        }
878
+        foreach ($dependencies['defined'] as $defined => $module) {
879
+            if (!defined($defined)) {
880
+                $missingDependencies[] = $module;
881
+            }
882
+        }
883
+        foreach ($dependencies['ini'] as $setting => $expected) {
884
+            if (is_bool($expected)) {
885
+                if ($iniWrapper->getBool($setting) !== $expected) {
886
+                    $invalidIniSettings[] = [$setting, $expected];
887
+                }
888
+            }
889
+            if (is_int($expected)) {
890
+                if ($iniWrapper->getNumeric($setting) !== $expected) {
891
+                    $invalidIniSettings[] = [$setting, $expected];
892
+                }
893
+            }
894
+            if (is_string($expected)) {
895
+                if (strtolower($iniWrapper->getString($setting)) !== strtolower($expected)) {
896
+                    $invalidIniSettings[] = [$setting, $expected];
897
+                }
898
+            }
899
+        }
900
+
901
+        foreach ($missingDependencies as $missingDependency) {
902
+            $errors[] = [
903
+                'error' => $l->t('PHP module %s not installed.', [$missingDependency]),
904
+                'hint' => $l->t('Please ask your server administrator to install the module.'),
905
+            ];
906
+            $webServerRestart = true;
907
+        }
908
+        foreach ($invalidIniSettings as $setting) {
909
+            if (is_bool($setting[1])) {
910
+                $setting[1] = $setting[1] ? 'on' : 'off';
911
+            }
912
+            $errors[] = [
913
+                'error' => $l->t('PHP setting "%s" is not set to "%s".', [$setting[0], var_export($setting[1], true)]),
914
+                'hint' =>  $l->t('Adjusting this setting in php.ini will make Nextcloud run again')
915
+            ];
916
+            $webServerRestart = true;
917
+        }
918
+
919
+        /**
920
+         * The mbstring.func_overload check can only be performed if the mbstring
921
+         * module is installed as it will return null if the checking setting is
922
+         * not available and thus a check on the boolean value fails.
923
+         *
924
+         * TODO: Should probably be implemented in the above generic dependency
925
+         *       check somehow in the long-term.
926
+         */
927
+        if ($iniWrapper->getBool('mbstring.func_overload') !== null &&
928
+            $iniWrapper->getBool('mbstring.func_overload') === true) {
929
+            $errors[] = [
930
+                'error' => $l->t('mbstring.func_overload is set to "%s" instead of the expected value "0"', [$iniWrapper->getString('mbstring.func_overload')]),
931
+                'hint' => $l->t('To fix this issue set <code>mbstring.func_overload</code> to <code>0</code> in your php.ini')
932
+            ];
933
+        }
934
+
935
+        if (function_exists('xml_parser_create') &&
936
+            LIBXML_LOADED_VERSION < 20700) {
937
+            $version = LIBXML_LOADED_VERSION;
938
+            $major = floor($version/10000);
939
+            $version -= ($major * 10000);
940
+            $minor = floor($version/100);
941
+            $version -= ($minor * 100);
942
+            $patch = $version;
943
+            $errors[] = [
944
+                'error' => $l->t('libxml2 2.7.0 is at least required. Currently %s is installed.', [$major . '.' . $minor . '.' . $patch]),
945
+                'hint' => $l->t('To fix this issue update your libxml2 version and restart your web server.')
946
+            ];
947
+        }
948
+
949
+        if (!self::isAnnotationsWorking()) {
950
+            $errors[] = [
951
+                'error' => $l->t('PHP is apparently set up to strip inline doc blocks. This will make several core apps inaccessible.'),
952
+                'hint' => $l->t('This is probably caused by a cache/accelerator such as Zend OPcache or eAccelerator.')
953
+            ];
954
+        }
955
+
956
+        if (!\OC::$CLI && $webServerRestart) {
957
+            $errors[] = [
958
+                'error' => $l->t('PHP modules have been installed, but they are still listed as missing?'),
959
+                'hint' => $l->t('Please ask your server administrator to restart the web server.')
960
+            ];
961
+        }
962
+
963
+        $errors = array_merge($errors, self::checkDatabaseVersion());
964
+
965
+        // Cache the result of this function
966
+        \OC::$server->getSession()->set('checkServer_succeeded', count($errors) == 0);
967
+
968
+        return $errors;
969
+    }
970
+
971
+    /**
972
+     * Check the database version
973
+     *
974
+     * @return array errors array
975
+     */
976
+    public static function checkDatabaseVersion() {
977
+        $l = \OC::$server->getL10N('lib');
978
+        $errors = [];
979
+        $dbType = \OC::$server->getSystemConfig()->getValue('dbtype', 'sqlite');
980
+        if ($dbType === 'pgsql') {
981
+            // check PostgreSQL version
982
+            try {
983
+                $result = \OC_DB::executeAudited('SHOW SERVER_VERSION');
984
+                $data = $result->fetchRow();
985
+                if (isset($data['server_version'])) {
986
+                    $version = $data['server_version'];
987
+                    if (version_compare($version, '9.0.0', '<')) {
988
+                        $errors[] = [
989
+                            'error' => $l->t('PostgreSQL >= 9 required'),
990
+                            'hint' => $l->t('Please upgrade your database version')
991
+                        ];
992
+                    }
993
+                }
994
+            } catch (\Doctrine\DBAL\DBALException $e) {
995
+                $logger = \OC::$server->getLogger();
996
+                $logger->warning('Error occurred while checking PostgreSQL version, assuming >= 9');
997
+                $logger->logException($e);
998
+            }
999
+        }
1000
+        return $errors;
1001
+    }
1002
+
1003
+    /**
1004
+     * Check for correct file permissions of data directory
1005
+     *
1006
+     * @param string $dataDirectory
1007
+     * @return array arrays with error messages and hints
1008
+     */
1009
+    public static function checkDataDirectoryPermissions($dataDirectory) {
1010
+        if (\OC::$server->getConfig()->getSystemValue('check_data_directory_permissions', true) === false) {
1011
+            return  [];
1012
+        }
1013
+
1014
+        $perms = substr(decoct(@fileperms($dataDirectory)), -3);
1015
+        if (substr($perms, -1) !== '0') {
1016
+            chmod($dataDirectory, 0770);
1017
+            clearstatcache();
1018
+            $perms = substr(decoct(@fileperms($dataDirectory)), -3);
1019
+            if ($perms[2] !== '0') {
1020
+                $l = \OC::$server->getL10N('lib');
1021
+                return [[
1022
+                    'error' => $l->t('Your data directory is readable by other users'),
1023
+                    'hint' => $l->t('Please change the permissions to 0770 so that the directory cannot be listed by other users.'),
1024
+                ]];
1025
+            }
1026
+        }
1027
+        return [];
1028
+    }
1029
+
1030
+    /**
1031
+     * Check that the data directory exists and is valid by
1032
+     * checking the existence of the ".ocdata" file.
1033
+     *
1034
+     * @param string $dataDirectory data directory path
1035
+     * @return array errors found
1036
+     */
1037
+    public static function checkDataDirectoryValidity($dataDirectory) {
1038
+        $l = \OC::$server->getL10N('lib');
1039
+        $errors = [];
1040
+        if ($dataDirectory[0] !== '/') {
1041
+            $errors[] = [
1042
+                'error' => $l->t('Your data directory must be an absolute path'),
1043
+                'hint' => $l->t('Check the value of "datadirectory" in your configuration')
1044
+            ];
1045
+        }
1046
+        if (!file_exists($dataDirectory . '/.ocdata')) {
1047
+            $errors[] = [
1048
+                'error' => $l->t('Your data directory is invalid'),
1049
+                'hint' => $l->t('Ensure there is a file called ".ocdata"' .
1050
+                    ' in the root of the data directory.')
1051
+            ];
1052
+        }
1053
+        return $errors;
1054
+    }
1055
+
1056
+    /**
1057
+     * Check if the user is logged in, redirects to home if not. With
1058
+     * redirect URL parameter to the request URI.
1059
+     *
1060
+     * @return void
1061
+     */
1062
+    public static function checkLoggedIn() {
1063
+        // Check if we are a user
1064
+        if (!\OC::$server->getUserSession()->isLoggedIn()) {
1065
+            header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute(
1066
+                        'core.login.showLoginForm',
1067
+                        [
1068
+                            'redirect_url' => \OC::$server->getRequest()->getRequestUri(),
1069
+                        ]
1070
+                    )
1071
+            );
1072
+            exit();
1073
+        }
1074
+        // Redirect to 2FA challenge selection if 2FA challenge was not solved yet
1075
+        if (\OC::$server->getTwoFactorAuthManager()->needsSecondFactor(\OC::$server->getUserSession()->getUser())) {
1076
+            header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute('core.TwoFactorChallenge.selectChallenge'));
1077
+            exit();
1078
+        }
1079
+    }
1080
+
1081
+    /**
1082
+     * Check if the user is a admin, redirects to home if not
1083
+     *
1084
+     * @return void
1085
+     */
1086
+    public static function checkAdminUser() {
1087
+        OC_Util::checkLoggedIn();
1088
+        if (!OC_User::isAdminUser(OC_User::getUser())) {
1089
+            header('Location: ' . \OCP\Util::linkToAbsolute('', 'index.php'));
1090
+            exit();
1091
+        }
1092
+    }
1093
+
1094
+    /**
1095
+     * Returns the URL of the default page
1096
+     * based on the system configuration and
1097
+     * the apps visible for the current user
1098
+     *
1099
+     * @return string URL
1100
+     * @suppress PhanDeprecatedFunction
1101
+     */
1102
+    public static function getDefaultPageUrl() {
1103
+        /** @var IConfig $config */
1104
+        $config = \OC::$server->get(IConfig::class);
1105
+        $urlGenerator = \OC::$server->getURLGenerator();
1106
+        // Deny the redirect if the URL contains a @
1107
+        // This prevents unvalidated redirects like ?redirect_url=:[email protected]
1108
+        if (isset($_REQUEST['redirect_url']) && strpos($_REQUEST['redirect_url'], '@') === false) {
1109
+            $location = $urlGenerator->getAbsoluteURL(urldecode($_REQUEST['redirect_url']));
1110
+        } else {
1111
+            $defaultPage = \OC::$server->getConfig()->getAppValue('core', 'defaultpage');
1112
+            if ($defaultPage) {
1113
+                $location = $urlGenerator->getAbsoluteURL($defaultPage);
1114
+            } else {
1115
+                $appId = 'files';
1116
+                $defaultApps = explode(',', $config->getSystemValue('defaultapp', 'dashboard,files'));
1117
+
1118
+                /** @var IUserSession $userSession */
1119
+                $userSession = \OC::$server->get(IUserSession::class);
1120
+                $user = $userSession->getUser();
1121
+                if ($user) {
1122
+                    $userDefaultApps = explode(',', $config->getUserValue($user->getUID(), 'core', 'defaultapp'));
1123
+                    $defaultApps = array_filter(array_merge($userDefaultApps, $defaultApps));
1124
+                }
1125
+
1126
+                // find the first app that is enabled for the current user
1127
+                foreach ($defaultApps as $defaultApp) {
1128
+                    $defaultApp = OC_App::cleanAppId(strip_tags($defaultApp));
1129
+                    if (static::getAppManager()->isEnabledForUser($defaultApp)) {
1130
+                        $appId = $defaultApp;
1131
+                        break;
1132
+                    }
1133
+                }
1134
+
1135
+                if ($config->getSystemValue('htaccess.IgnoreFrontController', false) === true || getenv('front_controller_active') === 'true') {
1136
+                    $location = $urlGenerator->getAbsoluteURL('/apps/' . $appId . '/');
1137
+                } else {
1138
+                    $location = $urlGenerator->getAbsoluteURL('/index.php/apps/' . $appId . '/');
1139
+                }
1140
+            }
1141
+        }
1142
+        return $location;
1143
+    }
1144
+
1145
+    /**
1146
+     * Redirect to the user default page
1147
+     *
1148
+     * @return void
1149
+     */
1150
+    public static function redirectToDefaultPage() {
1151
+        $location = self::getDefaultPageUrl();
1152
+        header('Location: ' . $location);
1153
+        exit();
1154
+    }
1155
+
1156
+    /**
1157
+     * get an id unique for this instance
1158
+     *
1159
+     * @return string
1160
+     */
1161
+    public static function getInstanceId() {
1162
+        $id = \OC::$server->getSystemConfig()->getValue('instanceid', null);
1163
+        if (is_null($id)) {
1164
+            // We need to guarantee at least one letter in instanceid so it can be used as the session_name
1165
+            $id = 'oc' . \OC::$server->getSecureRandom()->generate(10, \OCP\Security\ISecureRandom::CHAR_LOWER.\OCP\Security\ISecureRandom::CHAR_DIGITS);
1166
+            \OC::$server->getSystemConfig()->setValue('instanceid', $id);
1167
+        }
1168
+        return $id;
1169
+    }
1170
+
1171
+    /**
1172
+     * Public function to sanitize HTML
1173
+     *
1174
+     * This function is used to sanitize HTML and should be applied on any
1175
+     * string or array of strings before displaying it on a web page.
1176
+     *
1177
+     * @param string|array $value
1178
+     * @return string|array an array of sanitized strings or a single sanitized string, depends on the input parameter.
1179
+     */
1180
+    public static function sanitizeHTML($value) {
1181
+        if (is_array($value)) {
1182
+            $value = array_map(function ($value) {
1183
+                return self::sanitizeHTML($value);
1184
+            }, $value);
1185
+        } else {
1186
+            // Specify encoding for PHP<5.4
1187
+            $value = htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
1188
+        }
1189
+        return $value;
1190
+    }
1191
+
1192
+    /**
1193
+     * Public function to encode url parameters
1194
+     *
1195
+     * This function is used to encode path to file before output.
1196
+     * Encoding is done according to RFC 3986 with one exception:
1197
+     * Character '/' is preserved as is.
1198
+     *
1199
+     * @param string $component part of URI to encode
1200
+     * @return string
1201
+     */
1202
+    public static function encodePath($component) {
1203
+        $encoded = rawurlencode($component);
1204
+        $encoded = str_replace('%2F', '/', $encoded);
1205
+        return $encoded;
1206
+    }
1207
+
1208
+
1209
+    public function createHtaccessTestFile(\OCP\IConfig $config) {
1210
+        // php dev server does not support htaccess
1211
+        if (php_sapi_name() === 'cli-server') {
1212
+            return false;
1213
+        }
1214
+
1215
+        // testdata
1216
+        $fileName = '/htaccesstest.txt';
1217
+        $testContent = 'This is used for testing whether htaccess is properly enabled to disallow access from the outside. This file can be safely removed.';
1218
+
1219
+        // creating a test file
1220
+        $testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
1221
+
1222
+        if (file_exists($testFile)) {// already running this test, possible recursive call
1223
+            return false;
1224
+        }
1225
+
1226
+        $fp = @fopen($testFile, 'w');
1227
+        if (!$fp) {
1228
+            throw new OC\HintException('Can\'t create test file to check for working .htaccess file.',
1229
+                'Make sure it is possible for the webserver to write to ' . $testFile);
1230
+        }
1231
+        fwrite($fp, $testContent);
1232
+        fclose($fp);
1233
+
1234
+        return $testContent;
1235
+    }
1236
+
1237
+    /**
1238
+     * Check if the .htaccess file is working
1239
+     * @param \OCP\IConfig $config
1240
+     * @return bool
1241
+     * @throws Exception
1242
+     * @throws \OC\HintException If the test file can't get written.
1243
+     */
1244
+    public function isHtaccessWorking(\OCP\IConfig $config) {
1245
+        if (\OC::$CLI || !$config->getSystemValue('check_for_working_htaccess', true)) {
1246
+            return true;
1247
+        }
1248
+
1249
+        $testContent = $this->createHtaccessTestFile($config);
1250
+        if ($testContent === false) {
1251
+            return false;
1252
+        }
1253
+
1254
+        $fileName = '/htaccesstest.txt';
1255
+        $testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
1256
+
1257
+        // accessing the file via http
1258
+        $url = \OC::$server->getURLGenerator()->getAbsoluteURL(OC::$WEBROOT . '/data' . $fileName);
1259
+        try {
1260
+            $content = \OC::$server->getHTTPClientService()->newClient()->get($url)->getBody();
1261
+        } catch (\Exception $e) {
1262
+            $content = false;
1263
+        }
1264
+
1265
+        if (strpos($url, 'https:') === 0) {
1266
+            $url = 'http:' . substr($url, 6);
1267
+        } else {
1268
+            $url = 'https:' . substr($url, 5);
1269
+        }
1270
+
1271
+        try {
1272
+            $fallbackContent = \OC::$server->getHTTPClientService()->newClient()->get($url)->getBody();
1273
+        } catch (\Exception $e) {
1274
+            $fallbackContent = false;
1275
+        }
1276
+
1277
+        // cleanup
1278
+        @unlink($testFile);
1279
+
1280
+        /*
1281 1281
 		 * If the content is not equal to test content our .htaccess
1282 1282
 		 * is working as required
1283 1283
 		 */
1284
-		return $content !== $testContent && $fallbackContent !== $testContent;
1285
-	}
1286
-
1287
-	/**
1288
-	 * Check if the setlocal call does not work. This can happen if the right
1289
-	 * local packages are not available on the server.
1290
-	 *
1291
-	 * @return bool
1292
-	 */
1293
-	public static function isSetLocaleWorking() {
1294
-		\Patchwork\Utf8\Bootup::initLocale();
1295
-		if ('' === basename('§')) {
1296
-			return false;
1297
-		}
1298
-		return true;
1299
-	}
1300
-
1301
-	/**
1302
-	 * Check if it's possible to get the inline annotations
1303
-	 *
1304
-	 * @return bool
1305
-	 */
1306
-	public static function isAnnotationsWorking() {
1307
-		$reflection = new \ReflectionMethod(__METHOD__);
1308
-		$docs = $reflection->getDocComment();
1309
-
1310
-		return (is_string($docs) && strlen($docs) > 50);
1311
-	}
1312
-
1313
-	/**
1314
-	 * Check if the PHP module fileinfo is loaded.
1315
-	 *
1316
-	 * @return bool
1317
-	 */
1318
-	public static function fileInfoLoaded() {
1319
-		return function_exists('finfo_open');
1320
-	}
1321
-
1322
-	/**
1323
-	 * clear all levels of output buffering
1324
-	 *
1325
-	 * @return void
1326
-	 */
1327
-	public static function obEnd() {
1328
-		while (ob_get_level()) {
1329
-			ob_end_clean();
1330
-		}
1331
-	}
1332
-
1333
-	/**
1334
-	 * Checks whether the server is running on Mac OS X
1335
-	 *
1336
-	 * @return bool true if running on Mac OS X, false otherwise
1337
-	 */
1338
-	public static function runningOnMac() {
1339
-		return (strtoupper(substr(PHP_OS, 0, 6)) === 'DARWIN');
1340
-	}
1341
-
1342
-	/**
1343
-	 * Handles the case that there may not be a theme, then check if a "default"
1344
-	 * theme exists and take that one
1345
-	 *
1346
-	 * @return string the theme
1347
-	 */
1348
-	public static function getTheme() {
1349
-		$theme = \OC::$server->getSystemConfig()->getValue("theme", '');
1350
-
1351
-		if ($theme === '') {
1352
-			if (is_dir(OC::$SERVERROOT . '/themes/default')) {
1353
-				$theme = 'default';
1354
-			}
1355
-		}
1356
-
1357
-		return $theme;
1358
-	}
1359
-
1360
-	/**
1361
-	 * Normalize a unicode string
1362
-	 *
1363
-	 * @param string $value a not normalized string
1364
-	 * @return bool|string
1365
-	 */
1366
-	public static function normalizeUnicode($value) {
1367
-		if (Normalizer::isNormalized($value)) {
1368
-			return $value;
1369
-		}
1370
-
1371
-		$normalizedValue = Normalizer::normalize($value);
1372
-		if ($normalizedValue === null || $normalizedValue === false) {
1373
-			\OC::$server->getLogger()->warning('normalizing failed for "' . $value . '"', ['app' => 'core']);
1374
-			return $value;
1375
-		}
1376
-
1377
-		return $normalizedValue;
1378
-	}
1379
-
1380
-	/**
1381
-	 * A human readable string is generated based on version and build number
1382
-	 *
1383
-	 * @return string
1384
-	 */
1385
-	public static function getHumanVersion() {
1386
-		$version = OC_Util::getVersionString();
1387
-		$build = OC_Util::getBuild();
1388
-		if (!empty($build) and OC_Util::getChannel() === 'daily') {
1389
-			$version .= ' Build:' . $build;
1390
-		}
1391
-		return $version;
1392
-	}
1393
-
1394
-	/**
1395
-	 * Returns whether the given file name is valid
1396
-	 *
1397
-	 * @param string $file file name to check
1398
-	 * @return bool true if the file name is valid, false otherwise
1399
-	 * @deprecated use \OC\Files\View::verifyPath()
1400
-	 */
1401
-	public static function isValidFileName($file) {
1402
-		$trimmed = trim($file);
1403
-		if ($trimmed === '') {
1404
-			return false;
1405
-		}
1406
-		if (\OC\Files\Filesystem::isIgnoredDir($trimmed)) {
1407
-			return false;
1408
-		}
1409
-
1410
-		// detect part files
1411
-		if (preg_match('/' . \OCP\Files\FileInfo::BLACKLIST_FILES_REGEX . '/', $trimmed) !== 0) {
1412
-			return false;
1413
-		}
1414
-
1415
-		foreach (str_split($trimmed) as $char) {
1416
-			if (strpos(\OCP\Constants::FILENAME_INVALID_CHARS, $char) !== false) {
1417
-				return false;
1418
-			}
1419
-		}
1420
-		return true;
1421
-	}
1422
-
1423
-	/**
1424
-	 * Check whether the instance needs to perform an upgrade,
1425
-	 * either when the core version is higher or any app requires
1426
-	 * an upgrade.
1427
-	 *
1428
-	 * @param \OC\SystemConfig $config
1429
-	 * @return bool whether the core or any app needs an upgrade
1430
-	 * @throws \OC\HintException When the upgrade from the given version is not allowed
1431
-	 */
1432
-	public static function needUpgrade(\OC\SystemConfig $config) {
1433
-		if ($config->getValue('installed', false)) {
1434
-			$installedVersion = $config->getValue('version', '0.0.0');
1435
-			$currentVersion = implode('.', \OCP\Util::getVersion());
1436
-			$versionDiff = version_compare($currentVersion, $installedVersion);
1437
-			if ($versionDiff > 0) {
1438
-				return true;
1439
-			} elseif ($config->getValue('debug', false) && $versionDiff < 0) {
1440
-				// downgrade with debug
1441
-				$installedMajor = explode('.', $installedVersion);
1442
-				$installedMajor = $installedMajor[0] . '.' . $installedMajor[1];
1443
-				$currentMajor = explode('.', $currentVersion);
1444
-				$currentMajor = $currentMajor[0] . '.' . $currentMajor[1];
1445
-				if ($installedMajor === $currentMajor) {
1446
-					// Same major, allow downgrade for developers
1447
-					return true;
1448
-				} else {
1449
-					// downgrade attempt, throw exception
1450
-					throw new \OC\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
1451
-				}
1452
-			} elseif ($versionDiff < 0) {
1453
-				// downgrade attempt, throw exception
1454
-				throw new \OC\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
1455
-			}
1456
-
1457
-			// also check for upgrades for apps (independently from the user)
1458
-			$apps = \OC_App::getEnabledApps(false, true);
1459
-			$shouldUpgrade = false;
1460
-			foreach ($apps as $app) {
1461
-				if (\OC_App::shouldUpgrade($app)) {
1462
-					$shouldUpgrade = true;
1463
-					break;
1464
-				}
1465
-			}
1466
-			return $shouldUpgrade;
1467
-		} else {
1468
-			return false;
1469
-		}
1470
-	}
1471
-
1472
-	/**
1473
-	 * is this Internet explorer ?
1474
-	 *
1475
-	 * @return boolean
1476
-	 */
1477
-	public static function isIe() {
1478
-		if (!isset($_SERVER['HTTP_USER_AGENT'])) {
1479
-			return false;
1480
-		}
1481
-
1482
-		return preg_match(Request::USER_AGENT_IE, $_SERVER['HTTP_USER_AGENT']) === 1;
1483
-	}
1284
+        return $content !== $testContent && $fallbackContent !== $testContent;
1285
+    }
1286
+
1287
+    /**
1288
+     * Check if the setlocal call does not work. This can happen if the right
1289
+     * local packages are not available on the server.
1290
+     *
1291
+     * @return bool
1292
+     */
1293
+    public static function isSetLocaleWorking() {
1294
+        \Patchwork\Utf8\Bootup::initLocale();
1295
+        if ('' === basename('§')) {
1296
+            return false;
1297
+        }
1298
+        return true;
1299
+    }
1300
+
1301
+    /**
1302
+     * Check if it's possible to get the inline annotations
1303
+     *
1304
+     * @return bool
1305
+     */
1306
+    public static function isAnnotationsWorking() {
1307
+        $reflection = new \ReflectionMethod(__METHOD__);
1308
+        $docs = $reflection->getDocComment();
1309
+
1310
+        return (is_string($docs) && strlen($docs) > 50);
1311
+    }
1312
+
1313
+    /**
1314
+     * Check if the PHP module fileinfo is loaded.
1315
+     *
1316
+     * @return bool
1317
+     */
1318
+    public static function fileInfoLoaded() {
1319
+        return function_exists('finfo_open');
1320
+    }
1321
+
1322
+    /**
1323
+     * clear all levels of output buffering
1324
+     *
1325
+     * @return void
1326
+     */
1327
+    public static function obEnd() {
1328
+        while (ob_get_level()) {
1329
+            ob_end_clean();
1330
+        }
1331
+    }
1332
+
1333
+    /**
1334
+     * Checks whether the server is running on Mac OS X
1335
+     *
1336
+     * @return bool true if running on Mac OS X, false otherwise
1337
+     */
1338
+    public static function runningOnMac() {
1339
+        return (strtoupper(substr(PHP_OS, 0, 6)) === 'DARWIN');
1340
+    }
1341
+
1342
+    /**
1343
+     * Handles the case that there may not be a theme, then check if a "default"
1344
+     * theme exists and take that one
1345
+     *
1346
+     * @return string the theme
1347
+     */
1348
+    public static function getTheme() {
1349
+        $theme = \OC::$server->getSystemConfig()->getValue("theme", '');
1350
+
1351
+        if ($theme === '') {
1352
+            if (is_dir(OC::$SERVERROOT . '/themes/default')) {
1353
+                $theme = 'default';
1354
+            }
1355
+        }
1356
+
1357
+        return $theme;
1358
+    }
1359
+
1360
+    /**
1361
+     * Normalize a unicode string
1362
+     *
1363
+     * @param string $value a not normalized string
1364
+     * @return bool|string
1365
+     */
1366
+    public static function normalizeUnicode($value) {
1367
+        if (Normalizer::isNormalized($value)) {
1368
+            return $value;
1369
+        }
1370
+
1371
+        $normalizedValue = Normalizer::normalize($value);
1372
+        if ($normalizedValue === null || $normalizedValue === false) {
1373
+            \OC::$server->getLogger()->warning('normalizing failed for "' . $value . '"', ['app' => 'core']);
1374
+            return $value;
1375
+        }
1376
+
1377
+        return $normalizedValue;
1378
+    }
1379
+
1380
+    /**
1381
+     * A human readable string is generated based on version and build number
1382
+     *
1383
+     * @return string
1384
+     */
1385
+    public static function getHumanVersion() {
1386
+        $version = OC_Util::getVersionString();
1387
+        $build = OC_Util::getBuild();
1388
+        if (!empty($build) and OC_Util::getChannel() === 'daily') {
1389
+            $version .= ' Build:' . $build;
1390
+        }
1391
+        return $version;
1392
+    }
1393
+
1394
+    /**
1395
+     * Returns whether the given file name is valid
1396
+     *
1397
+     * @param string $file file name to check
1398
+     * @return bool true if the file name is valid, false otherwise
1399
+     * @deprecated use \OC\Files\View::verifyPath()
1400
+     */
1401
+    public static function isValidFileName($file) {
1402
+        $trimmed = trim($file);
1403
+        if ($trimmed === '') {
1404
+            return false;
1405
+        }
1406
+        if (\OC\Files\Filesystem::isIgnoredDir($trimmed)) {
1407
+            return false;
1408
+        }
1409
+
1410
+        // detect part files
1411
+        if (preg_match('/' . \OCP\Files\FileInfo::BLACKLIST_FILES_REGEX . '/', $trimmed) !== 0) {
1412
+            return false;
1413
+        }
1414
+
1415
+        foreach (str_split($trimmed) as $char) {
1416
+            if (strpos(\OCP\Constants::FILENAME_INVALID_CHARS, $char) !== false) {
1417
+                return false;
1418
+            }
1419
+        }
1420
+        return true;
1421
+    }
1422
+
1423
+    /**
1424
+     * Check whether the instance needs to perform an upgrade,
1425
+     * either when the core version is higher or any app requires
1426
+     * an upgrade.
1427
+     *
1428
+     * @param \OC\SystemConfig $config
1429
+     * @return bool whether the core or any app needs an upgrade
1430
+     * @throws \OC\HintException When the upgrade from the given version is not allowed
1431
+     */
1432
+    public static function needUpgrade(\OC\SystemConfig $config) {
1433
+        if ($config->getValue('installed', false)) {
1434
+            $installedVersion = $config->getValue('version', '0.0.0');
1435
+            $currentVersion = implode('.', \OCP\Util::getVersion());
1436
+            $versionDiff = version_compare($currentVersion, $installedVersion);
1437
+            if ($versionDiff > 0) {
1438
+                return true;
1439
+            } elseif ($config->getValue('debug', false) && $versionDiff < 0) {
1440
+                // downgrade with debug
1441
+                $installedMajor = explode('.', $installedVersion);
1442
+                $installedMajor = $installedMajor[0] . '.' . $installedMajor[1];
1443
+                $currentMajor = explode('.', $currentVersion);
1444
+                $currentMajor = $currentMajor[0] . '.' . $currentMajor[1];
1445
+                if ($installedMajor === $currentMajor) {
1446
+                    // Same major, allow downgrade for developers
1447
+                    return true;
1448
+                } else {
1449
+                    // downgrade attempt, throw exception
1450
+                    throw new \OC\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
1451
+                }
1452
+            } elseif ($versionDiff < 0) {
1453
+                // downgrade attempt, throw exception
1454
+                throw new \OC\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
1455
+            }
1456
+
1457
+            // also check for upgrades for apps (independently from the user)
1458
+            $apps = \OC_App::getEnabledApps(false, true);
1459
+            $shouldUpgrade = false;
1460
+            foreach ($apps as $app) {
1461
+                if (\OC_App::shouldUpgrade($app)) {
1462
+                    $shouldUpgrade = true;
1463
+                    break;
1464
+                }
1465
+            }
1466
+            return $shouldUpgrade;
1467
+        } else {
1468
+            return false;
1469
+        }
1470
+    }
1471
+
1472
+    /**
1473
+     * is this Internet explorer ?
1474
+     *
1475
+     * @return boolean
1476
+     */
1477
+    public static function isIe() {
1478
+        if (!isset($_SERVER['HTTP_USER_AGENT'])) {
1479
+            return false;
1480
+        }
1481
+
1482
+        return preg_match(Request::USER_AGENT_IE, $_SERVER['HTTP_USER_AGENT']) === 1;
1483
+    }
1484 1484
 }
Please login to merge, or discard this patch.
lib/private/TemplateLayout.php 1 patch
Indentation   +320 added lines, -320 removed lines patch added patch discarded remove patch
@@ -58,324 +58,324 @@
 block discarded – undo
58 58
 use OCP\Util;
59 59
 
60 60
 class TemplateLayout extends \OC_Template {
61
-	private static $versionHash = '';
62
-
63
-	/** @var IConfig */
64
-	private $config;
65
-
66
-	/** @var IInitialStateService */
67
-	private $initialState;
68
-
69
-	/** @var INavigationManager */
70
-	private $navigationManager;
71
-
72
-	/**
73
-	 * @param string $renderAs
74
-	 * @param string $appId application id
75
-	 */
76
-	public function __construct($renderAs, $appId = '') {
77
-
78
-		/** @var IConfig */
79
-		$this->config = \OC::$server->get(IConfig::class);
80
-
81
-		/** @var IInitialStateService */
82
-		$this->initialState = \OC::$server->get(IInitialStateService::class);
83
-
84
-		if (Util::isIE()) {
85
-			Util::addStyle('ie');
86
-		}
87
-
88
-		// Decide which page we show
89
-		if ($renderAs === TemplateResponse::RENDER_AS_USER) {
90
-			/** @var INavigationManager */
91
-			$this->navigationManager = \OC::$server->get(INavigationManager::class);
92
-
93
-			parent::__construct('core', 'layout.user');
94
-			if (in_array(\OC_App::getCurrentApp(), ['settings','admin', 'help']) !== false) {
95
-				$this->assign('bodyid', 'body-settings');
96
-			} else {
97
-				$this->assign('bodyid', 'body-user');
98
-			}
99
-
100
-			$this->initialState->provideInitialState('core', 'active-app', $this->navigationManager->getActiveEntry());
101
-			$this->initialState->provideInitialState('unified-search', 'limit-default', SearchQuery::LIMIT_DEFAULT);
102
-			Util::addScript('dist/unified-search', null, true);
103
-
104
-			// Add navigation entry
105
-			$this->assign('application', '');
106
-			$this->assign('appid', $appId);
107
-
108
-			$navigation = $this->navigationManager->getAll();
109
-			$this->assign('navigation', $navigation);
110
-			$settingsNavigation = $this->navigationManager->getAll('settings');
111
-			$this->assign('settingsnavigation', $settingsNavigation);
112
-
113
-			foreach ($navigation as $entry) {
114
-				if ($entry['active']) {
115
-					$this->assign('application', $entry['name']);
116
-					break;
117
-				}
118
-			}
119
-
120
-			foreach ($settingsNavigation as $entry) {
121
-				if ($entry['active']) {
122
-					$this->assign('application', $entry['name']);
123
-					break;
124
-				}
125
-			}
126
-			$userDisplayName = \OC_User::getDisplayName();
127
-			$this->assign('user_displayname', $userDisplayName);
128
-			$this->assign('user_uid', \OC_User::getUser());
129
-
130
-			if (\OC_User::getUser() === false) {
131
-				$this->assign('userAvatarSet', false);
132
-			} else {
133
-				$this->assign('userAvatarSet', \OC::$server->getAvatarManager()->getAvatar(\OC_User::getUser())->exists());
134
-				$this->assign('userAvatarVersion', $this->config->getUserValue(\OC_User::getUser(), 'avatar', 'version', 0));
135
-			}
136
-
137
-			// check if app menu icons should be inverted
138
-			try {
139
-				/** @var \OCA\Theming\Util $util */
140
-				$util = \OC::$server->query(\OCA\Theming\Util::class);
141
-				$this->assign('themingInvertMenu', $util->invertTextColor(\OC::$server->getThemingDefaults()->getColorPrimary()));
142
-			} catch (\OCP\AppFramework\QueryException $e) {
143
-				$this->assign('themingInvertMenu', false);
144
-			} catch (\OCP\AutoloadNotAllowedException $e) {
145
-				$this->assign('themingInvertMenu', false);
146
-			}
147
-		} elseif ($renderAs === TemplateResponse::RENDER_AS_ERROR) {
148
-			parent::__construct('core', 'layout.guest', '', false);
149
-			$this->assign('bodyid', 'body-login');
150
-			$this->assign('user_displayname', '');
151
-			$this->assign('user_uid', '');
152
-		} elseif ($renderAs === TemplateResponse::RENDER_AS_GUEST) {
153
-			parent::__construct('core', 'layout.guest');
154
-			\OC_Util::addStyle('guest');
155
-			$this->assign('bodyid', 'body-login');
156
-
157
-			$userDisplayName = \OC_User::getDisplayName();
158
-			$this->assign('user_displayname', $userDisplayName);
159
-			$this->assign('user_uid', \OC_User::getUser());
160
-		} elseif ($renderAs === TemplateResponse::RENDER_AS_PUBLIC) {
161
-			parent::__construct('core', 'layout.public');
162
-			$this->assign('appid', $appId);
163
-			$this->assign('bodyid', 'body-public');
164
-
165
-			/** @var IRegistry $subscription */
166
-			$subscription = \OC::$server->query(IRegistry::class);
167
-			$showSimpleSignup = $this->config->getSystemValueBool('simpleSignUpLink.shown', true);
168
-			if ($showSimpleSignup && $subscription->delegateHasValidSubscription()) {
169
-				$showSimpleSignup = false;
170
-			}
171
-			$this->assign('showSimpleSignUpLink', $showSimpleSignup);
172
-		} else {
173
-			parent::__construct('core', 'layout.base');
174
-		}
175
-		// Send the language and the locale to our layouts
176
-		$lang = \OC::$server->getL10NFactory()->findLanguage();
177
-		$locale = \OC::$server->getL10NFactory()->findLocale($lang);
178
-
179
-		$lang = str_replace('_', '-', $lang);
180
-		$this->assign('language', $lang);
181
-		$this->assign('locale', $locale);
182
-
183
-		if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
184
-			if (empty(self::$versionHash)) {
185
-				$v = \OC_App::getAppVersions();
186
-				$v['core'] = implode('.', \OCP\Util::getVersion());
187
-				self::$versionHash = substr(md5(implode(',', $v)), 0, 8);
188
-			}
189
-		} else {
190
-			self::$versionHash = md5('not installed');
191
-		}
192
-
193
-		// Add the js files
194
-		$jsFiles = self::findJavascriptFiles(\OC_Util::$scripts);
195
-		$this->assign('jsfiles', []);
196
-		if ($this->config->getSystemValue('installed', false) && $renderAs != TemplateResponse::RENDER_AS_ERROR) {
197
-			if (\OC::$server->getContentSecurityPolicyNonceManager()->browserSupportsCspV3()) {
198
-				$jsConfigHelper = new JSConfigHelper(
199
-					\OC::$server->getL10N('lib'),
200
-					\OC::$server->query(Defaults::class),
201
-					\OC::$server->getAppManager(),
202
-					\OC::$server->getSession(),
203
-					\OC::$server->getUserSession()->getUser(),
204
-					$this->config,
205
-					\OC::$server->getGroupManager(),
206
-					\OC::$server->get(IniGetWrapper::class),
207
-					\OC::$server->getURLGenerator(),
208
-					\OC::$server->getCapabilitiesManager(),
209
-					\OC::$server->query(IInitialStateService::class)
210
-				);
211
-				$this->assign('inline_ocjs', $jsConfigHelper->getConfig());
212
-			} else {
213
-				$this->append('jsfiles', \OC::$server->getURLGenerator()->linkToRoute('core.OCJS.getConfig', ['v' => self::$versionHash]));
214
-			}
215
-		}
216
-		foreach ($jsFiles as $info) {
217
-			$web = $info[1];
218
-			$file = $info[2];
219
-			$this->append('jsfiles', $web.'/'.$file . $this->getVersionHashSuffix());
220
-		}
221
-
222
-		try {
223
-			$pathInfo = \OC::$server->getRequest()->getPathInfo();
224
-		} catch (\Exception $e) {
225
-			$pathInfo = '';
226
-		}
227
-
228
-		// Do not initialise scss appdata until we have a fully installed instance
229
-		// Do not load scss for update, errors, installation or login page
230
-		if (\OC::$server->getSystemConfig()->getValue('installed', false)
231
-			&& !\OCP\Util::needUpgrade()
232
-			&& $pathInfo !== ''
233
-			&& !preg_match('/^\/login/', $pathInfo)
234
-			&& $renderAs !== TemplateResponse::RENDER_AS_ERROR
235
-		) {
236
-			$cssFiles = self::findStylesheetFiles(\OC_Util::$styles);
237
-		} else {
238
-			// If we ignore the scss compiler,
239
-			// we need to load the guest css fallback
240
-			\OC_Util::addStyle('guest');
241
-			$cssFiles = self::findStylesheetFiles(\OC_Util::$styles, false);
242
-		}
243
-
244
-		$this->assign('cssfiles', []);
245
-		$this->assign('printcssfiles', []);
246
-		$this->assign('versionHash', self::$versionHash);
247
-		foreach ($cssFiles as $info) {
248
-			$web = $info[1];
249
-			$file = $info[2];
250
-
251
-			if (substr($file, -strlen('print.css')) === 'print.css') {
252
-				$this->append('printcssfiles', $web.'/'.$file . $this->getVersionHashSuffix());
253
-			} else {
254
-				$suffix = $this->getVersionHashSuffix($web, $file);
255
-
256
-				if (strpos($file, '?v=') == false) {
257
-					$this->append('cssfiles', $web.'/'.$file . $suffix);
258
-				} else {
259
-					$this->append('cssfiles', $web.'/'.$file . '-' . substr($suffix, 3));
260
-				}
261
-			}
262
-		}
263
-
264
-		$this->assign('initialStates', $this->initialState->getInitialStates());
265
-	}
266
-
267
-	/**
268
-	 * @param string $path
269
-	 * @param string $file
270
-	 * @return string
271
-	 */
272
-	protected function getVersionHashSuffix($path = false, $file = false) {
273
-		if ($this->config->getSystemValue('debug', false)) {
274
-			// allows chrome workspace mapping in debug mode
275
-			return "";
276
-		}
277
-		$themingSuffix = '';
278
-		$v = [];
279
-
280
-		if ($this->config->getSystemValue('installed', false)) {
281
-			if (\OC::$server->getAppManager()->isInstalled('theming')) {
282
-				$themingSuffix = '-' . $this->config->getAppValue('theming', 'cachebuster', '0');
283
-			}
284
-			$v = \OC_App::getAppVersions();
285
-		}
286
-
287
-		// Try the webroot path for a match
288
-		if ($path !== false && $path !== '') {
289
-			$appName = $this->getAppNamefromPath($path);
290
-			if (array_key_exists($appName, $v)) {
291
-				$appVersion = $v[$appName];
292
-				return '?v=' . substr(md5($appVersion), 0, 8) . $themingSuffix;
293
-			}
294
-		}
295
-		// fallback to the file path instead
296
-		if ($file !== false && $file !== '') {
297
-			$appName = $this->getAppNamefromPath($file);
298
-			if (array_key_exists($appName, $v)) {
299
-				$appVersion = $v[$appName];
300
-				return '?v=' . substr(md5($appVersion), 0, 8) . $themingSuffix;
301
-			}
302
-		}
303
-
304
-		return '?v=' . self::$versionHash . $themingSuffix;
305
-	}
306
-
307
-	/**
308
-	 * @param array $styles
309
-	 * @return array
310
-	 */
311
-	public static function findStylesheetFiles($styles, $compileScss = true) {
312
-		// Read the selected theme from the config file
313
-		$theme = \OC_Util::getTheme();
314
-
315
-		if ($compileScss) {
316
-			$SCSSCacher = \OC::$server->query(SCSSCacher::class);
317
-		} else {
318
-			$SCSSCacher = null;
319
-		}
320
-
321
-		$locator = new \OC\Template\CSSResourceLocator(
322
-			\OC::$server->getLogger(),
323
-			$theme,
324
-			[ \OC::$SERVERROOT => \OC::$WEBROOT ],
325
-			[ \OC::$SERVERROOT => \OC::$WEBROOT ],
326
-			$SCSSCacher
327
-		);
328
-		$locator->find($styles);
329
-		return $locator->getResources();
330
-	}
331
-
332
-	/**
333
-	 * @param string $path
334
-	 * @return string|boolean
335
-	 */
336
-	public function getAppNamefromPath($path) {
337
-		if ($path !== '' && is_string($path)) {
338
-			$pathParts = explode('/', $path);
339
-			if ($pathParts[0] === 'css') {
340
-				// This is a scss request
341
-				return $pathParts[1];
342
-			}
343
-			return end($pathParts);
344
-		}
345
-		return false;
346
-	}
347
-
348
-	/**
349
-	 * @param array $scripts
350
-	 * @return array
351
-	 */
352
-	public static function findJavascriptFiles($scripts) {
353
-		// Read the selected theme from the config file
354
-		$theme = \OC_Util::getTheme();
355
-
356
-		$locator = new \OC\Template\JSResourceLocator(
357
-			\OC::$server->getLogger(),
358
-			$theme,
359
-			[ \OC::$SERVERROOT => \OC::$WEBROOT ],
360
-			[ \OC::$SERVERROOT => \OC::$WEBROOT ],
361
-			\OC::$server->query(JSCombiner::class)
362
-			);
363
-		$locator->find($scripts);
364
-		return $locator->getResources();
365
-	}
366
-
367
-	/**
368
-	 * Converts the absolute file path to a relative path from \OC::$SERVERROOT
369
-	 * @param string $filePath Absolute path
370
-	 * @return string Relative path
371
-	 * @throws \Exception If $filePath is not under \OC::$SERVERROOT
372
-	 */
373
-	public static function convertToRelativePath($filePath) {
374
-		$relativePath = explode(\OC::$SERVERROOT, $filePath);
375
-		if (count($relativePath) !== 2) {
376
-			throw new \Exception('$filePath is not under the \OC::$SERVERROOT');
377
-		}
378
-
379
-		return $relativePath[1];
380
-	}
61
+    private static $versionHash = '';
62
+
63
+    /** @var IConfig */
64
+    private $config;
65
+
66
+    /** @var IInitialStateService */
67
+    private $initialState;
68
+
69
+    /** @var INavigationManager */
70
+    private $navigationManager;
71
+
72
+    /**
73
+     * @param string $renderAs
74
+     * @param string $appId application id
75
+     */
76
+    public function __construct($renderAs, $appId = '') {
77
+
78
+        /** @var IConfig */
79
+        $this->config = \OC::$server->get(IConfig::class);
80
+
81
+        /** @var IInitialStateService */
82
+        $this->initialState = \OC::$server->get(IInitialStateService::class);
83
+
84
+        if (Util::isIE()) {
85
+            Util::addStyle('ie');
86
+        }
87
+
88
+        // Decide which page we show
89
+        if ($renderAs === TemplateResponse::RENDER_AS_USER) {
90
+            /** @var INavigationManager */
91
+            $this->navigationManager = \OC::$server->get(INavigationManager::class);
92
+
93
+            parent::__construct('core', 'layout.user');
94
+            if (in_array(\OC_App::getCurrentApp(), ['settings','admin', 'help']) !== false) {
95
+                $this->assign('bodyid', 'body-settings');
96
+            } else {
97
+                $this->assign('bodyid', 'body-user');
98
+            }
99
+
100
+            $this->initialState->provideInitialState('core', 'active-app', $this->navigationManager->getActiveEntry());
101
+            $this->initialState->provideInitialState('unified-search', 'limit-default', SearchQuery::LIMIT_DEFAULT);
102
+            Util::addScript('dist/unified-search', null, true);
103
+
104
+            // Add navigation entry
105
+            $this->assign('application', '');
106
+            $this->assign('appid', $appId);
107
+
108
+            $navigation = $this->navigationManager->getAll();
109
+            $this->assign('navigation', $navigation);
110
+            $settingsNavigation = $this->navigationManager->getAll('settings');
111
+            $this->assign('settingsnavigation', $settingsNavigation);
112
+
113
+            foreach ($navigation as $entry) {
114
+                if ($entry['active']) {
115
+                    $this->assign('application', $entry['name']);
116
+                    break;
117
+                }
118
+            }
119
+
120
+            foreach ($settingsNavigation as $entry) {
121
+                if ($entry['active']) {
122
+                    $this->assign('application', $entry['name']);
123
+                    break;
124
+                }
125
+            }
126
+            $userDisplayName = \OC_User::getDisplayName();
127
+            $this->assign('user_displayname', $userDisplayName);
128
+            $this->assign('user_uid', \OC_User::getUser());
129
+
130
+            if (\OC_User::getUser() === false) {
131
+                $this->assign('userAvatarSet', false);
132
+            } else {
133
+                $this->assign('userAvatarSet', \OC::$server->getAvatarManager()->getAvatar(\OC_User::getUser())->exists());
134
+                $this->assign('userAvatarVersion', $this->config->getUserValue(\OC_User::getUser(), 'avatar', 'version', 0));
135
+            }
136
+
137
+            // check if app menu icons should be inverted
138
+            try {
139
+                /** @var \OCA\Theming\Util $util */
140
+                $util = \OC::$server->query(\OCA\Theming\Util::class);
141
+                $this->assign('themingInvertMenu', $util->invertTextColor(\OC::$server->getThemingDefaults()->getColorPrimary()));
142
+            } catch (\OCP\AppFramework\QueryException $e) {
143
+                $this->assign('themingInvertMenu', false);
144
+            } catch (\OCP\AutoloadNotAllowedException $e) {
145
+                $this->assign('themingInvertMenu', false);
146
+            }
147
+        } elseif ($renderAs === TemplateResponse::RENDER_AS_ERROR) {
148
+            parent::__construct('core', 'layout.guest', '', false);
149
+            $this->assign('bodyid', 'body-login');
150
+            $this->assign('user_displayname', '');
151
+            $this->assign('user_uid', '');
152
+        } elseif ($renderAs === TemplateResponse::RENDER_AS_GUEST) {
153
+            parent::__construct('core', 'layout.guest');
154
+            \OC_Util::addStyle('guest');
155
+            $this->assign('bodyid', 'body-login');
156
+
157
+            $userDisplayName = \OC_User::getDisplayName();
158
+            $this->assign('user_displayname', $userDisplayName);
159
+            $this->assign('user_uid', \OC_User::getUser());
160
+        } elseif ($renderAs === TemplateResponse::RENDER_AS_PUBLIC) {
161
+            parent::__construct('core', 'layout.public');
162
+            $this->assign('appid', $appId);
163
+            $this->assign('bodyid', 'body-public');
164
+
165
+            /** @var IRegistry $subscription */
166
+            $subscription = \OC::$server->query(IRegistry::class);
167
+            $showSimpleSignup = $this->config->getSystemValueBool('simpleSignUpLink.shown', true);
168
+            if ($showSimpleSignup && $subscription->delegateHasValidSubscription()) {
169
+                $showSimpleSignup = false;
170
+            }
171
+            $this->assign('showSimpleSignUpLink', $showSimpleSignup);
172
+        } else {
173
+            parent::__construct('core', 'layout.base');
174
+        }
175
+        // Send the language and the locale to our layouts
176
+        $lang = \OC::$server->getL10NFactory()->findLanguage();
177
+        $locale = \OC::$server->getL10NFactory()->findLocale($lang);
178
+
179
+        $lang = str_replace('_', '-', $lang);
180
+        $this->assign('language', $lang);
181
+        $this->assign('locale', $locale);
182
+
183
+        if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
184
+            if (empty(self::$versionHash)) {
185
+                $v = \OC_App::getAppVersions();
186
+                $v['core'] = implode('.', \OCP\Util::getVersion());
187
+                self::$versionHash = substr(md5(implode(',', $v)), 0, 8);
188
+            }
189
+        } else {
190
+            self::$versionHash = md5('not installed');
191
+        }
192
+
193
+        // Add the js files
194
+        $jsFiles = self::findJavascriptFiles(\OC_Util::$scripts);
195
+        $this->assign('jsfiles', []);
196
+        if ($this->config->getSystemValue('installed', false) && $renderAs != TemplateResponse::RENDER_AS_ERROR) {
197
+            if (\OC::$server->getContentSecurityPolicyNonceManager()->browserSupportsCspV3()) {
198
+                $jsConfigHelper = new JSConfigHelper(
199
+                    \OC::$server->getL10N('lib'),
200
+                    \OC::$server->query(Defaults::class),
201
+                    \OC::$server->getAppManager(),
202
+                    \OC::$server->getSession(),
203
+                    \OC::$server->getUserSession()->getUser(),
204
+                    $this->config,
205
+                    \OC::$server->getGroupManager(),
206
+                    \OC::$server->get(IniGetWrapper::class),
207
+                    \OC::$server->getURLGenerator(),
208
+                    \OC::$server->getCapabilitiesManager(),
209
+                    \OC::$server->query(IInitialStateService::class)
210
+                );
211
+                $this->assign('inline_ocjs', $jsConfigHelper->getConfig());
212
+            } else {
213
+                $this->append('jsfiles', \OC::$server->getURLGenerator()->linkToRoute('core.OCJS.getConfig', ['v' => self::$versionHash]));
214
+            }
215
+        }
216
+        foreach ($jsFiles as $info) {
217
+            $web = $info[1];
218
+            $file = $info[2];
219
+            $this->append('jsfiles', $web.'/'.$file . $this->getVersionHashSuffix());
220
+        }
221
+
222
+        try {
223
+            $pathInfo = \OC::$server->getRequest()->getPathInfo();
224
+        } catch (\Exception $e) {
225
+            $pathInfo = '';
226
+        }
227
+
228
+        // Do not initialise scss appdata until we have a fully installed instance
229
+        // Do not load scss for update, errors, installation or login page
230
+        if (\OC::$server->getSystemConfig()->getValue('installed', false)
231
+            && !\OCP\Util::needUpgrade()
232
+            && $pathInfo !== ''
233
+            && !preg_match('/^\/login/', $pathInfo)
234
+            && $renderAs !== TemplateResponse::RENDER_AS_ERROR
235
+        ) {
236
+            $cssFiles = self::findStylesheetFiles(\OC_Util::$styles);
237
+        } else {
238
+            // If we ignore the scss compiler,
239
+            // we need to load the guest css fallback
240
+            \OC_Util::addStyle('guest');
241
+            $cssFiles = self::findStylesheetFiles(\OC_Util::$styles, false);
242
+        }
243
+
244
+        $this->assign('cssfiles', []);
245
+        $this->assign('printcssfiles', []);
246
+        $this->assign('versionHash', self::$versionHash);
247
+        foreach ($cssFiles as $info) {
248
+            $web = $info[1];
249
+            $file = $info[2];
250
+
251
+            if (substr($file, -strlen('print.css')) === 'print.css') {
252
+                $this->append('printcssfiles', $web.'/'.$file . $this->getVersionHashSuffix());
253
+            } else {
254
+                $suffix = $this->getVersionHashSuffix($web, $file);
255
+
256
+                if (strpos($file, '?v=') == false) {
257
+                    $this->append('cssfiles', $web.'/'.$file . $suffix);
258
+                } else {
259
+                    $this->append('cssfiles', $web.'/'.$file . '-' . substr($suffix, 3));
260
+                }
261
+            }
262
+        }
263
+
264
+        $this->assign('initialStates', $this->initialState->getInitialStates());
265
+    }
266
+
267
+    /**
268
+     * @param string $path
269
+     * @param string $file
270
+     * @return string
271
+     */
272
+    protected function getVersionHashSuffix($path = false, $file = false) {
273
+        if ($this->config->getSystemValue('debug', false)) {
274
+            // allows chrome workspace mapping in debug mode
275
+            return "";
276
+        }
277
+        $themingSuffix = '';
278
+        $v = [];
279
+
280
+        if ($this->config->getSystemValue('installed', false)) {
281
+            if (\OC::$server->getAppManager()->isInstalled('theming')) {
282
+                $themingSuffix = '-' . $this->config->getAppValue('theming', 'cachebuster', '0');
283
+            }
284
+            $v = \OC_App::getAppVersions();
285
+        }
286
+
287
+        // Try the webroot path for a match
288
+        if ($path !== false && $path !== '') {
289
+            $appName = $this->getAppNamefromPath($path);
290
+            if (array_key_exists($appName, $v)) {
291
+                $appVersion = $v[$appName];
292
+                return '?v=' . substr(md5($appVersion), 0, 8) . $themingSuffix;
293
+            }
294
+        }
295
+        // fallback to the file path instead
296
+        if ($file !== false && $file !== '') {
297
+            $appName = $this->getAppNamefromPath($file);
298
+            if (array_key_exists($appName, $v)) {
299
+                $appVersion = $v[$appName];
300
+                return '?v=' . substr(md5($appVersion), 0, 8) . $themingSuffix;
301
+            }
302
+        }
303
+
304
+        return '?v=' . self::$versionHash . $themingSuffix;
305
+    }
306
+
307
+    /**
308
+     * @param array $styles
309
+     * @return array
310
+     */
311
+    public static function findStylesheetFiles($styles, $compileScss = true) {
312
+        // Read the selected theme from the config file
313
+        $theme = \OC_Util::getTheme();
314
+
315
+        if ($compileScss) {
316
+            $SCSSCacher = \OC::$server->query(SCSSCacher::class);
317
+        } else {
318
+            $SCSSCacher = null;
319
+        }
320
+
321
+        $locator = new \OC\Template\CSSResourceLocator(
322
+            \OC::$server->getLogger(),
323
+            $theme,
324
+            [ \OC::$SERVERROOT => \OC::$WEBROOT ],
325
+            [ \OC::$SERVERROOT => \OC::$WEBROOT ],
326
+            $SCSSCacher
327
+        );
328
+        $locator->find($styles);
329
+        return $locator->getResources();
330
+    }
331
+
332
+    /**
333
+     * @param string $path
334
+     * @return string|boolean
335
+     */
336
+    public function getAppNamefromPath($path) {
337
+        if ($path !== '' && is_string($path)) {
338
+            $pathParts = explode('/', $path);
339
+            if ($pathParts[0] === 'css') {
340
+                // This is a scss request
341
+                return $pathParts[1];
342
+            }
343
+            return end($pathParts);
344
+        }
345
+        return false;
346
+    }
347
+
348
+    /**
349
+     * @param array $scripts
350
+     * @return array
351
+     */
352
+    public static function findJavascriptFiles($scripts) {
353
+        // Read the selected theme from the config file
354
+        $theme = \OC_Util::getTheme();
355
+
356
+        $locator = new \OC\Template\JSResourceLocator(
357
+            \OC::$server->getLogger(),
358
+            $theme,
359
+            [ \OC::$SERVERROOT => \OC::$WEBROOT ],
360
+            [ \OC::$SERVERROOT => \OC::$WEBROOT ],
361
+            \OC::$server->query(JSCombiner::class)
362
+            );
363
+        $locator->find($scripts);
364
+        return $locator->getResources();
365
+    }
366
+
367
+    /**
368
+     * Converts the absolute file path to a relative path from \OC::$SERVERROOT
369
+     * @param string $filePath Absolute path
370
+     * @return string Relative path
371
+     * @throws \Exception If $filePath is not under \OC::$SERVERROOT
372
+     */
373
+    public static function convertToRelativePath($filePath) {
374
+        $relativePath = explode(\OC::$SERVERROOT, $filePath);
375
+        if (count($relativePath) !== 2) {
376
+            throw new \Exception('$filePath is not under the \OC::$SERVERROOT');
377
+        }
378
+
379
+        return $relativePath[1];
380
+    }
381 381
 }
Please login to merge, or discard this patch.
lib/private/Memcache/APCu.php 1 patch
Indentation   +125 added lines, -125 removed lines patch added patch discarded remove patch
@@ -32,140 +32,140 @@
 block discarded – undo
32 32
 use OCP\IMemcache;
33 33
 
34 34
 class APCu extends Cache implements IMemcache {
35
-	use CASTrait {
36
-		cas as casEmulated;
37
-	}
35
+    use CASTrait {
36
+        cas as casEmulated;
37
+    }
38 38
 
39
-	use CADTrait;
39
+    use CADTrait;
40 40
 
41
-	public function get($key) {
42
-		$result = apcu_fetch($this->getPrefix() . $key, $success);
43
-		if (!$success) {
44
-			return null;
45
-		}
46
-		return $result;
47
-	}
41
+    public function get($key) {
42
+        $result = apcu_fetch($this->getPrefix() . $key, $success);
43
+        if (!$success) {
44
+            return null;
45
+        }
46
+        return $result;
47
+    }
48 48
 
49
-	public function set($key, $value, $ttl = 0) {
50
-		return apcu_store($this->getPrefix() . $key, $value, $ttl);
51
-	}
49
+    public function set($key, $value, $ttl = 0) {
50
+        return apcu_store($this->getPrefix() . $key, $value, $ttl);
51
+    }
52 52
 
53
-	public function hasKey($key) {
54
-		return apcu_exists($this->getPrefix() . $key);
55
-	}
53
+    public function hasKey($key) {
54
+        return apcu_exists($this->getPrefix() . $key);
55
+    }
56 56
 
57
-	public function remove($key) {
58
-		return apcu_delete($this->getPrefix() . $key);
59
-	}
57
+    public function remove($key) {
58
+        return apcu_delete($this->getPrefix() . $key);
59
+    }
60 60
 
61
-	public function clear($prefix = '') {
62
-		$ns = $this->getPrefix() . $prefix;
63
-		$ns = preg_quote($ns, '/');
64
-		if (class_exists('\APCIterator')) {
65
-			$iter = new \APCIterator('user', '/^' . $ns . '/', APC_ITER_KEY);
66
-		} else {
67
-			$iter = new \APCUIterator('/^' . $ns . '/', APC_ITER_KEY);
68
-		}
69
-		return apcu_delete($iter);
70
-	}
61
+    public function clear($prefix = '') {
62
+        $ns = $this->getPrefix() . $prefix;
63
+        $ns = preg_quote($ns, '/');
64
+        if (class_exists('\APCIterator')) {
65
+            $iter = new \APCIterator('user', '/^' . $ns . '/', APC_ITER_KEY);
66
+        } else {
67
+            $iter = new \APCUIterator('/^' . $ns . '/', APC_ITER_KEY);
68
+        }
69
+        return apcu_delete($iter);
70
+    }
71 71
 
72
-	/**
73
-	 * Set a value in the cache if it's not already stored
74
-	 *
75
-	 * @param string $key
76
-	 * @param mixed $value
77
-	 * @param int $ttl Time To Live in seconds. Defaults to 60*60*24
78
-	 * @return bool
79
-	 */
80
-	public function add($key, $value, $ttl = 0) {
81
-		return apcu_add($this->getPrefix() . $key, $value, $ttl);
82
-	}
72
+    /**
73
+     * Set a value in the cache if it's not already stored
74
+     *
75
+     * @param string $key
76
+     * @param mixed $value
77
+     * @param int $ttl Time To Live in seconds. Defaults to 60*60*24
78
+     * @return bool
79
+     */
80
+    public function add($key, $value, $ttl = 0) {
81
+        return apcu_add($this->getPrefix() . $key, $value, $ttl);
82
+    }
83 83
 
84
-	/**
85
-	 * Increase a stored number
86
-	 *
87
-	 * @param string $key
88
-	 * @param int $step
89
-	 * @return int | bool
90
-	 */
91
-	public function inc($key, $step = 1) {
92
-		$this->add($key, 0);
93
-		/**
94
-		 * TODO - hack around a PHP 7 specific issue in APCu
95
-		 *
96
-		 * on PHP 7 the apcu_inc method on a non-existing object will increment
97
-		 * "0" and result in "1" as value - therefore we check for existence
98
-		 * first
99
-		 *
100
-		 * on PHP 5.6 this is not the case
101
-		 *
102
-		 * see https://github.com/krakjoe/apcu/issues/183#issuecomment-244038221
103
-		 * for details
104
-		 */
105
-		return apcu_exists($this->getPrefix() . $key)
106
-			? apcu_inc($this->getPrefix() . $key, $step)
107
-			: false;
108
-	}
84
+    /**
85
+     * Increase a stored number
86
+     *
87
+     * @param string $key
88
+     * @param int $step
89
+     * @return int | bool
90
+     */
91
+    public function inc($key, $step = 1) {
92
+        $this->add($key, 0);
93
+        /**
94
+         * TODO - hack around a PHP 7 specific issue in APCu
95
+         *
96
+         * on PHP 7 the apcu_inc method on a non-existing object will increment
97
+         * "0" and result in "1" as value - therefore we check for existence
98
+         * first
99
+         *
100
+         * on PHP 5.6 this is not the case
101
+         *
102
+         * see https://github.com/krakjoe/apcu/issues/183#issuecomment-244038221
103
+         * for details
104
+         */
105
+        return apcu_exists($this->getPrefix() . $key)
106
+            ? apcu_inc($this->getPrefix() . $key, $step)
107
+            : false;
108
+    }
109 109
 
110
-	/**
111
-	 * Decrease a stored number
112
-	 *
113
-	 * @param string $key
114
-	 * @param int $step
115
-	 * @return int | bool
116
-	 */
117
-	public function dec($key, $step = 1) {
118
-		/**
119
-		 * TODO - hack around a PHP 7 specific issue in APCu
120
-		 *
121
-		 * on PHP 7 the apcu_dec method on a non-existing object will decrement
122
-		 * "0" and result in "-1" as value - therefore we check for existence
123
-		 * first
124
-		 *
125
-		 * on PHP 5.6 this is not the case
126
-		 *
127
-		 * see https://github.com/krakjoe/apcu/issues/183#issuecomment-244038221
128
-		 * for details
129
-		 */
130
-		return apcu_exists($this->getPrefix() . $key)
131
-			? apcu_dec($this->getPrefix() . $key, $step)
132
-			: false;
133
-	}
110
+    /**
111
+     * Decrease a stored number
112
+     *
113
+     * @param string $key
114
+     * @param int $step
115
+     * @return int | bool
116
+     */
117
+    public function dec($key, $step = 1) {
118
+        /**
119
+         * TODO - hack around a PHP 7 specific issue in APCu
120
+         *
121
+         * on PHP 7 the apcu_dec method on a non-existing object will decrement
122
+         * "0" and result in "-1" as value - therefore we check for existence
123
+         * first
124
+         *
125
+         * on PHP 5.6 this is not the case
126
+         *
127
+         * see https://github.com/krakjoe/apcu/issues/183#issuecomment-244038221
128
+         * for details
129
+         */
130
+        return apcu_exists($this->getPrefix() . $key)
131
+            ? apcu_dec($this->getPrefix() . $key, $step)
132
+            : false;
133
+    }
134 134
 
135
-	/**
136
-	 * Compare and set
137
-	 *
138
-	 * @param string $key
139
-	 * @param mixed $old
140
-	 * @param mixed $new
141
-	 * @return bool
142
-	 */
143
-	public function cas($key, $old, $new) {
144
-		// apc only does cas for ints
145
-		if (is_int($old) and is_int($new)) {
146
-			return apcu_cas($this->getPrefix() . $key, $old, $new);
147
-		} else {
148
-			return $this->casEmulated($key, $old, $new);
149
-		}
150
-	}
135
+    /**
136
+     * Compare and set
137
+     *
138
+     * @param string $key
139
+     * @param mixed $old
140
+     * @param mixed $new
141
+     * @return bool
142
+     */
143
+    public function cas($key, $old, $new) {
144
+        // apc only does cas for ints
145
+        if (is_int($old) and is_int($new)) {
146
+            return apcu_cas($this->getPrefix() . $key, $old, $new);
147
+        } else {
148
+            return $this->casEmulated($key, $old, $new);
149
+        }
150
+    }
151 151
 
152
-	/**
153
-	 * @return bool
154
-	 */
155
-	public static function isAvailable() {
156
-		if (!extension_loaded('apcu')) {
157
-			return false;
158
-		} elseif (!\OC::$server->get(IniGetWrapper::class)->getBool('apc.enabled')) {
159
-			return false;
160
-		} elseif (!\OC::$server->get(IniGetWrapper::class)->getBool('apc.enable_cli') && \OC::$CLI) {
161
-			return false;
162
-		} elseif (
163
-				version_compare(phpversion('apc') ?: '0.0.0', '4.0.6') === -1 &&
164
-				version_compare(phpversion('apcu') ?: '0.0.0', '5.1.0') === -1
165
-		) {
166
-			return false;
167
-		} else {
168
-			return true;
169
-		}
170
-	}
152
+    /**
153
+     * @return bool
154
+     */
155
+    public static function isAvailable() {
156
+        if (!extension_loaded('apcu')) {
157
+            return false;
158
+        } elseif (!\OC::$server->get(IniGetWrapper::class)->getBool('apc.enabled')) {
159
+            return false;
160
+        } elseif (!\OC::$server->get(IniGetWrapper::class)->getBool('apc.enable_cli') && \OC::$CLI) {
161
+            return false;
162
+        } elseif (
163
+                version_compare(phpversion('apc') ?: '0.0.0', '4.0.6') === -1 &&
164
+                version_compare(phpversion('apcu') ?: '0.0.0', '5.1.0') === -1
165
+        ) {
166
+            return false;
167
+        } else {
168
+            return true;
169
+        }
170
+    }
171 171
 }
Please login to merge, or discard this patch.
lib/private/Setup.php 1 patch
Indentation   +546 added lines, -546 removed lines patch added patch discarded remove patch
@@ -63,550 +63,550 @@
 block discarded – undo
63 63
 use OCP\Security\ISecureRandom;
64 64
 
65 65
 class Setup {
66
-	/** @var SystemConfig */
67
-	protected $config;
68
-	/** @var IniGetWrapper */
69
-	protected $iniWrapper;
70
-	/** @var IL10N */
71
-	protected $l10n;
72
-	/** @var Defaults */
73
-	protected $defaults;
74
-	/** @var ILogger */
75
-	protected $logger;
76
-	/** @var ISecureRandom */
77
-	protected $random;
78
-	/** @var Installer */
79
-	protected $installer;
80
-
81
-	/**
82
-	 * @param SystemConfig $config
83
-	 * @param IniGetWrapper $iniWrapper
84
-	 * @param IL10N $l10n
85
-	 * @param Defaults $defaults
86
-	 * @param ILogger $logger
87
-	 * @param ISecureRandom $random
88
-	 * @param Installer $installer
89
-	 */
90
-	public function __construct(
91
-		SystemConfig $config,
92
-		IniGetWrapper $iniWrapper,
93
-		IL10N $l10n,
94
-		Defaults $defaults,
95
-		ILogger $logger,
96
-		ISecureRandom $random,
97
-		Installer $installer
98
-	) {
99
-		$this->config = $config;
100
-		$this->iniWrapper = $iniWrapper;
101
-		$this->l10n = $l10n;
102
-		$this->defaults = $defaults;
103
-		$this->logger = $logger;
104
-		$this->random = $random;
105
-		$this->installer = $installer;
106
-	}
107
-
108
-	protected static $dbSetupClasses = [
109
-		'mysql' => \OC\Setup\MySQL::class,
110
-		'pgsql' => \OC\Setup\PostgreSQL::class,
111
-		'oci' => \OC\Setup\OCI::class,
112
-		'sqlite' => \OC\Setup\Sqlite::class,
113
-		'sqlite3' => \OC\Setup\Sqlite::class,
114
-	];
115
-
116
-	/**
117
-	 * Wrapper around the "class_exists" PHP function to be able to mock it
118
-	 *
119
-	 * @param string $name
120
-	 * @return bool
121
-	 */
122
-	protected function class_exists($name) {
123
-		return class_exists($name);
124
-	}
125
-
126
-	/**
127
-	 * Wrapper around the "is_callable" PHP function to be able to mock it
128
-	 *
129
-	 * @param string $name
130
-	 * @return bool
131
-	 */
132
-	protected function is_callable($name) {
133
-		return is_callable($name);
134
-	}
135
-
136
-	/**
137
-	 * Wrapper around \PDO::getAvailableDrivers
138
-	 *
139
-	 * @return array
140
-	 */
141
-	protected function getAvailableDbDriversForPdo() {
142
-		return \PDO::getAvailableDrivers();
143
-	}
144
-
145
-	/**
146
-	 * Get the available and supported databases of this instance
147
-	 *
148
-	 * @param bool $allowAllDatabases
149
-	 * @return array
150
-	 * @throws Exception
151
-	 */
152
-	public function getSupportedDatabases($allowAllDatabases = false) {
153
-		$availableDatabases = [
154
-			'sqlite' => [
155
-				'type' => 'pdo',
156
-				'call' => 'sqlite',
157
-				'name' => 'SQLite',
158
-			],
159
-			'mysql' => [
160
-				'type' => 'pdo',
161
-				'call' => 'mysql',
162
-				'name' => 'MySQL/MariaDB',
163
-			],
164
-			'pgsql' => [
165
-				'type' => 'pdo',
166
-				'call' => 'pgsql',
167
-				'name' => 'PostgreSQL',
168
-			],
169
-			'oci' => [
170
-				'type' => 'function',
171
-				'call' => 'oci_connect',
172
-				'name' => 'Oracle',
173
-			],
174
-		];
175
-		if ($allowAllDatabases) {
176
-			$configuredDatabases = array_keys($availableDatabases);
177
-		} else {
178
-			$configuredDatabases = $this->config->getValue('supportedDatabases',
179
-				['sqlite', 'mysql', 'pgsql']);
180
-		}
181
-		if (!is_array($configuredDatabases)) {
182
-			throw new Exception('Supported databases are not properly configured.');
183
-		}
184
-
185
-		$supportedDatabases = [];
186
-
187
-		foreach ($configuredDatabases as $database) {
188
-			if (array_key_exists($database, $availableDatabases)) {
189
-				$working = false;
190
-				$type = $availableDatabases[$database]['type'];
191
-				$call = $availableDatabases[$database]['call'];
192
-
193
-				if ($type === 'function') {
194
-					$working = $this->is_callable($call);
195
-				} elseif ($type === 'pdo') {
196
-					$working = in_array($call, $this->getAvailableDbDriversForPdo(), true);
197
-				}
198
-				if ($working) {
199
-					$supportedDatabases[$database] = $availableDatabases[$database]['name'];
200
-				}
201
-			}
202
-		}
203
-
204
-		return $supportedDatabases;
205
-	}
206
-
207
-	/**
208
-	 * Gathers system information like database type and does
209
-	 * a few system checks.
210
-	 *
211
-	 * @return array of system info, including an "errors" value
212
-	 * in case of errors/warnings
213
-	 */
214
-	public function getSystemInfo($allowAllDatabases = false) {
215
-		$databases = $this->getSupportedDatabases($allowAllDatabases);
216
-
217
-		$dataDir = $this->config->getValue('datadirectory', \OC::$SERVERROOT . '/data');
218
-
219
-		$errors = [];
220
-
221
-		// Create data directory to test whether the .htaccess works
222
-		// Notice that this is not necessarily the same data directory as the one
223
-		// that will effectively be used.
224
-		if (!file_exists($dataDir)) {
225
-			@mkdir($dataDir);
226
-		}
227
-		$htAccessWorking = true;
228
-		if (is_dir($dataDir) && is_writable($dataDir)) {
229
-			// Protect data directory here, so we can test if the protection is working
230
-			self::protectDataDirectory();
231
-
232
-			try {
233
-				$util = new \OC_Util();
234
-				$htAccessWorking = $util->isHtaccessWorking(\OC::$server->getConfig());
235
-			} catch (\OC\HintException $e) {
236
-				$errors[] = [
237
-					'error' => $e->getMessage(),
238
-					'hint' => $e->getHint(),
239
-				];
240
-				$htAccessWorking = false;
241
-			}
242
-		}
243
-
244
-		if (\OC_Util::runningOnMac()) {
245
-			$errors[] = [
246
-				'error' => $this->l10n->t(
247
-					'Mac OS X is not supported and %s will not work properly on this platform. ' .
248
-					'Use it at your own risk! ',
249
-					[$this->defaults->getName()]
250
-				),
251
-				'hint' => $this->l10n->t('For the best results, please consider using a GNU/Linux server instead.'),
252
-			];
253
-		}
254
-
255
-		if ($this->iniWrapper->getString('open_basedir') !== '' && PHP_INT_SIZE === 4) {
256
-			$errors[] = [
257
-				'error' => $this->l10n->t(
258
-					'It seems that this %s instance is running on a 32-bit PHP environment and the open_basedir has been configured in php.ini. ' .
259
-					'This will lead to problems with files over 4 GB and is highly discouraged.',
260
-					[$this->defaults->getName()]
261
-				),
262
-				'hint' => $this->l10n->t('Please remove the open_basedir setting within your php.ini or switch to 64-bit PHP.'),
263
-			];
264
-		}
265
-
266
-		return [
267
-			'hasSQLite' => isset($databases['sqlite']),
268
-			'hasMySQL' => isset($databases['mysql']),
269
-			'hasPostgreSQL' => isset($databases['pgsql']),
270
-			'hasOracle' => isset($databases['oci']),
271
-			'databases' => $databases,
272
-			'directory' => $dataDir,
273
-			'htaccessWorking' => $htAccessWorking,
274
-			'errors' => $errors,
275
-		];
276
-	}
277
-
278
-	/**
279
-	 * @param $options
280
-	 * @return array
281
-	 */
282
-	public function install($options) {
283
-		$l = $this->l10n;
284
-
285
-		$error = [];
286
-		$dbType = $options['dbtype'];
287
-
288
-		if (empty($options['adminlogin'])) {
289
-			$error[] = $l->t('Set an admin username.');
290
-		}
291
-		if (empty($options['adminpass'])) {
292
-			$error[] = $l->t('Set an admin password.');
293
-		}
294
-		if (empty($options['directory'])) {
295
-			$options['directory'] = \OC::$SERVERROOT . "/data";
296
-		}
297
-
298
-		if (!isset(self::$dbSetupClasses[$dbType])) {
299
-			$dbType = 'sqlite';
300
-		}
301
-
302
-		$username = htmlspecialchars_decode($options['adminlogin']);
303
-		$password = htmlspecialchars_decode($options['adminpass']);
304
-		$dataDir = htmlspecialchars_decode($options['directory']);
305
-
306
-		$class = self::$dbSetupClasses[$dbType];
307
-		/** @var \OC\Setup\AbstractDatabase $dbSetup */
308
-		$dbSetup = new $class($l, $this->config, $this->logger, $this->random);
309
-		$error = array_merge($error, $dbSetup->validate($options));
310
-
311
-		// validate the data directory
312
-		if ((!is_dir($dataDir) && !mkdir($dataDir)) || !is_writable($dataDir)) {
313
-			$error[] = $l->t("Can't create or write into the data directory %s", [$dataDir]);
314
-		}
315
-
316
-		if (!empty($error)) {
317
-			return $error;
318
-		}
319
-
320
-		$request = \OC::$server->getRequest();
321
-
322
-		//no errors, good
323
-		if (isset($options['trusted_domains'])
324
-			&& is_array($options['trusted_domains'])) {
325
-			$trustedDomains = $options['trusted_domains'];
326
-		} else {
327
-			$trustedDomains = [$request->getInsecureServerHost()];
328
-		}
329
-
330
-		//use sqlite3 when available, otherwise sqlite2 will be used.
331
-		if ($dbType === 'sqlite' && class_exists('SQLite3')) {
332
-			$dbType = 'sqlite3';
333
-		}
334
-
335
-		//generate a random salt that is used to salt the local user passwords
336
-		$salt = $this->random->generate(30);
337
-		// generate a secret
338
-		$secret = $this->random->generate(48);
339
-
340
-		//write the config file
341
-		$newConfigValues = [
342
-			'passwordsalt' => $salt,
343
-			'secret' => $secret,
344
-			'trusted_domains' => $trustedDomains,
345
-			'datadirectory' => $dataDir,
346
-			'dbtype' => $dbType,
347
-			'version' => implode('.', \OCP\Util::getVersion()),
348
-		];
349
-
350
-		if ($this->config->getValue('overwrite.cli.url', null) === null) {
351
-			$newConfigValues['overwrite.cli.url'] = $request->getServerProtocol() . '://' . $request->getInsecureServerHost() . \OC::$WEBROOT;
352
-		}
353
-
354
-		$this->config->setValues($newConfigValues);
355
-
356
-		$dbSetup->initialize($options);
357
-		try {
358
-			$dbSetup->setupDatabase($username);
359
-		} catch (\OC\DatabaseSetupException $e) {
360
-			$error[] = [
361
-				'error' => $e->getMessage(),
362
-				'hint' => $e->getHint(),
363
-			];
364
-			return $error;
365
-		} catch (Exception $e) {
366
-			$error[] = [
367
-				'error' => 'Error while trying to create admin user: ' . $e->getMessage(),
368
-				'hint' => '',
369
-			];
370
-			return $error;
371
-		}
372
-		try {
373
-			// apply necessary migrations
374
-			$dbSetup->runMigrations();
375
-		} catch (Exception $e) {
376
-			$error[] = [
377
-				'error' => 'Error while trying to initialise the database: ' . $e->getMessage(),
378
-				'hint' => '',
379
-			];
380
-			return $error;
381
-		}
382
-
383
-		//create the user and group
384
-		$user = null;
385
-		try {
386
-			$user = \OC::$server->getUserManager()->createUser($username, $password);
387
-			if (!$user) {
388
-				$error[] = "User <$username> could not be created.";
389
-			}
390
-		} catch (Exception $exception) {
391
-			$error[] = $exception->getMessage();
392
-		}
393
-
394
-		if (empty($error)) {
395
-			$config = \OC::$server->getConfig();
396
-			$config->setAppValue('core', 'installedat', microtime(true));
397
-			$config->setAppValue('core', 'lastupdatedat', microtime(true));
398
-			$config->setAppValue('core', 'vendor', $this->getVendor());
399
-
400
-			$group = \OC::$server->getGroupManager()->createGroup('admin');
401
-			if ($group instanceof IGroup) {
402
-				$group->addUser($user);
403
-			}
404
-
405
-			// Install shipped apps and specified app bundles
406
-			Installer::installShippedApps();
407
-			$bundleFetcher = new BundleFetcher(\OC::$server->getL10N('lib'));
408
-			$defaultInstallationBundles = $bundleFetcher->getDefaultInstallationBundle();
409
-			foreach ($defaultInstallationBundles as $bundle) {
410
-				try {
411
-					$this->installer->installAppBundle($bundle);
412
-				} catch (Exception $e) {
413
-				}
414
-			}
415
-
416
-			// create empty file in data dir, so we can later find
417
-			// out that this is indeed an ownCloud data directory
418
-			file_put_contents($config->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data') . '/.ocdata', '');
419
-
420
-			// Update .htaccess files
421
-			self::updateHtaccess();
422
-			self::protectDataDirectory();
423
-
424
-			self::installBackgroundJobs();
425
-
426
-			//and we are done
427
-			$config->setSystemValue('installed', true);
428
-
429
-			// Create a session token for the newly created user
430
-			// The token provider requires a working db, so it's not injected on setup
431
-			/* @var $userSession User\Session */
432
-			$userSession = \OC::$server->getUserSession();
433
-			$defaultTokenProvider = \OC::$server->query(DefaultTokenProvider::class);
434
-			$userSession->setTokenProvider($defaultTokenProvider);
435
-			$userSession->login($username, $password);
436
-			$userSession->createSessionToken($request, $userSession->getUser()->getUID(), $username, $password);
437
-
438
-			$session = $userSession->getSession();
439
-			$session->set('last-password-confirm', \OC::$server->query(ITimeFactory::class)->getTime());
440
-
441
-			// Set email for admin
442
-			if (!empty($options['adminemail'])) {
443
-				$config->setUserValue($user->getUID(), 'settings', 'email', $options['adminemail']);
444
-			}
445
-		}
446
-
447
-		return $error;
448
-	}
449
-
450
-	public static function installBackgroundJobs() {
451
-		$jobList = \OC::$server->getJobList();
452
-		$jobList->add(DefaultTokenCleanupJob::class);
453
-		$jobList->add(Rotate::class);
454
-		$jobList->add(BackgroundCleanupJob::class);
455
-	}
456
-
457
-	/**
458
-	 * @return string Absolute path to htaccess
459
-	 */
460
-	private function pathToHtaccess() {
461
-		return \OC::$SERVERROOT . '/.htaccess';
462
-	}
463
-
464
-	/**
465
-	 * Find webroot from config
466
-	 *
467
-	 * @param SystemConfig $config
468
-	 * @return string
469
-	 * @throws InvalidArgumentException when invalid value for overwrite.cli.url
470
-	 */
471
-	private static function findWebRoot(SystemConfig $config): string {
472
-		// For CLI read the value from overwrite.cli.url
473
-		if (\OC::$CLI) {
474
-			$webRoot = $config->getValue('overwrite.cli.url', '');
475
-			if ($webRoot === '') {
476
-				throw new InvalidArgumentException('overwrite.cli.url is empty');
477
-			}
478
-			if (!filter_var($webRoot, FILTER_VALIDATE_URL)) {
479
-				throw new InvalidArgumentException('invalid value for overwrite.cli.url');
480
-			}
481
-			$webRoot = rtrim(parse_url($webRoot, PHP_URL_PATH), '/');
482
-		} else {
483
-			$webRoot = !empty(\OC::$WEBROOT) ? \OC::$WEBROOT : '/';
484
-		}
485
-
486
-		return $webRoot;
487
-	}
488
-
489
-	/**
490
-	 * Append the correct ErrorDocument path for Apache hosts
491
-	 *
492
-	 * @return bool True when success, False otherwise
493
-	 * @throws \OCP\AppFramework\QueryException
494
-	 */
495
-	public static function updateHtaccess() {
496
-		$config = \OC::$server->getSystemConfig();
497
-
498
-		try {
499
-			$webRoot = self::findWebRoot($config);
500
-		} catch (InvalidArgumentException $e) {
501
-			return false;
502
-		}
503
-
504
-		$setupHelper = new \OC\Setup(
505
-			$config,
506
-			\OC::$server->get(IniGetWrapper::class),
507
-			\OC::$server->getL10N('lib'),
508
-			\OC::$server->query(Defaults::class),
509
-			\OC::$server->getLogger(),
510
-			\OC::$server->getSecureRandom(),
511
-			\OC::$server->query(Installer::class)
512
-		);
513
-
514
-		$htaccessContent = file_get_contents($setupHelper->pathToHtaccess());
515
-		$content = "#### DO NOT CHANGE ANYTHING ABOVE THIS LINE ####\n";
516
-		$htaccessContent = explode($content, $htaccessContent, 2)[0];
517
-
518
-		//custom 403 error page
519
-		$content .= "\nErrorDocument 403 " . $webRoot . '/';
520
-
521
-		//custom 404 error page
522
-		$content .= "\nErrorDocument 404 " . $webRoot . '/';
523
-
524
-		// Add rewrite rules if the RewriteBase is configured
525
-		$rewriteBase = $config->getValue('htaccess.RewriteBase', '');
526
-		if ($rewriteBase !== '') {
527
-			$content .= "\n<IfModule mod_rewrite.c>";
528
-			$content .= "\n  Options -MultiViews";
529
-			$content .= "\n  RewriteRule ^core/js/oc.js$ index.php [PT,E=PATH_INFO:$1]";
530
-			$content .= "\n  RewriteRule ^core/preview.png$ index.php [PT,E=PATH_INFO:$1]";
531
-			$content .= "\n  RewriteCond %{REQUEST_FILENAME} !\\.(css|js|svg|gif|png|html|ttf|woff2?|ico|jpg|jpeg|map|webm|mp4|mp3|ogg|wav)$";
532
-			$content .= "\n  RewriteCond %{REQUEST_FILENAME} !core/img/favicon.ico$";
533
-			$content .= "\n  RewriteCond %{REQUEST_FILENAME} !core/img/manifest.json$";
534
-			$content .= "\n  RewriteCond %{REQUEST_FILENAME} !/remote.php";
535
-			$content .= "\n  RewriteCond %{REQUEST_FILENAME} !/public.php";
536
-			$content .= "\n  RewriteCond %{REQUEST_FILENAME} !/cron.php";
537
-			$content .= "\n  RewriteCond %{REQUEST_FILENAME} !/core/ajax/update.php";
538
-			$content .= "\n  RewriteCond %{REQUEST_FILENAME} !/status.php";
539
-			$content .= "\n  RewriteCond %{REQUEST_FILENAME} !/ocs/v1.php";
540
-			$content .= "\n  RewriteCond %{REQUEST_FILENAME} !/ocs/v2.php";
541
-			$content .= "\n  RewriteCond %{REQUEST_FILENAME} !/robots.txt";
542
-			$content .= "\n  RewriteCond %{REQUEST_FILENAME} !/updater/";
543
-			$content .= "\n  RewriteCond %{REQUEST_FILENAME} !/ocs-provider/";
544
-			$content .= "\n  RewriteCond %{REQUEST_FILENAME} !/ocm-provider/";
545
-			$content .= "\n  RewriteCond %{REQUEST_URI} !^/\\.well-known/(acme-challenge|pki-validation)/.*";
546
-			$content .= "\n  RewriteCond %{REQUEST_FILENAME} !/richdocumentscode/proxy.php$";
547
-			$content .= "\n  RewriteRule . index.php [PT,E=PATH_INFO:$1]";
548
-			$content .= "\n  RewriteBase " . $rewriteBase;
549
-			$content .= "\n  <IfModule mod_env.c>";
550
-			$content .= "\n    SetEnv front_controller_active true";
551
-			$content .= "\n    <IfModule mod_dir.c>";
552
-			$content .= "\n      DirectorySlash off";
553
-			$content .= "\n    </IfModule>";
554
-			$content .= "\n  </IfModule>";
555
-			$content .= "\n</IfModule>";
556
-		}
557
-
558
-		if ($content !== '') {
559
-			//suppress errors in case we don't have permissions for it
560
-			return (bool)@file_put_contents($setupHelper->pathToHtaccess(), $htaccessContent . $content . "\n");
561
-		}
562
-
563
-		return false;
564
-	}
565
-
566
-	public static function protectDataDirectory() {
567
-		//Require all denied
568
-		$now = date('Y-m-d H:i:s');
569
-		$content = "# Generated by Nextcloud on $now\n";
570
-		$content .= "# Section for Apache 2.4 to 2.6\n";
571
-		$content .= "<IfModule mod_authz_core.c>\n";
572
-		$content .= "  Require all denied\n";
573
-		$content .= "</IfModule>\n";
574
-		$content .= "<IfModule mod_access_compat.c>\n";
575
-		$content .= "  Order Allow,Deny\n";
576
-		$content .= "  Deny from all\n";
577
-		$content .= "  Satisfy All\n";
578
-		$content .= "</IfModule>\n\n";
579
-		$content .= "# Section for Apache 2.2\n";
580
-		$content .= "<IfModule !mod_authz_core.c>\n";
581
-		$content .= "  <IfModule !mod_access_compat.c>\n";
582
-		$content .= "    <IfModule mod_authz_host.c>\n";
583
-		$content .= "      Order Allow,Deny\n";
584
-		$content .= "      Deny from all\n";
585
-		$content .= "    </IfModule>\n";
586
-		$content .= "    Satisfy All\n";
587
-		$content .= "  </IfModule>\n";
588
-		$content .= "</IfModule>\n\n";
589
-		$content .= "# Section for Apache 2.2 to 2.6\n";
590
-		$content .= "<IfModule mod_autoindex.c>\n";
591
-		$content .= "  IndexIgnore *\n";
592
-		$content .= "</IfModule>";
593
-
594
-		$baseDir = \OC::$server->getConfig()->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data');
595
-		file_put_contents($baseDir . '/.htaccess', $content);
596
-		file_put_contents($baseDir . '/index.html', '');
597
-	}
598
-
599
-	/**
600
-	 * Return vendor from which this version was published
601
-	 *
602
-	 * @return string Get the vendor
603
-	 *
604
-	 * Copy of \OC\Updater::getVendor()
605
-	 */
606
-	private function getVendor() {
607
-		// this should really be a JSON file
608
-		require \OC::$SERVERROOT . '/version.php';
609
-		/** @var string $vendor */
610
-		return (string)$vendor;
611
-	}
66
+    /** @var SystemConfig */
67
+    protected $config;
68
+    /** @var IniGetWrapper */
69
+    protected $iniWrapper;
70
+    /** @var IL10N */
71
+    protected $l10n;
72
+    /** @var Defaults */
73
+    protected $defaults;
74
+    /** @var ILogger */
75
+    protected $logger;
76
+    /** @var ISecureRandom */
77
+    protected $random;
78
+    /** @var Installer */
79
+    protected $installer;
80
+
81
+    /**
82
+     * @param SystemConfig $config
83
+     * @param IniGetWrapper $iniWrapper
84
+     * @param IL10N $l10n
85
+     * @param Defaults $defaults
86
+     * @param ILogger $logger
87
+     * @param ISecureRandom $random
88
+     * @param Installer $installer
89
+     */
90
+    public function __construct(
91
+        SystemConfig $config,
92
+        IniGetWrapper $iniWrapper,
93
+        IL10N $l10n,
94
+        Defaults $defaults,
95
+        ILogger $logger,
96
+        ISecureRandom $random,
97
+        Installer $installer
98
+    ) {
99
+        $this->config = $config;
100
+        $this->iniWrapper = $iniWrapper;
101
+        $this->l10n = $l10n;
102
+        $this->defaults = $defaults;
103
+        $this->logger = $logger;
104
+        $this->random = $random;
105
+        $this->installer = $installer;
106
+    }
107
+
108
+    protected static $dbSetupClasses = [
109
+        'mysql' => \OC\Setup\MySQL::class,
110
+        'pgsql' => \OC\Setup\PostgreSQL::class,
111
+        'oci' => \OC\Setup\OCI::class,
112
+        'sqlite' => \OC\Setup\Sqlite::class,
113
+        'sqlite3' => \OC\Setup\Sqlite::class,
114
+    ];
115
+
116
+    /**
117
+     * Wrapper around the "class_exists" PHP function to be able to mock it
118
+     *
119
+     * @param string $name
120
+     * @return bool
121
+     */
122
+    protected function class_exists($name) {
123
+        return class_exists($name);
124
+    }
125
+
126
+    /**
127
+     * Wrapper around the "is_callable" PHP function to be able to mock it
128
+     *
129
+     * @param string $name
130
+     * @return bool
131
+     */
132
+    protected function is_callable($name) {
133
+        return is_callable($name);
134
+    }
135
+
136
+    /**
137
+     * Wrapper around \PDO::getAvailableDrivers
138
+     *
139
+     * @return array
140
+     */
141
+    protected function getAvailableDbDriversForPdo() {
142
+        return \PDO::getAvailableDrivers();
143
+    }
144
+
145
+    /**
146
+     * Get the available and supported databases of this instance
147
+     *
148
+     * @param bool $allowAllDatabases
149
+     * @return array
150
+     * @throws Exception
151
+     */
152
+    public function getSupportedDatabases($allowAllDatabases = false) {
153
+        $availableDatabases = [
154
+            'sqlite' => [
155
+                'type' => 'pdo',
156
+                'call' => 'sqlite',
157
+                'name' => 'SQLite',
158
+            ],
159
+            'mysql' => [
160
+                'type' => 'pdo',
161
+                'call' => 'mysql',
162
+                'name' => 'MySQL/MariaDB',
163
+            ],
164
+            'pgsql' => [
165
+                'type' => 'pdo',
166
+                'call' => 'pgsql',
167
+                'name' => 'PostgreSQL',
168
+            ],
169
+            'oci' => [
170
+                'type' => 'function',
171
+                'call' => 'oci_connect',
172
+                'name' => 'Oracle',
173
+            ],
174
+        ];
175
+        if ($allowAllDatabases) {
176
+            $configuredDatabases = array_keys($availableDatabases);
177
+        } else {
178
+            $configuredDatabases = $this->config->getValue('supportedDatabases',
179
+                ['sqlite', 'mysql', 'pgsql']);
180
+        }
181
+        if (!is_array($configuredDatabases)) {
182
+            throw new Exception('Supported databases are not properly configured.');
183
+        }
184
+
185
+        $supportedDatabases = [];
186
+
187
+        foreach ($configuredDatabases as $database) {
188
+            if (array_key_exists($database, $availableDatabases)) {
189
+                $working = false;
190
+                $type = $availableDatabases[$database]['type'];
191
+                $call = $availableDatabases[$database]['call'];
192
+
193
+                if ($type === 'function') {
194
+                    $working = $this->is_callable($call);
195
+                } elseif ($type === 'pdo') {
196
+                    $working = in_array($call, $this->getAvailableDbDriversForPdo(), true);
197
+                }
198
+                if ($working) {
199
+                    $supportedDatabases[$database] = $availableDatabases[$database]['name'];
200
+                }
201
+            }
202
+        }
203
+
204
+        return $supportedDatabases;
205
+    }
206
+
207
+    /**
208
+     * Gathers system information like database type and does
209
+     * a few system checks.
210
+     *
211
+     * @return array of system info, including an "errors" value
212
+     * in case of errors/warnings
213
+     */
214
+    public function getSystemInfo($allowAllDatabases = false) {
215
+        $databases = $this->getSupportedDatabases($allowAllDatabases);
216
+
217
+        $dataDir = $this->config->getValue('datadirectory', \OC::$SERVERROOT . '/data');
218
+
219
+        $errors = [];
220
+
221
+        // Create data directory to test whether the .htaccess works
222
+        // Notice that this is not necessarily the same data directory as the one
223
+        // that will effectively be used.
224
+        if (!file_exists($dataDir)) {
225
+            @mkdir($dataDir);
226
+        }
227
+        $htAccessWorking = true;
228
+        if (is_dir($dataDir) && is_writable($dataDir)) {
229
+            // Protect data directory here, so we can test if the protection is working
230
+            self::protectDataDirectory();
231
+
232
+            try {
233
+                $util = new \OC_Util();
234
+                $htAccessWorking = $util->isHtaccessWorking(\OC::$server->getConfig());
235
+            } catch (\OC\HintException $e) {
236
+                $errors[] = [
237
+                    'error' => $e->getMessage(),
238
+                    'hint' => $e->getHint(),
239
+                ];
240
+                $htAccessWorking = false;
241
+            }
242
+        }
243
+
244
+        if (\OC_Util::runningOnMac()) {
245
+            $errors[] = [
246
+                'error' => $this->l10n->t(
247
+                    'Mac OS X is not supported and %s will not work properly on this platform. ' .
248
+                    'Use it at your own risk! ',
249
+                    [$this->defaults->getName()]
250
+                ),
251
+                'hint' => $this->l10n->t('For the best results, please consider using a GNU/Linux server instead.'),
252
+            ];
253
+        }
254
+
255
+        if ($this->iniWrapper->getString('open_basedir') !== '' && PHP_INT_SIZE === 4) {
256
+            $errors[] = [
257
+                'error' => $this->l10n->t(
258
+                    'It seems that this %s instance is running on a 32-bit PHP environment and the open_basedir has been configured in php.ini. ' .
259
+                    'This will lead to problems with files over 4 GB and is highly discouraged.',
260
+                    [$this->defaults->getName()]
261
+                ),
262
+                'hint' => $this->l10n->t('Please remove the open_basedir setting within your php.ini or switch to 64-bit PHP.'),
263
+            ];
264
+        }
265
+
266
+        return [
267
+            'hasSQLite' => isset($databases['sqlite']),
268
+            'hasMySQL' => isset($databases['mysql']),
269
+            'hasPostgreSQL' => isset($databases['pgsql']),
270
+            'hasOracle' => isset($databases['oci']),
271
+            'databases' => $databases,
272
+            'directory' => $dataDir,
273
+            'htaccessWorking' => $htAccessWorking,
274
+            'errors' => $errors,
275
+        ];
276
+    }
277
+
278
+    /**
279
+     * @param $options
280
+     * @return array
281
+     */
282
+    public function install($options) {
283
+        $l = $this->l10n;
284
+
285
+        $error = [];
286
+        $dbType = $options['dbtype'];
287
+
288
+        if (empty($options['adminlogin'])) {
289
+            $error[] = $l->t('Set an admin username.');
290
+        }
291
+        if (empty($options['adminpass'])) {
292
+            $error[] = $l->t('Set an admin password.');
293
+        }
294
+        if (empty($options['directory'])) {
295
+            $options['directory'] = \OC::$SERVERROOT . "/data";
296
+        }
297
+
298
+        if (!isset(self::$dbSetupClasses[$dbType])) {
299
+            $dbType = 'sqlite';
300
+        }
301
+
302
+        $username = htmlspecialchars_decode($options['adminlogin']);
303
+        $password = htmlspecialchars_decode($options['adminpass']);
304
+        $dataDir = htmlspecialchars_decode($options['directory']);
305
+
306
+        $class = self::$dbSetupClasses[$dbType];
307
+        /** @var \OC\Setup\AbstractDatabase $dbSetup */
308
+        $dbSetup = new $class($l, $this->config, $this->logger, $this->random);
309
+        $error = array_merge($error, $dbSetup->validate($options));
310
+
311
+        // validate the data directory
312
+        if ((!is_dir($dataDir) && !mkdir($dataDir)) || !is_writable($dataDir)) {
313
+            $error[] = $l->t("Can't create or write into the data directory %s", [$dataDir]);
314
+        }
315
+
316
+        if (!empty($error)) {
317
+            return $error;
318
+        }
319
+
320
+        $request = \OC::$server->getRequest();
321
+
322
+        //no errors, good
323
+        if (isset($options['trusted_domains'])
324
+            && is_array($options['trusted_domains'])) {
325
+            $trustedDomains = $options['trusted_domains'];
326
+        } else {
327
+            $trustedDomains = [$request->getInsecureServerHost()];
328
+        }
329
+
330
+        //use sqlite3 when available, otherwise sqlite2 will be used.
331
+        if ($dbType === 'sqlite' && class_exists('SQLite3')) {
332
+            $dbType = 'sqlite3';
333
+        }
334
+
335
+        //generate a random salt that is used to salt the local user passwords
336
+        $salt = $this->random->generate(30);
337
+        // generate a secret
338
+        $secret = $this->random->generate(48);
339
+
340
+        //write the config file
341
+        $newConfigValues = [
342
+            'passwordsalt' => $salt,
343
+            'secret' => $secret,
344
+            'trusted_domains' => $trustedDomains,
345
+            'datadirectory' => $dataDir,
346
+            'dbtype' => $dbType,
347
+            'version' => implode('.', \OCP\Util::getVersion()),
348
+        ];
349
+
350
+        if ($this->config->getValue('overwrite.cli.url', null) === null) {
351
+            $newConfigValues['overwrite.cli.url'] = $request->getServerProtocol() . '://' . $request->getInsecureServerHost() . \OC::$WEBROOT;
352
+        }
353
+
354
+        $this->config->setValues($newConfigValues);
355
+
356
+        $dbSetup->initialize($options);
357
+        try {
358
+            $dbSetup->setupDatabase($username);
359
+        } catch (\OC\DatabaseSetupException $e) {
360
+            $error[] = [
361
+                'error' => $e->getMessage(),
362
+                'hint' => $e->getHint(),
363
+            ];
364
+            return $error;
365
+        } catch (Exception $e) {
366
+            $error[] = [
367
+                'error' => 'Error while trying to create admin user: ' . $e->getMessage(),
368
+                'hint' => '',
369
+            ];
370
+            return $error;
371
+        }
372
+        try {
373
+            // apply necessary migrations
374
+            $dbSetup->runMigrations();
375
+        } catch (Exception $e) {
376
+            $error[] = [
377
+                'error' => 'Error while trying to initialise the database: ' . $e->getMessage(),
378
+                'hint' => '',
379
+            ];
380
+            return $error;
381
+        }
382
+
383
+        //create the user and group
384
+        $user = null;
385
+        try {
386
+            $user = \OC::$server->getUserManager()->createUser($username, $password);
387
+            if (!$user) {
388
+                $error[] = "User <$username> could not be created.";
389
+            }
390
+        } catch (Exception $exception) {
391
+            $error[] = $exception->getMessage();
392
+        }
393
+
394
+        if (empty($error)) {
395
+            $config = \OC::$server->getConfig();
396
+            $config->setAppValue('core', 'installedat', microtime(true));
397
+            $config->setAppValue('core', 'lastupdatedat', microtime(true));
398
+            $config->setAppValue('core', 'vendor', $this->getVendor());
399
+
400
+            $group = \OC::$server->getGroupManager()->createGroup('admin');
401
+            if ($group instanceof IGroup) {
402
+                $group->addUser($user);
403
+            }
404
+
405
+            // Install shipped apps and specified app bundles
406
+            Installer::installShippedApps();
407
+            $bundleFetcher = new BundleFetcher(\OC::$server->getL10N('lib'));
408
+            $defaultInstallationBundles = $bundleFetcher->getDefaultInstallationBundle();
409
+            foreach ($defaultInstallationBundles as $bundle) {
410
+                try {
411
+                    $this->installer->installAppBundle($bundle);
412
+                } catch (Exception $e) {
413
+                }
414
+            }
415
+
416
+            // create empty file in data dir, so we can later find
417
+            // out that this is indeed an ownCloud data directory
418
+            file_put_contents($config->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data') . '/.ocdata', '');
419
+
420
+            // Update .htaccess files
421
+            self::updateHtaccess();
422
+            self::protectDataDirectory();
423
+
424
+            self::installBackgroundJobs();
425
+
426
+            //and we are done
427
+            $config->setSystemValue('installed', true);
428
+
429
+            // Create a session token for the newly created user
430
+            // The token provider requires a working db, so it's not injected on setup
431
+            /* @var $userSession User\Session */
432
+            $userSession = \OC::$server->getUserSession();
433
+            $defaultTokenProvider = \OC::$server->query(DefaultTokenProvider::class);
434
+            $userSession->setTokenProvider($defaultTokenProvider);
435
+            $userSession->login($username, $password);
436
+            $userSession->createSessionToken($request, $userSession->getUser()->getUID(), $username, $password);
437
+
438
+            $session = $userSession->getSession();
439
+            $session->set('last-password-confirm', \OC::$server->query(ITimeFactory::class)->getTime());
440
+
441
+            // Set email for admin
442
+            if (!empty($options['adminemail'])) {
443
+                $config->setUserValue($user->getUID(), 'settings', 'email', $options['adminemail']);
444
+            }
445
+        }
446
+
447
+        return $error;
448
+    }
449
+
450
+    public static function installBackgroundJobs() {
451
+        $jobList = \OC::$server->getJobList();
452
+        $jobList->add(DefaultTokenCleanupJob::class);
453
+        $jobList->add(Rotate::class);
454
+        $jobList->add(BackgroundCleanupJob::class);
455
+    }
456
+
457
+    /**
458
+     * @return string Absolute path to htaccess
459
+     */
460
+    private function pathToHtaccess() {
461
+        return \OC::$SERVERROOT . '/.htaccess';
462
+    }
463
+
464
+    /**
465
+     * Find webroot from config
466
+     *
467
+     * @param SystemConfig $config
468
+     * @return string
469
+     * @throws InvalidArgumentException when invalid value for overwrite.cli.url
470
+     */
471
+    private static function findWebRoot(SystemConfig $config): string {
472
+        // For CLI read the value from overwrite.cli.url
473
+        if (\OC::$CLI) {
474
+            $webRoot = $config->getValue('overwrite.cli.url', '');
475
+            if ($webRoot === '') {
476
+                throw new InvalidArgumentException('overwrite.cli.url is empty');
477
+            }
478
+            if (!filter_var($webRoot, FILTER_VALIDATE_URL)) {
479
+                throw new InvalidArgumentException('invalid value for overwrite.cli.url');
480
+            }
481
+            $webRoot = rtrim(parse_url($webRoot, PHP_URL_PATH), '/');
482
+        } else {
483
+            $webRoot = !empty(\OC::$WEBROOT) ? \OC::$WEBROOT : '/';
484
+        }
485
+
486
+        return $webRoot;
487
+    }
488
+
489
+    /**
490
+     * Append the correct ErrorDocument path for Apache hosts
491
+     *
492
+     * @return bool True when success, False otherwise
493
+     * @throws \OCP\AppFramework\QueryException
494
+     */
495
+    public static function updateHtaccess() {
496
+        $config = \OC::$server->getSystemConfig();
497
+
498
+        try {
499
+            $webRoot = self::findWebRoot($config);
500
+        } catch (InvalidArgumentException $e) {
501
+            return false;
502
+        }
503
+
504
+        $setupHelper = new \OC\Setup(
505
+            $config,
506
+            \OC::$server->get(IniGetWrapper::class),
507
+            \OC::$server->getL10N('lib'),
508
+            \OC::$server->query(Defaults::class),
509
+            \OC::$server->getLogger(),
510
+            \OC::$server->getSecureRandom(),
511
+            \OC::$server->query(Installer::class)
512
+        );
513
+
514
+        $htaccessContent = file_get_contents($setupHelper->pathToHtaccess());
515
+        $content = "#### DO NOT CHANGE ANYTHING ABOVE THIS LINE ####\n";
516
+        $htaccessContent = explode($content, $htaccessContent, 2)[0];
517
+
518
+        //custom 403 error page
519
+        $content .= "\nErrorDocument 403 " . $webRoot . '/';
520
+
521
+        //custom 404 error page
522
+        $content .= "\nErrorDocument 404 " . $webRoot . '/';
523
+
524
+        // Add rewrite rules if the RewriteBase is configured
525
+        $rewriteBase = $config->getValue('htaccess.RewriteBase', '');
526
+        if ($rewriteBase !== '') {
527
+            $content .= "\n<IfModule mod_rewrite.c>";
528
+            $content .= "\n  Options -MultiViews";
529
+            $content .= "\n  RewriteRule ^core/js/oc.js$ index.php [PT,E=PATH_INFO:$1]";
530
+            $content .= "\n  RewriteRule ^core/preview.png$ index.php [PT,E=PATH_INFO:$1]";
531
+            $content .= "\n  RewriteCond %{REQUEST_FILENAME} !\\.(css|js|svg|gif|png|html|ttf|woff2?|ico|jpg|jpeg|map|webm|mp4|mp3|ogg|wav)$";
532
+            $content .= "\n  RewriteCond %{REQUEST_FILENAME} !core/img/favicon.ico$";
533
+            $content .= "\n  RewriteCond %{REQUEST_FILENAME} !core/img/manifest.json$";
534
+            $content .= "\n  RewriteCond %{REQUEST_FILENAME} !/remote.php";
535
+            $content .= "\n  RewriteCond %{REQUEST_FILENAME} !/public.php";
536
+            $content .= "\n  RewriteCond %{REQUEST_FILENAME} !/cron.php";
537
+            $content .= "\n  RewriteCond %{REQUEST_FILENAME} !/core/ajax/update.php";
538
+            $content .= "\n  RewriteCond %{REQUEST_FILENAME} !/status.php";
539
+            $content .= "\n  RewriteCond %{REQUEST_FILENAME} !/ocs/v1.php";
540
+            $content .= "\n  RewriteCond %{REQUEST_FILENAME} !/ocs/v2.php";
541
+            $content .= "\n  RewriteCond %{REQUEST_FILENAME} !/robots.txt";
542
+            $content .= "\n  RewriteCond %{REQUEST_FILENAME} !/updater/";
543
+            $content .= "\n  RewriteCond %{REQUEST_FILENAME} !/ocs-provider/";
544
+            $content .= "\n  RewriteCond %{REQUEST_FILENAME} !/ocm-provider/";
545
+            $content .= "\n  RewriteCond %{REQUEST_URI} !^/\\.well-known/(acme-challenge|pki-validation)/.*";
546
+            $content .= "\n  RewriteCond %{REQUEST_FILENAME} !/richdocumentscode/proxy.php$";
547
+            $content .= "\n  RewriteRule . index.php [PT,E=PATH_INFO:$1]";
548
+            $content .= "\n  RewriteBase " . $rewriteBase;
549
+            $content .= "\n  <IfModule mod_env.c>";
550
+            $content .= "\n    SetEnv front_controller_active true";
551
+            $content .= "\n    <IfModule mod_dir.c>";
552
+            $content .= "\n      DirectorySlash off";
553
+            $content .= "\n    </IfModule>";
554
+            $content .= "\n  </IfModule>";
555
+            $content .= "\n</IfModule>";
556
+        }
557
+
558
+        if ($content !== '') {
559
+            //suppress errors in case we don't have permissions for it
560
+            return (bool)@file_put_contents($setupHelper->pathToHtaccess(), $htaccessContent . $content . "\n");
561
+        }
562
+
563
+        return false;
564
+    }
565
+
566
+    public static function protectDataDirectory() {
567
+        //Require all denied
568
+        $now = date('Y-m-d H:i:s');
569
+        $content = "# Generated by Nextcloud on $now\n";
570
+        $content .= "# Section for Apache 2.4 to 2.6\n";
571
+        $content .= "<IfModule mod_authz_core.c>\n";
572
+        $content .= "  Require all denied\n";
573
+        $content .= "</IfModule>\n";
574
+        $content .= "<IfModule mod_access_compat.c>\n";
575
+        $content .= "  Order Allow,Deny\n";
576
+        $content .= "  Deny from all\n";
577
+        $content .= "  Satisfy All\n";
578
+        $content .= "</IfModule>\n\n";
579
+        $content .= "# Section for Apache 2.2\n";
580
+        $content .= "<IfModule !mod_authz_core.c>\n";
581
+        $content .= "  <IfModule !mod_access_compat.c>\n";
582
+        $content .= "    <IfModule mod_authz_host.c>\n";
583
+        $content .= "      Order Allow,Deny\n";
584
+        $content .= "      Deny from all\n";
585
+        $content .= "    </IfModule>\n";
586
+        $content .= "    Satisfy All\n";
587
+        $content .= "  </IfModule>\n";
588
+        $content .= "</IfModule>\n\n";
589
+        $content .= "# Section for Apache 2.2 to 2.6\n";
590
+        $content .= "<IfModule mod_autoindex.c>\n";
591
+        $content .= "  IndexIgnore *\n";
592
+        $content .= "</IfModule>";
593
+
594
+        $baseDir = \OC::$server->getConfig()->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data');
595
+        file_put_contents($baseDir . '/.htaccess', $content);
596
+        file_put_contents($baseDir . '/index.html', '');
597
+    }
598
+
599
+    /**
600
+     * Return vendor from which this version was published
601
+     *
602
+     * @return string Get the vendor
603
+     *
604
+     * Copy of \OC\Updater::getVendor()
605
+     */
606
+    private function getVendor() {
607
+        // this should really be a JSON file
608
+        require \OC::$SERVERROOT . '/version.php';
609
+        /** @var string $vendor */
610
+        return (string)$vendor;
611
+    }
612 612
 }
Please login to merge, or discard this patch.