Passed
Push — master ( 09d56e...b39fb5 )
by Roeland
10:17 queued 11s
created
lib/public/Authentication/Events/LoginFailedEvent.php 1 patch
Indentation   +17 added lines, -17 removed lines patch added patch discarded remove patch
@@ -35,24 +35,24 @@
 block discarded – undo
35 35
  */
36 36
 class LoginFailedEvent extends Event {
37 37
 
38
-	/** @var string */
39
-	private $uid;
38
+    /** @var string */
39
+    private $uid;
40 40
 
41
-	/**
42
-	 * @since 19.0.0
43
-	 */
44
-	public function __construct(string $uid) {
45
-		parent::__construct();
41
+    /**
42
+     * @since 19.0.0
43
+     */
44
+    public function __construct(string $uid) {
45
+        parent::__construct();
46 46
 
47
-		$this->uid = $uid;
48
-	}
47
+        $this->uid = $uid;
48
+    }
49 49
 
50
-	/**
51
-	 * returns the uid of the user that was tried to login against
52
-	 *
53
-	 * @since 19.0.0
54
-	 */
55
-	public function getUid(): string {
56
-		return $this->uid;
57
-	}
50
+    /**
51
+     * returns the uid of the user that was tried to login against
52
+     *
53
+     * @since 19.0.0
54
+     */
55
+    public function getUid(): string {
56
+        return $this->uid;
57
+    }
58 58
 }
Please login to merge, or discard this patch.
lib/private/Authentication/Events/LoginFailed.php 1 patch
Indentation   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -28,16 +28,16 @@
 block discarded – undo
28 28
 
29 29
 class LoginFailed extends Event {
30 30
 
31
-	/** @var string */
32
-	private $loginName;
31
+    /** @var string */
32
+    private $loginName;
33 33
 
34
-	public function __construct(string $loginName) {
35
-		parent::__construct();
34
+    public function __construct(string $loginName) {
35
+        parent::__construct();
36 36
 
37
-		$this->loginName = $loginName;
38
-	}
37
+        $this->loginName = $loginName;
38
+    }
39 39
 
40
-	public function getLoginName(): string {
41
-		return $this->loginName;
42
-	}
40
+    public function getLoginName(): string {
41
+        return $this->loginName;
42
+    }
43 43
 }
Please login to merge, or discard this patch.
lib/private/Authentication/Login/LoggedInCheckCommand.php 1 patch
Indentation   +20 added lines, -20 removed lines patch added patch discarded remove patch
@@ -35,31 +35,31 @@
 block discarded – undo
35 35
 
36 36
 class LoggedInCheckCommand extends ALoginCommand {
37 37
 
38
-	/** @var ILogger */
39
-	private $logger;
40
-	/** @var IEventDispatcher */
41
-	private $dispatcher;
42
-	/** @var IUserManager */
43
-	private $userManager;
38
+    /** @var ILogger */
39
+    private $logger;
40
+    /** @var IEventDispatcher */
41
+    private $dispatcher;
42
+    /** @var IUserManager */
43
+    private $userManager;
44 44
 
45
-	public function __construct(ILogger $logger, IEventDispatcher $dispatcher) {
46
-		$this->logger = $logger;
47
-		$this->dispatcher = $dispatcher;
48
-	}
45
+    public function __construct(ILogger $logger, IEventDispatcher $dispatcher) {
46
+        $this->logger = $logger;
47
+        $this->dispatcher = $dispatcher;
48
+    }
49 49
 
50
-	public function process(LoginData $loginData): LoginResult {
51
-		if ($loginData->getUser() === false) {
52
-			$loginName = $loginData->getUsername();
53
-			$ip = $loginData->getRequest()->getRemoteAddress();
50
+    public function process(LoginData $loginData): LoginResult {
51
+        if ($loginData->getUser() === false) {
52
+            $loginName = $loginData->getUsername();
53
+            $ip = $loginData->getRequest()->getRemoteAddress();
54 54
 
55
-			$this->logger->warning("Login failed: $loginName (Remote IP: $ip)");
55
+            $this->logger->warning("Login failed: $loginName (Remote IP: $ip)");
56 56
 
57
-			$this->dispatcher->dispatchTyped(new LoginFailed($loginName));
57
+            $this->dispatcher->dispatchTyped(new LoginFailed($loginName));
58 58
 
59
-			return LoginResult::failure($loginData, LoginController::LOGIN_MSG_INVALIDPASSWORD);
60
-		}
59
+            return LoginResult::failure($loginData, LoginController::LOGIN_MSG_INVALIDPASSWORD);
60
+        }
61 61
 
62
-		return $this->processNextOrFinishSuccessfully($loginData);
63
-	}
62
+        return $this->processNextOrFinishSuccessfully($loginData);
63
+    }
64 64
 
65 65
 }
Please login to merge, or discard this patch.
lib/private/Authentication/Listeners/LoginFailedListener.php 2 patches
Indentation   +22 added lines, -22 removed lines patch added patch discarded remove patch
@@ -34,31 +34,31 @@
 block discarded – undo
34 34
 
35 35
 class LoginFailedListener implements IEventListener {
36 36
 
37
-	/** @var IEventDispatcher */
38
-	private $dispatcher;
37
+    /** @var IEventDispatcher */
38
+    private $dispatcher;
39 39
 
40
-	/** @var IUserManager */
41
-	private $userManager;
40
+    /** @var IUserManager */
41
+    private $userManager;
42 42
 
43
-	public function __construct(IEventDispatcher $dispatcher, IUserManager $userManager) {
44
-		$this->dispatcher = $dispatcher;
45
-		$this->userManager = $userManager;
46
-	}
43
+    public function __construct(IEventDispatcher $dispatcher, IUserManager $userManager) {
44
+        $this->dispatcher = $dispatcher;
45
+        $this->userManager = $userManager;
46
+    }
47 47
 
48
-	public function handle(Event $event): void {
49
-		if (!($event instanceof LoginFailed)) {
50
-			return;
51
-		}
48
+    public function handle(Event $event): void {
49
+        if (!($event instanceof LoginFailed)) {
50
+            return;
51
+        }
52 52
 
53
-		$uid = $event->getLoginName();
54
-		Util::emitHook(
55
-			'\OCA\Files_Sharing\API\Server2Server',
56
-			'preLoginNameUsedAsUserName',
57
-			['uid' => &$uid]
58
-		);
59
-		if($this->userManager->userExists($uid)) {
60
-			$this->dispatcher->dispatchTyped(new LoginFailedEvent($uid));
61
-		}
62
-	}
53
+        $uid = $event->getLoginName();
54
+        Util::emitHook(
55
+            '\OCA\Files_Sharing\API\Server2Server',
56
+            'preLoginNameUsedAsUserName',
57
+            ['uid' => &$uid]
58
+        );
59
+        if($this->userManager->userExists($uid)) {
60
+            $this->dispatcher->dispatchTyped(new LoginFailedEvent($uid));
61
+        }
62
+    }
63 63
 
64 64
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -56,7 +56,7 @@
 block discarded – undo
56 56
 			'preLoginNameUsedAsUserName',
57 57
 			['uid' => &$uid]
58 58
 		);
59
-		if($this->userManager->userExists($uid)) {
59
+		if ($this->userManager->userExists($uid)) {
60 60
 			$this->dispatcher->dispatchTyped(new LoginFailedEvent($uid));
61 61
 		}
62 62
 	}
Please login to merge, or discard this patch.
lib/private/Server.php 1 patch
Indentation   +2000 added lines, -2000 removed lines patch added patch discarded remove patch
@@ -239,2009 +239,2009 @@
 block discarded – undo
239 239
  * TODO: hookup all manager classes
240 240
  */
