Completed
Pull Request — master (#8716)
by Julius
53:20 queued 33:25
created
lib/private/Server.php 1 patch
Indentation   +1834 added lines, -1834 removed lines patch added patch discarded remove patch
@@ -150,1843 +150,1843 @@
 block discarded – undo
150 150
  * TODO: hookup all manager classes
151 151
  */
152 152
 class Server extends ServerContainer implements IServerContainer {
153
-	/** @var string */
154
-	private $webRoot;
155
-
156
-	/**
157
-	 * @param string $webRoot
158
-	 * @param \OC\Config $config
159
-	 */
160
-	public function __construct($webRoot, \OC\Config $config) {
161
-		parent::__construct();
162
-		$this->webRoot = $webRoot;
163
-
164
-		$this->registerService(\OCP\IServerContainer::class, function (IServerContainer $c) {
165
-			return $c;
166
-		});
167
-
168
-		$this->registerAlias(\OCP\Calendar\IManager::class, \OC\Calendar\Manager::class);
169
-		$this->registerAlias('CalendarManager', \OC\Calendar\Manager::class);
170
-
171
-		$this->registerAlias(\OCP\Contacts\IManager::class, \OC\ContactsManager::class);
172
-		$this->registerAlias('ContactsManager', \OCP\Contacts\IManager::class);
173
-
174
-		$this->registerAlias(IActionFactory::class, ActionFactory::class);
175
-
176
-
177
-		$this->registerService(\OCP\IPreview::class, function (Server $c) {
178
-			return new PreviewManager(
179
-				$c->getConfig(),
180
-				$c->getRootFolder(),
181
-				$c->getAppDataDir('preview'),
182
-				$c->getEventDispatcher(),
183
-				$c->getSession()->get('user_id')
184
-			);
185
-		});
186
-		$this->registerAlias('PreviewManager', \OCP\IPreview::class);
187
-
188
-		$this->registerService(\OC\Preview\Watcher::class, function (Server $c) {
189
-			return new \OC\Preview\Watcher(
190
-				$c->getAppDataDir('preview')
191
-			);
192
-		});
193
-
194
-		$this->registerService('EncryptionManager', function (Server $c) {
195
-			$view = new View();
196
-			$util = new Encryption\Util(
197
-				$view,
198
-				$c->getUserManager(),
199
-				$c->getGroupManager(),
200
-				$c->getConfig()
201
-			);
202
-			return new Encryption\Manager(
203
-				$c->getConfig(),
204
-				$c->getLogger(),
205
-				$c->getL10N('core'),
206
-				new View(),
207
-				$util,
208
-				new ArrayCache()
209
-			);
210
-		});
211
-
212
-		$this->registerService('EncryptionFileHelper', function (Server $c) {
213
-			$util = new Encryption\Util(
214
-				new View(),
215
-				$c->getUserManager(),
216
-				$c->getGroupManager(),
217
-				$c->getConfig()
218
-			);
219
-			return new Encryption\File(
220
-				$util,
221
-				$c->getRootFolder(),
222
-				$c->getShareManager()
223
-			);
224
-		});
225
-
226
-		$this->registerService('EncryptionKeyStorage', function (Server $c) {
227
-			$view = new View();
228
-			$util = new Encryption\Util(
229
-				$view,
230
-				$c->getUserManager(),
231
-				$c->getGroupManager(),
232
-				$c->getConfig()
233
-			);
234
-
235
-			return new Encryption\Keys\Storage($view, $util);
236
-		});
237
-		$this->registerService('TagMapper', function (Server $c) {
238
-			return new TagMapper($c->getDatabaseConnection());
239
-		});
240
-
241
-		$this->registerService(\OCP\ITagManager::class, function (Server $c) {
242
-			$tagMapper = $c->query('TagMapper');
243
-			return new TagManager($tagMapper, $c->getUserSession());
244
-		});
245
-		$this->registerAlias('TagManager', \OCP\ITagManager::class);
246
-
247
-		$this->registerService('SystemTagManagerFactory', function (Server $c) {
248
-			$config = $c->getConfig();
249
-			$factoryClass = $config->getSystemValue('systemtags.managerFactory', SystemTagManagerFactory::class);
250
-			return new $factoryClass($this);
251
-		});
252
-		$this->registerService(\OCP\SystemTag\ISystemTagManager::class, function (Server $c) {
253
-			return $c->query('SystemTagManagerFactory')->getManager();
254
-		});
255
-		$this->registerAlias('SystemTagManager', \OCP\SystemTag\ISystemTagManager::class);
256
-
257
-		$this->registerService(\OCP\SystemTag\ISystemTagObjectMapper::class, function (Server $c) {
258
-			return $c->query('SystemTagManagerFactory')->getObjectMapper();
259
-		});
260
-		$this->registerService('RootFolder', function (Server $c) {
261
-			$manager = \OC\Files\Filesystem::getMountManager(null);
262
-			$view = new View();
263
-			$root = new Root(
264
-				$manager,
265
-				$view,
266
-				null,
267
-				$c->getUserMountCache(),
268
-				$this->getLogger(),
269
-				$this->getUserManager()
270
-			);
271
-			$connector = new HookConnector($root, $view);
272
-			$connector->viewToNode();
273
-
274
-			$previewConnector = new \OC\Preview\WatcherConnector($root, $c->getSystemConfig());
275
-			$previewConnector->connectWatcher();
276
-
277
-			return $root;
278
-		});
279
-		$this->registerAlias('SystemTagObjectMapper', \OCP\SystemTag\ISystemTagObjectMapper::class);
280
-
281
-		$this->registerService(\OCP\Files\IRootFolder::class, function (Server $c) {
282
-			return new LazyRoot(function () use ($c) {
283
-				return $c->query('RootFolder');
284
-			});
285
-		});
286
-		$this->registerAlias('LazyRootFolder', \OCP\Files\IRootFolder::class);
287
-
288
-		$this->registerService(\OC\User\Manager::class, function (Server $c) {
289
-			$config = $c->getConfig();
290
-			return new \OC\User\Manager($config);
291
-		});
292
-		$this->registerAlias('UserManager', \OC\User\Manager::class);
293
-		$this->registerAlias(\OCP\IUserManager::class, \OC\User\Manager::class);
294
-
295
-		$this->registerService(\OCP\IGroupManager::class, function (Server $c) {
296
-			$groupManager = new \OC\Group\Manager($this->getUserManager(), $this->getLogger());
297
-			$groupManager->listen('\OC\Group', 'preCreate', function ($gid) {
298
-				\OC_Hook::emit('OC_Group', 'pre_createGroup', array('run' => true, 'gid' => $gid));
299
-			});
300
-			$groupManager->listen('\OC\Group', 'postCreate', function (\OC\Group\Group $gid) {
301
-				\OC_Hook::emit('OC_User', 'post_createGroup', array('gid' => $gid->getGID()));
302
-			});
303
-			$groupManager->listen('\OC\Group', 'preDelete', function (\OC\Group\Group $group) {
304
-				\OC_Hook::emit('OC_Group', 'pre_deleteGroup', array('run' => true, 'gid' => $group->getGID()));
305
-			});
306
-			$groupManager->listen('\OC\Group', 'postDelete', function (\OC\Group\Group $group) {
307
-				\OC_Hook::emit('OC_User', 'post_deleteGroup', array('gid' => $group->getGID()));
308
-			});
309
-			$groupManager->listen('\OC\Group', 'preAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
310
-				\OC_Hook::emit('OC_Group', 'pre_addToGroup', array('run' => true, 'uid' => $user->getUID(), 'gid' => $group->getGID()));
311
-			});
312
-			$groupManager->listen('\OC\Group', 'postAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
313
-				\OC_Hook::emit('OC_Group', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
314
-				//Minimal fix to keep it backward compatible TODO: clean up all the GroupManager hooks
315
-				\OC_Hook::emit('OC_User', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
316
-			});
317
-			return $groupManager;
318
-		});
319
-		$this->registerAlias('GroupManager', \OCP\IGroupManager::class);
320
-
321
-		$this->registerService(Store::class, function (Server $c) {
322
-			$session = $c->getSession();
323
-			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
324
-				$tokenProvider = $c->query(IProvider::class);
325
-			} else {
326
-				$tokenProvider = null;
327
-			}
328
-			$logger = $c->getLogger();
329
-			return new Store($session, $logger, $tokenProvider);
330
-		});
331
-		$this->registerAlias(IStore::class, Store::class);
332
-		$this->registerService(Authentication\Token\DefaultTokenMapper::class, function (Server $c) {
333
-			$dbConnection = $c->getDatabaseConnection();
334
-			return new Authentication\Token\DefaultTokenMapper($dbConnection);
335
-		});
336
-		$this->registerService(Authentication\Token\DefaultTokenProvider::class, function (Server $c) {
337
-			$mapper = $c->query(Authentication\Token\DefaultTokenMapper::class);
338
-			$crypto = $c->getCrypto();
339
-			$config = $c->getConfig();
340
-			$logger = $c->getLogger();
341
-			$timeFactory = new TimeFactory();
342
-			return new \OC\Authentication\Token\DefaultTokenProvider($mapper, $crypto, $config, $logger, $timeFactory);
343
-		});
344
-		$this->registerAlias(IProvider::class, Authentication\Token\DefaultTokenProvider::class);
345
-
346
-		$this->registerService(\OCP\IUserSession::class, function (Server $c) {
347
-			$manager = $c->getUserManager();
348
-			$session = new \OC\Session\Memory('');
349
-			$timeFactory = new TimeFactory();
350
-			// Token providers might require a working database. This code
351
-			// might however be called when ownCloud is not yet setup.
352
-			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
353
-				$defaultTokenProvider = $c->query(IProvider::class);
354
-			} else {
355
-				$defaultTokenProvider = null;
356
-			}
357
-
358
-			$dispatcher = $c->getEventDispatcher();
359
-
360
-			$userSession = new \OC\User\Session(
361
-				$manager,
362
-				$session,
363
-				$timeFactory,
364
-				$defaultTokenProvider,
365
-				$c->getConfig(),
366
-				$c->getSecureRandom(),
367
-				$c->getLockdownManager(),
368
-				$c->getLogger()
369
-			);
370
-			$userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
371
-				\OC_Hook::emit('OC_User', 'pre_createUser', array('run' => true, 'uid' => $uid, 'password' => $password));
372
-			});
373
-			$userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
374
-				/** @var $user \OC\User\User */
375
-				\OC_Hook::emit('OC_User', 'post_createUser', array('uid' => $user->getUID(), 'password' => $password));
376
-			});
377
-			$userSession->listen('\OC\User', 'preDelete', function ($user) use ($dispatcher) {
378
-				/** @var $user \OC\User\User */
379
-				\OC_Hook::emit('OC_User', 'pre_deleteUser', array('run' => true, 'uid' => $user->getUID()));
380
-				$dispatcher->dispatch('OCP\IUser::preDelete', new GenericEvent($user));
381
-			});
382
-			$userSession->listen('\OC\User', 'postDelete', function ($user) {
383
-				/** @var $user \OC\User\User */
384
-				\OC_Hook::emit('OC_User', 'post_deleteUser', array('uid' => $user->getUID()));
385
-			});
386
-			$userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
387
-				/** @var $user \OC\User\User */
388
-				\OC_Hook::emit('OC_User', 'pre_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
389
-			});
390
-			$userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
391
-				/** @var $user \OC\User\User */
392
-				\OC_Hook::emit('OC_User', 'post_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
393
-			});
394
-			$userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
395
-				\OC_Hook::emit('OC_User', 'pre_login', array('run' => true, 'uid' => $uid, 'password' => $password));
396
-			});
397
-			$userSession->listen('\OC\User', 'postLogin', function ($user, $password) {
398
-				/** @var $user \OC\User\User */
399
-				\OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
400
-			});
401
-			$userSession->listen('\OC\User', 'postRememberedLogin', function ($user, $password) {
402
-				/** @var $user \OC\User\User */
403
-				\OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
404
-			});
405
-			$userSession->listen('\OC\User', 'logout', function () {
406
-				\OC_Hook::emit('OC_User', 'logout', array());
407
-			});
408
-			$userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value, $oldValue) use ($dispatcher) {
409
-				/** @var $user \OC\User\User */
410
-				\OC_Hook::emit('OC_User', 'changeUser', array('run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value, 'old_value' => $oldValue));
411
-				$dispatcher->dispatch('OCP\IUser::changeUser', new GenericEvent($user, ['feature' => $feature, 'oldValue' => $oldValue, 'value' => $value]));
412
-			});
413
-			return $userSession;
414
-		});
415
-		$this->registerAlias('UserSession', \OCP\IUserSession::class);
416
-
417
-		$this->registerService(\OC\Authentication\TwoFactorAuth\Manager::class, function (Server $c) {
418
-			return new \OC\Authentication\TwoFactorAuth\Manager(
419
-				$c->getAppManager(),
420
-				$c->getSession(),
421
-				$c->getConfig(),
422
-				$c->getActivityManager(),
423
-				$c->getLogger(),
424
-				$c->query(IProvider::class),
425
-				$c->query(ITimeFactory::class),
426
-				$c->query(EventDispatcherInterface::class)
427
-			);
428
-		});
429
-
430
-		$this->registerAlias(\OCP\INavigationManager::class, \OC\NavigationManager::class);
431
-		$this->registerAlias('NavigationManager', \OCP\INavigationManager::class);
432
-
433
-		$this->registerService(\OC\AllConfig::class, function (Server $c) {
434
-			return new \OC\AllConfig(
435
-				$c->getSystemConfig()
436
-			);
437
-		});
438
-		$this->registerAlias('AllConfig', \OC\AllConfig::class);
439
-		$this->registerAlias(\OCP\IConfig::class, \OC\AllConfig::class);
440
-
441
-		$this->registerService('SystemConfig', function ($c) use ($config) {
442
-			return new \OC\SystemConfig($config);
443
-		});
444
-
445
-		$this->registerService(\OC\AppConfig::class, function (Server $c) {
446
-			return new \OC\AppConfig($c->getDatabaseConnection());
447
-		});
448
-		$this->registerAlias('AppConfig', \OC\AppConfig::class);
449
-		$this->registerAlias(\OCP\IAppConfig::class, \OC\AppConfig::class);
450
-
451
-		$this->registerService(\OCP\L10N\IFactory::class, function (Server $c) {
452
-			return new \OC\L10N\Factory(
453
-				$c->getConfig(),
454
-				$c->getRequest(),
455
-				$c->getUserSession(),
456
-				\OC::$SERVERROOT
457
-			);
458
-		});
459
-		$this->registerAlias('L10NFactory', \OCP\L10N\IFactory::class);
460
-
461
-		$this->registerService(\OCP\IURLGenerator::class, function (Server $c) {
462
-			$config = $c->getConfig();
463
-			$cacheFactory = $c->getMemCacheFactory();
464
-			$request = $c->getRequest();
465
-			return new \OC\URLGenerator(
466
-				$config,
467
-				$cacheFactory,
468
-				$request
469
-			);
470
-		});
471
-		$this->registerAlias('URLGenerator', \OCP\IURLGenerator::class);
472
-
473
-		$this->registerService('AppHelper', function ($c) {
474
-			return new \OC\AppHelper();
475
-		});
476
-		$this->registerAlias('AppFetcher', AppFetcher::class);
477
-		$this->registerAlias('CategoryFetcher', CategoryFetcher::class);
478
-
479
-		$this->registerService(\OCP\ICache::class, function ($c) {
480
-			return new Cache\File();
481
-		});
482
-		$this->registerAlias('UserCache', \OCP\ICache::class);
483
-
484
-		$this->registerService(Factory::class, function (Server $c) {
485
-
486
-			$arrayCacheFactory = new \OC\Memcache\Factory('', $c->getLogger(),
487
-				ArrayCache::class,
488
-				ArrayCache::class,
489
-				ArrayCache::class
490
-			);
491
-			$config = $c->getConfig();
492
-			$request = $c->getRequest();
493
-			$urlGenerator = new URLGenerator($config, $arrayCacheFactory, $request);
494
-
495
-			if ($config->getSystemValue('installed', false) && !(defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
496
-				$v = \OC_App::getAppVersions();
497
-				$v['core'] = implode(',', \OC_Util::getVersion());
498
-				$version = implode(',', $v);
499
-				$instanceId = \OC_Util::getInstanceId();
500
-				$path = \OC::$SERVERROOT;
501
-				$prefix = md5($instanceId . '-' . $version . '-' . $path);
502
-				return new \OC\Memcache\Factory($prefix, $c->getLogger(),
503
-					$config->getSystemValue('memcache.local', null),
504
-					$config->getSystemValue('memcache.distributed', null),
505
-					$config->getSystemValue('memcache.locking', null)
506
-				);
507
-			}
508
-			return $arrayCacheFactory;
509
-
510
-		});
511
-		$this->registerAlias('MemCacheFactory', Factory::class);
512
-		$this->registerAlias(ICacheFactory::class, Factory::class);
513
-
514
-		$this->registerService('RedisFactory', function (Server $c) {
515
-			$systemConfig = $c->getSystemConfig();
516
-			return new RedisFactory($systemConfig);
517
-		});
518
-
519
-		$this->registerService(\OCP\Activity\IManager::class, function (Server $c) {
520
-			return new \OC\Activity\Manager(
521
-				$c->getRequest(),
522
-				$c->getUserSession(),
523
-				$c->getConfig(),
524
-				$c->query(IValidator::class)
525
-			);
526
-		});
527
-		$this->registerAlias('ActivityManager', \OCP\Activity\IManager::class);
528
-
529
-		$this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
530
-			return new \OC\Activity\EventMerger(
531
-				$c->getL10N('lib')
532
-			);
533
-		});
534
-		$this->registerAlias(IValidator::class, Validator::class);
535
-
536
-		$this->registerService(\OCP\IAvatarManager::class, function (Server $c) {
537
-			return new AvatarManager(
538
-				$c->query(\OC\User\Manager::class),
539
-				$c->getAppDataDir('avatar'),
540
-				$c->getL10N('lib'),
541
-				$c->getLogger(),
542
-				$c->getConfig()
543
-			);
544
-		});
545
-		$this->registerAlias('AvatarManager', \OCP\IAvatarManager::class);
546
-
547
-		$this->registerAlias(\OCP\Support\CrashReport\IRegistry::class, \OC\Support\CrashReport\Registry::class);
548
-
549
-		$this->registerService(\OCP\ILogger::class, function (Server $c) {
550
-			$logType = $c->query('AllConfig')->getSystemValue('log_type', 'file');
551
-			$logger = Log::getLogClass($logType);
552
-			call_user_func(array($logger, 'init'));
553
-			$config = $this->getSystemConfig();
554
-			$registry = $c->query(\OCP\Support\CrashReport\IRegistry::class);
555
-
556
-			return new Log($logger, $config, null, $registry);
557
-		});
558
-		$this->registerAlias('Logger', \OCP\ILogger::class);
559
-
560
-		$this->registerService(\OCP\BackgroundJob\IJobList::class, function (Server $c) {
561
-			$config = $c->getConfig();
562
-			return new \OC\BackgroundJob\JobList(
563
-				$c->getDatabaseConnection(),
564
-				$config,
565
-				new TimeFactory()
566
-			);
567
-		});
568
-		$this->registerAlias('JobList', \OCP\BackgroundJob\IJobList::class);
569
-
570
-		$this->registerService(\OCP\Route\IRouter::class, function (Server $c) {
571
-			$cacheFactory = $c->getMemCacheFactory();
572
-			$logger = $c->getLogger();
573
-			if ($cacheFactory->isAvailableLowLatency()) {
574
-				$router = new \OC\Route\CachingRouter($cacheFactory->createLocal('route'), $logger);
575
-			} else {
576
-				$router = new \OC\Route\Router($logger);
577
-			}
578
-			return $router;
579
-		});
580
-		$this->registerAlias('Router', \OCP\Route\IRouter::class);
581
-
582
-		$this->registerService(\OCP\ISearch::class, function ($c) {
583
-			return new Search();
584
-		});
585
-		$this->registerAlias('Search', \OCP\ISearch::class);
586
-
587
-		$this->registerService(\OC\Security\RateLimiting\Limiter::class, function ($c) {
588
-			return new \OC\Security\RateLimiting\Limiter(
589
-				$this->getUserSession(),
590
-				$this->getRequest(),
591
-				new \OC\AppFramework\Utility\TimeFactory(),
592
-				$c->query(\OC\Security\RateLimiting\Backend\IBackend::class)
593
-			);
594
-		});
595
-		$this->registerService(\OC\Security\RateLimiting\Backend\IBackend::class, function ($c) {
596
-			return new \OC\Security\RateLimiting\Backend\MemoryCache(
597
-				$this->getMemCacheFactory(),
598
-				new \OC\AppFramework\Utility\TimeFactory()
599
-			);
600
-		});
601
-
602
-		$this->registerService(\OCP\Security\ISecureRandom::class, function ($c) {
603
-			return new SecureRandom();
604
-		});
605
-		$this->registerAlias('SecureRandom', \OCP\Security\ISecureRandom::class);
606
-
607
-		$this->registerService(\OCP\Security\ICrypto::class, function (Server $c) {
608
-			return new Crypto($c->getConfig(), $c->getSecureRandom());
609
-		});
610
-		$this->registerAlias('Crypto', \OCP\Security\ICrypto::class);
611
-
612
-		$this->registerService(\OCP\Security\IHasher::class, function (Server $c) {
613
-			return new Hasher($c->getConfig());
614
-		});
615
-		$this->registerAlias('Hasher', \OCP\Security\IHasher::class);
616
-
617
-		$this->registerService(\OCP\Security\ICredentialsManager::class, function (Server $c) {
618
-			return new CredentialsManager($c->getCrypto(), $c->getDatabaseConnection());
619
-		});
620
-		$this->registerAlias('CredentialsManager', \OCP\Security\ICredentialsManager::class);
621
-
622
-		$this->registerService(IDBConnection::class, function (Server $c) {
623
-			$systemConfig = $c->getSystemConfig();
624
-			$factory = new \OC\DB\ConnectionFactory($systemConfig);
625
-			$type = $systemConfig->getValue('dbtype', 'sqlite');
626
-			if (!$factory->isValidType($type)) {
627
-				throw new \OC\DatabaseException('Invalid database type');
628
-			}
629
-			$connectionParams = $factory->createConnectionParams();
630
-			$connection = $factory->getConnection($type, $connectionParams);
631
-			$connection->getConfiguration()->setSQLLogger($c->getQueryLogger());
632
-			return $connection;
633
-		});
634
-		$this->registerAlias('DatabaseConnection', IDBConnection::class);
635
-
636
-		$this->registerService('HTTPHelper', function (Server $c) {
637
-			$config = $c->getConfig();
638
-			return new HTTPHelper(
639
-				$config,
640
-				$c->getHTTPClientService()
641
-			);
642
-		});
643
-
644
-		$this->registerService(\OCP\Http\Client\IClientService::class, function (Server $c) {
645
-			$user = \OC_User::getUser();
646
-			$uid = $user ? $user : null;
647
-			return new ClientService(
648
-				$c->getConfig(),
649
-				new \OC\Security\CertificateManager(
650
-					$uid,
651
-					new View(),
652
-					$c->getConfig(),
653
-					$c->getLogger(),
654
-					$c->getSecureRandom()
655
-				)
656
-			);
657
-		});
658
-		$this->registerAlias('HttpClientService', \OCP\Http\Client\IClientService::class);
659
-		$this->registerService(\OCP\Diagnostics\IEventLogger::class, function (Server $c) {
660
-			$eventLogger = new EventLogger();
661
-			if ($c->getSystemConfig()->getValue('debug', false)) {
662
-				// In debug mode, module is being activated by default
663
-				$eventLogger->activate();
664
-			}
665
-			return $eventLogger;
666
-		});
667
-		$this->registerAlias('EventLogger', \OCP\Diagnostics\IEventLogger::class);
668
-
669
-		$this->registerService(\OCP\Diagnostics\IQueryLogger::class, function (Server $c) {
670
-			$queryLogger = new QueryLogger();
671
-			if ($c->getSystemConfig()->getValue('debug', false)) {
672
-				// In debug mode, module is being activated by default
673
-				$queryLogger->activate();
674
-			}
675
-			return $queryLogger;
676
-		});
677
-		$this->registerAlias('QueryLogger', \OCP\Diagnostics\IQueryLogger::class);
678
-
679
-		$this->registerService(TempManager::class, function (Server $c) {
680
-			return new TempManager(
681
-				$c->getLogger(),
682
-				$c->getConfig()
683
-			);
684
-		});
685
-		$this->registerAlias('TempManager', TempManager::class);
686
-		$this->registerAlias(ITempManager::class, TempManager::class);
687
-
688
-		$this->registerService(AppManager::class, function (Server $c) {
689
-			return new \OC\App\AppManager(
690
-				$c->getUserSession(),
691
-				$c->query(\OC\AppConfig::class),
692
-				$c->getGroupManager(),
693
-				$c->getMemCacheFactory(),
694
-				$c->getEventDispatcher()
695
-			);
696
-		});
697
-		$this->registerAlias('AppManager', AppManager::class);
698
-		$this->registerAlias(IAppManager::class, AppManager::class);
699
-
700
-		$this->registerService(\OCP\IDateTimeZone::class, function (Server $c) {
701
-			return new DateTimeZone(
702
-				$c->getConfig(),
703
-				$c->getSession()
704
-			);
705
-		});
706
-		$this->registerAlias('DateTimeZone', \OCP\IDateTimeZone::class);
707
-
708
-		$this->registerService(\OCP\IDateTimeFormatter::class, function (Server $c) {
709
-			$language = $c->getConfig()->getUserValue($c->getSession()->get('user_id'), 'core', 'lang', null);
710
-
711
-			return new DateTimeFormatter(
712
-				$c->getDateTimeZone()->getTimeZone(),
713
-				$c->getL10N('lib', $language)
714
-			);
715
-		});
716
-		$this->registerAlias('DateTimeFormatter', \OCP\IDateTimeFormatter::class);
717
-
718
-		$this->registerService(\OCP\Files\Config\IUserMountCache::class, function (Server $c) {
719
-			$mountCache = new UserMountCache($c->getDatabaseConnection(), $c->getUserManager(), $c->getLogger());
720
-			$listener = new UserMountCacheListener($mountCache);
721
-			$listener->listen($c->getUserManager());
722
-			return $mountCache;
723
-		});
724
-		$this->registerAlias('UserMountCache', \OCP\Files\Config\IUserMountCache::class);
725
-
726
-		$this->registerService(\OCP\Files\Config\IMountProviderCollection::class, function (Server $c) {
727
-			$loader = \OC\Files\Filesystem::getLoader();
728
-			$mountCache = $c->query('UserMountCache');
729
-			$manager = new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
730
-
731
-			// builtin providers
732
-
733
-			$config = $c->getConfig();
734
-			$manager->registerProvider(new CacheMountProvider($config));
735
-			$manager->registerHomeProvider(new LocalHomeMountProvider());
736
-			$manager->registerHomeProvider(new ObjectHomeMountProvider($config));
737
-
738
-			return $manager;
739
-		});
740
-		$this->registerAlias('MountConfigManager', \OCP\Files\Config\IMountProviderCollection::class);
741
-
742
-		$this->registerService('IniWrapper', function ($c) {
743
-			return new IniGetWrapper();
744
-		});
745
-		$this->registerService('AsyncCommandBus', function (Server $c) {
746
-			$busClass = $c->getConfig()->getSystemValue('commandbus');
747
-			if ($busClass) {
748
-				list($app, $class) = explode('::', $busClass, 2);
749
-				if ($c->getAppManager()->isInstalled($app)) {
750
-					\OC_App::loadApp($app);
751
-					return $c->query($class);
752
-				} else {
753
-					throw new ServiceUnavailableException("The app providing the command bus ($app) is not enabled");
754
-				}
755
-			} else {
756
-				$jobList = $c->getJobList();
757
-				return new CronBus($jobList);
758
-			}
759
-		});
760
-		$this->registerService('TrustedDomainHelper', function ($c) {
761
-			return new TrustedDomainHelper($this->getConfig());
762
-		});
763
-		$this->registerService('Throttler', function (Server $c) {
764
-			return new Throttler(
765
-				$c->getDatabaseConnection(),
766
-				new TimeFactory(),
767
-				$c->getLogger(),
768
-				$c->getConfig()
769
-			);
770
-		});
771
-		$this->registerService('IntegrityCodeChecker', function (Server $c) {
772
-			// IConfig and IAppManager requires a working database. This code
773
-			// might however be called when ownCloud is not yet setup.
774
-			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
775
-				$config = $c->getConfig();
776
-				$appManager = $c->getAppManager();
777
-			} else {
778
-				$config = null;
779
-				$appManager = null;
780
-			}
781
-
782
-			return new Checker(
783
-				new EnvironmentHelper(),
784
-				new FileAccessHelper(),
785
-				new AppLocator(),
786
-				$config,
787
-				$c->getMemCacheFactory(),
788
-				$appManager,
789
-				$c->getTempManager()
790
-			);
791
-		});
792
-		$this->registerService(\OCP\IRequest::class, function ($c) {
793
-			if (isset($this['urlParams'])) {
794
-				$urlParams = $this['urlParams'];
795
-			} else {
796
-				$urlParams = [];
797
-			}
798
-
799
-			if (defined('PHPUNIT_RUN') && PHPUNIT_RUN
800
-				&& in_array('fakeinput', stream_get_wrappers())
801
-			) {
802
-				$stream = 'fakeinput://data';
803
-			} else {
804
-				$stream = 'php://input';
805
-			}
806
-
807
-			return new Request(
808
-				[
809
-					'get' => $_GET,
810
-					'post' => $_POST,
811
-					'files' => $_FILES,
812
-					'server' => $_SERVER,
813
-					'env' => $_ENV,
814
-					'cookies' => $_COOKIE,
815
-					'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
816
-						? $_SERVER['REQUEST_METHOD']
817
-						: '',
818
-					'urlParams' => $urlParams,
819
-				],
820
-				$this->getSecureRandom(),
821
-				$this->getConfig(),
822
-				$this->getCsrfTokenManager(),
823
-				$stream
824
-			);
825
-		});
826
-		$this->registerAlias('Request', \OCP\IRequest::class);
827
-
828
-		$this->registerService(\OCP\Mail\IMailer::class, function (Server $c) {
829
-			return new Mailer(
830
-				$c->getConfig(),
831
-				$c->getLogger(),
832
-				$c->query(Defaults::class),
833
-				$c->getURLGenerator(),
834
-				$c->getL10N('lib')
835
-			);
836
-		});
837
-		$this->registerAlias('Mailer', \OCP\Mail\IMailer::class);
838
-
839
-		$this->registerService('LDAPProvider', function (Server $c) {
840
-			$config = $c->getConfig();
841
-			$factoryClass = $config->getSystemValue('ldapProviderFactory', null);
842
-			if (is_null($factoryClass)) {
843
-				throw new \Exception('ldapProviderFactory not set');
844
-			}
845
-			/** @var \OCP\LDAP\ILDAPProviderFactory $factory */
846
-			$factory = new $factoryClass($this);
847
-			return $factory->getLDAPProvider();
848
-		});
849
-		$this->registerService(ILockingProvider::class, function (Server $c) {
850
-			$ini = $c->getIniWrapper();
851
-			$config = $c->getConfig();
852
-			$ttl = $config->getSystemValue('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
853
-			if ($config->getSystemValue('filelocking.enabled', true) or (defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
854
-				/** @var \OC\Memcache\Factory $memcacheFactory */
855
-				$memcacheFactory = $c->getMemCacheFactory();
856
-				$memcache = $memcacheFactory->createLocking('lock');
857
-				if (!($memcache instanceof \OC\Memcache\NullCache)) {
858
-					return new MemcacheLockingProvider($memcache, $ttl);
859
-				}
860
-				return new DBLockingProvider($c->getDatabaseConnection(), $c->getLogger(), new TimeFactory(), $ttl);
861
-			}
862
-			return new NoopLockingProvider();
863
-		});
864
-		$this->registerAlias('LockingProvider', ILockingProvider::class);
865
-
866
-		$this->registerService(\OCP\Files\Mount\IMountManager::class, function () {
867
-			return new \OC\Files\Mount\Manager();
868
-		});
869
-		$this->registerAlias('MountManager', \OCP\Files\Mount\IMountManager::class);
870
-
871
-		$this->registerService(\OCP\Files\IMimeTypeDetector::class, function (Server $c) {
872
-			return new \OC\Files\Type\Detection(
873
-				$c->getURLGenerator(),
874
-				\OC::$configDir,
875
-				\OC::$SERVERROOT . '/resources/config/'
876
-			);
877
-		});
878
-		$this->registerAlias('MimeTypeDetector', \OCP\Files\IMimeTypeDetector::class);
879
-
880
-		$this->registerService(\OCP\Files\IMimeTypeLoader::class, function (Server $c) {
881
-			return new \OC\Files\Type\Loader(
882
-				$c->getDatabaseConnection()
883
-			);
884
-		});
885
-		$this->registerAlias('MimeTypeLoader', \OCP\Files\IMimeTypeLoader::class);
886
-		$this->registerService(BundleFetcher::class, function () {
887
-			return new BundleFetcher($this->getL10N('lib'));
888
-		});
889
-		$this->registerService(\OCP\Notification\IManager::class, function (Server $c) {
890
-			return new Manager(
891
-				$c->query(IValidator::class)
892
-			);
893
-		});
894
-		$this->registerAlias('NotificationManager', \OCP\Notification\IManager::class);
895
-
896
-		$this->registerService(\OC\CapabilitiesManager::class, function (Server $c) {
897
-			$manager = new \OC\CapabilitiesManager($c->getLogger());
898
-			$manager->registerCapability(function () use ($c) {
899
-				return new \OC\OCS\CoreCapabilities($c->getConfig());
900
-			});
901
-			$manager->registerCapability(function () use ($c) {
902
-				return $c->query(\OC\Security\Bruteforce\Capabilities::class);
903
-			});
904
-			return $manager;
905
-		});
906
-		$this->registerAlias('CapabilitiesManager', \OC\CapabilitiesManager::class);
907
-
908
-		$this->registerService(\OCP\Comments\ICommentsManager::class, function (Server $c) {
909
-			$config = $c->getConfig();
910
-			$factoryClass = $config->getSystemValue('comments.managerFactory', CommentsManagerFactory::class);
911
-			/** @var \OCP\Comments\ICommentsManagerFactory $factory */
912
-			$factory = new $factoryClass($this);
913
-			$manager = $factory->getManager();
914
-
915
-			$manager->registerDisplayNameResolver('user', function($id) use ($c) {
916
-				$manager = $c->getUserManager();
917
-				$user = $manager->get($id);
918
-				if(is_null($user)) {
919
-					$l = $c->getL10N('core');
920
-					$displayName = $l->t('Unknown user');
921
-				} else {
922
-					$displayName = $user->getDisplayName();
923
-				}
924
-				return $displayName;
925
-			});
926
-
927
-			return $manager;
928
-		});
929
-		$this->registerAlias('CommentsManager', \OCP\Comments\ICommentsManager::class);
930
-
931
-		$this->registerService('ThemingDefaults', function (Server $c) {
932
-			/*
153
+    /** @var string */
154
+    private $webRoot;
155
+
156
+    /**
157
+     * @param string $webRoot
158
+     * @param \OC\Config $config
159
+     */
160
+    public function __construct($webRoot, \OC\Config $config) {
161
+        parent::__construct();
162
+        $this->webRoot = $webRoot;
163
+
164
+        $this->registerService(\OCP\IServerContainer::class, function (IServerContainer $c) {
165
+            return $c;
166
+        });
167
+
168
+        $this->registerAlias(\OCP\Calendar\IManager::class, \OC\Calendar\Manager::class);
169
+        $this->registerAlias('CalendarManager', \OC\Calendar\Manager::class);
170
+
171
+        $this->registerAlias(\OCP\Contacts\IManager::class, \OC\ContactsManager::class);
172
+        $this->registerAlias('ContactsManager', \OCP\Contacts\IManager::class);
173
+
174
+        $this->registerAlias(IActionFactory::class, ActionFactory::class);
175
+
176
+
177
+        $this->registerService(\OCP\IPreview::class, function (Server $c) {
178
+            return new PreviewManager(
179
+                $c->getConfig(),
180
+                $c->getRootFolder(),
181
+                $c->getAppDataDir('preview'),
182
+                $c->getEventDispatcher(),
183
+                $c->getSession()->get('user_id')
184
+            );
185
+        });
186
+        $this->registerAlias('PreviewManager', \OCP\IPreview::class);
187
+
188
+        $this->registerService(\OC\Preview\Watcher::class, function (Server $c) {
189
+            return new \OC\Preview\Watcher(
190
+                $c->getAppDataDir('preview')
191
+            );
192
+        });
193
+
194
+        $this->registerService('EncryptionManager', function (Server $c) {
195
+            $view = new View();
196
+            $util = new Encryption\Util(
197
+                $view,
198
+                $c->getUserManager(),
199
+                $c->getGroupManager(),
200
+                $c->getConfig()
201
+            );
202
+            return new Encryption\Manager(
203
+                $c->getConfig(),
204
+                $c->getLogger(),
205
+                $c->getL10N('core'),
206
+                new View(),
207
+                $util,
208
+                new ArrayCache()
209
+            );
210
+        });
211
+
212
+        $this->registerService('EncryptionFileHelper', function (Server $c) {
213
+            $util = new Encryption\Util(
214
+                new View(),
215
+                $c->getUserManager(),
216
+                $c->getGroupManager(),
217
+                $c->getConfig()
218
+            );
219
+            return new Encryption\File(
220
+                $util,
221
+                $c->getRootFolder(),
222
+                $c->getShareManager()
223
+            );
224
+        });
225
+
226
+        $this->registerService('EncryptionKeyStorage', function (Server $c) {
227
+            $view = new View();
228
+            $util = new Encryption\Util(
229
+                $view,
230
+                $c->getUserManager(),
231
+                $c->getGroupManager(),
232
+                $c->getConfig()
233
+            );
234
+
235
+            return new Encryption\Keys\Storage($view, $util);
236
+        });
237
+        $this->registerService('TagMapper', function (Server $c) {
238
+            return new TagMapper($c->getDatabaseConnection());
239
+        });
240
+
241
+        $this->registerService(\OCP\ITagManager::class, function (Server $c) {
242
+            $tagMapper = $c->query('TagMapper');
243
+            return new TagManager($tagMapper, $c->getUserSession());
244
+        });
245
+        $this->registerAlias('TagManager', \OCP\ITagManager::class);
246
+
247
+        $this->registerService('SystemTagManagerFactory', function (Server $c) {
248
+            $config = $c->getConfig();
249
+            $factoryClass = $config->getSystemValue('systemtags.managerFactory', SystemTagManagerFactory::class);
250
+            return new $factoryClass($this);
251
+        });
252
+        $this->registerService(\OCP\SystemTag\ISystemTagManager::class, function (Server $c) {
253
+            return $c->query('SystemTagManagerFactory')->getManager();
254
+        });
255
+        $this->registerAlias('SystemTagManager', \OCP\SystemTag\ISystemTagManager::class);
256
+
257
+        $this->registerService(\OCP\SystemTag\ISystemTagObjectMapper::class, function (Server $c) {
258
+            return $c->query('SystemTagManagerFactory')->getObjectMapper();
259
+        });
260
+        $this->registerService('RootFolder', function (Server $c) {
261
+            $manager = \OC\Files\Filesystem::getMountManager(null);
262
+            $view = new View();
263
+            $root = new Root(
264
+                $manager,
265
+                $view,
266
+                null,
267
+                $c->getUserMountCache(),
268
+                $this->getLogger(),
269
+                $this->getUserManager()
270
+            );
271
+            $connector = new HookConnector($root, $view);
272
+            $connector->viewToNode();
273
+
274
+            $previewConnector = new \OC\Preview\WatcherConnector($root, $c->getSystemConfig());
275
+            $previewConnector->connectWatcher();
276
+
277
+            return $root;
278
+        });
279
+        $this->registerAlias('SystemTagObjectMapper', \OCP\SystemTag\ISystemTagObjectMapper::class);
280
+
281
+        $this->registerService(\OCP\Files\IRootFolder::class, function (Server $c) {
282
+            return new LazyRoot(function () use ($c) {
283
+                return $c->query('RootFolder');
284
+            });
285
+        });
286
+        $this->registerAlias('LazyRootFolder', \OCP\Files\IRootFolder::class);
287
+
288
+        $this->registerService(\OC\User\Manager::class, function (Server $c) {
289
+            $config = $c->getConfig();
290
+            return new \OC\User\Manager($config);
291
+        });
292
+        $this->registerAlias('UserManager', \OC\User\Manager::class);
293
+        $this->registerAlias(\OCP\IUserManager::class, \OC\User\Manager::class);
294
+
295
+        $this->registerService(\OCP\IGroupManager::class, function (Server $c) {
296
+            $groupManager = new \OC\Group\Manager($this->getUserManager(), $this->getLogger());
297
+            $groupManager->listen('\OC\Group', 'preCreate', function ($gid) {
298
+                \OC_Hook::emit('OC_Group', 'pre_createGroup', array('run' => true, 'gid' => $gid));
299
+            });
300
+            $groupManager->listen('\OC\Group', 'postCreate', function (\OC\Group\Group $gid) {
301
+                \OC_Hook::emit('OC_User', 'post_createGroup', array('gid' => $gid->getGID()));
302
+            });
303
+            $groupManager->listen('\OC\Group', 'preDelete', function (\OC\Group\Group $group) {
304
+                \OC_Hook::emit('OC_Group', 'pre_deleteGroup', array('run' => true, 'gid' => $group->getGID()));
305
+            });
306
+            $groupManager->listen('\OC\Group', 'postDelete', function (\OC\Group\Group $group) {
307
+                \OC_Hook::emit('OC_User', 'post_deleteGroup', array('gid' => $group->getGID()));
308
+            });
309
+            $groupManager->listen('\OC\Group', 'preAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
310
+                \OC_Hook::emit('OC_Group', 'pre_addToGroup', array('run' => true, 'uid' => $user->getUID(), 'gid' => $group->getGID()));
311
+            });
312
+            $groupManager->listen('\OC\Group', 'postAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
313
+                \OC_Hook::emit('OC_Group', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
314
+                //Minimal fix to keep it backward compatible TODO: clean up all the GroupManager hooks
315
+                \OC_Hook::emit('OC_User', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
316
+            });
317
+            return $groupManager;
318
+        });
319
+        $this->registerAlias('GroupManager', \OCP\IGroupManager::class);
320
+
321
+        $this->registerService(Store::class, function (Server $c) {
322
+            $session = $c->getSession();
323
+            if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
324
+                $tokenProvider = $c->query(IProvider::class);
325
+            } else {
326
+                $tokenProvider = null;
327
+            }
328
+            $logger = $c->getLogger();
329
+            return new Store($session, $logger, $tokenProvider);
330
+        });
331
+        $this->registerAlias(IStore::class, Store::class);
332
+        $this->registerService(Authentication\Token\DefaultTokenMapper::class, function (Server $c) {
333
+            $dbConnection = $c->getDatabaseConnection();
334
+            return new Authentication\Token\DefaultTokenMapper($dbConnection);
335
+        });
336
+        $this->registerService(Authentication\Token\DefaultTokenProvider::class, function (Server $c) {
337
+            $mapper = $c->query(Authentication\Token\DefaultTokenMapper::class);
338
+            $crypto = $c->getCrypto();
339
+            $config = $c->getConfig();
340
+            $logger = $c->getLogger();
341
+            $timeFactory = new TimeFactory();
342
+            return new \OC\Authentication\Token\DefaultTokenProvider($mapper, $crypto, $config, $logger, $timeFactory);
343
+        });
344
+        $this->registerAlias(IProvider::class, Authentication\Token\DefaultTokenProvider::class);
345
+
346
+        $this->registerService(\OCP\IUserSession::class, function (Server $c) {
347
+            $manager = $c->getUserManager();
348
+            $session = new \OC\Session\Memory('');
349
+            $timeFactory = new TimeFactory();
350
+            // Token providers might require a working database. This code
351
+            // might however be called when ownCloud is not yet setup.
352
+            if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
353
+                $defaultTokenProvider = $c->query(IProvider::class);
354
+            } else {
355
+                $defaultTokenProvider = null;
356
+            }
357
+
358
+            $dispatcher = $c->getEventDispatcher();
359
+
360
+            $userSession = new \OC\User\Session(
361
+                $manager,
362
+                $session,
363
+                $timeFactory,
364
+                $defaultTokenProvider,
365
+                $c->getConfig(),
366
+                $c->getSecureRandom(),
367
+                $c->getLockdownManager(),
368
+                $c->getLogger()
369
+            );
370
+            $userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
371
+                \OC_Hook::emit('OC_User', 'pre_createUser', array('run' => true, 'uid' => $uid, 'password' => $password));
372
+            });
373
+            $userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
374
+                /** @var $user \OC\User\User */
375
+                \OC_Hook::emit('OC_User', 'post_createUser', array('uid' => $user->getUID(), 'password' => $password));
376
+            });
377
+            $userSession->listen('\OC\User', 'preDelete', function ($user) use ($dispatcher) {
378
+                /** @var $user \OC\User\User */
379
+                \OC_Hook::emit('OC_User', 'pre_deleteUser', array('run' => true, 'uid' => $user->getUID()));
380
+                $dispatcher->dispatch('OCP\IUser::preDelete', new GenericEvent($user));
381
+            });
382
+            $userSession->listen('\OC\User', 'postDelete', function ($user) {
383
+                /** @var $user \OC\User\User */
384
+                \OC_Hook::emit('OC_User', 'post_deleteUser', array('uid' => $user->getUID()));
385
+            });
386
+            $userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
387
+                /** @var $user \OC\User\User */
388
+                \OC_Hook::emit('OC_User', 'pre_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
389
+            });
390
+            $userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
391
+                /** @var $user \OC\User\User */
392
+                \OC_Hook::emit('OC_User', 'post_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
393
+            });
394
+            $userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
395
+                \OC_Hook::emit('OC_User', 'pre_login', array('run' => true, 'uid' => $uid, 'password' => $password));
396
+            });
397
+            $userSession->listen('\OC\User', 'postLogin', function ($user, $password) {
398
+                /** @var $user \OC\User\User */
399
+                \OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
400
+            });
401
+            $userSession->listen('\OC\User', 'postRememberedLogin', function ($user, $password) {
402
+                /** @var $user \OC\User\User */
403
+                \OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
404
+            });
405
+            $userSession->listen('\OC\User', 'logout', function () {
406
+                \OC_Hook::emit('OC_User', 'logout', array());
407
+            });
408
+            $userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value, $oldValue) use ($dispatcher) {
409
+                /** @var $user \OC\User\User */
410
+                \OC_Hook::emit('OC_User', 'changeUser', array('run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value, 'old_value' => $oldValue));
411
+                $dispatcher->dispatch('OCP\IUser::changeUser', new GenericEvent($user, ['feature' => $feature, 'oldValue' => $oldValue, 'value' => $value]));
412
+            });
413
+            return $userSession;
414
+        });
415
+        $this->registerAlias('UserSession', \OCP\IUserSession::class);
416
+
417
+        $this->registerService(\OC\Authentication\TwoFactorAuth\Manager::class, function (Server $c) {
418
+            return new \OC\Authentication\TwoFactorAuth\Manager(
419
+                $c->getAppManager(),
420
+                $c->getSession(),
421
+                $c->getConfig(),
422
+                $c->getActivityManager(),
423
+                $c->getLogger(),
424
+                $c->query(IProvider::class),
425
+                $c->query(ITimeFactory::class),
426
+                $c->query(EventDispatcherInterface::class)
427
+            );
428
+        });
429
+
430
+        $this->registerAlias(\OCP\INavigationManager::class, \OC\NavigationManager::class);
431
+        $this->registerAlias('NavigationManager', \OCP\INavigationManager::class);
432
+
433
+        $this->registerService(\OC\AllConfig::class, function (Server $c) {
434
+            return new \OC\AllConfig(
435
+                $c->getSystemConfig()
436
+            );
437
+        });
438
+        $this->registerAlias('AllConfig', \OC\AllConfig::class);
439
+        $this->registerAlias(\OCP\IConfig::class, \OC\AllConfig::class);
440
+
441
+        $this->registerService('SystemConfig', function ($c) use ($config) {
442
+            return new \OC\SystemConfig($config);
443
+        });
444
+
445
+        $this->registerService(\OC\AppConfig::class, function (Server $c) {
446
+            return new \OC\AppConfig($c->getDatabaseConnection());
447
+        });
448
+        $this->registerAlias('AppConfig', \OC\AppConfig::class);
449
+        $this->registerAlias(\OCP\IAppConfig::class, \OC\AppConfig::class);
450
+
451
+        $this->registerService(\OCP\L10N\IFactory::class, function (Server $c) {
452
+            return new \OC\L10N\Factory(
453
+                $c->getConfig(),
454
+                $c->getRequest(),
455
+                $c->getUserSession(),
456
+                \OC::$SERVERROOT
457
+            );
458
+        });
459
+        $this->registerAlias('L10NFactory', \OCP\L10N\IFactory::class);
460
+
461
+        $this->registerService(\OCP\IURLGenerator::class, function (Server $c) {
462
+            $config = $c->getConfig();
463
+            $cacheFactory = $c->getMemCacheFactory();
464
+            $request = $c->getRequest();
465
+            return new \OC\URLGenerator(
466
+                $config,
467
+                $cacheFactory,
468
+                $request
469
+            );
470
+        });
471
+        $this->registerAlias('URLGenerator', \OCP\IURLGenerator::class);
472
+
473
+        $this->registerService('AppHelper', function ($c) {
474
+            return new \OC\AppHelper();
475
+        });
476
+        $this->registerAlias('AppFetcher', AppFetcher::class);
477
+        $this->registerAlias('CategoryFetcher', CategoryFetcher::class);
478
+
479
+        $this->registerService(\OCP\ICache::class, function ($c) {
480
+            return new Cache\File();
481
+        });
482
+        $this->registerAlias('UserCache', \OCP\ICache::class);
483
+
484
+        $this->registerService(Factory::class, function (Server $c) {
485
+
486
+            $arrayCacheFactory = new \OC\Memcache\Factory('', $c->getLogger(),
487
+                ArrayCache::class,
488
+                ArrayCache::class,
489
+                ArrayCache::class
490
+            );
491
+            $config = $c->getConfig();
492
+            $request = $c->getRequest();
493
+            $urlGenerator = new URLGenerator($config, $arrayCacheFactory, $request);
494
+
495
+            if ($config->getSystemValue('installed', false) && !(defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
496
+                $v = \OC_App::getAppVersions();
497
+                $v['core'] = implode(',', \OC_Util::getVersion());
498
+                $version = implode(',', $v);
499
+                $instanceId = \OC_Util::getInstanceId();
500
+                $path = \OC::$SERVERROOT;
501
+                $prefix = md5($instanceId . '-' . $version . '-' . $path);
502
+                return new \OC\Memcache\Factory($prefix, $c->getLogger(),
503
+                    $config->getSystemValue('memcache.local', null),
504
+                    $config->getSystemValue('memcache.distributed', null),
505
+                    $config->getSystemValue('memcache.locking', null)
506
+                );
507
+            }
508
+            return $arrayCacheFactory;
509
+
510
+        });
511
+        $this->registerAlias('MemCacheFactory', Factory::class);
512
+        $this->registerAlias(ICacheFactory::class, Factory::class);
513
+
514
+        $this->registerService('RedisFactory', function (Server $c) {
515
+            $systemConfig = $c->getSystemConfig();
516
+            return new RedisFactory($systemConfig);
517
+        });
518
+
519
+        $this->registerService(\OCP\Activity\IManager::class, function (Server $c) {
520
+            return new \OC\Activity\Manager(
521
+                $c->getRequest(),
522
+                $c->getUserSession(),
523
+                $c->getConfig(),
524
+                $c->query(IValidator::class)
525
+            );
526
+        });
527
+        $this->registerAlias('ActivityManager', \OCP\Activity\IManager::class);
528
+
529
+        $this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
530
+            return new \OC\Activity\EventMerger(
531
+                $c->getL10N('lib')
532
+            );
533
+        });
534
+        $this->registerAlias(IValidator::class, Validator::class);
535
+
536
+        $this->registerService(\OCP\IAvatarManager::class, function (Server $c) {
537
+            return new AvatarManager(
538
+                $c->query(\OC\User\Manager::class),
539
+                $c->getAppDataDir('avatar'),
540
+                $c->getL10N('lib'),
541
+                $c->getLogger(),
542
+                $c->getConfig()
543
+            );
544
+        });
545
+        $this->registerAlias('AvatarManager', \OCP\IAvatarManager::class);
546
+
547
+        $this->registerAlias(\OCP\Support\CrashReport\IRegistry::class, \OC\Support\CrashReport\Registry::class);
548
+
549
+        $this->registerService(\OCP\ILogger::class, function (Server $c) {
550
+            $logType = $c->query('AllConfig')->getSystemValue('log_type', 'file');
551
+            $logger = Log::getLogClass($logType);
552
+            call_user_func(array($logger, 'init'));
553
+            $config = $this->getSystemConfig();
554
+            $registry = $c->query(\OCP\Support\CrashReport\IRegistry::class);
555
+
556
+            return new Log($logger, $config, null, $registry);
557
+        });
558
+        $this->registerAlias('Logger', \OCP\ILogger::class);
559
+
560
+        $this->registerService(\OCP\BackgroundJob\IJobList::class, function (Server $c) {
561
+            $config = $c->getConfig();
562
+            return new \OC\BackgroundJob\JobList(
563
+                $c->getDatabaseConnection(),
564
+                $config,
565
+                new TimeFactory()
566
+            );
567
+        });
568
+        $this->registerAlias('JobList', \OCP\BackgroundJob\IJobList::class);
569
+
570
+        $this->registerService(\OCP\Route\IRouter::class, function (Server $c) {
571
+            $cacheFactory = $c->getMemCacheFactory();
572
+            $logger = $c->getLogger();
573
+            if ($cacheFactory->isAvailableLowLatency()) {
574
+                $router = new \OC\Route\CachingRouter($cacheFactory->createLocal('route'), $logger);
575
+            } else {
576
+                $router = new \OC\Route\Router($logger);
577
+            }
578
+            return $router;
579
+        });
580
+        $this->registerAlias('Router', \OCP\Route\IRouter::class);
581
+
582
+        $this->registerService(\OCP\ISearch::class, function ($c) {
583
+            return new Search();
584
+        });
585
+        $this->registerAlias('Search', \OCP\ISearch::class);
586
+
587
+        $this->registerService(\OC\Security\RateLimiting\Limiter::class, function ($c) {
588
+            return new \OC\Security\RateLimiting\Limiter(
589
+                $this->getUserSession(),
590
+                $this->getRequest(),
591
+                new \OC\AppFramework\Utility\TimeFactory(),
592
+                $c->query(\OC\Security\RateLimiting\Backend\IBackend::class)
593
+            );
594
+        });
595
+        $this->registerService(\OC\Security\RateLimiting\Backend\IBackend::class, function ($c) {
596
+            return new \OC\Security\RateLimiting\Backend\MemoryCache(
597
+                $this->getMemCacheFactory(),
598
+                new \OC\AppFramework\Utility\TimeFactory()
599
+            );
600
+        });
601
+
602
+        $this->registerService(\OCP\Security\ISecureRandom::class, function ($c) {
603
+            return new SecureRandom();
604
+        });
605
+        $this->registerAlias('SecureRandom', \OCP\Security\ISecureRandom::class);
606
+
607
+        $this->registerService(\OCP\Security\ICrypto::class, function (Server $c) {
608
+            return new Crypto($c->getConfig(), $c->getSecureRandom());
609
+        });
610
+        $this->registerAlias('Crypto', \OCP\Security\ICrypto::class);
611
+
612
+        $this->registerService(\OCP\Security\IHasher::class, function (Server $c) {
613
+            return new Hasher($c->getConfig());
614
+        });
615
+        $this->registerAlias('Hasher', \OCP\Security\IHasher::class);
616
+
617
+        $this->registerService(\OCP\Security\ICredentialsManager::class, function (Server $c) {
618
+            return new CredentialsManager($c->getCrypto(), $c->getDatabaseConnection());
619
+        });
620
+        $this->registerAlias('CredentialsManager', \OCP\Security\ICredentialsManager::class);
621
+
622
+        $this->registerService(IDBConnection::class, function (Server $c) {
623
+            $systemConfig = $c->getSystemConfig();
624
+            $factory = new \OC\DB\ConnectionFactory($systemConfig);
625
+            $type = $systemConfig->getValue('dbtype', 'sqlite');
626
+            if (!$factory->isValidType($type)) {
627
+                throw new \OC\DatabaseException('Invalid database type');
628
+            }
629
+            $connectionParams = $factory->createConnectionParams();
630
+            $connection = $factory->getConnection($type, $connectionParams);
631
+            $connection->getConfiguration()->setSQLLogger($c->getQueryLogger());
632
+            return $connection;
633
+        });
634
+        $this->registerAlias('DatabaseConnection', IDBConnection::class);
635
+
636
+        $this->registerService('HTTPHelper', function (Server $c) {
637
+            $config = $c->getConfig();
638
+            return new HTTPHelper(
639
+                $config,
640
+                $c->getHTTPClientService()
641
+            );
642
+        });
643
+
644
+        $this->registerService(\OCP\Http\Client\IClientService::class, function (Server $c) {
645
+            $user = \OC_User::getUser();
646
+            $uid = $user ? $user : null;
647
+            return new ClientService(
648
+                $c->getConfig(),
649
+                new \OC\Security\CertificateManager(
650
+                    $uid,
651
+                    new View(),
652
+                    $c->getConfig(),
653
+                    $c->getLogger(),
654
+                    $c->getSecureRandom()
655
+                )
656
+            );
657
+        });
658
+        $this->registerAlias('HttpClientService', \OCP\Http\Client\IClientService::class);
659
+        $this->registerService(\OCP\Diagnostics\IEventLogger::class, function (Server $c) {
660
+            $eventLogger = new EventLogger();
661
+            if ($c->getSystemConfig()->getValue('debug', false)) {
662
+                // In debug mode, module is being activated by default
663
+                $eventLogger->activate();
664
+            }
665
+            return $eventLogger;
666
+        });
667
+        $this->registerAlias('EventLogger', \OCP\Diagnostics\IEventLogger::class);
668
+
669
+        $this->registerService(\OCP\Diagnostics\IQueryLogger::class, function (Server $c) {
670
+            $queryLogger = new QueryLogger();
671
+            if ($c->getSystemConfig()->getValue('debug', false)) {
672
+                // In debug mode, module is being activated by default
673
+                $queryLogger->activate();
674
+            }
675
+            return $queryLogger;
676
+        });
677
+        $this->registerAlias('QueryLogger', \OCP\Diagnostics\IQueryLogger::class);
678
+
679
+        $this->registerService(TempManager::class, function (Server $c) {
680
+            return new TempManager(
681
+                $c->getLogger(),
682
+                $c->getConfig()
683
+            );
684
+        });
685
+        $this->registerAlias('TempManager', TempManager::class);
686
+        $this->registerAlias(ITempManager::class, TempManager::class);
687
+
688
+        $this->registerService(AppManager::class, function (Server $c) {
689
+            return new \OC\App\AppManager(
690
+                $c->getUserSession(),
691
+                $c->query(\OC\AppConfig::class),
692
+                $c->getGroupManager(),
693
+                $c->getMemCacheFactory(),
694
+                $c->getEventDispatcher()
695
+            );
696
+        });
697
+        $this->registerAlias('AppManager', AppManager::class);
698
+        $this->registerAlias(IAppManager::class, AppManager::class);
699
+
700
+        $this->registerService(\OCP\IDateTimeZone::class, function (Server $c) {
701
+            return new DateTimeZone(
702
+                $c->getConfig(),
703
+                $c->getSession()
704
+            );
705
+        });
706
+        $this->registerAlias('DateTimeZone', \OCP\IDateTimeZone::class);
707
+
708
+        $this->registerService(\OCP\IDateTimeFormatter::class, function (Server $c) {
709
+            $language = $c->getConfig()->getUserValue($c->getSession()->get('user_id'), 'core', 'lang', null);
710
+
711
+            return new DateTimeFormatter(
712
+                $c->getDateTimeZone()->getTimeZone(),
713
+                $c->getL10N('lib', $language)
714
+            );
715
+        });
716
+        $this->registerAlias('DateTimeFormatter', \OCP\IDateTimeFormatter::class);
717
+
718
+        $this->registerService(\OCP\Files\Config\IUserMountCache::class, function (Server $c) {
719
+            $mountCache = new UserMountCache($c->getDatabaseConnection(), $c->getUserManager(), $c->getLogger());
720
+            $listener = new UserMountCacheListener($mountCache);
721
+            $listener->listen($c->getUserManager());
722
+            return $mountCache;
723
+        });
724
+        $this->registerAlias('UserMountCache', \OCP\Files\Config\IUserMountCache::class);
725
+
726
+        $this->registerService(\OCP\Files\Config\IMountProviderCollection::class, function (Server $c) {
727
+            $loader = \OC\Files\Filesystem::getLoader();
728
+            $mountCache = $c->query('UserMountCache');
729
+            $manager = new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
730
+
731
+            // builtin providers
732
+
733
+            $config = $c->getConfig();
734
+            $manager->registerProvider(new CacheMountProvider($config));
735
+            $manager->registerHomeProvider(new LocalHomeMountProvider());
736
+            $manager->registerHomeProvider(new ObjectHomeMountProvider($config));
737
+
738
+            return $manager;
739
+        });
740
+        $this->registerAlias('MountConfigManager', \OCP\Files\Config\IMountProviderCollection::class);
741
+
742
+        $this->registerService('IniWrapper', function ($c) {
743
+            return new IniGetWrapper();
744
+        });
745
+        $this->registerService('AsyncCommandBus', function (Server $c) {
746
+            $busClass = $c->getConfig()->getSystemValue('commandbus');
747
+            if ($busClass) {
748
+                list($app, $class) = explode('::', $busClass, 2);
749
+                if ($c->getAppManager()->isInstalled($app)) {
750
+                    \OC_App::loadApp($app);
751
+                    return $c->query($class);
752
+                } else {
753
+                    throw new ServiceUnavailableException("The app providing the command bus ($app) is not enabled");
754
+                }
755
+            } else {
756
+                $jobList = $c->getJobList();
757
+                return new CronBus($jobList);
758
+            }
759
+        });
760
+        $this->registerService('TrustedDomainHelper', function ($c) {
761
+            return new TrustedDomainHelper($this->getConfig());
762
+        });
763
+        $this->registerService('Throttler', function (Server $c) {
764
+            return new Throttler(
765
+                $c->getDatabaseConnection(),
766
+                new TimeFactory(),
767
+                $c->getLogger(),
768
+                $c->getConfig()
769
+            );
770
+        });
771
+        $this->registerService('IntegrityCodeChecker', function (Server $c) {
772
+            // IConfig and IAppManager requires a working database. This code
773
+            // might however be called when ownCloud is not yet setup.
774
+            if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
775
+                $config = $c->getConfig();
776
+                $appManager = $c->getAppManager();
777
+            } else {
778
+                $config = null;
779
+                $appManager = null;
780
+            }
781
+
782
+            return new Checker(
783
+                new EnvironmentHelper(),
784
+                new FileAccessHelper(),
785
+                new AppLocator(),
786
+                $config,
787
+                $c->getMemCacheFactory(),
788
+                $appManager,
789
+                $c->getTempManager()
790
+            );
791
+        });
792
+        $this->registerService(\OCP\IRequest::class, function ($c) {
793
+            if (isset($this['urlParams'])) {
794
+                $urlParams = $this['urlParams'];
795
+            } else {
796
+                $urlParams = [];
797
+            }
798
+
799
+            if (defined('PHPUNIT_RUN') && PHPUNIT_RUN
800
+                && in_array('fakeinput', stream_get_wrappers())
801
+            ) {
802
+                $stream = 'fakeinput://data';
803
+            } else {
804
+                $stream = 'php://input';
805
+            }
806
+
807
+            return new Request(
808
+                [
809
+                    'get' => $_GET,
810
+                    'post' => $_POST,
811
+                    'files' => $_FILES,
812
+                    'server' => $_SERVER,
813
+                    'env' => $_ENV,
814
+                    'cookies' => $_COOKIE,
815
+                    'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
816
+                        ? $_SERVER['REQUEST_METHOD']
817
+                        : '',
818
+                    'urlParams' => $urlParams,
819
+                ],
820
+                $this->getSecureRandom(),
821
+                $this->getConfig(),
822
+                $this->getCsrfTokenManager(),
823
+                $stream
824
+            );
825
+        });
826
+        $this->registerAlias('Request', \OCP\IRequest::class);
827
+
828
+        $this->registerService(\OCP\Mail\IMailer::class, function (Server $c) {
829
+            return new Mailer(
830
+                $c->getConfig(),
831
+                $c->getLogger(),
832
+                $c->query(Defaults::class),
833
+                $c->getURLGenerator(),
834
+                $c->getL10N('lib')
835
+            );
836
+        });
837
+        $this->registerAlias('Mailer', \OCP\Mail\IMailer::class);
838
+
839
+        $this->registerService('LDAPProvider', function (Server $c) {
840
+            $config = $c->getConfig();
841
+            $factoryClass = $config->getSystemValue('ldapProviderFactory', null);
842
+            if (is_null($factoryClass)) {
843
+                throw new \Exception('ldapProviderFactory not set');
844
+            }
845
+            /** @var \OCP\LDAP\ILDAPProviderFactory $factory */
846
+            $factory = new $factoryClass($this);
847
+            return $factory->getLDAPProvider();
848
+        });
849
+        $this->registerService(ILockingProvider::class, function (Server $c) {
850
+            $ini = $c->getIniWrapper();
851
+            $config = $c->getConfig();
852
+            $ttl = $config->getSystemValue('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
853
+            if ($config->getSystemValue('filelocking.enabled', true) or (defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
854
+                /** @var \OC\Memcache\Factory $memcacheFactory */
855
+                $memcacheFactory = $c->getMemCacheFactory();
856
+                $memcache = $memcacheFactory->createLocking('lock');
857
+                if (!($memcache instanceof \OC\Memcache\NullCache)) {
858
+                    return new MemcacheLockingProvider($memcache, $ttl);
859
+                }
860
+                return new DBLockingProvider($c->getDatabaseConnection(), $c->getLogger(), new TimeFactory(), $ttl);
861
+            }
862
+            return new NoopLockingProvider();
863
+        });
864
+        $this->registerAlias('LockingProvider', ILockingProvider::class);
865
+
866
+        $this->registerService(\OCP\Files\Mount\IMountManager::class, function () {
867
+            return new \OC\Files\Mount\Manager();
868
+        });
869
+        $this->registerAlias('MountManager', \OCP\Files\Mount\IMountManager::class);
870
+
871
+        $this->registerService(\OCP\Files\IMimeTypeDetector::class, function (Server $c) {
872
+            return new \OC\Files\Type\Detection(
873
+                $c->getURLGenerator(),
874
+                \OC::$configDir,
875
+                \OC::$SERVERROOT . '/resources/config/'
876
+            );
877
+        });
878
+        $this->registerAlias('MimeTypeDetector', \OCP\Files\IMimeTypeDetector::class);
879
+
880
+        $this->registerService(\OCP\Files\IMimeTypeLoader::class, function (Server $c) {
881
+            return new \OC\Files\Type\Loader(
882
+                $c->getDatabaseConnection()
883
+            );
884
+        });
885
+        $this->registerAlias('MimeTypeLoader', \OCP\Files\IMimeTypeLoader::class);
886
+        $this->registerService(BundleFetcher::class, function () {
887
+            return new BundleFetcher($this->getL10N('lib'));
888
+        });
889
+        $this->registerService(\OCP\Notification\IManager::class, function (Server $c) {
890
+            return new Manager(
891
+                $c->query(IValidator::class)
892
+            );
893
+        });
894
+        $this->registerAlias('NotificationManager', \OCP\Notification\IManager::class);
895
+
896
+        $this->registerService(\OC\CapabilitiesManager::class, function (Server $c) {
897
+            $manager = new \OC\CapabilitiesManager($c->getLogger());
898
+            $manager->registerCapability(function () use ($c) {
899
+                return new \OC\OCS\CoreCapabilities($c->getConfig());
900
+            });
901
+            $manager->registerCapability(function () use ($c) {
902
+                return $c->query(\OC\Security\Bruteforce\Capabilities::class);
903
+            });
904
+            return $manager;
905
+        });
906
+        $this->registerAlias('CapabilitiesManager', \OC\CapabilitiesManager::class);
907
+
908
+        $this->registerService(\OCP\Comments\ICommentsManager::class, function (Server $c) {
909
+            $config = $c->getConfig();
910
+            $factoryClass = $config->getSystemValue('comments.managerFactory', CommentsManagerFactory::class);
911
+            /** @var \OCP\Comments\ICommentsManagerFactory $factory */
912
+            $factory = new $factoryClass($this);
913
+            $manager = $factory->getManager();
914
+
915
+            $manager->registerDisplayNameResolver('user', function($id) use ($c) {
916
+                $manager = $c->getUserManager();
917
+                $user = $manager->get($id);
918
+                if(is_null($user)) {
919
+                    $l = $c->getL10N('core');
920
+                    $displayName = $l->t('Unknown user');
921
+                } else {
922
+                    $displayName = $user->getDisplayName();
923
+                }
924
+                return $displayName;
925
+            });
926
+
927
+            return $manager;
928
+        });
929
+        $this->registerAlias('CommentsManager', \OCP\Comments\ICommentsManager::class);
930
+
931
+        $this->registerService('ThemingDefaults', function (Server $c) {
932
+            /*
933 933
 			 * Dark magic for autoloader.
934 934
 			 * If we do a class_exists it will try to load the class which will
935 935
 			 * make composer cache the result. Resulting in errors when enabling
936 936
 			 * the theming app.
937 937
 			 */
938
-			$prefixes = \OC::$composerAutoloader->getPrefixesPsr4();
939
-			if (isset($prefixes['OCA\\Theming\\'])) {
940
-				$classExists = true;
941
-			} else {
942
-				$classExists = false;
943
-			}
944
-
945
-			if ($classExists && $c->getConfig()->getSystemValue('installed', false) && $c->getAppManager()->isInstalled('theming') && $c->getTrustedDomainHelper()->isTrustedDomain($c->getRequest()->getInsecureServerHost())) {
946
-				return new ThemingDefaults(
947
-					$c->getConfig(),
948
-					$c->getL10N('theming'),
949
-					$c->getURLGenerator(),
950
-					$c->getAppDataDir('theming'),
951
-					$c->getMemCacheFactory(),
952
-					new Util($c->getConfig(), $this->getAppManager(), $this->getAppDataDir('theming')),
953
-					$this->getAppManager()
954
-				);
955
-			}
956
-			return new \OC_Defaults();
957
-		});
958
-		$this->registerService(SCSSCacher::class, function (Server $c) {
959
-			/** @var Factory $cacheFactory */
960
-			$cacheFactory = $c->query(Factory::class);
961
-			return new SCSSCacher(
962
-				$c->getLogger(),
963
-				$c->query(\OC\Files\AppData\Factory::class),
964
-				$c->getURLGenerator(),
965
-				$c->getConfig(),
966
-				$c->getThemingDefaults(),
967
-				\OC::$SERVERROOT,
968
-				$this->getMemCacheFactory()
969
-			);
970
-		});
971
-		$this->registerService(JSCombiner::class, function (Server $c) {
972
-			/** @var Factory $cacheFactory */
973
-			$cacheFactory = $c->query(Factory::class);
974
-			return new JSCombiner(
975
-				$c->getAppDataDir('js'),
976
-				$c->getURLGenerator(),
977
-				$this->getMemCacheFactory(),
978
-				$c->getSystemConfig(),
979
-				$c->getLogger()
980
-			);
981
-		});
982
-		$this->registerService(EventDispatcher::class, function () {
983
-			return new EventDispatcher();
984
-		});
985
-		$this->registerAlias('EventDispatcher', EventDispatcher::class);
986
-		$this->registerAlias(EventDispatcherInterface::class, EventDispatcher::class);
987
-
988
-		$this->registerService('CryptoWrapper', function (Server $c) {
989
-			// FIXME: Instantiiated here due to cyclic dependency
990
-			$request = new Request(
991
-				[
992
-					'get' => $_GET,
993
-					'post' => $_POST,
994
-					'files' => $_FILES,
995
-					'server' => $_SERVER,
996
-					'env' => $_ENV,
997
-					'cookies' => $_COOKIE,
998
-					'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
999
-						? $_SERVER['REQUEST_METHOD']
1000
-						: null,
1001
-				],
1002
-				$c->getSecureRandom(),
1003
-				$c->getConfig()
1004
-			);
1005
-
1006
-			return new CryptoWrapper(
1007
-				$c->getConfig(),
1008
-				$c->getCrypto(),
1009
-				$c->getSecureRandom(),
1010
-				$request
1011
-			);
1012
-		});
1013
-		$this->registerService('CsrfTokenManager', function (Server $c) {
1014
-			$tokenGenerator = new CsrfTokenGenerator($c->getSecureRandom());
1015
-
1016
-			return new CsrfTokenManager(
1017
-				$tokenGenerator,
1018
-				$c->query(SessionStorage::class)
1019
-			);
1020
-		});
1021
-		$this->registerService(SessionStorage::class, function (Server $c) {
1022
-			return new SessionStorage($c->getSession());
1023
-		});
1024
-		$this->registerService(\OCP\Security\IContentSecurityPolicyManager::class, function (Server $c) {
1025
-			return new ContentSecurityPolicyManager();
1026
-		});
1027
-		$this->registerAlias('ContentSecurityPolicyManager', \OCP\Security\IContentSecurityPolicyManager::class);
1028
-
1029
-		$this->registerService('ContentSecurityPolicyNonceManager', function (Server $c) {
1030
-			return new ContentSecurityPolicyNonceManager(
1031
-				$c->getCsrfTokenManager(),
1032
-				$c->getRequest()
1033
-			);
1034
-		});
1035
-
1036
-		$this->registerService(\OCP\Share\IManager::class, function (Server $c) {
1037
-			$config = $c->getConfig();
1038
-			$factoryClass = $config->getSystemValue('sharing.managerFactory', ProviderFactory::class);
1039
-			/** @var \OCP\Share\IProviderFactory $factory */
1040
-			$factory = new $factoryClass($this);
1041
-
1042
-			$manager = new \OC\Share20\Manager(
1043
-				$c->getLogger(),
1044
-				$c->getConfig(),
1045
-				$c->getSecureRandom(),
1046
-				$c->getHasher(),
1047
-				$c->getMountManager(),
1048
-				$c->getGroupManager(),
1049
-				$c->getL10N('lib'),
1050
-				$c->getL10NFactory(),
1051
-				$factory,
1052
-				$c->getUserManager(),
1053
-				$c->getLazyRootFolder(),
1054
-				$c->getEventDispatcher(),
1055
-				$c->getMailer(),
1056
-				$c->getURLGenerator(),
1057
-				$c->getThemingDefaults()
1058
-			);
1059
-
1060
-			return $manager;
1061
-		});
1062
-		$this->registerAlias('ShareManager', \OCP\Share\IManager::class);
1063
-
1064
-		$this->registerService(\OCP\Collaboration\Collaborators\ISearch::class, function(Server $c) {
1065
-			$instance = new Collaboration\Collaborators\Search($c);
1066
-
1067
-			// register default plugins
1068
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_USER', 'class' => UserPlugin::class]);
1069
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_GROUP', 'class' => GroupPlugin::class]);
1070
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_EMAIL', 'class' => MailPlugin::class]);
1071
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_REMOTE', 'class' => RemotePlugin::class]);
1072
-
1073
-			return $instance;
1074
-		});
1075
-		$this->registerAlias('CollaboratorSearch', \OCP\Collaboration\Collaborators\ISearch::class);
1076
-
1077
-		$this->registerAlias(\OCP\Collaboration\AutoComplete\IManager::class, \OC\Collaboration\AutoComplete\Manager::class);
1078
-
1079
-		$this->registerService('SettingsManager', function (Server $c) {
1080
-			$manager = new \OC\Settings\Manager(
1081
-				$c->getLogger(),
1082
-				$c->getDatabaseConnection(),
1083
-				$c->getL10N('lib'),
1084
-				$c->getConfig(),
1085
-				$c->getEncryptionManager(),
1086
-				$c->getUserManager(),
1087
-				$c->getLockingProvider(),
1088
-				$c->getRequest(),
1089
-				$c->getURLGenerator(),
1090
-				$c->query(AccountManager::class),
1091
-				$c->getGroupManager(),
1092
-				$c->getL10NFactory(),
1093
-				$c->getAppManager()
1094
-			);
1095
-			return $manager;
1096
-		});
1097
-		$this->registerService(\OC\Files\AppData\Factory::class, function (Server $c) {
1098
-			return new \OC\Files\AppData\Factory(
1099
-				$c->getRootFolder(),
1100
-				$c->getSystemConfig()
1101
-			);
1102
-		});
1103
-
1104
-		$this->registerService('LockdownManager', function (Server $c) {
1105
-			return new LockdownManager(function () use ($c) {
1106
-				return $c->getSession();
1107
-			});
1108
-		});
1109
-
1110
-		$this->registerService(\OCP\OCS\IDiscoveryService::class, function (Server $c) {
1111
-			return new DiscoveryService($c->getMemCacheFactory(), $c->getHTTPClientService());
1112
-		});
1113
-
1114
-		$this->registerService(ICloudIdManager::class, function (Server $c) {
1115
-			return new CloudIdManager();
1116
-		});
1117
-
1118
-		$this->registerAlias(\OCP\AppFramework\Utility\IControllerMethodReflector::class, \OC\AppFramework\Utility\ControllerMethodReflector::class);
1119
-		$this->registerAlias('ControllerMethodReflector', \OCP\AppFramework\Utility\IControllerMethodReflector::class);
1120
-
1121
-		$this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
1122
-		$this->registerAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
1123
-
1124
-		$this->registerService(Defaults::class, function (Server $c) {
1125
-			return new Defaults(
1126
-				$c->getThemingDefaults()
1127
-			);
1128
-		});
1129
-		$this->registerAlias('Defaults', \OCP\Defaults::class);
1130
-
1131
-		$this->registerService(\OCP\ISession::class, function (SimpleContainer $c) {
1132
-			return $c->query(\OCP\IUserSession::class)->getSession();
1133
-		});
1134
-
1135
-		$this->registerService(IShareHelper::class, function (Server $c) {
1136
-			return new ShareHelper(
1137
-				$c->query(\OCP\Share\IManager::class)
1138
-			);
1139
-		});
1140
-
1141
-		$this->registerService(Installer::class, function(Server $c) {
1142
-			return new Installer(
1143
-				$c->getAppFetcher(),
1144
-				$c->getHTTPClientService(),
1145
-				$c->getTempManager(),
1146
-				$c->getLogger(),
1147
-				$c->getConfig()
1148
-			);
1149
-		});
1150
-
1151
-		$this->registerService(IApiFactory::class, function(Server $c) {
1152
-			return new ApiFactory($c->getHTTPClientService());
1153
-		});
1154
-
1155
-		$this->registerService(IInstanceFactory::class, function(Server $c) {
1156
-			$memcacheFactory = $c->getMemCacheFactory();
1157
-			return new InstanceFactory($memcacheFactory->createLocal('remoteinstance.'), $c->getHTTPClientService());
1158
-		});
1159
-
1160
-		$this->registerService(IContactsStore::class, function(Server $c) {
1161
-			return new ContactsStore(
1162
-				$c->getContactsManager(),
1163
-				$c->getConfig(),
1164
-				$c->getUserManager(),
1165
-				$c->getGroupManager()
1166
-			);
1167
-		});
1168
-		$this->registerAlias(IContactsStore::class, ContactsStore::class);
1169
-
1170
-		$this->connectDispatcher();
1171
-	}
1172
-
1173
-	/**
1174
-	 * @return \OCP\Calendar\IManager
1175
-	 */
1176
-	public function getCalendarManager() {
1177
-		return $this->query('CalendarManager');
1178
-	}
1179
-
1180
-	private function connectDispatcher() {
1181
-		$dispatcher = $this->getEventDispatcher();
1182
-
1183
-		// Delete avatar on user deletion
1184
-		$dispatcher->addListener('OCP\IUser::preDelete', function(GenericEvent $e) {
1185
-			$logger = $this->getLogger();
1186
-			$manager = $this->getAvatarManager();
1187
-			/** @var IUser $user */
1188
-			$user = $e->getSubject();
1189
-
1190
-			try {
1191
-				$avatar = $manager->getAvatar($user->getUID());
1192
-				$avatar->remove();
1193
-			} catch (NotFoundException $e) {
1194
-				// no avatar to remove
1195
-			} catch (\Exception $e) {
1196
-				// Ignore exceptions
1197
-				$logger->info('Could not cleanup avatar of ' . $user->getUID());
1198
-			}
1199
-		});
1200
-
1201
-		$dispatcher->addListener('OCP\IUser::changeUser', function (GenericEvent $e) {
1202
-			$manager = $this->getAvatarManager();
1203
-			/** @var IUser $user */
1204
-			$user = $e->getSubject();
1205
-			$feature = $e->getArgument('feature');
1206
-			$oldValue = $e->getArgument('oldValue');
1207
-			$value = $e->getArgument('value');
1208
-
1209
-			try {
1210
-				$avatar = $manager->getAvatar($user->getUID());
1211
-				$avatar->userChanged($feature, $oldValue, $value);
1212
-			} catch (NotFoundException $e) {
1213
-				// no avatar to remove
1214
-			}
1215
-		});
1216
-	}
1217
-
1218
-	/**
1219
-	 * @return \OCP\Contacts\IManager
1220
-	 */
1221
-	public function getContactsManager() {
1222
-		return $this->query('ContactsManager');
1223
-	}
1224
-
1225
-	/**
1226
-	 * @return \OC\Encryption\Manager
1227
-	 */
1228
-	public function getEncryptionManager() {
1229
-		return $this->query('EncryptionManager');
1230
-	}
1231
-
1232
-	/**
1233
-	 * @return \OC\Encryption\File
1234
-	 */
1235
-	public function getEncryptionFilesHelper() {
1236
-		return $this->query('EncryptionFileHelper');
1237
-	}
1238
-
1239
-	/**
1240
-	 * @return \OCP\Encryption\Keys\IStorage
1241
-	 */
1242
-	public function getEncryptionKeyStorage() {
1243
-		return $this->query('EncryptionKeyStorage');
1244
-	}
1245
-
1246
-	/**
1247
-	 * The current request object holding all information about the request
1248
-	 * currently being processed is returned from this method.
1249
-	 * In case the current execution was not initiated by a web request null is returned
1250
-	 *
1251
-	 * @return \OCP\IRequest
1252
-	 */
1253
-	public function getRequest() {
1254
-		return $this->query('Request');
1255
-	}
1256
-
1257
-	/**
1258
-	 * Returns the preview manager which can create preview images for a given file
1259
-	 *
1260
-	 * @return \OCP\IPreview
1261
-	 */
1262
-	public function getPreviewManager() {
1263
-		return $this->query('PreviewManager');
1264
-	}
1265
-
1266
-	/**
1267
-	 * Returns the tag manager which can get and set tags for different object types
1268
-	 *
1269
-	 * @see \OCP\ITagManager::load()
1270
-	 * @return \OCP\ITagManager
1271
-	 */
1272
-	public function getTagManager() {
1273
-		return $this->query('TagManager');
1274
-	}
1275
-
1276
-	/**
1277
-	 * Returns the system-tag manager
1278
-	 *
1279
-	 * @return \OCP\SystemTag\ISystemTagManager
1280
-	 *
1281
-	 * @since 9.0.0
1282
-	 */
1283
-	public function getSystemTagManager() {
1284
-		return $this->query('SystemTagManager');
1285
-	}
1286
-
1287
-	/**
1288
-	 * Returns the system-tag object mapper
1289
-	 *
1290
-	 * @return \OCP\SystemTag\ISystemTagObjectMapper
1291
-	 *
1292
-	 * @since 9.0.0
1293
-	 */
1294
-	public function getSystemTagObjectMapper() {
1295
-		return $this->query('SystemTagObjectMapper');
1296
-	}
1297
-
1298
-	/**
1299
-	 * Returns the avatar manager, used for avatar functionality
1300
-	 *
1301
-	 * @return \OCP\IAvatarManager
1302
-	 */
1303
-	public function getAvatarManager() {
1304
-		return $this->query('AvatarManager');
1305
-	}
1306
-
1307
-	/**
1308
-	 * Returns the root folder of ownCloud's data directory
1309
-	 *
1310
-	 * @return \OCP\Files\IRootFolder
1311
-	 */
1312
-	public function getRootFolder() {
1313
-		return $this->query('LazyRootFolder');
1314
-	}
1315
-
1316
-	/**
1317
-	 * Returns the root folder of ownCloud's data directory
1318
-	 * This is the lazy variant so this gets only initialized once it
1319
-	 * is actually used.
1320
-	 *
1321
-	 * @return \OCP\Files\IRootFolder
1322
-	 */
1323
-	public function getLazyRootFolder() {
1324
-		return $this->query('LazyRootFolder');
1325
-	}
1326
-
1327
-	/**
1328
-	 * Returns a view to ownCloud's files folder
1329
-	 *
1330
-	 * @param string $userId user ID
1331
-	 * @return \OCP\Files\Folder|null
1332
-	 */
1333
-	public function getUserFolder($userId = null) {
1334
-		if ($userId === null) {
1335
-			$user = $this->getUserSession()->getUser();
1336
-			if (!$user) {
1337
-				return null;
1338
-			}
1339
-			$userId = $user->getUID();
1340
-		}
1341
-		$root = $this->getRootFolder();
1342
-		return $root->getUserFolder($userId);
1343
-	}
1344
-
1345
-	/**
1346
-	 * Returns an app-specific view in ownClouds data directory
1347
-	 *
1348
-	 * @return \OCP\Files\Folder
1349
-	 * @deprecated since 9.2.0 use IAppData
1350
-	 */
1351
-	public function getAppFolder() {
1352
-		$dir = '/' . \OC_App::getCurrentApp();
1353
-		$root = $this->getRootFolder();
1354
-		if (!$root->nodeExists($dir)) {
1355
-			$folder = $root->newFolder($dir);
1356
-		} else {
1357
-			$folder = $root->get($dir);
1358
-		}
1359
-		return $folder;
1360
-	}
1361
-
1362
-	/**
1363
-	 * @return \OC\User\Manager
1364
-	 */
1365
-	public function getUserManager() {
1366
-		return $this->query('UserManager');
1367
-	}
1368
-
1369
-	/**
1370
-	 * @return \OC\Group\Manager
1371
-	 */
1372
-	public function getGroupManager() {
1373
-		return $this->query('GroupManager');
1374
-	}
1375
-
1376
-	/**
1377
-	 * @return \OC\User\Session
1378
-	 */
1379
-	public function getUserSession() {
1380
-		return $this->query('UserSession');
1381
-	}
1382
-
1383
-	/**
1384
-	 * @return \OCP\ISession
1385
-	 */
1386
-	public function getSession() {
1387
-		return $this->query('UserSession')->getSession();
1388
-	}
1389
-
1390
-	/**
1391
-	 * @param \OCP\ISession $session
1392
-	 */
1393
-	public function setSession(\OCP\ISession $session) {
1394
-		$this->query(SessionStorage::class)->setSession($session);
1395
-		$this->query('UserSession')->setSession($session);
1396
-		$this->query(Store::class)->setSession($session);
1397
-	}
1398
-
1399
-	/**
1400
-	 * @return \OC\Authentication\TwoFactorAuth\Manager
1401
-	 */
1402
-	public function getTwoFactorAuthManager() {
1403
-		return $this->query('\OC\Authentication\TwoFactorAuth\Manager');
1404
-	}
1405
-
1406
-	/**
1407
-	 * @return \OC\NavigationManager
1408
-	 */
1409
-	public function getNavigationManager() {
1410
-		return $this->query('NavigationManager');
1411
-	}
1412
-
1413
-	/**
1414
-	 * @return \OCP\IConfig
1415
-	 */
1416
-	public function getConfig() {
1417
-		return $this->query('AllConfig');
1418
-	}
1419
-
1420
-	/**
1421
-	 * @return \OC\SystemConfig
1422
-	 */
1423
-	public function getSystemConfig() {
1424
-		return $this->query('SystemConfig');
1425
-	}
1426
-
1427
-	/**
1428
-	 * Returns the app config manager
1429
-	 *
1430
-	 * @return \OCP\IAppConfig
1431
-	 */
1432
-	public function getAppConfig() {
1433
-		return $this->query('AppConfig');
1434
-	}
1435
-
1436
-	/**
1437
-	 * @return \OCP\L10N\IFactory
1438
-	 */
1439
-	public function getL10NFactory() {
1440
-		return $this->query('L10NFactory');
1441
-	}
1442
-
1443
-	/**
1444
-	 * get an L10N instance
1445
-	 *
1446
-	 * @param string $app appid
1447
-	 * @param string $lang
1448
-	 * @return IL10N
1449
-	 */
1450
-	public function getL10N($app, $lang = null) {
1451
-		return $this->getL10NFactory()->get($app, $lang);
1452
-	}
1453
-
1454
-	/**
1455
-	 * @return \OCP\IURLGenerator
1456
-	 */
1457
-	public function getURLGenerator() {
1458
-		return $this->query('URLGenerator');
1459
-	}
1460
-
1461
-	/**
1462
-	 * @return \OCP\IHelper
1463
-	 */
1464
-	public function getHelper() {
1465
-		return $this->query('AppHelper');
1466
-	}
1467
-
1468
-	/**
1469
-	 * @return AppFetcher
1470
-	 */
1471
-	public function getAppFetcher() {
1472
-		return $this->query(AppFetcher::class);
1473
-	}
1474
-
1475
-	/**
1476
-	 * Returns an ICache instance. Since 8.1.0 it returns a fake cache. Use
1477
-	 * getMemCacheFactory() instead.
1478
-	 *
1479
-	 * @return \OCP\ICache
1480
-	 * @deprecated 8.1.0 use getMemCacheFactory to obtain a proper cache
1481
-	 */
1482
-	public function getCache() {
1483
-		return $this->query('UserCache');
1484
-	}
1485
-
1486
-	/**
1487
-	 * Returns an \OCP\CacheFactory instance
1488
-	 *
1489
-	 * @return \OCP\ICacheFactory
1490
-	 */
1491
-	public function getMemCacheFactory() {
1492
-		return $this->query('MemCacheFactory');
1493
-	}
1494
-
1495
-	/**
1496
-	 * Returns an \OC\RedisFactory instance
1497
-	 *
1498
-	 * @return \OC\RedisFactory
1499
-	 */
1500
-	public function getGetRedisFactory() {
1501
-		return $this->query('RedisFactory');
1502
-	}
1503
-
1504
-
1505
-	/**
1506
-	 * Returns the current session
1507
-	 *
1508
-	 * @return \OCP\IDBConnection
1509
-	 */
1510
-	public function getDatabaseConnection() {
1511
-		return $this->query('DatabaseConnection');
1512
-	}
1513
-
1514
-	/**
1515
-	 * Returns the activity manager
1516
-	 *
1517
-	 * @return \OCP\Activity\IManager
1518
-	 */
1519
-	public function getActivityManager() {
1520
-		return $this->query('ActivityManager');
1521
-	}
1522
-
1523
-	/**
1524
-	 * Returns an job list for controlling background jobs
1525
-	 *
1526
-	 * @return \OCP\BackgroundJob\IJobList
1527
-	 */
1528
-	public function getJobList() {
1529
-		return $this->query('JobList');
1530
-	}
1531
-
1532
-	/**
1533
-	 * Returns a logger instance
1534
-	 *
1535
-	 * @return \OCP\ILogger
1536
-	 */
1537
-	public function getLogger() {
1538
-		return $this->query('Logger');
1539
-	}
1540
-
1541
-	/**
1542
-	 * Returns a router for generating and matching urls
1543
-	 *
1544
-	 * @return \OCP\Route\IRouter
1545
-	 */
1546
-	public function getRouter() {
1547
-		return $this->query('Router');
1548
-	}
1549
-
1550
-	/**
1551
-	 * Returns a search instance
1552
-	 *
1553
-	 * @return \OCP\ISearch
1554
-	 */
1555
-	public function getSearch() {
1556
-		return $this->query('Search');
1557
-	}
1558
-
1559
-	/**
1560
-	 * Returns a SecureRandom instance
1561
-	 *
1562
-	 * @return \OCP\Security\ISecureRandom
1563
-	 */
1564
-	public function getSecureRandom() {
1565
-		return $this->query('SecureRandom');
1566
-	}
1567
-
1568
-	/**
1569
-	 * Returns a Crypto instance
1570
-	 *
1571
-	 * @return \OCP\Security\ICrypto
1572
-	 */
1573
-	public function getCrypto() {
1574
-		return $this->query('Crypto');
1575
-	}
1576
-
1577
-	/**
1578
-	 * Returns a Hasher instance
1579
-	 *
1580
-	 * @return \OCP\Security\IHasher
1581
-	 */
1582
-	public function getHasher() {
1583
-		return $this->query('Hasher');
1584
-	}
1585
-
1586
-	/**
1587
-	 * Returns a CredentialsManager instance
1588
-	 *
1589
-	 * @return \OCP\Security\ICredentialsManager
1590
-	 */
1591
-	public function getCredentialsManager() {
1592
-		return $this->query('CredentialsManager');
1593
-	}
1594
-
1595
-	/**
1596
-	 * Returns an instance of the HTTP helper class
1597
-	 *
1598
-	 * @deprecated Use getHTTPClientService()
1599
-	 * @return \OC\HTTPHelper
1600
-	 */
1601
-	public function getHTTPHelper() {
1602
-		return $this->query('HTTPHelper');
1603
-	}
1604
-
1605
-	/**
1606
-	 * Get the certificate manager for the user
1607
-	 *
1608
-	 * @param string $userId (optional) if not specified the current loggedin user is used, use null to get the system certificate manager
1609
-	 * @return \OCP\ICertificateManager | null if $uid is null and no user is logged in
1610
-	 */
1611
-	public function getCertificateManager($userId = '') {
1612
-		if ($userId === '') {
1613
-			$userSession = $this->getUserSession();
1614
-			$user = $userSession->getUser();
1615
-			if (is_null($user)) {
1616
-				return null;
1617
-			}
1618
-			$userId = $user->getUID();
1619
-		}
1620
-		return new CertificateManager(
1621
-			$userId,
1622
-			new View(),
1623
-			$this->getConfig(),
1624
-			$this->getLogger(),
1625
-			$this->getSecureRandom()
1626
-		);
1627
-	}
1628
-
1629
-	/**
1630
-	 * Returns an instance of the HTTP client service
1631
-	 *
1632
-	 * @return \OCP\Http\Client\IClientService
1633
-	 */
1634
-	public function getHTTPClientService() {
1635
-		return $this->query('HttpClientService');
1636
-	}
1637
-
1638
-	/**
1639
-	 * Create a new event source
1640
-	 *
1641
-	 * @return \OCP\IEventSource
1642
-	 */
1643
-	public function createEventSource() {
1644
-		return new \OC_EventSource();
1645
-	}
1646
-
1647
-	/**
1648
-	 * Get the active event logger
1649
-	 *
1650
-	 * The returned logger only logs data when debug mode is enabled
1651
-	 *
1652
-	 * @return \OCP\Diagnostics\IEventLogger
1653
-	 */
1654
-	public function getEventLogger() {
1655
-		return $this->query('EventLogger');
1656
-	}
1657
-
1658
-	/**
1659
-	 * Get the active query logger
1660
-	 *
1661
-	 * The returned logger only logs data when debug mode is enabled
1662
-	 *
1663
-	 * @return \OCP\Diagnostics\IQueryLogger
1664
-	 */
1665
-	public function getQueryLogger() {
1666
-		return $this->query('QueryLogger');
1667
-	}
1668
-
1669
-	/**
1670
-	 * Get the manager for temporary files and folders
1671
-	 *
1672
-	 * @return \OCP\ITempManager
1673
-	 */
1674
-	public function getTempManager() {
1675
-		return $this->query('TempManager');
1676
-	}
1677
-
1678
-	/**
1679
-	 * Get the app manager
1680
-	 *
1681
-	 * @return \OCP\App\IAppManager
1682
-	 */
1683
-	public function getAppManager() {
1684
-		return $this->query('AppManager');
1685
-	}
1686
-
1687
-	/**
1688
-	 * Creates a new mailer
1689
-	 *
1690
-	 * @return \OCP\Mail\IMailer
1691
-	 */
1692
-	public function getMailer() {
1693
-		return $this->query('Mailer');
1694
-	}
1695
-
1696
-	/**
1697
-	 * Get the webroot
1698
-	 *
1699
-	 * @return string
1700
-	 */
1701
-	public function getWebRoot() {
1702
-		return $this->webRoot;
1703
-	}
1704
-
1705
-	/**
1706
-	 * @return \OC\OCSClient
1707
-	 */
1708
-	public function getOcsClient() {
1709
-		return $this->query('OcsClient');
1710
-	}
1711
-
1712
-	/**
1713
-	 * @return \OCP\IDateTimeZone
1714
-	 */
1715
-	public function getDateTimeZone() {
1716
-		return $this->query('DateTimeZone');
1717
-	}
1718
-
1719
-	/**
1720
-	 * @return \OCP\IDateTimeFormatter
1721
-	 */
1722
-	public function getDateTimeFormatter() {
1723
-		return $this->query('DateTimeFormatter');
1724
-	}
1725
-
1726
-	/**
1727
-	 * @return \OCP\Files\Config\IMountProviderCollection
1728
-	 */
1729
-	public function getMountProviderCollection() {
1730
-		return $this->query('MountConfigManager');
1731
-	}
1732
-
1733
-	/**
1734
-	 * Get the IniWrapper
1735
-	 *
1736
-	 * @return IniGetWrapper
1737
-	 */
1738
-	public function getIniWrapper() {
1739
-		return $this->query('IniWrapper');
1740
-	}
1741
-
1742
-	/**
1743
-	 * @return \OCP\Command\IBus
1744
-	 */
1745
-	public function getCommandBus() {
1746
-		return $this->query('AsyncCommandBus');
1747
-	}
1748
-
1749
-	/**
1750
-	 * Get the trusted domain helper
1751
-	 *
1752
-	 * @return TrustedDomainHelper
1753
-	 */
1754
-	public function getTrustedDomainHelper() {
1755
-		return $this->query('TrustedDomainHelper');
1756
-	}
1757
-
1758
-	/**
1759
-	 * Get the locking provider
1760
-	 *
1761
-	 * @return \OCP\Lock\ILockingProvider
1762
-	 * @since 8.1.0
1763
-	 */
1764
-	public function getLockingProvider() {
1765
-		return $this->query('LockingProvider');
1766
-	}
1767
-
1768
-	/**
1769
-	 * @return \OCP\Files\Mount\IMountManager
1770
-	 **/
1771
-	function getMountManager() {
1772
-		return $this->query('MountManager');
1773
-	}
1774
-
1775
-	/** @return \OCP\Files\Config\IUserMountCache */
1776
-	function getUserMountCache() {
1777
-		return $this->query('UserMountCache');
1778
-	}
1779
-
1780
-	/**
1781
-	 * Get the MimeTypeDetector
1782
-	 *
1783
-	 * @return \OCP\Files\IMimeTypeDetector
1784
-	 */
1785
-	public function getMimeTypeDetector() {
1786
-		return $this->query('MimeTypeDetector');
1787
-	}
1788
-
1789
-	/**
1790
-	 * Get the MimeTypeLoader
1791
-	 *
1792
-	 * @return \OCP\Files\IMimeTypeLoader
1793
-	 */
1794
-	public function getMimeTypeLoader() {
1795
-		return $this->query('MimeTypeLoader');
1796
-	}
1797
-
1798
-	/**
1799
-	 * Get the manager of all the capabilities
1800
-	 *
1801
-	 * @return \OC\CapabilitiesManager
1802
-	 */
1803
-	public function getCapabilitiesManager() {
1804
-		return $this->query('CapabilitiesManager');
1805
-	}
1806
-
1807
-	/**
1808
-	 * Get the EventDispatcher
1809
-	 *
1810
-	 * @return EventDispatcherInterface
1811
-	 * @since 8.2.0
1812
-	 */
1813
-	public function getEventDispatcher() {
1814
-		return $this->query('EventDispatcher');
1815
-	}
1816
-
1817
-	/**
1818
-	 * Get the Notification Manager
1819
-	 *
1820
-	 * @return \OCP\Notification\IManager
1821
-	 * @since 8.2.0
1822
-	 */
1823
-	public function getNotificationManager() {
1824
-		return $this->query('NotificationManager');
1825
-	}
1826
-
1827
-	/**
1828
-	 * @return \OCP\Comments\ICommentsManager
1829
-	 */
1830
-	public function getCommentsManager() {
1831
-		return $this->query('CommentsManager');
1832
-	}
1833
-
1834
-	/**
1835
-	 * @return \OCA\Theming\ThemingDefaults
1836
-	 */
1837
-	public function getThemingDefaults() {
1838
-		return $this->query('ThemingDefaults');
1839
-	}
1840
-
1841
-	/**
1842
-	 * @return \OC\IntegrityCheck\Checker
1843
-	 */
1844
-	public function getIntegrityCodeChecker() {
1845
-		return $this->query('IntegrityCodeChecker');
1846
-	}
1847
-
1848
-	/**
1849
-	 * @return \OC\Session\CryptoWrapper
1850
-	 */
1851
-	public function getSessionCryptoWrapper() {
1852
-		return $this->query('CryptoWrapper');
1853
-	}
1854
-
1855
-	/**
1856
-	 * @return CsrfTokenManager
1857
-	 */
1858
-	public function getCsrfTokenManager() {
1859
-		return $this->query('CsrfTokenManager');
1860
-	}
1861
-
1862
-	/**
1863
-	 * @return Throttler
1864
-	 */
1865
-	public function getBruteForceThrottler() {
1866
-		return $this->query('Throttler');
1867
-	}
1868
-
1869
-	/**
1870
-	 * @return IContentSecurityPolicyManager
1871
-	 */
1872
-	public function getContentSecurityPolicyManager() {
1873
-		return $this->query('ContentSecurityPolicyManager');
1874
-	}
1875
-
1876
-	/**
1877
-	 * @return ContentSecurityPolicyNonceManager
1878
-	 */
1879
-	public function getContentSecurityPolicyNonceManager() {
1880
-		return $this->query('ContentSecurityPolicyNonceManager');
1881
-	}
1882
-
1883
-	/**
1884
-	 * Not a public API as of 8.2, wait for 9.0
1885
-	 *
1886
-	 * @return \OCA\Files_External\Service\BackendService
1887
-	 */
1888
-	public function getStoragesBackendService() {
1889
-		return $this->query('OCA\\Files_External\\Service\\BackendService');
1890
-	}
1891
-
1892
-	/**
1893
-	 * Not a public API as of 8.2, wait for 9.0
1894
-	 *
1895
-	 * @return \OCA\Files_External\Service\GlobalStoragesService
1896
-	 */
1897
-	public function getGlobalStoragesService() {
1898
-		return $this->query('OCA\\Files_External\\Service\\GlobalStoragesService');
1899
-	}
1900
-
1901
-	/**
1902
-	 * Not a public API as of 8.2, wait for 9.0
1903
-	 *
1904
-	 * @return \OCA\Files_External\Service\UserGlobalStoragesService
1905
-	 */
1906
-	public function getUserGlobalStoragesService() {
1907
-		return $this->query('OCA\\Files_External\\Service\\UserGlobalStoragesService');
1908
-	}
1909
-
1910
-	/**
1911
-	 * Not a public API as of 8.2, wait for 9.0
1912
-	 *
1913
-	 * @return \OCA\Files_External\Service\UserStoragesService
1914
-	 */
1915
-	public function getUserStoragesService() {
1916
-		return $this->query('OCA\\Files_External\\Service\\UserStoragesService');
1917
-	}
1918
-
1919
-	/**
1920
-	 * @return \OCP\Share\IManager
1921
-	 */
1922
-	public function getShareManager() {
1923
-		return $this->query('ShareManager');
1924
-	}
1925
-
1926
-	/**
1927
-	 * @return \OCP\Collaboration\Collaborators\ISearch
1928
-	 */
1929
-	public function getCollaboratorSearch() {
1930
-		return $this->query('CollaboratorSearch');
1931
-	}
1932
-
1933
-	/**
1934
-	 * @return \OCP\Collaboration\AutoComplete\IManager
1935
-	 */
1936
-	public function getAutoCompleteManager(){
1937
-		return $this->query(IManager::class);
1938
-	}
1939
-
1940
-	/**
1941
-	 * Returns the LDAP Provider
1942
-	 *
1943
-	 * @return \OCP\LDAP\ILDAPProvider
1944
-	 */
1945
-	public function getLDAPProvider() {
1946
-		return $this->query('LDAPProvider');
1947
-	}
1948
-
1949
-	/**
1950
-	 * @return \OCP\Settings\IManager
1951
-	 */
1952
-	public function getSettingsManager() {
1953
-		return $this->query('SettingsManager');
1954
-	}
1955
-
1956
-	/**
1957
-	 * @return \OCP\Files\IAppData
1958
-	 */
1959
-	public function getAppDataDir($app) {
1960
-		/** @var \OC\Files\AppData\Factory $factory */
1961
-		$factory = $this->query(\OC\Files\AppData\Factory::class);
1962
-		return $factory->get($app);
1963
-	}
1964
-
1965
-	/**
1966
-	 * @return \OCP\Lockdown\ILockdownManager
1967
-	 */
1968
-	public function getLockdownManager() {
1969
-		return $this->query('LockdownManager');
1970
-	}
1971
-
1972
-	/**
1973
-	 * @return \OCP\Federation\ICloudIdManager
1974
-	 */
1975
-	public function getCloudIdManager() {
1976
-		return $this->query(ICloudIdManager::class);
1977
-	}
1978
-
1979
-	/**
1980
-	 * @return \OCP\Remote\Api\IApiFactory
1981
-	 */
1982
-	public function getRemoteApiFactory() {
1983
-		return $this->query(IApiFactory::class);
1984
-	}
1985
-
1986
-	/**
1987
-	 * @return \OCP\Remote\IInstanceFactory
1988
-	 */
1989
-	public function getRemoteInstanceFactory() {
1990
-		return $this->query(IInstanceFactory::class);
1991
-	}
938
+            $prefixes = \OC::$composerAutoloader->getPrefixesPsr4();
939
+            if (isset($prefixes['OCA\\Theming\\'])) {
940
+                $classExists = true;
941
+            } else {
942
+                $classExists = false;
943
+            }
944
+
945
+            if ($classExists && $c->getConfig()->getSystemValue('installed', false) && $c->getAppManager()->isInstalled('theming') && $c->getTrustedDomainHelper()->isTrustedDomain($c->getRequest()->getInsecureServerHost())) {
946
+                return new ThemingDefaults(
947
+                    $c->getConfig(),
948
+                    $c->getL10N('theming'),
949
+                    $c->getURLGenerator(),
950
+                    $c->getAppDataDir('theming'),
951
+                    $c->getMemCacheFactory(),
952
+                    new Util($c->getConfig(), $this->getAppManager(), $this->getAppDataDir('theming')),
953
+                    $this->getAppManager()
954
+                );
955
+            }
956
+            return new \OC_Defaults();
957
+        });
958
+        $this->registerService(SCSSCacher::class, function (Server $c) {
959
+            /** @var Factory $cacheFactory */
960
+            $cacheFactory = $c->query(Factory::class);
961
+            return new SCSSCacher(
962
+                $c->getLogger(),
963
+                $c->query(\OC\Files\AppData\Factory::class),
964
+                $c->getURLGenerator(),
965
+                $c->getConfig(),
966
+                $c->getThemingDefaults(),
967
+                \OC::$SERVERROOT,
968
+                $this->getMemCacheFactory()
969
+            );
970
+        });
971
+        $this->registerService(JSCombiner::class, function (Server $c) {
972
+            /** @var Factory $cacheFactory */
973
+            $cacheFactory = $c->query(Factory::class);
974
+            return new JSCombiner(
975
+                $c->getAppDataDir('js'),
976
+                $c->getURLGenerator(),
977
+                $this->getMemCacheFactory(),
978
+                $c->getSystemConfig(),
979
+                $c->getLogger()
980
+            );
981
+        });
982
+        $this->registerService(EventDispatcher::class, function () {
983
+            return new EventDispatcher();
984
+        });
985
+        $this->registerAlias('EventDispatcher', EventDispatcher::class);
986
+        $this->registerAlias(EventDispatcherInterface::class, EventDispatcher::class);
987
+
988
+        $this->registerService('CryptoWrapper', function (Server $c) {
989
+            // FIXME: Instantiiated here due to cyclic dependency
990
+            $request = new Request(
991
+                [
992
+                    'get' => $_GET,
993
+                    'post' => $_POST,
994
+                    'files' => $_FILES,
995
+                    'server' => $_SERVER,
996
+                    'env' => $_ENV,
997
+                    'cookies' => $_COOKIE,
998
+                    'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
999
+                        ? $_SERVER['REQUEST_METHOD']
1000
+                        : null,
1001
+                ],
1002
+                $c->getSecureRandom(),
1003
+                $c->getConfig()
1004
+            );
1005
+
1006
+            return new CryptoWrapper(
1007
+                $c->getConfig(),
1008
+                $c->getCrypto(),
1009
+                $c->getSecureRandom(),
1010
+                $request
1011
+            );
1012
+        });
1013
+        $this->registerService('CsrfTokenManager', function (Server $c) {
1014
+            $tokenGenerator = new CsrfTokenGenerator($c->getSecureRandom());
1015
+
1016
+            return new CsrfTokenManager(
1017
+                $tokenGenerator,
1018
+                $c->query(SessionStorage::class)
1019
+            );
1020
+        });
1021
+        $this->registerService(SessionStorage::class, function (Server $c) {
1022
+            return new SessionStorage($c->getSession());
1023
+        });
1024
+        $this->registerService(\OCP\Security\IContentSecurityPolicyManager::class, function (Server $c) {
1025
+            return new ContentSecurityPolicyManager();
1026
+        });
1027
+        $this->registerAlias('ContentSecurityPolicyManager', \OCP\Security\IContentSecurityPolicyManager::class);
1028
+
1029
+        $this->registerService('ContentSecurityPolicyNonceManager', function (Server $c) {
1030
+            return new ContentSecurityPolicyNonceManager(
1031
+                $c->getCsrfTokenManager(),
1032
+                $c->getRequest()
1033
+            );
1034
+        });
1035
+
1036
+        $this->registerService(\OCP\Share\IManager::class, function (Server $c) {
1037
+            $config = $c->getConfig();
1038
+            $factoryClass = $config->getSystemValue('sharing.managerFactory', ProviderFactory::class);
1039
+            /** @var \OCP\Share\IProviderFactory $factory */
1040
+            $factory = new $factoryClass($this);
1041
+
1042
+            $manager = new \OC\Share20\Manager(
1043
+                $c->getLogger(),
1044
+                $c->getConfig(),
1045
+                $c->getSecureRandom(),
1046
+                $c->getHasher(),
1047
+                $c->getMountManager(),
1048
+                $c->getGroupManager(),
1049
+                $c->getL10N('lib'),
1050
+                $c->getL10NFactory(),
1051
+                $factory,
1052
+                $c->getUserManager(),
1053
+                $c->getLazyRootFolder(),
1054
+                $c->getEventDispatcher(),
1055
+                $c->getMailer(),
1056
+                $c->getURLGenerator(),
1057
+                $c->getThemingDefaults()
1058
+            );
1059
+
1060
+            return $manager;
1061
+        });
1062
+        $this->registerAlias('ShareManager', \OCP\Share\IManager::class);
1063
+
1064
+        $this->registerService(\OCP\Collaboration\Collaborators\ISearch::class, function(Server $c) {
1065
+            $instance = new Collaboration\Collaborators\Search($c);
1066
+
1067
+            // register default plugins
1068
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_USER', 'class' => UserPlugin::class]);
1069
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_GROUP', 'class' => GroupPlugin::class]);
1070
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_EMAIL', 'class' => MailPlugin::class]);
1071
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_REMOTE', 'class' => RemotePlugin::class]);
1072
+
1073
+            return $instance;
1074
+        });
1075
+        $this->registerAlias('CollaboratorSearch', \OCP\Collaboration\Collaborators\ISearch::class);
1076
+
1077
+        $this->registerAlias(\OCP\Collaboration\AutoComplete\IManager::class, \OC\Collaboration\AutoComplete\Manager::class);
1078
+
1079
+        $this->registerService('SettingsManager', function (Server $c) {
1080
+            $manager = new \OC\Settings\Manager(
1081
+                $c->getLogger(),
1082
+                $c->getDatabaseConnection(),
1083
+                $c->getL10N('lib'),
1084
+                $c->getConfig(),
1085
+                $c->getEncryptionManager(),
1086
+                $c->getUserManager(),
1087
+                $c->getLockingProvider(),
1088
+                $c->getRequest(),
1089
+                $c->getURLGenerator(),
1090
+                $c->query(AccountManager::class),
1091
+                $c->getGroupManager(),
1092
+                $c->getL10NFactory(),
1093
+                $c->getAppManager()
1094
+            );
1095
+            return $manager;
1096
+        });
1097
+        $this->registerService(\OC\Files\AppData\Factory::class, function (Server $c) {
1098
+            return new \OC\Files\AppData\Factory(
1099
+                $c->getRootFolder(),
1100
+                $c->getSystemConfig()
1101
+            );
1102
+        });
1103
+
1104
+        $this->registerService('LockdownManager', function (Server $c) {
1105
+            return new LockdownManager(function () use ($c) {
1106
+                return $c->getSession();
1107
+            });
1108
+        });
1109
+
1110
+        $this->registerService(\OCP\OCS\IDiscoveryService::class, function (Server $c) {
1111
+            return new DiscoveryService($c->getMemCacheFactory(), $c->getHTTPClientService());
1112
+        });
1113
+
1114
+        $this->registerService(ICloudIdManager::class, function (Server $c) {
1115
+            return new CloudIdManager();
1116
+        });
1117
+
1118
+        $this->registerAlias(\OCP\AppFramework\Utility\IControllerMethodReflector::class, \OC\AppFramework\Utility\ControllerMethodReflector::class);
1119
+        $this->registerAlias('ControllerMethodReflector', \OCP\AppFramework\Utility\IControllerMethodReflector::class);
1120
+
1121
+        $this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
1122
+        $this->registerAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
1123
+
1124
+        $this->registerService(Defaults::class, function (Server $c) {
1125
+            return new Defaults(
1126
+                $c->getThemingDefaults()
1127
+            );
1128
+        });
1129
+        $this->registerAlias('Defaults', \OCP\Defaults::class);
1130
+
1131
+        $this->registerService(\OCP\ISession::class, function (SimpleContainer $c) {
1132
+            return $c->query(\OCP\IUserSession::class)->getSession();
1133
+        });
1134
+
1135
+        $this->registerService(IShareHelper::class, function (Server $c) {
1136
+            return new ShareHelper(
1137
+                $c->query(\OCP\Share\IManager::class)
1138
+            );
1139
+        });
1140
+
1141
+        $this->registerService(Installer::class, function(Server $c) {
1142
+            return new Installer(
1143
+                $c->getAppFetcher(),
1144
+                $c->getHTTPClientService(),
1145
+                $c->getTempManager(),
1146
+                $c->getLogger(),
1147
+                $c->getConfig()
1148
+            );
1149
+        });
1150
+
1151
+        $this->registerService(IApiFactory::class, function(Server $c) {
1152
+            return new ApiFactory($c->getHTTPClientService());
1153
+        });
1154
+
1155
+        $this->registerService(IInstanceFactory::class, function(Server $c) {
1156
+            $memcacheFactory = $c->getMemCacheFactory();
1157
+            return new InstanceFactory($memcacheFactory->createLocal('remoteinstance.'), $c->getHTTPClientService());
1158
+        });
1159
+
1160
+        $this->registerService(IContactsStore::class, function(Server $c) {
1161
+            return new ContactsStore(
1162
+                $c->getContactsManager(),
1163
+                $c->getConfig(),
1164
+                $c->getUserManager(),
1165
+                $c->getGroupManager()
1166
+            );
1167
+        });
1168
+        $this->registerAlias(IContactsStore::class, ContactsStore::class);
1169
+
1170
+        $this->connectDispatcher();
1171
+    }
1172
+
1173
+    /**
1174
+     * @return \OCP\Calendar\IManager
1175
+     */
1176
+    public function getCalendarManager() {
1177
+        return $this->query('CalendarManager');
1178
+    }
1179
+
1180
+    private function connectDispatcher() {
1181
+        $dispatcher = $this->getEventDispatcher();
1182
+
1183
+        // Delete avatar on user deletion
1184
+        $dispatcher->addListener('OCP\IUser::preDelete', function(GenericEvent $e) {
1185
+            $logger = $this->getLogger();
1186
+            $manager = $this->getAvatarManager();
1187
+            /** @var IUser $user */
1188
+            $user = $e->getSubject();
1189
+
1190
+            try {
1191
+                $avatar = $manager->getAvatar($user->getUID());
1192
+                $avatar->remove();
1193
+            } catch (NotFoundException $e) {
1194
+                // no avatar to remove
1195
+            } catch (\Exception $e) {
1196
+                // Ignore exceptions
1197
+                $logger->info('Could not cleanup avatar of ' . $user->getUID());
1198
+            }
1199
+        });
1200
+
1201
+        $dispatcher->addListener('OCP\IUser::changeUser', function (GenericEvent $e) {
1202
+            $manager = $this->getAvatarManager();
1203
+            /** @var IUser $user */
1204
+            $user = $e->getSubject();
1205
+            $feature = $e->getArgument('feature');
1206
+            $oldValue = $e->getArgument('oldValue');
1207
+            $value = $e->getArgument('value');
1208
+
1209
+            try {
1210
+                $avatar = $manager->getAvatar($user->getUID());
1211
+                $avatar->userChanged($feature, $oldValue, $value);
1212
+            } catch (NotFoundException $e) {
1213
+                // no avatar to remove
1214
+            }
1215
+        });
1216
+    }
1217
+
1218
+    /**
1219
+     * @return \OCP\Contacts\IManager
1220
+     */
1221
+    public function getContactsManager() {
1222
+        return $this->query('ContactsManager');
1223
+    }
1224
+
1225
+    /**
1226
+     * @return \OC\Encryption\Manager
1227
+     */
1228
+    public function getEncryptionManager() {
1229
+        return $this->query('EncryptionManager');
1230
+    }
1231
+
1232
+    /**
1233
+     * @return \OC\Encryption\File
1234
+     */
1235
+    public function getEncryptionFilesHelper() {
1236
+        return $this->query('EncryptionFileHelper');
1237
+    }
1238
+
1239
+    /**
1240
+     * @return \OCP\Encryption\Keys\IStorage
1241
+     */
1242
+    public function getEncryptionKeyStorage() {
1243
+        return $this->query('EncryptionKeyStorage');
1244
+    }
1245
+
1246
+    /**
1247
+     * The current request object holding all information about the request
1248
+     * currently being processed is returned from this method.
1249
+     * In case the current execution was not initiated by a web request null is returned
1250
+     *
1251
+     * @return \OCP\IRequest
1252
+     */
1253
+    public function getRequest() {
1254
+        return $this->query('Request');
1255
+    }
1256
+
1257
+    /**
1258
+     * Returns the preview manager which can create preview images for a given file
1259
+     *
1260
+     * @return \OCP\IPreview
1261
+     */
1262
+    public function getPreviewManager() {
1263
+        return $this->query('PreviewManager');
1264
+    }
1265
+
1266
+    /**
1267
+     * Returns the tag manager which can get and set tags for different object types
1268
+     *
1269
+     * @see \OCP\ITagManager::load()
1270
+     * @return \OCP\ITagManager
1271
+     */
1272
+    public function getTagManager() {
1273
+        return $this->query('TagManager');
1274
+    }
1275
+
1276
+    /**
1277
+     * Returns the system-tag manager
1278
+     *
1279
+     * @return \OCP\SystemTag\ISystemTagManager
1280
+     *
1281
+     * @since 9.0.0
1282
+     */
1283
+    public function getSystemTagManager() {
1284
+        return $this->query('SystemTagManager');
1285
+    }
1286
+
1287
+    /**
1288
+     * Returns the system-tag object mapper
1289
+     *
1290
+     * @return \OCP\SystemTag\ISystemTagObjectMapper
1291
+     *
1292
+     * @since 9.0.0
1293
+     */
1294
+    public function getSystemTagObjectMapper() {
1295
+        return $this->query('SystemTagObjectMapper');
1296
+    }
1297
+
1298
+    /**
1299
+     * Returns the avatar manager, used for avatar functionality
1300
+     *
1301
+     * @return \OCP\IAvatarManager
1302
+     */
1303
+    public function getAvatarManager() {
1304
+        return $this->query('AvatarManager');
1305
+    }
1306
+
1307
+    /**
1308
+     * Returns the root folder of ownCloud's data directory
1309
+     *
1310
+     * @return \OCP\Files\IRootFolder
1311
+     */
1312
+    public function getRootFolder() {
1313
+        return $this->query('LazyRootFolder');
1314
+    }
1315
+
1316
+    /**
1317
+     * Returns the root folder of ownCloud's data directory
1318
+     * This is the lazy variant so this gets only initialized once it
1319
+     * is actually used.
1320
+     *
1321
+     * @return \OCP\Files\IRootFolder
1322
+     */
1323
+    public function getLazyRootFolder() {
1324
+        return $this->query('LazyRootFolder');
1325
+    }
1326
+
1327
+    /**
1328
+     * Returns a view to ownCloud's files folder
1329
+     *
1330
+     * @param string $userId user ID
1331
+     * @return \OCP\Files\Folder|null
1332
+     */
1333
+    public function getUserFolder($userId = null) {
1334
+        if ($userId === null) {
1335
+            $user = $this->getUserSession()->getUser();
1336
+            if (!$user) {
1337
+                return null;
1338
+            }
1339
+            $userId = $user->getUID();
1340
+        }
1341
+        $root = $this->getRootFolder();
1342
+        return $root->getUserFolder($userId);
1343
+    }
1344
+
1345
+    /**
1346
+     * Returns an app-specific view in ownClouds data directory
1347
+     *
1348
+     * @return \OCP\Files\Folder
1349
+     * @deprecated since 9.2.0 use IAppData
1350
+     */
1351
+    public function getAppFolder() {
1352
+        $dir = '/' . \OC_App::getCurrentApp();
1353
+        $root = $this->getRootFolder();
1354
+        if (!$root->nodeExists($dir)) {
1355
+            $folder = $root->newFolder($dir);
1356
+        } else {
1357
+            $folder = $root->get($dir);
1358
+        }
1359
+        return $folder;
1360
+    }
1361
+
1362
+    /**
1363
+     * @return \OC\User\Manager
1364
+     */
1365
+    public function getUserManager() {
1366
+        return $this->query('UserManager');
1367
+    }
1368
+
1369
+    /**
1370
+     * @return \OC\Group\Manager
1371
+     */
1372
+    public function getGroupManager() {
1373
+        return $this->query('GroupManager');
1374
+    }
1375
+
1376
+    /**
1377
+     * @return \OC\User\Session
1378
+     */
1379
+    public function getUserSession() {
1380
+        return $this->query('UserSession');
1381
+    }
1382
+
1383
+    /**
1384
+     * @return \OCP\ISession
1385
+     */
1386
+    public function getSession() {
1387
+        return $this->query('UserSession')->getSession();
1388
+    }
1389
+
1390
+    /**
1391
+     * @param \OCP\ISession $session
1392
+     */
1393
+    public function setSession(\OCP\ISession $session) {
1394
+        $this->query(SessionStorage::class)->setSession($session);
1395
+        $this->query('UserSession')->setSession($session);
1396
+        $this->query(Store::class)->setSession($session);
1397
+    }
1398
+
1399
+    /**
1400
+     * @return \OC\Authentication\TwoFactorAuth\Manager
1401
+     */
1402
+    public function getTwoFactorAuthManager() {
1403
+        return $this->query('\OC\Authentication\TwoFactorAuth\Manager');
1404
+    }
1405
+
1406
+    /**
1407
+     * @return \OC\NavigationManager
1408
+     */
1409
+    public function getNavigationManager() {
1410
+        return $this->query('NavigationManager');
1411
+    }
1412
+
1413
+    /**
1414
+     * @return \OCP\IConfig
1415
+     */
1416
+    public function getConfig() {
1417
+        return $this->query('AllConfig');
1418
+    }
1419
+
1420
+    /**
1421
+     * @return \OC\SystemConfig
1422
+     */
1423
+    public function getSystemConfig() {
1424
+        return $this->query('SystemConfig');
1425
+    }
1426
+
1427
+    /**
1428
+     * Returns the app config manager
1429
+     *
1430
+     * @return \OCP\IAppConfig
1431
+     */
1432
+    public function getAppConfig() {
1433
+        return $this->query('AppConfig');
1434
+    }
1435
+
1436
+    /**
1437
+     * @return \OCP\L10N\IFactory
1438
+     */
1439
+    public function getL10NFactory() {
1440
+        return $this->query('L10NFactory');
1441
+    }
1442
+
1443
+    /**
1444
+     * get an L10N instance
1445
+     *
1446
+     * @param string $app appid
1447
+     * @param string $lang
1448
+     * @return IL10N
1449
+     */
1450
+    public function getL10N($app, $lang = null) {
1451
+        return $this->getL10NFactory()->get($app, $lang);
1452
+    }
1453
+
1454
+    /**
1455
+     * @return \OCP\IURLGenerator
1456
+     */
1457
+    public function getURLGenerator() {
1458
+        return $this->query('URLGenerator');
1459
+    }
1460
+
1461
+    /**
1462
+     * @return \OCP\IHelper
1463
+     */
1464
+    public function getHelper() {
1465
+        return $this->query('AppHelper');
1466
+    }
1467
+
1468
+    /**
1469
+     * @return AppFetcher
1470
+     */
1471
+    public function getAppFetcher() {
1472
+        return $this->query(AppFetcher::class);
1473
+    }
1474
+
1475
+    /**
1476
+     * Returns an ICache instance. Since 8.1.0 it returns a fake cache. Use
1477
+     * getMemCacheFactory() instead.
1478
+     *
1479
+     * @return \OCP\ICache
1480
+     * @deprecated 8.1.0 use getMemCacheFactory to obtain a proper cache
1481
+     */
1482
+    public function getCache() {
1483
+        return $this->query('UserCache');
1484
+    }
1485
+
1486
+    /**
1487
+     * Returns an \OCP\CacheFactory instance
1488
+     *
1489
+     * @return \OCP\ICacheFactory
1490
+     */
1491
+    public function getMemCacheFactory() {
1492
+        return $this->query('MemCacheFactory');
1493
+    }
1494
+
1495
+    /**
1496
+     * Returns an \OC\RedisFactory instance
1497
+     *
1498
+     * @return \OC\RedisFactory
1499
+     */
1500
+    public function getGetRedisFactory() {
1501
+        return $this->query('RedisFactory');
1502
+    }
1503
+
1504
+
1505
+    /**
1506
+     * Returns the current session
1507
+     *
1508
+     * @return \OCP\IDBConnection
1509
+     */
1510
+    public function getDatabaseConnection() {
1511
+        return $this->query('DatabaseConnection');
1512
+    }
1513
+
1514
+    /**
1515
+     * Returns the activity manager
1516
+     *
1517
+     * @return \OCP\Activity\IManager
1518
+     */
1519
+    public function getActivityManager() {
1520
+        return $this->query('ActivityManager');
1521
+    }
1522
+
1523
+    /**
1524
+     * Returns an job list for controlling background jobs
1525
+     *
1526
+     * @return \OCP\BackgroundJob\IJobList
1527
+     */
1528
+    public function getJobList() {
1529
+        return $this->query('JobList');
1530
+    }
1531
+
1532
+    /**
1533
+     * Returns a logger instance
1534
+     *
1535
+     * @return \OCP\ILogger
1536
+     */
1537
+    public function getLogger() {
1538
+        return $this->query('Logger');
1539
+    }
1540
+
1541
+    /**
1542
+     * Returns a router for generating and matching urls
1543
+     *
1544
+     * @return \OCP\Route\IRouter
1545
+     */
1546
+    public function getRouter() {
1547
+        return $this->query('Router');
1548
+    }
1549
+
1550
+    /**
1551
+     * Returns a search instance
1552
+     *
1553
+     * @return \OCP\ISearch
1554
+     */
1555
+    public function getSearch() {
1556
+        return $this->query('Search');
1557
+    }
1558
+
1559
+    /**
1560
+     * Returns a SecureRandom instance
1561
+     *
1562
+     * @return \OCP\Security\ISecureRandom
1563
+     */
1564
+    public function getSecureRandom() {
1565
+        return $this->query('SecureRandom');
1566
+    }
1567
+
1568
+    /**
1569
+     * Returns a Crypto instance
1570
+     *
1571
+     * @return \OCP\Security\ICrypto
1572
+     */
1573
+    public function getCrypto() {
1574
+        return $this->query('Crypto');
1575
+    }
1576
+
1577
+    /**
1578
+     * Returns a Hasher instance
1579
+     *
1580
+     * @return \OCP\Security\IHasher
1581
+     */
1582
+    public function getHasher() {
1583
+        return $this->query('Hasher');
1584
+    }
1585
+
1586
+    /**
1587
+     * Returns a CredentialsManager instance
1588
+     *
1589
+     * @return \OCP\Security\ICredentialsManager
1590
+     */
1591
+    public function getCredentialsManager() {
1592
+        return $this->query('CredentialsManager');
1593
+    }
1594
+
1595
+    /**
1596
+     * Returns an instance of the HTTP helper class
1597
+     *
1598
+     * @deprecated Use getHTTPClientService()
1599
+     * @return \OC\HTTPHelper
1600
+     */
1601
+    public function getHTTPHelper() {
1602
+        return $this->query('HTTPHelper');
1603
+    }
1604
+
1605
+    /**
1606
+     * Get the certificate manager for the user
1607
+     *
1608
+     * @param string $userId (optional) if not specified the current loggedin user is used, use null to get the system certificate manager
1609
+     * @return \OCP\ICertificateManager | null if $uid is null and no user is logged in
1610
+     */
1611
+    public function getCertificateManager($userId = '') {
1612
+        if ($userId === '') {
1613
+            $userSession = $this->getUserSession();
1614
+            $user = $userSession->getUser();
1615
+            if (is_null($user)) {
1616
+                return null;
1617
+            }
1618
+            $userId = $user->getUID();
1619
+        }
1620
+        return new CertificateManager(
1621
+            $userId,
1622
+            new View(),
1623
+            $this->getConfig(),
1624
+            $this->getLogger(),
1625
+            $this->getSecureRandom()
1626
+        );
1627
+    }
1628
+
1629
+    /**
1630
+     * Returns an instance of the HTTP client service
1631
+     *
1632
+     * @return \OCP\Http\Client\IClientService
1633
+     */
1634
+    public function getHTTPClientService() {
1635
+        return $this->query('HttpClientService');
1636
+    }
1637
+
1638
+    /**
1639
+     * Create a new event source
1640
+     *
1641
+     * @return \OCP\IEventSource
1642
+     */
1643
+    public function createEventSource() {
1644
+        return new \OC_EventSource();
1645
+    }
1646
+
1647
+    /**
1648
+     * Get the active event logger
1649
+     *
1650
+     * The returned logger only logs data when debug mode is enabled
1651
+     *
1652
+     * @return \OCP\Diagnostics\IEventLogger
1653
+     */
1654
+    public function getEventLogger() {
1655
+        return $this->query('EventLogger');
1656
+    }
1657
+
1658
+    /**
1659
+     * Get the active query logger
1660
+     *
1661
+     * The returned logger only logs data when debug mode is enabled
1662
+     *
1663
+     * @return \OCP\Diagnostics\IQueryLogger
1664
+     */
1665
+    public function getQueryLogger() {
1666
+        return $this->query('QueryLogger');
1667
+    }
1668
+
1669
+    /**
1670
+     * Get the manager for temporary files and folders
1671
+     *
1672
+     * @return \OCP\ITempManager
1673
+     */
1674
+    public function getTempManager() {
1675
+        return $this->query('TempManager');
1676
+    }
1677
+
1678
+    /**
1679
+     * Get the app manager
1680
+     *
1681
+     * @return \OCP\App\IAppManager
1682
+     */
1683
+    public function getAppManager() {
1684
+        return $this->query('AppManager');
1685
+    }
1686
+
1687
+    /**
1688
+     * Creates a new mailer
1689
+     *
1690
+     * @return \OCP\Mail\IMailer
1691
+     */
1692
+    public function getMailer() {
1693
+        return $this->query('Mailer');
1694
+    }
1695
+
1696
+    /**
1697
+     * Get the webroot
1698
+     *
1699
+     * @return string
1700
+     */
1701
+    public function getWebRoot() {
1702
+        return $this->webRoot;
1703
+    }
1704
+
1705
+    /**
1706
+     * @return \OC\OCSClient
1707
+     */
1708
+    public function getOcsClient() {
1709
+        return $this->query('OcsClient');
1710
+    }
1711
+
1712
+    /**
1713
+     * @return \OCP\IDateTimeZone
1714
+     */
1715
+    public function getDateTimeZone() {
1716
+        return $this->query('DateTimeZone');
1717
+    }
1718
+
1719
+    /**
1720
+     * @return \OCP\IDateTimeFormatter
1721
+     */
1722
+    public function getDateTimeFormatter() {
1723
+        return $this->query('DateTimeFormatter');
1724
+    }
1725
+
1726
+    /**
1727
+     * @return \OCP\Files\Config\IMountProviderCollection
1728
+     */
1729
+    public function getMountProviderCollection() {
1730
+        return $this->query('MountConfigManager');
1731
+    }
1732
+
1733
+    /**
1734
+     * Get the IniWrapper
1735
+     *
1736
+     * @return IniGetWrapper
1737
+     */
1738
+    public function getIniWrapper() {
1739
+        return $this->query('IniWrapper');
1740
+    }
1741
+
1742
+    /**
1743
+     * @return \OCP\Command\IBus
1744
+     */
1745
+    public function getCommandBus() {
1746
+        return $this->query('AsyncCommandBus');
1747
+    }
1748
+
1749
+    /**
1750
+     * Get the trusted domain helper
1751
+     *
1752
+     * @return TrustedDomainHelper
1753
+     */
1754
+    public function getTrustedDomainHelper() {
1755
+        return $this->query('TrustedDomainHelper');
1756
+    }
1757
+
1758
+    /**
1759
+     * Get the locking provider
1760
+     *
1761
+     * @return \OCP\Lock\ILockingProvider
1762
+     * @since 8.1.0
1763
+     */
1764
+    public function getLockingProvider() {
1765
+        return $this->query('LockingProvider');
1766
+    }
1767
+
1768
+    /**
1769
+     * @return \OCP\Files\Mount\IMountManager
1770
+     **/
1771
+    function getMountManager() {
1772
+        return $this->query('MountManager');
1773
+    }
1774
+
1775
+    /** @return \OCP\Files\Config\IUserMountCache */
1776
+    function getUserMountCache() {
1777
+        return $this->query('UserMountCache');
1778
+    }
1779
+
1780
+    /**
1781
+     * Get the MimeTypeDetector
1782
+     *
1783
+     * @return \OCP\Files\IMimeTypeDetector
1784
+     */
1785
+    public function getMimeTypeDetector() {
1786
+        return $this->query('MimeTypeDetector');
1787
+    }
1788
+
1789
+    /**
1790
+     * Get the MimeTypeLoader
1791
+     *
1792
+     * @return \OCP\Files\IMimeTypeLoader
1793
+     */
1794
+    public function getMimeTypeLoader() {
1795
+        return $this->query('MimeTypeLoader');
1796
+    }
1797
+
1798
+    /**
1799
+     * Get the manager of all the capabilities
1800
+     *
1801
+     * @return \OC\CapabilitiesManager
1802
+     */
1803
+    public function getCapabilitiesManager() {
1804
+        return $this->query('CapabilitiesManager');
1805
+    }
1806
+
1807
+    /**
1808
+     * Get the EventDispatcher
1809
+     *
1810
+     * @return EventDispatcherInterface
1811
+     * @since 8.2.0
1812
+     */
1813
+    public function getEventDispatcher() {
1814
+        return $this->query('EventDispatcher');
1815
+    }
1816
+
1817
+    /**
1818
+     * Get the Notification Manager
1819
+     *
1820
+     * @return \OCP\Notification\IManager
1821
+     * @since 8.2.0
1822
+     */
1823
+    public function getNotificationManager() {
1824
+        return $this->query('NotificationManager');
1825
+    }
1826
+
1827
+    /**
1828
+     * @return \OCP\Comments\ICommentsManager
1829
+     */
1830
+    public function getCommentsManager() {
1831
+        return $this->query('CommentsManager');
1832
+    }
1833
+
1834
+    /**
1835
+     * @return \OCA\Theming\ThemingDefaults
1836
+     */
1837
+    public function getThemingDefaults() {
1838
+        return $this->query('ThemingDefaults');
1839
+    }
1840
+
1841
+    /**
1842
+     * @return \OC\IntegrityCheck\Checker
1843
+     */
1844
+    public function getIntegrityCodeChecker() {
1845
+        return $this->query('IntegrityCodeChecker');
1846
+    }
1847
+
1848
+    /**
1849
+     * @return \OC\Session\CryptoWrapper
1850
+     */
1851
+    public function getSessionCryptoWrapper() {
1852
+        return $this->query('CryptoWrapper');
1853
+    }
1854
+
1855
+    /**
1856
+     * @return CsrfTokenManager
1857
+     */
1858
+    public function getCsrfTokenManager() {
1859
+        return $this->query('CsrfTokenManager');
1860
+    }
1861
+
1862
+    /**
1863
+     * @return Throttler
1864
+     */
1865
+    public function getBruteForceThrottler() {
1866
+        return $this->query('Throttler');
1867
+    }
1868
+
1869
+    /**
1870
+     * @return IContentSecurityPolicyManager
1871
+     */
1872
+    public function getContentSecurityPolicyManager() {
1873
+        return $this->query('ContentSecurityPolicyManager');
1874
+    }
1875
+
1876
+    /**
1877
+     * @return ContentSecurityPolicyNonceManager
1878
+     */
1879
+    public function getContentSecurityPolicyNonceManager() {
1880
+        return $this->query('ContentSecurityPolicyNonceManager');
1881
+    }
1882
+
1883
+    /**
1884
+     * Not a public API as of 8.2, wait for 9.0
1885
+     *
1886
+     * @return \OCA\Files_External\Service\BackendService
1887
+     */
1888
+    public function getStoragesBackendService() {
1889
+        return $this->query('OCA\\Files_External\\Service\\BackendService');
1890
+    }
1891
+
1892
+    /**
1893
+     * Not a public API as of 8.2, wait for 9.0
1894
+     *
1895
+     * @return \OCA\Files_External\Service\GlobalStoragesService
1896
+     */
1897
+    public function getGlobalStoragesService() {
1898
+        return $this->query('OCA\\Files_External\\Service\\GlobalStoragesService');
1899
+    }
1900
+
1901
+    /**
1902
+     * Not a public API as of 8.2, wait for 9.0
1903
+     *
1904
+     * @return \OCA\Files_External\Service\UserGlobalStoragesService
1905
+     */
1906
+    public function getUserGlobalStoragesService() {
1907
+        return $this->query('OCA\\Files_External\\Service\\UserGlobalStoragesService');
1908
+    }
1909
+
1910
+    /**
1911
+     * Not a public API as of 8.2, wait for 9.0
1912
+     *
1913
+     * @return \OCA\Files_External\Service\UserStoragesService
1914
+     */
1915
+    public function getUserStoragesService() {
1916
+        return $this->query('OCA\\Files_External\\Service\\UserStoragesService');
1917
+    }
1918
+
1919
+    /**
1920
+     * @return \OCP\Share\IManager
1921
+     */
1922
+    public function getShareManager() {
1923
+        return $this->query('ShareManager');
1924
+    }
1925
+
1926
+    /**
1927
+     * @return \OCP\Collaboration\Collaborators\ISearch
1928
+     */
1929
+    public function getCollaboratorSearch() {
1930
+        return $this->query('CollaboratorSearch');
1931
+    }
1932
+
1933
+    /**
1934
+     * @return \OCP\Collaboration\AutoComplete\IManager
1935
+     */
1936
+    public function getAutoCompleteManager(){
1937
+        return $this->query(IManager::class);
1938
+    }
1939
+
1940
+    /**
1941
+     * Returns the LDAP Provider
1942
+     *
1943
+     * @return \OCP\LDAP\ILDAPProvider
1944
+     */
1945
+    public function getLDAPProvider() {
1946
+        return $this->query('LDAPProvider');
1947
+    }
1948
+
1949
+    /**
1950
+     * @return \OCP\Settings\IManager
1951
+     */
1952
+    public function getSettingsManager() {
1953
+        return $this->query('SettingsManager');
1954
+    }
1955
+
1956
+    /**
1957
+     * @return \OCP\Files\IAppData
1958
+     */
1959
+    public function getAppDataDir($app) {
1960
+        /** @var \OC\Files\AppData\Factory $factory */
1961
+        $factory = $this->query(\OC\Files\AppData\Factory::class);
1962
+        return $factory->get($app);
1963
+    }
1964
+
1965
+    /**
1966
+     * @return \OCP\Lockdown\ILockdownManager
1967
+     */
1968
+    public function getLockdownManager() {
1969
+        return $this->query('LockdownManager');
1970
+    }
1971
+
1972
+    /**
1973
+     * @return \OCP\Federation\ICloudIdManager
1974
+     */
1975
+    public function getCloudIdManager() {
1976
+        return $this->query(ICloudIdManager::class);
1977
+    }
1978
+
1979
+    /**
1980
+     * @return \OCP\Remote\Api\IApiFactory
1981
+     */
1982
+    public function getRemoteApiFactory() {
1983
+        return $this->query(IApiFactory::class);
1984
+    }
1985
+
1986
+    /**
1987
+     * @return \OCP\Remote\IInstanceFactory
1988
+     */
1989
+    public function getRemoteInstanceFactory() {
1990
+        return $this->query(IInstanceFactory::class);
1991
+    }
1992 1992
 }
