Completed
Push — master ( f0d809...8ccb48 )
by Lukas
38:04 queued 19:05
created
lib/private/Server.php 1 patch
Indentation   +1735 added lines, -1735 removed lines patch added patch discarded remove patch
@@ -138,1744 +138,1744 @@
 block discarded – undo
138 138
  * TODO: hookup all manager classes
139 139
  */
140 140
 class Server extends ServerContainer implements IServerContainer {
141
-	/** @var string */
142
-	private $webRoot;
143
-
144
-	/**
145
-	 * @param string $webRoot
146
-	 * @param \OC\Config $config
147
-	 */
148
-	public function __construct($webRoot, \OC\Config $config) {
149
-		parent::__construct();
150
-		$this->webRoot = $webRoot;
151
-
152
-		$this->registerService(\OCP\IServerContainer::class, function (IServerContainer $c) {
153
-			return $c;
154
-		});
155
-
156
-		$this->registerAlias(\OCP\Calendar\IManager::class, \OC\Calendar\Manager::class);
157
-		$this->registerAlias('CalendarManager', \OC\Calendar\Manager::class);
158
-
159
-		$this->registerAlias(\OCP\Contacts\IManager::class, \OC\ContactsManager::class);
160
-		$this->registerAlias('ContactsManager', \OCP\Contacts\IManager::class);
161
-
162
-		$this->registerAlias(IActionFactory::class, ActionFactory::class);
163
-
164
-
165
-		$this->registerService(\OCP\IPreview::class, function (Server $c) {
166
-			return new PreviewManager(
167
-				$c->getConfig(),
168
-				$c->getRootFolder(),
169
-				$c->getAppDataDir('preview'),
170
-				$c->getEventDispatcher(),
171
-				$c->getSession()->get('user_id')
172
-			);
173
-		});
174
-		$this->registerAlias('PreviewManager', \OCP\IPreview::class);
175
-
176
-		$this->registerService(\OC\Preview\Watcher::class, function (Server $c) {
177
-			return new \OC\Preview\Watcher(
178
-				$c->getAppDataDir('preview')
179
-			);
180
-		});
181
-
182
-		$this->registerService('EncryptionManager', function (Server $c) {
183
-			$view = new View();
184
-			$util = new Encryption\Util(
185
-				$view,
186
-				$c->getUserManager(),
187
-				$c->getGroupManager(),
188
-				$c->getConfig()
189
-			);
190
-			return new Encryption\Manager(
191
-				$c->getConfig(),
192
-				$c->getLogger(),
193
-				$c->getL10N('core'),
194
-				new View(),
195
-				$util,
196
-				new ArrayCache()
197
-			);
198
-		});
199
-
200
-		$this->registerService('EncryptionFileHelper', function (Server $c) {
201
-			$util = new Encryption\Util(
202
-				new View(),
203
-				$c->getUserManager(),
204
-				$c->getGroupManager(),
205
-				$c->getConfig()
206
-			);
207
-			return new Encryption\File(
208
-				$util,
209
-				$c->getRootFolder(),
210
-				$c->getShareManager()
211
-			);
212
-		});
213
-
214
-		$this->registerService('EncryptionKeyStorage', function (Server $c) {
215
-			$view = new View();
216
-			$util = new Encryption\Util(
217
-				$view,
218
-				$c->getUserManager(),
219
-				$c->getGroupManager(),
220
-				$c->getConfig()
221
-			);
222
-
223
-			return new Encryption\Keys\Storage($view, $util);
224
-		});
225
-		$this->registerService('TagMapper', function (Server $c) {
226
-			return new TagMapper($c->getDatabaseConnection());
227
-		});
228
-
229
-		$this->registerService(\OCP\ITagManager::class, function (Server $c) {
230
-			$tagMapper = $c->query('TagMapper');
231
-			return new TagManager($tagMapper, $c->getUserSession());
232
-		});
233
-		$this->registerAlias('TagManager', \OCP\ITagManager::class);
234
-
235
-		$this->registerService('SystemTagManagerFactory', function (Server $c) {
236
-			$config = $c->getConfig();
237
-			$factoryClass = $config->getSystemValue('systemtags.managerFactory', '\OC\SystemTag\ManagerFactory');
238
-			/** @var \OC\SystemTag\ManagerFactory $factory */
239
-			$factory = new $factoryClass($this);
240
-			return $factory;
241
-		});
242
-		$this->registerService(\OCP\SystemTag\ISystemTagManager::class, function (Server $c) {
243
-			return $c->query('SystemTagManagerFactory')->getManager();
244
-		});
245
-		$this->registerAlias('SystemTagManager', \OCP\SystemTag\ISystemTagManager::class);
246
-
247
-		$this->registerService(\OCP\SystemTag\ISystemTagObjectMapper::class, function (Server $c) {
248
-			return $c->query('SystemTagManagerFactory')->getObjectMapper();
249
-		});
250
-		$this->registerService('RootFolder', function (Server $c) {
251
-			$manager = \OC\Files\Filesystem::getMountManager(null);
252
-			$view = new View();
253
-			$root = new Root(
254
-				$manager,
255
-				$view,
256
-				null,
257
-				$c->getUserMountCache(),
258
-				$this->getLogger(),
259
-				$this->getUserManager()
260
-			);
261
-			$connector = new HookConnector($root, $view);
262
-			$connector->viewToNode();
263
-
264
-			$previewConnector = new \OC\Preview\WatcherConnector($root, $c->getSystemConfig());
265
-			$previewConnector->connectWatcher();
266
-
267
-			return $root;
268
-		});
269
-		$this->registerAlias('SystemTagObjectMapper', \OCP\SystemTag\ISystemTagObjectMapper::class);
270
-
271
-		$this->registerService(\OCP\Files\IRootFolder::class, function (Server $c) {
272
-			return new LazyRoot(function () use ($c) {
273
-				return $c->query('RootFolder');
274
-			});
275
-		});
276
-		$this->registerAlias('LazyRootFolder', \OCP\Files\IRootFolder::class);
277
-
278
-		$this->registerService(\OCP\IUserManager::class, function (Server $c) {
279
-			$config = $c->getConfig();
280
-			return new \OC\User\Manager($config);
281
-		});
282
-		$this->registerAlias('UserManager', \OCP\IUserManager::class);
283
-
284
-		$this->registerService(\OCP\IGroupManager::class, function (Server $c) {
285
-			$groupManager = new \OC\Group\Manager($this->getUserManager(), $this->getLogger());
286
-			$groupManager->listen('\OC\Group', 'preCreate', function ($gid) {
287
-				\OC_Hook::emit('OC_Group', 'pre_createGroup', array('run' => true, 'gid' => $gid));
288
-			});
289
-			$groupManager->listen('\OC\Group', 'postCreate', function (\OC\Group\Group $gid) {
290
-				\OC_Hook::emit('OC_User', 'post_createGroup', array('gid' => $gid->getGID()));
291
-			});
292
-			$groupManager->listen('\OC\Group', 'preDelete', function (\OC\Group\Group $group) {
293
-				\OC_Hook::emit('OC_Group', 'pre_deleteGroup', array('run' => true, 'gid' => $group->getGID()));
294
-			});
295
-			$groupManager->listen('\OC\Group', 'postDelete', function (\OC\Group\Group $group) {
296
-				\OC_Hook::emit('OC_User', 'post_deleteGroup', array('gid' => $group->getGID()));
297
-			});
298
-			$groupManager->listen('\OC\Group', 'preAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
299
-				\OC_Hook::emit('OC_Group', 'pre_addToGroup', array('run' => true, 'uid' => $user->getUID(), 'gid' => $group->getGID()));
300
-			});
301
-			$groupManager->listen('\OC\Group', 'postAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
302
-				\OC_Hook::emit('OC_Group', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
303
-				//Minimal fix to keep it backward compatible TODO: clean up all the GroupManager hooks
304
-				\OC_Hook::emit('OC_User', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
305
-			});
306
-			return $groupManager;
307
-		});
308
-		$this->registerAlias('GroupManager', \OCP\IGroupManager::class);
309
-
310
-		$this->registerService(Store::class, function (Server $c) {
311
-			$session = $c->getSession();
312
-			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
313
-				$tokenProvider = $c->query('OC\Authentication\Token\IProvider');
314
-			} else {
315
-				$tokenProvider = null;
316
-			}
317
-			$logger = $c->getLogger();
318
-			return new Store($session, $logger, $tokenProvider);
319
-		});
320
-		$this->registerAlias(IStore::class, Store::class);
321
-		$this->registerService('OC\Authentication\Token\DefaultTokenMapper', function (Server $c) {
322
-			$dbConnection = $c->getDatabaseConnection();
323
-			return new Authentication\Token\DefaultTokenMapper($dbConnection);
324
-		});
325
-		$this->registerService('OC\Authentication\Token\DefaultTokenProvider', function (Server $c) {
326
-			$mapper = $c->query('OC\Authentication\Token\DefaultTokenMapper');
327
-			$crypto = $c->getCrypto();
328
-			$config = $c->getConfig();
329
-			$logger = $c->getLogger();
330
-			$timeFactory = new TimeFactory();
331
-			return new \OC\Authentication\Token\DefaultTokenProvider($mapper, $crypto, $config, $logger, $timeFactory);
332
-		});
333
-		$this->registerAlias('OC\Authentication\Token\IProvider', 'OC\Authentication\Token\DefaultTokenProvider');
334
-
335
-		$this->registerService(\OCP\IUserSession::class, function (Server $c) {
336
-			$manager = $c->getUserManager();
337
-			$session = new \OC\Session\Memory('');
338
-			$timeFactory = new TimeFactory();
339
-			// Token providers might require a working database. This code
340
-			// might however be called when ownCloud is not yet setup.
341
-			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
342
-				$defaultTokenProvider = $c->query('OC\Authentication\Token\IProvider');
343
-			} else {
344
-				$defaultTokenProvider = null;
345
-			}
346
-
347
-			$userSession = new \OC\User\Session($manager, $session, $timeFactory, $defaultTokenProvider, $c->getConfig(), $c->getSecureRandom(), $c->getLockdownManager());
348
-			$userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
349
-				\OC_Hook::emit('OC_User', 'pre_createUser', array('run' => true, 'uid' => $uid, 'password' => $password));
350
-			});
351
-			$userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
352
-				/** @var $user \OC\User\User */
353
-				\OC_Hook::emit('OC_User', 'post_createUser', array('uid' => $user->getUID(), 'password' => $password));
354
-			});
355
-			$userSession->listen('\OC\User', 'preDelete', function ($user) {
356
-				/** @var $user \OC\User\User */
357
-				\OC_Hook::emit('OC_User', 'pre_deleteUser', array('run' => true, 'uid' => $user->getUID()));
358
-			});
359
-			$userSession->listen('\OC\User', 'postDelete', function ($user) {
360
-				/** @var $user \OC\User\User */
361
-				\OC_Hook::emit('OC_User', 'post_deleteUser', array('uid' => $user->getUID()));
362
-			});
363
-			$userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
364
-				/** @var $user \OC\User\User */
365
-				\OC_Hook::emit('OC_User', 'pre_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
366
-			});
367
-			$userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
368
-				/** @var $user \OC\User\User */
369
-				\OC_Hook::emit('OC_User', 'post_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
370
-			});
371
-			$userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
372
-				\OC_Hook::emit('OC_User', 'pre_login', array('run' => true, 'uid' => $uid, 'password' => $password));
373
-			});
374
-			$userSession->listen('\OC\User', 'postLogin', function ($user, $password) {
375
-				/** @var $user \OC\User\User */
376
-				\OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
377
-			});
378
-			$userSession->listen('\OC\User', 'postRememberedLogin', function ($user, $password) {
379
-				/** @var $user \OC\User\User */
380
-				\OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
381
-			});
382
-			$userSession->listen('\OC\User', 'logout', function () {
383
-				\OC_Hook::emit('OC_User', 'logout', array());
384
-			});
385
-			$userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value, $oldValue) {
386
-				/** @var $user \OC\User\User */
387
-				\OC_Hook::emit('OC_User', 'changeUser', array('run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value, 'old_value' => $oldValue));
388
-			});
389
-			return $userSession;
390
-		});
391
-		$this->registerAlias('UserSession', \OCP\IUserSession::class);
392
-
393
-		$this->registerService(\OC\Authentication\TwoFactorAuth\Manager::class, function (Server $c) {
394
-			return new \OC\Authentication\TwoFactorAuth\Manager(
395
-				$c->getAppManager(),
396
-				$c->getSession(),
397
-				$c->getConfig(),
398
-				$c->getActivityManager(),
399
-				$c->getLogger(),
400
-				$c->query(\OC\Authentication\Token\IProvider::class),
401
-				$c->query(ITimeFactory::class)
402
-			);
403
-		});
404
-
405
-		$this->registerAlias(\OCP\INavigationManager::class, \OC\NavigationManager::class);
406
-		$this->registerAlias('NavigationManager', \OCP\INavigationManager::class);
407
-
408
-		$this->registerService(\OC\AllConfig::class, function (Server $c) {
409
-			return new \OC\AllConfig(
410
-				$c->getSystemConfig()
411
-			);
412
-		});
413
-		$this->registerAlias('AllConfig', \OC\AllConfig::class);
414
-		$this->registerAlias(\OCP\IConfig::class, \OC\AllConfig::class);
415
-
416
-		$this->registerService('SystemConfig', function ($c) use ($config) {
417
-			return new \OC\SystemConfig($config);
418
-		});
419
-
420
-		$this->registerService(\OC\AppConfig::class, function (Server $c) {
421
-			return new \OC\AppConfig($c->getDatabaseConnection());
422
-		});
423
-		$this->registerAlias('AppConfig', \OC\AppConfig::class);
424
-		$this->registerAlias(\OCP\IAppConfig::class, \OC\AppConfig::class);
425
-
426
-		$this->registerService(\OCP\L10N\IFactory::class, function (Server $c) {
427
-			return new \OC\L10N\Factory(
428
-				$c->getConfig(),
429
-				$c->getRequest(),
430
-				$c->getUserSession(),
431
-				\OC::$SERVERROOT
432
-			);
433
-		});
434
-		$this->registerAlias('L10NFactory', \OCP\L10N\IFactory::class);
435
-
436
-		$this->registerService(\OCP\IURLGenerator::class, function (Server $c) {
437
-			$config = $c->getConfig();
438
-			$cacheFactory = $c->getMemCacheFactory();
439
-			$request = $c->getRequest();
440
-			return new \OC\URLGenerator(
441
-				$config,
442
-				$cacheFactory,
443
-				$request
444
-			);
445
-		});
446
-		$this->registerAlias('URLGenerator', \OCP\IURLGenerator::class);
447
-
448
-		$this->registerService('AppHelper', function ($c) {
449
-			return new \OC\AppHelper();
450
-		});
451
-		$this->registerAlias('AppFetcher', AppFetcher::class);
452
-		$this->registerAlias('CategoryFetcher', CategoryFetcher::class);
453
-
454
-		$this->registerService(\OCP\ICache::class, function ($c) {
455
-			return new Cache\File();
456
-		});
457
-		$this->registerAlias('UserCache', \OCP\ICache::class);
458
-
459
-		$this->registerService(Factory::class, function (Server $c) {
460
-
461
-			$arrayCacheFactory = new \OC\Memcache\Factory('', $c->getLogger(),
462
-				'\\OC\\Memcache\\ArrayCache',
463
-				'\\OC\\Memcache\\ArrayCache',
464
-				'\\OC\\Memcache\\ArrayCache'
465
-			);
466
-			$config = $c->getConfig();
467
-			$request = $c->getRequest();
468
-			$urlGenerator = new URLGenerator($config, $arrayCacheFactory, $request);
469
-
470
-			if ($config->getSystemValue('installed', false) && !(defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
471
-				$v = \OC_App::getAppVersions();
472
-				$v['core'] = implode(',', \OC_Util::getVersion());
473
-				$version = implode(',', $v);
474
-				$instanceId = \OC_Util::getInstanceId();
475
-				$path = \OC::$SERVERROOT;
476
-				$prefix = md5($instanceId . '-' . $version . '-' . $path . '-' . $urlGenerator->getBaseUrl());
477
-				return new \OC\Memcache\Factory($prefix, $c->getLogger(),
478
-					$config->getSystemValue('memcache.local', null),
479
-					$config->getSystemValue('memcache.distributed', null),
480
-					$config->getSystemValue('memcache.locking', null)
481
-				);
482
-			}
483
-			return $arrayCacheFactory;
484
-
485
-		});
486
-		$this->registerAlias('MemCacheFactory', Factory::class);
487
-		$this->registerAlias(ICacheFactory::class, Factory::class);
488
-
489
-		$this->registerService('RedisFactory', function (Server $c) {
490
-			$systemConfig = $c->getSystemConfig();
491
-			return new RedisFactory($systemConfig);
492
-		});
493
-
494
-		$this->registerService(\OCP\Activity\IManager::class, function (Server $c) {
495
-			return new \OC\Activity\Manager(
496
-				$c->getRequest(),
497
-				$c->getUserSession(),
498
-				$c->getConfig(),
499
-				$c->query(IValidator::class)
500
-			);
501
-		});
502
-		$this->registerAlias('ActivityManager', \OCP\Activity\IManager::class);
503
-
504
-		$this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
505
-			return new \OC\Activity\EventMerger(
506
-				$c->getL10N('lib')
507
-			);
508
-		});
509
-		$this->registerAlias(IValidator::class, Validator::class);
510
-
511
-		$this->registerService(\OCP\IAvatarManager::class, function (Server $c) {
512
-			return new AvatarManager(
513
-				$c->getUserManager(),
514
-				$c->getAppDataDir('avatar'),
515
-				$c->getL10N('lib'),
516
-				$c->getLogger(),
517
-				$c->getConfig()
518
-			);
519
-		});
520
-		$this->registerAlias('AvatarManager', \OCP\IAvatarManager::class);
521
-
522
-		$this->registerAlias(\OCP\Support\CrashReport\IRegistry::class, \OC\Support\CrashReport\Registry::class);
523
-
524
-		$this->registerService(\OCP\ILogger::class, function (Server $c) {
525
-			$logType = $c->query('AllConfig')->getSystemValue('log_type', 'file');
526
-			$logger = Log::getLogClass($logType);
527
-			call_user_func(array($logger, 'init'));
528
-			$config = $this->getSystemConfig();
529
-			$registry = $c->query(\OCP\Support\CrashReport\IRegistry::class);
530
-
531
-			return new Log($logger, $config, null, $registry);
532
-		});
533
-		$this->registerAlias('Logger', \OCP\ILogger::class);
534
-
535
-		$this->registerService(\OCP\BackgroundJob\IJobList::class, function (Server $c) {
536
-			$config = $c->getConfig();
537
-			return new \OC\BackgroundJob\JobList(
538
-				$c->getDatabaseConnection(),
539
-				$config,
540
-				new TimeFactory()
541
-			);
542
-		});
543
-		$this->registerAlias('JobList', \OCP\BackgroundJob\IJobList::class);
544
-
545
-		$this->registerService(\OCP\Route\IRouter::class, function (Server $c) {
546
-			$cacheFactory = $c->getMemCacheFactory();
547
-			$logger = $c->getLogger();
548
-			if ($cacheFactory->isAvailableLowLatency()) {
549
-				$router = new \OC\Route\CachingRouter($cacheFactory->createLocal('route'), $logger);
550
-			} else {
551
-				$router = new \OC\Route\Router($logger);
552
-			}
553
-			return $router;
554
-		});
555
-		$this->registerAlias('Router', \OCP\Route\IRouter::class);
556
-
557
-		$this->registerService(\OCP\ISearch::class, function ($c) {
558
-			return new Search();
559
-		});
560
-		$this->registerAlias('Search', \OCP\ISearch::class);
561
-
562
-		$this->registerService(\OC\Security\RateLimiting\Limiter::class, function ($c) {
563
-			return new \OC\Security\RateLimiting\Limiter(
564
-				$this->getUserSession(),
565
-				$this->getRequest(),
566
-				new \OC\AppFramework\Utility\TimeFactory(),
567
-				$c->query(\OC\Security\RateLimiting\Backend\IBackend::class)
568
-			);
569
-		});
570
-		$this->registerService(\OC\Security\RateLimiting\Backend\IBackend::class, function ($c) {
571
-			return new \OC\Security\RateLimiting\Backend\MemoryCache(
572
-				$this->getMemCacheFactory(),
573
-				new \OC\AppFramework\Utility\TimeFactory()
574
-			);
575
-		});
576
-
577
-		$this->registerService(\OCP\Security\ISecureRandom::class, function ($c) {
578
-			return new SecureRandom();
579
-		});
580
-		$this->registerAlias('SecureRandom', \OCP\Security\ISecureRandom::class);
581
-
582
-		$this->registerService(\OCP\Security\ICrypto::class, function (Server $c) {
583
-			return new Crypto($c->getConfig(), $c->getSecureRandom());
584
-		});
585
-		$this->registerAlias('Crypto', \OCP\Security\ICrypto::class);
586
-
587
-		$this->registerService(\OCP\Security\IHasher::class, function (Server $c) {
588
-			return new Hasher($c->getConfig());
589
-		});
590
-		$this->registerAlias('Hasher', \OCP\Security\IHasher::class);
591
-
592
-		$this->registerService(\OCP\Security\ICredentialsManager::class, function (Server $c) {
593
-			return new CredentialsManager($c->getCrypto(), $c->getDatabaseConnection());
594
-		});
595
-		$this->registerAlias('CredentialsManager', \OCP\Security\ICredentialsManager::class);
596
-
597
-		$this->registerService(IDBConnection::class, function (Server $c) {
598
-			$systemConfig = $c->getSystemConfig();
599
-			$factory = new \OC\DB\ConnectionFactory($systemConfig);
600
-			$type = $systemConfig->getValue('dbtype', 'sqlite');
601
-			if (!$factory->isValidType($type)) {
602
-				throw new \OC\DatabaseException('Invalid database type');
603
-			}
604
-			$connectionParams = $factory->createConnectionParams();
605
-			$connection = $factory->getConnection($type, $connectionParams);
606
-			$connection->getConfiguration()->setSQLLogger($c->getQueryLogger());
607
-			return $connection;
608
-		});
609
-		$this->registerAlias('DatabaseConnection', IDBConnection::class);
610
-
611
-		$this->registerService('HTTPHelper', function (Server $c) {
612
-			$config = $c->getConfig();
613
-			return new HTTPHelper(
614
-				$config,
615
-				$c->getHTTPClientService()
616
-			);
617
-		});
618
-
619
-		$this->registerService(\OCP\Http\Client\IClientService::class, function (Server $c) {
620
-			$user = \OC_User::getUser();
621
-			$uid = $user ? $user : null;
622
-			return new ClientService(
623
-				$c->getConfig(),
624
-				new \OC\Security\CertificateManager(
625
-					$uid,
626
-					new View(),
627
-					$c->getConfig(),
628
-					$c->getLogger(),
629
-					$c->getSecureRandom()
630
-				)
631
-			);
632
-		});
633
-		$this->registerAlias('HttpClientService', \OCP\Http\Client\IClientService::class);
634
-		$this->registerService(\OCP\Diagnostics\IEventLogger::class, function (Server $c) {
635
-			$eventLogger = new EventLogger();
636
-			if ($c->getSystemConfig()->getValue('debug', false)) {
637
-				// In debug mode, module is being activated by default
638
-				$eventLogger->activate();
639
-			}
640
-			return $eventLogger;
641
-		});
642
-		$this->registerAlias('EventLogger', \OCP\Diagnostics\IEventLogger::class);
643
-
644
-		$this->registerService(\OCP\Diagnostics\IQueryLogger::class, function (Server $c) {
645
-			$queryLogger = new QueryLogger();
646
-			if ($c->getSystemConfig()->getValue('debug', false)) {
647
-				// In debug mode, module is being activated by default
648
-				$queryLogger->activate();
649
-			}
650
-			return $queryLogger;
651
-		});
652
-		$this->registerAlias('QueryLogger', \OCP\Diagnostics\IQueryLogger::class);
653
-
654
-		$this->registerService(TempManager::class, function (Server $c) {
655
-			return new TempManager(
656
-				$c->getLogger(),
657
-				$c->getConfig()
658
-			);
659
-		});
660
-		$this->registerAlias('TempManager', TempManager::class);
661
-		$this->registerAlias(ITempManager::class, TempManager::class);
662
-
663
-		$this->registerService(AppManager::class, function (Server $c) {
664
-			return new \OC\App\AppManager(
665
-				$c->getUserSession(),
666
-				$c->getAppConfig(),
667
-				$c->getGroupManager(),
668
-				$c->getMemCacheFactory(),
669
-				$c->getEventDispatcher()
670
-			);
671
-		});
672
-		$this->registerAlias('AppManager', AppManager::class);
673
-		$this->registerAlias(IAppManager::class, AppManager::class);
674
-
675
-		$this->registerService(\OCP\IDateTimeZone::class, function (Server $c) {
676
-			return new DateTimeZone(
677
-				$c->getConfig(),
678
-				$c->getSession()
679
-			);
680
-		});
681
-		$this->registerAlias('DateTimeZone', \OCP\IDateTimeZone::class);
682
-
683
-		$this->registerService(\OCP\IDateTimeFormatter::class, function (Server $c) {
684
-			$language = $c->getConfig()->getUserValue($c->getSession()->get('user_id'), 'core', 'lang', null);
685
-
686
-			return new DateTimeFormatter(
687
-				$c->getDateTimeZone()->getTimeZone(),
688
-				$c->getL10N('lib', $language)
689
-			);
690
-		});
691
-		$this->registerAlias('DateTimeFormatter', \OCP\IDateTimeFormatter::class);
692
-
693
-		$this->registerService(\OCP\Files\Config\IUserMountCache::class, function (Server $c) {
694
-			$mountCache = new UserMountCache($c->getDatabaseConnection(), $c->getUserManager(), $c->getLogger());
695
-			$listener = new UserMountCacheListener($mountCache);
696
-			$listener->listen($c->getUserManager());
697
-			return $mountCache;
698
-		});
699
-		$this->registerAlias('UserMountCache', \OCP\Files\Config\IUserMountCache::class);
700
-
701
-		$this->registerService(\OCP\Files\Config\IMountProviderCollection::class, function (Server $c) {
702
-			$loader = \OC\Files\Filesystem::getLoader();
703
-			$mountCache = $c->query('UserMountCache');
704
-			$manager = new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
705
-
706
-			// builtin providers
707
-
708
-			$config = $c->getConfig();
709
-			$manager->registerProvider(new CacheMountProvider($config));
710
-			$manager->registerHomeProvider(new LocalHomeMountProvider());
711
-			$manager->registerHomeProvider(new ObjectHomeMountProvider($config));
712
-
713
-			return $manager;
714
-		});
715
-		$this->registerAlias('MountConfigManager', \OCP\Files\Config\IMountProviderCollection::class);
716
-
717
-		$this->registerService('IniWrapper', function ($c) {
718
-			return new IniGetWrapper();
719
-		});
720
-		$this->registerService('AsyncCommandBus', function (Server $c) {
721
-			$busClass = $c->getConfig()->getSystemValue('commandbus');
722
-			if ($busClass) {
723
-				list($app, $class) = explode('::', $busClass, 2);
724
-				if ($c->getAppManager()->isInstalled($app)) {
725
-					\OC_App::loadApp($app);
726
-					return $c->query($class);
727
-				} else {
728
-					throw new ServiceUnavailableException("The app providing the command bus ($app) is not enabled");
729
-				}
730
-			} else {
731
-				$jobList = $c->getJobList();
732
-				return new CronBus($jobList);
733
-			}
734
-		});
735
-		$this->registerService('TrustedDomainHelper', function ($c) {
736
-			return new TrustedDomainHelper($this->getConfig());
737
-		});
738
-		$this->registerService('Throttler', function (Server $c) {
739
-			return new Throttler(
740
-				$c->getDatabaseConnection(),
741
-				new TimeFactory(),
742
-				$c->getLogger(),
743
-				$c->getConfig()
744
-			);
745
-		});
746
-		$this->registerService('IntegrityCodeChecker', function (Server $c) {
747
-			// IConfig and IAppManager requires a working database. This code
748
-			// might however be called when ownCloud is not yet setup.
749
-			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
750
-				$config = $c->getConfig();
751
-				$appManager = $c->getAppManager();
752
-			} else {
753
-				$config = null;
754
-				$appManager = null;
755
-			}
756
-
757
-			return new Checker(
758
-				new EnvironmentHelper(),
759
-				new FileAccessHelper(),
760
-				new AppLocator(),
761
-				$config,
762
-				$c->getMemCacheFactory(),
763
-				$appManager,
764
-				$c->getTempManager()
765
-			);
766
-		});
767
-		$this->registerService(\OCP\IRequest::class, function ($c) {
768
-			if (isset($this['urlParams'])) {
769
-				$urlParams = $this['urlParams'];
770
-			} else {
771
-				$urlParams = [];
772
-			}
773
-
774
-			if (defined('PHPUNIT_RUN') && PHPUNIT_RUN
775
-				&& in_array('fakeinput', stream_get_wrappers())
776
-			) {
777
-				$stream = 'fakeinput://data';
778
-			} else {
779
-				$stream = 'php://input';
780
-			}
781
-
782
-			return new Request(
783
-				[
784
-					'get' => $_GET,
785
-					'post' => $_POST,
786
-					'files' => $_FILES,
787
-					'server' => $_SERVER,
788
-					'env' => $_ENV,
789
-					'cookies' => $_COOKIE,
790
-					'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
791
-						? $_SERVER['REQUEST_METHOD']
792
-						: null,
793
-					'urlParams' => $urlParams,
794
-				],
795
-				$this->getSecureRandom(),
796
-				$this->getConfig(),
797
-				$this->getCsrfTokenManager(),
798
-				$stream
799
-			);
800
-		});
801
-		$this->registerAlias('Request', \OCP\IRequest::class);
802
-
803
-		$this->registerService(\OCP\Mail\IMailer::class, function (Server $c) {
804
-			return new Mailer(
805
-				$c->getConfig(),
806
-				$c->getLogger(),
807
-				$c->query(Defaults::class),
808
-				$c->getURLGenerator(),
809
-				$c->getL10N('lib')
810
-			);
811
-		});
812
-		$this->registerAlias('Mailer', \OCP\Mail\IMailer::class);
813
-
814
-		$this->registerService('LDAPProvider', function (Server $c) {
815
-			$config = $c->getConfig();
816
-			$factoryClass = $config->getSystemValue('ldapProviderFactory', null);
817
-			if (is_null($factoryClass)) {
818
-				throw new \Exception('ldapProviderFactory not set');
819
-			}
820
-			/** @var \OCP\LDAP\ILDAPProviderFactory $factory */
821
-			$factory = new $factoryClass($this);
822
-			return $factory->getLDAPProvider();
823
-		});
824
-		$this->registerService(ILockingProvider::class, function (Server $c) {
825
-			$ini = $c->getIniWrapper();
826
-			$config = $c->getConfig();
827
-			$ttl = $config->getSystemValue('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
828
-			if ($config->getSystemValue('filelocking.enabled', true) or (defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
829
-				/** @var \OC\Memcache\Factory $memcacheFactory */
830
-				$memcacheFactory = $c->getMemCacheFactory();
831
-				$memcache = $memcacheFactory->createLocking('lock');
832
-				if (!($memcache instanceof \OC\Memcache\NullCache)) {
833
-					return new MemcacheLockingProvider($memcache, $ttl);
834
-				}
835
-				return new DBLockingProvider($c->getDatabaseConnection(), $c->getLogger(), new TimeFactory(), $ttl);
836
-			}
837
-			return new NoopLockingProvider();
838
-		});
839
-		$this->registerAlias('LockingProvider', ILockingProvider::class);
840
-
841
-		$this->registerService(\OCP\Files\Mount\IMountManager::class, function () {
842
-			return new \OC\Files\Mount\Manager();
843
-		});
844
-		$this->registerAlias('MountManager', \OCP\Files\Mount\IMountManager::class);
845
-
846
-		$this->registerService(\OCP\Files\IMimeTypeDetector::class, function (Server $c) {
847
-			return new \OC\Files\Type\Detection(
848
-				$c->getURLGenerator(),
849
-				\OC::$configDir,
850
-				\OC::$SERVERROOT . '/resources/config/'
851
-			);
852
-		});
853
-		$this->registerAlias('MimeTypeDetector', \OCP\Files\IMimeTypeDetector::class);
854
-
855
-		$this->registerService(\OCP\Files\IMimeTypeLoader::class, function (Server $c) {
856
-			return new \OC\Files\Type\Loader(
857
-				$c->getDatabaseConnection()
858
-			);
859
-		});
860
-		$this->registerAlias('MimeTypeLoader', \OCP\Files\IMimeTypeLoader::class);
861
-		$this->registerService(BundleFetcher::class, function () {
862
-			return new BundleFetcher($this->getL10N('lib'));
863
-		});
864
-		$this->registerService(\OCP\Notification\IManager::class, function (Server $c) {
865
-			return new Manager(
866
-				$c->query(IValidator::class)
867
-			);
868
-		});
869
-		$this->registerAlias('NotificationManager', \OCP\Notification\IManager::class);
870
-
871
-		$this->registerService(\OC\CapabilitiesManager::class, function (Server $c) {
872
-			$manager = new \OC\CapabilitiesManager($c->getLogger());
873
-			$manager->registerCapability(function () use ($c) {
874
-				return new \OC\OCS\CoreCapabilities($c->getConfig());
875
-			});
876
-			$manager->registerCapability(function () use ($c) {
877
-				return $c->query(\OC\Security\Bruteforce\Capabilities::class);
878
-			});
879
-			return $manager;
880
-		});
881
-		$this->registerAlias('CapabilitiesManager', \OC\CapabilitiesManager::class);
882
-
883
-		$this->registerService(\OCP\Comments\ICommentsManager::class, function (Server $c) {
884
-			$config = $c->getConfig();
885
-			$factoryClass = $config->getSystemValue('comments.managerFactory', '\OC\Comments\ManagerFactory');
886
-			/** @var \OCP\Comments\ICommentsManagerFactory $factory */
887
-			$factory = new $factoryClass($this);
888
-			return $factory->getManager();
889
-		});
890
-		$this->registerAlias('CommentsManager', \OCP\Comments\ICommentsManager::class);
891
-
892
-		$this->registerService('ThemingDefaults', function (Server $c) {
893
-			/*
141
+    /** @var string */
142
+    private $webRoot;
143
+
144
+    /**
145
+     * @param string $webRoot
146
+     * @param \OC\Config $config
147
+     */
148
+    public function __construct($webRoot, \OC\Config $config) {
149
+        parent::__construct();
150
+        $this->webRoot = $webRoot;
151
+
152
+        $this->registerService(\OCP\IServerContainer::class, function (IServerContainer $c) {
153
+            return $c;
154
+        });
155
+
156
+        $this->registerAlias(\OCP\Calendar\IManager::class, \OC\Calendar\Manager::class);
157
+        $this->registerAlias('CalendarManager', \OC\Calendar\Manager::class);
158
+
159
+        $this->registerAlias(\OCP\Contacts\IManager::class, \OC\ContactsManager::class);
160
+        $this->registerAlias('ContactsManager', \OCP\Contacts\IManager::class);
161
+
162
+        $this->registerAlias(IActionFactory::class, ActionFactory::class);
163
+
164
+
165
+        $this->registerService(\OCP\IPreview::class, function (Server $c) {
166
+            return new PreviewManager(
167
+                $c->getConfig(),
168
+                $c->getRootFolder(),
169
+                $c->getAppDataDir('preview'),
170
+                $c->getEventDispatcher(),
171
+                $c->getSession()->get('user_id')
172
+            );
173
+        });
174
+        $this->registerAlias('PreviewManager', \OCP\IPreview::class);
175
+
176
+        $this->registerService(\OC\Preview\Watcher::class, function (Server $c) {
177
+            return new \OC\Preview\Watcher(
178
+                $c->getAppDataDir('preview')
179
+            );
180
+        });
181
+
182
+        $this->registerService('EncryptionManager', function (Server $c) {
183
+            $view = new View();
184
+            $util = new Encryption\Util(
185
+                $view,
186
+                $c->getUserManager(),
187
+                $c->getGroupManager(),
188
+                $c->getConfig()
189
+            );
190
+            return new Encryption\Manager(
191
+                $c->getConfig(),
192
+                $c->getLogger(),
193
+                $c->getL10N('core'),
194
+                new View(),
195
+                $util,
196
+                new ArrayCache()
197
+            );
198
+        });
199
+
200
+        $this->registerService('EncryptionFileHelper', function (Server $c) {
201
+            $util = new Encryption\Util(
202
+                new View(),
203
+                $c->getUserManager(),
204
+                $c->getGroupManager(),
205
+                $c->getConfig()
206
+            );
207
+            return new Encryption\File(
208
+                $util,
209
+                $c->getRootFolder(),
210
+                $c->getShareManager()
211
+            );
212
+        });
213
+
214
+        $this->registerService('EncryptionKeyStorage', function (Server $c) {
215
+            $view = new View();
216
+            $util = new Encryption\Util(
217
+                $view,
218
+                $c->getUserManager(),
219
+                $c->getGroupManager(),
220
+                $c->getConfig()
221
+            );
222
+
223
+            return new Encryption\Keys\Storage($view, $util);
224
+        });
225
+        $this->registerService('TagMapper', function (Server $c) {
226
+            return new TagMapper($c->getDatabaseConnection());
227
+        });
228
+
229
+        $this->registerService(\OCP\ITagManager::class, function (Server $c) {
230
+            $tagMapper = $c->query('TagMapper');
231
+            return new TagManager($tagMapper, $c->getUserSession());
232
+        });
233
+        $this->registerAlias('TagManager', \OCP\ITagManager::class);
234
+
235
+        $this->registerService('SystemTagManagerFactory', function (Server $c) {
236
+            $config = $c->getConfig();
237
+            $factoryClass = $config->getSystemValue('systemtags.managerFactory', '\OC\SystemTag\ManagerFactory');
238
+            /** @var \OC\SystemTag\ManagerFactory $factory */
239
+            $factory = new $factoryClass($this);
240
+            return $factory;
241
+        });
242
+        $this->registerService(\OCP\SystemTag\ISystemTagManager::class, function (Server $c) {
243
+            return $c->query('SystemTagManagerFactory')->getManager();
244
+        });
245
+        $this->registerAlias('SystemTagManager', \OCP\SystemTag\ISystemTagManager::class);
246
+
247
+        $this->registerService(\OCP\SystemTag\ISystemTagObjectMapper::class, function (Server $c) {
248
+            return $c->query('SystemTagManagerFactory')->getObjectMapper();
249
+        });
250
+        $this->registerService('RootFolder', function (Server $c) {
251
+            $manager = \OC\Files\Filesystem::getMountManager(null);
252
+            $view = new View();
253
+            $root = new Root(
254
+                $manager,
255
+                $view,
256
+                null,
257
+                $c->getUserMountCache(),
258
+                $this->getLogger(),
259
+                $this->getUserManager()
260
+            );
261
+            $connector = new HookConnector($root, $view);
262
+            $connector->viewToNode();
263
+
264
+            $previewConnector = new \OC\Preview\WatcherConnector($root, $c->getSystemConfig());
265
+            $previewConnector->connectWatcher();
266
+
267
+            return $root;
268
+        });
269
+        $this->registerAlias('SystemTagObjectMapper', \OCP\SystemTag\ISystemTagObjectMapper::class);
270
+
271
+        $this->registerService(\OCP\Files\IRootFolder::class, function (Server $c) {
272
+            return new LazyRoot(function () use ($c) {
273
+                return $c->query('RootFolder');
274
+            });
275
+        });
276
+        $this->registerAlias('LazyRootFolder', \OCP\Files\IRootFolder::class);
277
+
278
+        $this->registerService(\OCP\IUserManager::class, function (Server $c) {
279
+            $config = $c->getConfig();
280
+            return new \OC\User\Manager($config);
281
+        });
282
+        $this->registerAlias('UserManager', \OCP\IUserManager::class);
283
+
284
+        $this->registerService(\OCP\IGroupManager::class, function (Server $c) {
285
+            $groupManager = new \OC\Group\Manager($this->getUserManager(), $this->getLogger());
286
+            $groupManager->listen('\OC\Group', 'preCreate', function ($gid) {
287
+                \OC_Hook::emit('OC_Group', 'pre_createGroup', array('run' => true, 'gid' => $gid));
288
+            });
289
+            $groupManager->listen('\OC\Group', 'postCreate', function (\OC\Group\Group $gid) {
290
+                \OC_Hook::emit('OC_User', 'post_createGroup', array('gid' => $gid->getGID()));
291
+            });
292
+            $groupManager->listen('\OC\Group', 'preDelete', function (\OC\Group\Group $group) {
293
+                \OC_Hook::emit('OC_Group', 'pre_deleteGroup', array('run' => true, 'gid' => $group->getGID()));
294
+            });
295
+            $groupManager->listen('\OC\Group', 'postDelete', function (\OC\Group\Group $group) {
296
+                \OC_Hook::emit('OC_User', 'post_deleteGroup', array('gid' => $group->getGID()));
297
+            });
298
+            $groupManager->listen('\OC\Group', 'preAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
299
+                \OC_Hook::emit('OC_Group', 'pre_addToGroup', array('run' => true, 'uid' => $user->getUID(), 'gid' => $group->getGID()));
300
+            });
301
+            $groupManager->listen('\OC\Group', 'postAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
302
+                \OC_Hook::emit('OC_Group', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
303
+                //Minimal fix to keep it backward compatible TODO: clean up all the GroupManager hooks
304
+                \OC_Hook::emit('OC_User', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
305
+            });
306
+            return $groupManager;
307
+        });
308
+        $this->registerAlias('GroupManager', \OCP\IGroupManager::class);
309
+
310
+        $this->registerService(Store::class, function (Server $c) {
311
+            $session = $c->getSession();
312
+            if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
313
+                $tokenProvider = $c->query('OC\Authentication\Token\IProvider');
314
+            } else {
315
+                $tokenProvider = null;
316
+            }
317
+            $logger = $c->getLogger();
318
+            return new Store($session, $logger, $tokenProvider);
319
+        });
320
+        $this->registerAlias(IStore::class, Store::class);
321
+        $this->registerService('OC\Authentication\Token\DefaultTokenMapper', function (Server $c) {
322
+            $dbConnection = $c->getDatabaseConnection();
323
+            return new Authentication\Token\DefaultTokenMapper($dbConnection);
324
+        });
325
+        $this->registerService('OC\Authentication\Token\DefaultTokenProvider', function (Server $c) {
326
+            $mapper = $c->query('OC\Authentication\Token\DefaultTokenMapper');
327
+            $crypto = $c->getCrypto();
328
+            $config = $c->getConfig();
329
+            $logger = $c->getLogger();
330
+            $timeFactory = new TimeFactory();
331
+            return new \OC\Authentication\Token\DefaultTokenProvider($mapper, $crypto, $config, $logger, $timeFactory);
332
+        });
333
+        $this->registerAlias('OC\Authentication\Token\IProvider', 'OC\Authentication\Token\DefaultTokenProvider');
334
+
335
+        $this->registerService(\OCP\IUserSession::class, function (Server $c) {
336
+            $manager = $c->getUserManager();
337
+            $session = new \OC\Session\Memory('');
338
+            $timeFactory = new TimeFactory();
339
+            // Token providers might require a working database. This code
340
+            // might however be called when ownCloud is not yet setup.
341
+            if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
342
+                $defaultTokenProvider = $c->query('OC\Authentication\Token\IProvider');
343
+            } else {
344
+                $defaultTokenProvider = null;
345
+            }
346
+
347
+            $userSession = new \OC\User\Session($manager, $session, $timeFactory, $defaultTokenProvider, $c->getConfig(), $c->getSecureRandom(), $c->getLockdownManager());
348
+            $userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
349
+                \OC_Hook::emit('OC_User', 'pre_createUser', array('run' => true, 'uid' => $uid, 'password' => $password));
350
+            });
351
+            $userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
352
+                /** @var $user \OC\User\User */
353
+                \OC_Hook::emit('OC_User', 'post_createUser', array('uid' => $user->getUID(), 'password' => $password));
354
+            });
355
+            $userSession->listen('\OC\User', 'preDelete', function ($user) {
356
+                /** @var $user \OC\User\User */
357
+                \OC_Hook::emit('OC_User', 'pre_deleteUser', array('run' => true, 'uid' => $user->getUID()));
358
+            });
359
+            $userSession->listen('\OC\User', 'postDelete', function ($user) {
360
+                /** @var $user \OC\User\User */
361
+                \OC_Hook::emit('OC_User', 'post_deleteUser', array('uid' => $user->getUID()));
362
+            });
363
+            $userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
364
+                /** @var $user \OC\User\User */
365
+                \OC_Hook::emit('OC_User', 'pre_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
366
+            });
367
+            $userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
368
+                /** @var $user \OC\User\User */
369
+                \OC_Hook::emit('OC_User', 'post_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
370
+            });
371
+            $userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
372
+                \OC_Hook::emit('OC_User', 'pre_login', array('run' => true, 'uid' => $uid, 'password' => $password));
373
+            });
374
+            $userSession->listen('\OC\User', 'postLogin', function ($user, $password) {
375
+                /** @var $user \OC\User\User */
376
+                \OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
377
+            });
378
+            $userSession->listen('\OC\User', 'postRememberedLogin', function ($user, $password) {
379
+                /** @var $user \OC\User\User */
380
+                \OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
381
+            });
382
+            $userSession->listen('\OC\User', 'logout', function () {
383
+                \OC_Hook::emit('OC_User', 'logout', array());
384
+            });
385
+            $userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value, $oldValue) {
386
+                /** @var $user \OC\User\User */
387
+                \OC_Hook::emit('OC_User', 'changeUser', array('run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value, 'old_value' => $oldValue));
388
+            });
389
+            return $userSession;
390
+        });
391
+        $this->registerAlias('UserSession', \OCP\IUserSession::class);
392
+
393
+        $this->registerService(\OC\Authentication\TwoFactorAuth\Manager::class, function (Server $c) {
394
+            return new \OC\Authentication\TwoFactorAuth\Manager(
395
+                $c->getAppManager(),
396
+                $c->getSession(),
397
+                $c->getConfig(),
398
+                $c->getActivityManager(),
399
+                $c->getLogger(),
400
+                $c->query(\OC\Authentication\Token\IProvider::class),
401
+                $c->query(ITimeFactory::class)
402
+            );
403
+        });
404
+
405
+        $this->registerAlias(\OCP\INavigationManager::class, \OC\NavigationManager::class);
406
+        $this->registerAlias('NavigationManager', \OCP\INavigationManager::class);
407
+
408
+        $this->registerService(\OC\AllConfig::class, function (Server $c) {
409
+            return new \OC\AllConfig(
410
+                $c->getSystemConfig()
411
+            );
412
+        });
413
+        $this->registerAlias('AllConfig', \OC\AllConfig::class);
414
+        $this->registerAlias(\OCP\IConfig::class, \OC\AllConfig::class);
415
+
416
+        $this->registerService('SystemConfig', function ($c) use ($config) {
417
+            return new \OC\SystemConfig($config);
418
+        });
419
+
420
+        $this->registerService(\OC\AppConfig::class, function (Server $c) {
421
+            return new \OC\AppConfig($c->getDatabaseConnection());
422
+        });
423
+        $this->registerAlias('AppConfig', \OC\AppConfig::class);
424
+        $this->registerAlias(\OCP\IAppConfig::class, \OC\AppConfig::class);
425
+
426
+        $this->registerService(\OCP\L10N\IFactory::class, function (Server $c) {
427
+            return new \OC\L10N\Factory(
428
+                $c->getConfig(),
429
+                $c->getRequest(),
430
+                $c->getUserSession(),
431
+                \OC::$SERVERROOT
432
+            );
433
+        });
434
+        $this->registerAlias('L10NFactory', \OCP\L10N\IFactory::class);
435
+
436
+        $this->registerService(\OCP\IURLGenerator::class, function (Server $c) {
437
+            $config = $c->getConfig();
438
+            $cacheFactory = $c->getMemCacheFactory();
439
+            $request = $c->getRequest();
440
+            return new \OC\URLGenerator(
441
+                $config,
442
+                $cacheFactory,
443
+                $request
444
+            );
445
+        });
446
+        $this->registerAlias('URLGenerator', \OCP\IURLGenerator::class);
447
+
448
+        $this->registerService('AppHelper', function ($c) {
449
+            return new \OC\AppHelper();
450
+        });
451
+        $this->registerAlias('AppFetcher', AppFetcher::class);
452
+        $this->registerAlias('CategoryFetcher', CategoryFetcher::class);
453
+
454
+        $this->registerService(\OCP\ICache::class, function ($c) {
455
+            return new Cache\File();
456
+        });
457
+        $this->registerAlias('UserCache', \OCP\ICache::class);
458
+
459
+        $this->registerService(Factory::class, function (Server $c) {
460
+
461
+            $arrayCacheFactory = new \OC\Memcache\Factory('', $c->getLogger(),
462
+                '\\OC\\Memcache\\ArrayCache',
463
+                '\\OC\\Memcache\\ArrayCache',
464
+                '\\OC\\Memcache\\ArrayCache'
465
+            );
466
+            $config = $c->getConfig();
467
+            $request = $c->getRequest();
468
+            $urlGenerator = new URLGenerator($config, $arrayCacheFactory, $request);
469
+
470
+            if ($config->getSystemValue('installed', false) && !(defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
471
+                $v = \OC_App::getAppVersions();
472
+                $v['core'] = implode(',', \OC_Util::getVersion());
473
+                $version = implode(',', $v);
474
+                $instanceId = \OC_Util::getInstanceId();
475
+                $path = \OC::$SERVERROOT;
476
+                $prefix = md5($instanceId . '-' . $version . '-' . $path . '-' . $urlGenerator->getBaseUrl());
477
+                return new \OC\Memcache\Factory($prefix, $c->getLogger(),
478
+                    $config->getSystemValue('memcache.local', null),
479
+                    $config->getSystemValue('memcache.distributed', null),
480
+                    $config->getSystemValue('memcache.locking', null)
481
+                );
482
+            }
483
+            return $arrayCacheFactory;
484
+
485
+        });
486
+        $this->registerAlias('MemCacheFactory', Factory::class);
487
+        $this->registerAlias(ICacheFactory::class, Factory::class);
488
+
489
+        $this->registerService('RedisFactory', function (Server $c) {
490
+            $systemConfig = $c->getSystemConfig();
491
+            return new RedisFactory($systemConfig);
492
+        });
493
+
494
+        $this->registerService(\OCP\Activity\IManager::class, function (Server $c) {
495
+            return new \OC\Activity\Manager(
496
+                $c->getRequest(),
497
+                $c->getUserSession(),
498
+                $c->getConfig(),
499
+                $c->query(IValidator::class)
500
+            );
501
+        });
502
+        $this->registerAlias('ActivityManager', \OCP\Activity\IManager::class);
503
+
504
+        $this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
505
+            return new \OC\Activity\EventMerger(
506
+                $c->getL10N('lib')
507
+            );
508
+        });
509
+        $this->registerAlias(IValidator::class, Validator::class);
510
+
511
+        $this->registerService(\OCP\IAvatarManager::class, function (Server $c) {
512
+            return new AvatarManager(
513
+                $c->getUserManager(),
514
+                $c->getAppDataDir('avatar'),
515
+                $c->getL10N('lib'),
516
+                $c->getLogger(),
517
+                $c->getConfig()
518
+            );
519
+        });
520
+        $this->registerAlias('AvatarManager', \OCP\IAvatarManager::class);
521
+
522
+        $this->registerAlias(\OCP\Support\CrashReport\IRegistry::class, \OC\Support\CrashReport\Registry::class);
523
+
524
+        $this->registerService(\OCP\ILogger::class, function (Server $c) {
525
+            $logType = $c->query('AllConfig')->getSystemValue('log_type', 'file');
526
+            $logger = Log::getLogClass($logType);
527
+            call_user_func(array($logger, 'init'));
528
+            $config = $this->getSystemConfig();
529
+            $registry = $c->query(\OCP\Support\CrashReport\IRegistry::class);
530
+
531
+            return new Log($logger, $config, null, $registry);
532
+        });
533
+        $this->registerAlias('Logger', \OCP\ILogger::class);
534
+
535
+        $this->registerService(\OCP\BackgroundJob\IJobList::class, function (Server $c) {
536
+            $config = $c->getConfig();
537
+            return new \OC\BackgroundJob\JobList(
538
+                $c->getDatabaseConnection(),
539
+                $config,
540
+                new TimeFactory()
541
+            );
542
+        });
543
+        $this->registerAlias('JobList', \OCP\BackgroundJob\IJobList::class);
544
+
545
+        $this->registerService(\OCP\Route\IRouter::class, function (Server $c) {
546
+            $cacheFactory = $c->getMemCacheFactory();
547
+            $logger = $c->getLogger();
548
+            if ($cacheFactory->isAvailableLowLatency()) {
549
+                $router = new \OC\Route\CachingRouter($cacheFactory->createLocal('route'), $logger);
550
+            } else {
551
+                $router = new \OC\Route\Router($logger);
552
+            }
553
+            return $router;
554
+        });
555
+        $this->registerAlias('Router', \OCP\Route\IRouter::class);
556
+
557
+        $this->registerService(\OCP\ISearch::class, function ($c) {
558
+            return new Search();
559
+        });
560
+        $this->registerAlias('Search', \OCP\ISearch::class);
561
+
562
+        $this->registerService(\OC\Security\RateLimiting\Limiter::class, function ($c) {
563
+            return new \OC\Security\RateLimiting\Limiter(
564
+                $this->getUserSession(),
565
+                $this->getRequest(),
566
+                new \OC\AppFramework\Utility\TimeFactory(),
567
+                $c->query(\OC\Security\RateLimiting\Backend\IBackend::class)
568
+            );
569
+        });
570
+        $this->registerService(\OC\Security\RateLimiting\Backend\IBackend::class, function ($c) {
571
+            return new \OC\Security\RateLimiting\Backend\MemoryCache(
572
+                $this->getMemCacheFactory(),
573
+                new \OC\AppFramework\Utility\TimeFactory()
574
+            );
575
+        });
576
+
577
+        $this->registerService(\OCP\Security\ISecureRandom::class, function ($c) {
578
+            return new SecureRandom();
579
+        });
580
+        $this->registerAlias('SecureRandom', \OCP\Security\ISecureRandom::class);
581
+
582
+        $this->registerService(\OCP\Security\ICrypto::class, function (Server $c) {
583
+            return new Crypto($c->getConfig(), $c->getSecureRandom());
584
+        });
585
+        $this->registerAlias('Crypto', \OCP\Security\ICrypto::class);
586
+
587
+        $this->registerService(\OCP\Security\IHasher::class, function (Server $c) {
588
+            return new Hasher($c->getConfig());
589
+        });
590
+        $this->registerAlias('Hasher', \OCP\Security\IHasher::class);
591
+
592
+        $this->registerService(\OCP\Security\ICredentialsManager::class, function (Server $c) {
593
+            return new CredentialsManager($c->getCrypto(), $c->getDatabaseConnection());
594
+        });
595
+        $this->registerAlias('CredentialsManager', \OCP\Security\ICredentialsManager::class);
596
+
597
+        $this->registerService(IDBConnection::class, function (Server $c) {
598
+            $systemConfig = $c->getSystemConfig();
599
+            $factory = new \OC\DB\ConnectionFactory($systemConfig);
600
+            $type = $systemConfig->getValue('dbtype', 'sqlite');
601
+            if (!$factory->isValidType($type)) {
602
+                throw new \OC\DatabaseException('Invalid database type');
603
+            }
604
+            $connectionParams = $factory->createConnectionParams();
605
+            $connection = $factory->getConnection($type, $connectionParams);
606
+            $connection->getConfiguration()->setSQLLogger($c->getQueryLogger());
607
+            return $connection;
608
+        });
609
+        $this->registerAlias('DatabaseConnection', IDBConnection::class);
610
+
611
+        $this->registerService('HTTPHelper', function (Server $c) {
612
+            $config = $c->getConfig();
613
+            return new HTTPHelper(
614
+                $config,
615
+                $c->getHTTPClientService()
616
+            );
617
+        });
618
+
619
+        $this->registerService(\OCP\Http\Client\IClientService::class, function (Server $c) {
620
+            $user = \OC_User::getUser();
621
+            $uid = $user ? $user : null;
622
+            return new ClientService(
623
+                $c->getConfig(),
624
+                new \OC\Security\CertificateManager(
625
+                    $uid,
626
+                    new View(),
627
+                    $c->getConfig(),
628
+                    $c->getLogger(),
629
+                    $c->getSecureRandom()
630
+                )
631
+            );
632
+        });
633
+        $this->registerAlias('HttpClientService', \OCP\Http\Client\IClientService::class);
634
+        $this->registerService(\OCP\Diagnostics\IEventLogger::class, function (Server $c) {
635
+            $eventLogger = new EventLogger();
636
+            if ($c->getSystemConfig()->getValue('debug', false)) {
637
+                // In debug mode, module is being activated by default
638
+                $eventLogger->activate();
639
+            }
640
+            return $eventLogger;
641
+        });
642
+        $this->registerAlias('EventLogger', \OCP\Diagnostics\IEventLogger::class);
643
+
644
+        $this->registerService(\OCP\Diagnostics\IQueryLogger::class, function (Server $c) {
645
+            $queryLogger = new QueryLogger();
646
+            if ($c->getSystemConfig()->getValue('debug', false)) {
647
+                // In debug mode, module is being activated by default
648
+                $queryLogger->activate();
649
+            }
650
+            return $queryLogger;
651
+        });
652
+        $this->registerAlias('QueryLogger', \OCP\Diagnostics\IQueryLogger::class);
653
+
654
+        $this->registerService(TempManager::class, function (Server $c) {
655
+            return new TempManager(
656
+                $c->getLogger(),
657
+                $c->getConfig()
658
+            );
659
+        });
660
+        $this->registerAlias('TempManager', TempManager::class);
661
+        $this->registerAlias(ITempManager::class, TempManager::class);
662
+
663
+        $this->registerService(AppManager::class, function (Server $c) {
664
+            return new \OC\App\AppManager(
665
+                $c->getUserSession(),
666
+                $c->getAppConfig(),
667
+                $c->getGroupManager(),
668
+                $c->getMemCacheFactory(),
669
+                $c->getEventDispatcher()
670
+            );
671
+        });
672
+        $this->registerAlias('AppManager', AppManager::class);
673
+        $this->registerAlias(IAppManager::class, AppManager::class);
674
+
675
+        $this->registerService(\OCP\IDateTimeZone::class, function (Server $c) {
676
+            return new DateTimeZone(
677
+                $c->getConfig(),
678
+                $c->getSession()
679
+            );
680
+        });
681
+        $this->registerAlias('DateTimeZone', \OCP\IDateTimeZone::class);
682
+
683
+        $this->registerService(\OCP\IDateTimeFormatter::class, function (Server $c) {
684
+            $language = $c->getConfig()->getUserValue($c->getSession()->get('user_id'), 'core', 'lang', null);
685
+
686
+            return new DateTimeFormatter(
687
+                $c->getDateTimeZone()->getTimeZone(),
688
+                $c->getL10N('lib', $language)
689
+            );
690
+        });
691
+        $this->registerAlias('DateTimeFormatter', \OCP\IDateTimeFormatter::class);
692
+
693
+        $this->registerService(\OCP\Files\Config\IUserMountCache::class, function (Server $c) {
694
+            $mountCache = new UserMountCache($c->getDatabaseConnection(), $c->getUserManager(), $c->getLogger());
695
+            $listener = new UserMountCacheListener($mountCache);
696
+            $listener->listen($c->getUserManager());
697
+            return $mountCache;
698
+        });
699
+        $this->registerAlias('UserMountCache', \OCP\Files\Config\IUserMountCache::class);
700
+
701
+        $this->registerService(\OCP\Files\Config\IMountProviderCollection::class, function (Server $c) {
702
+            $loader = \OC\Files\Filesystem::getLoader();
703
+            $mountCache = $c->query('UserMountCache');
704
+            $manager = new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
705
+
706
+            // builtin providers
707
+
708
+            $config = $c->getConfig();
709
+            $manager->registerProvider(new CacheMountProvider($config));
710
+            $manager->registerHomeProvider(new LocalHomeMountProvider());
711
+            $manager->registerHomeProvider(new ObjectHomeMountProvider($config));
712
+
713
+            return $manager;
714
+        });
715
+        $this->registerAlias('MountConfigManager', \OCP\Files\Config\IMountProviderCollection::class);
716
+
717
+        $this->registerService('IniWrapper', function ($c) {
718
+            return new IniGetWrapper();
719
+        });
720
+        $this->registerService('AsyncCommandBus', function (Server $c) {
721
+            $busClass = $c->getConfig()->getSystemValue('commandbus');
722
+            if ($busClass) {
723
+                list($app, $class) = explode('::', $busClass, 2);
724
+                if ($c->getAppManager()->isInstalled($app)) {
725
+                    \OC_App::loadApp($app);
726
+                    return $c->query($class);
727
+                } else {
728
+                    throw new ServiceUnavailableException("The app providing the command bus ($app) is not enabled");
729
+                }
730
+            } else {
731
+                $jobList = $c->getJobList();
732
+                return new CronBus($jobList);
733
+            }
734
+        });
735
+        $this->registerService('TrustedDomainHelper', function ($c) {
736
+            return new TrustedDomainHelper($this->getConfig());
737
+        });
738
+        $this->registerService('Throttler', function (Server $c) {
739
+            return new Throttler(
740
+                $c->getDatabaseConnection(),
741
+                new TimeFactory(),
742
+                $c->getLogger(),
743
+                $c->getConfig()
744
+            );
745
+        });
746
+        $this->registerService('IntegrityCodeChecker', function (Server $c) {
747
+            // IConfig and IAppManager requires a working database. This code
748
+            // might however be called when ownCloud is not yet setup.
749
+            if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
750
+                $config = $c->getConfig();
751
+                $appManager = $c->getAppManager();
752
+            } else {
753
+                $config = null;
754
+                $appManager = null;
755
+            }
756
+
757
+            return new Checker(
758
+                new EnvironmentHelper(),
759
+                new FileAccessHelper(),
760
+                new AppLocator(),
761
+                $config,
762
+                $c->getMemCacheFactory(),
763
+                $appManager,
764
+                $c->getTempManager()
765
+            );
766
+        });
767
+        $this->registerService(\OCP\IRequest::class, function ($c) {
768
+            if (isset($this['urlParams'])) {
769
+                $urlParams = $this['urlParams'];
770
+            } else {
771
+                $urlParams = [];
772
+            }
773
+
774
+            if (defined('PHPUNIT_RUN') && PHPUNIT_RUN
775
+                && in_array('fakeinput', stream_get_wrappers())
776
+            ) {
777
+                $stream = 'fakeinput://data';
778
+            } else {
779
+                $stream = 'php://input';
780
+            }
781
+
782
+            return new Request(
783
+                [
784
+                    'get' => $_GET,
785
+                    'post' => $_POST,
786
+                    'files' => $_FILES,
787
+                    'server' => $_SERVER,
788
+                    'env' => $_ENV,
789
+                    'cookies' => $_COOKIE,
790
+                    'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
791
+                        ? $_SERVER['REQUEST_METHOD']
792
+                        : null,
793
+                    'urlParams' => $urlParams,
794
+                ],
795
+                $this->getSecureRandom(),
796
+                $this->getConfig(),
797
+                $this->getCsrfTokenManager(),
798
+                $stream
799
+            );
800
+        });
801
+        $this->registerAlias('Request', \OCP\IRequest::class);
802
+
803
+        $this->registerService(\OCP\Mail\IMailer::class, function (Server $c) {
804
+            return new Mailer(
805
+                $c->getConfig(),
806
+                $c->getLogger(),
807
+                $c->query(Defaults::class),
808
+                $c->getURLGenerator(),
809
+                $c->getL10N('lib')
810
+            );
811
+        });
812
+        $this->registerAlias('Mailer', \OCP\Mail\IMailer::class);
813
+
814
+        $this->registerService('LDAPProvider', function (Server $c) {
815
+            $config = $c->getConfig();
816
+            $factoryClass = $config->getSystemValue('ldapProviderFactory', null);
817
+            if (is_null($factoryClass)) {
818
+                throw new \Exception('ldapProviderFactory not set');
819
+            }
820
+            /** @var \OCP\LDAP\ILDAPProviderFactory $factory */
821
+            $factory = new $factoryClass($this);
822
+            return $factory->getLDAPProvider();
823
+        });
824
+        $this->registerService(ILockingProvider::class, function (Server $c) {
825
+            $ini = $c->getIniWrapper();
826
+            $config = $c->getConfig();
827
+            $ttl = $config->getSystemValue('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
828
+            if ($config->getSystemValue('filelocking.enabled', true) or (defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
829
+                /** @var \OC\Memcache\Factory $memcacheFactory */
830
+                $memcacheFactory = $c->getMemCacheFactory();
831
+                $memcache = $memcacheFactory->createLocking('lock');
832
+                if (!($memcache instanceof \OC\Memcache\NullCache)) {
833
+                    return new MemcacheLockingProvider($memcache, $ttl);
834
+                }
835
+                return new DBLockingProvider($c->getDatabaseConnection(), $c->getLogger(), new TimeFactory(), $ttl);
836
+            }
837
+            return new NoopLockingProvider();
838
+        });
839
+        $this->registerAlias('LockingProvider', ILockingProvider::class);
840
+
841
+        $this->registerService(\OCP\Files\Mount\IMountManager::class, function () {
842
+            return new \OC\Files\Mount\Manager();
843
+        });
844
+        $this->registerAlias('MountManager', \OCP\Files\Mount\IMountManager::class);
845
+
846
+        $this->registerService(\OCP\Files\IMimeTypeDetector::class, function (Server $c) {
847
+            return new \OC\Files\Type\Detection(
848
+                $c->getURLGenerator(),
849
+                \OC::$configDir,
850
+                \OC::$SERVERROOT . '/resources/config/'
851
+            );
852
+        });
853
+        $this->registerAlias('MimeTypeDetector', \OCP\Files\IMimeTypeDetector::class);
854
+
855
+        $this->registerService(\OCP\Files\IMimeTypeLoader::class, function (Server $c) {
856
+            return new \OC\Files\Type\Loader(
857
+                $c->getDatabaseConnection()
858
+            );
859
+        });
860
+        $this->registerAlias('MimeTypeLoader', \OCP\Files\IMimeTypeLoader::class);
861
+        $this->registerService(BundleFetcher::class, function () {
862
+            return new BundleFetcher($this->getL10N('lib'));
863
+        });
864
+        $this->registerService(\OCP\Notification\IManager::class, function (Server $c) {
865
+            return new Manager(
866
+                $c->query(IValidator::class)
867
+            );
868
+        });
869
+        $this->registerAlias('NotificationManager', \OCP\Notification\IManager::class);
870
+
871
+        $this->registerService(\OC\CapabilitiesManager::class, function (Server $c) {
872
+            $manager = new \OC\CapabilitiesManager($c->getLogger());
873
+            $manager->registerCapability(function () use ($c) {
874
+                return new \OC\OCS\CoreCapabilities($c->getConfig());
875
+            });
876
+            $manager->registerCapability(function () use ($c) {
877
+                return $c->query(\OC\Security\Bruteforce\Capabilities::class);
878
+            });
879
+            return $manager;
880
+        });
881
+        $this->registerAlias('CapabilitiesManager', \OC\CapabilitiesManager::class);
882
+
883
+        $this->registerService(\OCP\Comments\ICommentsManager::class, function (Server $c) {
884
+            $config = $c->getConfig();
885
+            $factoryClass = $config->getSystemValue('comments.managerFactory', '\OC\Comments\ManagerFactory');
886
+            /** @var \OCP\Comments\ICommentsManagerFactory $factory */
887
+            $factory = new $factoryClass($this);
888
+            return $factory->getManager();
889
+        });
890
+        $this->registerAlias('CommentsManager', \OCP\Comments\ICommentsManager::class);
891
+
892
+        $this->registerService('ThemingDefaults', function (Server $c) {
893
+            /*
894 894
 			 * Dark magic for autoloader.
895 895
 			 * If we do a class_exists it will try to load the class which will
896 896
 			 * make composer cache the result. Resulting in errors when enabling
897 897
 			 * the theming app.
898 898
 			 */
899
-			$prefixes = \OC::$composerAutoloader->getPrefixesPsr4();
900
-			if (isset($prefixes['OCA\\Theming\\'])) {
901
-				$classExists = true;
902
-			} else {
903
-				$classExists = false;
904
-			}
905
-
906
-			if ($classExists && $c->getConfig()->getSystemValue('installed', false) && $c->getAppManager()->isInstalled('theming') && $c->getTrustedDomainHelper()->isTrustedDomain($c->getRequest()->getInsecureServerHost())) {
907
-				return new ThemingDefaults(
908
-					$c->getConfig(),
909
-					$c->getL10N('theming'),
910
-					$c->getURLGenerator(),
911
-					$c->getAppDataDir('theming'),
912
-					$c->getMemCacheFactory(),
913
-					new Util($c->getConfig(), $this->getAppManager(), $this->getAppDataDir('theming')),
914
-					$this->getAppManager()
915
-				);
916
-			}
917
-			return new \OC_Defaults();
918
-		});
919
-		$this->registerService(SCSSCacher::class, function (Server $c) {
920
-			/** @var Factory $cacheFactory */
921
-			$cacheFactory = $c->query(Factory::class);
922
-			return new SCSSCacher(
923
-				$c->getLogger(),
924
-				$c->query(\OC\Files\AppData\Factory::class),
925
-				$c->getURLGenerator(),
926
-				$c->getConfig(),
927
-				$c->getThemingDefaults(),
928
-				\OC::$SERVERROOT,
929
-				$cacheFactory->create('SCSS')
930
-			);
931
-		});
932
-		$this->registerService(EventDispatcher::class, function () {
933
-			return new EventDispatcher();
934
-		});
935
-		$this->registerAlias('EventDispatcher', EventDispatcher::class);
936
-		$this->registerAlias(EventDispatcherInterface::class, EventDispatcher::class);
937
-
938
-		$this->registerService('CryptoWrapper', function (Server $c) {
939
-			// FIXME: Instantiiated here due to cyclic dependency
940
-			$request = new Request(
941
-				[
942
-					'get' => $_GET,
943
-					'post' => $_POST,
944
-					'files' => $_FILES,
945
-					'server' => $_SERVER,
946
-					'env' => $_ENV,
947
-					'cookies' => $_COOKIE,
948
-					'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
949
-						? $_SERVER['REQUEST_METHOD']
950
-						: null,
951
-				],
952
-				$c->getSecureRandom(),
953
-				$c->getConfig()
954
-			);
955
-
956
-			return new CryptoWrapper(
957
-				$c->getConfig(),
958
-				$c->getCrypto(),
959
-				$c->getSecureRandom(),
960
-				$request
961
-			);
962
-		});
963
-		$this->registerService('CsrfTokenManager', function (Server $c) {
964
-			$tokenGenerator = new CsrfTokenGenerator($c->getSecureRandom());
965
-
966
-			return new CsrfTokenManager(
967
-				$tokenGenerator,
968
-				$c->query(SessionStorage::class)
969
-			);
970
-		});
971
-		$this->registerService(SessionStorage::class, function (Server $c) {
972
-			return new SessionStorage($c->getSession());
973
-		});
974
-		$this->registerService(\OCP\Security\IContentSecurityPolicyManager::class, function (Server $c) {
975
-			return new ContentSecurityPolicyManager();
976
-		});
977
-		$this->registerAlias('ContentSecurityPolicyManager', \OCP\Security\IContentSecurityPolicyManager::class);
978
-
979
-		$this->registerService('ContentSecurityPolicyNonceManager', function (Server $c) {
980
-			return new ContentSecurityPolicyNonceManager(
981
-				$c->getCsrfTokenManager(),
982
-				$c->getRequest()
983
-			);
984
-		});
985
-
986
-		$this->registerService(\OCP\Share\IManager::class, function (Server $c) {
987
-			$config = $c->getConfig();
988
-			$factoryClass = $config->getSystemValue('sharing.managerFactory', '\OC\Share20\ProviderFactory');
989
-			/** @var \OCP\Share\IProviderFactory $factory */
990
-			$factory = new $factoryClass($this);
991
-
992
-			$manager = new \OC\Share20\Manager(
993
-				$c->getLogger(),
994
-				$c->getConfig(),
995
-				$c->getSecureRandom(),
996
-				$c->getHasher(),
997
-				$c->getMountManager(),
998
-				$c->getGroupManager(),
999
-				$c->getL10N('lib'),
1000
-				$c->getL10NFactory(),
1001
-				$factory,
1002
-				$c->getUserManager(),
1003
-				$c->getLazyRootFolder(),
1004
-				$c->getEventDispatcher(),
1005
-				$c->getMailer(),
1006
-				$c->getURLGenerator(),
1007
-				$c->getThemingDefaults()
1008
-			);
1009
-
1010
-			return $manager;
1011
-		});
1012
-		$this->registerAlias('ShareManager', \OCP\Share\IManager::class);
1013
-
1014
-		$this->registerService(\OCP\Collaboration\Collaborators\ISearch::class, function(Server $c) {
1015
-			$instance = new Collaboration\Collaborators\Search($c);
1016
-
1017
-			// register default plugins
1018
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_USER', 'class' => UserPlugin::class]);
1019
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_GROUP', 'class' => GroupPlugin::class]);
1020
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_EMAIL', 'class' => MailPlugin::class]);
1021
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_REMOTE', 'class' => RemotePlugin::class]);
1022
-
1023
-			return $instance;
1024
-		});
1025
-		$this->registerAlias('CollaboratorSearch', \OCP\Collaboration\Collaborators\ISearch::class);
1026
-
1027
-		$this->registerAlias(\OCP\Collaboration\AutoComplete\IManager::class, \OC\Collaboration\AutoComplete\Manager::class);
1028
-
1029
-		$this->registerService('SettingsManager', function (Server $c) {
1030
-			$manager = new \OC\Settings\Manager(
1031
-				$c->getLogger(),
1032
-				$c->getDatabaseConnection(),
1033
-				$c->getL10N('lib'),
1034
-				$c->getConfig(),
1035
-				$c->getEncryptionManager(),
1036
-				$c->getUserManager(),
1037
-				$c->getLockingProvider(),
1038
-				$c->getRequest(),
1039
-				new \OC\Settings\Mapper($c->getDatabaseConnection()),
1040
-				$c->getURLGenerator(),
1041
-				$c->query(AccountManager::class),
1042
-				$c->getGroupManager(),
1043
-				$c->getL10NFactory(),
1044
-				$c->getThemingDefaults(),
1045
-				$c->getAppManager()
1046
-			);
1047
-			return $manager;
1048
-		});
1049
-		$this->registerService(\OC\Files\AppData\Factory::class, function (Server $c) {
1050
-			return new \OC\Files\AppData\Factory(
1051
-				$c->getRootFolder(),
1052
-				$c->getSystemConfig()
1053
-			);
1054
-		});
1055
-
1056
-		$this->registerService('LockdownManager', function (Server $c) {
1057
-			return new LockdownManager(function () use ($c) {
1058
-				return $c->getSession();
1059
-			});
1060
-		});
1061
-
1062
-		$this->registerService(\OCP\OCS\IDiscoveryService::class, function (Server $c) {
1063
-			return new DiscoveryService($c->getMemCacheFactory(), $c->getHTTPClientService());
1064
-		});
1065
-
1066
-		$this->registerService(ICloudIdManager::class, function (Server $c) {
1067
-			return new CloudIdManager();
1068
-		});
1069
-
1070
-		/* To trick DI since we don't extend the DIContainer here */
1071
-		$this->registerService(CleanPreviewsBackgroundJob::class, function (Server $c) {
1072
-			return new CleanPreviewsBackgroundJob(
1073
-				$c->getRootFolder(),
1074
-				$c->getLogger(),
1075
-				$c->getJobList(),
1076
-				new TimeFactory()
1077
-			);
1078
-		});
1079
-
1080
-		$this->registerAlias(\OCP\AppFramework\Utility\IControllerMethodReflector::class, \OC\AppFramework\Utility\ControllerMethodReflector::class);
1081
-		$this->registerAlias('ControllerMethodReflector', \OCP\AppFramework\Utility\IControllerMethodReflector::class);
1082
-
1083
-		$this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
1084
-		$this->registerAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
1085
-
1086
-		$this->registerService(Defaults::class, function (Server $c) {
1087
-			return new Defaults(
1088
-				$c->getThemingDefaults()
1089
-			);
1090
-		});
1091
-		$this->registerAlias('Defaults', \OCP\Defaults::class);
1092
-
1093
-		$this->registerService(\OCP\ISession::class, function (SimpleContainer $c) {
1094
-			return $c->query(\OCP\IUserSession::class)->getSession();
1095
-		});
1096
-
1097
-		$this->registerService(IShareHelper::class, function (Server $c) {
1098
-			return new ShareHelper(
1099
-				$c->query(\OCP\Share\IManager::class)
1100
-			);
1101
-		});
1102
-
1103
-		$this->registerService(Installer::class, function(Server $c) {
1104
-			return new Installer(
1105
-				$c->getAppFetcher(),
1106
-				$c->getHTTPClientService(),
1107
-				$c->getTempManager(),
1108
-				$c->getLogger(),
1109
-				$c->getConfig()
1110
-			);
1111
-		});
1112
-	}
1113
-
1114
-	/**
1115
-	 * @return \OCP\Calendar\IManager
1116
-	 */
1117
-	public function getCalendarManager() {
1118
-		return $this->query('CalendarManager');
1119
-	}
1120
-
1121
-	/**
1122
-	 * @return \OCP\Contacts\IManager
1123
-	 */
1124
-	public function getContactsManager() {
1125
-		return $this->query('ContactsManager');
1126
-	}
1127
-
1128
-	/**
1129
-	 * @return \OC\Encryption\Manager
1130
-	 */
1131
-	public function getEncryptionManager() {
1132
-		return $this->query('EncryptionManager');
1133
-	}
1134
-
1135
-	/**
1136
-	 * @return \OC\Encryption\File
1137
-	 */
1138
-	public function getEncryptionFilesHelper() {
1139
-		return $this->query('EncryptionFileHelper');
1140
-	}
1141
-
1142
-	/**
1143
-	 * @return \OCP\Encryption\Keys\IStorage
1144
-	 */
1145
-	public function getEncryptionKeyStorage() {
1146
-		return $this->query('EncryptionKeyStorage');
1147
-	}
1148
-
1149
-	/**
1150
-	 * The current request object holding all information about the request
1151
-	 * currently being processed is returned from this method.
1152
-	 * In case the current execution was not initiated by a web request null is returned
1153
-	 *
1154
-	 * @return \OCP\IRequest
1155
-	 */
1156
-	public function getRequest() {
1157
-		return $this->query('Request');
1158
-	}
1159
-
1160
-	/**
1161
-	 * Returns the preview manager which can create preview images for a given file
1162
-	 *
1163
-	 * @return \OCP\IPreview
1164
-	 */
1165
-	public function getPreviewManager() {
1166
-		return $this->query('PreviewManager');
1167
-	}
1168
-
1169
-	/**
1170
-	 * Returns the tag manager which can get and set tags for different object types
1171
-	 *
1172
-	 * @see \OCP\ITagManager::load()
1173
-	 * @return \OCP\ITagManager
1174
-	 */
1175
-	public function getTagManager() {
1176
-		return $this->query('TagManager');
1177
-	}
1178
-
1179
-	/**
1180
-	 * Returns the system-tag manager
1181
-	 *
1182
-	 * @return \OCP\SystemTag\ISystemTagManager
1183
-	 *
1184
-	 * @since 9.0.0
1185
-	 */
1186
-	public function getSystemTagManager() {
1187
-		return $this->query('SystemTagManager');
1188
-	}
1189
-
1190
-	/**
1191
-	 * Returns the system-tag object mapper
1192
-	 *
1193
-	 * @return \OCP\SystemTag\ISystemTagObjectMapper
1194
-	 *
1195
-	 * @since 9.0.0
1196
-	 */
1197
-	public function getSystemTagObjectMapper() {
1198
-		return $this->query('SystemTagObjectMapper');
1199
-	}
1200
-
1201
-	/**
1202
-	 * Returns the avatar manager, used for avatar functionality
1203
-	 *
1204
-	 * @return \OCP\IAvatarManager
1205
-	 */
1206
-	public function getAvatarManager() {
1207
-		return $this->query('AvatarManager');
1208
-	}
1209
-
1210
-	/**
1211
-	 * Returns the root folder of ownCloud's data directory
1212
-	 *
1213
-	 * @return \OCP\Files\IRootFolder
1214
-	 */
1215
-	public function getRootFolder() {
1216
-		return $this->query('LazyRootFolder');
1217
-	}
1218
-
1219
-	/**
1220
-	 * Returns the root folder of ownCloud's data directory
1221
-	 * This is the lazy variant so this gets only initialized once it
1222
-	 * is actually used.
1223
-	 *
1224
-	 * @return \OCP\Files\IRootFolder
1225
-	 */
1226
-	public function getLazyRootFolder() {
1227
-		return $this->query('LazyRootFolder');
1228
-	}
1229
-
1230
-	/**
1231
-	 * Returns a view to ownCloud's files folder
1232
-	 *
1233
-	 * @param string $userId user ID
1234
-	 * @return \OCP\Files\Folder|null
1235
-	 */
1236
-	public function getUserFolder($userId = null) {
1237
-		if ($userId === null) {
1238
-			$user = $this->getUserSession()->getUser();
1239
-			if (!$user) {
1240
-				return null;
1241
-			}
1242
-			$userId = $user->getUID();
1243
-		}
1244
-		$root = $this->getRootFolder();
1245
-		return $root->getUserFolder($userId);
1246
-	}
1247
-
1248
-	/**
1249
-	 * Returns an app-specific view in ownClouds data directory
1250
-	 *
1251
-	 * @return \OCP\Files\Folder
1252
-	 * @deprecated since 9.2.0 use IAppData
1253
-	 */
1254
-	public function getAppFolder() {
1255
-		$dir = '/' . \OC_App::getCurrentApp();
1256
-		$root = $this->getRootFolder();
1257
-		if (!$root->nodeExists($dir)) {
1258
-			$folder = $root->newFolder($dir);
1259
-		} else {
1260
-			$folder = $root->get($dir);
1261
-		}
1262
-		return $folder;
1263
-	}
1264
-
1265
-	/**
1266
-	 * @return \OC\User\Manager
1267
-	 */
1268
-	public function getUserManager() {
1269
-		return $this->query('UserManager');
1270
-	}
1271
-
1272
-	/**
1273
-	 * @return \OC\Group\Manager
1274
-	 */
1275
-	public function getGroupManager() {
1276
-		return $this->query('GroupManager');
1277
-	}
1278
-
1279
-	/**
1280
-	 * @return \OC\User\Session
1281
-	 */
1282
-	public function getUserSession() {
1283
-		return $this->query('UserSession');
1284
-	}
1285
-
1286
-	/**
1287
-	 * @return \OCP\ISession
1288
-	 */
1289
-	public function getSession() {
1290
-		return $this->query('UserSession')->getSession();
1291
-	}
1292
-
1293
-	/**
1294
-	 * @param \OCP\ISession $session
1295
-	 */
1296
-	public function setSession(\OCP\ISession $session) {
1297
-		$this->query(SessionStorage::class)->setSession($session);
1298
-		$this->query('UserSession')->setSession($session);
1299
-		$this->query(Store::class)->setSession($session);
1300
-	}
1301
-
1302
-	/**
1303
-	 * @return \OC\Authentication\TwoFactorAuth\Manager
1304
-	 */
1305
-	public function getTwoFactorAuthManager() {
1306
-		return $this->query('\OC\Authentication\TwoFactorAuth\Manager');
1307
-	}
1308
-
1309
-	/**
1310
-	 * @return \OC\NavigationManager
1311
-	 */
1312
-	public function getNavigationManager() {
1313
-		return $this->query('NavigationManager');
1314
-	}
1315
-
1316
-	/**
1317
-	 * @return \OCP\IConfig
1318
-	 */
1319
-	public function getConfig() {
1320
-		return $this->query('AllConfig');
1321
-	}
1322
-
1323
-	/**
1324
-	 * @return \OC\SystemConfig
1325
-	 */
1326
-	public function getSystemConfig() {
1327
-		return $this->query('SystemConfig');
1328
-	}
1329
-
1330
-	/**
1331
-	 * Returns the app config manager
1332
-	 *
1333
-	 * @return \OCP\IAppConfig
1334
-	 */
1335
-	public function getAppConfig() {
1336
-		return $this->query('AppConfig');
1337
-	}
1338
-
1339
-	/**
1340
-	 * @return \OCP\L10N\IFactory
1341
-	 */
1342
-	public function getL10NFactory() {
1343
-		return $this->query('L10NFactory');
1344
-	}
1345
-
1346
-	/**
1347
-	 * get an L10N instance
1348
-	 *
1349
-	 * @param string $app appid
1350
-	 * @param string $lang
1351
-	 * @return IL10N
1352
-	 */
1353
-	public function getL10N($app, $lang = null) {
1354
-		return $this->getL10NFactory()->get($app, $lang);
1355
-	}
1356
-
1357
-	/**
1358
-	 * @return \OCP\IURLGenerator
1359
-	 */
1360
-	public function getURLGenerator() {
1361
-		return $this->query('URLGenerator');
1362
-	}
1363
-
1364
-	/**
1365
-	 * @return \OCP\IHelper
1366
-	 */
1367
-	public function getHelper() {
1368
-		return $this->query('AppHelper');
1369
-	}
1370
-
1371
-	/**
1372
-	 * @return AppFetcher
1373
-	 */
1374
-	public function getAppFetcher() {
1375
-		return $this->query(AppFetcher::class);
1376
-	}
1377
-
1378
-	/**
1379
-	 * Returns an ICache instance. Since 8.1.0 it returns a fake cache. Use
1380
-	 * getMemCacheFactory() instead.
1381
-	 *
1382
-	 * @return \OCP\ICache
1383
-	 * @deprecated 8.1.0 use getMemCacheFactory to obtain a proper cache
1384
-	 */
1385
-	public function getCache() {
1386
-		return $this->query('UserCache');
1387
-	}
1388
-
1389
-	/**
1390
-	 * Returns an \OCP\CacheFactory instance
1391
-	 *
1392
-	 * @return \OCP\ICacheFactory
1393
-	 */
1394
-	public function getMemCacheFactory() {
1395
-		return $this->query('MemCacheFactory');
1396
-	}
1397
-
1398
-	/**
1399
-	 * Returns an \OC\RedisFactory instance
1400
-	 *
1401
-	 * @return \OC\RedisFactory
1402
-	 */
1403
-	public function getGetRedisFactory() {
1404
-		return $this->query('RedisFactory');
1405
-	}
1406
-
1407
-
1408
-	/**
1409
-	 * Returns the current session
1410
-	 *
1411
-	 * @return \OCP\IDBConnection
1412
-	 */
1413
-	public function getDatabaseConnection() {
1414
-		return $this->query('DatabaseConnection');
1415
-	}
1416
-
1417
-	/**
1418
-	 * Returns the activity manager
1419
-	 *
1420
-	 * @return \OCP\Activity\IManager
1421
-	 */
1422
-	public function getActivityManager() {
1423
-		return $this->query('ActivityManager');
1424
-	}
1425
-
1426
-	/**
1427
-	 * Returns an job list for controlling background jobs
1428
-	 *
1429
-	 * @return \OCP\BackgroundJob\IJobList
1430
-	 */
1431
-	public function getJobList() {
1432
-		return $this->query('JobList');
1433
-	}
1434
-
1435
-	/**
1436
-	 * Returns a logger instance
1437
-	 *
1438
-	 * @return \OCP\ILogger
1439
-	 */
1440
-	public function getLogger() {
1441
-		return $this->query('Logger');
1442
-	}
1443
-
1444
-	/**
1445
-	 * Returns a router for generating and matching urls
1446
-	 *
1447
-	 * @return \OCP\Route\IRouter
1448
-	 */
1449
-	public function getRouter() {
1450
-		return $this->query('Router');
1451
-	}
1452
-
1453
-	/**
1454
-	 * Returns a search instance
1455
-	 *
1456
-	 * @return \OCP\ISearch
1457
-	 */
1458
-	public function getSearch() {
1459
-		return $this->query('Search');
1460
-	}
1461
-
1462
-	/**
1463
-	 * Returns a SecureRandom instance
1464
-	 *
1465
-	 * @return \OCP\Security\ISecureRandom
1466
-	 */
1467
-	public function getSecureRandom() {
1468
-		return $this->query('SecureRandom');
1469
-	}
1470
-
1471
-	/**
1472
-	 * Returns a Crypto instance
1473
-	 *
1474
-	 * @return \OCP\Security\ICrypto
1475
-	 */
1476
-	public function getCrypto() {
1477
-		return $this->query('Crypto');
1478
-	}
1479
-
1480
-	/**
1481
-	 * Returns a Hasher instance
1482
-	 *
1483
-	 * @return \OCP\Security\IHasher
1484
-	 */
1485
-	public function getHasher() {
1486
-		return $this->query('Hasher');
1487
-	}
1488
-
1489
-	/**
1490
-	 * Returns a CredentialsManager instance
1491
-	 *
1492
-	 * @return \OCP\Security\ICredentialsManager
1493
-	 */
1494
-	public function getCredentialsManager() {
1495
-		return $this->query('CredentialsManager');
1496
-	}
1497
-
1498
-	/**
1499
-	 * Returns an instance of the HTTP helper class
1500
-	 *
1501
-	 * @deprecated Use getHTTPClientService()
1502
-	 * @return \OC\HTTPHelper
1503
-	 */
1504
-	public function getHTTPHelper() {
1505
-		return $this->query('HTTPHelper');
1506
-	}
1507
-
1508
-	/**
1509
-	 * Get the certificate manager for the user
1510
-	 *
1511
-	 * @param string $userId (optional) if not specified the current loggedin user is used, use null to get the system certificate manager
1512
-	 * @return \OCP\ICertificateManager | null if $uid is null and no user is logged in
1513
-	 */
1514
-	public function getCertificateManager($userId = '') {
1515
-		if ($userId === '') {
1516
-			$userSession = $this->getUserSession();
1517
-			$user = $userSession->getUser();
1518
-			if (is_null($user)) {
1519
-				return null;
1520
-			}
1521
-			$userId = $user->getUID();
1522
-		}
1523
-		return new CertificateManager(
1524
-			$userId,
1525
-			new View(),
1526
-			$this->getConfig(),
1527
-			$this->getLogger(),
1528
-			$this->getSecureRandom()
1529
-		);
1530
-	}
1531
-
1532
-	/**
1533
-	 * Returns an instance of the HTTP client service
1534
-	 *
1535
-	 * @return \OCP\Http\Client\IClientService
1536
-	 */
1537
-	public function getHTTPClientService() {
1538
-		return $this->query('HttpClientService');
1539
-	}
1540
-
1541
-	/**
1542
-	 * Create a new event source
1543
-	 *
1544
-	 * @return \OCP\IEventSource
1545
-	 */
1546
-	public function createEventSource() {
1547
-		return new \OC_EventSource();
1548
-	}
1549
-
1550
-	/**
1551
-	 * Get the active event logger
1552
-	 *
1553
-	 * The returned logger only logs data when debug mode is enabled
1554
-	 *
1555
-	 * @return \OCP\Diagnostics\IEventLogger
1556
-	 */
1557
-	public function getEventLogger() {
1558
-		return $this->query('EventLogger');
1559
-	}
1560
-
1561
-	/**
1562
-	 * Get the active query logger
1563
-	 *
1564
-	 * The returned logger only logs data when debug mode is enabled
1565
-	 *
1566
-	 * @return \OCP\Diagnostics\IQueryLogger
1567
-	 */
1568
-	public function getQueryLogger() {
1569
-		return $this->query('QueryLogger');
1570
-	}
1571
-
1572
-	/**
1573
-	 * Get the manager for temporary files and folders
1574
-	 *
1575
-	 * @return \OCP\ITempManager
1576
-	 */
1577
-	public function getTempManager() {
1578
-		return $this->query('TempManager');
1579
-	}
1580
-
1581
-	/**
1582
-	 * Get the app manager
1583
-	 *
1584
-	 * @return \OCP\App\IAppManager
1585
-	 */
1586
-	public function getAppManager() {
1587
-		return $this->query('AppManager');
1588
-	}
1589
-
1590
-	/**
1591
-	 * Creates a new mailer
1592
-	 *
1593
-	 * @return \OCP\Mail\IMailer
1594
-	 */
1595
-	public function getMailer() {
1596
-		return $this->query('Mailer');
1597
-	}
1598
-
1599
-	/**
1600
-	 * Get the webroot
1601
-	 *
1602
-	 * @return string
1603
-	 */
1604
-	public function getWebRoot() {
1605
-		return $this->webRoot;
1606
-	}
1607
-
1608
-	/**
1609
-	 * @return \OC\OCSClient
1610
-	 */
1611
-	public function getOcsClient() {
1612
-		return $this->query('OcsClient');
1613
-	}
1614
-
1615
-	/**
1616
-	 * @return \OCP\IDateTimeZone
1617
-	 */
1618
-	public function getDateTimeZone() {
1619
-		return $this->query('DateTimeZone');
1620
-	}
1621
-
1622
-	/**
1623
-	 * @return \OCP\IDateTimeFormatter
1624
-	 */
1625
-	public function getDateTimeFormatter() {
1626
-		return $this->query('DateTimeFormatter');
1627
-	}
1628
-
1629
-	/**
1630
-	 * @return \OCP\Files\Config\IMountProviderCollection
1631
-	 */
1632
-	public function getMountProviderCollection() {
1633
-		return $this->query('MountConfigManager');
1634
-	}
1635
-
1636
-	/**
1637
-	 * Get the IniWrapper
1638
-	 *
1639
-	 * @return IniGetWrapper
1640
-	 */
1641
-	public function getIniWrapper() {
1642
-		return $this->query('IniWrapper');
1643
-	}
1644
-
1645
-	/**
1646
-	 * @return \OCP\Command\IBus
1647
-	 */
1648
-	public function getCommandBus() {
1649
-		return $this->query('AsyncCommandBus');
1650
-	}
1651
-
1652
-	/**
1653
-	 * Get the trusted domain helper
1654
-	 *
1655
-	 * @return TrustedDomainHelper
1656
-	 */
1657
-	public function getTrustedDomainHelper() {
1658
-		return $this->query('TrustedDomainHelper');
1659
-	}
1660
-
1661
-	/**
1662
-	 * Get the locking provider
1663
-	 *
1664
-	 * @return \OCP\Lock\ILockingProvider
1665
-	 * @since 8.1.0
1666
-	 */
1667
-	public function getLockingProvider() {
1668
-		return $this->query('LockingProvider');
1669
-	}
1670
-
1671
-	/**
1672
-	 * @return \OCP\Files\Mount\IMountManager
1673
-	 **/
1674
-	function getMountManager() {
1675
-		return $this->query('MountManager');
1676
-	}
1677
-
1678
-	/** @return \OCP\Files\Config\IUserMountCache */
1679
-	function getUserMountCache() {
1680
-		return $this->query('UserMountCache');
1681
-	}
1682
-
1683
-	/**
1684
-	 * Get the MimeTypeDetector
1685
-	 *
1686
-	 * @return \OCP\Files\IMimeTypeDetector
1687
-	 */
1688
-	public function getMimeTypeDetector() {
1689
-		return $this->query('MimeTypeDetector');
1690
-	}
1691
-
1692
-	/**
1693
-	 * Get the MimeTypeLoader
1694
-	 *
1695
-	 * @return \OCP\Files\IMimeTypeLoader
1696
-	 */
1697
-	public function getMimeTypeLoader() {
1698
-		return $this->query('MimeTypeLoader');
1699
-	}
1700
-
1701
-	/**
1702
-	 * Get the manager of all the capabilities
1703
-	 *
1704
-	 * @return \OC\CapabilitiesManager
1705
-	 */
1706
-	public function getCapabilitiesManager() {
1707
-		return $this->query('CapabilitiesManager');
1708
-	}
1709
-
1710
-	/**
1711
-	 * Get the EventDispatcher
1712
-	 *
1713
-	 * @return EventDispatcherInterface
1714
-	 * @since 8.2.0
1715
-	 */
1716
-	public function getEventDispatcher() {
1717
-		return $this->query('EventDispatcher');
1718
-	}
1719
-
1720
-	/**
1721
-	 * Get the Notification Manager
1722
-	 *
1723
-	 * @return \OCP\Notification\IManager
1724
-	 * @since 8.2.0
1725
-	 */
1726
-	public function getNotificationManager() {
1727
-		return $this->query('NotificationManager');
1728
-	}
1729
-
1730
-	/**
1731
-	 * @return \OCP\Comments\ICommentsManager
1732
-	 */
1733
-	public function getCommentsManager() {
1734
-		return $this->query('CommentsManager');
1735
-	}
1736
-
1737
-	/**
1738
-	 * @return \OCA\Theming\ThemingDefaults
1739
-	 */
1740
-	public function getThemingDefaults() {
1741
-		return $this->query('ThemingDefaults');
1742
-	}
1743
-
1744
-	/**
1745
-	 * @return \OC\IntegrityCheck\Checker
1746
-	 */
1747
-	public function getIntegrityCodeChecker() {
1748
-		return $this->query('IntegrityCodeChecker');
1749
-	}
1750
-
1751
-	/**
1752
-	 * @return \OC\Session\CryptoWrapper
1753
-	 */
1754
-	public function getSessionCryptoWrapper() {
1755
-		return $this->query('CryptoWrapper');
1756
-	}
1757
-
1758
-	/**
1759
-	 * @return CsrfTokenManager
1760
-	 */
1761
-	public function getCsrfTokenManager() {
1762
-		return $this->query('CsrfTokenManager');
1763
-	}
1764
-
1765
-	/**
1766
-	 * @return Throttler
1767
-	 */
1768
-	public function getBruteForceThrottler() {
1769
-		return $this->query('Throttler');
1770
-	}
1771
-
1772
-	/**
1773
-	 * @return IContentSecurityPolicyManager
1774
-	 */
1775
-	public function getContentSecurityPolicyManager() {
1776
-		return $this->query('ContentSecurityPolicyManager');
1777
-	}
1778
-
1779
-	/**
1780
-	 * @return ContentSecurityPolicyNonceManager
1781
-	 */
1782
-	public function getContentSecurityPolicyNonceManager() {
1783
-		return $this->query('ContentSecurityPolicyNonceManager');
1784
-	}
1785
-
1786
-	/**
1787
-	 * Not a public API as of 8.2, wait for 9.0
1788
-	 *
1789
-	 * @return \OCA\Files_External\Service\BackendService
1790
-	 */
1791
-	public function getStoragesBackendService() {
1792
-		return $this->query('OCA\\Files_External\\Service\\BackendService');
1793
-	}
1794
-
1795
-	/**
1796
-	 * Not a public API as of 8.2, wait for 9.0
1797
-	 *
1798
-	 * @return \OCA\Files_External\Service\GlobalStoragesService
1799
-	 */
1800
-	public function getGlobalStoragesService() {
1801
-		return $this->query('OCA\\Files_External\\Service\\GlobalStoragesService');
1802
-	}
1803
-
1804
-	/**
1805
-	 * Not a public API as of 8.2, wait for 9.0
1806
-	 *
1807
-	 * @return \OCA\Files_External\Service\UserGlobalStoragesService
1808
-	 */
1809
-	public function getUserGlobalStoragesService() {
1810
-		return $this->query('OCA\\Files_External\\Service\\UserGlobalStoragesService');
1811
-	}
1812
-
1813
-	/**
1814
-	 * Not a public API as of 8.2, wait for 9.0
1815
-	 *
1816
-	 * @return \OCA\Files_External\Service\UserStoragesService
1817
-	 */
1818
-	public function getUserStoragesService() {
1819
-		return $this->query('OCA\\Files_External\\Service\\UserStoragesService');
1820
-	}
1821
-
1822
-	/**
1823
-	 * @return \OCP\Share\IManager
1824
-	 */
1825
-	public function getShareManager() {
1826
-		return $this->query('ShareManager');
1827
-	}
1828
-
1829
-	/**
1830
-	 * @return \OCP\Collaboration\Collaborators\ISearch
1831
-	 */
1832
-	public function getCollaboratorSearch() {
1833
-		return $this->query('CollaboratorSearch');
1834
-	}
1835
-
1836
-	/**
1837
-	 * @return \OCP\Collaboration\AutoComplete\IManager
1838
-	 */
1839
-	public function getAutoCompleteManager(){
1840
-		return $this->query(IManager::class);
1841
-	}
1842
-
1843
-	/**
1844
-	 * Returns the LDAP Provider
1845
-	 *
1846
-	 * @return \OCP\LDAP\ILDAPProvider
1847
-	 */
1848
-	public function getLDAPProvider() {
1849
-		return $this->query('LDAPProvider');
1850
-	}
1851
-
1852
-	/**
1853
-	 * @return \OCP\Settings\IManager
1854
-	 */
1855
-	public function getSettingsManager() {
1856
-		return $this->query('SettingsManager');
1857
-	}
1858
-
1859
-	/**
1860
-	 * @return \OCP\Files\IAppData
1861
-	 */
1862
-	public function getAppDataDir($app) {
1863
-		/** @var \OC\Files\AppData\Factory $factory */
1864
-		$factory = $this->query(\OC\Files\AppData\Factory::class);
1865
-		return $factory->get($app);
1866
-	}
1867
-
1868
-	/**
1869
-	 * @return \OCP\Lockdown\ILockdownManager
1870
-	 */
1871
-	public function getLockdownManager() {
1872
-		return $this->query('LockdownManager');
1873
-	}
1874
-
1875
-	/**
1876
-	 * @return \OCP\Federation\ICloudIdManager
1877
-	 */
1878
-	public function getCloudIdManager() {
1879
-		return $this->query(ICloudIdManager::class);
1880
-	}
899
+            $prefixes = \OC::$composerAutoloader->getPrefixesPsr4();
900
+            if (isset($prefixes['OCA\\Theming\\'])) {
901
+                $classExists = true;
902
+            } else {
903
+                $classExists = false;
904
+            }
905
+
906
+            if ($classExists && $c->getConfig()->getSystemValue('installed', false) && $c->getAppManager()->isInstalled('theming') && $c->getTrustedDomainHelper()->isTrustedDomain($c->getRequest()->getInsecureServerHost())) {
907
+                return new ThemingDefaults(
908
+                    $c->getConfig(),
909
+                    $c->getL10N('theming'),
910
+                    $c->getURLGenerator(),
911
+                    $c->getAppDataDir('theming'),
912
+                    $c->getMemCacheFactory(),
913
+                    new Util($c->getConfig(), $this->getAppManager(), $this->getAppDataDir('theming')),
914
+                    $this->getAppManager()
915
+                );
916
+            }
917
+            return new \OC_Defaults();
918
+        });
919
+        $this->registerService(SCSSCacher::class, function (Server $c) {
920
+            /** @var Factory $cacheFactory */
921
+            $cacheFactory = $c->query(Factory::class);
922
+            return new SCSSCacher(
923
+                $c->getLogger(),
924
+                $c->query(\OC\Files\AppData\Factory::class),
925
+                $c->getURLGenerator(),
926
+                $c->getConfig(),
927
+                $c->getThemingDefaults(),
928
+                \OC::$SERVERROOT,
929
+                $cacheFactory->create('SCSS')
930
+            );
931
+        });
932
+        $this->registerService(EventDispatcher::class, function () {
933
+            return new EventDispatcher();
934
+        });
935
+        $this->registerAlias('EventDispatcher', EventDispatcher::class);
936
+        $this->registerAlias(EventDispatcherInterface::class, EventDispatcher::class);
937
+
938
+        $this->registerService('CryptoWrapper', function (Server $c) {
939
+            // FIXME: Instantiiated here due to cyclic dependency
940
+            $request = new Request(
941
+                [
942
+                    'get' => $_GET,
943
+                    'post' => $_POST,
944
+                    'files' => $_FILES,
945
+                    'server' => $_SERVER,
946
+                    'env' => $_ENV,
947
+                    'cookies' => $_COOKIE,
948
+                    'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
949
+                        ? $_SERVER['REQUEST_METHOD']
950
+                        : null,
951
+                ],
952
+                $c->getSecureRandom(),
953
+                $c->getConfig()
954
+            );
955
+
956
+            return new CryptoWrapper(
957
+                $c->getConfig(),
958
+                $c->getCrypto(),
959
+                $c->getSecureRandom(),
960
+                $request
961
+            );
962
+        });
963
+        $this->registerService('CsrfTokenManager', function (Server $c) {
964
+            $tokenGenerator = new CsrfTokenGenerator($c->getSecureRandom());
965
+
966
+            return new CsrfTokenManager(
967
+                $tokenGenerator,
968
+                $c->query(SessionStorage::class)
969
+            );
970
+        });
971
+        $this->registerService(SessionStorage::class, function (Server $c) {
972
+            return new SessionStorage($c->getSession());
973
+        });
974
+        $this->registerService(\OCP\Security\IContentSecurityPolicyManager::class, function (Server $c) {
975
+            return new ContentSecurityPolicyManager();
976
+        });
977
+        $this->registerAlias('ContentSecurityPolicyManager', \OCP\Security\IContentSecurityPolicyManager::class);
978
+
979
+        $this->registerService('ContentSecurityPolicyNonceManager', function (Server $c) {
980
+            return new ContentSecurityPolicyNonceManager(
981
+                $c->getCsrfTokenManager(),
982
+                $c->getRequest()
983
+            );
984
+        });
985
+
986
+        $this->registerService(\OCP\Share\IManager::class, function (Server $c) {
987
+            $config = $c->getConfig();
988
+            $factoryClass = $config->getSystemValue('sharing.managerFactory', '\OC\Share20\ProviderFactory');
989
+            /** @var \OCP\Share\IProviderFactory $factory */
990
+            $factory = new $factoryClass($this);
991
+
992
+            $manager = new \OC\Share20\Manager(
993
+                $c->getLogger(),
994
+                $c->getConfig(),
995
+                $c->getSecureRandom(),
996
+                $c->getHasher(),
997
+                $c->getMountManager(),
998
+                $c->getGroupManager(),
999
+                $c->getL10N('lib'),
1000
+                $c->getL10NFactory(),
1001
+                $factory,
1002
+                $c->getUserManager(),
1003
+                $c->getLazyRootFolder(),
1004
+                $c->getEventDispatcher(),
1005
+                $c->getMailer(),
1006
+                $c->getURLGenerator(),
1007
+                $c->getThemingDefaults()
1008
+            );
1009
+
1010
+            return $manager;
1011
+        });
1012
+        $this->registerAlias('ShareManager', \OCP\Share\IManager::class);
1013
+
1014
+        $this->registerService(\OCP\Collaboration\Collaborators\ISearch::class, function(Server $c) {
1015
+            $instance = new Collaboration\Collaborators\Search($c);
1016
+
1017
+            // register default plugins
1018
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_USER', 'class' => UserPlugin::class]);
1019
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_GROUP', 'class' => GroupPlugin::class]);
1020
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_EMAIL', 'class' => MailPlugin::class]);
1021
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_REMOTE', 'class' => RemotePlugin::class]);
1022
+
1023
+            return $instance;
1024
+        });
1025
+        $this->registerAlias('CollaboratorSearch', \OCP\Collaboration\Collaborators\ISearch::class);
1026
+
1027
+        $this->registerAlias(\OCP\Collaboration\AutoComplete\IManager::class, \OC\Collaboration\AutoComplete\Manager::class);
1028
+
1029
+        $this->registerService('SettingsManager', function (Server $c) {
1030
+            $manager = new \OC\Settings\Manager(
1031
+                $c->getLogger(),
1032
+                $c->getDatabaseConnection(),
1033
+                $c->getL10N('lib'),
1034
+                $c->getConfig(),
1035
+                $c->getEncryptionManager(),
1036
+                $c->getUserManager(),
1037
+                $c->getLockingProvider(),
1038
+                $c->getRequest(),
1039
+                new \OC\Settings\Mapper($c->getDatabaseConnection()),
1040
+                $c->getURLGenerator(),
1041
+                $c->query(AccountManager::class),
1042
+                $c->getGroupManager(),
1043
+                $c->getL10NFactory(),
1044
+                $c->getThemingDefaults(),
1045
+                $c->getAppManager()
1046
+            );
1047
+            return $manager;
1048
+        });
1049
+        $this->registerService(\OC\Files\AppData\Factory::class, function (Server $c) {
1050
+            return new \OC\Files\AppData\Factory(
1051
+                $c->getRootFolder(),
1052
+                $c->getSystemConfig()
1053
+            );
1054
+        });
1055
+
1056
+        $this->registerService('LockdownManager', function (Server $c) {
1057
+            return new LockdownManager(function () use ($c) {
1058
+                return $c->getSession();
1059
+            });
1060
+        });
1061
+
1062
+        $this->registerService(\OCP\OCS\IDiscoveryService::class, function (Server $c) {
1063
+            return new DiscoveryService($c->getMemCacheFactory(), $c->getHTTPClientService());
1064
+        });
1065
+
1066
+        $this->registerService(ICloudIdManager::class, function (Server $c) {
1067
+            return new CloudIdManager();
1068
+        });
1069
+
1070
+        /* To trick DI since we don't extend the DIContainer here */
1071
+        $this->registerService(CleanPreviewsBackgroundJob::class, function (Server $c) {
1072
+            return new CleanPreviewsBackgroundJob(
1073
+                $c->getRootFolder(),
1074
+                $c->getLogger(),
1075
+                $c->getJobList(),
1076
+                new TimeFactory()
1077
+            );
1078
+        });
1079
+
1080
+        $this->registerAlias(\OCP\AppFramework\Utility\IControllerMethodReflector::class, \OC\AppFramework\Utility\ControllerMethodReflector::class);
1081
+        $this->registerAlias('ControllerMethodReflector', \OCP\AppFramework\Utility\IControllerMethodReflector::class);
1082
+
1083
+        $this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
1084
+        $this->registerAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
1085
+
1086
+        $this->registerService(Defaults::class, function (Server $c) {
1087
+            return new Defaults(
1088
+                $c->getThemingDefaults()
1089
+            );
1090
+        });
1091
+        $this->registerAlias('Defaults', \OCP\Defaults::class);
1092
+
1093
+        $this->registerService(\OCP\ISession::class, function (SimpleContainer $c) {
1094
+            return $c->query(\OCP\IUserSession::class)->getSession();
1095
+        });
1096
+
1097
+        $this->registerService(IShareHelper::class, function (Server $c) {
1098
+            return new ShareHelper(
1099
+                $c->query(\OCP\Share\IManager::class)
1100
+            );
1101
+        });
1102
+
1103
+        $this->registerService(Installer::class, function(Server $c) {
1104
+            return new Installer(
1105
+                $c->getAppFetcher(),
1106
+                $c->getHTTPClientService(),
1107
+                $c->getTempManager(),
1108
+                $c->getLogger(),
1109
+                $c->getConfig()
1110
+            );
1111
+        });
1112
+    }
1113
+
1114
+    /**
1115
+     * @return \OCP\Calendar\IManager
1116
+     */
1117
+    public function getCalendarManager() {
1118
+        return $this->query('CalendarManager');
1119
+    }
1120
+
1121
+    /**
1122
+     * @return \OCP\Contacts\IManager
1123
+     */
1124
+    public function getContactsManager() {
1125
+        return $this->query('ContactsManager');
1126
+    }
1127
+
1128
+    /**
1129
+     * @return \OC\Encryption\Manager
1130
+     */
1131
+    public function getEncryptionManager() {
1132
+        return $this->query('EncryptionManager');
1133
+    }
1134
+
1135
+    /**
1136
+     * @return \OC\Encryption\File
1137
+     */
1138
+    public function getEncryptionFilesHelper() {
1139
+        return $this->query('EncryptionFileHelper');
1140
+    }
1141
+
1142
+    /**
1143
+     * @return \OCP\Encryption\Keys\IStorage
1144
+     */
1145
+    public function getEncryptionKeyStorage() {
1146
+        return $this->query('EncryptionKeyStorage');
1147
+    }
1148
+
1149
+    /**
1150
+     * The current request object holding all information about the request
1151
+     * currently being processed is returned from this method.
1152
+     * In case the current execution was not initiated by a web request null is returned
1153
+     *
1154
+     * @return \OCP\IRequest
1155
+     */
1156
+    public function getRequest() {
1157
+        return $this->query('Request');
1158
+    }
1159
+
1160
+    /**
1161
+     * Returns the preview manager which can create preview images for a given file
1162
+     *
1163
+     * @return \OCP\IPreview
1164
+     */
1165
+    public function getPreviewManager() {
1166
+        return $this->query('PreviewManager');
1167
+    }
1168
+
1169
+    /**
1170
+     * Returns the tag manager which can get and set tags for different object types
1171
+     *
1172
+     * @see \OCP\ITagManager::load()
1173
+     * @return \OCP\ITagManager
1174
+     */
1175
+    public function getTagManager() {
1176
+        return $this->query('TagManager');
1177
+    }
1178
+
1179
+    /**
1180
+     * Returns the system-tag manager
1181
+     *
1182
+     * @return \OCP\SystemTag\ISystemTagManager
1183
+     *
1184
+     * @since 9.0.0
1185
+     */
1186
+    public function getSystemTagManager() {
1187
+        return $this->query('SystemTagManager');
1188
+    }
1189
+
1190
+    /**
1191
+     * Returns the system-tag object mapper
1192
+     *
1193
+     * @return \OCP\SystemTag\ISystemTagObjectMapper
1194
+     *
1195
+     * @since 9.0.0
1196
+     */
1197
+    public function getSystemTagObjectMapper() {
1198
+        return $this->query('SystemTagObjectMapper');
1199
+    }
1200
+
1201
+    /**
1202
+     * Returns the avatar manager, used for avatar functionality
1203
+     *
1204
+     * @return \OCP\IAvatarManager
1205
+     */
1206
+    public function getAvatarManager() {
1207
+        return $this->query('AvatarManager');
1208
+    }
1209
+
1210
+    /**
1211
+     * Returns the root folder of ownCloud's data directory
1212
+     *
1213
+     * @return \OCP\Files\IRootFolder
1214
+     */
1215
+    public function getRootFolder() {
1216
+        return $this->query('LazyRootFolder');
1217
+    }
1218
+
1219
+    /**
1220
+     * Returns the root folder of ownCloud's data directory
1221
+     * This is the lazy variant so this gets only initialized once it
1222
+     * is actually used.
1223
+     *
1224
+     * @return \OCP\Files\IRootFolder
1225
+     */
1226
+    public function getLazyRootFolder() {
1227
+        return $this->query('LazyRootFolder');
1228
+    }
1229
+
1230
+    /**
1231
+     * Returns a view to ownCloud's files folder
1232
+     *
1233
+     * @param string $userId user ID
1234
+     * @return \OCP\Files\Folder|null
1235
+     */
1236
+    public function getUserFolder($userId = null) {
1237
+        if ($userId === null) {
1238
+            $user = $this->getUserSession()->getUser();
1239
+            if (!$user) {
1240
+                return null;
1241
+            }
1242
+            $userId = $user->getUID();
1243
+        }
1244
+        $root = $this->getRootFolder();
1245
+        return $root->getUserFolder($userId);
1246
+    }
1247
+
1248
+    /**
1249
+     * Returns an app-specific view in ownClouds data directory
1250
+     *
1251
+     * @return \OCP\Files\Folder
1252
+     * @deprecated since 9.2.0 use IAppData
1253
+     */
1254
+    public function getAppFolder() {
1255
+        $dir = '/' . \OC_App::getCurrentApp();
1256
+        $root = $this->getRootFolder();
1257
+        if (!$root->nodeExists($dir)) {
1258
+            $folder = $root->newFolder($dir);
1259
+        } else {
1260
+            $folder = $root->get($dir);
1261
+        }
1262
+        return $folder;
1263
+    }
1264
+
1265
+    /**
1266
+     * @return \OC\User\Manager
1267
+     */
1268
+    public function getUserManager() {
1269
+        return $this->query('UserManager');
1270
+    }
1271
+
1272
+    /**
1273
+     * @return \OC\Group\Manager
1274
+     */
1275
+    public function getGroupManager() {
1276
+        return $this->query('GroupManager');
1277
+    }
1278
+
1279
+    /**
1280
+     * @return \OC\User\Session
1281
+     */
1282
+    public function getUserSession() {
1283
+        return $this->query('UserSession');
1284
+    }
1285
+
1286
+    /**
1287
+     * @return \OCP\ISession
1288
+     */
1289
+    public function getSession() {
1290
+        return $this->query('UserSession')->getSession();
1291
+    }
1292
+
1293
+    /**
1294
+     * @param \OCP\ISession $session
1295
+     */
1296
+    public function setSession(\OCP\ISession $session) {
1297
+        $this->query(SessionStorage::class)->setSession($session);
1298
+        $this->query('UserSession')->setSession($session);
1299
+        $this->query(Store::class)->setSession($session);
1300
+    }
1301
+
1302
+    /**
1303
+     * @return \OC\Authentication\TwoFactorAuth\Manager
1304
+     */
1305
+    public function getTwoFactorAuthManager() {
1306
+        return $this->query('\OC\Authentication\TwoFactorAuth\Manager');
1307
+    }
1308
+
1309
+    /**
1310
+     * @return \OC\NavigationManager
1311
+     */
1312
+    public function getNavigationManager() {
1313
+        return $this->query('NavigationManager');
1314
+    }
1315
+
1316
+    /**
1317
+     * @return \OCP\IConfig
1318
+     */
1319
+    public function getConfig() {
1320
+        return $this->query('AllConfig');
1321
+    }
1322
+
1323
+    /**
1324
+     * @return \OC\SystemConfig
1325
+     */
1326
+    public function getSystemConfig() {
1327
+        return $this->query('SystemConfig');
1328
+    }
1329
+
1330
+    /**
1331
+     * Returns the app config manager
1332
+     *
1333
+     * @return \OCP\IAppConfig
1334
+     */
1335
+    public function getAppConfig() {
1336
+        return $this->query('AppConfig');
1337
+    }
1338
+
1339
+    /**
1340
+     * @return \OCP\L10N\IFactory
1341
+     */
1342
+    public function getL10NFactory() {
1343
+        return $this->query('L10NFactory');
1344
+    }
1345
+
1346
+    /**
1347
+     * get an L10N instance
1348
+     *
1349
+     * @param string $app appid
1350
+     * @param string $lang
1351
+     * @return IL10N
1352
+     */
1353
+    public function getL10N($app, $lang = null) {
1354
+        return $this->getL10NFactory()->get($app, $lang);
1355
+    }
1356
+
1357
+    /**
1358
+     * @return \OCP\IURLGenerator
1359
+     */
1360
+    public function getURLGenerator() {
1361
+        return $this->query('URLGenerator');
1362
+    }
1363
+
1364
+    /**
1365
+     * @return \OCP\IHelper
1366
+     */
1367
+    public function getHelper() {
1368
+        return $this->query('AppHelper');
1369
+    }
1370
+
1371
+    /**
1372
+     * @return AppFetcher
1373
+     */
1374
+    public function getAppFetcher() {
1375
+        return $this->query(AppFetcher::class);
1376
+    }
1377
+
1378
+    /**
1379
+     * Returns an ICache instance. Since 8.1.0 it returns a fake cache. Use
1380
+     * getMemCacheFactory() instead.
1381
+     *
1382
+     * @return \OCP\ICache
1383
+     * @deprecated 8.1.0 use getMemCacheFactory to obtain a proper cache
1384
+     */
1385
+    public function getCache() {
1386
+        return $this->query('UserCache');
1387
+    }
1388
+
1389
+    /**
1390
+     * Returns an \OCP\CacheFactory instance
1391
+     *
1392
+     * @return \OCP\ICacheFactory
1393
+     */
1394
+    public function getMemCacheFactory() {
1395
+        return $this->query('MemCacheFactory');
1396
+    }
1397
+
1398
+    /**
1399
+     * Returns an \OC\RedisFactory instance
1400
+     *
1401
+     * @return \OC\RedisFactory
1402
+     */
1403
+    public function getGetRedisFactory() {
1404
+        return $this->query('RedisFactory');
1405
+    }
1406
+
1407
+
1408
+    /**
1409
+     * Returns the current session
1410
+     *
1411
+     * @return \OCP\IDBConnection
1412
+     */
1413
+    public function getDatabaseConnection() {
1414
+        return $this->query('DatabaseConnection');
1415
+    }
1416
+
1417
+    /**
1418
+     * Returns the activity manager
1419
+     *
1420
+     * @return \OCP\Activity\IManager
1421
+     */
1422
+    public function getActivityManager() {
1423
+        return $this->query('ActivityManager');
1424
+    }
1425
+
1426
+    /**
1427
+     * Returns an job list for controlling background jobs
1428
+     *
1429
+     * @return \OCP\BackgroundJob\IJobList
1430
+     */
1431
+    public function getJobList() {
1432
+        return $this->query('JobList');
1433
+    }
1434
+
1435
+    /**
1436
+     * Returns a logger instance
1437
+     *
1438
+     * @return \OCP\ILogger
1439
+     */
1440
+    public function getLogger() {
1441
+        return $this->query('Logger');
1442
+    }
1443
+
1444
+    /**
1445
+     * Returns a router for generating and matching urls
1446
+     *
1447
+     * @return \OCP\Route\IRouter
1448
+     */
1449
+    public function getRouter() {
1450
+        return $this->query('Router');
1451
+    }
1452
+
1453
+    /**
1454
+     * Returns a search instance
1455
+     *
1456
+     * @return \OCP\ISearch
1457
+     */
1458
+    public function getSearch() {
1459
+        return $this->query('Search');
1460
+    }
1461
+
1462
+    /**
1463
+     * Returns a SecureRandom instance
1464
+     *
1465
+     * @return \OCP\Security\ISecureRandom
1466
+     */
1467
+    public function getSecureRandom() {
1468
+        return $this->query('SecureRandom');
1469
+    }
1470
+
1471
+    /**
1472
+     * Returns a Crypto instance
1473
+     *
1474
+     * @return \OCP\Security\ICrypto
1475
+     */
1476
+    public function getCrypto() {
1477
+        return $this->query('Crypto');
1478
+    }
1479
+
1480
+    /**
1481
+     * Returns a Hasher instance
1482
+     *
1483
+     * @return \OCP\Security\IHasher
1484
+     */
1485
+    public function getHasher() {
1486
+        return $this->query('Hasher');
1487
+    }
1488
+
1489
+    /**
1490
+     * Returns a CredentialsManager instance
1491
+     *
1492
+     * @return \OCP\Security\ICredentialsManager
1493
+     */
1494
+    public function getCredentialsManager() {
1495
+        return $this->query('CredentialsManager');
1496
+    }
1497
+
1498
+    /**
1499
+     * Returns an instance of the HTTP helper class
1500
+     *
1501
+     * @deprecated Use getHTTPClientService()
1502
+     * @return \OC\HTTPHelper
1503
+     */
1504
+    public function getHTTPHelper() {
1505
+        return $this->query('HTTPHelper');
1506
+    }
1507
+
1508
+    /**
1509
+     * Get the certificate manager for the user
1510
+     *
1511
+     * @param string $userId (optional) if not specified the current loggedin user is used, use null to get the system certificate manager
1512
+     * @return \OCP\ICertificateManager | null if $uid is null and no user is logged in
1513
+     */
1514
+    public function getCertificateManager($userId = '') {
1515
+        if ($userId === '') {
1516
+            $userSession = $this->getUserSession();
1517
+            $user = $userSession->getUser();
1518
+            if (is_null($user)) {
1519
+                return null;
1520
+            }
1521
+            $userId = $user->getUID();
1522
+        }
1523
+        return new CertificateManager(
1524
+            $userId,
1525
+            new View(),
1526
+            $this->getConfig(),
1527
+            $this->getLogger(),
1528
+            $this->getSecureRandom()
1529
+        );
1530
+    }
1531
+
1532
+    /**
1533
+     * Returns an instance of the HTTP client service
1534
+     *
1535
+     * @return \OCP\Http\Client\IClientService
1536
+     */
1537
+    public function getHTTPClientService() {
1538
+        return $this->query('HttpClientService');
1539
+    }
1540
+
1541
+    /**
1542
+     * Create a new event source
1543
+     *
1544
+     * @return \OCP\IEventSource
1545
+     */
1546
+    public function createEventSource() {
1547
+        return new \OC_EventSource();
1548
+    }
1549
+
1550
+    /**
1551
+     * Get the active event logger
1552
+     *
1553
+     * The returned logger only logs data when debug mode is enabled
1554
+     *
1555
+     * @return \OCP\Diagnostics\IEventLogger
1556
+     */
1557
+    public function getEventLogger() {
1558
+        return $this->query('EventLogger');
1559
+    }
1560
+
1561
+    /**
1562
+     * Get the active query logger
1563
+     *
1564
+     * The returned logger only logs data when debug mode is enabled
1565
+     *
1566
+     * @return \OCP\Diagnostics\IQueryLogger
1567
+     */
1568
+    public function getQueryLogger() {
1569
+        return $this->query('QueryLogger');
1570
+    }
1571
+
1572
+    /**
1573
+     * Get the manager for temporary files and folders
1574
+     *
1575
+     * @return \OCP\ITempManager
1576
+     */
1577
+    public function getTempManager() {
1578
+        return $this->query('TempManager');
1579
+    }
1580
+
1581
+    /**
1582
+     * Get the app manager
1583
+     *
1584
+     * @return \OCP\App\IAppManager
1585
+     */
1586
+    public function getAppManager() {
1587
+        return $this->query('AppManager');
1588
+    }
1589
+
1590
+    /**
1591
+     * Creates a new mailer
1592
+     *
1593
+     * @return \OCP\Mail\IMailer
1594
+     */
1595
+    public function getMailer() {
1596
+        return $this->query('Mailer');
1597
+    }
1598
+
1599
+    /**
1600
+     * Get the webroot
1601
+     *
1602
+     * @return string
1603
+     */
1604
+    public function getWebRoot() {
1605
+        return $this->webRoot;
1606
+    }
1607
+
1608
+    /**
1609
+     * @return \OC\OCSClient
1610
+     */
1611
+    public function getOcsClient() {
1612
+        return $this->query('OcsClient');
1613
+    }
1614
+
1615
+    /**
1616
+     * @return \OCP\IDateTimeZone
1617
+     */
1618
+    public function getDateTimeZone() {
1619
+        return $this->query('DateTimeZone');
1620
+    }
1621
+
1622
+    /**
1623
+     * @return \OCP\IDateTimeFormatter
1624
+     */
1625
+    public function getDateTimeFormatter() {
1626
+        return $this->query('DateTimeFormatter');
1627
+    }
1628
+
1629
+    /**
1630
+     * @return \OCP\Files\Config\IMountProviderCollection
1631
+     */
1632
+    public function getMountProviderCollection() {
1633
+        return $this->query('MountConfigManager');
1634
+    }
1635
+
1636
+    /**
1637
+     * Get the IniWrapper
1638
+     *
1639
+     * @return IniGetWrapper
1640
+     */
1641
+    public function getIniWrapper() {
1642
+        return $this->query('IniWrapper');
1643
+    }
1644
+
1645
+    /**
1646
+     * @return \OCP\Command\IBus
1647
+     */
1648
+    public function getCommandBus() {
1649
+        return $this->query('AsyncCommandBus');
1650
+    }
1651
+
1652
+    /**
1653
+     * Get the trusted domain helper
1654
+     *
1655
+     * @return TrustedDomainHelper
1656
+     */
1657
+    public function getTrustedDomainHelper() {
1658
+        return $this->query('TrustedDomainHelper');
1659
+    }
1660
+
1661
+    /**
1662
+     * Get the locking provider
1663
+     *
1664
+     * @return \OCP\Lock\ILockingProvider
1665
+     * @since 8.1.0
1666
+     */
1667
+    public function getLockingProvider() {
1668
+        return $this->query('LockingProvider');
1669
+    }
1670
+
1671
+    /**
1672
+     * @return \OCP\Files\Mount\IMountManager
1673
+     **/
1674
+    function getMountManager() {
1675
+        return $this->query('MountManager');
1676
+    }
1677
+
1678
+    /** @return \OCP\Files\Config\IUserMountCache */
1679
+    function getUserMountCache() {
1680
+        return $this->query('UserMountCache');
1681
+    }
1682
+
1683
+    /**
1684
+     * Get the MimeTypeDetector
1685
+     *
1686
+     * @return \OCP\Files\IMimeTypeDetector
1687
+     */
1688
+    public function getMimeTypeDetector() {
1689
+        return $this->query('MimeTypeDetector');
1690
+    }
1691
+
1692
+    /**
1693
+     * Get the MimeTypeLoader
1694
+     *
1695
+     * @return \OCP\Files\IMimeTypeLoader
1696
+     */
1697
+    public function getMimeTypeLoader() {
1698
+        return $this->query('MimeTypeLoader');
1699
+    }
1700
+
1701
+    /**
1702
+     * Get the manager of all the capabilities
1703
+     *
1704
+     * @return \OC\CapabilitiesManager
1705
+     */
1706
+    public function getCapabilitiesManager() {
1707
+        return $this->query('CapabilitiesManager');
1708
+    }
1709
+
1710
+    /**
1711
+     * Get the EventDispatcher
1712
+     *
1713
+     * @return EventDispatcherInterface
1714
+     * @since 8.2.0
1715
+     */
1716
+    public function getEventDispatcher() {
1717
+        return $this->query('EventDispatcher');
1718
+    }
1719
+
1720
+    /**
1721
+     * Get the Notification Manager
1722
+     *
1723
+     * @return \OCP\Notification\IManager
1724
+     * @since 8.2.0
1725
+     */
1726
+    public function getNotificationManager() {
1727
+        return $this->query('NotificationManager');
1728
+    }
1729
+
1730
+    /**
1731
+     * @return \OCP\Comments\ICommentsManager
1732
+     */
1733
+    public function getCommentsManager() {
1734
+        return $this->query('CommentsManager');
1735
+    }
1736
+
1737
+    /**
1738
+     * @return \OCA\Theming\ThemingDefaults
1739
+     */
1740
+    public function getThemingDefaults() {
1741
+        return $this->query('ThemingDefaults');
1742
+    }
1743
+
1744
+    /**
1745
+     * @return \OC\IntegrityCheck\Checker
1746
+     */
1747
+    public function getIntegrityCodeChecker() {
1748
+        return $this->query('IntegrityCodeChecker');
1749
+    }
1750
+
1751
+    /**
1752
+     * @return \OC\Session\CryptoWrapper
1753
+     */
1754
+    public function getSessionCryptoWrapper() {
1755
+        return $this->query('CryptoWrapper');
1756
+    }
1757
+
1758
+    /**
1759
+     * @return CsrfTokenManager
1760
+     */
1761
+    public function getCsrfTokenManager() {
1762
+        return $this->query('CsrfTokenManager');
1763
+    }
1764
+
1765
+    /**
1766
+     * @return Throttler
1767
+     */
1768
+    public function getBruteForceThrottler() {
1769
+        return $this->query('Throttler');
1770
+    }
1771
+
1772
+    /**
1773
+     * @return IContentSecurityPolicyManager
1774
+     */
1775
+    public function getContentSecurityPolicyManager() {
1776
+        return $this->query('ContentSecurityPolicyManager');
1777
+    }
1778
+
1779
+    /**
1780
+     * @return ContentSecurityPolicyNonceManager
1781
+     */
1782
+    public function getContentSecurityPolicyNonceManager() {
1783
+        return $this->query('ContentSecurityPolicyNonceManager');
1784
+    }
1785
+
1786
+    /**
1787
+     * Not a public API as of 8.2, wait for 9.0
1788
+     *
1789
+     * @return \OCA\Files_External\Service\BackendService
1790
+     */
1791
+    public function getStoragesBackendService() {
1792
+        return $this->query('OCA\\Files_External\\Service\\BackendService');
1793
+    }
1794
+
1795
+    /**
1796
+     * Not a public API as of 8.2, wait for 9.0
1797
+     *
1798
+     * @return \OCA\Files_External\Service\GlobalStoragesService
1799
+     */
1800
+    public function getGlobalStoragesService() {
1801
+        return $this->query('OCA\\Files_External\\Service\\GlobalStoragesService');
1802
+    }
1803
+
1804
+    /**
1805
+     * Not a public API as of 8.2, wait for 9.0
1806
+     *
1807
+     * @return \OCA\Files_External\Service\UserGlobalStoragesService
1808
+     */
1809
+    public function getUserGlobalStoragesService() {
1810
+        return $this->query('OCA\\Files_External\\Service\\UserGlobalStoragesService');
1811
+    }
1812
+
1813
+    /**
1814
+     * Not a public API as of 8.2, wait for 9.0
1815
+     *
1816
+     * @return \OCA\Files_External\Service\UserStoragesService
1817
+     */
1818
+    public function getUserStoragesService() {
1819
+        return $this->query('OCA\\Files_External\\Service\\UserStoragesService');
1820
+    }
1821
+
1822
+    /**
1823
+     * @return \OCP\Share\IManager
1824
+     */
1825
+    public function getShareManager() {
1826
+        return $this->query('ShareManager');
1827
+    }
1828
+
1829
+    /**
1830
+     * @return \OCP\Collaboration\Collaborators\ISearch
1831
+     */
1832
+    public function getCollaboratorSearch() {
1833
+        return $this->query('CollaboratorSearch');
1834
+    }
1835
+
1836
+    /**
1837
+     * @return \OCP\Collaboration\AutoComplete\IManager
1838
+     */
1839
+    public function getAutoCompleteManager(){
1840
+        return $this->query(IManager::class);
1841
+    }
1842
+
1843
+    /**
1844
+     * Returns the LDAP Provider
1845
+     *
1846
+     * @return \OCP\LDAP\ILDAPProvider
1847
+     */
1848
+    public function getLDAPProvider() {
1849
+        return $this->query('LDAPProvider');
1850
+    }
1851
+
1852
+    /**
1853
+     * @return \OCP\Settings\IManager
1854
+     */
1855
+    public function getSettingsManager() {
1856
+        return $this->query('SettingsManager');
1857
+    }
1858
+
1859
+    /**
1860
+     * @return \OCP\Files\IAppData
1861
+     */
1862
+    public function getAppDataDir($app) {
1863
+        /** @var \OC\Files\AppData\Factory $factory */
1864
+        $factory = $this->query(\OC\Files\AppData\Factory::class);
1865
+        return $factory->get($app);
1866
+    }
1867
+
1868
+    /**
1869
+     * @return \OCP\Lockdown\ILockdownManager
1870
+     */
1871
+    public function getLockdownManager() {
1872
+        return $this->query('LockdownManager');
1873
+    }
1874
+
1875
+    /**
1876
+     * @return \OCP\Federation\ICloudIdManager
1877
+     */
1878
+    public function getCloudIdManager() {
1879
+        return $this->query(ICloudIdManager::class);
1880
+    }
1881 1881
 }