241 241
 class Server extends ServerContainer implements IServerContainer {
242
-	/** @var string */
243
-	private $webRoot;
244
-
245
-	/**
246
-	 * @param string $webRoot
247
-	 * @param \OC\Config $config
248
-	 */
249
-	public function __construct($webRoot, \OC\Config $config) {
250
-		parent::__construct();
251
-		$this->webRoot = $webRoot;
252
-
253
-		// To find out if we are running from CLI or not
254
-		$this->registerParameter('isCLI', \OC::$CLI);
255
-
256
-		$this->registerService(\OCP\IServerContainer::class, function (IServerContainer $c) {
257
-			return $c;
258
-		});
259
-
260
-		$this->registerAlias(\OCP\Calendar\IManager::class, \OC\Calendar\Manager::class);
261
-		$this->registerDeprecatedAlias('CalendarManager', \OC\Calendar\Manager::class);
262
-
263
-		$this->registerAlias(\OCP\Calendar\Resource\IManager::class, \OC\Calendar\Resource\Manager::class);
264
-		$this->registerDeprecatedAlias('CalendarResourceBackendManager', \OC\Calendar\Resource\Manager::class);
265
-
266
-		$this->registerAlias(\OCP\Calendar\Room\IManager::class, \OC\Calendar\Room\Manager::class);
267
-		$this->registerDeprecatedAlias('CalendarRoomBackendManager', \OC\Calendar\Room\Manager::class);
268
-
269
-		$this->registerAlias(\OCP\Contacts\IManager::class, \OC\ContactsManager::class);
270
-		$this->registerDeprecatedAlias('ContactsManager', \OCP\Contacts\IManager::class);
271
-
272
-		$this->registerAlias(\OCP\DirectEditing\IManager::class, \OC\DirectEditing\Manager::class);
273
-
274
-		$this->registerAlias(IActionFactory::class, ActionFactory::class);
275
-
276
-
277
-		$this->registerService(IPreview::class, function (Server $c) {
278
-			return new PreviewManager(
279
-				$c->getConfig(),
280
-				$c->getRootFolder(),
281
-				$c->getAppDataDir('preview'),
282
-				$c->getEventDispatcher(),
283
-				$c->getGeneratorHelper(),
284
-				$c->getSession()->get('user_id')
285
-			);
286
-		});
287
-		$this->registerDeprecatedAlias('PreviewManager', IPreview::class);
288
-
289
-		$this->registerService(\OC\Preview\Watcher::class, function (Server $c) {
290
-			return new \OC\Preview\Watcher(
291
-				$c->getAppDataDir('preview')
292
-			);
293
-		});
294
-
295
-		$this->registerService(\OCP\Encryption\IManager::class, function (Server $c) {
296
-			$view = new View();
297
-			$util = new Encryption\Util(
298
-				$view,
299
-				$c->getUserManager(),
300
-				$c->getGroupManager(),
301
-				$c->getConfig()
302
-			);
303
-			return new Encryption\Manager(
304
-				$c->getConfig(),
305
-				$c->getLogger(),
306
-				$c->getL10N('core'),
307
-				new View(),
308
-				$util,
309
-				new ArrayCache()
310
-			);
311
-		});
312
-		$this->registerDeprecatedAlias('EncryptionManager', \OCP\Encryption\IManager::class);
313
-
314
-		$this->registerService('EncryptionFileHelper', function (Server $c) {
315
-			$util = new Encryption\Util(
316
-				new View(),
317
-				$c->getUserManager(),
318
-				$c->getGroupManager(),
319
-				$c->getConfig()
320
-			);
321
-			return new Encryption\File(
322
-				$util,
323
-				$c->getRootFolder(),
324
-				$c->getShareManager()
325
-			);
326
-		});
327
-
328
-		$this->registerService('EncryptionKeyStorage', function (Server $c) {
329
-			$view = new View();
330
-			$util = new Encryption\Util(
331
-				$view,
332
-				$c->getUserManager(),
333
-				$c->getGroupManager(),
334
-				$c->getConfig()
335
-			);
336
-
337
-			return new Encryption\Keys\Storage($view, $util);
338
-		});
339
-		$this->registerService('TagMapper', function (Server $c) {
340
-			return new TagMapper($c->getDatabaseConnection());
341
-		});
342
-
343
-		$this->registerService(\OCP\ITagManager::class, function (Server $c) {
344
-			$tagMapper = $c->query('TagMapper');
345
-			return new TagManager($tagMapper, $c->getUserSession());
346
-		});
347
-		$this->registerDeprecatedAlias('TagManager', \OCP\ITagManager::class);
348
-
349
-		$this->registerService('SystemTagManagerFactory', function (Server $c) {
350
-			$config = $c->getConfig();
351
-			$factoryClass = $config->getSystemValue('systemtags.managerFactory', SystemTagManagerFactory::class);
352
-			return new $factoryClass($this);
353
-		});
354
-		$this->registerService(ISystemTagManager::class, function (Server $c) {
355
-			return $c->query('SystemTagManagerFactory')->getManager();
356
-		});
357
-		$this->registerDeprecatedAlias('SystemTagManager', ISystemTagManager::class);
358
-
359
-		$this->registerService(ISystemTagObjectMapper::class, function (Server $c) {
360
-			return $c->query('SystemTagManagerFactory')->getObjectMapper();
361
-		});
362
-		$this->registerService('RootFolder', function (Server $c) {
363
-			$manager = \OC\Files\Filesystem::getMountManager(null);
364
-			$view = new View();
365
-			$root = new Root(
366
-				$manager,
367
-				$view,
368
-				null,
369
-				$c->getUserMountCache(),
370
-				$this->getLogger(),
371
-				$this->getUserManager()
372
-			);
373
-			$connector = new HookConnector($root, $view, $c->getEventDispatcher());
374
-			$connector->viewToNode();
375
-
376
-			$previewConnector = new \OC\Preview\WatcherConnector($root, $c->getSystemConfig());
377
-			$previewConnector->connectWatcher();
378
-
379
-			return $root;
380
-		});
381
-		$this->registerDeprecatedAlias('SystemTagObjectMapper', ISystemTagObjectMapper::class);
382
-
383
-		$this->registerService(IRootFolder::class, function (Server $c) {
384
-			return new LazyRoot(function () use ($c) {
385
-				return $c->query('RootFolder');
386
-			});
387
-		});
388
-		$this->registerDeprecatedAlias('LazyRootFolder', IRootFolder::class);
389
-
390
-		$this->registerDeprecatedAlias('UserManager', \OC\User\Manager::class);
391
-		$this->registerAlias(\OCP\IUserManager::class, \OC\User\Manager::class);
392
-
393
-		$this->registerService(\OCP\IGroupManager::class, function (Server $c) {
394
-			$groupManager = new \OC\Group\Manager($this->getUserManager(), $c->getEventDispatcher(), $this->getLogger());
395
-			$groupManager->listen('\OC\Group', 'preCreate', function ($gid) {
396
-				\OC_Hook::emit('OC_Group', 'pre_createGroup', ['run' => true, 'gid' => $gid]);
397
-
398
-				/** @var IEventDispatcher $dispatcher */
399
-				$dispatcher = $this->query(IEventDispatcher::class);
400
-				$dispatcher->dispatchTyped(new BeforeGroupCreatedEvent($gid));
401
-			});
402
-			$groupManager->listen('\OC\Group', 'postCreate', function (\OC\Group\Group $group) {
403
-				\OC_Hook::emit('OC_User', 'post_createGroup', ['gid' => $group->getGID()]);
404
-
405
-				/** @var IEventDispatcher $dispatcher */
406
-				$dispatcher = $this->query(IEventDispatcher::class);
407
-				$dispatcher->dispatchTyped(new GroupCreatedEvent($group));
408
-			});
409
-			$groupManager->listen('\OC\Group', 'preDelete', function (\OC\Group\Group $group) {
410
-				\OC_Hook::emit('OC_Group', 'pre_deleteGroup', ['run' => true, 'gid' => $group->getGID()]);
411
-
412
-				/** @var IEventDispatcher $dispatcher */
413
-				$dispatcher = $this->query(IEventDispatcher::class);
414
-				$dispatcher->dispatchTyped(new BeforeGroupDeletedEvent($group));
415
-			});
416
-			$groupManager->listen('\OC\Group', 'postDelete', function (\OC\Group\Group $group) {
417
-				\OC_Hook::emit('OC_User', 'post_deleteGroup', ['gid' => $group->getGID()]);
418
-
419
-				/** @var IEventDispatcher $dispatcher */
420
-				$dispatcher = $this->query(IEventDispatcher::class);
421
-				$dispatcher->dispatchTyped(new GroupDeletedEvent($group));
422
-			});
423
-			$groupManager->listen('\OC\Group', 'preAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
424
-				\OC_Hook::emit('OC_Group', 'pre_addToGroup', ['run' => true, 'uid' => $user->getUID(), 'gid' => $group->getGID()]);
425
-
426
-				/** @var IEventDispatcher $dispatcher */
427
-				$dispatcher = $this->query(IEventDispatcher::class);
428
-				$dispatcher->dispatchTyped(new BeforeUserAddedEvent($group, $user));
429
-			});
430
-			$groupManager->listen('\OC\Group', 'postAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
431
-				\OC_Hook::emit('OC_Group', 'post_addToGroup', ['uid' => $user->getUID(), 'gid' => $group->getGID()]);
432
-				//Minimal fix to keep it backward compatible TODO: clean up all the GroupManager hooks
433
-				\OC_Hook::emit('OC_User', 'post_addToGroup', ['uid' => $user->getUID(), 'gid' => $group->getGID()]);
434
-
435
-				/** @var IEventDispatcher $dispatcher */
436
-				$dispatcher = $this->query(IEventDispatcher::class);
437
-				$dispatcher->dispatchTyped(new UserAddedEvent($group, $user));
438
-			});
439
-			$groupManager->listen('\OC\Group', 'preRemoveUser', function (\OC\Group\Group $group, \OC\User\User $user) {
440
-				/** @var IEventDispatcher $dispatcher */
441
-				$dispatcher = $this->query(IEventDispatcher::class);
442
-				$dispatcher->dispatchTyped(new BeforeUserRemovedEvent($group, $user));
443
-			});
444
-			$groupManager->listen('\OC\Group', 'postRemoveUser', function (\OC\Group\Group $group, \OC\User\User $user) {
445
-				/** @var IEventDispatcher $dispatcher */
446
-				$dispatcher = $this->query(IEventDispatcher::class);
447
-				$dispatcher->dispatchTyped(new UserRemovedEvent($group, $user));
448
-			});
449
-			return $groupManager;
450
-		});
451
-		$this->registerDeprecatedAlias('GroupManager', \OCP\IGroupManager::class);
452
-
453
-		$this->registerService(Store::class, function (Server $c) {
454
-			$session = $c->getSession();
455
-			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
456
-				$tokenProvider = $c->query(IProvider::class);
457
-			} else {
458
-				$tokenProvider = null;
459
-			}
460
-			$logger = $c->getLogger();
461
-			return new Store($session, $logger, $tokenProvider);
462
-		});
463
-		$this->registerAlias(IStore::class, Store::class);
464
-		$this->registerService(Authentication\Token\DefaultTokenMapper::class, function (Server $c) {
465
-			$dbConnection = $c->getDatabaseConnection();
466
-			return new Authentication\Token\DefaultTokenMapper($dbConnection);
467
-		});
468
-		$this->registerAlias(IProvider::class, Authentication\Token\Manager::class);
469
-
470
-		$this->registerService(\OC\User\Session::class, function (Server $c) {
471
-			$manager = $c->getUserManager();
472
-			$session = new \OC\Session\Memory('');
473
-			$timeFactory = new TimeFactory();
474
-			// Token providers might require a working database. This code
475
-			// might however be called when ownCloud is not yet setup.
476
-			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
477
-				$defaultTokenProvider = $c->query(IProvider::class);
478
-			} else {
479
-				$defaultTokenProvider = null;
480
-			}
481
-
482
-			$legacyDispatcher = $c->getEventDispatcher();
483
-
484
-			$userSession = new \OC\User\Session(
485
-				$manager,
486
-				$session,
487
-				$timeFactory,
488
-				$defaultTokenProvider,
489
-				$c->getConfig(),
490
-				$c->getSecureRandom(),
491
-				$c->getLockdownManager(),
492
-				$c->getLogger(),
493
-				$c->query(IEventDispatcher::class)
494
-			);
495
-			$userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
496
-				\OC_Hook::emit('OC_User', 'pre_createUser', ['run' => true, 'uid' => $uid, 'password' => $password]);
497
-
498
-				/** @var IEventDispatcher $dispatcher */
499
-				$dispatcher = $this->query(IEventDispatcher::class);
500
-				$dispatcher->dispatchTyped(new BeforeUserCreatedEvent($uid, $password));
501
-			});
502
-			$userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
503
-				/** @var $user \OC\User\User */
504
-				\OC_Hook::emit('OC_User', 'post_createUser', ['uid' => $user->getUID(), 'password' => $password]);
505
-
506
-				/** @var IEventDispatcher $dispatcher */
507
-				$dispatcher = $this->query(IEventDispatcher::class);
508
-				$dispatcher->dispatchTyped(new UserCreatedEvent($user, $password));
509
-			});
510
-			$userSession->listen('\OC\User', 'preDelete', function ($user) use ($legacyDispatcher) {
511
-				/** @var $user \OC\User\User */
512
-				\OC_Hook::emit('OC_User', 'pre_deleteUser', ['run' => true, 'uid' => $user->getUID()]);
513
-				$legacyDispatcher->dispatch('OCP\IUser::preDelete', new GenericEvent($user));
514
-
515
-				/** @var IEventDispatcher $dispatcher */
516
-				$dispatcher = $this->query(IEventDispatcher::class);
517
-				$dispatcher->dispatchTyped(new BeforeUserDeletedEvent($user));
518
-			});
519
-			$userSession->listen('\OC\User', 'postDelete', function ($user) {
520
-				/** @var $user \OC\User\User */
521
-				\OC_Hook::emit('OC_User', 'post_deleteUser', ['uid' => $user->getUID()]);
522
-
523
-				/** @var IEventDispatcher $dispatcher */
524
-				$dispatcher = $this->query(IEventDispatcher::class);
525
-				$dispatcher->dispatchTyped(new UserDeletedEvent($user));
526
-			});
527
-			$userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
528
-				/** @var $user \OC\User\User */
529
-				\OC_Hook::emit('OC_User', 'pre_setPassword', ['run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword]);
530
-
531
-				/** @var IEventDispatcher $dispatcher */
532
-				$dispatcher = $this->query(IEventDispatcher::class);
533
-				$dispatcher->dispatchTyped(new BeforePasswordUpdatedEvent($user, $password, $recoveryPassword));
534
-			});
535
-			$userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
536
-				/** @var $user \OC\User\User */
537
-				\OC_Hook::emit('OC_User', 'post_setPassword', ['run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword]);
538
-
539
-				/** @var IEventDispatcher $dispatcher */
540
-				$dispatcher = $this->query(IEventDispatcher::class);
541
-				$dispatcher->dispatchTyped(new PasswordUpdatedEvent($user, $password, $recoveryPassword));
542
-			});
543
-			$userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
544
-				\OC_Hook::emit('OC_User', 'pre_login', ['run' => true, 'uid' => $uid, 'password' => $password]);
545
-
546
-				/** @var IEventDispatcher $dispatcher */
547
-				$dispatcher = $this->query(IEventDispatcher::class);
548
-				$dispatcher->dispatchTyped(new BeforeUserLoggedInEvent($uid, $password));
549
-			});
550
-			$userSession->listen('\OC\User', 'postLogin', function ($user, $password, $isTokenLogin) {
551
-				/** @var $user \OC\User\User */
552
-				\OC_Hook::emit('OC_User', 'post_login', ['run' => true, 'uid' => $user->getUID(), 'password' => $password, 'isTokenLogin' => $isTokenLogin]);
553
-
554
-				/** @var IEventDispatcher $dispatcher */
555
-				$dispatcher = $this->query(IEventDispatcher::class);
556
-				$dispatcher->dispatchTyped(new UserLoggedInEvent($user, $password, $isTokenLogin));
557
-			});
558
-			$userSession->listen('\OC\User', 'preRememberedLogin', function ($uid) {
559
-				/** @var IEventDispatcher $dispatcher */
560
-				$dispatcher = $this->query(IEventDispatcher::class);
561
-				$dispatcher->dispatchTyped(new BeforeUserLoggedInWithCookieEvent($uid));
562
-			});
563
-			$userSession->listen('\OC\User', 'postRememberedLogin', function ($user, $password) {
564
-				/** @var $user \OC\User\User */
565
-				\OC_Hook::emit('OC_User', 'post_login', ['run' => true, 'uid' => $user->getUID(), 'password' => $password]);
566
-
567
-				/** @var IEventDispatcher $dispatcher */
568
-				$dispatcher = $this->query(IEventDispatcher::class);
569
-				$dispatcher->dispatchTyped(new UserLoggedInWithCookieEvent($user, $password));
570
-			});
571
-			$userSession->listen('\OC\User', 'logout', function ($user) {
572
-				\OC_Hook::emit('OC_User', 'logout', []);
573
-
574
-				/** @var IEventDispatcher $dispatcher */
575
-				$dispatcher = $this->query(IEventDispatcher::class);
576
-				$dispatcher->dispatchTyped(new BeforeUserLoggedOutEvent($user));
577
-			});
578
-			$userSession->listen('\OC\User', 'postLogout', function ($user) {
579
-				/** @var IEventDispatcher $dispatcher */
580
-				$dispatcher = $this->query(IEventDispatcher::class);
581
-				$dispatcher->dispatchTyped(new UserLoggedOutEvent($user));
582
-			});
583
-			$userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value, $oldValue) {
584
-				/** @var $user \OC\User\User */
585
-				\OC_Hook::emit('OC_User', 'changeUser', ['run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value, 'old_value' => $oldValue]);
586
-
587
-				/** @var IEventDispatcher $dispatcher */
588
-				$dispatcher = $this->query(IEventDispatcher::class);
589
-				$dispatcher->dispatchTyped(new UserChangedEvent($user, $feature, $value, $oldValue));
590
-			});
591
-			return $userSession;
592
-		});
593
-		$this->registerAlias(\OCP\IUserSession::class, \OC\User\Session::class);
594
-		$this->registerDeprecatedAlias('UserSession', \OC\User\Session::class);
595
-
596
-		$this->registerAlias(\OCP\Authentication\TwoFactorAuth\IRegistry::class, \OC\Authentication\TwoFactorAuth\Registry::class);
597
-
598
-		$this->registerAlias(INavigationManager::class, \OC\NavigationManager::class);
599
-		$this->registerDeprecatedAlias('NavigationManager', INavigationManager::class);
600
-
601
-		$this->registerService(\OC\AllConfig::class, function (Server $c) {
602
-			return new \OC\AllConfig(
603
-				$c->getSystemConfig()
604
-			);
605
-		});
606
-		$this->registerDeprecatedAlias('AllConfig', \OC\AllConfig::class);
607
-		$this->registerAlias(\OCP\IConfig::class, \OC\AllConfig::class);
608
-
609
-		$this->registerService(\OC\SystemConfig::class, function ($c) use ($config) {
610
-			return new \OC\SystemConfig($config);
611
-		});
612
-		$this->registerDeprecatedAlias('SystemConfig', \OC\SystemConfig::class);
613
-
614
-		$this->registerService(\OC\AppConfig::class, function (Server $c) {
615
-			return new \OC\AppConfig($c->getDatabaseConnection());
616
-		});
617
-		$this->registerDeprecatedAlias('AppConfig', \OC\AppConfig::class);
618
-		$this->registerAlias(IAppConfig::class, \OC\AppConfig::class);
619
-
620
-		$this->registerService(IFactory::class, function (Server $c) {
621
-			return new \OC\L10N\Factory(
622
-				$c->getConfig(),
623
-				$c->getRequest(),
624
-				$c->getUserSession(),
625
-				\OC::$SERVERROOT
626
-			);
627
-		});
628
-		$this->registerDeprecatedAlias('L10NFactory', IFactory::class);
629
-
630
-		$this->registerService(IURLGenerator::class, function (Server $c) {
631
-			$config = $c->getConfig();
632
-			$cacheFactory = $c->getMemCacheFactory();
633
-			$request = $c->getRequest();
634
-			return new \OC\URLGenerator(
635
-				$config,
636
-				$cacheFactory,
637
-				$request
638
-			);
639
-		});
640
-		$this->registerDeprecatedAlias('URLGenerator', IURLGenerator::class);
641
-
642
-		$this->registerDeprecatedAlias('AppFetcher', AppFetcher::class);
643
-		$this->registerDeprecatedAlias('CategoryFetcher', CategoryFetcher::class);
644
-
645
-		$this->registerService(ICache::class, function ($c) {
646
-			return new Cache\File();
647
-		});
648
-		$this->registerDeprecatedAlias('UserCache', ICache::class);
649
-
650
-		$this->registerService(Factory::class, function (Server $c) {
651
-
652
-			$arrayCacheFactory = new \OC\Memcache\Factory('', $c->getLogger(),
653
-				ArrayCache::class,
654
-				ArrayCache::class,
655
-				ArrayCache::class
656
-			);
657
-			$config = $c->getConfig();
658
-
659
-			if ($config->getSystemValue('installed', false) && !(defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
660
-				$v = \OC_App::getAppVersions();
661
-				$v['core'] = implode(',', \OC_Util::getVersion());
662
-				$version = implode(',', $v);
663
-				$instanceId = \OC_Util::getInstanceId();
664
-				$path = \OC::$SERVERROOT;
665
-				$prefix = md5($instanceId . '-' . $version . '-' . $path);
666
-				return new \OC\Memcache\Factory($prefix, $c->getLogger(),
667
-					$config->getSystemValue('memcache.local', null),
668
-					$config->getSystemValue('memcache.distributed', null),
669
-					$config->getSystemValue('memcache.locking', null)
670
-				);
671
-			}
672
-			return $arrayCacheFactory;
673
-
674
-		});
675
-		$this->registerDeprecatedAlias('MemCacheFactory', Factory::class);
676
-		$this->registerAlias(ICacheFactory::class, Factory::class);
677
-
678
-		$this->registerService('RedisFactory', function (Server $c) {
679
-			$systemConfig = $c->getSystemConfig();
680
-			return new RedisFactory($systemConfig);
681
-		});
682
-
683
-		$this->registerService(\OCP\Activity\IManager::class, function (Server $c) {
684
-			return new \OC\Activity\Manager(
685
-				$c->getRequest(),
686
-				$c->getUserSession(),
687
-				$c->getConfig(),
688
-				$c->query(IValidator::class)
689
-			);
690
-		});
691
-		$this->registerDeprecatedAlias('ActivityManager', \OCP\Activity\IManager::class);
692
-
693
-		$this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
694
-			return new \OC\Activity\EventMerger(
695
-				$c->getL10N('lib')
696
-			);
697
-		});
698
-		$this->registerAlias(IValidator::class, Validator::class);
699
-
700
-		$this->registerService(AvatarManager::class, function(Server $c) {
701
-			return new AvatarManager(
702
-				$c->query(\OC\User\Manager::class),
703
-				$c->getAppDataDir('avatar'),
704
-				$c->getL10N('lib'),
705
-				$c->getLogger(),
706
-				$c->getConfig()
707
-			);
708
-		});
709
-		$this->registerAlias(IAvatarManager::class, AvatarManager::class);
710
-		$this->registerDeprecatedAlias('AvatarManager', AvatarManager::class);
711
-
712
-		$this->registerAlias(\OCP\Support\CrashReport\IRegistry::class, \OC\Support\CrashReport\Registry::class);
713
-		$this->registerAlias(\OCP\Support\Subscription\IRegistry::class, \OC\Support\Subscription\Registry::class);
714
-
715
-		$this->registerService(\OC\Log::class, function (Server $c) {
716
-			$logType = $c->query(AllConfig::class)->getSystemValue('log_type', 'file');
717
-			$factory = new LogFactory($c, $this->getSystemConfig());
718
-			$logger = $factory->get($logType);
719
-			$registry = $c->query(\OCP\Support\CrashReport\IRegistry::class);
720
-
721
-			return new Log($logger, $this->getSystemConfig(), null, $registry);
722
-		});
723
-		$this->registerAlias(ILogger::class, \OC\Log::class);
724
-		$this->registerDeprecatedAlias('Logger', \OC\Log::class);
725
-
726
-		$this->registerService(ILogFactory::class, function (Server $c) {
727
-			return new LogFactory($c, $this->getSystemConfig());
728
-		});
729
-
730
-		$this->registerService(IJobList::class, function (Server $c) {
731
-			$config = $c->getConfig();
732
-			return new \OC\BackgroundJob\JobList(
733
-				$c->getDatabaseConnection(),
734
-				$config,
735
-				new TimeFactory()
736
-			);
737
-		});
738
-		$this->registerDeprecatedAlias('JobList', IJobList::class);
739
-
740
-		$this->registerService(IRouter::class, function (Server $c) {
741
-			$cacheFactory = $c->getMemCacheFactory();
742
-			$logger = $c->getLogger();
743
-			if ($cacheFactory->isLocalCacheAvailable()) {
744
-				$router = new \OC\Route\CachingRouter($cacheFactory->createLocal('route'), $logger);
745
-			} else {
746
-				$router = new \OC\Route\Router($logger);
747
-			}
748
-			return $router;
749
-		});
750
-		$this->registerDeprecatedAlias('Router', IRouter::class);
751
-
752
-		$this->registerService(ISearch::class, function ($c) {
753
-			return new Search();
754
-		});
755
-		$this->registerDeprecatedAlias('Search', ISearch::class);
756
-
757
-		$this->registerService(\OC\Security\RateLimiting\Backend\IBackend::class, function ($c) {
758
-			return new \OC\Security\RateLimiting\Backend\MemoryCache(
759
-				$this->getMemCacheFactory(),
760
-				new \OC\AppFramework\Utility\TimeFactory()
761
-			);
762
-		});
763
-
764
-		$this->registerService(\OCP\Security\ISecureRandom::class, function ($c) {
765
-			return new SecureRandom();
766
-		});
767
-		$this->registerDeprecatedAlias('SecureRandom', \OCP\Security\ISecureRandom::class);
768
-
769
-		$this->registerService(ICrypto::class, function (Server $c) {
770
-			return new Crypto($c->getConfig(), $c->getSecureRandom());
771
-		});
772
-		$this->registerDeprecatedAlias('Crypto', ICrypto::class);
773
-
774
-		$this->registerService(IHasher::class, function (Server $c) {
775
-			return new Hasher($c->getConfig());
776
-		});
777
-		$this->registerDeprecatedAlias('Hasher', IHasher::class);
778
-
779
-		$this->registerService(ICredentialsManager::class, function (Server $c) {
780
-			return new CredentialsManager($c->getCrypto(), $c->getDatabaseConnection());
781
-		});
782
-		$this->registerDeprecatedAlias('CredentialsManager', ICredentialsManager::class);
783
-
784
-		$this->registerService(IDBConnection::class, function (Server $c) {
785
-			$systemConfig = $c->getSystemConfig();
786
-			$factory = new \OC\DB\ConnectionFactory($systemConfig);
787
-			$type = $systemConfig->getValue('dbtype', 'sqlite');
788
-			if (!$factory->isValidType($type)) {
789
-				throw new \OC\DatabaseException('Invalid database type');
790
-			}
791
-			$connectionParams = $factory->createConnectionParams();
792
-			$connection = $factory->getConnection($type, $connectionParams);
793
-			$connection->getConfiguration()->setSQLLogger($c->getQueryLogger());
794
-			return $connection;
795
-		});
796
-		$this->registerDeprecatedAlias('DatabaseConnection', IDBConnection::class);
797
-
798
-
799
-		$this->registerService(IClientService::class, function (Server $c) {
800
-			$user = \OC_User::getUser();
801
-			$uid = $user ? $user : null;
802
-			return new ClientService(
803
-				$c->getConfig(),
804
-				new \OC\Security\CertificateManager(
805
-					$uid,
806
-					new View(),
807
-					$c->getConfig(),
808
-					$c->getLogger(),
809
-					$c->getSecureRandom()
810
-				)
811
-			);
812
-		});
813
-		$this->registerDeprecatedAlias('HttpClientService', IClientService::class);
814
-		$this->registerService(IEventLogger::class, function (Server $c) {
815
-			$eventLogger = new EventLogger();
816
-			if ($c->getSystemConfig()->getValue('debug', false)) {
817
-				// In debug mode, module is being activated by default
818
-				$eventLogger->activate();
819
-			}
820
-			return $eventLogger;
821
-		});
822
-		$this->registerDeprecatedAlias('EventLogger', IEventLogger::class);
823
-
824
-		$this->registerService(IQueryLogger::class, function (Server $c) {
825
-			$queryLogger = new QueryLogger();
826
-			if ($c->getSystemConfig()->getValue('debug', false)) {
827
-				// In debug mode, module is being activated by default
828
-				$queryLogger->activate();
829
-			}
830
-			return $queryLogger;
831
-		});
832
-		$this->registerDeprecatedAlias('QueryLogger', IQueryLogger::class);
833
-
834
-		$this->registerService(TempManager::class, function (Server $c) {
835
-			return new TempManager(
836
-				$c->getLogger(),
837
-				$c->getConfig()
838
-			);
839
-		});
840
-		$this->registerDeprecatedAlias('TempManager', TempManager::class);
841
-		$this->registerAlias(ITempManager::class, TempManager::class);
842
-
843
-		$this->registerService(AppManager::class, function (Server $c) {
844
-			return new \OC\App\AppManager(
845
-				$c->getUserSession(),
846
-				$c->getConfig(),
847
-				$c->query(\OC\AppConfig::class),
848
-				$c->getGroupManager(),
849
-				$c->getMemCacheFactory(),
850
-				$c->getEventDispatcher(),
851
-				$c->getLogger()
852
-			);
853
-		});
854
-		$this->registerDeprecatedAlias('AppManager', AppManager::class);
855
-		$this->registerAlias(IAppManager::class, AppManager::class);
856
-
857
-		$this->registerService(IDateTimeZone::class, function (Server $c) {
858
-			return new DateTimeZone(
859
-				$c->getConfig(),
860
-				$c->getSession()
861
-			);
862
-		});
863
-		$this->registerDeprecatedAlias('DateTimeZone', IDateTimeZone::class);
864
-
865
-		$this->registerService(IDateTimeFormatter::class, function (Server $c) {
866
-			$language = $c->getConfig()->getUserValue($c->getSession()->get('user_id'), 'core', 'lang', null);
867
-
868
-			return new DateTimeFormatter(
869
-				$c->getDateTimeZone()->getTimeZone(),
870
-				$c->getL10N('lib', $language)
871
-			);
872
-		});
873
-		$this->registerDeprecatedAlias('DateTimeFormatter', IDateTimeFormatter::class);
874
-
875
-		$this->registerService(IUserMountCache::class, function (Server $c) {
876
-			$mountCache = new UserMountCache($c->getDatabaseConnection(), $c->getUserManager(), $c->getLogger());
877
-			$listener = new UserMountCacheListener($mountCache);
878
-			$listener->listen($c->getUserManager());
879
-			return $mountCache;
880
-		});
881
-		$this->registerDeprecatedAlias('UserMountCache', IUserMountCache::class);
882
-
883
-		$this->registerService(IMountProviderCollection::class, function (Server $c) {
884
-			$loader = \OC\Files\Filesystem::getLoader();
885
-			$mountCache = $c->query(IUserMountCache::class);
886
-			$manager = new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
887
-
888
-			// builtin providers
889
-
890
-			$config = $c->getConfig();
891
-			$manager->registerProvider(new CacheMountProvider($config));
892
-			$manager->registerHomeProvider(new LocalHomeMountProvider());
893
-			$manager->registerHomeProvider(new ObjectHomeMountProvider($config));
894
-
895
-			return $manager;
896
-		});
897
-		$this->registerDeprecatedAlias('MountConfigManager', IMountProviderCollection::class);
898
-
899
-		$this->registerService('IniWrapper', function ($c) {
900
-			return new IniGetWrapper();
901
-		});
902
-		$this->registerService('AsyncCommandBus', function (Server $c) {
903
-			$busClass = $c->getConfig()->getSystemValue('commandbus');
904
-			if ($busClass) {
905
-				list($app, $class) = explode('::', $busClass, 2);
906
-				if ($c->getAppManager()->isInstalled($app)) {
907
-					\OC_App::loadApp($app);
908
-					return $c->query($class);
909
-				} else {
910
-					throw new ServiceUnavailableException("The app providing the command bus ($app) is not enabled");
911
-				}
912
-			} else {
913
-				$jobList = $c->getJobList();
914
-				return new CronBus($jobList);
915
-			}
916
-		});
917
-		$this->registerService('TrustedDomainHelper', function ($c) {
918
-			return new TrustedDomainHelper($this->getConfig());
919
-		});
920
-		$this->registerService(Throttler::class, function (Server $c) {
921
-			return new Throttler(
922
-				$c->getDatabaseConnection(),
923
-				new TimeFactory(),
924
-				$c->getLogger(),
925
-				$c->getConfig()
926
-			);
927
-		});
928
-		$this->registerDeprecatedAlias('Throttler', Throttler::class);
929
-		$this->registerService('IntegrityCodeChecker', function (Server $c) {
930
-			// IConfig and IAppManager requires a working database. This code
931
-			// might however be called when ownCloud is not yet setup.
932
-			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
933
-				$config = $c->getConfig();
934
-				$appManager = $c->getAppManager();
935
-			} else {
936
-				$config = null;
937
-				$appManager = null;
938
-			}
939
-
940
-			return new Checker(
941
-				new EnvironmentHelper(),
942
-				new FileAccessHelper(),
943
-				new AppLocator(),
944
-				$config,
945
-				$c->getMemCacheFactory(),
946
-				$appManager,
947
-				$c->getTempManager(),
948
-				$c->getMimeTypeDetector()
949
-			);
950
-		});
951
-		$this->registerService(\OCP\IRequest::class, function ($c) {
952
-			if (isset($this['urlParams'])) {
953
-				$urlParams = $this['urlParams'];
954
-			} else {
955
-				$urlParams = [];
956
-			}
957
-
958
-			if (defined('PHPUNIT_RUN') && PHPUNIT_RUN
959
-				&& in_array('fakeinput', stream_get_wrappers())
960
-			) {
961
-				$stream = 'fakeinput://data';
962
-			} else {
963
-				$stream = 'php://input';
964
-			}
965
-
966
-			return new Request(
967
-				[
968
-					'get' => $_GET,
969
-					'post' => $_POST,
970
-					'files' => $_FILES,
971
-					'server' => $_SERVER,
972
-					'env' => $_ENV,
973
-					'cookies' => $_COOKIE,
974
-					'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
975
-						? $_SERVER['REQUEST_METHOD']
976
-						: '',
977
-					'urlParams' => $urlParams,
978
-				],
979
-				$this->getSecureRandom(),
980
-				$this->getConfig(),
981
-				$this->getCsrfTokenManager(),
982
-				$stream
983
-			);
984
-		});
985
-		$this->registerDeprecatedAlias('Request', \OCP\IRequest::class);
986
-
987
-		$this->registerService(IMailer::class, function (Server $c) {
988
-			return new Mailer(
989
-				$c->getConfig(),
990
-				$c->getLogger(),
991
-				$c->query(Defaults::class),
992
-				$c->getURLGenerator(),
993
-				$c->getL10N('lib'),
994
-				$c->query(IEventDispatcher::class)
995
-			);
996
-		});
997
-		$this->registerDeprecatedAlias('Mailer', IMailer::class);
998
-
999
-		$this->registerService('LDAPProvider', function (Server $c) {
1000
-			$config = $c->getConfig();
1001
-			$factoryClass = $config->getSystemValue('ldapProviderFactory', null);
1002
-			if (is_null($factoryClass)) {
1003
-				throw new \Exception('ldapProviderFactory not set');
1004
-			}
1005
-			/** @var \OCP\LDAP\ILDAPProviderFactory $factory */
1006
-			$factory = new $factoryClass($this);
1007
-			return $factory->getLDAPProvider();
1008
-		});
1009
-		$this->registerService(ILockingProvider::class, function (Server $c) {
1010
-			$ini = $c->getIniWrapper();
1011
-			$config = $c->getConfig();
1012
-			$ttl = $config->getSystemValue('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
1013
-			if ($config->getSystemValue('filelocking.enabled', true) or (defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
1014
-				/** @var \OC\Memcache\Factory $memcacheFactory */
1015
-				$memcacheFactory = $c->getMemCacheFactory();
1016
-				$memcache = $memcacheFactory->createLocking('lock');
1017
-				if (!($memcache instanceof \OC\Memcache\NullCache)) {
1018
-					return new MemcacheLockingProvider($memcache, $ttl);
1019
-				}
1020
-				return new DBLockingProvider(
1021
-					$c->getDatabaseConnection(),
1022
-					$c->getLogger(),
1023
-					new TimeFactory(),
1024
-					$ttl,
1025
-					!\OC::$CLI
1026
-				);
1027
-			}
1028
-			return new NoopLockingProvider();
1029
-		});
1030
-		$this->registerDeprecatedAlias('LockingProvider', ILockingProvider::class);
1031
-
1032
-		$this->registerService(IMountManager::class, function () {
1033
-			return new \OC\Files\Mount\Manager();
1034
-		});
1035
-		$this->registerDeprecatedAlias('MountManager', IMountManager::class);
1036
-
1037
-		$this->registerService(IMimeTypeDetector::class, function (Server $c) {
1038
-			return new \OC\Files\Type\Detection(
1039
-				$c->getURLGenerator(),
1040
-				$c->getLogger(),
1041
-				\OC::$configDir,
1042
-				\OC::$SERVERROOT . '/resources/config/'
1043
-			);
1044
-		});
1045
-		$this->registerDeprecatedAlias('MimeTypeDetector', IMimeTypeDetector::class);
1046
-
1047
-		$this->registerService(IMimeTypeLoader::class, function (Server $c) {
1048
-			return new \OC\Files\Type\Loader(
1049
-				$c->getDatabaseConnection()
1050
-			);
1051
-		});
1052
-		$this->registerDeprecatedAlias('MimeTypeLoader', IMimeTypeLoader::class);
1053
-		$this->registerService(BundleFetcher::class, function () {
1054
-			return new BundleFetcher($this->getL10N('lib'));
1055
-		});
1056
-		$this->registerService(\OCP\Notification\IManager::class, function (Server $c) {
1057
-			return new Manager(
1058
-				$c->query(IValidator::class),
1059
-				$c->getLogger()
1060
-			);
1061
-		});
1062
-		$this->registerDeprecatedAlias('NotificationManager', \OCP\Notification\IManager::class);
1063
-
1064
-		$this->registerService(CapabilitiesManager::class, function (Server $c) {
1065
-			$manager = new CapabilitiesManager($c->getLogger());
1066
-			$manager->registerCapability(function () use ($c) {
1067
-				return new \OC\OCS\CoreCapabilities($c->getConfig());
1068
-			});
1069
-			$manager->registerCapability(function () use ($c) {
1070
-				return $c->query(\OC\Security\Bruteforce\Capabilities::class);
1071
-			});
1072
-			return $manager;
1073
-		});
1074
-		$this->registerDeprecatedAlias('CapabilitiesManager', CapabilitiesManager::class);
1075
-
1076
-		$this->registerService(ICommentsManager::class, function (Server $c) {
1077
-			$config = $c->getConfig();
1078
-			$factoryClass = $config->getSystemValue('comments.managerFactory', CommentsManagerFactory::class);
1079
-			/** @var \OCP\Comments\ICommentsManagerFactory $factory */
1080
-			$factory = new $factoryClass($this);
1081
-			$manager = $factory->getManager();
1082
-
1083
-			$manager->registerDisplayNameResolver('user', function($id) use ($c) {
1084
-				$manager = $c->getUserManager();
1085
-				$user = $manager->get($id);
1086
-				if(is_null($user)) {
1087
-					$l = $c->getL10N('core');
1088
-					$displayName = $l->t('Unknown user');
1089
-				} else {
1090
-					$displayName = $user->getDisplayName();
1091
-				}
1092
-				return $displayName;
1093
-			});
1094
-
1095
-			return $manager;
1096
-		});
1097
-		$this->registerDeprecatedAlias('CommentsManager', ICommentsManager::class);
1098
-
1099
-		$this->registerService('ThemingDefaults', function (Server $c) {
1100
-			/*
242
+    /** @var string */
243
+    private $webRoot;
244
+
245
+    /**
246
+     * @param string $webRoot
247
+     * @param \OC\Config $config
248
+     */
249
+    public function __construct($webRoot, \OC\Config $config) {
250
+        parent::__construct();
251
+        $this->webRoot = $webRoot;
252
+
253
+        // To find out if we are running from CLI or not
254
+        $this->registerParameter('isCLI', \OC::$CLI);
255
+
256
+        $this->registerService(\OCP\IServerContainer::class, function (IServerContainer $c) {
257
+            return $c;
258
+        });
259
+
260
+        $this->registerAlias(\OCP\Calendar\IManager::class, \OC\Calendar\Manager::class);
261
+        $this->registerDeprecatedAlias('CalendarManager', \OC\Calendar\Manager::class);
262
+
263
+        $this->registerAlias(\OCP\Calendar\Resource\IManager::class, \OC\Calendar\Resource\Manager::class);
264
+        $this->registerDeprecatedAlias('CalendarResourceBackendManager', \OC\Calendar\Resource\Manager::class);
265
+
266
+        $this->registerAlias(\OCP\Calendar\Room\IManager::class, \OC\Calendar\Room\Manager::class);
267
+        $this->registerDeprecatedAlias('CalendarRoomBackendManager', \OC\Calendar\Room\Manager::class);
268
+
269
+        $this->registerAlias(\OCP\Contacts\IManager::class, \OC\ContactsManager::class);
270
+        $this->registerDeprecatedAlias('ContactsManager', \OCP\Contacts\IManager::class);
271
+
272
+        $this->registerAlias(\OCP\DirectEditing\IManager::class, \OC\DirectEditing\Manager::class);
273
+
274
+        $this->registerAlias(IActionFactory::class, ActionFactory::class);
275
+
276
+
277
+        $this->registerService(IPreview::class, function (Server $c) {
278
+            return new PreviewManager(
279
+                $c->getConfig(),
280
+                $c->getRootFolder(),
281
+                $c->getAppDataDir('preview'),
282
+                $c->getEventDispatcher(),
283
+                $c->getGeneratorHelper(),
284
+                $c->getSession()->get('user_id')
285
+            );
286
+        });
287
+        $this->registerDeprecatedAlias('PreviewManager', IPreview::class);
288
+
289
+        $this->registerService(\OC\Preview\Watcher::class, function (Server $c) {
290
+            return new \OC\Preview\Watcher(
291
+                $c->getAppDataDir('preview')
292
+            );
293
+        });
294
+
295
+        $this->registerService(\OCP\Encryption\IManager::class, function (Server $c) {
296
+            $view = new View();
297
+            $util = new Encryption\Util(
298
+                $view,
299
+                $c->getUserManager(),
300
+                $c->getGroupManager(),
301
+                $c->getConfig()
302
+            );
303
+            return new Encryption\Manager(
304
+                $c->getConfig(),
305
+                $c->getLogger(),
306
+                $c->getL10N('core'),
307
+                new View(),
308
+                $util,
309
+                new ArrayCache()
310
+            );
311
+        });
312
+        $this->registerDeprecatedAlias('EncryptionManager', \OCP\Encryption\IManager::class);
313
+
314
+        $this->registerService('EncryptionFileHelper', function (Server $c) {
315
+            $util = new Encryption\Util(
316
+                new View(),
317
+                $c->getUserManager(),
318
+                $c->getGroupManager(),
319
+                $c->getConfig()
320
+            );
321
+            return new Encryption\File(
322
+                $util,
323
+                $c->getRootFolder(),
324
+                $c->getShareManager()
325
+            );
326
+        });
327
+
328
+        $this->registerService('EncryptionKeyStorage', function (Server $c) {
329
+            $view = new View();
330
+            $util = new Encryption\Util(
331
+                $view,
332
+                $c->getUserManager(),
333
+                $c->getGroupManager(),
334
+                $c->getConfig()
335
+            );
336
+
337
+            return new Encryption\Keys\Storage($view, $util);
338
+        });
339
+        $this->registerService('TagMapper', function (Server $c) {
340
+            return new TagMapper($c->getDatabaseConnection());
341
+        });
342
+
343
+        $this->registerService(\OCP\ITagManager::class, function (Server $c) {
344
+            $tagMapper = $c->query('TagMapper');
345
+            return new TagManager($tagMapper, $c->getUserSession());
346
+        });
347
+        $this->registerDeprecatedAlias('TagManager', \OCP\ITagManager::class);
348
+
349
+        $this->registerService('SystemTagManagerFactory', function (Server $c) {
350
+            $config = $c->getConfig();
351
+            $factoryClass = $config->getSystemValue('systemtags.managerFactory', SystemTagManagerFactory::class);
352
+            return new $factoryClass($this);
353
+        });
354
+        $this->registerService(ISystemTagManager::class, function (Server $c) {
355
+            return $c->query('SystemTagManagerFactory')->getManager();
356
+        });
357
+        $this->registerDeprecatedAlias('SystemTagManager', ISystemTagManager::class);
358
+
359
+        $this->registerService(ISystemTagObjectMapper::class, function (Server $c) {
360
+            return $c->query('SystemTagManagerFactory')->getObjectMapper();
361
+        });
362
+        $this->registerService('RootFolder', function (Server $c) {
363
+            $manager = \OC\Files\Filesystem::getMountManager(null);
364
+            $view = new View();
365
+            $root = new Root(
366
+                $manager,
367
+                $view,
368
+                null,
369
+                $c->getUserMountCache(),
370
+                $this->getLogger(),
371
+                $this->getUserManager()
372
+            );
373
+            $connector = new HookConnector($root, $view, $c->getEventDispatcher());
374
+            $connector->viewToNode();
375
+
376
+            $previewConnector = new \OC\Preview\WatcherConnector($root, $c->getSystemConfig());
377
+            $previewConnector->connectWatcher();
378
+
379
+            return $root;
380
+        });
381
+        $this->registerDeprecatedAlias('SystemTagObjectMapper', ISystemTagObjectMapper::class);
382
+
383
+        $this->registerService(IRootFolder::class, function (Server $c) {
384
+            return new LazyRoot(function () use ($c) {
385
+                return $c->query('RootFolder');
386
+            });
387
+        });
388
+        $this->registerDeprecatedAlias('LazyRootFolder', IRootFolder::class);
389
+
390
+        $this->registerDeprecatedAlias('UserManager', \OC\User\Manager::class);
391
+        $this->registerAlias(\OCP\IUserManager::class, \OC\User\Manager::class);
392
+
393
+        $this->registerService(\OCP\IGroupManager::class, function (Server $c) {
394
+            $groupManager = new \OC\Group\Manager($this->getUserManager(), $c->getEventDispatcher(), $this->getLogger());
395
+            $groupManager->listen('\OC\Group', 'preCreate', function ($gid) {
396
+                \OC_Hook::emit('OC_Group', 'pre_createGroup', ['run' => true, 'gid' => $gid]);
397
+
398
+                /** @var IEventDispatcher $dispatcher */
399
+                $dispatcher = $this->query(IEventDispatcher::class);
400
+                $dispatcher->dispatchTyped(new BeforeGroupCreatedEvent($gid));
401
+            });
402
+            $groupManager->listen('\OC\Group', 'postCreate', function (\OC\Group\Group $group) {
403
+                \OC_Hook::emit('OC_User', 'post_createGroup', ['gid' => $group->getGID()]);
404
+
405
+                /** @var IEventDispatcher $dispatcher */
406
+                $dispatcher = $this->query(IEventDispatcher::class);
407
+                $dispatcher->dispatchTyped(new GroupCreatedEvent($group));
408
+            });
409
+            $groupManager->listen('\OC\Group', 'preDelete', function (\OC\Group\Group $group) {
410
+                \OC_Hook::emit('OC_Group', 'pre_deleteGroup', ['run' => true, 'gid' => $group->getGID()]);
411
+
412
+                /** @var IEventDispatcher $dispatcher */
413
+                $dispatcher = $this->query(IEventDispatcher::class);
414
+                $dispatcher->dispatchTyped(new BeforeGroupDeletedEvent($group));
415
+            });
416
+            $groupManager->listen('\OC\Group', 'postDelete', function (\OC\Group\Group $group) {
417
+                \OC_Hook::emit('OC_User', 'post_deleteGroup', ['gid' => $group->getGID()]);
418
+
419
+                /** @var IEventDispatcher $dispatcher */
420
+                $dispatcher = $this->query(IEventDispatcher::class);
421
+                $dispatcher->dispatchTyped(new GroupDeletedEvent($group));
422
+            });
423
+            $groupManager->listen('\OC\Group', 'preAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
424
+                \OC_Hook::emit('OC_Group', 'pre_addToGroup', ['run' => true, 'uid' => $user->getUID(), 'gid' => $group->getGID()]);
425
+
426
+                /** @var IEventDispatcher $dispatcher */
427
+                $dispatcher = $this->query(IEventDispatcher::class);
428
+                $dispatcher->dispatchTyped(new BeforeUserAddedEvent($group, $user));
429
+            });
430
+            $groupManager->listen('\OC\Group', 'postAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
431
+                \OC_Hook::emit('OC_Group', 'post_addToGroup', ['uid' => $user->getUID(), 'gid' => $group->getGID()]);
432
+                //Minimal fix to keep it backward compatible TODO: clean up all the GroupManager hooks
433
+                \OC_Hook::emit('OC_User', 'post_addToGroup', ['uid' => $user->getUID(), 'gid' => $group->getGID()]);
434
+
435
+                /** @var IEventDispatcher $dispatcher */
436
+                $dispatcher = $this->query(IEventDispatcher::class);
437
+                $dispatcher->dispatchTyped(new UserAddedEvent($group, $user));
438
+            });
439
+            $groupManager->listen('\OC\Group', 'preRemoveUser', function (\OC\Group\Group $group, \OC\User\User $user) {
440
+                /** @var IEventDispatcher $dispatcher */
441
+                $dispatcher = $this->query(IEventDispatcher::class);
442
+                $dispatcher->dispatchTyped(new BeforeUserRemovedEvent($group, $user));
443
+            });
444
+            $groupManager->listen('\OC\Group', 'postRemoveUser', function (\OC\Group\Group $group, \OC\User\User $user) {
445
+                /** @var IEventDispatcher $dispatcher */
446
+                $dispatcher = $this->query(IEventDispatcher::class);
447
+                $dispatcher->dispatchTyped(new UserRemovedEvent($group, $user));
448
+            });
449
+            return $groupManager;
450
+        });
451
+        $this->registerDeprecatedAlias('GroupManager', \OCP\IGroupManager::class);
452
+
453
+        $this->registerService(Store::class, function (Server $c) {
454
+            $session = $c->getSession();
455
+            if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
456
+                $tokenProvider = $c->query(IProvider::class);
457
+            } else {
458
+                $tokenProvider = null;
459
+            }
460
+            $logger = $c->getLogger();
461
+            return new Store($session, $logger, $tokenProvider);
462
+        });
463
+        $this->registerAlias(IStore::class, Store::class);
464
+        $this->registerService(Authentication\Token\DefaultTokenMapper::class, function (Server $c) {
465
+            $dbConnection = $c->getDatabaseConnection();
466
+            return new Authentication\Token\DefaultTokenMapper($dbConnection);
467
+        });
468
+        $this->registerAlias(IProvider::class, Authentication\Token\Manager::class);
469
+
470
+        $this->registerService(\OC\User\Session::class, function (Server $c) {
471
+            $manager = $c->getUserManager();
472
+            $session = new \OC\Session\Memory('');
473
+            $timeFactory = new TimeFactory();
474
+            // Token providers might require a working database. This code
475
+            // might however be called when ownCloud is not yet setup.
476
+            if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
477
+                $defaultTokenProvider = $c->query(IProvider::class);
478
+            } else {
479
+                $defaultTokenProvider = null;
480
+            }
481
+
482
+            $legacyDispatcher = $c->getEventDispatcher();
483
+
484
+            $userSession = new \OC\User\Session(
485
+                $manager,
486
+                $session,
487
+                $timeFactory,
488
+                $defaultTokenProvider,
489
+                $c->getConfig(),
490
+                $c->getSecureRandom(),
491
+                $c->getLockdownManager(),
492
+                $c->getLogger(),
493
+                $c->query(IEventDispatcher::class)
494
+            );
495
+            $userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
496
+                \OC_Hook::emit('OC_User', 'pre_createUser', ['run' => true, 'uid' => $uid, 'password' => $password]);
497
+
498
+                /** @var IEventDispatcher $dispatcher */
499
+                $dispatcher = $this->query(IEventDispatcher::class);
500
+                $dispatcher->dispatchTyped(new BeforeUserCreatedEvent($uid, $password));
501
+            });
502
+            $userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
503
+                /** @var $user \OC\User\User */
504
+                \OC_Hook::emit('OC_User', 'post_createUser', ['uid' => $user->getUID(), 'password' => $password]);
505
+
506
+                /** @var IEventDispatcher $dispatcher */
507
+                $dispatcher = $this->query(IEventDispatcher::class);
508
+                $dispatcher->dispatchTyped(new UserCreatedEvent($user, $password));
509
+            });
510
+            $userSession->listen('\OC\User', 'preDelete', function ($user) use ($legacyDispatcher) {
511
+                /** @var $user \OC\User\User */
512
+                \OC_Hook::emit('OC_User', 'pre_deleteUser', ['run' => true, 'uid' => $user->getUID()]);
513
+                $legacyDispatcher->dispatch('OCP\IUser::preDelete', new GenericEvent($user));
514
+
515
+                /** @var IEventDispatcher $dispatcher */
516
+                $dispatcher = $this->query(IEventDispatcher::class);
517
+                $dispatcher->dispatchTyped(new BeforeUserDeletedEvent($user));
518
+            });
519
+            $userSession->listen('\OC\User', 'postDelete', function ($user) {
520
+                /** @var $user \OC\User\User */
521
+                \OC_Hook::emit('OC_User', 'post_deleteUser', ['uid' => $user->getUID()]);
522
+
523
+                /** @var IEventDispatcher $dispatcher */
524
+                $dispatcher = $this->query(IEventDispatcher::class);
525
+                $dispatcher->dispatchTyped(new UserDeletedEvent($user));
526
+            });
527
+            $userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
528
+                /** @var $user \OC\User\User */
529
+                \OC_Hook::emit('OC_User', 'pre_setPassword', ['run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword]);
530
+
531
+                /** @var IEventDispatcher $dispatcher */
532
+                $dispatcher = $this->query(IEventDispatcher::class);
533
+                $dispatcher->dispatchTyped(new BeforePasswordUpdatedEvent($user, $password, $recoveryPassword));
534
+            });
535
+            $userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
536
+                /** @var $user \OC\User\User */
537
+                \OC_Hook::emit('OC_User', 'post_setPassword', ['run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword]);
538
+
539
+                /** @var IEventDispatcher $dispatcher */
540
+                $dispatcher = $this->query(IEventDispatcher::class);
541
+                $dispatcher->dispatchTyped(new PasswordUpdatedEvent($user, $password, $recoveryPassword));
542
+            });
543
+            $userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
544
+                \OC_Hook::emit('OC_User', 'pre_login', ['run' => true, 'uid' => $uid, 'password' => $password]);
545
+
546
+                /** @var IEventDispatcher $dispatcher */
547
+                $dispatcher = $this->query(IEventDispatcher::class);
548
+                $dispatcher->dispatchTyped(new BeforeUserLoggedInEvent($uid, $password));
549
+            });
550
+            $userSession->listen('\OC\User', 'postLogin', function ($user, $password, $isTokenLogin) {
551
+                /** @var $user \OC\User\User */
552
+                \OC_Hook::emit('OC_User', 'post_login', ['run' => true, 'uid' => $user->getUID(), 'password' => $password, 'isTokenLogin' => $isTokenLogin]);
553
+
554
+                /** @var IEventDispatcher $dispatcher */
555
+                $dispatcher = $this->query(IEventDispatcher::class);
556
+                $dispatcher->dispatchTyped(new UserLoggedInEvent($user, $password, $isTokenLogin));
557
+            });
558
+            $userSession->listen('\OC\User', 'preRememberedLogin', function ($uid) {
559
+                /** @var IEventDispatcher $dispatcher */
560
+                $dispatcher = $this->query(IEventDispatcher::class);
561
+                $dispatcher->dispatchTyped(new BeforeUserLoggedInWithCookieEvent($uid));
562
+            });
563
+            $userSession->listen('\OC\User', 'postRememberedLogin', function ($user, $password) {
564
+                /** @var $user \OC\User\User */
565
+                \OC_Hook::emit('OC_User', 'post_login', ['run' => true, 'uid' => $user->getUID(), 'password' => $password]);
566
+
567
+                /** @var IEventDispatcher $dispatcher */
568
+                $dispatcher = $this->query(IEventDispatcher::class);
569
+                $dispatcher->dispatchTyped(new UserLoggedInWithCookieEvent($user, $password));
570
+            });
571
+            $userSession->listen('\OC\User', 'logout', function ($user) {
572
+                \OC_Hook::emit('OC_User', 'logout', []);
573
+
574
+                /** @var IEventDispatcher $dispatcher */
575
+                $dispatcher = $this->query(IEventDispatcher::class);
576
+                $dispatcher->dispatchTyped(new BeforeUserLoggedOutEvent($user));
577
+            });
578
+            $userSession->listen('\OC\User', 'postLogout', function ($user) {
579
+                /** @var IEventDispatcher $dispatcher */
580
+                $dispatcher = $this->query(IEventDispatcher::class);
581
+                $dispatcher->dispatchTyped(new UserLoggedOutEvent($user));
582
+            });
583
+            $userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value, $oldValue) {
584
+                /** @var $user \OC\User\User */
585
+                \OC_Hook::emit('OC_User', 'changeUser', ['run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value, 'old_value' => $oldValue]);
586
+
587
+                /** @var IEventDispatcher $dispatcher */
588
+                $dispatcher = $this->query(IEventDispatcher::class);
589
+                $dispatcher->dispatchTyped(new UserChangedEvent($user, $feature, $value, $oldValue));
590
+            });
591
+            return $userSession;
592
+        });
593
+        $this->registerAlias(\OCP\IUserSession::class, \OC\User\Session::class);
594
+        $this->registerDeprecatedAlias('UserSession', \OC\User\Session::class);
595
+
596
+        $this->registerAlias(\OCP\Authentication\TwoFactorAuth\IRegistry::class, \OC\Authentication\TwoFactorAuth\Registry::class);
597
+
598
+        $this->registerAlias(INavigationManager::class, \OC\NavigationManager::class);
599
+        $this->registerDeprecatedAlias('NavigationManager', INavigationManager::class);
600
+
601
+        $this->registerService(\OC\AllConfig::class, function (Server $c) {
602
+            return new \OC\AllConfig(
603
+                $c->getSystemConfig()
604
+            );
605
+        });
606
+        $this->registerDeprecatedAlias('AllConfig', \OC\AllConfig::class);
607
+        $this->registerAlias(\OCP\IConfig::class, \OC\AllConfig::class);
608
+
609
+        $this->registerService(\OC\SystemConfig::class, function ($c) use ($config) {
610
+            return new \OC\SystemConfig($config);
611
+        });
612
+        $this->registerDeprecatedAlias('SystemConfig', \OC\SystemConfig::class);
613
+
614
+        $this->registerService(\OC\AppConfig::class, function (Server $c) {
615
+            return new \OC\AppConfig($c->getDatabaseConnection());
616
+        });
617
+        $this->registerDeprecatedAlias('AppConfig', \OC\AppConfig::class);
618
+        $this->registerAlias(IAppConfig::class, \OC\AppConfig::class);
619
+
620
+        $this->registerService(IFactory::class, function (Server $c) {
621
+            return new \OC\L10N\Factory(
622
+                $c->getConfig(),
623
+                $c->getRequest(),
624
+                $c->getUserSession(),
625
+                \OC::$SERVERROOT
626
+            );
627
+        });
628
+        $this->registerDeprecatedAlias('L10NFactory', IFactory::class);
629
+
630
+        $this->registerService(IURLGenerator::class, function (Server $c) {
631
+            $config = $c->getConfig();
632
+            $cacheFactory = $c->getMemCacheFactory();
633
+            $request = $c->getRequest();
634
+            return new \OC\URLGenerator(
635
+                $config,
636
+                $cacheFactory,
637
+                $request
638
+            );
639
+        });
640
+        $this->registerDeprecatedAlias('URLGenerator', IURLGenerator::class);
641
+
642
+        $this->registerDeprecatedAlias('AppFetcher', AppFetcher::class);
643
+        $this->registerDeprecatedAlias('CategoryFetcher', CategoryFetcher::class);
644
+
645
+        $this->registerService(ICache::class, function ($c) {
646
+            return new Cache\File();
647
+        });
648
+        $this->registerDeprecatedAlias('UserCache', ICache::class);
649
+
650
+        $this->registerService(Factory::class, function (Server $c) {
651
+
652
+            $arrayCacheFactory = new \OC\Memcache\Factory('', $c->getLogger(),
653
+                ArrayCache::class,
654
+                ArrayCache::class,
655
+                ArrayCache::class
656
+            );
657
+            $config = $c->getConfig();
658
+
659
+            if ($config->getSystemValue('installed', false) && !(defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
660
+                $v = \OC_App::getAppVersions();
661
+                $v['core'] = implode(',', \OC_Util::getVersion());
662
+                $version = implode(',', $v);
663
+                $instanceId = \OC_Util::getInstanceId();
664
+                $path = \OC::$SERVERROOT;
665
+                $prefix = md5($instanceId . '-' . $version . '-' . $path);
666
+                return new \OC\Memcache\Factory($prefix, $c->getLogger(),
667
+                    $config->getSystemValue('memcache.local', null),
668
+                    $config->getSystemValue('memcache.distributed', null),
669
+                    $config->getSystemValue('memcache.locking', null)
670
+                );
671
+            }
672
+            return $arrayCacheFactory;
673
+
674
+        });
675
+        $this->registerDeprecatedAlias('MemCacheFactory', Factory::class);
676
+        $this->registerAlias(ICacheFactory::class, Factory::class);
677
+
678
+        $this->registerService('RedisFactory', function (Server $c) {
679
+            $systemConfig = $c->getSystemConfig();
680
+            return new RedisFactory($systemConfig);
681
+        });
682
+
683
+        $this->registerService(\OCP\Activity\IManager::class, function (Server $c) {
684
+            return new \OC\Activity\Manager(
685
+                $c->getRequest(),
686
+                $c->getUserSession(),
687
+                $c->getConfig(),
688
+                $c->query(IValidator::class)
689
+            );
690
+        });
691
+        $this->registerDeprecatedAlias('ActivityManager', \OCP\Activity\IManager::class);
692
+
693
+        $this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
694
+            return new \OC\Activity\EventMerger(
695
+                $c->getL10N('lib')
696
+            );
697
+        });
698
+        $this->registerAlias(IValidator::class, Validator::class);
699
+
700
+        $this->registerService(AvatarManager::class, function(Server $c) {
701
+            return new AvatarManager(
702
+                $c->query(\OC\User\Manager::class),
703
+                $c->getAppDataDir('avatar'),
704
+                $c->getL10N('lib'),
705
+                $c->getLogger(),
706
+                $c->getConfig()
707
+            );
708
+        });
709
+        $this->registerAlias(IAvatarManager::class, AvatarManager::class);
710
+        $this->registerDeprecatedAlias('AvatarManager', AvatarManager::class);
711
+
712
+        $this->registerAlias(\OCP\Support\CrashReport\IRegistry::class, \OC\Support\CrashReport\Registry::class);
713
+        $this->registerAlias(\OCP\Support\Subscription\IRegistry::class, \OC\Support\Subscription\Registry::class);
714
+
715
+        $this->registerService(\OC\Log::class, function (Server $c) {
716
+            $logType = $c->query(AllConfig::class)->getSystemValue('log_type', 'file');
717
+            $factory = new LogFactory($c, $this->getSystemConfig());
718
+            $logger = $factory->get($logType);
719
+            $registry = $c->query(\OCP\Support\CrashReport\IRegistry::class);
720
+
721
+            return new Log($logger, $this->getSystemConfig(), null, $registry);
722
+        });
723
+        $this->registerAlias(ILogger::class, \OC\Log::class);
724
+        $this->registerDeprecatedAlias('Logger', \OC\Log::class);
725
+
726
+        $this->registerService(ILogFactory::class, function (Server $c) {
727
+            return new LogFactory($c, $this->getSystemConfig());
728
+        });
729
+
730
+        $this->registerService(IJobList::class, function (Server $c) {
731
+            $config = $c->getConfig();
732
+            return new \OC\BackgroundJob\JobList(
733
+                $c->getDatabaseConnection(),
734
+                $config,
735
+                new TimeFactory()
736
+            );
737
+        });
738
+        $this->registerDeprecatedAlias('JobList', IJobList::class);
739
+
740
+        $this->registerService(IRouter::class, function (Server $c) {
741
+            $cacheFactory = $c->getMemCacheFactory();
742
+            $logger = $c->getLogger();
743
+            if ($cacheFactory->isLocalCacheAvailable()) {
744
+                $router = new \OC\Route\CachingRouter($cacheFactory->createLocal('route'), $logger);
745
+            } else {
746
+                $router = new \OC\Route\Router($logger);
747
+            }
748
+            return $router;
749
+        });
750
+        $this->registerDeprecatedAlias('Router', IRouter::class);
751
+
752
+        $this->registerService(ISearch::class, function ($c) {
753
+            return new Search();
754
+        });
755
+        $this->registerDeprecatedAlias('Search', ISearch::class);
756
+
757
+        $this->registerService(\OC\Security\RateLimiting\Backend\IBackend::class, function ($c) {
758
+            return new \OC\Security\RateLimiting\Backend\MemoryCache(
759
+                $this->getMemCacheFactory(),
760
+                new \OC\AppFramework\Utility\TimeFactory()
761
+            );
762
+        });
763
+
764
+        $this->registerService(\OCP\Security\ISecureRandom::class, function ($c) {
765
+            return new SecureRandom();
766
+        });
767
+        $this->registerDeprecatedAlias('SecureRandom', \OCP\Security\ISecureRandom::class);
768
+
769
+        $this->registerService(ICrypto::class, function (Server $c) {
770
+            return new Crypto($c->getConfig(), $c->getSecureRandom());
771
+        });
772
+        $this->registerDeprecatedAlias('Crypto', ICrypto::class);
773
+
774
+        $this->registerService(IHasher::class, function (Server $c) {
775
+            return new Hasher($c->getConfig());
776
+        });
777
+        $this->registerDeprecatedAlias('Hasher', IHasher::class);
778
+
779
+        $this->registerService(ICredentialsManager::class, function (Server $c) {
780
+            return new CredentialsManager($c->getCrypto(), $c->getDatabaseConnection());
781
+        });
782
+        $this->registerDeprecatedAlias('CredentialsManager', ICredentialsManager::class);
783
+
784
+        $this->registerService(IDBConnection::class, function (Server $c) {
785
+            $systemConfig = $c->getSystemConfig();
786
+            $factory = new \OC\DB\ConnectionFactory($systemConfig);
787
+            $type = $systemConfig->getValue('dbtype', 'sqlite');
788
+            if (!$factory->isValidType($type)) {
789
+                throw new \OC\DatabaseException('Invalid database type');
790
+            }
791
+            $connectionParams = $factory->createConnectionParams();
792
+            $connection = $factory->getConnection($type, $connectionParams);
793
+            $connection->getConfiguration()->setSQLLogger($c->getQueryLogger());
794
+            return $connection;
795
+        });
796
+        $this->registerDeprecatedAlias('DatabaseConnection', IDBConnection::class);
797
+
798
+
799
+        $this->registerService(IClientService::class, function (Server $c) {
800
+            $user = \OC_User::getUser();
801
+            $uid = $user ? $user : null;
802
+            return new ClientService(
803
+                $c->getConfig(),
804
+                new \OC\Security\CertificateManager(
805
+                    $uid,
806
+                    new View(),
807
+                    $c->getConfig(),
808
+                    $c->getLogger(),
809
+                    $c->getSecureRandom()
810
+                )
811
+            );
812
+        });
813
+        $this->registerDeprecatedAlias('HttpClientService', IClientService::class);
814
+        $this->registerService(IEventLogger::class, function (Server $c) {
815
+            $eventLogger = new EventLogger();
816
+            if ($c->getSystemConfig()->getValue('debug', false)) {
817
+                // In debug mode, module is being activated by default
818
+                $eventLogger->activate();
819
+            }
820
+            return $eventLogger;
821
+        });
822
+        $this->registerDeprecatedAlias('EventLogger', IEventLogger::class);
823
+
824
+        $this->registerService(IQueryLogger::class, function (Server $c) {
825
+            $queryLogger = new QueryLogger();
826
+            if ($c->getSystemConfig()->getValue('debug', false)) {
827
+                // In debug mode, module is being activated by default
828
+                $queryLogger->activate();
829
+            }
830
+            return $queryLogger;
831
+        });
832
+        $this->registerDeprecatedAlias('QueryLogger', IQueryLogger::class);
833
+
834
+        $this->registerService(TempManager::class, function (Server $c) {
835
+            return new TempManager(
836
+                $c->getLogger(),
837
+                $c->getConfig()
838
+            );
839
+        });
840
+        $this->registerDeprecatedAlias('TempManager', TempManager::class);
841
+        $this->registerAlias(ITempManager::class, TempManager::class);
842
+
843
+        $this->registerService(AppManager::class, function (Server $c) {
844
+            return new \OC\App\AppManager(
845
+                $c->getUserSession(),
846
+                $c->getConfig(),
847
+                $c->query(\OC\AppConfig::class),
848
+                $c->getGroupManager(),
849
+                $c->getMemCacheFactory(),
850
+                $c->getEventDispatcher(),
851
+                $c->getLogger()
852
+            );
853
+        });
854
+        $this->registerDeprecatedAlias('AppManager', AppManager::class);
855
+        $this->registerAlias(IAppManager::class, AppManager::class);
856
+
857
+        $this->registerService(IDateTimeZone::class, function (Server $c) {
858
+            return new DateTimeZone(
859
+                $c->getConfig(),
860
+                $c->getSession()
861
+            );
862
+        });
863
+        $this->registerDeprecatedAlias('DateTimeZone', IDateTimeZone::class);
864
+
865
+        $this->registerService(IDateTimeFormatter::class, function (Server $c) {
866
+            $language = $c->getConfig()->getUserValue($c->getSession()->get('user_id'), 'core', 'lang', null);
867
+
868
+            return new DateTimeFormatter(
869
+                $c->getDateTimeZone()->getTimeZone(),
870
+                $c->getL10N('lib', $language)
871
+            );
872
+        });
873
+        $this->registerDeprecatedAlias('DateTimeFormatter', IDateTimeFormatter::class);
874
+
875
+        $this->registerService(IUserMountCache::class, function (Server $c) {
876
+            $mountCache = new UserMountCache($c->getDatabaseConnection(), $c->getUserManager(), $c->getLogger());
877
+            $listener = new UserMountCacheListener($mountCache);
878
+            $listener->listen($c->getUserManager());
879
+            return $mountCache;
880
+        });
881
+        $this->registerDeprecatedAlias('UserMountCache', IUserMountCache::class);
882
+
883
+        $this->registerService(IMountProviderCollection::class, function (Server $c) {
884
+            $loader = \OC\Files\Filesystem::getLoader();
885
+            $mountCache = $c->query(IUserMountCache::class);
886
+            $manager = new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
887
+
888
+            // builtin providers
889
+
890
+            $config = $c->getConfig();
891
+            $manager->registerProvider(new CacheMountProvider($config));
892
+            $manager->registerHomeProvider(new LocalHomeMountProvider());
893
+            $manager->registerHomeProvider(new ObjectHomeMountProvider($config));
894
+
895
+            return $manager;
896
+        });
897
+        $this->registerDeprecatedAlias('MountConfigManager', IMountProviderCollection::class);
898
+
899
+        $this->registerService('IniWrapper', function ($c) {
900
+            return new IniGetWrapper();
901
+        });
902
+        $this->registerService('AsyncCommandBus', function (Server $c) {
903
+            $busClass = $c->getConfig()->getSystemValue('commandbus');
904
+            if ($busClass) {
905
+                list($app, $class) = explode('::', $busClass, 2);
906
+                if ($c->getAppManager()->isInstalled($app)) {
907
+                    \OC_App::loadApp($app);
908
+                    return $c->query($class);
909
+                } else {
910
+                    throw new ServiceUnavailableException("The app providing the command bus ($app) is not enabled");
911
+                }
912
+            } else {
913
+                $jobList = $c->getJobList();
914
+                return new CronBus($jobList);
915
+            }
916
+        });
917
+        $this->registerService('TrustedDomainHelper', function ($c) {
918
+            return new TrustedDomainHelper($this->getConfig());
919
+        });
920
+        $this->registerService(Throttler::class, function (Server $c) {
921
+            return new Throttler(
922
+                $c->getDatabaseConnection(),
923
+                new TimeFactory(),
924
+                $c->getLogger(),
925
+                $c->getConfig()
926
+            );
927
+        });
928
+        $this->registerDeprecatedAlias('Throttler', Throttler::class);
929
+        $this->registerService('IntegrityCodeChecker', function (Server $c) {
930
+            // IConfig and IAppManager requires a working database. This code
931
+            // might however be called when ownCloud is not yet setup.
932
+            if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
933
+                $config = $c->getConfig();
934
+                $appManager = $c->getAppManager();
935
+            } else {
936
+                $config = null;
937
+                $appManager = null;
938
+            }
939
+
940
+            return new Checker(
941
+                new EnvironmentHelper(),
942
+                new FileAccessHelper(),
943
+                new AppLocator(),
944
+                $config,
945
+                $c->getMemCacheFactory(),
946
+                $appManager,
947
+                $c->getTempManager(),
948
+                $c->getMimeTypeDetector()
949
+            );
950
+        });
951
+        $this->registerService(\OCP\IRequest::class, function ($c) {
952
+            if (isset($this['urlParams'])) {
953
+                $urlParams = $this['urlParams'];
954
+            } else {
955
+                $urlParams = [];
956
+            }
957
+
958
+            if (defined('PHPUNIT_RUN') && PHPUNIT_RUN
959
+                && in_array('fakeinput', stream_get_wrappers())
960
+            ) {
961
+                $stream = 'fakeinput://data';
962
+            } else {
963
+                $stream = 'php://input';
964
+            }
965
+
966
+            return new Request(
967
+                [
968
+                    'get' => $_GET,
969
+                    'post' => $_POST,
970
+                    'files' => $_FILES,
971
+                    'server' => $_SERVER,
972
+                    'env' => $_ENV,
973
+                    'cookies' => $_COOKIE,
974
+                    'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
975
+                        ? $_SERVER['REQUEST_METHOD']
976
+                        : '',
977
+                    'urlParams' => $urlParams,
978
+                ],
979
+                $this->getSecureRandom(),
980
+                $this->getConfig(),
981
+                $this->getCsrfTokenManager(),
982
+                $stream
983
+            );
984
+        });
985
+        $this->registerDeprecatedAlias('Request', \OCP\IRequest::class);
986
+
987
+        $this->registerService(IMailer::class, function (Server $c) {
988
+            return new Mailer(
989
+                $c->getConfig(),
990
+                $c->getLogger(),
991
+                $c->query(Defaults::class),
992
+                $c->getURLGenerator(),
993
+                $c->getL10N('lib'),
994
+                $c->query(IEventDispatcher::class)
995
+            );
996
+        });
997
+        $this->registerDeprecatedAlias('Mailer', IMailer::class);
998
+
999
+        $this->registerService('LDAPProvider', function (Server $c) {
1000
+            $config = $c->getConfig();
1001
+            $factoryClass = $config->getSystemValue('ldapProviderFactory', null);
1002
+            if (is_null($factoryClass)) {
1003
+                throw new \Exception('ldapProviderFactory not set');
1004
+            }
1005
+            /** @var \OCP\LDAP\ILDAPProviderFactory $factory */
1006
+            $factory = new $factoryClass($this);
1007
+            return $factory->getLDAPProvider();
1008
+        });
1009
+        $this->registerService(ILockingProvider::class, function (Server $c) {
1010
+            $ini = $c->getIniWrapper();
1011
+            $config = $c->getConfig();
1012
+            $ttl = $config->getSystemValue('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
1013
+            if ($config->getSystemValue('filelocking.enabled', true) or (defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
1014
+                /** @var \OC\Memcache\Factory $memcacheFactory */
1015
+                $memcacheFactory = $c->getMemCacheFactory();
1016
+                $memcache = $memcacheFactory->createLocking('lock');
1017
+                if (!($memcache instanceof \OC\Memcache\NullCache)) {
1018
+                    return new MemcacheLockingProvider($memcache, $ttl);
1019
+                }
1020
+                return new DBLockingProvider(
1021
+                    $c->getDatabaseConnection(),
1022
+                    $c->getLogger(),
1023
+                    new TimeFactory(),
1024
+                    $ttl,
1025
+                    !\OC::$CLI
1026
+                );
1027
+            }
1028
+            return new NoopLockingProvider();
1029
+        });
1030
+        $this->registerDeprecatedAlias('LockingProvider', ILockingProvider::class);
1031
+
1032
+        $this->registerService(IMountManager::class, function () {
1033
+            return new \OC\Files\Mount\Manager();
1034
+        });
1035
+        $this->registerDeprecatedAlias('MountManager', IMountManager::class);
1036
+
1037
+        $this->registerService(IMimeTypeDetector::class, function (Server $c) {
1038
+            return new \OC\Files\Type\Detection(
1039
+                $c->getURLGenerator(),
1040
+                $c->getLogger(),
1041
+                \OC::$configDir,
1042
+                \OC::$SERVERROOT . '/resources/config/'
1043
+            );
1044
+        });
1045
+        $this->registerDeprecatedAlias('MimeTypeDetector', IMimeTypeDetector::class);
1046
+
1047
+        $this->registerService(IMimeTypeLoader::class, function (Server $c) {
1048
+            return new \OC\Files\Type\Loader(
1049
+                $c->getDatabaseConnection()
1050
+            );
1051
+        });
1052
+        $this->registerDeprecatedAlias('MimeTypeLoader', IMimeTypeLoader::class);
1053
+        $this->registerService(BundleFetcher::class, function () {
1054
+            return new BundleFetcher($this->getL10N('lib'));
1055
+        });
1056
+        $this->registerService(\OCP\Notification\IManager::class, function (Server $c) {
1057
+            return new Manager(
1058
+                $c->query(IValidator::class),
1059
+                $c->getLogger()
1060
+            );
1061
+        });
1062
+        $this->registerDeprecatedAlias('NotificationManager', \OCP\Notification\IManager::class);
1063
+
1064
+        $this->registerService(CapabilitiesManager::class, function (Server $c) {
1065
+            $manager = new CapabilitiesManager($c->getLogger());
1066
+            $manager->registerCapability(function () use ($c) {
1067
+                return new \OC\OCS\CoreCapabilities($c->getConfig());
1068
+            });
1069
+            $manager->registerCapability(function () use ($c) {
1070
+                return $c->query(\OC\Security\Bruteforce\Capabilities::class);
1071
+            });
1072
+            return $manager;
1073
+        });
1074
+        $this->registerDeprecatedAlias('CapabilitiesManager', CapabilitiesManager::class);
1075
+
1076
+        $this->registerService(ICommentsManager::class, function (Server $c) {
1077
+            $config = $c->getConfig();
1078
+            $factoryClass = $config->getSystemValue('comments.managerFactory', CommentsManagerFactory::class);
1079
+            /** @var \OCP\Comments\ICommentsManagerFactory $factory */
1080
+            $factory = new $factoryClass($this);
1081
+            $manager = $factory->getManager();
1082
+
1083
+            $manager->registerDisplayNameResolver('user', function($id) use ($c) {
1084
+                $manager = $c->getUserManager();
1085
+                $user = $manager->get($id);
1086
+                if(is_null($user)) {
1087
+                    $l = $c->getL10N('core');
1088
+                    $displayName = $l->t('Unknown user');
1089
+                } else {
1090
+                    $displayName = $user->getDisplayName();
1091
+                }
1092
+                return $displayName;
1093
+            });
1094
+
1095
+            return $manager;
1096
+        });
1097
+        $this->registerDeprecatedAlias('CommentsManager', ICommentsManager::class);
1098
+
1099
+        $this->registerService('ThemingDefaults', function (Server $c) {
1100
+            /*
1101 1101
 			 * Dark magic for autoloader.
1102 1102
 			 * If we do a class_exists it will try to load the class which will
1103 1103
 			 * make composer cache the result. Resulting in errors when enabling
1104 1104
 			 * the theming app.
1105 1105
 			 */
1106
-			$prefixes = \OC::$composerAutoloader->getPrefixesPsr4();
1107
-			if (isset($prefixes['OCA\\Theming\\'])) {
1108
-				$classExists = true;
1109
-			} else {
1110
-				$classExists = false;
1111
-			}
1112
-
1113
-			if ($classExists && $c->getConfig()->getSystemValue('installed', false) && $c->getAppManager()->isInstalled('theming') && $c->getTrustedDomainHelper()->isTrustedDomain($c->getRequest()->getInsecureServerHost())) {
1114
-				return new ThemingDefaults(
1115
-					$c->getConfig(),
1116
-					$c->getL10N('theming'),
1117
-					$c->getURLGenerator(),
1118
-					$c->getMemCacheFactory(),
1119
-					new Util($c->getConfig(), $this->getAppManager(), $c->getAppDataDir('theming')),
1120
-					new ImageManager($c->getConfig(), $c->getAppDataDir('theming'), $c->getURLGenerator(), $this->getMemCacheFactory(), $this->getLogger()),
1121
-					$c->getAppManager(),
1122
-					$c->getNavigationManager()
1123
-				);
1124
-			}
1125
-			return new \OC_Defaults();
1126
-		});
1127
-		$this->registerService(SCSSCacher::class, function (Server $c) {
1128
-			return new SCSSCacher(
1129
-				$c->getLogger(),
1130
-				$c->query(\OC\Files\AppData\Factory::class),
1131
-				$c->getURLGenerator(),
1132
-				$c->getConfig(),
1133
-				$c->getThemingDefaults(),
1134
-				\OC::$SERVERROOT,
1135
-				$this->getMemCacheFactory(),
1136
-				$c->query(IconsCacher::class),
1137
-				new TimeFactory()
1138
-			);
1139
-		});
1140
-		$this->registerService(JSCombiner::class, function (Server $c) {
1141
-			return new JSCombiner(
1142
-				$c->getAppDataDir('js'),
1143
-				$c->getURLGenerator(),
1144
-				$this->getMemCacheFactory(),
1145
-				$c->getSystemConfig(),
1146
-				$c->getLogger()
1147
-			);
1148
-		});
1149
-		$this->registerAlias(\OCP\EventDispatcher\IEventDispatcher::class, \OC\EventDispatcher\EventDispatcher::class);
1150
-		$this->registerDeprecatedAlias('EventDispatcher', \OC\EventDispatcher\SymfonyAdapter::class);
1151
-		$this->registerAlias(EventDispatcherInterface::class, \OC\EventDispatcher\SymfonyAdapter::class);
1152
-
1153
-		$this->registerService('CryptoWrapper', function (Server $c) {
1154
-			// FIXME: Instantiiated here due to cyclic dependency
1155
-			$request = new Request(
1156
-				[
1157
-					'get' => $_GET,
1158
-					'post' => $_POST,
1159
-					'files' => $_FILES,
1160
-					'server' => $_SERVER,
1161
-					'env' => $_ENV,
1162
-					'cookies' => $_COOKIE,
1163
-					'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
1164
-						? $_SERVER['REQUEST_METHOD']
1165
-						: null,
1166
-				],
1167
-				$c->getSecureRandom(),
1168
-				$c->getConfig()
1169
-			);
1170
-
1171
-			return new CryptoWrapper(
1172
-				$c->getConfig(),
1173
-				$c->getCrypto(),
1174
-				$c->getSecureRandom(),
1175
-				$request
1176
-			);
1177
-		});
1178
-		$this->registerService(CsrfTokenManager::class, function (Server $c) {
1179
-			$tokenGenerator = new CsrfTokenGenerator($c->getSecureRandom());
1180
-
1181
-			return new CsrfTokenManager(
1182
-				$tokenGenerator,
1183
-				$c->query(SessionStorage::class)
1184
-			);
1185
-		});
1186
-		$this->registerDeprecatedAlias('CsrfTokenManager', CsrfTokenManager::class);
1187
-		$this->registerService(SessionStorage::class, function (Server $c) {
1188
-			return new SessionStorage($c->getSession());
1189
-		});
1190
-		$this->registerAlias(\OCP\Security\IContentSecurityPolicyManager::class, ContentSecurityPolicyManager::class);
1191
-		$this->registerDeprecatedAlias('ContentSecurityPolicyManager', ContentSecurityPolicyManager::class);
1192
-
1193
-		$this->registerService('ContentSecurityPolicyNonceManager', function (Server $c) {
1194
-			return new ContentSecurityPolicyNonceManager(
1195
-				$c->getCsrfTokenManager(),
1196
-				$c->getRequest()
1197
-			);
1198
-		});
1199
-
1200
-		$this->registerService(\OCP\Share\IManager::class, function (Server $c) {
1201
-			$config = $c->getConfig();
1202
-			$factoryClass = $config->getSystemValue('sharing.managerFactory', ProviderFactory::class);
1203
-			/** @var \OCP\Share\IProviderFactory $factory */
1204
-			$factory = new $factoryClass($this);
1205
-
1206
-			$manager = new \OC\Share20\Manager(
1207
-				$c->getLogger(),
1208
-				$c->getConfig(),
1209
-				$c->getSecureRandom(),
1210
-				$c->getHasher(),
1211
-				$c->getMountManager(),
1212
-				$c->getGroupManager(),
1213
-				$c->getL10N('lib'),
1214
-				$c->getL10NFactory(),
1215
-				$factory,
1216
-				$c->getUserManager(),
1217
-				$c->getLazyRootFolder(),
1218
-				$c->getEventDispatcher(),
1219
-				$c->getMailer(),
1220
-				$c->getURLGenerator(),
1221
-				$c->getThemingDefaults(),
1222
-				$c->query(IEventDispatcher::class)
1223
-			);
1224
-
1225
-			return $manager;
1226
-		});
1227
-		$this->registerDeprecatedAlias('ShareManager', \OCP\Share\IManager::class);
1228
-
1229
-		$this->registerService(\OCP\Collaboration\Collaborators\ISearch::class, function(Server $c) {
1230
-			$instance = new Collaboration\Collaborators\Search($c);
1231
-
1232
-			// register default plugins
1233
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_USER', 'class' => UserPlugin::class]);
1234
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_GROUP', 'class' => GroupPlugin::class]);
1235
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_EMAIL', 'class' => MailPlugin::class]);
1236
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_REMOTE', 'class' => RemotePlugin::class]);
1237
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_REMOTE_GROUP', 'class' => RemoteGroupPlugin::class]);
1238
-
1239
-			return $instance;
1240
-		});
1241
-		$this->registerDeprecatedAlias('CollaboratorSearch', \OCP\Collaboration\Collaborators\ISearch::class);
1242
-		$this->registerAlias(\OCP\Collaboration\Collaborators\ISearchResult::class, \OC\Collaboration\Collaborators\SearchResult::class);
1243
-
1244
-		$this->registerAlias(\OCP\Collaboration\AutoComplete\IManager::class, \OC\Collaboration\AutoComplete\Manager::class);
1245
-
1246
-		$this->registerAlias(\OCP\Collaboration\Resources\IProviderManager::class, \OC\Collaboration\Resources\ProviderManager::class);
1247
-		$this->registerAlias(\OCP\Collaboration\Resources\IManager::class, \OC\Collaboration\Resources\Manager::class);
1248
-
1249
-		$this->registerService('SettingsManager', function (Server $c) {
1250
-			$manager = new \OC\Settings\Manager(
1251
-				$c->getLogger(),
1252
-				$c->getL10NFactory(),
1253
-				$c->getURLGenerator(),
1254
-				$c
1255
-			);
1256
-			return $manager;
1257
-		});
1258
-		$this->registerService(\OC\Files\AppData\Factory::class, function (Server $c) {
1259
-			return new \OC\Files\AppData\Factory(
1260
-				$c->getRootFolder(),
1261
-				$c->getSystemConfig()
1262
-			);
1263
-		});
1264
-
1265
-		$this->registerService('LockdownManager', function (Server $c) {
1266
-			return new LockdownManager(function () use ($c) {
1267
-				return $c->getSession();
1268
-			});
1269
-		});
1270
-
1271
-		$this->registerService(\OCP\OCS\IDiscoveryService::class, function (Server $c) {
1272
-			return new DiscoveryService($c->getMemCacheFactory(), $c->getHTTPClientService());
1273
-		});
1274
-
1275
-		$this->registerService(ICloudIdManager::class, function (Server $c) {
1276
-			return new CloudIdManager();
1277
-		});
1278
-
1279
-		$this->registerService(IConfig::class, function (Server $c) {
1280
-			return new GlobalScale\Config($c->getConfig());
1281
-		});
1282
-
1283
-		$this->registerService(ICloudFederationProviderManager::class, function (Server $c) {
1284
-			return new CloudFederationProviderManager($c->getAppManager(), $c->getHTTPClientService(), $c->getCloudIdManager(), $c->getLogger());
1285
-		});
1286
-
1287
-		$this->registerService(ICloudFederationFactory::class, function (Server $c) {
1288
-			return new CloudFederationFactory();
1289
-		});
1290
-
1291
-		$this->registerAlias(\OCP\AppFramework\Utility\IControllerMethodReflector::class, \OC\AppFramework\Utility\ControllerMethodReflector::class);
1292
-		$this->registerDeprecatedAlias('ControllerMethodReflector', \OCP\AppFramework\Utility\IControllerMethodReflector::class);
1293
-
1294
-		$this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
1295
-		$this->registerDeprecatedAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
1296
-
1297
-		$this->registerService(Defaults::class, function (Server $c) {
1298
-			return new Defaults(
1299
-				$c->getThemingDefaults()
1300
-			);
1301
-		});
1302
-		$this->registerDeprecatedAlias('Defaults', \OCP\Defaults::class);
1303
-
1304
-		$this->registerService(\OCP\ISession::class, function (SimpleContainer $c) {
1305
-			return $c->query(\OCP\IUserSession::class)->getSession();
1306
-		});
1307
-
1308
-		$this->registerService(IShareHelper::class, function (Server $c) {
1309
-			return new ShareHelper(
1310
-				$c->query(\OCP\Share\IManager::class)
1311
-			);
1312
-		});
1313
-
1314
-		$this->registerService(Installer::class, function(Server $c) {
1315
-			return new Installer(
1316
-				$c->getAppFetcher(),
1317
-				$c->getHTTPClientService(),
1318
-				$c->getTempManager(),
1319
-				$c->getLogger(),
1320
-				$c->getConfig(),
1321
-				\OC::$CLI
1322
-			);
1323
-		});
1324
-
1325
-		$this->registerService(IApiFactory::class, function(Server $c) {
1326
-			return new ApiFactory($c->getHTTPClientService());
1327
-		});
1328
-
1329
-		$this->registerService(IInstanceFactory::class, function(Server $c) {
1330
-			$memcacheFactory = $c->getMemCacheFactory();
1331
-			return new InstanceFactory($memcacheFactory->createLocal('remoteinstance.'), $c->getHTTPClientService());
1332
-		});
1333
-
1334
-		$this->registerService(IContactsStore::class, function(Server $c) {
1335
-			return new ContactsStore(
1336
-				$c->getContactsManager(),
1337
-				$c->getConfig(),
1338
-				$c->getUserManager(),
1339
-				$c->getGroupManager()
1340
-			);
1341
-		});
1342
-		$this->registerAlias(IContactsStore::class, ContactsStore::class);
1343
-		$this->registerAlias(IAccountManager::class, AccountManager::class);
1344
-
1345
-		$this->registerService(IStorageFactory::class, function() {
1346
-			return new StorageFactory();
1347
-		});
1348
-
1349
-		$this->registerAlias(IDashboardManager::class, DashboardManager::class);
1350
-		$this->registerAlias(IFullTextSearchManager::class, FullTextSearchManager::class);
1351
-
1352
-		$this->registerAlias(ISubAdmin::class, SubAdmin::class);
1353
-
1354
-		$this->registerAlias(IInitialStateService::class, InitialStateService::class);
1355
-
1356
-		$this->connectDispatcher();
1357
-	}
1358
-
1359
-	/**
1360
-	 * @return \OCP\Calendar\IManager
1361
-	 */
1362
-	public function getCalendarManager() {
1363
-		return $this->query(\OC\Calendar\Manager::class);
1364
-	}
1365
-
1366
-	/**
1367
-	 * @return \OCP\Calendar\Resource\IManager
1368
-	 */
1369
-	public function getCalendarResourceBackendManager() {
1370
-		return $this->query(\OC\Calendar\Resource\Manager::class);
1371
-	}
1372
-
1373
-	/**
1374
-	 * @return \OCP\Calendar\Room\IManager
1375
-	 */
1376
-	public function getCalendarRoomBackendManager() {
1377
-		return $this->query(\OC\Calendar\Room\Manager::class);
1378
-	}
1379
-
1380
-	private function connectDispatcher() {
1381
-		$dispatcher = $this->getEventDispatcher();
1382
-
1383
-		// Delete avatar on user deletion
1384
-		$dispatcher->addListener('OCP\IUser::preDelete', function(GenericEvent $e) {
1385
-			$logger = $this->getLogger();
1386
-			$manager = $this->getAvatarManager();
1387
-			/** @var IUser $user */
1388
-			$user = $e->getSubject();
1389
-
1390
-			try {
1391
-				$avatar = $manager->getAvatar($user->getUID());
1392
-				$avatar->remove();
1393
-			} catch (NotFoundException $e) {
1394
-				// no avatar to remove
1395
-			} catch (\Exception $e) {
1396
-				// Ignore exceptions
1397
-				$logger->info('Could not cleanup avatar of ' . $user->getUID());
1398
-			}
1399
-		});
1400
-
1401
-		$dispatcher->addListener('OCP\IUser::changeUser', function (GenericEvent $e) {
1402
-			$manager = $this->getAvatarManager();
1403
-			/** @var IUser $user */
1404
-			$user = $e->getSubject();
1405
-			$feature = $e->getArgument('feature');
1406
-			$oldValue = $e->getArgument('oldValue');
1407
-			$value = $e->getArgument('value');
1408
-
1409
-			// We only change the avatar on display name changes
1410
-			if ($feature !== 'displayName') {
1411
-				return;
1412
-			}
1413
-
1414
-			try {
1415
-				$avatar = $manager->getAvatar($user->getUID());
1416
-				$avatar->userChanged($feature, $oldValue, $value);
1417
-			} catch (NotFoundException $e) {
1418
-				// no avatar to remove
1419
-			}
1420
-		});
1421
-
1422
-		/** @var IEventDispatcher $eventDispatched */
1423
-		$eventDispatched = $this->query(IEventDispatcher::class);
1424
-		$eventDispatched->addServiceListener(LoginFailed::class, LoginFailedListener::class);
1425
-	}
1426
-
1427
-	/**
1428
-	 * @return \OCP\Contacts\IManager
1429
-	 */
1430
-	public function getContactsManager() {
1431
-		return $this->query(\OCP\Contacts\IManager::class);
1432
-	}
1433
-
1434
-	/**
1435
-	 * @return \OC\Encryption\Manager
1436
-	 */
1437
-	public function getEncryptionManager() {
1438
-		return $this->query(\OCP\Encryption\IManager::class);
1439
-	}
1440
-
1441
-	/**
1442
-	 * @return \OC\Encryption\File
1443
-	 */
1444
-	public function getEncryptionFilesHelper() {
1445
-		return $this->query('EncryptionFileHelper');
1446
-	}
1447
-
1448
-	/**
1449
-	 * @return \OCP\Encryption\Keys\IStorage
1450
-	 */
1451
-	public function getEncryptionKeyStorage() {
1452
-		return $this->query('EncryptionKeyStorage');
1453
-	}
1454
-
1455
-	/**
1456
-	 * The current request object holding all information about the request
1457
-	 * currently being processed is returned from this method.
1458
-	 * In case the current execution was not initiated by a web request null is returned
1459
-	 *
1460
-	 * @return \OCP\IRequest
1461
-	 */
1462
-	public function getRequest() {
1463
-		return $this->query(IRequest::class);
1464
-	}
1465
-
1466
-	/**
1467
-	 * Returns the preview manager which can create preview images for a given file
1468
-	 *
1469
-	 * @return IPreview
1470
-	 */
1471
-	public function getPreviewManager() {
1472
-		return $this->query(IPreview::class);
1473
-	}
1474
-
1475
-	/**
1476
-	 * Returns the tag manager which can get and set tags for different object types
1477
-	 *
1478
-	 * @see \OCP\ITagManager::load()
1479
-	 * @return ITagManager
1480
-	 */
1481
-	public function getTagManager() {
1482
-		return $this->query(ITagManager::class);
1483
-	}
1484
-
1485
-	/**
1486
-	 * Returns the system-tag manager
1487
-	 *
1488
-	 * @return ISystemTagManager
1489
-	 *
1490
-	 * @since 9.0.0
1491
-	 */
1492
-	public function getSystemTagManager() {
1493
-		return $this->query(ISystemTagManager::class);
1494
-	}
1495
-
1496
-	/**
1497
-	 * Returns the system-tag object mapper
1498
-	 *
1499
-	 * @return ISystemTagObjectMapper
1500
-	 *
1501
-	 * @since 9.0.0
1502
-	 */
1503
-	public function getSystemTagObjectMapper() {
1504
-		return $this->query(ISystemTagObjectMapper::class);
1505
-	}
1506
-
1507
-	/**
1508
-	 * Returns the avatar manager, used for avatar functionality
1509
-	 *
1510
-	 * @return IAvatarManager
1511
-	 */
1512
-	public function getAvatarManager() {
1513
-		return $this->query(IAvatarManager::class);
1514
-	}
1515
-
1516
-	/**
1517
-	 * Returns the root folder of ownCloud's data directory
1518
-	 *
1519
-	 * @return IRootFolder
1520
-	 */
1521
-	public function getRootFolder() {
1522
-		return $this->query(IRootFolder::class);
1523
-	}
1524
-
1525
-	/**
1526
-	 * Returns the root folder of ownCloud's data directory
1527
-	 * This is the lazy variant so this gets only initialized once it
1528
-	 * is actually used.
1529
-	 *
1530
-	 * @return IRootFolder
1531
-	 */
1532
-	public function getLazyRootFolder() {
1533
-		return $this->query(IRootFolder::class);
1534
-	}
1535
-
1536
-	/**
1537
-	 * Returns a view to ownCloud's files folder
1538
-	 *
1539
-	 * @param string $userId user ID
1540
-	 * @return \OCP\Files\Folder|null
1541
-	 */
1542
-	public function getUserFolder($userId = null) {
1543
-		if ($userId === null) {
1544
-			$user = $this->getUserSession()->getUser();
1545
-			if (!$user) {
1546
-				return null;
1547
-			}
1548
-			$userId = $user->getUID();
1549
-		}
1550
-		$root = $this->getRootFolder();
1551
-		return $root->getUserFolder($userId);
1552
-	}
1553
-
1554
-	/**
1555
-	 * Returns an app-specific view in ownClouds data directory
1556
-	 *
1557
-	 * @return \OCP\Files\Folder
1558
-	 * @deprecated since 9.2.0 use IAppData
1559
-	 */
1560
-	public function getAppFolder() {
1561
-		$dir = '/' . \OC_App::getCurrentApp();
1562
-		$root = $this->getRootFolder();
1563
-		if (!$root->nodeExists($dir)) {
1564
-			$folder = $root->newFolder($dir);
1565
-		} else {
1566
-			$folder = $root->get($dir);
1567
-		}
1568
-		return $folder;
1569
-	}
1570
-
1571
-	/**
1572
-	 * @return \OC\User\Manager
1573
-	 */
1574
-	public function getUserManager() {
1575
-		return $this->query(IUserManager::class);
1576
-	}
1577
-
1578
-	/**
1579
-	 * @return \OC\Group\Manager
1580
-	 */
1581
-	public function getGroupManager() {
1582
-		return $this->query(IGroupManager::class);
1583
-	}
1584
-
1585
-	/**
1586
-	 * @return \OC\User\Session
1587
-	 */
1588
-	public function getUserSession() {
1589
-		return $this->query(IUserSession::class);
1590
-	}
1591
-
1592
-	/**
1593
-	 * @return \OCP\ISession
1594
-	 */
1595
-	public function getSession() {
1596
-		return $this->getUserSession()->getSession();
1597
-	}
1598
-
1599
-	/**
1600
-	 * @param \OCP\ISession $session
1601
-	 */
1602
-	public function setSession(\OCP\ISession $session) {
1603
-		$this->query(SessionStorage::class)->setSession($session);
1604
-		$this->getUserSession()->setSession($session);
1605
-		$this->query(Store::class)->setSession($session);
1606
-	}
1607
-
1608
-	/**
1609
-	 * @return \OC\Authentication\TwoFactorAuth\Manager
1610
-	 */
1611
-	public function getTwoFactorAuthManager() {
1612
-		return $this->query(\OC\Authentication\TwoFactorAuth\Manager::class);
1613
-	}
1614
-
1615
-	/**
1616
-	 * @return \OC\NavigationManager
1617
-	 */
1618
-	public function getNavigationManager() {
1619
-		return $this->query(INavigationManager::class);
1620
-	}
1621
-
1622
-	/**
1623
-	 * @return \OCP\IConfig
1624
-	 */
1625
-	public function getConfig() {
1626
-		return $this->query(AllConfig::class);
1627
-	}
1628
-
1629
-	/**
1630
-	 * @return \OC\SystemConfig
1631
-	 */
1632
-	public function getSystemConfig() {
1633
-		return $this->query(SystemConfig::class);
1634
-	}
1635
-
1636
-	/**
1637
-	 * Returns the app config manager
1638
-	 *
1639
-	 * @return IAppConfig
1640
-	 */
1641
-	public function getAppConfig() {
1642
-		return $this->query(IAppConfig::class);
1643
-	}
1644
-
1645
-	/**
1646
-	 * @return IFactory
1647
-	 */
1648
-	public function getL10NFactory() {
1649
-		return $this->query(IFactory::class);
1650
-	}
1651
-
1652
-	/**
1653
-	 * get an L10N instance
1654
-	 *
1655
-	 * @param string $app appid
1656
-	 * @param string $lang
1657
-	 * @return IL10N
1658
-	 */
1659
-	public function getL10N($app, $lang = null) {
1660
-		return $this->getL10NFactory()->get($app, $lang);
1661
-	}
1662
-
1663
-	/**
1664
-	 * @return IURLGenerator
1665
-	 */
1666
-	public function getURLGenerator() {
1667
-		return $this->query(IURLGenerator::class);
1668
-	}
1669
-
1670
-	/**
1671
-	 * @return AppFetcher
1672
-	 */
1673
-	public function getAppFetcher() {
1674
-		return $this->query(AppFetcher::class);
1675
-	}
1676
-
1677
-	/**
1678
-	 * Returns an ICache instance. Since 8.1.0 it returns a fake cache. Use
1679
-	 * getMemCacheFactory() instead.
1680
-	 *
1681
-	 * @return ICache
1682
-	 * @deprecated 8.1.0 use getMemCacheFactory to obtain a proper cache
1683
-	 */
1684
-	public function getCache() {
1685
-		return $this->query(ICache::class);
1686
-	}
1687
-
1688
-	/**
1689
-	 * Returns an \OCP\CacheFactory instance
1690
-	 *
1691
-	 * @return \OCP\ICacheFactory
1692
-	 */
1693
-	public function getMemCacheFactory() {
1694
-		return $this->query(Factory::class);
1695
-	}
1696
-
1697
-	/**
1698
-	 * Returns an \OC\RedisFactory instance
1699
-	 *
1700
-	 * @return \OC\RedisFactory
1701
-	 */
1702
-	public function getGetRedisFactory() {
1703
-		return $this->query('RedisFactory');
1704
-	}
1705
-
1706
-
1707
-	/**
1708
-	 * Returns the current session
1709
-	 *
1710
-	 * @return \OCP\IDBConnection
1711
-	 */
1712
-	public function getDatabaseConnection() {
1713
-		return $this->query(IDBConnection::class);
1714
-	}
1715
-
1716
-	/**
1717
-	 * Returns the activity manager
1718
-	 *
1719
-	 * @return \OCP\Activity\IManager
1720
-	 */
1721
-	public function getActivityManager() {
1722
-		return $this->query(\OCP\Activity\IManager::class);
1723
-	}
1724
-
1725
-	/**
1726
-	 * Returns an job list for controlling background jobs
1727
-	 *
1728
-	 * @return IJobList
1729
-	 */
1730
-	public function getJobList() {
1731
-		return $this->query(IJobList::class);
1732
-	}
1733
-
1734
-	/**
1735
-	 * Returns a logger instance
1736
-	 *
1737
-	 * @return ILogger
1738
-	 */
1739
-	public function getLogger() {
1740
-		return $this->query(ILogger::class);
1741
-	}
1742
-
1743
-	/**
1744
-	 * @return ILogFactory
1745
-	 * @throws \OCP\AppFramework\QueryException
1746
-	 */
1747
-	public function getLogFactory() {
1748
-		return $this->query(ILogFactory::class);
1749
-	}
1750
-
1751
-	/**
1752
-	 * Returns a router for generating and matching urls
1753
-	 *
1754
-	 * @return IRouter
1755
-	 */
1756
-	public function getRouter() {
1757
-		return $this->query(IRouter::class);
1758
-	}
1759
-
1760
-	/**
1761
-	 * Returns a search instance
1762
-	 *
1763
-	 * @return ISearch
1764
-	 */
1765
-	public function getSearch() {
1766
-		return $this->query(ISearch::class);
1767
-	}
1768
-
1769
-	/**
1770
-	 * Returns a SecureRandom instance
1771
-	 *
1772
-	 * @return \OCP\Security\ISecureRandom
1773
-	 */
1774
-	public function getSecureRandom() {
1775
-		return $this->query(ISecureRandom::class);
1776
-	}
1777
-
1778
-	/**
1779
-	 * Returns a Crypto instance
1780
-	 *
1781
-	 * @return ICrypto
1782
-	 */
1783
-	public function getCrypto() {
1784
-		return $this->query(ICrypto::class);
1785
-	}
1786
-
1787
-	/**
1788
-	 * Returns a Hasher instance
1789
-	 *
1790
-	 * @return IHasher
1791
-	 */
1792
-	public function getHasher() {
1793
-		return $this->query(IHasher::class);
1794
-	}
1795
-
1796
-	/**
1797
-	 * Returns a CredentialsManager instance
1798
-	 *
1799
-	 * @return ICredentialsManager
1800
-	 */
1801
-	public function getCredentialsManager() {
1802
-		return $this->query(ICredentialsManager::class);
1803
-	}
1804
-
1805
-	/**
1806
-	 * Get the certificate manager for the user
1807
-	 *
1808
-	 * @param string $userId (optional) if not specified the current loggedin user is used, use null to get the system certificate manager
1809
-	 * @return \OCP\ICertificateManager | null if $uid is null and no user is logged in
1810
-	 */
1811
-	public function getCertificateManager($userId = '') {
1812
-		if ($userId === '') {
1813
-			$userSession = $this->getUserSession();
1814
-			$user = $userSession->getUser();
1815
-			if (is_null($user)) {
1816
-				return null;
1817
-			}
1818
-			$userId = $user->getUID();
1819
-		}
1820
-		return new CertificateManager(
1821
-			$userId,
1822
-			new View(),
1823
-			$this->getConfig(),
1824
-			$this->getLogger(),
1825
-			$this->getSecureRandom()
1826
-		);
1827
-	}
1828
-
1829
-	/**
1830
-	 * Returns an instance of the HTTP client service
1831
-	 *
1832
-	 * @return IClientService
1833
-	 */
1834
-	public function getHTTPClientService() {
1835
-		return $this->query(IClientService::class);
1836
-	}
1837
-
1838
-	/**
1839
-	 * Create a new event source
1840
-	 *
1841
-	 * @return \OCP\IEventSource
1842
-	 */
1843
-	public function createEventSource() {
1844
-		return new \OC_EventSource();
1845
-	}
1846
-
1847
-	/**
1848
-	 * Get the active event logger
1849
-	 *
1850
-	 * The returned logger only logs data when debug mode is enabled
1851
-	 *
1852
-	 * @return IEventLogger
1853
-	 */
1854
-	public function getEventLogger() {
1855
-		return $this->query(IEventLogger::class);
1856
-	}
1857
-
1858
-	/**
1859
-	 * Get the active query logger
1860
-	 *
1861
-	 * The returned logger only logs data when debug mode is enabled
1862
-	 *
1863
-	 * @return IQueryLogger
1864
-	 */
1865
-	public function getQueryLogger() {
1866
-		return $this->query(IQueryLogger::class);
1867
-	}
1868
-
1869
-	/**
1870
-	 * Get the manager for temporary files and folders
1871
-	 *
1872
-	 * @return \OCP\ITempManager
1873
-	 */
1874
-	public function getTempManager() {
1875
-		return $this->query(ITempManager::class);
1876
-	}
1877
-
1878
-	/**
1879
-	 * Get the app manager
1880
-	 *
1881
-	 * @return \OCP\App\IAppManager
1882
-	 */
1883
-	public function getAppManager() {
1884
-		return $this->query(IAppManager::class);
1885
-	}
1886
-
1887
-	/**
1888
-	 * Creates a new mailer
1889
-	 *
1890
-	 * @return IMailer
1891
-	 */
1892
-	public function getMailer() {
1893
-		return $this->query(IMailer::class);
1894
-	}
1895
-
1896
-	/**
1897
-	 * Get the webroot
1898
-	 *
1899
-	 * @return string
1900
-	 */
1901
-	public function getWebRoot() {
1902
-		return $this->webRoot;
1903
-	}
1904
-
1905
-	/**
1906
-	 * @return \OC\OCSClient
1907
-	 */
1908
-	public function getOcsClient() {
1909
-		return $this->query('OcsClient');
1910
-	}
1911
-
1912
-	/**
1913
-	 * @return IDateTimeZone
1914
-	 */
1915
-	public function getDateTimeZone() {
1916
-		return $this->query(IDateTimeZone::class);
1917
-	}
1918
-
1919
-	/**
1920
-	 * @return IDateTimeFormatter
1921
-	 */
1922
-	public function getDateTimeFormatter() {
1923
-		return $this->query(IDateTimeFormatter::class);
1924
-	}
1925
-
1926
-	/**
1927
-	 * @return IMountProviderCollection
1928
-	 */
1929
-	public function getMountProviderCollection() {
1930
-		return $this->query(IMountProviderCollection::class);
1931
-	}
1932
-
1933
-	/**
1934
-	 * Get the IniWrapper
1935
-	 *
1936
-	 * @return IniGetWrapper
1937
-	 */
1938
-	public function getIniWrapper() {
1939
-		return $this->query('IniWrapper');
1940
-	}
1941
-
1942
-	/**
1943
-	 * @return \OCP\Command\IBus
1944
-	 */
1945
-	public function getCommandBus() {
1946
-		return $this->query('AsyncCommandBus');
1947
-	}
1948
-
1949
-	/**
1950
-	 * Get the trusted domain helper
1951
-	 *
1952
-	 * @return TrustedDomainHelper
1953
-	 */
1954
-	public function getTrustedDomainHelper() {
1955
-		return $this->query('TrustedDomainHelper');
1956
-	}
1957
-
1958
-	/**
1959
-	 * Get the locking provider
1960
-	 *
1961
-	 * @return ILockingProvider
1962
-	 * @since 8.1.0
1963
-	 */
1964
-	public function getLockingProvider() {
1965
-		return $this->query(ILockingProvider::class);
1966
-	}
1967
-
1968
-	/**
1969
-	 * @return IMountManager
1970
-	 **/
1971
-	function getMountManager() {
1972
-		return $this->query(IMountManager::class);
1973
-	}
1974
-
1975
-	/**
1976
-	 * @return IUserMountCache
1977
-	 */
1978
-	function getUserMountCache() {
1979
-		return $this->query(IUserMountCache::class);
1980
-	}
1981
-
1982
-	/**
1983
-	 * Get the MimeTypeDetector
1984
-	 *
1985
-	 * @return IMimeTypeDetector
1986
-	 */
1987
-	public function getMimeTypeDetector() {
1988
-		return $this->query(IMimeTypeDetector::class);
1989
-	}
1990
-
1991
-	/**
1992
-	 * Get the MimeTypeLoader
1993
-	 *
1994
-	 * @return IMimeTypeLoader
1995
-	 */
1996
-	public function getMimeTypeLoader() {
1997
-		return $this->query(IMimeTypeLoader::class);
1998
-	}
1999
-
2000
-	/**
2001
-	 * Get the manager of all the capabilities
2002
-	 *
2003
-	 * @return CapabilitiesManager
2004
-	 */
2005
-	public function getCapabilitiesManager() {
2006
-		return $this->query(CapabilitiesManager::class);
2007
-	}
2008
-
2009
-	/**
2010
-	 * Get the EventDispatcher
2011
-	 *
2012
-	 * @return EventDispatcherInterface
2013
-	 * @since 8.2.0
2014
-	 * @deprecated 18.0.0 use \OCP\EventDispatcher\IEventDispatcher
2015
-	 */
2016
-	public function getEventDispatcher() {
2017
-		return $this->query(\OC\EventDispatcher\SymfonyAdapter::class);
2018
-	}
2019
-
2020
-	/**
2021
-	 * Get the Notification Manager
2022
-	 *
2023
-	 * @return \OCP\Notification\IManager
2024
-	 * @since 8.2.0
2025
-	 */
2026
-	public function getNotificationManager() {
2027
-		return $this->query(\OCP\Notification\IManager::class);
2028
-	}
2029
-
2030
-	/**
2031
-	 * @return ICommentsManager
2032
-	 */
2033
-	public function getCommentsManager() {
2034
-		return $this->query(ICommentsManager::class);
2035
-	}
2036
-
2037
-	/**
2038
-	 * @return \OCA\Theming\ThemingDefaults
2039
-	 */
2040
-	public function getThemingDefaults() {
2041
-		return $this->query('ThemingDefaults');
2042
-	}
2043
-
2044
-	/**
2045
-	 * @return \OC\IntegrityCheck\Checker
2046
-	 */
2047
-	public function getIntegrityCodeChecker() {
2048
-		return $this->query('IntegrityCodeChecker');
2049
-	}
2050
-
2051
-	/**
2052
-	 * @return \OC\Session\CryptoWrapper
2053
-	 */
2054
-	public function getSessionCryptoWrapper() {
2055
-		return $this->query('CryptoWrapper');
2056
-	}
2057
-
2058
-	/**
2059
-	 * @return CsrfTokenManager
2060
-	 */
2061
-	public function getCsrfTokenManager() {
2062
-		return $this->query(CsrfTokenManager::class);
2063
-	}
2064
-
2065
-	/**
2066
-	 * @return Throttler
2067
-	 */
2068
-	public function getBruteForceThrottler() {
2069
-		return $this->query(Throttler::class);
2070
-	}
2071
-
2072
-	/**
2073
-	 * @return IContentSecurityPolicyManager
2074
-	 */
2075
-	public function getContentSecurityPolicyManager() {
2076
-		return $this->query(ContentSecurityPolicyManager::class);
2077
-	}
2078
-
2079
-	/**
2080
-	 * @return ContentSecurityPolicyNonceManager
2081
-	 */
2082
-	public function getContentSecurityPolicyNonceManager() {
2083
-		return $this->query('ContentSecurityPolicyNonceManager');
2084
-	}
2085
-
2086
-	/**
2087
-	 * Not a public API as of 8.2, wait for 9.0
2088
-	 *
2089
-	 * @return \OCA\Files_External\Service\BackendService
2090
-	 */
2091
-	public function getStoragesBackendService() {
2092
-		return $this->query(BackendService::class);
2093
-	}
2094
-
2095
-	/**
2096
-	 * Not a public API as of 8.2, wait for 9.0
2097
-	 *
2098
-	 * @return \OCA\Files_External\Service\GlobalStoragesService
2099
-	 */
2100
-	public function getGlobalStoragesService() {
2101
-		return $this->query(GlobalStoragesService::class);
2102
-	}
2103
-
2104
-	/**
2105
-	 * Not a public API as of 8.2, wait for 9.0
2106
-	 *
2107
-	 * @return \OCA\Files_External\Service\UserGlobalStoragesService
2108
-	 */
2109
-	public function getUserGlobalStoragesService() {
2110
-		return $this->query(UserGlobalStoragesService::class);
2111
-	}
2112
-
2113
-	/**
2114
-	 * Not a public API as of 8.2, wait for 9.0
2115
-	 *
2116
-	 * @return \OCA\Files_External\Service\UserStoragesService
2117
-	 */
2118
-	public function getUserStoragesService() {
2119
-		return $this->query(UserStoragesService::class);
2120
-	}
2121
-
2122
-	/**
2123
-	 * @return \OCP\Share\IManager
2124
-	 */
2125
-	public function getShareManager() {
2126
-		return $this->query(\OCP\Share\IManager::class);
2127
-	}
2128
-
2129
-	/**
2130
-	 * @return \OCP\Collaboration\Collaborators\ISearch
2131
-	 */
2132
-	public function getCollaboratorSearch() {
2133
-		return $this->query(\OCP\Collaboration\Collaborators\ISearch::class);
2134
-	}
2135
-
2136
-	/**
2137
-	 * @return \OCP\Collaboration\AutoComplete\IManager
2138
-	 */
2139
-	public function getAutoCompleteManager(){
2140
-		return $this->query(IManager::class);
2141
-	}
2142
-
2143
-	/**
2144
-	 * Returns the LDAP Provider
2145
-	 *
2146
-	 * @return \OCP\LDAP\ILDAPProvider
2147
-	 */
2148
-	public function getLDAPProvider() {
2149
-		return $this->query('LDAPProvider');
2150
-	}
2151
-
2152
-	/**
2153
-	 * @return \OCP\Settings\IManager
2154
-	 */
2155
-	public function getSettingsManager() {
2156
-		return $this->query('SettingsManager');
2157
-	}
2158
-
2159
-	/**
2160
-	 * @return \OCP\Files\IAppData
2161
-	 */
2162
-	public function getAppDataDir($app) {
2163
-		/** @var \OC\Files\AppData\Factory $factory */
2164
-		$factory = $this->query(\OC\Files\AppData\Factory::class);
2165
-		return $factory->get($app);
2166
-	}
2167
-
2168
-	/**
2169
-	 * @return \OCP\Lockdown\ILockdownManager
2170
-	 */
2171
-	public function getLockdownManager() {
2172
-		return $this->query('LockdownManager');
2173
-	}
2174
-
2175
-	/**
2176
-	 * @return \OCP\Federation\ICloudIdManager
2177
-	 */
2178
-	public function getCloudIdManager() {
2179
-		return $this->query(ICloudIdManager::class);
2180
-	}
2181
-
2182
-	/**
2183
-	 * @return \OCP\GlobalScale\IConfig
2184
-	 */
2185
-	public function getGlobalScaleConfig() {
2186
-		return $this->query(IConfig::class);
2187
-	}
2188
-
2189
-	/**
2190
-	 * @return \OCP\Federation\ICloudFederationProviderManager
2191
-	 */
2192
-	public function getCloudFederationProviderManager() {
2193
-		return $this->query(ICloudFederationProviderManager::class);
2194
-	}
2195
-
2196
-	/**
2197
-	 * @return \OCP\Remote\Api\IApiFactory
2198
-	 */
2199
-	public function getRemoteApiFactory() {
2200
-		return $this->query(IApiFactory::class);
2201
-	}
2202
-
2203
-	/**
2204
-	 * @return \OCP\Federation\ICloudFederationFactory
2205
-	 */
2206
-	public function getCloudFederationFactory() {
2207
-		return $this->query(ICloudFederationFactory::class);
2208
-	}
2209
-
2210
-	/**
2211
-	 * @return \OCP\Remote\IInstanceFactory
2212
-	 */
2213
-	public function getRemoteInstanceFactory() {
2214
-		return $this->query(IInstanceFactory::class);
2215
-	}
2216
-
2217
-	/**
2218
-	 * @return IStorageFactory
2219
-	 */
2220
-	public function getStorageFactory() {
2221
-		return $this->query(IStorageFactory::class);
2222
-	}
2223
-
2224
-	/**
2225
-	 * Get the Preview GeneratorHelper
2226
-	 *
2227
-	 * @return GeneratorHelper
2228
-	 * @since 17.0.0
2229
-	 */
2230
-	public function getGeneratorHelper() {
2231
-		return $this->query(\OC\Preview\GeneratorHelper::class);
2232
-	}
2233
-
2234
-	private function registerDeprecatedAlias(string $alias, string $target) {
2235
-		$this->registerService($alias, function (IContainer $container) use ($target, $alias) {
2236
-			try {
2237
-				/** @var ILogger $logger */
2238
-				$logger = $container->query(ILogger::class);
2239
-				$logger->debug('The requested alias "' . $alias . '" is depreacted. Please request "' . $target . '" directly. This alias will be removed in a future Nextcloud version.', ['app' => 'serverDI']);
2240
-			} catch (QueryException $e) {
2241
-				// Could not get logger. Continue
2242
-			}
2243
-
2244
-			return $container->query($target);
2245
-		}, false);
2246
-	}
1106
+            $prefixes = \OC::$composerAutoloader->getPrefixesPsr4();
1107
+            if (isset($prefixes['OCA\\Theming\\'])) {
1108
+                $classExists = true;
1109
+            } else {
1110
+                $classExists = false;
1111
+            }
1112
+
1113
+            if ($classExists && $c->getConfig()->getSystemValue('installed', false) && $c->getAppManager()->isInstalled('theming') && $c->getTrustedDomainHelper()->isTrustedDomain($c->getRequest()->getInsecureServerHost())) {
1114
+                return new ThemingDefaults(
1115
+                    $c->getConfig(),
1116
+                    $c->getL10N('theming'),
1117
+                    $c->getURLGenerator(),
1118
+                    $c->getMemCacheFactory(),
1119
+                    new Util($c->getConfig(), $this->getAppManager(), $c->getAppDataDir('theming')),
1120
+                    new ImageManager($c->getConfig(), $c->getAppDataDir('theming'), $c->getURLGenerator(), $this->getMemCacheFactory(), $this->getLogger()),
1121
+                    $c->getAppManager(),
1122
+                    $c->getNavigationManager()
1123
+                );
1124
+            }
1125
+            return new \OC_Defaults();
1126
+        });
1127
+        $this->registerService(SCSSCacher::class, function (Server $c) {
1128
+            return new SCSSCacher(
1129
+                $c->getLogger(),
1130
+                $c->query(\OC\Files\AppData\Factory::class),
1131
+                $c->getURLGenerator(),
1132
+                $c->getConfig(),
1133
+                $c->getThemingDefaults(),
1134
+                \OC::$SERVERROOT,
1135
+                $this->getMemCacheFactory(),
1136
+                $c->query(IconsCacher::class),
1137
+                new TimeFactory()
1138
+            );
1139
+        });
1140
+        $this->registerService(JSCombiner::class, function (Server $c) {
1141
+            return new JSCombiner(
1142
+                $c->getAppDataDir('js'),
1143
+                $c->getURLGenerator(),
1144
+                $this->getMemCacheFactory(),
1145
+                $c->getSystemConfig(),
1146
+                $c->getLogger()
1147
+            );
1148
+        });
1149
+        $this->registerAlias(\OCP\EventDispatcher\IEventDispatcher::class, \OC\EventDispatcher\EventDispatcher::class);
1150
+        $this->registerDeprecatedAlias('EventDispatcher', \OC\EventDispatcher\SymfonyAdapter::class);
1151
+        $this->registerAlias(EventDispatcherInterface::class, \OC\EventDispatcher\SymfonyAdapter::class);
1152
+
1153
+        $this->registerService('CryptoWrapper', function (Server $c) {
1154
+            // FIXME: Instantiiated here due to cyclic dependency
1155
+            $request = new Request(
1156
+                [
1157
+                    'get' => $_GET,
1158
+                    'post' => $_POST,
1159
+                    'files' => $_FILES,
1160
+                    'server' => $_SERVER,
1161
+                    'env' => $_ENV,
1162
+                    'cookies' => $_COOKIE,
1163
+                    'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
1164
+                        ? $_SERVER['REQUEST_METHOD']
1165
+                        : null,
1166
+                ],
1167
+                $c->getSecureRandom(),
1168
+                $c->getConfig()
1169
+            );
1170
+
1171
+            return new CryptoWrapper(
1172
+                $c->getConfig(),
1173
+                $c->getCrypto(),
1174
+                $c->getSecureRandom(),
1175
+                $request
1176
+            );
1177
+        });
1178
+        $this->registerService(CsrfTokenManager::class, function (Server $c) {
1179
+            $tokenGenerator = new CsrfTokenGenerator($c->getSecureRandom());
1180
+
1181
+            return new CsrfTokenManager(
1182
+                $tokenGenerator,
1183
+                $c->query(SessionStorage::class)
1184
+            );
1185
+        });
1186
+        $this->registerDeprecatedAlias('CsrfTokenManager', CsrfTokenManager::class);
1187
+        $this->registerService(SessionStorage::class, function (Server $c) {
1188
+            return new SessionStorage($c->getSession());
1189
+        });
1190
+        $this->registerAlias(\OCP\Security\IContentSecurityPolicyManager::class, ContentSecurityPolicyManager::class);
1191
+        $this->registerDeprecatedAlias('ContentSecurityPolicyManager', ContentSecurityPolicyManager::class);
1192
+
1193
+        $this->registerService('ContentSecurityPolicyNonceManager', function (Server $c) {
1194
+            return new ContentSecurityPolicyNonceManager(
1195
+                $c->getCsrfTokenManager(),
1196
+                $c->getRequest()
1197
+            );
1198
+        });
1199
+
1200
+        $this->registerService(\OCP\Share\IManager::class, function (Server $c) {
1201
+            $config = $c->getConfig();
1202
+            $factoryClass = $config->getSystemValue('sharing.managerFactory', ProviderFactory::class);
1203
+            /** @var \OCP\Share\IProviderFactory $factory */
1204
+            $factory = new $factoryClass($this);
1205
+
1206
+            $manager = new \OC\Share20\Manager(
1207
+                $c->getLogger(),
1208
+                $c->getConfig(),
1209
+                $c->getSecureRandom(),
1210
+                $c->getHasher(),
1211
+                $c->getMountManager(),
1212
+                $c->getGroupManager(),
1213
+                $c->getL10N('lib'),
1214
+                $c->getL10NFactory(),
1215
+                $factory,
1216
+                $c->getUserManager(),
1217
+                $c->getLazyRootFolder(),
1218
+                $c->getEventDispatcher(),
1219
+                $c->getMailer(),
1220
+                $c->getURLGenerator(),
1221
+                $c->getThemingDefaults(),
1222
+                $c->query(IEventDispatcher::class)
1223
+            );
1224
+
1225
+            return $manager;
1226
+        });
1227
+        $this->registerDeprecatedAlias('ShareManager', \OCP\Share\IManager::class);
1228
+
1229
+        $this->registerService(\OCP\Collaboration\Collaborators\ISearch::class, function(Server $c) {
1230
+            $instance = new Collaboration\Collaborators\Search($c);
1231
+
1232
+            // register default plugins
1233
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_USER', 'class' => UserPlugin::class]);
1234
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_GROUP', 'class' => GroupPlugin::class]);
1235
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_EMAIL', 'class' => MailPlugin::class]);
1236
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_REMOTE', 'class' => RemotePlugin::class]);
1237
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_REMOTE_GROUP', 'class' => RemoteGroupPlugin::class]);
1238
+
1239
+            return $instance;
1240
+        });
1241
+        $this->registerDeprecatedAlias('CollaboratorSearch', \OCP\Collaboration\Collaborators\ISearch::class);
1242
+        $this->registerAlias(\OCP\Collaboration\Collaborators\ISearchResult::class, \OC\Collaboration\Collaborators\SearchResult::class);
1243
+
1244
+        $this->registerAlias(\OCP\Collaboration\AutoComplete\IManager::class, \OC\Collaboration\AutoComplete\Manager::class);
1245
+
1246
+        $this->registerAlias(\OCP\Collaboration\Resources\IProviderManager::class, \OC\Collaboration\Resources\ProviderManager::class);
1247
+        $this->registerAlias(\OCP\Collaboration\Resources\IManager::class, \OC\Collaboration\Resources\Manager::class);
1248
+
1249
+        $this->registerService('SettingsManager', function (Server $c) {
1250
+            $manager = new \OC\Settings\Manager(
1251
+                $c->getLogger(),
1252
+                $c->getL10NFactory(),
1253
+                $c->getURLGenerator(),
1254
+                $c
1255
+            );
1256
+            return $manager;
1257
+        });
1258
+        $this->registerService(\OC\Files\AppData\Factory::class, function (Server $c) {
1259
+            return new \OC\Files\AppData\Factory(
1260
+                $c->getRootFolder(),
1261
+                $c->getSystemConfig()
1262
+            );
1263
+        });
1264
+
1265
+        $this->registerService('LockdownManager', function (Server $c) {
1266
+            return new LockdownManager(function () use ($c) {
1267
+                return $c->getSession();
1268
+            });
1269
+        });
1270
+
1271
+        $this->registerService(\OCP\OCS\IDiscoveryService::class, function (Server $c) {
1272
+            return new DiscoveryService($c->getMemCacheFactory(), $c->getHTTPClientService());
1273
+        });
1274
+
1275
+        $this->registerService(ICloudIdManager::class, function (Server $c) {
1276
+            return new CloudIdManager();
1277
+        });
1278
+
1279
+        $this->registerService(IConfig::class, function (Server $c) {
1280
+            return new GlobalScale\Config($c->getConfig());
1281
+        });
1282
+
1283
+        $this->registerService(ICloudFederationProviderManager::class, function (Server $c) {
1284
+            return new CloudFederationProviderManager($c->getAppManager(), $c->getHTTPClientService(), $c->getCloudIdManager(), $c->getLogger());
1285
+        });
1286
+
1287
+        $this->registerService(ICloudFederationFactory::class, function (Server $c) {
1288
+            return new CloudFederationFactory();
1289
+        });
1290
+
1291
+        $this->registerAlias(\OCP\AppFramework\Utility\IControllerMethodReflector::class, \OC\AppFramework\Utility\ControllerMethodReflector::class);
1292
+        $this->registerDeprecatedAlias('ControllerMethodReflector', \OCP\AppFramework\Utility\IControllerMethodReflector::class);
1293
+
1294
+        $this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
1295
+        $this->registerDeprecatedAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
1296
+
1297
+        $this->registerService(Defaults::class, function (Server $c) {
1298
+            return new Defaults(
1299
+                $c->getThemingDefaults()
1300
+            );
1301
+        });
1302
+        $this->registerDeprecatedAlias('Defaults', \OCP\Defaults::class);
1303
+
1304
+        $this->registerService(\OCP\ISession::class, function (SimpleContainer $c) {
1305
+            return $c->query(\OCP\IUserSession::class)->getSession();
1306
+        });
1307
+
1308
+        $this->registerService(IShareHelper::class, function (Server $c) {
1309
+            return new ShareHelper(
1310
+                $c->query(\OCP\Share\IManager::class)
1311
+            );
1312
+        });
1313
+
1314
+        $this->registerService(Installer::class, function(Server $c) {
1315
+            return new Installer(
1316
+                $c->getAppFetcher(),
1317
+                $c->getHTTPClientService(),
1318
+                $c->getTempManager(),
1319
+                $c->getLogger(),
1320
+                $c->getConfig(),
1321
+                \OC::$CLI
1322
+            );
1323
+        });
1324
+
1325
+        $this->registerService(IApiFactory::class, function(Server $c) {
1326
+            return new ApiFactory($c->getHTTPClientService());
1327
+        });
1328
+
1329
+        $this->registerService(IInstanceFactory::class, function(Server $c) {
1330
+            $memcacheFactory = $c->getMemCacheFactory();
1331
+            return new InstanceFactory($memcacheFactory->createLocal('remoteinstance.'), $c->getHTTPClientService());
1332
+        });
1333
+
1334
+        $this->registerService(IContactsStore::class, function(Server $c) {
1335
+            return new ContactsStore(
1336
+                $c->getContactsManager(),
1337
+                $c->getConfig(),
1338
+                $c->getUserManager(),
1339
+                $c->getGroupManager()
1340
+            );
1341
+        });
1342
+        $this->registerAlias(IContactsStore::class, ContactsStore::class);
1343
+        $this->registerAlias(IAccountManager::class, AccountManager::class);
1344
+
1345
+        $this->registerService(IStorageFactory::class, function() {
1346
+            return new StorageFactory();
1347
+        });
1348
+
1349
+        $this->registerAlias(IDashboardManager::class, DashboardManager::class);
1350
+        $this->registerAlias(IFullTextSearchManager::class, FullTextSearchManager::class);
1351
+
1352
+        $this->registerAlias(ISubAdmin::class, SubAdmin::class);
1353
+
1354
+        $this->registerAlias(IInitialStateService::class, InitialStateService::class);
1355
+
1356
+        $this->connectDispatcher();
1357
+    }
1358
+
1359
+    /**
1360
+     * @return \OCP\Calendar\IManager
1361
+     */
1362
+    public function getCalendarManager() {
1363
+        return $this->query(\OC\Calendar\Manager::class);
1364
+    }
1365
+
1366
+    /**
1367
+     * @return \OCP\Calendar\Resource\IManager
1368
+     */
1369
+    public function getCalendarResourceBackendManager() {
1370
+        return $this->query(\OC\Calendar\Resource\Manager::class);
1371
+    }
1372
+
1373
+    /**
1374
+     * @return \OCP\Calendar\Room\IManager
1375
+     */
1376
+    public function getCalendarRoomBackendManager() {
1377
+        return $this->query(\OC\Calendar\Room\Manager::class);
1378
+    }
1379
+
1380
+    private function connectDispatcher() {
1381
+        $dispatcher = $this->getEventDispatcher();
1382
+
1383
+        // Delete avatar on user deletion
1384
+        $dispatcher->addListener('OCP\IUser::preDelete', function(GenericEvent $e) {
1385
+            $logger = $this->getLogger();
1386
+            $manager = $this->getAvatarManager();
1387
+            /** @var IUser $user */
1388
+            $user = $e->getSubject();
1389
+
1390
+            try {
1391
+                $avatar = $manager->getAvatar($user->getUID());
1392
+                $avatar->remove();
1393
+            } catch (NotFoundException $e) {
1394
+                // no avatar to remove
1395
+            } catch (\Exception $e) {
1396
+                // Ignore exceptions
1397
+                $logger->info('Could not cleanup avatar of ' . $user->getUID());
1398
+            }
1399
+        });
1400
+
1401
+        $dispatcher->addListener('OCP\IUser::changeUser', function (GenericEvent $e) {
1402
+            $manager = $this->getAvatarManager();
1403
+            /** @var IUser $user */
1404
+            $user = $e->getSubject();
1405
+            $feature = $e->getArgument('feature');
1406
+            $oldValue = $e->getArgument('oldValue');
1407
+            $value = $e->getArgument('value');
1408
+
1409
+            // We only change the avatar on display name changes
1410
+            if ($feature !== 'displayName') {
1411
+                return;
1412
+            }
1413
+
1414
+            try {
1415
+                $avatar = $manager->getAvatar($user->getUID());
1416
+                $avatar->userChanged($feature, $oldValue, $value);
1417
+            } catch (NotFoundException $e) {
1418
+                // no avatar to remove
1419
+            }
1420
+        });
1421
+
1422
+        /** @var IEventDispatcher $eventDispatched */
1423
+        $eventDispatched = $this->query(IEventDispatcher::class);
1424
+        $eventDispatched->addServiceListener(LoginFailed::class, LoginFailedListener::class);
1425
+    }
1426
+
1427
+    /**
1428
+     * @return \OCP\Contacts\IManager
1429
+     */
1430
+    public function getContactsManager() {
1431
+        return $this->query(\OCP\Contacts\IManager::class);
1432
+    }
1433
+
1434
+    /**
1435
+     * @return \OC\Encryption\Manager
1436
+     */
1437
+    public function getEncryptionManager() {
1438
+        return $this->query(\OCP\Encryption\IManager::class);
1439
+    }
1440
+
1441
+    /**
1442
+     * @return \OC\Encryption\File
1443
+     */
1444
+    public function getEncryptionFilesHelper() {
1445
+        return $this->query('EncryptionFileHelper');
1446
+    }
1447
+
1448
+    /**
1449
+     * @return \OCP\Encryption\Keys\IStorage
1450
+     */
1451
+    public function getEncryptionKeyStorage() {
1452
+        return $this->query('EncryptionKeyStorage');
1453
+    }
1454
+
1455
+    /**
1456
+     * The current request object holding all information about the request
1457
+     * currently being processed is returned from this method.
1458
+     * In case the current execution was not initiated by a web request null is returned
1459
+     *
1460
+     * @return \OCP\IRequest
1461
+     */
1462
+    public function getRequest() {
1463
+        return $this->query(IRequest::class);
1464
+    }
1465
+
1466
+    /**
1467
+     * Returns the preview manager which can create preview images for a given file
1468
+     *
1469
+     * @return IPreview
1470
+     */
1471
+    public function getPreviewManager() {
1472
+        return $this->query(IPreview::class);
1473
+    }
1474
+
1475
+    /**
1476
+     * Returns the tag manager which can get and set tags for different object types
1477
+     *
1478
+     * @see \OCP\ITagManager::load()
1479
+     * @return ITagManager
1480
+     */
1481
+    public function getTagManager() {
1482
+        return $this->query(ITagManager::class);
1483
+    }
1484
+
1485
+    /**
1486
+     * Returns the system-tag manager
1487
+     *
1488
+     * @return ISystemTagManager
1489
+     *
1490
+     * @since 9.0.0
1491
+     */
1492
+    public function getSystemTagManager() {
1493
+        return $this->query(ISystemTagManager::class);
1494
+    }
1495
+
1496
+    /**
1497
+     * Returns the system-tag object mapper
1498
+     *
1499
+     * @return ISystemTagObjectMapper
1500
+     *
1501
+     * @since 9.0.0
1502
+     */
1503
+    public function getSystemTagObjectMapper() {
1504
+        return $this->query(ISystemTagObjectMapper::class);
1505
+    }
1506
+
1507
+    /**
1508
+     * Returns the avatar manager, used for avatar functionality
1509
+     *
1510
+     * @return IAvatarManager
1511
+     */
1512
+    public function getAvatarManager() {
1513
+        return $this->query(IAvatarManager::class);
1514
+    }
1515
+
1516
+    /**
1517
+     * Returns the root folder of ownCloud's data directory
1518
+     *
1519
+     * @return IRootFolder
1520
+     */
1521
+    public function getRootFolder() {
1522
+        return $this->query(IRootFolder::class);
1523
+    }
1524
+
1525
+    /**
1526
+     * Returns the root folder of ownCloud's data directory
1527
+     * This is the lazy variant so this gets only initialized once it
1528
+     * is actually used.
1529
+     *
1530
+     * @return IRootFolder
1531
+     */
1532
+    public function getLazyRootFolder() {
1533
+        return $this->query(IRootFolder::class);
1534
+    }
1535
+
1536
+    /**
1537
+     * Returns a view to ownCloud's files folder
1538
+     *
1539
+     * @param string $userId user ID
1540
+     * @return \OCP\Files\Folder|null
1541
+     */
1542
+    public function getUserFolder($userId = null) {
1543
+        if ($userId === null) {
1544
+            $user = $this->getUserSession()->getUser();
1545
+            if (!$user) {
1546
+                return null;
1547
+            }
1548
+            $userId = $user->getUID();
1549
+        }
1550
+        $root = $this->getRootFolder();
1551
+        return $root->getUserFolder($userId);
1552
+    }
1553
+
1554
+    /**
1555
+     * Returns an app-specific view in ownClouds data directory
1556
+     *
1557
+     * @return \OCP\Files\Folder
1558
+     * @deprecated since 9.2.0 use IAppData
1559
+     */
1560
+    public function getAppFolder() {
1561
+        $dir = '/' . \OC_App::getCurrentApp();
1562
+        $root = $this->getRootFolder();
1563
+        if (!$root->nodeExists($dir)) {
1564
+            $folder = $root->newFolder($dir);
1565
+        } else {
1566
+            $folder = $root->get($dir);
1567
+        }
1568
+        return $folder;
1569
+    }
1570
+
1571
+    /**
1572
+     * @return \OC\User\Manager
1573
+     */
1574
+    public function getUserManager() {
1575
+        return $this->query(IUserManager::class);
1576
+    }
1577
+
1578
+    /**
1579
+     * @return \OC\Group\Manager
1580
+     */
1581
+    public function getGroupManager() {
1582
+        return $this->query(IGroupManager::class);
1583
+    }
1584
+
1585
+    /**
1586
+     * @return \OC\User\Session
1587
+     */
1588
+    public function getUserSession() {
1589
+        return $this->query(IUserSession::class);
1590
+    }
1591
+
1592
+    /**
1593
+     * @return \OCP\ISession
1594
+     */
1595
+    public function getSession() {
1596
+        return $this->getUserSession()->getSession();
1597
+    }
1598
+
1599
+    /**
1600
+     * @param \OCP\ISession $session
1601
+     */
1602
+    public function setSession(\OCP\ISession $session) {
1603
+        $this->query(SessionStorage::class)->setSession($session);
1604
+        $this->getUserSession()->setSession($session);
1605
+        $this->query(Store::class)->setSession($session);
1606
+    }
1607
+
1608
+    /**
1609
+     * @return \OC\Authentication\TwoFactorAuth\Manager
1610
+     */
1611
+    public function getTwoFactorAuthManager() {
1612
+        return $this->query(\OC\Authentication\TwoFactorAuth\Manager::class);
1613
+    }
1614
+
1615
+    /**
1616
+     * @return \OC\NavigationManager
1617
+     */
1618
+    public function getNavigationManager() {
1619
+        return $this->query(INavigationManager::class);
1620
+    }
1621
+
1622
+    /**
1623
+     * @return \OCP\IConfig
1624
+     */
1625
+    public function getConfig() {
1626
+        return $this->query(AllConfig::class);
1627
+    }
1628
+
1629
+    /**
1630
+     * @return \OC\SystemConfig
1631
+     */
1632
+    public function getSystemConfig() {
1633
+        return $this->query(SystemConfig::class);
1634
+    }
1635
+
1636
+    /**
1637
+     * Returns the app config manager
1638
+     *
1639
+     * @return IAppConfig
1640
+     */
1641
+    public function getAppConfig() {
1642
+        return $this->query(IAppConfig::class);
1643
+    }
1644
+
1645
+    /**
1646
+     * @return IFactory
1647
+     */
1648
+    public function getL10NFactory() {
1649
+        return $this->query(IFactory::class);
1650
+    }
1651
+
1652
+    /**
1653
+     * get an L10N instance
1654
+     *
1655
+     * @param string $app appid
1656
+     * @param string $lang
1657
+     * @return IL10N
1658
+     */
1659
+    public function getL10N($app, $lang = null) {
1660
+        return $this->getL10NFactory()->get($app, $lang);
1661
+    }
1662
+
1663
+    /**
1664
+     * @return IURLGenerator
1665
+     */
1666
+    public function getURLGenerator() {
1667
+        return $this->query(IURLGenerator::class);
1668
+    }
1669
+
1670
+    /**
1671
+     * @return AppFetcher
1672
+     */
1673
+    public function getAppFetcher() {
1674
+        return $this->query(AppFetcher::class);
1675
+    }
1676
+
1677
+    /**
1678
+     * Returns an ICache instance. Since 8.1.0 it returns a fake cache. Use
1679
+     * getMemCacheFactory() instead.
1680
+     *
1681
+     * @return ICache
1682
+     * @deprecated 8.1.0 use getMemCacheFactory to obtain a proper cache
1683
+     */
1684
+    public function getCache() {
1685
+        return $this->query(ICache::class);
1686
+    }
1687
+
1688
+    /**
1689
+     * Returns an \OCP\CacheFactory instance
1690
+     *
1691
+     * @return \OCP\ICacheFactory
1692
+     */
1693
+    public function getMemCacheFactory() {
1694
+        return $this->query(Factory::class);
1695
+    }
1696
+
1697
+    /**
1698
+     * Returns an \OC\RedisFactory instance
1699
+     *
1700
+     * @return \OC\RedisFactory
1701
+     */
1702
+    public function getGetRedisFactory() {
1703
+        return $this->query('RedisFactory');
1704
+    }
1705
+
1706
+
1707
+    /**
1708
+     * Returns the current session
1709
+     *
1710
+     * @return \OCP\IDBConnection
1711
+     */
1712
+    public function getDatabaseConnection() {
1713
+        return $this->query(IDBConnection::class);
1714
+    }
1715
+
1716
+    /**
1717
+     * Returns the activity manager
1718
+     *
1719
+     * @return \OCP\Activity\IManager
1720
+     */
1721
+    public function getActivityManager() {
1722
+        return $this->query(\OCP\Activity\IManager::class);
1723
+    }
1724
+
1725
+    /**
1726
+     * Returns an job list for controlling background jobs
1727
+     *
1728
+     * @return IJobList
1729
+     */
1730
+    public function getJobList() {
1731
+        return $this->query(IJobList::class);
1732
+    }
1733
+
1734
+    /**
1735
+     * Returns a logger instance
1736
+     *
1737
+     * @return ILogger
1738
+     */
1739
+    public function getLogger() {
1740
+        return $this->query(ILogger::class);
1741
+    }
1742
+
1743
+    /**
1744
+     * @return ILogFactory
1745
+     * @throws \OCP\AppFramework\QueryException
1746
+     */
1747
+    public function getLogFactory() {
1748
+        return $this->query(ILogFactory::class);
1749
+    }
1750
+
1751
+    /**
1752
+     * Returns a router for generating and matching urls
1753
+     *
1754
+     * @return IRouter
1755
+     */
1756
+    public function getRouter() {
1757
+        return $this->query(IRouter::class);
1758
+    }
1759
+
1760
+    /**
1761
+     * Returns a search instance
1762
+     *
1763
+     * @return ISearch
1764
+     */
1765
+    public function getSearch() {
1766
+        return $this->query(ISearch::class);
1767
+    }
1768
+
1769
+    /**
1770
+     * Returns a SecureRandom instance
1771
+     *
1772
+     * @return \OCP\Security\ISecureRandom
1773
+     */
1774
+    public function getSecureRandom() {
1775
+        return $this->query(ISecureRandom::class);
1776
+    }
1777
+
1778
+    /**
1779
+     * Returns a Crypto instance
1780
+     *
1781
+     * @return ICrypto
1782
+     */
1783
+    public function getCrypto() {
1784
+        return $this->query(ICrypto::class);
1785
+    }
1786
+
1787
+    /**
1788
+     * Returns a Hasher instance
1789
+     *
1790
+     * @return IHasher
1791
+     */
1792
+    public function getHasher() {
1793
+        return $this->query(IHasher::class);
1794
+    }
1795
+
1796
+    /**
1797
+     * Returns a CredentialsManager instance
1798
+     *
1799
+     * @return ICredentialsManager
1800
+     */
1801
+    public function getCredentialsManager() {
1802
+        return $this->query(ICredentialsManager::class);
1803
+    }
1804
+
1805
+    /**
1806
+     * Get the certificate manager for the user
1807
+     *
1808
+     * @param string $userId (optional) if not specified the current loggedin user is used, use null to get the system certificate manager
1809
+     * @return \OCP\ICertificateManager | null if $uid is null and no user is logged in
1810
+     */
1811
+    public function getCertificateManager($userId = '') {
1812
+        if ($userId === '') {
1813
+            $userSession = $this->getUserSession();
1814
+            $user = $userSession->getUser();
1815
+            if (is_null($user)) {
1816
+                return null;
1817
+            }
1818
+            $userId = $user->getUID();
1819
+        }
1820
+        return new CertificateManager(
1821
+            $userId,
1822
+            new View(),
1823
+            $this->getConfig(),
1824
+            $this->getLogger(),
1825
+            $this->getSecureRandom()
1826
+        );
1827
+    }
1828
+
1829
+    /**
1830
+     * Returns an instance of the HTTP client service
1831
+     *
1832
+     * @return IClientService
1833
+     */
1834
+    public function getHTTPClientService() {
1835
+        return $this->query(IClientService::class);
1836
+    }
1837
+
1838
+    /**
1839
+     * Create a new event source
1840
+     *
1841
+     * @return \OCP\IEventSource
1842
+     */
1843
+    public function createEventSource() {
1844
+        return new \OC_EventSource();
1845
+    }
1846
+
1847
+    /**
1848
+     * Get the active event logger
1849
+     *
1850
+     * The returned logger only logs data when debug mode is enabled
1851
+     *
1852
+     * @return IEventLogger
1853
+     */
1854
+    public function getEventLogger() {
1855
+        return $this->query(IEventLogger::class);
1856
+    }
1857
+
1858
+    /**
1859
+     * Get the active query logger
1860
+     *
1861
+     * The returned logger only logs data when debug mode is enabled
1862
+     *
1863
+     * @return IQueryLogger
1864
+     */
1865
+    public function getQueryLogger() {
1866
+        return $this->query(IQueryLogger::class);
1867
+    }
1868
+
1869
+    /**
1870
+     * Get the manager for temporary files and folders
1871
+     *
1872
+     * @return \OCP\ITempManager
1873
+     */
1874
+    public function getTempManager() {
1875
+        return $this->query(ITempManager::class);
1876
+    }
1877
+
1878
+    /**
1879
+     * Get the app manager
1880
+     *
1881
+     * @return \OCP\App\IAppManager
1882
+     */
1883
+    public function getAppManager() {
1884
+        return $this->query(IAppManager::class);
1885
+    }
1886
+
1887
+    /**
1888
+     * Creates a new mailer
1889
+     *
1890
+     * @return IMailer
1891
+     */
1892
+    public function getMailer() {
1893
+        return $this->query(IMailer::class);
1894
+    }
1895
+
1896
+    /**
1897
+     * Get the webroot
1898
+     *
1899
+     * @return string
1900
+     */
1901
+    public function getWebRoot() {
1902
+        return $this->webRoot;
1903
+    }
1904
+
1905
+    /**
1906
+     * @return \OC\OCSClient
1907
+     */
1908
+    public function getOcsClient() {
1909
+        return $this->query('OcsClient');
1910
+    }
1911
+
1912
+    /**
1913
+     * @return IDateTimeZone
1914
+     */
1915
+    public function getDateTimeZone() {
1916
+        return $this->query(IDateTimeZone::class);
1917
+    }
1918
+
1919
+    /**
1920
+     * @return IDateTimeFormatter
1921
+     */
1922
+    public function getDateTimeFormatter() {
1923
+        return $this->query(IDateTimeFormatter::class);
1924
+    }
1925
+
1926
+    /**
1927
+     * @return IMountProviderCollection
1928
+     */
1929
+    public function getMountProviderCollection() {
1930
+        return $this->query(IMountProviderCollection::class);
1931
+    }
1932
+
1933
+    /**
1934
+     * Get the IniWrapper
1935
+     *
1936
+     * @return IniGetWrapper
1937
+     */
1938
+    public function getIniWrapper() {
1939
+        return $this->query('IniWrapper');
1940
+    }
1941
+
1942
+    /**
1943
+     * @return \OCP\Command\IBus
1944
+     */
1945
+    public function getCommandBus() {
1946
+        return $this->query('AsyncCommandBus');
1947
+    }
1948
+
1949
+    /**
1950
+     * Get the trusted domain helper
1951
+     *
1952
+     * @return TrustedDomainHelper
1953
+     */
1954
+    public function getTrustedDomainHelper() {
1955
+        return $this->query('TrustedDomainHelper');
1956
+    }
1957
+
1958
+    /**
1959
+     * Get the locking provider
1960
+     *
1961
+     * @return ILockingProvider
1962
+     * @since 8.1.0
1963
+     */
1964
+    public function getLockingProvider() {
1965
+        return $this->query(ILockingProvider::class);
1966
+    }
1967
+
1968
+    /**
1969
+     * @return IMountManager
1970
+     **/
1971
+    function getMountManager() {
1972
+        return $this->query(IMountManager::class);
1973
+    }
1974
+
1975
+    /**
1976
+     * @return IUserMountCache
1977
+     */
1978
+    function getUserMountCache() {
1979
+        return $this->query(IUserMountCache::class);
1980
+    }
1981
+
1982
+    /**
1983
+     * Get the MimeTypeDetector
1984
+     *
1985
+     * @return IMimeTypeDetector
1986
+     */
1987
+    public function getMimeTypeDetector() {
1988
+        return $this->query(IMimeTypeDetector::class);
1989
+    }
1990
+
1991
+    /**
1992
+     * Get the MimeTypeLoader
1993
+     *
1994
+     * @return IMimeTypeLoader
1995
+     */
1996
+    public function getMimeTypeLoader() {
1997
+        return $this->query(IMimeTypeLoader::class);
1998
+    }
1999
+
2000
+    /**
2001
+     * Get the manager of all the capabilities
2002
+     *
2003
+     * @return CapabilitiesManager
2004
+     */
2005
+    public function getCapabilitiesManager() {
2006
+        return $this->query(CapabilitiesManager::class);
2007
+    }
2008
+
2009
+    /**
2010
+     * Get the EventDispatcher
2011
+     *
2012
+     * @return EventDispatcherInterface
2013
+     * @since 8.2.0
2014
+     * @deprecated 18.0.0 use \OCP\EventDispatcher\IEventDispatcher
2015
+     */
2016
+    public function getEventDispatcher() {
2017
+        return $this->query(\OC\EventDispatcher\SymfonyAdapter::class);
2018
+    }
2019
+
2020
+    /**
2021
+     * Get the Notification Manager
2022
+     *
2023
+     * @return \OCP\Notification\IManager
2024
+     * @since 8.2.0
2025
+     */
2026
+    public function getNotificationManager() {
2027
+        return $this->query(\OCP\Notification\IManager::class);
2028
+    }
2029
+
2030
+    /**
2031
+     * @return ICommentsManager
2032
+     */
2033
+    public function getCommentsManager() {
2034
+        return $this->query(ICommentsManager::class);
2035
+    }
2036
+
2037
+    /**
2038
+     * @return \OCA\Theming\ThemingDefaults
2039
+     */
2040
+    public function getThemingDefaults() {
2041
+        return $this->query('ThemingDefaults');
2042
+    }
2043
+
2044
+    /**
2045
+     * @return \OC\IntegrityCheck\Checker
2046
+     */
2047
+    public function getIntegrityCodeChecker() {
2048
+        return $this->query('IntegrityCodeChecker');
2049
+    }
2050
+
2051
+    /**
2052
+     * @return \OC\Session\CryptoWrapper
2053
+     */
2054
+    public function getSessionCryptoWrapper() {
2055
+        return $this->query('CryptoWrapper');
2056
+    }
2057
+
2058
+    /**
2059
+     * @return CsrfTokenManager
2060
+     */
2061
+    public function getCsrfTokenManager() {
2062
+        return $this->query(CsrfTokenManager::class);
2063
+    }
2064
+
2065
+    /**
2066
+     * @return Throttler
2067
+     */
2068
+    public function getBruteForceThrottler() {
2069
+        return $this->query(Throttler::class);
2070
+    }
2071
+
2072
+    /**
2073
+     * @return IContentSecurityPolicyManager
2074
+     */
2075
+    public function getContentSecurityPolicyManager() {
2076
+        return $this->query(ContentSecurityPolicyManager::class);
2077
+    }
2078
+
2079
+    /**
2080
+     * @return ContentSecurityPolicyNonceManager
2081
+     */
2082
+    public function getContentSecurityPolicyNonceManager() {
2083
+        return $this->query('ContentSecurityPolicyNonceManager');
2084
+    }
2085
+
2086
+    /**
2087
+     * Not a public API as of 8.2, wait for 9.0
2088
+     *
2089
+     * @return \OCA\Files_External\Service\BackendService
2090
+     */
2091
+    public function getStoragesBackendService() {
2092
+        return $this->query(BackendService::class);
2093
+    }
2094
+
2095
+    /**
2096
+     * Not a public API as of 8.2, wait for 9.0
2097
+     *
2098
+     * @return \OCA\Files_External\Service\GlobalStoragesService
2099
+     */
2100
+    public function getGlobalStoragesService() {
2101
+        return $this->query(GlobalStoragesService::class);
2102
+    }
2103
+
2104
+    /**
2105
+     * Not a public API as of 8.2, wait for 9.0
2106
+     *
2107
+     * @return \OCA\Files_External\Service\UserGlobalStoragesService
2108
+     */
2109
+    public function getUserGlobalStoragesService() {
2110
+        return $this->query(UserGlobalStoragesService::class);
2111
+    }
2112
+
2113
+    /**
2114
+     * Not a public API as of 8.2, wait for 9.0
2115
+     *
2116
+     * @return \OCA\Files_External\Service\UserStoragesService
2117
+     */
2118
+    public function getUserStoragesService() {
2119
+        return $this->query(UserStoragesService::class);
2120
+    }
2121
+
2122
+    /**
2123
+     * @return \OCP\Share\IManager
2124
+     */
2125
+    public function getShareManager() {
2126
+        return $this->query(\OCP\Share\IManager::class);
2127
+    }
2128
+
2129
+    /**
2130
+     * @return \OCP\Collaboration\Collaborators\ISearch
2131
+     */
2132
+    public function getCollaboratorSearch() {
2133
+        return $this->query(\OCP\Collaboration\Collaborators\ISearch::class);
2134
+    }
2135
+
2136
+    /**
2137
+     * @return \OCP\Collaboration\AutoComplete\IManager
2138
+     */
2139
+    public function getAutoCompleteManager(){
2140
+        return $this->query(IManager::class);
2141
+    }
2142
+
2143
+    /**
2144
+     * Returns the LDAP Provider
2145
+     *
2146
+     * @return \OCP\LDAP\ILDAPProvider
2147
+     */
2148
+    public function getLDAPProvider() {
2149
+        return $this->query('LDAPProvider');
2150
+    }
2151
+
2152
+    /**
2153
+     * @return \OCP\Settings\IManager
2154
+     */
2155
+    public function getSettingsManager() {
2156
+        return $this->query('SettingsManager');
2157
+    }
2158
+
2159
+    /**
2160
+     * @return \OCP\Files\IAppData
2161
+     */
2162
+    public function getAppDataDir($app) {
2163
+        /** @var \OC\Files\AppData\Factory $factory */
2164
+        $factory = $this->query(\OC\Files\AppData\Factory::class);
2165
+        return $factory->get($app);
2166
+    }
2167
+
2168
+    /**
2169
+     * @return \OCP\Lockdown\ILockdownManager
2170
+     */
2171
+    public function getLockdownManager() {
2172
+        return $this->query('LockdownManager');
2173
+    }
2174
+
2175
+    /**
2176
+     * @return \OCP\Federation\ICloudIdManager
2177
+     */
2178
+    public function getCloudIdManager() {
2179
+        return $this->query(ICloudIdManager::class);
2180
+    }
2181
+
2182
+    /**
2183
+     * @return \OCP\GlobalScale\IConfig
2184
+     */
2185
+    public function getGlobalScaleConfig() {
2186
+        return $this->query(IConfig::class);
2187
+    }
2188
+
2189
+    /**
2190
+     * @return \OCP\Federation\ICloudFederationProviderManager
2191
+     */
2192
+    public function getCloudFederationProviderManager() {
2193
+        return $this->query(ICloudFederationProviderManager::class);
2194
+    }
2195
+
2196
+    /**
2197
+     * @return \OCP\Remote\Api\IApiFactory
2198
+     */
2199
+    public function getRemoteApiFactory() {
2200
+        return $this->query(IApiFactory::class);
2201
+    }
2202
+
2203
+    /**
2204
+     * @return \OCP\Federation\ICloudFederationFactory
2205
+     */
2206
+    public function getCloudFederationFactory() {
2207
+        return $this->query(ICloudFederationFactory::class);
2208
+    }
2209
+
2210
+    /**
2211
+     * @return \OCP\Remote\IInstanceFactory
2212
+     */
2213
+    public function getRemoteInstanceFactory() {
2214
+        return $this->query(IInstanceFactory::class);
2215
+    }
2216
+
2217
+    /**
2218
+     * @return IStorageFactory
2219
+     */
2220
+    public function getStorageFactory() {
2221
+        return $this->query(IStorageFactory::class);
2222
+    }
2223
+
2224
+    /**
2225
+     * Get the Preview GeneratorHelper
2226
+     *
2227
+     * @return GeneratorHelper
2228
+     * @since 17.0.0
2229
+     */
2230
+    public function getGeneratorHelper() {
2231
+        return $this->query(\OC\Preview\GeneratorHelper::class);
2232
+    }
2233
+
2234
+    private function registerDeprecatedAlias(string $alias, string $target) {
2235
+        $this->registerService($alias, function (IContainer $container) use ($target, $alias) {
2236
+            try {
2237
+                /** @var ILogger $logger */
2238
+                $logger = $container->query(ILogger::class);
2239
+                $logger->debug('The requested alias "' . $alias . '" is depreacted. Please request "' . $target . '" directly. This alias will be removed in a future Nextcloud version.', ['app' => 'serverDI']);
2240
+            } catch (QueryException $e) {
2241
+                // Could not get logger. Continue
2242
+            }
2243
+
2244
+            return $container->query($target);
2245
+        }, false);
2246
+    }
2247 2247
 }
