Passed
Push — master ( f1cc6c...fa7364 )
by Julius
15:37 queued 12s
created
lib/private/Server.php 1 patch
Indentation   +2089 added lines, -2089 removed lines patch added patch discarded remove patch
@@ -278,2098 +278,2098 @@
 block discarded – undo
278 278
  */
279 279
 class Server extends ServerContainer implements IServerContainer {
280 280
 
281
-	/** @var string */
282
-	private $webRoot;
283
-
284
-	/**
285
-	 * @param string $webRoot
286
-	 * @param \OC\Config $config
287
-	 */
288
-	public function __construct($webRoot, \OC\Config $config) {
289
-		parent::__construct();
290
-		$this->webRoot = $webRoot;
291
-
292
-		// To find out if we are running from CLI or not
293
-		$this->registerParameter('isCLI', \OC::$CLI);
294
-		$this->registerParameter('serverRoot', \OC::$SERVERROOT);
295
-
296
-		$this->registerService(ContainerInterface::class, function (ContainerInterface $c) {
297
-			return $c;
298
-		});
299
-		$this->registerService(\OCP\IServerContainer::class, function (ContainerInterface $c) {
300
-			return $c;
301
-		});
302
-
303
-		$this->registerAlias(\OCP\Calendar\IManager::class, \OC\Calendar\Manager::class);
304
-		/** @deprecated 19.0.0 */
305
-		$this->registerDeprecatedAlias('CalendarManager', \OC\Calendar\Manager::class);
306
-
307
-		$this->registerAlias(\OCP\Calendar\Resource\IManager::class, \OC\Calendar\Resource\Manager::class);
308
-		/** @deprecated 19.0.0 */
309
-		$this->registerDeprecatedAlias('CalendarResourceBackendManager', \OC\Calendar\Resource\Manager::class);
310
-
311
-		$this->registerAlias(\OCP\Calendar\Room\IManager::class, \OC\Calendar\Room\Manager::class);
312
-		/** @deprecated 19.0.0 */
313
-		$this->registerDeprecatedAlias('CalendarRoomBackendManager', \OC\Calendar\Room\Manager::class);
314
-
315
-		$this->registerAlias(\OCP\Contacts\IManager::class, \OC\ContactsManager::class);
316
-		/** @deprecated 19.0.0 */
317
-		$this->registerDeprecatedAlias('ContactsManager', \OCP\Contacts\IManager::class);
318
-
319
-		$this->registerAlias(\OCP\DirectEditing\IManager::class, \OC\DirectEditing\Manager::class);
320
-		$this->registerAlias(ITemplateManager::class, TemplateManager::class);
321
-
322
-		$this->registerAlias(IActionFactory::class, ActionFactory::class);
323
-
324
-		$this->registerService(View::class, function (Server $c) {
325
-			return new View();
326
-		}, false);
327
-
328
-		$this->registerService(IPreview::class, function (ContainerInterface $c) {
329
-			return new PreviewManager(
330
-				$c->get(\OCP\IConfig::class),
331
-				$c->get(IRootFolder::class),
332
-				new \OC\Preview\Storage\Root(
333
-					$c->get(IRootFolder::class),
334
-					$c->get(SystemConfig::class)
335
-				),
336
-				$c->get(IEventDispatcher::class),
337
-				$c->get(SymfonyAdapter::class),
338
-				$c->get(GeneratorHelper::class),
339
-				$c->get(ISession::class)->get('user_id'),
340
-				$c->get(Coordinator::class),
341
-				$c->get(IServerContainer::class),
342
-				$c->get(IBinaryFinder::class)
343
-			);
344
-		});
345
-		/** @deprecated 19.0.0 */
346
-		$this->registerDeprecatedAlias('PreviewManager', IPreview::class);
347
-
348
-		$this->registerService(\OC\Preview\Watcher::class, function (ContainerInterface $c) {
349
-			return new \OC\Preview\Watcher(
350
-				new \OC\Preview\Storage\Root(
351
-					$c->get(IRootFolder::class),
352
-					$c->get(SystemConfig::class)
353
-				)
354
-			);
355
-		});
356
-
357
-		$this->registerService(IProfiler::class, function (Server $c) {
358
-			return new Profiler($c->get(SystemConfig::class));
359
-		});
360
-
361
-		$this->registerService(\OCP\Encryption\IManager::class, function (Server $c): Encryption\Manager {
362
-			$view = new View();
363
-			$util = new Encryption\Util(
364
-				$view,
365
-				$c->get(IUserManager::class),
366
-				$c->get(IGroupManager::class),
367
-				$c->get(\OCP\IConfig::class)
368
-			);
369
-			return new Encryption\Manager(
370
-				$c->get(\OCP\IConfig::class),
371
-				$c->get(LoggerInterface::class),
372
-				$c->getL10N('core'),
373
-				new View(),
374
-				$util,
375
-				new ArrayCache()
376
-			);
377
-		});
378
-		/** @deprecated 19.0.0 */
379
-		$this->registerDeprecatedAlias('EncryptionManager', \OCP\Encryption\IManager::class);
380
-
381
-		/** @deprecated 21.0.0 */
382
-		$this->registerDeprecatedAlias('EncryptionFileHelper', IFile::class);
383
-		$this->registerService(IFile::class, function (ContainerInterface $c) {
384
-			$util = new Encryption\Util(
385
-				new View(),
386
-				$c->get(IUserManager::class),
387
-				$c->get(IGroupManager::class),
388
-				$c->get(\OCP\IConfig::class)
389
-			);
390
-			return new Encryption\File(
391
-				$util,
392
-				$c->get(IRootFolder::class),
393
-				$c->get(\OCP\Share\IManager::class)
394
-			);
395
-		});
396
-
397
-		/** @deprecated 21.0.0 */
398
-		$this->registerDeprecatedAlias('EncryptionKeyStorage', IStorage::class);
399
-		$this->registerService(IStorage::class, function (ContainerInterface $c) {
400
-			$view = new View();
401
-			$util = new Encryption\Util(
402
-				$view,
403
-				$c->get(IUserManager::class),
404
-				$c->get(IGroupManager::class),
405
-				$c->get(\OCP\IConfig::class)
406
-			);
407
-
408
-			return new Encryption\Keys\Storage(
409
-				$view,
410
-				$util,
411
-				$c->get(ICrypto::class),
412
-				$c->get(\OCP\IConfig::class)
413
-			);
414
-		});
415
-		/** @deprecated 20.0.0 */
416
-		$this->registerDeprecatedAlias('TagMapper', TagMapper::class);
417
-
418
-		$this->registerAlias(\OCP\ITagManager::class, TagManager::class);
419
-		/** @deprecated 19.0.0 */
420
-		$this->registerDeprecatedAlias('TagManager', \OCP\ITagManager::class);
421
-
422
-		$this->registerService('SystemTagManagerFactory', function (ContainerInterface $c) {
423
-			/** @var \OCP\IConfig $config */
424
-			$config = $c->get(\OCP\IConfig::class);
425
-			$factoryClass = $config->getSystemValue('systemtags.managerFactory', SystemTagManagerFactory::class);
426
-			return new $factoryClass($this);
427
-		});
428
-		$this->registerService(ISystemTagManager::class, function (ContainerInterface $c) {
429
-			return $c->get('SystemTagManagerFactory')->getManager();
430
-		});
431
-		/** @deprecated 19.0.0 */
432
-		$this->registerDeprecatedAlias('SystemTagManager', ISystemTagManager::class);
433
-
434
-		$this->registerService(ISystemTagObjectMapper::class, function (ContainerInterface $c) {
435
-			return $c->get('SystemTagManagerFactory')->getObjectMapper();
436
-		});
437
-		$this->registerService('RootFolder', function (ContainerInterface $c) {
438
-			$manager = \OC\Files\Filesystem::getMountManager(null);
439
-			$view = new View();
440
-			$root = new Root(
441
-				$manager,
442
-				$view,
443
-				null,
444
-				$c->get(IUserMountCache::class),
445
-				$this->get(LoggerInterface::class),
446
-				$this->get(IUserManager::class),
447
-				$this->get(IEventDispatcher::class),
448
-			);
449
-
450
-			$previewConnector = new \OC\Preview\WatcherConnector(
451
-				$root,
452
-				$c->get(SystemConfig::class)
453
-			);
454
-			$previewConnector->connectWatcher();
455
-
456
-			return $root;
457
-		});
458
-		$this->registerService(HookConnector::class, function (ContainerInterface $c) {
459
-			return new HookConnector(
460
-				$c->get(IRootFolder::class),
461
-				new View(),
462
-				$c->get(\OC\EventDispatcher\SymfonyAdapter::class),
463
-				$c->get(IEventDispatcher::class)
464
-			);
465
-		});
466
-
467
-		/** @deprecated 19.0.0 */
468
-		$this->registerDeprecatedAlias('SystemTagObjectMapper', ISystemTagObjectMapper::class);
469
-
470
-		$this->registerService(IRootFolder::class, function (ContainerInterface $c) {
471
-			return new LazyRoot(function () use ($c) {
472
-				return $c->get('RootFolder');
473
-			});
474
-		});
475
-		/** @deprecated 19.0.0 */
476
-		$this->registerDeprecatedAlias('LazyRootFolder', IRootFolder::class);
477
-
478
-		/** @deprecated 19.0.0 */
479
-		$this->registerDeprecatedAlias('UserManager', \OC\User\Manager::class);
480
-		$this->registerAlias(\OCP\IUserManager::class, \OC\User\Manager::class);
481
-
482
-		$this->registerService(DisplayNameCache::class, function (ContainerInterface $c) {
483
-			return $c->get(\OC\User\Manager::class)->getDisplayNameCache();
484
-		});
485
-
486
-		$this->registerService(\OCP\IGroupManager::class, function (ContainerInterface $c) {
487
-			$groupManager = new \OC\Group\Manager(
488
-				$this->get(IUserManager::class),
489
-				$c->get(SymfonyAdapter::class),
490
-				$this->get(LoggerInterface::class),
491
-				$this->get(ICacheFactory::class)
492
-			);
493
-			$groupManager->listen('\OC\Group', 'preCreate', function ($gid) {
494
-				/** @var IEventDispatcher $dispatcher */
495
-				$dispatcher = $this->get(IEventDispatcher::class);
496
-				$dispatcher->dispatchTyped(new BeforeGroupCreatedEvent($gid));
497
-			});
498
-			$groupManager->listen('\OC\Group', 'postCreate', function (\OC\Group\Group $group) {
499
-				/** @var IEventDispatcher $dispatcher */
500
-				$dispatcher = $this->get(IEventDispatcher::class);
501
-				$dispatcher->dispatchTyped(new GroupCreatedEvent($group));
502
-			});
503
-			$groupManager->listen('\OC\Group', 'preDelete', function (\OC\Group\Group $group) {
504
-				/** @var IEventDispatcher $dispatcher */
505
-				$dispatcher = $this->get(IEventDispatcher::class);
506
-				$dispatcher->dispatchTyped(new BeforeGroupDeletedEvent($group));
507
-			});
508
-			$groupManager->listen('\OC\Group', 'postDelete', function (\OC\Group\Group $group) {
509
-				/** @var IEventDispatcher $dispatcher */
510
-				$dispatcher = $this->get(IEventDispatcher::class);
511
-				$dispatcher->dispatchTyped(new GroupDeletedEvent($group));
512
-			});
513
-			$groupManager->listen('\OC\Group', 'preAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
514
-				/** @var IEventDispatcher $dispatcher */
515
-				$dispatcher = $this->get(IEventDispatcher::class);
516
-				$dispatcher->dispatchTyped(new BeforeUserAddedEvent($group, $user));
517
-			});
518
-			$groupManager->listen('\OC\Group', 'postAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
519
-				/** @var IEventDispatcher $dispatcher */
520
-				$dispatcher = $this->get(IEventDispatcher::class);
521
-				$dispatcher->dispatchTyped(new UserAddedEvent($group, $user));
522
-			});
523
-			$groupManager->listen('\OC\Group', 'preRemoveUser', function (\OC\Group\Group $group, \OC\User\User $user) {
524
-				/** @var IEventDispatcher $dispatcher */
525
-				$dispatcher = $this->get(IEventDispatcher::class);
526
-				$dispatcher->dispatchTyped(new BeforeUserRemovedEvent($group, $user));
527
-			});
528
-			$groupManager->listen('\OC\Group', 'postRemoveUser', function (\OC\Group\Group $group, \OC\User\User $user) {
529
-				/** @var IEventDispatcher $dispatcher */
530
-				$dispatcher = $this->get(IEventDispatcher::class);
531
-				$dispatcher->dispatchTyped(new UserRemovedEvent($group, $user));
532
-			});
533
-			return $groupManager;
534
-		});
535
-		/** @deprecated 19.0.0 */
536
-		$this->registerDeprecatedAlias('GroupManager', \OCP\IGroupManager::class);
537
-
538
-		$this->registerService(Store::class, function (ContainerInterface $c) {
539
-			$session = $c->get(ISession::class);
540
-			if (\OC::$server->get(SystemConfig::class)->getValue('installed', false)) {
541
-				$tokenProvider = $c->get(IProvider::class);
542
-			} else {
543
-				$tokenProvider = null;
544
-			}
545
-			$logger = $c->get(LoggerInterface::class);
546
-			return new Store($session, $logger, $tokenProvider);
547
-		});
548
-		$this->registerAlias(IStore::class, Store::class);
549
-		$this->registerAlias(IProvider::class, Authentication\Token\Manager::class);
550
-
551
-		$this->registerService(\OC\User\Session::class, function (Server $c) {
552
-			$manager = $c->get(IUserManager::class);
553
-			$session = new \OC\Session\Memory('');
554
-			$timeFactory = new TimeFactory();
555
-			// Token providers might require a working database. This code
556
-			// might however be called when Nextcloud is not yet setup.
557
-			if (\OC::$server->get(SystemConfig::class)->getValue('installed', false)) {
558
-				$provider = $c->get(IProvider::class);
559
-			} else {
560
-				$provider = null;
561
-			}
562
-
563
-			$legacyDispatcher = $c->get(SymfonyAdapter::class);
564
-
565
-			$userSession = new \OC\User\Session(
566
-				$manager,
567
-				$session,
568
-				$timeFactory,
569
-				$provider,
570
-				$c->get(\OCP\IConfig::class),
571
-				$c->get(ISecureRandom::class),
572
-				$c->getLockdownManager(),
573
-				$c->get(LoggerInterface::class),
574
-				$c->get(IEventDispatcher::class)
575
-			);
576
-			/** @deprecated 21.0.0 use BeforeUserCreatedEvent event with the IEventDispatcher instead */
577
-			$userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
578
-				\OC_Hook::emit('OC_User', 'pre_createUser', ['run' => true, 'uid' => $uid, 'password' => $password]);
579
-			});
580
-			/** @deprecated 21.0.0 use UserCreatedEvent event with the IEventDispatcher instead */
581
-			$userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
582
-				/** @var \OC\User\User $user */
583
-				\OC_Hook::emit('OC_User', 'post_createUser', ['uid' => $user->getUID(), 'password' => $password]);
584
-			});
585
-			/** @deprecated 21.0.0 use BeforeUserDeletedEvent event with the IEventDispatcher instead */
586
-			$userSession->listen('\OC\User', 'preDelete', function ($user) use ($legacyDispatcher) {
587
-				/** @var \OC\User\User $user */
588
-				\OC_Hook::emit('OC_User', 'pre_deleteUser', ['run' => true, 'uid' => $user->getUID()]);
589
-				$legacyDispatcher->dispatch('OCP\IUser::preDelete', new GenericEvent($user));
590
-			});
591
-			/** @deprecated 21.0.0 use UserDeletedEvent event with the IEventDispatcher instead */
592
-			$userSession->listen('\OC\User', 'postDelete', function ($user) {
593
-				/** @var \OC\User\User $user */
594
-				\OC_Hook::emit('OC_User', 'post_deleteUser', ['uid' => $user->getUID()]);
595
-			});
596
-			$userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
597
-				/** @var \OC\User\User $user */
598
-				\OC_Hook::emit('OC_User', 'pre_setPassword', ['run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword]);
599
-
600
-				/** @var IEventDispatcher $dispatcher */
601
-				$dispatcher = $this->get(IEventDispatcher::class);
602
-				$dispatcher->dispatchTyped(new BeforePasswordUpdatedEvent($user, $password, $recoveryPassword));
603
-			});
604
-			$userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
605
-				/** @var \OC\User\User $user */
606
-				\OC_Hook::emit('OC_User', 'post_setPassword', ['run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword]);
607
-
608
-				/** @var IEventDispatcher $dispatcher */
609
-				$dispatcher = $this->get(IEventDispatcher::class);
610
-				$dispatcher->dispatchTyped(new PasswordUpdatedEvent($user, $password, $recoveryPassword));
611
-			});
612
-			$userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
613
-				\OC_Hook::emit('OC_User', 'pre_login', ['run' => true, 'uid' => $uid, 'password' => $password]);
614
-
615
-				/** @var IEventDispatcher $dispatcher */
616
-				$dispatcher = $this->get(IEventDispatcher::class);
617
-				$dispatcher->dispatchTyped(new BeforeUserLoggedInEvent($uid, $password));
618
-			});
619
-			$userSession->listen('\OC\User', 'postLogin', function ($user, $loginName, $password, $isTokenLogin) {
620
-				/** @var \OC\User\User $user */
621
-				\OC_Hook::emit('OC_User', 'post_login', ['run' => true, 'uid' => $user->getUID(), 'loginName' => $loginName, 'password' => $password, 'isTokenLogin' => $isTokenLogin]);
622
-
623
-				/** @var IEventDispatcher $dispatcher */
624
-				$dispatcher = $this->get(IEventDispatcher::class);
625
-				$dispatcher->dispatchTyped(new UserLoggedInEvent($user, $loginName, $password, $isTokenLogin));
626
-			});
627
-			$userSession->listen('\OC\User', 'preRememberedLogin', function ($uid) {
628
-				/** @var IEventDispatcher $dispatcher */
629
-				$dispatcher = $this->get(IEventDispatcher::class);
630
-				$dispatcher->dispatchTyped(new BeforeUserLoggedInWithCookieEvent($uid));
631
-			});
632
-			$userSession->listen('\OC\User', 'postRememberedLogin', function ($user, $password) {
633
-				/** @var \OC\User\User $user */
634
-				\OC_Hook::emit('OC_User', 'post_login', ['run' => true, 'uid' => $user->getUID(), 'password' => $password]);
635
-
636
-				/** @var IEventDispatcher $dispatcher */
637
-				$dispatcher = $this->get(IEventDispatcher::class);
638
-				$dispatcher->dispatchTyped(new UserLoggedInWithCookieEvent($user, $password));
639
-			});
640
-			$userSession->listen('\OC\User', 'logout', function ($user) {
641
-				\OC_Hook::emit('OC_User', 'logout', []);
642
-
643
-				/** @var IEventDispatcher $dispatcher */
644
-				$dispatcher = $this->get(IEventDispatcher::class);
645
-				$dispatcher->dispatchTyped(new BeforeUserLoggedOutEvent($user));
646
-			});
647
-			$userSession->listen('\OC\User', 'postLogout', function ($user) {
648
-				/** @var IEventDispatcher $dispatcher */
649
-				$dispatcher = $this->get(IEventDispatcher::class);
650
-				$dispatcher->dispatchTyped(new UserLoggedOutEvent($user));
651
-			});
652
-			$userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value, $oldValue) {
653
-				/** @var \OC\User\User $user */
654
-				\OC_Hook::emit('OC_User', 'changeUser', ['run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value, 'old_value' => $oldValue]);
655
-
656
-				/** @var IEventDispatcher $dispatcher */
657
-				$dispatcher = $this->get(IEventDispatcher::class);
658
-				$dispatcher->dispatchTyped(new UserChangedEvent($user, $feature, $value, $oldValue));
659
-			});
660
-			return $userSession;
661
-		});
662
-		$this->registerAlias(\OCP\IUserSession::class, \OC\User\Session::class);
663
-		/** @deprecated 19.0.0 */
664
-		$this->registerDeprecatedAlias('UserSession', \OC\User\Session::class);
665
-
666
-		$this->registerAlias(\OCP\Authentication\TwoFactorAuth\IRegistry::class, \OC\Authentication\TwoFactorAuth\Registry::class);
667
-
668
-		$this->registerAlias(INavigationManager::class, \OC\NavigationManager::class);
669
-		/** @deprecated 19.0.0 */
670
-		$this->registerDeprecatedAlias('NavigationManager', INavigationManager::class);
671
-
672
-		/** @deprecated 19.0.0 */
673
-		$this->registerDeprecatedAlias('AllConfig', \OC\AllConfig::class);
674
-		$this->registerAlias(\OCP\IConfig::class, \OC\AllConfig::class);
675
-
676
-		$this->registerService(\OC\SystemConfig::class, function ($c) use ($config) {
677
-			return new \OC\SystemConfig($config);
678
-		});
679
-		/** @deprecated 19.0.0 */
680
-		$this->registerDeprecatedAlias('SystemConfig', \OC\SystemConfig::class);
681
-
682
-		/** @deprecated 19.0.0 */
683
-		$this->registerDeprecatedAlias('AppConfig', \OC\AppConfig::class);
684
-		$this->registerAlias(IAppConfig::class, \OC\AppConfig::class);
685
-
686
-		$this->registerService(IFactory::class, function (Server $c) {
687
-			return new \OC\L10N\Factory(
688
-				$c->get(\OCP\IConfig::class),
689
-				$c->getRequest(),
690
-				$c->get(IUserSession::class),
691
-				$c->get(ICacheFactory::class),
692
-				\OC::$SERVERROOT
693
-			);
694
-		});
695
-		/** @deprecated 19.0.0 */
696
-		$this->registerDeprecatedAlias('L10NFactory', IFactory::class);
697
-
698
-		$this->registerAlias(IURLGenerator::class, URLGenerator::class);
699
-		/** @deprecated 19.0.0 */
700
-		$this->registerDeprecatedAlias('URLGenerator', IURLGenerator::class);
701
-
702
-		/** @deprecated 19.0.0 */
703
-		$this->registerDeprecatedAlias('AppFetcher', AppFetcher::class);
704
-		/** @deprecated 19.0.0 */
705
-		$this->registerDeprecatedAlias('CategoryFetcher', CategoryFetcher::class);
706
-
707
-		$this->registerService(ICache::class, function ($c) {
708
-			return new Cache\File();
709
-		});
710
-		/** @deprecated 19.0.0 */
711
-		$this->registerDeprecatedAlias('UserCache', ICache::class);
712
-
713
-		$this->registerService(Factory::class, function (Server $c) {
714
-			$profiler = $c->get(IProfiler::class);
715
-			$arrayCacheFactory = new \OC\Memcache\Factory('', $c->get(LoggerInterface::class),
716
-				$profiler,
717
-				ArrayCache::class,
718
-				ArrayCache::class,
719
-				ArrayCache::class
720
-			);
721
-			/** @var \OCP\IConfig $config */
722
-			$config = $c->get(\OCP\IConfig::class);
723
-
724
-			if ($config->getSystemValue('installed', false) && !(defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
725
-				if (!$config->getSystemValueBool('log_query')) {
726
-					$v = \OC_App::getAppVersions();
727
-				} else {
728
-					// If the log_query is enabled, we can not get the app versions
729
-					// as that does a query, which will be logged and the logging
730
-					// depends on redis and here we are back again in the same function.
731
-					$v = [
732
-						'log_query' => 'enabled',
733
-					];
734
-				}
735
-				$v['core'] = implode(',', \OC_Util::getVersion());
736
-				$version = implode(',', $v);
737
-				$instanceId = \OC_Util::getInstanceId();
738
-				$path = \OC::$SERVERROOT;
739
-				$prefix = md5($instanceId . '-' . $version . '-' . $path);
740
-				return new \OC\Memcache\Factory($prefix,
741
-					$c->get(LoggerInterface::class),
742
-					$profiler,
743
-					$config->getSystemValue('memcache.local', null),
744
-					$config->getSystemValue('memcache.distributed', null),
745
-					$config->getSystemValue('memcache.locking', null),
746
-					$config->getSystemValueString('redis_log_file')
747
-				);
748
-			}
749
-			return $arrayCacheFactory;
750
-		});
751
-		/** @deprecated 19.0.0 */
752
-		$this->registerDeprecatedAlias('MemCacheFactory', Factory::class);
753
-		$this->registerAlias(ICacheFactory::class, Factory::class);
754
-
755
-		$this->registerService('RedisFactory', function (Server $c) {
756
-			$systemConfig = $c->get(SystemConfig::class);
757
-			return new RedisFactory($systemConfig, $c->getEventLogger());
758
-		});
759
-
760
-		$this->registerService(\OCP\Activity\IManager::class, function (Server $c) {
761
-			$l10n = $this->get(IFactory::class)->get('lib');
762
-			return new \OC\Activity\Manager(
763
-				$c->getRequest(),
764
-				$c->get(IUserSession::class),
765
-				$c->get(\OCP\IConfig::class),
766
-				$c->get(IValidator::class),
767
-				$l10n
768
-			);
769
-		});
770
-		/** @deprecated 19.0.0 */
771
-		$this->registerDeprecatedAlias('ActivityManager', \OCP\Activity\IManager::class);
772
-
773
-		$this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
774
-			return new \OC\Activity\EventMerger(
775
-				$c->getL10N('lib')
776
-			);
777
-		});
778
-		$this->registerAlias(IValidator::class, Validator::class);
779
-
780
-		$this->registerService(AvatarManager::class, function (Server $c) {
781
-			return new AvatarManager(
782
-				$c->get(IUserSession::class),
783
-				$c->get(\OC\User\Manager::class),
784
-				$c->getAppDataDir('avatar'),
785
-				$c->getL10N('lib'),
786
-				$c->get(LoggerInterface::class),
787
-				$c->get(\OCP\IConfig::class),
788
-				$c->get(IAccountManager::class),
789
-				$c->get(KnownUserService::class)
790
-			);
791
-		});
792
-
793
-		$this->registerAlias(IAvatarManager::class, AvatarManager::class);
794
-		/** @deprecated 19.0.0 */
795
-		$this->registerDeprecatedAlias('AvatarManager', AvatarManager::class);
796
-
797
-		$this->registerAlias(\OCP\Support\CrashReport\IRegistry::class, \OC\Support\CrashReport\Registry::class);
798
-		$this->registerAlias(\OCP\Support\Subscription\IRegistry::class, \OC\Support\Subscription\Registry::class);
799
-		$this->registerAlias(\OCP\Support\Subscription\IAssertion::class, \OC\Support\Subscription\Assertion::class);
800
-
801
-		$this->registerService(\OC\Log::class, function (Server $c) {
802
-			$logType = $c->get(AllConfig::class)->getSystemValue('log_type', 'file');
803
-			$factory = new LogFactory($c, $this->get(SystemConfig::class));
804
-			$logger = $factory->get($logType);
805
-			$registry = $c->get(\OCP\Support\CrashReport\IRegistry::class);
806
-
807
-			return new Log($logger, $this->get(SystemConfig::class), null, $registry);
808
-		});
809
-		$this->registerAlias(ILogger::class, \OC\Log::class);
810
-		/** @deprecated 19.0.0 */
811
-		$this->registerDeprecatedAlias('Logger', \OC\Log::class);
812
-		// PSR-3 logger
813
-		$this->registerAlias(LoggerInterface::class, PsrLoggerAdapter::class);
814
-
815
-		$this->registerService(ILogFactory::class, function (Server $c) {
816
-			return new LogFactory($c, $this->get(SystemConfig::class));
817
-		});
818
-
819
-		$this->registerAlias(IJobList::class, \OC\BackgroundJob\JobList::class);
820
-		/** @deprecated 19.0.0 */
821
-		$this->registerDeprecatedAlias('JobList', IJobList::class);
822
-
823
-		$this->registerService(Router::class, function (Server $c) {
824
-			$cacheFactory = $c->get(ICacheFactory::class);
825
-			$logger = $c->get(LoggerInterface::class);
826
-			if ($cacheFactory->isLocalCacheAvailable()) {
827
-				$router = new \OC\Route\CachingRouter($cacheFactory->createLocal('route'), $logger);
828
-			} else {
829
-				$router = new \OC\Route\Router($logger);
830
-			}
831
-			return $router;
832
-		});
833
-		$this->registerAlias(IRouter::class, Router::class);
834
-		/** @deprecated 19.0.0 */
835
-		$this->registerDeprecatedAlias('Router', IRouter::class);
836
-
837
-		$this->registerAlias(ISearch::class, Search::class);
838
-		/** @deprecated 19.0.0 */
839
-		$this->registerDeprecatedAlias('Search', ISearch::class);
840
-
841
-		$this->registerService(\OC\Security\RateLimiting\Backend\IBackend::class, function ($c) {
842
-			$cacheFactory = $c->get(ICacheFactory::class);
843
-			if ($cacheFactory->isAvailable()) {
844
-				$backend = new \OC\Security\RateLimiting\Backend\MemoryCacheBackend(
845
-					$this->get(ICacheFactory::class),
846
-					new \OC\AppFramework\Utility\TimeFactory()
847
-				);
848
-			} else {
849
-				$backend = new \OC\Security\RateLimiting\Backend\DatabaseBackend(
850
-					$c->get(IDBConnection::class),
851
-					new \OC\AppFramework\Utility\TimeFactory()
852
-				);
853
-			}
854
-
855
-			return $backend;
856
-		});
857
-
858
-		$this->registerAlias(\OCP\Security\ISecureRandom::class, SecureRandom::class);
859
-		/** @deprecated 19.0.0 */
860
-		$this->registerDeprecatedAlias('SecureRandom', \OCP\Security\ISecureRandom::class);
861
-		$this->registerAlias(\OCP\Security\IRemoteHostValidator::class, \OC\Security\RemoteHostValidator::class);
862
-		$this->registerAlias(IVerificationToken::class, VerificationToken::class);
863
-
864
-		$this->registerAlias(ICrypto::class, Crypto::class);
865
-		/** @deprecated 19.0.0 */
866
-		$this->registerDeprecatedAlias('Crypto', ICrypto::class);
867
-
868
-		$this->registerAlias(IHasher::class, Hasher::class);
869
-		/** @deprecated 19.0.0 */
870
-		$this->registerDeprecatedAlias('Hasher', IHasher::class);
871
-
872
-		$this->registerAlias(ICredentialsManager::class, CredentialsManager::class);
873
-		/** @deprecated 19.0.0 */
874
-		$this->registerDeprecatedAlias('CredentialsManager', ICredentialsManager::class);
875
-
876
-		$this->registerAlias(IDBConnection::class, ConnectionAdapter::class);
877
-		$this->registerService(Connection::class, function (Server $c) {
878
-			$systemConfig = $c->get(SystemConfig::class);
879
-			$factory = new \OC\DB\ConnectionFactory($systemConfig);
880
-			$type = $systemConfig->getValue('dbtype', 'sqlite');
881
-			if (!$factory->isValidType($type)) {
882
-				throw new \OC\DatabaseException('Invalid database type');
883
-			}
884
-			$connectionParams = $factory->createConnectionParams();
885
-			$connection = $factory->getConnection($type, $connectionParams);
886
-			return $connection;
887
-		});
888
-		/** @deprecated 19.0.0 */
889
-		$this->registerDeprecatedAlias('DatabaseConnection', IDBConnection::class);
890
-
891
-		$this->registerAlias(ICertificateManager::class, CertificateManager::class);
892
-		$this->registerAlias(IClientService::class, ClientService::class);
893
-		$this->registerService(NegativeDnsCache::class, function (ContainerInterface $c) {
894
-			return new NegativeDnsCache(
895
-				$c->get(ICacheFactory::class),
896
-			);
897
-		});
898
-		$this->registerDeprecatedAlias('HttpClientService', IClientService::class);
899
-		$this->registerService(IEventLogger::class, function (ContainerInterface $c) {
900
-			return new EventLogger($c->get(SystemConfig::class), $c->get(LoggerInterface::class), $c->get(Log::class));
901
-		});
902
-		/** @deprecated 19.0.0 */
903
-		$this->registerDeprecatedAlias('EventLogger', IEventLogger::class);
904
-
905
-		$this->registerService(IQueryLogger::class, function (ContainerInterface $c) {
906
-			$queryLogger = new QueryLogger();
907
-			if ($c->get(SystemConfig::class)->getValue('debug', false)) {
908
-				// In debug mode, module is being activated by default
909
-				$queryLogger->activate();
910
-			}
911
-			return $queryLogger;
912
-		});
913
-		/** @deprecated 19.0.0 */
914
-		$this->registerDeprecatedAlias('QueryLogger', IQueryLogger::class);
915
-
916
-		/** @deprecated 19.0.0 */
917
-		$this->registerDeprecatedAlias('TempManager', TempManager::class);
918
-		$this->registerAlias(ITempManager::class, TempManager::class);
919
-
920
-		$this->registerService(AppManager::class, function (ContainerInterface $c) {
921
-			// TODO: use auto-wiring
922
-			return new \OC\App\AppManager(
923
-				$c->get(IUserSession::class),
924
-				$c->get(\OCP\IConfig::class),
925
-				$c->get(\OC\AppConfig::class),
926
-				$c->get(IGroupManager::class),
927
-				$c->get(ICacheFactory::class),
928
-				$c->get(SymfonyAdapter::class),
929
-				$c->get(LoggerInterface::class)
930
-			);
931
-		});
932
-		/** @deprecated 19.0.0 */
933
-		$this->registerDeprecatedAlias('AppManager', AppManager::class);
934
-		$this->registerAlias(IAppManager::class, AppManager::class);
935
-
936
-		$this->registerAlias(IDateTimeZone::class, DateTimeZone::class);
937
-		/** @deprecated 19.0.0 */
938
-		$this->registerDeprecatedAlias('DateTimeZone', IDateTimeZone::class);
939
-
940
-		$this->registerService(IDateTimeFormatter::class, function (Server $c) {
941
-			$language = $c->get(\OCP\IConfig::class)->getUserValue($c->get(ISession::class)->get('user_id'), 'core', 'lang', null);
942
-
943
-			return new DateTimeFormatter(
944
-				$c->get(IDateTimeZone::class)->getTimeZone(),
945
-				$c->getL10N('lib', $language)
946
-			);
947
-		});
948
-		/** @deprecated 19.0.0 */
949
-		$this->registerDeprecatedAlias('DateTimeFormatter', IDateTimeFormatter::class);
950
-
951
-		$this->registerService(IUserMountCache::class, function (ContainerInterface $c) {
952
-			$mountCache = new UserMountCache(
953
-				$c->get(IDBConnection::class),
954
-				$c->get(IUserManager::class),
955
-				$c->get(LoggerInterface::class)
956
-			);
957
-			$listener = new UserMountCacheListener($mountCache);
958
-			$listener->listen($c->get(IUserManager::class));
959
-			return $mountCache;
960
-		});
961
-		/** @deprecated 19.0.0 */
962
-		$this->registerDeprecatedAlias('UserMountCache', IUserMountCache::class);
963
-
964
-		$this->registerService(IMountProviderCollection::class, function (ContainerInterface $c) {
965
-			$loader = \OC\Files\Filesystem::getLoader();
966
-			$mountCache = $c->get(IUserMountCache::class);
967
-			$manager = new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
968
-
969
-			// builtin providers
970
-
971
-			$config = $c->get(\OCP\IConfig::class);
972
-			$logger = $c->get(LoggerInterface::class);
973
-			$manager->registerProvider(new CacheMountProvider($config));
974
-			$manager->registerHomeProvider(new LocalHomeMountProvider());
975
-			$manager->registerHomeProvider(new ObjectHomeMountProvider($config));
976
-			$manager->registerRootProvider(new RootMountProvider($config, $c->get(LoggerInterface::class)));
977
-			$manager->registerRootProvider(new ObjectStorePreviewCacheMountProvider($logger, $config));
978
-
979
-			return $manager;
980
-		});
981
-		/** @deprecated 19.0.0 */
982
-		$this->registerDeprecatedAlias('MountConfigManager', IMountProviderCollection::class);
983
-
984
-		/** @deprecated 20.0.0 */
985
-		$this->registerDeprecatedAlias('IniWrapper', IniGetWrapper::class);
986
-		$this->registerService(IBus::class, function (ContainerInterface $c) {
987
-			$busClass = $c->get(\OCP\IConfig::class)->getSystemValue('commandbus');
988
-			if ($busClass) {
989
-				[$app, $class] = explode('::', $busClass, 2);
990
-				if ($c->get(IAppManager::class)->isInstalled($app)) {
991
-					\OC_App::loadApp($app);
992
-					return $c->get($class);
993
-				} else {
994
-					throw new ServiceUnavailableException("The app providing the command bus ($app) is not enabled");
995
-				}
996
-			} else {
997
-				$jobList = $c->get(IJobList::class);
998
-				return new CronBus($jobList);
999
-			}
1000
-		});
1001
-		$this->registerDeprecatedAlias('AsyncCommandBus', IBus::class);
1002
-		/** @deprecated 20.0.0 */
1003
-		$this->registerDeprecatedAlias('TrustedDomainHelper', TrustedDomainHelper::class);
1004
-		$this->registerAlias(ITrustedDomainHelper::class, TrustedDomainHelper::class);
1005
-		/** @deprecated 19.0.0 */
1006
-		$this->registerDeprecatedAlias('Throttler', Throttler::class);
1007
-		$this->registerAlias(IThrottler::class, Throttler::class);
1008
-		$this->registerService('IntegrityCodeChecker', function (ContainerInterface $c) {
1009
-			// IConfig and IAppManager requires a working database. This code
1010
-			// might however be called when ownCloud is not yet setup.
1011
-			if (\OC::$server->get(SystemConfig::class)->getValue('installed', false)) {
1012
-				$config = $c->get(\OCP\IConfig::class);
1013
-				$appManager = $c->get(IAppManager::class);
1014
-			} else {
1015
-				$config = null;
1016
-				$appManager = null;
1017
-			}
1018
-
1019
-			return new Checker(
1020
-				new EnvironmentHelper(),
1021
-				new FileAccessHelper(),
1022
-				new AppLocator(),
1023
-				$config,
1024
-				$c->get(ICacheFactory::class),
1025
-				$appManager,
1026
-				$c->get(IMimeTypeDetector::class)
1027
-			);
1028
-		});
1029
-		$this->registerService(\OCP\IRequest::class, function (ContainerInterface $c) {
1030
-			if (isset($this['urlParams'])) {
1031
-				$urlParams = $this['urlParams'];
1032
-			} else {
1033
-				$urlParams = [];
1034
-			}
1035
-
1036
-			if (defined('PHPUNIT_RUN') && PHPUNIT_RUN
1037
-				&& in_array('fakeinput', stream_get_wrappers())
1038
-			) {
1039
-				$stream = 'fakeinput://data';
1040
-			} else {
1041
-				$stream = 'php://input';
1042
-			}
1043
-
1044
-			return new Request(
1045
-				[
1046
-					'get' => $_GET,
1047
-					'post' => $_POST,
1048
-					'files' => $_FILES,
1049
-					'server' => $_SERVER,
1050
-					'env' => $_ENV,
1051
-					'cookies' => $_COOKIE,
1052
-					'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
1053
-						? $_SERVER['REQUEST_METHOD']
1054
-						: '',
1055
-					'urlParams' => $urlParams,
1056
-				],
1057
-				$this->get(IRequestId::class),
1058
-				$this->get(\OCP\IConfig::class),
1059
-				$this->get(CsrfTokenManager::class),
1060
-				$stream
1061
-			);
1062
-		});
1063
-		/** @deprecated 19.0.0 */
1064
-		$this->registerDeprecatedAlias('Request', \OCP\IRequest::class);
1065
-
1066
-		$this->registerService(IRequestId::class, function (ContainerInterface $c): IRequestId {
1067
-			return new RequestId(
1068
-				$_SERVER['UNIQUE_ID'] ?? '',
1069
-				$this->get(ISecureRandom::class)
1070
-			);
1071
-		});
1072
-
1073
-		$this->registerService(IMailer::class, function (Server $c) {
1074
-			return new Mailer(
1075
-				$c->get(\OCP\IConfig::class),
1076
-				$c->get(LoggerInterface::class),
1077
-				$c->get(Defaults::class),
1078
-				$c->get(IURLGenerator::class),
1079
-				$c->getL10N('lib'),
1080
-				$c->get(IEventDispatcher::class),
1081
-				$c->get(IFactory::class)
1082
-			);
1083
-		});
1084
-		/** @deprecated 19.0.0 */
1085
-		$this->registerDeprecatedAlias('Mailer', IMailer::class);
1086
-
1087
-		/** @deprecated 21.0.0 */
1088
-		$this->registerDeprecatedAlias('LDAPProvider', ILDAPProvider::class);
1089
-
1090
-		$this->registerService(ILDAPProviderFactory::class, function (ContainerInterface $c) {
1091
-			$config = $c->get(\OCP\IConfig::class);
1092
-			$factoryClass = $config->getSystemValue('ldapProviderFactory', null);
1093
-			if (is_null($factoryClass) || !class_exists($factoryClass)) {
1094
-				return new NullLDAPProviderFactory($this);
1095
-			}
1096
-			/** @var \OCP\LDAP\ILDAPProviderFactory $factory */
1097
-			return new $factoryClass($this);
1098
-		});
1099
-		$this->registerService(ILDAPProvider::class, function (ContainerInterface $c) {
1100
-			$factory = $c->get(ILDAPProviderFactory::class);
1101
-			return $factory->getLDAPProvider();
1102
-		});
1103
-		$this->registerService(ILockingProvider::class, function (ContainerInterface $c) {
1104
-			$ini = $c->get(IniGetWrapper::class);
1105
-			$config = $c->get(\OCP\IConfig::class);
1106
-			$ttl = $config->getSystemValue('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
1107
-			if ($config->getSystemValue('filelocking.enabled', true) or (defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
1108
-				/** @var \OC\Memcache\Factory $memcacheFactory */
1109
-				$memcacheFactory = $c->get(ICacheFactory::class);
1110
-				$memcache = $memcacheFactory->createLocking('lock');
1111
-				if (!($memcache instanceof \OC\Memcache\NullCache)) {
1112
-					return new MemcacheLockingProvider($memcache, $ttl);
1113
-				}
1114
-				return new DBLockingProvider(
1115
-					$c->get(IDBConnection::class),
1116
-					new TimeFactory(),
1117
-					$ttl,
1118
-					!\OC::$CLI
1119
-				);
1120
-			}
1121
-			return new NoopLockingProvider();
1122
-		});
1123
-		/** @deprecated 19.0.0 */
1124
-		$this->registerDeprecatedAlias('LockingProvider', ILockingProvider::class);
1125
-
1126
-		$this->registerService(ILockManager::class, function (Server $c): LockManager {
1127
-			return new LockManager();
1128
-		});
1129
-
1130
-		$this->registerAlias(ILockdownManager::class, 'LockdownManager');
1131
-		$this->registerService(SetupManager::class, function ($c) {
1132
-			// create the setupmanager through the mount manager to resolve the cyclic dependency
1133
-			return $c->get(\OC\Files\Mount\Manager::class)->getSetupManager();
1134
-		});
1135
-		$this->registerAlias(IMountManager::class, \OC\Files\Mount\Manager::class);
1136
-		/** @deprecated 19.0.0 */
1137
-		$this->registerDeprecatedAlias('MountManager', IMountManager::class);
1138
-
1139
-		$this->registerService(IMimeTypeDetector::class, function (ContainerInterface $c) {
1140
-			return new \OC\Files\Type\Detection(
1141
-				$c->get(IURLGenerator::class),
1142
-				$c->get(LoggerInterface::class),
1143
-				\OC::$configDir,
1144
-				\OC::$SERVERROOT . '/resources/config/'
1145
-			);
1146
-		});
1147
-		/** @deprecated 19.0.0 */
1148
-		$this->registerDeprecatedAlias('MimeTypeDetector', IMimeTypeDetector::class);
1149
-
1150
-		$this->registerAlias(IMimeTypeLoader::class, Loader::class);
1151
-		/** @deprecated 19.0.0 */
1152
-		$this->registerDeprecatedAlias('MimeTypeLoader', IMimeTypeLoader::class);
1153
-		$this->registerService(BundleFetcher::class, function () {
1154
-			return new BundleFetcher($this->getL10N('lib'));
1155
-		});
1156
-		$this->registerAlias(\OCP\Notification\IManager::class, Manager::class);
1157
-		/** @deprecated 19.0.0 */
1158
-		$this->registerDeprecatedAlias('NotificationManager', \OCP\Notification\IManager::class);
1159
-
1160
-		$this->registerService(CapabilitiesManager::class, function (ContainerInterface $c) {
1161
-			$manager = new CapabilitiesManager($c->get(LoggerInterface::class));
1162
-			$manager->registerCapability(function () use ($c) {
1163
-				return new \OC\OCS\CoreCapabilities($c->get(\OCP\IConfig::class));
1164
-			});
1165
-			$manager->registerCapability(function () use ($c) {
1166
-				return $c->get(\OC\Security\Bruteforce\Capabilities::class);
1167
-			});
1168
-			$manager->registerCapability(function () use ($c) {
1169
-				return $c->get(MetadataCapabilities::class);
1170
-			});
1171
-			return $manager;
1172
-		});
1173
-		/** @deprecated 19.0.0 */
1174
-		$this->registerDeprecatedAlias('CapabilitiesManager', CapabilitiesManager::class);
1175
-
1176
-		$this->registerService(ICommentsManager::class, function (Server $c) {
1177
-			$config = $c->get(\OCP\IConfig::class);
1178
-			$factoryClass = $config->getSystemValue('comments.managerFactory', CommentsManagerFactory::class);
1179
-			/** @var \OCP\Comments\ICommentsManagerFactory $factory */
1180
-			$factory = new $factoryClass($this);
1181
-			$manager = $factory->getManager();
1182
-
1183
-			$manager->registerDisplayNameResolver('user', function ($id) use ($c) {
1184
-				$manager = $c->get(IUserManager::class);
1185
-				$userDisplayName = $manager->getDisplayName($id);
1186
-				if ($userDisplayName === null) {
1187
-					$l = $c->get(IFactory::class)->get('core');
1188
-					return $l->t('Unknown user');
1189
-				}
1190
-				return $userDisplayName;
1191
-			});
1192
-
1193
-			return $manager;
1194
-		});
1195
-		/** @deprecated 19.0.0 */
1196
-		$this->registerDeprecatedAlias('CommentsManager', ICommentsManager::class);
1197
-
1198
-		$this->registerAlias(\OC_Defaults::class, 'ThemingDefaults');
1199
-		$this->registerService('ThemingDefaults', function (Server $c) {
1200
-			/*
281
+    /** @var string */
282
+    private $webRoot;
283
+
284
+    /**
285
+     * @param string $webRoot
286
+     * @param \OC\Config $config
287
+     */
288
+    public function __construct($webRoot, \OC\Config $config) {
289
+        parent::__construct();
290
+        $this->webRoot = $webRoot;
291
+
292
+        // To find out if we are running from CLI or not
293
+        $this->registerParameter('isCLI', \OC::$CLI);
294
+        $this->registerParameter('serverRoot', \OC::$SERVERROOT);
295
+
296
+        $this->registerService(ContainerInterface::class, function (ContainerInterface $c) {
297
+            return $c;
298
+        });
299
+        $this->registerService(\OCP\IServerContainer::class, function (ContainerInterface $c) {
300
+            return $c;
301
+        });
302
+
303
+        $this->registerAlias(\OCP\Calendar\IManager::class, \OC\Calendar\Manager::class);
304
+        /** @deprecated 19.0.0 */
305
+        $this->registerDeprecatedAlias('CalendarManager', \OC\Calendar\Manager::class);
306
+
307
+        $this->registerAlias(\OCP\Calendar\Resource\IManager::class, \OC\Calendar\Resource\Manager::class);
308
+        /** @deprecated 19.0.0 */
309
+        $this->registerDeprecatedAlias('CalendarResourceBackendManager', \OC\Calendar\Resource\Manager::class);
310
+
311
+        $this->registerAlias(\OCP\Calendar\Room\IManager::class, \OC\Calendar\Room\Manager::class);
312
+        /** @deprecated 19.0.0 */
313
+        $this->registerDeprecatedAlias('CalendarRoomBackendManager', \OC\Calendar\Room\Manager::class);
314
+
315
+        $this->registerAlias(\OCP\Contacts\IManager::class, \OC\ContactsManager::class);
316
+        /** @deprecated 19.0.0 */
317
+        $this->registerDeprecatedAlias('ContactsManager', \OCP\Contacts\IManager::class);
318
+
319
+        $this->registerAlias(\OCP\DirectEditing\IManager::class, \OC\DirectEditing\Manager::class);
320
+        $this->registerAlias(ITemplateManager::class, TemplateManager::class);
321
+
322
+        $this->registerAlias(IActionFactory::class, ActionFactory::class);
323
+
324
+        $this->registerService(View::class, function (Server $c) {
325
+            return new View();
326
+        }, false);
327
+
328
+        $this->registerService(IPreview::class, function (ContainerInterface $c) {
329
+            return new PreviewManager(
330
+                $c->get(\OCP\IConfig::class),
331
+                $c->get(IRootFolder::class),
332
+                new \OC\Preview\Storage\Root(
333
+                    $c->get(IRootFolder::class),
334
+                    $c->get(SystemConfig::class)
335
+                ),
336
+                $c->get(IEventDispatcher::class),
337
+                $c->get(SymfonyAdapter::class),
338
+                $c->get(GeneratorHelper::class),
339
+                $c->get(ISession::class)->get('user_id'),
340
+                $c->get(Coordinator::class),
341
+                $c->get(IServerContainer::class),
342
+                $c->get(IBinaryFinder::class)
343
+            );
344
+        });
345
+        /** @deprecated 19.0.0 */
346
+        $this->registerDeprecatedAlias('PreviewManager', IPreview::class);
347
+
348
+        $this->registerService(\OC\Preview\Watcher::class, function (ContainerInterface $c) {
349
+            return new \OC\Preview\Watcher(
350
+                new \OC\Preview\Storage\Root(
351
+                    $c->get(IRootFolder::class),
352
+                    $c->get(SystemConfig::class)
353
+                )
354
+            );
355
+        });
356
+
357
+        $this->registerService(IProfiler::class, function (Server $c) {
358
+            return new Profiler($c->get(SystemConfig::class));
359
+        });
360
+
361
+        $this->registerService(\OCP\Encryption\IManager::class, function (Server $c): Encryption\Manager {
362
+            $view = new View();
363
+            $util = new Encryption\Util(
364
+                $view,
365
+                $c->get(IUserManager::class),
366
+                $c->get(IGroupManager::class),
367
+                $c->get(\OCP\IConfig::class)
368
+            );
369
+            return new Encryption\Manager(
370
+                $c->get(\OCP\IConfig::class),
371
+                $c->get(LoggerInterface::class),
372
+                $c->getL10N('core'),
373
+                new View(),
374
+                $util,
375
+                new ArrayCache()
376
+            );
377
+        });
378
+        /** @deprecated 19.0.0 */
379
+        $this->registerDeprecatedAlias('EncryptionManager', \OCP\Encryption\IManager::class);
380
+
381
+        /** @deprecated 21.0.0 */
382
+        $this->registerDeprecatedAlias('EncryptionFileHelper', IFile::class);
383
+        $this->registerService(IFile::class, function (ContainerInterface $c) {
384
+            $util = new Encryption\Util(
385
+                new View(),
386
+                $c->get(IUserManager::class),
387
+                $c->get(IGroupManager::class),
388
+                $c->get(\OCP\IConfig::class)
389
+            );
390
+            return new Encryption\File(
391
+                $util,
392
+                $c->get(IRootFolder::class),
393
+                $c->get(\OCP\Share\IManager::class)
394
+            );
395
+        });
396
+
397
+        /** @deprecated 21.0.0 */
398
+        $this->registerDeprecatedAlias('EncryptionKeyStorage', IStorage::class);
399
+        $this->registerService(IStorage::class, function (ContainerInterface $c) {
400
+            $view = new View();
401
+            $util = new Encryption\Util(
402
+                $view,
403
+                $c->get(IUserManager::class),
404
+                $c->get(IGroupManager::class),
405
+                $c->get(\OCP\IConfig::class)
406
+            );
407
+
408
+            return new Encryption\Keys\Storage(
409
+                $view,
410
+                $util,
411
+                $c->get(ICrypto::class),
412
+                $c->get(\OCP\IConfig::class)
413
+            );
414
+        });
415
+        /** @deprecated 20.0.0 */
416
+        $this->registerDeprecatedAlias('TagMapper', TagMapper::class);
417
+
418
+        $this->registerAlias(\OCP\ITagManager::class, TagManager::class);
419
+        /** @deprecated 19.0.0 */
420
+        $this->registerDeprecatedAlias('TagManager', \OCP\ITagManager::class);
421
+
422
+        $this->registerService('SystemTagManagerFactory', function (ContainerInterface $c) {
423
+            /** @var \OCP\IConfig $config */
424
+            $config = $c->get(\OCP\IConfig::class);
425
+            $factoryClass = $config->getSystemValue('systemtags.managerFactory', SystemTagManagerFactory::class);
426
+            return new $factoryClass($this);
427
+        });
428
+        $this->registerService(ISystemTagManager::class, function (ContainerInterface $c) {
429
+            return $c->get('SystemTagManagerFactory')->getManager();
430
+        });
431
+        /** @deprecated 19.0.0 */
432
+        $this->registerDeprecatedAlias('SystemTagManager', ISystemTagManager::class);
433
+
434
+        $this->registerService(ISystemTagObjectMapper::class, function (ContainerInterface $c) {
435
+            return $c->get('SystemTagManagerFactory')->getObjectMapper();
436
+        });
437
+        $this->registerService('RootFolder', function (ContainerInterface $c) {
438
+            $manager = \OC\Files\Filesystem::getMountManager(null);
439
+            $view = new View();
440
+            $root = new Root(
441
+                $manager,
442
+                $view,
443
+                null,
444
+                $c->get(IUserMountCache::class),
445
+                $this->get(LoggerInterface::class),
446
+                $this->get(IUserManager::class),
447
+                $this->get(IEventDispatcher::class),
448
+            );
449
+
450
+            $previewConnector = new \OC\Preview\WatcherConnector(
451
+                $root,
452
+                $c->get(SystemConfig::class)
453
+            );
454
+            $previewConnector->connectWatcher();
455
+
456
+            return $root;
457
+        });
458
+        $this->registerService(HookConnector::class, function (ContainerInterface $c) {
459
+            return new HookConnector(
460
+                $c->get(IRootFolder::class),
461
+                new View(),
462
+                $c->get(\OC\EventDispatcher\SymfonyAdapter::class),
463
+                $c->get(IEventDispatcher::class)
464
+            );
465
+        });
466
+
467
+        /** @deprecated 19.0.0 */
468
+        $this->registerDeprecatedAlias('SystemTagObjectMapper', ISystemTagObjectMapper::class);
469
+
470
+        $this->registerService(IRootFolder::class, function (ContainerInterface $c) {
471
+            return new LazyRoot(function () use ($c) {
472
+                return $c->get('RootFolder');
473
+            });
474
+        });
475
+        /** @deprecated 19.0.0 */
476
+        $this->registerDeprecatedAlias('LazyRootFolder', IRootFolder::class);
477
+
478
+        /** @deprecated 19.0.0 */
479
+        $this->registerDeprecatedAlias('UserManager', \OC\User\Manager::class);
480
+        $this->registerAlias(\OCP\IUserManager::class, \OC\User\Manager::class);
481
+
482
+        $this->registerService(DisplayNameCache::class, function (ContainerInterface $c) {
483
+            return $c->get(\OC\User\Manager::class)->getDisplayNameCache();
484
+        });
485
+
486
+        $this->registerService(\OCP\IGroupManager::class, function (ContainerInterface $c) {
487
+            $groupManager = new \OC\Group\Manager(
488
+                $this->get(IUserManager::class),
489
+                $c->get(SymfonyAdapter::class),
490
+                $this->get(LoggerInterface::class),
491
+                $this->get(ICacheFactory::class)
492
+            );
493
+            $groupManager->listen('\OC\Group', 'preCreate', function ($gid) {
494
+                /** @var IEventDispatcher $dispatcher */
495
+                $dispatcher = $this->get(IEventDispatcher::class);
496
+                $dispatcher->dispatchTyped(new BeforeGroupCreatedEvent($gid));
497
+            });
498
+            $groupManager->listen('\OC\Group', 'postCreate', function (\OC\Group\Group $group) {
499
+                /** @var IEventDispatcher $dispatcher */
500
+                $dispatcher = $this->get(IEventDispatcher::class);
501
+                $dispatcher->dispatchTyped(new GroupCreatedEvent($group));
502
+            });
503
+            $groupManager->listen('\OC\Group', 'preDelete', function (\OC\Group\Group $group) {
504
+                /** @var IEventDispatcher $dispatcher */
505
+                $dispatcher = $this->get(IEventDispatcher::class);
506
+                $dispatcher->dispatchTyped(new BeforeGroupDeletedEvent($group));
507
+            });
508
+            $groupManager->listen('\OC\Group', 'postDelete', function (\OC\Group\Group $group) {
509
+                /** @var IEventDispatcher $dispatcher */
510
+                $dispatcher = $this->get(IEventDispatcher::class);
511
+                $dispatcher->dispatchTyped(new GroupDeletedEvent($group));
512
+            });
513
+            $groupManager->listen('\OC\Group', 'preAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
514
+                /** @var IEventDispatcher $dispatcher */
515
+                $dispatcher = $this->get(IEventDispatcher::class);
516
+                $dispatcher->dispatchTyped(new BeforeUserAddedEvent($group, $user));
517
+            });
518
+            $groupManager->listen('\OC\Group', 'postAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
519
+                /** @var IEventDispatcher $dispatcher */
520
+                $dispatcher = $this->get(IEventDispatcher::class);
521
+                $dispatcher->dispatchTyped(new UserAddedEvent($group, $user));
522
+            });
523
+            $groupManager->listen('\OC\Group', 'preRemoveUser', function (\OC\Group\Group $group, \OC\User\User $user) {
524
+                /** @var IEventDispatcher $dispatcher */
525
+                $dispatcher = $this->get(IEventDispatcher::class);
526
+                $dispatcher->dispatchTyped(new BeforeUserRemovedEvent($group, $user));
527
+            });
528
+            $groupManager->listen('\OC\Group', 'postRemoveUser', function (\OC\Group\Group $group, \OC\User\User $user) {
529
+                /** @var IEventDispatcher $dispatcher */
530
+                $dispatcher = $this->get(IEventDispatcher::class);
531
+                $dispatcher->dispatchTyped(new UserRemovedEvent($group, $user));
532
+            });
533
+            return $groupManager;
534
+        });
535
+        /** @deprecated 19.0.0 */
536
+        $this->registerDeprecatedAlias('GroupManager', \OCP\IGroupManager::class);
537
+
538
+        $this->registerService(Store::class, function (ContainerInterface $c) {
539
+            $session = $c->get(ISession::class);
540
+            if (\OC::$server->get(SystemConfig::class)->getValue('installed', false)) {
541
+                $tokenProvider = $c->get(IProvider::class);
542
+            } else {
543
+                $tokenProvider = null;
544
+            }
545
+            $logger = $c->get(LoggerInterface::class);
546
+            return new Store($session, $logger, $tokenProvider);
547
+        });
548
+        $this->registerAlias(IStore::class, Store::class);
549
+        $this->registerAlias(IProvider::class, Authentication\Token\Manager::class);
550
+
551
+        $this->registerService(\OC\User\Session::class, function (Server $c) {
552
+            $manager = $c->get(IUserManager::class);
553
+            $session = new \OC\Session\Memory('');
554
+            $timeFactory = new TimeFactory();
555
+            // Token providers might require a working database. This code
556
+            // might however be called when Nextcloud is not yet setup.
557
+            if (\OC::$server->get(SystemConfig::class)->getValue('installed', false)) {
558
+                $provider = $c->get(IProvider::class);
559
+            } else {
560
+                $provider = null;
561
+            }
562
+
563
+            $legacyDispatcher = $c->get(SymfonyAdapter::class);
564
+
565
+            $userSession = new \OC\User\Session(
566
+                $manager,
567
+                $session,
568
+                $timeFactory,
569
+                $provider,
570
+                $c->get(\OCP\IConfig::class),
571
+                $c->get(ISecureRandom::class),
572
+                $c->getLockdownManager(),
573
+                $c->get(LoggerInterface::class),
574
+                $c->get(IEventDispatcher::class)
575
+            );
576
+            /** @deprecated 21.0.0 use BeforeUserCreatedEvent event with the IEventDispatcher instead */
577
+            $userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
578
+                \OC_Hook::emit('OC_User', 'pre_createUser', ['run' => true, 'uid' => $uid, 'password' => $password]);
579
+            });
580
+            /** @deprecated 21.0.0 use UserCreatedEvent event with the IEventDispatcher instead */
581
+            $userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
582
+                /** @var \OC\User\User $user */
583
+                \OC_Hook::emit('OC_User', 'post_createUser', ['uid' => $user->getUID(), 'password' => $password]);
584
+            });
585
+            /** @deprecated 21.0.0 use BeforeUserDeletedEvent event with the IEventDispatcher instead */
586
+            $userSession->listen('\OC\User', 'preDelete', function ($user) use ($legacyDispatcher) {
587
+                /** @var \OC\User\User $user */
588
+                \OC_Hook::emit('OC_User', 'pre_deleteUser', ['run' => true, 'uid' => $user->getUID()]);
589
+                $legacyDispatcher->dispatch('OCP\IUser::preDelete', new GenericEvent($user));
590
+            });
591
+            /** @deprecated 21.0.0 use UserDeletedEvent event with the IEventDispatcher instead */
592
+            $userSession->listen('\OC\User', 'postDelete', function ($user) {
593
+                /** @var \OC\User\User $user */
594
+                \OC_Hook::emit('OC_User', 'post_deleteUser', ['uid' => $user->getUID()]);
595
+            });
596
+            $userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
597
+                /** @var \OC\User\User $user */
598
+                \OC_Hook::emit('OC_User', 'pre_setPassword', ['run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword]);
599
+
600
+                /** @var IEventDispatcher $dispatcher */
601
+                $dispatcher = $this->get(IEventDispatcher::class);
602
+                $dispatcher->dispatchTyped(new BeforePasswordUpdatedEvent($user, $password, $recoveryPassword));
603
+            });
604
+            $userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
605
+                /** @var \OC\User\User $user */
606
+                \OC_Hook::emit('OC_User', 'post_setPassword', ['run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword]);
607
+
608
+                /** @var IEventDispatcher $dispatcher */
609
+                $dispatcher = $this->get(IEventDispatcher::class);
610
+                $dispatcher->dispatchTyped(new PasswordUpdatedEvent($user, $password, $recoveryPassword));
611
+            });
612
+            $userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
613
+                \OC_Hook::emit('OC_User', 'pre_login', ['run' => true, 'uid' => $uid, 'password' => $password]);
614
+
615
+                /** @var IEventDispatcher $dispatcher */
616
+                $dispatcher = $this->get(IEventDispatcher::class);
617
+                $dispatcher->dispatchTyped(new BeforeUserLoggedInEvent($uid, $password));
618
+            });
619
+            $userSession->listen('\OC\User', 'postLogin', function ($user, $loginName, $password, $isTokenLogin) {
620
+                /** @var \OC\User\User $user */
621
+                \OC_Hook::emit('OC_User', 'post_login', ['run' => true, 'uid' => $user->getUID(), 'loginName' => $loginName, 'password' => $password, 'isTokenLogin' => $isTokenLogin]);
622
+
623
+                /** @var IEventDispatcher $dispatcher */
624
+                $dispatcher = $this->get(IEventDispatcher::class);
625
+                $dispatcher->dispatchTyped(new UserLoggedInEvent($user, $loginName, $password, $isTokenLogin));
626
+            });
627
+            $userSession->listen('\OC\User', 'preRememberedLogin', function ($uid) {
628
+                /** @var IEventDispatcher $dispatcher */
629
+                $dispatcher = $this->get(IEventDispatcher::class);
630
+                $dispatcher->dispatchTyped(new BeforeUserLoggedInWithCookieEvent($uid));
631
+            });
632
+            $userSession->listen('\OC\User', 'postRememberedLogin', function ($user, $password) {
633
+                /** @var \OC\User\User $user */
634
+                \OC_Hook::emit('OC_User', 'post_login', ['run' => true, 'uid' => $user->getUID(), 'password' => $password]);
635
+
636
+                /** @var IEventDispatcher $dispatcher */
637
+                $dispatcher = $this->get(IEventDispatcher::class);
638
+                $dispatcher->dispatchTyped(new UserLoggedInWithCookieEvent($user, $password));
639
+            });
640
+            $userSession->listen('\OC\User', 'logout', function ($user) {
641
+                \OC_Hook::emit('OC_User', 'logout', []);
642
+
643
+                /** @var IEventDispatcher $dispatcher */
644
+                $dispatcher = $this->get(IEventDispatcher::class);
645
+                $dispatcher->dispatchTyped(new BeforeUserLoggedOutEvent($user));
646
+            });
647
+            $userSession->listen('\OC\User', 'postLogout', function ($user) {
648
+                /** @var IEventDispatcher $dispatcher */
649
+                $dispatcher = $this->get(IEventDispatcher::class);
650
+                $dispatcher->dispatchTyped(new UserLoggedOutEvent($user));
651
+            });
652
+            $userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value, $oldValue) {
653
+                /** @var \OC\User\User $user */
654
+                \OC_Hook::emit('OC_User', 'changeUser', ['run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value, 'old_value' => $oldValue]);
655
+
656
+                /** @var IEventDispatcher $dispatcher */
657
+                $dispatcher = $this->get(IEventDispatcher::class);
658
+                $dispatcher->dispatchTyped(new UserChangedEvent($user, $feature, $value, $oldValue));
659
+            });
660
+            return $userSession;
661
+        });
662
+        $this->registerAlias(\OCP\IUserSession::class, \OC\User\Session::class);
663
+        /** @deprecated 19.0.0 */
664
+        $this->registerDeprecatedAlias('UserSession', \OC\User\Session::class);
665
+
666
+        $this->registerAlias(\OCP\Authentication\TwoFactorAuth\IRegistry::class, \OC\Authentication\TwoFactorAuth\Registry::class);
667
+
668
+        $this->registerAlias(INavigationManager::class, \OC\NavigationManager::class);
669
+        /** @deprecated 19.0.0 */
670
+        $this->registerDeprecatedAlias('NavigationManager', INavigationManager::class);
671
+
672
+        /** @deprecated 19.0.0 */
673
+        $this->registerDeprecatedAlias('AllConfig', \OC\AllConfig::class);
674
+        $this->registerAlias(\OCP\IConfig::class, \OC\AllConfig::class);
675
+
676
+        $this->registerService(\OC\SystemConfig::class, function ($c) use ($config) {
677
+            return new \OC\SystemConfig($config);
678
+        });
679
+        /** @deprecated 19.0.0 */
680
+        $this->registerDeprecatedAlias('SystemConfig', \OC\SystemConfig::class);
681
+
682
+        /** @deprecated 19.0.0 */
683
+        $this->registerDeprecatedAlias('AppConfig', \OC\AppConfig::class);
684
+        $this->registerAlias(IAppConfig::class, \OC\AppConfig::class);
685
+
686
+        $this->registerService(IFactory::class, function (Server $c) {
687
+            return new \OC\L10N\Factory(
688
+                $c->get(\OCP\IConfig::class),
689
+                $c->getRequest(),
690
+                $c->get(IUserSession::class),
691
+                $c->get(ICacheFactory::class),
692
+                \OC::$SERVERROOT
693
+            );
694
+        });
695
+        /** @deprecated 19.0.0 */
696
+        $this->registerDeprecatedAlias('L10NFactory', IFactory::class);
697
+
698
+        $this->registerAlias(IURLGenerator::class, URLGenerator::class);
699
+        /** @deprecated 19.0.0 */
700
+        $this->registerDeprecatedAlias('URLGenerator', IURLGenerator::class);
701
+
702
+        /** @deprecated 19.0.0 */
703
+        $this->registerDeprecatedAlias('AppFetcher', AppFetcher::class);
704
+        /** @deprecated 19.0.0 */
705
+        $this->registerDeprecatedAlias('CategoryFetcher', CategoryFetcher::class);
706
+
707
+        $this->registerService(ICache::class, function ($c) {
708
+            return new Cache\File();
709
+        });
710
+        /** @deprecated 19.0.0 */
711
+        $this->registerDeprecatedAlias('UserCache', ICache::class);
712
+
713
+        $this->registerService(Factory::class, function (Server $c) {
714
+            $profiler = $c->get(IProfiler::class);
715
+            $arrayCacheFactory = new \OC\Memcache\Factory('', $c->get(LoggerInterface::class),
716
+                $profiler,
717
+                ArrayCache::class,
718
+                ArrayCache::class,
719
+                ArrayCache::class
720
+            );
721
+            /** @var \OCP\IConfig $config */
722
+            $config = $c->get(\OCP\IConfig::class);
723
+
724
+            if ($config->getSystemValue('installed', false) && !(defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
725
+                if (!$config->getSystemValueBool('log_query')) {
726
+                    $v = \OC_App::getAppVersions();
727
+                } else {
728
+                    // If the log_query is enabled, we can not get the app versions
729
+                    // as that does a query, which will be logged and the logging
730
+                    // depends on redis and here we are back again in the same function.
731
+                    $v = [
732
+                        'log_query' => 'enabled',
733
+                    ];
734
+                }
735
+                $v['core'] = implode(',', \OC_Util::getVersion());
736
+                $version = implode(',', $v);
737
+                $instanceId = \OC_Util::getInstanceId();
738
+                $path = \OC::$SERVERROOT;
739
+                $prefix = md5($instanceId . '-' . $version . '-' . $path);
740
+                return new \OC\Memcache\Factory($prefix,
741
+                    $c->get(LoggerInterface::class),
742
+                    $profiler,
743
+                    $config->getSystemValue('memcache.local', null),
744
+                    $config->getSystemValue('memcache.distributed', null),
745
+                    $config->getSystemValue('memcache.locking', null),
746
+                    $config->getSystemValueString('redis_log_file')
747
+                );
748
+            }
749
+            return $arrayCacheFactory;
750
+        });
751
+        /** @deprecated 19.0.0 */
752
+        $this->registerDeprecatedAlias('MemCacheFactory', Factory::class);
753
+        $this->registerAlias(ICacheFactory::class, Factory::class);
754
+
755
+        $this->registerService('RedisFactory', function (Server $c) {
756
+            $systemConfig = $c->get(SystemConfig::class);
757
+            return new RedisFactory($systemConfig, $c->getEventLogger());
758
+        });
759
+
760
+        $this->registerService(\OCP\Activity\IManager::class, function (Server $c) {
761
+            $l10n = $this->get(IFactory::class)->get('lib');
762
+            return new \OC\Activity\Manager(
763
+                $c->getRequest(),
764
+                $c->get(IUserSession::class),
765
+                $c->get(\OCP\IConfig::class),
766
+                $c->get(IValidator::class),
767
+                $l10n
768
+            );
769
+        });
770
+        /** @deprecated 19.0.0 */
771
+        $this->registerDeprecatedAlias('ActivityManager', \OCP\Activity\IManager::class);
772
+
773
+        $this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
774
+            return new \OC\Activity\EventMerger(
775
+                $c->getL10N('lib')
776
+            );
777
+        });
778
+        $this->registerAlias(IValidator::class, Validator::class);
779
+
780
+        $this->registerService(AvatarManager::class, function (Server $c) {
781
+            return new AvatarManager(
782
+                $c->get(IUserSession::class),
783
+                $c->get(\OC\User\Manager::class),
784
+                $c->getAppDataDir('avatar'),
785
+                $c->getL10N('lib'),
786
+                $c->get(LoggerInterface::class),
787
+                $c->get(\OCP\IConfig::class),
788
+                $c->get(IAccountManager::class),
789
+                $c->get(KnownUserService::class)
790
+            );
791
+        });
792
+
793
+        $this->registerAlias(IAvatarManager::class, AvatarManager::class);
794
+        /** @deprecated 19.0.0 */
795
+        $this->registerDeprecatedAlias('AvatarManager', AvatarManager::class);
796
+
797
+        $this->registerAlias(\OCP\Support\CrashReport\IRegistry::class, \OC\Support\CrashReport\Registry::class);
798
+        $this->registerAlias(\OCP\Support\Subscription\IRegistry::class, \OC\Support\Subscription\Registry::class);
799
+        $this->registerAlias(\OCP\Support\Subscription\IAssertion::class, \OC\Support\Subscription\Assertion::class);
800
+
801
+        $this->registerService(\OC\Log::class, function (Server $c) {
802
+            $logType = $c->get(AllConfig::class)->getSystemValue('log_type', 'file');
803
+            $factory = new LogFactory($c, $this->get(SystemConfig::class));
804
+            $logger = $factory->get($logType);
805
+            $registry = $c->get(\OCP\Support\CrashReport\IRegistry::class);
806
+
807
+            return new Log($logger, $this->get(SystemConfig::class), null, $registry);
808
+        });
809
+        $this->registerAlias(ILogger::class, \OC\Log::class);
810
+        /** @deprecated 19.0.0 */
811
+        $this->registerDeprecatedAlias('Logger', \OC\Log::class);
812
+        // PSR-3 logger
813
+        $this->registerAlias(LoggerInterface::class, PsrLoggerAdapter::class);
814
+
815
+        $this->registerService(ILogFactory::class, function (Server $c) {
816
+            return new LogFactory($c, $this->get(SystemConfig::class));
817
+        });
818
+
819
+        $this->registerAlias(IJobList::class, \OC\BackgroundJob\JobList::class);
820
+        /** @deprecated 19.0.0 */
821
+        $this->registerDeprecatedAlias('JobList', IJobList::class);
822
+
823
+        $this->registerService(Router::class, function (Server $c) {
824
+            $cacheFactory = $c->get(ICacheFactory::class);
825
+            $logger = $c->get(LoggerInterface::class);
826
+            if ($cacheFactory->isLocalCacheAvailable()) {
827
+                $router = new \OC\Route\CachingRouter($cacheFactory->createLocal('route'), $logger);
828
+            } else {
829
+                $router = new \OC\Route\Router($logger);
830
+            }
831
+            return $router;
832
+        });
833
+        $this->registerAlias(IRouter::class, Router::class);
834
+        /** @deprecated 19.0.0 */
835
+        $this->registerDeprecatedAlias('Router', IRouter::class);
836
+
837
+        $this->registerAlias(ISearch::class, Search::class);
838
+        /** @deprecated 19.0.0 */
839
+        $this->registerDeprecatedAlias('Search', ISearch::class);
840
+
841
+        $this->registerService(\OC\Security\RateLimiting\Backend\IBackend::class, function ($c) {
842
+            $cacheFactory = $c->get(ICacheFactory::class);
843
+            if ($cacheFactory->isAvailable()) {
844
+                $backend = new \OC\Security\RateLimiting\Backend\MemoryCacheBackend(
845
+                    $this->get(ICacheFactory::class),
846
+                    new \OC\AppFramework\Utility\TimeFactory()
847
+                );
848
+            } else {
849
+                $backend = new \OC\Security\RateLimiting\Backend\DatabaseBackend(
850
+                    $c->get(IDBConnection::class),
851
+                    new \OC\AppFramework\Utility\TimeFactory()
852
+                );
853
+            }
854
+
855
+            return $backend;
856
+        });
857
+
858
+        $this->registerAlias(\OCP\Security\ISecureRandom::class, SecureRandom::class);
859
+        /** @deprecated 19.0.0 */
860
+        $this->registerDeprecatedAlias('SecureRandom', \OCP\Security\ISecureRandom::class);
861
+        $this->registerAlias(\OCP\Security\IRemoteHostValidator::class, \OC\Security\RemoteHostValidator::class);
862
+        $this->registerAlias(IVerificationToken::class, VerificationToken::class);
863
+
864
+        $this->registerAlias(ICrypto::class, Crypto::class);
865
+        /** @deprecated 19.0.0 */
866
+        $this->registerDeprecatedAlias('Crypto', ICrypto::class);
867
+
868
+        $this->registerAlias(IHasher::class, Hasher::class);
869
+        /** @deprecated 19.0.0 */
870
+        $this->registerDeprecatedAlias('Hasher', IHasher::class);
871
+
872
+        $this->registerAlias(ICredentialsManager::class, CredentialsManager::class);
873
+        /** @deprecated 19.0.0 */
874
+        $this->registerDeprecatedAlias('CredentialsManager', ICredentialsManager::class);
875
+
876
+        $this->registerAlias(IDBConnection::class, ConnectionAdapter::class);
877
+        $this->registerService(Connection::class, function (Server $c) {
878
+            $systemConfig = $c->get(SystemConfig::class);
879
+            $factory = new \OC\DB\ConnectionFactory($systemConfig);
880
+            $type = $systemConfig->getValue('dbtype', 'sqlite');
881
+            if (!$factory->isValidType($type)) {
882
+                throw new \OC\DatabaseException('Invalid database type');
883
+            }
884
+            $connectionParams = $factory->createConnectionParams();
885
+            $connection = $factory->getConnection($type, $connectionParams);
886
+            return $connection;
887
+        });
888
+        /** @deprecated 19.0.0 */
889
+        $this->registerDeprecatedAlias('DatabaseConnection', IDBConnection::class);
890
+
891
+        $this->registerAlias(ICertificateManager::class, CertificateManager::class);
892
+        $this->registerAlias(IClientService::class, ClientService::class);
893
+        $this->registerService(NegativeDnsCache::class, function (ContainerInterface $c) {
894
+            return new NegativeDnsCache(
895
+                $c->get(ICacheFactory::class),
896
+            );
897
+        });
898
+        $this->registerDeprecatedAlias('HttpClientService', IClientService::class);
899
+        $this->registerService(IEventLogger::class, function (ContainerInterface $c) {
900
+            return new EventLogger($c->get(SystemConfig::class), $c->get(LoggerInterface::class), $c->get(Log::class));
901
+        });
902
+        /** @deprecated 19.0.0 */
903
+        $this->registerDeprecatedAlias('EventLogger', IEventLogger::class);
904
+
905
+        $this->registerService(IQueryLogger::class, function (ContainerInterface $c) {
906
+            $queryLogger = new QueryLogger();
907
+            if ($c->get(SystemConfig::class)->getValue('debug', false)) {
908
+                // In debug mode, module is being activated by default
909
+                $queryLogger->activate();
910
+            }
911
+            return $queryLogger;
912
+        });
913
+        /** @deprecated 19.0.0 */
914
+        $this->registerDeprecatedAlias('QueryLogger', IQueryLogger::class);
915
+
916
+        /** @deprecated 19.0.0 */
917
+        $this->registerDeprecatedAlias('TempManager', TempManager::class);
918
+        $this->registerAlias(ITempManager::class, TempManager::class);
919
+
920
+        $this->registerService(AppManager::class, function (ContainerInterface $c) {
921
+            // TODO: use auto-wiring
922
+            return new \OC\App\AppManager(
923
+                $c->get(IUserSession::class),
924
+                $c->get(\OCP\IConfig::class),
925
+                $c->get(\OC\AppConfig::class),
926
+                $c->get(IGroupManager::class),
927
+                $c->get(ICacheFactory::class),
928
+                $c->get(SymfonyAdapter::class),
929
+                $c->get(LoggerInterface::class)
930
+            );
931
+        });
932
+        /** @deprecated 19.0.0 */
933
+        $this->registerDeprecatedAlias('AppManager', AppManager::class);
934
+        $this->registerAlias(IAppManager::class, AppManager::class);
935
+
936
+        $this->registerAlias(IDateTimeZone::class, DateTimeZone::class);
937
+        /** @deprecated 19.0.0 */
938
+        $this->registerDeprecatedAlias('DateTimeZone', IDateTimeZone::class);
939
+
940
+        $this->registerService(IDateTimeFormatter::class, function (Server $c) {
941
+            $language = $c->get(\OCP\IConfig::class)->getUserValue($c->get(ISession::class)->get('user_id'), 'core', 'lang', null);
942
+
943
+            return new DateTimeFormatter(
944
+                $c->get(IDateTimeZone::class)->getTimeZone(),
945
+                $c->getL10N('lib', $language)
946
+            );
947
+        });
948
+        /** @deprecated 19.0.0 */
949
+        $this->registerDeprecatedAlias('DateTimeFormatter', IDateTimeFormatter::class);
950
+
951
+        $this->registerService(IUserMountCache::class, function (ContainerInterface $c) {
952
+            $mountCache = new UserMountCache(
953
+                $c->get(IDBConnection::class),
954
+                $c->get(IUserManager::class),
955
+                $c->get(LoggerInterface::class)
956
+            );
957
+            $listener = new UserMountCacheListener($mountCache);
958
+            $listener->listen($c->get(IUserManager::class));
959
+            return $mountCache;
960
+        });
961
+        /** @deprecated 19.0.0 */
962
+        $this->registerDeprecatedAlias('UserMountCache', IUserMountCache::class);
963
+
964
+        $this->registerService(IMountProviderCollection::class, function (ContainerInterface $c) {
965
+            $loader = \OC\Files\Filesystem::getLoader();
966
+            $mountCache = $c->get(IUserMountCache::class);
967
+            $manager = new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
968
+
969
+            // builtin providers
970
+
971
+            $config = $c->get(\OCP\IConfig::class);
972
+            $logger = $c->get(LoggerInterface::class);
973
+            $manager->registerProvider(new CacheMountProvider($config));
974
+            $manager->registerHomeProvider(new LocalHomeMountProvider());
975
+            $manager->registerHomeProvider(new ObjectHomeMountProvider($config));
976
+            $manager->registerRootProvider(new RootMountProvider($config, $c->get(LoggerInterface::class)));
977
+            $manager->registerRootProvider(new ObjectStorePreviewCacheMountProvider($logger, $config));
978
+
979
+            return $manager;
980
+        });
981
+        /** @deprecated 19.0.0 */
982
+        $this->registerDeprecatedAlias('MountConfigManager', IMountProviderCollection::class);
983
+
984
+        /** @deprecated 20.0.0 */
985
+        $this->registerDeprecatedAlias('IniWrapper', IniGetWrapper::class);
986
+        $this->registerService(IBus::class, function (ContainerInterface $c) {
987
+            $busClass = $c->get(\OCP\IConfig::class)->getSystemValue('commandbus');
988
+            if ($busClass) {
989
+                [$app, $class] = explode('::', $busClass, 2);
990
+                if ($c->get(IAppManager::class)->isInstalled($app)) {
991
+                    \OC_App::loadApp($app);
992
+                    return $c->get($class);
993
+                } else {
994
+                    throw new ServiceUnavailableException("The app providing the command bus ($app) is not enabled");
995
+                }
996
+            } else {
997
+                $jobList = $c->get(IJobList::class);
998
+                return new CronBus($jobList);
999
+            }
1000
+        });
1001
+        $this->registerDeprecatedAlias('AsyncCommandBus', IBus::class);
1002
+        /** @deprecated 20.0.0 */
1003
+        $this->registerDeprecatedAlias('TrustedDomainHelper', TrustedDomainHelper::class);
1004
+        $this->registerAlias(ITrustedDomainHelper::class, TrustedDomainHelper::class);
1005
+        /** @deprecated 19.0.0 */
1006
+        $this->registerDeprecatedAlias('Throttler', Throttler::class);
1007
+        $this->registerAlias(IThrottler::class, Throttler::class);
1008
+        $this->registerService('IntegrityCodeChecker', function (ContainerInterface $c) {
1009
+            // IConfig and IAppManager requires a working database. This code
1010
+            // might however be called when ownCloud is not yet setup.
1011
+            if (\OC::$server->get(SystemConfig::class)->getValue('installed', false)) {
1012
+                $config = $c->get(\OCP\IConfig::class);
1013
+                $appManager = $c->get(IAppManager::class);
1014
+            } else {
1015
+                $config = null;
1016
+                $appManager = null;
1017
+            }
1018
+
1019
+            return new Checker(
1020
+                new EnvironmentHelper(),
1021
+                new FileAccessHelper(),
1022
+                new AppLocator(),
1023
+                $config,
1024
+                $c->get(ICacheFactory::class),
1025
+                $appManager,
1026
+                $c->get(IMimeTypeDetector::class)
1027
+            );
1028
+        });
1029
+        $this->registerService(\OCP\IRequest::class, function (ContainerInterface $c) {
1030
+            if (isset($this['urlParams'])) {
1031
+                $urlParams = $this['urlParams'];
1032
+            } else {
1033
+                $urlParams = [];
1034
+            }
1035
+
1036
+            if (defined('PHPUNIT_RUN') && PHPUNIT_RUN
1037
+                && in_array('fakeinput', stream_get_wrappers())
1038
+            ) {
1039
+                $stream = 'fakeinput://data';
1040
+            } else {
1041
+                $stream = 'php://input';
1042
+            }
1043
+
1044
+            return new Request(
1045
+                [
1046
+                    'get' => $_GET,
1047
+                    'post' => $_POST,
1048
+                    'files' => $_FILES,
1049
+                    'server' => $_SERVER,
1050
+                    'env' => $_ENV,
1051
+                    'cookies' => $_COOKIE,
1052
+                    'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
1053
+                        ? $_SERVER['REQUEST_METHOD']
1054
+                        : '',
1055
+                    'urlParams' => $urlParams,
1056
+                ],
1057
+                $this->get(IRequestId::class),
1058
+                $this->get(\OCP\IConfig::class),
1059
+                $this->get(CsrfTokenManager::class),
1060
+                $stream
1061
+            );
1062
+        });
1063
+        /** @deprecated 19.0.0 */
1064
+        $this->registerDeprecatedAlias('Request', \OCP\IRequest::class);
1065
+
1066
+        $this->registerService(IRequestId::class, function (ContainerInterface $c): IRequestId {
1067
+            return new RequestId(
1068
+                $_SERVER['UNIQUE_ID'] ?? '',
1069
+                $this->get(ISecureRandom::class)
1070
+            );
1071
+        });
1072
+
1073
+        $this->registerService(IMailer::class, function (Server $c) {
1074
+            return new Mailer(
1075
+                $c->get(\OCP\IConfig::class),
1076
+                $c->get(LoggerInterface::class),
1077
+                $c->get(Defaults::class),
1078
+                $c->get(IURLGenerator::class),
1079
+                $c->getL10N('lib'),
1080
+                $c->get(IEventDispatcher::class),
1081
+                $c->get(IFactory::class)
1082
+            );
1083
+        });
1084
+        /** @deprecated 19.0.0 */
1085
+        $this->registerDeprecatedAlias('Mailer', IMailer::class);
1086
+
1087
+        /** @deprecated 21.0.0 */
1088
+        $this->registerDeprecatedAlias('LDAPProvider', ILDAPProvider::class);
1089
+
1090
+        $this->registerService(ILDAPProviderFactory::class, function (ContainerInterface $c) {
1091
+            $config = $c->get(\OCP\IConfig::class);
1092
+            $factoryClass = $config->getSystemValue('ldapProviderFactory', null);
1093
+            if (is_null($factoryClass) || !class_exists($factoryClass)) {
1094
+                return new NullLDAPProviderFactory($this);
1095
+            }
1096
+            /** @var \OCP\LDAP\ILDAPProviderFactory $factory */
1097
+            return new $factoryClass($this);
1098
+        });
1099
+        $this->registerService(ILDAPProvider::class, function (ContainerInterface $c) {
1100
+            $factory = $c->get(ILDAPProviderFactory::class);
1101
+            return $factory->getLDAPProvider();
1102
+        });
1103
+        $this->registerService(ILockingProvider::class, function (ContainerInterface $c) {
1104
+            $ini = $c->get(IniGetWrapper::class);
1105
+            $config = $c->get(\OCP\IConfig::class);
1106
+            $ttl = $config->getSystemValue('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
1107
+            if ($config->getSystemValue('filelocking.enabled', true) or (defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
1108
+                /** @var \OC\Memcache\Factory $memcacheFactory */
1109
+                $memcacheFactory = $c->get(ICacheFactory::class);
1110
+                $memcache = $memcacheFactory->createLocking('lock');
1111
+                if (!($memcache instanceof \OC\Memcache\NullCache)) {
1112
+                    return new MemcacheLockingProvider($memcache, $ttl);
1113
+                }
1114
+                return new DBLockingProvider(
1115
+                    $c->get(IDBConnection::class),
1116
+                    new TimeFactory(),
1117
+                    $ttl,
1118
+                    !\OC::$CLI
1119
+                );
1120
+            }
1121
+            return new NoopLockingProvider();
1122
+        });
1123
+        /** @deprecated 19.0.0 */
1124
+        $this->registerDeprecatedAlias('LockingProvider', ILockingProvider::class);
1125
+
1126
+        $this->registerService(ILockManager::class, function (Server $c): LockManager {
1127
+            return new LockManager();
1128
+        });
1129
+
1130
+        $this->registerAlias(ILockdownManager::class, 'LockdownManager');
1131
+        $this->registerService(SetupManager::class, function ($c) {
1132
+            // create the setupmanager through the mount manager to resolve the cyclic dependency
1133
+            return $c->get(\OC\Files\Mount\Manager::class)->getSetupManager();
1134
+        });
1135
+        $this->registerAlias(IMountManager::class, \OC\Files\Mount\Manager::class);
1136
+        /** @deprecated 19.0.0 */
1137
+        $this->registerDeprecatedAlias('MountManager', IMountManager::class);
1138
+
1139
+        $this->registerService(IMimeTypeDetector::class, function (ContainerInterface $c) {
1140
+            return new \OC\Files\Type\Detection(
1141
+                $c->get(IURLGenerator::class),
1142
+                $c->get(LoggerInterface::class),
1143
+                \OC::$configDir,
1144
+                \OC::$SERVERROOT . '/resources/config/'
1145
+            );
1146
+        });
1147
+        /** @deprecated 19.0.0 */
1148
+        $this->registerDeprecatedAlias('MimeTypeDetector', IMimeTypeDetector::class);
1149
+
1150
+        $this->registerAlias(IMimeTypeLoader::class, Loader::class);
1151
+        /** @deprecated 19.0.0 */
1152
+        $this->registerDeprecatedAlias('MimeTypeLoader', IMimeTypeLoader::class);
1153
+        $this->registerService(BundleFetcher::class, function () {
1154
+            return new BundleFetcher($this->getL10N('lib'));
1155
+        });
1156
+        $this->registerAlias(\OCP\Notification\IManager::class, Manager::class);
1157
+        /** @deprecated 19.0.0 */
1158
+        $this->registerDeprecatedAlias('NotificationManager', \OCP\Notification\IManager::class);
1159
+
1160
+        $this->registerService(CapabilitiesManager::class, function (ContainerInterface $c) {
1161
+            $manager = new CapabilitiesManager($c->get(LoggerInterface::class));
1162
+            $manager->registerCapability(function () use ($c) {
1163
+                return new \OC\OCS\CoreCapabilities($c->get(\OCP\IConfig::class));
1164
+            });
1165
+            $manager->registerCapability(function () use ($c) {
1166
+                return $c->get(\OC\Security\Bruteforce\Capabilities::class);
1167
+            });
1168
+            $manager->registerCapability(function () use ($c) {
1169
+                return $c->get(MetadataCapabilities::class);
1170
+            });
1171
+            return $manager;
1172
+        });
1173
+        /** @deprecated 19.0.0 */
1174
+        $this->registerDeprecatedAlias('CapabilitiesManager', CapabilitiesManager::class);
1175
+
1176
+        $this->registerService(ICommentsManager::class, function (Server $c) {
1177
+            $config = $c->get(\OCP\IConfig::class);
1178
+            $factoryClass = $config->getSystemValue('comments.managerFactory', CommentsManagerFactory::class);
1179
+            /** @var \OCP\Comments\ICommentsManagerFactory $factory */
1180
+            $factory = new $factoryClass($this);
1181
+            $manager = $factory->getManager();
1182
+
1183
+            $manager->registerDisplayNameResolver('user', function ($id) use ($c) {
1184
+                $manager = $c->get(IUserManager::class);
1185
+                $userDisplayName = $manager->getDisplayName($id);
1186
+                if ($userDisplayName === null) {
1187
+                    $l = $c->get(IFactory::class)->get('core');
1188
+                    return $l->t('Unknown user');
1189
+                }
1190
+                return $userDisplayName;
1191
+            });
1192
+
1193
+            return $manager;
1194
+        });
1195
+        /** @deprecated 19.0.0 */
1196
+        $this->registerDeprecatedAlias('CommentsManager', ICommentsManager::class);
1197
+
1198
+        $this->registerAlias(\OC_Defaults::class, 'ThemingDefaults');
1199
+        $this->registerService('ThemingDefaults', function (Server $c) {
1200
+            /*
1201 1201
 			 * Dark magic for autoloader.
1202 1202
 			 * If we do a class_exists it will try to load the class which will
1203 1203
 			 * make composer cache the result. Resulting in errors when enabling
1204 1204
 			 * the theming app.
1205 1205
 			 */
1206
-			$prefixes = \OC::$composerAutoloader->getPrefixesPsr4();
1207
-			if (isset($prefixes['OCA\\Theming\\'])) {
1208
-				$classExists = true;
1209
-			} else {
1210
-				$classExists = false;
1211
-			}
1212
-
1213
-			if ($classExists && $c->get(\OCP\IConfig::class)->getSystemValue('installed', false) && $c->get(IAppManager::class)->isInstalled('theming') && $c->getTrustedDomainHelper()->isTrustedDomain($c->getRequest()->getInsecureServerHost())) {
1214
-				$imageManager = new ImageManager(
1215
-					$c->get(\OCP\IConfig::class),
1216
-					$c->getAppDataDir('theming'),
1217
-					$c->get(IURLGenerator::class),
1218
-					$this->get(ICacheFactory::class),
1219
-					$this->get(ILogger::class),
1220
-					$this->get(ITempManager::class)
1221
-				);
1222
-				return new ThemingDefaults(
1223
-					$c->get(\OCP\IConfig::class),
1224
-					$c->getL10N('theming'),
1225
-					$c->get(IUserSession::class),
1226
-					$c->get(IURLGenerator::class),
1227
-					$c->get(ICacheFactory::class),
1228
-					new Util($c->get(\OCP\IConfig::class), $this->get(IAppManager::class), $c->getAppDataDir('theming'), $imageManager),
1229
-					$imageManager,
1230
-					$c->get(IAppManager::class),
1231
-					$c->get(INavigationManager::class)
1232
-				);
1233
-			}
1234
-			return new \OC_Defaults();
1235
-		});
1236
-		$this->registerService(JSCombiner::class, function (Server $c) {
1237
-			return new JSCombiner(
1238
-				$c->getAppDataDir('js'),
1239
-				$c->get(IURLGenerator::class),
1240
-				$this->get(ICacheFactory::class),
1241
-				$c->get(SystemConfig::class),
1242
-				$c->get(LoggerInterface::class)
1243
-			);
1244
-		});
1245
-		$this->registerAlias(\OCP\EventDispatcher\IEventDispatcher::class, \OC\EventDispatcher\EventDispatcher::class);
1246
-		/** @deprecated 19.0.0 */
1247
-		$this->registerDeprecatedAlias('EventDispatcher', \OC\EventDispatcher\SymfonyAdapter::class);
1248
-		$this->registerAlias(EventDispatcherInterface::class, \OC\EventDispatcher\SymfonyAdapter::class);
1249
-
1250
-		$this->registerService('CryptoWrapper', function (ContainerInterface $c) {
1251
-			// FIXME: Instantiated here due to cyclic dependency
1252
-			$request = new Request(
1253
-				[
1254
-					'get' => $_GET,
1255
-					'post' => $_POST,
1256
-					'files' => $_FILES,
1257
-					'server' => $_SERVER,
1258
-					'env' => $_ENV,
1259
-					'cookies' => $_COOKIE,
1260
-					'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
1261
-						? $_SERVER['REQUEST_METHOD']
1262
-						: null,
1263
-				],
1264
-				$c->get(IRequestId::class),
1265
-				$c->get(\OCP\IConfig::class)
1266
-			);
1267
-
1268
-			return new CryptoWrapper(
1269
-				$c->get(\OCP\IConfig::class),
1270
-				$c->get(ICrypto::class),
1271
-				$c->get(ISecureRandom::class),
1272
-				$request
1273
-			);
1274
-		});
1275
-		/** @deprecated 19.0.0 */
1276
-		$this->registerDeprecatedAlias('CsrfTokenManager', CsrfTokenManager::class);
1277
-		$this->registerService(SessionStorage::class, function (ContainerInterface $c) {
1278
-			return new SessionStorage($c->get(ISession::class));
1279
-		});
1280
-		$this->registerAlias(\OCP\Security\IContentSecurityPolicyManager::class, ContentSecurityPolicyManager::class);
1281
-		/** @deprecated 19.0.0 */
1282
-		$this->registerDeprecatedAlias('ContentSecurityPolicyManager', ContentSecurityPolicyManager::class);
1283
-
1284
-		$this->registerService(\OCP\Share\IManager::class, function (IServerContainer $c) {
1285
-			$config = $c->get(\OCP\IConfig::class);
1286
-			$factoryClass = $config->getSystemValue('sharing.managerFactory', ProviderFactory::class);
1287
-			/** @var \OCP\Share\IProviderFactory $factory */
1288
-			$factory = new $factoryClass($this);
1289
-
1290
-			$manager = new \OC\Share20\Manager(
1291
-				$c->get(LoggerInterface::class),
1292
-				$c->get(\OCP\IConfig::class),
1293
-				$c->get(ISecureRandom::class),
1294
-				$c->get(IHasher::class),
1295
-				$c->get(IMountManager::class),
1296
-				$c->get(IGroupManager::class),
1297
-				$c->getL10N('lib'),
1298
-				$c->get(IFactory::class),
1299
-				$factory,
1300
-				$c->get(IUserManager::class),
1301
-				$c->get(IRootFolder::class),
1302
-				$c->get(SymfonyAdapter::class),
1303
-				$c->get(IMailer::class),
1304
-				$c->get(IURLGenerator::class),
1305
-				$c->get('ThemingDefaults'),
1306
-				$c->get(IEventDispatcher::class),
1307
-				$c->get(IUserSession::class),
1308
-				$c->get(KnownUserService::class)
1309
-			);
1310
-
1311
-			return $manager;
1312
-		});
1313
-		/** @deprecated 19.0.0 */
1314
-		$this->registerDeprecatedAlias('ShareManager', \OCP\Share\IManager::class);
1315
-
1316
-		$this->registerService(\OCP\Collaboration\Collaborators\ISearch::class, function (Server $c) {
1317
-			$instance = new Collaboration\Collaborators\Search($c);
1318
-
1319
-			// register default plugins
1320
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_USER', 'class' => UserPlugin::class]);
1321
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_GROUP', 'class' => GroupPlugin::class]);
1322
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_EMAIL', 'class' => MailPlugin::class]);
1323
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_REMOTE', 'class' => RemotePlugin::class]);
1324
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_REMOTE_GROUP', 'class' => RemoteGroupPlugin::class]);
1325
-
1326
-			return $instance;
1327
-		});
1328
-		/** @deprecated 19.0.0 */
1329
-		$this->registerDeprecatedAlias('CollaboratorSearch', \OCP\Collaboration\Collaborators\ISearch::class);
1330
-		$this->registerAlias(\OCP\Collaboration\Collaborators\ISearchResult::class, \OC\Collaboration\Collaborators\SearchResult::class);
1331
-
1332
-		$this->registerAlias(\OCP\Collaboration\AutoComplete\IManager::class, \OC\Collaboration\AutoComplete\Manager::class);
1333
-
1334
-		$this->registerAlias(\OCP\Collaboration\Resources\IProviderManager::class, \OC\Collaboration\Resources\ProviderManager::class);
1335
-		$this->registerAlias(\OCP\Collaboration\Resources\IManager::class, \OC\Collaboration\Resources\Manager::class);
1336
-
1337
-		$this->registerAlias(IReferenceManager::class, ReferenceManager::class);
1338
-
1339
-		$this->registerDeprecatedAlias('SettingsManager', \OC\Settings\Manager::class);
1340
-		$this->registerAlias(\OCP\Settings\IManager::class, \OC\Settings\Manager::class);
1341
-		$this->registerService(\OC\Files\AppData\Factory::class, function (ContainerInterface $c) {
1342
-			return new \OC\Files\AppData\Factory(
1343
-				$c->get(IRootFolder::class),
1344
-				$c->get(SystemConfig::class)
1345
-			);
1346
-		});
1347
-
1348
-		$this->registerService('LockdownManager', function (ContainerInterface $c) {
1349
-			return new LockdownManager(function () use ($c) {
1350
-				return $c->get(ISession::class);
1351
-			});
1352
-		});
1353
-
1354
-		$this->registerService(\OCP\OCS\IDiscoveryService::class, function (ContainerInterface $c) {
1355
-			return new DiscoveryService(
1356
-				$c->get(ICacheFactory::class),
1357
-				$c->get(IClientService::class)
1358
-			);
1359
-		});
1360
-
1361
-		$this->registerService(ICloudIdManager::class, function (ContainerInterface $c) {
1362
-			return new CloudIdManager(
1363
-				$c->get(\OCP\Contacts\IManager::class),
1364
-				$c->get(IURLGenerator::class),
1365
-				$c->get(IUserManager::class),
1366
-				$c->get(ICacheFactory::class),
1367
-				$c->get(IEventDispatcher::class),
1368
-			);
1369
-		});
1370
-
1371
-		$this->registerAlias(\OCP\GlobalScale\IConfig::class, \OC\GlobalScale\Config::class);
1372
-
1373
-		$this->registerService(ICloudFederationProviderManager::class, function (ContainerInterface $c) {
1374
-			return new CloudFederationProviderManager(
1375
-				$c->get(IAppManager::class),
1376
-				$c->get(IClientService::class),
1377
-				$c->get(ICloudIdManager::class),
1378
-				$c->get(LoggerInterface::class)
1379
-			);
1380
-		});
1381
-
1382
-		$this->registerService(ICloudFederationFactory::class, function (Server $c) {
1383
-			return new CloudFederationFactory();
1384
-		});
1385
-
1386
-		$this->registerAlias(\OCP\AppFramework\Utility\IControllerMethodReflector::class, \OC\AppFramework\Utility\ControllerMethodReflector::class);
1387
-		/** @deprecated 19.0.0 */
1388
-		$this->registerDeprecatedAlias('ControllerMethodReflector', \OCP\AppFramework\Utility\IControllerMethodReflector::class);
1389
-
1390
-		$this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
1391
-		/** @deprecated 19.0.0 */
1392
-		$this->registerDeprecatedAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
1393
-
1394
-		$this->registerService(Defaults::class, function (Server $c) {
1395
-			return new Defaults(
1396
-				$c->getThemingDefaults()
1397
-			);
1398
-		});
1399
-		/** @deprecated 19.0.0 */
1400
-		$this->registerDeprecatedAlias('Defaults', \OCP\Defaults::class);
1401
-
1402
-		$this->registerService(\OCP\ISession::class, function (ContainerInterface $c) {
1403
-			return $c->get(\OCP\IUserSession::class)->getSession();
1404
-		}, false);
1405
-
1406
-		$this->registerService(IShareHelper::class, function (ContainerInterface $c) {
1407
-			return new ShareHelper(
1408
-				$c->get(\OCP\Share\IManager::class)
1409
-			);
1410
-		});
1411
-
1412
-		$this->registerService(Installer::class, function (ContainerInterface $c) {
1413
-			return new Installer(
1414
-				$c->get(AppFetcher::class),
1415
-				$c->get(IClientService::class),
1416
-				$c->get(ITempManager::class),
1417
-				$c->get(LoggerInterface::class),
1418
-				$c->get(\OCP\IConfig::class),
1419
-				\OC::$CLI
1420
-			);
1421
-		});
1422
-
1423
-		$this->registerService(IApiFactory::class, function (ContainerInterface $c) {
1424
-			return new ApiFactory($c->get(IClientService::class));
1425
-		});
1426
-
1427
-		$this->registerService(IInstanceFactory::class, function (ContainerInterface $c) {
1428
-			$memcacheFactory = $c->get(ICacheFactory::class);
1429
-			return new InstanceFactory($memcacheFactory->createLocal('remoteinstance.'), $c->get(IClientService::class));
1430
-		});
1431
-
1432
-		$this->registerAlias(IContactsStore::class, ContactsStore::class);
1433
-		$this->registerAlias(IAccountManager::class, AccountManager::class);
1434
-
1435
-		$this->registerAlias(IStorageFactory::class, StorageFactory::class);
1436
-
1437
-		$this->registerAlias(IDashboardManager::class, DashboardManager::class);
1438
-		$this->registerAlias(\OCP\Dashboard\IManager::class, \OC\Dashboard\Manager::class);
1439
-		$this->registerAlias(IFullTextSearchManager::class, FullTextSearchManager::class);
1440
-
1441
-		$this->registerAlias(ISubAdmin::class, SubAdmin::class);
1442
-
1443
-		$this->registerAlias(IInitialStateService::class, InitialStateService::class);
1444
-
1445
-		$this->registerAlias(\OCP\IEmojiHelper::class, \OC\EmojiHelper::class);
1446
-
1447
-		$this->registerAlias(\OCP\UserStatus\IManager::class, \OC\UserStatus\Manager::class);
1448
-
1449
-		$this->registerAlias(IBroker::class, Broker::class);
1450
-
1451
-		$this->registerAlias(IMetadataManager::class, MetadataManager::class);
1452
-
1453
-		$this->registerAlias(\OCP\Files\AppData\IAppDataFactory::class, \OC\Files\AppData\Factory::class);
1454
-
1455
-		$this->registerAlias(IBinaryFinder::class, BinaryFinder::class);
1456
-
1457
-		$this->connectDispatcher();
1458
-	}
1459
-
1460
-	public function boot() {
1461
-		/** @var HookConnector $hookConnector */
1462
-		$hookConnector = $this->get(HookConnector::class);
1463
-		$hookConnector->viewToNode();
1464
-	}
1465
-
1466
-	/**
1467
-	 * @return \OCP\Calendar\IManager
1468
-	 * @deprecated 20.0.0
1469
-	 */
1470
-	public function getCalendarManager() {
1471
-		return $this->get(\OC\Calendar\Manager::class);
1472
-	}
1473
-
1474
-	/**
1475
-	 * @return \OCP\Calendar\Resource\IManager
1476
-	 * @deprecated 20.0.0
1477
-	 */
1478
-	public function getCalendarResourceBackendManager() {
1479
-		return $this->get(\OC\Calendar\Resource\Manager::class);
1480
-	}
1481
-
1482
-	/**
1483
-	 * @return \OCP\Calendar\Room\IManager
1484
-	 * @deprecated 20.0.0
1485
-	 */
1486
-	public function getCalendarRoomBackendManager() {
1487
-		return $this->get(\OC\Calendar\Room\Manager::class);
1488
-	}
1489
-
1490
-	private function connectDispatcher(): void {
1491
-		/** @var IEventDispatcher $eventDispatcher */
1492
-		$eventDispatcher = $this->get(IEventDispatcher::class);
1493
-		$eventDispatcher->addServiceListener(LoginFailed::class, LoginFailedListener::class);
1494
-		$eventDispatcher->addServiceListener(PostLoginEvent::class, UserLoggedInListener::class);
1495
-		$eventDispatcher->addServiceListener(UserChangedEvent::class, UserChangedListener::class);
1496
-		$eventDispatcher->addServiceListener(BeforeUserDeletedEvent::class, BeforeUserDeletedListener::class);
1497
-	}
1498
-
1499
-	/**
1500
-	 * @return \OCP\Contacts\IManager
1501
-	 * @deprecated 20.0.0
1502
-	 */
1503
-	public function getContactsManager() {
1504
-		return $this->get(\OCP\Contacts\IManager::class);
1505
-	}
1506
-
1507
-	/**
1508
-	 * @return \OC\Encryption\Manager
1509
-	 * @deprecated 20.0.0
1510
-	 */
1511
-	public function getEncryptionManager() {
1512
-		return $this->get(\OCP\Encryption\IManager::class);
1513
-	}
1514
-
1515
-	/**
1516
-	 * @return \OC\Encryption\File
1517
-	 * @deprecated 20.0.0
1518
-	 */
1519
-	public function getEncryptionFilesHelper() {
1520
-		return $this->get(IFile::class);
1521
-	}
1522
-
1523
-	/**
1524
-	 * @return \OCP\Encryption\Keys\IStorage
1525
-	 * @deprecated 20.0.0
1526
-	 */
1527
-	public function getEncryptionKeyStorage() {
1528
-		return $this->get(IStorage::class);
1529
-	}
1530
-
1531
-	/**
1532
-	 * The current request object holding all information about the request
1533
-	 * currently being processed is returned from this method.
1534
-	 * In case the current execution was not initiated by a web request null is returned
1535
-	 *
1536
-	 * @return \OCP\IRequest
1537
-	 * @deprecated 20.0.0
1538
-	 */
1539
-	public function getRequest() {
1540
-		return $this->get(IRequest::class);
1541
-	}
1542
-
1543
-	/**
1544
-	 * Returns the preview manager which can create preview images for a given file
1545
-	 *
1546
-	 * @return IPreview
1547
-	 * @deprecated 20.0.0
1548
-	 */
1549
-	public function getPreviewManager() {
1550
-		return $this->get(IPreview::class);
1551
-	}
1552
-
1553
-	/**
1554
-	 * Returns the tag manager which can get and set tags for different object types
1555
-	 *
1556
-	 * @see \OCP\ITagManager::load()
1557
-	 * @return ITagManager
1558
-	 * @deprecated 20.0.0
1559
-	 */
1560
-	public function getTagManager() {
1561
-		return $this->get(ITagManager::class);
1562
-	}
1563
-
1564
-	/**
1565
-	 * Returns the system-tag manager
1566
-	 *
1567
-	 * @return ISystemTagManager
1568
-	 *
1569
-	 * @since 9.0.0
1570
-	 * @deprecated 20.0.0
1571
-	 */
1572
-	public function getSystemTagManager() {
1573
-		return $this->get(ISystemTagManager::class);
1574
-	}
1575
-
1576
-	/**
1577
-	 * Returns the system-tag object mapper
1578
-	 *
1579
-	 * @return ISystemTagObjectMapper
1580
-	 *
1581
-	 * @since 9.0.0
1582
-	 * @deprecated 20.0.0
1583
-	 */
1584
-	public function getSystemTagObjectMapper() {
1585
-		return $this->get(ISystemTagObjectMapper::class);
1586
-	}
1587
-
1588
-	/**
1589
-	 * Returns the avatar manager, used for avatar functionality
1590
-	 *
1591
-	 * @return IAvatarManager
1592
-	 * @deprecated 20.0.0
1593
-	 */
1594
-	public function getAvatarManager() {
1595
-		return $this->get(IAvatarManager::class);
1596
-	}
1597
-
1598
-	/**
1599
-	 * Returns the root folder of ownCloud's data directory
1600
-	 *
1601
-	 * @return IRootFolder
1602
-	 * @deprecated 20.0.0
1603
-	 */
1604
-	public function getRootFolder() {
1605
-		return $this->get(IRootFolder::class);
1606
-	}
1607
-
1608
-	/**
1609
-	 * Returns the root folder of ownCloud's data directory
1610
-	 * This is the lazy variant so this gets only initialized once it
1611
-	 * is actually used.
1612
-	 *
1613
-	 * @return IRootFolder
1614
-	 * @deprecated 20.0.0
1615
-	 */
1616
-	public function getLazyRootFolder() {
1617
-		return $this->get(IRootFolder::class);
1618
-	}
1619
-
1620
-	/**
1621
-	 * Returns a view to ownCloud's files folder
1622
-	 *
1623
-	 * @param string $userId user ID
1624
-	 * @return \OCP\Files\Folder|null
1625
-	 * @deprecated 20.0.0
1626
-	 */
1627
-	public function getUserFolder($userId = null) {
1628
-		if ($userId === null) {
1629
-			$user = $this->get(IUserSession::class)->getUser();
1630
-			if (!$user) {
1631
-				return null;
1632
-			}
1633
-			$userId = $user->getUID();
1634
-		}
1635
-		$root = $this->get(IRootFolder::class);
1636
-		return $root->getUserFolder($userId);
1637
-	}
1638
-
1639
-	/**
1640
-	 * @return \OC\User\Manager
1641
-	 * @deprecated 20.0.0
1642
-	 */
1643
-	public function getUserManager() {
1644
-		return $this->get(IUserManager::class);
1645
-	}
1646
-
1647
-	/**
1648
-	 * @return \OC\Group\Manager
1649
-	 * @deprecated 20.0.0
1650
-	 */
1651
-	public function getGroupManager() {
1652
-		return $this->get(IGroupManager::class);
1653
-	}
1654
-
1655
-	/**
1656
-	 * @return \OC\User\Session
1657
-	 * @deprecated 20.0.0
1658
-	 */
1659
-	public function getUserSession() {
1660
-		return $this->get(IUserSession::class);
1661
-	}
1662
-
1663
-	/**
1664
-	 * @return \OCP\ISession
1665
-	 * @deprecated 20.0.0
1666
-	 */
1667
-	public function getSession() {
1668
-		return $this->get(Session::class)->getSession();
1669
-	}
1670
-
1671
-	/**
1672
-	 * @param \OCP\ISession $session
1673
-	 */
1674
-	public function setSession(\OCP\ISession $session) {
1675
-		$this->get(SessionStorage::class)->setSession($session);
1676
-		$this->get(Session::class)->setSession($session);
1677
-		$this->get(Store::class)->setSession($session);
1678
-	}
1679
-
1680
-	/**
1681
-	 * @return \OC\Authentication\TwoFactorAuth\Manager
1682
-	 * @deprecated 20.0.0
1683
-	 */
1684
-	public function getTwoFactorAuthManager() {
1685
-		return $this->get(\OC\Authentication\TwoFactorAuth\Manager::class);
1686
-	}
1687
-
1688
-	/**
1689
-	 * @return \OC\NavigationManager
1690
-	 * @deprecated 20.0.0
1691
-	 */
1692
-	public function getNavigationManager() {
1693
-		return $this->get(INavigationManager::class);
1694
-	}
1695
-
1696
-	/**
1697
-	 * @return \OCP\IConfig
1698
-	 * @deprecated 20.0.0
1699
-	 */
1700
-	public function getConfig() {
1701
-		return $this->get(AllConfig::class);
1702
-	}
1703
-
1704
-	/**
1705
-	 * @return \OC\SystemConfig
1706
-	 * @deprecated 20.0.0
1707
-	 */
1708
-	public function getSystemConfig() {
1709
-		return $this->get(SystemConfig::class);
1710
-	}
1711
-
1712
-	/**
1713
-	 * Returns the app config manager
1714
-	 *
1715
-	 * @return IAppConfig
1716
-	 * @deprecated 20.0.0
1717
-	 */
1718
-	public function getAppConfig() {
1719
-		return $this->get(IAppConfig::class);
1720
-	}
1721
-
1722
-	/**
1723
-	 * @return IFactory
1724
-	 * @deprecated 20.0.0
1725
-	 */
1726
-	public function getL10NFactory() {
1727
-		return $this->get(IFactory::class);
1728
-	}
1729
-
1730
-	/**
1731
-	 * get an L10N instance
1732
-	 *
1733
-	 * @param string $app appid
1734
-	 * @param string $lang
1735
-	 * @return IL10N
1736
-	 * @deprecated 20.0.0
1737
-	 */
1738
-	public function getL10N($app, $lang = null) {
1739
-		return $this->get(IFactory::class)->get($app, $lang);
1740
-	}
1741
-
1742
-	/**
1743
-	 * @return IURLGenerator
1744
-	 * @deprecated 20.0.0
1745
-	 */
1746
-	public function getURLGenerator() {
1747
-		return $this->get(IURLGenerator::class);
1748
-	}
1749
-
1750
-	/**
1751
-	 * @return AppFetcher
1752
-	 * @deprecated 20.0.0
1753
-	 */
1754
-	public function getAppFetcher() {
1755
-		return $this->get(AppFetcher::class);
1756
-	}
1757
-
1758
-	/**
1759
-	 * Returns an ICache instance. Since 8.1.0 it returns a fake cache. Use
1760
-	 * getMemCacheFactory() instead.
1761
-	 *
1762
-	 * @return ICache
1763
-	 * @deprecated 8.1.0 use getMemCacheFactory to obtain a proper cache
1764
-	 */
1765
-	public function getCache() {
1766
-		return $this->get(ICache::class);
1767
-	}
1768
-
1769
-	/**
1770
-	 * Returns an \OCP\CacheFactory instance
1771
-	 *
1772
-	 * @return \OCP\ICacheFactory
1773
-	 * @deprecated 20.0.0
1774
-	 */
1775
-	public function getMemCacheFactory() {
1776
-		return $this->get(ICacheFactory::class);
1777
-	}
1778
-
1779
-	/**
1780
-	 * Returns an \OC\RedisFactory instance
1781
-	 *
1782
-	 * @return \OC\RedisFactory
1783
-	 * @deprecated 20.0.0
1784
-	 */
1785
-	public function getGetRedisFactory() {
1786
-		return $this->get('RedisFactory');
1787
-	}
1788
-
1789
-
1790
-	/**
1791
-	 * Returns the current session
1792
-	 *
1793
-	 * @return \OCP\IDBConnection
1794
-	 * @deprecated 20.0.0
1795
-	 */
1796
-	public function getDatabaseConnection() {
1797
-		return $this->get(IDBConnection::class);
1798
-	}
1799
-
1800
-	/**
1801
-	 * Returns the activity manager
1802
-	 *
1803
-	 * @return \OCP\Activity\IManager
1804
-	 * @deprecated 20.0.0
1805
-	 */
1806
-	public function getActivityManager() {
1807
-		return $this->get(\OCP\Activity\IManager::class);
1808
-	}
1809
-
1810
-	/**
1811
-	 * Returns an job list for controlling background jobs
1812
-	 *
1813
-	 * @return IJobList
1814
-	 * @deprecated 20.0.0
1815
-	 */
1816
-	public function getJobList() {
1817
-		return $this->get(IJobList::class);
1818
-	}
1819
-
1820
-	/**
1821
-	 * Returns a logger instance
1822
-	 *
1823
-	 * @return ILogger
1824
-	 * @deprecated 20.0.0
1825
-	 */
1826
-	public function getLogger() {
1827
-		return $this->get(ILogger::class);
1828
-	}
1829
-
1830
-	/**
1831
-	 * @return ILogFactory
1832
-	 * @throws \OCP\AppFramework\QueryException
1833
-	 * @deprecated 20.0.0
1834
-	 */
1835
-	public function getLogFactory() {
1836
-		return $this->get(ILogFactory::class);
1837
-	}
1838
-
1839
-	/**
1840
-	 * Returns a router for generating and matching urls
1841
-	 *
1842
-	 * @return IRouter
1843
-	 * @deprecated 20.0.0
1844
-	 */
1845
-	public function getRouter() {
1846
-		return $this->get(IRouter::class);
1847
-	}
1848
-
1849
-	/**
1850
-	 * Returns a search instance
1851
-	 *
1852
-	 * @return ISearch
1853
-	 * @deprecated 20.0.0
1854
-	 */
1855
-	public function getSearch() {
1856
-		return $this->get(ISearch::class);
1857
-	}
1858
-
1859
-	/**
1860
-	 * Returns a SecureRandom instance
1861
-	 *
1862
-	 * @return \OCP\Security\ISecureRandom
1863
-	 * @deprecated 20.0.0
1864
-	 */
1865
-	public function getSecureRandom() {
1866
-		return $this->get(ISecureRandom::class);
1867
-	}
1868
-
1869
-	/**
1870
-	 * Returns a Crypto instance
1871
-	 *
1872
-	 * @return ICrypto
1873
-	 * @deprecated 20.0.0
1874
-	 */
1875
-	public function getCrypto() {
1876
-		return $this->get(ICrypto::class);
1877
-	}
1878
-
1879
-	/**
1880
-	 * Returns a Hasher instance
1881
-	 *
1882
-	 * @return IHasher
1883
-	 * @deprecated 20.0.0
1884
-	 */
1885
-	public function getHasher() {
1886
-		return $this->get(IHasher::class);
1887
-	}
1888
-
1889
-	/**
1890
-	 * Returns a CredentialsManager instance
1891
-	 *
1892
-	 * @return ICredentialsManager
1893
-	 * @deprecated 20.0.0
1894
-	 */
1895
-	public function getCredentialsManager() {
1896
-		return $this->get(ICredentialsManager::class);
1897
-	}
1898
-
1899
-	/**
1900
-	 * Get the certificate manager
1901
-	 *
1902
-	 * @return \OCP\ICertificateManager
1903
-	 */
1904
-	public function getCertificateManager() {
1905
-		return $this->get(ICertificateManager::class);
1906
-	}
1907
-
1908
-	/**
1909
-	 * Returns an instance of the HTTP client service
1910
-	 *
1911
-	 * @return IClientService
1912
-	 * @deprecated 20.0.0
1913
-	 */
1914
-	public function getHTTPClientService() {
1915
-		return $this->get(IClientService::class);
1916
-	}
1917
-
1918
-	/**
1919
-	 * Create a new event source
1920
-	 *
1921
-	 * @return \OCP\IEventSource
1922
-	 * @deprecated 20.0.0
1923
-	 */
1924
-	public function createEventSource() {
1925
-		return new \OC_EventSource();
1926
-	}
1927
-
1928
-	/**
1929
-	 * Get the active event logger
1930
-	 *
1931
-	 * The returned logger only logs data when debug mode is enabled
1932
-	 *
1933
-	 * @return IEventLogger
1934
-	 * @deprecated 20.0.0
1935
-	 */
1936
-	public function getEventLogger() {
1937
-		return $this->get(IEventLogger::class);
1938
-	}
1939
-
1940
-	/**
1941
-	 * Get the active query logger
1942
-	 *
1943
-	 * The returned logger only logs data when debug mode is enabled
1944
-	 *
1945
-	 * @return IQueryLogger
1946
-	 * @deprecated 20.0.0
1947
-	 */
1948
-	public function getQueryLogger() {
1949
-		return $this->get(IQueryLogger::class);
1950
-	}
1951
-
1952
-	/**
1953
-	 * Get the manager for temporary files and folders
1954
-	 *
1955
-	 * @return \OCP\ITempManager
1956
-	 * @deprecated 20.0.0
1957
-	 */
1958
-	public function getTempManager() {
1959
-		return $this->get(ITempManager::class);
1960
-	}
1961
-
1962
-	/**
1963
-	 * Get the app manager
1964
-	 *
1965
-	 * @return \OCP\App\IAppManager
1966
-	 * @deprecated 20.0.0
1967
-	 */
1968
-	public function getAppManager() {
1969
-		return $this->get(IAppManager::class);
1970
-	}
1971
-
1972
-	/**
1973
-	 * Creates a new mailer
1974
-	 *
1975
-	 * @return IMailer
1976
-	 * @deprecated 20.0.0
1977
-	 */
1978
-	public function getMailer() {
1979
-		return $this->get(IMailer::class);
1980
-	}
1981
-
1982
-	/**
1983
-	 * Get the webroot
1984
-	 *
1985
-	 * @return string
1986
-	 * @deprecated 20.0.0
1987
-	 */
1988
-	public function getWebRoot() {
1989
-		return $this->webRoot;
1990
-	}
1991
-
1992
-	/**
1993
-	 * @return \OC\OCSClient
1994
-	 * @deprecated 20.0.0
1995
-	 */
1996
-	public function getOcsClient() {
1997
-		return $this->get('OcsClient');
1998
-	}
1999
-
2000
-	/**
2001
-	 * @return IDateTimeZone
2002
-	 * @deprecated 20.0.0
2003
-	 */
2004
-	public function getDateTimeZone() {
2005
-		return $this->get(IDateTimeZone::class);
2006
-	}
2007
-
2008
-	/**
2009
-	 * @return IDateTimeFormatter
2010
-	 * @deprecated 20.0.0
2011
-	 */
2012
-	public function getDateTimeFormatter() {
2013
-		return $this->get(IDateTimeFormatter::class);
2014
-	}
2015
-
2016
-	/**
2017
-	 * @return IMountProviderCollection
2018
-	 * @deprecated 20.0.0
2019
-	 */
2020
-	public function getMountProviderCollection() {
2021
-		return $this->get(IMountProviderCollection::class);
2022
-	}
2023
-
2024
-	/**
2025
-	 * Get the IniWrapper
2026
-	 *
2027
-	 * @return IniGetWrapper
2028
-	 * @deprecated 20.0.0
2029
-	 */
2030
-	public function getIniWrapper() {
2031
-		return $this->get(IniGetWrapper::class);
2032
-	}
2033
-
2034
-	/**
2035
-	 * @return \OCP\Command\IBus
2036
-	 * @deprecated 20.0.0
2037
-	 */
2038
-	public function getCommandBus() {
2039
-		return $this->get(IBus::class);
2040
-	}
2041
-
2042
-	/**
2043
-	 * Get the trusted domain helper
2044
-	 *
2045
-	 * @return TrustedDomainHelper
2046
-	 * @deprecated 20.0.0
2047
-	 */
2048
-	public function getTrustedDomainHelper() {
2049
-		return $this->get(TrustedDomainHelper::class);
2050
-	}
2051
-
2052
-	/**
2053
-	 * Get the locking provider
2054
-	 *
2055
-	 * @return ILockingProvider
2056
-	 * @since 8.1.0
2057
-	 * @deprecated 20.0.0
2058
-	 */
2059
-	public function getLockingProvider() {
2060
-		return $this->get(ILockingProvider::class);
2061
-	}
2062
-
2063
-	/**
2064
-	 * @return IMountManager
2065
-	 * @deprecated 20.0.0
2066
-	 **/
2067
-	public function getMountManager() {
2068
-		return $this->get(IMountManager::class);
2069
-	}
2070
-
2071
-	/**
2072
-	 * @return IUserMountCache
2073
-	 * @deprecated 20.0.0
2074
-	 */
2075
-	public function getUserMountCache() {
2076
-		return $this->get(IUserMountCache::class);
2077
-	}
2078
-
2079
-	/**
2080
-	 * Get the MimeTypeDetector
2081
-	 *
2082
-	 * @return IMimeTypeDetector
2083
-	 * @deprecated 20.0.0
2084
-	 */
2085
-	public function getMimeTypeDetector() {
2086
-		return $this->get(IMimeTypeDetector::class);
2087
-	}
2088
-
2089
-	/**
2090
-	 * Get the MimeTypeLoader
2091
-	 *
2092
-	 * @return IMimeTypeLoader
2093
-	 * @deprecated 20.0.0
2094
-	 */
2095
-	public function getMimeTypeLoader() {
2096
-		return $this->get(IMimeTypeLoader::class);
2097
-	}
2098
-
2099
-	/**
2100
-	 * Get the manager of all the capabilities
2101
-	 *
2102
-	 * @return CapabilitiesManager
2103
-	 * @deprecated 20.0.0
2104
-	 */
2105
-	public function getCapabilitiesManager() {
2106
-		return $this->get(CapabilitiesManager::class);
2107
-	}
2108
-
2109
-	/**
2110
-	 * Get the EventDispatcher
2111
-	 *
2112
-	 * @return EventDispatcherInterface
2113
-	 * @since 8.2.0
2114
-	 * @deprecated 18.0.0 use \OCP\EventDispatcher\IEventDispatcher
2115
-	 */
2116
-	public function getEventDispatcher() {
2117
-		return $this->get(\OC\EventDispatcher\SymfonyAdapter::class);
2118
-	}
2119
-
2120
-	/**
2121
-	 * Get the Notification Manager
2122
-	 *
2123
-	 * @return \OCP\Notification\IManager
2124
-	 * @since 8.2.0
2125
-	 * @deprecated 20.0.0
2126
-	 */
2127
-	public function getNotificationManager() {
2128
-		return $this->get(\OCP\Notification\IManager::class);
2129
-	}
2130
-
2131
-	/**
2132
-	 * @return ICommentsManager
2133
-	 * @deprecated 20.0.0
2134
-	 */
2135
-	public function getCommentsManager() {
2136
-		return $this->get(ICommentsManager::class);
2137
-	}
2138
-
2139
-	/**
2140
-	 * @return \OCA\Theming\ThemingDefaults
2141
-	 * @deprecated 20.0.0
2142
-	 */
2143
-	public function getThemingDefaults() {
2144
-		return $this->get('ThemingDefaults');
2145
-	}
2146
-
2147
-	/**
2148
-	 * @return \OC\IntegrityCheck\Checker
2149
-	 * @deprecated 20.0.0
2150
-	 */
2151
-	public function getIntegrityCodeChecker() {
2152
-		return $this->get('IntegrityCodeChecker');
2153
-	}
2154
-
2155
-	/**
2156
-	 * @return \OC\Session\CryptoWrapper
2157
-	 * @deprecated 20.0.0
2158
-	 */
2159
-	public function getSessionCryptoWrapper() {
2160
-		return $this->get('CryptoWrapper');
2161
-	}
2162
-
2163
-	/**
2164
-	 * @return CsrfTokenManager
2165
-	 * @deprecated 20.0.0
2166
-	 */
2167
-	public function getCsrfTokenManager() {
2168
-		return $this->get(CsrfTokenManager::class);
2169
-	}
2170
-
2171
-	/**
2172
-	 * @return Throttler
2173
-	 * @deprecated 20.0.0
2174
-	 */
2175
-	public function getBruteForceThrottler() {
2176
-		return $this->get(Throttler::class);
2177
-	}
2178
-
2179
-	/**
2180
-	 * @return IContentSecurityPolicyManager
2181
-	 * @deprecated 20.0.0
2182
-	 */
2183
-	public function getContentSecurityPolicyManager() {
2184
-		return $this->get(ContentSecurityPolicyManager::class);
2185
-	}
2186
-
2187
-	/**
2188
-	 * @return ContentSecurityPolicyNonceManager
2189
-	 * @deprecated 20.0.0
2190
-	 */
2191
-	public function getContentSecurityPolicyNonceManager() {
2192
-		return $this->get(ContentSecurityPolicyNonceManager::class);
2193
-	}
2194
-
2195
-	/**
2196
-	 * Not a public API as of 8.2, wait for 9.0
2197
-	 *
2198
-	 * @return \OCA\Files_External\Service\BackendService
2199
-	 * @deprecated 20.0.0
2200
-	 */
2201
-	public function getStoragesBackendService() {
2202
-		return $this->get(BackendService::class);
2203
-	}
2204
-
2205
-	/**
2206
-	 * Not a public API as of 8.2, wait for 9.0
2207
-	 *
2208
-	 * @return \OCA\Files_External\Service\GlobalStoragesService
2209
-	 * @deprecated 20.0.0
2210
-	 */
2211
-	public function getGlobalStoragesService() {
2212
-		return $this->get(GlobalStoragesService::class);
2213
-	}
2214
-
2215
-	/**
2216
-	 * Not a public API as of 8.2, wait for 9.0
2217
-	 *
2218
-	 * @return \OCA\Files_External\Service\UserGlobalStoragesService
2219
-	 * @deprecated 20.0.0
2220
-	 */
2221
-	public function getUserGlobalStoragesService() {
2222
-		return $this->get(UserGlobalStoragesService::class);
2223
-	}
2224
-
2225
-	/**
2226
-	 * Not a public API as of 8.2, wait for 9.0
2227
-	 *
2228
-	 * @return \OCA\Files_External\Service\UserStoragesService
2229
-	 * @deprecated 20.0.0
2230
-	 */
2231
-	public function getUserStoragesService() {
2232
-		return $this->get(UserStoragesService::class);
2233
-	}
2234
-
2235
-	/**
2236
-	 * @return \OCP\Share\IManager
2237
-	 * @deprecated 20.0.0
2238
-	 */
2239
-	public function getShareManager() {
2240
-		return $this->get(\OCP\Share\IManager::class);
2241
-	}
2242
-
2243
-	/**
2244
-	 * @return \OCP\Collaboration\Collaborators\ISearch
2245
-	 * @deprecated 20.0.0
2246
-	 */
2247
-	public function getCollaboratorSearch() {
2248
-		return $this->get(\OCP\Collaboration\Collaborators\ISearch::class);
2249
-	}
2250
-
2251
-	/**
2252
-	 * @return \OCP\Collaboration\AutoComplete\IManager
2253
-	 * @deprecated 20.0.0
2254
-	 */
2255
-	public function getAutoCompleteManager() {
2256
-		return $this->get(IManager::class);
2257
-	}
2258
-
2259
-	/**
2260
-	 * Returns the LDAP Provider
2261
-	 *
2262
-	 * @return \OCP\LDAP\ILDAPProvider
2263
-	 * @deprecated 20.0.0
2264
-	 */
2265
-	public function getLDAPProvider() {
2266
-		return $this->get('LDAPProvider');
2267
-	}
2268
-
2269
-	/**
2270
-	 * @return \OCP\Settings\IManager
2271
-	 * @deprecated 20.0.0
2272
-	 */
2273
-	public function getSettingsManager() {
2274
-		return $this->get(\OC\Settings\Manager::class);
2275
-	}
2276
-
2277
-	/**
2278
-	 * @return \OCP\Files\IAppData
2279
-	 * @deprecated 20.0.0 Use get(\OCP\Files\AppData\IAppDataFactory::class)->get($app) instead
2280
-	 */
2281
-	public function getAppDataDir($app) {
2282
-		/** @var \OC\Files\AppData\Factory $factory */
2283
-		$factory = $this->get(\OC\Files\AppData\Factory::class);
2284
-		return $factory->get($app);
2285
-	}
2286
-
2287
-	/**
2288
-	 * @return \OCP\Lockdown\ILockdownManager
2289
-	 * @deprecated 20.0.0
2290
-	 */
2291
-	public function getLockdownManager() {
2292
-		return $this->get('LockdownManager');
2293
-	}
2294
-
2295
-	/**
2296
-	 * @return \OCP\Federation\ICloudIdManager
2297
-	 * @deprecated 20.0.0
2298
-	 */
2299
-	public function getCloudIdManager() {
2300
-		return $this->get(ICloudIdManager::class);
2301
-	}
2302
-
2303
-	/**
2304
-	 * @return \OCP\GlobalScale\IConfig
2305
-	 * @deprecated 20.0.0
2306
-	 */
2307
-	public function getGlobalScaleConfig() {
2308
-		return $this->get(IConfig::class);
2309
-	}
2310
-
2311
-	/**
2312
-	 * @return \OCP\Federation\ICloudFederationProviderManager
2313
-	 * @deprecated 20.0.0
2314
-	 */
2315
-	public function getCloudFederationProviderManager() {
2316
-		return $this->get(ICloudFederationProviderManager::class);
2317
-	}
2318
-
2319
-	/**
2320
-	 * @return \OCP\Remote\Api\IApiFactory
2321
-	 * @deprecated 20.0.0
2322
-	 */
2323
-	public function getRemoteApiFactory() {
2324
-		return $this->get(IApiFactory::class);
2325
-	}
2326
-
2327
-	/**
2328
-	 * @return \OCP\Federation\ICloudFederationFactory
2329
-	 * @deprecated 20.0.0
2330
-	 */
2331
-	public function getCloudFederationFactory() {
2332
-		return $this->get(ICloudFederationFactory::class);
2333
-	}
2334
-
2335
-	/**
2336
-	 * @return \OCP\Remote\IInstanceFactory
2337
-	 * @deprecated 20.0.0
2338
-	 */
2339
-	public function getRemoteInstanceFactory() {
2340
-		return $this->get(IInstanceFactory::class);
2341
-	}
2342
-
2343
-	/**
2344
-	 * @return IStorageFactory
2345
-	 * @deprecated 20.0.0
2346
-	 */
2347
-	public function getStorageFactory() {
2348
-		return $this->get(IStorageFactory::class);
2349
-	}
2350
-
2351
-	/**
2352
-	 * Get the Preview GeneratorHelper
2353
-	 *
2354
-	 * @return GeneratorHelper
2355
-	 * @since 17.0.0
2356
-	 * @deprecated 20.0.0
2357
-	 */
2358
-	public function getGeneratorHelper() {
2359
-		return $this->get(\OC\Preview\GeneratorHelper::class);
2360
-	}
2361
-
2362
-	private function registerDeprecatedAlias(string $alias, string $target) {
2363
-		$this->registerService($alias, function (ContainerInterface $container) use ($target, $alias) {
2364
-			try {
2365
-				/** @var LoggerInterface $logger */
2366
-				$logger = $container->get(LoggerInterface::class);
2367
-				$logger->debug('The requested alias "' . $alias . '" is deprecated. Please request "' . $target . '" directly. This alias will be removed in a future Nextcloud version.', ['app' => 'serverDI']);
2368
-			} catch (ContainerExceptionInterface $e) {
2369
-				// Could not get logger. Continue
2370
-			}
2371
-
2372
-			return $container->get($target);
2373
-		}, false);
2374
-	}
1206
+            $prefixes = \OC::$composerAutoloader->getPrefixesPsr4();
1207
+            if (isset($prefixes['OCA\\Theming\\'])) {
1208
+                $classExists = true;
1209
+            } else {
1210
+                $classExists = false;
1211
+            }
1212
+
1213
+            if ($classExists && $c->get(\OCP\IConfig::class)->getSystemValue('installed', false) && $c->get(IAppManager::class)->isInstalled('theming') && $c->getTrustedDomainHelper()->isTrustedDomain($c->getRequest()->getInsecureServerHost())) {
1214
+                $imageManager = new ImageManager(
1215
+                    $c->get(\OCP\IConfig::class),
1216
+                    $c->getAppDataDir('theming'),
1217
+                    $c->get(IURLGenerator::class),
1218
+                    $this->get(ICacheFactory::class),
1219
+                    $this->get(ILogger::class),
1220
+                    $this->get(ITempManager::class)
1221
+                );
1222
+                return new ThemingDefaults(
1223
+                    $c->get(\OCP\IConfig::class),
1224
+                    $c->getL10N('theming'),
1225
+                    $c->get(IUserSession::class),
1226
+                    $c->get(IURLGenerator::class),
1227
+                    $c->get(ICacheFactory::class),
1228
+                    new Util($c->get(\OCP\IConfig::class), $this->get(IAppManager::class), $c->getAppDataDir('theming'), $imageManager),
1229
+                    $imageManager,
1230
+                    $c->get(IAppManager::class),
1231
+                    $c->get(INavigationManager::class)
1232
+                );
1233
+            }
1234
+            return new \OC_Defaults();
1235
+        });
1236
+        $this->registerService(JSCombiner::class, function (Server $c) {
1237
+            return new JSCombiner(
1238
+                $c->getAppDataDir('js'),
1239
+                $c->get(IURLGenerator::class),
1240
+                $this->get(ICacheFactory::class),
1241
+                $c->get(SystemConfig::class),
1242
+                $c->get(LoggerInterface::class)
1243
+            );
1244
+        });
1245
+        $this->registerAlias(\OCP\EventDispatcher\IEventDispatcher::class, \OC\EventDispatcher\EventDispatcher::class);
1246
+        /** @deprecated 19.0.0 */
1247
+        $this->registerDeprecatedAlias('EventDispatcher', \OC\EventDispatcher\SymfonyAdapter::class);
1248
+        $this->registerAlias(EventDispatcherInterface::class, \OC\EventDispatcher\SymfonyAdapter::class);
1249
+
1250
+        $this->registerService('CryptoWrapper', function (ContainerInterface $c) {
1251
+            // FIXME: Instantiated here due to cyclic dependency
1252
+            $request = new Request(
1253
+                [
1254
+                    'get' => $_GET,
1255
+                    'post' => $_POST,
1256
+                    'files' => $_FILES,
1257
+                    'server' => $_SERVER,
1258
+                    'env' => $_ENV,
1259
+                    'cookies' => $_COOKIE,
1260
+                    'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
1261
+                        ? $_SERVER['REQUEST_METHOD']
1262
+                        : null,
1263
+                ],
1264
+                $c->get(IRequestId::class),
1265
+                $c->get(\OCP\IConfig::class)
1266
+            );
1267
+
1268
+            return new CryptoWrapper(
1269
+                $c->get(\OCP\IConfig::class),
1270
+                $c->get(ICrypto::class),
1271
+                $c->get(ISecureRandom::class),
1272
+                $request
1273
+            );
1274
+        });
1275
+        /** @deprecated 19.0.0 */
1276
+        $this->registerDeprecatedAlias('CsrfTokenManager', CsrfTokenManager::class);
1277
+        $this->registerService(SessionStorage::class, function (ContainerInterface $c) {
1278
+            return new SessionStorage($c->get(ISession::class));
1279
+        });
1280
+        $this->registerAlias(\OCP\Security\IContentSecurityPolicyManager::class, ContentSecurityPolicyManager::class);
1281
+        /** @deprecated 19.0.0 */
1282
+        $this->registerDeprecatedAlias('ContentSecurityPolicyManager', ContentSecurityPolicyManager::class);
1283
+
1284
+        $this->registerService(\OCP\Share\IManager::class, function (IServerContainer $c) {
1285
+            $config = $c->get(\OCP\IConfig::class);
1286
+            $factoryClass = $config->getSystemValue('sharing.managerFactory', ProviderFactory::class);
1287
+            /** @var \OCP\Share\IProviderFactory $factory */
1288
+            $factory = new $factoryClass($this);
1289
+
1290
+            $manager = new \OC\Share20\Manager(
1291
+                $c->get(LoggerInterface::class),
1292
+                $c->get(\OCP\IConfig::class),
1293
+                $c->get(ISecureRandom::class),
1294
+                $c->get(IHasher::class),
1295
+                $c->get(IMountManager::class),
1296
+                $c->get(IGroupManager::class),
1297
+                $c->getL10N('lib'),
1298
+                $c->get(IFactory::class),
1299
+                $factory,
1300
+                $c->get(IUserManager::class),
1301
+                $c->get(IRootFolder::class),
1302
+                $c->get(SymfonyAdapter::class),
1303
+                $c->get(IMailer::class),
1304
+                $c->get(IURLGenerator::class),
1305
+                $c->get('ThemingDefaults'),
1306
+                $c->get(IEventDispatcher::class),
1307
+                $c->get(IUserSession::class),
1308
+                $c->get(KnownUserService::class)
1309
+            );
1310
+
1311
+            return $manager;
1312
+        });
1313
+        /** @deprecated 19.0.0 */
1314
+        $this->registerDeprecatedAlias('ShareManager', \OCP\Share\IManager::class);
1315
+
1316
+        $this->registerService(\OCP\Collaboration\Collaborators\ISearch::class, function (Server $c) {
1317
+            $instance = new Collaboration\Collaborators\Search($c);
1318
+
1319
+            // register default plugins
1320
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_USER', 'class' => UserPlugin::class]);
1321
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_GROUP', 'class' => GroupPlugin::class]);
1322
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_EMAIL', 'class' => MailPlugin::class]);
1323
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_REMOTE', 'class' => RemotePlugin::class]);
1324
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_REMOTE_GROUP', 'class' => RemoteGroupPlugin::class]);
1325
+
1326
+            return $instance;
1327
+        });
1328
+        /** @deprecated 19.0.0 */
1329
+        $this->registerDeprecatedAlias('CollaboratorSearch', \OCP\Collaboration\Collaborators\ISearch::class);
1330
+        $this->registerAlias(\OCP\Collaboration\Collaborators\ISearchResult::class, \OC\Collaboration\Collaborators\SearchResult::class);
1331
+
1332
+        $this->registerAlias(\OCP\Collaboration\AutoComplete\IManager::class, \OC\Collaboration\AutoComplete\Manager::class);
1333
+
1334
+        $this->registerAlias(\OCP\Collaboration\Resources\IProviderManager::class, \OC\Collaboration\Resources\ProviderManager::class);
1335
+        $this->registerAlias(\OCP\Collaboration\Resources\IManager::class, \OC\Collaboration\Resources\Manager::class);
1336
+
1337
+        $this->registerAlias(IReferenceManager::class, ReferenceManager::class);
1338
+
1339
+        $this->registerDeprecatedAlias('SettingsManager', \OC\Settings\Manager::class);
1340
+        $this->registerAlias(\OCP\Settings\IManager::class, \OC\Settings\Manager::class);
1341
+        $this->registerService(\OC\Files\AppData\Factory::class, function (ContainerInterface $c) {
1342
+            return new \OC\Files\AppData\Factory(
1343
+                $c->get(IRootFolder::class),
1344
+                $c->get(SystemConfig::class)
1345
+            );
1346
+        });
1347
+
1348
+        $this->registerService('LockdownManager', function (ContainerInterface $c) {
1349
+            return new LockdownManager(function () use ($c) {
1350
+                return $c->get(ISession::class);
1351
+            });
1352
+        });
1353
+
1354
+        $this->registerService(\OCP\OCS\IDiscoveryService::class, function (ContainerInterface $c) {
1355
+            return new DiscoveryService(
1356
+                $c->get(ICacheFactory::class),
1357
+                $c->get(IClientService::class)
1358
+            );
1359
+        });
1360
+
1361
+        $this->registerService(ICloudIdManager::class, function (ContainerInterface $c) {
1362
+            return new CloudIdManager(
1363
+                $c->get(\OCP\Contacts\IManager::class),
1364
+                $c->get(IURLGenerator::class),
1365
+                $c->get(IUserManager::class),
1366
+                $c->get(ICacheFactory::class),
1367
+                $c->get(IEventDispatcher::class),
1368
+            );
1369
+        });
1370
+
1371
+        $this->registerAlias(\OCP\GlobalScale\IConfig::class, \OC\GlobalScale\Config::class);
1372
+
1373
+        $this->registerService(ICloudFederationProviderManager::class, function (ContainerInterface $c) {
1374
+            return new CloudFederationProviderManager(
1375
+                $c->get(IAppManager::class),
1376
+                $c->get(IClientService::class),
1377
+                $c->get(ICloudIdManager::class),
1378
+                $c->get(LoggerInterface::class)
1379
+            );
1380
+        });
1381
+
1382
+        $this->registerService(ICloudFederationFactory::class, function (Server $c) {
1383
+            return new CloudFederationFactory();
1384
+        });
1385
+
1386
+        $this->registerAlias(\OCP\AppFramework\Utility\IControllerMethodReflector::class, \OC\AppFramework\Utility\ControllerMethodReflector::class);
1387
+        /** @deprecated 19.0.0 */
1388
+        $this->registerDeprecatedAlias('ControllerMethodReflector', \OCP\AppFramework\Utility\IControllerMethodReflector::class);
1389
+
1390
+        $this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
1391
+        /** @deprecated 19.0.0 */
1392
+        $this->registerDeprecatedAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
1393
+
1394
+        $this->registerService(Defaults::class, function (Server $c) {
1395
+            return new Defaults(
1396
+                $c->getThemingDefaults()
1397
+            );
1398
+        });
1399
+        /** @deprecated 19.0.0 */
1400
+        $this->registerDeprecatedAlias('Defaults', \OCP\Defaults::class);
1401
+
1402
+        $this->registerService(\OCP\ISession::class, function (ContainerInterface $c) {
1403
+            return $c->get(\OCP\IUserSession::class)->getSession();
1404
+        }, false);
1405
+
1406
+        $this->registerService(IShareHelper::class, function (ContainerInterface $c) {
1407
+            return new ShareHelper(
1408
+                $c->get(\OCP\Share\IManager::class)
1409
+            );
1410
+        });
1411
+
1412
+        $this->registerService(Installer::class, function (ContainerInterface $c) {
1413
+            return new Installer(
1414
+                $c->get(AppFetcher::class),
1415
+                $c->get(IClientService::class),
1416
+                $c->get(ITempManager::class),
1417
+                $c->get(LoggerInterface::class),
1418
+                $c->get(\OCP\IConfig::class),
1419
+                \OC::$CLI
1420
+            );
1421
+        });
1422
+
1423
+        $this->registerService(IApiFactory::class, function (ContainerInterface $c) {
1424
+            return new ApiFactory($c->get(IClientService::class));
1425
+        });
1426
+
1427
+        $this->registerService(IInstanceFactory::class, function (ContainerInterface $c) {
1428
+            $memcacheFactory = $c->get(ICacheFactory::class);
1429
+            return new InstanceFactory($memcacheFactory->createLocal('remoteinstance.'), $c->get(IClientService::class));
1430
+        });
1431
+
1432
+        $this->registerAlias(IContactsStore::class, ContactsStore::class);
1433
+        $this->registerAlias(IAccountManager::class, AccountManager::class);
1434
+
1435
+        $this->registerAlias(IStorageFactory::class, StorageFactory::class);
1436
+
1437
+        $this->registerAlias(IDashboardManager::class, DashboardManager::class);
1438
+        $this->registerAlias(\OCP\Dashboard\IManager::class, \OC\Dashboard\Manager::class);
1439
+        $this->registerAlias(IFullTextSearchManager::class, FullTextSearchManager::class);
1440
+
1441
+        $this->registerAlias(ISubAdmin::class, SubAdmin::class);
1442
+
1443
+        $this->registerAlias(IInitialStateService::class, InitialStateService::class);
1444
+
1445
+        $this->registerAlias(\OCP\IEmojiHelper::class, \OC\EmojiHelper::class);
1446
+
1447
+        $this->registerAlias(\OCP\UserStatus\IManager::class, \OC\UserStatus\Manager::class);
1448
+
1449
+        $this->registerAlias(IBroker::class, Broker::class);
1450
+
1451
+        $this->registerAlias(IMetadataManager::class, MetadataManager::class);
1452
+
1453
+        $this->registerAlias(\OCP\Files\AppData\IAppDataFactory::class, \OC\Files\AppData\Factory::class);
1454
+
1455
+        $this->registerAlias(IBinaryFinder::class, BinaryFinder::class);
1456
+
1457
+        $this->connectDispatcher();
1458
+    }
1459
+
1460
+    public function boot() {
1461
+        /** @var HookConnector $hookConnector */
1462
+        $hookConnector = $this->get(HookConnector::class);
1463
+        $hookConnector->viewToNode();
1464
+    }
1465
+
1466
+    /**
1467
+     * @return \OCP\Calendar\IManager
1468
+     * @deprecated 20.0.0
1469
+     */
1470
+    public function getCalendarManager() {
1471
+        return $this->get(\OC\Calendar\Manager::class);
1472
+    }
1473
+
1474
+    /**
1475
+     * @return \OCP\Calendar\Resource\IManager
1476
+     * @deprecated 20.0.0
1477
+     */
1478
+    public function getCalendarResourceBackendManager() {
1479
+        return $this->get(\OC\Calendar\Resource\Manager::class);
1480
+    }
1481
+
1482
+    /**
1483
+     * @return \OCP\Calendar\Room\IManager
1484
+     * @deprecated 20.0.0
1485
+     */
1486
+    public function getCalendarRoomBackendManager() {
1487
+        return $this->get(\OC\Calendar\Room\Manager::class);
1488
+    }
1489
+
1490
+    private function connectDispatcher(): void {
1491
+        /** @var IEventDispatcher $eventDispatcher */
1492
+        $eventDispatcher = $this->get(IEventDispatcher::class);
1493
+        $eventDispatcher->addServiceListener(LoginFailed::class, LoginFailedListener::class);
1494
+        $eventDispatcher->addServiceListener(PostLoginEvent::class, UserLoggedInListener::class);
1495
+        $eventDispatcher->addServiceListener(UserChangedEvent::class, UserChangedListener::class);
1496
+        $eventDispatcher->addServiceListener(BeforeUserDeletedEvent::class, BeforeUserDeletedListener::class);
1497
+    }
1498
+
1499
+    /**
1500
+     * @return \OCP\Contacts\IManager
1501
+     * @deprecated 20.0.0
1502
+     */
1503
+    public function getContactsManager() {
1504
+        return $this->get(\OCP\Contacts\IManager::class);
1505
+    }
1506
+
1507
+    /**
1508
+     * @return \OC\Encryption\Manager
1509
+     * @deprecated 20.0.0
1510
+     */
1511
+    public function getEncryptionManager() {
1512
+        return $this->get(\OCP\Encryption\IManager::class);
1513
+    }
1514
+
1515
+    /**
1516
+     * @return \OC\Encryption\File
1517
+     * @deprecated 20.0.0
1518
+     */
1519
+    public function getEncryptionFilesHelper() {
1520
+        return $this->get(IFile::class);
1521
+    }
1522
+
1523
+    /**
1524
+     * @return \OCP\Encryption\Keys\IStorage
1525
+     * @deprecated 20.0.0
1526
+     */
1527
+    public function getEncryptionKeyStorage() {
1528
+        return $this->get(IStorage::class);
1529
+    }
1530
+
1531
+    /**
1532
+     * The current request object holding all information about the request
1533
+     * currently being processed is returned from this method.
1534
+     * In case the current execution was not initiated by a web request null is returned
1535
+     *
1536
+     * @return \OCP\IRequest
1537
+     * @deprecated 20.0.0
1538
+     */
1539
+    public function getRequest() {
1540
+        return $this->get(IRequest::class);
1541
+    }
1542
+
1543
+    /**
1544
+     * Returns the preview manager which can create preview images for a given file
1545
+     *
1546
+     * @return IPreview
1547
+     * @deprecated 20.0.0
1548
+     */
1549
+    public function getPreviewManager() {
1550
+        return $this->get(IPreview::class);
1551
+    }
1552
+
1553
+    /**
1554
+     * Returns the tag manager which can get and set tags for different object types
1555
+     *
1556
+     * @see \OCP\ITagManager::load()
1557
+     * @return ITagManager
1558
+     * @deprecated 20.0.0
1559
+     */
1560
+    public function getTagManager() {
1561
+        return $this->get(ITagManager::class);
1562
+    }
1563
+
1564
+    /**
1565
+     * Returns the system-tag manager
1566
+     *
1567
+     * @return ISystemTagManager
1568
+     *
1569
+     * @since 9.0.0
1570
+     * @deprecated 20.0.0
1571
+     */
1572
+    public function getSystemTagManager() {
1573
+        return $this->get(ISystemTagManager::class);
1574
+    }
1575
+
1576
+    /**
1577
+     * Returns the system-tag object mapper
1578
+     *
1579
+     * @return ISystemTagObjectMapper
1580
+     *
1581
+     * @since 9.0.0
1582
+     * @deprecated 20.0.0
1583
+     */
1584
+    public function getSystemTagObjectMapper() {
1585
+        return $this->get(ISystemTagObjectMapper::class);
1586
+    }
1587
+
1588
+    /**
1589
+     * Returns the avatar manager, used for avatar functionality
1590
+     *
1591
+     * @return IAvatarManager
1592
+     * @deprecated 20.0.0
1593
+     */
1594
+    public function getAvatarManager() {
1595
+        return $this->get(IAvatarManager::class);
1596
+    }
1597
+
1598
+    /**
1599
+     * Returns the root folder of ownCloud's data directory
1600
+     *
1601
+     * @return IRootFolder
1602
+     * @deprecated 20.0.0
1603
+     */
1604
+    public function getRootFolder() {
1605
+        return $this->get(IRootFolder::class);
1606
+    }
1607
+
1608
+    /**
1609
+     * Returns the root folder of ownCloud's data directory
1610
+     * This is the lazy variant so this gets only initialized once it
1611
+     * is actually used.
1612
+     *
1613
+     * @return IRootFolder
1614
+     * @deprecated 20.0.0
1615
+     */
1616
+    public function getLazyRootFolder() {
1617
+        return $this->get(IRootFolder::class);
1618
+    }
1619
+
1620
+    /**
1621
+     * Returns a view to ownCloud's files folder
1622
+     *
1623
+     * @param string $userId user ID
1624
+     * @return \OCP\Files\Folder|null
1625
+     * @deprecated 20.0.0
1626
+     */
1627
+    public function getUserFolder($userId = null) {
1628
+        if ($userId === null) {
1629
+            $user = $this->get(IUserSession::class)->getUser();
1630
+            if (!$user) {
1631
+                return null;
1632
+            }
1633
+            $userId = $user->getUID();
1634
+        }
1635
+        $root = $this->get(IRootFolder::class);
1636
+        return $root->getUserFolder($userId);
1637
+    }
1638
+
1639
+    /**
1640
+     * @return \OC\User\Manager
1641
+     * @deprecated 20.0.0
1642
+     */
1643
+    public function getUserManager() {
1644
+        return $this->get(IUserManager::class);
1645
+    }
1646
+
1647
+    /**
1648
+     * @return \OC\Group\Manager
1649
+     * @deprecated 20.0.0
1650
+     */
1651
+    public function getGroupManager() {
1652
+        return $this->get(IGroupManager::class);
1653
+    }
1654
+
1655
+    /**
1656
+     * @return \OC\User\Session
1657
+     * @deprecated 20.0.0
1658
+     */
1659
+    public function getUserSession() {
1660
+        return $this->get(IUserSession::class);
1661
+    }
1662
+
1663
+    /**
1664
+     * @return \OCP\ISession
1665
+     * @deprecated 20.0.0
1666
+     */
1667
+    public function getSession() {
1668
+        return $this->get(Session::class)->getSession();
1669
+    }
1670
+
1671
+    /**
1672
+     * @param \OCP\ISession $session
1673
+     */
1674
+    public function setSession(\OCP\ISession $session) {
1675
+        $this->get(SessionStorage::class)->setSession($session);
1676
+        $this->get(Session::class)->setSession($session);
1677
+        $this->get(Store::class)->setSession($session);
1678
+    }
1679
+
1680
+    /**
1681
+     * @return \OC\Authentication\TwoFactorAuth\Manager
1682
+     * @deprecated 20.0.0
1683
+     */
1684
+    public function getTwoFactorAuthManager() {
1685
+        return $this->get(\OC\Authentication\TwoFactorAuth\Manager::class);
1686
+    }
1687
+
1688
+    /**
1689
+     * @return \OC\NavigationManager
1690
+     * @deprecated 20.0.0
1691
+     */
1692
+    public function getNavigationManager() {
1693
+        return $this->get(INavigationManager::class);
1694
+    }
1695
+
1696
+    /**
1697
+     * @return \OCP\IConfig
1698
+     * @deprecated 20.0.0
1699
+     */
1700
+    public function getConfig() {
1701
+        return $this->get(AllConfig::class);
1702
+    }
1703
+
1704
+    /**
1705
+     * @return \OC\SystemConfig
1706
+     * @deprecated 20.0.0
1707
+     */
1708
+    public function getSystemConfig() {
1709
+        return $this->get(SystemConfig::class);
1710
+    }
1711
+
1712
+    /**
1713
+     * Returns the app config manager
1714
+     *
1715
+     * @return IAppConfig
1716
+     * @deprecated 20.0.0
1717
+     */
1718
+    public function getAppConfig() {
1719
+        return $this->get(IAppConfig::class);
1720
+    }
1721
+
1722
+    /**
1723
+     * @return IFactory
1724
+     * @deprecated 20.0.0
1725
+     */
1726
+    public function getL10NFactory() {
1727
+        return $this->get(IFactory::class);
1728
+    }
1729
+
1730
+    /**
1731
+     * get an L10N instance
1732
+     *
1733
+     * @param string $app appid
1734
+     * @param string $lang
1735
+     * @return IL10N
1736
+     * @deprecated 20.0.0
1737
+     */
1738
+    public function getL10N($app, $lang = null) {
1739
+        return $this->get(IFactory::class)->get($app, $lang);
1740
+    }
1741
+
1742
+    /**
1743
+     * @return IURLGenerator
1744
+     * @deprecated 20.0.0
1745
+     */
1746
+    public function getURLGenerator() {
1747
+        return $this->get(IURLGenerator::class);
1748
+    }
1749
+
1750
+    /**
1751
+     * @return AppFetcher
1752
+     * @deprecated 20.0.0
1753
+     */
1754
+    public function getAppFetcher() {
1755
+        return $this->get(AppFetcher::class);
1756
+    }
1757
+
1758
+    /**
1759
+     * Returns an ICache instance. Since 8.1.0 it returns a fake cache. Use
1760
+     * getMemCacheFactory() instead.
1761
+     *
1762
+     * @return ICache
1763
+     * @deprecated 8.1.0 use getMemCacheFactory to obtain a proper cache
1764
+     */
1765
+    public function getCache() {
1766
+        return $this->get(ICache::class);
1767
+    }
1768
+
1769
+    /**
1770
+     * Returns an \OCP\CacheFactory instance
1771
+     *
1772
+     * @return \OCP\ICacheFactory
1773
+     * @deprecated 20.0.0
1774
+     */
1775
+    public function getMemCacheFactory() {
1776
+        return $this->get(ICacheFactory::class);
1777
+    }
1778
+
1779
+    /**
1780
+     * Returns an \OC\RedisFactory instance
1781
+     *
1782
+     * @return \OC\RedisFactory
1783
+     * @deprecated 20.0.0
1784
+     */
1785
+    public function getGetRedisFactory() {
1786
+        return $this->get('RedisFactory');
1787
+    }
1788
+
1789
+
1790
+    /**
1791
+     * Returns the current session
1792
+     *
1793
+     * @return \OCP\IDBConnection
1794
+     * @deprecated 20.0.0
1795
+     */
1796
+    public function getDatabaseConnection() {
1797
+        return $this->get(IDBConnection::class);
1798
+    }
1799
+
1800
+    /**
1801
+     * Returns the activity manager
1802
+     *
1803
+     * @return \OCP\Activity\IManager
1804
+     * @deprecated 20.0.0
1805
+     */
1806
+    public function getActivityManager() {
1807
+        return $this->get(\OCP\Activity\IManager::class);
1808
+    }
1809
+
1810
+    /**
1811
+     * Returns an job list for controlling background jobs
1812
+     *
1813
+     * @return IJobList
1814
+     * @deprecated 20.0.0
1815
+     */
1816
+    public function getJobList() {
1817
+        return $this->get(IJobList::class);
1818
+    }
1819
+
1820
+    /**
1821
+     * Returns a logger instance
1822
+     *
1823
+     * @return ILogger
1824
+     * @deprecated 20.0.0
1825
+     */
1826
+    public function getLogger() {
1827
+        return $this->get(ILogger::class);
1828
+    }
1829
+
1830
+    /**
1831
+     * @return ILogFactory
1832
+     * @throws \OCP\AppFramework\QueryException
1833
+     * @deprecated 20.0.0
1834
+     */
1835
+    public function getLogFactory() {
1836
+        return $this->get(ILogFactory::class);
1837
+    }
1838
+
1839
+    /**
1840
+     * Returns a router for generating and matching urls
1841
+     *
1842
+     * @return IRouter
1843
+     * @deprecated 20.0.0
1844
+     */
1845
+    public function getRouter() {
1846
+        return $this->get(IRouter::class);
1847
+    }
1848
+
1849
+    /**
1850
+     * Returns a search instance
1851
+     *
1852
+     * @return ISearch
1853
+     * @deprecated 20.0.0
1854
+     */
1855
+    public function getSearch() {
1856
+        return $this->get(ISearch::class);
1857
+    }
1858
+
1859
+    /**
1860
+     * Returns a SecureRandom instance
1861
+     *
1862
+     * @return \OCP\Security\ISecureRandom
1863
+     * @deprecated 20.0.0
1864
+     */
1865
+    public function getSecureRandom() {
1866
+        return $this->get(ISecureRandom::class);
1867
+    }
1868
+
1869
+    /**
1870
+     * Returns a Crypto instance
1871
+     *
1872
+     * @return ICrypto
1873
+     * @deprecated 20.0.0
1874
+     */
1875
+    public function getCrypto() {
1876
+        return $this->get(ICrypto::class);
1877
+    }
1878
+
1879
+    /**
1880
+     * Returns a Hasher instance
1881
+     *
1882
+     * @return IHasher
1883
+     * @deprecated 20.0.0
1884
+     */
1885
+    public function getHasher() {
1886
+        return $this->get(IHasher::class);
1887
+    }
1888
+
1889
+    /**
1890
+     * Returns a CredentialsManager instance
1891
+     *
1892
+     * @return ICredentialsManager
1893
+     * @deprecated 20.0.0
1894
+     */
1895
+    public function getCredentialsManager() {
1896
+        return $this->get(ICredentialsManager::class);
1897
+    }
1898
+
1899
+    /**
1900
+     * Get the certificate manager
1901
+     *
1902
+     * @return \OCP\ICertificateManager
1903
+     */
1904
+    public function getCertificateManager() {
1905
+        return $this->get(ICertificateManager::class);
1906
+    }
1907
+
1908
+    /**
1909
+     * Returns an instance of the HTTP client service
1910
+     *
1911
+     * @return IClientService
1912
+     * @deprecated 20.0.0
1913
+     */
1914
+    public function getHTTPClientService() {
1915
+        return $this->get(IClientService::class);
1916
+    }
1917
+
1918
+    /**
1919
+     * Create a new event source
1920
+     *
1921
+     * @return \OCP\IEventSource
1922
+     * @deprecated 20.0.0
1923
+     */
1924
+    public function createEventSource() {
1925
+        return new \OC_EventSource();
1926
+    }
1927
+
1928
+    /**
1929
+     * Get the active event logger
1930
+     *
1931
+     * The returned logger only logs data when debug mode is enabled
1932
+     *
1933
+     * @return IEventLogger
1934
+     * @deprecated 20.0.0
1935
+     */
1936
+    public function getEventLogger() {
1937
+        return $this->get(IEventLogger::class);
1938
+    }
1939
+
1940
+    /**
1941
+     * Get the active query logger
1942
+     *
1943
+     * The returned logger only logs data when debug mode is enabled
1944
+     *
1945
+     * @return IQueryLogger
1946
+     * @deprecated 20.0.0
1947
+     */
1948
+    public function getQueryLogger() {
1949
+        return $this->get(IQueryLogger::class);
1950
+    }
1951
+
1952
+    /**
1953
+     * Get the manager for temporary files and folders
1954
+     *
1955
+     * @return \OCP\ITempManager
1956
+     * @deprecated 20.0.0
1957
+     */
1958
+    public function getTempManager() {
1959
+        return $this->get(ITempManager::class);
1960
+    }
1961
+
1962
+    /**
1963
+     * Get the app manager
1964
+     *
1965
+     * @return \OCP\App\IAppManager
1966
+     * @deprecated 20.0.0
1967
+     */
1968
+    public function getAppManager() {
1969
+        return $this->get(IAppManager::class);
1970
+    }
1971
+
1972
+    /**
1973
+     * Creates a new mailer
1974
+     *
1975
+     * @return IMailer
1976
+     * @deprecated 20.0.0
1977
+     */
1978
+    public function getMailer() {
1979
+        return $this->get(IMailer::class);
1980
+    }
1981
+
1982
+    /**
1983
+     * Get the webroot
1984
+     *
1985
+     * @return string
1986
+     * @deprecated 20.0.0
1987
+     */
1988
+    public function getWebRoot() {
1989
+        return $this->webRoot;
1990
+    }
1991
+
1992
+    /**
1993
+     * @return \OC\OCSClient
1994
+     * @deprecated 20.0.0
1995
+     */
1996
+    public function getOcsClient() {
1997
+        return $this->get('OcsClient');
1998
+    }
1999
+
2000
+    /**
2001
+     * @return IDateTimeZone
2002
+     * @deprecated 20.0.0
2003
+     */
2004
+    public function getDateTimeZone() {
2005
+        return $this->get(IDateTimeZone::class);
2006
+    }
2007
+
2008
+    /**
2009
+     * @return IDateTimeFormatter
2010
+     * @deprecated 20.0.0
2011
+     */
2012
+    public function getDateTimeFormatter() {
2013
+        return $this->get(IDateTimeFormatter::class);
2014
+    }
2015
+
2016
+    /**
2017
+     * @return IMountProviderCollection
2018
+     * @deprecated 20.0.0
2019
+     */
2020
+    public function getMountProviderCollection() {
2021
+        return $this->get(IMountProviderCollection::class);
2022
+    }
2023
+
2024
+    /**
2025
+     * Get the IniWrapper
2026
+     *
2027
+     * @return IniGetWrapper
2028
+     * @deprecated 20.0.0
2029
+     */
2030
+    public function getIniWrapper() {
2031
+        return $this->get(IniGetWrapper::class);
2032
+    }
2033
+
2034
+    /**
2035
+     * @return \OCP\Command\IBus
2036
+     * @deprecated 20.0.0
2037
+     */
2038
+    public function getCommandBus() {
2039
+        return $this->get(IBus::class);
2040
+    }
2041
+
2042
+    /**
2043
+     * Get the trusted domain helper
2044
+     *
2045
+     * @return TrustedDomainHelper
2046
+     * @deprecated 20.0.0
2047
+     */
2048
+    public function getTrustedDomainHelper() {
2049
+        return $this->get(TrustedDomainHelper::class);
2050
+    }
2051
+
2052
+    /**
2053
+     * Get the locking provider
2054
+     *
2055
+     * @return ILockingProvider
2056
+     * @since 8.1.0
2057
+     * @deprecated 20.0.0
2058
+     */
2059
+    public function getLockingProvider() {
2060
+        return $this->get(ILockingProvider::class);
2061
+    }
2062
+
2063
+    /**
2064
+     * @return IMountManager
2065
+     * @deprecated 20.0.0
2066
+     **/
2067
+    public function getMountManager() {
2068
+        return $this->get(IMountManager::class);
2069
+    }
2070
+
2071
+    /**
2072
+     * @return IUserMountCache
2073
+     * @deprecated 20.0.0
2074
+     */
2075
+    public function getUserMountCache() {
2076
+        return $this->get(IUserMountCache::class);
2077
+    }
2078
+
2079
+    /**
2080
+     * Get the MimeTypeDetector
2081
+     *
2082
+     * @return IMimeTypeDetector
2083
+     * @deprecated 20.0.0
2084
+     */
2085
+    public function getMimeTypeDetector() {
2086
+        return $this->get(IMimeTypeDetector::class);
2087
+    }
2088
+
2089
+    /**
2090
+     * Get the MimeTypeLoader
2091
+     *
2092
+     * @return IMimeTypeLoader
2093
+     * @deprecated 20.0.0
2094
+     */
2095
+    public function getMimeTypeLoader() {
2096
+        return $this->get(IMimeTypeLoader::class);
2097
+    }
2098
+
2099
+    /**
2100
+     * Get the manager of all the capabilities
2101
+     *
2102
+     * @return CapabilitiesManager
2103
+     * @deprecated 20.0.0
2104
+     */
2105
+    public function getCapabilitiesManager() {
2106
+        return $this->get(CapabilitiesManager::class);
2107
+    }
2108
+
2109
+    /**
2110
+     * Get the EventDispatcher
2111
+     *
2112
+     * @return EventDispatcherInterface
2113
+     * @since 8.2.0
2114
+     * @deprecated 18.0.0 use \OCP\EventDispatcher\IEventDispatcher
2115
+     */
2116
+    public function getEventDispatcher() {
2117
+        return $this->get(\OC\EventDispatcher\SymfonyAdapter::class);
2118
+    }
2119
+
2120
+    /**
2121
+     * Get the Notification Manager
2122
+     *
2123
+     * @return \OCP\Notification\IManager
2124
+     * @since 8.2.0
2125
+     * @deprecated 20.0.0
2126
+     */
2127
+    public function getNotificationManager() {
2128
+        return $this->get(\OCP\Notification\IManager::class);
2129
+    }
2130
+
2131
+    /**
2132
+     * @return ICommentsManager
2133
+     * @deprecated 20.0.0
2134
+     */
2135
+    public function getCommentsManager() {
2136
+        return $this->get(ICommentsManager::class);
2137
+    }
2138
+
2139
+    /**
2140
+     * @return \OCA\Theming\ThemingDefaults
2141
+     * @deprecated 20.0.0
2142
+     */
2143
+    public function getThemingDefaults() {
2144
+        return $this->get('ThemingDefaults');
2145
+    }
2146
+
2147
+    /**
2148
+     * @return \OC\IntegrityCheck\Checker
2149
+     * @deprecated 20.0.0
2150
+     */
2151
+    public function getIntegrityCodeChecker() {
2152
+        return $this->get('IntegrityCodeChecker');
2153
+    }
2154
+
2155
+    /**
2156
+     * @return \OC\Session\CryptoWrapper
2157
+     * @deprecated 20.0.0
2158
+     */
2159
+    public function getSessionCryptoWrapper() {
2160
+        return $this->get('CryptoWrapper');
2161
+    }
2162
+
2163
+    /**
2164
+     * @return CsrfTokenManager
2165
+     * @deprecated 20.0.0
2166
+     */
2167
+    public function getCsrfTokenManager() {
2168
+        return $this->get(CsrfTokenManager::class);
2169
+    }
2170
+
2171
+    /**
2172
+     * @return Throttler
2173
+     * @deprecated 20.0.0
2174
+     */
2175
+    public function getBruteForceThrottler() {
2176
+        return $this->get(Throttler::class);
2177
+    }
2178
+
2179
+    /**
2180
+     * @return IContentSecurityPolicyManager
2181
+     * @deprecated 20.0.0
2182
+     */
2183
+    public function getContentSecurityPolicyManager() {
2184
+        return $this->get(ContentSecurityPolicyManager::class);
2185
+    }
2186
+
2187
+    /**
2188
+     * @return ContentSecurityPolicyNonceManager
2189
+     * @deprecated 20.0.0
2190
+     */
2191
+    public function getContentSecurityPolicyNonceManager() {
2192
+        return $this->get(ContentSecurityPolicyNonceManager::class);
2193
+    }
2194
+
2195
+    /**
2196
+     * Not a public API as of 8.2, wait for 9.0
2197
+     *
2198
+     * @return \OCA\Files_External\Service\BackendService
2199
+     * @deprecated 20.0.0
2200
+     */
2201
+    public function getStoragesBackendService() {
2202
+        return $this->get(BackendService::class);
2203
+    }
2204
+
2205
+    /**
2206
+     * Not a public API as of 8.2, wait for 9.0
2207
+     *
2208
+     * @return \OCA\Files_External\Service\GlobalStoragesService
2209
+     * @deprecated 20.0.0
2210
+     */
2211
+    public function getGlobalStoragesService() {
2212
+        return $this->get(GlobalStoragesService::class);
2213
+    }
2214
+
2215
+    /**
2216
+     * Not a public API as of 8.2, wait for 9.0
2217
+     *
2218
+     * @return \OCA\Files_External\Service\UserGlobalStoragesService
2219
+     * @deprecated 20.0.0
2220
+     */
2221
+    public function getUserGlobalStoragesService() {
2222
+        return $this->get(UserGlobalStoragesService::class);
2223
+    }
2224
+
2225
+    /**
2226
+     * Not a public API as of 8.2, wait for 9.0
2227
+     *
2228
+     * @return \OCA\Files_External\Service\UserStoragesService
2229
+     * @deprecated 20.0.0
2230
+     */
2231
+    public function getUserStoragesService() {
2232
+        return $this->get(UserStoragesService::class);
2233
+    }
2234
+
2235
+    /**
2236
+     * @return \OCP\Share\IManager
2237
+     * @deprecated 20.0.0
2238
+     */
2239
+    public function getShareManager() {
2240
+        return $this->get(\OCP\Share\IManager::class);
2241
+    }
2242
+
2243
+    /**
2244
+     * @return \OCP\Collaboration\Collaborators\ISearch
2245
+     * @deprecated 20.0.0
2246
+     */
2247
+    public function getCollaboratorSearch() {
2248
+        return $this->get(\OCP\Collaboration\Collaborators\ISearch::class);
2249
+    }
2250
+
2251
+    /**
2252
+     * @return \OCP\Collaboration\AutoComplete\IManager
2253
+     * @deprecated 20.0.0
2254
+     */
2255
+    public function getAutoCompleteManager() {
2256
+        return $this->get(IManager::class);
2257
+    }
2258
+
2259
+    /**
2260
+     * Returns the LDAP Provider
2261
+     *
2262
+     * @return \OCP\LDAP\ILDAPProvider
2263
+     * @deprecated 20.0.0
2264
+     */
2265
+    public function getLDAPProvider() {
2266
+        return $this->get('LDAPProvider');
2267
+    }
2268
+
2269
+    /**
2270
+     * @return \OCP\Settings\IManager
2271
+     * @deprecated 20.0.0
2272
+     */
2273
+    public function getSettingsManager() {
2274
+        return $this->get(\OC\Settings\Manager::class);
2275
+    }
2276
+
2277
+    /**
2278
+     * @return \OCP\Files\IAppData
2279
+     * @deprecated 20.0.0 Use get(\OCP\Files\AppData\IAppDataFactory::class)->get($app) instead
2280
+     */
2281
+    public function getAppDataDir($app) {
2282
+        /** @var \OC\Files\AppData\Factory $factory */
2283
+        $factory = $this->get(\OC\Files\AppData\Factory::class);
2284
+        return $factory->get($app);
2285
+    }
2286
+
2287
+    /**
2288
+     * @return \OCP\Lockdown\ILockdownManager
2289
+     * @deprecated 20.0.0
2290
+     */
2291
+    public function getLockdownManager() {
2292
+        return $this->get('LockdownManager');
2293
+    }
2294
+
2295
+    /**
2296
+     * @return \OCP\Federation\ICloudIdManager
2297
+     * @deprecated 20.0.0
2298
+     */
2299
+    public function getCloudIdManager() {
2300
+        return $this->get(ICloudIdManager::class);
2301
+    }
2302
+
2303
+    /**
2304
+     * @return \OCP\GlobalScale\IConfig
2305
+     * @deprecated 20.0.0
2306
+     */
2307
+    public function getGlobalScaleConfig() {
2308
+        return $this->get(IConfig::class);
2309
+    }
2310
+
2311
+    /**
2312
+     * @return \OCP\Federation\ICloudFederationProviderManager
2313
+     * @deprecated 20.0.0
2314
+     */
2315
+    public function getCloudFederationProviderManager() {
2316
+        return $this->get(ICloudFederationProviderManager::class);
2317
+    }
2318
+
2319
+    /**
2320
+     * @return \OCP\Remote\Api\IApiFactory
2321
+     * @deprecated 20.0.0
2322
+     */
2323
+    public function getRemoteApiFactory() {
2324
+        return $this->get(IApiFactory::class);
2325
+    }
2326
+
2327
+    /**
2328
+     * @return \OCP\Federation\ICloudFederationFactory
2329
+     * @deprecated 20.0.0
2330
+     */
2331
+    public function getCloudFederationFactory() {
2332
+        return $this->get(ICloudFederationFactory::class);
2333
+    }
2334
+
2335
+    /**
2336
+     * @return \OCP\Remote\IInstanceFactory
2337
+     * @deprecated 20.0.0
2338
+     */
2339
+    public function getRemoteInstanceFactory() {
2340
+        return $this->get(IInstanceFactory::class);
2341
+    }
2342
+
2343
+    /**
2344
+     * @return IStorageFactory
2345
+     * @deprecated 20.0.0
2346
+     */
2347
+    public function getStorageFactory() {
2348
+        return $this->get(IStorageFactory::class);
2349
+    }
2350
+
2351
+    /**
2352
+     * Get the Preview GeneratorHelper
2353
+     *
2354
+     * @return GeneratorHelper
2355
+     * @since 17.0.0
2356
+     * @deprecated 20.0.0
2357
+     */
2358
+    public function getGeneratorHelper() {
2359
+        return $this->get(\OC\Preview\GeneratorHelper::class);
2360
+    }
2361
+
2362
+    private function registerDeprecatedAlias(string $alias, string $target) {
2363
+        $this->registerService($alias, function (ContainerInterface $container) use ($target, $alias) {
2364
+            try {
2365
+                /** @var LoggerInterface $logger */
2366
+                $logger = $container->get(LoggerInterface::class);
2367
+                $logger->debug('The requested alias "' . $alias . '" is deprecated. Please request "' . $target . '" directly. This alias will be removed in a future Nextcloud version.', ['app' => 'serverDI']);
2368
+            } catch (ContainerExceptionInterface $e) {
2369
+                // Could not get logger. Continue
2370
+            }
2371
+
2372
+            return $container->get($target);
2373
+        }, false);
2374
+    }
2375 2375
 }
Please login to merge, or discard this patch.
lib/private/Template/ResourceLocator.php 1 patch
Indentation   +161 added lines, -161 removed lines patch added patch discarded remove patch
@@ -32,165 +32,165 @@
 block discarded – undo
32 32
 use Psr\Log\LoggerInterface;
33 33
 
34 34
 abstract class ResourceLocator {
35
-	protected $theme;
36
-
37
-	protected $mapping;
38
-	protected $serverroot;
39
-	protected $webroot;
40
-
41
-	protected $resources = [];
42
-
43
-	protected LoggerInterface $logger;
44
-
45
-	public function __construct(LoggerInterface $logger) {
46
-		$this->logger = $logger;
47
-		$this->mapping = [
48
-			\OC::$SERVERROOT => \OC::$WEBROOT
49
-		];
50
-		$this->serverroot = \OC::$SERVERROOT;
51
-		$this->webroot = \OC::$WEBROOT;
52
-		$this->theme = \OC_Util::getTheme();
53
-	}
54
-
55
-	/**
56
-	 * @param string $resource
57
-	 */
58
-	abstract public function doFind($resource);
59
-
60
-	/**
61
-	 * @param string $resource
62
-	 */
63
-	abstract public function doFindTheme($resource);
64
-
65
-	/**
66
-	 * Finds the resources and adds them to the list
67
-	 *
68
-	 * @param array $resources
69
-	 */
70
-	public function find($resources) {
71
-		foreach ($resources as $resource) {
72
-			try {
73
-				$this->doFind($resource);
74
-			} catch (ResourceNotFoundException $e) {
75
-				$resourceApp = substr($resource, 0, strpos($resource, '/'));
76
-				$this->logger->debug('Could not find resource file "' . $e->getResourcePath() . '"', ['app' => $resourceApp]);
77
-			}
78
-		}
79
-		if (!empty($this->theme)) {
80
-			foreach ($resources as $resource) {
81
-				try {
82
-					$this->doFindTheme($resource);
83
-				} catch (ResourceNotFoundException $e) {
84
-					$resourceApp = substr($resource, 0, strpos($resource, '/'));
85
-					$this->logger->debug('Could not find resource file in theme "' . $e->getResourcePath() . '"', ['app' => $resourceApp]);
86
-				}
87
-			}
88
-		}
89
-	}
90
-
91
-	/**
92
-	 * append the $file resource if exist at $root
93
-	 *
94
-	 * @param string $root path to check
95
-	 * @param string $file the filename
96
-	 * @param string|null $webRoot base for path, default map $root to $webRoot
97
-	 * @return bool True if the resource was found, false otherwise
98
-	 */
99
-	protected function appendIfExist($root, $file, $webRoot = null) {
100
-		if ($root !== false && is_file($root.'/'.$file)) {
101
-			$this->append($root, $file, $webRoot, false);
102
-			return true;
103
-		}
104
-		return false;
105
-	}
106
-
107
-	/**
108
-	 * Attempt to find the webRoot
109
-	 *
110
-	 * traverse the potential web roots upwards in the path
111
-	 *
112
-	 * example:
113
-	 *   - root: /srv/www/apps/myapp
114
-	 *   - available mappings: ['/srv/www']
115
-	 *
116
-	 * First we check if a mapping for /srv/www/apps/myapp is available,
117
-	 * then /srv/www/apps, /srv/www/apps, /srv/www, ... until we find a
118
-	 * valid web root
119
-	 *
120
-	 * @param string $root
121
-	 * @return string|null The web root or null on failure
122
-	 */
123
-	protected function findWebRoot($root) {
124
-		$webRoot = null;
125
-		$tmpRoot = $root;
126
-
127
-		while ($webRoot === null) {
128
-			if (isset($this->mapping[$tmpRoot])) {
129
-				$webRoot = $this->mapping[$tmpRoot];
130
-				break;
131
-			}
132
-
133
-			if ($tmpRoot === '/') {
134
-				break;
135
-			}
136
-
137
-			$tmpRoot = dirname($tmpRoot);
138
-		}
139
-
140
-		if ($webRoot === null) {
141
-			$realpath = realpath($root);
142
-
143
-			if ($realpath && ($realpath !== $root)) {
144
-				return $this->findWebRoot($realpath);
145
-			}
146
-		}
147
-
148
-		return $webRoot;
149
-	}
150
-
151
-	/**
152
-	 * append the $file resource at $root
153
-	 *
154
-	 * @param string $root path to check
155
-	 * @param string $file the filename
156
-	 * @param string|null $webRoot base for path, default map $root to $webRoot
157
-	 * @param bool $throw Throw an exception, when the route does not exist
158
-	 * @throws ResourceNotFoundException Only thrown when $throw is true and the resource is missing
159
-	 */
160
-	protected function append($root, $file, $webRoot = null, $throw = true) {
161
-		if (!is_string($root)) {
162
-			if ($throw) {
163
-				throw new ResourceNotFoundException($file, $webRoot);
164
-			}
165
-			return;
166
-		}
167
-
168
-		if (!$webRoot) {
169
-			$webRoot = $this->findWebRoot($root);
170
-
171
-			if ($webRoot === null) {
172
-				$webRoot = '';
173
-				$this->logger->error('ResourceLocator can not find a web root (root: {root}, file: {file}, webRoot: {webRoot}, throw: {throw})', [
174
-					'app' => 'lib',
175
-					'root' => $root,
176
-					'file' => $file,
177
-					'webRoot' => $webRoot,
178
-					'throw' => $throw ? 'true' : 'false'
179
-				]);
180
-			}
181
-		}
182
-		$this->resources[] = [$root, $webRoot, $file];
183
-
184
-		if ($throw && !is_file($root . '/' . $file)) {
185
-			throw new ResourceNotFoundException($file, $webRoot);
186
-		}
187
-	}
188
-
189
-	/**
190
-	 * Returns the list of all resources that should be loaded
191
-	 * @return array
192
-	 */
193
-	public function getResources() {
194
-		return $this->resources;
195
-	}
35
+    protected $theme;
36
+
37
+    protected $mapping;
38
+    protected $serverroot;
39
+    protected $webroot;
40
+
41
+    protected $resources = [];
42
+
43
+    protected LoggerInterface $logger;
44
+
45
+    public function __construct(LoggerInterface $logger) {
46
+        $this->logger = $logger;
47
+        $this->mapping = [
48
+            \OC::$SERVERROOT => \OC::$WEBROOT
49
+        ];
50
+        $this->serverroot = \OC::$SERVERROOT;
51
+        $this->webroot = \OC::$WEBROOT;
52
+        $this->theme = \OC_Util::getTheme();
53
+    }
54
+
55
+    /**
56
+     * @param string $resource
57
+     */
58
+    abstract public function doFind($resource);
59
+
60
+    /**
61
+     * @param string $resource
62
+     */
63
+    abstract public function doFindTheme($resource);
64
+
65
+    /**
66
+     * Finds the resources and adds them to the list
67
+     *
68
+     * @param array $resources
69
+     */
70
+    public function find($resources) {
71
+        foreach ($resources as $resource) {
72
+            try {
73
+                $this->doFind($resource);
74
+            } catch (ResourceNotFoundException $e) {
75
+                $resourceApp = substr($resource, 0, strpos($resource, '/'));
76
+                $this->logger->debug('Could not find resource file "' . $e->getResourcePath() . '"', ['app' => $resourceApp]);
77
+            }
78
+        }
79
+        if (!empty($this->theme)) {
80
+            foreach ($resources as $resource) {
81
+                try {
82
+                    $this->doFindTheme($resource);
83
+                } catch (ResourceNotFoundException $e) {
84
+                    $resourceApp = substr($resource, 0, strpos($resource, '/'));
85
+                    $this->logger->debug('Could not find resource file in theme "' . $e->getResourcePath() . '"', ['app' => $resourceApp]);
86
+                }
87
+            }
88
+        }
89
+    }
90
+
91
+    /**
92
+     * append the $file resource if exist at $root
93
+     *
94
+     * @param string $root path to check
95
+     * @param string $file the filename
96
+     * @param string|null $webRoot base for path, default map $root to $webRoot
97
+     * @return bool True if the resource was found, false otherwise
98
+     */
99
+    protected function appendIfExist($root, $file, $webRoot = null) {
100
+        if ($root !== false && is_file($root.'/'.$file)) {
101
+            $this->append($root, $file, $webRoot, false);
102
+            return true;
103
+        }
104
+        return false;
105
+    }
106
+
107
+    /**
108
+     * Attempt to find the webRoot
109
+     *
110
+     * traverse the potential web roots upwards in the path
111
+     *
112
+     * example:
113
+     *   - root: /srv/www/apps/myapp
114
+     *   - available mappings: ['/srv/www']
115
+     *
116
+     * First we check if a mapping for /srv/www/apps/myapp is available,
117
+     * then /srv/www/apps, /srv/www/apps, /srv/www, ... until we find a
118
+     * valid web root
119
+     *
120
+     * @param string $root
121
+     * @return string|null The web root or null on failure
122
+     */
123
+    protected function findWebRoot($root) {
124
+        $webRoot = null;
125
+        $tmpRoot = $root;
126
+
127
+        while ($webRoot === null) {
128
+            if (isset($this->mapping[$tmpRoot])) {
129
+                $webRoot = $this->mapping[$tmpRoot];
130
+                break;
131
+            }
132
+
133
+            if ($tmpRoot === '/') {
134
+                break;
135
+            }
136
+
137
+            $tmpRoot = dirname($tmpRoot);
138
+        }
139
+
140
+        if ($webRoot === null) {
141
+            $realpath = realpath($root);
142
+
143
+            if ($realpath && ($realpath !== $root)) {
144
+                return $this->findWebRoot($realpath);
145
+            }
146
+        }
147
+
148
+        return $webRoot;
149
+    }
150
+
151
+    /**
152
+     * append the $file resource at $root
153
+     *
154
+     * @param string $root path to check
155
+     * @param string $file the filename
156
+     * @param string|null $webRoot base for path, default map $root to $webRoot
157
+     * @param bool $throw Throw an exception, when the route does not exist
158
+     * @throws ResourceNotFoundException Only thrown when $throw is true and the resource is missing
159
+     */
160
+    protected function append($root, $file, $webRoot = null, $throw = true) {
161
+        if (!is_string($root)) {
162
+            if ($throw) {
163
+                throw new ResourceNotFoundException($file, $webRoot);
164
+            }
165
+            return;
166
+        }
167
+
168
+        if (!$webRoot) {
169
+            $webRoot = $this->findWebRoot($root);
170
+
171
+            if ($webRoot === null) {
172
+                $webRoot = '';
173
+                $this->logger->error('ResourceLocator can not find a web root (root: {root}, file: {file}, webRoot: {webRoot}, throw: {throw})', [
174
+                    'app' => 'lib',
175
+                    'root' => $root,
176
+                    'file' => $file,
177
+                    'webRoot' => $webRoot,
178
+                    'throw' => $throw ? 'true' : 'false'
179
+                ]);
180
+            }
181
+        }
182
+        $this->resources[] = [$root, $webRoot, $file];
183
+
184
+        if ($throw && !is_file($root . '/' . $file)) {
185
+            throw new ResourceNotFoundException($file, $webRoot);
186
+        }
187
+    }
188
+
189
+    /**
190
+     * Returns the list of all resources that should be loaded
191
+     * @return array
192
+     */
193
+    public function getResources() {
194
+        return $this->resources;
195
+    }
196 196
 }
Please login to merge, or discard this patch.
lib/private/Template/CSSResourceLocator.php 1 patch
Indentation   +62 added lines, -62 removed lines patch added patch discarded remove patch
@@ -34,75 +34,75 @@
 block discarded – undo
34 34
 use Psr\Log\LoggerInterface;
35 35
 
36 36
 class CSSResourceLocator extends ResourceLocator {
37
-	public function __construct(LoggerInterface $logger) {
38
-		parent::__construct($logger);
39
-	}
37
+    public function __construct(LoggerInterface $logger) {
38
+        parent::__construct($logger);
39
+    }
40 40
 
41
-	/**
42
-	 * @param string $style
43
-	 */
44
-	public function doFind($style) {
45
-		$app = substr($style, 0, strpos($style, '/'));
46
-		if (strpos($style, '3rdparty') === 0
47
-			&& $this->appendIfExist($this->serverroot, $style.'.css')
48
-			|| $this->appendIfExist($this->serverroot, 'core/'.$style.'.css')
49
-		) {
50
-			return;
51
-		}
52
-		$style = substr($style, strpos($style, '/') + 1);
53
-		$app_path = \OC_App::getAppPath($app);
54
-		$app_url = \OC_App::getAppWebPath($app);
41
+    /**
42
+     * @param string $style
43
+     */
44
+    public function doFind($style) {
45
+        $app = substr($style, 0, strpos($style, '/'));
46
+        if (strpos($style, '3rdparty') === 0
47
+            && $this->appendIfExist($this->serverroot, $style.'.css')
48
+            || $this->appendIfExist($this->serverroot, 'core/'.$style.'.css')
49
+        ) {
50
+            return;
51
+        }
52
+        $style = substr($style, strpos($style, '/') + 1);
53
+        $app_path = \OC_App::getAppPath($app);
54
+        $app_url = \OC_App::getAppWebPath($app);
55 55
 
56
-		if ($app_path === false && $app_url === false) {
57
-			$this->logger->error('Could not find resource {resource} to load', [
58
-				'resource' => $app . '/' . $style . '.css',
59
-				'app' => 'cssresourceloader',
60
-			]);
61
-			return;
62
-		}
56
+        if ($app_path === false && $app_url === false) {
57
+            $this->logger->error('Could not find resource {resource} to load', [
58
+                'resource' => $app . '/' . $style . '.css',
59
+                'app' => 'cssresourceloader',
60
+            ]);
61
+            return;
62
+        }
63 63
 
64
-		// Account for the possibility of having symlinks in app path. Doing
65
-		// this here instead of above as an empty argument to realpath gets
66
-		// turned into cwd.
67
-		$app_path = realpath($app_path);
64
+        // Account for the possibility of having symlinks in app path. Doing
65
+        // this here instead of above as an empty argument to realpath gets
66
+        // turned into cwd.
67
+        $app_path = realpath($app_path);
68 68
 
69
-		$this->append($app_path, $style.'.css', $app_url);
70
-	}
69
+        $this->append($app_path, $style.'.css', $app_url);
70
+    }
71 71
 
72
-	/**
73
-	 * @param string $style
74
-	 */
75
-	public function doFindTheme($style) {
76
-		$theme_dir = 'themes/'.$this->theme.'/';
77
-		$this->appendIfExist($this->serverroot, $theme_dir.'apps/'.$style.'.css')
78
-			|| $this->appendIfExist($this->serverroot, $theme_dir.$style.'.css')
79
-			|| $this->appendIfExist($this->serverroot, $theme_dir.'core/'.$style.'.css');
80
-	}
72
+    /**
73
+     * @param string $style
74
+     */
75
+    public function doFindTheme($style) {
76
+        $theme_dir = 'themes/'.$this->theme.'/';
77
+        $this->appendIfExist($this->serverroot, $theme_dir.'apps/'.$style.'.css')
78
+            || $this->appendIfExist($this->serverroot, $theme_dir.$style.'.css')
79
+            || $this->appendIfExist($this->serverroot, $theme_dir.'core/'.$style.'.css');
80
+    }
81 81
 
82
-	public function append($root, $file, $webRoot = null, $throw = true, $scss = false) {
83
-		if (!$scss) {
84
-			parent::append($root, $file, $webRoot, $throw);
85
-		} else {
86
-			if (!$webRoot) {
87
-				$webRoot = $this->findWebRoot($root);
82
+    public function append($root, $file, $webRoot = null, $throw = true, $scss = false) {
83
+        if (!$scss) {
84
+            parent::append($root, $file, $webRoot, $throw);
85
+        } else {
86
+            if (!$webRoot) {
87
+                $webRoot = $this->findWebRoot($root);
88 88
 
89
-				if ($webRoot === null) {
90
-					$webRoot = '';
91
-					$this->logger->error('ResourceLocator can not find a web root (root: {root}, file: {file}, webRoot: {webRoot}, throw: {throw})', [
92
-						'app' => 'lib',
93
-						'root' => $root,
94
-						'file' => $file,
95
-						'webRoot' => $webRoot,
96
-						'throw' => $throw ? 'true' : 'false'
97
-					]);
89
+                if ($webRoot === null) {
90
+                    $webRoot = '';
91
+                    $this->logger->error('ResourceLocator can not find a web root (root: {root}, file: {file}, webRoot: {webRoot}, throw: {throw})', [
92
+                        'app' => 'lib',
93
+                        'root' => $root,
94
+                        'file' => $file,
95
+                        'webRoot' => $webRoot,
96
+                        'throw' => $throw ? 'true' : 'false'
97
+                    ]);
98 98
 
99
-					if ($throw && $root === '/') {
100
-						throw new ResourceNotFoundException($file, $webRoot);
101
-					}
102
-				}
103
-			}
99
+                    if ($throw && $root === '/') {
100
+                        throw new ResourceNotFoundException($file, $webRoot);
101
+                    }
102
+                }
103
+            }
104 104
 
105
-			$this->resources[] = [$webRoot ?: \OC::$WEBROOT, $webRoot, $file];
106
-		}
107
-	}
105
+            $this->resources[] = [$webRoot ?: \OC::$WEBROOT, $webRoot, $file];
106
+        }
107
+    }
108 108
 }
Please login to merge, or discard this patch.
lib/private/Template/JSResourceLocator.php 1 patch
Indentation   +103 added lines, -103 removed lines patch added patch discarded remove patch
@@ -31,107 +31,107 @@
 block discarded – undo
31 31
 
32 32
 class JSResourceLocator extends ResourceLocator {
33 33
 
34
-	/** @var JSCombiner */
35
-	protected $jsCombiner;
36
-
37
-	public function __construct(LoggerInterface $logger, JSCombiner $JSCombiner) {
38
-		parent::__construct($logger);
39
-
40
-		$this->jsCombiner = $JSCombiner;
41
-	}
42
-
43
-	/**
44
-	 * @param string $script
45
-	 */
46
-	public function doFind($script) {
47
-		$theme_dir = 'themes/'.$this->theme.'/';
48
-
49
-		// Extracting the appId and the script file name
50
-		$app = substr($script, 0, strpos($script, '/'));
51
-		$scriptName = basename($script);
52
-
53
-		if (strpos($script, '/l10n/') !== false) {
54
-			// For language files we try to load them all, so themes can overwrite
55
-			// single l10n strings without having to translate all of them.
56
-			$found = 0;
57
-			$found += $this->appendIfExist($this->serverroot, 'core/'.$script.'.js');
58
-			$found += $this->appendIfExist($this->serverroot, $theme_dir.'core/'.$script.'.js');
59
-			$found += $this->appendIfExist($this->serverroot, $script.'.js');
60
-			$found += $this->appendIfExist($this->serverroot, $theme_dir.$script.'.js');
61
-			$found += $this->appendIfExist($this->serverroot, 'apps/'.$script.'.js');
62
-			$found += $this->appendIfExist($this->serverroot, $theme_dir.'apps/'.$script.'.js');
63
-
64
-			if ($found) {
65
-				return;
66
-			}
67
-		} elseif ($this->appendIfExist($this->serverroot, $theme_dir.'apps/'.$script.'.js')
68
-			|| $this->appendIfExist($this->serverroot, $theme_dir.$script.'.js')
69
-			|| $this->appendIfExist($this->serverroot, $script.'.js')
70
-			|| $this->appendIfExist($this->serverroot, $theme_dir . "dist/$app-$scriptName.js")
71
-			|| $this->appendIfExist($this->serverroot, "dist/$app-$scriptName.js")
72
-			|| $this->appendIfExist($this->serverroot, 'apps/'.$script.'.js')
73
-			|| $this->cacheAndAppendCombineJsonIfExist($this->serverroot, $script.'.json')
74
-			|| $this->appendIfExist($this->serverroot, $theme_dir.'core/'.$script.'.js')
75
-			|| $this->appendIfExist($this->serverroot, 'core/'.$script.'.js')
76
-			|| (strpos($scriptName, '/') === -1 && ($this->appendIfExist($this->serverroot, $theme_dir . "dist/core-$scriptName.js")
77
-				|| $this->appendIfExist($this->serverroot, "dist/core-$scriptName.js")))
78
-			|| $this->cacheAndAppendCombineJsonIfExist($this->serverroot, 'core/'.$script.'.json')
79
-		) {
80
-			return;
81
-		}
82
-
83
-		$script = substr($script, strpos($script, '/') + 1);
84
-		$app_path = \OC_App::getAppPath($app);
85
-		$app_url = \OC_App::getAppWebPath($app);
86
-
87
-		if ($app_path !== false) {
88
-			// Account for the possibility of having symlinks in app path. Only
89
-			// do this if $app_path is set, because an empty argument to realpath
90
-			// gets turned into cwd.
91
-			$app_path = realpath($app_path);
92
-		}
93
-
94
-		// missing translations files fill be ignored
95
-		if (strpos($script, 'l10n/') === 0) {
96
-			$this->appendIfExist($app_path, $script . '.js', $app_url);
97
-			return;
98
-		}
99
-
100
-		if ($app_path === false && $app_url === false) {
101
-			$this->logger->error('Could not find resource {resource} to load', [
102
-				'resource' => $app . '/' . $script . '.js',
103
-				'app' => 'jsresourceloader',
104
-			]);
105
-			return;
106
-		}
107
-
108
-		if (!$this->cacheAndAppendCombineJsonIfExist($app_path, $script.'.json', $app)) {
109
-			$this->append($app_path, $script . '.js', $app_url);
110
-		}
111
-	}
112
-
113
-	/**
114
-	 * @param string $script
115
-	 */
116
-	public function doFindTheme($script) {
117
-	}
118
-
119
-	protected function cacheAndAppendCombineJsonIfExist($root, $file, $app = 'core') {
120
-		if (is_file($root.'/'.$file)) {
121
-			if ($this->jsCombiner->process($root, $file, $app)) {
122
-				$this->append($this->serverroot, $this->jsCombiner->getCachedJS($app, $file), false, false);
123
-			} else {
124
-				// Add all the files from the json
125
-				$files = $this->jsCombiner->getContent($root, $file);
126
-				$app_url = \OC_App::getAppWebPath($app);
127
-
128
-				foreach ($files as $jsFile) {
129
-					$this->append($root, $jsFile, $app_url);
130
-				}
131
-			}
132
-			return true;
133
-		}
134
-
135
-		return false;
136
-	}
34
+    /** @var JSCombiner */
35
+    protected $jsCombiner;
36
+
37
+    public function __construct(LoggerInterface $logger, JSCombiner $JSCombiner) {
38
+        parent::__construct($logger);
39
+
40
+        $this->jsCombiner = $JSCombiner;
41
+    }
42
+
43
+    /**
44
+     * @param string $script
45
+     */
46
+    public function doFind($script) {
47
+        $theme_dir = 'themes/'.$this->theme.'/';
48
+
49
+        // Extracting the appId and the script file name
50
+        $app = substr($script, 0, strpos($script, '/'));
51
+        $scriptName = basename($script);
52
+
53
+        if (strpos($script, '/l10n/') !== false) {
54
+            // For language files we try to load them all, so themes can overwrite
55
+            // single l10n strings without having to translate all of them.
56
+            $found = 0;
57
+            $found += $this->appendIfExist($this->serverroot, 'core/'.$script.'.js');
58
+            $found += $this->appendIfExist($this->serverroot, $theme_dir.'core/'.$script.'.js');
59
+            $found += $this->appendIfExist($this->serverroot, $script.'.js');
60
+            $found += $this->appendIfExist($this->serverroot, $theme_dir.$script.'.js');
61
+            $found += $this->appendIfExist($this->serverroot, 'apps/'.$script.'.js');
62
+            $found += $this->appendIfExist($this->serverroot, $theme_dir.'apps/'.$script.'.js');
63
+
64
+            if ($found) {
65
+                return;
66
+            }
67
+        } elseif ($this->appendIfExist($this->serverroot, $theme_dir.'apps/'.$script.'.js')
68
+            || $this->appendIfExist($this->serverroot, $theme_dir.$script.'.js')
69
+            || $this->appendIfExist($this->serverroot, $script.'.js')
70
+            || $this->appendIfExist($this->serverroot, $theme_dir . "dist/$app-$scriptName.js")
71
+            || $this->appendIfExist($this->serverroot, "dist/$app-$scriptName.js")
72
+            || $this->appendIfExist($this->serverroot, 'apps/'.$script.'.js')
73
+            || $this->cacheAndAppendCombineJsonIfExist($this->serverroot, $script.'.json')
74
+            || $this->appendIfExist($this->serverroot, $theme_dir.'core/'.$script.'.js')
75
+            || $this->appendIfExist($this->serverroot, 'core/'.$script.'.js')
76
+            || (strpos($scriptName, '/') === -1 && ($this->appendIfExist($this->serverroot, $theme_dir . "dist/core-$scriptName.js")
77
+                || $this->appendIfExist($this->serverroot, "dist/core-$scriptName.js")))
78
+            || $this->cacheAndAppendCombineJsonIfExist($this->serverroot, 'core/'.$script.'.json')
79
+        ) {
80
+            return;
81
+        }
82
+
83
+        $script = substr($script, strpos($script, '/') + 1);
84
+        $app_path = \OC_App::getAppPath($app);
85
+        $app_url = \OC_App::getAppWebPath($app);
86
+
87
+        if ($app_path !== false) {
88
+            // Account for the possibility of having symlinks in app path. Only
89
+            // do this if $app_path is set, because an empty argument to realpath
90
+            // gets turned into cwd.
91
+            $app_path = realpath($app_path);
92
+        }
93
+
94
+        // missing translations files fill be ignored
95
+        if (strpos($script, 'l10n/') === 0) {
96
+            $this->appendIfExist($app_path, $script . '.js', $app_url);
97
+            return;
98
+        }
99
+
100
+        if ($app_path === false && $app_url === false) {
101
+            $this->logger->error('Could not find resource {resource} to load', [
102
+                'resource' => $app . '/' . $script . '.js',
103
+                'app' => 'jsresourceloader',
104
+            ]);
105
+            return;
106
+        }
107
+
108
+        if (!$this->cacheAndAppendCombineJsonIfExist($app_path, $script.'.json', $app)) {
109
+            $this->append($app_path, $script . '.js', $app_url);
110
+        }
111
+    }
112
+
113
+    /**
114
+     * @param string $script
115
+     */
116
+    public function doFindTheme($script) {
117
+    }
118
+
119
+    protected function cacheAndAppendCombineJsonIfExist($root, $file, $app = 'core') {
120
+        if (is_file($root.'/'.$file)) {
121
+            if ($this->jsCombiner->process($root, $file, $app)) {
122
+                $this->append($this->serverroot, $this->jsCombiner->getCachedJS($app, $file), false, false);
123
+            } else {
124
+                // Add all the files from the json
125
+                $files = $this->jsCombiner->getContent($root, $file);
126
+                $app_url = \OC_App::getAppWebPath($app);
127
+
128
+                foreach ($files as $jsFile) {
129
+                    $this->append($root, $jsFile, $app_url);
130
+                }
131
+            }
132
+            return true;
133
+        }
134
+
135
+        return false;
136
+    }
137 137
 }
Please login to merge, or discard this patch.
lib/private/ServerContainer.php 1 patch
Indentation   +149 added lines, -149 removed lines patch added patch discarded remove patch
@@ -39,153 +39,153 @@
 block discarded – undo
39 39
  * @package OC
40 40
  */
41 41
 class ServerContainer extends SimpleContainer {
42
-	/** @var DIContainer[] */
43
-	protected $appContainers;
44
-
45
-	/** @var string[] */
46
-	protected $hasNoAppContainer;
47
-
48
-	/** @var string[] */
49
-	protected $namespaces;
50
-
51
-	/**
52
-	 * ServerContainer constructor.
53
-	 */
54
-	public function __construct() {
55
-		parent::__construct();
56
-		$this->appContainers = [];
57
-		$this->namespaces = [];
58
-		$this->hasNoAppContainer = [];
59
-	}
60
-
61
-	/**
62
-	 * @param string $appName
63
-	 * @param string $appNamespace
64
-	 */
65
-	public function registerNamespace(string $appName, string $appNamespace): void {
66
-		// Cut of OCA\ and lowercase
67
-		$appNamespace = strtolower(substr($appNamespace, strrpos($appNamespace, '\\') + 1));
68
-		$this->namespaces[$appNamespace] = $appName;
69
-	}
70
-
71
-	/**
72
-	 * @param string $appName
73
-	 * @param DIContainer $container
74
-	 */
75
-	public function registerAppContainer(string $appName, DIContainer $container): void {
76
-		$this->appContainers[strtolower(App::buildAppNamespace($appName, ''))] = $container;
77
-	}
78
-
79
-	/**
80
-	 * @param string $appName
81
-	 * @return DIContainer
82
-	 * @throws QueryException
83
-	 */
84
-	public function getRegisteredAppContainer(string $appName): DIContainer {
85
-		if (isset($this->appContainers[strtolower(App::buildAppNamespace($appName, ''))])) {
86
-			return $this->appContainers[strtolower(App::buildAppNamespace($appName, ''))];
87
-		}
88
-
89
-		throw new QueryException();
90
-	}
91
-
92
-	/**
93
-	 * @param string $namespace
94
-	 * @param string $sensitiveNamespace
95
-	 * @return DIContainer
96
-	 * @throws QueryException
97
-	 */
98
-	protected function getAppContainer(string $namespace, string $sensitiveNamespace): DIContainer {
99
-		if (isset($this->appContainers[$namespace])) {
100
-			return $this->appContainers[$namespace];
101
-		}
102
-
103
-		if (isset($this->namespaces[$namespace])) {
104
-			if (!isset($this->hasNoAppContainer[$namespace])) {
105
-				$applicationClassName = 'OCA\\' . $sensitiveNamespace . '\\AppInfo\\Application';
106
-				if (class_exists($applicationClassName)) {
107
-					$app = new $applicationClassName();
108
-					if (isset($this->appContainers[$namespace])) {
109
-						$this->appContainers[$namespace]->offsetSet($applicationClassName, $app);
110
-						return $this->appContainers[$namespace];
111
-					}
112
-				}
113
-				$this->hasNoAppContainer[$namespace] = true;
114
-			}
115
-
116
-			return new DIContainer($this->namespaces[$namespace]);
117
-		}
118
-		throw new QueryException();
119
-	}
120
-
121
-	public function has($id, bool $noRecursion = false): bool {
122
-		if (!$noRecursion && ($appContainer = $this->getAppContainerForService($id)) !== null) {
123
-			return $appContainer->has($id);
124
-		}
125
-
126
-		return parent::has($id);
127
-	}
128
-
129
-	/**
130
-	 * @template T
131
-	 * @param class-string<T>|string $name
132
-	 * @return T|mixed
133
-	 * @psalm-template S as class-string<T>|string
134
-	 * @psalm-param S $name
135
-	 * @psalm-return (S is class-string<T> ? T : mixed)
136
-	 * @throws QueryException
137
-	 * @deprecated 20.0.0 use \Psr\Container\ContainerInterface::get
138
-	 */
139
-	public function query(string $name, bool $autoload = true) {
140
-		$name = $this->sanitizeName($name);
141
-
142
-		if (str_starts_with($name, 'OCA\\')) {
143
-			// Skip server container query for app namespace classes
144
-			try {
145
-				return parent::query($name, false);
146
-			} catch (QueryException $e) {
147
-				// Continue with general autoloading then
148
-			}
149
-		}
150
-
151
-		// In case the service starts with OCA\ we try to find the service in
152
-		// the apps container first.
153
-		if (($appContainer = $this->getAppContainerForService($name)) !== null) {
154
-			try {
155
-				return $appContainer->queryNoFallback($name);
156
-			} catch (QueryException $e) {
157
-				// Didn't find the service or the respective app container,
158
-				// ignore it and fall back to the core container.
159
-			}
160
-		} elseif (strpos($name, 'OC\\Settings\\') === 0 && substr_count($name, '\\') >= 3) {
161
-			$segments = explode('\\', $name);
162
-			try {
163
-				$appContainer = $this->getAppContainer(strtolower($segments[1]), $segments[1]);
164
-				return $appContainer->queryNoFallback($name);
165
-			} catch (QueryException $e) {
166
-				// Didn't find the service or the respective app container,
167
-				// ignore it and fall back to the core container.
168
-			}
169
-		}
170
-
171
-		return parent::query($name, $autoload);
172
-	}
173
-
174
-	/**
175
-	 * @internal
176
-	 * @param string $id
177
-	 * @return DIContainer|null
178
-	 */
179
-	public function getAppContainerForService(string $id): ?DIContainer {
180
-		if (strpos($id, 'OCA\\') !== 0 || substr_count($id, '\\') < 2) {
181
-			return null;
182
-		}
183
-
184
-		try {
185
-			[,$namespace,] = explode('\\', $id);
186
-			return $this->getAppContainer(strtolower($namespace), $namespace);
187
-		} catch (QueryException $e) {
188
-			return null;
189
-		}
190
-	}
42
+    /** @var DIContainer[] */
43
+    protected $appContainers;
44
+
45
+    /** @var string[] */
46
+    protected $hasNoAppContainer;
47
+
48
+    /** @var string[] */
49
+    protected $namespaces;
50
+
51
+    /**
52
+     * ServerContainer constructor.
53
+     */
54
+    public function __construct() {
55
+        parent::__construct();
56
+        $this->appContainers = [];
57
+        $this->namespaces = [];
58
+        $this->hasNoAppContainer = [];
59
+    }
60
+
61
+    /**
62
+     * @param string $appName
63
+     * @param string $appNamespace
64
+     */
65
+    public function registerNamespace(string $appName, string $appNamespace): void {
66
+        // Cut of OCA\ and lowercase
67
+        $appNamespace = strtolower(substr($appNamespace, strrpos($appNamespace, '\\') + 1));
68
+        $this->namespaces[$appNamespace] = $appName;
69
+    }
70
+
71
+    /**
72
+     * @param string $appName
73
+     * @param DIContainer $container
74
+     */
75
+    public function registerAppContainer(string $appName, DIContainer $container): void {
76
+        $this->appContainers[strtolower(App::buildAppNamespace($appName, ''))] = $container;
77
+    }
78
+
79
+    /**
80
+     * @param string $appName
81
+     * @return DIContainer
82
+     * @throws QueryException
83
+     */
84
+    public function getRegisteredAppContainer(string $appName): DIContainer {
85
+        if (isset($this->appContainers[strtolower(App::buildAppNamespace($appName, ''))])) {
86
+            return $this->appContainers[strtolower(App::buildAppNamespace($appName, ''))];
87
+        }
88
+
89
+        throw new QueryException();
90
+    }
91
+
92
+    /**
93
+     * @param string $namespace
94
+     * @param string $sensitiveNamespace
95
+     * @return DIContainer
96
+     * @throws QueryException
97
+     */
98
+    protected function getAppContainer(string $namespace, string $sensitiveNamespace): DIContainer {
99
+        if (isset($this->appContainers[$namespace])) {
100
+            return $this->appContainers[$namespace];
101
+        }
102
+
103
+        if (isset($this->namespaces[$namespace])) {
104
+            if (!isset($this->hasNoAppContainer[$namespace])) {
105
+                $applicationClassName = 'OCA\\' . $sensitiveNamespace . '\\AppInfo\\Application';
106
+                if (class_exists($applicationClassName)) {
107
+                    $app = new $applicationClassName();
108
+                    if (isset($this->appContainers[$namespace])) {
109
+                        $this->appContainers[$namespace]->offsetSet($applicationClassName, $app);
110
+                        return $this->appContainers[$namespace];
111
+                    }
112
+                }
113
+                $this->hasNoAppContainer[$namespace] = true;
114
+            }
115
+
116
+            return new DIContainer($this->namespaces[$namespace]);
117
+        }
118
+        throw new QueryException();
119
+    }
120
+
121
+    public function has($id, bool $noRecursion = false): bool {
122
+        if (!$noRecursion && ($appContainer = $this->getAppContainerForService($id)) !== null) {
123
+            return $appContainer->has($id);
124
+        }
125
+
126
+        return parent::has($id);
127
+    }
128
+
129
+    /**
130
+     * @template T
131
+     * @param class-string<T>|string $name
132
+     * @return T|mixed
133
+     * @psalm-template S as class-string<T>|string
134
+     * @psalm-param S $name
135
+     * @psalm-return (S is class-string<T> ? T : mixed)
136
+     * @throws QueryException
137
+     * @deprecated 20.0.0 use \Psr\Container\ContainerInterface::get
138
+     */
139
+    public function query(string $name, bool $autoload = true) {
140
+        $name = $this->sanitizeName($name);
141
+
142
+        if (str_starts_with($name, 'OCA\\')) {
143
+            // Skip server container query for app namespace classes
144
+            try {
145
+                return parent::query($name, false);
146
+            } catch (QueryException $e) {
147
+                // Continue with general autoloading then
148
+            }
149
+        }
150
+
151
+        // In case the service starts with OCA\ we try to find the service in
152
+        // the apps container first.
153
+        if (($appContainer = $this->getAppContainerForService($name)) !== null) {
154
+            try {
155
+                return $appContainer->queryNoFallback($name);
156
+            } catch (QueryException $e) {
157
+                // Didn't find the service or the respective app container,
158
+                // ignore it and fall back to the core container.
159
+            }
160
+        } elseif (strpos($name, 'OC\\Settings\\') === 0 && substr_count($name, '\\') >= 3) {
161
+            $segments = explode('\\', $name);
162
+            try {
163
+                $appContainer = $this->getAppContainer(strtolower($segments[1]), $segments[1]);
164
+                return $appContainer->queryNoFallback($name);
165
+            } catch (QueryException $e) {
166
+                // Didn't find the service or the respective app container,
167
+                // ignore it and fall back to the core container.
168
+            }
169
+        }
170
+
171
+        return parent::query($name, $autoload);
172
+    }
173
+
174
+    /**
175
+     * @internal
176
+     * @param string $id
177
+     * @return DIContainer|null
178
+     */
179
+    public function getAppContainerForService(string $id): ?DIContainer {
180
+        if (strpos($id, 'OCA\\') !== 0 || substr_count($id, '\\') < 2) {
181
+            return null;
182
+        }
183
+
184
+        try {
185
+            [,$namespace,] = explode('\\', $id);
186
+            return $this->getAppContainer(strtolower($namespace), $namespace);
187
+        } catch (QueryException $e) {
188
+            return null;
189
+        }
190
+    }
191 191
 }
Please login to merge, or discard this patch.
lib/private/L10N/Factory.php 1 patch
Indentation   +626 added lines, -626 removed lines patch added patch discarded remove patch
@@ -55,630 +55,630 @@
 block discarded – undo
55 55
  */
56 56
 class Factory implements IFactory {
57 57
 
58
-	/** @var string */
59
-	protected $requestLanguage = '';
60
-
61
-	/**
62
-	 * cached instances
63
-	 * @var array Structure: Lang => App => \OCP\IL10N
64
-	 */
65
-	protected $instances = [];
66
-
67
-	/**
68
-	 * @var array Structure: App => string[]
69
-	 */
70
-	protected $availableLanguages = [];
71
-
72
-	/**
73
-	 * @var array
74
-	 */
75
-	protected $localeCache = [];
76
-
77
-	/**
78
-	 * @var array
79
-	 */
80
-	protected $availableLocales = [];
81
-
82
-	/**
83
-	 * @var array Structure: string => callable
84
-	 */
85
-	protected $pluralFunctions = [];
86
-
87
-	public const COMMON_LANGUAGE_CODES = [
88
-		'en', 'es', 'fr', 'de', 'de_DE', 'ja', 'ar', 'ru', 'nl', 'it',
89
-		'pt_BR', 'pt_PT', 'da', 'fi_FI', 'nb_NO', 'sv', 'tr', 'zh_CN', 'ko'
90
-	];
91
-
92
-	/** @var IConfig */
93
-	protected $config;
94
-
95
-	/** @var IRequest */
96
-	protected $request;
97
-
98
-	/** @var IUserSession */
99
-	protected IUserSession $userSession;
100
-
101
-	private ICache $cache;
102
-
103
-	/** @var string */
104
-	protected $serverRoot;
105
-
106
-	/**
107
-	 * @param IConfig $config
108
-	 * @param IRequest $request
109
-	 * @param IUserSession $userSession
110
-	 * @param string $serverRoot
111
-	 */
112
-	public function __construct(
113
-		IConfig $config,
114
-		IRequest $request,
115
-		IUserSession $userSession,
116
-		ICacheFactory $cacheFactory,
117
-		$serverRoot
118
-	) {
119
-		$this->config = $config;
120
-		$this->request = $request;
121
-		$this->userSession = $userSession;
122
-		$this->cache = $cacheFactory->createLocal('L10NFactory');
123
-		$this->serverRoot = $serverRoot;
124
-	}
125
-
126
-	/**
127
-	 * Get a language instance
128
-	 *
129
-	 * @param string $app
130
-	 * @param string|null $lang
131
-	 * @param string|null $locale
132
-	 * @return \OCP\IL10N
133
-	 */
134
-	public function get($app, $lang = null, $locale = null) {
135
-		return new LazyL10N(function () use ($app, $lang, $locale) {
136
-			$app = \OC_App::cleanAppId($app);
137
-			if ($lang !== null) {
138
-				$lang = str_replace(['\0', '/', '\\', '..'], '', $lang);
139
-			}
140
-
141
-			$forceLang = $this->config->getSystemValue('force_language', false);
142
-			if (is_string($forceLang)) {
143
-				$lang = $forceLang;
144
-			}
145
-
146
-			$forceLocale = $this->config->getSystemValue('force_locale', false);
147
-			if (is_string($forceLocale)) {
148
-				$locale = $forceLocale;
149
-			}
150
-
151
-			if ($lang === null || !$this->languageExists($app, $lang)) {
152
-				$lang = $this->findLanguage($app);
153
-			}
154
-
155
-			if ($locale === null || !$this->localeExists($locale)) {
156
-				$locale = $this->findLocale($lang);
157
-			}
158
-
159
-			if (!isset($this->instances[$lang][$app])) {
160
-				$this->instances[$lang][$app] = new L10N(
161
-					$this,
162
-					$app,
163
-					$lang,
164
-					$locale,
165
-					$this->getL10nFilesForApp($app, $lang)
166
-				);
167
-			}
168
-
169
-			return $this->instances[$lang][$app];
170
-		});
171
-	}
172
-
173
-	/**
174
-	 * Find the best language
175
-	 *
176
-	 * @param string|null $appId App id or null for core
177
-	 *
178
-	 * @return string language If nothing works it returns 'en'
179
-	 */
180
-	public function findLanguage(?string $appId = null): string {
181
-		// Step 1: Forced language always has precedence over anything else
182
-		$forceLang = $this->config->getSystemValue('force_language', false);
183
-		if (is_string($forceLang)) {
184
-			$this->requestLanguage = $forceLang;
185
-		}
186
-
187
-		// Step 2: Return cached language
188
-		if ($this->requestLanguage !== '' && $this->languageExists($appId, $this->requestLanguage)) {
189
-			return $this->requestLanguage;
190
-		}
191
-
192
-		/**
193
-		 * Step 3: At this point Nextcloud might not yet be installed and thus the lookup
194
-		 * in the preferences table might fail. For this reason we need to check
195
-		 * whether the instance has already been installed
196
-		 *
197
-		 * @link https://github.com/owncloud/core/issues/21955
198
-		 */
199
-		if ($this->config->getSystemValue('installed', false)) {
200
-			$userId = !is_null($this->userSession->getUser()) ? $this->userSession->getUser()->getUID() :  null;
201
-			if (!is_null($userId)) {
202
-				$userLang = $this->config->getUserValue($userId, 'core', 'lang', null);
203
-			} else {
204
-				$userLang = null;
205
-			}
206
-		} else {
207
-			$userId = null;
208
-			$userLang = null;
209
-		}
210
-		if ($userLang) {
211
-			$this->requestLanguage = $userLang;
212
-			if ($this->languageExists($appId, $userLang)) {
213
-				return $userLang;
214
-			}
215
-		}
216
-
217
-		// Step 4: Check the request headers
218
-		try {
219
-			// Try to get the language from the Request
220
-			$lang = $this->getLanguageFromRequest($appId);
221
-			if ($userId !== null && $appId === null && !$userLang) {
222
-				$this->config->setUserValue($userId, 'core', 'lang', $lang);
223
-			}
224
-			return $lang;
225
-		} catch (LanguageNotFoundException $e) {
226
-			// Finding language from request failed fall back to default language
227
-			$defaultLanguage = $this->config->getSystemValue('default_language', false);
228
-			if ($defaultLanguage !== false && $this->languageExists($appId, $defaultLanguage)) {
229
-				return $defaultLanguage;
230
-			}
231
-		}
232
-
233
-		// Step 5: fall back to English
234
-		return 'en';
235
-	}
236
-
237
-	public function findGenericLanguage(string $appId = null): string {
238
-		// Step 1: Forced language always has precedence over anything else
239
-		$forcedLanguage = $this->config->getSystemValue('force_language', false);
240
-		if ($forcedLanguage !== false) {
241
-			return $forcedLanguage;
242
-		}
243
-
244
-		// Step 2: Check if we have a default language
245
-		$defaultLanguage = $this->config->getSystemValue('default_language', false);
246
-		if ($defaultLanguage !== false && $this->languageExists($appId, $defaultLanguage)) {
247
-			return $defaultLanguage;
248
-		}
249
-
250
-		// Step 3.1: Check if Nextcloud is already installed before we try to access user info
251
-		if (!$this->config->getSystemValue('installed', false)) {
252
-			return 'en';
253
-		}
254
-		// Step 3.2: Check the current user (if any) for their preferred language
255
-		$user = $this->userSession->getUser();
256
-		if ($user !== null) {
257
-			$userLang = $this->config->getUserValue($user->getUID(), 'core', 'lang', null);
258
-			if ($userLang !== null) {
259
-				return $userLang;
260
-			}
261
-		}
262
-
263
-		// Step 4: Check the request headers
264
-		try {
265
-			return $this->getLanguageFromRequest($appId);
266
-		} catch (LanguageNotFoundException $e) {
267
-			// Ignore and continue
268
-		}
269
-
270
-		// Step 5: fall back to English
271
-		return 'en';
272
-	}
273
-
274
-	/**
275
-	 * find the best locale
276
-	 *
277
-	 * @param string $lang
278
-	 * @return null|string
279
-	 */
280
-	public function findLocale($lang = null) {
281
-		$forceLocale = $this->config->getSystemValue('force_locale', false);
282
-		if (is_string($forceLocale) && $this->localeExists($forceLocale)) {
283
-			return $forceLocale;
284
-		}
285
-
286
-		if ($this->config->getSystemValue('installed', false)) {
287
-			$userId = null !== $this->userSession->getUser() ? $this->userSession->getUser()->getUID() :  null;
288
-			$userLocale = null;
289
-			if (null !== $userId) {
290
-				$userLocale = $this->config->getUserValue($userId, 'core', 'locale', null);
291
-			}
292
-		} else {
293
-			$userId = null;
294
-			$userLocale = null;
295
-		}
296
-
297
-		if ($userLocale && $this->localeExists($userLocale)) {
298
-			return $userLocale;
299
-		}
300
-
301
-		// Default : use system default locale
302
-		$defaultLocale = $this->config->getSystemValue('default_locale', false);
303
-		if ($defaultLocale !== false && $this->localeExists($defaultLocale)) {
304
-			return $defaultLocale;
305
-		}
306
-
307
-		// If no user locale set, use lang as locale
308
-		if (null !== $lang && $this->localeExists($lang)) {
309
-			return $lang;
310
-		}
311
-
312
-		// At last, return USA
313
-		return 'en_US';
314
-	}
315
-
316
-	/**
317
-	 * find the matching lang from the locale
318
-	 *
319
-	 * @param string $app
320
-	 * @param string $locale
321
-	 * @return null|string
322
-	 */
323
-	public function findLanguageFromLocale(string $app = 'core', string $locale = null) {
324
-		if ($this->languageExists($app, $locale)) {
325
-			return $locale;
326
-		}
327
-
328
-		// Try to split e.g: fr_FR => fr
329
-		$locale = explode('_', $locale)[0];
330
-		if ($this->languageExists($app, $locale)) {
331
-			return $locale;
332
-		}
333
-	}
334
-
335
-	/**
336
-	 * Find all available languages for an app
337
-	 *
338
-	 * @param string|null $app App id or null for core
339
-	 * @return string[] an array of available languages
340
-	 */
341
-	public function findAvailableLanguages($app = null): array {
342
-		$key = $app;
343
-		if ($key === null) {
344
-			$key = 'null';
345
-		}
346
-
347
-		if ($availableLanguages = $this->cache->get($key)) {
348
-			$this->availableLanguages[$key] = $availableLanguages;
349
-		}
350
-
351
-		// also works with null as key
352
-		if (!empty($this->availableLanguages[$key])) {
353
-			return $this->availableLanguages[$key];
354
-		}
355
-
356
-		$available = ['en']; //english is always available
357
-		$dir = $this->findL10nDir($app);
358
-		if (is_dir($dir)) {
359
-			$files = scandir($dir);
360
-			if ($files !== false) {
361
-				foreach ($files as $file) {
362
-					if (substr($file, -5) === '.json' && substr($file, 0, 4) !== 'l10n') {
363
-						$available[] = substr($file, 0, -5);
364
-					}
365
-				}
366
-			}
367
-		}
368
-
369
-		// merge with translations from theme
370
-		$theme = $this->config->getSystemValue('theme');
371
-		if (!empty($theme)) {
372
-			$themeDir = $this->serverRoot . '/themes/' . $theme . substr($dir, strlen($this->serverRoot));
373
-
374
-			if (is_dir($themeDir)) {
375
-				$files = scandir($themeDir);
376
-				if ($files !== false) {
377
-					foreach ($files as $file) {
378
-						if (substr($file, -5) === '.json' && substr($file, 0, 4) !== 'l10n') {
379
-							$available[] = substr($file, 0, -5);
380
-						}
381
-					}
382
-				}
383
-			}
384
-		}
385
-
386
-		$this->availableLanguages[$key] = $available;
387
-		$this->cache->set($key, $available, 60);
388
-		return $available;
389
-	}
390
-
391
-	/**
392
-	 * @return array|mixed
393
-	 */
394
-	public function findAvailableLocales() {
395
-		if (!empty($this->availableLocales)) {
396
-			return $this->availableLocales;
397
-		}
398
-
399
-		$localeData = file_get_contents(\OC::$SERVERROOT . '/resources/locales.json');
400
-		$this->availableLocales = \json_decode($localeData, true);
401
-
402
-		return $this->availableLocales;
403
-	}
404
-
405
-	/**
406
-	 * @param string|null $app App id or null for core
407
-	 * @param string $lang
408
-	 * @return bool
409
-	 */
410
-	public function languageExists($app, $lang) {
411
-		if ($lang === 'en') { //english is always available
412
-			return true;
413
-		}
414
-
415
-		$languages = $this->findAvailableLanguages($app);
416
-		return in_array($lang, $languages);
417
-	}
418
-
419
-	public function getLanguageIterator(IUser $user = null): ILanguageIterator {
420
-		$user = $user ?? $this->userSession->getUser();
421
-		if ($user === null) {
422
-			throw new \RuntimeException('Failed to get an IUser instance');
423
-		}
424
-		return new LanguageIterator($user, $this->config);
425
-	}
426
-
427
-	/**
428
-	 * Return the language to use when sending something to a user
429
-	 *
430
-	 * @param IUser|null $user
431
-	 * @return string
432
-	 * @since 20.0.0
433
-	 */
434
-	public function getUserLanguage(IUser $user = null): string {
435
-		$language = $this->config->getSystemValue('force_language', false);
436
-		if ($language !== false) {
437
-			return $language;
438
-		}
439
-
440
-		if ($user instanceof IUser) {
441
-			$language = $this->config->getUserValue($user->getUID(), 'core', 'lang', null);
442
-			if ($language !== null) {
443
-				return $language;
444
-			}
445
-
446
-			// Use language from request
447
-			if ($this->userSession->getUser() instanceof IUser &&
448
-				$user->getUID() === $this->userSession->getUser()->getUID()) {
449
-				try {
450
-					return $this->getLanguageFromRequest();
451
-				} catch (LanguageNotFoundException $e) {
452
-				}
453
-			}
454
-		}
455
-
456
-		return $this->config->getSystemValue('default_language', 'en');
457
-	}
458
-
459
-	/**
460
-	 * @param string $locale
461
-	 * @return bool
462
-	 */
463
-	public function localeExists($locale) {
464
-		if ($locale === 'en') { //english is always available
465
-			return true;
466
-		}
467
-
468
-		if ($this->localeCache === []) {
469
-			$locales = $this->findAvailableLocales();
470
-			foreach ($locales as $l) {
471
-				$this->localeCache[$l['code']] = true;
472
-			}
473
-		}
474
-
475
-		return isset($this->localeCache[$locale]);
476
-	}
477
-
478
-	/**
479
-	 * @throws LanguageNotFoundException
480
-	 */
481
-	private function getLanguageFromRequest(?string $app = null): string {
482
-		$header = $this->request->getHeader('ACCEPT_LANGUAGE');
483
-		if ($header !== '') {
484
-			$available = $this->findAvailableLanguages($app);
485
-
486
-			// E.g. make sure that 'de' is before 'de_DE'.
487
-			sort($available);
488
-
489
-			$preferences = preg_split('/,\s*/', strtolower($header));
490
-			foreach ($preferences as $preference) {
491
-				[$preferred_language] = explode(';', $preference);
492
-				$preferred_language = str_replace('-', '_', $preferred_language);
493
-
494
-				foreach ($available as $available_language) {
495
-					if ($preferred_language === strtolower($available_language)) {
496
-						return $this->respectDefaultLanguage($app, $available_language);
497
-					}
498
-				}
499
-
500
-				// Fallback from de_De to de
501
-				foreach ($available as $available_language) {
502
-					if (substr($preferred_language, 0, 2) === $available_language) {
503
-						return $available_language;
504
-					}
505
-				}
506
-			}
507
-		}
508
-
509
-		throw new LanguageNotFoundException();
510
-	}
511
-
512
-	/**
513
-	 * if default language is set to de_DE (formal German) this should be
514
-	 * preferred to 'de' (non-formal German) if possible
515
-	 */
516
-	protected function respectDefaultLanguage(?string $app, string $lang): string {
517
-		$result = $lang;
518
-		$defaultLanguage = $this->config->getSystemValue('default_language', false);
519
-
520
-		// use formal version of german ("Sie" instead of "Du") if the default
521
-		// language is set to 'de_DE' if possible
522
-		if (
523
-			is_string($defaultLanguage) &&
524
-			strtolower($lang) === 'de' &&
525
-			strtolower($defaultLanguage) === 'de_de' &&
526
-			$this->languageExists($app, 'de_DE')
527
-		) {
528
-			$result = 'de_DE';
529
-		}
530
-
531
-		return $result;
532
-	}
533
-
534
-	/**
535
-	 * Checks if $sub is a subdirectory of $parent
536
-	 *
537
-	 * @param string $sub
538
-	 * @param string $parent
539
-	 * @return bool
540
-	 */
541
-	private function isSubDirectory($sub, $parent) {
542
-		// Check whether $sub contains no ".."
543
-		if (strpos($sub, '..') !== false) {
544
-			return false;
545
-		}
546
-
547
-		// Check whether $sub is a subdirectory of $parent
548
-		if (strpos($sub, $parent) === 0) {
549
-			return true;
550
-		}
551
-
552
-		return false;
553
-	}
554
-
555
-	/**
556
-	 * Get a list of language files that should be loaded
557
-	 *
558
-	 * @param string $app
559
-	 * @param string $lang
560
-	 * @return string[]
561
-	 */
562
-	// FIXME This method is only public, until OC_L10N does not need it anymore,
563
-	// FIXME This is also the reason, why it is not in the public interface
564
-	public function getL10nFilesForApp($app, $lang) {
565
-		$languageFiles = [];
566
-
567
-		$i18nDir = $this->findL10nDir($app);
568
-		$transFile = strip_tags($i18nDir) . strip_tags($lang) . '.json';
569
-
570
-		if (($this->isSubDirectory($transFile, $this->serverRoot . '/core/l10n/')
571
-				|| $this->isSubDirectory($transFile, $this->serverRoot . '/lib/l10n/')
572
-				|| $this->isSubDirectory($transFile, \OC_App::getAppPath($app) . '/l10n/'))
573
-			&& file_exists($transFile)
574
-		) {
575
-			// load the translations file
576
-			$languageFiles[] = $transFile;
577
-		}
578
-
579
-		// merge with translations from theme
580
-		$theme = $this->config->getSystemValue('theme');
581
-		if (!empty($theme)) {
582
-			$transFile = $this->serverRoot . '/themes/' . $theme . substr($transFile, strlen($this->serverRoot));
583
-			if (file_exists($transFile)) {
584
-				$languageFiles[] = $transFile;
585
-			}
586
-		}
587
-
588
-		return $languageFiles;
589
-	}
590
-
591
-	/**
592
-	 * find the l10n directory
593
-	 *
594
-	 * @param string $app App id or empty string for core
595
-	 * @return string directory
596
-	 */
597
-	protected function findL10nDir($app = null) {
598
-		if (in_array($app, ['core', 'lib'])) {
599
-			if (file_exists($this->serverRoot . '/' . $app . '/l10n/')) {
600
-				return $this->serverRoot . '/' . $app . '/l10n/';
601
-			}
602
-		} elseif ($app && \OC_App::getAppPath($app) !== false) {
603
-			// Check if the app is in the app folder
604
-			return \OC_App::getAppPath($app) . '/l10n/';
605
-		}
606
-		return $this->serverRoot . '/core/l10n/';
607
-	}
608
-
609
-	/**
610
-	 * @inheritDoc
611
-	 */
612
-	public function getLanguages(): array {
613
-		$forceLanguage = $this->config->getSystemValue('force_language', false);
614
-		if ($forceLanguage !== false) {
615
-			$l = $this->get('lib', $forceLanguage);
616
-			$potentialName = $l->t('__language_name__');
617
-
618
-			return [
619
-				'commonLanguages' => [[
620
-					'code' => $forceLanguage,
621
-					'name' => $potentialName,
622
-				]],
623
-				'otherLanguages' => [],
624
-			];
625
-		}
626
-
627
-		$languageCodes = $this->findAvailableLanguages();
628
-
629
-		$commonLanguages = [];
630
-		$otherLanguages = [];
631
-
632
-		foreach ($languageCodes as $lang) {
633
-			$l = $this->get('lib', $lang);
634
-			// TRANSLATORS this is the language name for the language switcher in the personal settings and should be the localized version
635
-			$potentialName = $l->t('__language_name__');
636
-			if ($l->getLanguageCode() === $lang && $potentialName[0] !== '_') { //first check if the language name is in the translation file
637
-				$ln = [
638
-					'code' => $lang,
639
-					'name' => $potentialName
640
-				];
641
-			} elseif ($lang === 'en') {
642
-				$ln = [
643
-					'code' => $lang,
644
-					'name' => 'English (US)'
645
-				];
646
-			} else { //fallback to language code
647
-				$ln = [
648
-					'code' => $lang,
649
-					'name' => $lang
650
-				];
651
-			}
652
-
653
-			// put appropriate languages into appropriate arrays, to print them sorted
654
-			// common languages -> divider -> other languages
655
-			if (in_array($lang, self::COMMON_LANGUAGE_CODES)) {
656
-				$commonLanguages[array_search($lang, self::COMMON_LANGUAGE_CODES)] = $ln;
657
-			} else {
658
-				$otherLanguages[] = $ln;
659
-			}
660
-		}
661
-
662
-		ksort($commonLanguages);
663
-
664
-		// sort now by displayed language not the iso-code
665
-		usort($otherLanguages, function ($a, $b) {
666
-			if ($a['code'] === $a['name'] && $b['code'] !== $b['name']) {
667
-				// If a doesn't have a name, but b does, list b before a
668
-				return 1;
669
-			}
670
-			if ($a['code'] !== $a['name'] && $b['code'] === $b['name']) {
671
-				// If a does have a name, but b doesn't, list a before b
672
-				return -1;
673
-			}
674
-			// Otherwise compare the names
675
-			return strcmp($a['name'], $b['name']);
676
-		});
677
-
678
-		return [
679
-			// reset indexes
680
-			'commonLanguages' => array_values($commonLanguages),
681
-			'otherLanguages' => $otherLanguages
682
-		];
683
-	}
58
+    /** @var string */
59
+    protected $requestLanguage = '';
60
+
61
+    /**
62
+     * cached instances
63
+     * @var array Structure: Lang => App => \OCP\IL10N
64
+     */
65
+    protected $instances = [];
66
+
67
+    /**
68
+     * @var array Structure: App => string[]
69
+     */
70
+    protected $availableLanguages = [];
71
+
72
+    /**
73
+     * @var array
74
+     */
75
+    protected $localeCache = [];
76
+
77
+    /**
78
+     * @var array
79
+     */
80
+    protected $availableLocales = [];
81
+
82
+    /**
83
+     * @var array Structure: string => callable
84
+     */
85
+    protected $pluralFunctions = [];
86
+
87
+    public const COMMON_LANGUAGE_CODES = [
88
+        'en', 'es', 'fr', 'de', 'de_DE', 'ja', 'ar', 'ru', 'nl', 'it',
89
+        'pt_BR', 'pt_PT', 'da', 'fi_FI', 'nb_NO', 'sv', 'tr', 'zh_CN', 'ko'
90
+    ];
91
+
92
+    /** @var IConfig */
93
+    protected $config;
94
+
95
+    /** @var IRequest */
96
+    protected $request;
97
+
98
+    /** @var IUserSession */
99
+    protected IUserSession $userSession;
100
+
101
+    private ICache $cache;
102
+
103
+    /** @var string */
104
+    protected $serverRoot;
105
+
106
+    /**
107
+     * @param IConfig $config
108
+     * @param IRequest $request
109
+     * @param IUserSession $userSession
110
+     * @param string $serverRoot
111
+     */
112
+    public function __construct(
113
+        IConfig $config,
114
+        IRequest $request,
115
+        IUserSession $userSession,
116
+        ICacheFactory $cacheFactory,
117
+        $serverRoot
118
+    ) {
119
+        $this->config = $config;
120
+        $this->request = $request;
121
+        $this->userSession = $userSession;
122
+        $this->cache = $cacheFactory->createLocal('L10NFactory');
123
+        $this->serverRoot = $serverRoot;
124
+    }
125
+
126
+    /**
127
+     * Get a language instance
128
+     *
129
+     * @param string $app
130
+     * @param string|null $lang
131
+     * @param string|null $locale
132
+     * @return \OCP\IL10N
133
+     */
134
+    public function get($app, $lang = null, $locale = null) {
135
+        return new LazyL10N(function () use ($app, $lang, $locale) {
136
+            $app = \OC_App::cleanAppId($app);
137
+            if ($lang !== null) {
138
+                $lang = str_replace(['\0', '/', '\\', '..'], '', $lang);
139
+            }
140
+
141
+            $forceLang = $this->config->getSystemValue('force_language', false);
142
+            if (is_string($forceLang)) {
143
+                $lang = $forceLang;
144
+            }
145
+
146
+            $forceLocale = $this->config->getSystemValue('force_locale', false);
147
+            if (is_string($forceLocale)) {
148
+                $locale = $forceLocale;
149
+            }
150
+
151
+            if ($lang === null || !$this->languageExists($app, $lang)) {
152
+                $lang = $this->findLanguage($app);
153
+            }
154
+
155
+            if ($locale === null || !$this->localeExists($locale)) {
156
+                $locale = $this->findLocale($lang);
157
+            }
158
+
159
+            if (!isset($this->instances[$lang][$app])) {
160
+                $this->instances[$lang][$app] = new L10N(
161
+                    $this,
162
+                    $app,
163
+                    $lang,
164
+                    $locale,
165
+                    $this->getL10nFilesForApp($app, $lang)
166
+                );
167
+            }
168
+
169
+            return $this->instances[$lang][$app];
170
+        });
171
+    }
172
+
173
+    /**
174
+     * Find the best language
175
+     *
176
+     * @param string|null $appId App id or null for core
177
+     *
178
+     * @return string language If nothing works it returns 'en'
179
+     */
180
+    public function findLanguage(?string $appId = null): string {
181
+        // Step 1: Forced language always has precedence over anything else
182
+        $forceLang = $this->config->getSystemValue('force_language', false);
183
+        if (is_string($forceLang)) {
184
+            $this->requestLanguage = $forceLang;
185
+        }
186
+
187
+        // Step 2: Return cached language
188
+        if ($this->requestLanguage !== '' && $this->languageExists($appId, $this->requestLanguage)) {
189
+            return $this->requestLanguage;
190
+        }
191
+
192
+        /**
193
+         * Step 3: At this point Nextcloud might not yet be installed and thus the lookup
194
+         * in the preferences table might fail. For this reason we need to check
195
+         * whether the instance has already been installed
196
+         *
197
+         * @link https://github.com/owncloud/core/issues/21955
198
+         */
199
+        if ($this->config->getSystemValue('installed', false)) {
200
+            $userId = !is_null($this->userSession->getUser()) ? $this->userSession->getUser()->getUID() :  null;
201
+            if (!is_null($userId)) {
202
+                $userLang = $this->config->getUserValue($userId, 'core', 'lang', null);
203
+            } else {
204
+                $userLang = null;
205
+            }
206
+        } else {
207
+            $userId = null;
208
+            $userLang = null;
209
+        }
210
+        if ($userLang) {
211
+            $this->requestLanguage = $userLang;
212
+            if ($this->languageExists($appId, $userLang)) {
213
+                return $userLang;
214
+            }
215
+        }
216
+
217
+        // Step 4: Check the request headers
218
+        try {
219
+            // Try to get the language from the Request
220
+            $lang = $this->getLanguageFromRequest($appId);
221
+            if ($userId !== null && $appId === null && !$userLang) {
222
+                $this->config->setUserValue($userId, 'core', 'lang', $lang);
223
+            }
224
+            return $lang;
225
+        } catch (LanguageNotFoundException $e) {
226
+            // Finding language from request failed fall back to default language
227
+            $defaultLanguage = $this->config->getSystemValue('default_language', false);
228
+            if ($defaultLanguage !== false && $this->languageExists($appId, $defaultLanguage)) {
229
+                return $defaultLanguage;
230
+            }
231
+        }
232
+
233
+        // Step 5: fall back to English
234
+        return 'en';
235
+    }
236
+
237
+    public function findGenericLanguage(string $appId = null): string {
238
+        // Step 1: Forced language always has precedence over anything else
239
+        $forcedLanguage = $this->config->getSystemValue('force_language', false);
240
+        if ($forcedLanguage !== false) {
241
+            return $forcedLanguage;
242
+        }
243
+
244
+        // Step 2: Check if we have a default language
245
+        $defaultLanguage = $this->config->getSystemValue('default_language', false);
246
+        if ($defaultLanguage !== false && $this->languageExists($appId, $defaultLanguage)) {
247
+            return $defaultLanguage;
248
+        }
249
+
250
+        // Step 3.1: Check if Nextcloud is already installed before we try to access user info
251
+        if (!$this->config->getSystemValue('installed', false)) {
252
+            return 'en';
253
+        }
254
+        // Step 3.2: Check the current user (if any) for their preferred language
255
+        $user = $this->userSession->getUser();
256
+        if ($user !== null) {
257
+            $userLang = $this->config->getUserValue($user->getUID(), 'core', 'lang', null);
258
+            if ($userLang !== null) {
259
+                return $userLang;
260
+            }
261
+        }
262
+
263
+        // Step 4: Check the request headers
264
+        try {
265
+            return $this->getLanguageFromRequest($appId);
266
+        } catch (LanguageNotFoundException $e) {
267
+            // Ignore and continue
268
+        }
269
+
270
+        // Step 5: fall back to English
271
+        return 'en';
272
+    }
273
+
274
+    /**
275
+     * find the best locale
276
+     *
277
+     * @param string $lang
278
+     * @return null|string
279
+     */
280
+    public function findLocale($lang = null) {
281
+        $forceLocale = $this->config->getSystemValue('force_locale', false);
282
+        if (is_string($forceLocale) && $this->localeExists($forceLocale)) {
283
+            return $forceLocale;
284
+        }
285
+
286
+        if ($this->config->getSystemValue('installed', false)) {
287
+            $userId = null !== $this->userSession->getUser() ? $this->userSession->getUser()->getUID() :  null;
288
+            $userLocale = null;
289
+            if (null !== $userId) {
290
+                $userLocale = $this->config->getUserValue($userId, 'core', 'locale', null);
291
+            }
292
+        } else {
293
+            $userId = null;
294
+            $userLocale = null;
295
+        }
296
+
297
+        if ($userLocale && $this->localeExists($userLocale)) {
298
+            return $userLocale;
299
+        }
300
+
301
+        // Default : use system default locale
302
+        $defaultLocale = $this->config->getSystemValue('default_locale', false);
303
+        if ($defaultLocale !== false && $this->localeExists($defaultLocale)) {
304
+            return $defaultLocale;
305
+        }
306
+
307
+        // If no user locale set, use lang as locale
308
+        if (null !== $lang && $this->localeExists($lang)) {
309
+            return $lang;
310
+        }
311
+
312
+        // At last, return USA
313
+        return 'en_US';
314
+    }
315
+
316
+    /**
317
+     * find the matching lang from the locale
318
+     *
319
+     * @param string $app
320
+     * @param string $locale
321
+     * @return null|string
322
+     */
323
+    public function findLanguageFromLocale(string $app = 'core', string $locale = null) {
324
+        if ($this->languageExists($app, $locale)) {
325
+            return $locale;
326
+        }
327
+
328
+        // Try to split e.g: fr_FR => fr
329
+        $locale = explode('_', $locale)[0];
330
+        if ($this->languageExists($app, $locale)) {
331
+            return $locale;
332
+        }
333
+    }
334
+
335
+    /**
336
+     * Find all available languages for an app
337
+     *
338
+     * @param string|null $app App id or null for core
339
+     * @return string[] an array of available languages
340
+     */
341
+    public function findAvailableLanguages($app = null): array {
342
+        $key = $app;
343
+        if ($key === null) {
344
+            $key = 'null';
345
+        }
346
+
347
+        if ($availableLanguages = $this->cache->get($key)) {
348
+            $this->availableLanguages[$key] = $availableLanguages;
349
+        }
350
+
351
+        // also works with null as key
352
+        if (!empty($this->availableLanguages[$key])) {
353
+            return $this->availableLanguages[$key];
354
+        }
355
+
356
+        $available = ['en']; //english is always available
357
+        $dir = $this->findL10nDir($app);
358
+        if (is_dir($dir)) {
359
+            $files = scandir($dir);
360
+            if ($files !== false) {
361
+                foreach ($files as $file) {
362
+                    if (substr($file, -5) === '.json' && substr($file, 0, 4) !== 'l10n') {
363
+                        $available[] = substr($file, 0, -5);
364
+                    }
365
+                }
366
+            }
367
+        }
368
+
369
+        // merge with translations from theme
370
+        $theme = $this->config->getSystemValue('theme');
371
+        if (!empty($theme)) {
372
+            $themeDir = $this->serverRoot . '/themes/' . $theme . substr($dir, strlen($this->serverRoot));
373
+
374
+            if (is_dir($themeDir)) {
375
+                $files = scandir($themeDir);
376
+                if ($files !== false) {
377
+                    foreach ($files as $file) {
378
+                        if (substr($file, -5) === '.json' && substr($file, 0, 4) !== 'l10n') {
379
+                            $available[] = substr($file, 0, -5);
380
+                        }
381
+                    }
382
+                }
383
+            }
384
+        }
385
+
386
+        $this->availableLanguages[$key] = $available;
387
+        $this->cache->set($key, $available, 60);
388
+        return $available;
389
+    }
390
+
391
+    /**
392
+     * @return array|mixed
393
+     */
394
+    public function findAvailableLocales() {
395
+        if (!empty($this->availableLocales)) {
396
+            return $this->availableLocales;
397
+        }
398
+
399
+        $localeData = file_get_contents(\OC::$SERVERROOT . '/resources/locales.json');
400
+        $this->availableLocales = \json_decode($localeData, true);
401
+
402
+        return $this->availableLocales;
403
+    }
404
+
405
+    /**
406
+     * @param string|null $app App id or null for core
407
+     * @param string $lang
408
+     * @return bool
409
+     */
410
+    public function languageExists($app, $lang) {
411
+        if ($lang === 'en') { //english is always available
412
+            return true;
413
+        }
414
+
415
+        $languages = $this->findAvailableLanguages($app);
416
+        return in_array($lang, $languages);
417
+    }
418
+
419
+    public function getLanguageIterator(IUser $user = null): ILanguageIterator {
420
+        $user = $user ?? $this->userSession->getUser();
421
+        if ($user === null) {
422
+            throw new \RuntimeException('Failed to get an IUser instance');
423
+        }
424
+        return new LanguageIterator($user, $this->config);
425
+    }
426
+
427
+    /**
428
+     * Return the language to use when sending something to a user
429
+     *
430
+     * @param IUser|null $user
431
+     * @return string
432
+     * @since 20.0.0
433
+     */
434
+    public function getUserLanguage(IUser $user = null): string {
435
+        $language = $this->config->getSystemValue('force_language', false);
436
+        if ($language !== false) {
437
+            return $language;
438
+        }
439
+
440
+        if ($user instanceof IUser) {
441
+            $language = $this->config->getUserValue($user->getUID(), 'core', 'lang', null);
442
+            if ($language !== null) {
443
+                return $language;
444
+            }
445
+
446
+            // Use language from request
447
+            if ($this->userSession->getUser() instanceof IUser &&
448
+                $user->getUID() === $this->userSession->getUser()->getUID()) {
449
+                try {
450
+                    return $this->getLanguageFromRequest();
451
+                } catch (LanguageNotFoundException $e) {
452
+                }
453
+            }
454
+        }
455
+
456
+        return $this->config->getSystemValue('default_language', 'en');
457
+    }
458
+
459
+    /**
460
+     * @param string $locale
461
+     * @return bool
462
+     */
463
+    public function localeExists($locale) {
464
+        if ($locale === 'en') { //english is always available
465
+            return true;
466
+        }
467
+
468
+        if ($this->localeCache === []) {
469
+            $locales = $this->findAvailableLocales();
470
+            foreach ($locales as $l) {
471
+                $this->localeCache[$l['code']] = true;
472
+            }
473
+        }
474
+
475
+        return isset($this->localeCache[$locale]);
476
+    }
477
+
478
+    /**
479
+     * @throws LanguageNotFoundException
480
+     */
481
+    private function getLanguageFromRequest(?string $app = null): string {
482
+        $header = $this->request->getHeader('ACCEPT_LANGUAGE');
483
+        if ($header !== '') {
484
+            $available = $this->findAvailableLanguages($app);
485
+
486
+            // E.g. make sure that 'de' is before 'de_DE'.
487
+            sort($available);
488
+
489
+            $preferences = preg_split('/,\s*/', strtolower($header));
490
+            foreach ($preferences as $preference) {
491
+                [$preferred_language] = explode(';', $preference);
492
+                $preferred_language = str_replace('-', '_', $preferred_language);
493
+
494
+                foreach ($available as $available_language) {
495
+                    if ($preferred_language === strtolower($available_language)) {
496
+                        return $this->respectDefaultLanguage($app, $available_language);
497
+                    }
498
+                }
499
+
500
+                // Fallback from de_De to de
501
+                foreach ($available as $available_language) {
502
+                    if (substr($preferred_language, 0, 2) === $available_language) {
503
+                        return $available_language;
504
+                    }
505
+                }
506
+            }
507
+        }
508
+
509
+        throw new LanguageNotFoundException();
510
+    }
511
+
512
+    /**
513
+     * if default language is set to de_DE (formal German) this should be
514
+     * preferred to 'de' (non-formal German) if possible
515
+     */
516
+    protected function respectDefaultLanguage(?string $app, string $lang): string {
517
+        $result = $lang;
518
+        $defaultLanguage = $this->config->getSystemValue('default_language', false);
519
+
520
+        // use formal version of german ("Sie" instead of "Du") if the default
521
+        // language is set to 'de_DE' if possible
522
+        if (
523
+            is_string($defaultLanguage) &&
524
+            strtolower($lang) === 'de' &&
525
+            strtolower($defaultLanguage) === 'de_de' &&
526
+            $this->languageExists($app, 'de_DE')
527
+        ) {
528
+            $result = 'de_DE';
529
+        }
530
+
531
+        return $result;
532
+    }
533
+
534
+    /**
535
+     * Checks if $sub is a subdirectory of $parent
536
+     *
537
+     * @param string $sub
538
+     * @param string $parent
539
+     * @return bool
540
+     */
541
+    private function isSubDirectory($sub, $parent) {
542
+        // Check whether $sub contains no ".."
543
+        if (strpos($sub, '..') !== false) {
544
+            return false;
545
+        }
546
+
547
+        // Check whether $sub is a subdirectory of $parent
548
+        if (strpos($sub, $parent) === 0) {
549
+            return true;
550
+        }
551
+
552
+        return false;
553
+    }
554
+
555
+    /**
556
+     * Get a list of language files that should be loaded
557
+     *
558
+     * @param string $app
559
+     * @param string $lang
560
+     * @return string[]
561
+     */
562
+    // FIXME This method is only public, until OC_L10N does not need it anymore,
563
+    // FIXME This is also the reason, why it is not in the public interface
564
+    public function getL10nFilesForApp($app, $lang) {
565
+        $languageFiles = [];
566
+
567
+        $i18nDir = $this->findL10nDir($app);
568
+        $transFile = strip_tags($i18nDir) . strip_tags($lang) . '.json';
569
+
570
+        if (($this->isSubDirectory($transFile, $this->serverRoot . '/core/l10n/')
571
+                || $this->isSubDirectory($transFile, $this->serverRoot . '/lib/l10n/')
572
+                || $this->isSubDirectory($transFile, \OC_App::getAppPath($app) . '/l10n/'))
573
+            && file_exists($transFile)
574
+        ) {
575
+            // load the translations file
576
+            $languageFiles[] = $transFile;
577
+        }
578
+
579
+        // merge with translations from theme
580
+        $theme = $this->config->getSystemValue('theme');
581
+        if (!empty($theme)) {
582
+            $transFile = $this->serverRoot . '/themes/' . $theme . substr($transFile, strlen($this->serverRoot));
583
+            if (file_exists($transFile)) {
584
+                $languageFiles[] = $transFile;
585
+            }
586
+        }
587
+
588
+        return $languageFiles;
589
+    }
590
+
591
+    /**
592
+     * find the l10n directory
593
+     *
594
+     * @param string $app App id or empty string for core
595
+     * @return string directory
596
+     */
597
+    protected function findL10nDir($app = null) {
598
+        if (in_array($app, ['core', 'lib'])) {
599
+            if (file_exists($this->serverRoot . '/' . $app . '/l10n/')) {
600
+                return $this->serverRoot . '/' . $app . '/l10n/';
601
+            }
602
+        } elseif ($app && \OC_App::getAppPath($app) !== false) {
603
+            // Check if the app is in the app folder
604
+            return \OC_App::getAppPath($app) . '/l10n/';
605
+        }
606
+        return $this->serverRoot . '/core/l10n/';
607
+    }
608
+
609
+    /**
610
+     * @inheritDoc
611
+     */
612
+    public function getLanguages(): array {
613
+        $forceLanguage = $this->config->getSystemValue('force_language', false);
614
+        if ($forceLanguage !== false) {
615
+            $l = $this->get('lib', $forceLanguage);
616
+            $potentialName = $l->t('__language_name__');
617
+
618
+            return [
619
+                'commonLanguages' => [[
620
+                    'code' => $forceLanguage,
621
+                    'name' => $potentialName,
622
+                ]],
623
+                'otherLanguages' => [],
624
+            ];
625
+        }
626
+
627
+        $languageCodes = $this->findAvailableLanguages();
628
+
629
+        $commonLanguages = [];
630
+        $otherLanguages = [];
631
+
632
+        foreach ($languageCodes as $lang) {
633
+            $l = $this->get('lib', $lang);
634
+            // TRANSLATORS this is the language name for the language switcher in the personal settings and should be the localized version
635
+            $potentialName = $l->t('__language_name__');
636
+            if ($l->getLanguageCode() === $lang && $potentialName[0] !== '_') { //first check if the language name is in the translation file
637
+                $ln = [
638
+                    'code' => $lang,
639
+                    'name' => $potentialName
640
+                ];
641
+            } elseif ($lang === 'en') {
642
+                $ln = [
643
+                    'code' => $lang,
644
+                    'name' => 'English (US)'
645
+                ];
646
+            } else { //fallback to language code
647
+                $ln = [
648
+                    'code' => $lang,
649
+                    'name' => $lang
650
+                ];
651
+            }
652
+
653
+            // put appropriate languages into appropriate arrays, to print them sorted
654
+            // common languages -> divider -> other languages
655
+            if (in_array($lang, self::COMMON_LANGUAGE_CODES)) {
656
+                $commonLanguages[array_search($lang, self::COMMON_LANGUAGE_CODES)] = $ln;
657
+            } else {
658
+                $otherLanguages[] = $ln;
659
+            }
660
+        }
661
+
662
+        ksort($commonLanguages);
663
+
664
+        // sort now by displayed language not the iso-code
665
+        usort($otherLanguages, function ($a, $b) {
666
+            if ($a['code'] === $a['name'] && $b['code'] !== $b['name']) {
667
+                // If a doesn't have a name, but b does, list b before a
668
+                return 1;
669
+            }
670
+            if ($a['code'] !== $a['name'] && $b['code'] === $b['name']) {
671
+                // If a does have a name, but b doesn't, list a before b
672
+                return -1;
673
+            }
674
+            // Otherwise compare the names
675
+            return strcmp($a['name'], $b['name']);
676
+        });
677
+
678
+        return [
679
+            // reset indexes
680
+            'commonLanguages' => array_values($commonLanguages),
681
+            'otherLanguages' => $otherLanguages
682
+        ];
683
+    }
684 684
 }
Please login to merge, or discard this patch.
lib/private/AppFramework/DependencyInjection/DIContainer.php 1 patch
Indentation   +404 added lines, -404 removed lines patch added patch discarded remove patch
@@ -79,408 +79,408 @@
 block discarded – undo
79 79
  * @deprecated 20.0.0
80 80
  */
81 81
 class DIContainer extends SimpleContainer implements IAppContainer {
82
-	private string $appName;
83
-
84
-	/**
85
-	 * @var array
86
-	 */
87
-	private $middleWares = [];
88
-
89
-	/** @var ServerContainer */
90
-	private $server;
91
-
92
-	/**
93
-	 * Put your class dependencies in here
94
-	 * @param string $appName the name of the app
95
-	 * @param array $urlParams
96
-	 * @param ServerContainer|null $server
97
-	 */
98
-	public function __construct(string $appName, array $urlParams = [], ServerContainer $server = null) {
99
-		parent::__construct();
100
-		$this->appName = $appName;
101
-		$this['appName'] = $appName;
102
-		$this['urlParams'] = $urlParams;
103
-
104
-		$this->registerAlias('Request', IRequest::class);
105
-
106
-		/** @var \OC\ServerContainer $server */
107
-		if ($server === null) {
108
-			$server = \OC::$server;
109
-		}
110
-		$this->server = $server;
111
-		$this->server->registerAppContainer($appName, $this);
112
-
113
-		// aliases
114
-		/** @deprecated inject $appName */
115
-		$this->registerAlias('AppName', 'appName');
116
-		/** @deprecated inject $webRoot*/
117
-		$this->registerAlias('WebRoot', 'webRoot');
118
-		/** @deprecated inject $userId */
119
-		$this->registerAlias('UserId', 'userId');
120
-
121
-		/**
122
-		 * Core services
123
-		 */
124
-		$this->registerService(IOutput::class, function () {
125
-			return new Output($this->getServer()->getWebRoot());
126
-		});
127
-
128
-		$this->registerService(Folder::class, function () {
129
-			return $this->getServer()->getUserFolder();
130
-		});
131
-
132
-		$this->registerService(IAppData::class, function (ContainerInterface $c) {
133
-			return $this->getServer()->getAppDataDir($c->get('AppName'));
134
-		});
135
-
136
-		$this->registerService(IL10N::class, function (ContainerInterface $c) {
137
-			return $this->getServer()->getL10N($c->get('AppName'));
138
-		});
139
-
140
-		// Log wrappers
141
-		$this->registerService(LoggerInterface::class, function (ContainerInterface $c) {
142
-			return new ScopedPsrLogger(
143
-				$c->get(PsrLoggerAdapter::class),
144
-				$c->get('AppName')
145
-			);
146
-		});
147
-		$this->registerService(ILogger::class, function (ContainerInterface $c) {
148
-			return new OC\AppFramework\Logger($this->server->query(ILogger::class), $c->get('AppName'));
149
-		});
150
-
151
-		$this->registerService(IServerContainer::class, function () {
152
-			return $this->getServer();
153
-		});
154
-		$this->registerAlias('ServerContainer', IServerContainer::class);
155
-
156
-		$this->registerService(\OCP\WorkflowEngine\IManager::class, function (ContainerInterface $c) {
157
-			return $c->get(Manager::class);
158
-		});
159
-
160
-		$this->registerService(ContainerInterface::class, function (ContainerInterface $c) {
161
-			return $c;
162
-		});
163
-		$this->registerAlias(IAppContainer::class, ContainerInterface::class);
164
-
165
-		// commonly used attributes
166
-		$this->registerService('userId', function (ContainerInterface $c) {
167
-			return $c->get(IUserSession::class)->getSession()->get('user_id');
168
-		});
169
-
170
-		$this->registerService('webRoot', function (ContainerInterface $c) {
171
-			return $c->get(IServerContainer::class)->getWebRoot();
172
-		});
173
-
174
-		$this->registerService('OC_Defaults', function (ContainerInterface $c) {
175
-			return $c->get(IServerContainer::class)->getThemingDefaults();
176
-		});
177
-
178
-		$this->registerService('Protocol', function (ContainerInterface $c) {
179
-			/** @var \OC\Server $server */
180
-			$server = $c->get(IServerContainer::class);
181
-			$protocol = $server->getRequest()->getHttpProtocol();
182
-			return new Http($_SERVER, $protocol);
183
-		});
184
-
185
-		$this->registerService('Dispatcher', function (ContainerInterface $c) {
186
-			return new Dispatcher(
187
-				$c->get('Protocol'),
188
-				$c->get(MiddlewareDispatcher::class),
189
-				$c->get(IControllerMethodReflector::class),
190
-				$c->get(IRequest::class),
191
-				$c->get(IConfig::class),
192
-				$c->get(IDBConnection::class),
193
-				$c->get(LoggerInterface::class),
194
-				$c->get(EventLogger::class)
195
-			);
196
-		});
197
-
198
-		/**
199
-		 * App Framework default arguments
200
-		 */
201
-		$this->registerParameter('corsMethods', 'PUT, POST, GET, DELETE, PATCH');
202
-		$this->registerParameter('corsAllowedHeaders', 'Authorization, Content-Type, Accept');
203
-		$this->registerParameter('corsMaxAge', 1728000);
204
-
205
-		/**
206
-		 * Middleware
207
-		 */
208
-		$this->registerAlias('MiddlewareDispatcher', MiddlewareDispatcher::class);
209
-		$this->registerService(MiddlewareDispatcher::class, function (ContainerInterface $c) {
210
-			$server = $this->getServer();
211
-
212
-			$dispatcher = new MiddlewareDispatcher();
213
-
214
-			$dispatcher->registerMiddleware(
215
-				$c->get(OC\AppFramework\Middleware\CompressionMiddleware::class)
216
-			);
217
-
218
-			$dispatcher->registerMiddleware($c->get(OC\AppFramework\Middleware\NotModifiedMiddleware::class));
219
-
220
-			$dispatcher->registerMiddleware(
221
-				$c->get(OC\AppFramework\Middleware\Security\ReloadExecutionMiddleware::class)
222
-			);
223
-
224
-			$dispatcher->registerMiddleware(
225
-				new OC\AppFramework\Middleware\Security\SameSiteCookieMiddleware(
226
-					$c->get(IRequest::class),
227
-					$c->get(IControllerMethodReflector::class)
228
-				)
229
-			);
230
-			$dispatcher->registerMiddleware(
231
-				new CORSMiddleware(
232
-					$c->get(IRequest::class),
233
-					$c->get(IControllerMethodReflector::class),
234
-					$c->get(IUserSession::class),
235
-					$c->get(OC\Security\Bruteforce\Throttler::class)
236
-				)
237
-			);
238
-			$dispatcher->registerMiddleware(
239
-				new OCSMiddleware(
240
-					$c->get(IRequest::class)
241
-				)
242
-			);
243
-
244
-
245
-
246
-			$securityMiddleware = new SecurityMiddleware(
247
-				$c->get(IRequest::class),
248
-				$c->get(IControllerMethodReflector::class),
249
-				$c->get(INavigationManager::class),
250
-				$c->get(IURLGenerator::class),
251
-				$server->get(LoggerInterface::class),
252
-				$c->get('AppName'),
253
-				$server->getUserSession()->isLoggedIn(),
254
-				$this->getUserId() !== null && $server->getGroupManager()->isAdmin($this->getUserId()),
255
-				$server->getUserSession()->getUser() !== null && $server->query(ISubAdmin::class)->isSubAdmin($server->getUserSession()->getUser()),
256
-				$server->getAppManager(),
257
-				$server->getL10N('lib'),
258
-				$c->get(AuthorizedGroupMapper::class),
259
-				$server->get(IUserSession::class)
260
-			);
261
-			$dispatcher->registerMiddleware($securityMiddleware);
262
-			$dispatcher->registerMiddleware(
263
-				new OC\AppFramework\Middleware\Security\CSPMiddleware(
264
-					$server->query(OC\Security\CSP\ContentSecurityPolicyManager::class),
265
-					$server->query(OC\Security\CSP\ContentSecurityPolicyNonceManager::class),
266
-					$server->query(OC\Security\CSRF\CsrfTokenManager::class)
267
-				)
268
-			);
269
-			$dispatcher->registerMiddleware(
270
-				$server->query(OC\AppFramework\Middleware\Security\FeaturePolicyMiddleware::class)
271
-			);
272
-			$dispatcher->registerMiddleware(
273
-				new OC\AppFramework\Middleware\Security\PasswordConfirmationMiddleware(
274
-					$c->get(IControllerMethodReflector::class),
275
-					$c->get(ISession::class),
276
-					$c->get(IUserSession::class),
277
-					$c->get(ITimeFactory::class)
278
-				)
279
-			);
280
-			$dispatcher->registerMiddleware(
281
-				new TwoFactorMiddleware(
282
-					$c->get(OC\Authentication\TwoFactorAuth\Manager::class),
283
-					$c->get(IUserSession::class),
284
-					$c->get(ISession::class),
285
-					$c->get(IURLGenerator::class),
286
-					$c->get(IControllerMethodReflector::class),
287
-					$c->get(IRequest::class)
288
-				)
289
-			);
290
-			$dispatcher->registerMiddleware(
291
-				new OC\AppFramework\Middleware\Security\BruteForceMiddleware(
292
-					$c->get(IControllerMethodReflector::class),
293
-					$c->get(OC\Security\Bruteforce\Throttler::class),
294
-					$c->get(IRequest::class)
295
-				)
296
-			);
297
-			$dispatcher->registerMiddleware(
298
-				new RateLimitingMiddleware(
299
-					$c->get(IRequest::class),
300
-					$c->get(IUserSession::class),
301
-					$c->get(IControllerMethodReflector::class),
302
-					$c->get(OC\Security\RateLimiting\Limiter::class)
303
-				)
304
-			);
305
-			$dispatcher->registerMiddleware(
306
-				new OC\AppFramework\Middleware\PublicShare\PublicShareMiddleware(
307
-					$c->get(IRequest::class),
308
-					$c->get(ISession::class),
309
-					$c->get(\OCP\IConfig::class),
310
-					$c->get(OC\Security\Bruteforce\Throttler::class)
311
-				)
312
-			);
313
-			$dispatcher->registerMiddleware(
314
-				$c->get(\OC\AppFramework\Middleware\AdditionalScriptsMiddleware::class)
315
-			);
316
-
317
-			foreach ($this->middleWares as $middleWare) {
318
-				$dispatcher->registerMiddleware($c->get($middleWare));
319
-			}
320
-
321
-			$dispatcher->registerMiddleware(
322
-				new SessionMiddleware(
323
-					$c->get(IControllerMethodReflector::class),
324
-					$c->get(ISession::class)
325
-				)
326
-			);
327
-			return $dispatcher;
328
-		});
329
-
330
-		$this->registerService(IAppConfig::class, function (ContainerInterface $c) {
331
-			return new OC\AppFramework\Services\AppConfig(
332
-				$c->get(IConfig::class),
333
-				$c->get('AppName')
334
-			);
335
-		});
336
-		$this->registerService(IInitialState::class, function (ContainerInterface $c) {
337
-			return new OC\AppFramework\Services\InitialState(
338
-				$c->get(IInitialStateService::class),
339
-				$c->get('AppName')
340
-			);
341
-		});
342
-	}
343
-
344
-	/**
345
-	 * @return \OCP\IServerContainer
346
-	 */
347
-	public function getServer() {
348
-		return $this->server;
349
-	}
350
-
351
-	/**
352
-	 * @param string $middleWare
353
-	 * @return boolean|null
354
-	 */
355
-	public function registerMiddleWare($middleWare) {
356
-		if (in_array($middleWare, $this->middleWares, true) !== false) {
357
-			return false;
358
-		}
359
-		$this->middleWares[] = $middleWare;
360
-	}
361
-
362
-	/**
363
-	 * used to return the appname of the set application
364
-	 * @return string the name of your application
365
-	 */
366
-	public function getAppName() {
367
-		return $this->query('AppName');
368
-	}
369
-
370
-	/**
371
-	 * @deprecated use IUserSession->isLoggedIn()
372
-	 * @return boolean
373
-	 */
374
-	public function isLoggedIn() {
375
-		return \OC::$server->getUserSession()->isLoggedIn();
376
-	}
377
-
378
-	/**
379
-	 * @deprecated use IGroupManager->isAdmin($userId)
380
-	 * @return boolean
381
-	 */
382
-	public function isAdminUser() {
383
-		$uid = $this->getUserId();
384
-		return \OC_User::isAdminUser($uid);
385
-	}
386
-
387
-	private function getUserId() {
388
-		return $this->getServer()->getSession()->get('user_id');
389
-	}
390
-
391
-	/**
392
-	 * @deprecated use the ILogger instead
393
-	 * @param string $message
394
-	 * @param string $level
395
-	 * @return mixed
396
-	 */
397
-	public function log($message, $level) {
398
-		switch ($level) {
399
-			case 'debug':
400
-				$level = ILogger::DEBUG;
401
-				break;
402
-			case 'info':
403
-				$level = ILogger::INFO;
404
-				break;
405
-			case 'warn':
406
-				$level = ILogger::WARN;
407
-				break;
408
-			case 'fatal':
409
-				$level = ILogger::FATAL;
410
-				break;
411
-			default:
412
-				$level = ILogger::ERROR;
413
-				break;
414
-		}
415
-		\OCP\Util::writeLog($this->getAppName(), $message, $level);
416
-	}
417
-
418
-	/**
419
-	 * Register a capability
420
-	 *
421
-	 * @param string $serviceName e.g. 'OCA\Files\Capabilities'
422
-	 */
423
-	public function registerCapability($serviceName) {
424
-		$this->query('OC\CapabilitiesManager')->registerCapability(function () use ($serviceName) {
425
-			return $this->query($serviceName);
426
-		});
427
-	}
428
-
429
-	public function has($id): bool {
430
-		if (parent::has($id)) {
431
-			return true;
432
-		}
433
-
434
-		if ($this->server->has($id, true)) {
435
-			return true;
436
-		}
437
-
438
-		return false;
439
-	}
440
-
441
-	public function query(string $name, bool $autoload = true) {
442
-		if ($name === 'AppName' || $name === 'appName') {
443
-			return $this->appName;
444
-		}
445
-
446
-		$isServerClass = str_starts_with($name, 'OCP\\') || str_starts_with($name, 'OC\\');
447
-		if ($isServerClass && !$this->has($name)) {
448
-			return $this->getServer()->query($name, $autoload);
449
-		}
450
-
451
-		try {
452
-			return $this->queryNoFallback($name);
453
-		} catch (QueryException $firstException) {
454
-			try {
455
-				return $this->getServer()->query($name, $autoload);
456
-			} catch (QueryException $secondException) {
457
-				if ($firstException->getCode() === 1) {
458
-					throw $secondException;
459
-				}
460
-				throw $firstException;
461
-			}
462
-		}
463
-	}
464
-
465
-	/**
466
-	 * @param string $name
467
-	 * @return mixed
468
-	 * @throws QueryException if the query could not be resolved
469
-	 */
470
-	public function queryNoFallback($name) {
471
-		$name = $this->sanitizeName($name);
472
-
473
-		if ($this->offsetExists($name)) {
474
-			return parent::query($name);
475
-		} elseif ($this->appName === 'settings' && str_starts_with($name, 'OC\\Settings\\')) {
476
-			return parent::query($name);
477
-		} elseif ($this->appName === 'core' && str_starts_with($name, 'OC\\Core\\')) {
478
-			return parent::query($name);
479
-		} elseif (str_starts_with($name, \OC\AppFramework\App::buildAppNamespace($this->appName) . '\\')) {
480
-			return parent::query($name);
481
-		}
482
-
483
-		throw new QueryException('Could not resolve ' . $name . '!' .
484
-			' Class can not be instantiated', 1);
485
-	}
82
+    private string $appName;
83
+
84
+    /**
85
+     * @var array
86
+     */
87
+    private $middleWares = [];
88
+
89
+    /** @var ServerContainer */
90
+    private $server;
91
+
92
+    /**
93
+     * Put your class dependencies in here
94
+     * @param string $appName the name of the app
95
+     * @param array $urlParams
96
+     * @param ServerContainer|null $server
97
+     */
98
+    public function __construct(string $appName, array $urlParams = [], ServerContainer $server = null) {
99
+        parent::__construct();
100
+        $this->appName = $appName;
101
+        $this['appName'] = $appName;
102
+        $this['urlParams'] = $urlParams;
103
+
104
+        $this->registerAlias('Request', IRequest::class);
105
+
106
+        /** @var \OC\ServerContainer $server */
107
+        if ($server === null) {
108
+            $server = \OC::$server;
109
+        }
110
+        $this->server = $server;
111
+        $this->server->registerAppContainer($appName, $this);
112
+
113
+        // aliases
114
+        /** @deprecated inject $appName */
115
+        $this->registerAlias('AppName', 'appName');
116
+        /** @deprecated inject $webRoot*/
117
+        $this->registerAlias('WebRoot', 'webRoot');
118
+        /** @deprecated inject $userId */
119
+        $this->registerAlias('UserId', 'userId');
120
+
121
+        /**
122
+         * Core services
123
+         */
124
+        $this->registerService(IOutput::class, function () {
125
+            return new Output($this->getServer()->getWebRoot());
126
+        });
127
+
128
+        $this->registerService(Folder::class, function () {
129
+            return $this->getServer()->getUserFolder();
130
+        });
131
+
132
+        $this->registerService(IAppData::class, function (ContainerInterface $c) {
133
+            return $this->getServer()->getAppDataDir($c->get('AppName'));
134
+        });
135
+
136
+        $this->registerService(IL10N::class, function (ContainerInterface $c) {
137
+            return $this->getServer()->getL10N($c->get('AppName'));
138
+        });
139
+
140
+        // Log wrappers
141
+        $this->registerService(LoggerInterface::class, function (ContainerInterface $c) {
142
+            return new ScopedPsrLogger(
143
+                $c->get(PsrLoggerAdapter::class),
144
+                $c->get('AppName')
145
+            );
146
+        });
147
+        $this->registerService(ILogger::class, function (ContainerInterface $c) {
148
+            return new OC\AppFramework\Logger($this->server->query(ILogger::class), $c->get('AppName'));
149
+        });
150
+
151
+        $this->registerService(IServerContainer::class, function () {
152
+            return $this->getServer();
153
+        });
154
+        $this->registerAlias('ServerContainer', IServerContainer::class);
155
+
156
+        $this->registerService(\OCP\WorkflowEngine\IManager::class, function (ContainerInterface $c) {
157
+            return $c->get(Manager::class);
158
+        });
159
+
160
+        $this->registerService(ContainerInterface::class, function (ContainerInterface $c) {
161
+            return $c;
162
+        });
163
+        $this->registerAlias(IAppContainer::class, ContainerInterface::class);
164
+
165
+        // commonly used attributes
166
+        $this->registerService('userId', function (ContainerInterface $c) {
167
+            return $c->get(IUserSession::class)->getSession()->get('user_id');
168
+        });
169
+
170
+        $this->registerService('webRoot', function (ContainerInterface $c) {
171
+            return $c->get(IServerContainer::class)->getWebRoot();
172
+        });
173
+
174
+        $this->registerService('OC_Defaults', function (ContainerInterface $c) {
175
+            return $c->get(IServerContainer::class)->getThemingDefaults();
176
+        });
177
+
178
+        $this->registerService('Protocol', function (ContainerInterface $c) {
179
+            /** @var \OC\Server $server */
180
+            $server = $c->get(IServerContainer::class);
181
+            $protocol = $server->getRequest()->getHttpProtocol();
182
+            return new Http($_SERVER, $protocol);
183
+        });
184
+
185
+        $this->registerService('Dispatcher', function (ContainerInterface $c) {
186
+            return new Dispatcher(
187
+                $c->get('Protocol'),
188
+                $c->get(MiddlewareDispatcher::class),
189
+                $c->get(IControllerMethodReflector::class),
190
+                $c->get(IRequest::class),
191
+                $c->get(IConfig::class),
192
+                $c->get(IDBConnection::class),
193
+                $c->get(LoggerInterface::class),
194
+                $c->get(EventLogger::class)
195
+            );
196
+        });
197
+
198
+        /**
199
+         * App Framework default arguments
200
+         */
201
+        $this->registerParameter('corsMethods', 'PUT, POST, GET, DELETE, PATCH');
202
+        $this->registerParameter('corsAllowedHeaders', 'Authorization, Content-Type, Accept');
203
+        $this->registerParameter('corsMaxAge', 1728000);
204
+
205
+        /**
206
+         * Middleware
207
+         */
208
+        $this->registerAlias('MiddlewareDispatcher', MiddlewareDispatcher::class);
209
+        $this->registerService(MiddlewareDispatcher::class, function (ContainerInterface $c) {
210
+            $server = $this->getServer();
211
+
212
+            $dispatcher = new MiddlewareDispatcher();
213
+
214
+            $dispatcher->registerMiddleware(
215
+                $c->get(OC\AppFramework\Middleware\CompressionMiddleware::class)
216
+            );
217
+
218
+            $dispatcher->registerMiddleware($c->get(OC\AppFramework\Middleware\NotModifiedMiddleware::class));
219
+
220
+            $dispatcher->registerMiddleware(
221
+                $c->get(OC\AppFramework\Middleware\Security\ReloadExecutionMiddleware::class)
222
+            );
223
+
224
+            $dispatcher->registerMiddleware(
225
+                new OC\AppFramework\Middleware\Security\SameSiteCookieMiddleware(
226
+                    $c->get(IRequest::class),
227
+                    $c->get(IControllerMethodReflector::class)
228
+                )
229
+            );
230
+            $dispatcher->registerMiddleware(
231
+                new CORSMiddleware(
232
+                    $c->get(IRequest::class),
233
+                    $c->get(IControllerMethodReflector::class),
234
+                    $c->get(IUserSession::class),
235
+                    $c->get(OC\Security\Bruteforce\Throttler::class)
236
+                )
237
+            );
238
+            $dispatcher->registerMiddleware(
239
+                new OCSMiddleware(
240
+                    $c->get(IRequest::class)
241
+                )
242
+            );
243
+
244
+
245
+
246
+            $securityMiddleware = new SecurityMiddleware(
247
+                $c->get(IRequest::class),
248
+                $c->get(IControllerMethodReflector::class),
249
+                $c->get(INavigationManager::class),
250
+                $c->get(IURLGenerator::class),
251
+                $server->get(LoggerInterface::class),
252
+                $c->get('AppName'),
253
+                $server->getUserSession()->isLoggedIn(),
254
+                $this->getUserId() !== null && $server->getGroupManager()->isAdmin($this->getUserId()),
255
+                $server->getUserSession()->getUser() !== null && $server->query(ISubAdmin::class)->isSubAdmin($server->getUserSession()->getUser()),
256
+                $server->getAppManager(),
257
+                $server->getL10N('lib'),
258
+                $c->get(AuthorizedGroupMapper::class),
259
+                $server->get(IUserSession::class)
260
+            );
261
+            $dispatcher->registerMiddleware($securityMiddleware);
262
+            $dispatcher->registerMiddleware(
263
+                new OC\AppFramework\Middleware\Security\CSPMiddleware(
264
+                    $server->query(OC\Security\CSP\ContentSecurityPolicyManager::class),
265
+                    $server->query(OC\Security\CSP\ContentSecurityPolicyNonceManager::class),
266
+                    $server->query(OC\Security\CSRF\CsrfTokenManager::class)
267
+                )
268
+            );
269
+            $dispatcher->registerMiddleware(
270
+                $server->query(OC\AppFramework\Middleware\Security\FeaturePolicyMiddleware::class)
271
+            );
272
+            $dispatcher->registerMiddleware(
273
+                new OC\AppFramework\Middleware\Security\PasswordConfirmationMiddleware(
274
+                    $c->get(IControllerMethodReflector::class),
275
+                    $c->get(ISession::class),
276
+                    $c->get(IUserSession::class),
277
+                    $c->get(ITimeFactory::class)
278
+                )
279
+            );
280
+            $dispatcher->registerMiddleware(
281
+                new TwoFactorMiddleware(
282
+                    $c->get(OC\Authentication\TwoFactorAuth\Manager::class),
283
+                    $c->get(IUserSession::class),
284
+                    $c->get(ISession::class),
285
+                    $c->get(IURLGenerator::class),
286
+                    $c->get(IControllerMethodReflector::class),
287
+                    $c->get(IRequest::class)
288
+                )
289
+            );
290
+            $dispatcher->registerMiddleware(
291
+                new OC\AppFramework\Middleware\Security\BruteForceMiddleware(
292
+                    $c->get(IControllerMethodReflector::class),
293
+                    $c->get(OC\Security\Bruteforce\Throttler::class),
294
+                    $c->get(IRequest::class)
295
+                )
296
+            );
297
+            $dispatcher->registerMiddleware(
298
+                new RateLimitingMiddleware(
299
+                    $c->get(IRequest::class),
300
+                    $c->get(IUserSession::class),
301
+                    $c->get(IControllerMethodReflector::class),
302
+                    $c->get(OC\Security\RateLimiting\Limiter::class)
303
+                )
304
+            );
305
+            $dispatcher->registerMiddleware(
306
+                new OC\AppFramework\Middleware\PublicShare\PublicShareMiddleware(
307
+                    $c->get(IRequest::class),
308
+                    $c->get(ISession::class),
309
+                    $c->get(\OCP\IConfig::class),
310
+                    $c->get(OC\Security\Bruteforce\Throttler::class)
311
+                )
312
+            );
313
+            $dispatcher->registerMiddleware(
314
+                $c->get(\OC\AppFramework\Middleware\AdditionalScriptsMiddleware::class)
315
+            );
316
+
317
+            foreach ($this->middleWares as $middleWare) {
318
+                $dispatcher->registerMiddleware($c->get($middleWare));
319
+            }
320
+
321
+            $dispatcher->registerMiddleware(
322
+                new SessionMiddleware(
323
+                    $c->get(IControllerMethodReflector::class),
324
+                    $c->get(ISession::class)
325
+                )
326
+            );
327
+            return $dispatcher;
328
+        });
329
+
330
+        $this->registerService(IAppConfig::class, function (ContainerInterface $c) {
331
+            return new OC\AppFramework\Services\AppConfig(
332
+                $c->get(IConfig::class),
333
+                $c->get('AppName')
334
+            );
335
+        });
336
+        $this->registerService(IInitialState::class, function (ContainerInterface $c) {
337
+            return new OC\AppFramework\Services\InitialState(
338
+                $c->get(IInitialStateService::class),
339
+                $c->get('AppName')
340
+            );
341
+        });
342
+    }
343
+
344
+    /**
345
+     * @return \OCP\IServerContainer
346
+     */
347
+    public function getServer() {
348
+        return $this->server;
349
+    }
350
+
351
+    /**
352
+     * @param string $middleWare
353
+     * @return boolean|null
354
+     */
355
+    public function registerMiddleWare($middleWare) {
356
+        if (in_array($middleWare, $this->middleWares, true) !== false) {
357
+            return false;
358
+        }
359
+        $this->middleWares[] = $middleWare;
360
+    }
361
+
362
+    /**
363
+     * used to return the appname of the set application
364
+     * @return string the name of your application
365
+     */
366
+    public function getAppName() {
367
+        return $this->query('AppName');
368
+    }
369
+
370
+    /**
371
+     * @deprecated use IUserSession->isLoggedIn()
372
+     * @return boolean
373
+     */
374
+    public function isLoggedIn() {
375
+        return \OC::$server->getUserSession()->isLoggedIn();
376
+    }
377
+
378
+    /**
379
+     * @deprecated use IGroupManager->isAdmin($userId)
380
+     * @return boolean
381
+     */
382
+    public function isAdminUser() {
383
+        $uid = $this->getUserId();
384
+        return \OC_User::isAdminUser($uid);
385
+    }
386
+
387
+    private function getUserId() {
388
+        return $this->getServer()->getSession()->get('user_id');
389
+    }
390
+
391
+    /**
392
+     * @deprecated use the ILogger instead
393
+     * @param string $message
394
+     * @param string $level
395
+     * @return mixed
396
+     */
397
+    public function log($message, $level) {
398
+        switch ($level) {
399
+            case 'debug':
400
+                $level = ILogger::DEBUG;
401
+                break;
402
+            case 'info':
403
+                $level = ILogger::INFO;
404
+                break;
405
+            case 'warn':
406
+                $level = ILogger::WARN;
407
+                break;
408
+            case 'fatal':
409
+                $level = ILogger::FATAL;
410
+                break;
411
+            default:
412
+                $level = ILogger::ERROR;
413
+                break;
414
+        }
415
+        \OCP\Util::writeLog($this->getAppName(), $message, $level);
416
+    }
417
+
418
+    /**
419
+     * Register a capability
420
+     *
421
+     * @param string $serviceName e.g. 'OCA\Files\Capabilities'
422
+     */
423
+    public function registerCapability($serviceName) {
424
+        $this->query('OC\CapabilitiesManager')->registerCapability(function () use ($serviceName) {
425
+            return $this->query($serviceName);
426
+        });
427
+    }
428
+
429
+    public function has($id): bool {
430
+        if (parent::has($id)) {
431
+            return true;
432
+        }
433
+
434
+        if ($this->server->has($id, true)) {
435
+            return true;
436
+        }
437
+
438
+        return false;
439
+    }
440
+
441
+    public function query(string $name, bool $autoload = true) {
442
+        if ($name === 'AppName' || $name === 'appName') {
443
+            return $this->appName;
444
+        }
445
+
446
+        $isServerClass = str_starts_with($name, 'OCP\\') || str_starts_with($name, 'OC\\');
447
+        if ($isServerClass && !$this->has($name)) {
448
+            return $this->getServer()->query($name, $autoload);
449
+        }
450
+
451
+        try {
452
+            return $this->queryNoFallback($name);
453
+        } catch (QueryException $firstException) {
454
+            try {
455
+                return $this->getServer()->query($name, $autoload);
456
+            } catch (QueryException $secondException) {
457
+                if ($firstException->getCode() === 1) {
458
+                    throw $secondException;
459
+                }
460
+                throw $firstException;
461
+            }
462
+        }
463
+    }
464
+
465
+    /**
466
+     * @param string $name
467
+     * @return mixed
468
+     * @throws QueryException if the query could not be resolved
469
+     */
470
+    public function queryNoFallback($name) {
471
+        $name = $this->sanitizeName($name);
472
+
473
+        if ($this->offsetExists($name)) {
474
+            return parent::query($name);
475
+        } elseif ($this->appName === 'settings' && str_starts_with($name, 'OC\\Settings\\')) {
476
+            return parent::query($name);
477
+        } elseif ($this->appName === 'core' && str_starts_with($name, 'OC\\Core\\')) {
478
+            return parent::query($name);
479
+        } elseif (str_starts_with($name, \OC\AppFramework\App::buildAppNamespace($this->appName) . '\\')) {
480
+            return parent::query($name);
481
+        }
482
+
483
+        throw new QueryException('Could not resolve ' . $name . '!' .
484
+            ' Class can not be instantiated', 1);
485
+    }
486 486
 }
Please login to merge, or discard this patch.
lib/private/TemplateLayout.php 1 patch
Indentation   +330 added lines, -330 removed lines patch added patch discarded remove patch
@@ -57,334 +57,334 @@
 block discarded – undo
57 57
 use OCP\Util;
58 58
 
59 59
 class TemplateLayout extends \OC_Template {
60
-	private static $versionHash = '';
61
-
62
-	/** @var CSSResourceLocator|null */
63
-	public static $cssLocator = null;
64
-
65
-	/** @var JSResourceLocator|null */
66
-	public static $jsLocator = null;
67
-
68
-	/** @var IConfig */
69
-	private $config;
70
-
71
-	/** @var IInitialStateService */
72
-	private $initialState;
73
-
74
-	/** @var INavigationManager */
75
-	private $navigationManager;
76
-
77
-	/**
78
-	 * @param string $renderAs
79
-	 * @param string $appId application id
80
-	 */
81
-	public function __construct($renderAs, $appId = '') {
82
-
83
-		/** @var IConfig */
84
-		$this->config = \OC::$server->get(IConfig::class);
85
-
86
-		/** @var IInitialStateService */
87
-		$this->initialState = \OC::$server->get(IInitialStateService::class);
88
-
89
-		// Add fallback theming variables if theming is disabled
90
-		if ($renderAs !== TemplateResponse::RENDER_AS_USER
91
-			|| !\OC::$server->getAppManager()->isEnabledForUser('theming')) {
92
-			// TODO cache generated default theme if enabled for fallback if server is erroring ?
93
-			Util::addStyle('theming', 'default');
94
-		}
95
-
96
-		// Decide which page we show
97
-		if ($renderAs === TemplateResponse::RENDER_AS_USER) {
98
-			/** @var INavigationManager */
99
-			$this->navigationManager = \OC::$server->get(INavigationManager::class);
100
-
101
-			parent::__construct('core', 'layout.user');
102
-			if (in_array(\OC_App::getCurrentApp(), ['settings','admin', 'help']) !== false) {
103
-				$this->assign('bodyid', 'body-settings');
104
-			} else {
105
-				$this->assign('bodyid', 'body-user');
106
-			}
107
-
108
-			$this->initialState->provideInitialState('core', 'active-app', $this->navigationManager->getActiveEntry());
109
-			$this->initialState->provideInitialState('core', 'apps', $this->navigationManager->getAll());
110
-			$this->initialState->provideInitialState('unified-search', 'limit-default', (int)$this->config->getAppValue('core', 'unified-search.limit-default', (string)SearchQuery::LIMIT_DEFAULT));
111
-			$this->initialState->provideInitialState('unified-search', 'min-search-length', (int)$this->config->getAppValue('core', 'unified-search.min-search-length', (string)1));
112
-			$this->initialState->provideInitialState('unified-search', 'live-search', $this->config->getAppValue('core', 'unified-search.live-search', 'yes') === 'yes');
113
-			Util::addScript('core', 'unified-search', 'core');
114
-
115
-			// Set body data-theme
116
-			$this->assign('enabledThemes', []);
117
-			if (\OC::$server->getAppManager()->isEnabledForUser('theming') && class_exists('\OCA\Theming\Service\ThemesService')) {
118
-				/** @var \OCA\Theming\Service\ThemesService */
119
-				$themesService = \OC::$server->get(\OCA\Theming\Service\ThemesService::class);
120
-				$this->assign('enabledThemes', $themesService->getEnabledThemes());
121
-			}
122
-
123
-			// set logo link target
124
-			$logoUrl = $this->config->getSystemValueString('logo_url', '');
125
-			$this->assign('logoUrl', $logoUrl);
126
-
127
-			// Add navigation entry
128
-			$this->assign('application', '');
129
-			$this->assign('appid', $appId);
130
-
131
-			$navigation = $this->navigationManager->getAll();
132
-			$this->assign('navigation', $navigation);
133
-			$settingsNavigation = $this->navigationManager->getAll('settings');
134
-			$this->assign('settingsnavigation', $settingsNavigation);
135
-
136
-			foreach ($navigation as $entry) {
137
-				if ($entry['active']) {
138
-					$this->assign('application', $entry['name']);
139
-					break;
140
-				}
141
-			}
142
-
143
-			foreach ($settingsNavigation as $entry) {
144
-				if ($entry['active']) {
145
-					$this->assign('application', $entry['name']);
146
-					break;
147
-				}
148
-			}
149
-
150
-			$userDisplayName = false;
151
-			$user = \OC::$server->get(IUserSession::class)->getUser();
152
-			if ($user) {
153
-				$userDisplayName = $user->getDisplayName();
154
-			}
155
-			$this->assign('user_displayname', $userDisplayName);
156
-			$this->assign('user_uid', \OC_User::getUser());
157
-
158
-			if ($user === null) {
159
-				$this->assign('userAvatarSet', false);
160
-				$this->assign('userStatus', false);
161
-			} else {
162
-				$this->assign('userAvatarSet', true);
163
-				$this->assign('userAvatarVersion', $this->config->getUserValue(\OC_User::getUser(), 'avatar', 'version', 0));
164
-			}
165
-		} elseif ($renderAs === TemplateResponse::RENDER_AS_ERROR) {
166
-			parent::__construct('core', 'layout.guest', '', false);
167
-			$this->assign('bodyid', 'body-login');
168
-			$this->assign('user_displayname', '');
169
-			$this->assign('user_uid', '');
170
-		} elseif ($renderAs === TemplateResponse::RENDER_AS_GUEST) {
171
-			parent::__construct('core', 'layout.guest');
172
-			\OC_Util::addStyle('guest');
173
-			$this->assign('bodyid', 'body-login');
174
-
175
-			$userDisplayName = false;
176
-			$user = \OC::$server->get(IUserSession::class)->getUser();
177
-			if ($user) {
178
-				$userDisplayName = $user->getDisplayName();
179
-			}
180
-			$this->assign('user_displayname', $userDisplayName);
181
-			$this->assign('user_uid', \OC_User::getUser());
182
-		} elseif ($renderAs === TemplateResponse::RENDER_AS_PUBLIC) {
183
-			parent::__construct('core', 'layout.public');
184
-			$this->assign('appid', $appId);
185
-			$this->assign('bodyid', 'body-public');
186
-
187
-			/** @var IRegistry $subscription */
188
-			$subscription = \OC::$server->query(IRegistry::class);
189
-			$showSimpleSignup = $this->config->getSystemValueBool('simpleSignUpLink.shown', true);
190
-			if ($showSimpleSignup && $subscription->delegateHasValidSubscription()) {
191
-				$showSimpleSignup = false;
192
-			}
193
-			$this->assign('showSimpleSignUpLink', $showSimpleSignup);
194
-		} else {
195
-			parent::__construct('core', 'layout.base');
196
-		}
197
-		// Send the language and the locale to our layouts
198
-		$lang = \OC::$server->getL10NFactory()->findLanguage();
199
-		$locale = \OC::$server->getL10NFactory()->findLocale($lang);
200
-
201
-		$lang = str_replace('_', '-', $lang);
202
-		$this->assign('language', $lang);
203
-		$this->assign('locale', $locale);
204
-
205
-		if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
206
-			if (empty(self::$versionHash)) {
207
-				$v = \OC_App::getAppVersions();
208
-				$v['core'] = implode('.', \OCP\Util::getVersion());
209
-				self::$versionHash = substr(md5(implode(',', $v)), 0, 8);
210
-			}
211
-		} else {
212
-			self::$versionHash = md5('not installed');
213
-		}
214
-
215
-		// Add the js files
216
-		// TODO: remove deprecated OC_Util injection
217
-		$jsFiles = self::findJavascriptFiles(array_merge(\OC_Util::$scripts, Util::getScripts()));
218
-		$this->assign('jsfiles', []);
219
-		if ($this->config->getSystemValue('installed', false) && $renderAs != TemplateResponse::RENDER_AS_ERROR) {
220
-			// this is on purpose outside of the if statement below so that the initial state is prefilled (done in the getConfig() call)
221
-			// see https://github.com/nextcloud/server/pull/22636 for details
222
-			$jsConfigHelper = new JSConfigHelper(
223
-				\OC::$server->getL10N('lib'),
224
-				\OC::$server->query(Defaults::class),
225
-				\OC::$server->getAppManager(),
226
-				\OC::$server->getSession(),
227
-				\OC::$server->getUserSession()->getUser(),
228
-				$this->config,
229
-				\OC::$server->getGroupManager(),
230
-				\OC::$server->get(IniGetWrapper::class),
231
-				\OC::$server->getURLGenerator(),
232
-				\OC::$server->getCapabilitiesManager(),
233
-				\OC::$server->query(IInitialStateService::class)
234
-			);
235
-			$config = $jsConfigHelper->getConfig();
236
-			if (\OC::$server->getContentSecurityPolicyNonceManager()->browserSupportsCspV3()) {
237
-				$this->assign('inline_ocjs', $config);
238
-			} else {
239
-				$this->append('jsfiles', \OC::$server->getURLGenerator()->linkToRoute('core.OCJS.getConfig', ['v' => self::$versionHash]));
240
-			}
241
-		}
242
-		foreach ($jsFiles as $info) {
243
-			$web = $info[1];
244
-			$file = $info[2];
245
-			$this->append('jsfiles', $web.'/'.$file . $this->getVersionHashSuffix());
246
-		}
247
-
248
-		try {
249
-			$pathInfo = \OC::$server->getRequest()->getPathInfo();
250
-		} catch (\Exception $e) {
251
-			$pathInfo = '';
252
-		}
253
-
254
-		// Do not initialise scss appdata until we have a fully installed instance
255
-		// Do not load scss for update, errors, installation or login page
256
-		if (\OC::$server->getSystemConfig()->getValue('installed', false)
257
-			&& !\OCP\Util::needUpgrade()
258
-			&& $pathInfo !== ''
259
-			&& !preg_match('/^\/login/', $pathInfo)
260
-			&& $renderAs !== TemplateResponse::RENDER_AS_ERROR
261
-		) {
262
-			$cssFiles = self::findStylesheetFiles(\OC_Util::$styles);
263
-		} else {
264
-			// If we ignore the scss compiler,
265
-			// we need to load the guest css fallback
266
-			\OC_Util::addStyle('guest');
267
-			$cssFiles = self::findStylesheetFiles(\OC_Util::$styles, false);
268
-		}
269
-
270
-		$this->assign('cssfiles', []);
271
-		$this->assign('printcssfiles', []);
272
-		$this->assign('versionHash', self::$versionHash);
273
-		foreach ($cssFiles as $info) {
274
-			$web = $info[1];
275
-			$file = $info[2];
276
-
277
-			if (substr($file, -strlen('print.css')) === 'print.css') {
278
-				$this->append('printcssfiles', $web.'/'.$file . $this->getVersionHashSuffix());
279
-			} else {
280
-				$suffix = $this->getVersionHashSuffix($web, $file);
281
-
282
-				if (strpos($file, '?v=') == false) {
283
-					$this->append('cssfiles', $web.'/'.$file . $suffix);
284
-				} else {
285
-					$this->append('cssfiles', $web.'/'.$file . '-' . substr($suffix, 3));
286
-				}
287
-			}
288
-		}
289
-
290
-		$this->assign('initialStates', $this->initialState->getInitialStates());
291
-
292
-		$this->assign('id-app-content', $renderAs === TemplateResponse::RENDER_AS_USER ? '#app-content' : '#content');
293
-		$this->assign('id-app-navigation', $renderAs === TemplateResponse::RENDER_AS_USER ? '#app-navigation' : null);
294
-	}
295
-
296
-	/**
297
-	 * @param string $path
298
-	 * @param string $file
299
-	 * @return string
300
-	 */
301
-	protected function getVersionHashSuffix($path = false, $file = false) {
302
-		if ($this->config->getSystemValue('debug', false)) {
303
-			// allows chrome workspace mapping in debug mode
304
-			return "";
305
-		}
306
-		$themingSuffix = '';
307
-		$v = [];
308
-
309
-		if ($this->config->getSystemValue('installed', false)) {
310
-			if (\OC::$server->getAppManager()->isInstalled('theming')) {
311
-				$themingSuffix = '-' . $this->config->getAppValue('theming', 'cachebuster', '0');
312
-			}
313
-			$v = \OC_App::getAppVersions();
314
-		}
315
-
316
-		// Try the webroot path for a match
317
-		if ($path !== false && $path !== '') {
318
-			$appName = $this->getAppNamefromPath($path);
319
-			if (array_key_exists($appName, $v)) {
320
-				$appVersion = $v[$appName];
321
-				return '?v=' . substr(md5($appVersion), 0, 8) . $themingSuffix;
322
-			}
323
-		}
324
-		// fallback to the file path instead
325
-		if ($file !== false && $file !== '') {
326
-			$appName = $this->getAppNamefromPath($file);
327
-			if (array_key_exists($appName, $v)) {
328
-				$appVersion = $v[$appName];
329
-				return '?v=' . substr(md5($appVersion), 0, 8) . $themingSuffix;
330
-			}
331
-		}
332
-
333
-		return '?v=' . self::$versionHash . $themingSuffix;
334
-	}
335
-
336
-	/**
337
-	 * @param array $styles
338
-	 * @return array
339
-	 */
340
-	public static function findStylesheetFiles($styles, $compileScss = true) {
341
-		if (!self::$cssLocator) {
342
-			self::$cssLocator = \OCP\Server::get(CSSResourceLocator::class);
343
-		}
344
-		self::$cssLocator->find($styles);
345
-		return self::$cssLocator->getResources();
346
-	}
347
-
348
-	/**
349
-	 * @param string $path
350
-	 * @return string|boolean
351
-	 */
352
-	public function getAppNamefromPath($path) {
353
-		if ($path !== '' && is_string($path)) {
354
-			$pathParts = explode('/', $path);
355
-			if ($pathParts[0] === 'css') {
356
-				// This is a scss request
357
-				return $pathParts[1];
358
-			}
359
-			return end($pathParts);
360
-		}
361
-		return false;
362
-	}
363
-
364
-	/**
365
-	 * @param array $scripts
366
-	 * @return array
367
-	 */
368
-	public static function findJavascriptFiles($scripts) {
369
-		if (!self::$jsLocator) {
370
-			self::$jsLocator = \OCP\Server::get(JSResourceLocator::class);
371
-		}
372
-		self::$jsLocator->find($scripts);
373
-		return self::$jsLocator->getResources();
374
-	}
375
-
376
-	/**
377
-	 * Converts the absolute file path to a relative path from \OC::$SERVERROOT
378
-	 * @param string $filePath Absolute path
379
-	 * @return string Relative path
380
-	 * @throws \Exception If $filePath is not under \OC::$SERVERROOT
381
-	 */
382
-	public static function convertToRelativePath($filePath) {
383
-		$relativePath = explode(\OC::$SERVERROOT, $filePath);
384
-		if (count($relativePath) !== 2) {
385
-			throw new \Exception('$filePath is not under the \OC::$SERVERROOT');
386
-		}
387
-
388
-		return $relativePath[1];
389
-	}
60
+    private static $versionHash = '';
61
+
62
+    /** @var CSSResourceLocator|null */
63
+    public static $cssLocator = null;
64
+
65
+    /** @var JSResourceLocator|null */
66
+    public static $jsLocator = null;
67
+
68
+    /** @var IConfig */
69
+    private $config;
70
+
71
+    /** @var IInitialStateService */
72
+    private $initialState;
73
+
74
+    /** @var INavigationManager */
75
+    private $navigationManager;
76
+
77
+    /**
78
+     * @param string $renderAs
79
+     * @param string $appId application id
80
+     */
81
+    public function __construct($renderAs, $appId = '') {
82
+
83
+        /** @var IConfig */
84
+        $this->config = \OC::$server->get(IConfig::class);
85
+
86
+        /** @var IInitialStateService */
87
+        $this->initialState = \OC::$server->get(IInitialStateService::class);
88
+
89
+        // Add fallback theming variables if theming is disabled
90
+        if ($renderAs !== TemplateResponse::RENDER_AS_USER
91
+            || !\OC::$server->getAppManager()->isEnabledForUser('theming')) {
92
+            // TODO cache generated default theme if enabled for fallback if server is erroring ?
93
+            Util::addStyle('theming', 'default');
94
+        }
95
+
96
+        // Decide which page we show
97
+        if ($renderAs === TemplateResponse::RENDER_AS_USER) {
98
+            /** @var INavigationManager */
99
+            $this->navigationManager = \OC::$server->get(INavigationManager::class);
100
+
101
+            parent::__construct('core', 'layout.user');
102
+            if (in_array(\OC_App::getCurrentApp(), ['settings','admin', 'help']) !== false) {
103
+                $this->assign('bodyid', 'body-settings');
104
+            } else {
105
+                $this->assign('bodyid', 'body-user');
106
+            }
107
+
108
+            $this->initialState->provideInitialState('core', 'active-app', $this->navigationManager->getActiveEntry());
109
+            $this->initialState->provideInitialState('core', 'apps', $this->navigationManager->getAll());
110
+            $this->initialState->provideInitialState('unified-search', 'limit-default', (int)$this->config->getAppValue('core', 'unified-search.limit-default', (string)SearchQuery::LIMIT_DEFAULT));
111
+            $this->initialState->provideInitialState('unified-search', 'min-search-length', (int)$this->config->getAppValue('core', 'unified-search.min-search-length', (string)1));
112
+            $this->initialState->provideInitialState('unified-search', 'live-search', $this->config->getAppValue('core', 'unified-search.live-search', 'yes') === 'yes');
113
+            Util::addScript('core', 'unified-search', 'core');
114
+
115
+            // Set body data-theme
116
+            $this->assign('enabledThemes', []);
117
+            if (\OC::$server->getAppManager()->isEnabledForUser('theming') && class_exists('\OCA\Theming\Service\ThemesService')) {
118
+                /** @var \OCA\Theming\Service\ThemesService */
119
+                $themesService = \OC::$server->get(\OCA\Theming\Service\ThemesService::class);
120
+                $this->assign('enabledThemes', $themesService->getEnabledThemes());
121
+            }
122
+
123
+            // set logo link target
124
+            $logoUrl = $this->config->getSystemValueString('logo_url', '');
125
+            $this->assign('logoUrl', $logoUrl);
126
+
127
+            // Add navigation entry
128
+            $this->assign('application', '');
129
+            $this->assign('appid', $appId);
130
+
131
+            $navigation = $this->navigationManager->getAll();
132
+            $this->assign('navigation', $navigation);
133
+            $settingsNavigation = $this->navigationManager->getAll('settings');
134
+            $this->assign('settingsnavigation', $settingsNavigation);
135
+
136
+            foreach ($navigation as $entry) {
137
+                if ($entry['active']) {
138
+                    $this->assign('application', $entry['name']);
139
+                    break;
140
+                }
141
+            }
142
+
143
+            foreach ($settingsNavigation as $entry) {
144
+                if ($entry['active']) {
145
+                    $this->assign('application', $entry['name']);
146
+                    break;
147
+                }
148
+            }
149
+
150
+            $userDisplayName = false;
151
+            $user = \OC::$server->get(IUserSession::class)->getUser();
152
+            if ($user) {
153
+                $userDisplayName = $user->getDisplayName();
154
+            }
155
+            $this->assign('user_displayname', $userDisplayName);
156
+            $this->assign('user_uid', \OC_User::getUser());
157
+
158
+            if ($user === null) {
159
+                $this->assign('userAvatarSet', false);
160
+                $this->assign('userStatus', false);
161
+            } else {
162
+                $this->assign('userAvatarSet', true);
163
+                $this->assign('userAvatarVersion', $this->config->getUserValue(\OC_User::getUser(), 'avatar', 'version', 0));
164
+            }
165
+        } elseif ($renderAs === TemplateResponse::RENDER_AS_ERROR) {
166
+            parent::__construct('core', 'layout.guest', '', false);
167
+            $this->assign('bodyid', 'body-login');
168
+            $this->assign('user_displayname', '');
169
+            $this->assign('user_uid', '');
170
+        } elseif ($renderAs === TemplateResponse::RENDER_AS_GUEST) {
171
+            parent::__construct('core', 'layout.guest');
172
+            \OC_Util::addStyle('guest');
173
+            $this->assign('bodyid', 'body-login');
174
+
175
+            $userDisplayName = false;
176
+            $user = \OC::$server->get(IUserSession::class)->getUser();
177
+            if ($user) {
178
+                $userDisplayName = $user->getDisplayName();
179
+            }
180
+            $this->assign('user_displayname', $userDisplayName);
181
+            $this->assign('user_uid', \OC_User::getUser());
182
+        } elseif ($renderAs === TemplateResponse::RENDER_AS_PUBLIC) {
183
+            parent::__construct('core', 'layout.public');
184
+            $this->assign('appid', $appId);
185
+            $this->assign('bodyid', 'body-public');
186
+
187
+            /** @var IRegistry $subscription */
188
+            $subscription = \OC::$server->query(IRegistry::class);
189
+            $showSimpleSignup = $this->config->getSystemValueBool('simpleSignUpLink.shown', true);
190
+            if ($showSimpleSignup && $subscription->delegateHasValidSubscription()) {
191
+                $showSimpleSignup = false;
192
+            }
193
+            $this->assign('showSimpleSignUpLink', $showSimpleSignup);
194
+        } else {
195
+            parent::__construct('core', 'layout.base');
196
+        }
197
+        // Send the language and the locale to our layouts
198
+        $lang = \OC::$server->getL10NFactory()->findLanguage();
199
+        $locale = \OC::$server->getL10NFactory()->findLocale($lang);
200
+
201
+        $lang = str_replace('_', '-', $lang);
202
+        $this->assign('language', $lang);
203
+        $this->assign('locale', $locale);
204
+
205
+        if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
206
+            if (empty(self::$versionHash)) {
207
+                $v = \OC_App::getAppVersions();
208
+                $v['core'] = implode('.', \OCP\Util::getVersion());
209
+                self::$versionHash = substr(md5(implode(',', $v)), 0, 8);
210
+            }
211
+        } else {
212
+            self::$versionHash = md5('not installed');
213
+        }
214
+
215
+        // Add the js files
216
+        // TODO: remove deprecated OC_Util injection
217
+        $jsFiles = self::findJavascriptFiles(array_merge(\OC_Util::$scripts, Util::getScripts()));
218
+        $this->assign('jsfiles', []);
219
+        if ($this->config->getSystemValue('installed', false) && $renderAs != TemplateResponse::RENDER_AS_ERROR) {
220
+            // this is on purpose outside of the if statement below so that the initial state is prefilled (done in the getConfig() call)
221
+            // see https://github.com/nextcloud/server/pull/22636 for details
222
+            $jsConfigHelper = new JSConfigHelper(
223
+                \OC::$server->getL10N('lib'),
224
+                \OC::$server->query(Defaults::class),
225
+                \OC::$server->getAppManager(),
226
+                \OC::$server->getSession(),
227
+                \OC::$server->getUserSession()->getUser(),
228
+                $this->config,
229
+                \OC::$server->getGroupManager(),
230
+                \OC::$server->get(IniGetWrapper::class),
231
+                \OC::$server->getURLGenerator(),
232
+                \OC::$server->getCapabilitiesManager(),
233
+                \OC::$server->query(IInitialStateService::class)
234
+            );
235
+            $config = $jsConfigHelper->getConfig();
236
+            if (\OC::$server->getContentSecurityPolicyNonceManager()->browserSupportsCspV3()) {
237
+                $this->assign('inline_ocjs', $config);
238
+            } else {
239
+                $this->append('jsfiles', \OC::$server->getURLGenerator()->linkToRoute('core.OCJS.getConfig', ['v' => self::$versionHash]));
240
+            }
241
+        }
242
+        foreach ($jsFiles as $info) {
243
+            $web = $info[1];
244
+            $file = $info[2];
245
+            $this->append('jsfiles', $web.'/'.$file . $this->getVersionHashSuffix());
246
+        }
247
+
248
+        try {
249
+            $pathInfo = \OC::$server->getRequest()->getPathInfo();
250
+        } catch (\Exception $e) {
251
+            $pathInfo = '';
252
+        }
253
+
254
+        // Do not initialise scss appdata until we have a fully installed instance
255
+        // Do not load scss for update, errors, installation or login page
256
+        if (\OC::$server->getSystemConfig()->getValue('installed', false)
257
+            && !\OCP\Util::needUpgrade()
258
+            && $pathInfo !== ''
259
+            && !preg_match('/^\/login/', $pathInfo)
260
+            && $renderAs !== TemplateResponse::RENDER_AS_ERROR
261
+        ) {
262
+            $cssFiles = self::findStylesheetFiles(\OC_Util::$styles);
263
+        } else {
264
+            // If we ignore the scss compiler,
265
+            // we need to load the guest css fallback
266
+            \OC_Util::addStyle('guest');
267
+            $cssFiles = self::findStylesheetFiles(\OC_Util::$styles, false);
268
+        }
269
+
270
+        $this->assign('cssfiles', []);
271
+        $this->assign('printcssfiles', []);
272
+        $this->assign('versionHash', self::$versionHash);
273
+        foreach ($cssFiles as $info) {
274
+            $web = $info[1];
275
+            $file = $info[2];
276
+
277
+            if (substr($file, -strlen('print.css')) === 'print.css') {
278
+                $this->append('printcssfiles', $web.'/'.$file . $this->getVersionHashSuffix());
279
+            } else {
280
+                $suffix = $this->getVersionHashSuffix($web, $file);
281
+
282
+                if (strpos($file, '?v=') == false) {
283
+                    $this->append('cssfiles', $web.'/'.$file . $suffix);
284
+                } else {
285
+                    $this->append('cssfiles', $web.'/'.$file . '-' . substr($suffix, 3));
286
+                }
287
+            }
288
+        }
289
+
290
+        $this->assign('initialStates', $this->initialState->getInitialStates());
291
+
292
+        $this->assign('id-app-content', $renderAs === TemplateResponse::RENDER_AS_USER ? '#app-content' : '#content');
293
+        $this->assign('id-app-navigation', $renderAs === TemplateResponse::RENDER_AS_USER ? '#app-navigation' : null);
294
+    }
295
+
296
+    /**
297
+     * @param string $path
298
+     * @param string $file
299
+     * @return string
300
+     */
301
+    protected function getVersionHashSuffix($path = false, $file = false) {
302
+        if ($this->config->getSystemValue('debug', false)) {
303
+            // allows chrome workspace mapping in debug mode
304
+            return "";
305
+        }
306
+        $themingSuffix = '';
307
+        $v = [];
308
+
309
+        if ($this->config->getSystemValue('installed', false)) {
310
+            if (\OC::$server->getAppManager()->isInstalled('theming')) {
311
+                $themingSuffix = '-' . $this->config->getAppValue('theming', 'cachebuster', '0');
312
+            }
313
+            $v = \OC_App::getAppVersions();
314
+        }
315
+
316
+        // Try the webroot path for a match
317
+        if ($path !== false && $path !== '') {
318
+            $appName = $this->getAppNamefromPath($path);
319
+            if (array_key_exists($appName, $v)) {
320
+                $appVersion = $v[$appName];
321
+                return '?v=' . substr(md5($appVersion), 0, 8) . $themingSuffix;
322
+            }
323
+        }
324
+        // fallback to the file path instead
325
+        if ($file !== false && $file !== '') {
326
+            $appName = $this->getAppNamefromPath($file);
327
+            if (array_key_exists($appName, $v)) {
328
+                $appVersion = $v[$appName];
329
+                return '?v=' . substr(md5($appVersion), 0, 8) . $themingSuffix;
330
+            }
331
+        }
332
+
333
+        return '?v=' . self::$versionHash . $themingSuffix;
334
+    }
335
+
336
+    /**
337
+     * @param array $styles
338
+     * @return array
339
+     */
340
+    public static function findStylesheetFiles($styles, $compileScss = true) {
341
+        if (!self::$cssLocator) {
342
+            self::$cssLocator = \OCP\Server::get(CSSResourceLocator::class);
343
+        }
344
+        self::$cssLocator->find($styles);
345
+        return self::$cssLocator->getResources();
346
+    }
347
+
348
+    /**
349
+     * @param string $path
350
+     * @return string|boolean
351
+     */
352
+    public function getAppNamefromPath($path) {
353
+        if ($path !== '' && is_string($path)) {
354
+            $pathParts = explode('/', $path);
355
+            if ($pathParts[0] === 'css') {
356
+                // This is a scss request
357
+                return $pathParts[1];
358
+            }
359
+            return end($pathParts);
360
+        }
361
+        return false;
362
+    }
363
+
364
+    /**
365
+     * @param array $scripts
366
+     * @return array
367
+     */
368
+    public static function findJavascriptFiles($scripts) {
369
+        if (!self::$jsLocator) {
370
+            self::$jsLocator = \OCP\Server::get(JSResourceLocator::class);
371
+        }
372
+        self::$jsLocator->find($scripts);
373
+        return self::$jsLocator->getResources();
374
+    }
375
+
376
+    /**
377
+     * Converts the absolute file path to a relative path from \OC::$SERVERROOT
378
+     * @param string $filePath Absolute path
379
+     * @return string Relative path
380
+     * @throws \Exception If $filePath is not under \OC::$SERVERROOT
381
+     */
382
+    public static function convertToRelativePath($filePath) {
383
+        $relativePath = explode(\OC::$SERVERROOT, $filePath);
384
+        if (count($relativePath) !== 2) {
385
+            throw new \Exception('$filePath is not under the \OC::$SERVERROOT');
386
+        }
387
+
388
+        return $relativePath[1];
389
+    }
390 390
 }
Please login to merge, or discard this patch.
lib/base.php 1 patch
Indentation   +1073 added lines, -1073 removed lines patch added patch discarded remove patch
@@ -82,1079 +82,1079 @@
 block discarded – undo
82 82
  * OC_autoload!
83 83
  */
84 84
 class OC {
85
-	/**
86
-	 * Associative array for autoloading. classname => filename
87
-	 */
88
-	public static $CLASSPATH = [];
89
-	/**
90
-	 * The installation path for Nextcloud  on the server (e.g. /srv/http/nextcloud)
91
-	 */
92
-	public static $SERVERROOT = '';
93
-	/**
94
-	 * the current request path relative to the Nextcloud root (e.g. files/index.php)
95
-	 */
96
-	private static $SUBURI = '';
97
-	/**
98
-	 * the Nextcloud root path for http requests (e.g. nextcloud/)
99
-	 */
100
-	public static $WEBROOT = '';
101
-	/**
102
-	 * The installation path array of the apps folder on the server (e.g. /srv/http/nextcloud) 'path' and
103
-	 * web path in 'url'
104
-	 */
105
-	public static $APPSROOTS = [];
106
-
107
-	/**
108
-	 * @var string
109
-	 */
110
-	public static $configDir;
111
-
112
-	/**
113
-	 * requested app
114
-	 */
115
-	public static $REQUESTEDAPP = '';
116
-
117
-	/**
118
-	 * check if Nextcloud runs in cli mode
119
-	 */
120
-	public static $CLI = false;
121
-
122
-	/**
123
-	 * @var \OC\Autoloader $loader
124
-	 */
125
-	public static $loader = null;
126
-
127
-	/** @var \Composer\Autoload\ClassLoader $composerAutoloader */
128
-	public static $composerAutoloader = null;
129
-
130
-	/**
131
-	 * @var \OC\Server
132
-	 */
133
-	public static $server = null;
134
-
135
-	/**
136
-	 * @var \OC\Config
137
-	 */
138
-	private static $config = null;
139
-
140
-	/**
141
-	 * @throws \RuntimeException when the 3rdparty directory is missing or
142
-	 * the app path list is empty or contains an invalid path
143
-	 */
144
-	public static function initPaths() {
145
-		if (defined('PHPUNIT_CONFIG_DIR')) {
146
-			self::$configDir = OC::$SERVERROOT . '/' . PHPUNIT_CONFIG_DIR . '/';
147
-		} elseif (defined('PHPUNIT_RUN') and PHPUNIT_RUN and is_dir(OC::$SERVERROOT . '/tests/config/')) {
148
-			self::$configDir = OC::$SERVERROOT . '/tests/config/';
149
-		} elseif ($dir = getenv('NEXTCLOUD_CONFIG_DIR')) {
150
-			self::$configDir = rtrim($dir, '/') . '/';
151
-		} else {
152
-			self::$configDir = OC::$SERVERROOT . '/config/';
153
-		}
154
-		self::$config = new \OC\Config(self::$configDir);
155
-
156
-		OC::$SUBURI = str_replace("\\", "/", substr(realpath($_SERVER["SCRIPT_FILENAME"]), strlen(OC::$SERVERROOT)));
157
-		/**
158
-		 * FIXME: The following lines are required because we can't yet instantiate
159
-		 *        \OC::$server->getRequest() since \OC::$server does not yet exist.
160
-		 */
161
-		$params = [
162
-			'server' => [
163
-				'SCRIPT_NAME' => $_SERVER['SCRIPT_NAME'],
164
-				'SCRIPT_FILENAME' => $_SERVER['SCRIPT_FILENAME'],
165
-			],
166
-		];
167
-		$fakeRequest = new \OC\AppFramework\Http\Request(
168
-			$params,
169
-			new \OC\AppFramework\Http\RequestId($_SERVER['UNIQUE_ID'] ?? '', new \OC\Security\SecureRandom()),
170
-			new \OC\AllConfig(new \OC\SystemConfig(self::$config))
171
-		);
172
-		$scriptName = $fakeRequest->getScriptName();
173
-		if (substr($scriptName, -1) == '/') {
174
-			$scriptName .= 'index.php';
175
-			//make sure suburi follows the same rules as scriptName
176
-			if (substr(OC::$SUBURI, -9) != 'index.php') {
177
-				if (substr(OC::$SUBURI, -1) != '/') {
178
-					OC::$SUBURI = OC::$SUBURI . '/';
179
-				}
180
-				OC::$SUBURI = OC::$SUBURI . 'index.php';
181
-			}
182
-		}
183
-
184
-
185
-		if (OC::$CLI) {
186
-			OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
187
-		} else {
188
-			if (substr($scriptName, 0 - strlen(OC::$SUBURI)) === OC::$SUBURI) {
189
-				OC::$WEBROOT = substr($scriptName, 0, 0 - strlen(OC::$SUBURI));
190
-
191
-				if (OC::$WEBROOT != '' && OC::$WEBROOT[0] !== '/') {
192
-					OC::$WEBROOT = '/' . OC::$WEBROOT;
193
-				}
194
-			} else {
195
-				// The scriptName is not ending with OC::$SUBURI
196
-				// This most likely means that we are calling from CLI.
197
-				// However some cron jobs still need to generate
198
-				// a web URL, so we use overwritewebroot as a fallback.
199
-				OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
200
-			}
201
-
202
-			// Resolve /nextcloud to /nextcloud/ to ensure to always have a trailing
203
-			// slash which is required by URL generation.
204
-			if (isset($_SERVER['REQUEST_URI']) && $_SERVER['REQUEST_URI'] === \OC::$WEBROOT &&
205
-					substr($_SERVER['REQUEST_URI'], -1) !== '/') {
206
-				header('Location: '.\OC::$WEBROOT.'/');
207
-				exit();
208
-			}
209
-		}
210
-
211
-		// search the apps folder
212
-		$config_paths = self::$config->getValue('apps_paths', []);
213
-		if (!empty($config_paths)) {
214
-			foreach ($config_paths as $paths) {
215
-				if (isset($paths['url']) && isset($paths['path'])) {
216
-					$paths['url'] = rtrim($paths['url'], '/');
217
-					$paths['path'] = rtrim($paths['path'], '/');
218
-					OC::$APPSROOTS[] = $paths;
219
-				}
220
-			}
221
-		} elseif (file_exists(OC::$SERVERROOT . '/apps')) {
222
-			OC::$APPSROOTS[] = ['path' => OC::$SERVERROOT . '/apps', 'url' => '/apps', 'writable' => true];
223
-		}
224
-
225
-		if (empty(OC::$APPSROOTS)) {
226
-			throw new \RuntimeException('apps directory not found! Please put the Nextcloud apps folder in the Nextcloud folder'
227
-				. '. You can also configure the location in the config.php file.');
228
-		}
229
-		$paths = [];
230
-		foreach (OC::$APPSROOTS as $path) {
231
-			$paths[] = $path['path'];
232
-			if (!is_dir($path['path'])) {
233
-				throw new \RuntimeException(sprintf('App directory "%s" not found! Please put the Nextcloud apps folder in the'
234
-					. ' Nextcloud folder. You can also configure the location in the config.php file.', $path['path']));
235
-			}
236
-		}
237
-
238
-		// set the right include path
239
-		set_include_path(
240
-			implode(PATH_SEPARATOR, $paths)
241
-		);
242
-	}
243
-
244
-	public static function checkConfig() {
245
-		$l = \OC::$server->getL10N('lib');
246
-
247
-		// Create config if it does not already exist
248
-		$configFilePath = self::$configDir .'/config.php';
249
-		if (!file_exists($configFilePath)) {
250
-			@touch($configFilePath);
251
-		}
252
-
253
-		// Check if config is writable
254
-		$configFileWritable = is_writable($configFilePath);
255
-		if (!$configFileWritable && !OC_Helper::isReadOnlyConfigEnabled()
256
-			|| !$configFileWritable && \OCP\Util::needUpgrade()) {
257
-			$urlGenerator = \OC::$server->getURLGenerator();
258
-
259
-			if (self::$CLI) {
260
-				echo $l->t('Cannot write into "config" directory!')."\n";
261
-				echo $l->t('This can usually be fixed by giving the web server write access to the config directory.')."\n";
262
-				echo "\n";
263
-				echo $l->t('But, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it.')."\n";
264
-				echo $l->t('See %s', [ $urlGenerator->linkToDocs('admin-config') ])."\n";
265
-				exit;
266
-			} else {
267
-				OC_Template::printErrorPage(
268
-					$l->t('Cannot write into "config" directory!'),
269
-					$l->t('This can usually be fixed by giving the web server write access to the config directory.') . ' '
270
-					. $l->t('But, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it.') . ' '
271
-					. $l->t('See %s', [ $urlGenerator->linkToDocs('admin-config') ]),
272
-					503
273
-				);
274
-			}
275
-		}
276
-	}
277
-
278
-	public static function checkInstalled(\OC\SystemConfig $systemConfig) {
279
-		if (defined('OC_CONSOLE')) {
280
-			return;
281
-		}
282
-		// Redirect to installer if not installed
283
-		if (!$systemConfig->getValue('installed', false) && OC::$SUBURI !== '/index.php' && OC::$SUBURI !== '/status.php') {
284
-			if (OC::$CLI) {
285
-				throw new Exception('Not installed');
286
-			} else {
287
-				$url = OC::$WEBROOT . '/index.php';
288
-				header('Location: ' . $url);
289
-			}
290
-			exit();
291
-		}
292
-	}
293
-
294
-	public static function checkMaintenanceMode(\OC\SystemConfig $systemConfig) {
295
-		// Allow ajax update script to execute without being stopped
296
-		if (((bool) $systemConfig->getValue('maintenance', false)) && OC::$SUBURI != '/core/ajax/update.php') {
297
-			// send http status 503
298
-			http_response_code(503);
299
-			header('X-Nextcloud-Maintenance-Mode: 1');
300
-			header('Retry-After: 120');
301
-
302
-			// render error page
303
-			$template = new OC_Template('', 'update.user', 'guest');
304
-			\OCP\Util::addScript('core', 'maintenance');
305
-			\OCP\Util::addStyle('core', 'guest');
306
-			$template->printPage();
307
-			die();
308
-		}
309
-	}
310
-
311
-	/**
312
-	 * Prints the upgrade page
313
-	 *
314
-	 * @param \OC\SystemConfig $systemConfig
315
-	 */
316
-	private static function printUpgradePage(\OC\SystemConfig $systemConfig) {
317
-		$disableWebUpdater = $systemConfig->getValue('upgrade.disable-web', false);
318
-		$tooBig = false;
319
-		if (!$disableWebUpdater) {
320
-			$apps = \OC::$server->getAppManager();
321
-			if ($apps->isInstalled('user_ldap')) {
322
-				$qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
323
-
324
-				$result = $qb->select($qb->func()->count('*', 'user_count'))
325
-					->from('ldap_user_mapping')
326
-					->execute();
327
-				$row = $result->fetch();
328
-				$result->closeCursor();
329
-
330
-				$tooBig = ($row['user_count'] > 50);
331
-			}
332
-			if (!$tooBig && $apps->isInstalled('user_saml')) {
333
-				$qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
334
-
335
-				$result = $qb->select($qb->func()->count('*', 'user_count'))
336
-					->from('user_saml_users')
337
-					->execute();
338
-				$row = $result->fetch();
339
-				$result->closeCursor();
340
-
341
-				$tooBig = ($row['user_count'] > 50);
342
-			}
343
-			if (!$tooBig) {
344
-				// count users
345
-				$stats = \OC::$server->getUserManager()->countUsers();
346
-				$totalUsers = array_sum($stats);
347
-				$tooBig = ($totalUsers > 50);
348
-			}
349
-		}
350
-		$ignoreTooBigWarning = isset($_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup']) &&
351
-			$_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup'] === 'IAmSuperSureToDoThis';
352
-
353
-		if ($disableWebUpdater || ($tooBig && !$ignoreTooBigWarning)) {
354
-			// send http status 503
355
-			http_response_code(503);
356
-			header('Retry-After: 120');
357
-
358
-			// render error page
359
-			$template = new OC_Template('', 'update.use-cli', 'guest');
360
-			$template->assign('productName', 'nextcloud'); // for now
361
-			$template->assign('version', OC_Util::getVersionString());
362
-			$template->assign('tooBig', $tooBig);
363
-
364
-			$template->printPage();
365
-			die();
366
-		}
367
-
368
-		// check whether this is a core update or apps update
369
-		$installedVersion = $systemConfig->getValue('version', '0.0.0');
370
-		$currentVersion = implode('.', \OCP\Util::getVersion());
371
-
372
-		// if not a core upgrade, then it's apps upgrade
373
-		$isAppsOnlyUpgrade = version_compare($currentVersion, $installedVersion, '=');
374
-
375
-		$oldTheme = $systemConfig->getValue('theme');
376
-		$systemConfig->setValue('theme', '');
377
-		\OCP\Util::addScript('core', 'common');
378
-		\OCP\Util::addScript('core', 'main');
379
-		\OCP\Util::addTranslations('core');
380
-		\OCP\Util::addScript('core', 'update');
381
-
382
-		/** @var \OC\App\AppManager $appManager */
383
-		$appManager = \OC::$server->getAppManager();
384
-
385
-		$tmpl = new OC_Template('', 'update.admin', 'guest');
386
-		$tmpl->assign('version', OC_Util::getVersionString());
387
-		$tmpl->assign('isAppsOnlyUpgrade', $isAppsOnlyUpgrade);
388
-
389
-		// get third party apps
390
-		$ocVersion = \OCP\Util::getVersion();
391
-		$ocVersion = implode('.', $ocVersion);
392
-		$incompatibleApps = $appManager->getIncompatibleApps($ocVersion);
393
-		$incompatibleShippedApps = [];
394
-		foreach ($incompatibleApps as $appInfo) {
395
-			if ($appManager->isShipped($appInfo['id'])) {
396
-				$incompatibleShippedApps[] = $appInfo['name'] . ' (' . $appInfo['id'] . ')';
397
-			}
398
-		}
399
-
400
-		if (!empty($incompatibleShippedApps)) {
401
-			$l = \OC::$server->getL10N('core');
402
-			$hint = $l->t('The files of the app %1$s were not replaced correctly. Make sure it is a version compatible with the server.', [implode(', ', $incompatibleShippedApps)]);
403
-			throw new \OCP\HintException('The files of the app ' . implode(', ', $incompatibleShippedApps) . ' were not replaced correctly. Make sure it is a version compatible with the server.', $hint);
404
-		}
405
-
406
-		$tmpl->assign('appsToUpgrade', $appManager->getAppsNeedingUpgrade($ocVersion));
407
-		$tmpl->assign('incompatibleAppsList', $incompatibleApps);
408
-		try {
409
-			$defaults = new \OC_Defaults();
410
-			$tmpl->assign('productName', $defaults->getName());
411
-		} catch (Throwable $error) {
412
-			$tmpl->assign('productName', 'Nextcloud');
413
-		}
414
-		$tmpl->assign('oldTheme', $oldTheme);
415
-		$tmpl->printPage();
416
-	}
417
-
418
-	public static function initSession() {
419
-		if (self::$server->getRequest()->getServerProtocol() === 'https') {
420
-			ini_set('session.cookie_secure', 'true');
421
-		}
422
-
423
-		// prevents javascript from accessing php session cookies
424
-		ini_set('session.cookie_httponly', 'true');
425
-
426
-		// set the cookie path to the Nextcloud directory
427
-		$cookie_path = OC::$WEBROOT ? : '/';
428
-		ini_set('session.cookie_path', $cookie_path);
429
-
430
-		// Let the session name be changed in the initSession Hook
431
-		$sessionName = OC_Util::getInstanceId();
432
-
433
-		try {
434
-			// set the session name to the instance id - which is unique
435
-			$session = new \OC\Session\Internal($sessionName);
436
-
437
-			$cryptoWrapper = \OC::$server->getSessionCryptoWrapper();
438
-			$session = $cryptoWrapper->wrapSession($session);
439
-			self::$server->setSession($session);
440
-
441
-			// if session can't be started break with http 500 error
442
-		} catch (Exception $e) {
443
-			\OC::$server->getLogger()->logException($e, ['app' => 'base']);
444
-			//show the user a detailed error page
445
-			OC_Template::printExceptionErrorPage($e, 500);
446
-			die();
447
-		}
448
-
449
-		//try to set the session lifetime
450
-		$sessionLifeTime = self::getSessionLifeTime();
451
-		@ini_set('gc_maxlifetime', (string)$sessionLifeTime);
452
-
453
-		// session timeout
454
-		if ($session->exists('LAST_ACTIVITY') && (time() - $session->get('LAST_ACTIVITY') > $sessionLifeTime)) {
455
-			if (isset($_COOKIE[session_name()])) {
456
-				setcookie(session_name(), '', -1, self::$WEBROOT ? : '/');
457
-			}
458
-			\OC::$server->getUserSession()->logout();
459
-		}
460
-
461
-		if (!self::hasSessionRelaxedExpiry()) {
462
-			$session->set('LAST_ACTIVITY', time());
463
-		}
464
-		$session->close();
465
-	}
466
-
467
-	/**
468
-	 * @return string
469
-	 */
470
-	private static function getSessionLifeTime() {
471
-		return \OC::$server->getConfig()->getSystemValue('session_lifetime', 60 * 60 * 24);
472
-	}
473
-
474
-	/**
475
-	 * @return bool true if the session expiry should only be done by gc instead of an explicit timeout
476
-	 */
477
-	public static function hasSessionRelaxedExpiry(): bool {
478
-		return \OC::$server->getConfig()->getSystemValue('session_relaxed_expiry', false);
479
-	}
480
-
481
-	/**
482
-	 * Try to set some values to the required Nextcloud default
483
-	 */
484
-	public static function setRequiredIniValues() {
485
-		@ini_set('default_charset', 'UTF-8');
486
-		@ini_set('gd.jpeg_ignore_warning', '1');
487
-	}
488
-
489
-	/**
490
-	 * Send the same site cookies
491
-	 */
492
-	private static function sendSameSiteCookies() {
493
-		$cookieParams = session_get_cookie_params();
494
-		$secureCookie = ($cookieParams['secure'] === true) ? 'secure; ' : '';
495
-		$policies = [
496
-			'lax',
497
-			'strict',
498
-		];
499
-
500
-		// Append __Host to the cookie if it meets the requirements
501
-		$cookiePrefix = '';
502
-		if ($cookieParams['secure'] === true && $cookieParams['path'] === '/') {
503
-			$cookiePrefix = '__Host-';
504
-		}
505
-
506
-		foreach ($policies as $policy) {
507
-			header(
508
-				sprintf(
509
-					'Set-Cookie: %snc_sameSiteCookie%s=true; path=%s; httponly;' . $secureCookie . 'expires=Fri, 31-Dec-2100 23:59:59 GMT; SameSite=%s',
510
-					$cookiePrefix,
511
-					$policy,
512
-					$cookieParams['path'],
513
-					$policy
514
-				),
515
-				false
516
-			);
517
-		}
518
-	}
519
-
520
-	/**
521
-	 * Same Site cookie to further mitigate CSRF attacks. This cookie has to
522
-	 * be set in every request if cookies are sent to add a second level of
523
-	 * defense against CSRF.
524
-	 *
525
-	 * If the cookie is not sent this will set the cookie and reload the page.
526
-	 * We use an additional cookie since we want to protect logout CSRF and
527
-	 * also we can't directly interfere with PHP's session mechanism.
528
-	 */
529
-	private static function performSameSiteCookieProtection(\OCP\IConfig $config) {
530
-		$request = \OC::$server->getRequest();
531
-
532
-		// Some user agents are notorious and don't really properly follow HTTP
533
-		// specifications. For those, have an automated opt-out. Since the protection
534
-		// for remote.php is applied in base.php as starting point we need to opt out
535
-		// here.
536
-		$incompatibleUserAgents = $config->getSystemValue('csrf.optout');
537
-
538
-		// Fallback, if csrf.optout is unset
539
-		if (!is_array($incompatibleUserAgents)) {
540
-			$incompatibleUserAgents = [
541
-				// OS X Finder
542
-				'/^WebDAVFS/',
543
-				// Windows webdav drive
544
-				'/^Microsoft-WebDAV-MiniRedir/',
545
-			];
546
-		}
547
-
548
-		if ($request->isUserAgent($incompatibleUserAgents)) {
549
-			return;
550
-		}
551
-
552
-		if (count($_COOKIE) > 0) {
553
-			$requestUri = $request->getScriptName();
554
-			$processingScript = explode('/', $requestUri);
555
-			$processingScript = $processingScript[count($processingScript) - 1];
556
-
557
-			// index.php routes are handled in the middleware
558
-			if ($processingScript === 'index.php') {
559
-				return;
560
-			}
561
-
562
-			// All other endpoints require the lax and the strict cookie
563
-			if (!$request->passesStrictCookieCheck()) {
564
-				self::sendSameSiteCookies();
565
-				// Debug mode gets access to the resources without strict cookie
566
-				// due to the fact that the SabreDAV browser also lives there.
567
-				if (!$config->getSystemValue('debug', false)) {
568
-					http_response_code(\OCP\AppFramework\Http::STATUS_SERVICE_UNAVAILABLE);
569
-					exit();
570
-				}
571
-			}
572
-		} elseif (!isset($_COOKIE['nc_sameSiteCookielax']) || !isset($_COOKIE['nc_sameSiteCookiestrict'])) {
573
-			self::sendSameSiteCookies();
574
-		}
575
-	}
576
-
577
-	public static function init() {
578
-		// calculate the root directories
579
-		OC::$SERVERROOT = str_replace("\\", '/', substr(__DIR__, 0, -4));
580
-
581
-		// register autoloader
582
-		$loaderStart = microtime(true);
583
-		require_once __DIR__ . '/autoloader.php';
584
-		self::$loader = new \OC\Autoloader([
585
-			OC::$SERVERROOT . '/lib/private/legacy',
586
-		]);
587
-		if (defined('PHPUNIT_RUN')) {
588
-			self::$loader->addValidRoot(OC::$SERVERROOT . '/tests');
589
-		}
590
-		spl_autoload_register([self::$loader, 'load']);
591
-		$loaderEnd = microtime(true);
592
-
593
-		self::$CLI = (php_sapi_name() == 'cli');
594
-
595
-		// Add default composer PSR-4 autoloader
596
-		self::$composerAutoloader = require_once OC::$SERVERROOT . '/lib/composer/autoload.php';
597
-		self::$composerAutoloader->setApcuPrefix('composer_autoload');
598
-
599
-		try {
600
-			self::initPaths();
601
-			// setup 3rdparty autoloader
602
-			$vendorAutoLoad = OC::$SERVERROOT. '/3rdparty/autoload.php';
603
-			if (!file_exists($vendorAutoLoad)) {
604
-				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".');
605
-			}
606
-			require_once $vendorAutoLoad;
607
-		} catch (\RuntimeException $e) {
608
-			if (!self::$CLI) {
609
-				http_response_code(503);
610
-			}
611
-			// we can't use the template error page here, because this needs the
612
-			// DI container which isn't available yet
613
-			print($e->getMessage());
614
-			exit();
615
-		}
616
-
617
-		// setup the basic server
618
-		self::$server = new \OC\Server(\OC::$WEBROOT, self::$config);
619
-		self::$server->boot();
620
-
621
-		$eventLogger = \OC::$server->getEventLogger();
622
-		$eventLogger->log('autoloader', 'Autoloader', $loaderStart, $loaderEnd);
623
-		$eventLogger->start('boot', 'Initialize');
624
-
625
-		// Override php.ini and log everything if we're troubleshooting
626
-		if (self::$config->getValue('loglevel') === ILogger::DEBUG) {
627
-			error_reporting(E_ALL);
628
-		}
629
-
630
-		// Don't display errors and log them
631
-		@ini_set('display_errors', '0');
632
-		@ini_set('log_errors', '1');
633
-
634
-		if (!date_default_timezone_set('UTC')) {
635
-			throw new \RuntimeException('Could not set timezone to UTC');
636
-		}
637
-
638
-
639
-		//try to configure php to enable big file uploads.
640
-		//this doesn´t work always depending on the webserver and php configuration.
641
-		//Let´s try to overwrite some defaults if they are smaller than 1 hour
642
-
643
-		if (intval(@ini_get('max_execution_time') ?? 0) < 3600) {
644
-			@ini_set('max_execution_time', strval(3600));
645
-		}
646
-
647
-		if (intval(@ini_get('max_input_time') ?? 0) < 3600) {
648
-			@ini_set('max_input_time', strval(3600));
649
-		}
650
-
651
-		//try to set the maximum execution time to the largest time limit we have
652
-		if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
653
-			@set_time_limit(max(intval(@ini_get('max_execution_time')), intval(@ini_get('max_input_time'))));
654
-		}
655
-
656
-		self::setRequiredIniValues();
657
-		self::handleAuthHeaders();
658
-		$systemConfig = \OC::$server->get(\OC\SystemConfig::class);
659
-		self::registerAutoloaderCache($systemConfig);
660
-
661
-		// initialize intl fallback if necessary
662
-		OC_Util::isSetLocaleWorking();
663
-
664
-		$config = \OC::$server->get(\OCP\IConfig::class);
665
-		if (!defined('PHPUNIT_RUN')) {
666
-			$errorHandler = new OC\Log\ErrorHandler(
667
-				\OCP\Server::get(\Psr\Log\LoggerInterface::class),
668
-			);
669
-			$exceptionHandler = [$errorHandler, 'onException'];
670
-			if ($config->getSystemValue('debug', false)) {
671
-				set_error_handler([$errorHandler, 'onAll'], E_ALL);
672
-				if (\OC::$CLI) {
673
-					$exceptionHandler = ['OC_Template', 'printExceptionErrorPage'];
674
-				}
675
-			} else {
676
-				set_error_handler([$errorHandler, 'onError']);
677
-			}
678
-			register_shutdown_function([$errorHandler, 'onShutdown']);
679
-			set_exception_handler($exceptionHandler);
680
-		}
681
-
682
-		/** @var \OC\AppFramework\Bootstrap\Coordinator $bootstrapCoordinator */
683
-		$bootstrapCoordinator = \OC::$server->query(\OC\AppFramework\Bootstrap\Coordinator::class);
684
-		$bootstrapCoordinator->runInitialRegistration();
685
-
686
-		$eventLogger->start('init_session', 'Initialize session');
687
-		OC_App::loadApps(['session']);
688
-		if (!self::$CLI) {
689
-			self::initSession();
690
-		}
691
-		$eventLogger->end('init_session');
692
-		self::checkConfig();
693
-		self::checkInstalled($systemConfig);
694
-
695
-		OC_Response::addSecurityHeaders();
696
-
697
-		self::performSameSiteCookieProtection($config);
698
-
699
-		if (!defined('OC_CONSOLE')) {
700
-			$errors = OC_Util::checkServer($systemConfig);
701
-			if (count($errors) > 0) {
702
-				if (!self::$CLI) {
703
-					http_response_code(503);
704
-					OC_Util::addStyle('guest');
705
-					try {
706
-						OC_Template::printGuestPage('', 'error', ['errors' => $errors]);
707
-						exit;
708
-					} catch (\Exception $e) {
709
-						// In case any error happens when showing the error page, we simply fall back to posting the text.
710
-						// This might be the case when e.g. the data directory is broken and we can not load/write SCSS to/from it.
711
-					}
712
-				}
713
-
714
-				// Convert l10n string into regular string for usage in database
715
-				$staticErrors = [];
716
-				foreach ($errors as $error) {
717
-					echo $error['error'] . "\n";
718
-					echo $error['hint'] . "\n\n";
719
-					$staticErrors[] = [
720
-						'error' => (string)$error['error'],
721
-						'hint' => (string)$error['hint'],
722
-					];
723
-				}
724
-
725
-				try {
726
-					$config->setAppValue('core', 'cronErrors', json_encode($staticErrors));
727
-				} catch (\Exception $e) {
728
-					echo('Writing to database failed');
729
-				}
730
-				exit(1);
731
-			} elseif (self::$CLI && $config->getSystemValue('installed', false)) {
732
-				$config->deleteAppValue('core', 'cronErrors');
733
-			}
734
-		}
735
-
736
-		// User and Groups
737
-		if (!$systemConfig->getValue("installed", false)) {
738
-			self::$server->getSession()->set('user_id', '');
739
-		}
740
-
741
-		OC_User::useBackend(new \OC\User\Database());
742
-		\OC::$server->getGroupManager()->addBackend(new \OC\Group\Database());
743
-
744
-		// Subscribe to the hook
745
-		\OCP\Util::connectHook(
746
-			'\OCA\Files_Sharing\API\Server2Server',
747
-			'preLoginNameUsedAsUserName',
748
-			'\OC\User\Database',
749
-			'preLoginNameUsedAsUserName'
750
-		);
751
-
752
-		//setup extra user backends
753
-		if (!\OCP\Util::needUpgrade()) {
754
-			OC_User::setupBackends();
755
-		} else {
756
-			// Run upgrades in incognito mode
757
-			OC_User::setIncognitoMode(true);
758
-		}
759
-
760
-		self::registerCleanupHooks($systemConfig);
761
-		self::registerShareHooks($systemConfig);
762
-		self::registerEncryptionWrapperAndHooks();
763
-		self::registerAccountHooks();
764
-		self::registerResourceCollectionHooks();
765
-		self::registerFileReferenceEventListener();
766
-		self::registerAppRestrictionsHooks();
767
-
768
-		// Make sure that the application class is not loaded before the database is setup
769
-		if ($systemConfig->getValue("installed", false)) {
770
-			OC_App::loadApp('settings');
771
-			/* Build core application to make sure that listeners are registered */
772
-			self::$server->get(\OC\Core\Application::class);
773
-		}
774
-
775
-		//make sure temporary files are cleaned up
776
-		$tmpManager = \OC::$server->getTempManager();
777
-		register_shutdown_function([$tmpManager, 'clean']);
778
-		$lockProvider = \OC::$server->getLockingProvider();
779
-		register_shutdown_function([$lockProvider, 'releaseAll']);
780
-
781
-		// Check whether the sample configuration has been copied
782
-		if ($systemConfig->getValue('copied_sample_config', false)) {
783
-			$l = \OC::$server->getL10N('lib');
784
-			OC_Template::printErrorPage(
785
-				$l->t('Sample configuration detected'),
786
-				$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'),
787
-				503
788
-			);
789
-			return;
790
-		}
791
-
792
-		$request = \OC::$server->getRequest();
793
-		$host = $request->getInsecureServerHost();
794
-		/**
795
-		 * if the host passed in headers isn't trusted
796
-		 * FIXME: Should not be in here at all :see_no_evil:
797
-		 */
798
-		if (!OC::$CLI
799
-			&& !\OC::$server->getTrustedDomainHelper()->isTrustedDomain($host)
800
-			&& $config->getSystemValue('installed', false)
801
-		) {
802
-			// Allow access to CSS resources
803
-			$isScssRequest = false;
804
-			if (strpos($request->getPathInfo(), '/css/') === 0) {
805
-				$isScssRequest = true;
806
-			}
807
-
808
-			if (substr($request->getRequestUri(), -11) === '/status.php') {
809
-				http_response_code(400);
810
-				header('Content-Type: application/json');
811
-				echo '{"error": "Trusted domain error.", "code": 15}';
812
-				exit();
813
-			}
814
-
815
-			if (!$isScssRequest) {
816
-				http_response_code(400);
817
-
818
-				\OC::$server->getLogger()->info(
819
-					'Trusted domain error. "{remoteAddress}" tried to access using "{host}" as host.',
820
-					[
821
-						'app' => 'core',
822
-						'remoteAddress' => $request->getRemoteAddress(),
823
-						'host' => $host,
824
-					]
825
-				);
826
-
827
-				$tmpl = new OCP\Template('core', 'untrustedDomain', 'guest');
828
-				$tmpl->assign('docUrl', \OC::$server->getURLGenerator()->linkToDocs('admin-trusted-domains'));
829
-				$tmpl->printPage();
830
-
831
-				exit();
832
-			}
833
-		}
834
-		$eventLogger->end('boot');
835
-		$eventLogger->log('init', 'OC::init', $loaderStart, microtime(true));
836
-		$eventLogger->start('runtime', 'Runtime');
837
-		$eventLogger->start('request', 'Full request after boot');
838
-		register_shutdown_function(function () use ($eventLogger) {
839
-			$eventLogger->end('request');
840
-		});
841
-	}
842
-
843
-	/**
844
-	 * register hooks for the cleanup of cache and bruteforce protection
845
-	 */
846
-	public static function registerCleanupHooks(\OC\SystemConfig $systemConfig) {
847
-		//don't try to do this before we are properly setup
848
-		if ($systemConfig->getValue('installed', false) && !\OCP\Util::needUpgrade()) {
849
-
850
-			// NOTE: This will be replaced to use OCP
851
-			$userSession = self::$server->getUserSession();
852
-			$userSession->listen('\OC\User', 'postLogin', function () use ($userSession) {
853
-				if (!defined('PHPUNIT_RUN') && $userSession->isLoggedIn()) {
854
-					// reset brute force delay for this IP address and username
855
-					$uid = \OC::$server->getUserSession()->getUser()->getUID();
856
-					$request = \OC::$server->getRequest();
857
-					$throttler = \OC::$server->getBruteForceThrottler();
858
-					$throttler->resetDelay($request->getRemoteAddress(), 'login', ['user' => $uid]);
859
-				}
860
-
861
-				try {
862
-					$cache = new \OC\Cache\File();
863
-					$cache->gc();
864
-				} catch (\OC\ServerNotAvailableException $e) {
865
-					// not a GC exception, pass it on
866
-					throw $e;
867
-				} catch (\OC\ForbiddenException $e) {
868
-					// filesystem blocked for this request, ignore
869
-				} catch (\Exception $e) {
870
-					// a GC exception should not prevent users from using OC,
871
-					// so log the exception
872
-					\OC::$server->getLogger()->logException($e, [
873
-						'message' => 'Exception when running cache gc.',
874
-						'level' => ILogger::WARN,
875
-						'app' => 'core',
876
-					]);
877
-				}
878
-			});
879
-		}
880
-	}
881
-
882
-	private static function registerEncryptionWrapperAndHooks() {
883
-		$manager = self::$server->getEncryptionManager();
884
-		\OCP\Util::connectHook('OC_Filesystem', 'preSetup', $manager, 'setupStorage');
885
-
886
-		$enabled = $manager->isEnabled();
887
-		if ($enabled) {
888
-			\OCP\Util::connectHook(Share::class, 'post_shared', HookManager::class, 'postShared');
889
-			\OCP\Util::connectHook(Share::class, 'post_unshare', HookManager::class, 'postUnshared');
890
-			\OCP\Util::connectHook('OC_Filesystem', 'post_rename', HookManager::class, 'postRename');
891
-			\OCP\Util::connectHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', HookManager::class, 'postRestore');
892
-		}
893
-	}
894
-
895
-	private static function registerAccountHooks() {
896
-		/** @var IEventDispatcher $dispatcher */
897
-		$dispatcher = \OC::$server->get(IEventDispatcher::class);
898
-		$dispatcher->addServiceListener(UserChangedEvent::class, \OC\Accounts\Hooks::class);
899
-	}
900
-
901
-	private static function registerAppRestrictionsHooks() {
902
-		/** @var \OC\Group\Manager $groupManager */
903
-		$groupManager = self::$server->query(\OCP\IGroupManager::class);
904
-		$groupManager->listen('\OC\Group', 'postDelete', function (\OCP\IGroup $group) {
905
-			$appManager = self::$server->getAppManager();
906
-			$apps = $appManager->getEnabledAppsForGroup($group);
907
-			foreach ($apps as $appId) {
908
-				$restrictions = $appManager->getAppRestriction($appId);
909
-				if (empty($restrictions)) {
910
-					continue;
911
-				}
912
-				$key = array_search($group->getGID(), $restrictions);
913
-				unset($restrictions[$key]);
914
-				$restrictions = array_values($restrictions);
915
-				if (empty($restrictions)) {
916
-					$appManager->disableApp($appId);
917
-				} else {
918
-					$appManager->enableAppForGroups($appId, $restrictions);
919
-				}
920
-			}
921
-		});
922
-	}
923
-
924
-	private static function registerResourceCollectionHooks() {
925
-		\OC\Collaboration\Resources\Listener::register(Server::get(SymfonyAdapter::class), Server::get(IEventDispatcher::class));
926
-	}
927
-
928
-	private static function registerFileReferenceEventListener() {
929
-		\OC\Collaboration\Reference\File\FileReferenceEventListener::register(Server::get(IEventDispatcher::class));
930
-	}
931
-
932
-	/**
933
-	 * register hooks for sharing
934
-	 */
935
-	public static function registerShareHooks(\OC\SystemConfig $systemConfig) {
936
-		if ($systemConfig->getValue('installed')) {
937
-			OC_Hook::connect('OC_User', 'post_deleteUser', Hooks::class, 'post_deleteUser');
938
-			OC_Hook::connect('OC_User', 'post_deleteGroup', Hooks::class, 'post_deleteGroup');
939
-
940
-			/** @var IEventDispatcher $dispatcher */
941
-			$dispatcher = \OC::$server->get(IEventDispatcher::class);
942
-			$dispatcher->addServiceListener(UserRemovedEvent::class, \OC\Share20\UserRemovedListener::class);
943
-		}
944
-	}
945
-
946
-	protected static function registerAutoloaderCache(\OC\SystemConfig $systemConfig) {
947
-		// The class loader takes an optional low-latency cache, which MUST be
948
-		// namespaced. The instanceid is used for namespacing, but might be
949
-		// unavailable at this point. Furthermore, it might not be possible to
950
-		// generate an instanceid via \OC_Util::getInstanceId() because the
951
-		// config file may not be writable. As such, we only register a class
952
-		// loader cache if instanceid is available without trying to create one.
953
-		$instanceId = $systemConfig->getValue('instanceid', null);
954
-		if ($instanceId) {
955
-			try {
956
-				$memcacheFactory = \OC::$server->getMemCacheFactory();
957
-				self::$loader->setMemoryCache($memcacheFactory->createLocal('Autoloader'));
958
-			} catch (\Exception $ex) {
959
-			}
960
-		}
961
-	}
962
-
963
-	/**
964
-	 * Handle the request
965
-	 */
966
-	public static function handleRequest() {
967
-		\OC::$server->getEventLogger()->start('handle_request', 'Handle request');
968
-		$systemConfig = \OC::$server->getSystemConfig();
969
-
970
-		// Check if Nextcloud is installed or in maintenance (update) mode
971
-		if (!$systemConfig->getValue('installed', false)) {
972
-			\OC::$server->getSession()->clear();
973
-			$setupHelper = new OC\Setup(
974
-				$systemConfig,
975
-				\OC::$server->get(\bantu\IniGetWrapper\IniGetWrapper::class),
976
-				\OC::$server->getL10N('lib'),
977
-				\OC::$server->query(\OCP\Defaults::class),
978
-				\OC::$server->get(\Psr\Log\LoggerInterface::class),
979
-				\OC::$server->getSecureRandom(),
980
-				\OC::$server->query(\OC\Installer::class)
981
-			);
982
-			$controller = new OC\Core\Controller\SetupController($setupHelper);
983
-			$controller->run($_POST);
984
-			exit();
985
-		}
986
-
987
-		$request = \OC::$server->getRequest();
988
-		$requestPath = $request->getRawPathInfo();
989
-		if ($requestPath === '/heartbeat') {
990
-			return;
991
-		}
992
-		if (substr($requestPath, -3) !== '.js') { // we need these files during the upgrade
993
-			self::checkMaintenanceMode($systemConfig);
994
-
995
-			if (\OCP\Util::needUpgrade()) {
996
-				if (function_exists('opcache_reset')) {
997
-					opcache_reset();
998
-				}
999
-				if (!((bool) $systemConfig->getValue('maintenance', false))) {
1000
-					self::printUpgradePage($systemConfig);
1001
-					exit();
1002
-				}
1003
-			}
1004
-		}
1005
-
1006
-		// emergency app disabling
1007
-		if ($requestPath === '/disableapp'
1008
-			&& $request->getMethod() === 'POST'
1009
-			&& ((array)$request->getParam('appid')) !== ''
1010
-		) {
1011
-			\OC_JSON::callCheck();
1012
-			\OC_JSON::checkAdminUser();
1013
-			$appIds = (array)$request->getParam('appid');
1014
-			foreach ($appIds as $appId) {
1015
-				$appId = \OC_App::cleanAppId($appId);
1016
-				\OC::$server->getAppManager()->disableApp($appId);
1017
-			}
1018
-			\OC_JSON::success();
1019
-			exit();
1020
-		}
1021
-
1022
-		// Always load authentication apps
1023
-		OC_App::loadApps(['authentication']);
1024
-
1025
-		// Load minimum set of apps
1026
-		if (!\OCP\Util::needUpgrade()
1027
-			&& !((bool) $systemConfig->getValue('maintenance', false))) {
1028
-			// For logged-in users: Load everything
1029
-			if (\OC::$server->getUserSession()->isLoggedIn()) {
1030
-				OC_App::loadApps();
1031
-			} else {
1032
-				// For guests: Load only filesystem and logging
1033
-				OC_App::loadApps(['filesystem', 'logging']);
1034
-
1035
-				// Don't try to login when a client is trying to get a OAuth token.
1036
-				// OAuth needs to support basic auth too, so the login is not valid
1037
-				// inside Nextcloud and the Login exception would ruin it.
1038
-				if ($request->getRawPathInfo() !== '/apps/oauth2/api/v1/token') {
1039
-					self::handleLogin($request);
1040
-				}
1041
-			}
1042
-		}
1043
-
1044
-		if (!self::$CLI) {
1045
-			try {
1046
-				if (!((bool) $systemConfig->getValue('maintenance', false)) && !\OCP\Util::needUpgrade()) {
1047
-					OC_App::loadApps(['filesystem', 'logging']);
1048
-					OC_App::loadApps();
1049
-				}
1050
-				OC::$server->get(\OC\Route\Router::class)->match($request->getRawPathInfo());
1051
-				return;
1052
-			} catch (Symfony\Component\Routing\Exception\ResourceNotFoundException $e) {
1053
-				//header('HTTP/1.0 404 Not Found');
1054
-			} catch (Symfony\Component\Routing\Exception\MethodNotAllowedException $e) {
1055
-				http_response_code(405);
1056
-				return;
1057
-			}
1058
-		}
1059
-
1060
-		// Handle WebDAV
1061
-		if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'PROPFIND') {
1062
-			// not allowed any more to prevent people
1063
-			// mounting this root directly.
1064
-			// Users need to mount remote.php/webdav instead.
1065
-			http_response_code(405);
1066
-			return;
1067
-		}
1068
-
1069
-		// Handle requests for JSON or XML
1070
-		$acceptHeader = $request->getHeader('Accept');
1071
-		if (in_array($acceptHeader, ['application/json', 'application/xml'], true)) {
1072
-			http_response_code(404);
1073
-			return;
1074
-		}
1075
-
1076
-		// Handle resources that can't be found
1077
-		// This prevents browsers from redirecting to the default page and then
1078
-		// attempting to parse HTML as CSS and similar.
1079
-		$destinationHeader = $request->getHeader('Sec-Fetch-Dest');
1080
-		if (in_array($destinationHeader, ['font', 'script', 'style'])) {
1081
-			http_response_code(404);
1082
-			return;
1083
-		}
1084
-
1085
-		// Redirect to the default app or login only as an entry point
1086
-		if ($requestPath === '') {
1087
-			// Someone is logged in
1088
-			if (\OC::$server->getUserSession()->isLoggedIn()) {
1089
-				header('Location: ' . \OC::$server->getURLGenerator()->linkToDefaultPageUrl());
1090
-			} else {
1091
-				// Not handled and not logged in
1092
-				header('Location: ' . \OC::$server->getURLGenerator()->linkToRouteAbsolute('core.login.showLoginForm'));
1093
-			}
1094
-			return;
1095
-		}
1096
-
1097
-		try {
1098
-			return OC::$server->get(\OC\Route\Router::class)->match('/error/404');
1099
-		} catch (\Exception $e) {
1100
-			logger('core')->emergency($e->getMessage(), ['exception' => $e]);
1101
-			$l = \OC::$server->getL10N('lib');
1102
-			OC_Template::printErrorPage(
1103
-				$l->t('404'),
1104
-				$l->t('The page could not be found on the server.'),
1105
-				404
1106
-			);
1107
-		}
1108
-	}
1109
-
1110
-	/**
1111
-	 * Check login: apache auth, auth token, basic auth
1112
-	 *
1113
-	 * @param OCP\IRequest $request
1114
-	 * @return boolean
1115
-	 */
1116
-	public static function handleLogin(OCP\IRequest $request) {
1117
-		$userSession = self::$server->getUserSession();
1118
-		if (OC_User::handleApacheAuth()) {
1119
-			return true;
1120
-		}
1121
-		if ($userSession->tryTokenLogin($request)) {
1122
-			return true;
1123
-		}
1124
-		if (isset($_COOKIE['nc_username'])
1125
-			&& isset($_COOKIE['nc_token'])
1126
-			&& isset($_COOKIE['nc_session_id'])
1127
-			&& $userSession->loginWithCookie($_COOKIE['nc_username'], $_COOKIE['nc_token'], $_COOKIE['nc_session_id'])) {
1128
-			return true;
1129
-		}
1130
-		if ($userSession->tryBasicAuthLogin($request, \OC::$server->getBruteForceThrottler())) {
1131
-			return true;
1132
-		}
1133
-		return false;
1134
-	}
1135
-
1136
-	protected static function handleAuthHeaders() {
1137
-		//copy http auth headers for apache+php-fcgid work around
1138
-		if (isset($_SERVER['HTTP_XAUTHORIZATION']) && !isset($_SERVER['HTTP_AUTHORIZATION'])) {
1139
-			$_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['HTTP_XAUTHORIZATION'];
1140
-		}
1141
-
1142
-		// Extract PHP_AUTH_USER/PHP_AUTH_PW from other headers if necessary.
1143
-		$vars = [
1144
-			'HTTP_AUTHORIZATION', // apache+php-cgi work around
1145
-			'REDIRECT_HTTP_AUTHORIZATION', // apache+php-cgi alternative
1146
-		];
1147
-		foreach ($vars as $var) {
1148
-			if (isset($_SERVER[$var]) && preg_match('/Basic\s+(.*)$/i', $_SERVER[$var], $matches)) {
1149
-				$credentials = explode(':', base64_decode($matches[1]), 2);
1150
-				if (count($credentials) === 2) {
1151
-					$_SERVER['PHP_AUTH_USER'] = $credentials[0];
1152
-					$_SERVER['PHP_AUTH_PW'] = $credentials[1];
1153
-					break;
1154
-				}
1155
-			}
1156
-		}
1157
-	}
85
+    /**
86
+     * Associative array for autoloading. classname => filename
87
+     */
88
+    public static $CLASSPATH = [];
89
+    /**
90
+     * The installation path for Nextcloud  on the server (e.g. /srv/http/nextcloud)
91
+     */
92
+    public static $SERVERROOT = '';
93
+    /**
94
+     * the current request path relative to the Nextcloud root (e.g. files/index.php)
95
+     */
96
+    private static $SUBURI = '';
97
+    /**
98
+     * the Nextcloud root path for http requests (e.g. nextcloud/)
99
+     */
100
+    public static $WEBROOT = '';
101
+    /**
102
+     * The installation path array of the apps folder on the server (e.g. /srv/http/nextcloud) 'path' and
103
+     * web path in 'url'
104
+     */
105
+    public static $APPSROOTS = [];
106
+
107
+    /**
108
+     * @var string
109
+     */
110
+    public static $configDir;
111
+
112
+    /**
113
+     * requested app
114
+     */
115
+    public static $REQUESTEDAPP = '';
116
+
117
+    /**
118
+     * check if Nextcloud runs in cli mode
119
+     */
120
+    public static $CLI = false;
121
+
122
+    /**
123
+     * @var \OC\Autoloader $loader
124
+     */
125
+    public static $loader = null;
126
+
127
+    /** @var \Composer\Autoload\ClassLoader $composerAutoloader */
128
+    public static $composerAutoloader = null;
129
+
130
+    /**
131
+     * @var \OC\Server
132
+     */
133
+    public static $server = null;
134
+
135
+    /**
136
+     * @var \OC\Config
137
+     */
138
+    private static $config = null;
139
+
140
+    /**
141
+     * @throws \RuntimeException when the 3rdparty directory is missing or
142
+     * the app path list is empty or contains an invalid path
143
+     */
144
+    public static function initPaths() {
145
+        if (defined('PHPUNIT_CONFIG_DIR')) {
146
+            self::$configDir = OC::$SERVERROOT . '/' . PHPUNIT_CONFIG_DIR . '/';
147
+        } elseif (defined('PHPUNIT_RUN') and PHPUNIT_RUN and is_dir(OC::$SERVERROOT . '/tests/config/')) {
148
+            self::$configDir = OC::$SERVERROOT . '/tests/config/';
149
+        } elseif ($dir = getenv('NEXTCLOUD_CONFIG_DIR')) {
150
+            self::$configDir = rtrim($dir, '/') . '/';
151
+        } else {
152
+            self::$configDir = OC::$SERVERROOT . '/config/';
153
+        }
154
+        self::$config = new \OC\Config(self::$configDir);
155
+
156
+        OC::$SUBURI = str_replace("\\", "/", substr(realpath($_SERVER["SCRIPT_FILENAME"]), strlen(OC::$SERVERROOT)));
157
+        /**
158
+         * FIXME: The following lines are required because we can't yet instantiate
159
+         *        \OC::$server->getRequest() since \OC::$server does not yet exist.
160
+         */
161
+        $params = [
162
+            'server' => [
163
+                'SCRIPT_NAME' => $_SERVER['SCRIPT_NAME'],
164
+                'SCRIPT_FILENAME' => $_SERVER['SCRIPT_FILENAME'],
165
+            ],
166
+        ];
167
+        $fakeRequest = new \OC\AppFramework\Http\Request(
168
+            $params,
169
+            new \OC\AppFramework\Http\RequestId($_SERVER['UNIQUE_ID'] ?? '', new \OC\Security\SecureRandom()),
170
+            new \OC\AllConfig(new \OC\SystemConfig(self::$config))
171
+        );
172
+        $scriptName = $fakeRequest->getScriptName();
173
+        if (substr($scriptName, -1) == '/') {
174
+            $scriptName .= 'index.php';
175
+            //make sure suburi follows the same rules as scriptName
176
+            if (substr(OC::$SUBURI, -9) != 'index.php') {
177
+                if (substr(OC::$SUBURI, -1) != '/') {
178
+                    OC::$SUBURI = OC::$SUBURI . '/';
179
+                }
180
+                OC::$SUBURI = OC::$SUBURI . 'index.php';
181
+            }
182
+        }
183
+
184
+
185
+        if (OC::$CLI) {
186
+            OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
187
+        } else {
188
+            if (substr($scriptName, 0 - strlen(OC::$SUBURI)) === OC::$SUBURI) {
189
+                OC::$WEBROOT = substr($scriptName, 0, 0 - strlen(OC::$SUBURI));
190
+
191
+                if (OC::$WEBROOT != '' && OC::$WEBROOT[0] !== '/') {
192
+                    OC::$WEBROOT = '/' . OC::$WEBROOT;
193
+                }
194
+            } else {
195
+                // The scriptName is not ending with OC::$SUBURI
196
+                // This most likely means that we are calling from CLI.
197
+                // However some cron jobs still need to generate
198
+                // a web URL, so we use overwritewebroot as a fallback.
199
+                OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
200
+            }
201
+
202
+            // Resolve /nextcloud to /nextcloud/ to ensure to always have a trailing
203
+            // slash which is required by URL generation.
204
+            if (isset($_SERVER['REQUEST_URI']) && $_SERVER['REQUEST_URI'] === \OC::$WEBROOT &&
205
+                    substr($_SERVER['REQUEST_URI'], -1) !== '/') {
206
+                header('Location: '.\OC::$WEBROOT.'/');
207
+                exit();
208
+            }
209
+        }
210
+
211
+        // search the apps folder
212
+        $config_paths = self::$config->getValue('apps_paths', []);
213
+        if (!empty($config_paths)) {
214
+            foreach ($config_paths as $paths) {
215
+                if (isset($paths['url']) && isset($paths['path'])) {
216
+                    $paths['url'] = rtrim($paths['url'], '/');
217
+                    $paths['path'] = rtrim($paths['path'], '/');
218
+                    OC::$APPSROOTS[] = $paths;
219
+                }
220
+            }
221
+        } elseif (file_exists(OC::$SERVERROOT . '/apps')) {
222
+            OC::$APPSROOTS[] = ['path' => OC::$SERVERROOT . '/apps', 'url' => '/apps', 'writable' => true];
223
+        }
224
+
225
+        if (empty(OC::$APPSROOTS)) {
226
+            throw new \RuntimeException('apps directory not found! Please put the Nextcloud apps folder in the Nextcloud folder'
227
+                . '. You can also configure the location in the config.php file.');
228
+        }
229
+        $paths = [];
230
+        foreach (OC::$APPSROOTS as $path) {
231
+            $paths[] = $path['path'];
232
+            if (!is_dir($path['path'])) {
233
+                throw new \RuntimeException(sprintf('App directory "%s" not found! Please put the Nextcloud apps folder in the'
234
+                    . ' Nextcloud folder. You can also configure the location in the config.php file.', $path['path']));
235
+            }
236
+        }
237
+
238
+        // set the right include path
239
+        set_include_path(
240
+            implode(PATH_SEPARATOR, $paths)
241
+        );
242
+    }
243
+
244
+    public static function checkConfig() {
245
+        $l = \OC::$server->getL10N('lib');
246
+
247
+        // Create config if it does not already exist
248
+        $configFilePath = self::$configDir .'/config.php';
249
+        if (!file_exists($configFilePath)) {
250
+            @touch($configFilePath);
251
+        }
252
+
253
+        // Check if config is writable
254
+        $configFileWritable = is_writable($configFilePath);
255
+        if (!$configFileWritable && !OC_Helper::isReadOnlyConfigEnabled()
256
+            || !$configFileWritable && \OCP\Util::needUpgrade()) {
257
+            $urlGenerator = \OC::$server->getURLGenerator();
258
+
259
+            if (self::$CLI) {
260
+                echo $l->t('Cannot write into "config" directory!')."\n";
261
+                echo $l->t('This can usually be fixed by giving the web server write access to the config directory.')."\n";
262
+                echo "\n";
263
+                echo $l->t('But, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it.')."\n";
264
+                echo $l->t('See %s', [ $urlGenerator->linkToDocs('admin-config') ])."\n";
265
+                exit;
266
+            } else {
267
+                OC_Template::printErrorPage(
268
+                    $l->t('Cannot write into "config" directory!'),
269
+                    $l->t('This can usually be fixed by giving the web server write access to the config directory.') . ' '
270
+                    . $l->t('But, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it.') . ' '
271
+                    . $l->t('See %s', [ $urlGenerator->linkToDocs('admin-config') ]),
272
+                    503
273
+                );
274
+            }
275
+        }
276
+    }
277
+
278
+    public static function checkInstalled(\OC\SystemConfig $systemConfig) {
279
+        if (defined('OC_CONSOLE')) {
280
+            return;
281
+        }
282
+        // Redirect to installer if not installed
283
+        if (!$systemConfig->getValue('installed', false) && OC::$SUBURI !== '/index.php' && OC::$SUBURI !== '/status.php') {
284
+            if (OC::$CLI) {
285
+                throw new Exception('Not installed');
286
+            } else {
287
+                $url = OC::$WEBROOT . '/index.php';
288
+                header('Location: ' . $url);
289
+            }
290
+            exit();
291
+        }
292
+    }
293
+
294
+    public static function checkMaintenanceMode(\OC\SystemConfig $systemConfig) {
295
+        // Allow ajax update script to execute without being stopped
296
+        if (((bool) $systemConfig->getValue('maintenance', false)) && OC::$SUBURI != '/core/ajax/update.php') {
297
+            // send http status 503
298
+            http_response_code(503);
299
+            header('X-Nextcloud-Maintenance-Mode: 1');
300
+            header('Retry-After: 120');
301
+
302
+            // render error page
303
+            $template = new OC_Template('', 'update.user', 'guest');
304
+            \OCP\Util::addScript('core', 'maintenance');
305
+            \OCP\Util::addStyle('core', 'guest');
306
+            $template->printPage();
307
+            die();
308
+        }
309
+    }
310
+
311
+    /**
312
+     * Prints the upgrade page
313
+     *
314
+     * @param \OC\SystemConfig $systemConfig
315
+     */
316
+    private static function printUpgradePage(\OC\SystemConfig $systemConfig) {
317
+        $disableWebUpdater = $systemConfig->getValue('upgrade.disable-web', false);
318
+        $tooBig = false;
319
+        if (!$disableWebUpdater) {
320
+            $apps = \OC::$server->getAppManager();
321
+            if ($apps->isInstalled('user_ldap')) {
322
+                $qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
323
+
324
+                $result = $qb->select($qb->func()->count('*', 'user_count'))
325
+                    ->from('ldap_user_mapping')
326
+                    ->execute();
327
+                $row = $result->fetch();
328
+                $result->closeCursor();
329
+
330
+                $tooBig = ($row['user_count'] > 50);
331
+            }
332
+            if (!$tooBig && $apps->isInstalled('user_saml')) {
333
+                $qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
334
+
335
+                $result = $qb->select($qb->func()->count('*', 'user_count'))
336
+                    ->from('user_saml_users')
337
+                    ->execute();
338
+                $row = $result->fetch();
339
+                $result->closeCursor();
340
+
341
+                $tooBig = ($row['user_count'] > 50);
342
+            }
343
+            if (!$tooBig) {
344
+                // count users
345
+                $stats = \OC::$server->getUserManager()->countUsers();
346
+                $totalUsers = array_sum($stats);
347
+                $tooBig = ($totalUsers > 50);
348
+            }
349
+        }
350
+        $ignoreTooBigWarning = isset($_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup']) &&
351
+            $_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup'] === 'IAmSuperSureToDoThis';
352
+
353
+        if ($disableWebUpdater || ($tooBig && !$ignoreTooBigWarning)) {
354
+            // send http status 503
355
+            http_response_code(503);
356
+            header('Retry-After: 120');
357
+
358
+            // render error page
359
+            $template = new OC_Template('', 'update.use-cli', 'guest');
360
+            $template->assign('productName', 'nextcloud'); // for now
361
+            $template->assign('version', OC_Util::getVersionString());
362
+            $template->assign('tooBig', $tooBig);
363
+
364
+            $template->printPage();
365
+            die();
366
+        }
367
+
368
+        // check whether this is a core update or apps update
369
+        $installedVersion = $systemConfig->getValue('version', '0.0.0');
370
+        $currentVersion = implode('.', \OCP\Util::getVersion());
371
+
372
+        // if not a core upgrade, then it's apps upgrade
373
+        $isAppsOnlyUpgrade = version_compare($currentVersion, $installedVersion, '=');
374
+
375
+        $oldTheme = $systemConfig->getValue('theme');
376
+        $systemConfig->setValue('theme', '');
377
+        \OCP\Util::addScript('core', 'common');
378
+        \OCP\Util::addScript('core', 'main');
379
+        \OCP\Util::addTranslations('core');
380
+        \OCP\Util::addScript('core', 'update');
381
+
382
+        /** @var \OC\App\AppManager $appManager */
383
+        $appManager = \OC::$server->getAppManager();
384
+
385
+        $tmpl = new OC_Template('', 'update.admin', 'guest');
386
+        $tmpl->assign('version', OC_Util::getVersionString());
387
+        $tmpl->assign('isAppsOnlyUpgrade', $isAppsOnlyUpgrade);
388
+
389
+        // get third party apps
390
+        $ocVersion = \OCP\Util::getVersion();
391
+        $ocVersion = implode('.', $ocVersion);
392
+        $incompatibleApps = $appManager->getIncompatibleApps($ocVersion);
393
+        $incompatibleShippedApps = [];
394
+        foreach ($incompatibleApps as $appInfo) {
395
+            if ($appManager->isShipped($appInfo['id'])) {
396
+                $incompatibleShippedApps[] = $appInfo['name'] . ' (' . $appInfo['id'] . ')';
397
+            }
398
+        }
399
+
400
+        if (!empty($incompatibleShippedApps)) {
401
+            $l = \OC::$server->getL10N('core');
402
+            $hint = $l->t('The files of the app %1$s were not replaced correctly. Make sure it is a version compatible with the server.', [implode(', ', $incompatibleShippedApps)]);
403
+            throw new \OCP\HintException('The files of the app ' . implode(', ', $incompatibleShippedApps) . ' were not replaced correctly. Make sure it is a version compatible with the server.', $hint);
404
+        }
405
+
406
+        $tmpl->assign('appsToUpgrade', $appManager->getAppsNeedingUpgrade($ocVersion));
407
+        $tmpl->assign('incompatibleAppsList', $incompatibleApps);
408
+        try {
409
+            $defaults = new \OC_Defaults();
410
+            $tmpl->assign('productName', $defaults->getName());
411
+        } catch (Throwable $error) {
412
+            $tmpl->assign('productName', 'Nextcloud');
413
+        }
414
+        $tmpl->assign('oldTheme', $oldTheme);
415
+        $tmpl->printPage();
416
+    }
417
+
418
+    public static function initSession() {
419
+        if (self::$server->getRequest()->getServerProtocol() === 'https') {
420
+            ini_set('session.cookie_secure', 'true');
421
+        }
422
+
423
+        // prevents javascript from accessing php session cookies
424
+        ini_set('session.cookie_httponly', 'true');
425
+
426
+        // set the cookie path to the Nextcloud directory
427
+        $cookie_path = OC::$WEBROOT ? : '/';
428
+        ini_set('session.cookie_path', $cookie_path);
429
+
430
+        // Let the session name be changed in the initSession Hook
431
+        $sessionName = OC_Util::getInstanceId();
432
+
433
+        try {
434
+            // set the session name to the instance id - which is unique
435
+            $session = new \OC\Session\Internal($sessionName);
436
+
437
+            $cryptoWrapper = \OC::$server->getSessionCryptoWrapper();
438
+            $session = $cryptoWrapper->wrapSession($session);
439
+            self::$server->setSession($session);
440
+
441
+            // if session can't be started break with http 500 error
442
+        } catch (Exception $e) {
443
+            \OC::$server->getLogger()->logException($e, ['app' => 'base']);
444
+            //show the user a detailed error page
445
+            OC_Template::printExceptionErrorPage($e, 500);
446
+            die();
447
+        }
448
+
449
+        //try to set the session lifetime
450
+        $sessionLifeTime = self::getSessionLifeTime();
451
+        @ini_set('gc_maxlifetime', (string)$sessionLifeTime);
452
+
453
+        // session timeout
454
+        if ($session->exists('LAST_ACTIVITY') && (time() - $session->get('LAST_ACTIVITY') > $sessionLifeTime)) {
455
+            if (isset($_COOKIE[session_name()])) {
456
+                setcookie(session_name(), '', -1, self::$WEBROOT ? : '/');
457
+            }
458
+            \OC::$server->getUserSession()->logout();
459
+        }
460
+
461
+        if (!self::hasSessionRelaxedExpiry()) {
462
+            $session->set('LAST_ACTIVITY', time());
463
+        }
464
+        $session->close();
465
+    }
466
+
467
+    /**
468
+     * @return string
469
+     */
470
+    private static function getSessionLifeTime() {
471
+        return \OC::$server->getConfig()->getSystemValue('session_lifetime', 60 * 60 * 24);
472
+    }
473
+
474
+    /**
475
+     * @return bool true if the session expiry should only be done by gc instead of an explicit timeout
476
+     */
477
+    public static function hasSessionRelaxedExpiry(): bool {
478
+        return \OC::$server->getConfig()->getSystemValue('session_relaxed_expiry', false);
479
+    }
480
+
481
+    /**
482
+     * Try to set some values to the required Nextcloud default
483
+     */
484
+    public static function setRequiredIniValues() {
485
+        @ini_set('default_charset', 'UTF-8');
486
+        @ini_set('gd.jpeg_ignore_warning', '1');
487
+    }
488
+
489
+    /**
490
+     * Send the same site cookies
491
+     */
492
+    private static function sendSameSiteCookies() {
493
+        $cookieParams = session_get_cookie_params();
494
+        $secureCookie = ($cookieParams['secure'] === true) ? 'secure; ' : '';
495
+        $policies = [
496
+            'lax',
497
+            'strict',
498
+        ];
499
+
500
+        // Append __Host to the cookie if it meets the requirements
501
+        $cookiePrefix = '';
502
+        if ($cookieParams['secure'] === true && $cookieParams['path'] === '/') {
503
+            $cookiePrefix = '__Host-';
504
+        }
505
+
506
+        foreach ($policies as $policy) {
507
+            header(
508
+                sprintf(
509
+                    'Set-Cookie: %snc_sameSiteCookie%s=true; path=%s; httponly;' . $secureCookie . 'expires=Fri, 31-Dec-2100 23:59:59 GMT; SameSite=%s',
510
+                    $cookiePrefix,
511
+                    $policy,
512
+                    $cookieParams['path'],
513
+                    $policy
514
+                ),
515
+                false
516
+            );
517
+        }
518
+    }
519
+
520
+    /**
521
+     * Same Site cookie to further mitigate CSRF attacks. This cookie has to
522
+     * be set in every request if cookies are sent to add a second level of
523
+     * defense against CSRF.
524
+     *
525
+     * If the cookie is not sent this will set the cookie and reload the page.
526
+     * We use an additional cookie since we want to protect logout CSRF and
527
+     * also we can't directly interfere with PHP's session mechanism.
528
+     */
529
+    private static function performSameSiteCookieProtection(\OCP\IConfig $config) {
530
+        $request = \OC::$server->getRequest();
531
+
532
+        // Some user agents are notorious and don't really properly follow HTTP
533
+        // specifications. For those, have an automated opt-out. Since the protection
534
+        // for remote.php is applied in base.php as starting point we need to opt out
535
+        // here.
536
+        $incompatibleUserAgents = $config->getSystemValue('csrf.optout');
537
+
538
+        // Fallback, if csrf.optout is unset
539
+        if (!is_array($incompatibleUserAgents)) {
540
+            $incompatibleUserAgents = [
541
+                // OS X Finder
542
+                '/^WebDAVFS/',
543
+                // Windows webdav drive
544
+                '/^Microsoft-WebDAV-MiniRedir/',
545
+            ];
546
+        }
547
+
548
+        if ($request->isUserAgent($incompatibleUserAgents)) {
549
+            return;
550
+        }
551
+
552
+        if (count($_COOKIE) > 0) {
553
+            $requestUri = $request->getScriptName();
554
+            $processingScript = explode('/', $requestUri);
555
+            $processingScript = $processingScript[count($processingScript) - 1];
556
+
557
+            // index.php routes are handled in the middleware
558
+            if ($processingScript === 'index.php') {
559
+                return;
560
+            }
561
+
562
+            // All other endpoints require the lax and the strict cookie
563
+            if (!$request->passesStrictCookieCheck()) {
564
+                self::sendSameSiteCookies();
565
+                // Debug mode gets access to the resources without strict cookie
566
+                // due to the fact that the SabreDAV browser also lives there.
567
+                if (!$config->getSystemValue('debug', false)) {
568
+                    http_response_code(\OCP\AppFramework\Http::STATUS_SERVICE_UNAVAILABLE);
569
+                    exit();
570
+                }
571
+            }
572
+        } elseif (!isset($_COOKIE['nc_sameSiteCookielax']) || !isset($_COOKIE['nc_sameSiteCookiestrict'])) {
573
+            self::sendSameSiteCookies();
574
+        }
575
+    }
576
+
577
+    public static function init() {
578
+        // calculate the root directories
579
+        OC::$SERVERROOT = str_replace("\\", '/', substr(__DIR__, 0, -4));
580
+
581
+        // register autoloader
582
+        $loaderStart = microtime(true);
583
+        require_once __DIR__ . '/autoloader.php';
584
+        self::$loader = new \OC\Autoloader([
585
+            OC::$SERVERROOT . '/lib/private/legacy',
586
+        ]);
587
+        if (defined('PHPUNIT_RUN')) {
588
+            self::$loader->addValidRoot(OC::$SERVERROOT . '/tests');
589
+        }
590
+        spl_autoload_register([self::$loader, 'load']);
591
+        $loaderEnd = microtime(true);
592
+
593
+        self::$CLI = (php_sapi_name() == 'cli');
594
+
595
+        // Add default composer PSR-4 autoloader
596
+        self::$composerAutoloader = require_once OC::$SERVERROOT . '/lib/composer/autoload.php';
597
+        self::$composerAutoloader->setApcuPrefix('composer_autoload');
598
+
599
+        try {
600
+            self::initPaths();
601
+            // setup 3rdparty autoloader
602
+            $vendorAutoLoad = OC::$SERVERROOT. '/3rdparty/autoload.php';
603
+            if (!file_exists($vendorAutoLoad)) {
604
+                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".');
605
+            }
606
+            require_once $vendorAutoLoad;
607
+        } catch (\RuntimeException $e) {
608
+            if (!self::$CLI) {
609
+                http_response_code(503);
610
+            }
611
+            // we can't use the template error page here, because this needs the
612
+            // DI container which isn't available yet
613
+            print($e->getMessage());
614
+            exit();
615
+        }
616
+
617
+        // setup the basic server
618
+        self::$server = new \OC\Server(\OC::$WEBROOT, self::$config);
619
+        self::$server->boot();
620
+
621
+        $eventLogger = \OC::$server->getEventLogger();
622
+        $eventLogger->log('autoloader', 'Autoloader', $loaderStart, $loaderEnd);
623
+        $eventLogger->start('boot', 'Initialize');
624
+
625
+        // Override php.ini and log everything if we're troubleshooting
626
+        if (self::$config->getValue('loglevel') === ILogger::DEBUG) {
627
+            error_reporting(E_ALL);
628
+        }
629
+
630
+        // Don't display errors and log them
631
+        @ini_set('display_errors', '0');
632
+        @ini_set('log_errors', '1');
633
+
634
+        if (!date_default_timezone_set('UTC')) {
635
+            throw new \RuntimeException('Could not set timezone to UTC');
636
+        }
637
+
638
+
639
+        //try to configure php to enable big file uploads.
640
+        //this doesn´t work always depending on the webserver and php configuration.
641
+        //Let´s try to overwrite some defaults if they are smaller than 1 hour
642
+
643
+        if (intval(@ini_get('max_execution_time') ?? 0) < 3600) {
644
+            @ini_set('max_execution_time', strval(3600));
645
+        }
646
+
647
+        if (intval(@ini_get('max_input_time') ?? 0) < 3600) {
648
+            @ini_set('max_input_time', strval(3600));
649
+        }
650
+
651
+        //try to set the maximum execution time to the largest time limit we have
652
+        if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
653
+            @set_time_limit(max(intval(@ini_get('max_execution_time')), intval(@ini_get('max_input_time'))));
654
+        }
655
+
656
+        self::setRequiredIniValues();
657
+        self::handleAuthHeaders();
658
+        $systemConfig = \OC::$server->get(\OC\SystemConfig::class);
659
+        self::registerAutoloaderCache($systemConfig);
660
+
661
+        // initialize intl fallback if necessary
662
+        OC_Util::isSetLocaleWorking();
663
+
664
+        $config = \OC::$server->get(\OCP\IConfig::class);
665
+        if (!defined('PHPUNIT_RUN')) {
666
+            $errorHandler = new OC\Log\ErrorHandler(
667
+                \OCP\Server::get(\Psr\Log\LoggerInterface::class),
668
+            );
669
+            $exceptionHandler = [$errorHandler, 'onException'];
670
+            if ($config->getSystemValue('debug', false)) {
671
+                set_error_handler([$errorHandler, 'onAll'], E_ALL);
672
+                if (\OC::$CLI) {
673
+                    $exceptionHandler = ['OC_Template', 'printExceptionErrorPage'];
674
+                }
675
+            } else {
676
+                set_error_handler([$errorHandler, 'onError']);
677
+            }
678
+            register_shutdown_function([$errorHandler, 'onShutdown']);
679
+            set_exception_handler($exceptionHandler);
680
+        }
681
+
682
+        /** @var \OC\AppFramework\Bootstrap\Coordinator $bootstrapCoordinator */
683
+        $bootstrapCoordinator = \OC::$server->query(\OC\AppFramework\Bootstrap\Coordinator::class);
684
+        $bootstrapCoordinator->runInitialRegistration();
685
+
686
+        $eventLogger->start('init_session', 'Initialize session');
687
+        OC_App::loadApps(['session']);
688
+        if (!self::$CLI) {
689
+            self::initSession();
690
+        }
691
+        $eventLogger->end('init_session');
692
+        self::checkConfig();
693
+        self::checkInstalled($systemConfig);
694
+
695
+        OC_Response::addSecurityHeaders();
696
+
697
+        self::performSameSiteCookieProtection($config);
698
+
699
+        if (!defined('OC_CONSOLE')) {
700
+            $errors = OC_Util::checkServer($systemConfig);
701
+            if (count($errors) > 0) {
702
+                if (!self::$CLI) {
703
+                    http_response_code(503);
704
+                    OC_Util::addStyle('guest');
705
+                    try {
706
+                        OC_Template::printGuestPage('', 'error', ['errors' => $errors]);
707
+                        exit;
708
+                    } catch (\Exception $e) {
709
+                        // In case any error happens when showing the error page, we simply fall back to posting the text.
710
+                        // This might be the case when e.g. the data directory is broken and we can not load/write SCSS to/from it.
711
+                    }
712
+                }
713
+
714
+                // Convert l10n string into regular string for usage in database
715
+                $staticErrors = [];
716
+                foreach ($errors as $error) {
717
+                    echo $error['error'] . "\n";
718
+                    echo $error['hint'] . "\n\n";
719
+                    $staticErrors[] = [
720
+                        'error' => (string)$error['error'],
721
+                        'hint' => (string)$error['hint'],
722
+                    ];
723
+                }
724
+
725
+                try {
726
+                    $config->setAppValue('core', 'cronErrors', json_encode($staticErrors));
727
+                } catch (\Exception $e) {
728
+                    echo('Writing to database failed');
729
+                }
730
+                exit(1);
731
+            } elseif (self::$CLI && $config->getSystemValue('installed', false)) {
732
+                $config->deleteAppValue('core', 'cronErrors');
733
+            }
734
+        }
735
+
736
+        // User and Groups
737
+        if (!$systemConfig->getValue("installed", false)) {
738
+            self::$server->getSession()->set('user_id', '');
739
+        }
740
+
741
+        OC_User::useBackend(new \OC\User\Database());
742
+        \OC::$server->getGroupManager()->addBackend(new \OC\Group\Database());
743
+
744
+        // Subscribe to the hook
745
+        \OCP\Util::connectHook(
746
+            '\OCA\Files_Sharing\API\Server2Server',
747
+            'preLoginNameUsedAsUserName',
748
+            '\OC\User\Database',
749
+            'preLoginNameUsedAsUserName'
750
+        );
751
+
752
+        //setup extra user backends
753
+        if (!\OCP\Util::needUpgrade()) {
754
+            OC_User::setupBackends();
755
+        } else {
756
+            // Run upgrades in incognito mode
757
+            OC_User::setIncognitoMode(true);
758
+        }
759
+
760
+        self::registerCleanupHooks($systemConfig);
761
+        self::registerShareHooks($systemConfig);
762
+        self::registerEncryptionWrapperAndHooks();
763
+        self::registerAccountHooks();
764
+        self::registerResourceCollectionHooks();
765
+        self::registerFileReferenceEventListener();
766
+        self::registerAppRestrictionsHooks();
767
+
768
+        // Make sure that the application class is not loaded before the database is setup
769
+        if ($systemConfig->getValue("installed", false)) {
770
+            OC_App::loadApp('settings');
771
+            /* Build core application to make sure that listeners are registered */
772
+            self::$server->get(\OC\Core\Application::class);
773
+        }
774
+
775
+        //make sure temporary files are cleaned up
776
+        $tmpManager = \OC::$server->getTempManager();
777
+        register_shutdown_function([$tmpManager, 'clean']);
778
+        $lockProvider = \OC::$server->getLockingProvider();
779
+        register_shutdown_function([$lockProvider, 'releaseAll']);
780
+
781
+        // Check whether the sample configuration has been copied
782
+        if ($systemConfig->getValue('copied_sample_config', false)) {
783
+            $l = \OC::$server->getL10N('lib');
784
+            OC_Template::printErrorPage(
785
+                $l->t('Sample configuration detected'),
786
+                $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'),
787
+                503
788
+            );
789
+            return;
790
+        }
791
+
792
+        $request = \OC::$server->getRequest();
793
+        $host = $request->getInsecureServerHost();
794
+        /**
795
+         * if the host passed in headers isn't trusted
796
+         * FIXME: Should not be in here at all :see_no_evil:
797
+         */
798
+        if (!OC::$CLI
799
+            && !\OC::$server->getTrustedDomainHelper()->isTrustedDomain($host)
800
+            && $config->getSystemValue('installed', false)
801
+        ) {
802
+            // Allow access to CSS resources
803
+            $isScssRequest = false;
804
+            if (strpos($request->getPathInfo(), '/css/') === 0) {
805
+                $isScssRequest = true;
806
+            }
807
+
808
+            if (substr($request->getRequestUri(), -11) === '/status.php') {
809
+                http_response_code(400);
810
+                header('Content-Type: application/json');
811
+                echo '{"error": "Trusted domain error.", "code": 15}';
812
+                exit();
813
+            }
814
+
815
+            if (!$isScssRequest) {
816
+                http_response_code(400);
817
+
818
+                \OC::$server->getLogger()->info(
819
+                    'Trusted domain error. "{remoteAddress}" tried to access using "{host}" as host.',
820
+                    [
821
+                        'app' => 'core',
822
+                        'remoteAddress' => $request->getRemoteAddress(),
823
+                        'host' => $host,
824
+                    ]
825
+                );
826
+
827
+                $tmpl = new OCP\Template('core', 'untrustedDomain', 'guest');
828
+                $tmpl->assign('docUrl', \OC::$server->getURLGenerator()->linkToDocs('admin-trusted-domains'));
829
+                $tmpl->printPage();
830
+
831
+                exit();
832
+            }
833
+        }
834
+        $eventLogger->end('boot');
835
+        $eventLogger->log('init', 'OC::init', $loaderStart, microtime(true));
836
+        $eventLogger->start('runtime', 'Runtime');
837
+        $eventLogger->start('request', 'Full request after boot');
838
+        register_shutdown_function(function () use ($eventLogger) {
839
+            $eventLogger->end('request');
840
+        });
841
+    }
842
+
843
+    /**
844
+     * register hooks for the cleanup of cache and bruteforce protection
845
+     */
846
+    public static function registerCleanupHooks(\OC\SystemConfig $systemConfig) {
847
+        //don't try to do this before we are properly setup
848
+        if ($systemConfig->getValue('installed', false) && !\OCP\Util::needUpgrade()) {
849
+
850
+            // NOTE: This will be replaced to use OCP
851
+            $userSession = self::$server->getUserSession();
852
+            $userSession->listen('\OC\User', 'postLogin', function () use ($userSession) {
853
+                if (!defined('PHPUNIT_RUN') && $userSession->isLoggedIn()) {
854
+                    // reset brute force delay for this IP address and username
855
+                    $uid = \OC::$server->getUserSession()->getUser()->getUID();
856
+                    $request = \OC::$server->getRequest();
857
+                    $throttler = \OC::$server->getBruteForceThrottler();
858
+                    $throttler->resetDelay($request->getRemoteAddress(), 'login', ['user' => $uid]);
859
+                }
860
+
861
+                try {
862
+                    $cache = new \OC\Cache\File();
863
+                    $cache->gc();
864
+                } catch (\OC\ServerNotAvailableException $e) {
865
+                    // not a GC exception, pass it on
866
+                    throw $e;
867
+                } catch (\OC\ForbiddenException $e) {
868
+                    // filesystem blocked for this request, ignore
869
+                } catch (\Exception $e) {
870
+                    // a GC exception should not prevent users from using OC,
871
+                    // so log the exception
872
+                    \OC::$server->getLogger()->logException($e, [
873
+                        'message' => 'Exception when running cache gc.',
874
+                        'level' => ILogger::WARN,
875
+                        'app' => 'core',
876
+                    ]);
877
+                }
878
+            });
879
+        }
880
+    }
881
+
882
+    private static function registerEncryptionWrapperAndHooks() {
883
+        $manager = self::$server->getEncryptionManager();
884
+        \OCP\Util::connectHook('OC_Filesystem', 'preSetup', $manager, 'setupStorage');
885
+
886
+        $enabled = $manager->isEnabled();
887
+        if ($enabled) {
888
+            \OCP\Util::connectHook(Share::class, 'post_shared', HookManager::class, 'postShared');
889
+            \OCP\Util::connectHook(Share::class, 'post_unshare', HookManager::class, 'postUnshared');
890
+            \OCP\Util::connectHook('OC_Filesystem', 'post_rename', HookManager::class, 'postRename');
891
+            \OCP\Util::connectHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', HookManager::class, 'postRestore');
892
+        }
893
+    }
894
+
895
+    private static function registerAccountHooks() {
896
+        /** @var IEventDispatcher $dispatcher */
897
+        $dispatcher = \OC::$server->get(IEventDispatcher::class);
898
+        $dispatcher->addServiceListener(UserChangedEvent::class, \OC\Accounts\Hooks::class);
899
+    }
900
+
901
+    private static function registerAppRestrictionsHooks() {
902
+        /** @var \OC\Group\Manager $groupManager */
903
+        $groupManager = self::$server->query(\OCP\IGroupManager::class);
904
+        $groupManager->listen('\OC\Group', 'postDelete', function (\OCP\IGroup $group) {
905
+            $appManager = self::$server->getAppManager();
906
+            $apps = $appManager->getEnabledAppsForGroup($group);
907
+            foreach ($apps as $appId) {
908
+                $restrictions = $appManager->getAppRestriction($appId);
909
+                if (empty($restrictions)) {
910
+                    continue;
911
+                }
912
+                $key = array_search($group->getGID(), $restrictions);
913
+                unset($restrictions[$key]);
914
+                $restrictions = array_values($restrictions);
915
+                if (empty($restrictions)) {
916
+                    $appManager->disableApp($appId);
917
+                } else {
918
+                    $appManager->enableAppForGroups($appId, $restrictions);
919
+                }
920
+            }
921
+        });
922
+    }
923
+
924
+    private static function registerResourceCollectionHooks() {
925
+        \OC\Collaboration\Resources\Listener::register(Server::get(SymfonyAdapter::class), Server::get(IEventDispatcher::class));
926
+    }
927
+
928
+    private static function registerFileReferenceEventListener() {
929
+        \OC\Collaboration\Reference\File\FileReferenceEventListener::register(Server::get(IEventDispatcher::class));
930
+    }
931
+
932
+    /**
933
+     * register hooks for sharing
934
+     */
935
+    public static function registerShareHooks(\OC\SystemConfig $systemConfig) {
936
+        if ($systemConfig->getValue('installed')) {
937
+            OC_Hook::connect('OC_User', 'post_deleteUser', Hooks::class, 'post_deleteUser');
938
+            OC_Hook::connect('OC_User', 'post_deleteGroup', Hooks::class, 'post_deleteGroup');
939
+
940
+            /** @var IEventDispatcher $dispatcher */
941
+            $dispatcher = \OC::$server->get(IEventDispatcher::class);
942
+            $dispatcher->addServiceListener(UserRemovedEvent::class, \OC\Share20\UserRemovedListener::class);
943
+        }
944
+    }
945
+
946
+    protected static function registerAutoloaderCache(\OC\SystemConfig $systemConfig) {
947
+        // The class loader takes an optional low-latency cache, which MUST be
948
+        // namespaced. The instanceid is used for namespacing, but might be
949
+        // unavailable at this point. Furthermore, it might not be possible to
950
+        // generate an instanceid via \OC_Util::getInstanceId() because the
951
+        // config file may not be writable. As such, we only register a class
952
+        // loader cache if instanceid is available without trying to create one.
953
+        $instanceId = $systemConfig->getValue('instanceid', null);
954
+        if ($instanceId) {
955
+            try {
956
+                $memcacheFactory = \OC::$server->getMemCacheFactory();
957
+                self::$loader->setMemoryCache($memcacheFactory->createLocal('Autoloader'));
958
+            } catch (\Exception $ex) {
959
+            }
960
+        }
961
+    }
962
+
963
+    /**
964
+     * Handle the request
965
+     */
966
+    public static function handleRequest() {
967
+        \OC::$server->getEventLogger()->start('handle_request', 'Handle request');
968
+        $systemConfig = \OC::$server->getSystemConfig();
969
+
970
+        // Check if Nextcloud is installed or in maintenance (update) mode
971
+        if (!$systemConfig->getValue('installed', false)) {
972
+            \OC::$server->getSession()->clear();
973
+            $setupHelper = new OC\Setup(
974
+                $systemConfig,
975
+                \OC::$server->get(\bantu\IniGetWrapper\IniGetWrapper::class),
976
+                \OC::$server->getL10N('lib'),
977
+                \OC::$server->query(\OCP\Defaults::class),
978
+                \OC::$server->get(\Psr\Log\LoggerInterface::class),
979
+                \OC::$server->getSecureRandom(),
980
+                \OC::$server->query(\OC\Installer::class)
981
+            );
982
+            $controller = new OC\Core\Controller\SetupController($setupHelper);
983
+            $controller->run($_POST);
984
+            exit();
985
+        }
986
+
987
+        $request = \OC::$server->getRequest();
988
+        $requestPath = $request->getRawPathInfo();
989
+        if ($requestPath === '/heartbeat') {
990
+            return;
991
+        }
992
+        if (substr($requestPath, -3) !== '.js') { // we need these files during the upgrade
993
+            self::checkMaintenanceMode($systemConfig);
994
+
995
+            if (\OCP\Util::needUpgrade()) {
996
+                if (function_exists('opcache_reset')) {
997
+                    opcache_reset();
998
+                }
999
+                if (!((bool) $systemConfig->getValue('maintenance', false))) {
1000
+                    self::printUpgradePage($systemConfig);
1001
+                    exit();
1002
+                }
1003
+            }
1004
+        }
1005
+
1006
+        // emergency app disabling
1007
+        if ($requestPath === '/disableapp'
1008
+            && $request->getMethod() === 'POST'
1009
+            && ((array)$request->getParam('appid')) !== ''
1010
+        ) {
1011
+            \OC_JSON::callCheck();
1012
+            \OC_JSON::checkAdminUser();
1013
+            $appIds = (array)$request->getParam('appid');
1014
+            foreach ($appIds as $appId) {
1015
+                $appId = \OC_App::cleanAppId($appId);
1016
+                \OC::$server->getAppManager()->disableApp($appId);
1017
+            }
1018
+            \OC_JSON::success();
1019
+            exit();
1020
+        }
1021
+
1022
+        // Always load authentication apps
1023
+        OC_App::loadApps(['authentication']);
1024
+
1025
+        // Load minimum set of apps
1026
+        if (!\OCP\Util::needUpgrade()
1027
+            && !((bool) $systemConfig->getValue('maintenance', false))) {
1028
+            // For logged-in users: Load everything
1029
+            if (\OC::$server->getUserSession()->isLoggedIn()) {
1030
+                OC_App::loadApps();
1031
+            } else {
1032
+                // For guests: Load only filesystem and logging
1033
+                OC_App::loadApps(['filesystem', 'logging']);
1034
+
1035
+                // Don't try to login when a client is trying to get a OAuth token.
1036
+                // OAuth needs to support basic auth too, so the login is not valid
1037
+                // inside Nextcloud and the Login exception would ruin it.
1038
+                if ($request->getRawPathInfo() !== '/apps/oauth2/api/v1/token') {
1039
+                    self::handleLogin($request);
1040
+                }
1041
+            }
1042
+        }
1043
+
1044
+        if (!self::$CLI) {
1045
+            try {
1046
+                if (!((bool) $systemConfig->getValue('maintenance', false)) && !\OCP\Util::needUpgrade()) {
1047
+                    OC_App::loadApps(['filesystem', 'logging']);
1048
+                    OC_App::loadApps();
1049
+                }
1050
+                OC::$server->get(\OC\Route\Router::class)->match($request->getRawPathInfo());
1051
+                return;
1052
+            } catch (Symfony\Component\Routing\Exception\ResourceNotFoundException $e) {
1053
+                //header('HTTP/1.0 404 Not Found');
1054
+            } catch (Symfony\Component\Routing\Exception\MethodNotAllowedException $e) {
1055
+                http_response_code(405);
1056
+                return;
1057
+            }
1058
+        }
1059
+
1060
+        // Handle WebDAV
1061
+        if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'PROPFIND') {
1062
+            // not allowed any more to prevent people
1063
+            // mounting this root directly.
1064
+            // Users need to mount remote.php/webdav instead.
1065
+            http_response_code(405);
1066
+            return;
1067
+        }
1068
+
1069
+        // Handle requests for JSON or XML
1070
+        $acceptHeader = $request->getHeader('Accept');
1071
+        if (in_array($acceptHeader, ['application/json', 'application/xml'], true)) {
1072
+            http_response_code(404);
1073
+            return;
1074
+        }
1075
+
1076
+        // Handle resources that can't be found
1077
+        // This prevents browsers from redirecting to the default page and then
1078
+        // attempting to parse HTML as CSS and similar.
1079
+        $destinationHeader = $request->getHeader('Sec-Fetch-Dest');
1080
+        if (in_array($destinationHeader, ['font', 'script', 'style'])) {
1081
+            http_response_code(404);
1082
+            return;
1083
+        }
1084
+
1085
+        // Redirect to the default app or login only as an entry point
1086
+        if ($requestPath === '') {
1087
+            // Someone is logged in
1088
+            if (\OC::$server->getUserSession()->isLoggedIn()) {
1089
+                header('Location: ' . \OC::$server->getURLGenerator()->linkToDefaultPageUrl());
1090
+            } else {
1091
+                // Not handled and not logged in
1092
+                header('Location: ' . \OC::$server->getURLGenerator()->linkToRouteAbsolute('core.login.showLoginForm'));
1093
+            }
1094
+            return;
1095
+        }
1096
+
1097
+        try {
1098
+            return OC::$server->get(\OC\Route\Router::class)->match('/error/404');
1099
+        } catch (\Exception $e) {
1100
+            logger('core')->emergency($e->getMessage(), ['exception' => $e]);
1101
+            $l = \OC::$server->getL10N('lib');
1102
+            OC_Template::printErrorPage(
1103
+                $l->t('404'),
1104
+                $l->t('The page could not be found on the server.'),
1105
+                404
1106
+            );
1107
+        }
1108
+    }
1109
+
1110
+    /**
1111
+     * Check login: apache auth, auth token, basic auth
1112
+     *
1113
+     * @param OCP\IRequest $request
1114
+     * @return boolean
1115
+     */
1116
+    public static function handleLogin(OCP\IRequest $request) {
1117
+        $userSession = self::$server->getUserSession();
1118
+        if (OC_User::handleApacheAuth()) {
1119
+            return true;
1120
+        }
1121
+        if ($userSession->tryTokenLogin($request)) {
1122
+            return true;
1123
+        }
1124
+        if (isset($_COOKIE['nc_username'])
1125
+            && isset($_COOKIE['nc_token'])
1126
+            && isset($_COOKIE['nc_session_id'])
1127
+            && $userSession->loginWithCookie($_COOKIE['nc_username'], $_COOKIE['nc_token'], $_COOKIE['nc_session_id'])) {
1128
+            return true;
1129
+        }
1130
+        if ($userSession->tryBasicAuthLogin($request, \OC::$server->getBruteForceThrottler())) {
1131
+            return true;
1132
+        }
1133
+        return false;
1134
+    }
1135
+
1136
+    protected static function handleAuthHeaders() {
1137
+        //copy http auth headers for apache+php-fcgid work around
1138
+        if (isset($_SERVER['HTTP_XAUTHORIZATION']) && !isset($_SERVER['HTTP_AUTHORIZATION'])) {
1139
+            $_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['HTTP_XAUTHORIZATION'];
1140
+        }
1141
+
1142
+        // Extract PHP_AUTH_USER/PHP_AUTH_PW from other headers if necessary.
1143
+        $vars = [
1144
+            'HTTP_AUTHORIZATION', // apache+php-cgi work around
1145
+            'REDIRECT_HTTP_AUTHORIZATION', // apache+php-cgi alternative
1146
+        ];
1147
+        foreach ($vars as $var) {
1148
+            if (isset($_SERVER[$var]) && preg_match('/Basic\s+(.*)$/i', $_SERVER[$var], $matches)) {
1149
+                $credentials = explode(':', base64_decode($matches[1]), 2);
1150
+                if (count($credentials) === 2) {
1151
+                    $_SERVER['PHP_AUTH_USER'] = $credentials[0];
1152
+                    $_SERVER['PHP_AUTH_PW'] = $credentials[1];
1153
+                    break;
1154
+                }
1155
+            }
1156
+        }
1157
+    }
1158 1158
 }
1159 1159
 
1160 1160
 OC::init();
Please login to merge, or discard this patch.