Please login to merge, or discard this patch.
lib/private/Template/JSCombiner.php 1 patch
Indentation   +213 added lines, -213 removed lines patch added patch discarded remove patch
@@ -36,217 +36,217 @@
 block discarded – undo
36 36
 
37 37
 class JSCombiner {
38 38
 
39
-	/** @var IAppData */
40
-	protected $appData;
41
-
42
-	/** @var IURLGenerator */
43
-	protected $urlGenerator;
44
-
45
-	/** @var ICache */
46
-	protected $depsCache;
47
-
48
-	/** @var SystemConfig */
49
-	protected $config;
50
-
51
-	/** @var ILogger */
52
-	protected $logger;
53
-
54
-	/** @var ICacheFactory */
55
-	private $cacheFactory;
56
-
57
-	/**
58
-	 * @param IAppData $appData
59
-	 * @param IURLGenerator $urlGenerator
60
-	 * @param ICacheFactory $cacheFactory
61
-	 * @param SystemConfig $config
62
-	 * @param ILogger $logger
63
-	 */
64
-	public function __construct(IAppData $appData,
65
-								IURLGenerator $urlGenerator,
66
-								ICacheFactory $cacheFactory,
67
-								SystemConfig $config,
68
-								ILogger $logger) {
69
-		$this->appData = $appData;
70
-		$this->urlGenerator = $urlGenerator;
71
-		$this->cacheFactory = $cacheFactory;
72
-		$this->depsCache = $this->cacheFactory->createDistributed('JS-' . md5($this->urlGenerator->getBaseUrl()));
73
-		$this->config = $config;
74
-		$this->logger = $logger;
75
-	}
76
-
77
-	/**
78
-	 * @param string $root
79
-	 * @param string $file
80
-	 * @param string $app
81
-	 * @return bool
82
-	 */
83
-	public function process($root, $file, $app) {
84
-		if ($this->config->getValue('debug') || !$this->config->getValue('installed')) {
85
-			return false;
86
-		}
87
-
88
-		$path = explode('/', $root . '/' . $file);
89
-
90
-		$fileName = array_pop($path);
91
-		$path = implode('/', $path);
92
-
93
-		try {
94
-			$folder = $this->appData->getFolder($app);
95
-		} catch(NotFoundException $e) {
96
-			// creating css appdata folder
97
-			$folder = $this->appData->newFolder($app);
98
-		}
99
-
100
-		if($this->isCached($fileName, $folder)) {
101
-			return true;
102
-		}
103
-		return $this->cache($path, $fileName, $folder);
104
-	}
105
-
106
-	/**
107
-	 * @param string $fileName
108
-	 * @param ISimpleFolder $folder
109
-	 * @return bool
110
-	 */
111
-	protected function isCached($fileName, ISimpleFolder $folder) {
112
-		$fileName = str_replace('.json', '.js', $fileName) . '.deps';
113
-		try {
114
-			$deps = $this->depsCache->get($folder->getName() . '-' . $fileName);
115
-			if ($deps === null || $deps === '') {
116
-				$depFile = $folder->getFile($fileName);
117
-				$deps = $depFile->getContent();
118
-			}
119
-			// check again
120
-			if ($deps === null || $deps === '') {
121
-				$this->logger->info('JSCombiner: deps file empty: ' . $fileName);
122
-				return false;
123
-			}
124
-
125
-			$deps = json_decode($deps, true);
126
-
127
-			if ($deps === NULL) {
128
-				return false;
129
-			}
130
-
131
-			foreach ($deps as $file=>$mtime) {
132
-				if (!file_exists($file) || filemtime($file) > $mtime) {
133
-					return false;
134
-				}
135
-			}
136
-
137
-			return true;
138
-		} catch(NotFoundException $e) {
139
-			return false;
140
-		}
141
-	}
142
-
143
-	/**
144
-	 * @param string $path
145
-	 * @param string $fileName
146
-	 * @param ISimpleFolder $folder
147
-	 * @return bool
148
-	 */
149
-	protected function cache($path, $fileName, ISimpleFolder $folder) {
150
-		$deps = [];
151
-		$fullPath = $path . '/' . $fileName;
152
-		$data = json_decode(file_get_contents($fullPath));
153
-		$deps[$fullPath] = filemtime($fullPath);
154
-
155
-		$res = '';
156
-		foreach ($data as $file) {
157
-			$filePath = $path . '/' . $file;
158
-
159
-			if (is_file($filePath)) {
160
-				$res .= file_get_contents($filePath);
161
-				$res .= PHP_EOL . PHP_EOL;
162
-				$deps[$filePath] = filemtime($filePath);
163
-			}
164
-		}
165
-
166
-		$fileName = str_replace('.json', '.js', $fileName);
167
-		try {
168
-			$cachedfile = $folder->getFile($fileName);
169
-		} catch(NotFoundException $e) {
170
-			$cachedfile = $folder->newFile($fileName);
171
-		}
172
-
173
-		$depFileName = $fileName . '.deps';
174
-		try {
175
-			$depFile = $folder->getFile($depFileName);
176
-		} catch (NotFoundException $e) {
177
-			$depFile = $folder->newFile($depFileName);
178
-		}
179
-
180
-		try {
181
-			$gzipFile = $folder->getFile($fileName . '.gzip'); # Safari doesn't like .gz
182
-		} catch (NotFoundException $e) {
183
-			$gzipFile = $folder->newFile($fileName . '.gzip'); # Safari doesn't like .gz
184
-		}
185
-
186
-		try {
187
-			$cachedfile->putContent($res);
188
-			$deps = json_encode($deps);
189
-			$depFile->putContent($deps);
190
-			$this->depsCache->set($folder->getName() . '-' . $depFileName, $deps);
191
-			$gzipFile->putContent(gzencode($res, 9));
192
-			$this->logger->debug('JSCombiner: successfully cached: ' . $fileName);
193
-			return true;
194
-		} catch (NotPermittedException $e) {
195
-			$this->logger->error('JSCombiner: unable to cache: ' . $fileName);
196
-			return false;
197
-		}
198
-	}
199
-
200
-	/**
201
-	 * @param string $appName
202
-	 * @param string $fileName
203
-	 * @return string
204
-	 */
205
-	public function getCachedJS($appName, $fileName) {
206
-		$tmpfileLoc = explode('/', $fileName);
207
-		$fileName = array_pop($tmpfileLoc);
208
-		$fileName = str_replace('.json', '.js', $fileName);
209
-
210
-		return substr($this->urlGenerator->linkToRoute('core.Js.getJs', array('fileName' => $fileName, 'appName' => $appName)), strlen(\OC::$WEBROOT) + 1);
211
-	}
212
-
213
-	/**
214
-	 * @param string $root
215
-	 * @param string $file
216
-	 * @return string[]
217
-	 */
218
-	public function getContent($root, $file) {
219
-		/** @var array $data */
220
-		$data = json_decode(file_get_contents($root . '/' . $file));
221
-		if(!is_array($data)) {
222
-			return [];
223
-		}
224
-
225
-		$path = explode('/', $file);
226
-		array_pop($path);
227
-		$path = implode('/', $path);
228
-
229
-		$result = [];
230
-		foreach ($data as $f) {
231
-			$result[] = $path . '/' . $f;
232
-		}
233
-
234
-		return $result;
235
-	}
236
-
237
-
238
-	/**
239
-	 * Clear cache with combined javascript files
240
-	 *
241
-	 * @throws NotFoundException
242
-	 */
243
-	public function resetCache() {
244
-		$this->cacheFactory->createDistributed('JS-')->clear();
245
-		$appDirectory = $this->appData->getDirectoryListing();
246
-		foreach ($appDirectory as $folder) {
247
-			foreach ($folder->getDirectoryListing() as $file) {
248
-				$file->delete();
249
-			}
250
-		}
251
-	}
39
+    /** @var IAppData */
40
+    protected $appData;
41
+
42
+    /** @var IURLGenerator */
43
+    protected $urlGenerator;
44
+
45
+    /** @var ICache */
46
+    protected $depsCache;
47
+
48
+    /** @var SystemConfig */
49
+    protected $config;
50
+
51
+    /** @var ILogger */
52
+    protected $logger;
53
+
54
+    /** @var ICacheFactory */
55
+    private $cacheFactory;
56
+
57
+    /**
58
+     * @param IAppData $appData
59
+     * @param IURLGenerator $urlGenerator
60
+     * @param ICacheFactory $cacheFactory
61
+     * @param SystemConfig $config
62
+     * @param ILogger $logger
63
+     */
64
+    public function __construct(IAppData $appData,
65
+                                IURLGenerator $urlGenerator,
66
+                                ICacheFactory $cacheFactory,
67
+                                SystemConfig $config,
68
+                                ILogger $logger) {
69
+        $this->appData = $appData;
70
+        $this->urlGenerator = $urlGenerator;
71
+        $this->cacheFactory = $cacheFactory;
72
+        $this->depsCache = $this->cacheFactory->createDistributed('JS-' . md5($this->urlGenerator->getBaseUrl()));
73
+        $this->config = $config;
74
+        $this->logger = $logger;
75
+    }
76
+
77
+    /**
78
+     * @param string $root
79
+     * @param string $file
80
+     * @param string $app
81
+     * @return bool
82
+     */
83
+    public function process($root, $file, $app) {
84
+        if ($this->config->getValue('debug') || !$this->config->getValue('installed')) {
85
+            return false;
86
+        }
87
+
88
+        $path = explode('/', $root . '/' . $file);
89
+
90
+        $fileName = array_pop($path);
91
+        $path = implode('/', $path);
92
+
93
+        try {
94
+            $folder = $this->appData->getFolder($app);
95
+        } catch(NotFoundException $e) {
96
+            // creating css appdata folder
97
+            $folder = $this->appData->newFolder($app);
98
+        }
99
+
100
+        if($this->isCached($fileName, $folder)) {
101
+            return true;
102
+        }
103
+        return $this->cache($path, $fileName, $folder);
104
+    }
105
+
106
+    /**
107
+     * @param string $fileName
108
+     * @param ISimpleFolder $folder
109
+     * @return bool
110
+     */
111
+    protected function isCached($fileName, ISimpleFolder $folder) {
112
+        $fileName = str_replace('.json', '.js', $fileName) . '.deps';
113
+        try {
114
+            $deps = $this->depsCache->get($folder->getName() . '-' . $fileName);
115
+            if ($deps === null || $deps === '') {
116
+                $depFile = $folder->getFile($fileName);
117
+                $deps = $depFile->getContent();
118
+            }
119
+            // check again
120
+            if ($deps === null || $deps === '') {
121
+                $this->logger->info('JSCombiner: deps file empty: ' . $fileName);
122
+                return false;
123
+            }
124
+
125
+            $deps = json_decode($deps, true);
126
+
127
+            if ($deps === NULL) {
128
+                return false;
129
+            }
130
+
131
+            foreach ($deps as $file=>$mtime) {
132
+                if (!file_exists($file) || filemtime($file) > $mtime) {
133
+                    return false;
134
+                }
135
+            }
136
+
137
+            return true;
138
+        } catch(NotFoundException $e) {
139
+            return false;
140
+        }
141
+    }
142
+
143
+    /**
144
+     * @param string $path
145
+     * @param string $fileName
146
+     * @param ISimpleFolder $folder
147
+     * @return bool
148
+     */
149
+    protected function cache($path, $fileName, ISimpleFolder $folder) {
150
+        $deps = [];
151
+        $fullPath = $path . '/' . $fileName;
152
+        $data = json_decode(file_get_contents($fullPath));
153
+        $deps[$fullPath] = filemtime($fullPath);
154
+
155
+        $res = '';
156
+        foreach ($data as $file) {
157
+            $filePath = $path . '/' . $file;
158
+
159
+            if (is_file($filePath)) {
160
+                $res .= file_get_contents($filePath);
161
+                $res .= PHP_EOL . PHP_EOL;
162
+                $deps[$filePath] = filemtime($filePath);
163
+            }
164
+        }
165
+
166
+        $fileName = str_replace('.json', '.js', $fileName);
167
+        try {
168
+            $cachedfile = $folder->getFile($fileName);
169
+        } catch(NotFoundException $e) {
170
+            $cachedfile = $folder->newFile($fileName);
171
+        }
172
+
173
+        $depFileName = $fileName . '.deps';
174
+        try {
175
+            $depFile = $folder->getFile($depFileName);
176
+        } catch (NotFoundException $e) {
177
+            $depFile = $folder->newFile($depFileName);
178
+        }
179
+
180
+        try {
181
+            $gzipFile = $folder->getFile($fileName . '.gzip'); # Safari doesn't like .gz
182
+        } catch (NotFoundException $e) {
183
+            $gzipFile = $folder->newFile($fileName . '.gzip'); # Safari doesn't like .gz
184
+        }
185
+
186
+        try {
187
+            $cachedfile->putContent($res);
188
+            $deps = json_encode($deps);
189
+            $depFile->putContent($deps);
190
+            $this->depsCache->set($folder->getName() . '-' . $depFileName, $deps);
191
+            $gzipFile->putContent(gzencode($res, 9));
192
+            $this->logger->debug('JSCombiner: successfully cached: ' . $fileName);
193
+            return true;
194
+        } catch (NotPermittedException $e) {
195
+            $this->logger->error('JSCombiner: unable to cache: ' . $fileName);
196
+            return false;
197
+        }
198
+    }
199
+
200
+    /**
201
+     * @param string $appName
202
+     * @param string $fileName
203
+     * @return string
204
+     */
205
+    public function getCachedJS($appName, $fileName) {
206
+        $tmpfileLoc = explode('/', $fileName);
207
+        $fileName = array_pop($tmpfileLoc);
208
+        $fileName = str_replace('.json', '.js', $fileName);
209
+
210
+        return substr($this->urlGenerator->linkToRoute('core.Js.getJs', array('fileName' => $fileName, 'appName' => $appName)), strlen(\OC::$WEBROOT) + 1);
211
+    }
212
+
213
+    /**
214
+     * @param string $root
215
+     * @param string $file
216
+     * @return string[]
217
+     */
218
+    public function getContent($root, $file) {
219
+        /** @var array $data */
220
+        $data = json_decode(file_get_contents($root . '/' . $file));
221
+        if(!is_array($data)) {
222
+            return [];
223
+        }
224
+
225
+        $path = explode('/', $file);
226
+        array_pop($path);
227
+        $path = implode('/', $path);
228
+
229
+        $result = [];
230
+        foreach ($data as $f) {
231
+            $result[] = $path . '/' . $f;
232
+        }
233
+
234
+        return $result;
235
+    }
236
+
237
+
238
+    /**
239
+     * Clear cache with combined javascript files
240
+     *
241
+     * @throws NotFoundException
242
+     */
243
+    public function resetCache() {
244
+        $this->cacheFactory->createDistributed('JS-')->clear();
245
+        $appDirectory = $this->appData->getDirectoryListing();
246
+        foreach ($appDirectory as $folder) {
247
+            foreach ($folder->getDirectoryListing() as $file) {
248
+                $file->delete();
249
+            }
250
+        }
251
+    }
252 252
 }