Please login to merge, or discard this patch.
lib/private/User/Session.php 2 patches
Indentation   +921 added lines, -921 removed lines patch added patch discarded remove patch
@@ -92,927 +92,927 @@
 block discarded – undo
92 92
  */
93 93
 class Session implements IUserSession, Emitter {
94 94
 
95
-	/** @var Manager|PublicEmitter $manager */
96
-	private $manager;
97
-
98
-	/** @var ISession $session */
99
-	private $session;
100
-
101
-	/** @var ITimeFactory */
102
-	private $timeFactory;
103
-
104
-	/** @var IProvider */
105
-	private $tokenProvider;
106
-
107
-	/** @var IConfig */
108
-	private $config;
109
-
110
-	/** @var User $activeUser */
111
-	protected $activeUser;
112
-
113
-	/** @var ISecureRandom */
114
-	private $random;
115
-
116
-	/** @var ILockdownManager  */
117
-	private $lockdownManager;
118
-
119
-	/** @var ILogger */
120
-	private $logger;
121
-	/** @var IEventDispatcher */
122
-	private $dispatcher;
123
-
124
-	/**
125
-	 * @param Manager $manager
126
-	 * @param ISession $session
127
-	 * @param ITimeFactory $timeFactory
128
-	 * @param IProvider $tokenProvider
129
-	 * @param IConfig $config
130
-	 * @param ISecureRandom $random
131
-	 * @param ILockdownManager $lockdownManager
132
-	 * @param ILogger $logger
133
-	 */
134
-	public function __construct(Manager $manager,
135
-								ISession $session,
136
-								ITimeFactory $timeFactory,
137
-								$tokenProvider,
138
-								IConfig $config,
139
-								ISecureRandom $random,
140
-								ILockdownManager $lockdownManager,
141
-								ILogger $logger,
142
-								IEventDispatcher $dispatcher
143
-	) {
144
-		$this->manager = $manager;
145
-		$this->session = $session;
146
-		$this->timeFactory = $timeFactory;
147
-		$this->tokenProvider = $tokenProvider;
148
-		$this->config = $config;
149
-		$this->random = $random;
150
-		$this->lockdownManager = $lockdownManager;
151
-		$this->logger = $logger;
152
-		$this->dispatcher = $dispatcher;
153
-	}
154
-
155
-	/**
156
-	 * @param IProvider $provider
157
-	 */
158
-	public function setTokenProvider(IProvider $provider) {
159
-		$this->tokenProvider = $provider;
160
-	}
161
-
162
-	/**
163
-	 * @param string $scope
164
-	 * @param string $method
165
-	 * @param callable $callback
166
-	 */
167
-	public function listen($scope, $method, callable $callback) {
168
-		$this->manager->listen($scope, $method, $callback);
169
-	}
170
-
171
-	/**
172
-	 * @param string $scope optional
173
-	 * @param string $method optional
174
-	 * @param callable $callback optional
175
-	 */
176
-	public function removeListener($scope = null, $method = null, callable $callback = null) {
177
-		$this->manager->removeListener($scope, $method, $callback);
178
-	}
179
-
180
-	/**
181
-	 * get the manager object
182
-	 *
183
-	 * @return Manager|PublicEmitter
184
-	 */
185
-	public function getManager() {
186
-		return $this->manager;
187
-	}
188
-
189
-	/**
190
-	 * get the session object
191
-	 *
192
-	 * @return ISession
193
-	 */
194
-	public function getSession() {
195
-		return $this->session;
196
-	}
197
-
198
-	/**
199
-	 * set the session object
200
-	 *
201
-	 * @param ISession $session
202
-	 */
203
-	public function setSession(ISession $session) {
204
-		if ($this->session instanceof ISession) {
205
-			$this->session->close();
206
-		}
207
-		$this->session = $session;
208
-		$this->activeUser = null;
209
-	}
210
-
211
-	/**
212
-	 * set the currently active user
213
-	 *
214
-	 * @param IUser|null $user
215
-	 */
216
-	public function setUser($user) {
217
-		if (is_null($user)) {
218
-			$this->session->remove('user_id');
219
-		} else {
220
-			$this->session->set('user_id', $user->getUID());
221
-		}
222
-		$this->activeUser = $user;
223
-	}
224
-
225
-	/**
226
-	 * get the current active user
227
-	 *
228
-	 * @return IUser|null Current user, otherwise null
229
-	 */
230
-	public function getUser() {
231
-		// FIXME: This is a quick'n dirty work-around for the incognito mode as
232
-		// described at https://github.com/owncloud/core/pull/12912#issuecomment-67391155
233
-		if (OC_User::isIncognitoMode()) {
234
-			return null;
235
-		}
236
-		if (is_null($this->activeUser)) {
237
-			$uid = $this->session->get('user_id');
238
-			if (is_null($uid)) {
239
-				return null;
240
-			}
241
-			$this->activeUser = $this->manager->get($uid);
242
-			if (is_null($this->activeUser)) {
243
-				return null;
244
-			}
245
-			$this->validateSession();
246
-		}
247
-		return $this->activeUser;
248
-	}
249
-
250
-	/**
251
-	 * Validate whether the current session is valid
252
-	 *
253
-	 * - For token-authenticated clients, the token validity is checked
254
-	 * - For browsers, the session token validity is checked
255
-	 */
256
-	protected function validateSession() {
257
-		$token = null;
258
-		$appPassword = $this->session->get('app_password');
259
-
260
-		if (is_null($appPassword)) {
261
-			try {
262
-				$token = $this->session->getId();
263
-			} catch (SessionNotAvailableException $ex) {
264
-				return;
265
-			}
266
-		} else {
267
-			$token = $appPassword;
268
-		}
269
-
270
-		if (!$this->validateToken($token)) {
271
-			// Session was invalidated
272
-			$this->logout();
273
-		}
274
-	}
275
-
276
-	/**
277
-	 * Checks whether the user is logged in
278
-	 *
279
-	 * @return bool if logged in
280
-	 */
281
-	public function isLoggedIn() {
282
-		$user = $this->getUser();
283
-		if (is_null($user)) {
284
-			return false;
285
-		}
286
-
287
-		return $user->isEnabled();
288
-	}
289
-
290
-	/**
291
-	 * set the login name
292
-	 *
293
-	 * @param string|null $loginName for the logged in user
294
-	 */
295
-	public function setLoginName($loginName) {
296
-		if (is_null($loginName)) {
297
-			$this->session->remove('loginname');
298
-		} else {
299
-			$this->session->set('loginname', $loginName);
300
-		}
301
-	}
302
-
303
-	/**
304
-	 * get the login name of the current user
305
-	 *
306
-	 * @return string
307
-	 */
308
-	public function getLoginName() {
309
-		if ($this->activeUser) {
310
-			return $this->session->get('loginname');
311
-		}
312
-
313
-		$uid = $this->session->get('user_id');
314
-		if ($uid) {
315
-			$this->activeUser = $this->manager->get($uid);
316
-			return $this->session->get('loginname');
317
-		}
318
-
319
-		return null;
320
-	}
321
-
322
-	/**
323
-	 * @return null|string
324
-	 */
325
-	public function getImpersonatingUserID(): ?string {
326
-
327
-		return $this->session->get('oldUserId');
328
-
329
-	}
330
-
331
-	public function setImpersonatingUserID(bool $useCurrentUser = true): void {
332
-		if ($useCurrentUser === false) {
333
-			$this->session->remove('oldUserId');
334
-			return;
335
-		}
336
-
337
-		$currentUser = $this->getUser();
338
-
339
-		if ($currentUser === null) {
340
-			throw new \OC\User\NoUserException();
341
-		}
342
-		$this->session->set('oldUserId', $currentUser->getUID());
343
-
344
-	}
345
-	/**
346
-	 * set the token id
347
-	 *
348
-	 * @param int|null $token that was used to log in
349
-	 */
350
-	protected function setToken($token) {
351
-		if ($token === null) {
352
-			$this->session->remove('token-id');
353
-		} else {
354
-			$this->session->set('token-id', $token);
355
-		}
356
-	}
357
-
358
-	/**
359
-	 * try to log in with the provided credentials
360
-	 *
361
-	 * @param string $uid
362
-	 * @param string $password
363
-	 * @return boolean|null
364
-	 * @throws LoginException
365
-	 */
366
-	public function login($uid, $password) {
367
-		$this->session->regenerateId();
368
-		if ($this->validateToken($password, $uid)) {
369
-			return $this->loginWithToken($password);
370
-		}
371
-		return $this->loginWithPassword($uid, $password);
372
-	}
373
-
374
-	/**
375
-	 * @param IUser $user
376
-	 * @param array $loginDetails
377
-	 * @param bool $regenerateSessionId
378
-	 * @return true returns true if login successful or an exception otherwise
379
-	 * @throws LoginException
380
-	 */
381
-	public function completeLogin(IUser $user, array $loginDetails, $regenerateSessionId = true) {
382
-		if (!$user->isEnabled()) {
383
-			// disabled users can not log in
384
-			// injecting l10n does not work - there is a circular dependency between session and \OCP\L10N\IFactory
385
-			$message = \OC::$server->getL10N('lib')->t('User disabled');
386
-			throw new LoginException($message);
387
-		}
388
-
389
-		if($regenerateSessionId) {
390
-			$this->session->regenerateId();
391
-		}
392
-
393
-		$this->setUser($user);
394
-		$this->setLoginName($loginDetails['loginName']);
395
-
396
-		$isToken = isset($loginDetails['token']) && $loginDetails['token'] instanceof IToken;
397
-		if ($isToken) {
398
-			$this->setToken($loginDetails['token']->getId());
399
-			$this->lockdownManager->setToken($loginDetails['token']);
400
-			$firstTimeLogin = false;
401
-		} else {
402
-			$this->setToken(null);
403
-			$firstTimeLogin = $user->updateLastLoginTimestamp();
404
-		}
405
-
406
-		$this->dispatcher->dispatchTyped(new PostLoginEvent(
407
-			$user,
408
-			$loginDetails['password'],
409
-			$isToken
410
-		));
411
-		$this->manager->emit('\OC\User', 'postLogin', [
412
-			$user,
413
-			$loginDetails['password'],
414
-			$isToken,
415
-		]);
416
-		if($this->isLoggedIn()) {
417
-			$this->prepareUserLogin($firstTimeLogin, $regenerateSessionId);
418
-			return true;
419
-		}
420
-
421
-		$message = \OC::$server->getL10N('lib')->t('Login canceled by app');
422
-		throw new LoginException($message);
423
-	}
424
-
425
-	/**
426
-	 * Tries to log in a client
427
-	 *
428
-	 * Checks token auth enforced
429
-	 * Checks 2FA enabled
430
-	 *
431
-	 * @param string $user
432
-	 * @param string $password
433
-	 * @param IRequest $request
434
-	 * @param OC\Security\Bruteforce\Throttler $throttler
435
-	 * @throws LoginException
436
-	 * @throws PasswordLoginForbiddenException
437
-	 * @return boolean
438
-	 */
439
-	public function logClientIn($user,
440
-								$password,
441
-								IRequest $request,
442
-								OC\Security\Bruteforce\Throttler $throttler) {
443
-		$currentDelay = $throttler->sleepDelay($request->getRemoteAddress(), 'login');
444
-
445
-		if ($this->manager instanceof PublicEmitter) {
446
-			$this->manager->emit('\OC\User', 'preLogin', [$user, $password]);
447
-		}
448
-
449
-		try {
450
-			$isTokenPassword = $this->isTokenPassword($password);
451
-		} catch (ExpiredTokenException $e) {
452
-			// Just return on an expired token no need to check further or record a failed login
453
-			return false;
454
-		}
455
-
456
-		if (!$isTokenPassword && $this->isTokenAuthEnforced()) {
457
-			throw new PasswordLoginForbiddenException();
458
-		}
459
-		if (!$isTokenPassword && $this->isTwoFactorEnforced($user)) {
460
-			throw new PasswordLoginForbiddenException();
461
-		}
462
-
463
-		// Try to login with this username and password
464
-		if (!$this->login($user, $password) ) {
465
-
466
-			// Failed, maybe the user used their email address
467
-			$users = $this->manager->getByEmail($user);
468
-			if (!(\count($users) === 1 && $this->login($users[0]->getUID(), $password))) {
469
-
470
-				$this->logger->warning('Login failed: \'' . $user . '\' (Remote IP: \'' . \OC::$server->getRequest()->getRemoteAddress() . '\')', ['app' => 'core']);
471
-
472
-				$throttler->registerAttempt('login', $request->getRemoteAddress(), ['user' => $user]);
473
-
474
-				$this->dispatcher->dispatchTyped(new OC\Authentication\Events\LoginFailed($user));
475
-
476
-				if ($currentDelay === 0) {
477
-					$throttler->sleepDelay($request->getRemoteAddress(), 'login');
478
-				}
479
-				return false;
480
-			}
481
-		}
482
-
483
-		if ($isTokenPassword) {
484
-			$this->session->set('app_password', $password);
485
-		} else if($this->supportsCookies($request)) {
486
-			// Password login, but cookies supported -> create (browser) session token
487
-			$this->createSessionToken($request, $this->getUser()->getUID(), $user, $password);
488
-		}
489
-
490
-		return true;
491
-	}
492
-
493
-	protected function supportsCookies(IRequest $request) {
494
-		if (!is_null($request->getCookie('cookie_test'))) {
495
-			return true;
496
-		}
497
-		setcookie('cookie_test', 'test', $this->timeFactory->getTime() + 3600);
498
-		return false;
499
-	}
500
-
501
-	private function isTokenAuthEnforced() {
502
-		return $this->config->getSystemValue('token_auth_enforced', false);
503
-	}
504
-
505
-	protected function isTwoFactorEnforced($username) {
506
-		Util::emitHook(
507
-			'\OCA\Files_Sharing\API\Server2Server',
508
-			'preLoginNameUsedAsUserName',
509
-			['uid' => &$username]
510
-		);
511
-		$user = $this->manager->get($username);
512
-		if (is_null($user)) {
513
-			$users = $this->manager->getByEmail($username);
514
-			if (empty($users)) {
515
-				return false;
516
-			}
517
-			if (count($users) !== 1) {
518
-				return true;
519
-			}
520
-			$user = $users[0];
521
-		}
522
-		// DI not possible due to cyclic dependencies :'-/
523
-		return OC::$server->getTwoFactorAuthManager()->isTwoFactorAuthenticated($user);
524
-	}
525
-
526
-	/**
527
-	 * Check if the given 'password' is actually a device token
528
-	 *
529
-	 * @param string $password
530
-	 * @return boolean
531
-	 * @throws ExpiredTokenException
532
-	 */
533
-	public function isTokenPassword($password) {
534
-		try {
535
-			$this->tokenProvider->getToken($password);
536
-			return true;
537
-		} catch (ExpiredTokenException $e) {
538
-			throw $e;
539
-		} catch (InvalidTokenException $ex) {
540
-			return false;
541
-		}
542
-	}
543
-
544
-	protected function prepareUserLogin($firstTimeLogin, $refreshCsrfToken = true) {
545
-		if ($refreshCsrfToken) {
546
-			// TODO: mock/inject/use non-static
547
-			// Refresh the token
548
-			\OC::$server->getCsrfTokenManager()->refreshToken();
549
-		}
550
-
551
-		//we need to pass the user name, which may differ from login name
552
-		$user = $this->getUser()->getUID();
553
-		OC_Util::setupFS($user);
554
-
555
-		if ($firstTimeLogin) {
556
-			// TODO: lock necessary?
557
-			//trigger creation of user home and /files folder
558
-			$userFolder = \OC::$server->getUserFolder($user);
559
-
560
-			try {
561
-				// copy skeleton
562
-				\OC_Util::copySkeleton($user, $userFolder);
563
-			} catch (NotPermittedException $ex) {
564
-				// read only uses
565
-			}
566
-
567
-			// trigger any other initialization
568
-			\OC::$server->getEventDispatcher()->dispatch(IUser::class . '::firstLogin', new GenericEvent($this->getUser()));
569
-		}
570
-	}
571
-
572
-	/**
573
-	 * Tries to login the user with HTTP Basic Authentication
574
-	 *
575
-	 * @todo do not allow basic auth if the user is 2FA enforced
576
-	 * @param IRequest $request
577
-	 * @param OC\Security\Bruteforce\Throttler $throttler
578
-	 * @return boolean if the login was successful
579
-	 */
580
-	public function tryBasicAuthLogin(IRequest $request,
581
-									  OC\Security\Bruteforce\Throttler $throttler) {
582
-		if (!empty($request->server['PHP_AUTH_USER']) && !empty($request->server['PHP_AUTH_PW'])) {
583
-			try {
584
-				if ($this->logClientIn($request->server['PHP_AUTH_USER'], $request->server['PHP_AUTH_PW'], $request, $throttler)) {
585
-					/**
586
-					 * Add DAV authenticated. This should in an ideal world not be
587
-					 * necessary but the iOS App reads cookies from anywhere instead
588
-					 * only the DAV endpoint.
589
-					 * This makes sure that the cookies will be valid for the whole scope
590
-					 * @see https://github.com/owncloud/core/issues/22893
591
-					 */
592
-					$this->session->set(
593
-						Auth::DAV_AUTHENTICATED, $this->getUser()->getUID()
594
-					);
595
-
596
-					// Set the last-password-confirm session to make the sudo mode work
597
-					 $this->session->set('last-password-confirm', $this->timeFactory->getTime());
598
-
599
-					return true;
600
-				}
601
-			} catch (PasswordLoginForbiddenException $ex) {
602
-				// Nothing to do
603
-			}
604
-		}
605
-		return false;
606
-	}
607
-
608
-	/**
609
-	 * Log an user in via login name and password
610
-	 *
611
-	 * @param string $uid
612
-	 * @param string $password
613
-	 * @return boolean
614
-	 * @throws LoginException if an app canceld the login process or the user is not enabled
615
-	 */
616
-	private function loginWithPassword($uid, $password) {
617
-		$user = $this->manager->checkPasswordNoLogging($uid, $password);
618
-		if ($user === false) {
619
-			// Password check failed
620
-			return false;
621
-		}
622
-
623
-		return $this->completeLogin($user, ['loginName' => $uid, 'password' => $password], false);
624
-	}
625
-
626
-	/**
627
-	 * Log an user in with a given token (id)
628
-	 *
629
-	 * @param string $token
630
-	 * @return boolean
631
-	 * @throws LoginException if an app canceled the login process or the user is not enabled
632
-	 */
633
-	private function loginWithToken($token) {
634
-		try {
635
-			$dbToken = $this->tokenProvider->getToken($token);
636
-		} catch (InvalidTokenException $ex) {
637
-			return false;
638
-		}
639
-		$uid = $dbToken->getUID();
640
-
641
-		// When logging in with token, the password must be decrypted first before passing to login hook
642
-		$password = '';
643
-		try {
644
-			$password = $this->tokenProvider->getPassword($dbToken, $token);
645
-		} catch (PasswordlessTokenException $ex) {
646
-			// Ignore and use empty string instead
647
-		}
648
-
649
-		$this->manager->emit('\OC\User', 'preLogin', [$uid, $password]);
650
-
651
-		$user = $this->manager->get($uid);
652
-		if (is_null($user)) {
653
-			// user does not exist
654
-			return false;
655
-		}
656
-
657
-		return $this->completeLogin(
658
-			$user,
659
-			[
660
-				'loginName' => $dbToken->getLoginName(),
661
-				'password' => $password,
662
-				'token' => $dbToken
663
-			],
664
-			false);
665
-	}
666
-
667
-	/**
668
-	 * Create a new session token for the given user credentials
669
-	 *
670
-	 * @param IRequest $request
671
-	 * @param string $uid user UID
672
-	 * @param string $loginName login name
673
-	 * @param string $password
674
-	 * @param int $remember
675
-	 * @return boolean
676
-	 */
677
-	public function createSessionToken(IRequest $request, $uid, $loginName, $password = null, $remember = IToken::DO_NOT_REMEMBER) {
678
-		if (is_null($this->manager->get($uid))) {
679
-			// User does not exist
680
-			return false;
681
-		}
682
-		$name = isset($request->server['HTTP_USER_AGENT']) ? $request->server['HTTP_USER_AGENT'] : 'unknown browser';
683
-		try {
684
-			$sessionId = $this->session->getId();
685
-			$pwd = $this->getPassword($password);
686
-			// Make sure the current sessionId has no leftover tokens
687
-			$this->tokenProvider->invalidateToken($sessionId);
688
-			$this->tokenProvider->generateToken($sessionId, $uid, $loginName, $pwd, $name, IToken::TEMPORARY_TOKEN, $remember);
689
-			return true;
690
-		} catch (SessionNotAvailableException $ex) {
691
-			// This can happen with OCC, where a memory session is used
692
-			// if a memory session is used, we shouldn't create a session token anyway
693
-			return false;
694
-		}
695
-	}
696
-
697
-	/**
698
-	 * Checks if the given password is a token.
699
-	 * If yes, the password is extracted from the token.
700
-	 * If no, the same password is returned.
701
-	 *
702
-	 * @param string $password either the login password or a device token
703
-	 * @return string|null the password or null if none was set in the token
704
-	 */
705
-	private function getPassword($password) {
706
-		if (is_null($password)) {
707
-			// This is surely no token ;-)
708
-			return null;
709
-		}
710
-		try {
711
-			$token = $this->tokenProvider->getToken($password);
712
-			try {
713
-				return $this->tokenProvider->getPassword($token, $password);
714
-			} catch (PasswordlessTokenException $ex) {
715
-				return null;
716
-			}
717
-		} catch (InvalidTokenException $ex) {
718
-			return $password;
719
-		}
720
-	}
721
-
722
-	/**
723
-	 * @param IToken $dbToken
724
-	 * @param string $token
725
-	 * @return boolean
726
-	 */
727
-	private function checkTokenCredentials(IToken $dbToken, $token) {
728
-		// Check whether login credentials are still valid and the user was not disabled
729
-		// This check is performed each 5 minutes
730
-		$lastCheck = $dbToken->getLastCheck() ? : 0;
731
-		$now = $this->timeFactory->getTime();
732
-		if ($lastCheck > ($now - 60 * 5)) {
733
-			// Checked performed recently, nothing to do now
734
-			return true;
735
-		}
736
-
737
-		try {
738
-			$pwd = $this->tokenProvider->getPassword($dbToken, $token);
739
-		} catch (InvalidTokenException $ex) {
740
-			// An invalid token password was used -> log user out
741
-			return false;
742
-		} catch (PasswordlessTokenException $ex) {
743
-			// Token has no password
744
-
745
-			if (!is_null($this->activeUser) && !$this->activeUser->isEnabled()) {
746
-				$this->tokenProvider->invalidateToken($token);
747
-				return false;
748
-			}
749
-
750
-			$dbToken->setLastCheck($now);
751
-			return true;
752
-		}
753
-
754
-		// Invalidate token if the user is no longer active
755
-		if (!is_null($this->activeUser) && !$this->activeUser->isEnabled()) {
756
-			$this->tokenProvider->invalidateToken($token);
757
-			return false;
758
-		}
759
-
760
-		// If the token password is no longer valid mark it as such
761
-		if ($this->manager->checkPassword($dbToken->getLoginName(), $pwd) === false) {
762
-			$this->tokenProvider->markPasswordInvalid($dbToken, $token);
763
-			// User is logged out
764
-			return false;
765
-		}
766
-
767
-		$dbToken->setLastCheck($now);
768
-		return true;
769
-	}
770
-
771
-	/**
772
-	 * Check if the given token exists and performs password/user-enabled checks
773
-	 *
774
-	 * Invalidates the token if checks fail
775
-	 *
776
-	 * @param string $token
777
-	 * @param string $user login name
778
-	 * @return boolean
779
-	 */
780
-	private function validateToken($token, $user = null) {
781
-		try {
782
-			$dbToken = $this->tokenProvider->getToken($token);
783
-		} catch (InvalidTokenException $ex) {
784
-			return false;
785
-		}
786
-
787
-		// Check if login names match
788
-		if (!is_null($user) && $dbToken->getLoginName() !== $user) {
789
-			// TODO: this makes it imposssible to use different login names on browser and client
790
-			// e.g. login by e-mail '[email protected]' on browser for generating the token will not
791
-			//      allow to use the client token with the login name 'user'.
792
-			return false;
793
-		}
794
-
795
-		if (!$this->checkTokenCredentials($dbToken, $token)) {
796
-			return false;
797
-		}
798
-
799
-		// Update token scope
800
-		$this->lockdownManager->setToken($dbToken);
801
-
802
-		$this->tokenProvider->updateTokenActivity($dbToken);
803
-
804
-		return true;
805
-	}
806
-
807
-	/**
808
-	 * Tries to login the user with auth token header
809
-	 *
810
-	 * @param IRequest $request
811
-	 * @todo check remember me cookie
812
-	 * @return boolean
813
-	 */
814
-	public function tryTokenLogin(IRequest $request) {
815
-		$authHeader = $request->getHeader('Authorization');
816
-		if (strpos($authHeader, 'Bearer ') === false) {
817
-			// No auth header, let's try session id
818
-			try {
819
-				$token = $this->session->getId();
820
-			} catch (SessionNotAvailableException $ex) {
821
-				return false;
822
-			}
823
-		} else {
824
-			$token = substr($authHeader, 7);
825
-		}
826
-
827
-		if (!$this->loginWithToken($token)) {
828
-			return false;
829
-		}
830
-		if(!$this->validateToken($token)) {
831
-			return false;
832
-		}
833
-
834
-		// Set the session variable so we know this is an app password
835
-		$this->session->set('app_password', $token);
836
-
837
-		return true;
838
-	}
839
-
840
-	/**
841
-	 * perform login using the magic cookie (remember login)
842
-	 *
843
-	 * @param string $uid the username
844
-	 * @param string $currentToken
845
-	 * @param string $oldSessionId
846
-	 * @return bool
847
-	 */
848
-	public function loginWithCookie($uid, $currentToken, $oldSessionId) {
849
-		$this->session->regenerateId();
850
-		$this->manager->emit('\OC\User', 'preRememberedLogin', [$uid]);
851
-		$user = $this->manager->get($uid);
852
-		if (is_null($user)) {
853
-			// user does not exist
854
-			return false;
855
-		}
856
-
857
-		// get stored tokens
858
-		$tokens = $this->config->getUserKeys($uid, 'login_token');
859
-		// test cookies token against stored tokens
860
-		if (!in_array($currentToken, $tokens, true)) {
861
-			return false;
862
-		}
863
-		// replace successfully used token with a new one
864
-		$this->config->deleteUserValue($uid, 'login_token', $currentToken);
865
-		$newToken = $this->random->generate(32);
866
-		$this->config->setUserValue($uid, 'login_token', $newToken, $this->timeFactory->getTime());
867
-
868
-		try {
869
-			$sessionId = $this->session->getId();
870
-			$token = $this->tokenProvider->renewSessionToken($oldSessionId, $sessionId);
871
-		} catch (SessionNotAvailableException $ex) {
872
-			return false;
873
-		} catch (InvalidTokenException $ex) {
874
-			\OC::$server->getLogger()->warning('Renewing session token failed', ['app' => 'core']);
875
-			return false;
876
-		}
877
-
878
-		$this->setMagicInCookie($user->getUID(), $newToken);
879
-
880
-		//login
881
-		$this->setUser($user);
882
-		$this->setLoginName($token->getLoginName());
883
-		$this->setToken($token->getId());
884
-		$this->lockdownManager->setToken($token);
885
-		$user->updateLastLoginTimestamp();
886
-		$password = null;
887
-		try {
888
-			$password = $this->tokenProvider->getPassword($token, $sessionId);
889
-		} catch (PasswordlessTokenException $ex) {
890
-			// Ignore
891
-		}
892
-		$this->manager->emit('\OC\User', 'postRememberedLogin', [$user, $password]);
893
-		return true;
894
-	}
895
-
896
-	/**
897
-	 * @param IUser $user
898
-	 */
899
-	public function createRememberMeToken(IUser $user) {
900
-		$token = $this->random->generate(32);
901
-		$this->config->setUserValue($user->getUID(), 'login_token', $token, $this->timeFactory->getTime());
902
-		$this->setMagicInCookie($user->getUID(), $token);
903
-	}
904
-
905
-	/**
906
-	 * logout the user from the session
907
-	 */
908
-	public function logout() {
909
-		$user = $this->getUser();
910
-		$this->manager->emit('\OC\User', 'logout', [$user]);
911
-		if ($user !== null) {
912
-			try {
913
-				$this->tokenProvider->invalidateToken($this->session->getId());
914
-			} catch (SessionNotAvailableException $ex) {
915
-
916
-			}
917
-		}
918
-		$this->setUser(null);
919
-		$this->setLoginName(null);
920
-		$this->setToken(null);
921
-		$this->unsetMagicInCookie();
922
-		$this->session->clear();
923
-		$this->manager->emit('\OC\User', 'postLogout', [$user]);
924
-	}
925
-
926
-	/**
927
-	 * Set cookie value to use in next page load
928
-	 *
929
-	 * @param string $username username to be set
930
-	 * @param string $token
931
-	 */
932
-	public function setMagicInCookie($username, $token) {
933
-		$secureCookie = OC::$server->getRequest()->getServerProtocol() === 'https';
934
-		$webRoot = \OC::$WEBROOT;
935
-		if ($webRoot === '') {
936
-			$webRoot = '/';
937
-		}
938
-
939
-		$maxAge = $this->config->getSystemValue('remember_login_cookie_lifetime', 60 * 60 * 24 * 15);
940
-		\OC\Http\CookieHelper::setCookie(
941
-			'nc_username',
942
-			$username,
943
-			$maxAge,
944
-			$webRoot,
945
-			'',
946
-			$secureCookie,
947
-			true,
948
-			\OC\Http\CookieHelper::SAMESITE_LAX
949
-		);
950
-		\OC\Http\CookieHelper::setCookie(
951
-			'nc_token',
952
-			$token,
953
-			$maxAge,
954
-			$webRoot,
955
-			'',
956
-			$secureCookie,
957
-			true,
958
-			\OC\Http\CookieHelper::SAMESITE_LAX
959
-		);
960
-		try {
961
-			\OC\Http\CookieHelper::setCookie(
962
-				'nc_session_id',
963
-				$this->session->getId(),
964
-				$maxAge,
965
-				$webRoot,
966
-				'',
967
-				$secureCookie,
968
-				true,
969
-				\OC\Http\CookieHelper::SAMESITE_LAX
970
-			);
971
-		} catch (SessionNotAvailableException $ex) {
972
-			// ignore
973
-		}
974
-	}
975
-
976
-	/**
977
-	 * Remove cookie for "remember username"
978
-	 */
979
-	public function unsetMagicInCookie() {
980
-		//TODO: DI for cookies and IRequest
981
-		$secureCookie = OC::$server->getRequest()->getServerProtocol() === 'https';
982
-
983
-		unset($_COOKIE['nc_username']); //TODO: DI
984
-		unset($_COOKIE['nc_token']);
985
-		unset($_COOKIE['nc_session_id']);
986
-		setcookie('nc_username', '', $this->timeFactory->getTime() - 3600, OC::$WEBROOT, '', $secureCookie, true);
987
-		setcookie('nc_token', '', $this->timeFactory->getTime() - 3600, OC::$WEBROOT, '', $secureCookie, true);
988
-		setcookie('nc_session_id', '', $this->timeFactory->getTime() - 3600, OC::$WEBROOT, '', $secureCookie, true);
989
-		// old cookies might be stored under /webroot/ instead of /webroot
990
-		// and Firefox doesn't like it!
991
-		setcookie('nc_username', '', $this->timeFactory->getTime() - 3600, OC::$WEBROOT . '/', '', $secureCookie, true);
992
-		setcookie('nc_token', '', $this->timeFactory->getTime() - 3600, OC::$WEBROOT . '/', '', $secureCookie, true);
993
-		setcookie('nc_session_id', '', $this->timeFactory->getTime() - 3600, OC::$WEBROOT . '/', '', $secureCookie, true);
994
-	}
995
-
996
-	/**
997
-	 * Update password of the browser session token if there is one
998
-	 *
999
-	 * @param string $password
1000
-	 */
1001
-	public function updateSessionTokenPassword($password) {
1002
-		try {
1003
-			$sessionId = $this->session->getId();
1004
-			$token = $this->tokenProvider->getToken($sessionId);
1005
-			$this->tokenProvider->setPassword($token, $sessionId, $password);
1006
-		} catch (SessionNotAvailableException $ex) {
1007
-			// Nothing to do
1008
-		} catch (InvalidTokenException $ex) {
1009
-			// Nothing to do
1010
-		}
1011
-	}
1012
-
1013
-	public function updateTokens(string $uid, string $password) {
1014
-		$this->tokenProvider->updatePasswords($uid, $password);
1015
-	}
95
+    /** @var Manager|PublicEmitter $manager */
96
+    private $manager;
97
+
98
+    /** @var ISession $session */
99
+    private $session;
100
+
101
+    /** @var ITimeFactory */
102
+    private $timeFactory;
103
+
104
+    /** @var IProvider */
105
+    private $tokenProvider;
106
+
107
+    /** @var IConfig */
108
+    private $config;
109
+
110
+    /** @var User $activeUser */
111
+    protected $activeUser;
112
+
113
+    /** @var ISecureRandom */
114
+    private $random;
115
+
116
+    /** @var ILockdownManager  */
117
+    private $lockdownManager;
118
+
119
+    /** @var ILogger */
120
+    private $logger;
121
+    /** @var IEventDispatcher */
122
+    private $dispatcher;
123
+
124
+    /**
125
+     * @param Manager $manager
126
+     * @param ISession $session
127
+     * @param ITimeFactory $timeFactory
128
+     * @param IProvider $tokenProvider
129
+     * @param IConfig $config
130
+     * @param ISecureRandom $random
131
+     * @param ILockdownManager $lockdownManager
132
+     * @param ILogger $logger
133
+     */
134
+    public function __construct(Manager $manager,
135
+                                ISession $session,
136
+                                ITimeFactory $timeFactory,
137
+                                $tokenProvider,
138
+                                IConfig $config,
139
+                                ISecureRandom $random,
140
+                                ILockdownManager $lockdownManager,
141
+                                ILogger $logger,
142
+                                IEventDispatcher $dispatcher
143
+    ) {
144
+        $this->manager = $manager;
145
+        $this->session = $session;
146
+        $this->timeFactory = $timeFactory;
147
+        $this->tokenProvider = $tokenProvider;
148
+        $this->config = $config;
149
+        $this->random = $random;
150
+        $this->lockdownManager = $lockdownManager;
151
+        $this->logger = $logger;
152
+        $this->dispatcher = $dispatcher;
153
+    }
154
+
155
+    /**
156
+     * @param IProvider $provider
157
+     */
158
+    public function setTokenProvider(IProvider $provider) {
159
+        $this->tokenProvider = $provider;
160
+    }
161
+
162
+    /**
163
+     * @param string $scope
164
+     * @param string $method
165
+     * @param callable $callback
166
+     */
167
+    public function listen($scope, $method, callable $callback) {
168
+        $this->manager->listen($scope, $method, $callback);
169
+    }
170
+
171
+    /**
172
+     * @param string $scope optional
173
+     * @param string $method optional
174
+     * @param callable $callback optional
175
+     */
176
+    public function removeListener($scope = null, $method = null, callable $callback = null) {
177
+        $this->manager->removeListener($scope, $method, $callback);
178
+    }
179
+
180
+    /**
181
+     * get the manager object
182
+     *
183
+     * @return Manager|PublicEmitter
184
+     */
185
+    public function getManager() {
186
+        return $this->manager;
187
+    }
188
+
189
+    /**
190
+     * get the session object
191
+     *
192
+     * @return ISession
193
+     */
194
+    public function getSession() {
195
+        return $this->session;
196
+    }
197
+
198
+    /**
199
+     * set the session object
200
+     *
201
+     * @param ISession $session
202
+     */
203
+    public function setSession(ISession $session) {
204
+        if ($this->session instanceof ISession) {
205
+            $this->session->close();
206
+        }
207
+        $this->session = $session;
208
+        $this->activeUser = null;
209
+    }
210
+
211
+    /**
212
+     * set the currently active user
213
+     *
214
+     * @param IUser|null $user
215
+     */
216
+    public function setUser($user) {
217
+        if (is_null($user)) {
218
+            $this->session->remove('user_id');
219
+        } else {
220
+            $this->session->set('user_id', $user->getUID());
221
+        }
222
+        $this->activeUser = $user;
223
+    }
224
+
225
+    /**
226
+     * get the current active user
227
+     *
228
+     * @return IUser|null Current user, otherwise null
229
+     */
230
+    public function getUser() {
231
+        // FIXME: This is a quick'n dirty work-around for the incognito mode as
232
+        // described at https://github.com/owncloud/core/pull/12912#issuecomment-67391155
233
+        if (OC_User::isIncognitoMode()) {
234
+            return null;
235
+        }
236
+        if (is_null($this->activeUser)) {
237
+            $uid = $this->session->get('user_id');
238
+            if (is_null($uid)) {
239
+                return null;
240
+            }
241
+            $this->activeUser = $this->manager->get($uid);
242
+            if (is_null($this->activeUser)) {
243
+                return null;
244
+            }
245
+            $this->validateSession();
246
+        }
247
+        return $this->activeUser;
248
+    }
249
+
250
+    /**
251
+     * Validate whether the current session is valid
252
+     *
253
+     * - For token-authenticated clients, the token validity is checked
254
+     * - For browsers, the session token validity is checked
255
+     */
256
+    protected function validateSession() {
257
+        $token = null;
258
+        $appPassword = $this->session->get('app_password');
259
+
260
+        if (is_null($appPassword)) {
261
+            try {
262
+                $token = $this->session->getId();
263
+            } catch (SessionNotAvailableException $ex) {
264
+                return;
265
+            }
266
+        } else {
267
+            $token = $appPassword;
268
+        }
269
+
270
+        if (!$this->validateToken($token)) {
271
+            // Session was invalidated
272
+            $this->logout();
273
+        }
274
+    }
275
+
276
+    /**
277
+     * Checks whether the user is logged in
278
+     *
279
+     * @return bool if logged in
280
+     */
281
+    public function isLoggedIn() {
282
+        $user = $this->getUser();
283
+        if (is_null($user)) {
284
+            return false;
285
+        }
286
+
287
+        return $user->isEnabled();
288
+    }
289
+
290
+    /**
291
+     * set the login name
292
+     *
293
+     * @param string|null $loginName for the logged in user
294
+     */
295
+    public function setLoginName($loginName) {
296
+        if (is_null($loginName)) {
297
+            $this->session->remove('loginname');
298
+        } else {
299
+            $this->session->set('loginname', $loginName);
300
+        }
301
+    }
302
+
303
+    /**
304
+     * get the login name of the current user
305
+     *
306
+     * @return string
307
+     */
308
+    public function getLoginName() {
309
+        if ($this->activeUser) {
310
+            return $this->session->get('loginname');
311
+        }
312
+
313
+        $uid = $this->session->get('user_id');
314
+        if ($uid) {
315
+            $this->activeUser = $this->manager->get($uid);
316
+            return $this->session->get('loginname');
317
+        }
318
+
319
+        return null;
320
+    }
321
+
322
+    /**
323
+     * @return null|string
324
+     */
325
+    public function getImpersonatingUserID(): ?string {
326
+
327
+        return $this->session->get('oldUserId');
328
+
329
+    }
330
+
331
+    public function setImpersonatingUserID(bool $useCurrentUser = true): void {
332
+        if ($useCurrentUser === false) {
333
+            $this->session->remove('oldUserId');
334
+            return;
335
+        }
336
+
337
+        $currentUser = $this->getUser();
338
+
339
+        if ($currentUser === null) {
340
+            throw new \OC\User\NoUserException();
341
+        }
342
+        $this->session->set('oldUserId', $currentUser->getUID());
343
+
344
+    }
345
+    /**
346
+     * set the token id
347
+     *
348
+     * @param int|null $token that was used to log in
349
+     */
350
+    protected function setToken($token) {
351
+        if ($token === null) {
352
+            $this->session->remove('token-id');
353
+        } else {
354
+            $this->session->set('token-id', $token);
355
+        }
356
+    }
357
+
358
+    /**
359
+     * try to log in with the provided credentials
360
+     *
361
+     * @param string $uid
362
+     * @param string $password
363
+     * @return boolean|null
364
+     * @throws LoginException
365
+     */
366
+    public function login($uid, $password) {
367
+        $this->session->regenerateId();
368
+        if ($this->validateToken($password, $uid)) {
369
+            return $this->loginWithToken($password);
370
+        }
371
+        return $this->loginWithPassword($uid, $password);
372
+    }
373
+
374
+    /**
375
+     * @param IUser $user
376
+     * @param array $loginDetails
377
+     * @param bool $regenerateSessionId
378
+     * @return true returns true if login successful or an exception otherwise
379
+     * @throws LoginException
380
+     */
381
+    public function completeLogin(IUser $user, array $loginDetails, $regenerateSessionId = true) {
382
+        if (!$user->isEnabled()) {
383
+            // disabled users can not log in
384
+            // injecting l10n does not work - there is a circular dependency between session and \OCP\L10N\IFactory
385
+            $message = \OC::$server->getL10N('lib')->t('User disabled');
386
+            throw new LoginException($message);
387
+        }
388
+
389
+        if($regenerateSessionId) {
390
+            $this->session->regenerateId();
391
+        }
392
+
393
+        $this->setUser($user);
394
+        $this->setLoginName($loginDetails['loginName']);
395
+
396
+        $isToken = isset($loginDetails['token']) && $loginDetails['token'] instanceof IToken;
397
+        if ($isToken) {
398
+            $this->setToken($loginDetails['token']->getId());
399
+            $this->lockdownManager->setToken($loginDetails['token']);
400
+            $firstTimeLogin = false;
401
+        } else {
402
+            $this->setToken(null);
403
+            $firstTimeLogin = $user->updateLastLoginTimestamp();
404
+        }
405
+
406
+        $this->dispatcher->dispatchTyped(new PostLoginEvent(
407
+            $user,
408
+            $loginDetails['password'],
409
+            $isToken
410
+        ));
411
+        $this->manager->emit('\OC\User', 'postLogin', [
412
+            $user,
413
+            $loginDetails['password'],
414
+            $isToken,
415
+        ]);
416
+        if($this->isLoggedIn()) {
417
+            $this->prepareUserLogin($firstTimeLogin, $regenerateSessionId);
418
+            return true;
419
+        }
420
+
421
+        $message = \OC::$server->getL10N('lib')->t('Login canceled by app');
422
+        throw new LoginException($message);
423
+    }
424
+
425
+    /**
426
+     * Tries to log in a client
427
+     *
428
+     * Checks token auth enforced
429
+     * Checks 2FA enabled
430
+     *
431
+     * @param string $user
432
+     * @param string $password
433
+     * @param IRequest $request
434
+     * @param OC\Security\Bruteforce\Throttler $throttler
435
+     * @throws LoginException
436
+     * @throws PasswordLoginForbiddenException
437
+     * @return boolean
438
+     */
439
+    public function logClientIn($user,
440
+                                $password,
441
+                                IRequest $request,
442
+                                OC\Security\Bruteforce\Throttler $throttler) {
443
+        $currentDelay = $throttler->sleepDelay($request->getRemoteAddress(), 'login');
444
+
445
+        if ($this->manager instanceof PublicEmitter) {
446
+            $this->manager->emit('\OC\User', 'preLogin', [$user, $password]);
447
+        }
448
+
449
+        try {
450
+            $isTokenPassword = $this->isTokenPassword($password);
451
+        } catch (ExpiredTokenException $e) {
452
+            // Just return on an expired token no need to check further or record a failed login
453
+            return false;
454
+        }
455
+
456
+        if (!$isTokenPassword && $this->isTokenAuthEnforced()) {
457
+            throw new PasswordLoginForbiddenException();
458
+        }
459
+        if (!$isTokenPassword && $this->isTwoFactorEnforced($user)) {
460
+            throw new PasswordLoginForbiddenException();
461
+        }
462
+
463
+        // Try to login with this username and password
464
+        if (!$this->login($user, $password) ) {
465
+
466
+            // Failed, maybe the user used their email address
467
+            $users = $this->manager->getByEmail($user);
468
+            if (!(\count($users) === 1 && $this->login($users[0]->getUID(), $password))) {
469
+
470
+                $this->logger->warning('Login failed: \'' . $user . '\' (Remote IP: \'' . \OC::$server->getRequest()->getRemoteAddress() . '\')', ['app' => 'core']);
471
+
472
+                $throttler->registerAttempt('login', $request->getRemoteAddress(), ['user' => $user]);
473
+
474
+                $this->dispatcher->dispatchTyped(new OC\Authentication\Events\LoginFailed($user));
475
+
476
+                if ($currentDelay === 0) {
477
+                    $throttler->sleepDelay($request->getRemoteAddress(), 'login');
478
+                }
479
+                return false;
480
+            }
481
+        }
482
+
483
+        if ($isTokenPassword) {
484
+            $this->session->set('app_password', $password);
485
+        } else if($this->supportsCookies($request)) {
486
+            // Password login, but cookies supported -> create (browser) session token
487
+            $this->createSessionToken($request, $this->getUser()->getUID(), $user, $password);
488
+        }
489
+
490
+        return true;
491
+    }
492
+
493
+    protected function supportsCookies(IRequest $request) {
494
+        if (!is_null($request->getCookie('cookie_test'))) {
495
+            return true;
496
+        }
497
+        setcookie('cookie_test', 'test', $this->timeFactory->getTime() + 3600);
498
+        return false;
499
+    }
500
+
501
+    private function isTokenAuthEnforced() {
502
+        return $this->config->getSystemValue('token_auth_enforced', false);
503
+    }
504
+
505
+    protected function isTwoFactorEnforced($username) {
506
+        Util::emitHook(
507
+            '\OCA\Files_Sharing\API\Server2Server',
508
+            'preLoginNameUsedAsUserName',
509
+            ['uid' => &$username]
510
+        );
511
+        $user = $this->manager->get($username);
512
+        if (is_null($user)) {
513
+            $users = $this->manager->getByEmail($username);
514
+            if (empty($users)) {
515
+                return false;
516
+            }
517
+            if (count($users) !== 1) {
518
+                return true;
519
+            }
520
+            $user = $users[0];
521
+        }
522
+        // DI not possible due to cyclic dependencies :'-/
523
+        return OC::$server->getTwoFactorAuthManager()->isTwoFactorAuthenticated($user);
524
+    }
525
+
526
+    /**
527
+     * Check if the given 'password' is actually a device token
528
+     *
529
+     * @param string $password
530
+     * @return boolean
531
+     * @throws ExpiredTokenException
532
+     */
533
+    public function isTokenPassword($password) {
534
+        try {
535
+            $this->tokenProvider->getToken($password);
536
+            return true;
537
+        } catch (ExpiredTokenException $e) {
538
+            throw $e;
539
+        } catch (InvalidTokenException $ex) {
540
+            return false;
541
+        }
542
+    }
543
+
544
+    protected function prepareUserLogin($firstTimeLogin, $refreshCsrfToken = true) {
545
+        if ($refreshCsrfToken) {
546
+            // TODO: mock/inject/use non-static
547
+            // Refresh the token
548
+            \OC::$server->getCsrfTokenManager()->refreshToken();
549
+        }
550
+
551
+        //we need to pass the user name, which may differ from login name
552
+        $user = $this->getUser()->getUID();
553
+        OC_Util::setupFS($user);
554
+
555
+        if ($firstTimeLogin) {
556
+            // TODO: lock necessary?
557
+            //trigger creation of user home and /files folder
558
+            $userFolder = \OC::$server->getUserFolder($user);
559
+
560
+            try {
561
+                // copy skeleton
562
+                \OC_Util::copySkeleton($user, $userFolder);
563
+            } catch (NotPermittedException $ex) {
564
+                // read only uses
565
+            }
566
+
567
+            // trigger any other initialization
568
+            \OC::$server->getEventDispatcher()->dispatch(IUser::class . '::firstLogin', new GenericEvent($this->getUser()));
569
+        }
570
+    }
571
+
572
+    /**
573
+     * Tries to login the user with HTTP Basic Authentication
574
+     *
575
+     * @todo do not allow basic auth if the user is 2FA enforced
576
+     * @param IRequest $request
577
+     * @param OC\Security\Bruteforce\Throttler $throttler
578
+     * @return boolean if the login was successful
579
+     */
580
+    public function tryBasicAuthLogin(IRequest $request,
581
+                                        OC\Security\Bruteforce\Throttler $throttler) {
582
+        if (!empty($request->server['PHP_AUTH_USER']) && !empty($request->server['PHP_AUTH_PW'])) {
583
+            try {
584
+                if ($this->logClientIn($request->server['PHP_AUTH_USER'], $request->server['PHP_AUTH_PW'], $request, $throttler)) {
585
+                    /**
586
+                     * Add DAV authenticated. This should in an ideal world not be
587
+                     * necessary but the iOS App reads cookies from anywhere instead
588
+                     * only the DAV endpoint.
589
+                     * This makes sure that the cookies will be valid for the whole scope
590
+                     * @see https://github.com/owncloud/core/issues/22893
591
+                     */
592
+                    $this->session->set(
593
+                        Auth::DAV_AUTHENTICATED, $this->getUser()->getUID()
594
+                    );
595
+
596
+                    // Set the last-password-confirm session to make the sudo mode work
597
+                        $this->session->set('last-password-confirm', $this->timeFactory->getTime());
598
+
599
+                    return true;
600
+                }
601
+            } catch (PasswordLoginForbiddenException $ex) {
602
+                // Nothing to do
603
+            }
604
+        }
605
+        return false;
606
+    }
607
+
608
+    /**
609
+     * Log an user in via login name and password
610
+     *
611
+     * @param string $uid
612
+     * @param string $password
613
+     * @return boolean
614
+     * @throws LoginException if an app canceld the login process or the user is not enabled
615
+     */
616
+    private function loginWithPassword($uid, $password) {
617
+        $user = $this->manager->checkPasswordNoLogging($uid, $password);
618
+        if ($user === false) {
619
+            // Password check failed
620
+            return false;
621
+        }
622
+
623
+        return $this->completeLogin($user, ['loginName' => $uid, 'password' => $password], false);
624
+    }
625
+
626
+    /**
627
+     * Log an user in with a given token (id)
628
+     *
629
+     * @param string $token
630
+     * @return boolean
631
+     * @throws LoginException if an app canceled the login process or the user is not enabled
632
+     */
633
+    private function loginWithToken($token) {
634
+        try {
635
+            $dbToken = $this->tokenProvider->getToken($token);
636
+        } catch (InvalidTokenException $ex) {
637
+            return false;
638
+        }
639
+        $uid = $dbToken->getUID();
640
+
641
+        // When logging in with token, the password must be decrypted first before passing to login hook
642
+        $password = '';
643
+        try {
644
+            $password = $this->tokenProvider->getPassword($dbToken, $token);
645
+        } catch (PasswordlessTokenException $ex) {
646
+            // Ignore and use empty string instead
647
+        }
648
+
649
+        $this->manager->emit('\OC\User', 'preLogin', [$uid, $password]);
650
+
651
+        $user = $this->manager->get($uid);
652
+        if (is_null($user)) {
653
+            // user does not exist
654
+            return false;
655
+        }
656
+
657
+        return $this->completeLogin(
658
+            $user,
659
+            [
660
+                'loginName' => $dbToken->getLoginName(),
661
+                'password' => $password,
662
+                'token' => $dbToken
663
+            ],
664
+            false);
665
+    }
666
+
667
+    /**
668
+     * Create a new session token for the given user credentials
669
+     *
670
+     * @param IRequest $request
671
+     * @param string $uid user UID
672
+     * @param string $loginName login name
673
+     * @param string $password
674
+     * @param int $remember
675
+     * @return boolean
676
+     */
677
+    public function createSessionToken(IRequest $request, $uid, $loginName, $password = null, $remember = IToken::DO_NOT_REMEMBER) {
678
+        if (is_null($this->manager->get($uid))) {
679
+            // User does not exist
680
+            return false;
681
+        }
682
+        $name = isset($request->server['HTTP_USER_AGENT']) ? $request->server['HTTP_USER_AGENT'] : 'unknown browser';
683
+        try {
684
+            $sessionId = $this->session->getId();
685
+            $pwd = $this->getPassword($password);
686
+            // Make sure the current sessionId has no leftover tokens
687
+            $this->tokenProvider->invalidateToken($sessionId);
688
+            $this->tokenProvider->generateToken($sessionId, $uid, $loginName, $pwd, $name, IToken::TEMPORARY_TOKEN, $remember);
689
+            return true;
690
+        } catch (SessionNotAvailableException $ex) {
691
+            // This can happen with OCC, where a memory session is used
692
+            // if a memory session is used, we shouldn't create a session token anyway
693
+            return false;
694
+        }
695
+    }
696
+
697
+    /**
698
+     * Checks if the given password is a token.
699
+     * If yes, the password is extracted from the token.
700
+     * If no, the same password is returned.
701
+     *
702
+     * @param string $password either the login password or a device token
703
+     * @return string|null the password or null if none was set in the token
704
+     */
705
+    private function getPassword($password) {
706
+        if (is_null($password)) {
707
+            // This is surely no token ;-)
708
+            return null;
709
+        }
710
+        try {
711
+            $token = $this->tokenProvider->getToken($password);
712
+            try {
713
+                return $this->tokenProvider->getPassword($token, $password);
714
+            } catch (PasswordlessTokenException $ex) {
715
+                return null;
716
+            }
717
+        } catch (InvalidTokenException $ex) {
718
+            return $password;
719
+        }
720
+    }
721
+
722
+    /**
723
+     * @param IToken $dbToken
724
+     * @param string $token
725
+     * @return boolean
726
+     */
727
+    private function checkTokenCredentials(IToken $dbToken, $token) {
728
+        // Check whether login credentials are still valid and the user was not disabled
729
+        // This check is performed each 5 minutes
730
+        $lastCheck = $dbToken->getLastCheck() ? : 0;
731
+        $now = $this->timeFactory->getTime();
732
+        if ($lastCheck > ($now - 60 * 5)) {
733
+            // Checked performed recently, nothing to do now
734
+            return true;
735
+        }
736
+
737
+        try {
738
+            $pwd = $this->tokenProvider->getPassword($dbToken, $token);
739
+        } catch (InvalidTokenException $ex) {
740
+            // An invalid token password was used -> log user out
741
+            return false;
742
+        } catch (PasswordlessTokenException $ex) {
743
+            // Token has no password
744
+
745
+            if (!is_null($this->activeUser) && !$this->activeUser->isEnabled()) {
746
+                $this->tokenProvider->invalidateToken($token);
747
+                return false;
748
+            }
749
+
750
+            $dbToken->setLastCheck($now);
751
+            return true;
752
+        }
753
+
754
+        // Invalidate token if the user is no longer active
755
+        if (!is_null($this->activeUser) && !$this->activeUser->isEnabled()) {
756
+            $this->tokenProvider->invalidateToken($token);
757
+            return false;
758
+        }
759
+
760
+        // If the token password is no longer valid mark it as such
761
+        if ($this->manager->checkPassword($dbToken->getLoginName(), $pwd) === false) {
762
+            $this->tokenProvider->markPasswordInvalid($dbToken, $token);
763
+            // User is logged out
764
+            return false;
765
+        }
766
+
767
+        $dbToken->setLastCheck($now);
768
+        return true;
769
+    }
770
+
771
+    /**
772
+     * Check if the given token exists and performs password/user-enabled checks
773
+     *
774
+     * Invalidates the token if checks fail
775
+     *
776
+     * @param string $token
777
+     * @param string $user login name
778
+     * @return boolean
779
+     */
780
+    private function validateToken($token, $user = null) {
781
+        try {
782
+            $dbToken = $this->tokenProvider->getToken($token);
783
+        } catch (InvalidTokenException $ex) {
784
+            return false;
785
+        }
786
+
787
+        // Check if login names match
788
+        if (!is_null($user) && $dbToken->getLoginName() !== $user) {
789
+            // TODO: this makes it imposssible to use different login names on browser and client
790
+            // e.g. login by e-mail '[email protected]' on browser for generating the token will not
791
+            //      allow to use the client token with the login name 'user'.
792
+            return false;
793
+        }
794
+
795
+        if (!$this->checkTokenCredentials($dbToken, $token)) {
796
+            return false;
797
+        }
798
+
799
+        // Update token scope
800
+        $this->lockdownManager->setToken($dbToken);
801
+
802
+        $this->tokenProvider->updateTokenActivity($dbToken);
803
+
804
+        return true;
805
+    }
806
+
807
+    /**
808
+     * Tries to login the user with auth token header
809
+     *
810
+     * @param IRequest $request
811
+     * @todo check remember me cookie
812
+     * @return boolean
813
+     */
814
+    public function tryTokenLogin(IRequest $request) {
815
+        $authHeader = $request->getHeader('Authorization');
816
+        if (strpos($authHeader, 'Bearer ') === false) {
817
+            // No auth header, let's try session id
818
+            try {
819
+                $token = $this->session->getId();
820
+            } catch (SessionNotAvailableException $ex) {
821
+                return false;
822
+            }
823
+        } else {
824
+            $token = substr($authHeader, 7);
825
+        }
826
+
827
+        if (!$this->loginWithToken($token)) {
828
+            return false;
829
+        }
830
+        if(!$this->validateToken($token)) {
831
+            return false;
832
+        }
833
+
834
+        // Set the session variable so we know this is an app password
835
+        $this->session->set('app_password', $token);
836
+
837
+        return true;
838
+    }
839
+
840
+    /**
841
+     * perform login using the magic cookie (remember login)
842
+     *
843
+     * @param string $uid the username
844
+     * @param string $currentToken
845
+     * @param string $oldSessionId
846
+     * @return bool
847
+     */
848
+    public function loginWithCookie($uid, $currentToken, $oldSessionId) {
849
+        $this->session->regenerateId();
850
+        $this->manager->emit('\OC\User', 'preRememberedLogin', [$uid]);
851
+        $user = $this->manager->get($uid);
852
+        if (is_null($user)) {
853
+            // user does not exist
854
+            return false;
855
+        }
856
+
857
+        // get stored tokens
858
+        $tokens = $this->config->getUserKeys($uid, 'login_token');
859
+        // test cookies token against stored tokens
860
+        if (!in_array($currentToken, $tokens, true)) {
861
+            return false;
862
+        }
863
+        // replace successfully used token with a new one
864
+        $this->config->deleteUserValue($uid, 'login_token', $currentToken);
865
+        $newToken = $this->random->generate(32);
866
+        $this->config->setUserValue($uid, 'login_token', $newToken, $this->timeFactory->getTime());
867
+
868
+        try {
869
+            $sessionId = $this->session->getId();
870
+            $token = $this->tokenProvider->renewSessionToken($oldSessionId, $sessionId);
871
+        } catch (SessionNotAvailableException $ex) {
872
+            return false;
873
+        } catch (InvalidTokenException $ex) {
874
+            \OC::$server->getLogger()->warning('Renewing session token failed', ['app' => 'core']);
875
+            return false;
876
+        }
877
+
878
+        $this->setMagicInCookie($user->getUID(), $newToken);
879
+
880
+        //login
881
+        $this->setUser($user);
882
+        $this->setLoginName($token->getLoginName());
883
+        $this->setToken($token->getId());
884
+        $this->lockdownManager->setToken($token);
885
+        $user->updateLastLoginTimestamp();
886
+        $password = null;
887
+        try {
888
+            $password = $this->tokenProvider->getPassword($token, $sessionId);
889
+        } catch (PasswordlessTokenException $ex) {
890
+            // Ignore
891
+        }
892
+        $this->manager->emit('\OC\User', 'postRememberedLogin', [$user, $password]);
893
+        return true;
894
+    }
895
+
896
+    /**
897
+     * @param IUser $user
898
+     */
899
+    public function createRememberMeToken(IUser $user) {
900
+        $token = $this->random->generate(32);
901
+        $this->config->setUserValue($user->getUID(), 'login_token', $token, $this->timeFactory->getTime());
902
+        $this->setMagicInCookie($user->getUID(), $token);
903
+    }
904
+
905
+    /**
906
+     * logout the user from the session
907
+     */
908
+    public function logout() {
909
+        $user = $this->getUser();
910
+        $this->manager->emit('\OC\User', 'logout', [$user]);
911
+        if ($user !== null) {
912
+            try {
913
+                $this->tokenProvider->invalidateToken($this->session->getId());
914
+            } catch (SessionNotAvailableException $ex) {
915
+
916
+            }
917
+        }
918
+        $this->setUser(null);
919
+        $this->setLoginName(null);
920
+        $this->setToken(null);
921
+        $this->unsetMagicInCookie();
922
+        $this->session->clear();
923
+        $this->manager->emit('\OC\User', 'postLogout', [$user]);
924
+    }
925
+
926
+    /**
927
+     * Set cookie value to use in next page load
928
+     *
929
+     * @param string $username username to be set
930
+     * @param string $token
931
+     */
932
+    public function setMagicInCookie($username, $token) {
933
+        $secureCookie = OC::$server->getRequest()->getServerProtocol() === 'https';
934
+        $webRoot = \OC::$WEBROOT;
935
+        if ($webRoot === '') {
936
+            $webRoot = '/';
937
+        }
938
+
939
+        $maxAge = $this->config->getSystemValue('remember_login_cookie_lifetime', 60 * 60 * 24 * 15);
940
+        \OC\Http\CookieHelper::setCookie(
941
+            'nc_username',
942
+            $username,
943
+            $maxAge,
944
+            $webRoot,
945
+            '',
946
+            $secureCookie,
947
+            true,
948
+            \OC\Http\CookieHelper::SAMESITE_LAX
949
+        );
950
+        \OC\Http\CookieHelper::setCookie(
951
+            'nc_token',
952
+            $token,
953
+            $maxAge,
954
+            $webRoot,
955
+            '',
956
+            $secureCookie,
957
+            true,
958
+            \OC\Http\CookieHelper::SAMESITE_LAX
959
+        );
960
+        try {
961
+            \OC\Http\CookieHelper::setCookie(
962
+                'nc_session_id',
963
+                $this->session->getId(),
964
+                $maxAge,
965
+                $webRoot,
966
+                '',
967
+                $secureCookie,
968
+                true,
969
+                \OC\Http\CookieHelper::SAMESITE_LAX
970
+            );
971
+        } catch (SessionNotAvailableException $ex) {
972
+            // ignore
973
+        }
974
+    }
975
+
976
+    /**
977
+     * Remove cookie for "remember username"
978
+     */
979
+    public function unsetMagicInCookie() {
980
+        //TODO: DI for cookies and IRequest
981
+        $secureCookie = OC::$server->getRequest()->getServerProtocol() === 'https';
982
+
983
+        unset($_COOKIE['nc_username']); //TODO: DI
984
+        unset($_COOKIE['nc_token']);
985
+        unset($_COOKIE['nc_session_id']);
986
+        setcookie('nc_username', '', $this->timeFactory->getTime() - 3600, OC::$WEBROOT, '', $secureCookie, true);
987
+        setcookie('nc_token', '', $this->timeFactory->getTime() - 3600, OC::$WEBROOT, '', $secureCookie, true);
988
+        setcookie('nc_session_id', '', $this->timeFactory->getTime() - 3600, OC::$WEBROOT, '', $secureCookie, true);
989
+        // old cookies might be stored under /webroot/ instead of /webroot
990
+        // and Firefox doesn't like it!
991
+        setcookie('nc_username', '', $this->timeFactory->getTime() - 3600, OC::$WEBROOT . '/', '', $secureCookie, true);
992
+        setcookie('nc_token', '', $this->timeFactory->getTime() - 3600, OC::$WEBROOT . '/', '', $secureCookie, true);
993
+        setcookie('nc_session_id', '', $this->timeFactory->getTime() - 3600, OC::$WEBROOT . '/', '', $secureCookie, true);
994
+    }
995
+
996
+    /**
997
+     * Update password of the browser session token if there is one
998
+     *
999
+     * @param string $password
1000
+     */
1001
+    public function updateSessionTokenPassword($password) {
1002
+        try {
1003
+            $sessionId = $this->session->getId();
1004
+            $token = $this->tokenProvider->getToken($sessionId);
1005
+            $this->tokenProvider->setPassword($token, $sessionId, $password);
1006
+        } catch (SessionNotAvailableException $ex) {
1007
+            // Nothing to do
1008
+        } catch (InvalidTokenException $ex) {
1009
+            // Nothing to do
1010
+        }
1011
+    }
1012
+
1013
+    public function updateTokens(string $uid, string $password) {
1014
+        $this->tokenProvider->updatePasswords($uid, $password);
1015
+    }
1016 1016
 
1017 1017
 
1018 1018
 }