Please login to merge, or discard this patch.
lib/private/Installer.php 2 patches
Indentation   +542 added lines, -542 removed lines patch added patch discarded remove patch
@@ -57,546 +57,546 @@
 block discarded – undo
57 57
  * This class provides the functionality needed to install, update and remove apps
58 58
  */
59 59
 class Installer {
60
-	/** @var AppFetcher */
61
-	private $appFetcher;
62
-	/** @var IClientService */
63
-	private $clientService;
64
-	/** @var ITempManager */
65
-	private $tempManager;
66
-	/** @var ILogger */
67
-	private $logger;
68
-	/** @var IConfig */
69
-	private $config;
70
-	/** @var array - for caching the result of app fetcher */
71
-	private $apps = null;
72
-	/** @var bool|null - for caching the result of the ready status */
73
-	private $isInstanceReadyForUpdates = null;
74
-
75
-	/**
76
-	 * @param AppFetcher $appFetcher
77
-	 * @param IClientService $clientService
78
-	 * @param ITempManager $tempManager
79
-	 * @param ILogger $logger
80
-	 * @param IConfig $config
81
-	 */
82
-	public function __construct(AppFetcher $appFetcher,
83
-								IClientService $clientService,
84
-								ITempManager $tempManager,
85
-								ILogger $logger,
86
-								IConfig $config) {
87
-		$this->appFetcher = $appFetcher;
88
-		$this->clientService = $clientService;
89
-		$this->tempManager = $tempManager;
90
-		$this->logger = $logger;
91
-		$this->config = $config;
92
-	}
93
-
94
-	/**
95
-	 * Installs an app that is located in one of the app folders already
96
-	 *
97
-	 * @param string $appId App to install
98
-	 * @throws \Exception
99
-	 * @return string app ID
100
-	 */
101
-	public function installApp($appId) {
102
-		$app = \OC_App::findAppInDirectories($appId);
103
-		if($app === false) {
104
-			throw new \Exception('App not found in any app directory');
105
-		}
106
-
107
-		$basedir = $app['path'].'/'.$appId;
108
-		$info = OC_App::getAppInfo($basedir.'/appinfo/info.xml', true);
109
-
110
-		$l = \OC::$server->getL10N('core');
111
-
112
-		if(!is_array($info)) {
113
-			throw new \Exception(
114
-				$l->t('App "%s" cannot be installed because appinfo file cannot be read.',
115
-					[$info['name']]
116
-				)
117
-			);
118
-		}
119
-
120
-		$version = \OCP\Util::getVersion();
121
-		if (!\OC_App::isAppCompatible($version, $info)) {
122
-			throw new \Exception(
123
-				// TODO $l
124
-				$l->t('App "%s" cannot be installed because it is not compatible with this version of the server.',
125
-					[$info['name']]
126
-				)
127
-			);
128
-		}
129
-
130
-		// check for required dependencies
131
-		\OC_App::checkAppDependencies($this->config, $l, $info);
132
-		\OC_App::registerAutoloading($appId, $basedir);
133
-
134
-		//install the database
135
-		if(is_file($basedir.'/appinfo/database.xml')) {
136
-			if (\OC::$server->getAppConfig()->getValue($info['id'], 'installed_version') === null) {
137
-				OC_DB::createDbFromStructure($basedir.'/appinfo/database.xml');
138
-			} else {
139
-				OC_DB::updateDbFromStructure($basedir.'/appinfo/database.xml');
140
-			}
141
-		} else {
142
-			$ms = new \OC\DB\MigrationService($info['id'], \OC::$server->getDatabaseConnection());
143
-			$ms->migrate();
144
-		}
145
-
146
-		\OC_App::setupBackgroundJobs($info['background-jobs']);
147
-		if(isset($info['settings']) && is_array($info['settings'])) {
148
-			\OC::$server->getSettingsManager()->setupSettings($info['settings']);
149
-		}
150
-
151
-		//run appinfo/install.php
152
-		if((!isset($data['noinstall']) or $data['noinstall']==false)) {
153
-			self::includeAppScript($basedir . '/appinfo/install.php');
154
-		}
155
-
156
-		$appData = OC_App::getAppInfo($appId);
157
-		OC_App::executeRepairSteps($appId, $appData['repair-steps']['install']);
158
-
159
-		//set the installed version
160
-		\OC::$server->getConfig()->setAppValue($info['id'], 'installed_version', OC_App::getAppVersion($info['id'], false));
161
-		\OC::$server->getConfig()->setAppValue($info['id'], 'enabled', 'no');
162
-
163
-		//set remote/public handlers
164
-		foreach($info['remote'] as $name=>$path) {
165
-			\OC::$server->getConfig()->setAppValue('core', 'remote_'.$name, $info['id'].'/'.$path);
166
-		}
167
-		foreach($info['public'] as $name=>$path) {
168
-			\OC::$server->getConfig()->setAppValue('core', 'public_'.$name, $info['id'].'/'.$path);
169
-		}
170
-
171
-		OC_App::setAppTypes($info['id']);
172
-
173
-		return $info['id'];
174
-	}
175
-
176
-	/**
177
-	 * @brief checks whether or not an app is installed
178
-	 * @param string $app app
179
-	 * @returns bool
180
-	 *
181
-	 * Checks whether or not an app is installed, i.e. registered in apps table.
182
-	 */
183
-	public static function isInstalled( $app ) {
184
-		return (\OC::$server->getConfig()->getAppValue($app, "installed_version", null) !== null);
185
-	}
186
-
187
-	/**
188
-	 * Updates the specified app from the appstore
189
-	 *
190
-	 * @param string $appId
191
-	 * @return bool
192
-	 */
193
-	public function updateAppstoreApp($appId) {
194
-		if($this->isUpdateAvailable($appId)) {
195
-			try {
196
-				$this->downloadApp($appId);
197
-			} catch (\Exception $e) {
198
-				$this->logger->error($e->getMessage(), ['app' => 'core']);
199
-				return false;
200
-			}
201
-			return OC_App::updateApp($appId);
202
-		}
203
-
204
-		return false;
205
-	}
206
-
207
-	/**
208
-	 * Downloads an app and puts it into the app directory
209
-	 *
210
-	 * @param string $appId
211
-	 *
212
-	 * @throws \Exception If the installation was not successful
213
-	 */
214
-	public function downloadApp($appId) {
215
-		$appId = strtolower($appId);
216
-
217
-		$apps = $this->appFetcher->get();
218
-		foreach($apps as $app) {
219
-			if($app['id'] === $appId) {
220
-				// Load the certificate
221
-				$certificate = new X509();
222
-				$certificate->loadCA(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crt'));
223
-				$loadedCertificate = $certificate->loadX509($app['certificate']);
224
-
225
-				// Verify if the certificate has been revoked
226
-				$crl = new X509();
227
-				$crl->loadCA(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crt'));
228
-				$crl->loadCRL(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crl'));
229
-				if($crl->validateSignature() !== true) {
230
-					throw new \Exception('Could not validate CRL signature');
231
-				}
232
-				$csn = $loadedCertificate['tbsCertificate']['serialNumber']->toString();
233
-				$revoked = $crl->getRevoked($csn);
234
-				if ($revoked !== false) {
235
-					throw new \Exception(
236
-						sprintf(
237
-							'Certificate "%s" has been revoked',
238
-							$csn
239
-						)
240
-					);
241
-				}
242
-
243
-				// Verify if the certificate has been issued by the Nextcloud Code Authority CA
244
-				if($certificate->validateSignature() !== true) {
245
-					throw new \Exception(
246
-						sprintf(
247
-							'App with id %s has a certificate not issued by a trusted Code Signing Authority',
248
-							$appId
249
-						)
250
-					);
251
-				}
252
-
253
-				// Verify if the certificate is issued for the requested app id
254
-				$certInfo = openssl_x509_parse($app['certificate']);
255
-				if(!isset($certInfo['subject']['CN'])) {
256
-					throw new \Exception(
257
-						sprintf(
258
-							'App with id %s has a cert with no CN',
259
-							$appId
260
-						)
261
-					);
262
-				}
263
-				if($certInfo['subject']['CN'] !== $appId) {
264
-					throw new \Exception(
265
-						sprintf(
266
-							'App with id %s has a cert issued to %s',
267
-							$appId,
268
-							$certInfo['subject']['CN']
269
-						)
270
-					);
271
-				}
272
-
273
-				// Download the release
274
-				$tempFile = $this->tempManager->getTemporaryFile('.tar.gz');
275
-				$client = $this->clientService->newClient();
276
-				$client->get($app['releases'][0]['download'], ['save_to' => $tempFile]);
277
-
278
-				// Check if the signature actually matches the downloaded content
279
-				$certificate = openssl_get_publickey($app['certificate']);
280
-				$verified = (bool)openssl_verify(file_get_contents($tempFile), base64_decode($app['releases'][0]['signature']), $certificate, OPENSSL_ALGO_SHA512);
281
-				openssl_free_key($certificate);
282
-
283
-				if($verified === true) {
284
-					// Seems to match, let's proceed
285
-					$extractDir = $this->tempManager->getTemporaryFolder();
286
-					$archive = new TAR($tempFile);
287
-
288
-					if($archive) {
289
-						if (!$archive->extract($extractDir)) {
290
-							throw new \Exception(
291
-								sprintf(
292
-									'Could not extract app %s',
293
-									$appId
294
-								)
295
-							);
296
-						}
297
-						$allFiles = scandir($extractDir);
298
-						$folders = array_diff($allFiles, ['.', '..']);
299
-						$folders = array_values($folders);
300
-
301
-						if(count($folders) > 1) {
302
-							throw new \Exception(
303
-								sprintf(
304
-									'Extracted app %s has more than 1 folder',
305
-									$appId
306
-								)
307
-							);
308
-						}
309
-
310
-						// Check if appinfo/info.xml has the same app ID as well
311
-						$loadEntities = libxml_disable_entity_loader(false);
312
-						$xml = simplexml_load_file($extractDir . '/' . $folders[0] . '/appinfo/info.xml');
313
-						libxml_disable_entity_loader($loadEntities);
314
-						if((string)$xml->id !== $appId) {
315
-							throw new \Exception(
316
-								sprintf(
317
-									'App for id %s has a wrong app ID in info.xml: %s',
318
-									$appId,
319
-									(string)$xml->id
320
-								)
321
-							);
322
-						}
323
-
324
-						// Check if the version is lower than before
325
-						$currentVersion = OC_App::getAppVersion($appId);
326
-						$newVersion = (string)$xml->version;
327
-						if(version_compare($currentVersion, $newVersion) === 1) {
328
-							throw new \Exception(
329
-								sprintf(
330
-									'App for id %s has version %s and tried to update to lower version %s',
331
-									$appId,
332
-									$currentVersion,
333
-									$newVersion
334
-								)
335
-							);
336
-						}
337
-
338
-						$baseDir = OC_App::getInstallPath() . '/' . $appId;
339
-						// Remove old app with the ID if existent
340
-						OC_Helper::rmdirr($baseDir);
341
-						// Move to app folder
342
-						if(@mkdir($baseDir)) {
343
-							$extractDir .= '/' . $folders[0];
344
-							OC_Helper::copyr($extractDir, $baseDir);
345
-						}
346
-						OC_Helper::copyr($extractDir, $baseDir);
347
-						OC_Helper::rmdirr($extractDir);
348
-						return;
349
-					} else {
350
-						throw new \Exception(
351
-							sprintf(
352
-								'Could not extract app with ID %s to %s',
353
-								$appId,
354
-								$extractDir
355
-							)
356
-						);
357
-					}
358
-				} else {
359
-					// Signature does not match
360
-					throw new \Exception(
361
-						sprintf(
362
-							'App with id %s has invalid signature',
363
-							$appId
364
-						)
365
-					);
366
-				}
367
-			}
368
-		}
369
-
370
-		throw new \Exception(
371
-			sprintf(
372
-				'Could not download app %s',
373
-				$appId
374
-			)
375
-		);
376
-	}
377
-
378
-	/**
379
-	 * Check if an update for the app is available
380
-	 *
381
-	 * @param string $appId
382
-	 * @return string|false false or the version number of the update
383
-	 */
384
-	public function isUpdateAvailable($appId) {
385
-		if ($this->isInstanceReadyForUpdates === null) {
386
-			$installPath = OC_App::getInstallPath();
387
-			if ($installPath === false || $installPath === null) {
388
-				$this->isInstanceReadyForUpdates = false;
389
-			} else {
390
-				$this->isInstanceReadyForUpdates = true;
391
-			}
392
-		}
393
-
394
-		if ($this->isInstanceReadyForUpdates === false) {
395
-			return false;
396
-		}
397
-
398
-		if ($this->apps === null) {
399
-			$apps = $this->appFetcher->get();
400
-		}
401
-
402
-		foreach($apps as $app) {
403
-			if($app['id'] === $appId) {
404
-				$currentVersion = OC_App::getAppVersion($appId);
405
-				$newestVersion = $app['releases'][0]['version'];
406
-				if (version_compare($newestVersion, $currentVersion, '>')) {
407
-					return $newestVersion;
408
-				} else {
409
-					return false;
410
-				}
411
-			}
412
-		}
413
-
414
-		return false;
415
-	}
416
-
417
-	/**
418
-	 * Check if app is already downloaded
419
-	 * @param string $name name of the application to remove
420
-	 * @return boolean
421
-	 *
422
-	 * The function will check if the app is already downloaded in the apps repository
423
-	 */
424
-	public function isDownloaded($name) {
425
-		foreach(\OC::$APPSROOTS as $dir) {
426
-			$dirToTest  = $dir['path'];
427
-			$dirToTest .= '/';
428
-			$dirToTest .= $name;
429
-			$dirToTest .= '/';
430
-
431
-			if (is_dir($dirToTest)) {
432
-				return true;
433
-			}
434
-		}
435
-
436
-		return false;
437
-	}
438
-
439
-	/**
440
-	 * Removes an app
441
-	 * @param string $appId ID of the application to remove
442
-	 * @return boolean
443
-	 *
444
-	 *
445
-	 * This function works as follows
446
-	 *   -# call uninstall repair steps
447
-	 *   -# removing the files
448
-	 *
449
-	 * The function will not delete preferences, tables and the configuration,
450
-	 * this has to be done by the function oc_app_uninstall().
451
-	 */
452
-	public function removeApp($appId) {
453
-		if($this->isDownloaded( $appId )) {
454
-			$appDir = OC_App::getInstallPath() . '/' . $appId;
455
-			OC_Helper::rmdirr($appDir);
456
-			return true;
457
-		}else{
458
-			\OCP\Util::writeLog('core', 'can\'t remove app '.$appId.'. It is not installed.', \OCP\Util::ERROR);
459
-
460
-			return false;
461
-		}
462
-
463
-	}
464
-
465
-	/**
466
-	 * Installs the app within the bundle and marks the bundle as installed
467
-	 *
468
-	 * @param Bundle $bundle
469
-	 * @throws \Exception If app could not get installed
470
-	 */
471
-	public function installAppBundle(Bundle $bundle) {
472
-		$appIds = $bundle->getAppIdentifiers();
473
-		foreach($appIds as $appId) {
474
-			if(!$this->isDownloaded($appId)) {
475
-				$this->downloadApp($appId);
476
-			}
477
-			$this->installApp($appId);
478
-			$app = new OC_App();
479
-			$app->enable($appId);
480
-		}
481
-		$bundles = json_decode($this->config->getAppValue('core', 'installed.bundles', json_encode([])), true);
482
-		$bundles[] = $bundle->getIdentifier();
483
-		$this->config->setAppValue('core', 'installed.bundles', json_encode($bundles));
484
-	}
485
-
486
-	/**
487
-	 * Installs shipped apps
488
-	 *
489
-	 * This function installs all apps found in the 'apps' directory that should be enabled by default;
490
-	 * @param bool $softErrors When updating we ignore errors and simply log them, better to have a
491
-	 *                         working ownCloud at the end instead of an aborted update.
492
-	 * @return array Array of error messages (appid => Exception)
493
-	 */
494
-	public static function installShippedApps($softErrors = false) {
495
-		$errors = [];
496
-		foreach(\OC::$APPSROOTS as $app_dir) {
497
-			if($dir = opendir( $app_dir['path'] )) {
498
-				while( false !== ( $filename = readdir( $dir ))) {
499
-					if( substr( $filename, 0, 1 ) != '.' and is_dir($app_dir['path']."/$filename") ) {
500
-						if( file_exists( $app_dir['path']."/$filename/appinfo/info.xml" )) {
501
-							if(!Installer::isInstalled($filename)) {
502
-								$info=OC_App::getAppInfo($filename);
503
-								$enabled = isset($info['default_enable']);
504
-								if (($enabled || in_array($filename, \OC::$server->getAppManager()->getAlwaysEnabledApps()))
505
-									  && \OC::$server->getConfig()->getAppValue($filename, 'enabled') !== 'no') {
506
-									if ($softErrors) {
507
-										try {
508
-											Installer::installShippedApp($filename);
509
-										} catch (HintException $e) {
510
-											if ($e->getPrevious() instanceof TableExistsException) {
511
-												$errors[$filename] = $e;
512
-												continue;
513
-											}
514
-											throw $e;
515
-										}
516
-									} else {
517
-										Installer::installShippedApp($filename);
518
-									}
519
-									\OC::$server->getConfig()->setAppValue($filename, 'enabled', 'yes');
520
-								}
521
-							}
522
-						}
523
-					}
524
-				}
525
-				closedir( $dir );
526
-			}
527
-		}
528
-
529
-		return $errors;
530
-	}
531
-
532
-	/**
533
-	 * install an app already placed in the app folder
534
-	 * @param string $app id of the app to install
535
-	 * @return integer
536
-	 */
537
-	public static function installShippedApp($app) {
538
-		//install the database
539
-		$appPath = OC_App::getAppPath($app);
540
-		\OC_App::registerAutoloading($app, $appPath);
541
-
542
-		if(is_file("$appPath/appinfo/database.xml")) {
543
-			try {
544
-				OC_DB::createDbFromStructure("$appPath/appinfo/database.xml");
545
-			} catch (TableExistsException $e) {
546
-				throw new HintException(
547
-					'Failed to enable app ' . $app,
548
-					'Please ask for help via one of our <a href="https://nextcloud.com/support/" target="_blank" rel="noreferrer noopener">support channels</a>.',
549
-					0, $e
550
-				);
551
-			}
552
-		} else {
553
-			$ms = new \OC\DB\MigrationService($app, \OC::$server->getDatabaseConnection());
554
-			$ms->migrate();
555
-		}
556
-
557
-		//run appinfo/install.php
558
-		self::includeAppScript("$appPath/appinfo/install.php");
559
-
560
-		$info = OC_App::getAppInfo($app);
561
-		if (is_null($info)) {
562
-			return false;
563
-		}
564
-		\OC_App::setupBackgroundJobs($info['background-jobs']);
565
-
566
-		OC_App::executeRepairSteps($app, $info['repair-steps']['install']);
567
-
568
-		$config = \OC::$server->getConfig();
569
-
570
-		$config->setAppValue($app, 'installed_version', OC_App::getAppVersion($app));
571
-		if (array_key_exists('ocsid', $info)) {
572
-			$config->setAppValue($app, 'ocsid', $info['ocsid']);
573
-		}
574
-
575
-		//set remote/public handlers
576
-		foreach($info['remote'] as $name=>$path) {
577
-			$config->setAppValue('core', 'remote_'.$name, $app.'/'.$path);
578
-		}
579
-		foreach($info['public'] as $name=>$path) {
580
-			$config->setAppValue('core', 'public_'.$name, $app.'/'.$path);
581
-		}
582
-
583
-		OC_App::setAppTypes($info['id']);
584
-
585
-		if(isset($info['settings']) && is_array($info['settings'])) {
586
-			// requires that autoloading was registered for the app,
587
-			// as happens before running the install.php some lines above
588
-			\OC::$server->getSettingsManager()->setupSettings($info['settings']);
589
-		}
590
-
591
-		return $info['id'];
592
-	}
593
-
594
-	/**
595
-	 * @param string $script
596
-	 */
597
-	private static function includeAppScript($script) {
598
-		if ( file_exists($script) ){
599
-			include $script;
600
-		}
601
-	}
60
+    /** @var AppFetcher */
61
+    private $appFetcher;
62
+    /** @var IClientService */
63
+    private $clientService;
64
+    /** @var ITempManager */
65
+    private $tempManager;
66
+    /** @var ILogger */
67
+    private $logger;
68
+    /** @var IConfig */
69
+    private $config;
70
+    /** @var array - for caching the result of app fetcher */
71
+    private $apps = null;
72
+    /** @var bool|null - for caching the result of the ready status */
73
+    private $isInstanceReadyForUpdates = null;
74
+
75
+    /**
76
+     * @param AppFetcher $appFetcher
77
+     * @param IClientService $clientService
78
+     * @param ITempManager $tempManager
79
+     * @param ILogger $logger
80
+     * @param IConfig $config
81
+     */
82
+    public function __construct(AppFetcher $appFetcher,
83
+                                IClientService $clientService,
84
+                                ITempManager $tempManager,
85
+                                ILogger $logger,
86
+                                IConfig $config) {
87
+        $this->appFetcher = $appFetcher;
88
+        $this->clientService = $clientService;
89
+        $this->tempManager = $tempManager;
90
+        $this->logger = $logger;
91
+        $this->config = $config;
92
+    }
93
+
94
+    /**
95
+     * Installs an app that is located in one of the app folders already
96
+     *
97
+     * @param string $appId App to install
98
+     * @throws \Exception
99
+     * @return string app ID
100
+     */
101
+    public function installApp($appId) {
102
+        $app = \OC_App::findAppInDirectories($appId);
103
+        if($app === false) {
104
+            throw new \Exception('App not found in any app directory');
105
+        }
106
+
107
+        $basedir = $app['path'].'/'.$appId;
108
+        $info = OC_App::getAppInfo($basedir.'/appinfo/info.xml', true);
109
+
110
+        $l = \OC::$server->getL10N('core');
111
+
112
+        if(!is_array($info)) {
113
+            throw new \Exception(
114
+                $l->t('App "%s" cannot be installed because appinfo file cannot be read.',
115
+                    [$info['name']]
116
+                )
117
+            );
118
+        }
119
+
120
+        $version = \OCP\Util::getVersion();
121
+        if (!\OC_App::isAppCompatible($version, $info)) {
122
+            throw new \Exception(
123
+                // TODO $l
124
+                $l->t('App "%s" cannot be installed because it is not compatible with this version of the server.',
125
+                    [$info['name']]
126
+                )
127
+            );
128
+        }
129
+
130
+        // check for required dependencies
131
+        \OC_App::checkAppDependencies($this->config, $l, $info);
132
+        \OC_App::registerAutoloading($appId, $basedir);
133
+
134
+        //install the database
135
+        if(is_file($basedir.'/appinfo/database.xml')) {
136
+            if (\OC::$server->getAppConfig()->getValue($info['id'], 'installed_version') === null) {
137
+                OC_DB::createDbFromStructure($basedir.'/appinfo/database.xml');
138
+            } else {
139
+                OC_DB::updateDbFromStructure($basedir.'/appinfo/database.xml');
140
+            }
141
+        } else {
142
+            $ms = new \OC\DB\MigrationService($info['id'], \OC::$server->getDatabaseConnection());
143
+            $ms->migrate();
144
+        }
145
+
146
+        \OC_App::setupBackgroundJobs($info['background-jobs']);
147
+        if(isset($info['settings']) && is_array($info['settings'])) {
148
+            \OC::$server->getSettingsManager()->setupSettings($info['settings']);
149
+        }
150
+
151
+        //run appinfo/install.php
152
+        if((!isset($data['noinstall']) or $data['noinstall']==false)) {
153
+            self::includeAppScript($basedir . '/appinfo/install.php');
154
+        }
155
+
156
+        $appData = OC_App::getAppInfo($appId);
157
+        OC_App::executeRepairSteps($appId, $appData['repair-steps']['install']);
158
+
159
+        //set the installed version
160
+        \OC::$server->getConfig()->setAppValue($info['id'], 'installed_version', OC_App::getAppVersion($info['id'], false));
161
+        \OC::$server->getConfig()->setAppValue($info['id'], 'enabled', 'no');
162
+
163
+        //set remote/public handlers
164
+        foreach($info['remote'] as $name=>$path) {
165
+            \OC::$server->getConfig()->setAppValue('core', 'remote_'.$name, $info['id'].'/'.$path);
166
+        }
167
+        foreach($info['public'] as $name=>$path) {
168
+            \OC::$server->getConfig()->setAppValue('core', 'public_'.$name, $info['id'].'/'.$path);
169
+        }
170
+
171
+        OC_App::setAppTypes($info['id']);
172
+
173
+        return $info['id'];
174
+    }
175
+
176
+    /**
177
+     * @brief checks whether or not an app is installed
178
+     * @param string $app app
179
+     * @returns bool
180
+     *
181
+     * Checks whether or not an app is installed, i.e. registered in apps table.
182
+     */
183
+    public static function isInstalled( $app ) {
184
+        return (\OC::$server->getConfig()->getAppValue($app, "installed_version", null) !== null);
185
+    }
186
+
187
+    /**
188
+     * Updates the specified app from the appstore
189
+     *
190
+     * @param string $appId
191
+     * @return bool
192
+     */
193
+    public function updateAppstoreApp($appId) {
194
+        if($this->isUpdateAvailable($appId)) {
195
+            try {
196
+                $this->downloadApp($appId);
197
+            } catch (\Exception $e) {
198
+                $this->logger->error($e->getMessage(), ['app' => 'core']);
199
+                return false;
200
+            }
201
+            return OC_App::updateApp($appId);
202
+        }
203
+
204
+        return false;
205
+    }
206
+
207
+    /**
208
+     * Downloads an app and puts it into the app directory
209
+     *
210
+     * @param string $appId
211
+     *
212
+     * @throws \Exception If the installation was not successful
213
+     */
214
+    public function downloadApp($appId) {
215
+        $appId = strtolower($appId);
216
+
217
+        $apps = $this->appFetcher->get();
218
+        foreach($apps as $app) {
219
+            if($app['id'] === $appId) {
220
+                // Load the certificate
221
+                $certificate = new X509();
222
+                $certificate->loadCA(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crt'));
223
+                $loadedCertificate = $certificate->loadX509($app['certificate']);
224
+
225
+                // Verify if the certificate has been revoked
226
+                $crl = new X509();
227
+                $crl->loadCA(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crt'));
228
+                $crl->loadCRL(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crl'));
229
+                if($crl->validateSignature() !== true) {
230
+                    throw new \Exception('Could not validate CRL signature');
231
+                }
232
+                $csn = $loadedCertificate['tbsCertificate']['serialNumber']->toString();
233
+                $revoked = $crl->getRevoked($csn);
234
+                if ($revoked !== false) {
235
+                    throw new \Exception(
236
+                        sprintf(
237
+                            'Certificate "%s" has been revoked',
238
+                            $csn
239
+                        )
240
+                    );
241
+                }
242
+
243
+                // Verify if the certificate has been issued by the Nextcloud Code Authority CA
244
+                if($certificate->validateSignature() !== true) {
245
+                    throw new \Exception(
246
+                        sprintf(
247
+                            'App with id %s has a certificate not issued by a trusted Code Signing Authority',
248
+                            $appId
249
+                        )
250
+                    );
251
+                }
252
+
253
+                // Verify if the certificate is issued for the requested app id
254
+                $certInfo = openssl_x509_parse($app['certificate']);
255
+                if(!isset($certInfo['subject']['CN'])) {
256
+                    throw new \Exception(
257
+                        sprintf(
258
+                            'App with id %s has a cert with no CN',
259
+                            $appId
260
+                        )
261
+                    );
262
+                }
263
+                if($certInfo['subject']['CN'] !== $appId) {
264
+                    throw new \Exception(
265
+                        sprintf(
266
+                            'App with id %s has a cert issued to %s',
267
+                            $appId,
268
+                            $certInfo['subject']['CN']
269
+                        )
270
+                    );
271
+                }
272
+
273
+                // Download the release
274
+                $tempFile = $this->tempManager->getTemporaryFile('.tar.gz');
275
+                $client = $this->clientService->newClient();
276
+                $client->get($app['releases'][0]['download'], ['save_to' => $tempFile]);
277
+
278
+                // Check if the signature actually matches the downloaded content
279
+                $certificate = openssl_get_publickey($app['certificate']);
280
+                $verified = (bool)openssl_verify(file_get_contents($tempFile), base64_decode($app['releases'][0]['signature']), $certificate, OPENSSL_ALGO_SHA512);
281
+                openssl_free_key($certificate);
282
+
283
+                if($verified === true) {
284
+                    // Seems to match, let's proceed
285
+                    $extractDir = $this->tempManager->getTemporaryFolder();
286
+                    $archive = new TAR($tempFile);
287
+
288
+                    if($archive) {
289
+                        if (!$archive->extract($extractDir)) {
290
+                            throw new \Exception(
291
+                                sprintf(
292
+                                    'Could not extract app %s',
293
+                                    $appId
294
+                                )
295
+                            );
296
+                        }
297
+                        $allFiles = scandir($extractDir);
298
+                        $folders = array_diff($allFiles, ['.', '..']);
299
+                        $folders = array_values($folders);
300
+
301
+                        if(count($folders) > 1) {
302
+                            throw new \Exception(
303
+                                sprintf(
304
+                                    'Extracted app %s has more than 1 folder',
305
+                                    $appId
306
+                                )
307
+                            );
308
+                        }
309
+
310
+                        // Check if appinfo/info.xml has the same app ID as well
311
+                        $loadEntities = libxml_disable_entity_loader(false);
312
+                        $xml = simplexml_load_file($extractDir . '/' . $folders[0] . '/appinfo/info.xml');
313
+                        libxml_disable_entity_loader($loadEntities);
314
+                        if((string)$xml->id !== $appId) {
315
+                            throw new \Exception(
316
+                                sprintf(
317
+                                    'App for id %s has a wrong app ID in info.xml: %s',
318
+                                    $appId,
319
+                                    (string)$xml->id
320
+                                )
321
+                            );
322
+                        }
323
+
324
+                        // Check if the version is lower than before
325
+                        $currentVersion = OC_App::getAppVersion($appId);
326
+                        $newVersion = (string)$xml->version;
327
+                        if(version_compare($currentVersion, $newVersion) === 1) {
328
+                            throw new \Exception(
329
+                                sprintf(
330
+                                    'App for id %s has version %s and tried to update to lower version %s',
331
+                                    $appId,
332
+                                    $currentVersion,
333
+                                    $newVersion
334
+                                )
335
+                            );
336
+                        }
337
+
338
+                        $baseDir = OC_App::getInstallPath() . '/' . $appId;
339
+                        // Remove old app with the ID if existent
340
+                        OC_Helper::rmdirr($baseDir);
341
+                        // Move to app folder
342
+                        if(@mkdir($baseDir)) {
343
+                            $extractDir .= '/' . $folders[0];
344
+                            OC_Helper::copyr($extractDir, $baseDir);
345
+                        }
346
+                        OC_Helper::copyr($extractDir, $baseDir);
347
+                        OC_Helper::rmdirr($extractDir);
348
+                        return;
349
+                    } else {
350
+                        throw new \Exception(
351
+                            sprintf(
352
+                                'Could not extract app with ID %s to %s',
353
+                                $appId,
354
+                                $extractDir
355
+                            )
356
+                        );
357
+                    }
358
+                } else {
359
+                    // Signature does not match
360
+                    throw new \Exception(
361
+                        sprintf(
362
+                            'App with id %s has invalid signature',
363
+                            $appId
364
+                        )
365
+                    );
366
+                }
367
+            }
368
+        }
369
+
370
+        throw new \Exception(
371
+            sprintf(
372
+                'Could not download app %s',
373
+                $appId
374
+            )
375
+        );
376
+    }
377
+
378
+    /**
379
+     * Check if an update for the app is available
380
+     *
381
+     * @param string $appId
382
+     * @return string|false false or the version number of the update
383
+     */
384
+    public function isUpdateAvailable($appId) {
385
+        if ($this->isInstanceReadyForUpdates === null) {
386
+            $installPath = OC_App::getInstallPath();
387
+            if ($installPath === false || $installPath === null) {
388
+                $this->isInstanceReadyForUpdates = false;
389
+            } else {
390
+                $this->isInstanceReadyForUpdates = true;
391
+            }
392
+        }
393
+
394
+        if ($this->isInstanceReadyForUpdates === false) {
395
+            return false;
396
+        }
397
+
398
+        if ($this->apps === null) {
399
+            $apps = $this->appFetcher->get();
400
+        }
401
+
402
+        foreach($apps as $app) {
403
+            if($app['id'] === $appId) {
404
+                $currentVersion = OC_App::getAppVersion($appId);
405
+                $newestVersion = $app['releases'][0]['version'];
406
+                if (version_compare($newestVersion, $currentVersion, '>')) {
407
+                    return $newestVersion;
408
+                } else {
409
+                    return false;
410
+                }
411
+            }
412
+        }
413
+
414
+        return false;
415
+    }
416
+
417
+    /**
418
+     * Check if app is already downloaded
419
+     * @param string $name name of the application to remove
420
+     * @return boolean
421
+     *
422
+     * The function will check if the app is already downloaded in the apps repository
423
+     */
424
+    public function isDownloaded($name) {
425
+        foreach(\OC::$APPSROOTS as $dir) {
426
+            $dirToTest  = $dir['path'];
427
+            $dirToTest .= '/';
428
+            $dirToTest .= $name;
429
+            $dirToTest .= '/';
430
+
431
+            if (is_dir($dirToTest)) {
432
+                return true;
433
+            }
434
+        }
435
+
436
+        return false;
437
+    }
438
+
439
+    /**
440
+     * Removes an app
441
+     * @param string $appId ID of the application to remove
442
+     * @return boolean
443
+     *
444
+     *
445
+     * This function works as follows
446
+     *   -# call uninstall repair steps
447
+     *   -# removing the files
448
+     *
449
+     * The function will not delete preferences, tables and the configuration,
450
+     * this has to be done by the function oc_app_uninstall().
451
+     */
452
+    public function removeApp($appId) {
453
+        if($this->isDownloaded( $appId )) {
454
+            $appDir = OC_App::getInstallPath() . '/' . $appId;
455
+            OC_Helper::rmdirr($appDir);
456
+            return true;
457
+        }else{
458
+            \OCP\Util::writeLog('core', 'can\'t remove app '.$appId.'. It is not installed.', \OCP\Util::ERROR);
459
+
460
+            return false;
461
+        }
462
+
463
+    }
464
+
465
+    /**
466
+     * Installs the app within the bundle and marks the bundle as installed
467
+     *
468
+     * @param Bundle $bundle
469
+     * @throws \Exception If app could not get installed
470
+     */
471
+    public function installAppBundle(Bundle $bundle) {
472
+        $appIds = $bundle->getAppIdentifiers();
473
+        foreach($appIds as $appId) {
474
+            if(!$this->isDownloaded($appId)) {
475
+                $this->downloadApp($appId);
476
+            }
477
+            $this->installApp($appId);
478
+            $app = new OC_App();
479
+            $app->enable($appId);
480
+        }
481
+        $bundles = json_decode($this->config->getAppValue('core', 'installed.bundles', json_encode([])), true);
482
+        $bundles[] = $bundle->getIdentifier();
483
+        $this->config->setAppValue('core', 'installed.bundles', json_encode($bundles));
484
+    }
485
+
486
+    /**
487
+     * Installs shipped apps
488
+     *
489
+     * This function installs all apps found in the 'apps' directory that should be enabled by default;
490
+     * @param bool $softErrors When updating we ignore errors and simply log them, better to have a
491
+     *                         working ownCloud at the end instead of an aborted update.
492
+     * @return array Array of error messages (appid => Exception)
493
+     */
494
+    public static function installShippedApps($softErrors = false) {
495
+        $errors = [];
496
+        foreach(\OC::$APPSROOTS as $app_dir) {
497
+            if($dir = opendir( $app_dir['path'] )) {
498
+                while( false !== ( $filename = readdir( $dir ))) {
499
+                    if( substr( $filename, 0, 1 ) != '.' and is_dir($app_dir['path']."/$filename") ) {
500
+                        if( file_exists( $app_dir['path']."/$filename/appinfo/info.xml" )) {
501
+                            if(!Installer::isInstalled($filename)) {
502
+                                $info=OC_App::getAppInfo($filename);
503
+                                $enabled = isset($info['default_enable']);
504
+                                if (($enabled || in_array($filename, \OC::$server->getAppManager()->getAlwaysEnabledApps()))
505
+                                      && \OC::$server->getConfig()->getAppValue($filename, 'enabled') !== 'no') {
506
+                                    if ($softErrors) {
507
+                                        try {
508
+                                            Installer::installShippedApp($filename);
509
+                                        } catch (HintException $e) {
510
+                                            if ($e->getPrevious() instanceof TableExistsException) {
511
+                                                $errors[$filename] = $e;
512
+                                                continue;
513
+                                            }
514
+                                            throw $e;
515
+                                        }
516
+                                    } else {
517
+                                        Installer::installShippedApp($filename);
518
+                                    }
519
+                                    \OC::$server->getConfig()->setAppValue($filename, 'enabled', 'yes');
520
+                                }
521
+                            }
522
+                        }
523
+                    }
524
+                }
525
+                closedir( $dir );
526
+            }
527
+        }
528
+
529
+        return $errors;
530
+    }
531
+
532
+    /**
533
+     * install an app already placed in the app folder
534
+     * @param string $app id of the app to install
535
+     * @return integer
536
+     */
537
+    public static function installShippedApp($app) {
538
+        //install the database
539
+        $appPath = OC_App::getAppPath($app);
540
+        \OC_App::registerAutoloading($app, $appPath);
541
+
542
+        if(is_file("$appPath/appinfo/database.xml")) {
543
+            try {
544
+                OC_DB::createDbFromStructure("$appPath/appinfo/database.xml");
545
+            } catch (TableExistsException $e) {
546
+                throw new HintException(
547
+                    'Failed to enable app ' . $app,
548
+                    'Please ask for help via one of our <a href="https://nextcloud.com/support/" target="_blank" rel="noreferrer noopener">support channels</a>.',
549
+                    0, $e
550
+                );
551
+            }
552
+        } else {
553
+            $ms = new \OC\DB\MigrationService($app, \OC::$server->getDatabaseConnection());
554
+            $ms->migrate();
555
+        }
556
+
557
+        //run appinfo/install.php
558
+        self::includeAppScript("$appPath/appinfo/install.php");
559
+
560
+        $info = OC_App::getAppInfo($app);
561
+        if (is_null($info)) {
562
+            return false;
563
+        }
564
+        \OC_App::setupBackgroundJobs($info['background-jobs']);
565
+
566
+        OC_App::executeRepairSteps($app, $info['repair-steps']['install']);
567
+
568
+        $config = \OC::$server->getConfig();
569
+
570
+        $config->setAppValue($app, 'installed_version', OC_App::getAppVersion($app));
571
+        if (array_key_exists('ocsid', $info)) {
572
+            $config->setAppValue($app, 'ocsid', $info['ocsid']);
573
+        }
574
+
575
+        //set remote/public handlers
576
+        foreach($info['remote'] as $name=>$path) {
577
+            $config->setAppValue('core', 'remote_'.$name, $app.'/'.$path);
578
+        }
579
+        foreach($info['public'] as $name=>$path) {
580
+            $config->setAppValue('core', 'public_'.$name, $app.'/'.$path);
581
+        }
582
+
583
+        OC_App::setAppTypes($info['id']);
584
+
585
+        if(isset($info['settings']) && is_array($info['settings'])) {
586
+            // requires that autoloading was registered for the app,
587
+            // as happens before running the install.php some lines above
588
+            \OC::$server->getSettingsManager()->setupSettings($info['settings']);
589
+        }
590
+
591
+        return $info['id'];
592
+    }
593
+
594
+    /**
595
+     * @param string $script
596
+     */
597
+    private static function includeAppScript($script) {
598
+        if ( file_exists($script) ){
599
+            include $script;
600
+        }
601
+    }
602 602
 }
Please login to merge, or discard this patch.
Spacing   +53 added lines, -53 removed lines patch added patch discarded remove patch
@@ -100,7 +100,7 @@  discard block
 block discarded – undo
100 100
 	 */
101 101
 	public function installApp($appId) {
102 102
 		$app = \OC_App::findAppInDirectories($appId);
103
-		if($app === false) {
103
+		if ($app === false) {
104 104
 			throw new \Exception('App not found in any app directory');
105 105
 		}
106 106
 
@@ -109,7 +109,7 @@  discard block
 block discarded – undo
109 109
 
110 110
 		$l = \OC::$server->getL10N('core');
111 111
 
112
-		if(!is_array($info)) {
112
+		if (!is_array($info)) {
113 113
 			throw new \Exception(
114 114
 				$l->t('App "%s" cannot be installed because appinfo file cannot be read.',
115 115
 					[$info['name']]
@@ -132,7 +132,7 @@  discard block
 block discarded – undo
132 132
 		\OC_App::registerAutoloading($appId, $basedir);
133 133
 
134 134
 		//install the database
135
-		if(is_file($basedir.'/appinfo/database.xml')) {
135
+		if (is_file($basedir.'/appinfo/database.xml')) {
136 136
 			if (\OC::$server->getAppConfig()->getValue($info['id'], 'installed_version') === null) {
137 137
 				OC_DB::createDbFromStructure($basedir.'/appinfo/database.xml');
138 138
 			} else {
@@ -144,13 +144,13 @@  discard block
 block discarded – undo
144 144
 		}
145 145
 
146 146
 		\OC_App::setupBackgroundJobs($info['background-jobs']);
147
-		if(isset($info['settings']) && is_array($info['settings'])) {
147
+		if (isset($info['settings']) && is_array($info['settings'])) {
148 148
 			\OC::$server->getSettingsManager()->setupSettings($info['settings']);
149 149
 		}
150 150
 
151 151
 		//run appinfo/install.php
152
-		if((!isset($data['noinstall']) or $data['noinstall']==false)) {
153
-			self::includeAppScript($basedir . '/appinfo/install.php');
152
+		if ((!isset($data['noinstall']) or $data['noinstall'] == false)) {
153
+			self::includeAppScript($basedir.'/appinfo/install.php');
154 154
 		}
155 155
 
156 156
 		$appData = OC_App::getAppInfo($appId);
@@ -161,10 +161,10 @@  discard block
 block discarded – undo
161 161
 		\OC::$server->getConfig()->setAppValue($info['id'], 'enabled', 'no');
162 162
 
163 163
 		//set remote/public handlers
164
-		foreach($info['remote'] as $name=>$path) {
164
+		foreach ($info['remote'] as $name=>$path) {
165 165
 			\OC::$server->getConfig()->setAppValue('core', 'remote_'.$name, $info['id'].'/'.$path);
166 166
 		}
167
-		foreach($info['public'] as $name=>$path) {
167
+		foreach ($info['public'] as $name=>$path) {
168 168
 			\OC::$server->getConfig()->setAppValue('core', 'public_'.$name, $info['id'].'/'.$path);
169 169
 		}
170 170
 
@@ -180,7 +180,7 @@  discard block
 block discarded – undo
180 180
 	 *
181 181
 	 * Checks whether or not an app is installed, i.e. registered in apps table.
182 182
 	 */
183
-	public static function isInstalled( $app ) {
183
+	public static function isInstalled($app) {
184 184
 		return (\OC::$server->getConfig()->getAppValue($app, "installed_version", null) !== null);
185 185
 	}
186 186
 
@@ -191,7 +191,7 @@  discard block
 block discarded – undo
191 191
 	 * @return bool
192 192
 	 */
193 193
 	public function updateAppstoreApp($appId) {
194
-		if($this->isUpdateAvailable($appId)) {
194
+		if ($this->isUpdateAvailable($appId)) {
195 195
 			try {
196 196
 				$this->downloadApp($appId);
197 197
 			} catch (\Exception $e) {
@@ -215,18 +215,18 @@  discard block
 block discarded – undo
215 215
 		$appId = strtolower($appId);
216 216
 
217 217
 		$apps = $this->appFetcher->get();
218
-		foreach($apps as $app) {
219
-			if($app['id'] === $appId) {
218
+		foreach ($apps as $app) {
219
+			if ($app['id'] === $appId) {
220 220
 				// Load the certificate
221 221
 				$certificate = new X509();
222
-				$certificate->loadCA(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crt'));
222
+				$certificate->loadCA(file_get_contents(__DIR__.'/../../resources/codesigning/root.crt'));
223 223
 				$loadedCertificate = $certificate->loadX509($app['certificate']);
224 224
 
225 225
 				// Verify if the certificate has been revoked
226 226
 				$crl = new X509();
227
-				$crl->loadCA(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crt'));
228
-				$crl->loadCRL(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crl'));
229
-				if($crl->validateSignature() !== true) {
227
+				$crl->loadCA(file_get_contents(__DIR__.'/../../resources/codesigning/root.crt'));
228
+				$crl->loadCRL(file_get_contents(__DIR__.'/../../resources/codesigning/root.crl'));
229
+				if ($crl->validateSignature() !== true) {
230 230
 					throw new \Exception('Could not validate CRL signature');
231 231
 				}
232 232
 				$csn = $loadedCertificate['tbsCertificate']['serialNumber']->toString();
@@ -241,7 +241,7 @@  discard block
 block discarded – undo
241 241
 				}
242 242
 
243 243
 				// Verify if the certificate has been issued by the Nextcloud Code Authority CA
244
-				if($certificate->validateSignature() !== true) {
244
+				if ($certificate->validateSignature() !== true) {
245 245
 					throw new \Exception(
246 246
 						sprintf(
247 247
 							'App with id %s has a certificate not issued by a trusted Code Signing Authority',
@@ -252,7 +252,7 @@  discard block
 block discarded – undo
252 252
 
253 253
 				// Verify if the certificate is issued for the requested app id
254 254
 				$certInfo = openssl_x509_parse($app['certificate']);
255
-				if(!isset($certInfo['subject']['CN'])) {
255
+				if (!isset($certInfo['subject']['CN'])) {
256 256
 					throw new \Exception(
257 257
 						sprintf(
258 258
 							'App with id %s has a cert with no CN',
@@ -260,7 +260,7 @@  discard block
 block discarded – undo
260 260
 						)
261 261
 					);
262 262
 				}
263
-				if($certInfo['subject']['CN'] !== $appId) {
263
+				if ($certInfo['subject']['CN'] !== $appId) {
264 264
 					throw new \Exception(
265 265
 						sprintf(
266 266
 							'App with id %s has a cert issued to %s',
@@ -277,15 +277,15 @@  discard block
 block discarded – undo
277 277
 
278 278
 				// Check if the signature actually matches the downloaded content
279 279
 				$certificate = openssl_get_publickey($app['certificate']);
280
-				$verified = (bool)openssl_verify(file_get_contents($tempFile), base64_decode($app['releases'][0]['signature']), $certificate, OPENSSL_ALGO_SHA512);
280
+				$verified = (bool) openssl_verify(file_get_contents($tempFile), base64_decode($app['releases'][0]['signature']), $certificate, OPENSSL_ALGO_SHA512);
281 281
 				openssl_free_key($certificate);
282 282
 
283
-				if($verified === true) {
283
+				if ($verified === true) {
284 284
 					// Seems to match, let's proceed
285 285
 					$extractDir = $this->tempManager->getTemporaryFolder();
286 286
 					$archive = new TAR($tempFile);
287 287
 
288
-					if($archive) {
288
+					if ($archive) {
289 289
 						if (!$archive->extract($extractDir)) {
290 290
 							throw new \Exception(
291 291
 								sprintf(
@@ -298,7 +298,7 @@  discard block
 block discarded – undo
298 298
 						$folders = array_diff($allFiles, ['.', '..']);
299 299
 						$folders = array_values($folders);
300 300
 
301
-						if(count($folders) > 1) {
301
+						if (count($folders) > 1) {
302 302
 							throw new \Exception(
303 303
 								sprintf(
304 304
 									'Extracted app %s has more than 1 folder',
@@ -309,22 +309,22 @@  discard block
 block discarded – undo
309 309
 
310 310
 						// Check if appinfo/info.xml has the same app ID as well
311 311
 						$loadEntities = libxml_disable_entity_loader(false);
312
-						$xml = simplexml_load_file($extractDir . '/' . $folders[0] . '/appinfo/info.xml');
312
+						$xml = simplexml_load_file($extractDir.'/'.$folders[0].'/appinfo/info.xml');
313 313
 						libxml_disable_entity_loader($loadEntities);
314
-						if((string)$xml->id !== $appId) {
314
+						if ((string) $xml->id !== $appId) {
315 315
 							throw new \Exception(
316 316
 								sprintf(
317 317
 									'App for id %s has a wrong app ID in info.xml: %s',
318 318
 									$appId,
319
-									(string)$xml->id
319
+									(string) $xml->id
320 320
 								)
321 321
 							);
322 322
 						}
323 323
 
324 324
 						// Check if the version is lower than before
325 325
 						$currentVersion = OC_App::getAppVersion($appId);
326
-						$newVersion = (string)$xml->version;
327
-						if(version_compare($currentVersion, $newVersion) === 1) {
326
+						$newVersion = (string) $xml->version;
327
+						if (version_compare($currentVersion, $newVersion) === 1) {
328 328
 							throw new \Exception(
329 329
 								sprintf(
330 330
 									'App for id %s has version %s and tried to update to lower version %s',
@@ -335,12 +335,12 @@  discard block
 block discarded – undo
335 335
 							);
336 336
 						}
337 337
 
338
-						$baseDir = OC_App::getInstallPath() . '/' . $appId;
338
+						$baseDir = OC_App::getInstallPath().'/'.$appId;
339 339
 						// Remove old app with the ID if existent
340 340
 						OC_Helper::rmdirr($baseDir);
341 341
 						// Move to app folder
342
-						if(@mkdir($baseDir)) {
343
-							$extractDir .= '/' . $folders[0];
342
+						if (@mkdir($baseDir)) {
343
+							$extractDir .= '/'.$folders[0];
344 344
 							OC_Helper::copyr($extractDir, $baseDir);
345 345
 						}
346 346
 						OC_Helper::copyr($extractDir, $baseDir);
@@ -399,8 +399,8 @@  discard block
 block discarded – undo
399 399
 			$apps = $this->appFetcher->get();
400 400
 		}
401 401
 
402
-		foreach($apps as $app) {
403
-			if($app['id'] === $appId) {
402
+		foreach ($apps as $app) {
403
+			if ($app['id'] === $appId) {
404 404
 				$currentVersion = OC_App::getAppVersion($appId);
405 405
 				$newestVersion = $app['releases'][0]['version'];
406 406
 				if (version_compare($newestVersion, $currentVersion, '>')) {
@@ -422,7 +422,7 @@  discard block
 block discarded – undo
422 422
 	 * The function will check if the app is already downloaded in the apps repository
423 423
 	 */
424 424
 	public function isDownloaded($name) {
425
-		foreach(\OC::$APPSROOTS as $dir) {
425
+		foreach (\OC::$APPSROOTS as $dir) {
426 426
 			$dirToTest  = $dir['path'];
427 427
 			$dirToTest .= '/';
428 428
 			$dirToTest .= $name;
@@ -450,11 +450,11 @@  discard block
 block discarded – undo
450 450
 	 * this has to be done by the function oc_app_uninstall().
451 451
 	 */
452 452
 	public function removeApp($appId) {
453
-		if($this->isDownloaded( $appId )) {
454
-			$appDir = OC_App::getInstallPath() . '/' . $appId;
453
+		if ($this->isDownloaded($appId)) {
454
+			$appDir = OC_App::getInstallPath().'/'.$appId;
455 455
 			OC_Helper::rmdirr($appDir);
456 456
 			return true;
457
-		}else{
457
+		} else {
458 458
 			\OCP\Util::writeLog('core', 'can\'t remove app '.$appId.'. It is not installed.', \OCP\Util::ERROR);
459 459
 
460 460
 			return false;
@@ -470,8 +470,8 @@  discard block
 block discarded – undo
470 470
 	 */
471 471
 	public function installAppBundle(Bundle $bundle) {
472 472
 		$appIds = $bundle->getAppIdentifiers();
473
-		foreach($appIds as $appId) {
474
-			if(!$this->isDownloaded($appId)) {
473
+		foreach ($appIds as $appId) {
474
+			if (!$this->isDownloaded($appId)) {
475 475
 				$this->downloadApp($appId);
476 476
 			}
477 477
 			$this->installApp($appId);
@@ -493,13 +493,13 @@  discard block
 block discarded – undo
493 493
 	 */
494 494
 	public static function installShippedApps($softErrors = false) {
495 495
 		$errors = [];
496
-		foreach(\OC::$APPSROOTS as $app_dir) {
497
-			if($dir = opendir( $app_dir['path'] )) {
498
-				while( false !== ( $filename = readdir( $dir ))) {
499
-					if( substr( $filename, 0, 1 ) != '.' and is_dir($app_dir['path']."/$filename") ) {
500
-						if( file_exists( $app_dir['path']."/$filename/appinfo/info.xml" )) {
501
-							if(!Installer::isInstalled($filename)) {
502
-								$info=OC_App::getAppInfo($filename);
496
+		foreach (\OC::$APPSROOTS as $app_dir) {
497
+			if ($dir = opendir($app_dir['path'])) {
498
+				while (false !== ($filename = readdir($dir))) {
499
+					if (substr($filename, 0, 1) != '.' and is_dir($app_dir['path']."/$filename")) {
500
+						if (file_exists($app_dir['path']."/$filename/appinfo/info.xml")) {
501
+							if (!Installer::isInstalled($filename)) {
502
+								$info = OC_App::getAppInfo($filename);
503 503
 								$enabled = isset($info['default_enable']);
504 504
 								if (($enabled || in_array($filename, \OC::$server->getAppManager()->getAlwaysEnabledApps()))
505 505
 									  && \OC::$server->getConfig()->getAppValue($filename, 'enabled') !== 'no') {
@@ -522,7 +522,7 @@  discard block
 block discarded – undo
522 522
 						}
523 523
 					}
524 524
 				}
525
-				closedir( $dir );
525
+				closedir($dir);
526 526
 			}
527 527
 		}
528 528
 
@@ -539,12 +539,12 @@  discard block
 block discarded – undo
539 539
 		$appPath = OC_App::getAppPath($app);
540 540
 		\OC_App::registerAutoloading($app, $appPath);
541 541
 
542
-		if(is_file("$appPath/appinfo/database.xml")) {
542
+		if (is_file("$appPath/appinfo/database.xml")) {
543 543
 			try {
544 544
 				OC_DB::createDbFromStructure("$appPath/appinfo/database.xml");
545 545
 			} catch (TableExistsException $e) {
546 546
 				throw new HintException(
547
-					'Failed to enable app ' . $app,
547
+					'Failed to enable app '.$app,
548 548
 					'Please ask for help via one of our <a href="https://nextcloud.com/support/" target="_blank" rel="noreferrer noopener">support channels</a>.',
549 549
 					0, $e
550 550
 				);
@@ -573,16 +573,16 @@  discard block
 block discarded – undo
573 573
 		}
574 574
 
575 575
 		//set remote/public handlers
576
-		foreach($info['remote'] as $name=>$path) {
576
+		foreach ($info['remote'] as $name=>$path) {
577 577
 			$config->setAppValue('core', 'remote_'.$name, $app.'/'.$path);
578 578
 		}
579
-		foreach($info['public'] as $name=>$path) {
579
+		foreach ($info['public'] as $name=>$path) {
580 580
 			$config->setAppValue('core', 'public_'.$name, $app.'/'.$path);
581 581
 		}
582 582
 
583 583
 		OC_App::setAppTypes($info['id']);
584 584
 
585
-		if(isset($info['settings']) && is_array($info['settings'])) {
585
+		if (isset($info['settings']) && is_array($info['settings'])) {
586 586
 			// requires that autoloading was registered for the app,
587 587
 			// as happens before running the install.php some lines above
588 588
 			\OC::$server->getSettingsManager()->setupSettings($info['settings']);
@@ -595,7 +595,7 @@  discard block
 block discarded – undo
595 595
 	 * @param string $script
596 596
 	 */
597 597
 	private static function includeAppScript($script) {
598
-		if ( file_exists($script) ){
598
+		if (file_exists($script)) {
599 599
 			include $script;
600 600
 		}
601 601
 	}
Please login to merge, or discard this patch.
core/register_command.php 1 patch
Indentation   +95 added lines, -95 removed lines patch added patch discarded remove patch
@@ -44,122 +44,122 @@
 block discarded – undo
44 44
 $application->add(new OC\Core\Command\App\CheckCode($infoParser));
45 45
 $application->add(new OC\Core\Command\L10n\CreateJs());
46 46
 $application->add(new \OC\Core\Command\Integrity\SignApp(
47
-		\OC::$server->getIntegrityCodeChecker(),
48
-		new \OC\IntegrityCheck\Helpers\FileAccessHelper(),
49
-		\OC::$server->getURLGenerator()
47
+        \OC::$server->getIntegrityCodeChecker(),
48
+        new \OC\IntegrityCheck\Helpers\FileAccessHelper(),
49
+        \OC::$server->getURLGenerator()
50 50
 ));
51 51
 $application->add(new \OC\Core\Command\Integrity\SignCore(
52
-		\OC::$server->getIntegrityCodeChecker(),
53
-		new \OC\IntegrityCheck\Helpers\FileAccessHelper()
52
+        \OC::$server->getIntegrityCodeChecker(),
53
+        new \OC\IntegrityCheck\Helpers\FileAccessHelper()
54 54
 ));
55 55
 $application->add(new \OC\Core\Command\Integrity\CheckApp(
56
-		\OC::$server->getIntegrityCodeChecker()
56
+        \OC::$server->getIntegrityCodeChecker()
57 57
 ));
58 58
 $application->add(new \OC\Core\Command\Integrity\CheckCore(
59
-		\OC::$server->getIntegrityCodeChecker()
59
+        \OC::$server->getIntegrityCodeChecker()
60 60
 ));
61 61
 
62 62
 
63 63
 if (\OC::$server->getConfig()->getSystemValue('installed', false)) {
64
-	$application->add(new OC\Core\Command\App\Disable(\OC::$server->getAppManager()));
65
-	$application->add(new OC\Core\Command\App\Enable(\OC::$server->getAppManager()));
66
-	$application->add(new OC\Core\Command\App\Install());
67
-	$application->add(new OC\Core\Command\App\GetPath());
68
-	$application->add(new OC\Core\Command\App\ListApps(\OC::$server->getAppManager()));
64
+    $application->add(new OC\Core\Command\App\Disable(\OC::$server->getAppManager()));
65
+    $application->add(new OC\Core\Command\App\Enable(\OC::$server->getAppManager()));
66
+    $application->add(new OC\Core\Command\App\Install());
67
+    $application->add(new OC\Core\Command\App\GetPath());
68
+    $application->add(new OC\Core\Command\App\ListApps(\OC::$server->getAppManager()));
69 69
 
70
-	$application->add(new OC\Core\Command\TwoFactorAuth\Enable(
71
-		\OC::$server->getTwoFactorAuthManager(), \OC::$server->getUserManager()
72
-	));
73
-	$application->add(new OC\Core\Command\TwoFactorAuth\Disable(
74
-		\OC::$server->getTwoFactorAuthManager(), \OC::$server->getUserManager()
75
-	));
70
+    $application->add(new OC\Core\Command\TwoFactorAuth\Enable(
71
+        \OC::$server->getTwoFactorAuthManager(), \OC::$server->getUserManager()
72
+    ));
73
+    $application->add(new OC\Core\Command\TwoFactorAuth\Disable(
74
+        \OC::$server->getTwoFactorAuthManager(), \OC::$server->getUserManager()
75
+    ));
76 76
 
77
-	$application->add(new OC\Core\Command\Background\Cron(\OC::$server->getConfig()));
78
-	$application->add(new OC\Core\Command\Background\WebCron(\OC::$server->getConfig()));
79
-	$application->add(new OC\Core\Command\Background\Ajax(\OC::$server->getConfig()));
77
+    $application->add(new OC\Core\Command\Background\Cron(\OC::$server->getConfig()));
78
+    $application->add(new OC\Core\Command\Background\WebCron(\OC::$server->getConfig()));
79
+    $application->add(new OC\Core\Command\Background\Ajax(\OC::$server->getConfig()));
80 80
 
81
-	$application->add(new OC\Core\Command\Config\App\DeleteConfig(\OC::$server->getConfig()));
82
-	$application->add(new OC\Core\Command\Config\App\GetConfig(\OC::$server->getConfig()));
83
-	$application->add(new OC\Core\Command\Config\App\SetConfig(\OC::$server->getConfig()));
84
-	$application->add(new OC\Core\Command\Config\Import(\OC::$server->getConfig()));
85
-	$application->add(new OC\Core\Command\Config\ListConfigs(\OC::$server->getSystemConfig(), \OC::$server->getAppConfig()));
86
-	$application->add(new OC\Core\Command\Config\System\DeleteConfig(\OC::$server->getSystemConfig()));
87
-	$application->add(new OC\Core\Command\Config\System\GetConfig(\OC::$server->getSystemConfig()));
88
-	$application->add(new OC\Core\Command\Config\System\SetConfig(\OC::$server->getSystemConfig()));
81
+    $application->add(new OC\Core\Command\Config\App\DeleteConfig(\OC::$server->getConfig()));
82
+    $application->add(new OC\Core\Command\Config\App\GetConfig(\OC::$server->getConfig()));
83
+    $application->add(new OC\Core\Command\Config\App\SetConfig(\OC::$server->getConfig()));
84
+    $application->add(new OC\Core\Command\Config\Import(\OC::$server->getConfig()));
85
+    $application->add(new OC\Core\Command\Config\ListConfigs(\OC::$server->getSystemConfig(), \OC::$server->getAppConfig()));
86
+    $application->add(new OC\Core\Command\Config\System\DeleteConfig(\OC::$server->getSystemConfig()));
87
+    $application->add(new OC\Core\Command\Config\System\GetConfig(\OC::$server->getSystemConfig()));
88
+    $application->add(new OC\Core\Command\Config\System\SetConfig(\OC::$server->getSystemConfig()));
89 89
 
90
-	$application->add(new OC\Core\Command\Db\ConvertType(\OC::$server->getConfig(), new \OC\DB\ConnectionFactory(\OC::$server->getSystemConfig())));
91
-	$application->add(new OC\Core\Command\Db\ConvertMysqlToMB4(\OC::$server->getConfig(), \OC::$server->getDatabaseConnection(), \OC::$server->getURLGenerator(), \OC::$server->getLogger()));
92
-	$application->add(new OC\Core\Command\Db\ConvertFilecacheBigInt(\OC::$server->getDatabaseConnection()));
93
-	$application->add(new OC\Core\Command\Db\Migrations\StatusCommand(\OC::$server->getDatabaseConnection()));
94
-	$application->add(new OC\Core\Command\Db\Migrations\MigrateCommand(\OC::$server->getDatabaseConnection()));
95
-	$application->add(new OC\Core\Command\Db\Migrations\GenerateCommand(\OC::$server->getDatabaseConnection()));
96
-	$application->add(new OC\Core\Command\Db\Migrations\GenerateFromSchemaFileCommand(\OC::$server->getConfig(), \OC::$server->getAppManager(), \OC::$server->getDatabaseConnection()));
97
-	$application->add(new OC\Core\Command\Db\Migrations\ExecuteCommand(\OC::$server->getDatabaseConnection(), \OC::$server->getConfig()));
90
+    $application->add(new OC\Core\Command\Db\ConvertType(\OC::$server->getConfig(), new \OC\DB\ConnectionFactory(\OC::$server->getSystemConfig())));
91
+    $application->add(new OC\Core\Command\Db\ConvertMysqlToMB4(\OC::$server->getConfig(), \OC::$server->getDatabaseConnection(), \OC::$server->getURLGenerator(), \OC::$server->getLogger()));
92
+    $application->add(new OC\Core\Command\Db\ConvertFilecacheBigInt(\OC::$server->getDatabaseConnection()));
93
+    $application->add(new OC\Core\Command\Db\Migrations\StatusCommand(\OC::$server->getDatabaseConnection()));
94
+    $application->add(new OC\Core\Command\Db\Migrations\MigrateCommand(\OC::$server->getDatabaseConnection()));
95
+    $application->add(new OC\Core\Command\Db\Migrations\GenerateCommand(\OC::$server->getDatabaseConnection()));
96
+    $application->add(new OC\Core\Command\Db\Migrations\GenerateFromSchemaFileCommand(\OC::$server->getConfig(), \OC::$server->getAppManager(), \OC::$server->getDatabaseConnection()));
97
+    $application->add(new OC\Core\Command\Db\Migrations\ExecuteCommand(\OC::$server->getDatabaseConnection(), \OC::$server->getConfig()));
98 98
 
99
-	$application->add(new OC\Core\Command\Encryption\Disable(\OC::$server->getConfig()));
100
-	$application->add(new OC\Core\Command\Encryption\Enable(\OC::$server->getConfig(), \OC::$server->getEncryptionManager()));
101
-	$application->add(new OC\Core\Command\Encryption\ListModules(\OC::$server->getEncryptionManager()));
102
-	$application->add(new OC\Core\Command\Encryption\SetDefaultModule(\OC::$server->getEncryptionManager()));
103
-	$application->add(new OC\Core\Command\Encryption\Status(\OC::$server->getEncryptionManager()));
104
-	$application->add(new OC\Core\Command\Encryption\EncryptAll(\OC::$server->getEncryptionManager(), \OC::$server->getAppManager(), \OC::$server->getConfig(), new \Symfony\Component\Console\Helper\QuestionHelper()));
105
-	$application->add(new OC\Core\Command\Encryption\DecryptAll(
106
-		\OC::$server->getEncryptionManager(),
107
-		\OC::$server->getAppManager(),
108
-		\OC::$server->getConfig(),
109
-		new \OC\Encryption\DecryptAll(\OC::$server->getEncryptionManager(), \OC::$server->getUserManager(), new \OC\Files\View()),
110
-		new \Symfony\Component\Console\Helper\QuestionHelper())
111
-	);
99
+    $application->add(new OC\Core\Command\Encryption\Disable(\OC::$server->getConfig()));
100
+    $application->add(new OC\Core\Command\Encryption\Enable(\OC::$server->getConfig(), \OC::$server->getEncryptionManager()));
101
+    $application->add(new OC\Core\Command\Encryption\ListModules(\OC::$server->getEncryptionManager()));
102
+    $application->add(new OC\Core\Command\Encryption\SetDefaultModule(\OC::$server->getEncryptionManager()));
103
+    $application->add(new OC\Core\Command\Encryption\Status(\OC::$server->getEncryptionManager()));
104
+    $application->add(new OC\Core\Command\Encryption\EncryptAll(\OC::$server->getEncryptionManager(), \OC::$server->getAppManager(), \OC::$server->getConfig(), new \Symfony\Component\Console\Helper\QuestionHelper()));
105
+    $application->add(new OC\Core\Command\Encryption\DecryptAll(
106
+        \OC::$server->getEncryptionManager(),
107
+        \OC::$server->getAppManager(),
108
+        \OC::$server->getConfig(),
109
+        new \OC\Encryption\DecryptAll(\OC::$server->getEncryptionManager(), \OC::$server->getUserManager(), new \OC\Files\View()),
110
+        new \Symfony\Component\Console\Helper\QuestionHelper())
111
+    );
112 112
 
113
-	$application->add(new OC\Core\Command\Log\Manage(\OC::$server->getConfig()));
114
-	$application->add(new OC\Core\Command\Log\File(\OC::$server->getConfig()));
113
+    $application->add(new OC\Core\Command\Log\Manage(\OC::$server->getConfig()));
114
+    $application->add(new OC\Core\Command\Log\File(\OC::$server->getConfig()));
115 115
 
116
-	$view = new \OC\Files\View();
117
-	$util = new \OC\Encryption\Util(
118
-		$view,
119
-		\OC::$server->getUserManager(),
120
-		\OC::$server->getGroupManager(),
121
-		\OC::$server->getConfig()
122
-	);
123
-	$application->add(new OC\Core\Command\Encryption\ChangeKeyStorageRoot(
124
-			$view,
125
-			\OC::$server->getUserManager(),
126
-			\OC::$server->getConfig(),
127
-			$util,
128
-			new \Symfony\Component\Console\Helper\QuestionHelper()
129
-		)
130
-	);
131
-	$application->add(new OC\Core\Command\Encryption\ShowKeyStorageRoot($util));
116
+    $view = new \OC\Files\View();
117
+    $util = new \OC\Encryption\Util(
118
+        $view,
119
+        \OC::$server->getUserManager(),
120
+        \OC::$server->getGroupManager(),
121
+        \OC::$server->getConfig()
122
+    );
123
+    $application->add(new OC\Core\Command\Encryption\ChangeKeyStorageRoot(
124
+            $view,
125
+            \OC::$server->getUserManager(),
126
+            \OC::$server->getConfig(),
127
+            $util,
128
+            new \Symfony\Component\Console\Helper\QuestionHelper()
129
+        )
130
+    );
131
+    $application->add(new OC\Core\Command\Encryption\ShowKeyStorageRoot($util));
132 132
 
133
-	$application->add(new OC\Core\Command\Maintenance\DataFingerprint(\OC::$server->getConfig(), new \OC\AppFramework\Utility\TimeFactory()));
134
-	$application->add(new OC\Core\Command\Maintenance\Mimetype\UpdateDB(\OC::$server->getMimeTypeDetector(), \OC::$server->getMimeTypeLoader()));
135
-	$application->add(new OC\Core\Command\Maintenance\Mimetype\UpdateJS(\OC::$server->getMimeTypeDetector()));
136
-	$application->add(new OC\Core\Command\Maintenance\Mode(\OC::$server->getConfig()));
137
-	$application->add(new OC\Core\Command\Maintenance\UpdateHtaccess());
138
-	$application->add(new OC\Core\Command\Maintenance\UpdateTheme(\OC::$server->getMimeTypeDetector(), \OC::$server->getMemCacheFactory()));
133
+    $application->add(new OC\Core\Command\Maintenance\DataFingerprint(\OC::$server->getConfig(), new \OC\AppFramework\Utility\TimeFactory()));
134
+    $application->add(new OC\Core\Command\Maintenance\Mimetype\UpdateDB(\OC::$server->getMimeTypeDetector(), \OC::$server->getMimeTypeLoader()));
135
+    $application->add(new OC\Core\Command\Maintenance\Mimetype\UpdateJS(\OC::$server->getMimeTypeDetector()));
136
+    $application->add(new OC\Core\Command\Maintenance\Mode(\OC::$server->getConfig()));
137
+    $application->add(new OC\Core\Command\Maintenance\UpdateHtaccess());
138
+    $application->add(new OC\Core\Command\Maintenance\UpdateTheme(\OC::$server->getMimeTypeDetector(), \OC::$server->getMemCacheFactory()));
139 139
 
140
-	$application->add(new OC\Core\Command\Upgrade(\OC::$server->getConfig(), \OC::$server->getLogger(), \OC::$server->query(\OC\Installer::class)));
141
-	$application->add(new OC\Core\Command\Maintenance\Repair(
142
-		new \OC\Repair(\OC\Repair::getRepairSteps(), \OC::$server->getEventDispatcher()), \OC::$server->getConfig(),
143
-		\OC::$server->getEventDispatcher(), \OC::$server->getAppManager()));
140
+    $application->add(new OC\Core\Command\Upgrade(\OC::$server->getConfig(), \OC::$server->getLogger(), \OC::$server->query(\OC\Installer::class)));
141
+    $application->add(new OC\Core\Command\Maintenance\Repair(
142
+        new \OC\Repair(\OC\Repair::getRepairSteps(), \OC::$server->getEventDispatcher()), \OC::$server->getConfig(),
143
+        \OC::$server->getEventDispatcher(), \OC::$server->getAppManager()));
144 144
 
145
-	$application->add(new OC\Core\Command\User\Add(\OC::$server->getUserManager(), \OC::$server->getGroupManager()));
146
-	$application->add(new OC\Core\Command\User\Delete(\OC::$server->getUserManager()));
147
-	$application->add(new OC\Core\Command\User\Disable(\OC::$server->getUserManager()));
148
-	$application->add(new OC\Core\Command\User\Enable(\OC::$server->getUserManager()));
149
-	$application->add(new OC\Core\Command\User\LastSeen(\OC::$server->getUserManager()));
150
-	$application->add(new OC\Core\Command\User\Report(\OC::$server->getUserManager()));
151
-	$application->add(new OC\Core\Command\User\ResetPassword(\OC::$server->getUserManager()));
152
-	$application->add(new OC\Core\Command\User\Setting(\OC::$server->getUserManager(), \OC::$server->getConfig(), \OC::$server->getDatabaseConnection()));
153
-	$application->add(new OC\Core\Command\User\ListCommand(\OC::$server->getUserManager()));
154
-	$application->add(new OC\Core\Command\User\Info(\OC::$server->getUserManager(), \OC::$server->getGroupManager()));
145
+    $application->add(new OC\Core\Command\User\Add(\OC::$server->getUserManager(), \OC::$server->getGroupManager()));
146
+    $application->add(new OC\Core\Command\User\Delete(\OC::$server->getUserManager()));
147
+    $application->add(new OC\Core\Command\User\Disable(\OC::$server->getUserManager()));
148
+    $application->add(new OC\Core\Command\User\Enable(\OC::$server->getUserManager()));
149
+    $application->add(new OC\Core\Command\User\LastSeen(\OC::$server->getUserManager()));
150
+    $application->add(new OC\Core\Command\User\Report(\OC::$server->getUserManager()));
151
+    $application->add(new OC\Core\Command\User\ResetPassword(\OC::$server->getUserManager()));
152
+    $application->add(new OC\Core\Command\User\Setting(\OC::$server->getUserManager(), \OC::$server->getConfig(), \OC::$server->getDatabaseConnection()));
153
+    $application->add(new OC\Core\Command\User\ListCommand(\OC::$server->getUserManager()));
154
+    $application->add(new OC\Core\Command\User\Info(\OC::$server->getUserManager(), \OC::$server->getGroupManager()));
155 155
 
156
-	$application->add(new OC\Core\Command\Group\ListCommand(\OC::$server->getGroupManager()));
157
-	$application->add(new OC\Core\Command\Group\AddUser(\OC::$server->getUserManager(), \OC::$server->getGroupManager()));
158
-	$application->add(new OC\Core\Command\Group\RemoveUser(\OC::$server->getUserManager(), \OC::$server->getGroupManager()));
156
+    $application->add(new OC\Core\Command\Group\ListCommand(\OC::$server->getGroupManager()));
157
+    $application->add(new OC\Core\Command\Group\AddUser(\OC::$server->getUserManager(), \OC::$server->getGroupManager()));
158
+    $application->add(new OC\Core\Command\Group\RemoveUser(\OC::$server->getUserManager(), \OC::$server->getGroupManager()));
159 159
 
160
-	$application->add(new OC\Core\Command\Security\ListCertificates(\OC::$server->getCertificateManager(null), \OC::$server->getL10N('core')));
161
-	$application->add(new OC\Core\Command\Security\ImportCertificate(\OC::$server->getCertificateManager(null)));
162
-	$application->add(new OC\Core\Command\Security\RemoveCertificate(\OC::$server->getCertificateManager(null)));
160
+    $application->add(new OC\Core\Command\Security\ListCertificates(\OC::$server->getCertificateManager(null), \OC::$server->getL10N('core')));
161
+    $application->add(new OC\Core\Command\Security\ImportCertificate(\OC::$server->getCertificateManager(null)));
162
+    $application->add(new OC\Core\Command\Security\RemoveCertificate(\OC::$server->getCertificateManager(null)));
163 163
 } else {
164
-	$application->add(new OC\Core\Command\Maintenance\Install(\OC::$server->getSystemConfig()));
164
+    $application->add(new OC\Core\Command\Maintenance\Install(\OC::$server->getSystemConfig()));
165 165
 }
Please login to merge, or discard this patch.
settings/ajax/updateapp.php 2 patches
Indentation   +13 added lines, -13 removed lines patch added patch discarded remove patch
@@ -29,10 +29,10 @@  discard block
 block discarded – undo
29 29
 OCP\JSON::callCheck();
30 30
 
31 31
 if (!array_key_exists('appid', $_POST)) {
32
-	OCP\JSON::error(array(
33
-		'message' => 'No AppId given!'
34
-	));
35
-	return;
32
+    OCP\JSON::error(array(
33
+        'message' => 'No AppId given!'
34
+    ));
35
+    return;
36 36
 }
37 37
 
38 38
 $appId = (string)$_POST['appid'];
@@ -41,18 +41,18 @@  discard block
 block discarded – undo
41 41
 $config = \OC::$server->getConfig();
42 42
 $config->setSystemValue('maintenance', true);
43 43
 try {
44
-	$installer = \OC::$server->query(\OC\Installer::class);
45
-	$result = $installer->updateAppstoreApp($appId);
46
-	$config->setSystemValue('maintenance', false);
44
+    $installer = \OC::$server->query(\OC\Installer::class);
45
+    $result = $installer->updateAppstoreApp($appId);
46
+    $config->setSystemValue('maintenance', false);
47 47
 } catch(Exception $ex) {
48
-	$config->setSystemValue('maintenance', false);
49
-	OC_JSON::error(array('data' => array( 'message' => $ex->getMessage() )));
50
-	return;
48
+    $config->setSystemValue('maintenance', false);
49
+    OC_JSON::error(array('data' => array( 'message' => $ex->getMessage() )));
50
+    return;
51 51
 }
52 52
 
53 53
 if($result !== false) {
54
-	OC_JSON::success(array('data' => array('appid' => $appId)));
54
+    OC_JSON::success(array('data' => array('appid' => $appId)));
55 55
 } else {
56
-	$l = \OC::$server->getL10N('settings');
57
-	OC_JSON::error(array('data' => array( 'message' => $l->t("Couldn't update app.") )));
56
+    $l = \OC::$server->getL10N('settings');
57
+    OC_JSON::error(array('data' => array( 'message' => $l->t("Couldn't update app.") )));
58 58
 }
Please login to merge, or discard this patch.
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -35,7 +35,7 @@  discard block
 block discarded – undo
35 35
 	return;
36 36
 }
37 37
 
38
-$appId = (string)$_POST['appid'];
38
+$appId = (string) $_POST['appid'];
39 39
 $appId = OC_App::cleanAppId($appId);
40 40
 
41 41
 $config = \OC::$server->getConfig();
@@ -44,15 +44,15 @@  discard block
 block discarded – undo
44 44
 	$installer = \OC::$server->query(\OC\Installer::class);
45 45
 	$result = $installer->updateAppstoreApp($appId);
46 46
 	$config->setSystemValue('maintenance', false);
47
-} catch(Exception $ex) {
47
+} catch (Exception $ex) {
48 48
 	$config->setSystemValue('maintenance', false);
49
-	OC_JSON::error(array('data' => array( 'message' => $ex->getMessage() )));
49
+	OC_JSON::error(array('data' => array('message' => $ex->getMessage())));
50 50
 	return;
51 51
 }
52 52
 
53
-if($result !== false) {
53
+if ($result !== false) {
54 54
 	OC_JSON::success(array('data' => array('appid' => $appId)));
55 55
 } else {
56 56
 	$l = \OC::$server->getL10N('settings');
57
-	OC_JSON::error(array('data' => array( 'message' => $l->t("Couldn't update app.") )));
57
+	OC_JSON::error(array('data' => array('message' => $l->t("Couldn't update app."))));
58 58
 }
Please login to merge, or discard this patch.
lib/base.php 1 patch
Indentation   +1004 added lines, -1004 removed lines patch added patch discarded remove patch
@@ -62,1010 +62,1010 @@
 block discarded – undo
62 62
  * OC_autoload!
63 63
  */
64 64
 class OC {
65
-	/**
66
-	 * Associative array for autoloading. classname => filename
67
-	 */
68
-	public static $CLASSPATH = array();
69
-	/**
70
-	 * The installation path for Nextcloud  on the server (e.g. /srv/http/nextcloud)
71
-	 */
72
-	public static $SERVERROOT = '';
73
-	/**
74
-	 * the current request path relative to the Nextcloud root (e.g. files/index.php)
75
-	 */
76
-	private static $SUBURI = '';
77
-	/**
78
-	 * the Nextcloud root path for http requests (e.g. nextcloud/)
79
-	 */
80
-	public static $WEBROOT = '';
81
-	/**
82
-	 * The installation path array of the apps folder on the server (e.g. /srv/http/nextcloud) 'path' and
83
-	 * web path in 'url'
84
-	 */
85
-	public static $APPSROOTS = array();
86
-
87
-	/**
88
-	 * @var string
89
-	 */
90
-	public static $configDir;
91
-
92
-	/**
93
-	 * requested app
94
-	 */
95
-	public static $REQUESTEDAPP = '';
96
-
97
-	/**
98
-	 * check if Nextcloud runs in cli mode
99
-	 */
100
-	public static $CLI = false;
101
-
102
-	/**
103
-	 * @var \OC\Autoloader $loader
104
-	 */
105
-	public static $loader = null;
106
-
107
-	/** @var \Composer\Autoload\ClassLoader $composerAutoloader */
108
-	public static $composerAutoloader = null;
109
-
110
-	/**
111
-	 * @var \OC\Server
112
-	 */
113
-	public static $server = null;
114
-
115
-	/**
116
-	 * @var \OC\Config
117
-	 */
118
-	private static $config = null;
119
-
120
-	/**
121
-	 * @throws \RuntimeException when the 3rdparty directory is missing or
122
-	 * the app path list is empty or contains an invalid path
123
-	 */
124
-	public static function initPaths() {
125
-		if(defined('PHPUNIT_CONFIG_DIR')) {
126
-			self::$configDir = OC::$SERVERROOT . '/' . PHPUNIT_CONFIG_DIR . '/';
127
-		} elseif(defined('PHPUNIT_RUN') and PHPUNIT_RUN and is_dir(OC::$SERVERROOT . '/tests/config/')) {
128
-			self::$configDir = OC::$SERVERROOT . '/tests/config/';
129
-		} elseif($dir = getenv('NEXTCLOUD_CONFIG_DIR')) {
130
-			self::$configDir = rtrim($dir, '/') . '/';
131
-		} else {
132
-			self::$configDir = OC::$SERVERROOT . '/config/';
133
-		}
134
-		self::$config = new \OC\Config(self::$configDir);
135
-
136
-		OC::$SUBURI = str_replace("\\", "/", substr(realpath($_SERVER["SCRIPT_FILENAME"]), strlen(OC::$SERVERROOT)));
137
-		/**
138
-		 * FIXME: The following lines are required because we can't yet instantiate
139
-		 *        \OC::$server->getRequest() since \OC::$server does not yet exist.
140
-		 */
141
-		$params = [
142
-			'server' => [
143
-				'SCRIPT_NAME' => $_SERVER['SCRIPT_NAME'],
144
-				'SCRIPT_FILENAME' => $_SERVER['SCRIPT_FILENAME'],
145
-			],
146
-		];
147
-		$fakeRequest = new \OC\AppFramework\Http\Request($params, null, new \OC\AllConfig(new \OC\SystemConfig(self::$config)));
148
-		$scriptName = $fakeRequest->getScriptName();
149
-		if (substr($scriptName, -1) == '/') {
150
-			$scriptName .= 'index.php';
151
-			//make sure suburi follows the same rules as scriptName
152
-			if (substr(OC::$SUBURI, -9) != 'index.php') {
153
-				if (substr(OC::$SUBURI, -1) != '/') {
154
-					OC::$SUBURI = OC::$SUBURI . '/';
155
-				}
156
-				OC::$SUBURI = OC::$SUBURI . 'index.php';
157
-			}
158
-		}
159
-
160
-
161
-		if (OC::$CLI) {
162
-			OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
163
-		} else {
164
-			if (substr($scriptName, 0 - strlen(OC::$SUBURI)) === OC::$SUBURI) {
165
-				OC::$WEBROOT = substr($scriptName, 0, 0 - strlen(OC::$SUBURI));
166
-
167
-				if (OC::$WEBROOT != '' && OC::$WEBROOT[0] !== '/') {
168
-					OC::$WEBROOT = '/' . OC::$WEBROOT;
169
-				}
170
-			} else {
171
-				// The scriptName is not ending with OC::$SUBURI
172
-				// This most likely means that we are calling from CLI.
173
-				// However some cron jobs still need to generate
174
-				// a web URL, so we use overwritewebroot as a fallback.
175
-				OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
176
-			}
177
-
178
-			// Resolve /nextcloud to /nextcloud/ to ensure to always have a trailing
179
-			// slash which is required by URL generation.
180
-			if (isset($_SERVER['REQUEST_URI']) && $_SERVER['REQUEST_URI'] === \OC::$WEBROOT &&
181
-					substr($_SERVER['REQUEST_URI'], -1) !== '/') {
182
-				header('Location: '.\OC::$WEBROOT.'/');
183
-				exit();
184
-			}
185
-		}
186
-
187
-		// search the apps folder
188
-		$config_paths = self::$config->getValue('apps_paths', array());
189
-		if (!empty($config_paths)) {
190
-			foreach ($config_paths as $paths) {
191
-				if (isset($paths['url']) && isset($paths['path'])) {
192
-					$paths['url'] = rtrim($paths['url'], '/');
193
-					$paths['path'] = rtrim($paths['path'], '/');
194
-					OC::$APPSROOTS[] = $paths;
195
-				}
196
-			}
197
-		} elseif (file_exists(OC::$SERVERROOT . '/apps')) {
198
-			OC::$APPSROOTS[] = array('path' => OC::$SERVERROOT . '/apps', 'url' => '/apps', 'writable' => true);
199
-		} elseif (file_exists(OC::$SERVERROOT . '/../apps')) {
200
-			OC::$APPSROOTS[] = array(
201
-				'path' => rtrim(dirname(OC::$SERVERROOT), '/') . '/apps',
202
-				'url' => '/apps',
203
-				'writable' => true
204
-			);
205
-		}
206
-
207
-		if (empty(OC::$APPSROOTS)) {
208
-			throw new \RuntimeException('apps directory not found! Please put the Nextcloud apps folder in the Nextcloud folder'
209
-				. ' or the folder above. You can also configure the location in the config.php file.');
210
-		}
211
-		$paths = array();
212
-		foreach (OC::$APPSROOTS as $path) {
213
-			$paths[] = $path['path'];
214
-			if (!is_dir($path['path'])) {
215
-				throw new \RuntimeException(sprintf('App directory "%s" not found! Please put the Nextcloud apps folder in the'
216
-					. ' Nextcloud folder or the folder above. You can also configure the location in the'
217
-					. ' config.php file.', $path['path']));
218
-			}
219
-		}
220
-
221
-		// set the right include path
222
-		set_include_path(
223
-			implode(PATH_SEPARATOR, $paths)
224
-		);
225
-	}
226
-
227
-	public static function checkConfig() {
228
-		$l = \OC::$server->getL10N('lib');
229
-
230
-		// Create config if it does not already exist
231
-		$configFilePath = self::$configDir .'/config.php';
232
-		if(!file_exists($configFilePath)) {
233
-			@touch($configFilePath);
234
-		}
235
-
236
-		// Check if config is writable
237
-		$configFileWritable = is_writable($configFilePath);
238
-		if (!$configFileWritable && !OC_Helper::isReadOnlyConfigEnabled()
239
-			|| !$configFileWritable && self::checkUpgrade(false)) {
240
-
241
-			$urlGenerator = \OC::$server->getURLGenerator();
242
-
243
-			if (self::$CLI) {
244
-				echo $l->t('Cannot write into "config" directory!')."\n";
245
-				echo $l->t('This can usually be fixed by giving the webserver write access to the config directory')."\n";
246
-				echo "\n";
247
-				echo $l->t('See %s', [ $urlGenerator->linkToDocs('admin-dir_permissions') ])."\n";
248
-				exit;
249
-			} else {
250
-				OC_Template::printErrorPage(
251
-					$l->t('Cannot write into "config" directory!'),
252
-					$l->t('This can usually be fixed by giving the webserver write access to the config directory. See %s',
253
-					 [ $urlGenerator->linkToDocs('admin-dir_permissions') ])
254
-				);
255
-			}
256
-		}
257
-	}
258
-
259
-	public static function checkInstalled() {
260
-		if (defined('OC_CONSOLE')) {
261
-			return;
262
-		}
263
-		// Redirect to installer if not installed
264
-		if (!\OC::$server->getSystemConfig()->getValue('installed', false) && OC::$SUBURI !== '/index.php' && OC::$SUBURI !== '/status.php') {
265
-			if (OC::$CLI) {
266
-				throw new Exception('Not installed');
267
-			} else {
268
-				$url = OC::$WEBROOT . '/index.php';
269
-				header('Location: ' . $url);
270
-			}
271
-			exit();
272
-		}
273
-	}
274
-
275
-	public static function checkMaintenanceMode() {
276
-		// Allow ajax update script to execute without being stopped
277
-		if (\OC::$server->getSystemConfig()->getValue('maintenance', false) && OC::$SUBURI != '/core/ajax/update.php') {
278
-			// send http status 503
279
-			header('HTTP/1.1 503 Service Temporarily Unavailable');
280
-			header('Status: 503 Service Temporarily Unavailable');
281
-			header('Retry-After: 120');
282
-
283
-			// render error page
284
-			$template = new OC_Template('', 'update.user', 'guest');
285
-			OC_Util::addScript('maintenance-check');
286
-			OC_Util::addStyle('core', 'guest');
287
-			$template->printPage();
288
-			die();
289
-		}
290
-	}
291
-
292
-	/**
293
-	 * Checks if the version requires an update and shows
294
-	 * @param bool $showTemplate Whether an update screen should get shown
295
-	 * @return bool|void
296
-	 */
297
-	public static function checkUpgrade($showTemplate = true) {
298
-		if (\OCP\Util::needUpgrade()) {
299
-			if (function_exists('opcache_reset')) {
300
-				opcache_reset();
301
-			}
302
-			$systemConfig = \OC::$server->getSystemConfig();
303
-			if ($showTemplate && !$systemConfig->getValue('maintenance', false)) {
304
-				self::printUpgradePage();
305
-				exit();
306
-			} else {
307
-				return true;
308
-			}
309
-		}
310
-		return false;
311
-	}
312
-
313
-	/**
314
-	 * Prints the upgrade page
315
-	 */
316
-	private static function printUpgradePage() {
317
-		$systemConfig = \OC::$server->getSystemConfig();
318
-
319
-		$disableWebUpdater = $systemConfig->getValue('upgrade.disable-web', false);
320
-		$tooBig = false;
321
-		if (!$disableWebUpdater) {
322
-			$apps = \OC::$server->getAppManager();
323
-			$tooBig = false;
324
-			if ($apps->isInstalled('user_ldap')) {
325
-				$qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
326
-
327
-				$result = $qb->selectAlias($qb->createFunction('COUNT(*)'), 'user_count')
328
-					->from('ldap_user_mapping')
329
-					->execute();
330
-				$row = $result->fetch();
331
-				$result->closeCursor();
332
-
333
-				$tooBig = ($row['user_count'] > 50);
334
-			}
335
-			if (!$tooBig && $apps->isInstalled('user_saml')) {
336
-				$qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
337
-
338
-				$result = $qb->selectAlias($qb->createFunction('COUNT(*)'), 'user_count')
339
-					->from('user_saml_users')
340
-					->execute();
341
-				$row = $result->fetch();
342
-				$result->closeCursor();
343
-
344
-				$tooBig = ($row['user_count'] > 50);
345
-			}
346
-			if (!$tooBig) {
347
-				// count users
348
-				$stats = \OC::$server->getUserManager()->countUsers();
349
-				$totalUsers = array_sum($stats);
350
-				$tooBig = ($totalUsers > 50);
351
-			}
352
-		}
353
-		$ignoreTooBigWarning = isset($_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup']) &&
354
-			$_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup'] === 'IAmSuperSureToDoThis';
355
-
356
-		if ($disableWebUpdater || ($tooBig && !$ignoreTooBigWarning)) {
357
-			// send http status 503
358
-			header('HTTP/1.1 503 Service Temporarily Unavailable');
359
-			header('Status: 503 Service Temporarily Unavailable');
360
-			header('Retry-After: 120');
361
-
362
-			// render error page
363
-			$template = new OC_Template('', 'update.use-cli', 'guest');
364
-			$template->assign('productName', 'nextcloud'); // for now
365
-			$template->assign('version', OC_Util::getVersionString());
366
-			$template->assign('tooBig', $tooBig);
367
-
368
-			$template->printPage();
369
-			die();
370
-		}
371
-
372
-		// check whether this is a core update or apps update
373
-		$installedVersion = $systemConfig->getValue('version', '0.0.0');
374
-		$currentVersion = implode('.', \OCP\Util::getVersion());
375
-
376
-		// if not a core upgrade, then it's apps upgrade
377
-		$isAppsOnlyUpgrade = (version_compare($currentVersion, $installedVersion, '='));
378
-
379
-		$oldTheme = $systemConfig->getValue('theme');
380
-		$systemConfig->setValue('theme', '');
381
-		OC_Util::addScript('config'); // needed for web root
382
-		OC_Util::addScript('update');
383
-
384
-		/** @var \OC\App\AppManager $appManager */
385
-		$appManager = \OC::$server->getAppManager();
386
-
387
-		$tmpl = new OC_Template('', 'update.admin', 'guest');
388
-		$tmpl->assign('version', OC_Util::getVersionString());
389
-		$tmpl->assign('isAppsOnlyUpgrade', $isAppsOnlyUpgrade);
390
-
391
-		// get third party apps
392
-		$ocVersion = \OCP\Util::getVersion();
393
-		$incompatibleApps = $appManager->getIncompatibleApps($ocVersion);
394
-		$incompatibleShippedApps = [];
395
-		foreach ($incompatibleApps as $appInfo) {
396
-			if ($appManager->isShipped($appInfo['id'])) {
397
-				$incompatibleShippedApps[] = $appInfo['name'] . ' (' . $appInfo['id'] . ')';
398
-			}
399
-		}
400
-
401
-		if (!empty($incompatibleShippedApps)) {
402
-			$l = \OC::$server->getL10N('core');
403
-			$hint = $l->t('The files of the app %$1s were not replaced correctly. Make sure it is a version compatible with the server.', [implode(', ', $incompatibleShippedApps)]);
404
-			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);
405
-		}
406
-
407
-		$tmpl->assign('appsToUpgrade', $appManager->getAppsNeedingUpgrade($ocVersion));
408
-		$tmpl->assign('incompatibleAppsList', $incompatibleApps);
409
-		$tmpl->assign('productName', 'Nextcloud'); // for now
410
-		$tmpl->assign('oldTheme', $oldTheme);
411
-		$tmpl->printPage();
412
-	}
413
-
414
-	public static function initSession() {
415
-		// prevents javascript from accessing php session cookies
416
-		ini_set('session.cookie_httponly', true);
417
-
418
-		// set the cookie path to the Nextcloud directory
419
-		$cookie_path = OC::$WEBROOT ? : '/';
420
-		ini_set('session.cookie_path', $cookie_path);
421
-
422
-		// Let the session name be changed in the initSession Hook
423
-		$sessionName = OC_Util::getInstanceId();
424
-
425
-		try {
426
-			// Allow session apps to create a custom session object
427
-			$useCustomSession = false;
428
-			$session = self::$server->getSession();
429
-			OC_Hook::emit('OC', 'initSession', array('session' => &$session, 'sessionName' => &$sessionName, 'useCustomSession' => &$useCustomSession));
430
-			if (!$useCustomSession) {
431
-				// set the session name to the instance id - which is unique
432
-				$session = new \OC\Session\Internal($sessionName);
433
-			}
434
-
435
-			$cryptoWrapper = \OC::$server->getSessionCryptoWrapper();
436
-			$session = $cryptoWrapper->wrapSession($session);
437
-			self::$server->setSession($session);
438
-
439
-			// if session can't be started break with http 500 error
440
-		} catch (Exception $e) {
441
-			\OCP\Util::logException('base', $e);
442
-			//show the user a detailed error page
443
-			OC_Response::setStatus(OC_Response::STATUS_INTERNAL_SERVER_ERROR);
444
-			OC_Template::printExceptionErrorPage($e);
445
-			die();
446
-		}
447
-
448
-		$sessionLifeTime = self::getSessionLifeTime();
449
-
450
-		// session timeout
451
-		if ($session->exists('LAST_ACTIVITY') && (time() - $session->get('LAST_ACTIVITY') > $sessionLifeTime)) {
452
-			if (isset($_COOKIE[session_name()])) {
453
-				setcookie(session_name(), null, -1, self::$WEBROOT ? : '/');
454
-			}
455
-			\OC::$server->getUserSession()->logout();
456
-		}
457
-
458
-		$session->set('LAST_ACTIVITY', time());
459
-	}
460
-
461
-	/**
462
-	 * @return string
463
-	 */
464
-	private static function getSessionLifeTime() {
465
-		return \OC::$server->getConfig()->getSystemValue('session_lifetime', 60 * 60 * 24);
466
-	}
467
-
468
-	public static function loadAppClassPaths() {
469
-		foreach (OC_App::getEnabledApps() as $app) {
470
-			$appPath = OC_App::getAppPath($app);
471
-			if ($appPath === false) {
472
-				continue;
473
-			}
474
-
475
-			$file = $appPath . '/appinfo/classpath.php';
476
-			if (file_exists($file)) {
477
-				require_once $file;
478
-			}
479
-		}
480
-	}
481
-
482
-	/**
483
-	 * Try to set some values to the required Nextcloud default
484
-	 */
485
-	public static function setRequiredIniValues() {
486
-		@ini_set('default_charset', 'UTF-8');
487
-		@ini_set('gd.jpeg_ignore_warning', 1);
488
-	}
489
-
490
-	/**
491
-	 * Send the same site cookies
492
-	 */
493
-	private static function sendSameSiteCookies() {
494
-		$cookieParams = session_get_cookie_params();
495
-		$secureCookie = ($cookieParams['secure'] === true) ? 'secure; ' : '';
496
-		$policies = [
497
-			'lax',
498
-			'strict',
499
-		];
500
-
501
-		// Append __Host to the cookie if it meets the requirements
502
-		$cookiePrefix = '';
503
-		if($cookieParams['secure'] === true && $cookieParams['path'] === '/') {
504
-			$cookiePrefix = '__Host-';
505
-		}
506
-
507
-		foreach($policies as $policy) {
508
-			header(
509
-				sprintf(
510
-					'Set-Cookie: %snc_sameSiteCookie%s=true; path=%s; httponly;' . $secureCookie . 'expires=Fri, 31-Dec-2100 23:59:59 GMT; SameSite=%s',
511
-					$cookiePrefix,
512
-					$policy,
513
-					$cookieParams['path'],
514
-					$policy
515
-				),
516
-				false
517
-			);
518
-		}
519
-	}
520
-
521
-	/**
522
-	 * Same Site cookie to further mitigate CSRF attacks. This cookie has to
523
-	 * be set in every request if cookies are sent to add a second level of
524
-	 * defense against CSRF.
525
-	 *
526
-	 * If the cookie is not sent this will set the cookie and reload the page.
527
-	 * We use an additional cookie since we want to protect logout CSRF and
528
-	 * also we can't directly interfere with PHP's session mechanism.
529
-	 */
530
-	private static function performSameSiteCookieProtection() {
531
-		$request = \OC::$server->getRequest();
532
-
533
-		// Some user agents are notorious and don't really properly follow HTTP
534
-		// specifications. For those, have an automated opt-out. Since the protection
535
-		// for remote.php is applied in base.php as starting point we need to opt out
536
-		// here.
537
-		$incompatibleUserAgents = [
538
-			// OS X Finder
539
-			'/^WebDAVFS/',
540
-		];
541
-		if($request->isUserAgent($incompatibleUserAgents)) {
542
-			return;
543
-		}
544
-
545
-		if(count($_COOKIE) > 0) {
546
-			$requestUri = $request->getScriptName();
547
-			$processingScript = explode('/', $requestUri);
548
-			$processingScript = $processingScript[count($processingScript)-1];
549
-
550
-			// index.php routes are handled in the middleware
551
-			if($processingScript === 'index.php') {
552
-				return;
553
-			}
554
-
555
-			// All other endpoints require the lax and the strict cookie
556
-			if(!$request->passesStrictCookieCheck()) {
557
-				self::sendSameSiteCookies();
558
-				// Debug mode gets access to the resources without strict cookie
559
-				// due to the fact that the SabreDAV browser also lives there.
560
-				if(!\OC::$server->getConfig()->getSystemValue('debug', false)) {
561
-					http_response_code(\OCP\AppFramework\Http::STATUS_SERVICE_UNAVAILABLE);
562
-					exit();
563
-				}
564
-			}
565
-		} elseif(!isset($_COOKIE['nc_sameSiteCookielax']) || !isset($_COOKIE['nc_sameSiteCookiestrict'])) {
566
-			self::sendSameSiteCookies();
567
-		}
568
-	}
569
-
570
-	public static function init() {
571
-		// calculate the root directories
572
-		OC::$SERVERROOT = str_replace("\\", '/', substr(__DIR__, 0, -4));
573
-
574
-		// register autoloader
575
-		$loaderStart = microtime(true);
576
-		require_once __DIR__ . '/autoloader.php';
577
-		self::$loader = new \OC\Autoloader([
578
-			OC::$SERVERROOT . '/lib/private/legacy',
579
-		]);
580
-		if (defined('PHPUNIT_RUN')) {
581
-			self::$loader->addValidRoot(OC::$SERVERROOT . '/tests');
582
-		}
583
-		spl_autoload_register(array(self::$loader, 'load'));
584
-		$loaderEnd = microtime(true);
585
-
586
-		self::$CLI = (php_sapi_name() == 'cli');
587
-
588
-		// Add default composer PSR-4 autoloader
589
-		self::$composerAutoloader = require_once OC::$SERVERROOT . '/lib/composer/autoload.php';
590
-
591
-		try {
592
-			self::initPaths();
593
-			// setup 3rdparty autoloader
594
-			$vendorAutoLoad = OC::$SERVERROOT. '/3rdparty/autoload.php';
595
-			if (!file_exists($vendorAutoLoad)) {
596
-				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".');
597
-			}
598
-			require_once $vendorAutoLoad;
599
-
600
-		} catch (\RuntimeException $e) {
601
-			if (!self::$CLI) {
602
-				$claimedProtocol = strtoupper($_SERVER['SERVER_PROTOCOL']);
603
-				$protocol = in_array($claimedProtocol, ['HTTP/1.0', 'HTTP/1.1', 'HTTP/2']) ? $claimedProtocol : 'HTTP/1.1';
604
-				header($protocol . ' ' . OC_Response::STATUS_SERVICE_UNAVAILABLE);
605
-			}
606
-			// we can't use the template error page here, because this needs the
607
-			// DI container which isn't available yet
608
-			print($e->getMessage());
609
-			exit();
610
-		}
611
-
612
-		// setup the basic server
613
-		self::$server = new \OC\Server(\OC::$WEBROOT, self::$config);
614
-		\OC::$server->getEventLogger()->log('autoloader', 'Autoloader', $loaderStart, $loaderEnd);
615
-		\OC::$server->getEventLogger()->start('boot', 'Initialize');
616
-
617
-		// Don't display errors and log them
618
-		error_reporting(E_ALL | E_STRICT);
619
-		@ini_set('display_errors', 0);
620
-		@ini_set('log_errors', 1);
621
-
622
-		if(!date_default_timezone_set('UTC')) {
623
-			throw new \RuntimeException('Could not set timezone to UTC');
624
-		};
625
-
626
-		//try to configure php to enable big file uploads.
627
-		//this doesn´t work always depending on the webserver and php configuration.
628
-		//Let´s try to overwrite some defaults anyway
629
-
630
-		//try to set the maximum execution time to 60min
631
-		if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
632
-			@set_time_limit(3600);
633
-		}
634
-		@ini_set('max_execution_time', 3600);
635
-		@ini_set('max_input_time', 3600);
636
-
637
-		//try to set the maximum filesize to 10G
638
-		@ini_set('upload_max_filesize', '10G');
639
-		@ini_set('post_max_size', '10G');
640
-		@ini_set('file_uploads', '50');
641
-
642
-		self::setRequiredIniValues();
643
-		self::handleAuthHeaders();
644
-		self::registerAutoloaderCache();
645
-
646
-		// initialize intl fallback is necessary
647
-		\Patchwork\Utf8\Bootup::initIntl();
648
-		OC_Util::isSetLocaleWorking();
649
-
650
-		if (!defined('PHPUNIT_RUN')) {
651
-			OC\Log\ErrorHandler::setLogger(\OC::$server->getLogger());
652
-			$debug = \OC::$server->getConfig()->getSystemValue('debug', false);
653
-			OC\Log\ErrorHandler::register($debug);
654
-		}
655
-
656
-		\OC::$server->getEventLogger()->start('init_session', 'Initialize session');
657
-		OC_App::loadApps(array('session'));
658
-		if (!self::$CLI) {
659
-			self::initSession();
660
-		}
661
-		\OC::$server->getEventLogger()->end('init_session');
662
-		self::checkConfig();
663
-		self::checkInstalled();
664
-
665
-		OC_Response::addSecurityHeaders();
666
-		if(self::$server->getRequest()->getServerProtocol() === 'https') {
667
-			ini_set('session.cookie_secure', true);
668
-		}
669
-
670
-		self::performSameSiteCookieProtection();
671
-
672
-		if (!defined('OC_CONSOLE')) {
673
-			$errors = OC_Util::checkServer(\OC::$server->getSystemConfig());
674
-			if (count($errors) > 0) {
675
-				if (self::$CLI) {
676
-					// Convert l10n string into regular string for usage in database
677
-					$staticErrors = [];
678
-					foreach ($errors as $error) {
679
-						echo $error['error'] . "\n";
680
-						echo $error['hint'] . "\n\n";
681
-						$staticErrors[] = [
682
-							'error' => (string)$error['error'],
683
-							'hint' => (string)$error['hint'],
684
-						];
685
-					}
686
-
687
-					try {
688
-						\OC::$server->getConfig()->setAppValue('core', 'cronErrors', json_encode($staticErrors));
689
-					} catch (\Exception $e) {
690
-						echo('Writing to database failed');
691
-					}
692
-					exit(1);
693
-				} else {
694
-					OC_Response::setStatus(OC_Response::STATUS_SERVICE_UNAVAILABLE);
695
-					OC_Util::addStyle('guest');
696
-					OC_Template::printGuestPage('', 'error', array('errors' => $errors));
697
-					exit;
698
-				}
699
-			} elseif (self::$CLI && \OC::$server->getConfig()->getSystemValue('installed', false)) {
700
-				\OC::$server->getConfig()->deleteAppValue('core', 'cronErrors');
701
-			}
702
-		}
703
-		//try to set the session lifetime
704
-		$sessionLifeTime = self::getSessionLifeTime();
705
-		@ini_set('gc_maxlifetime', (string)$sessionLifeTime);
706
-
707
-		$systemConfig = \OC::$server->getSystemConfig();
708
-
709
-		// User and Groups
710
-		if (!$systemConfig->getValue("installed", false)) {
711
-			self::$server->getSession()->set('user_id', '');
712
-		}
713
-
714
-		OC_User::useBackend(new \OC\User\Database());
715
-		\OC::$server->getGroupManager()->addBackend(new \OC\Group\Database());
716
-
717
-		// Subscribe to the hook
718
-		\OCP\Util::connectHook(
719
-			'\OCA\Files_Sharing\API\Server2Server',
720
-			'preLoginNameUsedAsUserName',
721
-			'\OC\User\Database',
722
-			'preLoginNameUsedAsUserName'
723
-		);
724
-
725
-		//setup extra user backends
726
-		if (!self::checkUpgrade(false)) {
727
-			OC_User::setupBackends();
728
-		} else {
729
-			// Run upgrades in incognito mode
730
-			OC_User::setIncognitoMode(true);
731
-		}
732
-
733
-		self::registerCleanupHooks();
734
-		self::registerFilesystemHooks();
735
-		self::registerShareHooks();
736
-		self::registerEncryptionWrapper();
737
-		self::registerEncryptionHooks();
738
-		self::registerAccountHooks();
739
-		self::registerSettingsHooks();
740
-
741
-		$settings = new \OC\Settings\Application();
742
-		$settings->register();
743
-
744
-		//make sure temporary files are cleaned up
745
-		$tmpManager = \OC::$server->getTempManager();
746
-		register_shutdown_function(array($tmpManager, 'clean'));
747
-		$lockProvider = \OC::$server->getLockingProvider();
748
-		register_shutdown_function(array($lockProvider, 'releaseAll'));
749
-
750
-		// Check whether the sample configuration has been copied
751
-		if($systemConfig->getValue('copied_sample_config', false)) {
752
-			$l = \OC::$server->getL10N('lib');
753
-			header('HTTP/1.1 503 Service Temporarily Unavailable');
754
-			header('Status: 503 Service Temporarily Unavailable');
755
-			OC_Template::printErrorPage(
756
-				$l->t('Sample configuration detected'),
757
-				$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')
758
-			);
759
-			return;
760
-		}
761
-
762
-		$request = \OC::$server->getRequest();
763
-		$host = $request->getInsecureServerHost();
764
-		/**
765
-		 * if the host passed in headers isn't trusted
766
-		 * FIXME: Should not be in here at all :see_no_evil:
767
-		 */
768
-		if (!OC::$CLI
769
-			// overwritehost is always trusted, workaround to not have to make
770
-			// \OC\AppFramework\Http\Request::getOverwriteHost public
771
-			&& self::$server->getConfig()->getSystemValue('overwritehost') === ''
772
-			&& !\OC::$server->getTrustedDomainHelper()->isTrustedDomain($host)
773
-			&& self::$server->getConfig()->getSystemValue('installed', false)
774
-		) {
775
-			// Allow access to CSS resources
776
-			$isScssRequest = false;
777
-			if(strpos($request->getPathInfo(), '/css/') === 0) {
778
-				$isScssRequest = true;
779
-			}
780
-
781
-			if (!$isScssRequest) {
782
-				header('HTTP/1.1 400 Bad Request');
783
-				header('Status: 400 Bad Request');
784
-
785
-				\OC::$server->getLogger()->warning(
786
-					'Trusted domain error. "{remoteAddress}" tried to access using "{host}" as host.',
787
-					[
788
-						'app' => 'core',
789
-						'remoteAddress' => $request->getRemoteAddress(),
790
-						'host' => $host,
791
-					]
792
-				);
793
-
794
-				$tmpl = new OCP\Template('core', 'untrustedDomain', 'guest');
795
-				$tmpl->assign('domain', $host);
796
-				$tmpl->printPage();
797
-
798
-				exit();
799
-			}
800
-		}
801
-		\OC::$server->getEventLogger()->end('boot');
802
-	}
803
-
804
-	/**
805
-	 * register hooks for the cleanup of cache and bruteforce protection
806
-	 */
807
-	public static function registerCleanupHooks() {
808
-		//don't try to do this before we are properly setup
809
-		if (\OC::$server->getSystemConfig()->getValue('installed', false) && !self::checkUpgrade(false)) {
810
-
811
-			// NOTE: This will be replaced to use OCP
812
-			$userSession = self::$server->getUserSession();
813
-			$userSession->listen('\OC\User', 'postLogin', function () use ($userSession) {
814
-				if (!defined('PHPUNIT_RUN')) {
815
-					// reset brute force delay for this IP address and username
816
-					$uid = \OC::$server->getUserSession()->getUser()->getUID();
817
-					$request = \OC::$server->getRequest();
818
-					$throttler = \OC::$server->getBruteForceThrottler();
819
-					$throttler->resetDelay($request->getRemoteAddress(), 'login', ['user' => $uid]);
820
-				}
821
-
822
-				try {
823
-					$cache = new \OC\Cache\File();
824
-					$cache->gc();
825
-				} catch (\OC\ServerNotAvailableException $e) {
826
-					// not a GC exception, pass it on
827
-					throw $e;
828
-				} catch (\OC\ForbiddenException $e) {
829
-					// filesystem blocked for this request, ignore
830
-				} catch (\Exception $e) {
831
-					// a GC exception should not prevent users from using OC,
832
-					// so log the exception
833
-					\OC::$server->getLogger()->warning('Exception when running cache gc: ' . $e->getMessage(), array('app' => 'core'));
834
-				}
835
-			});
836
-		}
837
-	}
838
-
839
-	public static function registerSettingsHooks() {
840
-		$dispatcher = \OC::$server->getEventDispatcher();
841
-		$dispatcher->addListener(OCP\App\ManagerEvent::EVENT_APP_DISABLE, function($event) {
842
-			/** @var \OCP\App\ManagerEvent $event */
843
-			\OC::$server->getSettingsManager()->onAppDisabled($event->getAppID());
844
-		});
845
-		$dispatcher->addListener(OCP\App\ManagerEvent::EVENT_APP_UPDATE, function($event) {
846
-			/** @var \OCP\App\ManagerEvent $event */
847
-			$jobList = \OC::$server->getJobList();
848
-			$job = 'OC\\Settings\\RemoveOrphaned';
849
-			if(!($jobList->has($job, null))) {
850
-				$jobList->add($job);
851
-			}
852
-		});
853
-	}
854
-
855
-	private static function registerEncryptionWrapper() {
856
-		$manager = self::$server->getEncryptionManager();
857
-		\OCP\Util::connectHook('OC_Filesystem', 'preSetup', $manager, 'setupStorage');
858
-	}
859
-
860
-	private static function registerEncryptionHooks() {
861
-		$enabled = self::$server->getEncryptionManager()->isEnabled();
862
-		if ($enabled) {
863
-			\OCP\Util::connectHook('OCP\Share', 'post_shared', 'OC\Encryption\HookManager', 'postShared');
864
-			\OCP\Util::connectHook('OCP\Share', 'post_unshare', 'OC\Encryption\HookManager', 'postUnshared');
865
-			\OCP\Util::connectHook('OC_Filesystem', 'post_rename', 'OC\Encryption\HookManager', 'postRename');
866
-			\OCP\Util::connectHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', 'OC\Encryption\HookManager', 'postRestore');
867
-		}
868
-	}
869
-
870
-	private static function registerAccountHooks() {
871
-		$hookHandler = new \OC\Accounts\Hooks(\OC::$server->getLogger());
872
-		\OCP\Util::connectHook('OC_User', 'changeUser', $hookHandler, 'changeUserHook');
873
-	}
874
-
875
-	/**
876
-	 * register hooks for the filesystem
877
-	 */
878
-	public static function registerFilesystemHooks() {
879
-		// Check for blacklisted files
880
-		OC_Hook::connect('OC_Filesystem', 'write', 'OC\Files\Filesystem', 'isBlacklisted');
881
-		OC_Hook::connect('OC_Filesystem', 'rename', 'OC\Files\Filesystem', 'isBlacklisted');
882
-	}
883
-
884
-	/**
885
-	 * register hooks for sharing
886
-	 */
887
-	public static function registerShareHooks() {
888
-		if (\OC::$server->getSystemConfig()->getValue('installed')) {
889
-			OC_Hook::connect('OC_User', 'post_deleteUser', 'OC\Share20\Hooks', 'post_deleteUser');
890
-			OC_Hook::connect('OC_User', 'post_removeFromGroup', 'OC\Share20\Hooks', 'post_removeFromGroup');
891
-			OC_Hook::connect('OC_User', 'post_deleteGroup', 'OC\Share20\Hooks', 'post_deleteGroup');
892
-		}
893
-	}
894
-
895
-	protected static function registerAutoloaderCache() {
896
-		// The class loader takes an optional low-latency cache, which MUST be
897
-		// namespaced. The instanceid is used for namespacing, but might be
898
-		// unavailable at this point. Furthermore, it might not be possible to
899
-		// generate an instanceid via \OC_Util::getInstanceId() because the
900
-		// config file may not be writable. As such, we only register a class
901
-		// loader cache if instanceid is available without trying to create one.
902
-		$instanceId = \OC::$server->getSystemConfig()->getValue('instanceid', null);
903
-		if ($instanceId) {
904
-			try {
905
-				$memcacheFactory = \OC::$server->getMemCacheFactory();
906
-				self::$loader->setMemoryCache($memcacheFactory->createLocal('Autoloader'));
907
-			} catch (\Exception $ex) {
908
-			}
909
-		}
910
-	}
911
-
912
-	/**
913
-	 * Handle the request
914
-	 */
915
-	public static function handleRequest() {
916
-
917
-		\OC::$server->getEventLogger()->start('handle_request', 'Handle request');
918
-		$systemConfig = \OC::$server->getSystemConfig();
919
-		// load all the classpaths from the enabled apps so they are available
920
-		// in the routing files of each app
921
-		OC::loadAppClassPaths();
922
-
923
-		// Check if Nextcloud is installed or in maintenance (update) mode
924
-		if (!$systemConfig->getValue('installed', false)) {
925
-			\OC::$server->getSession()->clear();
926
-			$setupHelper = new OC\Setup(
927
-				\OC::$server->getSystemConfig(),
928
-				\OC::$server->getIniWrapper(),
929
-				\OC::$server->getL10N('lib'),
930
-				\OC::$server->query(\OCP\Defaults::class),
931
-				\OC::$server->getLogger(),
932
-				\OC::$server->getSecureRandom(),
933
-				\OC::$server->query(\OC\Installer::class)
934
-			);
935
-			$controller = new OC\Core\Controller\SetupController($setupHelper);
936
-			$controller->run($_POST);
937
-			exit();
938
-		}
939
-
940
-		$request = \OC::$server->getRequest();
941
-		$requestPath = $request->getRawPathInfo();
942
-		if ($requestPath === '/heartbeat') {
943
-			return;
944
-		}
945
-		if (substr($requestPath, -3) !== '.js') { // we need these files during the upgrade
946
-			self::checkMaintenanceMode();
947
-			self::checkUpgrade();
948
-		}
949
-
950
-		// emergency app disabling
951
-		if ($requestPath === '/disableapp'
952
-			&& $request->getMethod() === 'POST'
953
-			&& ((array)$request->getParam('appid')) !== ''
954
-		) {
955
-			\OCP\JSON::callCheck();
956
-			\OCP\JSON::checkAdminUser();
957
-			$appIds = (array)$request->getParam('appid');
958
-			foreach($appIds as $appId) {
959
-				$appId = \OC_App::cleanAppId($appId);
960
-				\OC_App::disable($appId);
961
-			}
962
-			\OC_JSON::success();
963
-			exit();
964
-		}
965
-
966
-		// Always load authentication apps
967
-		OC_App::loadApps(['authentication']);
968
-
969
-		// Load minimum set of apps
970
-		if (!self::checkUpgrade(false)
971
-			&& !$systemConfig->getValue('maintenance', false)) {
972
-			// For logged-in users: Load everything
973
-			if(\OC::$server->getUserSession()->isLoggedIn()) {
974
-				OC_App::loadApps();
975
-			} else {
976
-				// For guests: Load only filesystem and logging
977
-				OC_App::loadApps(array('filesystem', 'logging'));
978
-				self::handleLogin($request);
979
-			}
980
-		}
981
-
982
-		if (!self::$CLI) {
983
-			try {
984
-				if (!$systemConfig->getValue('maintenance', false) && !self::checkUpgrade(false)) {
985
-					OC_App::loadApps(array('filesystem', 'logging'));
986
-					OC_App::loadApps();
987
-				}
988
-				OC_Util::setupFS();
989
-				OC::$server->getRouter()->match(\OC::$server->getRequest()->getRawPathInfo());
990
-				return;
991
-			} catch (Symfony\Component\Routing\Exception\ResourceNotFoundException $e) {
992
-				//header('HTTP/1.0 404 Not Found');
993
-			} catch (Symfony\Component\Routing\Exception\MethodNotAllowedException $e) {
994
-				OC_Response::setStatus(405);
995
-				return;
996
-			}
997
-		}
998
-
999
-		// Handle WebDAV
1000
-		if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'PROPFIND') {
1001
-			// not allowed any more to prevent people
1002
-			// mounting this root directly.
1003
-			// Users need to mount remote.php/webdav instead.
1004
-			header('HTTP/1.1 405 Method Not Allowed');
1005
-			header('Status: 405 Method Not Allowed');
1006
-			return;
1007
-		}
1008
-
1009
-		// Someone is logged in
1010
-		if (\OC::$server->getUserSession()->isLoggedIn()) {
1011
-			OC_App::loadApps();
1012
-			OC_User::setupBackends();
1013
-			OC_Util::setupFS();
1014
-			// FIXME
1015
-			// Redirect to default application
1016
-			OC_Util::redirectToDefaultPage();
1017
-		} else {
1018
-			// Not handled and not logged in
1019
-			header('Location: '.\OC::$server->getURLGenerator()->linkToRouteAbsolute('core.login.showLoginForm'));
1020
-		}
1021
-	}
1022
-
1023
-	/**
1024
-	 * Check login: apache auth, auth token, basic auth
1025
-	 *
1026
-	 * @param OCP\IRequest $request
1027
-	 * @return boolean
1028
-	 */
1029
-	static function handleLogin(OCP\IRequest $request) {
1030
-		$userSession = self::$server->getUserSession();
1031
-		if (OC_User::handleApacheAuth()) {
1032
-			return true;
1033
-		}
1034
-		if ($userSession->tryTokenLogin($request)) {
1035
-			return true;
1036
-		}
1037
-		if (isset($_COOKIE['nc_username'])
1038
-			&& isset($_COOKIE['nc_token'])
1039
-			&& isset($_COOKIE['nc_session_id'])
1040
-			&& $userSession->loginWithCookie($_COOKIE['nc_username'], $_COOKIE['nc_token'], $_COOKIE['nc_session_id'])) {
1041
-			return true;
1042
-		}
1043
-		if ($userSession->tryBasicAuthLogin($request, \OC::$server->getBruteForceThrottler())) {
1044
-			return true;
1045
-		}
1046
-		return false;
1047
-	}
1048
-
1049
-	protected static function handleAuthHeaders() {
1050
-		//copy http auth headers for apache+php-fcgid work around
1051
-		if (isset($_SERVER['HTTP_XAUTHORIZATION']) && !isset($_SERVER['HTTP_AUTHORIZATION'])) {
1052
-			$_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['HTTP_XAUTHORIZATION'];
1053
-		}
1054
-
1055
-		// Extract PHP_AUTH_USER/PHP_AUTH_PW from other headers if necessary.
1056
-		$vars = array(
1057
-			'HTTP_AUTHORIZATION', // apache+php-cgi work around
1058
-			'REDIRECT_HTTP_AUTHORIZATION', // apache+php-cgi alternative
1059
-		);
1060
-		foreach ($vars as $var) {
1061
-			if (isset($_SERVER[$var]) && preg_match('/Basic\s+(.*)$/i', $_SERVER[$var], $matches)) {
1062
-				list($name, $password) = explode(':', base64_decode($matches[1]), 2);
1063
-				$_SERVER['PHP_AUTH_USER'] = $name;
1064
-				$_SERVER['PHP_AUTH_PW'] = $password;
1065
-				break;
1066
-			}
1067
-		}
1068
-	}
65
+    /**
66
+     * Associative array for autoloading. classname => filename
67
+     */
68
+    public static $CLASSPATH = array();
69
+    /**
70
+     * The installation path for Nextcloud  on the server (e.g. /srv/http/nextcloud)
71
+     */
72
+    public static $SERVERROOT = '';
73
+    /**
74
+     * the current request path relative to the Nextcloud root (e.g. files/index.php)
75
+     */
76
+    private static $SUBURI = '';
77
+    /**
78
+     * the Nextcloud root path for http requests (e.g. nextcloud/)
79
+     */
80
+    public static $WEBROOT = '';
81
+    /**
82
+     * The installation path array of the apps folder on the server (e.g. /srv/http/nextcloud) 'path' and
83
+     * web path in 'url'
84
+     */
85
+    public static $APPSROOTS = array();
86
+
87
+    /**
88
+     * @var string
89
+     */
90
+    public static $configDir;
91
+
92
+    /**
93
+     * requested app
94
+     */
95
+    public static $REQUESTEDAPP = '';
96
+
97
+    /**
98
+     * check if Nextcloud runs in cli mode
99
+     */
100
+    public static $CLI = false;
101
+
102
+    /**
103
+     * @var \OC\Autoloader $loader
104
+     */
105
+    public static $loader = null;
106
+
107
+    /** @var \Composer\Autoload\ClassLoader $composerAutoloader */
108
+    public static $composerAutoloader = null;
109
+
110
+    /**
111
+     * @var \OC\Server
112
+     */
113
+    public static $server = null;
114
+
115
+    /**
116
+     * @var \OC\Config
117
+     */
118
+    private static $config = null;
119
+
120
+    /**
121
+     * @throws \RuntimeException when the 3rdparty directory is missing or
122
+     * the app path list is empty or contains an invalid path
123
+     */
124
+    public static function initPaths() {
125
+        if(defined('PHPUNIT_CONFIG_DIR')) {
126
+            self::$configDir = OC::$SERVERROOT . '/' . PHPUNIT_CONFIG_DIR . '/';
127
+        } elseif(defined('PHPUNIT_RUN') and PHPUNIT_RUN and is_dir(OC::$SERVERROOT . '/tests/config/')) {
128
+            self::$configDir = OC::$SERVERROOT . '/tests/config/';
129
+        } elseif($dir = getenv('NEXTCLOUD_CONFIG_DIR')) {
130
+            self::$configDir = rtrim($dir, '/') . '/';
131
+        } else {
132
+            self::$configDir = OC::$SERVERROOT . '/config/';
133
+        }
134
+        self::$config = new \OC\Config(self::$configDir);
135
+
136
+        OC::$SUBURI = str_replace("\\", "/", substr(realpath($_SERVER["SCRIPT_FILENAME"]), strlen(OC::$SERVERROOT)));
137
+        /**
138
+         * FIXME: The following lines are required because we can't yet instantiate
139
+         *        \OC::$server->getRequest() since \OC::$server does not yet exist.
140
+         */
141
+        $params = [
142
+            'server' => [
143
+                'SCRIPT_NAME' => $_SERVER['SCRIPT_NAME'],
144
+                'SCRIPT_FILENAME' => $_SERVER['SCRIPT_FILENAME'],
145
+            ],
146
+        ];
147
+        $fakeRequest = new \OC\AppFramework\Http\Request($params, null, new \OC\AllConfig(new \OC\SystemConfig(self::$config)));
148
+        $scriptName = $fakeRequest->getScriptName();
149
+        if (substr($scriptName, -1) == '/') {
150
+            $scriptName .= 'index.php';
151
+            //make sure suburi follows the same rules as scriptName
152
+            if (substr(OC::$SUBURI, -9) != 'index.php') {
153
+                if (substr(OC::$SUBURI, -1) != '/') {
154
+                    OC::$SUBURI = OC::$SUBURI . '/';
155
+                }
156
+                OC::$SUBURI = OC::$SUBURI . 'index.php';
157
+            }
158
+        }
159
+
160
+
161
+        if (OC::$CLI) {
162
+            OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
163
+        } else {
164
+            if (substr($scriptName, 0 - strlen(OC::$SUBURI)) === OC::$SUBURI) {
165
+                OC::$WEBROOT = substr($scriptName, 0, 0 - strlen(OC::$SUBURI));
166
+
167
+                if (OC::$WEBROOT != '' && OC::$WEBROOT[0] !== '/') {
168
+                    OC::$WEBROOT = '/' . OC::$WEBROOT;
169
+                }
170
+            } else {
171
+                // The scriptName is not ending with OC::$SUBURI
172
+                // This most likely means that we are calling from CLI.
173
+                // However some cron jobs still need to generate
174
+                // a web URL, so we use overwritewebroot as a fallback.
175
+                OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
176
+            }
177
+
178
+            // Resolve /nextcloud to /nextcloud/ to ensure to always have a trailing
179
+            // slash which is required by URL generation.
180
+            if (isset($_SERVER['REQUEST_URI']) && $_SERVER['REQUEST_URI'] === \OC::$WEBROOT &&
181
+                    substr($_SERVER['REQUEST_URI'], -1) !== '/') {
182
+                header('Location: '.\OC::$WEBROOT.'/');
183
+                exit();
184
+            }
185
+        }
186
+
187
+        // search the apps folder
188
+        $config_paths = self::$config->getValue('apps_paths', array());
189
+        if (!empty($config_paths)) {
190
+            foreach ($config_paths as $paths) {
191
+                if (isset($paths['url']) && isset($paths['path'])) {
192
+                    $paths['url'] = rtrim($paths['url'], '/');
193
+                    $paths['path'] = rtrim($paths['path'], '/');
194
+                    OC::$APPSROOTS[] = $paths;
195
+                }
196
+            }
197
+        } elseif (file_exists(OC::$SERVERROOT . '/apps')) {
198
+            OC::$APPSROOTS[] = array('path' => OC::$SERVERROOT . '/apps', 'url' => '/apps', 'writable' => true);
199
+        } elseif (file_exists(OC::$SERVERROOT . '/../apps')) {
200
+            OC::$APPSROOTS[] = array(
201
+                'path' => rtrim(dirname(OC::$SERVERROOT), '/') . '/apps',
202
+                'url' => '/apps',
203
+                'writable' => true
204
+            );
205
+        }
206
+
207
+        if (empty(OC::$APPSROOTS)) {
208
+            throw new \RuntimeException('apps directory not found! Please put the Nextcloud apps folder in the Nextcloud folder'
209
+                . ' or the folder above. You can also configure the location in the config.php file.');
210
+        }
211
+        $paths = array();
212
+        foreach (OC::$APPSROOTS as $path) {
213
+            $paths[] = $path['path'];
214
+            if (!is_dir($path['path'])) {
215
+                throw new \RuntimeException(sprintf('App directory "%s" not found! Please put the Nextcloud apps folder in the'
216
+                    . ' Nextcloud folder or the folder above. You can also configure the location in the'
217
+                    . ' config.php file.', $path['path']));
218
+            }
219
+        }
220
+
221
+        // set the right include path
222
+        set_include_path(
223
+            implode(PATH_SEPARATOR, $paths)
224
+        );
225
+    }
226
+
227
+    public static function checkConfig() {
228
+        $l = \OC::$server->getL10N('lib');
229
+
230
+        // Create config if it does not already exist
231
+        $configFilePath = self::$configDir .'/config.php';
232
+        if(!file_exists($configFilePath)) {
233
+            @touch($configFilePath);
234
+        }
235
+
236
+        // Check if config is writable
237
+        $configFileWritable = is_writable($configFilePath);
238
+        if (!$configFileWritable && !OC_Helper::isReadOnlyConfigEnabled()
239
+            || !$configFileWritable && self::checkUpgrade(false)) {
240
+
241
+            $urlGenerator = \OC::$server->getURLGenerator();
242
+
243
+            if (self::$CLI) {
244
+                echo $l->t('Cannot write into "config" directory!')."\n";
245
+                echo $l->t('This can usually be fixed by giving the webserver write access to the config directory')."\n";
246
+                echo "\n";
247
+                echo $l->t('See %s', [ $urlGenerator->linkToDocs('admin-dir_permissions') ])."\n";
248
+                exit;
249
+            } else {
250
+                OC_Template::printErrorPage(
251
+                    $l->t('Cannot write into "config" directory!'),
252
+                    $l->t('This can usually be fixed by giving the webserver write access to the config directory. See %s',
253
+                        [ $urlGenerator->linkToDocs('admin-dir_permissions') ])
254
+                );
255
+            }
256
+        }
257
+    }
258
+
259
+    public static function checkInstalled() {
260
+        if (defined('OC_CONSOLE')) {
261
+            return;
262
+        }
263
+        // Redirect to installer if not installed
264
+        if (!\OC::$server->getSystemConfig()->getValue('installed', false) && OC::$SUBURI !== '/index.php' && OC::$SUBURI !== '/status.php') {
265
+            if (OC::$CLI) {
266
+                throw new Exception('Not installed');
267
+            } else {
268
+                $url = OC::$WEBROOT . '/index.php';
269
+                header('Location: ' . $url);
270
+            }
271
+            exit();
272
+        }
273
+    }
274
+
275
+    public static function checkMaintenanceMode() {
276
+        // Allow ajax update script to execute without being stopped
277
+        if (\OC::$server->getSystemConfig()->getValue('maintenance', false) && OC::$SUBURI != '/core/ajax/update.php') {
278
+            // send http status 503
279
+            header('HTTP/1.1 503 Service Temporarily Unavailable');
280
+            header('Status: 503 Service Temporarily Unavailable');
281
+            header('Retry-After: 120');
282
+
283
+            // render error page
284
+            $template = new OC_Template('', 'update.user', 'guest');
285
+            OC_Util::addScript('maintenance-check');
286
+            OC_Util::addStyle('core', 'guest');
287
+            $template->printPage();
288
+            die();
289
+        }
290
+    }
291
+
292
+    /**
293
+     * Checks if the version requires an update and shows
294
+     * @param bool $showTemplate Whether an update screen should get shown
295
+     * @return bool|void
296
+     */
297
+    public static function checkUpgrade($showTemplate = true) {
298
+        if (\OCP\Util::needUpgrade()) {
299
+            if (function_exists('opcache_reset')) {
300
+                opcache_reset();
301
+            }
302
+            $systemConfig = \OC::$server->getSystemConfig();
303
+            if ($showTemplate && !$systemConfig->getValue('maintenance', false)) {
304
+                self::printUpgradePage();
305
+                exit();
306
+            } else {
307
+                return true;
308
+            }
309
+        }
310
+        return false;
311
+    }
312
+
313
+    /**
314
+     * Prints the upgrade page
315
+     */
316
+    private static function printUpgradePage() {
317
+        $systemConfig = \OC::$server->getSystemConfig();
318
+
319
+        $disableWebUpdater = $systemConfig->getValue('upgrade.disable-web', false);
320
+        $tooBig = false;
321
+        if (!$disableWebUpdater) {
322
+            $apps = \OC::$server->getAppManager();
323
+            $tooBig = false;
324
+            if ($apps->isInstalled('user_ldap')) {
325
+                $qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
326
+
327
+                $result = $qb->selectAlias($qb->createFunction('COUNT(*)'), 'user_count')
328
+                    ->from('ldap_user_mapping')
329
+                    ->execute();
330
+                $row = $result->fetch();
331
+                $result->closeCursor();
332
+
333
+                $tooBig = ($row['user_count'] > 50);
334
+            }
335
+            if (!$tooBig && $apps->isInstalled('user_saml')) {
336
+                $qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
337
+
338
+                $result = $qb->selectAlias($qb->createFunction('COUNT(*)'), 'user_count')
339
+                    ->from('user_saml_users')
340
+                    ->execute();
341
+                $row = $result->fetch();
342
+                $result->closeCursor();
343
+
344
+                $tooBig = ($row['user_count'] > 50);
345
+            }
346
+            if (!$tooBig) {
347
+                // count users
348
+                $stats = \OC::$server->getUserManager()->countUsers();
349
+                $totalUsers = array_sum($stats);
350
+                $tooBig = ($totalUsers > 50);
351
+            }
352
+        }
353
+        $ignoreTooBigWarning = isset($_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup']) &&
354
+            $_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup'] === 'IAmSuperSureToDoThis';
355
+
356
+        if ($disableWebUpdater || ($tooBig && !$ignoreTooBigWarning)) {
357
+            // send http status 503
358
+            header('HTTP/1.1 503 Service Temporarily Unavailable');
359
+            header('Status: 503 Service Temporarily Unavailable');
360
+            header('Retry-After: 120');
361
+
362
+            // render error page
363
+            $template = new OC_Template('', 'update.use-cli', 'guest');
364
+            $template->assign('productName', 'nextcloud'); // for now
365
+            $template->assign('version', OC_Util::getVersionString());
366
+            $template->assign('tooBig', $tooBig);
367
+
368
+            $template->printPage();
369
+            die();
370
+        }
371
+
372
+        // check whether this is a core update or apps update
373
+        $installedVersion = $systemConfig->getValue('version', '0.0.0');
374
+        $currentVersion = implode('.', \OCP\Util::getVersion());
375
+
376
+        // if not a core upgrade, then it's apps upgrade
377
+        $isAppsOnlyUpgrade = (version_compare($currentVersion, $installedVersion, '='));
378
+
379
+        $oldTheme = $systemConfig->getValue('theme');
380
+        $systemConfig->setValue('theme', '');
381
+        OC_Util::addScript('config'); // needed for web root
382
+        OC_Util::addScript('update');
383
+
384
+        /** @var \OC\App\AppManager $appManager */
385
+        $appManager = \OC::$server->getAppManager();
386
+
387
+        $tmpl = new OC_Template('', 'update.admin', 'guest');
388
+        $tmpl->assign('version', OC_Util::getVersionString());
389
+        $tmpl->assign('isAppsOnlyUpgrade', $isAppsOnlyUpgrade);
390
+
391
+        // get third party apps
392
+        $ocVersion = \OCP\Util::getVersion();
393
+        $incompatibleApps = $appManager->getIncompatibleApps($ocVersion);
394
+        $incompatibleShippedApps = [];
395
+        foreach ($incompatibleApps as $appInfo) {
396
+            if ($appManager->isShipped($appInfo['id'])) {
397
+                $incompatibleShippedApps[] = $appInfo['name'] . ' (' . $appInfo['id'] . ')';
398
+            }
399
+        }
400
+
401
+        if (!empty($incompatibleShippedApps)) {
402
+            $l = \OC::$server->getL10N('core');
403
+            $hint = $l->t('The files of the app %$1s were not replaced correctly. Make sure it is a version compatible with the server.', [implode(', ', $incompatibleShippedApps)]);
404
+            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);
405
+        }
406
+
407
+        $tmpl->assign('appsToUpgrade', $appManager->getAppsNeedingUpgrade($ocVersion));
408
+        $tmpl->assign('incompatibleAppsList', $incompatibleApps);
409
+        $tmpl->assign('productName', 'Nextcloud'); // for now
410
+        $tmpl->assign('oldTheme', $oldTheme);
411
+        $tmpl->printPage();
412
+    }
413
+
414
+    public static function initSession() {
415
+        // prevents javascript from accessing php session cookies
416
+        ini_set('session.cookie_httponly', true);
417
+
418
+        // set the cookie path to the Nextcloud directory
419
+        $cookie_path = OC::$WEBROOT ? : '/';
420
+        ini_set('session.cookie_path', $cookie_path);
421
+
422
+        // Let the session name be changed in the initSession Hook
423
+        $sessionName = OC_Util::getInstanceId();
424
+
425
+        try {
426
+            // Allow session apps to create a custom session object
427
+            $useCustomSession = false;
428
+            $session = self::$server->getSession();
429
+            OC_Hook::emit('OC', 'initSession', array('session' => &$session, 'sessionName' => &$sessionName, 'useCustomSession' => &$useCustomSession));
430
+            if (!$useCustomSession) {
431
+                // set the session name to the instance id - which is unique
432
+                $session = new \OC\Session\Internal($sessionName);
433
+            }
434
+
435
+            $cryptoWrapper = \OC::$server->getSessionCryptoWrapper();
436
+            $session = $cryptoWrapper->wrapSession($session);
437
+            self::$server->setSession($session);
438
+
439
+            // if session can't be started break with http 500 error
440
+        } catch (Exception $e) {
441
+            \OCP\Util::logException('base', $e);
442
+            //show the user a detailed error page
443
+            OC_Response::setStatus(OC_Response::STATUS_INTERNAL_SERVER_ERROR);
444
+            OC_Template::printExceptionErrorPage($e);
445
+            die();
446
+        }
447
+
448
+        $sessionLifeTime = self::getSessionLifeTime();
449
+
450
+        // session timeout
451
+        if ($session->exists('LAST_ACTIVITY') && (time() - $session->get('LAST_ACTIVITY') > $sessionLifeTime)) {
452
+            if (isset($_COOKIE[session_name()])) {
453
+                setcookie(session_name(), null, -1, self::$WEBROOT ? : '/');
454
+            }
455
+            \OC::$server->getUserSession()->logout();
456
+        }
457
+
458
+        $session->set('LAST_ACTIVITY', time());
459
+    }
460
+
461
+    /**
462
+     * @return string
463
+     */
464
+    private static function getSessionLifeTime() {
465
+        return \OC::$server->getConfig()->getSystemValue('session_lifetime', 60 * 60 * 24);
466
+    }
467
+
468
+    public static function loadAppClassPaths() {
469
+        foreach (OC_App::getEnabledApps() as $app) {
470
+            $appPath = OC_App::getAppPath($app);
471
+            if ($appPath === false) {
472
+                continue;
473
+            }
474
+
475
+            $file = $appPath . '/appinfo/classpath.php';
476
+            if (file_exists($file)) {
477
+                require_once $file;
478
+            }
479
+        }
480
+    }
481
+
482
+    /**
483
+     * Try to set some values to the required Nextcloud default
484
+     */
485
+    public static function setRequiredIniValues() {
486
+        @ini_set('default_charset', 'UTF-8');
487
+        @ini_set('gd.jpeg_ignore_warning', 1);
488
+    }
489
+
490
+    /**
491
+     * Send the same site cookies
492
+     */
493
+    private static function sendSameSiteCookies() {
494
+        $cookieParams = session_get_cookie_params();
495
+        $secureCookie = ($cookieParams['secure'] === true) ? 'secure; ' : '';
496
+        $policies = [
497
+            'lax',
498
+            'strict',
499
+        ];
500
+
501
+        // Append __Host to the cookie if it meets the requirements
502
+        $cookiePrefix = '';
503
+        if($cookieParams['secure'] === true && $cookieParams['path'] === '/') {
504
+            $cookiePrefix = '__Host-';
505
+        }
506
+
507
+        foreach($policies as $policy) {
508
+            header(
509
+                sprintf(
510
+                    'Set-Cookie: %snc_sameSiteCookie%s=true; path=%s; httponly;' . $secureCookie . 'expires=Fri, 31-Dec-2100 23:59:59 GMT; SameSite=%s',
511
+                    $cookiePrefix,
512
+                    $policy,
513
+                    $cookieParams['path'],
514
+                    $policy
515
+                ),
516
+                false
517
+            );
518
+        }
519
+    }
520
+
521
+    /**
522
+     * Same Site cookie to further mitigate CSRF attacks. This cookie has to
523
+     * be set in every request if cookies are sent to add a second level of
524
+     * defense against CSRF.
525
+     *
526
+     * If the cookie is not sent this will set the cookie and reload the page.
527
+     * We use an additional cookie since we want to protect logout CSRF and
528
+     * also we can't directly interfere with PHP's session mechanism.
529
+     */
530
+    private static function performSameSiteCookieProtection() {
531
+        $request = \OC::$server->getRequest();
532
+
533
+        // Some user agents are notorious and don't really properly follow HTTP
534
+        // specifications. For those, have an automated opt-out. Since the protection
535
+        // for remote.php is applied in base.php as starting point we need to opt out
536
+        // here.
537
+        $incompatibleUserAgents = [
538
+            // OS X Finder
539
+            '/^WebDAVFS/',
540
+        ];
541
+        if($request->isUserAgent($incompatibleUserAgents)) {
542
+            return;
543
+        }
544
+
545
+        if(count($_COOKIE) > 0) {
546
+            $requestUri = $request->getScriptName();
547
+            $processingScript = explode('/', $requestUri);
548
+            $processingScript = $processingScript[count($processingScript)-1];
549
+
550
+            // index.php routes are handled in the middleware
551
+            if($processingScript === 'index.php') {
552
+                return;
553
+            }
554
+
555
+            // All other endpoints require the lax and the strict cookie
556
+            if(!$request->passesStrictCookieCheck()) {
557
+                self::sendSameSiteCookies();
558
+                // Debug mode gets access to the resources without strict cookie
559
+                // due to the fact that the SabreDAV browser also lives there.
560
+                if(!\OC::$server->getConfig()->getSystemValue('debug', false)) {
561
+                    http_response_code(\OCP\AppFramework\Http::STATUS_SERVICE_UNAVAILABLE);
562
+                    exit();
563
+                }
564
+            }
565
+        } elseif(!isset($_COOKIE['nc_sameSiteCookielax']) || !isset($_COOKIE['nc_sameSiteCookiestrict'])) {
566
+            self::sendSameSiteCookies();
567
+        }
568
+    }
569
+
570
+    public static function init() {
571
+        // calculate the root directories
572
+        OC::$SERVERROOT = str_replace("\\", '/', substr(__DIR__, 0, -4));
573
+
574
+        // register autoloader
575
+        $loaderStart = microtime(true);
576
+        require_once __DIR__ . '/autoloader.php';
577
+        self::$loader = new \OC\Autoloader([
578
+            OC::$SERVERROOT . '/lib/private/legacy',
579
+        ]);
580
+        if (defined('PHPUNIT_RUN')) {
581
+            self::$loader->addValidRoot(OC::$SERVERROOT . '/tests');
582
+        }
583
+        spl_autoload_register(array(self::$loader, 'load'));
584
+        $loaderEnd = microtime(true);
585
+
586
+        self::$CLI = (php_sapi_name() == 'cli');
587
+
588
+        // Add default composer PSR-4 autoloader
589
+        self::$composerAutoloader = require_once OC::$SERVERROOT . '/lib/composer/autoload.php';
590
+
591
+        try {
592
+            self::initPaths();
593
+            // setup 3rdparty autoloader
594
+            $vendorAutoLoad = OC::$SERVERROOT. '/3rdparty/autoload.php';
595
+            if (!file_exists($vendorAutoLoad)) {
596
+                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".');
597
+            }
598
+            require_once $vendorAutoLoad;
599
+
600
+        } catch (\RuntimeException $e) {
601
+            if (!self::$CLI) {
602
+                $claimedProtocol = strtoupper($_SERVER['SERVER_PROTOCOL']);
603
+                $protocol = in_array($claimedProtocol, ['HTTP/1.0', 'HTTP/1.1', 'HTTP/2']) ? $claimedProtocol : 'HTTP/1.1';
604
+                header($protocol . ' ' . OC_Response::STATUS_SERVICE_UNAVAILABLE);
605
+            }
606
+            // we can't use the template error page here, because this needs the
607
+            // DI container which isn't available yet
608
+            print($e->getMessage());
609
+            exit();
610
+        }
611
+
612
+        // setup the basic server
613
+        self::$server = new \OC\Server(\OC::$WEBROOT, self::$config);
614
+        \OC::$server->getEventLogger()->log('autoloader', 'Autoloader', $loaderStart, $loaderEnd);
615
+        \OC::$server->getEventLogger()->start('boot', 'Initialize');
616
+
617
+        // Don't display errors and log them
618
+        error_reporting(E_ALL | E_STRICT);
619
+        @ini_set('display_errors', 0);
620
+        @ini_set('log_errors', 1);
621
+
622
+        if(!date_default_timezone_set('UTC')) {
623
+            throw new \RuntimeException('Could not set timezone to UTC');
624
+        };
625
+
626
+        //try to configure php to enable big file uploads.
627
+        //this doesn´t work always depending on the webserver and php configuration.
628
+        //Let´s try to overwrite some defaults anyway
629
+
630
+        //try to set the maximum execution time to 60min
631
+        if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
632
+            @set_time_limit(3600);
633
+        }
634
+        @ini_set('max_execution_time', 3600);
635
+        @ini_set('max_input_time', 3600);
636
+
637
+        //try to set the maximum filesize to 10G
638
+        @ini_set('upload_max_filesize', '10G');
639
+        @ini_set('post_max_size', '10G');
640
+        @ini_set('file_uploads', '50');
641
+
642
+        self::setRequiredIniValues();
643
+        self::handleAuthHeaders();
644
+        self::registerAutoloaderCache();
645
+
646
+        // initialize intl fallback is necessary
647
+        \Patchwork\Utf8\Bootup::initIntl();
648
+        OC_Util::isSetLocaleWorking();
649
+
650
+        if (!defined('PHPUNIT_RUN')) {
651
+            OC\Log\ErrorHandler::setLogger(\OC::$server->getLogger());
652
+            $debug = \OC::$server->getConfig()->getSystemValue('debug', false);
653
+            OC\Log\ErrorHandler::register($debug);
654
+        }
655
+
656
+        \OC::$server->getEventLogger()->start('init_session', 'Initialize session');
657
+        OC_App::loadApps(array('session'));
658
+        if (!self::$CLI) {
659
+            self::initSession();
660
+        }
661
+        \OC::$server->getEventLogger()->end('init_session');
662
+        self::checkConfig();
663
+        self::checkInstalled();
664
+
665
+        OC_Response::addSecurityHeaders();
666
+        if(self::$server->getRequest()->getServerProtocol() === 'https') {
667
+            ini_set('session.cookie_secure', true);
668
+        }
669
+
670
+        self::performSameSiteCookieProtection();
671
+
672
+        if (!defined('OC_CONSOLE')) {
673
+            $errors = OC_Util::checkServer(\OC::$server->getSystemConfig());
674
+            if (count($errors) > 0) {
675
+                if (self::$CLI) {
676
+                    // Convert l10n string into regular string for usage in database
677
+                    $staticErrors = [];
678
+                    foreach ($errors as $error) {
679
+                        echo $error['error'] . "\n";
680
+                        echo $error['hint'] . "\n\n";
681
+                        $staticErrors[] = [
682
+                            'error' => (string)$error['error'],
683
+                            'hint' => (string)$error['hint'],
684
+                        ];
685
+                    }
686
+
687
+                    try {
688
+                        \OC::$server->getConfig()->setAppValue('core', 'cronErrors', json_encode($staticErrors));
689
+                    } catch (\Exception $e) {
690
+                        echo('Writing to database failed');
691
+                    }
692
+                    exit(1);
693
+                } else {
694
+                    OC_Response::setStatus(OC_Response::STATUS_SERVICE_UNAVAILABLE);
695
+                    OC_Util::addStyle('guest');
696
+                    OC_Template::printGuestPage('', 'error', array('errors' => $errors));
697
+                    exit;
698
+                }
699
+            } elseif (self::$CLI && \OC::$server->getConfig()->getSystemValue('installed', false)) {
700
+                \OC::$server->getConfig()->deleteAppValue('core', 'cronErrors');
701
+            }
702
+        }
703
+        //try to set the session lifetime
704
+        $sessionLifeTime = self::getSessionLifeTime();
705
+        @ini_set('gc_maxlifetime', (string)$sessionLifeTime);
706
+
707
+        $systemConfig = \OC::$server->getSystemConfig();
708
+
709
+        // User and Groups
710
+        if (!$systemConfig->getValue("installed", false)) {
711
+            self::$server->getSession()->set('user_id', '');
712
+        }
713
+
714
+        OC_User::useBackend(new \OC\User\Database());
715
+        \OC::$server->getGroupManager()->addBackend(new \OC\Group\Database());
716
+
717
+        // Subscribe to the hook
718
+        \OCP\Util::connectHook(
719
+            '\OCA\Files_Sharing\API\Server2Server',
720
+            'preLoginNameUsedAsUserName',
721
+            '\OC\User\Database',
722
+            'preLoginNameUsedAsUserName'
723
+        );
724
+
725
+        //setup extra user backends
726
+        if (!self::checkUpgrade(false)) {
727
+            OC_User::setupBackends();
728
+        } else {
729
+            // Run upgrades in incognito mode
730
+            OC_User::setIncognitoMode(true);
731
+        }
732
+
733
+        self::registerCleanupHooks();
734
+        self::registerFilesystemHooks();
735
+        self::registerShareHooks();
736
+        self::registerEncryptionWrapper();
737
+        self::registerEncryptionHooks();
738
+        self::registerAccountHooks();
739
+        self::registerSettingsHooks();
740
+
741
+        $settings = new \OC\Settings\Application();
742
+        $settings->register();
743
+
744
+        //make sure temporary files are cleaned up
745
+        $tmpManager = \OC::$server->getTempManager();
746
+        register_shutdown_function(array($tmpManager, 'clean'));
747
+        $lockProvider = \OC::$server->getLockingProvider();
748
+        register_shutdown_function(array($lockProvider, 'releaseAll'));
749
+
750
+        // Check whether the sample configuration has been copied
751
+        if($systemConfig->getValue('copied_sample_config', false)) {
752
+            $l = \OC::$server->getL10N('lib');
753
+            header('HTTP/1.1 503 Service Temporarily Unavailable');
754
+            header('Status: 503 Service Temporarily Unavailable');
755
+            OC_Template::printErrorPage(
756
+                $l->t('Sample configuration detected'),
757
+                $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')
758
+            );
759
+            return;
760
+        }
761
+
762
+        $request = \OC::$server->getRequest();
763
+        $host = $request->getInsecureServerHost();
764
+        /**
765
+         * if the host passed in headers isn't trusted
766
+         * FIXME: Should not be in here at all :see_no_evil:
767
+         */
768
+        if (!OC::$CLI
769
+            // overwritehost is always trusted, workaround to not have to make
770
+            // \OC\AppFramework\Http\Request::getOverwriteHost public
771
+            && self::$server->getConfig()->getSystemValue('overwritehost') === ''
772
+            && !\OC::$server->getTrustedDomainHelper()->isTrustedDomain($host)
773
+            && self::$server->getConfig()->getSystemValue('installed', false)
774
+        ) {
775
+            // Allow access to CSS resources
776
+            $isScssRequest = false;
777
+            if(strpos($request->getPathInfo(), '/css/') === 0) {
778
+                $isScssRequest = true;
779
+            }
780
+
781
+            if (!$isScssRequest) {
782
+                header('HTTP/1.1 400 Bad Request');
783
+                header('Status: 400 Bad Request');
784
+
785
+                \OC::$server->getLogger()->warning(
786
+                    'Trusted domain error. "{remoteAddress}" tried to access using "{host}" as host.',
787
+                    [
788
+                        'app' => 'core',
789
+                        'remoteAddress' => $request->getRemoteAddress(),
790
+                        'host' => $host,
791
+                    ]
792
+                );
793
+
794
+                $tmpl = new OCP\Template('core', 'untrustedDomain', 'guest');
795
+                $tmpl->assign('domain', $host);
796
+                $tmpl->printPage();
797
+
798
+                exit();
799
+            }
800
+        }
801
+        \OC::$server->getEventLogger()->end('boot');
802
+    }
803
+
804
+    /**
805
+     * register hooks for the cleanup of cache and bruteforce protection
806
+     */
807
+    public static function registerCleanupHooks() {
808
+        //don't try to do this before we are properly setup
809
+        if (\OC::$server->getSystemConfig()->getValue('installed', false) && !self::checkUpgrade(false)) {
810
+
811
+            // NOTE: This will be replaced to use OCP
812
+            $userSession = self::$server->getUserSession();
813
+            $userSession->listen('\OC\User', 'postLogin', function () use ($userSession) {
814
+                if (!defined('PHPUNIT_RUN')) {
815
+                    // reset brute force delay for this IP address and username
816
+                    $uid = \OC::$server->getUserSession()->getUser()->getUID();
817
+                    $request = \OC::$server->getRequest();
818
+                    $throttler = \OC::$server->getBruteForceThrottler();
819
+                    $throttler->resetDelay($request->getRemoteAddress(), 'login', ['user' => $uid]);
820
+                }
821
+
822
+                try {
823
+                    $cache = new \OC\Cache\File();
824
+                    $cache->gc();
825
+                } catch (\OC\ServerNotAvailableException $e) {
826
+                    // not a GC exception, pass it on
827
+                    throw $e;
828
+                } catch (\OC\ForbiddenException $e) {
829
+                    // filesystem blocked for this request, ignore
830
+                } catch (\Exception $e) {
831
+                    // a GC exception should not prevent users from using OC,
832
+                    // so log the exception
833
+                    \OC::$server->getLogger()->warning('Exception when running cache gc: ' . $e->getMessage(), array('app' => 'core'));
834
+                }
835
+            });
836
+        }
837
+    }
838
+
839
+    public static function registerSettingsHooks() {
840
+        $dispatcher = \OC::$server->getEventDispatcher();
841
+        $dispatcher->addListener(OCP\App\ManagerEvent::EVENT_APP_DISABLE, function($event) {
842
+            /** @var \OCP\App\ManagerEvent $event */
843
+            \OC::$server->getSettingsManager()->onAppDisabled($event->getAppID());
844
+        });
845
+        $dispatcher->addListener(OCP\App\ManagerEvent::EVENT_APP_UPDATE, function($event) {
846
+            /** @var \OCP\App\ManagerEvent $event */
847
+            $jobList = \OC::$server->getJobList();
848
+            $job = 'OC\\Settings\\RemoveOrphaned';
849
+            if(!($jobList->has($job, null))) {
850
+                $jobList->add($job);
851
+            }
852
+        });
853
+    }
854
+
855
+    private static function registerEncryptionWrapper() {
856
+        $manager = self::$server->getEncryptionManager();
857
+        \OCP\Util::connectHook('OC_Filesystem', 'preSetup', $manager, 'setupStorage');
858
+    }
859
+
860
+    private static function registerEncryptionHooks() {
861
+        $enabled = self::$server->getEncryptionManager()->isEnabled();
862
+        if ($enabled) {
863
+            \OCP\Util::connectHook('OCP\Share', 'post_shared', 'OC\Encryption\HookManager', 'postShared');
864
+            \OCP\Util::connectHook('OCP\Share', 'post_unshare', 'OC\Encryption\HookManager', 'postUnshared');
865
+            \OCP\Util::connectHook('OC_Filesystem', 'post_rename', 'OC\Encryption\HookManager', 'postRename');
866
+            \OCP\Util::connectHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', 'OC\Encryption\HookManager', 'postRestore');
867
+        }
868
+    }
869
+
870
+    private static function registerAccountHooks() {
871
+        $hookHandler = new \OC\Accounts\Hooks(\OC::$server->getLogger());
872
+        \OCP\Util::connectHook('OC_User', 'changeUser', $hookHandler, 'changeUserHook');
873
+    }
874
+
875
+    /**
876
+     * register hooks for the filesystem
877
+     */
878
+    public static function registerFilesystemHooks() {
879
+        // Check for blacklisted files
880
+        OC_Hook::connect('OC_Filesystem', 'write', 'OC\Files\Filesystem', 'isBlacklisted');
881
+        OC_Hook::connect('OC_Filesystem', 'rename', 'OC\Files\Filesystem', 'isBlacklisted');
882
+    }
883
+
884
+    /**
885
+     * register hooks for sharing
886
+     */
887
+    public static function registerShareHooks() {
888
+        if (\OC::$server->getSystemConfig()->getValue('installed')) {
889
+            OC_Hook::connect('OC_User', 'post_deleteUser', 'OC\Share20\Hooks', 'post_deleteUser');
890
+            OC_Hook::connect('OC_User', 'post_removeFromGroup', 'OC\Share20\Hooks', 'post_removeFromGroup');
891
+            OC_Hook::connect('OC_User', 'post_deleteGroup', 'OC\Share20\Hooks', 'post_deleteGroup');
892
+        }
893
+    }
894
+
895
+    protected static function registerAutoloaderCache() {
896
+        // The class loader takes an optional low-latency cache, which MUST be
897
+        // namespaced. The instanceid is used for namespacing, but might be
898
+        // unavailable at this point. Furthermore, it might not be possible to
899
+        // generate an instanceid via \OC_Util::getInstanceId() because the
900
+        // config file may not be writable. As such, we only register a class
901
+        // loader cache if instanceid is available without trying to create one.
902
+        $instanceId = \OC::$server->getSystemConfig()->getValue('instanceid', null);
903
+        if ($instanceId) {
904
+            try {
905
+                $memcacheFactory = \OC::$server->getMemCacheFactory();
906
+                self::$loader->setMemoryCache($memcacheFactory->createLocal('Autoloader'));
907
+            } catch (\Exception $ex) {
908
+            }
909
+        }
910
+    }
911
+
912
+    /**
913
+     * Handle the request
914
+     */
915
+    public static function handleRequest() {
916
+
917
+        \OC::$server->getEventLogger()->start('handle_request', 'Handle request');
918
+        $systemConfig = \OC::$server->getSystemConfig();
919
+        // load all the classpaths from the enabled apps so they are available
920
+        // in the routing files of each app
921
+        OC::loadAppClassPaths();
922
+
923
+        // Check if Nextcloud is installed or in maintenance (update) mode
924
+        if (!$systemConfig->getValue('installed', false)) {
925
+            \OC::$server->getSession()->clear();
926
+            $setupHelper = new OC\Setup(
927
+                \OC::$server->getSystemConfig(),
928
+                \OC::$server->getIniWrapper(),
929
+                \OC::$server->getL10N('lib'),
930
+                \OC::$server->query(\OCP\Defaults::class),
931
+                \OC::$server->getLogger(),
932
+                \OC::$server->getSecureRandom(),
933
+                \OC::$server->query(\OC\Installer::class)
934
+            );
935
+            $controller = new OC\Core\Controller\SetupController($setupHelper);
936
+            $controller->run($_POST);
937
+            exit();
938
+        }
939
+
940
+        $request = \OC::$server->getRequest();
941
+        $requestPath = $request->getRawPathInfo();
942
+        if ($requestPath === '/heartbeat') {
943
+            return;
944
+        }
945
+        if (substr($requestPath, -3) !== '.js') { // we need these files during the upgrade
946
+            self::checkMaintenanceMode();
947
+            self::checkUpgrade();
948
+        }
949
+
950
+        // emergency app disabling
951
+        if ($requestPath === '/disableapp'
952
+            && $request->getMethod() === 'POST'
953
+            && ((array)$request->getParam('appid')) !== ''
954
+        ) {
955
+            \OCP\JSON::callCheck();
956
+            \OCP\JSON::checkAdminUser();
957
+            $appIds = (array)$request->getParam('appid');
958
+            foreach($appIds as $appId) {
959
+                $appId = \OC_App::cleanAppId($appId);
960
+                \OC_App::disable($appId);
961
+            }
962
+            \OC_JSON::success();
963
+            exit();
964
+        }
965
+
966
+        // Always load authentication apps
967
+        OC_App::loadApps(['authentication']);
968
+
969
+        // Load minimum set of apps
970
+        if (!self::checkUpgrade(false)
971
+            && !$systemConfig->getValue('maintenance', false)) {
972
+            // For logged-in users: Load everything
973
+            if(\OC::$server->getUserSession()->isLoggedIn()) {
974
+                OC_App::loadApps();
975
+            } else {
976
+                // For guests: Load only filesystem and logging
977
+                OC_App::loadApps(array('filesystem', 'logging'));
978
+                self::handleLogin($request);
979
+            }
980
+        }
981
+
982
+        if (!self::$CLI) {
983
+            try {
984
+                if (!$systemConfig->getValue('maintenance', false) && !self::checkUpgrade(false)) {
985
+                    OC_App::loadApps(array('filesystem', 'logging'));
986
+                    OC_App::loadApps();
987
+                }
988
+                OC_Util::setupFS();
989
+                OC::$server->getRouter()->match(\OC::$server->getRequest()->getRawPathInfo());
990
+                return;
991
+            } catch (Symfony\Component\Routing\Exception\ResourceNotFoundException $e) {
992
+                //header('HTTP/1.0 404 Not Found');
993
+            } catch (Symfony\Component\Routing\Exception\MethodNotAllowedException $e) {
994
+                OC_Response::setStatus(405);
995
+                return;
996
+            }
997
+        }
998
+
999
+        // Handle WebDAV
1000
+        if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'PROPFIND') {
1001
+            // not allowed any more to prevent people
1002
+            // mounting this root directly.
1003
+            // Users need to mount remote.php/webdav instead.
1004
+            header('HTTP/1.1 405 Method Not Allowed');
1005
+            header('Status: 405 Method Not Allowed');
1006
+            return;
1007
+        }
1008
+
1009
+        // Someone is logged in
1010
+        if (\OC::$server->getUserSession()->isLoggedIn()) {
1011
+            OC_App::loadApps();
1012
+            OC_User::setupBackends();
1013
+            OC_Util::setupFS();
1014
+            // FIXME
1015
+            // Redirect to default application
1016
+            OC_Util::redirectToDefaultPage();
1017
+        } else {
1018
+            // Not handled and not logged in
1019
+            header('Location: '.\OC::$server->getURLGenerator()->linkToRouteAbsolute('core.login.showLoginForm'));
1020
+        }
1021
+    }
1022
+
1023
+    /**
1024
+     * Check login: apache auth, auth token, basic auth
1025
+     *
1026
+     * @param OCP\IRequest $request
1027
+     * @return boolean
1028
+     */
1029
+    static function handleLogin(OCP\IRequest $request) {
1030
+        $userSession = self::$server->getUserSession();
1031
+        if (OC_User::handleApacheAuth()) {
1032
+            return true;
1033
+        }
1034
+        if ($userSession->tryTokenLogin($request)) {
1035
+            return true;
1036
+        }
1037
+        if (isset($_COOKIE['nc_username'])
1038
+            && isset($_COOKIE['nc_token'])
1039
+            && isset($_COOKIE['nc_session_id'])
1040
+            && $userSession->loginWithCookie($_COOKIE['nc_username'], $_COOKIE['nc_token'], $_COOKIE['nc_session_id'])) {
1041
+            return true;
1042
+        }
1043
+        if ($userSession->tryBasicAuthLogin($request, \OC::$server->getBruteForceThrottler())) {
1044
+            return true;
1045
+        }
1046
+        return false;
1047
+    }
1048
+
1049
+    protected static function handleAuthHeaders() {
1050
+        //copy http auth headers for apache+php-fcgid work around
1051
+        if (isset($_SERVER['HTTP_XAUTHORIZATION']) && !isset($_SERVER['HTTP_AUTHORIZATION'])) {
1052
+            $_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['HTTP_XAUTHORIZATION'];
1053
+        }
1054
+
1055
+        // Extract PHP_AUTH_USER/PHP_AUTH_PW from other headers if necessary.
1056
+        $vars = array(
1057
+            'HTTP_AUTHORIZATION', // apache+php-cgi work around
1058
+            'REDIRECT_HTTP_AUTHORIZATION', // apache+php-cgi alternative
1059
+        );
1060
+        foreach ($vars as $var) {
1061
+            if (isset($_SERVER[$var]) && preg_match('/Basic\s+(.*)$/i', $_SERVER[$var], $matches)) {
1062
+                list($name, $password) = explode(':', base64_decode($matches[1]), 2);
1063
+                $_SERVER['PHP_AUTH_USER'] = $name;
1064
+                $_SERVER['PHP_AUTH_PW'] = $password;
1065
+                break;
1066
+            }
1067
+        }
1068
+    }
1069 1069
 }
1070 1070
 
1071 1071
 OC::init();
Please login to merge, or discard this patch.