Please login to merge, or discard this patch.
lib/private/Template/SCSSCacher.php 1 patch
Indentation   +309 added lines, -309 removed lines patch added patch discarded remove patch
@@ -46,313 +46,313 @@
 block discarded – undo
46 46
 
47 47
 class SCSSCacher {
48 48
 
49
-	/** @var ILogger */
50
-	protected $logger;
51
-
52
-	/** @var IAppData */
53
-	protected $appData;
54
-
55
-	/** @var IURLGenerator */
56
-	protected $urlGenerator;
57
-
58
-	/** @var IConfig */
59
-	protected $config;
60
-
61
-	/** @var \OC_Defaults */
62
-	private $defaults;
63
-
64
-	/** @var string */
65
-	protected $serverRoot;
66
-
67
-	/** @var ICache */
68
-	protected $depsCache;
69
-
70
-	/** @var null|string */
71
-	private $injectedVariables;
72
-
73
-	/** @var ICacheFactory */
74
-	private $cacheFactory;
75
-
76
-	/**
77
-	 * @param ILogger $logger
78
-	 * @param Factory $appDataFactory
79
-	 * @param IURLGenerator $urlGenerator
80
-	 * @param IConfig $config
81
-	 * @param \OC_Defaults $defaults
82
-	 * @param string $serverRoot
83
-	 * @param ICacheFactory $cacheFactory
84
-	 */
85
-	public function __construct(ILogger $logger,
86
-								Factory $appDataFactory,
87
-								IURLGenerator $urlGenerator,
88
-								IConfig $config,
89
-								\OC_Defaults $defaults,
90
-								$serverRoot,
91
-								ICacheFactory $cacheFactory) {
92
-		$this->logger = $logger;
93
-		$this->appData = $appDataFactory->get('css');
94
-		$this->urlGenerator = $urlGenerator;
95
-		$this->config = $config;
96
-		$this->defaults = $defaults;
97
-		$this->serverRoot = $serverRoot;
98
-		$this->cacheFactory = $cacheFactory;
99
-		$this->depsCache = $cacheFactory->createDistributed('SCSS-' . md5($this->urlGenerator->getBaseUrl()));
100
-	}
101
-
102
-	/**
103
-	 * Process the caching process if needed
104
-	 *
105
-	 * @param string $root Root path to the nextcloud installation
106
-	 * @param string $file
107
-	 * @param string $app The app name
108
-	 * @return boolean
109
-	 * @throws NotPermittedException
110
-	 */
111
-	public function process(string $root, string $file, string $app): bool {
112
-		$path = explode('/', $root . '/' . $file);
113
-
114
-		$fileNameSCSS = array_pop($path);
115
-		$fileNameCSS = $this->prependBaseurlPrefix(str_replace('.scss', '.css', $fileNameSCSS));
116
-
117
-		$path = implode('/', $path);
118
-		$webDir = $this->getWebDir($path, $app, $this->serverRoot, \OC::$WEBROOT);
119
-
120
-		try {
121
-			$folder = $this->appData->getFolder($app);
122
-		} catch(NotFoundException $e) {
123
-			// creating css appdata folder
124
-			$folder = $this->appData->newFolder($app);
125
-		}
126
-
127
-
128
-		if(!$this->variablesChanged() && $this->isCached($fileNameCSS, $folder)) {
129
-			return true;
130
-		}
131
-		return $this->cache($path, $fileNameCSS, $fileNameSCSS, $folder, $webDir);
132
-	}
133
-
134
-	/**
135
-	 * @param $appName
136
-	 * @param $fileName
137
-	 * @return ISimpleFile
138
-	 */
139
-	public function getCachedCSS(string $appName, string $fileName): ISimpleFile {
140
-		$folder = $this->appData->getFolder($appName);
141
-		return $folder->getFile($this->prependBaseurlPrefix($fileName));
142
-	}
143
-
144
-	/**
145
-	 * Check if the file is cached or not
146
-	 * @param string $fileNameCSS
147
-	 * @param ISimpleFolder $folder
148
-	 * @return boolean
149
-	 */
150
-	private function isCached(string $fileNameCSS, ISimpleFolder $folder) {
151
-		try {
152
-			$cachedFile = $folder->getFile($fileNameCSS);
153
-			if ($cachedFile->getSize() > 0) {
154
-				$depFileName = $fileNameCSS . '.deps';
155
-				$deps = $this->depsCache->get($folder->getName() . '-' . $depFileName);
156
-				if ($deps === null) {
157
-					$depFile = $folder->getFile($depFileName);
158
-					$deps = $depFile->getContent();
159
-					//Set to memcache for next run
160
-					$this->depsCache->set($folder->getName() . '-' . $depFileName, $deps);
161
-				}
162
-				$deps = json_decode($deps, true);
163
-
164
-				foreach ((array)$deps as $file=>$mtime) {
165
-					if (!file_exists($file) || filemtime($file) > $mtime) {
166
-						return false;
167
-					}
168
-				}
169
-				return true;
170
-			}
171
-			return false;
172
-		} catch(NotFoundException $e) {
173
-			return false;
174
-		}
175
-	}
176
-
177
-	/**
178
-	 * Check if the variables file has changed
179
-	 * @return bool
180
-	 */
181
-	private function variablesChanged(): bool {
182
-		$injectedVariables = $this->getInjectedVariables();
183
-		if($this->config->getAppValue('core', 'scss.variables') !== md5($injectedVariables)) {
184
-			$this->resetCache();
185
-			$this->config->setAppValue('core', 'scss.variables', md5($injectedVariables));
186
-			return true;
187
-		}
188
-		return false;
189
-	}
190
-
191
-	/**
192
-	 * Cache the file with AppData
193
-	 *
194
-	 * @param string $path
195
-	 * @param string $fileNameCSS
196
-	 * @param string $fileNameSCSS
197
-	 * @param ISimpleFolder $folder
198
-	 * @param string $webDir
199
-	 * @return boolean
200
-	 * @throws NotPermittedException
201
-	 */
202
-	private function cache(string $path, string $fileNameCSS, string $fileNameSCSS, ISimpleFolder $folder, string $webDir) {
203
-		$scss = new Compiler();
204
-		$scss->setImportPaths([
205
-			$path,
206
-			$this->serverRoot . '/core/css/',
207
-		]);
208
-		// Continue after throw
209
-		$scss->setIgnoreErrors(true);
210
-		if($this->config->getSystemValue('debug')) {
211
-			// Debug mode
212
-			$scss->setFormatter(Expanded::class);
213
-			$scss->setLineNumberStyle(Compiler::LINE_COMMENTS);
214
-		} else {
215
-			// Compression
216
-			$scss->setFormatter(Crunched::class);
217
-		}
218
-
219
-		try {
220
-			$cachedfile = $folder->getFile($fileNameCSS);
221
-		} catch(NotFoundException $e) {
222
-			$cachedfile = $folder->newFile($fileNameCSS);
223
-		}
224
-
225
-		$depFileName = $fileNameCSS . '.deps';
226
-		try {
227
-			$depFile = $folder->getFile($depFileName);
228
-		} catch (NotFoundException $e) {
229
-			$depFile = $folder->newFile($depFileName);
230
-		}
231
-
232
-		// Compile
233
-		try {
234
-			$compiledScss = $scss->compile(
235
-				'@import "variables.scss";' .
236
-				$this->getInjectedVariables() .
237
-				'@import "'.$fileNameSCSS.'";');
238
-		} catch(ParserException $e) {
239
-			$this->logger->error($e, ['app' => 'core']);
240
-			return false;
241
-		}
242
-
243
-		// Gzip file
244
-		try {
245
-			$gzipFile = $folder->getFile($fileNameCSS . '.gzip'); # Safari doesn't like .gz
246
-		} catch (NotFoundException $e) {
247
-			$gzipFile = $folder->newFile($fileNameCSS . '.gzip'); # Safari doesn't like .gz
248
-		}
249
-
250
-		try {
251
-			$data = $this->rebaseUrls($compiledScss, $webDir);
252
-			$cachedfile->putContent($data);
253
-			$deps = json_encode($scss->getParsedFiles());
254
-			$depFile->putContent($deps);
255
-			$this->depsCache->set($folder->getName() . '-' . $depFileName, $deps);
256
-			$gzipFile->putContent(gzencode($data, 9));
257
-			$this->logger->debug('SCSSCacher: '.$webDir.'/'.$fileNameSCSS.' compiled and successfully cached', ['app' => 'core']);
258
-			return true;
259
-		} catch(NotPermittedException $e) {
260
-			$this->logger->error('SCSSCacher: unable to cache: ' . $fileNameSCSS);
261
-			return false;
262
-		}
263
-	}
264
-
265
-	/**
266
-	 * Reset scss cache by deleting all generated css files
267
-	 * We need to regenerate all files when variables change
268
-	 */
269
-	public function resetCache() {
270
-		$this->injectedVariables = null;
271
-		$this->cacheFactory->createDistributed('SCSS-')->clear();
272
-		$appDirectory = $this->appData->getDirectoryListing();
273
-		foreach ($appDirectory as $folder) {
274
-			foreach ($folder->getDirectoryListing() as $file) {
275
-				$file->delete();
276
-			}
277
-		}
278
-	}
279
-
280
-	/**
281
-	 * @return string SCSS code for variables from OC_Defaults
282
-	 */
283
-	private function getInjectedVariables(): string {
284
-		if ($this->injectedVariables !== null) {
285
-			return $this->injectedVariables;
286
-		}
287
-		$variables = '';
288
-		foreach ($this->defaults->getScssVariables() as $key => $value) {
289
-			$variables .= '$' . $key . ': ' . $value . ';';
290
-		}
291
-
292
-		// check for valid variables / otherwise fall back to defaults
293
-		try {
294
-			$scss = new Compiler();
295
-			$scss->compile($variables);
296
-			$this->injectedVariables = $variables;
297
-		} catch (ParserException $e) {
298
-			$this->logger->error($e, ['app' => 'core']);
299
-		}
300
-
301
-		return $variables;
302
-	}
303
-
304
-	/**
305
-	 * Add the correct uri prefix to make uri valid again
306
-	 * @param string $css
307
-	 * @param string $webDir
308
-	 * @return string
309
-	 */
310
-	private function rebaseUrls(string $css, string $webDir): string {
311
-		$re = '/url\([\'"]([^\/][\.\w?=\/-]*)[\'"]\)/x';
312
-		$subst = 'url(\''.$webDir.'/$1\')';
313
-		return preg_replace($re, $subst, $css);
314
-	}
315
-
316
-	/**
317
-	 * Return the cached css file uri
318
-	 * @param string $appName the app name
319
-	 * @param string $fileName
320
-	 * @return string
321
-	 */
322
-	public function getCachedSCSS(string $appName, string $fileName): string {
323
-		$tmpfileLoc = explode('/', $fileName);
324
-		$fileName = array_pop($tmpfileLoc);
325
-		$fileName = $this->prependBaseurlPrefix(str_replace('.scss', '.css', $fileName));
326
-
327
-		return substr($this->urlGenerator->linkToRoute('core.Css.getCss', ['fileName' => $fileName, 'appName' => $appName]), strlen(\OC::$WEBROOT) + 1);
328
-	}
329
-
330
-	/**
331
-	 * Prepend hashed base url to the css file
332
-	 * @param string$cssFile
333
-	 * @return string
334
-	 */
335
-	private function prependBaseurlPrefix(string $cssFile): string {
336
-		$frontendController = ($this->config->getSystemValue('htaccess.IgnoreFrontController', false) === true || getenv('front_controller_active') === 'true');
337
-		return substr(md5($this->urlGenerator->getBaseUrl() . $frontendController), 0, 8) . '-' . $cssFile;
338
-	}
339
-
340
-	/**
341
-	 * Get WebDir root
342
-	 * @param string $path the css file path
343
-	 * @param string $appName the app name
344
-	 * @param string $serverRoot the server root path
345
-	 * @param string $webRoot the nextcloud installation root path
346
-	 * @return string the webDir
347
-	 */
348
-	private function getWebDir(string $path, string $appName, string $serverRoot, string $webRoot): string {
349
-		// Detect if path is within server root AND if path is within an app path
350
-		if ( strpos($path, $serverRoot) === false && $appWebPath = \OC_App::getAppWebPath($appName)) {
351
-			// Get the file path within the app directory
352
-			$appDirectoryPath = explode($appName, $path)[1];
353
-			// Remove the webroot
354
-			return str_replace($webRoot, '', $appWebPath.$appDirectoryPath);
355
-		}
356
-		return $webRoot.substr($path, strlen($serverRoot));
357
-	}
49
+    /** @var ILogger */
50
+    protected $logger;
51
+
52
+    /** @var IAppData */
53
+    protected $appData;
54
+
55
+    /** @var IURLGenerator */
56
+    protected $urlGenerator;
57
+
58
+    /** @var IConfig */
59
+    protected $config;
60
+
61
+    /** @var \OC_Defaults */
62
+    private $defaults;
63
+
64
+    /** @var string */
65
+    protected $serverRoot;
66
+
67
+    /** @var ICache */
68
+    protected $depsCache;
69
+
70
+    /** @var null|string */
71
+    private $injectedVariables;
72
+
73
+    /** @var ICacheFactory */
74
+    private $cacheFactory;
75
+
76
+    /**
77
+     * @param ILogger $logger
78
+     * @param Factory $appDataFactory
79
+     * @param IURLGenerator $urlGenerator
80
+     * @param IConfig $config
81
+     * @param \OC_Defaults $defaults
82
+     * @param string $serverRoot
83
+     * @param ICacheFactory $cacheFactory
84
+     */
85
+    public function __construct(ILogger $logger,
86
+                                Factory $appDataFactory,
87
+                                IURLGenerator $urlGenerator,
88
+                                IConfig $config,
89
+                                \OC_Defaults $defaults,
90
+                                $serverRoot,
91
+                                ICacheFactory $cacheFactory) {
92
+        $this->logger = $logger;
93
+        $this->appData = $appDataFactory->get('css');
94
+        $this->urlGenerator = $urlGenerator;
95
+        $this->config = $config;
96
+        $this->defaults = $defaults;
97
+        $this->serverRoot = $serverRoot;
98
+        $this->cacheFactory = $cacheFactory;
99
+        $this->depsCache = $cacheFactory->createDistributed('SCSS-' . md5($this->urlGenerator->getBaseUrl()));
100
+    }
101
+
102
+    /**
103
+     * Process the caching process if needed
104
+     *
105
+     * @param string $root Root path to the nextcloud installation
106
+     * @param string $file
107
+     * @param string $app The app name
108
+     * @return boolean
109
+     * @throws NotPermittedException
110
+     */
111
+    public function process(string $root, string $file, string $app): bool {
112
+        $path = explode('/', $root . '/' . $file);
113
+
114
+        $fileNameSCSS = array_pop($path);
115
+        $fileNameCSS = $this->prependBaseurlPrefix(str_replace('.scss', '.css', $fileNameSCSS));
116
+
117
+        $path = implode('/', $path);
118
+        $webDir = $this->getWebDir($path, $app, $this->serverRoot, \OC::$WEBROOT);
119
+
120
+        try {
121
+            $folder = $this->appData->getFolder($app);
122
+        } catch(NotFoundException $e) {
123
+            // creating css appdata folder
124
+            $folder = $this->appData->newFolder($app);
125
+        }
126
+
127
+
128
+        if(!$this->variablesChanged() && $this->isCached($fileNameCSS, $folder)) {
129
+            return true;
130
+        }
131
+        return $this->cache($path, $fileNameCSS, $fileNameSCSS, $folder, $webDir);
132
+    }
133
+
134
+    /**
135
+     * @param $appName
136
+     * @param $fileName
137
+     * @return ISimpleFile
138
+     */
139
+    public function getCachedCSS(string $appName, string $fileName): ISimpleFile {
140
+        $folder = $this->appData->getFolder($appName);
141
+        return $folder->getFile($this->prependBaseurlPrefix($fileName));
142
+    }
143
+
144
+    /**
145
+     * Check if the file is cached or not
146
+     * @param string $fileNameCSS
147
+     * @param ISimpleFolder $folder
148
+     * @return boolean
149
+     */
150
+    private function isCached(string $fileNameCSS, ISimpleFolder $folder) {
151
+        try {
152
+            $cachedFile = $folder->getFile($fileNameCSS);
153
+            if ($cachedFile->getSize() > 0) {
154
+                $depFileName = $fileNameCSS . '.deps';
155
+                $deps = $this->depsCache->get($folder->getName() . '-' . $depFileName);
156
+                if ($deps === null) {
157
+                    $depFile = $folder->getFile($depFileName);
158
+                    $deps = $depFile->getContent();
159
+                    //Set to memcache for next run
160
+                    $this->depsCache->set($folder->getName() . '-' . $depFileName, $deps);
161
+                }
162
+                $deps = json_decode($deps, true);
163
+
164
+                foreach ((array)$deps as $file=>$mtime) {
165
+                    if (!file_exists($file) || filemtime($file) > $mtime) {
166
+                        return false;
167
+                    }
168
+                }
169
+                return true;
170
+            }
171
+            return false;
172
+        } catch(NotFoundException $e) {
173
+            return false;
174
+        }
175
+    }
176
+
177
+    /**
178
+     * Check if the variables file has changed
179
+     * @return bool
180
+     */
181
+    private function variablesChanged(): bool {
182
+        $injectedVariables = $this->getInjectedVariables();
183
+        if($this->config->getAppValue('core', 'scss.variables') !== md5($injectedVariables)) {
184
+            $this->resetCache();
185
+            $this->config->setAppValue('core', 'scss.variables', md5($injectedVariables));
186
+            return true;
187
+        }
188
+        return false;
189
+    }
190
+
191
+    /**
192
+     * Cache the file with AppData
193
+     *
194
+     * @param string $path
195
+     * @param string $fileNameCSS
196
+     * @param string $fileNameSCSS
197
+     * @param ISimpleFolder $folder
198
+     * @param string $webDir
199
+     * @return boolean
200
+     * @throws NotPermittedException
201
+     */
202
+    private function cache(string $path, string $fileNameCSS, string $fileNameSCSS, ISimpleFolder $folder, string $webDir) {
203
+        $scss = new Compiler();
204
+        $scss->setImportPaths([
205
+            $path,
206
+            $this->serverRoot . '/core/css/',
207
+        ]);
208
+        // Continue after throw
209
+        $scss->setIgnoreErrors(true);
210
+        if($this->config->getSystemValue('debug')) {
211
+            // Debug mode
212
+            $scss->setFormatter(Expanded::class);
213
+            $scss->setLineNumberStyle(Compiler::LINE_COMMENTS);
214
+        } else {
215
+            // Compression
216
+            $scss->setFormatter(Crunched::class);
217
+        }
218
+
219
+        try {
220
+            $cachedfile = $folder->getFile($fileNameCSS);
221
+        } catch(NotFoundException $e) {
222
+            $cachedfile = $folder->newFile($fileNameCSS);
223
+        }
224
+
225
+        $depFileName = $fileNameCSS . '.deps';
226
+        try {
227
+            $depFile = $folder->getFile($depFileName);
228
+        } catch (NotFoundException $e) {
229
+            $depFile = $folder->newFile($depFileName);
230
+        }
231
+
232
+        // Compile
233
+        try {
234
+            $compiledScss = $scss->compile(
235
+                '@import "variables.scss";' .
236
+                $this->getInjectedVariables() .
237
+                '@import "'.$fileNameSCSS.'";');
238
+        } catch(ParserException $e) {
239
+            $this->logger->error($e, ['app' => 'core']);
240
+            return false;
241
+        }
242
+
243
+        // Gzip file
244
+        try {
245
+            $gzipFile = $folder->getFile($fileNameCSS . '.gzip'); # Safari doesn't like .gz
246
+        } catch (NotFoundException $e) {
247
+            $gzipFile = $folder->newFile($fileNameCSS . '.gzip'); # Safari doesn't like .gz
248
+        }
249
+
250
+        try {
251
+            $data = $this->rebaseUrls($compiledScss, $webDir);
252
+            $cachedfile->putContent($data);
253
+            $deps = json_encode($scss->getParsedFiles());
254
+            $depFile->putContent($deps);
255
+            $this->depsCache->set($folder->getName() . '-' . $depFileName, $deps);
256
+            $gzipFile->putContent(gzencode($data, 9));
257
+            $this->logger->debug('SCSSCacher: '.$webDir.'/'.$fileNameSCSS.' compiled and successfully cached', ['app' => 'core']);
258
+            return true;
259
+        } catch(NotPermittedException $e) {
260
+            $this->logger->error('SCSSCacher: unable to cache: ' . $fileNameSCSS);
261
+            return false;
262
+        }
263
+    }
264
+
265
+    /**
266
+     * Reset scss cache by deleting all generated css files
267
+     * We need to regenerate all files when variables change
268
+     */
269
+    public function resetCache() {
270
+        $this->injectedVariables = null;
271
+        $this->cacheFactory->createDistributed('SCSS-')->clear();
272
+        $appDirectory = $this->appData->getDirectoryListing();
273
+        foreach ($appDirectory as $folder) {
274
+            foreach ($folder->getDirectoryListing() as $file) {
275
+                $file->delete();
276
+            }
277
+        }
278
+    }
279
+
280
+    /**
281
+     * @return string SCSS code for variables from OC_Defaults
282
+     */
283
+    private function getInjectedVariables(): string {
284
+        if ($this->injectedVariables !== null) {
285
+            return $this->injectedVariables;
286
+        }
287
+        $variables = '';
288
+        foreach ($this->defaults->getScssVariables() as $key => $value) {
289
+            $variables .= '$' . $key . ': ' . $value . ';';
290
+        }
291
+
292
+        // check for valid variables / otherwise fall back to defaults
293
+        try {
294
+            $scss = new Compiler();
295
+            $scss->compile($variables);
296
+            $this->injectedVariables = $variables;
297
+        } catch (ParserException $e) {
298
+            $this->logger->error($e, ['app' => 'core']);
299
+        }
300
+
301
+        return $variables;
302
+    }
303
+
304
+    /**
305
+     * Add the correct uri prefix to make uri valid again
306
+     * @param string $css
307
+     * @param string $webDir
308
+     * @return string
309
+     */
310
+    private function rebaseUrls(string $css, string $webDir): string {
311
+        $re = '/url\([\'"]([^\/][\.\w?=\/-]*)[\'"]\)/x';
312
+        $subst = 'url(\''.$webDir.'/$1\')';
313
+        return preg_replace($re, $subst, $css);
314
+    }
315
+
316
+    /**
317
+     * Return the cached css file uri
318
+     * @param string $appName the app name
319
+     * @param string $fileName
320
+     * @return string
321
+     */
322
+    public function getCachedSCSS(string $appName, string $fileName): string {
323
+        $tmpfileLoc = explode('/', $fileName);
324
+        $fileName = array_pop($tmpfileLoc);
325
+        $fileName = $this->prependBaseurlPrefix(str_replace('.scss', '.css', $fileName));
326
+
327
+        return substr($this->urlGenerator->linkToRoute('core.Css.getCss', ['fileName' => $fileName, 'appName' => $appName]), strlen(\OC::$WEBROOT) + 1);
328
+    }
329
+
330
+    /**
331
+     * Prepend hashed base url to the css file
332
+     * @param string$cssFile
333
+     * @return string
334
+     */
335
+    private function prependBaseurlPrefix(string $cssFile): string {
336
+        $frontendController = ($this->config->getSystemValue('htaccess.IgnoreFrontController', false) === true || getenv('front_controller_active') === 'true');
337
+        return substr(md5($this->urlGenerator->getBaseUrl() . $frontendController), 0, 8) . '-' . $cssFile;
338
+    }
339
+
340
+    /**
341
+     * Get WebDir root
342
+     * @param string $path the css file path
343
+     * @param string $appName the app name
344
+     * @param string $serverRoot the server root path
345
+     * @param string $webRoot the nextcloud installation root path
346
+     * @return string the webDir
347
+     */
348
+    private function getWebDir(string $path, string $appName, string $serverRoot, string $webRoot): string {
349
+        // Detect if path is within server root AND if path is within an app path
350
+        if ( strpos($path, $serverRoot) === false && $appWebPath = \OC_App::getAppWebPath($appName)) {
351
+            // Get the file path within the app directory
352
+            $appDirectoryPath = explode($appName, $path)[1];
353
+            // Remove the webroot
354
+            return str_replace($webRoot, '', $appWebPath.$appDirectoryPath);
355
+        }
356
+        return $webRoot.substr($path, strlen($serverRoot));
357
+    }
358 358
 }
Please login to merge, or discard this patch.