Please login to merge, or discard this patch.
Spacing   +11 added lines, -11 removed lines patch added patch discarded remove patch
@@ -386,7 +386,7 @@  discard block
 block discarded – undo
386 386
 			throw new LoginException($message);
387 387
 		}
388 388
 
389
-		if($regenerateSessionId) {
389
+		if ($regenerateSessionId) {
390 390
 			$this->session->regenerateId();
391 391
 		}
392 392
 
@@ -413,7 +413,7 @@  discard block
 block discarded – undo
413 413
 			$loginDetails['password'],
414 414
 			$isToken,
415 415
 		]);
416
-		if($this->isLoggedIn()) {
416
+		if ($this->isLoggedIn()) {
417 417
 			$this->prepareUserLogin($firstTimeLogin, $regenerateSessionId);
418 418
 			return true;
419 419
 		}
@@ -461,13 +461,13 @@  discard block
 block discarded – undo
461 461
 		}
462 462
 
463 463
 		// Try to login with this username and password
464
-		if (!$this->login($user, $password) ) {
464
+		if (!$this->login($user, $password)) {
465 465
 
466 466
 			// Failed, maybe the user used their email address
467 467
 			$users = $this->manager->getByEmail($user);
468 468
 			if (!(\count($users) === 1 && $this->login($users[0]->getUID(), $password))) {
469 469
 
470
-				$this->logger->warning('Login failed: \'' . $user . '\' (Remote IP: \'' . \OC::$server->getRequest()->getRemoteAddress() . '\')', ['app' => 'core']);
470
+				$this->logger->warning('Login failed: \''.$user.'\' (Remote IP: \''.\OC::$server->getRequest()->getRemoteAddress().'\')', ['app' => 'core']);
471 471
 
472 472
 				$throttler->registerAttempt('login', $request->getRemoteAddress(), ['user' => $user]);
473 473
 
@@ -482,7 +482,7 @@  discard block
 block discarded – undo
482 482
 
483 483
 		if ($isTokenPassword) {
484 484
 			$this->session->set('app_password', $password);
485
-		} else if($this->supportsCookies($request)) {
485
+		} else if ($this->supportsCookies($request)) {
486 486
 			// Password login, but cookies supported -> create (browser) session token
487 487
 			$this->createSessionToken($request, $this->getUser()->getUID(), $user, $password);
488 488
 		}
@@ -565,7 +565,7 @@  discard block
 block discarded – undo
565 565
 			}
566 566
 
567 567
 			// trigger any other initialization
568
-			\OC::$server->getEventDispatcher()->dispatch(IUser::class . '::firstLogin', new GenericEvent($this->getUser()));
568
+			\OC::$server->getEventDispatcher()->dispatch(IUser::class.'::firstLogin', new GenericEvent($this->getUser()));
569 569
 		}
570 570
 	}
571 571
 
@@ -727,7 +727,7 @@  discard block
 block discarded – undo
727 727
 	private function checkTokenCredentials(IToken $dbToken, $token) {
728 728
 		// Check whether login credentials are still valid and the user was not disabled
729 729
 		// This check is performed each 5 minutes
730
-		$lastCheck = $dbToken->getLastCheck() ? : 0;
730
+		$lastCheck = $dbToken->getLastCheck() ?: 0;
731 731
 		$now = $this->timeFactory->getTime();
732 732
 		if ($lastCheck > ($now - 60 * 5)) {
733 733
 			// Checked performed recently, nothing to do now
@@ -827,7 +827,7 @@  discard block
 block discarded – undo
827 827
 		if (!$this->loginWithToken($token)) {
828 828
 			return false;
829 829
 		}
830
-		if(!$this->validateToken($token)) {
830
+		if (!$this->validateToken($token)) {
831 831
 			return false;
832 832
 		}
833 833
 
@@ -988,9 +988,9 @@  discard block
 block discarded – undo
988 988
 		setcookie('nc_session_id', '', $this->timeFactory->getTime() - 3600, OC::$WEBROOT, '', $secureCookie, true);
989 989
 		// old cookies might be stored under /webroot/ instead of /webroot
990 990
 		// and Firefox doesn't like it!
991
-		setcookie('nc_username', '', $this->timeFactory->getTime() - 3600, OC::$WEBROOT . '/', '', $secureCookie, true);
992
-		setcookie('nc_token', '', $this->timeFactory->getTime() - 3600, OC::$WEBROOT . '/', '', $secureCookie, true);
993
-		setcookie('nc_session_id', '', $this->timeFactory->getTime() - 3600, OC::$WEBROOT . '/', '', $secureCookie, true);
991
+		setcookie('nc_username', '', $this->timeFactory->getTime() - 3600, OC::$WEBROOT.'/', '', $secureCookie, true);
992
+		setcookie('nc_token', '', $this->timeFactory->getTime() - 3600, OC::$WEBROOT.'/', '', $secureCookie, true);
993
+		setcookie('nc_session_id', '', $this->timeFactory->getTime() - 3600, OC::$WEBROOT.'/', '', $secureCookie, true);
994 994
 	}
995 995
 
996 996
 	/**
Please login to merge, or discard this patch.