Completed
Pull Request — master (#9565)
by Julius
273:38 queued 257:14
created
lib/private/Server.php 1 patch
Indentation   +1827 added lines, -1827 removed lines patch added patch discarded remove patch
@@ -153,1836 +153,1836 @@
 block discarded – undo
153 153
  * TODO: hookup all manager classes
154 154
  */
155 155
 class Server extends ServerContainer implements IServerContainer {
156
-	/** @var string */
157
-	private $webRoot;
158
-
159
-	/**
160
-	 * @param string $webRoot
161
-	 * @param \OC\Config $config
162
-	 */
163
-	public function __construct($webRoot, \OC\Config $config) {
164
-		parent::__construct();
165
-		$this->webRoot = $webRoot;
166
-
167
-		// To find out if we are running from CLI or not
168
-		$this->registerParameter('isCLI', \OC::$CLI);
169
-
170
-		$this->registerService(\OCP\IServerContainer::class, function (IServerContainer $c) {
171
-			return $c;
172
-		});
173
-
174
-		$this->registerAlias(\OCP\Calendar\IManager::class, \OC\Calendar\Manager::class);
175
-		$this->registerAlias('CalendarManager', \OC\Calendar\Manager::class);
176
-
177
-		$this->registerAlias(\OCP\Contacts\IManager::class, \OC\ContactsManager::class);
178
-		$this->registerAlias('ContactsManager', \OCP\Contacts\IManager::class);
179
-
180
-		$this->registerAlias(IActionFactory::class, ActionFactory::class);
181
-
182
-
183
-		$this->registerService(\OCP\IPreview::class, function (Server $c) {
184
-			return new PreviewManager(
185
-				$c->getConfig(),
186
-				$c->getRootFolder(),
187
-				$c->getAppDataDir('preview'),
188
-				$c->getEventDispatcher(),
189
-				$c->getSession()->get('user_id')
190
-			);
191
-		});
192
-		$this->registerAlias('PreviewManager', \OCP\IPreview::class);
193
-
194
-		$this->registerService(\OC\Preview\Watcher::class, function (Server $c) {
195
-			return new \OC\Preview\Watcher(
196
-				$c->getAppDataDir('preview')
197
-			);
198
-		});
199
-
200
-		$this->registerService('EncryptionManager', function (Server $c) {
201
-			$view = new View();
202
-			$util = new Encryption\Util(
203
-				$view,
204
-				$c->getUserManager(),
205
-				$c->getGroupManager(),
206
-				$c->getConfig()
207
-			);
208
-			return new Encryption\Manager(
209
-				$c->getConfig(),
210
-				$c->getLogger(),
211
-				$c->getL10N('core'),
212
-				new View(),
213
-				$util,
214
-				new ArrayCache()
215
-			);
216
-		});
217
-
218
-		$this->registerService('EncryptionFileHelper', function (Server $c) {
219
-			$util = new Encryption\Util(
220
-				new View(),
221
-				$c->getUserManager(),
222
-				$c->getGroupManager(),
223
-				$c->getConfig()
224
-			);
225
-			return new Encryption\File(
226
-				$util,
227
-				$c->getRootFolder(),
228
-				$c->getShareManager()
229
-			);
230
-		});
231
-
232
-		$this->registerService('EncryptionKeyStorage', function (Server $c) {
233
-			$view = new View();
234
-			$util = new Encryption\Util(
235
-				$view,
236
-				$c->getUserManager(),
237
-				$c->getGroupManager(),
238
-				$c->getConfig()
239
-			);
240
-
241
-			return new Encryption\Keys\Storage($view, $util);
242
-		});
243
-		$this->registerService('TagMapper', function (Server $c) {
244
-			return new TagMapper($c->getDatabaseConnection());
245
-		});
246
-
247
-		$this->registerService(\OCP\ITagManager::class, function (Server $c) {
248
-			$tagMapper = $c->query('TagMapper');
249
-			return new TagManager($tagMapper, $c->getUserSession());
250
-		});
251
-		$this->registerAlias('TagManager', \OCP\ITagManager::class);
252
-
253
-		$this->registerService('SystemTagManagerFactory', function (Server $c) {
254
-			$config = $c->getConfig();
255
-			$factoryClass = $config->getSystemValue('systemtags.managerFactory', SystemTagManagerFactory::class);
256
-			return new $factoryClass($this);
257
-		});
258
-		$this->registerService(\OCP\SystemTag\ISystemTagManager::class, function (Server $c) {
259
-			return $c->query('SystemTagManagerFactory')->getManager();
260
-		});
261
-		$this->registerAlias('SystemTagManager', \OCP\SystemTag\ISystemTagManager::class);
262
-
263
-		$this->registerService(\OCP\SystemTag\ISystemTagObjectMapper::class, function (Server $c) {
264
-			return $c->query('SystemTagManagerFactory')->getObjectMapper();
265
-		});
266
-		$this->registerService('RootFolder', function (Server $c) {
267
-			$manager = \OC\Files\Filesystem::getMountManager(null);
268
-			$view = new View();
269
-			$root = new Root(
270
-				$manager,
271
-				$view,
272
-				null,
273
-				$c->getUserMountCache(),
274
-				$this->getLogger(),
275
-				$this->getUserManager()
276
-			);
277
-			$connector = new HookConnector($root, $view);
278
-			$connector->viewToNode();
279
-
280
-			$previewConnector = new \OC\Preview\WatcherConnector($root, $c->getSystemConfig());
281
-			$previewConnector->connectWatcher();
282
-
283
-			return $root;
284
-		});
285
-		$this->registerAlias('SystemTagObjectMapper', \OCP\SystemTag\ISystemTagObjectMapper::class);
286
-
287
-		$this->registerService(\OCP\Files\IRootFolder::class, function (Server $c) {
288
-			return new LazyRoot(function () use ($c) {
289
-				return $c->query('RootFolder');
290
-			});
291
-		});
292
-		$this->registerAlias('LazyRootFolder', \OCP\Files\IRootFolder::class);
293
-
294
-		$this->registerService(\OC\User\Manager::class, function (Server $c) {
295
-			$config = $c->getConfig();
296
-			return new \OC\User\Manager($config);
297
-		});
298
-		$this->registerAlias('UserManager', \OC\User\Manager::class);
299
-		$this->registerAlias(\OCP\IUserManager::class, \OC\User\Manager::class);
300
-
301
-		$this->registerService(\OCP\IGroupManager::class, function (Server $c) {
302
-			$groupManager = new \OC\Group\Manager($this->getUserManager(), $this->getLogger());
303
-			$groupManager->listen('\OC\Group', 'preCreate', function ($gid) {
304
-				\OC_Hook::emit('OC_Group', 'pre_createGroup', array('run' => true, 'gid' => $gid));
305
-			});
306
-			$groupManager->listen('\OC\Group', 'postCreate', function (\OC\Group\Group $gid) {
307
-				\OC_Hook::emit('OC_User', 'post_createGroup', array('gid' => $gid->getGID()));
308
-			});
309
-			$groupManager->listen('\OC\Group', 'preDelete', function (\OC\Group\Group $group) {
310
-				\OC_Hook::emit('OC_Group', 'pre_deleteGroup', array('run' => true, 'gid' => $group->getGID()));
311
-			});
312
-			$groupManager->listen('\OC\Group', 'postDelete', function (\OC\Group\Group $group) {
313
-				\OC_Hook::emit('OC_User', 'post_deleteGroup', array('gid' => $group->getGID()));
314
-			});
315
-			$groupManager->listen('\OC\Group', 'preAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
316
-				\OC_Hook::emit('OC_Group', 'pre_addToGroup', array('run' => true, 'uid' => $user->getUID(), 'gid' => $group->getGID()));
317
-			});
318
-			$groupManager->listen('\OC\Group', 'postAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
319
-				\OC_Hook::emit('OC_Group', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
320
-				//Minimal fix to keep it backward compatible TODO: clean up all the GroupManager hooks
321
-				\OC_Hook::emit('OC_User', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
322
-			});
323
-			return $groupManager;
324
-		});
325
-		$this->registerAlias('GroupManager', \OCP\IGroupManager::class);
326
-
327
-		$this->registerService(Store::class, function (Server $c) {
328
-			$session = $c->getSession();
329
-			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
330
-				$tokenProvider = $c->query(IProvider::class);
331
-			} else {
332
-				$tokenProvider = null;
333
-			}
334
-			$logger = $c->getLogger();
335
-			return new Store($session, $logger, $tokenProvider);
336
-		});
337
-		$this->registerAlias(IStore::class, Store::class);
338
-		$this->registerService(Authentication\Token\DefaultTokenMapper::class, function (Server $c) {
339
-			$dbConnection = $c->getDatabaseConnection();
340
-			return new Authentication\Token\DefaultTokenMapper($dbConnection);
341
-		});
342
-		$this->registerService(Authentication\Token\DefaultTokenProvider::class, function (Server $c) {
343
-			$mapper = $c->query(Authentication\Token\DefaultTokenMapper::class);
344
-			$crypto = $c->getCrypto();
345
-			$config = $c->getConfig();
346
-			$logger = $c->getLogger();
347
-			$timeFactory = new TimeFactory();
348
-			return new \OC\Authentication\Token\DefaultTokenProvider($mapper, $crypto, $config, $logger, $timeFactory);
349
-		});
350
-		$this->registerAlias(IProvider::class, Authentication\Token\DefaultTokenProvider::class);
351
-
352
-		$this->registerService(\OCP\IUserSession::class, function (Server $c) {
353
-			$manager = $c->getUserManager();
354
-			$session = new \OC\Session\Memory('');
355
-			$timeFactory = new TimeFactory();
356
-			// Token providers might require a working database. This code
357
-			// might however be called when ownCloud is not yet setup.
358
-			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
359
-				$defaultTokenProvider = $c->query(IProvider::class);
360
-			} else {
361
-				$defaultTokenProvider = null;
362
-			}
363
-
364
-			$dispatcher = $c->getEventDispatcher();
365
-
366
-			$userSession = new \OC\User\Session(
367
-				$manager,
368
-				$session,
369
-				$timeFactory,
370
-				$defaultTokenProvider,
371
-				$c->getConfig(),
372
-				$c->getSecureRandom(),
373
-				$c->getLockdownManager(),
374
-				$c->getLogger()
375
-			);
376
-			$userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
377
-				\OC_Hook::emit('OC_User', 'pre_createUser', array('run' => true, 'uid' => $uid, 'password' => $password));
378
-			});
379
-			$userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
380
-				/** @var $user \OC\User\User */
381
-				\OC_Hook::emit('OC_User', 'post_createUser', array('uid' => $user->getUID(), 'password' => $password));
382
-			});
383
-			$userSession->listen('\OC\User', 'preDelete', function ($user) use ($dispatcher) {
384
-				/** @var $user \OC\User\User */
385
-				\OC_Hook::emit('OC_User', 'pre_deleteUser', array('run' => true, 'uid' => $user->getUID()));
386
-				$dispatcher->dispatch('OCP\IUser::preDelete', new GenericEvent($user));
387
-			});
388
-			$userSession->listen('\OC\User', 'postDelete', function ($user) {
389
-				/** @var $user \OC\User\User */
390
-				\OC_Hook::emit('OC_User', 'post_deleteUser', array('uid' => $user->getUID()));
391
-			});
392
-			$userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
393
-				/** @var $user \OC\User\User */
394
-				\OC_Hook::emit('OC_User', 'pre_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
395
-			});
396
-			$userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
397
-				/** @var $user \OC\User\User */
398
-				\OC_Hook::emit('OC_User', 'post_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
399
-			});
400
-			$userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
401
-				\OC_Hook::emit('OC_User', 'pre_login', array('run' => true, 'uid' => $uid, 'password' => $password));
402
-			});
403
-			$userSession->listen('\OC\User', 'postLogin', function ($user, $password) {
404
-				/** @var $user \OC\User\User */
405
-				\OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
406
-			});
407
-			$userSession->listen('\OC\User', 'postRememberedLogin', function ($user, $password) {
408
-				/** @var $user \OC\User\User */
409
-				\OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
410
-			});
411
-			$userSession->listen('\OC\User', 'logout', function () {
412
-				\OC_Hook::emit('OC_User', 'logout', array());
413
-			});
414
-			$userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value, $oldValue) use ($dispatcher) {
415
-				/** @var $user \OC\User\User */
416
-				\OC_Hook::emit('OC_User', 'changeUser', array('run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value, 'old_value' => $oldValue));
417
-				$dispatcher->dispatch('OCP\IUser::changeUser', new GenericEvent($user, ['feature' => $feature, 'oldValue' => $oldValue, 'value' => $value]));
418
-			});
419
-			return $userSession;
420
-		});
421
-		$this->registerAlias('UserSession', \OCP\IUserSession::class);
422
-
423
-		$this->registerService(\OC\Authentication\TwoFactorAuth\Manager::class, function (Server $c) {
424
-			return new \OC\Authentication\TwoFactorAuth\Manager(
425
-				$c->getAppManager(),
426
-				$c->getSession(),
427
-				$c->getConfig(),
428
-				$c->getActivityManager(),
429
-				$c->getLogger(),
430
-				$c->query(IProvider::class),
431
-				$c->query(ITimeFactory::class),
432
-				$c->query(EventDispatcherInterface::class)
433
-			);
434
-		});
435
-
436
-		$this->registerAlias(\OCP\INavigationManager::class, \OC\NavigationManager::class);
437
-		$this->registerAlias('NavigationManager', \OCP\INavigationManager::class);
438
-
439
-		$this->registerService(\OC\AllConfig::class, function (Server $c) {
440
-			return new \OC\AllConfig(
441
-				$c->getSystemConfig()
442
-			);
443
-		});
444
-		$this->registerAlias('AllConfig', \OC\AllConfig::class);
445
-		$this->registerAlias(\OCP\IConfig::class, \OC\AllConfig::class);
446
-
447
-		$this->registerService('SystemConfig', function ($c) use ($config) {
448
-			return new \OC\SystemConfig($config);
449
-		});
450
-
451
-		$this->registerService(\OC\AppConfig::class, function (Server $c) {
452
-			return new \OC\AppConfig($c->getDatabaseConnection());
453
-		});
454
-		$this->registerAlias('AppConfig', \OC\AppConfig::class);
455
-		$this->registerAlias(\OCP\IAppConfig::class, \OC\AppConfig::class);
456
-
457
-		$this->registerService(\OCP\L10N\IFactory::class, function (Server $c) {
458
-			return new \OC\L10N\Factory(
459
-				$c->getConfig(),
460
-				$c->getRequest(),
461
-				$c->getUserSession(),
462
-				\OC::$SERVERROOT
463
-			);
464
-		});
465
-		$this->registerAlias('L10NFactory', \OCP\L10N\IFactory::class);
466
-
467
-		$this->registerService(\OCP\IURLGenerator::class, function (Server $c) {
468
-			$config = $c->getConfig();
469
-			$cacheFactory = $c->getMemCacheFactory();
470
-			$request = $c->getRequest();
471
-			return new \OC\URLGenerator(
472
-				$config,
473
-				$cacheFactory,
474
-				$request
475
-			);
476
-		});
477
-		$this->registerAlias('URLGenerator', \OCP\IURLGenerator::class);
478
-
479
-		$this->registerAlias('AppFetcher', AppFetcher::class);
480
-		$this->registerAlias('CategoryFetcher', CategoryFetcher::class);
481
-
482
-		$this->registerService(\OCP\ICache::class, function ($c) {
483
-			return new Cache\File();
484
-		});
485
-		$this->registerAlias('UserCache', \OCP\ICache::class);
486
-
487
-		$this->registerService(Factory::class, function (Server $c) {
488
-
489
-			$arrayCacheFactory = new \OC\Memcache\Factory('', $c->getLogger(),
490
-				ArrayCache::class,
491
-				ArrayCache::class,
492
-				ArrayCache::class
493
-			);
494
-			$config = $c->getConfig();
495
-			$request = $c->getRequest();
496
-			$urlGenerator = new URLGenerator($config, $arrayCacheFactory, $request);
497
-
498
-			if ($config->getSystemValue('installed', false) && !(defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
499
-				$v = \OC_App::getAppVersions();
500
-				$v['core'] = implode(',', \OC_Util::getVersion());
501
-				$version = implode(',', $v);
502
-				$instanceId = \OC_Util::getInstanceId();
503
-				$path = \OC::$SERVERROOT;
504
-				$prefix = md5($instanceId . '-' . $version . '-' . $path);
505
-				return new \OC\Memcache\Factory($prefix, $c->getLogger(),
506
-					$config->getSystemValue('memcache.local', null),
507
-					$config->getSystemValue('memcache.distributed', null),
508
-					$config->getSystemValue('memcache.locking', null)
509
-				);
510
-			}
511
-			return $arrayCacheFactory;
512
-
513
-		});
514
-		$this->registerAlias('MemCacheFactory', Factory::class);
515
-		$this->registerAlias(ICacheFactory::class, Factory::class);
516
-
517
-		$this->registerService('RedisFactory', function (Server $c) {
518
-			$systemConfig = $c->getSystemConfig();
519
-			return new RedisFactory($systemConfig);
520
-		});
521
-
522
-		$this->registerService(\OCP\Activity\IManager::class, function (Server $c) {
523
-			return new \OC\Activity\Manager(
524
-				$c->getRequest(),
525
-				$c->getUserSession(),
526
-				$c->getConfig(),
527
-				$c->query(IValidator::class)
528
-			);
529
-		});
530
-		$this->registerAlias('ActivityManager', \OCP\Activity\IManager::class);
531
-
532
-		$this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
533
-			return new \OC\Activity\EventMerger(
534
-				$c->getL10N('lib')
535
-			);
536
-		});
537
-		$this->registerAlias(IValidator::class, Validator::class);
538
-
539
-		$this->registerService(\OCP\IAvatarManager::class, function (Server $c) {
540
-			return new AvatarManager(
541
-				$c->query(\OC\User\Manager::class),
542
-				$c->getAppDataDir('avatar'),
543
-				$c->getL10N('lib'),
544
-				$c->getLogger(),
545
-				$c->getConfig()
546
-			);
547
-		});
548
-		$this->registerAlias('AvatarManager', \OCP\IAvatarManager::class);
549
-
550
-		$this->registerAlias(\OCP\Support\CrashReport\IRegistry::class, \OC\Support\CrashReport\Registry::class);
551
-
552
-		$this->registerService(\OCP\ILogger::class, function (Server $c) {
553
-			$logType = $c->query('AllConfig')->getSystemValue('log_type', 'file');
554
-			$factory = new LogFactory($c, $this->getSystemConfig());
555
-			$logger = $factory->get($logType);
556
-			$registry = $c->query(\OCP\Support\CrashReport\IRegistry::class);
557
-
558
-			return new Log($logger, $this->getSystemConfig(), null, $registry);
559
-		});
560
-		$this->registerAlias('Logger', \OCP\ILogger::class);
561
-
562
-		$this->registerService(ILogFactory::class, function (Server $c) {
563
-			return new LogFactory($c, $this->getSystemConfig());
564
-		});
565
-
566
-		$this->registerService(\OCP\BackgroundJob\IJobList::class, function (Server $c) {
567
-			$config = $c->getConfig();
568
-			return new \OC\BackgroundJob\JobList(
569
-				$c->getDatabaseConnection(),
570
-				$config,
571
-				new TimeFactory()
572
-			);
573
-		});
574
-		$this->registerAlias('JobList', \OCP\BackgroundJob\IJobList::class);
575
-
576
-		$this->registerService(\OCP\Route\IRouter::class, function (Server $c) {
577
-			$cacheFactory = $c->getMemCacheFactory();
578
-			$logger = $c->getLogger();
579
-			if ($cacheFactory->isLocalCacheAvailable()) {
580
-				$router = new \OC\Route\CachingRouter($cacheFactory->createLocal('route'), $logger);
581
-			} else {
582
-				$router = new \OC\Route\Router($logger);
583
-			}
584
-			return $router;
585
-		});
586
-		$this->registerAlias('Router', \OCP\Route\IRouter::class);
587
-
588
-		$this->registerService(\OCP\ISearch::class, function ($c) {
589
-			return new Search();
590
-		});
591
-		$this->registerAlias('Search', \OCP\ISearch::class);
592
-
593
-		$this->registerService(\OC\Security\RateLimiting\Limiter::class, function (Server $c) {
594
-			return new \OC\Security\RateLimiting\Limiter(
595
-				$this->getUserSession(),
596
-				$this->getRequest(),
597
-				new \OC\AppFramework\Utility\TimeFactory(),
598
-				$c->query(\OC\Security\RateLimiting\Backend\IBackend::class)
599
-			);
600
-		});
601
-		$this->registerService(\OC\Security\RateLimiting\Backend\IBackend::class, function ($c) {
602
-			return new \OC\Security\RateLimiting\Backend\MemoryCache(
603
-				$this->getMemCacheFactory(),
604
-				new \OC\AppFramework\Utility\TimeFactory()
605
-			);
606
-		});
607
-
608
-		$this->registerService(\OCP\Security\ISecureRandom::class, function ($c) {
609
-			return new SecureRandom();
610
-		});
611
-		$this->registerAlias('SecureRandom', \OCP\Security\ISecureRandom::class);
612
-
613
-		$this->registerService(\OCP\Security\ICrypto::class, function (Server $c) {
614
-			return new Crypto($c->getConfig(), $c->getSecureRandom());
615
-		});
616
-		$this->registerAlias('Crypto', \OCP\Security\ICrypto::class);
617
-
618
-		$this->registerService(\OCP\Security\IHasher::class, function (Server $c) {
619
-			return new Hasher($c->getConfig());
620
-		});
621
-		$this->registerAlias('Hasher', \OCP\Security\IHasher::class);
622
-
623
-		$this->registerService(\OCP\Security\ICredentialsManager::class, function (Server $c) {
624
-			return new CredentialsManager($c->getCrypto(), $c->getDatabaseConnection());
625
-		});
626
-		$this->registerAlias('CredentialsManager', \OCP\Security\ICredentialsManager::class);
627
-
628
-		$this->registerService(IDBConnection::class, function (Server $c) {
629
-			$systemConfig = $c->getSystemConfig();
630
-			$factory = new \OC\DB\ConnectionFactory($systemConfig);
631
-			$type = $systemConfig->getValue('dbtype', 'sqlite');
632
-			if (!$factory->isValidType($type)) {
633
-				throw new \OC\DatabaseException('Invalid database type');
634
-			}
635
-			$connectionParams = $factory->createConnectionParams();
636
-			$connection = $factory->getConnection($type, $connectionParams);
637
-			$connection->getConfiguration()->setSQLLogger($c->getQueryLogger());
638
-			return $connection;
639
-		});
640
-		$this->registerAlias('DatabaseConnection', IDBConnection::class);
641
-
642
-
643
-		$this->registerService(\OCP\Http\Client\IClientService::class, function (Server $c) {
644
-			$user = \OC_User::getUser();
645
-			$uid = $user ? $user : null;
646
-			return new ClientService(
647
-				$c->getConfig(),
648
-				new \OC\Security\CertificateManager(
649
-					$uid,
650
-					new View(),
651
-					$c->getConfig(),
652
-					$c->getLogger(),
653
-					$c->getSecureRandom()
654
-				)
655
-			);
656
-		});
657
-		$this->registerAlias('HttpClientService', \OCP\Http\Client\IClientService::class);
658
-		$this->registerService(\OCP\Diagnostics\IEventLogger::class, function (Server $c) {
659
-			$eventLogger = new EventLogger();
660
-			if ($c->getSystemConfig()->getValue('debug', false)) {
661
-				// In debug mode, module is being activated by default
662
-				$eventLogger->activate();
663
-			}
664
-			return $eventLogger;
665
-		});
666
-		$this->registerAlias('EventLogger', \OCP\Diagnostics\IEventLogger::class);
667
-
668
-		$this->registerService(\OCP\Diagnostics\IQueryLogger::class, function (Server $c) {
669
-			$queryLogger = new QueryLogger();
670
-			if ($c->getSystemConfig()->getValue('debug', false)) {
671
-				// In debug mode, module is being activated by default
672
-				$queryLogger->activate();
673
-			}
674
-			return $queryLogger;
675
-		});
676
-		$this->registerAlias('QueryLogger', \OCP\Diagnostics\IQueryLogger::class);
677
-
678
-		$this->registerService(TempManager::class, function (Server $c) {
679
-			return new TempManager(
680
-				$c->getLogger(),
681
-				$c->getConfig()
682
-			);
683
-		});
684
-		$this->registerAlias('TempManager', TempManager::class);
685
-		$this->registerAlias(ITempManager::class, TempManager::class);
686
-
687
-		$this->registerService(AppManager::class, function (Server $c) {
688
-			return new \OC\App\AppManager(
689
-				$c->getUserSession(),
690
-				$c->getConfig(),
691
-				$c->getGroupManager(),
692
-				$c->getMemCacheFactory(),
693
-				$c->getEventDispatcher()
694
-			);
695
-		});
696
-		$this->registerAlias('AppManager', AppManager::class);
697
-		$this->registerAlias(IAppManager::class, AppManager::class);
698
-
699
-		$this->registerService(\OCP\IDateTimeZone::class, function (Server $c) {
700
-			return new DateTimeZone(
701
-				$c->getConfig(),
702
-				$c->getSession()
703
-			);
704
-		});
705
-		$this->registerAlias('DateTimeZone', \OCP\IDateTimeZone::class);
706
-
707
-		$this->registerService(\OCP\IDateTimeFormatter::class, function (Server $c) {
708
-			$language = $c->getConfig()->getUserValue($c->getSession()->get('user_id'), 'core', 'lang', null);
709
-
710
-			return new DateTimeFormatter(
711
-				$c->getDateTimeZone()->getTimeZone(),
712
-				$c->getL10N('lib', $language)
713
-			);
714
-		});
715
-		$this->registerAlias('DateTimeFormatter', \OCP\IDateTimeFormatter::class);
716
-
717
-		$this->registerService(\OCP\Files\Config\IUserMountCache::class, function (Server $c) {
718
-			$mountCache = new UserMountCache($c->getDatabaseConnection(), $c->getUserManager(), $c->getLogger());
719
-			$listener = new UserMountCacheListener($mountCache);
720
-			$listener->listen($c->getUserManager());
721
-			return $mountCache;
722
-		});
723
-		$this->registerAlias('UserMountCache', \OCP\Files\Config\IUserMountCache::class);
724
-
725
-		$this->registerService(\OCP\Files\Config\IMountProviderCollection::class, function (Server $c) {
726
-			$loader = \OC\Files\Filesystem::getLoader();
727
-			$mountCache = $c->query('UserMountCache');
728
-			$manager = new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
729
-
730
-			// builtin providers
731
-
732
-			$config = $c->getConfig();
733
-			$manager->registerProvider(new CacheMountProvider($config));
734
-			$manager->registerHomeProvider(new LocalHomeMountProvider());
735
-			$manager->registerHomeProvider(new ObjectHomeMountProvider($config));
736
-
737
-			return $manager;
738
-		});
739
-		$this->registerAlias('MountConfigManager', \OCP\Files\Config\IMountProviderCollection::class);
740
-
741
-		$this->registerService('IniWrapper', function ($c) {
742
-			return new IniGetWrapper();
743
-		});
744
-		$this->registerService('AsyncCommandBus', function (Server $c) {
745
-			$busClass = $c->getConfig()->getSystemValue('commandbus');
746
-			if ($busClass) {
747
-				list($app, $class) = explode('::', $busClass, 2);
748
-				if ($c->getAppManager()->isInstalled($app)) {
749
-					\OC_App::loadApp($app);
750
-					return $c->query($class);
751
-				} else {
752
-					throw new ServiceUnavailableException("The app providing the command bus ($app) is not enabled");
753
-				}
754
-			} else {
755
-				$jobList = $c->getJobList();
756
-				return new CronBus($jobList);
757
-			}
758
-		});
759
-		$this->registerService('TrustedDomainHelper', function ($c) {
760
-			return new TrustedDomainHelper($this->getConfig());
761
-		});
762
-		$this->registerService('Throttler', function (Server $c) {
763
-			return new Throttler(
764
-				$c->getDatabaseConnection(),
765
-				new TimeFactory(),
766
-				$c->getLogger(),
767
-				$c->getConfig()
768
-			);
769
-		});
770
-		$this->registerService('IntegrityCodeChecker', function (Server $c) {
771
-			// IConfig and IAppManager requires a working database. This code
772
-			// might however be called when ownCloud is not yet setup.
773
-			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
774
-				$config = $c->getConfig();
775
-				$appManager = $c->getAppManager();
776
-			} else {
777
-				$config = null;
778
-				$appManager = null;
779
-			}
780
-
781
-			return new Checker(
782
-				new EnvironmentHelper(),
783
-				new FileAccessHelper(),
784
-				new AppLocator(),
785
-				$config,
786
-				$c->getMemCacheFactory(),
787
-				$appManager,
788
-				$c->getTempManager()
789
-			);
790
-		});
791
-		$this->registerService(\OCP\IRequest::class, function ($c) {
792
-			if (isset($this['urlParams'])) {
793
-				$urlParams = $this['urlParams'];
794
-			} else {
795
-				$urlParams = [];
796
-			}
797
-
798
-			if (defined('PHPUNIT_RUN') && PHPUNIT_RUN
799
-				&& in_array('fakeinput', stream_get_wrappers())
800
-			) {
801
-				$stream = 'fakeinput://data';
802
-			} else {
803
-				$stream = 'php://input';
804
-			}
805
-
806
-			return new Request(
807
-				[
808
-					'get' => $_GET,
809
-					'post' => $_POST,
810
-					'files' => $_FILES,
811
-					'server' => $_SERVER,
812
-					'env' => $_ENV,
813
-					'cookies' => $_COOKIE,
814
-					'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
815
-						? $_SERVER['REQUEST_METHOD']
816
-						: '',
817
-					'urlParams' => $urlParams,
818
-				],
819
-				$this->getSecureRandom(),
820
-				$this->getConfig(),
821
-				$this->getCsrfTokenManager(),
822
-				$stream
823
-			);
824
-		});
825
-		$this->registerAlias('Request', \OCP\IRequest::class);
826
-
827
-		$this->registerService(\OCP\Mail\IMailer::class, function (Server $c) {
828
-			return new Mailer(
829
-				$c->getConfig(),
830
-				$c->getLogger(),
831
-				$c->query(Defaults::class),
832
-				$c->getURLGenerator(),
833
-				$c->getL10N('lib')
834
-			);
835
-		});
836
-		$this->registerAlias('Mailer', \OCP\Mail\IMailer::class);
837
-
838
-		$this->registerService('LDAPProvider', function (Server $c) {
839
-			$config = $c->getConfig();
840
-			$factoryClass = $config->getSystemValue('ldapProviderFactory', null);
841
-			if (is_null($factoryClass)) {
842
-				throw new \Exception('ldapProviderFactory not set');
843
-			}
844
-			/** @var \OCP\LDAP\ILDAPProviderFactory $factory */
845
-			$factory = new $factoryClass($this);
846
-			return $factory->getLDAPProvider();
847
-		});
848
-		$this->registerService(ILockingProvider::class, function (Server $c) {
849
-			$ini = $c->getIniWrapper();
850
-			$config = $c->getConfig();
851
-			$ttl = $config->getSystemValue('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
852
-			if ($config->getSystemValue('filelocking.enabled', true) or (defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
853
-				/** @var \OC\Memcache\Factory $memcacheFactory */
854
-				$memcacheFactory = $c->getMemCacheFactory();
855
-				$memcache = $memcacheFactory->createLocking('lock');
856
-				if (!($memcache instanceof \OC\Memcache\NullCache)) {
857
-					return new MemcacheLockingProvider($memcache, $ttl);
858
-				}
859
-				return new DBLockingProvider(
860
-					$c->getDatabaseConnection(),
861
-					$c->getLogger(),
862
-					new TimeFactory(),
863
-					$ttl,
864
-					!\OC::$CLI
865
-				);
866
-			}
867
-			return new NoopLockingProvider();
868
-		});
869
-		$this->registerAlias('LockingProvider', ILockingProvider::class);
870
-
871
-		$this->registerService(\OCP\Files\Mount\IMountManager::class, function () {
872
-			return new \OC\Files\Mount\Manager();
873
-		});
874
-		$this->registerAlias('MountManager', \OCP\Files\Mount\IMountManager::class);
875
-
876
-		$this->registerService(\OCP\Files\IMimeTypeDetector::class, function (Server $c) {
877
-			return new \OC\Files\Type\Detection(
878
-				$c->getURLGenerator(),
879
-				\OC::$configDir,
880
-				\OC::$SERVERROOT . '/resources/config/'
881
-			);
882
-		});
883
-		$this->registerAlias('MimeTypeDetector', \OCP\Files\IMimeTypeDetector::class);
884
-
885
-		$this->registerService(\OCP\Files\IMimeTypeLoader::class, function (Server $c) {
886
-			return new \OC\Files\Type\Loader(
887
-				$c->getDatabaseConnection()
888
-			);
889
-		});
890
-		$this->registerAlias('MimeTypeLoader', \OCP\Files\IMimeTypeLoader::class);
891
-		$this->registerService(BundleFetcher::class, function () {
892
-			return new BundleFetcher($this->getL10N('lib'));
893
-		});
894
-		$this->registerService(\OCP\Notification\IManager::class, function (Server $c) {
895
-			return new Manager(
896
-				$c->query(IValidator::class)
897
-			);
898
-		});
899
-		$this->registerAlias('NotificationManager', \OCP\Notification\IManager::class);
900
-
901
-		$this->registerService(\OC\CapabilitiesManager::class, function (Server $c) {
902
-			$manager = new \OC\CapabilitiesManager($c->getLogger());
903
-			$manager->registerCapability(function () use ($c) {
904
-				return new \OC\OCS\CoreCapabilities($c->getConfig());
905
-			});
906
-			$manager->registerCapability(function () use ($c) {
907
-				return $c->query(\OC\Security\Bruteforce\Capabilities::class);
908
-			});
909
-			return $manager;
910
-		});
911
-		$this->registerAlias('CapabilitiesManager', \OC\CapabilitiesManager::class);
912
-
913
-		$this->registerService(\OCP\Comments\ICommentsManager::class, function (Server $c) {
914
-			$config = $c->getConfig();
915
-			$factoryClass = $config->getSystemValue('comments.managerFactory', CommentsManagerFactory::class);
916
-			/** @var \OCP\Comments\ICommentsManagerFactory $factory */
917
-			$factory = new $factoryClass($this);
918
-			$manager = $factory->getManager();
919
-
920
-			$manager->registerDisplayNameResolver('user', function($id) use ($c) {
921
-				$manager = $c->getUserManager();
922
-				$user = $manager->get($id);
923
-				if(is_null($user)) {
924
-					$l = $c->getL10N('core');
925
-					$displayName = $l->t('Unknown user');
926
-				} else {
927
-					$displayName = $user->getDisplayName();
928
-				}
929
-				return $displayName;
930
-			});
931
-
932
-			return $manager;
933
-		});
934
-		$this->registerAlias('CommentsManager', \OCP\Comments\ICommentsManager::class);
935
-
936
-		$this->registerService('ThemingDefaults', function (Server $c) {
937
-			/*
156
+    /** @var string */
157
+    private $webRoot;
158
+
159
+    /**
160
+     * @param string $webRoot
161
+     * @param \OC\Config $config
162
+     */
163
+    public function __construct($webRoot, \OC\Config $config) {
164
+        parent::__construct();
165
+        $this->webRoot = $webRoot;
166
+
167
+        // To find out if we are running from CLI or not
168
+        $this->registerParameter('isCLI', \OC::$CLI);
169
+
170
+        $this->registerService(\OCP\IServerContainer::class, function (IServerContainer $c) {
171
+            return $c;
172
+        });
173
+
174
+        $this->registerAlias(\OCP\Calendar\IManager::class, \OC\Calendar\Manager::class);
175
+        $this->registerAlias('CalendarManager', \OC\Calendar\Manager::class);
176
+
177
+        $this->registerAlias(\OCP\Contacts\IManager::class, \OC\ContactsManager::class);
178
+        $this->registerAlias('ContactsManager', \OCP\Contacts\IManager::class);
179
+
180
+        $this->registerAlias(IActionFactory::class, ActionFactory::class);
181
+
182
+
183
+        $this->registerService(\OCP\IPreview::class, function (Server $c) {
184
+            return new PreviewManager(
185
+                $c->getConfig(),
186
+                $c->getRootFolder(),
187
+                $c->getAppDataDir('preview'),
188
+                $c->getEventDispatcher(),
189
+                $c->getSession()->get('user_id')
190
+            );
191
+        });
192
+        $this->registerAlias('PreviewManager', \OCP\IPreview::class);
193
+
194
+        $this->registerService(\OC\Preview\Watcher::class, function (Server $c) {
195
+            return new \OC\Preview\Watcher(
196
+                $c->getAppDataDir('preview')
197
+            );
198
+        });
199
+
200
+        $this->registerService('EncryptionManager', function (Server $c) {
201
+            $view = new View();
202
+            $util = new Encryption\Util(
203
+                $view,
204
+                $c->getUserManager(),
205
+                $c->getGroupManager(),
206
+                $c->getConfig()
207
+            );
208
+            return new Encryption\Manager(
209
+                $c->getConfig(),
210
+                $c->getLogger(),
211
+                $c->getL10N('core'),
212
+                new View(),
213
+                $util,
214
+                new ArrayCache()
215
+            );
216
+        });
217
+
218
+        $this->registerService('EncryptionFileHelper', function (Server $c) {
219
+            $util = new Encryption\Util(
220
+                new View(),
221
+                $c->getUserManager(),
222
+                $c->getGroupManager(),
223
+                $c->getConfig()
224
+            );
225
+            return new Encryption\File(
226
+                $util,
227
+                $c->getRootFolder(),
228
+                $c->getShareManager()
229
+            );
230
+        });
231
+
232
+        $this->registerService('EncryptionKeyStorage', function (Server $c) {
233
+            $view = new View();
234
+            $util = new Encryption\Util(
235
+                $view,
236
+                $c->getUserManager(),
237
+                $c->getGroupManager(),
238
+                $c->getConfig()
239
+            );
240
+
241
+            return new Encryption\Keys\Storage($view, $util);
242
+        });
243
+        $this->registerService('TagMapper', function (Server $c) {
244
+            return new TagMapper($c->getDatabaseConnection());
245
+        });
246
+
247
+        $this->registerService(\OCP\ITagManager::class, function (Server $c) {
248
+            $tagMapper = $c->query('TagMapper');
249
+            return new TagManager($tagMapper, $c->getUserSession());
250
+        });
251
+        $this->registerAlias('TagManager', \OCP\ITagManager::class);
252
+
253
+        $this->registerService('SystemTagManagerFactory', function (Server $c) {
254
+            $config = $c->getConfig();
255
+            $factoryClass = $config->getSystemValue('systemtags.managerFactory', SystemTagManagerFactory::class);
256
+            return new $factoryClass($this);
257
+        });
258
+        $this->registerService(\OCP\SystemTag\ISystemTagManager::class, function (Server $c) {
259
+            return $c->query('SystemTagManagerFactory')->getManager();
260
+        });
261
+        $this->registerAlias('SystemTagManager', \OCP\SystemTag\ISystemTagManager::class);
262
+
263
+        $this->registerService(\OCP\SystemTag\ISystemTagObjectMapper::class, function (Server $c) {
264
+            return $c->query('SystemTagManagerFactory')->getObjectMapper();
265
+        });
266
+        $this->registerService('RootFolder', function (Server $c) {
267
+            $manager = \OC\Files\Filesystem::getMountManager(null);
268
+            $view = new View();
269
+            $root = new Root(
270
+                $manager,
271
+                $view,
272
+                null,
273
+                $c->getUserMountCache(),
274
+                $this->getLogger(),
275
+                $this->getUserManager()
276
+            );
277
+            $connector = new HookConnector($root, $view);
278
+            $connector->viewToNode();
279
+
280
+            $previewConnector = new \OC\Preview\WatcherConnector($root, $c->getSystemConfig());
281
+            $previewConnector->connectWatcher();
282
+
283
+            return $root;
284
+        });
285
+        $this->registerAlias('SystemTagObjectMapper', \OCP\SystemTag\ISystemTagObjectMapper::class);
286
+
287
+        $this->registerService(\OCP\Files\IRootFolder::class, function (Server $c) {
288
+            return new LazyRoot(function () use ($c) {
289
+                return $c->query('RootFolder');
290
+            });
291
+        });
292
+        $this->registerAlias('LazyRootFolder', \OCP\Files\IRootFolder::class);
293
+
294
+        $this->registerService(\OC\User\Manager::class, function (Server $c) {
295
+            $config = $c->getConfig();
296
+            return new \OC\User\Manager($config);
297
+        });
298
+        $this->registerAlias('UserManager', \OC\User\Manager::class);
299
+        $this->registerAlias(\OCP\IUserManager::class, \OC\User\Manager::class);
300
+
301
+        $this->registerService(\OCP\IGroupManager::class, function (Server $c) {
302
+            $groupManager = new \OC\Group\Manager($this->getUserManager(), $this->getLogger());
303
+            $groupManager->listen('\OC\Group', 'preCreate', function ($gid) {
304
+                \OC_Hook::emit('OC_Group', 'pre_createGroup', array('run' => true, 'gid' => $gid));
305
+            });
306
+            $groupManager->listen('\OC\Group', 'postCreate', function (\OC\Group\Group $gid) {
307
+                \OC_Hook::emit('OC_User', 'post_createGroup', array('gid' => $gid->getGID()));
308
+            });
309
+            $groupManager->listen('\OC\Group', 'preDelete', function (\OC\Group\Group $group) {
310
+                \OC_Hook::emit('OC_Group', 'pre_deleteGroup', array('run' => true, 'gid' => $group->getGID()));
311
+            });
312
+            $groupManager->listen('\OC\Group', 'postDelete', function (\OC\Group\Group $group) {
313
+                \OC_Hook::emit('OC_User', 'post_deleteGroup', array('gid' => $group->getGID()));
314
+            });
315
+            $groupManager->listen('\OC\Group', 'preAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
316
+                \OC_Hook::emit('OC_Group', 'pre_addToGroup', array('run' => true, 'uid' => $user->getUID(), 'gid' => $group->getGID()));
317
+            });
318
+            $groupManager->listen('\OC\Group', 'postAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
319
+                \OC_Hook::emit('OC_Group', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
320
+                //Minimal fix to keep it backward compatible TODO: clean up all the GroupManager hooks
321
+                \OC_Hook::emit('OC_User', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
322
+            });
323
+            return $groupManager;
324
+        });
325
+        $this->registerAlias('GroupManager', \OCP\IGroupManager::class);
326
+
327
+        $this->registerService(Store::class, function (Server $c) {
328
+            $session = $c->getSession();
329
+            if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
330
+                $tokenProvider = $c->query(IProvider::class);
331
+            } else {
332
+                $tokenProvider = null;
333
+            }
334
+            $logger = $c->getLogger();
335
+            return new Store($session, $logger, $tokenProvider);
336
+        });
337
+        $this->registerAlias(IStore::class, Store::class);
338
+        $this->registerService(Authentication\Token\DefaultTokenMapper::class, function (Server $c) {
339
+            $dbConnection = $c->getDatabaseConnection();
340
+            return new Authentication\Token\DefaultTokenMapper($dbConnection);
341
+        });
342
+        $this->registerService(Authentication\Token\DefaultTokenProvider::class, function (Server $c) {
343
+            $mapper = $c->query(Authentication\Token\DefaultTokenMapper::class);
344
+            $crypto = $c->getCrypto();
345
+            $config = $c->getConfig();
346
+            $logger = $c->getLogger();
347
+            $timeFactory = new TimeFactory();
348
+            return new \OC\Authentication\Token\DefaultTokenProvider($mapper, $crypto, $config, $logger, $timeFactory);
349
+        });
350
+        $this->registerAlias(IProvider::class, Authentication\Token\DefaultTokenProvider::class);
351
+
352
+        $this->registerService(\OCP\IUserSession::class, function (Server $c) {
353
+            $manager = $c->getUserManager();
354
+            $session = new \OC\Session\Memory('');
355
+            $timeFactory = new TimeFactory();
356
+            // Token providers might require a working database. This code
357
+            // might however be called when ownCloud is not yet setup.
358
+            if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
359
+                $defaultTokenProvider = $c->query(IProvider::class);
360
+            } else {
361
+                $defaultTokenProvider = null;
362
+            }
363
+
364
+            $dispatcher = $c->getEventDispatcher();
365
+
366
+            $userSession = new \OC\User\Session(
367
+                $manager,
368
+                $session,
369
+                $timeFactory,
370
+                $defaultTokenProvider,
371
+                $c->getConfig(),
372
+                $c->getSecureRandom(),
373
+                $c->getLockdownManager(),
374
+                $c->getLogger()
375
+            );
376
+            $userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
377
+                \OC_Hook::emit('OC_User', 'pre_createUser', array('run' => true, 'uid' => $uid, 'password' => $password));
378
+            });
379
+            $userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
380
+                /** @var $user \OC\User\User */
381
+                \OC_Hook::emit('OC_User', 'post_createUser', array('uid' => $user->getUID(), 'password' => $password));
382
+            });
383
+            $userSession->listen('\OC\User', 'preDelete', function ($user) use ($dispatcher) {
384
+                /** @var $user \OC\User\User */
385
+                \OC_Hook::emit('OC_User', 'pre_deleteUser', array('run' => true, 'uid' => $user->getUID()));
386
+                $dispatcher->dispatch('OCP\IUser::preDelete', new GenericEvent($user));
387
+            });
388
+            $userSession->listen('\OC\User', 'postDelete', function ($user) {
389
+                /** @var $user \OC\User\User */
390
+                \OC_Hook::emit('OC_User', 'post_deleteUser', array('uid' => $user->getUID()));
391
+            });
392
+            $userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
393
+                /** @var $user \OC\User\User */
394
+                \OC_Hook::emit('OC_User', 'pre_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
395
+            });
396
+            $userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
397
+                /** @var $user \OC\User\User */
398
+                \OC_Hook::emit('OC_User', 'post_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
399
+            });
400
+            $userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
401
+                \OC_Hook::emit('OC_User', 'pre_login', array('run' => true, 'uid' => $uid, 'password' => $password));
402
+            });
403
+            $userSession->listen('\OC\User', 'postLogin', function ($user, $password) {
404
+                /** @var $user \OC\User\User */
405
+                \OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
406
+            });
407
+            $userSession->listen('\OC\User', 'postRememberedLogin', function ($user, $password) {
408
+                /** @var $user \OC\User\User */
409
+                \OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
410
+            });
411
+            $userSession->listen('\OC\User', 'logout', function () {
412
+                \OC_Hook::emit('OC_User', 'logout', array());
413
+            });
414
+            $userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value, $oldValue) use ($dispatcher) {
415
+                /** @var $user \OC\User\User */
416
+                \OC_Hook::emit('OC_User', 'changeUser', array('run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value, 'old_value' => $oldValue));
417
+                $dispatcher->dispatch('OCP\IUser::changeUser', new GenericEvent($user, ['feature' => $feature, 'oldValue' => $oldValue, 'value' => $value]));
418
+            });
419
+            return $userSession;
420
+        });
421
+        $this->registerAlias('UserSession', \OCP\IUserSession::class);
422
+
423
+        $this->registerService(\OC\Authentication\TwoFactorAuth\Manager::class, function (Server $c) {
424
+            return new \OC\Authentication\TwoFactorAuth\Manager(
425
+                $c->getAppManager(),
426
+                $c->getSession(),
427
+                $c->getConfig(),
428
+                $c->getActivityManager(),
429
+                $c->getLogger(),
430
+                $c->query(IProvider::class),
431
+                $c->query(ITimeFactory::class),
432
+                $c->query(EventDispatcherInterface::class)
433
+            );
434
+        });
435
+
436
+        $this->registerAlias(\OCP\INavigationManager::class, \OC\NavigationManager::class);
437
+        $this->registerAlias('NavigationManager', \OCP\INavigationManager::class);
438
+
439
+        $this->registerService(\OC\AllConfig::class, function (Server $c) {
440
+            return new \OC\AllConfig(
441
+                $c->getSystemConfig()
442
+            );
443
+        });
444
+        $this->registerAlias('AllConfig', \OC\AllConfig::class);
445
+        $this->registerAlias(\OCP\IConfig::class, \OC\AllConfig::class);
446
+
447
+        $this->registerService('SystemConfig', function ($c) use ($config) {
448
+            return new \OC\SystemConfig($config);
449
+        });
450
+
451
+        $this->registerService(\OC\AppConfig::class, function (Server $c) {
452
+            return new \OC\AppConfig($c->getDatabaseConnection());
453
+        });
454
+        $this->registerAlias('AppConfig', \OC\AppConfig::class);
455
+        $this->registerAlias(\OCP\IAppConfig::class, \OC\AppConfig::class);
456
+
457
+        $this->registerService(\OCP\L10N\IFactory::class, function (Server $c) {
458
+            return new \OC\L10N\Factory(
459
+                $c->getConfig(),
460
+                $c->getRequest(),
461
+                $c->getUserSession(),
462
+                \OC::$SERVERROOT
463
+            );
464
+        });
465
+        $this->registerAlias('L10NFactory', \OCP\L10N\IFactory::class);
466
+
467
+        $this->registerService(\OCP\IURLGenerator::class, function (Server $c) {
468
+            $config = $c->getConfig();
469
+            $cacheFactory = $c->getMemCacheFactory();
470
+            $request = $c->getRequest();
471
+            return new \OC\URLGenerator(
472
+                $config,
473
+                $cacheFactory,
474
+                $request
475
+            );
476
+        });
477
+        $this->registerAlias('URLGenerator', \OCP\IURLGenerator::class);
478
+
479
+        $this->registerAlias('AppFetcher', AppFetcher::class);
480
+        $this->registerAlias('CategoryFetcher', CategoryFetcher::class);
481
+
482
+        $this->registerService(\OCP\ICache::class, function ($c) {
483
+            return new Cache\File();
484
+        });
485
+        $this->registerAlias('UserCache', \OCP\ICache::class);
486
+
487
+        $this->registerService(Factory::class, function (Server $c) {
488
+
489
+            $arrayCacheFactory = new \OC\Memcache\Factory('', $c->getLogger(),
490
+                ArrayCache::class,
491
+                ArrayCache::class,
492
+                ArrayCache::class
493
+            );
494
+            $config = $c->getConfig();
495
+            $request = $c->getRequest();
496
+            $urlGenerator = new URLGenerator($config, $arrayCacheFactory, $request);
497
+
498
+            if ($config->getSystemValue('installed', false) && !(defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
499
+                $v = \OC_App::getAppVersions();
500
+                $v['core'] = implode(',', \OC_Util::getVersion());
501
+                $version = implode(',', $v);
502
+                $instanceId = \OC_Util::getInstanceId();
503
+                $path = \OC::$SERVERROOT;
504
+                $prefix = md5($instanceId . '-' . $version . '-' . $path);
505
+                return new \OC\Memcache\Factory($prefix, $c->getLogger(),
506
+                    $config->getSystemValue('memcache.local', null),
507
+                    $config->getSystemValue('memcache.distributed', null),
508
+                    $config->getSystemValue('memcache.locking', null)
509
+                );
510
+            }
511
+            return $arrayCacheFactory;
512
+
513
+        });
514
+        $this->registerAlias('MemCacheFactory', Factory::class);
515
+        $this->registerAlias(ICacheFactory::class, Factory::class);
516
+
517
+        $this->registerService('RedisFactory', function (Server $c) {
518
+            $systemConfig = $c->getSystemConfig();
519
+            return new RedisFactory($systemConfig);
520
+        });
521
+
522
+        $this->registerService(\OCP\Activity\IManager::class, function (Server $c) {
523
+            return new \OC\Activity\Manager(
524
+                $c->getRequest(),
525
+                $c->getUserSession(),
526
+                $c->getConfig(),
527
+                $c->query(IValidator::class)
528
+            );
529
+        });
530
+        $this->registerAlias('ActivityManager', \OCP\Activity\IManager::class);
531
+
532
+        $this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
533
+            return new \OC\Activity\EventMerger(
534
+                $c->getL10N('lib')
535
+            );
536
+        });
537
+        $this->registerAlias(IValidator::class, Validator::class);
538
+
539
+        $this->registerService(\OCP\IAvatarManager::class, function (Server $c) {
540
+            return new AvatarManager(
541
+                $c->query(\OC\User\Manager::class),
542
+                $c->getAppDataDir('avatar'),
543
+                $c->getL10N('lib'),
544
+                $c->getLogger(),
545
+                $c->getConfig()
546
+            );
547
+        });
548
+        $this->registerAlias('AvatarManager', \OCP\IAvatarManager::class);
549
+
550
+        $this->registerAlias(\OCP\Support\CrashReport\IRegistry::class, \OC\Support\CrashReport\Registry::class);
551
+
552
+        $this->registerService(\OCP\ILogger::class, function (Server $c) {
553
+            $logType = $c->query('AllConfig')->getSystemValue('log_type', 'file');
554
+            $factory = new LogFactory($c, $this->getSystemConfig());
555
+            $logger = $factory->get($logType);
556
+            $registry = $c->query(\OCP\Support\CrashReport\IRegistry::class);
557
+
558
+            return new Log($logger, $this->getSystemConfig(), null, $registry);
559
+        });
560
+        $this->registerAlias('Logger', \OCP\ILogger::class);
561
+
562
+        $this->registerService(ILogFactory::class, function (Server $c) {
563
+            return new LogFactory($c, $this->getSystemConfig());
564
+        });
565
+
566
+        $this->registerService(\OCP\BackgroundJob\IJobList::class, function (Server $c) {
567
+            $config = $c->getConfig();
568
+            return new \OC\BackgroundJob\JobList(
569
+                $c->getDatabaseConnection(),
570
+                $config,
571
+                new TimeFactory()
572
+            );
573
+        });
574
+        $this->registerAlias('JobList', \OCP\BackgroundJob\IJobList::class);
575
+
576
+        $this->registerService(\OCP\Route\IRouter::class, function (Server $c) {
577
+            $cacheFactory = $c->getMemCacheFactory();
578
+            $logger = $c->getLogger();
579
+            if ($cacheFactory->isLocalCacheAvailable()) {
580
+                $router = new \OC\Route\CachingRouter($cacheFactory->createLocal('route'), $logger);
581
+            } else {
582
+                $router = new \OC\Route\Router($logger);
583
+            }
584
+            return $router;
585
+        });
586
+        $this->registerAlias('Router', \OCP\Route\IRouter::class);
587
+
588
+        $this->registerService(\OCP\ISearch::class, function ($c) {
589
+            return new Search();
590
+        });
591
+        $this->registerAlias('Search', \OCP\ISearch::class);
592
+
593
+        $this->registerService(\OC\Security\RateLimiting\Limiter::class, function (Server $c) {
594
+            return new \OC\Security\RateLimiting\Limiter(
595
+                $this->getUserSession(),
596
+                $this->getRequest(),
597
+                new \OC\AppFramework\Utility\TimeFactory(),
598
+                $c->query(\OC\Security\RateLimiting\Backend\IBackend::class)
599
+            );
600
+        });
601
+        $this->registerService(\OC\Security\RateLimiting\Backend\IBackend::class, function ($c) {
602
+            return new \OC\Security\RateLimiting\Backend\MemoryCache(
603
+                $this->getMemCacheFactory(),
604
+                new \OC\AppFramework\Utility\TimeFactory()
605
+            );
606
+        });
607
+
608
+        $this->registerService(\OCP\Security\ISecureRandom::class, function ($c) {
609
+            return new SecureRandom();
610
+        });
611
+        $this->registerAlias('SecureRandom', \OCP\Security\ISecureRandom::class);
612
+
613
+        $this->registerService(\OCP\Security\ICrypto::class, function (Server $c) {
614
+            return new Crypto($c->getConfig(), $c->getSecureRandom());
615
+        });
616
+        $this->registerAlias('Crypto', \OCP\Security\ICrypto::class);
617
+
618
+        $this->registerService(\OCP\Security\IHasher::class, function (Server $c) {
619
+            return new Hasher($c->getConfig());
620
+        });
621
+        $this->registerAlias('Hasher', \OCP\Security\IHasher::class);
622
+
623
+        $this->registerService(\OCP\Security\ICredentialsManager::class, function (Server $c) {
624
+            return new CredentialsManager($c->getCrypto(), $c->getDatabaseConnection());
625
+        });
626
+        $this->registerAlias('CredentialsManager', \OCP\Security\ICredentialsManager::class);
627
+
628
+        $this->registerService(IDBConnection::class, function (Server $c) {
629
+            $systemConfig = $c->getSystemConfig();
630
+            $factory = new \OC\DB\ConnectionFactory($systemConfig);
631
+            $type = $systemConfig->getValue('dbtype', 'sqlite');
632
+            if (!$factory->isValidType($type)) {
633
+                throw new \OC\DatabaseException('Invalid database type');
634
+            }
635
+            $connectionParams = $factory->createConnectionParams();
636
+            $connection = $factory->getConnection($type, $connectionParams);
637
+            $connection->getConfiguration()->setSQLLogger($c->getQueryLogger());
638
+            return $connection;
639
+        });
640
+        $this->registerAlias('DatabaseConnection', IDBConnection::class);
641
+
642
+
643
+        $this->registerService(\OCP\Http\Client\IClientService::class, function (Server $c) {
644
+            $user = \OC_User::getUser();
645
+            $uid = $user ? $user : null;
646
+            return new ClientService(
647
+                $c->getConfig(),
648
+                new \OC\Security\CertificateManager(
649
+                    $uid,
650
+                    new View(),
651
+                    $c->getConfig(),
652
+                    $c->getLogger(),
653
+                    $c->getSecureRandom()
654
+                )
655
+            );
656
+        });
657
+        $this->registerAlias('HttpClientService', \OCP\Http\Client\IClientService::class);
658
+        $this->registerService(\OCP\Diagnostics\IEventLogger::class, function (Server $c) {
659
+            $eventLogger = new EventLogger();
660
+            if ($c->getSystemConfig()->getValue('debug', false)) {
661
+                // In debug mode, module is being activated by default
662
+                $eventLogger->activate();
663
+            }
664
+            return $eventLogger;
665
+        });
666
+        $this->registerAlias('EventLogger', \OCP\Diagnostics\IEventLogger::class);
667
+
668
+        $this->registerService(\OCP\Diagnostics\IQueryLogger::class, function (Server $c) {
669
+            $queryLogger = new QueryLogger();
670
+            if ($c->getSystemConfig()->getValue('debug', false)) {
671
+                // In debug mode, module is being activated by default
672
+                $queryLogger->activate();
673
+            }
674
+            return $queryLogger;
675
+        });
676
+        $this->registerAlias('QueryLogger', \OCP\Diagnostics\IQueryLogger::class);
677
+
678
+        $this->registerService(TempManager::class, function (Server $c) {
679
+            return new TempManager(
680
+                $c->getLogger(),
681
+                $c->getConfig()
682
+            );
683
+        });
684
+        $this->registerAlias('TempManager', TempManager::class);
685
+        $this->registerAlias(ITempManager::class, TempManager::class);
686
+
687
+        $this->registerService(AppManager::class, function (Server $c) {
688
+            return new \OC\App\AppManager(
689
+                $c->getUserSession(),
690
+                $c->getConfig(),
691
+                $c->getGroupManager(),
692
+                $c->getMemCacheFactory(),
693
+                $c->getEventDispatcher()
694
+            );
695
+        });
696
+        $this->registerAlias('AppManager', AppManager::class);
697
+        $this->registerAlias(IAppManager::class, AppManager::class);
698
+
699
+        $this->registerService(\OCP\IDateTimeZone::class, function (Server $c) {
700
+            return new DateTimeZone(
701
+                $c->getConfig(),
702
+                $c->getSession()
703
+            );
704
+        });
705
+        $this->registerAlias('DateTimeZone', \OCP\IDateTimeZone::class);
706
+
707
+        $this->registerService(\OCP\IDateTimeFormatter::class, function (Server $c) {
708
+            $language = $c->getConfig()->getUserValue($c->getSession()->get('user_id'), 'core', 'lang', null);
709
+
710
+            return new DateTimeFormatter(
711
+                $c->getDateTimeZone()->getTimeZone(),
712
+                $c->getL10N('lib', $language)
713
+            );
714
+        });
715
+        $this->registerAlias('DateTimeFormatter', \OCP\IDateTimeFormatter::class);
716
+
717
+        $this->registerService(\OCP\Files\Config\IUserMountCache::class, function (Server $c) {
718
+            $mountCache = new UserMountCache($c->getDatabaseConnection(), $c->getUserManager(), $c->getLogger());
719
+            $listener = new UserMountCacheListener($mountCache);
720
+            $listener->listen($c->getUserManager());
721
+            return $mountCache;
722
+        });
723
+        $this->registerAlias('UserMountCache', \OCP\Files\Config\IUserMountCache::class);
724
+
725
+        $this->registerService(\OCP\Files\Config\IMountProviderCollection::class, function (Server $c) {
726
+            $loader = \OC\Files\Filesystem::getLoader();
727
+            $mountCache = $c->query('UserMountCache');
728
+            $manager = new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
729
+
730
+            // builtin providers
731
+
732
+            $config = $c->getConfig();
733
+            $manager->registerProvider(new CacheMountProvider($config));
734
+            $manager->registerHomeProvider(new LocalHomeMountProvider());
735
+            $manager->registerHomeProvider(new ObjectHomeMountProvider($config));
736
+
737
+            return $manager;
738
+        });
739
+        $this->registerAlias('MountConfigManager', \OCP\Files\Config\IMountProviderCollection::class);
740
+
741
+        $this->registerService('IniWrapper', function ($c) {
742
+            return new IniGetWrapper();
743
+        });
744
+        $this->registerService('AsyncCommandBus', function (Server $c) {
745
+            $busClass = $c->getConfig()->getSystemValue('commandbus');
746
+            if ($busClass) {
747
+                list($app, $class) = explode('::', $busClass, 2);
748
+                if ($c->getAppManager()->isInstalled($app)) {
749
+                    \OC_App::loadApp($app);
750
+                    return $c->query($class);
751
+                } else {
752
+                    throw new ServiceUnavailableException("The app providing the command bus ($app) is not enabled");
753
+                }
754
+            } else {
755
+                $jobList = $c->getJobList();
756
+                return new CronBus($jobList);
757
+            }
758
+        });
759
+        $this->registerService('TrustedDomainHelper', function ($c) {
760
+            return new TrustedDomainHelper($this->getConfig());
761
+        });
762
+        $this->registerService('Throttler', function (Server $c) {
763
+            return new Throttler(
764
+                $c->getDatabaseConnection(),
765
+                new TimeFactory(),
766
+                $c->getLogger(),
767
+                $c->getConfig()
768
+            );
769
+        });
770
+        $this->registerService('IntegrityCodeChecker', function (Server $c) {
771
+            // IConfig and IAppManager requires a working database. This code
772
+            // might however be called when ownCloud is not yet setup.
773
+            if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
774
+                $config = $c->getConfig();
775
+                $appManager = $c->getAppManager();
776
+            } else {
777
+                $config = null;
778
+                $appManager = null;
779
+            }
780
+
781
+            return new Checker(
782
+                new EnvironmentHelper(),
783
+                new FileAccessHelper(),
784
+                new AppLocator(),
785
+                $config,
786
+                $c->getMemCacheFactory(),
787
+                $appManager,
788
+                $c->getTempManager()
789
+            );
790
+        });
791
+        $this->registerService(\OCP\IRequest::class, function ($c) {
792
+            if (isset($this['urlParams'])) {
793
+                $urlParams = $this['urlParams'];
794
+            } else {
795
+                $urlParams = [];
796
+            }
797
+
798
+            if (defined('PHPUNIT_RUN') && PHPUNIT_RUN
799
+                && in_array('fakeinput', stream_get_wrappers())
800
+            ) {
801
+                $stream = 'fakeinput://data';
802
+            } else {
803
+                $stream = 'php://input';
804
+            }
805
+
806
+            return new Request(
807
+                [
808
+                    'get' => $_GET,
809
+                    'post' => $_POST,
810
+                    'files' => $_FILES,
811
+                    'server' => $_SERVER,
812
+                    'env' => $_ENV,
813
+                    'cookies' => $_COOKIE,
814
+                    'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
815
+                        ? $_SERVER['REQUEST_METHOD']
816
+                        : '',
817
+                    'urlParams' => $urlParams,
818
+                ],
819
+                $this->getSecureRandom(),
820
+                $this->getConfig(),
821
+                $this->getCsrfTokenManager(),
822
+                $stream
823
+            );
824
+        });
825
+        $this->registerAlias('Request', \OCP\IRequest::class);
826
+
827
+        $this->registerService(\OCP\Mail\IMailer::class, function (Server $c) {
828
+            return new Mailer(
829
+                $c->getConfig(),
830
+                $c->getLogger(),
831
+                $c->query(Defaults::class),
832
+                $c->getURLGenerator(),
833
+                $c->getL10N('lib')
834
+            );
835
+        });
836
+        $this->registerAlias('Mailer', \OCP\Mail\IMailer::class);
837
+
838
+        $this->registerService('LDAPProvider', function (Server $c) {
839
+            $config = $c->getConfig();
840
+            $factoryClass = $config->getSystemValue('ldapProviderFactory', null);
841
+            if (is_null($factoryClass)) {
842
+                throw new \Exception('ldapProviderFactory not set');
843
+            }
844
+            /** @var \OCP\LDAP\ILDAPProviderFactory $factory */
845
+            $factory = new $factoryClass($this);
846
+            return $factory->getLDAPProvider();
847
+        });
848
+        $this->registerService(ILockingProvider::class, function (Server $c) {
849
+            $ini = $c->getIniWrapper();
850
+            $config = $c->getConfig();
851
+            $ttl = $config->getSystemValue('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
852
+            if ($config->getSystemValue('filelocking.enabled', true) or (defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
853
+                /** @var \OC\Memcache\Factory $memcacheFactory */
854
+                $memcacheFactory = $c->getMemCacheFactory();
855
+                $memcache = $memcacheFactory->createLocking('lock');
856
+                if (!($memcache instanceof \OC\Memcache\NullCache)) {
857
+                    return new MemcacheLockingProvider($memcache, $ttl);
858
+                }
859
+                return new DBLockingProvider(
860
+                    $c->getDatabaseConnection(),
861
+                    $c->getLogger(),
862
+                    new TimeFactory(),
863
+                    $ttl,
864
+                    !\OC::$CLI
865
+                );
866
+            }
867
+            return new NoopLockingProvider();
868
+        });
869
+        $this->registerAlias('LockingProvider', ILockingProvider::class);
870
+
871
+        $this->registerService(\OCP\Files\Mount\IMountManager::class, function () {
872
+            return new \OC\Files\Mount\Manager();
873
+        });
874
+        $this->registerAlias('MountManager', \OCP\Files\Mount\IMountManager::class);
875
+
876
+        $this->registerService(\OCP\Files\IMimeTypeDetector::class, function (Server $c) {
877
+            return new \OC\Files\Type\Detection(
878
+                $c->getURLGenerator(),
879
+                \OC::$configDir,
880
+                \OC::$SERVERROOT . '/resources/config/'
881
+            );
882
+        });
883
+        $this->registerAlias('MimeTypeDetector', \OCP\Files\IMimeTypeDetector::class);
884
+
885
+        $this->registerService(\OCP\Files\IMimeTypeLoader::class, function (Server $c) {
886
+            return new \OC\Files\Type\Loader(
887
+                $c->getDatabaseConnection()
888
+            );
889
+        });
890
+        $this->registerAlias('MimeTypeLoader', \OCP\Files\IMimeTypeLoader::class);
891
+        $this->registerService(BundleFetcher::class, function () {
892
+            return new BundleFetcher($this->getL10N('lib'));
893
+        });
894
+        $this->registerService(\OCP\Notification\IManager::class, function (Server $c) {
895
+            return new Manager(
896
+                $c->query(IValidator::class)
897
+            );
898
+        });
899
+        $this->registerAlias('NotificationManager', \OCP\Notification\IManager::class);
900
+
901
+        $this->registerService(\OC\CapabilitiesManager::class, function (Server $c) {
902
+            $manager = new \OC\CapabilitiesManager($c->getLogger());
903
+            $manager->registerCapability(function () use ($c) {
904
+                return new \OC\OCS\CoreCapabilities($c->getConfig());
905
+            });
906
+            $manager->registerCapability(function () use ($c) {
907
+                return $c->query(\OC\Security\Bruteforce\Capabilities::class);
908
+            });
909
+            return $manager;
910
+        });
911
+        $this->registerAlias('CapabilitiesManager', \OC\CapabilitiesManager::class);
912
+
913
+        $this->registerService(\OCP\Comments\ICommentsManager::class, function (Server $c) {
914
+            $config = $c->getConfig();
915
+            $factoryClass = $config->getSystemValue('comments.managerFactory', CommentsManagerFactory::class);
916
+            /** @var \OCP\Comments\ICommentsManagerFactory $factory */
917
+            $factory = new $factoryClass($this);
918
+            $manager = $factory->getManager();
919
+
920
+            $manager->registerDisplayNameResolver('user', function($id) use ($c) {
921
+                $manager = $c->getUserManager();
922
+                $user = $manager->get($id);
923
+                if(is_null($user)) {
924
+                    $l = $c->getL10N('core');
925
+                    $displayName = $l->t('Unknown user');
926
+                } else {
927
+                    $displayName = $user->getDisplayName();
928
+                }
929
+                return $displayName;
930
+            });
931
+
932
+            return $manager;
933
+        });
934
+        $this->registerAlias('CommentsManager', \OCP\Comments\ICommentsManager::class);
935
+
936
+        $this->registerService('ThemingDefaults', function (Server $c) {
937
+            /*
938 938
 			 * Dark magic for autoloader.
939 939
 			 * If we do a class_exists it will try to load the class which will
940 940
 			 * make composer cache the result. Resulting in errors when enabling
941 941
 			 * the theming app.
942 942
 			 */
943
-			$prefixes = \OC::$composerAutoloader->getPrefixesPsr4();
944
-			if (isset($prefixes['OCA\\Theming\\'])) {
945
-				$classExists = true;
946
-			} else {
947
-				$classExists = false;
948
-			}
949
-
950
-			if ($classExists && $c->getConfig()->getSystemValue('installed', false) && $c->getAppManager()->isInstalled('theming') && $c->getTrustedDomainHelper()->isTrustedDomain($c->getRequest()->getInsecureServerHost())) {
951
-				return new ThemingDefaults(
952
-					$c->getConfig(),
953
-					$c->getL10N('theming'),
954
-					$c->getURLGenerator(),
955
-					$c->getMemCacheFactory(),
956
-					new Util($c->getConfig(), $this->getAppManager(), $c->getAppDataDir('theming')),
957
-					new ImageManager($c->getConfig(), $c->getAppDataDir('theming'), $c->getURLGenerator()),
958
-					$c->getAppManager()
959
-				);
960
-			}
961
-			return new \OC_Defaults();
962
-		});
963
-		$this->registerService(SCSSCacher::class, function (Server $c) {
964
-			/** @var Factory $cacheFactory */
965
-			$cacheFactory = $c->query(Factory::class);
966
-			return new SCSSCacher(
967
-				$c->getLogger(),
968
-				$c->query(\OC\Files\AppData\Factory::class),
969
-				$c->getURLGenerator(),
970
-				$c->getConfig(),
971
-				$c->getThemingDefaults(),
972
-				\OC::$SERVERROOT,
973
-				$this->getMemCacheFactory()
974
-			);
975
-		});
976
-		$this->registerService(JSCombiner::class, function (Server $c) {
977
-			/** @var Factory $cacheFactory */
978
-			$cacheFactory = $c->query(Factory::class);
979
-			return new JSCombiner(
980
-				$c->getAppDataDir('js'),
981
-				$c->getURLGenerator(),
982
-				$this->getMemCacheFactory(),
983
-				$c->getSystemConfig(),
984
-				$c->getLogger()
985
-			);
986
-		});
987
-		$this->registerService(EventDispatcher::class, function () {
988
-			return new EventDispatcher();
989
-		});
990
-		$this->registerAlias('EventDispatcher', EventDispatcher::class);
991
-		$this->registerAlias(EventDispatcherInterface::class, EventDispatcher::class);
992
-
993
-		$this->registerService('CryptoWrapper', function (Server $c) {
994
-			// FIXME: Instantiiated here due to cyclic dependency
995
-			$request = new Request(
996
-				[
997
-					'get' => $_GET,
998
-					'post' => $_POST,
999
-					'files' => $_FILES,
1000
-					'server' => $_SERVER,
1001
-					'env' => $_ENV,
1002
-					'cookies' => $_COOKIE,
1003
-					'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
1004
-						? $_SERVER['REQUEST_METHOD']
1005
-						: null,
1006
-				],
1007
-				$c->getSecureRandom(),
1008
-				$c->getConfig()
1009
-			);
1010
-
1011
-			return new CryptoWrapper(
1012
-				$c->getConfig(),
1013
-				$c->getCrypto(),
1014
-				$c->getSecureRandom(),
1015
-				$request
1016
-			);
1017
-		});
1018
-		$this->registerService('CsrfTokenManager', function (Server $c) {
1019
-			$tokenGenerator = new CsrfTokenGenerator($c->getSecureRandom());
1020
-
1021
-			return new CsrfTokenManager(
1022
-				$tokenGenerator,
1023
-				$c->query(SessionStorage::class)
1024
-			);
1025
-		});
1026
-		$this->registerService(SessionStorage::class, function (Server $c) {
1027
-			return new SessionStorage($c->getSession());
1028
-		});
1029
-		$this->registerService(\OCP\Security\IContentSecurityPolicyManager::class, function (Server $c) {
1030
-			return new ContentSecurityPolicyManager();
1031
-		});
1032
-		$this->registerAlias('ContentSecurityPolicyManager', \OCP\Security\IContentSecurityPolicyManager::class);
1033
-
1034
-		$this->registerService('ContentSecurityPolicyNonceManager', function (Server $c) {
1035
-			return new ContentSecurityPolicyNonceManager(
1036
-				$c->getCsrfTokenManager(),
1037
-				$c->getRequest()
1038
-			);
1039
-		});
1040
-
1041
-		$this->registerService(\OCP\Share\IManager::class, function (Server $c) {
1042
-			$config = $c->getConfig();
1043
-			$factoryClass = $config->getSystemValue('sharing.managerFactory', ProviderFactory::class);
1044
-			/** @var \OCP\Share\IProviderFactory $factory */
1045
-			$factory = new $factoryClass($this);
1046
-
1047
-			$manager = new \OC\Share20\Manager(
1048
-				$c->getLogger(),
1049
-				$c->getConfig(),
1050
-				$c->getSecureRandom(),
1051
-				$c->getHasher(),
1052
-				$c->getMountManager(),
1053
-				$c->getGroupManager(),
1054
-				$c->getL10N('lib'),
1055
-				$c->getL10NFactory(),
1056
-				$factory,
1057
-				$c->getUserManager(),
1058
-				$c->getLazyRootFolder(),
1059
-				$c->getEventDispatcher(),
1060
-				$c->getMailer(),
1061
-				$c->getURLGenerator(),
1062
-				$c->getThemingDefaults()
1063
-			);
1064
-
1065
-			return $manager;
1066
-		});
1067
-		$this->registerAlias('ShareManager', \OCP\Share\IManager::class);
1068
-
1069
-		$this->registerService(\OCP\Collaboration\Collaborators\ISearch::class, function(Server $c) {
1070
-			$instance = new Collaboration\Collaborators\Search($c);
1071
-
1072
-			// register default plugins
1073
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_USER', 'class' => UserPlugin::class]);
1074
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_GROUP', 'class' => GroupPlugin::class]);
1075
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_EMAIL', 'class' => MailPlugin::class]);
1076
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_REMOTE', 'class' => RemotePlugin::class]);
1077
-
1078
-			return $instance;
1079
-		});
1080
-		$this->registerAlias('CollaboratorSearch', \OCP\Collaboration\Collaborators\ISearch::class);
1081
-
1082
-		$this->registerAlias(\OCP\Collaboration\AutoComplete\IManager::class, \OC\Collaboration\AutoComplete\Manager::class);
1083
-
1084
-		$this->registerService('SettingsManager', function (Server $c) {
1085
-			$manager = new \OC\Settings\Manager(
1086
-				$c->getLogger(),
1087
-				$c->getDatabaseConnection(),
1088
-				$c->getL10N('lib'),
1089
-				$c->getConfig(),
1090
-				$c->getEncryptionManager(),
1091
-				$c->getUserManager(),
1092
-				$c->getLockingProvider(),
1093
-				$c->getRequest(),
1094
-				$c->getURLGenerator(),
1095
-				$c->query(AccountManager::class),
1096
-				$c->getGroupManager(),
1097
-				$c->getL10NFactory(),
1098
-				$c->getAppManager()
1099
-			);
1100
-			return $manager;
1101
-		});
1102
-		$this->registerService(\OC\Files\AppData\Factory::class, function (Server $c) {
1103
-			return new \OC\Files\AppData\Factory(
1104
-				$c->getRootFolder(),
1105
-				$c->getSystemConfig()
1106
-			);
1107
-		});
1108
-
1109
-		$this->registerService('LockdownManager', function (Server $c) {
1110
-			return new LockdownManager(function () use ($c) {
1111
-				return $c->getSession();
1112
-			});
1113
-		});
1114
-
1115
-		$this->registerService(\OCP\OCS\IDiscoveryService::class, function (Server $c) {
1116
-			return new DiscoveryService($c->getMemCacheFactory(), $c->getHTTPClientService());
1117
-		});
1118
-
1119
-		$this->registerService(ICloudIdManager::class, function (Server $c) {
1120
-			return new CloudIdManager();
1121
-		});
1122
-
1123
-		$this->registerAlias(\OCP\AppFramework\Utility\IControllerMethodReflector::class, \OC\AppFramework\Utility\ControllerMethodReflector::class);
1124
-		$this->registerAlias('ControllerMethodReflector', \OCP\AppFramework\Utility\IControllerMethodReflector::class);
1125
-
1126
-		$this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
1127
-		$this->registerAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
1128
-
1129
-		$this->registerService(Defaults::class, function (Server $c) {
1130
-			return new Defaults(
1131
-				$c->getThemingDefaults()
1132
-			);
1133
-		});
1134
-		$this->registerAlias('Defaults', \OCP\Defaults::class);
1135
-
1136
-		$this->registerService(\OCP\ISession::class, function (SimpleContainer $c) {
1137
-			return $c->query(\OCP\IUserSession::class)->getSession();
1138
-		});
1139
-
1140
-		$this->registerService(IShareHelper::class, function (Server $c) {
1141
-			return new ShareHelper(
1142
-				$c->query(\OCP\Share\IManager::class)
1143
-			);
1144
-		});
1145
-
1146
-		$this->registerService(Installer::class, function(Server $c) {
1147
-			return new Installer(
1148
-				$c->getAppFetcher(),
1149
-				$c->getHTTPClientService(),
1150
-				$c->getTempManager(),
1151
-				$c->getLogger(),
1152
-				$c->getConfig()
1153
-			);
1154
-		});
1155
-
1156
-		$this->registerService(IApiFactory::class, function(Server $c) {
1157
-			return new ApiFactory($c->getHTTPClientService());
1158
-		});
1159
-
1160
-		$this->registerService(IInstanceFactory::class, function(Server $c) {
1161
-			$memcacheFactory = $c->getMemCacheFactory();
1162
-			return new InstanceFactory($memcacheFactory->createLocal('remoteinstance.'), $c->getHTTPClientService());
1163
-		});
1164
-
1165
-		$this->registerService(IContactsStore::class, function(Server $c) {
1166
-			return new ContactsStore(
1167
-				$c->getContactsManager(),
1168
-				$c->getConfig(),
1169
-				$c->getUserManager(),
1170
-				$c->getGroupManager()
1171
-			);
1172
-		});
1173
-		$this->registerAlias(IContactsStore::class, ContactsStore::class);
1174
-
1175
-		$this->connectDispatcher();
1176
-	}
1177
-
1178
-	/**
1179
-	 * @return \OCP\Calendar\IManager
1180
-	 */
1181
-	public function getCalendarManager() {
1182
-		return $this->query('CalendarManager');
1183
-	}
1184
-
1185
-	private function connectDispatcher() {
1186
-		$dispatcher = $this->getEventDispatcher();
1187
-
1188
-		// Delete avatar on user deletion
1189
-		$dispatcher->addListener('OCP\IUser::preDelete', function(GenericEvent $e) {
1190
-			$logger = $this->getLogger();
1191
-			$manager = $this->getAvatarManager();
1192
-			/** @var IUser $user */
1193
-			$user = $e->getSubject();
1194
-
1195
-			try {
1196
-				$avatar = $manager->getAvatar($user->getUID());
1197
-				$avatar->remove();
1198
-			} catch (NotFoundException $e) {
1199
-				// no avatar to remove
1200
-			} catch (\Exception $e) {
1201
-				// Ignore exceptions
1202
-				$logger->info('Could not cleanup avatar of ' . $user->getUID());
1203
-			}
1204
-		});
1205
-
1206
-		$dispatcher->addListener('OCP\IUser::changeUser', function (GenericEvent $e) {
1207
-			$manager = $this->getAvatarManager();
1208
-			/** @var IUser $user */
1209
-			$user = $e->getSubject();
1210
-			$feature = $e->getArgument('feature');
1211
-			$oldValue = $e->getArgument('oldValue');
1212
-			$value = $e->getArgument('value');
1213
-
1214
-			try {
1215
-				$avatar = $manager->getAvatar($user->getUID());
1216
-				$avatar->userChanged($feature, $oldValue, $value);
1217
-			} catch (NotFoundException $e) {
1218
-				// no avatar to remove
1219
-			}
1220
-		});
1221
-	}
1222
-
1223
-	/**
1224
-	 * @return \OCP\Contacts\IManager
1225
-	 */
1226
-	public function getContactsManager() {
1227
-		return $this->query('ContactsManager');
1228
-	}
1229
-
1230
-	/**
1231
-	 * @return \OC\Encryption\Manager
1232
-	 */
1233
-	public function getEncryptionManager() {
1234
-		return $this->query('EncryptionManager');
1235
-	}
1236
-
1237
-	/**
1238
-	 * @return \OC\Encryption\File
1239
-	 */
1240
-	public function getEncryptionFilesHelper() {
1241
-		return $this->query('EncryptionFileHelper');
1242
-	}
1243
-
1244
-	/**
1245
-	 * @return \OCP\Encryption\Keys\IStorage
1246
-	 */
1247
-	public function getEncryptionKeyStorage() {
1248
-		return $this->query('EncryptionKeyStorage');
1249
-	}
1250
-
1251
-	/**
1252
-	 * The current request object holding all information about the request
1253
-	 * currently being processed is returned from this method.
1254
-	 * In case the current execution was not initiated by a web request null is returned
1255
-	 *
1256
-	 * @return \OCP\IRequest
1257
-	 */
1258
-	public function getRequest() {
1259
-		return $this->query('Request');
1260
-	}
1261
-
1262
-	/**
1263
-	 * Returns the preview manager which can create preview images for a given file
1264
-	 *
1265
-	 * @return \OCP\IPreview
1266
-	 */
1267
-	public function getPreviewManager() {
1268
-		return $this->query('PreviewManager');
1269
-	}
1270
-
1271
-	/**
1272
-	 * Returns the tag manager which can get and set tags for different object types
1273
-	 *
1274
-	 * @see \OCP\ITagManager::load()
1275
-	 * @return \OCP\ITagManager
1276
-	 */
1277
-	public function getTagManager() {
1278
-		return $this->query('TagManager');
1279
-	}
1280
-
1281
-	/**
1282
-	 * Returns the system-tag manager
1283
-	 *
1284
-	 * @return \OCP\SystemTag\ISystemTagManager
1285
-	 *
1286
-	 * @since 9.0.0
1287
-	 */
1288
-	public function getSystemTagManager() {
1289
-		return $this->query('SystemTagManager');
1290
-	}
1291
-
1292
-	/**
1293
-	 * Returns the system-tag object mapper
1294
-	 *
1295
-	 * @return \OCP\SystemTag\ISystemTagObjectMapper
1296
-	 *
1297
-	 * @since 9.0.0
1298
-	 */
1299
-	public function getSystemTagObjectMapper() {
1300
-		return $this->query('SystemTagObjectMapper');
1301
-	}
1302
-
1303
-	/**
1304
-	 * Returns the avatar manager, used for avatar functionality
1305
-	 *
1306
-	 * @return \OCP\IAvatarManager
1307
-	 */
1308
-	public function getAvatarManager() {
1309
-		return $this->query('AvatarManager');
1310
-	}
1311
-
1312
-	/**
1313
-	 * Returns the root folder of ownCloud's data directory
1314
-	 *
1315
-	 * @return \OCP\Files\IRootFolder
1316
-	 */
1317
-	public function getRootFolder() {
1318
-		return $this->query('LazyRootFolder');
1319
-	}
1320
-
1321
-	/**
1322
-	 * Returns the root folder of ownCloud's data directory
1323
-	 * This is the lazy variant so this gets only initialized once it
1324
-	 * is actually used.
1325
-	 *
1326
-	 * @return \OCP\Files\IRootFolder
1327
-	 */
1328
-	public function getLazyRootFolder() {
1329
-		return $this->query('LazyRootFolder');
1330
-	}
1331
-
1332
-	/**
1333
-	 * Returns a view to ownCloud's files folder
1334
-	 *
1335
-	 * @param string $userId user ID
1336
-	 * @return \OCP\Files\Folder|null
1337
-	 */
1338
-	public function getUserFolder($userId = null) {
1339
-		if ($userId === null) {
1340
-			$user = $this->getUserSession()->getUser();
1341
-			if (!$user) {
1342
-				return null;
1343
-			}
1344
-			$userId = $user->getUID();
1345
-		}
1346
-		$root = $this->getRootFolder();
1347
-		return $root->getUserFolder($userId);
1348
-	}
1349
-
1350
-	/**
1351
-	 * Returns an app-specific view in ownClouds data directory
1352
-	 *
1353
-	 * @return \OCP\Files\Folder
1354
-	 * @deprecated since 9.2.0 use IAppData
1355
-	 */
1356
-	public function getAppFolder() {
1357
-		$dir = '/' . \OC_App::getCurrentApp();
1358
-		$root = $this->getRootFolder();
1359
-		if (!$root->nodeExists($dir)) {
1360
-			$folder = $root->newFolder($dir);
1361
-		} else {
1362
-			$folder = $root->get($dir);
1363
-		}
1364
-		return $folder;
1365
-	}
1366
-
1367
-	/**
1368
-	 * @return \OC\User\Manager
1369
-	 */
1370
-	public function getUserManager() {
1371
-		return $this->query('UserManager');
1372
-	}
1373
-
1374
-	/**
1375
-	 * @return \OC\Group\Manager
1376
-	 */
1377
-	public function getGroupManager() {
1378
-		return $this->query('GroupManager');
1379
-	}
1380
-
1381
-	/**
1382
-	 * @return \OC\User\Session
1383
-	 */
1384
-	public function getUserSession() {
1385
-		return $this->query('UserSession');
1386
-	}
1387
-
1388
-	/**
1389
-	 * @return \OCP\ISession
1390
-	 */
1391
-	public function getSession() {
1392
-		return $this->query('UserSession')->getSession();
1393
-	}
1394
-
1395
-	/**
1396
-	 * @param \OCP\ISession $session
1397
-	 */
1398
-	public function setSession(\OCP\ISession $session) {
1399
-		$this->query(SessionStorage::class)->setSession($session);
1400
-		$this->query('UserSession')->setSession($session);
1401
-		$this->query(Store::class)->setSession($session);
1402
-	}
1403
-
1404
-	/**
1405
-	 * @return \OC\Authentication\TwoFactorAuth\Manager
1406
-	 */
1407
-	public function getTwoFactorAuthManager() {
1408
-		return $this->query('\OC\Authentication\TwoFactorAuth\Manager');
1409
-	}
1410
-
1411
-	/**
1412
-	 * @return \OC\NavigationManager
1413
-	 */
1414
-	public function getNavigationManager() {
1415
-		return $this->query('NavigationManager');
1416
-	}
1417
-
1418
-	/**
1419
-	 * @return \OCP\IConfig
1420
-	 */
1421
-	public function getConfig() {
1422
-		return $this->query('AllConfig');
1423
-	}
1424
-
1425
-	/**
1426
-	 * @return \OC\SystemConfig
1427
-	 */
1428
-	public function getSystemConfig() {
1429
-		return $this->query('SystemConfig');
1430
-	}
1431
-
1432
-	/**
1433
-	 * Returns the app config manager
1434
-	 *
1435
-	 * @return \OCP\IAppConfig
1436
-	 */
1437
-	public function getAppConfig() {
1438
-		return $this->query('AppConfig');
1439
-	}
1440
-
1441
-	/**
1442
-	 * @return \OCP\L10N\IFactory
1443
-	 */
1444
-	public function getL10NFactory() {
1445
-		return $this->query('L10NFactory');
1446
-	}
1447
-
1448
-	/**
1449
-	 * get an L10N instance
1450
-	 *
1451
-	 * @param string $app appid
1452
-	 * @param string $lang
1453
-	 * @return IL10N
1454
-	 */
1455
-	public function getL10N($app, $lang = null) {
1456
-		return $this->getL10NFactory()->get($app, $lang);
1457
-	}
1458
-
1459
-	/**
1460
-	 * @return \OCP\IURLGenerator
1461
-	 */
1462
-	public function getURLGenerator() {
1463
-		return $this->query('URLGenerator');
1464
-	}
1465
-
1466
-	/**
1467
-	 * @return AppFetcher
1468
-	 */
1469
-	public function getAppFetcher() {
1470
-		return $this->query(AppFetcher::class);
1471
-	}
1472
-
1473
-	/**
1474
-	 * Returns an ICache instance. Since 8.1.0 it returns a fake cache. Use
1475
-	 * getMemCacheFactory() instead.
1476
-	 *
1477
-	 * @return \OCP\ICache
1478
-	 * @deprecated 8.1.0 use getMemCacheFactory to obtain a proper cache
1479
-	 */
1480
-	public function getCache() {
1481
-		return $this->query('UserCache');
1482
-	}
1483
-
1484
-	/**
1485
-	 * Returns an \OCP\CacheFactory instance
1486
-	 *
1487
-	 * @return \OCP\ICacheFactory
1488
-	 */
1489
-	public function getMemCacheFactory() {
1490
-		return $this->query('MemCacheFactory');
1491
-	}
1492
-
1493
-	/**
1494
-	 * Returns an \OC\RedisFactory instance
1495
-	 *
1496
-	 * @return \OC\RedisFactory
1497
-	 */
1498
-	public function getGetRedisFactory() {
1499
-		return $this->query('RedisFactory');
1500
-	}
1501
-
1502
-
1503
-	/**
1504
-	 * Returns the current session
1505
-	 *
1506
-	 * @return \OCP\IDBConnection
1507
-	 */
1508
-	public function getDatabaseConnection() {
1509
-		return $this->query('DatabaseConnection');
1510
-	}
1511
-
1512
-	/**
1513
-	 * Returns the activity manager
1514
-	 *
1515
-	 * @return \OCP\Activity\IManager
1516
-	 */
1517
-	public function getActivityManager() {
1518
-		return $this->query('ActivityManager');
1519
-	}
1520
-
1521
-	/**
1522
-	 * Returns an job list for controlling background jobs
1523
-	 *
1524
-	 * @return \OCP\BackgroundJob\IJobList
1525
-	 */
1526
-	public function getJobList() {
1527
-		return $this->query('JobList');
1528
-	}
1529
-
1530
-	/**
1531
-	 * Returns a logger instance
1532
-	 *
1533
-	 * @return \OCP\ILogger
1534
-	 */
1535
-	public function getLogger() {
1536
-		return $this->query('Logger');
1537
-	}
1538
-
1539
-	/**
1540
-	 * @return ILogFactory
1541
-	 * @throws \OCP\AppFramework\QueryException
1542
-	 */
1543
-	public function getLogFactory() {
1544
-		return $this->query(ILogFactory::class);
1545
-	}
1546
-
1547
-	/**
1548
-	 * Returns a router for generating and matching urls
1549
-	 *
1550
-	 * @return \OCP\Route\IRouter
1551
-	 */
1552
-	public function getRouter() {
1553
-		return $this->query('Router');
1554
-	}
1555
-
1556
-	/**
1557
-	 * Returns a search instance
1558
-	 *
1559
-	 * @return \OCP\ISearch
1560
-	 */
1561
-	public function getSearch() {
1562
-		return $this->query('Search');
1563
-	}
1564
-
1565
-	/**
1566
-	 * Returns a SecureRandom instance
1567
-	 *
1568
-	 * @return \OCP\Security\ISecureRandom
1569
-	 */
1570
-	public function getSecureRandom() {
1571
-		return $this->query('SecureRandom');
1572
-	}
1573
-
1574
-	/**
1575
-	 * Returns a Crypto instance
1576
-	 *
1577
-	 * @return \OCP\Security\ICrypto
1578
-	 */
1579
-	public function getCrypto() {
1580
-		return $this->query('Crypto');
1581
-	}
1582
-
1583
-	/**
1584
-	 * Returns a Hasher instance
1585
-	 *
1586
-	 * @return \OCP\Security\IHasher
1587
-	 */
1588
-	public function getHasher() {
1589
-		return $this->query('Hasher');
1590
-	}
1591
-
1592
-	/**
1593
-	 * Returns a CredentialsManager instance
1594
-	 *
1595
-	 * @return \OCP\Security\ICredentialsManager
1596
-	 */
1597
-	public function getCredentialsManager() {
1598
-		return $this->query('CredentialsManager');
1599
-	}
1600
-
1601
-	/**
1602
-	 * Get the certificate manager for the user
1603
-	 *
1604
-	 * @param string $userId (optional) if not specified the current loggedin user is used, use null to get the system certificate manager
1605
-	 * @return \OCP\ICertificateManager | null if $uid is null and no user is logged in
1606
-	 */
1607
-	public function getCertificateManager($userId = '') {
1608
-		if ($userId === '') {
1609
-			$userSession = $this->getUserSession();
1610
-			$user = $userSession->getUser();
1611
-			if (is_null($user)) {
1612
-				return null;
1613
-			}
1614
-			$userId = $user->getUID();
1615
-		}
1616
-		return new CertificateManager(
1617
-			$userId,
1618
-			new View(),
1619
-			$this->getConfig(),
1620
-			$this->getLogger(),
1621
-			$this->getSecureRandom()
1622
-		);
1623
-	}
1624
-
1625
-	/**
1626
-	 * Returns an instance of the HTTP client service
1627
-	 *
1628
-	 * @return \OCP\Http\Client\IClientService
1629
-	 */
1630
-	public function getHTTPClientService() {
1631
-		return $this->query('HttpClientService');
1632
-	}
1633
-
1634
-	/**
1635
-	 * Create a new event source
1636
-	 *
1637
-	 * @return \OCP\IEventSource
1638
-	 */
1639
-	public function createEventSource() {
1640
-		return new \OC_EventSource();
1641
-	}
1642
-
1643
-	/**
1644
-	 * Get the active event logger
1645
-	 *
1646
-	 * The returned logger only logs data when debug mode is enabled
1647
-	 *
1648
-	 * @return \OCP\Diagnostics\IEventLogger
1649
-	 */
1650
-	public function getEventLogger() {
1651
-		return $this->query('EventLogger');
1652
-	}
1653
-
1654
-	/**
1655
-	 * Get the active query logger
1656
-	 *
1657
-	 * The returned logger only logs data when debug mode is enabled
1658
-	 *
1659
-	 * @return \OCP\Diagnostics\IQueryLogger
1660
-	 */
1661
-	public function getQueryLogger() {
1662
-		return $this->query('QueryLogger');
1663
-	}
1664
-
1665
-	/**
1666
-	 * Get the manager for temporary files and folders
1667
-	 *
1668
-	 * @return \OCP\ITempManager
1669
-	 */
1670
-	public function getTempManager() {
1671
-		return $this->query('TempManager');
1672
-	}
1673
-
1674
-	/**
1675
-	 * Get the app manager
1676
-	 *
1677
-	 * @return \OCP\App\IAppManager
1678
-	 */
1679
-	public function getAppManager() {
1680
-		return $this->query('AppManager');
1681
-	}
1682
-
1683
-	/**
1684
-	 * Creates a new mailer
1685
-	 *
1686
-	 * @return \OCP\Mail\IMailer
1687
-	 */
1688
-	public function getMailer() {
1689
-		return $this->query('Mailer');
1690
-	}
1691
-
1692
-	/**
1693
-	 * Get the webroot
1694
-	 *
1695
-	 * @return string
1696
-	 */
1697
-	public function getWebRoot() {
1698
-		return $this->webRoot;
1699
-	}
1700
-
1701
-	/**
1702
-	 * @return \OC\OCSClient
1703
-	 */
1704
-	public function getOcsClient() {
1705
-		return $this->query('OcsClient');
1706
-	}
1707
-
1708
-	/**
1709
-	 * @return \OCP\IDateTimeZone
1710
-	 */
1711
-	public function getDateTimeZone() {
1712
-		return $this->query('DateTimeZone');
1713
-	}
1714
-
1715
-	/**
1716
-	 * @return \OCP\IDateTimeFormatter
1717
-	 */
1718
-	public function getDateTimeFormatter() {
1719
-		return $this->query('DateTimeFormatter');
1720
-	}
1721
-
1722
-	/**
1723
-	 * @return \OCP\Files\Config\IMountProviderCollection
1724
-	 */
1725
-	public function getMountProviderCollection() {
1726
-		return $this->query('MountConfigManager');
1727
-	}
1728
-
1729
-	/**
1730
-	 * Get the IniWrapper
1731
-	 *
1732
-	 * @return IniGetWrapper
1733
-	 */
1734
-	public function getIniWrapper() {
1735
-		return $this->query('IniWrapper');
1736
-	}
1737
-
1738
-	/**
1739
-	 * @return \OCP\Command\IBus
1740
-	 */
1741
-	public function getCommandBus() {
1742
-		return $this->query('AsyncCommandBus');
1743
-	}
1744
-
1745
-	/**
1746
-	 * Get the trusted domain helper
1747
-	 *
1748
-	 * @return TrustedDomainHelper
1749
-	 */
1750
-	public function getTrustedDomainHelper() {
1751
-		return $this->query('TrustedDomainHelper');
1752
-	}
1753
-
1754
-	/**
1755
-	 * Get the locking provider
1756
-	 *
1757
-	 * @return \OCP\Lock\ILockingProvider
1758
-	 * @since 8.1.0
1759
-	 */
1760
-	public function getLockingProvider() {
1761
-		return $this->query('LockingProvider');
1762
-	}
1763
-
1764
-	/**
1765
-	 * @return \OCP\Files\Mount\IMountManager
1766
-	 **/
1767
-	function getMountManager() {
1768
-		return $this->query('MountManager');
1769
-	}
1770
-
1771
-	/** @return \OCP\Files\Config\IUserMountCache */
1772
-	function getUserMountCache() {
1773
-		return $this->query('UserMountCache');
1774
-	}
1775
-
1776
-	/**
1777
-	 * Get the MimeTypeDetector
1778
-	 *
1779
-	 * @return \OCP\Files\IMimeTypeDetector
1780
-	 */
1781
-	public function getMimeTypeDetector() {
1782
-		return $this->query('MimeTypeDetector');
1783
-	}
1784
-
1785
-	/**
1786
-	 * Get the MimeTypeLoader
1787
-	 *
1788
-	 * @return \OCP\Files\IMimeTypeLoader
1789
-	 */
1790
-	public function getMimeTypeLoader() {
1791
-		return $this->query('MimeTypeLoader');
1792
-	}
1793
-
1794
-	/**
1795
-	 * Get the manager of all the capabilities
1796
-	 *
1797
-	 * @return \OC\CapabilitiesManager
1798
-	 */
1799
-	public function getCapabilitiesManager() {
1800
-		return $this->query('CapabilitiesManager');
1801
-	}
1802
-
1803
-	/**
1804
-	 * Get the EventDispatcher
1805
-	 *
1806
-	 * @return EventDispatcherInterface
1807
-	 * @since 8.2.0
1808
-	 */
1809
-	public function getEventDispatcher() {
1810
-		return $this->query('EventDispatcher');
1811
-	}
1812
-
1813
-	/**
1814
-	 * Get the Notification Manager
1815
-	 *
1816
-	 * @return \OCP\Notification\IManager
1817
-	 * @since 8.2.0
1818
-	 */
1819
-	public function getNotificationManager() {
1820
-		return $this->query('NotificationManager');
1821
-	}
1822
-
1823
-	/**
1824
-	 * @return \OCP\Comments\ICommentsManager
1825
-	 */
1826
-	public function getCommentsManager() {
1827
-		return $this->query('CommentsManager');
1828
-	}
1829
-
1830
-	/**
1831
-	 * @return \OCA\Theming\ThemingDefaults
1832
-	 */
1833
-	public function getThemingDefaults() {
1834
-		return $this->query('ThemingDefaults');
1835
-	}
1836
-
1837
-	/**
1838
-	 * @return \OC\IntegrityCheck\Checker
1839
-	 */
1840
-	public function getIntegrityCodeChecker() {
1841
-		return $this->query('IntegrityCodeChecker');
1842
-	}
1843
-
1844
-	/**
1845
-	 * @return \OC\Session\CryptoWrapper
1846
-	 */
1847
-	public function getSessionCryptoWrapper() {
1848
-		return $this->query('CryptoWrapper');
1849
-	}
1850
-
1851
-	/**
1852
-	 * @return CsrfTokenManager
1853
-	 */
1854
-	public function getCsrfTokenManager() {
1855
-		return $this->query('CsrfTokenManager');
1856
-	}
1857
-
1858
-	/**
1859
-	 * @return Throttler
1860
-	 */
1861
-	public function getBruteForceThrottler() {
1862
-		return $this->query('Throttler');
1863
-	}
1864
-
1865
-	/**
1866
-	 * @return IContentSecurityPolicyManager
1867
-	 */
1868
-	public function getContentSecurityPolicyManager() {
1869
-		return $this->query('ContentSecurityPolicyManager');
1870
-	}
1871
-
1872
-	/**
1873
-	 * @return ContentSecurityPolicyNonceManager
1874
-	 */
1875
-	public function getContentSecurityPolicyNonceManager() {
1876
-		return $this->query('ContentSecurityPolicyNonceManager');
1877
-	}
1878
-
1879
-	/**
1880
-	 * Not a public API as of 8.2, wait for 9.0
1881
-	 *
1882
-	 * @return \OCA\Files_External\Service\BackendService
1883
-	 */
1884
-	public function getStoragesBackendService() {
1885
-		return $this->query('OCA\\Files_External\\Service\\BackendService');
1886
-	}
1887
-
1888
-	/**
1889
-	 * Not a public API as of 8.2, wait for 9.0
1890
-	 *
1891
-	 * @return \OCA\Files_External\Service\GlobalStoragesService
1892
-	 */
1893
-	public function getGlobalStoragesService() {
1894
-		return $this->query('OCA\\Files_External\\Service\\GlobalStoragesService');
1895
-	}
1896
-
1897
-	/**
1898
-	 * Not a public API as of 8.2, wait for 9.0
1899
-	 *
1900
-	 * @return \OCA\Files_External\Service\UserGlobalStoragesService
1901
-	 */
1902
-	public function getUserGlobalStoragesService() {
1903
-		return $this->query('OCA\\Files_External\\Service\\UserGlobalStoragesService');
1904
-	}
1905
-
1906
-	/**
1907
-	 * Not a public API as of 8.2, wait for 9.0
1908
-	 *
1909
-	 * @return \OCA\Files_External\Service\UserStoragesService
1910
-	 */
1911
-	public function getUserStoragesService() {
1912
-		return $this->query('OCA\\Files_External\\Service\\UserStoragesService');
1913
-	}
1914
-
1915
-	/**
1916
-	 * @return \OCP\Share\IManager
1917
-	 */
1918
-	public function getShareManager() {
1919
-		return $this->query('ShareManager');
1920
-	}
1921
-
1922
-	/**
1923
-	 * @return \OCP\Collaboration\Collaborators\ISearch
1924
-	 */
1925
-	public function getCollaboratorSearch() {
1926
-		return $this->query('CollaboratorSearch');
1927
-	}
1928
-
1929
-	/**
1930
-	 * @return \OCP\Collaboration\AutoComplete\IManager
1931
-	 */
1932
-	public function getAutoCompleteManager(){
1933
-		return $this->query(IManager::class);
1934
-	}
1935
-
1936
-	/**
1937
-	 * Returns the LDAP Provider
1938
-	 *
1939
-	 * @return \OCP\LDAP\ILDAPProvider
1940
-	 */
1941
-	public function getLDAPProvider() {
1942
-		return $this->query('LDAPProvider');
1943
-	}
1944
-
1945
-	/**
1946
-	 * @return \OCP\Settings\IManager
1947
-	 */
1948
-	public function getSettingsManager() {
1949
-		return $this->query('SettingsManager');
1950
-	}
1951
-
1952
-	/**
1953
-	 * @return \OCP\Files\IAppData
1954
-	 */
1955
-	public function getAppDataDir($app) {
1956
-		/** @var \OC\Files\AppData\Factory $factory */
1957
-		$factory = $this->query(\OC\Files\AppData\Factory::class);
1958
-		return $factory->get($app);
1959
-	}
1960
-
1961
-	/**
1962
-	 * @return \OCP\Lockdown\ILockdownManager
1963
-	 */
1964
-	public function getLockdownManager() {
1965
-		return $this->query('LockdownManager');
1966
-	}
1967
-
1968
-	/**
1969
-	 * @return \OCP\Federation\ICloudIdManager
1970
-	 */
1971
-	public function getCloudIdManager() {
1972
-		return $this->query(ICloudIdManager::class);
1973
-	}
1974
-
1975
-	/**
1976
-	 * @return \OCP\Remote\Api\IApiFactory
1977
-	 */
1978
-	public function getRemoteApiFactory() {
1979
-		return $this->query(IApiFactory::class);
1980
-	}
1981
-
1982
-	/**
1983
-	 * @return \OCP\Remote\IInstanceFactory
1984
-	 */
1985
-	public function getRemoteInstanceFactory() {
1986
-		return $this->query(IInstanceFactory::class);
1987
-	}
943
+            $prefixes = \OC::$composerAutoloader->getPrefixesPsr4();
944
+            if (isset($prefixes['OCA\\Theming\\'])) {
945
+                $classExists = true;
946
+            } else {
947
+                $classExists = false;
948
+            }
949
+
950
+            if ($classExists && $c->getConfig()->getSystemValue('installed', false) && $c->getAppManager()->isInstalled('theming') && $c->getTrustedDomainHelper()->isTrustedDomain($c->getRequest()->getInsecureServerHost())) {
951
+                return new ThemingDefaults(
952
+                    $c->getConfig(),
953
+                    $c->getL10N('theming'),
954
+                    $c->getURLGenerator(),
955
+                    $c->getMemCacheFactory(),
956
+                    new Util($c->getConfig(), $this->getAppManager(), $c->getAppDataDir('theming')),
957
+                    new ImageManager($c->getConfig(), $c->getAppDataDir('theming'), $c->getURLGenerator()),
958
+                    $c->getAppManager()
959
+                );
960
+            }
961
+            return new \OC_Defaults();
962
+        });
963
+        $this->registerService(SCSSCacher::class, function (Server $c) {
964
+            /** @var Factory $cacheFactory */
965
+            $cacheFactory = $c->query(Factory::class);
966
+            return new SCSSCacher(
967
+                $c->getLogger(),
968
+                $c->query(\OC\Files\AppData\Factory::class),
969
+                $c->getURLGenerator(),
970
+                $c->getConfig(),
971
+                $c->getThemingDefaults(),
972
+                \OC::$SERVERROOT,
973
+                $this->getMemCacheFactory()
974
+            );
975
+        });
976
+        $this->registerService(JSCombiner::class, function (Server $c) {
977
+            /** @var Factory $cacheFactory */
978
+            $cacheFactory = $c->query(Factory::class);
979
+            return new JSCombiner(
980
+                $c->getAppDataDir('js'),
981
+                $c->getURLGenerator(),
982
+                $this->getMemCacheFactory(),
983
+                $c->getSystemConfig(),
984
+                $c->getLogger()
985
+            );
986
+        });
987
+        $this->registerService(EventDispatcher::class, function () {
988
+            return new EventDispatcher();
989
+        });
990
+        $this->registerAlias('EventDispatcher', EventDispatcher::class);
991
+        $this->registerAlias(EventDispatcherInterface::class, EventDispatcher::class);
992
+
993
+        $this->registerService('CryptoWrapper', function (Server $c) {
994
+            // FIXME: Instantiiated here due to cyclic dependency
995
+            $request = new Request(
996
+                [
997
+                    'get' => $_GET,
998
+                    'post' => $_POST,
999
+                    'files' => $_FILES,
1000
+                    'server' => $_SERVER,
1001
+                    'env' => $_ENV,
1002
+                    'cookies' => $_COOKIE,
1003
+                    'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
1004
+                        ? $_SERVER['REQUEST_METHOD']
1005
+                        : null,
1006
+                ],
1007
+                $c->getSecureRandom(),
1008
+                $c->getConfig()
1009
+            );
1010
+
1011
+            return new CryptoWrapper(
1012
+                $c->getConfig(),
1013
+                $c->getCrypto(),
1014
+                $c->getSecureRandom(),
1015
+                $request
1016
+            );
1017
+        });
1018
+        $this->registerService('CsrfTokenManager', function (Server $c) {
1019
+            $tokenGenerator = new CsrfTokenGenerator($c->getSecureRandom());
1020
+
1021
+            return new CsrfTokenManager(
1022
+                $tokenGenerator,
1023
+                $c->query(SessionStorage::class)
1024
+            );
1025
+        });
1026
+        $this->registerService(SessionStorage::class, function (Server $c) {
1027
+            return new SessionStorage($c->getSession());
1028
+        });
1029
+        $this->registerService(\OCP\Security\IContentSecurityPolicyManager::class, function (Server $c) {
1030
+            return new ContentSecurityPolicyManager();
1031
+        });
1032
+        $this->registerAlias('ContentSecurityPolicyManager', \OCP\Security\IContentSecurityPolicyManager::class);
1033
+
1034
+        $this->registerService('ContentSecurityPolicyNonceManager', function (Server $c) {
1035
+            return new ContentSecurityPolicyNonceManager(
1036
+                $c->getCsrfTokenManager(),
1037
+                $c->getRequest()
1038
+            );
1039
+        });
1040
+
1041
+        $this->registerService(\OCP\Share\IManager::class, function (Server $c) {
1042
+            $config = $c->getConfig();
1043
+            $factoryClass = $config->getSystemValue('sharing.managerFactory', ProviderFactory::class);
1044
+            /** @var \OCP\Share\IProviderFactory $factory */
1045
+            $factory = new $factoryClass($this);
1046
+
1047
+            $manager = new \OC\Share20\Manager(
1048
+                $c->getLogger(),
1049
+                $c->getConfig(),
1050
+                $c->getSecureRandom(),
1051
+                $c->getHasher(),
1052
+                $c->getMountManager(),
1053
+                $c->getGroupManager(),
1054
+                $c->getL10N('lib'),
1055
+                $c->getL10NFactory(),
1056
+                $factory,
1057
+                $c->getUserManager(),
1058
+                $c->getLazyRootFolder(),
1059
+                $c->getEventDispatcher(),
1060
+                $c->getMailer(),
1061
+                $c->getURLGenerator(),
1062
+                $c->getThemingDefaults()
1063
+            );
1064
+
1065
+            return $manager;
1066
+        });
1067
+        $this->registerAlias('ShareManager', \OCP\Share\IManager::class);
1068
+
1069
+        $this->registerService(\OCP\Collaboration\Collaborators\ISearch::class, function(Server $c) {
1070
+            $instance = new Collaboration\Collaborators\Search($c);
1071
+
1072
+            // register default plugins
1073
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_USER', 'class' => UserPlugin::class]);
1074
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_GROUP', 'class' => GroupPlugin::class]);
1075
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_EMAIL', 'class' => MailPlugin::class]);
1076
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_REMOTE', 'class' => RemotePlugin::class]);
1077
+
1078
+            return $instance;
1079
+        });
1080
+        $this->registerAlias('CollaboratorSearch', \OCP\Collaboration\Collaborators\ISearch::class);
1081
+
1082
+        $this->registerAlias(\OCP\Collaboration\AutoComplete\IManager::class, \OC\Collaboration\AutoComplete\Manager::class);
1083
+
1084
+        $this->registerService('SettingsManager', function (Server $c) {
1085
+            $manager = new \OC\Settings\Manager(
1086
+                $c->getLogger(),
1087
+                $c->getDatabaseConnection(),
1088
+                $c->getL10N('lib'),
1089
+                $c->getConfig(),
1090
+                $c->getEncryptionManager(),
1091
+                $c->getUserManager(),
1092
+                $c->getLockingProvider(),
1093
+                $c->getRequest(),
1094
+                $c->getURLGenerator(),
1095
+                $c->query(AccountManager::class),
1096
+                $c->getGroupManager(),
1097
+                $c->getL10NFactory(),
1098
+                $c->getAppManager()
1099
+            );
1100
+            return $manager;
1101
+        });
1102
+        $this->registerService(\OC\Files\AppData\Factory::class, function (Server $c) {
1103
+            return new \OC\Files\AppData\Factory(
1104
+                $c->getRootFolder(),
1105
+                $c->getSystemConfig()
1106
+            );
1107
+        });
1108
+
1109
+        $this->registerService('LockdownManager', function (Server $c) {
1110
+            return new LockdownManager(function () use ($c) {
1111
+                return $c->getSession();
1112
+            });
1113
+        });
1114
+
1115
+        $this->registerService(\OCP\OCS\IDiscoveryService::class, function (Server $c) {
1116
+            return new DiscoveryService($c->getMemCacheFactory(), $c->getHTTPClientService());
1117
+        });
1118
+
1119
+        $this->registerService(ICloudIdManager::class, function (Server $c) {
1120
+            return new CloudIdManager();
1121
+        });
1122
+
1123
+        $this->registerAlias(\OCP\AppFramework\Utility\IControllerMethodReflector::class, \OC\AppFramework\Utility\ControllerMethodReflector::class);
1124
+        $this->registerAlias('ControllerMethodReflector', \OCP\AppFramework\Utility\IControllerMethodReflector::class);
1125
+
1126
+        $this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
1127
+        $this->registerAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
1128
+
1129
+        $this->registerService(Defaults::class, function (Server $c) {
1130
+            return new Defaults(
1131
+                $c->getThemingDefaults()
1132
+            );
1133
+        });
1134
+        $this->registerAlias('Defaults', \OCP\Defaults::class);
1135
+
1136
+        $this->registerService(\OCP\ISession::class, function (SimpleContainer $c) {
1137
+            return $c->query(\OCP\IUserSession::class)->getSession();
1138
+        });
1139
+
1140
+        $this->registerService(IShareHelper::class, function (Server $c) {
1141
+            return new ShareHelper(
1142
+                $c->query(\OCP\Share\IManager::class)
1143
+            );
1144
+        });
1145
+
1146
+        $this->registerService(Installer::class, function(Server $c) {
1147
+            return new Installer(
1148
+                $c->getAppFetcher(),
1149
+                $c->getHTTPClientService(),
1150
+                $c->getTempManager(),
1151
+                $c->getLogger(),
1152
+                $c->getConfig()
1153
+            );
1154
+        });
1155
+
1156
+        $this->registerService(IApiFactory::class, function(Server $c) {
1157
+            return new ApiFactory($c->getHTTPClientService());
1158
+        });
1159
+
1160
+        $this->registerService(IInstanceFactory::class, function(Server $c) {
1161
+            $memcacheFactory = $c->getMemCacheFactory();
1162
+            return new InstanceFactory($memcacheFactory->createLocal('remoteinstance.'), $c->getHTTPClientService());
1163
+        });
1164
+
1165
+        $this->registerService(IContactsStore::class, function(Server $c) {
1166
+            return new ContactsStore(
1167
+                $c->getContactsManager(),
1168
+                $c->getConfig(),
1169
+                $c->getUserManager(),
1170
+                $c->getGroupManager()
1171
+            );
1172
+        });
1173
+        $this->registerAlias(IContactsStore::class, ContactsStore::class);
1174
+
1175
+        $this->connectDispatcher();
1176
+    }
1177
+
1178
+    /**
1179
+     * @return \OCP\Calendar\IManager
1180
+     */
1181
+    public function getCalendarManager() {
1182
+        return $this->query('CalendarManager');
1183
+    }
1184
+
1185
+    private function connectDispatcher() {
1186
+        $dispatcher = $this->getEventDispatcher();
1187
+
1188
+        // Delete avatar on user deletion
1189
+        $dispatcher->addListener('OCP\IUser::preDelete', function(GenericEvent $e) {
1190
+            $logger = $this->getLogger();
1191
+            $manager = $this->getAvatarManager();
1192
+            /** @var IUser $user */
1193
+            $user = $e->getSubject();
1194
+
1195
+            try {
1196
+                $avatar = $manager->getAvatar($user->getUID());
1197
+                $avatar->remove();
1198
+            } catch (NotFoundException $e) {
1199
+                // no avatar to remove
1200
+            } catch (\Exception $e) {
1201
+                // Ignore exceptions
1202
+                $logger->info('Could not cleanup avatar of ' . $user->getUID());
1203
+            }
1204
+        });
1205
+
1206
+        $dispatcher->addListener('OCP\IUser::changeUser', function (GenericEvent $e) {
1207
+            $manager = $this->getAvatarManager();
1208
+            /** @var IUser $user */
1209
+            $user = $e->getSubject();
1210
+            $feature = $e->getArgument('feature');
1211
+            $oldValue = $e->getArgument('oldValue');
1212
+            $value = $e->getArgument('value');
1213
+
1214
+            try {
1215
+                $avatar = $manager->getAvatar($user->getUID());
1216
+                $avatar->userChanged($feature, $oldValue, $value);
1217
+            } catch (NotFoundException $e) {
1218
+                // no avatar to remove
1219
+            }
1220
+        });
1221
+    }
1222
+
1223
+    /**
1224
+     * @return \OCP\Contacts\IManager
1225
+     */
1226
+    public function getContactsManager() {
1227
+        return $this->query('ContactsManager');
1228
+    }
1229
+
1230
+    /**
1231
+     * @return \OC\Encryption\Manager
1232
+     */
1233
+    public function getEncryptionManager() {
1234
+        return $this->query('EncryptionManager');
1235
+    }
1236
+
1237
+    /**
1238
+     * @return \OC\Encryption\File
1239
+     */
1240
+    public function getEncryptionFilesHelper() {
1241
+        return $this->query('EncryptionFileHelper');
1242
+    }
1243
+
1244
+    /**
1245
+     * @return \OCP\Encryption\Keys\IStorage
1246
+     */
1247
+    public function getEncryptionKeyStorage() {
1248
+        return $this->query('EncryptionKeyStorage');
1249
+    }
1250
+
1251
+    /**
1252
+     * The current request object holding all information about the request
1253
+     * currently being processed is returned from this method.
1254
+     * In case the current execution was not initiated by a web request null is returned
1255
+     *
1256
+     * @return \OCP\IRequest
1257
+     */
1258
+    public function getRequest() {
1259
+        return $this->query('Request');
1260
+    }
1261
+
1262
+    /**
1263
+     * Returns the preview manager which can create preview images for a given file
1264
+     *
1265
+     * @return \OCP\IPreview
1266
+     */
1267
+    public function getPreviewManager() {
1268
+        return $this->query('PreviewManager');
1269
+    }
1270
+
1271
+    /**
1272
+     * Returns the tag manager which can get and set tags for different object types
1273
+     *
1274
+     * @see \OCP\ITagManager::load()
1275
+     * @return \OCP\ITagManager
1276
+     */
1277
+    public function getTagManager() {
1278
+        return $this->query('TagManager');
1279
+    }
1280
+
1281
+    /**
1282
+     * Returns the system-tag manager
1283
+     *
1284
+     * @return \OCP\SystemTag\ISystemTagManager
1285
+     *
1286
+     * @since 9.0.0
1287
+     */
1288
+    public function getSystemTagManager() {
1289
+        return $this->query('SystemTagManager');
1290
+    }
1291
+
1292
+    /**
1293
+     * Returns the system-tag object mapper
1294
+     *
1295
+     * @return \OCP\SystemTag\ISystemTagObjectMapper
1296
+     *
1297
+     * @since 9.0.0
1298
+     */
1299
+    public function getSystemTagObjectMapper() {
1300
+        return $this->query('SystemTagObjectMapper');
1301
+    }
1302
+
1303
+    /**
1304
+     * Returns the avatar manager, used for avatar functionality
1305
+     *
1306
+     * @return \OCP\IAvatarManager
1307
+     */
1308
+    public function getAvatarManager() {
1309
+        return $this->query('AvatarManager');
1310
+    }
1311
+
1312
+    /**
1313
+     * Returns the root folder of ownCloud's data directory
1314
+     *
1315
+     * @return \OCP\Files\IRootFolder
1316
+     */
1317
+    public function getRootFolder() {
1318
+        return $this->query('LazyRootFolder');
1319
+    }
1320
+
1321
+    /**
1322
+     * Returns the root folder of ownCloud's data directory
1323
+     * This is the lazy variant so this gets only initialized once it
1324
+     * is actually used.
1325
+     *
1326
+     * @return \OCP\Files\IRootFolder
1327
+     */
1328
+    public function getLazyRootFolder() {
1329
+        return $this->query('LazyRootFolder');
1330
+    }
1331
+
1332
+    /**
1333
+     * Returns a view to ownCloud's files folder
1334
+     *
1335
+     * @param string $userId user ID
1336
+     * @return \OCP\Files\Folder|null
1337
+     */
1338
+    public function getUserFolder($userId = null) {
1339
+        if ($userId === null) {
1340
+            $user = $this->getUserSession()->getUser();
1341
+            if (!$user) {
1342
+                return null;
1343
+            }
1344
+            $userId = $user->getUID();
1345
+        }
1346
+        $root = $this->getRootFolder();
1347
+        return $root->getUserFolder($userId);
1348
+    }
1349
+
1350
+    /**
1351
+     * Returns an app-specific view in ownClouds data directory
1352
+     *
1353
+     * @return \OCP\Files\Folder
1354
+     * @deprecated since 9.2.0 use IAppData
1355
+     */
1356
+    public function getAppFolder() {
1357
+        $dir = '/' . \OC_App::getCurrentApp();
1358
+        $root = $this->getRootFolder();
1359
+        if (!$root->nodeExists($dir)) {
1360
+            $folder = $root->newFolder($dir);
1361
+        } else {
1362
+            $folder = $root->get($dir);
1363
+        }
1364
+        return $folder;
1365
+    }
1366
+
1367
+    /**
1368
+     * @return \OC\User\Manager
1369
+     */
1370
+    public function getUserManager() {
1371
+        return $this->query('UserManager');
1372
+    }
1373
+
1374
+    /**
1375
+     * @return \OC\Group\Manager
1376
+     */
1377
+    public function getGroupManager() {
1378
+        return $this->query('GroupManager');
1379
+    }
1380
+
1381
+    /**
1382
+     * @return \OC\User\Session
1383
+     */
1384
+    public function getUserSession() {
1385
+        return $this->query('UserSession');
1386
+    }
1387
+
1388
+    /**
1389
+     * @return \OCP\ISession
1390
+     */
1391
+    public function getSession() {
1392
+        return $this->query('UserSession')->getSession();
1393
+    }
1394
+
1395
+    /**
1396
+     * @param \OCP\ISession $session
1397
+     */
1398
+    public function setSession(\OCP\ISession $session) {
1399
+        $this->query(SessionStorage::class)->setSession($session);
1400
+        $this->query('UserSession')->setSession($session);
1401
+        $this->query(Store::class)->setSession($session);
1402
+    }
1403
+
1404
+    /**
1405
+     * @return \OC\Authentication\TwoFactorAuth\Manager
1406
+     */
1407
+    public function getTwoFactorAuthManager() {
1408
+        return $this->query('\OC\Authentication\TwoFactorAuth\Manager');
1409
+    }
1410
+
1411
+    /**
1412
+     * @return \OC\NavigationManager
1413
+     */
1414
+    public function getNavigationManager() {
1415
+        return $this->query('NavigationManager');
1416
+    }
1417
+
1418
+    /**
1419
+     * @return \OCP\IConfig
1420
+     */
1421
+    public function getConfig() {
1422
+        return $this->query('AllConfig');
1423
+    }
1424
+
1425
+    /**
1426
+     * @return \OC\SystemConfig
1427
+     */
1428
+    public function getSystemConfig() {
1429
+        return $this->query('SystemConfig');
1430
+    }
1431
+
1432
+    /**
1433
+     * Returns the app config manager
1434
+     *
1435
+     * @return \OCP\IAppConfig
1436
+     */
1437
+    public function getAppConfig() {
1438
+        return $this->query('AppConfig');
1439
+    }
1440
+
1441
+    /**
1442
+     * @return \OCP\L10N\IFactory
1443
+     */
1444
+    public function getL10NFactory() {
1445
+        return $this->query('L10NFactory');
1446
+    }
1447
+
1448
+    /**
1449
+     * get an L10N instance
1450
+     *
1451
+     * @param string $app appid
1452
+     * @param string $lang
1453
+     * @return IL10N
1454
+     */
1455
+    public function getL10N($app, $lang = null) {
1456
+        return $this->getL10NFactory()->get($app, $lang);
1457
+    }
1458
+
1459
+    /**
1460
+     * @return \OCP\IURLGenerator
1461
+     */
1462
+    public function getURLGenerator() {
1463
+        return $this->query('URLGenerator');
1464
+    }
1465
+
1466
+    /**
1467
+     * @return AppFetcher
1468
+     */
1469
+    public function getAppFetcher() {
1470
+        return $this->query(AppFetcher::class);
1471
+    }
1472
+
1473
+    /**
1474
+     * Returns an ICache instance. Since 8.1.0 it returns a fake cache. Use
1475
+     * getMemCacheFactory() instead.
1476
+     *
1477
+     * @return \OCP\ICache
1478
+     * @deprecated 8.1.0 use getMemCacheFactory to obtain a proper cache
1479
+     */
1480
+    public function getCache() {
1481
+        return $this->query('UserCache');
1482
+    }
1483
+
1484
+    /**
1485
+     * Returns an \OCP\CacheFactory instance
1486
+     *
1487
+     * @return \OCP\ICacheFactory
1488
+     */
1489
+    public function getMemCacheFactory() {
1490
+        return $this->query('MemCacheFactory');
1491
+    }
1492
+
1493
+    /**
1494
+     * Returns an \OC\RedisFactory instance
1495
+     *
1496
+     * @return \OC\RedisFactory
1497
+     */
1498
+    public function getGetRedisFactory() {
1499
+        return $this->query('RedisFactory');
1500
+    }
1501
+
1502
+
1503
+    /**
1504
+     * Returns the current session
1505
+     *
1506
+     * @return \OCP\IDBConnection
1507
+     */
1508
+    public function getDatabaseConnection() {
1509
+        return $this->query('DatabaseConnection');
1510
+    }
1511
+
1512
+    /**
1513
+     * Returns the activity manager
1514
+     *
1515
+     * @return \OCP\Activity\IManager
1516
+     */
1517
+    public function getActivityManager() {
1518
+        return $this->query('ActivityManager');
1519
+    }
1520
+
1521
+    /**
1522
+     * Returns an job list for controlling background jobs
1523
+     *
1524
+     * @return \OCP\BackgroundJob\IJobList
1525
+     */
1526
+    public function getJobList() {
1527
+        return $this->query('JobList');
1528
+    }
1529
+
1530
+    /**
1531
+     * Returns a logger instance
1532
+     *
1533
+     * @return \OCP\ILogger
1534
+     */
1535
+    public function getLogger() {
1536
+        return $this->query('Logger');
1537
+    }
1538
+
1539
+    /**
1540
+     * @return ILogFactory
1541
+     * @throws \OCP\AppFramework\QueryException
1542
+     */
1543
+    public function getLogFactory() {
1544
+        return $this->query(ILogFactory::class);
1545
+    }
1546
+
1547
+    /**
1548
+     * Returns a router for generating and matching urls
1549
+     *
1550
+     * @return \OCP\Route\IRouter
1551
+     */
1552
+    public function getRouter() {
1553
+        return $this->query('Router');
1554
+    }
1555
+
1556
+    /**
1557
+     * Returns a search instance
1558
+     *
1559
+     * @return \OCP\ISearch
1560
+     */
1561
+    public function getSearch() {
1562
+        return $this->query('Search');
1563
+    }
1564
+
1565
+    /**
1566
+     * Returns a SecureRandom instance
1567
+     *
1568
+     * @return \OCP\Security\ISecureRandom
1569
+     */
1570
+    public function getSecureRandom() {
1571
+        return $this->query('SecureRandom');
1572
+    }
1573
+
1574
+    /**
1575
+     * Returns a Crypto instance
1576
+     *
1577
+     * @return \OCP\Security\ICrypto
1578
+     */
1579
+    public function getCrypto() {
1580
+        return $this->query('Crypto');
1581
+    }
1582
+
1583
+    /**
1584
+     * Returns a Hasher instance
1585
+     *
1586
+     * @return \OCP\Security\IHasher
1587
+     */
1588
+    public function getHasher() {
1589
+        return $this->query('Hasher');
1590
+    }
1591
+
1592
+    /**
1593
+     * Returns a CredentialsManager instance
1594
+     *
1595
+     * @return \OCP\Security\ICredentialsManager
1596
+     */
1597
+    public function getCredentialsManager() {
1598
+        return $this->query('CredentialsManager');
1599
+    }
1600
+
1601
+    /**
1602
+     * Get the certificate manager for the user
1603
+     *
1604
+     * @param string $userId (optional) if not specified the current loggedin user is used, use null to get the system certificate manager
1605
+     * @return \OCP\ICertificateManager | null if $uid is null and no user is logged in
1606
+     */
1607
+    public function getCertificateManager($userId = '') {
1608
+        if ($userId === '') {
1609
+            $userSession = $this->getUserSession();
1610
+            $user = $userSession->getUser();
1611
+            if (is_null($user)) {
1612
+                return null;
1613
+            }
1614
+            $userId = $user->getUID();
1615
+        }
1616
+        return new CertificateManager(
1617
+            $userId,
1618
+            new View(),
1619
+            $this->getConfig(),
1620
+            $this->getLogger(),
1621
+            $this->getSecureRandom()
1622
+        );
1623
+    }
1624
+
1625
+    /**
1626
+     * Returns an instance of the HTTP client service
1627
+     *
1628
+     * @return \OCP\Http\Client\IClientService
1629
+     */
1630
+    public function getHTTPClientService() {
1631
+        return $this->query('HttpClientService');
1632
+    }
1633
+
1634
+    /**
1635
+     * Create a new event source
1636
+     *
1637
+     * @return \OCP\IEventSource
1638
+     */
1639
+    public function createEventSource() {
1640
+        return new \OC_EventSource();
1641
+    }
1642
+
1643
+    /**
1644
+     * Get the active event logger
1645
+     *
1646
+     * The returned logger only logs data when debug mode is enabled
1647
+     *
1648
+     * @return \OCP\Diagnostics\IEventLogger
1649
+     */
1650
+    public function getEventLogger() {
1651
+        return $this->query('EventLogger');
1652
+    }
1653
+
1654
+    /**
1655
+     * Get the active query logger
1656
+     *
1657
+     * The returned logger only logs data when debug mode is enabled
1658
+     *
1659
+     * @return \OCP\Diagnostics\IQueryLogger
1660
+     */
1661
+    public function getQueryLogger() {
1662
+        return $this->query('QueryLogger');
1663
+    }
1664
+
1665
+    /**
1666
+     * Get the manager for temporary files and folders
1667
+     *
1668
+     * @return \OCP\ITempManager
1669
+     */
1670
+    public function getTempManager() {
1671
+        return $this->query('TempManager');
1672
+    }
1673
+
1674
+    /**
1675
+     * Get the app manager
1676
+     *
1677
+     * @return \OCP\App\IAppManager
1678
+     */
1679
+    public function getAppManager() {
1680
+        return $this->query('AppManager');
1681
+    }
1682
+
1683
+    /**
1684
+     * Creates a new mailer
1685
+     *
1686
+     * @return \OCP\Mail\IMailer
1687
+     */
1688
+    public function getMailer() {
1689
+        return $this->query('Mailer');
1690
+    }
1691
+
1692
+    /**
1693
+     * Get the webroot
1694
+     *
1695
+     * @return string
1696
+     */
1697
+    public function getWebRoot() {
1698
+        return $this->webRoot;
1699
+    }
1700
+
1701
+    /**
1702
+     * @return \OC\OCSClient
1703
+     */
1704
+    public function getOcsClient() {
1705
+        return $this->query('OcsClient');
1706
+    }
1707
+
1708
+    /**
1709
+     * @return \OCP\IDateTimeZone
1710
+     */
1711
+    public function getDateTimeZone() {
1712
+        return $this->query('DateTimeZone');
1713
+    }
1714
+
1715
+    /**
1716
+     * @return \OCP\IDateTimeFormatter
1717
+     */
1718
+    public function getDateTimeFormatter() {
1719
+        return $this->query('DateTimeFormatter');
1720
+    }
1721
+
1722
+    /**
1723
+     * @return \OCP\Files\Config\IMountProviderCollection
1724
+     */
1725
+    public function getMountProviderCollection() {
1726
+        return $this->query('MountConfigManager');
1727
+    }
1728
+
1729
+    /**
1730
+     * Get the IniWrapper
1731
+     *
1732
+     * @return IniGetWrapper
1733
+     */
1734
+    public function getIniWrapper() {
1735
+        return $this->query('IniWrapper');
1736
+    }
1737
+
1738
+    /**
1739
+     * @return \OCP\Command\IBus
1740
+     */
1741
+    public function getCommandBus() {
1742
+        return $this->query('AsyncCommandBus');
1743
+    }
1744
+
1745
+    /**
1746
+     * Get the trusted domain helper
1747
+     *
1748
+     * @return TrustedDomainHelper
1749
+     */
1750
+    public function getTrustedDomainHelper() {
1751
+        return $this->query('TrustedDomainHelper');
1752
+    }
1753
+
1754
+    /**
1755
+     * Get the locking provider
1756
+     *
1757
+     * @return \OCP\Lock\ILockingProvider
1758
+     * @since 8.1.0
1759
+     */
1760
+    public function getLockingProvider() {
1761
+        return $this->query('LockingProvider');
1762
+    }
1763
+
1764
+    /**
1765
+     * @return \OCP\Files\Mount\IMountManager
1766
+     **/
1767
+    function getMountManager() {
1768
+        return $this->query('MountManager');
1769
+    }
1770
+
1771
+    /** @return \OCP\Files\Config\IUserMountCache */
1772
+    function getUserMountCache() {
1773
+        return $this->query('UserMountCache');
1774
+    }
1775
+
1776
+    /**
1777
+     * Get the MimeTypeDetector
1778
+     *
1779
+     * @return \OCP\Files\IMimeTypeDetector
1780
+     */
1781
+    public function getMimeTypeDetector() {
1782
+        return $this->query('MimeTypeDetector');
1783
+    }
1784
+
1785
+    /**
1786
+     * Get the MimeTypeLoader
1787
+     *
1788
+     * @return \OCP\Files\IMimeTypeLoader
1789
+     */
1790
+    public function getMimeTypeLoader() {
1791
+        return $this->query('MimeTypeLoader');
1792
+    }
1793
+
1794
+    /**
1795
+     * Get the manager of all the capabilities
1796
+     *
1797
+     * @return \OC\CapabilitiesManager
1798
+     */
1799
+    public function getCapabilitiesManager() {
1800
+        return $this->query('CapabilitiesManager');
1801
+    }
1802
+
1803
+    /**
1804
+     * Get the EventDispatcher
1805
+     *
1806
+     * @return EventDispatcherInterface
1807
+     * @since 8.2.0
1808
+     */
1809
+    public function getEventDispatcher() {
1810
+        return $this->query('EventDispatcher');
1811
+    }
1812
+
1813
+    /**
1814
+     * Get the Notification Manager
1815
+     *
1816
+     * @return \OCP\Notification\IManager
1817
+     * @since 8.2.0
1818
+     */
1819
+    public function getNotificationManager() {
1820
+        return $this->query('NotificationManager');
1821
+    }
1822
+
1823
+    /**
1824
+     * @return \OCP\Comments\ICommentsManager
1825
+     */
1826
+    public function getCommentsManager() {
1827
+        return $this->query('CommentsManager');
1828
+    }
1829
+
1830
+    /**
1831
+     * @return \OCA\Theming\ThemingDefaults
1832
+     */
1833
+    public function getThemingDefaults() {
1834
+        return $this->query('ThemingDefaults');
1835
+    }
1836
+
1837
+    /**
1838
+     * @return \OC\IntegrityCheck\Checker
1839
+     */
1840
+    public function getIntegrityCodeChecker() {
1841
+        return $this->query('IntegrityCodeChecker');
1842
+    }
1843
+
1844
+    /**
1845
+     * @return \OC\Session\CryptoWrapper
1846
+     */
1847
+    public function getSessionCryptoWrapper() {
1848
+        return $this->query('CryptoWrapper');
1849
+    }
1850
+
1851
+    /**
1852
+     * @return CsrfTokenManager
1853
+     */
1854
+    public function getCsrfTokenManager() {
1855
+        return $this->query('CsrfTokenManager');
1856
+    }
1857
+
1858
+    /**
1859
+     * @return Throttler
1860
+     */
1861
+    public function getBruteForceThrottler() {
1862
+        return $this->query('Throttler');
1863
+    }
1864
+
1865
+    /**
1866
+     * @return IContentSecurityPolicyManager
1867
+     */
1868
+    public function getContentSecurityPolicyManager() {
1869
+        return $this->query('ContentSecurityPolicyManager');
1870
+    }
1871
+
1872
+    /**
1873
+     * @return ContentSecurityPolicyNonceManager
1874
+     */
1875
+    public function getContentSecurityPolicyNonceManager() {
1876
+        return $this->query('ContentSecurityPolicyNonceManager');
1877
+    }
1878
+
1879
+    /**
1880
+     * Not a public API as of 8.2, wait for 9.0
1881
+     *
1882
+     * @return \OCA\Files_External\Service\BackendService
1883
+     */
1884
+    public function getStoragesBackendService() {
1885
+        return $this->query('OCA\\Files_External\\Service\\BackendService');
1886
+    }
1887
+
1888
+    /**
1889
+     * Not a public API as of 8.2, wait for 9.0
1890
+     *
1891
+     * @return \OCA\Files_External\Service\GlobalStoragesService
1892
+     */
1893
+    public function getGlobalStoragesService() {
1894
+        return $this->query('OCA\\Files_External\\Service\\GlobalStoragesService');
1895
+    }
1896
+
1897
+    /**
1898
+     * Not a public API as of 8.2, wait for 9.0
1899
+     *
1900
+     * @return \OCA\Files_External\Service\UserGlobalStoragesService
1901
+     */
1902
+    public function getUserGlobalStoragesService() {
1903
+        return $this->query('OCA\\Files_External\\Service\\UserGlobalStoragesService');
1904
+    }
1905
+
1906
+    /**
1907
+     * Not a public API as of 8.2, wait for 9.0
1908
+     *
1909
+     * @return \OCA\Files_External\Service\UserStoragesService
1910
+     */
1911
+    public function getUserStoragesService() {
1912
+        return $this->query('OCA\\Files_External\\Service\\UserStoragesService');
1913
+    }
1914
+
1915
+    /**
1916
+     * @return \OCP\Share\IManager
1917
+     */
1918
+    public function getShareManager() {
1919
+        return $this->query('ShareManager');
1920
+    }
1921
+
1922
+    /**
1923
+     * @return \OCP\Collaboration\Collaborators\ISearch
1924
+     */
1925
+    public function getCollaboratorSearch() {
1926
+        return $this->query('CollaboratorSearch');
1927
+    }
1928
+
1929
+    /**
1930
+     * @return \OCP\Collaboration\AutoComplete\IManager
1931
+     */
1932
+    public function getAutoCompleteManager(){
1933
+        return $this->query(IManager::class);
1934
+    }
1935
+
1936
+    /**
1937
+     * Returns the LDAP Provider
1938
+     *
1939
+     * @return \OCP\LDAP\ILDAPProvider
1940
+     */
1941
+    public function getLDAPProvider() {
1942
+        return $this->query('LDAPProvider');
1943
+    }
1944
+
1945
+    /**
1946
+     * @return \OCP\Settings\IManager
1947
+     */
1948
+    public function getSettingsManager() {
1949
+        return $this->query('SettingsManager');
1950
+    }
1951
+
1952
+    /**
1953
+     * @return \OCP\Files\IAppData
1954
+     */
1955
+    public function getAppDataDir($app) {
1956
+        /** @var \OC\Files\AppData\Factory $factory */
1957
+        $factory = $this->query(\OC\Files\AppData\Factory::class);
1958
+        return $factory->get($app);
1959
+    }
1960
+
1961
+    /**
1962
+     * @return \OCP\Lockdown\ILockdownManager
1963
+     */
1964
+    public function getLockdownManager() {
1965
+        return $this->query('LockdownManager');
1966
+    }
1967
+
1968
+    /**
1969
+     * @return \OCP\Federation\ICloudIdManager
1970
+     */
1971
+    public function getCloudIdManager() {
1972
+        return $this->query(ICloudIdManager::class);
1973
+    }
1974
+
1975
+    /**
1976
+     * @return \OCP\Remote\Api\IApiFactory
1977
+     */
1978
+    public function getRemoteApiFactory() {
1979
+        return $this->query(IApiFactory::class);
1980
+    }
1981
+
1982
+    /**
1983
+     * @return \OCP\Remote\IInstanceFactory
1984
+     */
1985
+    public function getRemoteInstanceFactory() {
1986
+        return $this->query(IInstanceFactory::class);
1987
+    }
1988 1988
 }
Please login to merge, or discard this patch.
lib/public/App/IAppManager.php 1 patch
Indentation   +122 added lines, -122 removed lines patch added patch discarded remove patch
@@ -37,126 +37,126 @@
 block discarded – undo
37 37
  */
38 38
 interface IAppManager {
39 39
 
40
-	/**
41
-	 * Returns the app information from "appinfo/info.xml".
42
-	 *
43
-	 * @param string $appId
44
-	 * @return mixed
45
-	 * @since 14.0.0
46
-	 */
47
-	public function getAppInfo(string $appId, bool $path = false, $lang = null);
48
-
49
-	/**
50
-	 * Returns the app information from "appinfo/info.xml".
51
-	 *
52
-	 * @param string $appId
53
-	 * @param bool $useCache
54
-	 * @return string
55
-	 * @since 14.0.0
56
-	 */
57
-	public function getAppVersion(string $appId, bool $useCache = true): string;
58
-
59
-	/**
60
-	 * Check if an app is enabled for user
61
-	 *
62
-	 * @param string $appId
63
-	 * @param \OCP\IUser $user (optional) if not defined, the currently loggedin user will be used
64
-	 * @return bool
65
-	 * @since 8.0.0
66
-	 */
67
-	public function isEnabledForUser($appId, $user = null);
68
-
69
-	/**
70
-	 * Check if an app is enabled in the instance
71
-	 *
72
-	 * Notice: This actually checks if the app is enabled and not only if it is installed.
73
-	 *
74
-	 * @param string $appId
75
-	 * @return bool
76
-	 * @since 8.0.0
77
-	 */
78
-	public function isInstalled($appId);
79
-
80
-	/**
81
-	 * Enable an app for every user
82
-	 *
83
-	 * @param string $appId
84
-	 * @throws AppPathNotFoundException
85
-	 * @since 8.0.0
86
-	 */
87
-	public function enableApp($appId);
88
-
89
-	/**
90
-	 * Whether a list of types contains a protected app type
91
-	 *
92
-	 * @param string[] $types
93
-	 * @return bool
94
-	 * @since 12.0.0
95
-	 */
96
-	public function hasProtectedAppType($types);
97
-
98
-	/**
99
-	 * Enable an app only for specific groups
100
-	 *
101
-	 * @param string $appId
102
-	 * @param \OCP\IGroup[] $groups
103
-	 * @throws \Exception
104
-	 * @since 8.0.0
105
-	 */
106
-	public function enableAppForGroups($appId, $groups);
107
-
108
-	/**
109
-	 * Disable an app for every user
110
-	 *
111
-	 * @param string $appId
112
-	 * @since 8.0.0
113
-	 * @throws \Exception
114
-	 */
115
-	public function disableApp($appId);
116
-
117
-	/**
118
-	 * Get the directory for the given app.
119
-	 *
120
-	 * @param string $appId
121
-	 * @return string
122
-	 * @since 11.0.0
123
-	 * @throws AppPathNotFoundException
124
-	 */
125
-	public function getAppPath($appId);
126
-
127
-	/**
128
-	 * List all apps enabled for a user
129
-	 *
130
-	 * @param \OCP\IUser $user
131
-	 * @return string[]
132
-	 * @since 8.1.0
133
-	 */
134
-	public function getEnabledAppsForUser(IUser $user);
135
-
136
-	/**
137
-	 * List all installed apps
138
-	 *
139
-	 * @return string[]
140
-	 * @since 8.1.0
141
-	 */
142
-	public function getInstalledApps();
143
-
144
-	/**
145
-	 * Clear the cached list of apps when enabling/disabling an app
146
-	 * @since 8.1.0
147
-	 */
148
-	public function clearAppsCache();
149
-
150
-	/**
151
-	 * @param string $appId
152
-	 * @return boolean
153
-	 * @since 9.0.0
154
-	 */
155
-	public function isShipped($appId);
156
-
157
-	/**
158
-	 * @return string[]
159
-	 * @since 9.0.0
160
-	 */
161
-	public function getAlwaysEnabledApps();
40
+    /**
41
+     * Returns the app information from "appinfo/info.xml".
42
+     *
43
+     * @param string $appId
44
+     * @return mixed
45
+     * @since 14.0.0
46
+     */
47
+    public function getAppInfo(string $appId, bool $path = false, $lang = null);
48
+
49
+    /**
50
+     * Returns the app information from "appinfo/info.xml".
51
+     *
52
+     * @param string $appId
53
+     * @param bool $useCache
54
+     * @return string
55
+     * @since 14.0.0
56
+     */
57
+    public function getAppVersion(string $appId, bool $useCache = true): string;
58
+
59
+    /**
60
+     * Check if an app is enabled for user
61
+     *
62
+     * @param string $appId
63
+     * @param \OCP\IUser $user (optional) if not defined, the currently loggedin user will be used
64
+     * @return bool
65
+     * @since 8.0.0
66
+     */
67
+    public function isEnabledForUser($appId, $user = null);
68
+
69
+    /**
70
+     * Check if an app is enabled in the instance
71
+     *
72
+     * Notice: This actually checks if the app is enabled and not only if it is installed.
73
+     *
74
+     * @param string $appId
75
+     * @return bool
76
+     * @since 8.0.0
77
+     */
78
+    public function isInstalled($appId);
79
+
80
+    /**
81
+     * Enable an app for every user
82
+     *
83
+     * @param string $appId
84
+     * @throws AppPathNotFoundException
85
+     * @since 8.0.0
86
+     */
87
+    public function enableApp($appId);
88
+
89
+    /**
90
+     * Whether a list of types contains a protected app type
91
+     *
92
+     * @param string[] $types
93
+     * @return bool
94
+     * @since 12.0.0
95
+     */
96
+    public function hasProtectedAppType($types);
97
+
98
+    /**
99
+     * Enable an app only for specific groups
100
+     *
101
+     * @param string $appId
102
+     * @param \OCP\IGroup[] $groups
103
+     * @throws \Exception
104
+     * @since 8.0.0
105
+     */
106
+    public function enableAppForGroups($appId, $groups);
107
+
108
+    /**
109
+     * Disable an app for every user
110
+     *
111
+     * @param string $appId
112
+     * @since 8.0.0
113
+     * @throws \Exception
114
+     */
115
+    public function disableApp($appId);
116
+
117
+    /**
118
+     * Get the directory for the given app.
119
+     *
120
+     * @param string $appId
121
+     * @return string
122
+     * @since 11.0.0
123
+     * @throws AppPathNotFoundException
124
+     */
125
+    public function getAppPath($appId);
126
+
127
+    /**
128
+     * List all apps enabled for a user
129
+     *
130
+     * @param \OCP\IUser $user
131
+     * @return string[]
132
+     * @since 8.1.0
133
+     */
134
+    public function getEnabledAppsForUser(IUser $user);
135
+
136
+    /**
137
+     * List all installed apps
138
+     *
139
+     * @return string[]
140
+     * @since 8.1.0
141
+     */
142
+    public function getInstalledApps();
143
+
144
+    /**
145
+     * Clear the cached list of apps when enabling/disabling an app
146
+     * @since 8.1.0
147
+     */
148
+    public function clearAppsCache();
149
+
150
+    /**
151
+     * @param string $appId
152
+     * @return boolean
153
+     * @since 9.0.0
154
+     */
155
+    public function isShipped($appId);
156
+
157
+    /**
158
+     * @return string[]
159
+     * @since 9.0.0
160
+     */
161
+    public function getAlwaysEnabledApps();
162 162
 }
Please login to merge, or discard this patch.
settings/routes.php 1 patch
Indentation   +43 added lines, -43 removed lines patch added patch discarded remove patch
@@ -38,55 +38,55 @@
 block discarded – undo
38 38
 
39 39
 $application = new Application();
40 40
 $application->registerRoutes($this, [
41
-	'resources' => [
42
-		'AuthSettings' => ['url' => '/settings/personal/authtokens'],
43
-	],
44
-	'routes' => [
45
-		['name' => 'MailSettings#setMailSettings', 'url' => '/settings/admin/mailsettings', 'verb' => 'POST'],
46
-		['name' => 'MailSettings#storeCredentials', 'url' => '/settings/admin/mailsettings/credentials', 'verb' => 'POST'],
47
-		['name' => 'MailSettings#sendTestMail', 'url' => '/settings/admin/mailtest', 'verb' => 'POST'],
48
-		['name' => 'Encryption#startMigration', 'url' => '/settings/admin/startmigration', 'verb' => 'POST'],
41
+    'resources' => [
42
+        'AuthSettings' => ['url' => '/settings/personal/authtokens'],
43
+    ],
44
+    'routes' => [
45
+        ['name' => 'MailSettings#setMailSettings', 'url' => '/settings/admin/mailsettings', 'verb' => 'POST'],
46
+        ['name' => 'MailSettings#storeCredentials', 'url' => '/settings/admin/mailsettings/credentials', 'verb' => 'POST'],
47
+        ['name' => 'MailSettings#sendTestMail', 'url' => '/settings/admin/mailtest', 'verb' => 'POST'],
48
+        ['name' => 'Encryption#startMigration', 'url' => '/settings/admin/startmigration', 'verb' => 'POST'],
49 49
 
50
-		['name' => 'AppSettings#listCategories', 'url' => '/settings/apps/categories', 'verb' => 'GET'],
51
-		['name' => 'AppSettings#viewApps', 'url' => '/settings/apps', 'verb' => 'GET'],
52
-		['name' => 'AppSettings#listApps', 'url' => '/settings/apps/list', 'verb' => 'GET'],
53
-		['name' => 'AppSettings#enableApp', 'url' => '/settings/apps/enable/{appId}', 'verb' => 'GET'],
54
-		['name' => 'AppSettings#enableApp', 'url' => '/settings/apps/enable/{appId}', 'verb' => 'POST'],
55
-		['name' => 'AppSettings#enableApps', 'url' => '/settings/apps/enable', 'verb' => 'POST'],
56
-		['name' => 'AppSettings#disableApp', 'url' => '/settings/apps/disable/{appId}', 'verb' => 'GET'],
57
-		['name' => 'AppSettings#disableApps', 'url' => '/settings/apps/disable', 'verb' => 'POST'],
58
-		['name' => 'AppSettings#updateApp', 'url' => '/settings/apps/update/{appId}', 'verb' => 'GET'],
59
-		['name' => 'AppSettings#uninstallApp', 'url' => '/settings/apps/uninstall/{appId}', 'verb' => 'GET'],
60
-		['name' => 'AppSettings#viewApps', 'url' => '/settings/apps/{category}', 'verb' => 'GET', 'defaults' => ['category' => '']],
61
-		['name' => 'AppSettings#viewApps', 'url' => '/settings/apps/{category}/{id}', 'verb' => 'GET', 'defaults' => ['category' => '', 'id' => '']],
50
+        ['name' => 'AppSettings#listCategories', 'url' => '/settings/apps/categories', 'verb' => 'GET'],
51
+        ['name' => 'AppSettings#viewApps', 'url' => '/settings/apps', 'verb' => 'GET'],
52
+        ['name' => 'AppSettings#listApps', 'url' => '/settings/apps/list', 'verb' => 'GET'],
53
+        ['name' => 'AppSettings#enableApp', 'url' => '/settings/apps/enable/{appId}', 'verb' => 'GET'],
54
+        ['name' => 'AppSettings#enableApp', 'url' => '/settings/apps/enable/{appId}', 'verb' => 'POST'],
55
+        ['name' => 'AppSettings#enableApps', 'url' => '/settings/apps/enable', 'verb' => 'POST'],
56
+        ['name' => 'AppSettings#disableApp', 'url' => '/settings/apps/disable/{appId}', 'verb' => 'GET'],
57
+        ['name' => 'AppSettings#disableApps', 'url' => '/settings/apps/disable', 'verb' => 'POST'],
58
+        ['name' => 'AppSettings#updateApp', 'url' => '/settings/apps/update/{appId}', 'verb' => 'GET'],
59
+        ['name' => 'AppSettings#uninstallApp', 'url' => '/settings/apps/uninstall/{appId}', 'verb' => 'GET'],
60
+        ['name' => 'AppSettings#viewApps', 'url' => '/settings/apps/{category}', 'verb' => 'GET', 'defaults' => ['category' => '']],
61
+        ['name' => 'AppSettings#viewApps', 'url' => '/settings/apps/{category}/{id}', 'verb' => 'GET', 'defaults' => ['category' => '', 'id' => '']],
62 62
 
63
-		['name' => 'Users#setDisplayName', 'url' => '/settings/users/{username}/displayName', 'verb' => 'POST'],
64
-		['name' => 'Users#setEMailAddress', 'url' => '/settings/users/{id}/mailAddress', 'verb' => 'PUT'],
65
-		['name' => 'Users#setUserSettings', 'url' => '/settings/users/{username}/settings', 'verb' => 'PUT'],
66
-		['name' => 'Users#getVerificationCode', 'url' => '/settings/users/{account}/verify', 'verb' => 'GET'],
67
-		['name' => 'Users#usersList', 'url' => '/settings/users', 'verb' => 'GET'],
68
-		['name' => 'Users#usersListByGroup', 'url' => '/settings/users/{group}', 'verb' => 'GET'],
69
-		['name' => 'LogSettings#setLogLevel', 'url' => '/settings/admin/log/level', 'verb' => 'POST'],
70
-		['name' => 'LogSettings#getEntries', 'url' => '/settings/admin/log/entries', 'verb' => 'GET'],
71
-		['name' => 'LogSettings#download', 'url' => '/settings/admin/log/download', 'verb' => 'GET'],
72
-		['name' => 'CheckSetup#check', 'url' => '/settings/ajax/checksetup', 'verb' => 'GET'],
73
-		['name' => 'CheckSetup#getFailedIntegrityCheckFiles', 'url' => '/settings/integrity/failed', 'verb' => 'GET'],
74
-		['name' => 'CheckSetup#rescanFailedIntegrityCheck', 'url' => '/settings/integrity/rescan', 'verb' => 'GET'],
75
-		['name' => 'Certificate#addPersonalRootCertificate', 'url' => '/settings/personal/certificate', 'verb' => 'POST'],
76
-		['name' => 'Certificate#removePersonalRootCertificate', 'url' => '/settings/personal/certificate/{certificateIdentifier}', 'verb' => 'DELETE'],
77
-		['name' => 'Certificate#addSystemRootCertificate', 'url' => '/settings/admin/certificate', 'verb' => 'POST'],
78
-		['name' => 'Certificate#removeSystemRootCertificate', 'url' => '/settings/admin/certificate/{certificateIdentifier}', 'verb' => 'DELETE'],
79
-		['name' => 'PersonalSettings#index', 'url' => '/settings/user/{section}', 'verb' => 'GET', 'defaults' => ['section' => 'personal-info']],
80
-		['name' => 'AdminSettings#index', 'url' => '/settings/admin/{section}', 'verb' => 'GET', 'defaults' => ['section' => 'server']],
81
-		['name' => 'AdminSettings#form', 'url' => '/settings/admin/{section}', 'verb' => 'GET'],
82
-		['name' => 'ChangePassword#changePersonalPassword', 'url' => '/settings/personal/changepassword', 'verb' => 'POST'],
83
-		['name' => 'ChangePassword#changeUserPassword', 'url' => '/settings/users/changepassword', 'verb' => 'POST']
84
-	]
63
+        ['name' => 'Users#setDisplayName', 'url' => '/settings/users/{username}/displayName', 'verb' => 'POST'],
64
+        ['name' => 'Users#setEMailAddress', 'url' => '/settings/users/{id}/mailAddress', 'verb' => 'PUT'],
65
+        ['name' => 'Users#setUserSettings', 'url' => '/settings/users/{username}/settings', 'verb' => 'PUT'],
66
+        ['name' => 'Users#getVerificationCode', 'url' => '/settings/users/{account}/verify', 'verb' => 'GET'],
67
+        ['name' => 'Users#usersList', 'url' => '/settings/users', 'verb' => 'GET'],
68
+        ['name' => 'Users#usersListByGroup', 'url' => '/settings/users/{group}', 'verb' => 'GET'],
69
+        ['name' => 'LogSettings#setLogLevel', 'url' => '/settings/admin/log/level', 'verb' => 'POST'],
70
+        ['name' => 'LogSettings#getEntries', 'url' => '/settings/admin/log/entries', 'verb' => 'GET'],
71
+        ['name' => 'LogSettings#download', 'url' => '/settings/admin/log/download', 'verb' => 'GET'],
72
+        ['name' => 'CheckSetup#check', 'url' => '/settings/ajax/checksetup', 'verb' => 'GET'],
73
+        ['name' => 'CheckSetup#getFailedIntegrityCheckFiles', 'url' => '/settings/integrity/failed', 'verb' => 'GET'],
74
+        ['name' => 'CheckSetup#rescanFailedIntegrityCheck', 'url' => '/settings/integrity/rescan', 'verb' => 'GET'],
75
+        ['name' => 'Certificate#addPersonalRootCertificate', 'url' => '/settings/personal/certificate', 'verb' => 'POST'],
76
+        ['name' => 'Certificate#removePersonalRootCertificate', 'url' => '/settings/personal/certificate/{certificateIdentifier}', 'verb' => 'DELETE'],
77
+        ['name' => 'Certificate#addSystemRootCertificate', 'url' => '/settings/admin/certificate', 'verb' => 'POST'],
78
+        ['name' => 'Certificate#removeSystemRootCertificate', 'url' => '/settings/admin/certificate/{certificateIdentifier}', 'verb' => 'DELETE'],
79
+        ['name' => 'PersonalSettings#index', 'url' => '/settings/user/{section}', 'verb' => 'GET', 'defaults' => ['section' => 'personal-info']],
80
+        ['name' => 'AdminSettings#index', 'url' => '/settings/admin/{section}', 'verb' => 'GET', 'defaults' => ['section' => 'server']],
81
+        ['name' => 'AdminSettings#form', 'url' => '/settings/admin/{section}', 'verb' => 'GET'],
82
+        ['name' => 'ChangePassword#changePersonalPassword', 'url' => '/settings/personal/changepassword', 'verb' => 'POST'],
83
+        ['name' => 'ChangePassword#changeUserPassword', 'url' => '/settings/users/changepassword', 'verb' => 'POST']
84
+    ]
85 85
 ]);
86 86
 
87 87
 /** @var $this \OCP\Route\IRouter */
88 88
 
89 89
 // Settings pages
90 90
 $this->create('settings_help', '/settings/help')
91
-	->actionInclude('settings/help.php');
91
+    ->actionInclude('settings/help.php');
92 92
 
Please login to merge, or discard this patch.
lib/private/App/AppStore/Manager.php 1 patch
Indentation   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -28,14 +28,14 @@
 block discarded – undo
28 28
 
29 29
 class Manager {
30 30
 
31
-	public function __construct(AppFetcher $appFetcher) {
32
-		$apps = $appFetcher->get();
33
-		foreach ($apps as $app) {
34
-			$this->apps[$app['id']] = $app;
35
-		}
36
-	}
31
+    public function __construct(AppFetcher $appFetcher) {
32
+        $apps = $appFetcher->get();
33
+        foreach ($apps as $app) {
34
+            $this->apps[$app['id']] = $app;
35
+        }
36
+    }
37 37
 
38
-	public function getApp(string $appId) {
39
-		return $this->apps[$appId];
40
-	}
38
+    public function getApp(string $appId) {
39
+        return $this->apps[$appId];
40
+    }
41 41
 }
42 42
\ No newline at end of file
Please login to merge, or discard this patch.
settings/Controller/AppSettingsController.php 1 patch
Indentation   +512 added lines, -512 removed lines patch added patch discarded remove patch
@@ -57,517 +57,517 @@
 block discarded – undo
57 57
  * @package OC\Settings\Controller
58 58
  */
59 59
 class AppSettingsController extends Controller {
60
-	const CAT_ENABLED = 0;
61
-	const CAT_DISABLED = 1;
62
-	const CAT_ALL_INSTALLED = 2;
63
-	const CAT_APP_BUNDLES = 3;
64
-	const CAT_UPDATES = 4;
65
-
66
-	/** @var \OCP\IL10N */
67
-	private $l10n;
68
-	/** @var IConfig */
69
-	private $config;
70
-	/** @var INavigationManager */
71
-	private $navigationManager;
72
-	/** @var IAppManager */
73
-	private $appManager;
74
-	/** @var CategoryFetcher */
75
-	private $categoryFetcher;
76
-	/** @var AppFetcher */
77
-	private $appFetcher;
78
-	/** @var IFactory */
79
-	private $l10nFactory;
80
-	/** @var BundleFetcher */
81
-	private $bundleFetcher;
82
-	/** @var Installer */
83
-	private $installer;
84
-	/** @var IURLGenerator */
85
-	private $urlGenerator;
86
-	/** @var ILogger */
87
-	private $logger;
88
-
89
-	/**
90
-	 * @param string $appName
91
-	 * @param IRequest $request
92
-	 * @param IL10N $l10n
93
-	 * @param IConfig $config
94
-	 * @param INavigationManager $navigationManager
95
-	 * @param IAppManager $appManager
96
-	 * @param CategoryFetcher $categoryFetcher
97
-	 * @param AppFetcher $appFetcher
98
-	 * @param IFactory $l10nFactory
99
-	 * @param BundleFetcher $bundleFetcher
100
-	 * @param Installer $installer
101
-	 * @param IURLGenerator $urlGenerator
102
-	 * @param ILogger $logger
103
-	 */
104
-	public function __construct(string $appName,
105
-								IRequest $request,
106
-								IL10N $l10n,
107
-								IConfig $config,
108
-								INavigationManager $navigationManager,
109
-								IAppManager $appManager,
110
-								CategoryFetcher $categoryFetcher,
111
-								AppFetcher $appFetcher,
112
-								IFactory $l10nFactory,
113
-								BundleFetcher $bundleFetcher,
114
-								Installer $installer,
115
-								IURLGenerator $urlGenerator,
116
-								ILogger $logger) {
117
-		parent::__construct($appName, $request);
118
-		$this->l10n = $l10n;
119
-		$this->config = $config;
120
-		$this->navigationManager = $navigationManager;
121
-		$this->appManager = $appManager;
122
-		$this->categoryFetcher = $categoryFetcher;
123
-		$this->appFetcher = $appFetcher;
124
-		$this->l10nFactory = $l10nFactory;
125
-		$this->bundleFetcher = $bundleFetcher;
126
-		$this->installer = $installer;
127
-		$this->urlGenerator = $urlGenerator;
128
-		$this->logger = $logger;
129
-	}
130
-
131
-	/**
132
-	 * @NoCSRFRequired
133
-	 *
134
-	 * @return TemplateResponse
135
-	 */
136
-	public function viewApps(): TemplateResponse {
137
-		\OC_Util::addScript('settings', 'apps');
138
-		\OC_Util::addVendorScript('core', 'marked/marked.min');
139
-		$params = [];
140
-		$params['appstoreEnabled'] = $this->config->getSystemValue('appstoreenabled', true) === true;
141
-		$params['urlGenerator'] = $this->urlGenerator;
142
-		$params['updateCount'] = count($this->getAppsWithUpdates());
143
-		$params['developerDocumentation'] = $this->urlGenerator->linkToDocs('developer-manual');
144
-		$params['bundles'] = $this->getBundles();
145
-		$this->navigationManager->setActiveEntry('core_apps');
146
-
147
-		$templateResponse = new TemplateResponse('settings', 'settings', ['serverData' => $params]);
148
-		$policy = new ContentSecurityPolicy();
149
-		$policy->addAllowedImageDomain('https://usercontent.apps.nextcloud.com');
150
-		$templateResponse->setContentSecurityPolicy($policy);
151
-
152
-		return $templateResponse;
153
-	}
154
-
155
-	private function getAppsWithUpdates() {
156
-		$appClass = new \OC_App();
157
-		$apps = $appClass->listAllApps();
158
-		foreach($apps as $key => $app) {
159
-			$newVersion = $this->installer->isUpdateAvailable($app['id']);
160
-			if($newVersion === false) {
161
-				unset($apps[$key]);
162
-			}
163
-		}
164
-		return $apps;
165
-	}
166
-
167
-	private function getBundles() {
168
-		$result = [];
169
-		$bundles = $this->bundleFetcher->getBundles();
170
-		foreach ($bundles as $bundle) {
171
-			$result[] = [
172
-				'name' => $bundle->getName(),
173
-				'id' => $bundle->getIdentifier(),
174
-				'appIdentifiers' => $bundle->getAppIdentifiers()
175
-			];
176
-		}
177
-		return $result;
178
-
179
-	}
180
-
181
-	/**
182
-	 * Get all available categories
183
-	 *
184
-	 * @return JSONResponse
185
-	 */
186
-	public function listCategories(): JSONResponse {
187
-		return new JSONResponse($this->getAllCategories());
188
-	}
189
-
190
-	private function getAllCategories() {
191
-		$currentLanguage = substr($this->l10nFactory->findLanguage(), 0, 2);
192
-
193
-		$formattedCategories = [];
194
-		$categories = $this->categoryFetcher->get();
195
-		foreach($categories as $category) {
196
-			$formattedCategories[] = [
197
-				'id' => $category['id'],
198
-				'ident' => $category['id'],
199
-				'displayName' => isset($category['translations'][$currentLanguage]['name']) ? $category['translations'][$currentLanguage]['name'] : $category['translations']['en']['name'],
200
-			];
201
-		}
202
-
203
-		return $formattedCategories;
204
-	}
205
-
206
-	/**
207
-	 * Get all available apps in a category
208
-	 *
209
-	 * @param string $category
210
-	 * @return JSONResponse
211
-	 * @throws \Exception
212
-	 */
213
-	public function listApps($category = ''): JSONResponse {
214
-		$appClass = new \OC_App();
215
-
216
-		switch ($category) {
217
-			case 'installed':
218
-				$apps = $appClass->listAllApps();
219
-				break;
220
-			case 'updates':
221
-				$apps = $this->getAppsWithUpdates();
222
-				break;
223
-			case 'enabled':
224
-				$apps = $appClass->listAllApps();
225
-				$apps = array_filter($apps, function ($app) {
226
-					return $app['active'];
227
-				});
228
-				break;
229
-			case 'disabled':
230
-				$apps = $appClass->listAllApps();
231
-				$apps = array_filter($apps, function ($app) {
232
-					return !$app['active'];
233
-				});
234
-				break;
235
-			case 'app-bundles':
236
-				$bundles = $this->bundleFetcher->getBundles();
237
-				$apps = [];
238
-				$installedApps = $appClass->listAllApps();
239
-				$appstoreApps = $this->getAppsForCategory();
240
-				foreach($bundles as $bundle) {
241
-					foreach($bundle->getAppIdentifiers() as $identifier) {
242
-						$alreadyMatched = false;
243
-						foreach($installedApps as $app) {
244
-							if($app['id'] === $identifier) {
245
-								$app['bundleId'] = $bundle->getIdentifier();
246
-								$apps[] = $app;
247
-								$alreadyMatched = true;
248
-								continue;
249
-							}
250
-						}
251
-						if (!$alreadyMatched) {
252
-							foreach ($appstoreApps as $app) {
253
-								if ($app['id'] === $identifier) {
254
-									$app['bundleId'] = $bundle->getIdentifier();
255
-									$apps[] = $app;
256
-									continue;
257
-								}
258
-							}
259
-						}
260
-					}
261
-				}
262
-				break;
263
-			default:
264
-				$apps = $this->getAppsForCategory($category);
265
-				break;
266
-		}
267
-
268
-
269
-		// Fetch all apps from appstore
270
-		$appstoreData = [];
271
-		$fetchedApps = $this->appFetcher->get();
272
-		foreach ($fetchedApps as $app) {
273
-			$appstoreData[$app['id']] = $app;
274
-		}
275
-
276
-		$dependencyAnalyzer = new DependencyAnalyzer(new Platform($this->config), $this->l10n);
277
-
278
-		// Extend existing app details
279
-		$apps = array_map(function($appData) use ($appstoreData, $dependencyAnalyzer) {
280
-			$appData['appstoreData'] = $appstoreData[$appData['id']];
281
-			$appData['license'] = $appstoreData['releases'][0]['licenses'];
282
-			$appData['screenshot'] = isset($appstoreData['screenshots'][0]['url']) ? 'https://usercontent.apps.nextcloud.com/'.base64_encode($appstoreData['screenshots'][0]['url']) : '';
283
-			$newVersion = $this->installer->isUpdateAvailable($appData['id']);
284
-			if($newVersion && $this->appManager->isInstalled($appData['id'])) {
285
-				$appData['update'] = $newVersion;
286
-			}
287
-
288
-			// fix groups to be an array
289
-			$groups = array();
290
-			if (is_string($appData['groups'])) {
291
-				$groups = json_decode($appData['groups']);
292
-			}
293
-			$appData['groups'] = $groups;
294
-			$appData['canUnInstall'] = !$appData['active'] && $appData['removable'];
295
-
296
-			// fix licence vs license
297
-			if (isset($appData['license']) && !isset($appData['licence'])) {
298
-				$appData['licence'] = $appData['license'];
299
-			}
300
-
301
-			// analyse dependencies
302
-			$missing = $dependencyAnalyzer->analyze($appData);
303
-			$appData['canInstall'] = empty($missing);
304
-			$appData['missingDependencies'] = $missing;
305
-
306
-			$appData['missingMinOwnCloudVersion'] = !isset($appData['dependencies']['nextcloud']['@attributes']['min-version']);
307
-			$appData['missingMaxOwnCloudVersion'] = !isset($appData['dependencies']['nextcloud']['@attributes']['max-version']);
308
-
309
-			return $appData;
310
-		}, $apps);
311
-
312
-		usort($apps, [$this, 'sortApps']);
313
-
314
-		return new JSONResponse(['apps' => $apps, 'status' => 'success']);
315
-	}
316
-
317
-	/**
318
-	 * Get all apps for a category
319
-	 *
320
-	 * @param string $requestedCategory
321
-	 * @return array
322
-	 * @throws \Exception
323
-	 */
324
-	private function getAppsForCategory($requestedCategory = ''): array {
325
-		$versionParser = new VersionParser();
326
-		$formattedApps = [];
327
-		$apps = $this->appFetcher->get();
328
-		foreach($apps as $app) {
329
-			// Skip all apps not in the requested category
330
-			if ($requestedCategory !== '') {
331
-				$isInCategory = false;
332
-				foreach($app['categories'] as $category) {
333
-					if($category === $requestedCategory) {
334
-						$isInCategory = true;
335
-					}
336
-				}
337
-				if(!$isInCategory) {
338
-					continue;
339
-				}
340
-			}
341
-
342
-			$nextCloudVersion = $versionParser->getVersion($app['releases'][0]['rawPlatformVersionSpec']);
343
-			$nextCloudVersionDependencies = [];
344
-			if($nextCloudVersion->getMinimumVersion() !== '') {
345
-				$nextCloudVersionDependencies['nextcloud']['@attributes']['min-version'] = $nextCloudVersion->getMinimumVersion();
346
-			}
347
-			if($nextCloudVersion->getMaximumVersion() !== '') {
348
-				$nextCloudVersionDependencies['nextcloud']['@attributes']['max-version'] = $nextCloudVersion->getMaximumVersion();
349
-			}
350
-			$phpVersion = $versionParser->getVersion($app['releases'][0]['rawPhpVersionSpec']);
351
-			$existsLocally = \OC_App::getAppPath($app['id']) !== false;
352
-			$phpDependencies = [];
353
-			if($phpVersion->getMinimumVersion() !== '') {
354
-				$phpDependencies['php']['@attributes']['min-version'] = $phpVersion->getMinimumVersion();
355
-			}
356
-			if($phpVersion->getMaximumVersion() !== '') {
357
-				$phpDependencies['php']['@attributes']['max-version'] = $phpVersion->getMaximumVersion();
358
-			}
359
-			if(isset($app['releases'][0]['minIntSize'])) {
360
-				$phpDependencies['php']['@attributes']['min-int-size'] = $app['releases'][0]['minIntSize'];
361
-			}
362
-			$authors = '';
363
-			foreach($app['authors'] as $key => $author) {
364
-				$authors .= $author['name'];
365
-				if($key !== count($app['authors']) - 1) {
366
-					$authors .= ', ';
367
-				}
368
-			}
369
-
370
-			$currentLanguage = substr(\OC::$server->getL10NFactory()->findLanguage(), 0, 2);
371
-			$enabledValue = $this->config->getAppValue($app['id'], 'enabled', 'no');
372
-			$groups = null;
373
-			if($enabledValue !== 'no' && $enabledValue !== 'yes') {
374
-				$groups = $enabledValue;
375
-			}
376
-
377
-			$currentVersion = '';
378
-			if($this->appManager->isInstalled($app['id'])) {
379
-				$currentVersion = $this->appManager->getAppVersion($app['id']);
380
-			} else {
381
-				$currentLanguage = $app['releases'][0]['version'];
382
-			}
383
-
384
-			$formattedApps[] = [
385
-				'id' => $app['id'],
386
-				'name' => isset($app['translations'][$currentLanguage]['name']) ? $app['translations'][$currentLanguage]['name'] : $app['translations']['en']['name'],
387
-				'description' => isset($app['translations'][$currentLanguage]['description']) ? $app['translations'][$currentLanguage]['description'] : $app['translations']['en']['description'],
388
-				'summary' => isset($app['translations'][$currentLanguage]['summary']) ? $app['translations'][$currentLanguage]['summary'] : $app['translations']['en']['summary'],
389
-				'license' => $app['releases'][0]['licenses'],
390
-				'author' => $authors,
391
-				'shipped' => false,
392
-				'version' => $currentVersion,
393
-				'default_enable' => '',
394
-				'types' => [],
395
-				'documentation' => [
396
-					'admin' => $app['adminDocs'],
397
-					'user' => $app['userDocs'],
398
-					'developer' => $app['developerDocs']
399
-				],
400
-				'website' => $app['website'],
401
-				'bugs' => $app['issueTracker'],
402
-				'detailpage' => $app['website'],
403
-				'dependencies' => array_merge(
404
-					$nextCloudVersionDependencies,
405
-					$phpDependencies
406
-				),
407
-				'level' => ($app['isFeatured'] === true) ? 200 : 100,
408
-				'missingMaxOwnCloudVersion' => false,
409
-				'missingMinOwnCloudVersion' => false,
410
-				'canInstall' => true,
411
-				'preview' => isset($app['screenshots'][0]['url']) ? 'https://usercontent.apps.nextcloud.com/'.base64_encode($app['screenshots'][0]['url']) : '',
412
-				'score' => $app['ratingOverall'],
413
-				'ratingNumOverall' => $app['ratingNumOverall'],
414
-				'ratingNumThresholdReached' => $app['ratingNumOverall'] > 5,
415
-				'removable' => $existsLocally,
416
-				'active' => $this->appManager->isEnabledForUser($app['id']),
417
-				'needsDownload' => !$existsLocally,
418
-				'groups' => $groups,
419
-				'fromAppStore' => true,
420
-				'appstoreData' => $app,
421
-			];
422
-		}
423
-
424
-		return $formattedApps;
425
-	}
426
-
427
-	/**
428
-	 * @PasswordConfirmationRequired
429
-	 *
430
-	 * @param string $appId
431
-	 * @param array $groups
432
-	 * @return JSONResponse
433
-	 */
434
-	public function enableApp(string $appId, array $groups = []): JSONResponse {
435
-		return $this->enableApps([$appId], $groups);
436
-	}
437
-
438
-	/**
439
-	 * Enable one or more apps
440
-	 *
441
-	 * apps will be enabled for specific groups only if $groups is defined
442
-	 *
443
-	 * @PasswordConfirmationRequired
444
-	 * @param array $appIds
445
-	 * @param array $groups
446
-	 * @return JSONResponse
447
-	 */
448
-	public function enableApps(array $appIds, array $groups = []): JSONResponse {
449
-		try {
450
-			$updateRequired = false;
451
-
452
-			foreach ($appIds as $appId) {
453
-				$appId = OC_App::cleanAppId($appId);
454
-
455
-				// Check if app is already downloaded
456
-				/** @var Installer $installer */
457
-				$installer = \OC::$server->query(Installer::class);
458
-				$isDownloaded = $installer->isDownloaded($appId);
459
-
460
-				if(!$isDownloaded) {
461
-					$installer->downloadApp($appId);
462
-				}
463
-
464
-				$installer->installApp($appId);
465
-
466
-				if (count($groups) > 0) {
467
-					$this->appManager->enableAppForGroups($appId, $this->getGroupList($groups));
468
-				} else {
469
-					$this->appManager->enableApp($appId);
470
-				}
471
-				if (\OC_App::shouldUpgrade($appId)) {
472
-					$updateRequired = true;
473
-				}
474
-			}
475
-			return new JSONResponse(['data' => ['update_required' => $updateRequired]]);
476
-
477
-		} catch (\Exception $e) {
478
-			$this->logger->logException($e);
479
-			return new JSONResponse(['data' => ['message' => $e->getMessage()]], Http::STATUS_INTERNAL_SERVER_ERROR);
480
-		}
481
-	}
482
-
483
-	private function getGroupList(array $groups) {
484
-		$groupManager = \OC::$server->getGroupManager();
485
-		$groupsList = [];
486
-		foreach ($groups as $group) {
487
-			$groupItem = $groupManager->get($group);
488
-			if ($groupItem instanceof \OCP\IGroup) {
489
-				$groupsList[] = $groupManager->get($group);
490
-			}
491
-		}
492
-		return $groupsList;
493
-	}
494
-
495
-	/**
496
-	 * @PasswordConfirmationRequired
497
-	 *
498
-	 * @param string $appId
499
-	 * @return JSONResponse
500
-	 */
501
-	public function disableApp(string $appId): JSONResponse {
502
-		return $this->disableApps([$appId]);
503
-	}
504
-
505
-	/**
506
-	 * @PasswordConfirmationRequired
507
-	 *
508
-	 * @param array $appIds
509
-	 * @return JSONResponse
510
-	 */
511
-	public function disableApps(array $appIds): JSONResponse {
512
-		try {
513
-			foreach ($appIds as $appId) {
514
-				$appId = OC_App::cleanAppId($appId);
515
-				$this->appManager->disableApp($appId);
516
-			}
517
-			return new JSONResponse([]);
518
-		} catch (\Exception $e) {
519
-			$this->logger->logException($e);
520
-			return new JSONResponse(['data' => ['message' => $e->getMessage()]], Http::STATUS_INTERNAL_SERVER_ERROR);
521
-		}
522
-	}
523
-
524
-	/**
525
-	 * @PasswordConfirmationRequired
526
-	 *
527
-	 * @param string $appId
528
-	 * @return JSONResponse
529
-	 */
530
-	public function uninstallApp(string $appId): JSONResponse {
531
-		$appId = OC_App::cleanAppId($appId);
532
-		$result = $this->installer->removeApp($appId);
533
-		if($result !== false) {
534
-			// FIXME: Clear the cache - move that into some sane helper method
535
-			\OC::$server->getMemCacheFactory()->createDistributed('settings')->remove('listApps-0');
536
-			\OC::$server->getMemCacheFactory()->createDistributed('settings')->remove('listApps-1');
537
-			return new JSONResponse(['data' => ['appid' => $appId]]);
538
-		}
539
-		return new JSONResponse(['data' => ['message' => $this->l10n->t('Couldn\'t remove app.')]], Http::STATUS_INTERNAL_SERVER_ERROR);
540
-	}
541
-
542
-	/**
543
-	 * @param string $appId
544
-	 * @return JSONResponse
545
-	 */
546
-	public function updateApp(string $appId): JSONResponse {
547
-		$appId = OC_App::cleanAppId($appId);
548
-
549
-		$this->config->setSystemValue('maintenance', true);
550
-		try {
551
-			$result = $this->installer->updateAppstoreApp($appId);
552
-			$this->config->setSystemValue('maintenance', false);
553
-		} catch (\Exception $ex) {
554
-			$this->config->setSystemValue('maintenance', false);
555
-			return new JSONResponse(['data' => ['message' => $ex->getMessage()]], Http::STATUS_INTERNAL_SERVER_ERROR);
556
-		}
557
-
558
-		if ($result !== false) {
559
-			return new JSONResponse(['data' => ['appid' => $appId]]);
560
-		}
561
-		return new JSONResponse(['data' => ['message' => $this->l10n->t('Couldn\'t update app.')]], Http::STATUS_INTERNAL_SERVER_ERROR);
562
-	}
563
-
564
-	private function sortApps($a, $b) {
565
-		$a = (string)$a['name'];
566
-		$b = (string)$b['name'];
567
-		if ($a === $b) {
568
-			return 0;
569
-		}
570
-		return ($a < $b) ? -1 : 1;
571
-	}
60
+    const CAT_ENABLED = 0;
61
+    const CAT_DISABLED = 1;
62
+    const CAT_ALL_INSTALLED = 2;
63
+    const CAT_APP_BUNDLES = 3;
64
+    const CAT_UPDATES = 4;
65
+
66
+    /** @var \OCP\IL10N */
67
+    private $l10n;
68
+    /** @var IConfig */
69
+    private $config;
70
+    /** @var INavigationManager */
71
+    private $navigationManager;
72
+    /** @var IAppManager */
73
+    private $appManager;
74
+    /** @var CategoryFetcher */
75
+    private $categoryFetcher;
76
+    /** @var AppFetcher */
77
+    private $appFetcher;
78
+    /** @var IFactory */
79
+    private $l10nFactory;
80
+    /** @var BundleFetcher */
81
+    private $bundleFetcher;
82
+    /** @var Installer */
83
+    private $installer;
84
+    /** @var IURLGenerator */
85
+    private $urlGenerator;
86
+    /** @var ILogger */
87
+    private $logger;
88
+
89
+    /**
90
+     * @param string $appName
91
+     * @param IRequest $request
92
+     * @param IL10N $l10n
93
+     * @param IConfig $config
94
+     * @param INavigationManager $navigationManager
95
+     * @param IAppManager $appManager
96
+     * @param CategoryFetcher $categoryFetcher
97
+     * @param AppFetcher $appFetcher
98
+     * @param IFactory $l10nFactory
99
+     * @param BundleFetcher $bundleFetcher
100
+     * @param Installer $installer
101
+     * @param IURLGenerator $urlGenerator
102
+     * @param ILogger $logger
103
+     */
104
+    public function __construct(string $appName,
105
+                                IRequest $request,
106
+                                IL10N $l10n,
107
+                                IConfig $config,
108
+                                INavigationManager $navigationManager,
109
+                                IAppManager $appManager,
110
+                                CategoryFetcher $categoryFetcher,
111
+                                AppFetcher $appFetcher,
112
+                                IFactory $l10nFactory,
113
+                                BundleFetcher $bundleFetcher,
114
+                                Installer $installer,
115
+                                IURLGenerator $urlGenerator,
116
+                                ILogger $logger) {
117
+        parent::__construct($appName, $request);
118
+        $this->l10n = $l10n;
119
+        $this->config = $config;
120
+        $this->navigationManager = $navigationManager;
121
+        $this->appManager = $appManager;
122
+        $this->categoryFetcher = $categoryFetcher;
123
+        $this->appFetcher = $appFetcher;
124
+        $this->l10nFactory = $l10nFactory;
125
+        $this->bundleFetcher = $bundleFetcher;
126
+        $this->installer = $installer;
127
+        $this->urlGenerator = $urlGenerator;
128
+        $this->logger = $logger;
129
+    }
130
+
131
+    /**
132
+     * @NoCSRFRequired
133
+     *
134
+     * @return TemplateResponse
135
+     */
136
+    public function viewApps(): TemplateResponse {
137
+        \OC_Util::addScript('settings', 'apps');
138
+        \OC_Util::addVendorScript('core', 'marked/marked.min');
139
+        $params = [];
140
+        $params['appstoreEnabled'] = $this->config->getSystemValue('appstoreenabled', true) === true;
141
+        $params['urlGenerator'] = $this->urlGenerator;
142
+        $params['updateCount'] = count($this->getAppsWithUpdates());
143
+        $params['developerDocumentation'] = $this->urlGenerator->linkToDocs('developer-manual');
144
+        $params['bundles'] = $this->getBundles();
145
+        $this->navigationManager->setActiveEntry('core_apps');
146
+
147
+        $templateResponse = new TemplateResponse('settings', 'settings', ['serverData' => $params]);
148
+        $policy = new ContentSecurityPolicy();
149
+        $policy->addAllowedImageDomain('https://usercontent.apps.nextcloud.com');
150
+        $templateResponse->setContentSecurityPolicy($policy);
151
+
152
+        return $templateResponse;
153
+    }
154
+
155
+    private function getAppsWithUpdates() {
156
+        $appClass = new \OC_App();
157
+        $apps = $appClass->listAllApps();
158
+        foreach($apps as $key => $app) {
159
+            $newVersion = $this->installer->isUpdateAvailable($app['id']);
160
+            if($newVersion === false) {
161
+                unset($apps[$key]);
162
+            }
163
+        }
164
+        return $apps;
165
+    }
166
+
167
+    private function getBundles() {
168
+        $result = [];
169
+        $bundles = $this->bundleFetcher->getBundles();
170
+        foreach ($bundles as $bundle) {
171
+            $result[] = [
172
+                'name' => $bundle->getName(),
173
+                'id' => $bundle->getIdentifier(),
174
+                'appIdentifiers' => $bundle->getAppIdentifiers()
175
+            ];
176
+        }
177
+        return $result;
178
+
179
+    }
180
+
181
+    /**
182
+     * Get all available categories
183
+     *
184
+     * @return JSONResponse
185
+     */
186
+    public function listCategories(): JSONResponse {
187
+        return new JSONResponse($this->getAllCategories());
188
+    }
189
+
190
+    private function getAllCategories() {
191
+        $currentLanguage = substr($this->l10nFactory->findLanguage(), 0, 2);
192
+
193
+        $formattedCategories = [];
194
+        $categories = $this->categoryFetcher->get();
195
+        foreach($categories as $category) {
196
+            $formattedCategories[] = [
197
+                'id' => $category['id'],
198
+                'ident' => $category['id'],
199
+                'displayName' => isset($category['translations'][$currentLanguage]['name']) ? $category['translations'][$currentLanguage]['name'] : $category['translations']['en']['name'],
200
+            ];
201
+        }
202
+
203
+        return $formattedCategories;
204
+    }
205
+
206
+    /**
207
+     * Get all available apps in a category
208
+     *
209
+     * @param string $category
210
+     * @return JSONResponse
211
+     * @throws \Exception
212
+     */
213
+    public function listApps($category = ''): JSONResponse {
214
+        $appClass = new \OC_App();
215
+
216
+        switch ($category) {
217
+            case 'installed':
218
+                $apps = $appClass->listAllApps();
219
+                break;
220
+            case 'updates':
221
+                $apps = $this->getAppsWithUpdates();
222
+                break;
223
+            case 'enabled':
224
+                $apps = $appClass->listAllApps();
225
+                $apps = array_filter($apps, function ($app) {
226
+                    return $app['active'];
227
+                });
228
+                break;
229
+            case 'disabled':
230
+                $apps = $appClass->listAllApps();
231
+                $apps = array_filter($apps, function ($app) {
232
+                    return !$app['active'];
233
+                });
234
+                break;
235
+            case 'app-bundles':
236
+                $bundles = $this->bundleFetcher->getBundles();
237
+                $apps = [];
238
+                $installedApps = $appClass->listAllApps();
239
+                $appstoreApps = $this->getAppsForCategory();
240
+                foreach($bundles as $bundle) {
241
+                    foreach($bundle->getAppIdentifiers() as $identifier) {
242
+                        $alreadyMatched = false;
243
+                        foreach($installedApps as $app) {
244
+                            if($app['id'] === $identifier) {
245
+                                $app['bundleId'] = $bundle->getIdentifier();
246
+                                $apps[] = $app;
247
+                                $alreadyMatched = true;
248
+                                continue;
249
+                            }
250
+                        }
251
+                        if (!$alreadyMatched) {
252
+                            foreach ($appstoreApps as $app) {
253
+                                if ($app['id'] === $identifier) {
254
+                                    $app['bundleId'] = $bundle->getIdentifier();
255
+                                    $apps[] = $app;
256
+                                    continue;
257
+                                }
258
+                            }
259
+                        }
260
+                    }
261
+                }
262
+                break;
263
+            default:
264
+                $apps = $this->getAppsForCategory($category);
265
+                break;
266
+        }
267
+
268
+
269
+        // Fetch all apps from appstore
270
+        $appstoreData = [];
271
+        $fetchedApps = $this->appFetcher->get();
272
+        foreach ($fetchedApps as $app) {
273
+            $appstoreData[$app['id']] = $app;
274
+        }
275
+
276
+        $dependencyAnalyzer = new DependencyAnalyzer(new Platform($this->config), $this->l10n);
277
+
278
+        // Extend existing app details
279
+        $apps = array_map(function($appData) use ($appstoreData, $dependencyAnalyzer) {
280
+            $appData['appstoreData'] = $appstoreData[$appData['id']];
281
+            $appData['license'] = $appstoreData['releases'][0]['licenses'];
282
+            $appData['screenshot'] = isset($appstoreData['screenshots'][0]['url']) ? 'https://usercontent.apps.nextcloud.com/'.base64_encode($appstoreData['screenshots'][0]['url']) : '';
283
+            $newVersion = $this->installer->isUpdateAvailable($appData['id']);
284
+            if($newVersion && $this->appManager->isInstalled($appData['id'])) {
285
+                $appData['update'] = $newVersion;
286
+            }
287
+
288
+            // fix groups to be an array
289
+            $groups = array();
290
+            if (is_string($appData['groups'])) {
291
+                $groups = json_decode($appData['groups']);
292
+            }
293
+            $appData['groups'] = $groups;
294
+            $appData['canUnInstall'] = !$appData['active'] && $appData['removable'];
295
+
296
+            // fix licence vs license
297
+            if (isset($appData['license']) && !isset($appData['licence'])) {
298
+                $appData['licence'] = $appData['license'];
299
+            }
300
+
301
+            // analyse dependencies
302
+            $missing = $dependencyAnalyzer->analyze($appData);
303
+            $appData['canInstall'] = empty($missing);
304
+            $appData['missingDependencies'] = $missing;
305
+
306
+            $appData['missingMinOwnCloudVersion'] = !isset($appData['dependencies']['nextcloud']['@attributes']['min-version']);
307
+            $appData['missingMaxOwnCloudVersion'] = !isset($appData['dependencies']['nextcloud']['@attributes']['max-version']);
308
+
309
+            return $appData;
310
+        }, $apps);
311
+
312
+        usort($apps, [$this, 'sortApps']);
313
+
314
+        return new JSONResponse(['apps' => $apps, 'status' => 'success']);
315
+    }
316
+
317
+    /**
318
+     * Get all apps for a category
319
+     *
320
+     * @param string $requestedCategory
321
+     * @return array
322
+     * @throws \Exception
323
+     */
324
+    private function getAppsForCategory($requestedCategory = ''): array {
325
+        $versionParser = new VersionParser();
326
+        $formattedApps = [];
327
+        $apps = $this->appFetcher->get();
328
+        foreach($apps as $app) {
329
+            // Skip all apps not in the requested category
330
+            if ($requestedCategory !== '') {
331
+                $isInCategory = false;
332
+                foreach($app['categories'] as $category) {
333
+                    if($category === $requestedCategory) {
334
+                        $isInCategory = true;
335
+                    }
336
+                }
337
+                if(!$isInCategory) {
338
+                    continue;
339
+                }
340
+            }
341
+
342
+            $nextCloudVersion = $versionParser->getVersion($app['releases'][0]['rawPlatformVersionSpec']);
343
+            $nextCloudVersionDependencies = [];
344
+            if($nextCloudVersion->getMinimumVersion() !== '') {
345
+                $nextCloudVersionDependencies['nextcloud']['@attributes']['min-version'] = $nextCloudVersion->getMinimumVersion();
346
+            }
347
+            if($nextCloudVersion->getMaximumVersion() !== '') {
348
+                $nextCloudVersionDependencies['nextcloud']['@attributes']['max-version'] = $nextCloudVersion->getMaximumVersion();
349
+            }
350
+            $phpVersion = $versionParser->getVersion($app['releases'][0]['rawPhpVersionSpec']);
351
+            $existsLocally = \OC_App::getAppPath($app['id']) !== false;
352
+            $phpDependencies = [];
353
+            if($phpVersion->getMinimumVersion() !== '') {
354
+                $phpDependencies['php']['@attributes']['min-version'] = $phpVersion->getMinimumVersion();
355
+            }
356
+            if($phpVersion->getMaximumVersion() !== '') {
357
+                $phpDependencies['php']['@attributes']['max-version'] = $phpVersion->getMaximumVersion();
358
+            }
359
+            if(isset($app['releases'][0]['minIntSize'])) {
360
+                $phpDependencies['php']['@attributes']['min-int-size'] = $app['releases'][0]['minIntSize'];
361
+            }
362
+            $authors = '';
363
+            foreach($app['authors'] as $key => $author) {
364
+                $authors .= $author['name'];
365
+                if($key !== count($app['authors']) - 1) {
366
+                    $authors .= ', ';
367
+                }
368
+            }
369
+
370
+            $currentLanguage = substr(\OC::$server->getL10NFactory()->findLanguage(), 0, 2);
371
+            $enabledValue = $this->config->getAppValue($app['id'], 'enabled', 'no');
372
+            $groups = null;
373
+            if($enabledValue !== 'no' && $enabledValue !== 'yes') {
374
+                $groups = $enabledValue;
375
+            }
376
+
377
+            $currentVersion = '';
378
+            if($this->appManager->isInstalled($app['id'])) {
379
+                $currentVersion = $this->appManager->getAppVersion($app['id']);
380
+            } else {
381
+                $currentLanguage = $app['releases'][0]['version'];
382
+            }
383
+
384
+            $formattedApps[] = [
385
+                'id' => $app['id'],
386
+                'name' => isset($app['translations'][$currentLanguage]['name']) ? $app['translations'][$currentLanguage]['name'] : $app['translations']['en']['name'],
387
+                'description' => isset($app['translations'][$currentLanguage]['description']) ? $app['translations'][$currentLanguage]['description'] : $app['translations']['en']['description'],
388
+                'summary' => isset($app['translations'][$currentLanguage]['summary']) ? $app['translations'][$currentLanguage]['summary'] : $app['translations']['en']['summary'],
389
+                'license' => $app['releases'][0]['licenses'],
390
+                'author' => $authors,
391
+                'shipped' => false,
392
+                'version' => $currentVersion,
393
+                'default_enable' => '',
394
+                'types' => [],
395
+                'documentation' => [
396
+                    'admin' => $app['adminDocs'],
397
+                    'user' => $app['userDocs'],
398
+                    'developer' => $app['developerDocs']
399
+                ],
400
+                'website' => $app['website'],
401
+                'bugs' => $app['issueTracker'],
402
+                'detailpage' => $app['website'],
403
+                'dependencies' => array_merge(
404
+                    $nextCloudVersionDependencies,
405
+                    $phpDependencies
406
+                ),
407
+                'level' => ($app['isFeatured'] === true) ? 200 : 100,
408
+                'missingMaxOwnCloudVersion' => false,
409
+                'missingMinOwnCloudVersion' => false,
410
+                'canInstall' => true,
411
+                'preview' => isset($app['screenshots'][0]['url']) ? 'https://usercontent.apps.nextcloud.com/'.base64_encode($app['screenshots'][0]['url']) : '',
412
+                'score' => $app['ratingOverall'],
413
+                'ratingNumOverall' => $app['ratingNumOverall'],
414
+                'ratingNumThresholdReached' => $app['ratingNumOverall'] > 5,
415
+                'removable' => $existsLocally,
416
+                'active' => $this->appManager->isEnabledForUser($app['id']),
417
+                'needsDownload' => !$existsLocally,
418
+                'groups' => $groups,
419
+                'fromAppStore' => true,
420
+                'appstoreData' => $app,
421
+            ];
422
+        }
423
+
424
+        return $formattedApps;
425
+    }
426
+
427
+    /**
428
+     * @PasswordConfirmationRequired
429
+     *
430
+     * @param string $appId
431
+     * @param array $groups
432
+     * @return JSONResponse
433
+     */
434
+    public function enableApp(string $appId, array $groups = []): JSONResponse {
435
+        return $this->enableApps([$appId], $groups);
436
+    }
437
+
438
+    /**
439
+     * Enable one or more apps
440
+     *
441
+     * apps will be enabled for specific groups only if $groups is defined
442
+     *
443
+     * @PasswordConfirmationRequired
444
+     * @param array $appIds
445
+     * @param array $groups
446
+     * @return JSONResponse
447
+     */
448
+    public function enableApps(array $appIds, array $groups = []): JSONResponse {
449
+        try {
450
+            $updateRequired = false;
451
+
452
+            foreach ($appIds as $appId) {
453
+                $appId = OC_App::cleanAppId($appId);
454
+
455
+                // Check if app is already downloaded
456
+                /** @var Installer $installer */
457
+                $installer = \OC::$server->query(Installer::class);
458
+                $isDownloaded = $installer->isDownloaded($appId);
459
+
460
+                if(!$isDownloaded) {
461
+                    $installer->downloadApp($appId);
462
+                }
463
+
464
+                $installer->installApp($appId);
465
+
466
+                if (count($groups) > 0) {
467
+                    $this->appManager->enableAppForGroups($appId, $this->getGroupList($groups));
468
+                } else {
469
+                    $this->appManager->enableApp($appId);
470
+                }
471
+                if (\OC_App::shouldUpgrade($appId)) {
472
+                    $updateRequired = true;
473
+                }
474
+            }
475
+            return new JSONResponse(['data' => ['update_required' => $updateRequired]]);
476
+
477
+        } catch (\Exception $e) {
478
+            $this->logger->logException($e);
479
+            return new JSONResponse(['data' => ['message' => $e->getMessage()]], Http::STATUS_INTERNAL_SERVER_ERROR);
480
+        }
481
+    }
482
+
483
+    private function getGroupList(array $groups) {
484
+        $groupManager = \OC::$server->getGroupManager();
485
+        $groupsList = [];
486
+        foreach ($groups as $group) {
487
+            $groupItem = $groupManager->get($group);
488
+            if ($groupItem instanceof \OCP\IGroup) {
489
+                $groupsList[] = $groupManager->get($group);
490
+            }
491
+        }
492
+        return $groupsList;
493
+    }
494
+
495
+    /**
496
+     * @PasswordConfirmationRequired
497
+     *
498
+     * @param string $appId
499
+     * @return JSONResponse
500
+     */
501
+    public function disableApp(string $appId): JSONResponse {
502
+        return $this->disableApps([$appId]);
503
+    }
504
+
505
+    /**
506
+     * @PasswordConfirmationRequired
507
+     *
508
+     * @param array $appIds
509
+     * @return JSONResponse
510
+     */
511
+    public function disableApps(array $appIds): JSONResponse {
512
+        try {
513
+            foreach ($appIds as $appId) {
514
+                $appId = OC_App::cleanAppId($appId);
515
+                $this->appManager->disableApp($appId);
516
+            }
517
+            return new JSONResponse([]);
518
+        } catch (\Exception $e) {
519
+            $this->logger->logException($e);
520
+            return new JSONResponse(['data' => ['message' => $e->getMessage()]], Http::STATUS_INTERNAL_SERVER_ERROR);
521
+        }
522
+    }
523
+
524
+    /**
525
+     * @PasswordConfirmationRequired
526
+     *
527
+     * @param string $appId
528
+     * @return JSONResponse
529
+     */
530
+    public function uninstallApp(string $appId): JSONResponse {
531
+        $appId = OC_App::cleanAppId($appId);
532
+        $result = $this->installer->removeApp($appId);
533
+        if($result !== false) {
534
+            // FIXME: Clear the cache - move that into some sane helper method
535
+            \OC::$server->getMemCacheFactory()->createDistributed('settings')->remove('listApps-0');
536
+            \OC::$server->getMemCacheFactory()->createDistributed('settings')->remove('listApps-1');
537
+            return new JSONResponse(['data' => ['appid' => $appId]]);
538
+        }
539
+        return new JSONResponse(['data' => ['message' => $this->l10n->t('Couldn\'t remove app.')]], Http::STATUS_INTERNAL_SERVER_ERROR);
540
+    }
541
+
542
+    /**
543
+     * @param string $appId
544
+     * @return JSONResponse
545
+     */
546
+    public function updateApp(string $appId): JSONResponse {
547
+        $appId = OC_App::cleanAppId($appId);
548
+
549
+        $this->config->setSystemValue('maintenance', true);
550
+        try {
551
+            $result = $this->installer->updateAppstoreApp($appId);
552
+            $this->config->setSystemValue('maintenance', false);
553
+        } catch (\Exception $ex) {
554
+            $this->config->setSystemValue('maintenance', false);
555
+            return new JSONResponse(['data' => ['message' => $ex->getMessage()]], Http::STATUS_INTERNAL_SERVER_ERROR);
556
+        }
557
+
558
+        if ($result !== false) {
559
+            return new JSONResponse(['data' => ['appid' => $appId]]);
560
+        }
561
+        return new JSONResponse(['data' => ['message' => $this->l10n->t('Couldn\'t update app.')]], Http::STATUS_INTERNAL_SERVER_ERROR);
562
+    }
563
+
564
+    private function sortApps($a, $b) {
565
+        $a = (string)$a['name'];
566
+        $b = (string)$b['name'];
567
+        if ($a === $b) {
568
+            return 0;
569
+        }
570
+        return ($a < $b) ? -1 : 1;
571
+    }
572 572
 
573 573
 }
Please login to merge, or discard this patch.
lib/private/App/AppManager.php 1 patch
Indentation   +407 added lines, -407 removed lines patch added patch discarded remove patch
@@ -45,411 +45,411 @@
 block discarded – undo
45 45
 
46 46
 class AppManager implements IAppManager {
47 47
 
48
-	/**
49
-	 * Apps with these types can not be enabled for certain groups only
50
-	 * @var string[]
51
-	 */
52
-	protected $protectedAppTypes = [
53
-		'filesystem',
54
-		'prelogin',
55
-		'authentication',
56
-		'logging',
57
-		'prevent_group_restriction',
58
-	];
59
-
60
-	/** @var IUserSession */
61
-	private $userSession;
62
-
63
-	/** @var IConfig */
64
-	private $config;
65
-
66
-	/** @var IGroupManager */
67
-	private $groupManager;
68
-
69
-	/** @var ICacheFactory */
70
-	private $memCacheFactory;
71
-
72
-	/** @var EventDispatcherInterface */
73
-	private $dispatcher;
74
-
75
-	/** @var string[] $appId => $enabled */
76
-	private $installedAppsCache;
77
-
78
-	/** @var string[] */
79
-	private $shippedApps;
80
-
81
-	/** @var string[] */
82
-	private $alwaysEnabled;
83
-
84
-	/** @var array */
85
-	private $appInfos = [];
86
-
87
-	/** @var array */
88
-	private $appVersions = [];
89
-
90
-	/**
91
-	 * @param IUserSession $userSession
92
-	 * @param IConfig $config
93
-	 * @param IGroupManager $groupManager
94
-	 * @param ICacheFactory $memCacheFactory
95
-	 * @param EventDispatcherInterface $dispatcher
96
-	 */
97
-	public function __construct(IUserSession $userSession,
98
-								IConfig $config,
99
-								IGroupManager $groupManager,
100
-								ICacheFactory $memCacheFactory,
101
-								EventDispatcherInterface $dispatcher) {
102
-		$this->userSession = $userSession;
103
-		$this->config = $config;
104
-		$this->groupManager = $groupManager;
105
-		$this->memCacheFactory = $memCacheFactory;
106
-		$this->dispatcher = $dispatcher;
107
-	}
108
-
109
-	/**
110
-	 * @return string[] $appId => $enabled
111
-	 */
112
-	private function getInstalledAppsValues() {
113
-		if (!$this->installedAppsCache) {
114
-			$values = \OC::$server->getAppConfig()->getValues(false, 'enabled');
115
-
116
-			$alwaysEnabledApps = $this->getAlwaysEnabledApps();
117
-			foreach($alwaysEnabledApps as $appId) {
118
-				$values[$appId] = 'yes';
119
-			}
120
-
121
-			$this->installedAppsCache = array_filter($values, function ($value) {
122
-				return $value !== 'no';
123
-			});
124
-			ksort($this->installedAppsCache);
125
-		}
126
-		return $this->installedAppsCache;
127
-	}
128
-
129
-	/**
130
-	 * List all installed apps
131
-	 *
132
-	 * @return string[]
133
-	 */
134
-	public function getInstalledApps() {
135
-		return array_keys($this->getInstalledAppsValues());
136
-	}
137
-
138
-	/**
139
-	 * List all apps enabled for a user
140
-	 *
141
-	 * @param \OCP\IUser $user
142
-	 * @return string[]
143
-	 */
144
-	public function getEnabledAppsForUser(IUser $user) {
145
-		$apps = $this->getInstalledAppsValues();
146
-		$appsForUser = array_filter($apps, function ($enabled) use ($user) {
147
-			return $this->checkAppForUser($enabled, $user);
148
-		});
149
-		return array_keys($appsForUser);
150
-	}
151
-
152
-	/**
153
-	 * Check if an app is enabled for user
154
-	 *
155
-	 * @param string $appId
156
-	 * @param \OCP\IUser $user (optional) if not defined, the currently logged in user will be used
157
-	 * @return bool
158
-	 */
159
-	public function isEnabledForUser($appId, $user = null) {
160
-		if ($this->isAlwaysEnabled($appId)) {
161
-			return true;
162
-		}
163
-		if ($user === null) {
164
-			$user = $this->userSession->getUser();
165
-		}
166
-		$installedApps = $this->getInstalledAppsValues();
167
-		if (isset($installedApps[$appId])) {
168
-			return $this->checkAppForUser($installedApps[$appId], $user);
169
-		} else {
170
-			return false;
171
-		}
172
-	}
173
-
174
-	/**
175
-	 * @param string $enabled
176
-	 * @param IUser $user
177
-	 * @return bool
178
-	 */
179
-	private function checkAppForUser($enabled, $user) {
180
-		if ($enabled === 'yes') {
181
-			return true;
182
-		} elseif ($user === null) {
183
-			return false;
184
-		} else {
185
-			if(empty($enabled)){
186
-				return false;
187
-			}
188
-
189
-			$groupIds = json_decode($enabled);
190
-
191
-			if (!is_array($groupIds)) {
192
-				$jsonError = json_last_error();
193
-				\OC::$server->getLogger()->warning('AppManger::checkAppForUser - can\'t decode group IDs: ' . print_r($enabled, true) . ' - json error code: ' . $jsonError, ['app' => 'lib']);
194
-				return false;
195
-			}
196
-
197
-			$userGroups = $this->groupManager->getUserGroupIds($user);
198
-			foreach ($userGroups as $groupId) {
199
-				if (in_array($groupId, $groupIds, true)) {
200
-					return true;
201
-				}
202
-			}
203
-			return false;
204
-		}
205
-	}
206
-
207
-	/**
208
-	 * Check if an app is enabled in the instance
209
-	 *
210
-	 * Notice: This actually checks if the app is enabled and not only if it is installed.
211
-	 *
212
-	 * @param string $appId
213
-	 * @return bool
214
-	 */
215
-	public function isInstalled($appId) {
216
-		$installedApps = $this->getInstalledAppsValues();
217
-		return isset($installedApps[$appId]);
218
-	}
219
-
220
-	/**
221
-	 * Enable an app for every user
222
-	 *
223
-	 * @param string $appId
224
-	 * @throws AppPathNotFoundException
225
-	 */
226
-	public function enableApp($appId) {
227
-		// Check if app exists
228
-		$this->getAppPath($appId);
229
-
230
-		$this->installedAppsCache[$appId] = 'yes';
231
-		$this->config->setAppValue($appId, 'enabled', 'yes');
232
-		$this->dispatcher->dispatch(ManagerEvent::EVENT_APP_ENABLE, new ManagerEvent(
233
-			ManagerEvent::EVENT_APP_ENABLE, $appId
234
-		));
235
-		$this->clearAppsCache();
236
-	}
237
-
238
-	/**
239
-	 * Whether a list of types contains a protected app type
240
-	 *
241
-	 * @param string[] $types
242
-	 * @return bool
243
-	 */
244
-	public function hasProtectedAppType($types) {
245
-		if (empty($types)) {
246
-			return false;
247
-		}
248
-
249
-		$protectedTypes = array_intersect($this->protectedAppTypes, $types);
250
-		return !empty($protectedTypes);
251
-	}
252
-
253
-	/**
254
-	 * Enable an app only for specific groups
255
-	 *
256
-	 * @param string $appId
257
-	 * @param \OCP\IGroup[] $groups
258
-	 * @throws \Exception if app can't be enabled for groups
259
-	 */
260
-	public function enableAppForGroups($appId, $groups) {
261
-		$info = $this->getAppInfo($appId);
262
-		if (!empty($info['types'])) {
263
-			$protectedTypes = array_intersect($this->protectedAppTypes, $info['types']);
264
-			if (!empty($protectedTypes)) {
265
-				throw new \Exception("$appId can't be enabled for groups.");
266
-			}
267
-		}
268
-
269
-		$groupIds = array_map(function ($group) {
270
-			/** @var \OCP\IGroup $group */
271
-			return $group->getGID();
272
-		}, $groups);
273
-		$this->installedAppsCache[$appId] = json_encode($groupIds);
274
-		$this->config->setAppValue($appId, 'enabled', json_encode($groupIds));
275
-		$this->dispatcher->dispatch(ManagerEvent::EVENT_APP_ENABLE_FOR_GROUPS, new ManagerEvent(
276
-			ManagerEvent::EVENT_APP_ENABLE_FOR_GROUPS, $appId, $groups
277
-		));
278
-		$this->clearAppsCache();
279
-	}
280
-
281
-	/**
282
-	 * Disable an app for every user
283
-	 *
284
-	 * @param string $appId
285
-	 * @throws \Exception if app can't be disabled
286
-	 */
287
-	public function disableApp($appId) {
288
-		if ($this->isAlwaysEnabled($appId)) {
289
-			throw new \Exception("$appId can't be disabled.");
290
-		}
291
-		unset($this->installedAppsCache[$appId]);
292
-		$this->config->setAppValue($appId, 'enabled', 'no');
293
-		$this->dispatcher->dispatch(ManagerEvent::EVENT_APP_DISABLE, new ManagerEvent(
294
-			ManagerEvent::EVENT_APP_DISABLE, $appId
295
-		));
296
-		$this->clearAppsCache();
297
-	}
298
-
299
-	/**
300
-	 * Get the directory for the given app.
301
-	 *
302
-	 * @param string $appId
303
-	 * @return string
304
-	 * @throws AppPathNotFoundException if app folder can't be found
305
-	 */
306
-	public function getAppPath($appId) {
307
-		$appPath = \OC_App::getAppPath($appId);
308
-		if($appPath === false) {
309
-			throw new AppPathNotFoundException('Could not find path for ' . $appId);
310
-		}
311
-		return $appPath;
312
-	}
313
-
314
-	/**
315
-	 * Clear the cached list of apps when enabling/disabling an app
316
-	 */
317
-	public function clearAppsCache() {
318
-		$settingsMemCache = $this->memCacheFactory->createDistributed('settings');
319
-		$settingsMemCache->clear('listApps');
320
-		$this->appInfos = [];
321
-	}
322
-
323
-	/**
324
-	 * Returns a list of apps that need upgrade
325
-	 *
326
-	 * @param string $version Nextcloud version as array of version components
327
-	 * @return array list of app info from apps that need an upgrade
328
-	 *
329
-	 * @internal
330
-	 */
331
-	public function getAppsNeedingUpgrade($version) {
332
-		$appsToUpgrade = [];
333
-		$apps = $this->getInstalledApps();
334
-		foreach ($apps as $appId) {
335
-			$appInfo = $this->getAppInfo($appId);
336
-			$appDbVersion = $this->config->getAppValue($appId, 'installed_version', '0.0.0');
337
-			if ($appDbVersion
338
-				&& isset($appInfo['version'])
339
-				&& version_compare($appInfo['version'], $appDbVersion, '>')
340
-				&& \OC_App::isAppCompatible($version, $appInfo)
341
-			) {
342
-				$appsToUpgrade[] = $appInfo;
343
-			}
344
-		}
345
-
346
-		return $appsToUpgrade;
347
-	}
348
-
349
-	/**
350
-	 * Returns the app information from "appinfo/info.xml".
351
-	 *
352
-	 * @param string $appId app id
353
-	 *
354
-	 * @param bool $path
355
-	 * @param null $lang
356
-	 * @return array|null app info
357
-	 */
358
-	public function getAppInfo(string $appId, bool $path = false, $lang = null) {
359
-		if ($path) {
360
-			$file = $appId;
361
-		} else {
362
-			if ($lang === null && isset($this->appInfos[$appId])) {
363
-				return $this->appInfos[$appId];
364
-			}
365
-			try {
366
-				$appPath = $this->getAppPath($appId);
367
-			} catch (AppPathNotFoundException $e) {
368
-				return null;
369
-			}
370
-			$file = $appPath . '/appinfo/info.xml';
371
-		}
372
-
373
-		$parser = new InfoParser($this->memCacheFactory->createLocal('core.appinfo'));
374
-		$data = $parser->parse($file);
375
-
376
-		if (is_array($data)) {
377
-			$data = \OC_App::parseAppInfo($data, $lang);
378
-		}
379
-
380
-		if ($lang === null) {
381
-			$this->appInfos[$appId] = $data;
382
-		}
383
-
384
-		return $data;
385
-	}
386
-
387
-	public function getAppVersion(string $appId, bool $useCache = true): string {
388
-		if(!$useCache || !isset($this->appVersions[$appId])) {
389
-			$appInfo = \OC::$server->getAppManager()->getAppInfo($appId);
390
-			$this->appVersions[$appId] = ($appInfo !== null && isset($appInfo['version'])) ? $appInfo['version'] : '0';
391
-		}
392
-		return $this->appVersions[$appId];
393
-	}
394
-
395
-	/**
396
-	 * Returns a list of apps incompatible with the given version
397
-	 *
398
-	 * @param string $version Nextcloud version as array of version components
399
-	 *
400
-	 * @return array list of app info from incompatible apps
401
-	 *
402
-	 * @internal
403
-	 */
404
-	public function getIncompatibleApps(string $version): array {
405
-		$apps = $this->getInstalledApps();
406
-		$incompatibleApps = array();
407
-		foreach ($apps as $appId) {
408
-			$info = $this->getAppInfo($appId);
409
-			if ($info === null) {
410
-				$incompatibleApps[] = ['id' => $appId];
411
-			} else if (!\OC_App::isAppCompatible($version, $info)) {
412
-				$incompatibleApps[] = $info;
413
-			}
414
-		}
415
-		return $incompatibleApps;
416
-	}
417
-
418
-	/**
419
-	 * @inheritdoc
420
-	 * In case you change this method, also change \OC\App\CodeChecker\InfoChecker::isShipped()
421
-	 */
422
-	public function isShipped($appId) {
423
-		$this->loadShippedJson();
424
-		return in_array($appId, $this->shippedApps, true);
425
-	}
426
-
427
-	private function isAlwaysEnabled($appId) {
428
-		$alwaysEnabled = $this->getAlwaysEnabledApps();
429
-		return in_array($appId, $alwaysEnabled, true);
430
-	}
431
-
432
-	/**
433
-	 * In case you change this method, also change \OC\App\CodeChecker\InfoChecker::loadShippedJson()
434
-	 * @throws \Exception
435
-	 */
436
-	private function loadShippedJson() {
437
-		if ($this->shippedApps === null) {
438
-			$shippedJson = \OC::$SERVERROOT . '/core/shipped.json';
439
-			if (!file_exists($shippedJson)) {
440
-				throw new \Exception("File not found: $shippedJson");
441
-			}
442
-			$content = json_decode(file_get_contents($shippedJson), true);
443
-			$this->shippedApps = $content['shippedApps'];
444
-			$this->alwaysEnabled = $content['alwaysEnabled'];
445
-		}
446
-	}
447
-
448
-	/**
449
-	 * @inheritdoc
450
-	 */
451
-	public function getAlwaysEnabledApps() {
452
-		$this->loadShippedJson();
453
-		return $this->alwaysEnabled;
454
-	}
48
+    /**
49
+     * Apps with these types can not be enabled for certain groups only
50
+     * @var string[]
51
+     */
52
+    protected $protectedAppTypes = [
53
+        'filesystem',
54
+        'prelogin',
55
+        'authentication',
56
+        'logging',
57
+        'prevent_group_restriction',
58
+    ];
59
+
60
+    /** @var IUserSession */
61
+    private $userSession;
62
+
63
+    /** @var IConfig */
64
+    private $config;
65
+
66
+    /** @var IGroupManager */
67
+    private $groupManager;
68
+
69
+    /** @var ICacheFactory */
70
+    private $memCacheFactory;
71
+
72
+    /** @var EventDispatcherInterface */
73
+    private $dispatcher;
74
+
75
+    /** @var string[] $appId => $enabled */
76
+    private $installedAppsCache;
77
+
78
+    /** @var string[] */
79
+    private $shippedApps;
80
+
81
+    /** @var string[] */
82
+    private $alwaysEnabled;
83
+
84
+    /** @var array */
85
+    private $appInfos = [];
86
+
87
+    /** @var array */
88
+    private $appVersions = [];
89
+
90
+    /**
91
+     * @param IUserSession $userSession
92
+     * @param IConfig $config
93
+     * @param IGroupManager $groupManager
94
+     * @param ICacheFactory $memCacheFactory
95
+     * @param EventDispatcherInterface $dispatcher
96
+     */
97
+    public function __construct(IUserSession $userSession,
98
+                                IConfig $config,
99
+                                IGroupManager $groupManager,
100
+                                ICacheFactory $memCacheFactory,
101
+                                EventDispatcherInterface $dispatcher) {
102
+        $this->userSession = $userSession;
103
+        $this->config = $config;
104
+        $this->groupManager = $groupManager;
105
+        $this->memCacheFactory = $memCacheFactory;
106
+        $this->dispatcher = $dispatcher;
107
+    }
108
+
109
+    /**
110
+     * @return string[] $appId => $enabled
111
+     */
112
+    private function getInstalledAppsValues() {
113
+        if (!$this->installedAppsCache) {
114
+            $values = \OC::$server->getAppConfig()->getValues(false, 'enabled');
115
+
116
+            $alwaysEnabledApps = $this->getAlwaysEnabledApps();
117
+            foreach($alwaysEnabledApps as $appId) {
118
+                $values[$appId] = 'yes';
119
+            }
120
+
121
+            $this->installedAppsCache = array_filter($values, function ($value) {
122
+                return $value !== 'no';
123
+            });
124
+            ksort($this->installedAppsCache);
125
+        }
126
+        return $this->installedAppsCache;
127
+    }
128
+
129
+    /**
130
+     * List all installed apps
131
+     *
132
+     * @return string[]
133
+     */
134
+    public function getInstalledApps() {
135
+        return array_keys($this->getInstalledAppsValues());
136
+    }
137
+
138
+    /**
139
+     * List all apps enabled for a user
140
+     *
141
+     * @param \OCP\IUser $user
142
+     * @return string[]
143
+     */
144
+    public function getEnabledAppsForUser(IUser $user) {
145
+        $apps = $this->getInstalledAppsValues();
146
+        $appsForUser = array_filter($apps, function ($enabled) use ($user) {
147
+            return $this->checkAppForUser($enabled, $user);
148
+        });
149
+        return array_keys($appsForUser);
150
+    }
151
+
152
+    /**
153
+     * Check if an app is enabled for user
154
+     *
155
+     * @param string $appId
156
+     * @param \OCP\IUser $user (optional) if not defined, the currently logged in user will be used
157
+     * @return bool
158
+     */
159
+    public function isEnabledForUser($appId, $user = null) {
160
+        if ($this->isAlwaysEnabled($appId)) {
161
+            return true;
162
+        }
163
+        if ($user === null) {
164
+            $user = $this->userSession->getUser();
165
+        }
166
+        $installedApps = $this->getInstalledAppsValues();
167
+        if (isset($installedApps[$appId])) {
168
+            return $this->checkAppForUser($installedApps[$appId], $user);
169
+        } else {
170
+            return false;
171
+        }
172
+    }
173
+
174
+    /**
175
+     * @param string $enabled
176
+     * @param IUser $user
177
+     * @return bool
178
+     */
179
+    private function checkAppForUser($enabled, $user) {
180
+        if ($enabled === 'yes') {
181
+            return true;
182
+        } elseif ($user === null) {
183
+            return false;
184
+        } else {
185
+            if(empty($enabled)){
186
+                return false;
187
+            }
188
+
189
+            $groupIds = json_decode($enabled);
190
+
191
+            if (!is_array($groupIds)) {
192
+                $jsonError = json_last_error();
193
+                \OC::$server->getLogger()->warning('AppManger::checkAppForUser - can\'t decode group IDs: ' . print_r($enabled, true) . ' - json error code: ' . $jsonError, ['app' => 'lib']);
194
+                return false;
195
+            }
196
+
197
+            $userGroups = $this->groupManager->getUserGroupIds($user);
198
+            foreach ($userGroups as $groupId) {
199
+                if (in_array($groupId, $groupIds, true)) {
200
+                    return true;
201
+                }
202
+            }
203
+            return false;
204
+        }
205
+    }
206
+
207
+    /**
208
+     * Check if an app is enabled in the instance
209
+     *
210
+     * Notice: This actually checks if the app is enabled and not only if it is installed.
211
+     *
212
+     * @param string $appId
213
+     * @return bool
214
+     */
215
+    public function isInstalled($appId) {
216
+        $installedApps = $this->getInstalledAppsValues();
217
+        return isset($installedApps[$appId]);
218
+    }
219
+
220
+    /**
221
+     * Enable an app for every user
222
+     *
223
+     * @param string $appId
224
+     * @throws AppPathNotFoundException
225
+     */
226
+    public function enableApp($appId) {
227
+        // Check if app exists
228
+        $this->getAppPath($appId);
229
+
230
+        $this->installedAppsCache[$appId] = 'yes';
231
+        $this->config->setAppValue($appId, 'enabled', 'yes');
232
+        $this->dispatcher->dispatch(ManagerEvent::EVENT_APP_ENABLE, new ManagerEvent(
233
+            ManagerEvent::EVENT_APP_ENABLE, $appId
234
+        ));
235
+        $this->clearAppsCache();
236
+    }
237
+
238
+    /**
239
+     * Whether a list of types contains a protected app type
240
+     *
241
+     * @param string[] $types
242
+     * @return bool
243
+     */
244
+    public function hasProtectedAppType($types) {
245
+        if (empty($types)) {
246
+            return false;
247
+        }
248
+
249
+        $protectedTypes = array_intersect($this->protectedAppTypes, $types);
250
+        return !empty($protectedTypes);
251
+    }
252
+
253
+    /**
254
+     * Enable an app only for specific groups
255
+     *
256
+     * @param string $appId
257
+     * @param \OCP\IGroup[] $groups
258
+     * @throws \Exception if app can't be enabled for groups
259
+     */
260
+    public function enableAppForGroups($appId, $groups) {
261
+        $info = $this->getAppInfo($appId);
262
+        if (!empty($info['types'])) {
263
+            $protectedTypes = array_intersect($this->protectedAppTypes, $info['types']);
264
+            if (!empty($protectedTypes)) {
265
+                throw new \Exception("$appId can't be enabled for groups.");
266
+            }
267
+        }
268
+
269
+        $groupIds = array_map(function ($group) {
270
+            /** @var \OCP\IGroup $group */
271
+            return $group->getGID();
272
+        }, $groups);
273
+        $this->installedAppsCache[$appId] = json_encode($groupIds);
274
+        $this->config->setAppValue($appId, 'enabled', json_encode($groupIds));
275
+        $this->dispatcher->dispatch(ManagerEvent::EVENT_APP_ENABLE_FOR_GROUPS, new ManagerEvent(
276
+            ManagerEvent::EVENT_APP_ENABLE_FOR_GROUPS, $appId, $groups
277
+        ));
278
+        $this->clearAppsCache();
279
+    }
280
+
281
+    /**
282
+     * Disable an app for every user
283
+     *
284
+     * @param string $appId
285
+     * @throws \Exception if app can't be disabled
286
+     */
287
+    public function disableApp($appId) {
288
+        if ($this->isAlwaysEnabled($appId)) {
289
+            throw new \Exception("$appId can't be disabled.");
290
+        }
291
+        unset($this->installedAppsCache[$appId]);
292
+        $this->config->setAppValue($appId, 'enabled', 'no');
293
+        $this->dispatcher->dispatch(ManagerEvent::EVENT_APP_DISABLE, new ManagerEvent(
294
+            ManagerEvent::EVENT_APP_DISABLE, $appId
295
+        ));
296
+        $this->clearAppsCache();
297
+    }
298
+
299
+    /**
300
+     * Get the directory for the given app.
301
+     *
302
+     * @param string $appId
303
+     * @return string
304
+     * @throws AppPathNotFoundException if app folder can't be found
305
+     */
306
+    public function getAppPath($appId) {
307
+        $appPath = \OC_App::getAppPath($appId);
308
+        if($appPath === false) {
309
+            throw new AppPathNotFoundException('Could not find path for ' . $appId);
310
+        }
311
+        return $appPath;
312
+    }
313
+
314
+    /**
315
+     * Clear the cached list of apps when enabling/disabling an app
316
+     */
317
+    public function clearAppsCache() {
318
+        $settingsMemCache = $this->memCacheFactory->createDistributed('settings');
319
+        $settingsMemCache->clear('listApps');
320
+        $this->appInfos = [];
321
+    }
322
+
323
+    /**
324
+     * Returns a list of apps that need upgrade
325
+     *
326
+     * @param string $version Nextcloud version as array of version components
327
+     * @return array list of app info from apps that need an upgrade
328
+     *
329
+     * @internal
330
+     */
331
+    public function getAppsNeedingUpgrade($version) {
332
+        $appsToUpgrade = [];
333
+        $apps = $this->getInstalledApps();
334
+        foreach ($apps as $appId) {
335
+            $appInfo = $this->getAppInfo($appId);
336
+            $appDbVersion = $this->config->getAppValue($appId, 'installed_version', '0.0.0');
337
+            if ($appDbVersion
338
+                && isset($appInfo['version'])
339
+                && version_compare($appInfo['version'], $appDbVersion, '>')
340
+                && \OC_App::isAppCompatible($version, $appInfo)
341
+            ) {
342
+                $appsToUpgrade[] = $appInfo;
343
+            }
344
+        }
345
+
346
+        return $appsToUpgrade;
347
+    }
348
+
349
+    /**
350
+     * Returns the app information from "appinfo/info.xml".
351
+     *
352
+     * @param string $appId app id
353
+     *
354
+     * @param bool $path
355
+     * @param null $lang
356
+     * @return array|null app info
357
+     */
358
+    public function getAppInfo(string $appId, bool $path = false, $lang = null) {
359
+        if ($path) {
360
+            $file = $appId;
361
+        } else {
362
+            if ($lang === null && isset($this->appInfos[$appId])) {
363
+                return $this->appInfos[$appId];
364
+            }
365
+            try {
366
+                $appPath = $this->getAppPath($appId);
367
+            } catch (AppPathNotFoundException $e) {
368
+                return null;
369
+            }
370
+            $file = $appPath . '/appinfo/info.xml';
371
+        }
372
+
373
+        $parser = new InfoParser($this->memCacheFactory->createLocal('core.appinfo'));
374
+        $data = $parser->parse($file);
375
+
376
+        if (is_array($data)) {
377
+            $data = \OC_App::parseAppInfo($data, $lang);
378
+        }
379
+
380
+        if ($lang === null) {
381
+            $this->appInfos[$appId] = $data;
382
+        }
383
+
384
+        return $data;
385
+    }
386
+
387
+    public function getAppVersion(string $appId, bool $useCache = true): string {
388
+        if(!$useCache || !isset($this->appVersions[$appId])) {
389
+            $appInfo = \OC::$server->getAppManager()->getAppInfo($appId);
390
+            $this->appVersions[$appId] = ($appInfo !== null && isset($appInfo['version'])) ? $appInfo['version'] : '0';
391
+        }
392
+        return $this->appVersions[$appId];
393
+    }
394
+
395
+    /**
396
+     * Returns a list of apps incompatible with the given version
397
+     *
398
+     * @param string $version Nextcloud version as array of version components
399
+     *
400
+     * @return array list of app info from incompatible apps
401
+     *
402
+     * @internal
403
+     */
404
+    public function getIncompatibleApps(string $version): array {
405
+        $apps = $this->getInstalledApps();
406
+        $incompatibleApps = array();
407
+        foreach ($apps as $appId) {
408
+            $info = $this->getAppInfo($appId);
409
+            if ($info === null) {
410
+                $incompatibleApps[] = ['id' => $appId];
411
+            } else if (!\OC_App::isAppCompatible($version, $info)) {
412
+                $incompatibleApps[] = $info;
413
+            }
414
+        }
415
+        return $incompatibleApps;
416
+    }
417
+
418
+    /**
419
+     * @inheritdoc
420
+     * In case you change this method, also change \OC\App\CodeChecker\InfoChecker::isShipped()
421
+     */
422
+    public function isShipped($appId) {
423
+        $this->loadShippedJson();
424
+        return in_array($appId, $this->shippedApps, true);
425
+    }
426
+
427
+    private function isAlwaysEnabled($appId) {
428
+        $alwaysEnabled = $this->getAlwaysEnabledApps();
429
+        return in_array($appId, $alwaysEnabled, true);
430
+    }
431
+
432
+    /**
433
+     * In case you change this method, also change \OC\App\CodeChecker\InfoChecker::loadShippedJson()
434
+     * @throws \Exception
435
+     */
436
+    private function loadShippedJson() {
437
+        if ($this->shippedApps === null) {
438
+            $shippedJson = \OC::$SERVERROOT . '/core/shipped.json';
439
+            if (!file_exists($shippedJson)) {
440
+                throw new \Exception("File not found: $shippedJson");
441
+            }
442
+            $content = json_decode(file_get_contents($shippedJson), true);
443
+            $this->shippedApps = $content['shippedApps'];
444
+            $this->alwaysEnabled = $content['alwaysEnabled'];
445
+        }
446
+    }
447
+
448
+    /**
449
+     * @inheritdoc
450
+     */
451
+    public function getAlwaysEnabledApps() {
452
+        $this->loadShippedJson();
453
+        return $this->alwaysEnabled;
454
+    }
455 455
 }
Please login to merge, or discard this patch.
lib/private/legacy/app.php 1 patch
Indentation   +1035 added lines, -1035 removed lines patch added patch discarded remove patch
@@ -64,1039 +64,1039 @@
 block discarded – undo
64 64
  * upgrading and removing apps.
65 65
  */
66 66
 class OC_App {
67
-	static private $adminForms = [];
68
-	static private $personalForms = [];
69
-	static private $appTypes = [];
70
-	static private $loadedApps = [];
71
-	static private $altLogin = [];
72
-	static private $alreadyRegistered = [];
73
-	const officialApp = 200;
74
-
75
-	/**
76
-	 * clean the appId
77
-	 *
78
-	 * @param string $app AppId that needs to be cleaned
79
-	 * @return string
80
-	 */
81
-	public static function cleanAppId(string $app): string {
82
-		return str_replace(array('\0', '/', '\\', '..'), '', $app);
83
-	}
84
-
85
-	/**
86
-	 * Check if an app is loaded
87
-	 *
88
-	 * @param string $app
89
-	 * @return bool
90
-	 */
91
-	public static function isAppLoaded(string $app): bool {
92
-		return in_array($app, self::$loadedApps, true);
93
-	}
94
-
95
-	/**
96
-	 * loads all apps
97
-	 *
98
-	 * @param string[] $types
99
-	 * @return bool
100
-	 *
101
-	 * This function walks through the ownCloud directory and loads all apps
102
-	 * it can find. A directory contains an app if the file /appinfo/info.xml
103
-	 * exists.
104
-	 *
105
-	 * if $types is set to non-empty array, only apps of those types will be loaded
106
-	 */
107
-	public static function loadApps(array $types = []): bool {
108
-		if (\OC::$server->getSystemConfig()->getValue('maintenance', false)) {
109
-			return false;
110
-		}
111
-		// Load the enabled apps here
112
-		$apps = self::getEnabledApps();
113
-
114
-		// Add each apps' folder as allowed class path
115
-		foreach($apps as $app) {
116
-			$path = self::getAppPath($app);
117
-			if($path !== false) {
118
-				self::registerAutoloading($app, $path);
119
-			}
120
-		}
121
-
122
-		// prevent app.php from printing output
123
-		ob_start();
124
-		foreach ($apps as $app) {
125
-			if (($types === [] or self::isType($app, $types)) && !in_array($app, self::$loadedApps)) {
126
-				self::loadApp($app);
127
-			}
128
-		}
129
-		ob_end_clean();
130
-
131
-		return true;
132
-	}
133
-
134
-	/**
135
-	 * load a single app
136
-	 *
137
-	 * @param string $app
138
-	 * @throws Exception
139
-	 */
140
-	public static function loadApp(string $app) {
141
-		self::$loadedApps[] = $app;
142
-		$appPath = self::getAppPath($app);
143
-		if($appPath === false) {
144
-			return;
145
-		}
146
-
147
-		// in case someone calls loadApp() directly
148
-		self::registerAutoloading($app, $appPath);
149
-
150
-		if (is_file($appPath . '/appinfo/app.php')) {
151
-			\OC::$server->getEventLogger()->start('load_app_' . $app, 'Load app: ' . $app);
152
-			try {
153
-				self::requireAppFile($app);
154
-			} catch (Error $ex) {
155
-				\OC::$server->getLogger()->logException($ex);
156
-				if (!\OC::$server->getAppManager()->isShipped($app)) {
157
-					// Only disable apps which are not shipped
158
-					\OC::$server->getAppManager()->disableApp($app);
159
-				}
160
-			}
161
-			\OC::$server->getEventLogger()->end('load_app_' . $app);
162
-		}
163
-
164
-		$info = self::getAppInfo($app);
165
-		if (!empty($info['activity']['filters'])) {
166
-			foreach ($info['activity']['filters'] as $filter) {
167
-				\OC::$server->getActivityManager()->registerFilter($filter);
168
-			}
169
-		}
170
-		if (!empty($info['activity']['settings'])) {
171
-			foreach ($info['activity']['settings'] as $setting) {
172
-				\OC::$server->getActivityManager()->registerSetting($setting);
173
-			}
174
-		}
175
-		if (!empty($info['activity']['providers'])) {
176
-			foreach ($info['activity']['providers'] as $provider) {
177
-				\OC::$server->getActivityManager()->registerProvider($provider);
178
-			}
179
-		}
180
-
181
-		if (!empty($info['settings']['admin'])) {
182
-			foreach ($info['settings']['admin'] as $setting) {
183
-				\OC::$server->getSettingsManager()->registerSetting('admin', $setting);
184
-			}
185
-		}
186
-		if (!empty($info['settings']['admin-section'])) {
187
-			foreach ($info['settings']['admin-section'] as $section) {
188
-				\OC::$server->getSettingsManager()->registerSection('admin', $section);
189
-			}
190
-		}
191
-		if (!empty($info['settings']['personal'])) {
192
-			foreach ($info['settings']['personal'] as $setting) {
193
-				\OC::$server->getSettingsManager()->registerSetting('personal', $setting);
194
-			}
195
-		}
196
-		if (!empty($info['settings']['personal-section'])) {
197
-			foreach ($info['settings']['personal-section'] as $section) {
198
-				\OC::$server->getSettingsManager()->registerSection('personal', $section);
199
-			}
200
-		}
201
-
202
-		if (!empty($info['collaboration']['plugins'])) {
203
-			// deal with one or many plugin entries
204
-			$plugins = isset($info['collaboration']['plugins']['plugin']['@value']) ?
205
-				[$info['collaboration']['plugins']['plugin']] : $info['collaboration']['plugins']['plugin'];
206
-			foreach ($plugins as $plugin) {
207
-				if($plugin['@attributes']['type'] === 'collaborator-search') {
208
-					$pluginInfo = [
209
-						'shareType' => $plugin['@attributes']['share-type'],
210
-						'class' => $plugin['@value'],
211
-					];
212
-					\OC::$server->getCollaboratorSearch()->registerPlugin($pluginInfo);
213
-				} else if ($plugin['@attributes']['type'] === 'autocomplete-sort') {
214
-					\OC::$server->getAutoCompleteManager()->registerSorter($plugin['@value']);
215
-				}
216
-			}
217
-		}
218
-	}
219
-
220
-	/**
221
-	 * @internal
222
-	 * @param string $app
223
-	 * @param string $path
224
-	 */
225
-	public static function registerAutoloading(string $app, string $path) {
226
-		$key = $app . '-' . $path;
227
-		if(isset(self::$alreadyRegistered[$key])) {
228
-			return;
229
-		}
230
-
231
-		self::$alreadyRegistered[$key] = true;
232
-
233
-		// Register on PSR-4 composer autoloader
234
-		$appNamespace = \OC\AppFramework\App::buildAppNamespace($app);
235
-		\OC::$server->registerNamespace($app, $appNamespace);
236
-
237
-		if (file_exists($path . '/composer/autoload.php')) {
238
-			require_once $path . '/composer/autoload.php';
239
-		} else {
240
-			\OC::$composerAutoloader->addPsr4($appNamespace . '\\', $path . '/lib/', true);
241
-			// Register on legacy autoloader
242
-			\OC::$loader->addValidRoot($path);
243
-		}
244
-
245
-		// Register Test namespace only when testing
246
-		if (defined('PHPUNIT_RUN') || defined('CLI_TEST_RUN')) {
247
-			\OC::$composerAutoloader->addPsr4($appNamespace . '\\Tests\\', $path . '/tests/', true);
248
-		}
249
-	}
250
-
251
-	/**
252
-	 * Load app.php from the given app
253
-	 *
254
-	 * @param string $app app name
255
-	 * @throws Error
256
-	 */
257
-	private static function requireAppFile(string $app) {
258
-		// encapsulated here to avoid variable scope conflicts
259
-		require_once $app . '/appinfo/app.php';
260
-	}
261
-
262
-	/**
263
-	 * check if an app is of a specific type
264
-	 *
265
-	 * @param string $app
266
-	 * @param array $types
267
-	 * @return bool
268
-	 */
269
-	public static function isType(string $app, array $types): bool {
270
-		$appTypes = self::getAppTypes($app);
271
-		foreach ($types as $type) {
272
-			if (array_search($type, $appTypes) !== false) {
273
-				return true;
274
-			}
275
-		}
276
-		return false;
277
-	}
278
-
279
-	/**
280
-	 * get the types of an app
281
-	 *
282
-	 * @param string $app
283
-	 * @return array
284
-	 */
285
-	private static function getAppTypes(string $app): array {
286
-		//load the cache
287
-		if (count(self::$appTypes) == 0) {
288
-			self::$appTypes = \OC::$server->getAppConfig()->getValues(false, 'types');
289
-		}
290
-
291
-		if (isset(self::$appTypes[$app])) {
292
-			return explode(',', self::$appTypes[$app]);
293
-		}
294
-
295
-		return [];
296
-	}
297
-
298
-	/**
299
-	 * read app types from info.xml and cache them in the database
300
-	 */
301
-	public static function setAppTypes(string $app) {
302
-		$appManager = \OC::$server->getAppManager();
303
-		$appData = $appManager->getAppInfo($app);
304
-		if(!is_array($appData)) {
305
-			return;
306
-		}
307
-
308
-		if (isset($appData['types'])) {
309
-			$appTypes = implode(',', $appData['types']);
310
-		} else {
311
-			$appTypes = '';
312
-			$appData['types'] = [];
313
-		}
314
-
315
-		$config = \OC::$server->getConfig();
316
-		$config->setAppValue($app, 'types', $appTypes);
317
-
318
-		if ($appManager->hasProtectedAppType($appData['types'])) {
319
-			$enabled = $config->getAppValue($app, 'enabled', 'yes');
320
-			if ($enabled !== 'yes' && $enabled !== 'no') {
321
-				$config->setAppValue($app, 'enabled', 'yes');
322
-			}
323
-		}
324
-	}
325
-
326
-	/**
327
-	 * Returns apps enabled for the current user.
328
-	 *
329
-	 * @param bool $forceRefresh whether to refresh the cache
330
-	 * @param bool $all whether to return apps for all users, not only the
331
-	 * currently logged in one
332
-	 * @return string[]
333
-	 */
334
-	public static function getEnabledApps(bool $forceRefresh = false, bool $all = false): array {
335
-		if (!\OC::$server->getSystemConfig()->getValue('installed', false)) {
336
-			return [];
337
-		}
338
-		// in incognito mode or when logged out, $user will be false,
339
-		// which is also the case during an upgrade
340
-		$appManager = \OC::$server->getAppManager();
341
-		if ($all) {
342
-			$user = null;
343
-		} else {
344
-			$user = \OC::$server->getUserSession()->getUser();
345
-		}
346
-
347
-		if (is_null($user)) {
348
-			$apps = $appManager->getInstalledApps();
349
-		} else {
350
-			$apps = $appManager->getEnabledAppsForUser($user);
351
-		}
352
-		$apps = array_filter($apps, function ($app) {
353
-			return $app !== 'files';//we add this manually
354
-		});
355
-		sort($apps);
356
-		array_unshift($apps, 'files');
357
-		return $apps;
358
-	}
359
-
360
-	/**
361
-	 * checks whether or not an app is enabled
362
-	 *
363
-	 * @param string $app app
364
-	 * @return bool
365
-	 * @deprecated 13.0.0 use \OC::$server->getAppManager()->isEnabledForUser($appId)
366
-	 *
367
-	 * This function checks whether or not an app is enabled.
368
-	 */
369
-	public static function isEnabled(string $app): bool {
370
-		return \OC::$server->getAppManager()->isEnabledForUser($app);
371
-	}
372
-
373
-	/**
374
-	 * enables an app
375
-	 *
376
-	 * @param string $appId
377
-	 * @param array $groups (optional) when set, only these groups will have access to the app
378
-	 * @throws \Exception
379
-	 * @return void
380
-	 *
381
-	 * This function set an app as enabled in appconfig.
382
-	 */
383
-	public function enable(string $appId,
384
-						   array $groups = []) {
385
-
386
-		// Check if app is already downloaded
387
-		/** @var Installer $installer */
388
-		$installer = \OC::$server->query(Installer::class);
389
-		$isDownloaded = $installer->isDownloaded($appId);
390
-
391
-		if(!$isDownloaded) {
392
-			$installer->downloadApp($appId);
393
-		}
394
-
395
-		$installer->installApp($appId);
396
-
397
-		$appManager = \OC::$server->getAppManager();
398
-		if ($groups !== []) {
399
-			$groupManager = \OC::$server->getGroupManager();
400
-			$groupsList = [];
401
-			foreach ($groups as $group) {
402
-				$groupItem = $groupManager->get($group);
403
-				if ($groupItem instanceof \OCP\IGroup) {
404
-					$groupsList[] = $groupManager->get($group);
405
-				}
406
-			}
407
-			$appManager->enableAppForGroups($appId, $groupsList);
408
-		} else {
409
-			$appManager->enableApp($appId);
410
-		}
411
-	}
412
-
413
-	/**
414
-	 * Get the path where to install apps
415
-	 *
416
-	 * @return string|false
417
-	 */
418
-	public static function getInstallPath() {
419
-		if (\OC::$server->getSystemConfig()->getValue('appstoreenabled', true) == false) {
420
-			return false;
421
-		}
422
-
423
-		foreach (OC::$APPSROOTS as $dir) {
424
-			if (isset($dir['writable']) && $dir['writable'] === true) {
425
-				return $dir['path'];
426
-			}
427
-		}
428
-
429
-		\OCP\Util::writeLog('core', 'No application directories are marked as writable.', ILogger::ERROR);
430
-		return null;
431
-	}
432
-
433
-
434
-	/**
435
-	 * search for an app in all app-directories
436
-	 *
437
-	 * @param string $appId
438
-	 * @return false|string
439
-	 */
440
-	public static function findAppInDirectories(string $appId) {
441
-		$sanitizedAppId = self::cleanAppId($appId);
442
-		if($sanitizedAppId !== $appId) {
443
-			return false;
444
-		}
445
-		static $app_dir = [];
446
-
447
-		if (isset($app_dir[$appId])) {
448
-			return $app_dir[$appId];
449
-		}
450
-
451
-		$possibleApps = [];
452
-		foreach (OC::$APPSROOTS as $dir) {
453
-			if (file_exists($dir['path'] . '/' . $appId)) {
454
-				$possibleApps[] = $dir;
455
-			}
456
-		}
457
-
458
-		if (empty($possibleApps)) {
459
-			return false;
460
-		} elseif (count($possibleApps) === 1) {
461
-			$dir = array_shift($possibleApps);
462
-			$app_dir[$appId] = $dir;
463
-			return $dir;
464
-		} else {
465
-			$versionToLoad = [];
466
-			foreach ($possibleApps as $possibleApp) {
467
-				$version = self::getAppVersionByPath($possibleApp['path'] . '/' . $appId);
468
-				if (empty($versionToLoad) || version_compare($version, $versionToLoad['version'], '>')) {
469
-					$versionToLoad = array(
470
-						'dir' => $possibleApp,
471
-						'version' => $version,
472
-					);
473
-				}
474
-			}
475
-			$app_dir[$appId] = $versionToLoad['dir'];
476
-			return $versionToLoad['dir'];
477
-			//TODO - write test
478
-		}
479
-	}
480
-
481
-	/**
482
-	 * Get the directory for the given app.
483
-	 * If the app is defined in multiple directories, the first one is taken. (false if not found)
484
-	 *
485
-	 * @param string $appId
486
-	 * @return string|false
487
-	 */
488
-	public static function getAppPath(string $appId) {
489
-		if ($appId === null || trim($appId) === '') {
490
-			return false;
491
-		}
492
-
493
-		if (($dir = self::findAppInDirectories($appId)) != false) {
494
-			return $dir['path'] . '/' . $appId;
495
-		}
496
-		return false;
497
-	}
498
-
499
-	/**
500
-	 * Get the path for the given app on the access
501
-	 * If the app is defined in multiple directories, the first one is taken. (false if not found)
502
-	 *
503
-	 * @param string $appId
504
-	 * @return string|false
505
-	 */
506
-	public static function getAppWebPath(string $appId) {
507
-		if (($dir = self::findAppInDirectories($appId)) != false) {
508
-			return OC::$WEBROOT . $dir['url'] . '/' . $appId;
509
-		}
510
-		return false;
511
-	}
512
-
513
-	/**
514
-	 * get the last version of the app from appinfo/info.xml
515
-	 *
516
-	 * @param string $appId
517
-	 * @param bool $useCache
518
-	 * @return string
519
-	 * @deprecated 14.0.0 use \OC::$server->getAppManager()->getAppVersion()
520
-	 */
521
-	public static function getAppVersion(string $appId, bool $useCache = true): string {
522
-		return \OC::$server->getAppManager()->getAppVersion($appId, $useCache);
523
-	}
524
-
525
-	/**
526
-	 * get app's version based on it's path
527
-	 *
528
-	 * @param string $path
529
-	 * @return string
530
-	 */
531
-	public static function getAppVersionByPath(string $path): string {
532
-		$infoFile = $path . '/appinfo/info.xml';
533
-		$appData = \OC::$server->getAppManager()->getAppInfo($infoFile, true);
534
-		return isset($appData['version']) ? $appData['version'] : '';
535
-	}
536
-
537
-
538
-	/**
539
-	 * Read all app metadata from the info.xml file
540
-	 *
541
-	 * @param string $appId id of the app or the path of the info.xml file
542
-	 * @param bool $path
543
-	 * @param string $lang
544
-	 * @return array|null
545
-	 * @note all data is read from info.xml, not just pre-defined fields
546
-	 * @deprecated 14.0.0 use \OC::$server->getAppManager()->getAppInfo()
547
-	 */
548
-	public static function getAppInfo(string $appId, bool $path = false, string $lang = null) {
549
-		return \OC::$server->getAppManager()->getAppInfo($appId, $path, $lang);
550
-	}
551
-
552
-	/**
553
-	 * Returns the navigation
554
-	 *
555
-	 * @return array
556
-	 * @deprecated 14.0.0 use \OC::$server->getNavigationManager()->getAll()
557
-	 *
558
-	 * This function returns an array containing all entries added. The
559
-	 * entries are sorted by the key 'order' ascending. Additional to the keys
560
-	 * given for each app the following keys exist:
561
-	 *   - active: boolean, signals if the user is on this navigation entry
562
-	 */
563
-	public static function getNavigation(): array {
564
-		return OC::$server->getNavigationManager()->getAll();
565
-	}
566
-
567
-	/**
568
-	 * Returns the Settings Navigation
569
-	 *
570
-	 * @return string[]
571
-	 * @deprecated 14.0.0 use \OC::$server->getNavigationManager()->getAll('settings')
572
-	 *
573
-	 * This function returns an array containing all settings pages added. The
574
-	 * entries are sorted by the key 'order' ascending.
575
-	 */
576
-	public static function getSettingsNavigation(): array {
577
-		return OC::$server->getNavigationManager()->getAll('settings');
578
-	}
579
-
580
-	/**
581
-	 * get the id of loaded app
582
-	 *
583
-	 * @return string
584
-	 */
585
-	public static function getCurrentApp(): string {
586
-		$request = \OC::$server->getRequest();
587
-		$script = substr($request->getScriptName(), strlen(OC::$WEBROOT) + 1);
588
-		$topFolder = substr($script, 0, strpos($script, '/') ?: 0);
589
-		if (empty($topFolder)) {
590
-			$path_info = $request->getPathInfo();
591
-			if ($path_info) {
592
-				$topFolder = substr($path_info, 1, strpos($path_info, '/', 1) - 1);
593
-			}
594
-		}
595
-		if ($topFolder == 'apps') {
596
-			$length = strlen($topFolder);
597
-			return substr($script, $length + 1, strpos($script, '/', $length + 1) - $length - 1) ?: '';
598
-		} else {
599
-			return $topFolder;
600
-		}
601
-	}
602
-
603
-	/**
604
-	 * @param string $type
605
-	 * @return array
606
-	 */
607
-	public static function getForms(string $type): array {
608
-		$forms = [];
609
-		switch ($type) {
610
-			case 'admin':
611
-				$source = self::$adminForms;
612
-				break;
613
-			case 'personal':
614
-				$source = self::$personalForms;
615
-				break;
616
-			default:
617
-				return [];
618
-		}
619
-		foreach ($source as $form) {
620
-			$forms[] = include $form;
621
-		}
622
-		return $forms;
623
-	}
624
-
625
-	/**
626
-	 * register an admin form to be shown
627
-	 *
628
-	 * @param string $app
629
-	 * @param string $page
630
-	 */
631
-	public static function registerAdmin(string $app, string $page) {
632
-		self::$adminForms[] = $app . '/' . $page . '.php';
633
-	}
634
-
635
-	/**
636
-	 * register a personal form to be shown
637
-	 * @param string $app
638
-	 * @param string $page
639
-	 */
640
-	public static function registerPersonal(string $app, string $page) {
641
-		self::$personalForms[] = $app . '/' . $page . '.php';
642
-	}
643
-
644
-	/**
645
-	 * @param array $entry
646
-	 */
647
-	public static function registerLogIn(array $entry) {
648
-		self::$altLogin[] = $entry;
649
-	}
650
-
651
-	/**
652
-	 * @return array
653
-	 */
654
-	public static function getAlternativeLogIns(): array {
655
-		return self::$altLogin;
656
-	}
657
-
658
-	/**
659
-	 * get a list of all apps in the apps folder
660
-	 *
661
-	 * @return array an array of app names (string IDs)
662
-	 * @todo: change the name of this method to getInstalledApps, which is more accurate
663
-	 */
664
-	public static function getAllApps(): array {
665
-
666
-		$apps = [];
667
-
668
-		foreach (OC::$APPSROOTS as $apps_dir) {
669
-			if (!is_readable($apps_dir['path'])) {
670
-				\OCP\Util::writeLog('core', 'unable to read app folder : ' . $apps_dir['path'], ILogger::WARN);
671
-				continue;
672
-			}
673
-			$dh = opendir($apps_dir['path']);
674
-
675
-			if (is_resource($dh)) {
676
-				while (($file = readdir($dh)) !== false) {
677
-
678
-					if ($file[0] != '.' and is_dir($apps_dir['path'] . '/' . $file) and is_file($apps_dir['path'] . '/' . $file . '/appinfo/info.xml')) {
679
-
680
-						$apps[] = $file;
681
-					}
682
-				}
683
-			}
684
-		}
685
-
686
-		$apps = array_unique($apps);
687
-
688
-		return $apps;
689
-	}
690
-
691
-	/**
692
-	 * List all apps, this is used in apps.php
693
-	 *
694
-	 * @return array
695
-	 */
696
-	public function listAllApps(): array {
697
-		$installedApps = OC_App::getAllApps();
698
-
699
-		$appManager = \OC::$server->getAppManager();
700
-		//we don't want to show configuration for these
701
-		$blacklist = $appManager->getAlwaysEnabledApps();
702
-		$appList = [];
703
-		$langCode = \OC::$server->getL10N('core')->getLanguageCode();
704
-		$urlGenerator = \OC::$server->getURLGenerator();
705
-
706
-		foreach ($installedApps as $app) {
707
-			if (array_search($app, $blacklist) === false) {
708
-
709
-				$info = OC_App::getAppInfo($app, false, $langCode);
710
-				if (!is_array($info)) {
711
-					\OCP\Util::writeLog('core', 'Could not read app info file for app "' . $app . '"', ILogger::ERROR);
712
-					continue;
713
-				}
714
-
715
-				if (!isset($info['name'])) {
716
-					\OCP\Util::writeLog('core', 'App id "' . $app . '" has no name in appinfo', ILogger::ERROR);
717
-					continue;
718
-				}
719
-
720
-				$enabled = \OC::$server->getConfig()->getAppValue($app, 'enabled', 'no');
721
-				$info['groups'] = null;
722
-				if ($enabled === 'yes') {
723
-					$active = true;
724
-				} else if ($enabled === 'no') {
725
-					$active = false;
726
-				} else {
727
-					$active = true;
728
-					$info['groups'] = $enabled;
729
-				}
730
-
731
-				$info['active'] = $active;
732
-
733
-				if ($appManager->isShipped($app)) {
734
-					$info['internal'] = true;
735
-					$info['level'] = self::officialApp;
736
-					$info['removable'] = false;
737
-				} else {
738
-					$info['internal'] = false;
739
-					$info['removable'] = true;
740
-				}
741
-
742
-				$appPath = self::getAppPath($app);
743
-				if($appPath !== false) {
744
-					$appIcon = $appPath . '/img/' . $app . '.svg';
745
-					if (file_exists($appIcon)) {
746
-						$info['preview'] = $urlGenerator->imagePath($app, $app . '.svg');
747
-						$info['previewAsIcon'] = true;
748
-					} else {
749
-						$appIcon = $appPath . '/img/app.svg';
750
-						if (file_exists($appIcon)) {
751
-							$info['preview'] = $urlGenerator->imagePath($app, 'app.svg');
752
-							$info['previewAsIcon'] = true;
753
-						}
754
-					}
755
-				}
756
-				// fix documentation
757
-				if (isset($info['documentation']) && is_array($info['documentation'])) {
758
-					foreach ($info['documentation'] as $key => $url) {
759
-						// If it is not an absolute URL we assume it is a key
760
-						// i.e. admin-ldap will get converted to go.php?to=admin-ldap
761
-						if (stripos($url, 'https://') !== 0 && stripos($url, 'http://') !== 0) {
762
-							$url = $urlGenerator->linkToDocs($url);
763
-						}
764
-
765
-						$info['documentation'][$key] = $url;
766
-					}
767
-				}
768
-
769
-				$info['version'] = OC_App::getAppVersion($app);
770
-				$appList[] = $info;
771
-			}
772
-		}
773
-
774
-		return $appList;
775
-	}
776
-
777
-	public static function shouldUpgrade(string $app): bool {
778
-		$versions = self::getAppVersions();
779
-		$currentVersion = OC_App::getAppVersion($app);
780
-		if ($currentVersion && isset($versions[$app])) {
781
-			$installedVersion = $versions[$app];
782
-			if (!version_compare($currentVersion, $installedVersion, '=')) {
783
-				return true;
784
-			}
785
-		}
786
-		return false;
787
-	}
788
-
789
-	/**
790
-	 * Adjust the number of version parts of $version1 to match
791
-	 * the number of version parts of $version2.
792
-	 *
793
-	 * @param string $version1 version to adjust
794
-	 * @param string $version2 version to take the number of parts from
795
-	 * @return string shortened $version1
796
-	 */
797
-	private static function adjustVersionParts(string $version1, string $version2): string {
798
-		$version1 = explode('.', $version1);
799
-		$version2 = explode('.', $version2);
800
-		// reduce $version1 to match the number of parts in $version2
801
-		while (count($version1) > count($version2)) {
802
-			array_pop($version1);
803
-		}
804
-		// if $version1 does not have enough parts, add some
805
-		while (count($version1) < count($version2)) {
806
-			$version1[] = '0';
807
-		}
808
-		return implode('.', $version1);
809
-	}
810
-
811
-	/**
812
-	 * Check whether the current ownCloud version matches the given
813
-	 * application's version requirements.
814
-	 *
815
-	 * The comparison is made based on the number of parts that the
816
-	 * app info version has. For example for ownCloud 6.0.3 if the
817
-	 * app info version is expecting version 6.0, the comparison is
818
-	 * made on the first two parts of the ownCloud version.
819
-	 * This means that it's possible to specify "requiremin" => 6
820
-	 * and "requiremax" => 6 and it will still match ownCloud 6.0.3.
821
-	 *
822
-	 * @param string $ocVersion ownCloud version to check against
823
-	 * @param array $appInfo app info (from xml)
824
-	 *
825
-	 * @return boolean true if compatible, otherwise false
826
-	 */
827
-	public static function isAppCompatible(string $ocVersion, array $appInfo): bool {
828
-		$requireMin = '';
829
-		$requireMax = '';
830
-		if (isset($appInfo['dependencies']['nextcloud']['@attributes']['min-version'])) {
831
-			$requireMin = $appInfo['dependencies']['nextcloud']['@attributes']['min-version'];
832
-		} elseif (isset($appInfo['dependencies']['owncloud']['@attributes']['min-version'])) {
833
-			$requireMin = $appInfo['dependencies']['owncloud']['@attributes']['min-version'];
834
-		} else if (isset($appInfo['requiremin'])) {
835
-			$requireMin = $appInfo['requiremin'];
836
-		} else if (isset($appInfo['require'])) {
837
-			$requireMin = $appInfo['require'];
838
-		}
839
-
840
-		if (isset($appInfo['dependencies']['nextcloud']['@attributes']['max-version'])) {
841
-			$requireMax = $appInfo['dependencies']['nextcloud']['@attributes']['max-version'];
842
-		} elseif (isset($appInfo['dependencies']['owncloud']['@attributes']['max-version'])) {
843
-			$requireMax = $appInfo['dependencies']['owncloud']['@attributes']['max-version'];
844
-		} else if (isset($appInfo['requiremax'])) {
845
-			$requireMax = $appInfo['requiremax'];
846
-		}
847
-
848
-		if (!empty($requireMin)
849
-			&& version_compare(self::adjustVersionParts($ocVersion, $requireMin), $requireMin, '<')
850
-		) {
851
-
852
-			return false;
853
-		}
854
-
855
-		if (!empty($requireMax)
856
-			&& version_compare(self::adjustVersionParts($ocVersion, $requireMax), $requireMax, '>')
857
-		) {
858
-			return false;
859
-		}
860
-
861
-		return true;
862
-	}
863
-
864
-	/**
865
-	 * get the installed version of all apps
866
-	 */
867
-	public static function getAppVersions() {
868
-		static $versions;
869
-
870
-		if(!$versions) {
871
-			$appConfig = \OC::$server->getAppConfig();
872
-			$versions = $appConfig->getValues(false, 'installed_version');
873
-		}
874
-		return $versions;
875
-	}
876
-
877
-	/**
878
-	 * update the database for the app and call the update script
879
-	 *
880
-	 * @param string $appId
881
-	 * @return bool
882
-	 */
883
-	public static function updateApp(string $appId): bool {
884
-		$appPath = self::getAppPath($appId);
885
-		if($appPath === false) {
886
-			return false;
887
-		}
888
-		self::registerAutoloading($appId, $appPath);
889
-
890
-		\OC::$server->getAppManager()->clearAppsCache();
891
-		$appData = self::getAppInfo($appId);
892
-		self::executeRepairSteps($appId, $appData['repair-steps']['pre-migration']);
893
-
894
-		if (file_exists($appPath . '/appinfo/database.xml')) {
895
-			OC_DB::updateDbFromStructure($appPath . '/appinfo/database.xml');
896
-		} else {
897
-			$ms = new MigrationService($appId, \OC::$server->getDatabaseConnection());
898
-			$ms->migrate();
899
-		}
900
-
901
-		self::executeRepairSteps($appId, $appData['repair-steps']['post-migration']);
902
-		self::setupLiveMigrations($appId, $appData['repair-steps']['live-migration']);
903
-		// update appversion in app manager
904
-		\OC::$server->getAppManager()->getAppVersion($appId, false);
905
-
906
-		// run upgrade code
907
-		if (file_exists($appPath . '/appinfo/update.php')) {
908
-			self::loadApp($appId);
909
-			include $appPath . '/appinfo/update.php';
910
-		}
911
-		self::setupBackgroundJobs($appData['background-jobs']);
912
-
913
-		//set remote/public handlers
914
-		if (array_key_exists('ocsid', $appData)) {
915
-			\OC::$server->getConfig()->setAppValue($appId, 'ocsid', $appData['ocsid']);
916
-		} elseif(\OC::$server->getConfig()->getAppValue($appId, 'ocsid', null) !== null) {
917
-			\OC::$server->getConfig()->deleteAppValue($appId, 'ocsid');
918
-		}
919
-		foreach ($appData['remote'] as $name => $path) {
920
-			\OC::$server->getConfig()->setAppValue('core', 'remote_' . $name, $appId . '/' . $path);
921
-		}
922
-		foreach ($appData['public'] as $name => $path) {
923
-			\OC::$server->getConfig()->setAppValue('core', 'public_' . $name, $appId . '/' . $path);
924
-		}
925
-
926
-		self::setAppTypes($appId);
927
-
928
-		$version = \OC_App::getAppVersion($appId);
929
-		\OC::$server->getConfig()->setAppValue($appId, 'installed_version', $version);
930
-
931
-		\OC::$server->getEventDispatcher()->dispatch(ManagerEvent::EVENT_APP_UPDATE, new ManagerEvent(
932
-			ManagerEvent::EVENT_APP_UPDATE, $appId
933
-		));
934
-
935
-		return true;
936
-	}
937
-
938
-	/**
939
-	 * @param string $appId
940
-	 * @param string[] $steps
941
-	 * @throws \OC\NeedsUpdateException
942
-	 */
943
-	public static function executeRepairSteps(string $appId, array $steps) {
944
-		if (empty($steps)) {
945
-			return;
946
-		}
947
-		// load the app
948
-		self::loadApp($appId);
949
-
950
-		$dispatcher = OC::$server->getEventDispatcher();
951
-
952
-		// load the steps
953
-		$r = new Repair([], $dispatcher);
954
-		foreach ($steps as $step) {
955
-			try {
956
-				$r->addStep($step);
957
-			} catch (Exception $ex) {
958
-				$r->emit('\OC\Repair', 'error', [$ex->getMessage()]);
959
-				\OC::$server->getLogger()->logException($ex);
960
-			}
961
-		}
962
-		// run the steps
963
-		$r->run();
964
-	}
965
-
966
-	public static function setupBackgroundJobs(array $jobs) {
967
-		$queue = \OC::$server->getJobList();
968
-		foreach ($jobs as $job) {
969
-			$queue->add($job);
970
-		}
971
-	}
972
-
973
-	/**
974
-	 * @param string $appId
975
-	 * @param string[] $steps
976
-	 */
977
-	private static function setupLiveMigrations(string $appId, array $steps) {
978
-		$queue = \OC::$server->getJobList();
979
-		foreach ($steps as $step) {
980
-			$queue->add('OC\Migration\BackgroundRepair', [
981
-				'app' => $appId,
982
-				'step' => $step]);
983
-		}
984
-	}
985
-
986
-	/**
987
-	 * @param string $appId
988
-	 * @return \OC\Files\View|false
989
-	 */
990
-	public static function getStorage(string $appId) {
991
-		if (\OC::$server->getAppManager()->isEnabledForUser($appId)) { //sanity check
992
-			if (\OC::$server->getUserSession()->isLoggedIn()) {
993
-				$view = new \OC\Files\View('/' . OC_User::getUser());
994
-				if (!$view->file_exists($appId)) {
995
-					$view->mkdir($appId);
996
-				}
997
-				return new \OC\Files\View('/' . OC_User::getUser() . '/' . $appId);
998
-			} else {
999
-				\OCP\Util::writeLog('core', 'Can\'t get app storage, app ' . $appId . ', user not logged in', ILogger::ERROR);
1000
-				return false;
1001
-			}
1002
-		} else {
1003
-			\OCP\Util::writeLog('core', 'Can\'t get app storage, app ' . $appId . ' not enabled', ILogger::ERROR);
1004
-			return false;
1005
-		}
1006
-	}
1007
-
1008
-	protected static function findBestL10NOption(array $options, string $lang): string {
1009
-		// only a single option
1010
-		if (isset($options['@value'])) {
1011
-			return $options['@value'];
1012
-		}
1013
-
1014
-		$fallback = $similarLangFallback = $englishFallback = false;
1015
-
1016
-		$lang = strtolower($lang);
1017
-		$similarLang = $lang;
1018
-		if (strpos($similarLang, '_')) {
1019
-			// For "de_DE" we want to find "de" and the other way around
1020
-			$similarLang = substr($lang, 0, strpos($lang, '_'));
1021
-		}
1022
-
1023
-		foreach ($options as $option) {
1024
-			if (is_array($option)) {
1025
-				if ($fallback === false) {
1026
-					$fallback = $option['@value'];
1027
-				}
1028
-
1029
-				if (!isset($option['@attributes']['lang'])) {
1030
-					continue;
1031
-				}
1032
-
1033
-				$attributeLang = strtolower($option['@attributes']['lang']);
1034
-				if ($attributeLang === $lang) {
1035
-					return $option['@value'];
1036
-				}
1037
-
1038
-				if ($attributeLang === $similarLang) {
1039
-					$similarLangFallback = $option['@value'];
1040
-				} else if (strpos($attributeLang, $similarLang . '_') === 0) {
1041
-					if ($similarLangFallback === false) {
1042
-						$similarLangFallback =  $option['@value'];
1043
-					}
1044
-				}
1045
-			} else {
1046
-				$englishFallback = $option;
1047
-			}
1048
-		}
1049
-
1050
-		if ($similarLangFallback !== false) {
1051
-			return $similarLangFallback;
1052
-		} else if ($englishFallback !== false) {
1053
-			return $englishFallback;
1054
-		}
1055
-		return (string) $fallback;
1056
-	}
1057
-
1058
-	/**
1059
-	 * parses the app data array and enhanced the 'description' value
1060
-	 *
1061
-	 * @param array $data the app data
1062
-	 * @param string $lang
1063
-	 * @return array improved app data
1064
-	 */
1065
-	public static function parseAppInfo(array $data, $lang = null): array {
1066
-
1067
-		if ($lang && isset($data['name']) && is_array($data['name'])) {
1068
-			$data['name'] = self::findBestL10NOption($data['name'], $lang);
1069
-		}
1070
-		if ($lang && isset($data['summary']) && is_array($data['summary'])) {
1071
-			$data['summary'] = self::findBestL10NOption($data['summary'], $lang);
1072
-		}
1073
-		if ($lang && isset($data['description']) && is_array($data['description'])) {
1074
-			$data['description'] = trim(self::findBestL10NOption($data['description'], $lang));
1075
-		} else if (isset($data['description']) && is_string($data['description'])) {
1076
-			$data['description'] = trim($data['description']);
1077
-		} else  {
1078
-			$data['description'] = '';
1079
-		}
1080
-
1081
-		return $data;
1082
-	}
1083
-
1084
-	/**
1085
-	 * @param \OCP\IConfig $config
1086
-	 * @param \OCP\IL10N $l
1087
-	 * @param array $info
1088
-	 * @throws \Exception
1089
-	 */
1090
-	public static function checkAppDependencies(\OCP\IConfig $config, \OCP\IL10N $l, array $info) {
1091
-		$dependencyAnalyzer = new DependencyAnalyzer(new Platform($config), $l);
1092
-		$missing = $dependencyAnalyzer->analyze($info);
1093
-		if (!empty($missing)) {
1094
-			$missingMsg = implode(PHP_EOL, $missing);
1095
-			throw new \Exception(
1096
-				$l->t('App "%s" cannot be installed because the following dependencies are not fulfilled: %s',
1097
-					[$info['name'], $missingMsg]
1098
-				)
1099
-			);
1100
-		}
1101
-	}
67
+    static private $adminForms = [];
68
+    static private $personalForms = [];
69
+    static private $appTypes = [];
70
+    static private $loadedApps = [];
71
+    static private $altLogin = [];
72
+    static private $alreadyRegistered = [];
73
+    const officialApp = 200;
74
+
75
+    /**
76
+     * clean the appId
77
+     *
78
+     * @param string $app AppId that needs to be cleaned
79
+     * @return string
80
+     */
81
+    public static function cleanAppId(string $app): string {
82
+        return str_replace(array('\0', '/', '\\', '..'), '', $app);
83
+    }
84
+
85
+    /**
86
+     * Check if an app is loaded
87
+     *
88
+     * @param string $app
89
+     * @return bool
90
+     */
91
+    public static function isAppLoaded(string $app): bool {
92
+        return in_array($app, self::$loadedApps, true);
93
+    }
94
+
95
+    /**
96
+     * loads all apps
97
+     *
98
+     * @param string[] $types
99
+     * @return bool
100
+     *
101
+     * This function walks through the ownCloud directory and loads all apps
102
+     * it can find. A directory contains an app if the file /appinfo/info.xml
103
+     * exists.
104
+     *
105
+     * if $types is set to non-empty array, only apps of those types will be loaded
106
+     */
107
+    public static function loadApps(array $types = []): bool {
108
+        if (\OC::$server->getSystemConfig()->getValue('maintenance', false)) {
109
+            return false;
110
+        }
111
+        // Load the enabled apps here
112
+        $apps = self::getEnabledApps();
113
+
114
+        // Add each apps' folder as allowed class path
115
+        foreach($apps as $app) {
116
+            $path = self::getAppPath($app);
117
+            if($path !== false) {
118
+                self::registerAutoloading($app, $path);
119
+            }
120
+        }
121
+
122
+        // prevent app.php from printing output
123
+        ob_start();
124
+        foreach ($apps as $app) {
125
+            if (($types === [] or self::isType($app, $types)) && !in_array($app, self::$loadedApps)) {
126
+                self::loadApp($app);
127
+            }
128
+        }
129
+        ob_end_clean();
130
+
131
+        return true;
132
+    }
133
+
134
+    /**
135
+     * load a single app
136
+     *
137
+     * @param string $app
138
+     * @throws Exception
139
+     */
140
+    public static function loadApp(string $app) {
141
+        self::$loadedApps[] = $app;
142
+        $appPath = self::getAppPath($app);
143
+        if($appPath === false) {
144
+            return;
145
+        }
146
+
147
+        // in case someone calls loadApp() directly
148
+        self::registerAutoloading($app, $appPath);
149
+
150
+        if (is_file($appPath . '/appinfo/app.php')) {
151
+            \OC::$server->getEventLogger()->start('load_app_' . $app, 'Load app: ' . $app);
152
+            try {
153
+                self::requireAppFile($app);
154
+            } catch (Error $ex) {
155
+                \OC::$server->getLogger()->logException($ex);
156
+                if (!\OC::$server->getAppManager()->isShipped($app)) {
157
+                    // Only disable apps which are not shipped
158
+                    \OC::$server->getAppManager()->disableApp($app);
159
+                }
160
+            }
161
+            \OC::$server->getEventLogger()->end('load_app_' . $app);
162
+        }
163
+
164
+        $info = self::getAppInfo($app);
165
+        if (!empty($info['activity']['filters'])) {
166
+            foreach ($info['activity']['filters'] as $filter) {
167
+                \OC::$server->getActivityManager()->registerFilter($filter);
168
+            }
169
+        }
170
+        if (!empty($info['activity']['settings'])) {
171
+            foreach ($info['activity']['settings'] as $setting) {
172
+                \OC::$server->getActivityManager()->registerSetting($setting);
173
+            }
174
+        }
175
+        if (!empty($info['activity']['providers'])) {
176
+            foreach ($info['activity']['providers'] as $provider) {
177
+                \OC::$server->getActivityManager()->registerProvider($provider);
178
+            }
179
+        }
180
+
181
+        if (!empty($info['settings']['admin'])) {
182
+            foreach ($info['settings']['admin'] as $setting) {
183
+                \OC::$server->getSettingsManager()->registerSetting('admin', $setting);
184
+            }
185
+        }
186
+        if (!empty($info['settings']['admin-section'])) {
187
+            foreach ($info['settings']['admin-section'] as $section) {
188
+                \OC::$server->getSettingsManager()->registerSection('admin', $section);
189
+            }
190
+        }
191
+        if (!empty($info['settings']['personal'])) {
192
+            foreach ($info['settings']['personal'] as $setting) {
193
+                \OC::$server->getSettingsManager()->registerSetting('personal', $setting);
194
+            }
195
+        }
196
+        if (!empty($info['settings']['personal-section'])) {
197
+            foreach ($info['settings']['personal-section'] as $section) {
198
+                \OC::$server->getSettingsManager()->registerSection('personal', $section);
199
+            }
200
+        }
201
+
202
+        if (!empty($info['collaboration']['plugins'])) {
203
+            // deal with one or many plugin entries
204
+            $plugins = isset($info['collaboration']['plugins']['plugin']['@value']) ?
205
+                [$info['collaboration']['plugins']['plugin']] : $info['collaboration']['plugins']['plugin'];
206
+            foreach ($plugins as $plugin) {
207
+                if($plugin['@attributes']['type'] === 'collaborator-search') {
208
+                    $pluginInfo = [
209
+                        'shareType' => $plugin['@attributes']['share-type'],
210
+                        'class' => $plugin['@value'],
211
+                    ];
212
+                    \OC::$server->getCollaboratorSearch()->registerPlugin($pluginInfo);
213
+                } else if ($plugin['@attributes']['type'] === 'autocomplete-sort') {
214
+                    \OC::$server->getAutoCompleteManager()->registerSorter($plugin['@value']);
215
+                }
216
+            }
217
+        }
218
+    }
219
+
220
+    /**
221
+     * @internal
222
+     * @param string $app
223
+     * @param string $path
224
+     */
225
+    public static function registerAutoloading(string $app, string $path) {
226
+        $key = $app . '-' . $path;
227
+        if(isset(self::$alreadyRegistered[$key])) {
228
+            return;
229
+        }
230
+
231
+        self::$alreadyRegistered[$key] = true;
232
+
233
+        // Register on PSR-4 composer autoloader
234
+        $appNamespace = \OC\AppFramework\App::buildAppNamespace($app);
235
+        \OC::$server->registerNamespace($app, $appNamespace);
236
+
237
+        if (file_exists($path . '/composer/autoload.php')) {
238
+            require_once $path . '/composer/autoload.php';
239
+        } else {
240
+            \OC::$composerAutoloader->addPsr4($appNamespace . '\\', $path . '/lib/', true);
241
+            // Register on legacy autoloader
242
+            \OC::$loader->addValidRoot($path);
243
+        }
244
+
245
+        // Register Test namespace only when testing
246
+        if (defined('PHPUNIT_RUN') || defined('CLI_TEST_RUN')) {
247
+            \OC::$composerAutoloader->addPsr4($appNamespace . '\\Tests\\', $path . '/tests/', true);
248
+        }
249
+    }
250
+
251
+    /**
252
+     * Load app.php from the given app
253
+     *
254
+     * @param string $app app name
255
+     * @throws Error
256
+     */
257
+    private static function requireAppFile(string $app) {
258
+        // encapsulated here to avoid variable scope conflicts
259
+        require_once $app . '/appinfo/app.php';
260
+    }
261
+
262
+    /**
263
+     * check if an app is of a specific type
264
+     *
265
+     * @param string $app
266
+     * @param array $types
267
+     * @return bool
268
+     */
269
+    public static function isType(string $app, array $types): bool {
270
+        $appTypes = self::getAppTypes($app);
271
+        foreach ($types as $type) {
272
+            if (array_search($type, $appTypes) !== false) {
273
+                return true;
274
+            }
275
+        }
276
+        return false;
277
+    }
278
+
279
+    /**
280
+     * get the types of an app
281
+     *
282
+     * @param string $app
283
+     * @return array
284
+     */
285
+    private static function getAppTypes(string $app): array {
286
+        //load the cache
287
+        if (count(self::$appTypes) == 0) {
288
+            self::$appTypes = \OC::$server->getAppConfig()->getValues(false, 'types');
289
+        }
290
+
291
+        if (isset(self::$appTypes[$app])) {
292
+            return explode(',', self::$appTypes[$app]);
293
+        }
294
+
295
+        return [];
296
+    }
297
+
298
+    /**
299
+     * read app types from info.xml and cache them in the database
300
+     */
301
+    public static function setAppTypes(string $app) {
302
+        $appManager = \OC::$server->getAppManager();
303
+        $appData = $appManager->getAppInfo($app);
304
+        if(!is_array($appData)) {
305
+            return;
306
+        }
307
+
308
+        if (isset($appData['types'])) {
309
+            $appTypes = implode(',', $appData['types']);
310
+        } else {
311
+            $appTypes = '';
312
+            $appData['types'] = [];
313
+        }
314
+
315
+        $config = \OC::$server->getConfig();
316
+        $config->setAppValue($app, 'types', $appTypes);
317
+
318
+        if ($appManager->hasProtectedAppType($appData['types'])) {
319
+            $enabled = $config->getAppValue($app, 'enabled', 'yes');
320
+            if ($enabled !== 'yes' && $enabled !== 'no') {
321
+                $config->setAppValue($app, 'enabled', 'yes');
322
+            }
323
+        }
324
+    }
325
+
326
+    /**
327
+     * Returns apps enabled for the current user.
328
+     *
329
+     * @param bool $forceRefresh whether to refresh the cache
330
+     * @param bool $all whether to return apps for all users, not only the
331
+     * currently logged in one
332
+     * @return string[]
333
+     */
334
+    public static function getEnabledApps(bool $forceRefresh = false, bool $all = false): array {
335
+        if (!\OC::$server->getSystemConfig()->getValue('installed', false)) {
336
+            return [];
337
+        }
338
+        // in incognito mode or when logged out, $user will be false,
339
+        // which is also the case during an upgrade
340
+        $appManager = \OC::$server->getAppManager();
341
+        if ($all) {
342
+            $user = null;
343
+        } else {
344
+            $user = \OC::$server->getUserSession()->getUser();
345
+        }
346
+
347
+        if (is_null($user)) {
348
+            $apps = $appManager->getInstalledApps();
349
+        } else {
350
+            $apps = $appManager->getEnabledAppsForUser($user);
351
+        }
352
+        $apps = array_filter($apps, function ($app) {
353
+            return $app !== 'files';//we add this manually
354
+        });
355
+        sort($apps);
356
+        array_unshift($apps, 'files');
357
+        return $apps;
358
+    }
359
+
360
+    /**
361
+     * checks whether or not an app is enabled
362
+     *
363
+     * @param string $app app
364
+     * @return bool
365
+     * @deprecated 13.0.0 use \OC::$server->getAppManager()->isEnabledForUser($appId)
366
+     *
367
+     * This function checks whether or not an app is enabled.
368
+     */
369
+    public static function isEnabled(string $app): bool {
370
+        return \OC::$server->getAppManager()->isEnabledForUser($app);
371
+    }
372
+
373
+    /**
374
+     * enables an app
375
+     *
376
+     * @param string $appId
377
+     * @param array $groups (optional) when set, only these groups will have access to the app
378
+     * @throws \Exception
379
+     * @return void
380
+     *
381
+     * This function set an app as enabled in appconfig.
382
+     */
383
+    public function enable(string $appId,
384
+                            array $groups = []) {
385
+
386
+        // Check if app is already downloaded
387
+        /** @var Installer $installer */
388
+        $installer = \OC::$server->query(Installer::class);
389
+        $isDownloaded = $installer->isDownloaded($appId);
390
+
391
+        if(!$isDownloaded) {
392
+            $installer->downloadApp($appId);
393
+        }
394
+
395
+        $installer->installApp($appId);
396
+
397
+        $appManager = \OC::$server->getAppManager();
398
+        if ($groups !== []) {
399
+            $groupManager = \OC::$server->getGroupManager();
400
+            $groupsList = [];
401
+            foreach ($groups as $group) {
402
+                $groupItem = $groupManager->get($group);
403
+                if ($groupItem instanceof \OCP\IGroup) {
404
+                    $groupsList[] = $groupManager->get($group);
405
+                }
406
+            }
407
+            $appManager->enableAppForGroups($appId, $groupsList);
408
+        } else {
409
+            $appManager->enableApp($appId);
410
+        }
411
+    }
412
+
413
+    /**
414
+     * Get the path where to install apps
415
+     *
416
+     * @return string|false
417
+     */
418
+    public static function getInstallPath() {
419
+        if (\OC::$server->getSystemConfig()->getValue('appstoreenabled', true) == false) {
420
+            return false;
421
+        }
422
+
423
+        foreach (OC::$APPSROOTS as $dir) {
424
+            if (isset($dir['writable']) && $dir['writable'] === true) {
425
+                return $dir['path'];
426
+            }
427
+        }
428
+
429
+        \OCP\Util::writeLog('core', 'No application directories are marked as writable.', ILogger::ERROR);
430
+        return null;
431
+    }
432
+
433
+
434
+    /**
435
+     * search for an app in all app-directories
436
+     *
437
+     * @param string $appId
438
+     * @return false|string
439
+     */
440
+    public static function findAppInDirectories(string $appId) {
441
+        $sanitizedAppId = self::cleanAppId($appId);
442
+        if($sanitizedAppId !== $appId) {
443
+            return false;
444
+        }
445
+        static $app_dir = [];
446
+
447
+        if (isset($app_dir[$appId])) {
448
+            return $app_dir[$appId];
449
+        }
450
+
451
+        $possibleApps = [];
452
+        foreach (OC::$APPSROOTS as $dir) {
453
+            if (file_exists($dir['path'] . '/' . $appId)) {
454
+                $possibleApps[] = $dir;
455
+            }
456
+        }
457
+
458
+        if (empty($possibleApps)) {
459
+            return false;
460
+        } elseif (count($possibleApps) === 1) {
461
+            $dir = array_shift($possibleApps);
462
+            $app_dir[$appId] = $dir;
463
+            return $dir;
464
+        } else {
465
+            $versionToLoad = [];
466
+            foreach ($possibleApps as $possibleApp) {
467
+                $version = self::getAppVersionByPath($possibleApp['path'] . '/' . $appId);
468
+                if (empty($versionToLoad) || version_compare($version, $versionToLoad['version'], '>')) {
469
+                    $versionToLoad = array(
470
+                        'dir' => $possibleApp,
471
+                        'version' => $version,
472
+                    );
473
+                }
474
+            }
475
+            $app_dir[$appId] = $versionToLoad['dir'];
476
+            return $versionToLoad['dir'];
477
+            //TODO - write test
478
+        }
479
+    }
480
+
481
+    /**
482
+     * Get the directory for the given app.
483
+     * If the app is defined in multiple directories, the first one is taken. (false if not found)
484
+     *
485
+     * @param string $appId
486
+     * @return string|false
487
+     */
488
+    public static function getAppPath(string $appId) {
489
+        if ($appId === null || trim($appId) === '') {
490
+            return false;
491
+        }
492
+
493
+        if (($dir = self::findAppInDirectories($appId)) != false) {
494
+            return $dir['path'] . '/' . $appId;
495
+        }
496
+        return false;
497
+    }
498
+
499
+    /**
500
+     * Get the path for the given app on the access
501
+     * If the app is defined in multiple directories, the first one is taken. (false if not found)
502
+     *
503
+     * @param string $appId
504
+     * @return string|false
505
+     */
506
+    public static function getAppWebPath(string $appId) {
507
+        if (($dir = self::findAppInDirectories($appId)) != false) {
508
+            return OC::$WEBROOT . $dir['url'] . '/' . $appId;
509
+        }
510
+        return false;
511
+    }
512
+
513
+    /**
514
+     * get the last version of the app from appinfo/info.xml
515
+     *
516
+     * @param string $appId
517
+     * @param bool $useCache
518
+     * @return string
519
+     * @deprecated 14.0.0 use \OC::$server->getAppManager()->getAppVersion()
520
+     */
521
+    public static function getAppVersion(string $appId, bool $useCache = true): string {
522
+        return \OC::$server->getAppManager()->getAppVersion($appId, $useCache);
523
+    }
524
+
525
+    /**
526
+     * get app's version based on it's path
527
+     *
528
+     * @param string $path
529
+     * @return string
530
+     */
531
+    public static function getAppVersionByPath(string $path): string {
532
+        $infoFile = $path . '/appinfo/info.xml';
533
+        $appData = \OC::$server->getAppManager()->getAppInfo($infoFile, true);
534
+        return isset($appData['version']) ? $appData['version'] : '';
535
+    }
536
+
537
+
538
+    /**
539
+     * Read all app metadata from the info.xml file
540
+     *
541
+     * @param string $appId id of the app or the path of the info.xml file
542
+     * @param bool $path
543
+     * @param string $lang
544
+     * @return array|null
545
+     * @note all data is read from info.xml, not just pre-defined fields
546
+     * @deprecated 14.0.0 use \OC::$server->getAppManager()->getAppInfo()
547
+     */
548
+    public static function getAppInfo(string $appId, bool $path = false, string $lang = null) {
549
+        return \OC::$server->getAppManager()->getAppInfo($appId, $path, $lang);
550
+    }
551
+
552
+    /**
553
+     * Returns the navigation
554
+     *
555
+     * @return array
556
+     * @deprecated 14.0.0 use \OC::$server->getNavigationManager()->getAll()
557
+     *
558
+     * This function returns an array containing all entries added. The
559
+     * entries are sorted by the key 'order' ascending. Additional to the keys
560
+     * given for each app the following keys exist:
561
+     *   - active: boolean, signals if the user is on this navigation entry
562
+     */
563
+    public static function getNavigation(): array {
564
+        return OC::$server->getNavigationManager()->getAll();
565
+    }
566
+
567
+    /**
568
+     * Returns the Settings Navigation
569
+     *
570
+     * @return string[]
571
+     * @deprecated 14.0.0 use \OC::$server->getNavigationManager()->getAll('settings')
572
+     *
573
+     * This function returns an array containing all settings pages added. The
574
+     * entries are sorted by the key 'order' ascending.
575
+     */
576
+    public static function getSettingsNavigation(): array {
577
+        return OC::$server->getNavigationManager()->getAll('settings');
578
+    }
579
+
580
+    /**
581
+     * get the id of loaded app
582
+     *
583
+     * @return string
584
+     */
585
+    public static function getCurrentApp(): string {
586
+        $request = \OC::$server->getRequest();
587
+        $script = substr($request->getScriptName(), strlen(OC::$WEBROOT) + 1);
588
+        $topFolder = substr($script, 0, strpos($script, '/') ?: 0);
589
+        if (empty($topFolder)) {
590
+            $path_info = $request->getPathInfo();
591
+            if ($path_info) {
592
+                $topFolder = substr($path_info, 1, strpos($path_info, '/', 1) - 1);
593
+            }
594
+        }
595
+        if ($topFolder == 'apps') {
596
+            $length = strlen($topFolder);
597
+            return substr($script, $length + 1, strpos($script, '/', $length + 1) - $length - 1) ?: '';
598
+        } else {
599
+            return $topFolder;
600
+        }
601
+    }
602
+
603
+    /**
604
+     * @param string $type
605
+     * @return array
606
+     */
607
+    public static function getForms(string $type): array {
608
+        $forms = [];
609
+        switch ($type) {
610
+            case 'admin':
611
+                $source = self::$adminForms;
612
+                break;
613
+            case 'personal':
614
+                $source = self::$personalForms;
615
+                break;
616
+            default:
617
+                return [];
618
+        }
619
+        foreach ($source as $form) {
620
+            $forms[] = include $form;
621
+        }
622
+        return $forms;
623
+    }
624
+
625
+    /**
626
+     * register an admin form to be shown
627
+     *
628
+     * @param string $app
629
+     * @param string $page
630
+     */
631
+    public static function registerAdmin(string $app, string $page) {
632
+        self::$adminForms[] = $app . '/' . $page . '.php';
633
+    }
634
+
635
+    /**
636
+     * register a personal form to be shown
637
+     * @param string $app
638
+     * @param string $page
639
+     */
640
+    public static function registerPersonal(string $app, string $page) {
641
+        self::$personalForms[] = $app . '/' . $page . '.php';
642
+    }
643
+
644
+    /**
645
+     * @param array $entry
646
+     */
647
+    public static function registerLogIn(array $entry) {
648
+        self::$altLogin[] = $entry;
649
+    }
650
+
651
+    /**
652
+     * @return array
653
+     */
654
+    public static function getAlternativeLogIns(): array {
655
+        return self::$altLogin;
656
+    }
657
+
658
+    /**
659
+     * get a list of all apps in the apps folder
660
+     *
661
+     * @return array an array of app names (string IDs)
662
+     * @todo: change the name of this method to getInstalledApps, which is more accurate
663
+     */
664
+    public static function getAllApps(): array {
665
+
666
+        $apps = [];
667
+
668
+        foreach (OC::$APPSROOTS as $apps_dir) {
669
+            if (!is_readable($apps_dir['path'])) {
670
+                \OCP\Util::writeLog('core', 'unable to read app folder : ' . $apps_dir['path'], ILogger::WARN);
671
+                continue;
672
+            }
673
+            $dh = opendir($apps_dir['path']);
674
+
675
+            if (is_resource($dh)) {
676
+                while (($file = readdir($dh)) !== false) {
677
+
678
+                    if ($file[0] != '.' and is_dir($apps_dir['path'] . '/' . $file) and is_file($apps_dir['path'] . '/' . $file . '/appinfo/info.xml')) {
679
+
680
+                        $apps[] = $file;
681
+                    }
682
+                }
683
+            }
684
+        }
685
+
686
+        $apps = array_unique($apps);
687
+
688
+        return $apps;
689
+    }
690
+
691
+    /**
692
+     * List all apps, this is used in apps.php
693
+     *
694
+     * @return array
695
+     */
696
+    public function listAllApps(): array {
697
+        $installedApps = OC_App::getAllApps();
698
+
699
+        $appManager = \OC::$server->getAppManager();
700
+        //we don't want to show configuration for these
701
+        $blacklist = $appManager->getAlwaysEnabledApps();
702
+        $appList = [];
703
+        $langCode = \OC::$server->getL10N('core')->getLanguageCode();
704
+        $urlGenerator = \OC::$server->getURLGenerator();
705
+
706
+        foreach ($installedApps as $app) {
707
+            if (array_search($app, $blacklist) === false) {
708
+
709
+                $info = OC_App::getAppInfo($app, false, $langCode);
710
+                if (!is_array($info)) {
711
+                    \OCP\Util::writeLog('core', 'Could not read app info file for app "' . $app . '"', ILogger::ERROR);
712
+                    continue;
713
+                }
714
+
715
+                if (!isset($info['name'])) {
716
+                    \OCP\Util::writeLog('core', 'App id "' . $app . '" has no name in appinfo', ILogger::ERROR);
717
+                    continue;
718
+                }
719
+
720
+                $enabled = \OC::$server->getConfig()->getAppValue($app, 'enabled', 'no');
721
+                $info['groups'] = null;
722
+                if ($enabled === 'yes') {
723
+                    $active = true;
724
+                } else if ($enabled === 'no') {
725
+                    $active = false;
726
+                } else {
727
+                    $active = true;
728
+                    $info['groups'] = $enabled;
729
+                }
730
+
731
+                $info['active'] = $active;
732
+
733
+                if ($appManager->isShipped($app)) {
734
+                    $info['internal'] = true;
735
+                    $info['level'] = self::officialApp;
736
+                    $info['removable'] = false;
737
+                } else {
738
+                    $info['internal'] = false;
739
+                    $info['removable'] = true;
740
+                }
741
+
742
+                $appPath = self::getAppPath($app);
743
+                if($appPath !== false) {
744
+                    $appIcon = $appPath . '/img/' . $app . '.svg';
745
+                    if (file_exists($appIcon)) {
746
+                        $info['preview'] = $urlGenerator->imagePath($app, $app . '.svg');
747
+                        $info['previewAsIcon'] = true;
748
+                    } else {
749
+                        $appIcon = $appPath . '/img/app.svg';
750
+                        if (file_exists($appIcon)) {
751
+                            $info['preview'] = $urlGenerator->imagePath($app, 'app.svg');
752
+                            $info['previewAsIcon'] = true;
753
+                        }
754
+                    }
755
+                }
756
+                // fix documentation
757
+                if (isset($info['documentation']) && is_array($info['documentation'])) {
758
+                    foreach ($info['documentation'] as $key => $url) {
759
+                        // If it is not an absolute URL we assume it is a key
760
+                        // i.e. admin-ldap will get converted to go.php?to=admin-ldap
761
+                        if (stripos($url, 'https://') !== 0 && stripos($url, 'http://') !== 0) {
762
+                            $url = $urlGenerator->linkToDocs($url);
763
+                        }
764
+
765
+                        $info['documentation'][$key] = $url;
766
+                    }
767
+                }
768
+
769
+                $info['version'] = OC_App::getAppVersion($app);
770
+                $appList[] = $info;
771
+            }
772
+        }
773
+
774
+        return $appList;
775
+    }
776
+
777
+    public static function shouldUpgrade(string $app): bool {
778
+        $versions = self::getAppVersions();
779
+        $currentVersion = OC_App::getAppVersion($app);
780
+        if ($currentVersion && isset($versions[$app])) {
781
+            $installedVersion = $versions[$app];
782
+            if (!version_compare($currentVersion, $installedVersion, '=')) {
783
+                return true;
784
+            }
785
+        }
786
+        return false;
787
+    }
788
+
789
+    /**
790
+     * Adjust the number of version parts of $version1 to match
791
+     * the number of version parts of $version2.
792
+     *
793
+     * @param string $version1 version to adjust
794
+     * @param string $version2 version to take the number of parts from
795
+     * @return string shortened $version1
796
+     */
797
+    private static function adjustVersionParts(string $version1, string $version2): string {
798
+        $version1 = explode('.', $version1);
799
+        $version2 = explode('.', $version2);
800
+        // reduce $version1 to match the number of parts in $version2
801
+        while (count($version1) > count($version2)) {
802
+            array_pop($version1);
803
+        }
804
+        // if $version1 does not have enough parts, add some
805
+        while (count($version1) < count($version2)) {
806
+            $version1[] = '0';
807
+        }
808
+        return implode('.', $version1);
809
+    }
810
+
811
+    /**
812
+     * Check whether the current ownCloud version matches the given
813
+     * application's version requirements.
814
+     *
815
+     * The comparison is made based on the number of parts that the
816
+     * app info version has. For example for ownCloud 6.0.3 if the
817
+     * app info version is expecting version 6.0, the comparison is
818
+     * made on the first two parts of the ownCloud version.
819
+     * This means that it's possible to specify "requiremin" => 6
820
+     * and "requiremax" => 6 and it will still match ownCloud 6.0.3.
821
+     *
822
+     * @param string $ocVersion ownCloud version to check against
823
+     * @param array $appInfo app info (from xml)
824
+     *
825
+     * @return boolean true if compatible, otherwise false
826
+     */
827
+    public static function isAppCompatible(string $ocVersion, array $appInfo): bool {
828
+        $requireMin = '';
829
+        $requireMax = '';
830
+        if (isset($appInfo['dependencies']['nextcloud']['@attributes']['min-version'])) {
831
+            $requireMin = $appInfo['dependencies']['nextcloud']['@attributes']['min-version'];
832
+        } elseif (isset($appInfo['dependencies']['owncloud']['@attributes']['min-version'])) {
833
+            $requireMin = $appInfo['dependencies']['owncloud']['@attributes']['min-version'];
834
+        } else if (isset($appInfo['requiremin'])) {
835
+            $requireMin = $appInfo['requiremin'];
836
+        } else if (isset($appInfo['require'])) {
837
+            $requireMin = $appInfo['require'];
838
+        }
839
+
840
+        if (isset($appInfo['dependencies']['nextcloud']['@attributes']['max-version'])) {
841
+            $requireMax = $appInfo['dependencies']['nextcloud']['@attributes']['max-version'];
842
+        } elseif (isset($appInfo['dependencies']['owncloud']['@attributes']['max-version'])) {
843
+            $requireMax = $appInfo['dependencies']['owncloud']['@attributes']['max-version'];
844
+        } else if (isset($appInfo['requiremax'])) {
845
+            $requireMax = $appInfo['requiremax'];
846
+        }
847
+
848
+        if (!empty($requireMin)
849
+            && version_compare(self::adjustVersionParts($ocVersion, $requireMin), $requireMin, '<')
850
+        ) {
851
+
852
+            return false;
853
+        }
854
+
855
+        if (!empty($requireMax)
856
+            && version_compare(self::adjustVersionParts($ocVersion, $requireMax), $requireMax, '>')
857
+        ) {
858
+            return false;
859
+        }
860
+
861
+        return true;
862
+    }
863
+
864
+    /**
865
+     * get the installed version of all apps
866
+     */
867
+    public static function getAppVersions() {
868
+        static $versions;
869
+
870
+        if(!$versions) {
871
+            $appConfig = \OC::$server->getAppConfig();
872
+            $versions = $appConfig->getValues(false, 'installed_version');
873
+        }
874
+        return $versions;
875
+    }
876
+
877
+    /**
878
+     * update the database for the app and call the update script
879
+     *
880
+     * @param string $appId
881
+     * @return bool
882
+     */
883
+    public static function updateApp(string $appId): bool {
884
+        $appPath = self::getAppPath($appId);
885
+        if($appPath === false) {
886
+            return false;
887
+        }
888
+        self::registerAutoloading($appId, $appPath);
889
+
890
+        \OC::$server->getAppManager()->clearAppsCache();
891
+        $appData = self::getAppInfo($appId);
892
+        self::executeRepairSteps($appId, $appData['repair-steps']['pre-migration']);
893
+
894
+        if (file_exists($appPath . '/appinfo/database.xml')) {
895
+            OC_DB::updateDbFromStructure($appPath . '/appinfo/database.xml');
896
+        } else {
897
+            $ms = new MigrationService($appId, \OC::$server->getDatabaseConnection());
898
+            $ms->migrate();
899
+        }
900
+
901
+        self::executeRepairSteps($appId, $appData['repair-steps']['post-migration']);
902
+        self::setupLiveMigrations($appId, $appData['repair-steps']['live-migration']);
903
+        // update appversion in app manager
904
+        \OC::$server->getAppManager()->getAppVersion($appId, false);
905
+
906
+        // run upgrade code
907
+        if (file_exists($appPath . '/appinfo/update.php')) {
908
+            self::loadApp($appId);
909
+            include $appPath . '/appinfo/update.php';
910
+        }
911
+        self::setupBackgroundJobs($appData['background-jobs']);
912
+
913
+        //set remote/public handlers
914
+        if (array_key_exists('ocsid', $appData)) {
915
+            \OC::$server->getConfig()->setAppValue($appId, 'ocsid', $appData['ocsid']);
916
+        } elseif(\OC::$server->getConfig()->getAppValue($appId, 'ocsid', null) !== null) {
917
+            \OC::$server->getConfig()->deleteAppValue($appId, 'ocsid');
918
+        }
919
+        foreach ($appData['remote'] as $name => $path) {
920
+            \OC::$server->getConfig()->setAppValue('core', 'remote_' . $name, $appId . '/' . $path);
921
+        }
922
+        foreach ($appData['public'] as $name => $path) {
923
+            \OC::$server->getConfig()->setAppValue('core', 'public_' . $name, $appId . '/' . $path);
924
+        }
925
+
926
+        self::setAppTypes($appId);
927
+
928
+        $version = \OC_App::getAppVersion($appId);
929
+        \OC::$server->getConfig()->setAppValue($appId, 'installed_version', $version);
930
+
931
+        \OC::$server->getEventDispatcher()->dispatch(ManagerEvent::EVENT_APP_UPDATE, new ManagerEvent(
932
+            ManagerEvent::EVENT_APP_UPDATE, $appId
933
+        ));
934
+
935
+        return true;
936
+    }
937
+
938
+    /**
939
+     * @param string $appId
940
+     * @param string[] $steps
941
+     * @throws \OC\NeedsUpdateException
942
+     */
943
+    public static function executeRepairSteps(string $appId, array $steps) {
944
+        if (empty($steps)) {
945
+            return;
946
+        }
947
+        // load the app
948
+        self::loadApp($appId);
949
+
950
+        $dispatcher = OC::$server->getEventDispatcher();
951
+
952
+        // load the steps
953
+        $r = new Repair([], $dispatcher);
954
+        foreach ($steps as $step) {
955
+            try {
956
+                $r->addStep($step);
957
+            } catch (Exception $ex) {
958
+                $r->emit('\OC\Repair', 'error', [$ex->getMessage()]);
959
+                \OC::$server->getLogger()->logException($ex);
960
+            }
961
+        }
962
+        // run the steps
963
+        $r->run();
964
+    }
965
+
966
+    public static function setupBackgroundJobs(array $jobs) {
967
+        $queue = \OC::$server->getJobList();
968
+        foreach ($jobs as $job) {
969
+            $queue->add($job);
970
+        }
971
+    }
972
+
973
+    /**
974
+     * @param string $appId
975
+     * @param string[] $steps
976
+     */
977
+    private static function setupLiveMigrations(string $appId, array $steps) {
978
+        $queue = \OC::$server->getJobList();
979
+        foreach ($steps as $step) {
980
+            $queue->add('OC\Migration\BackgroundRepair', [
981
+                'app' => $appId,
982
+                'step' => $step]);
983
+        }
984
+    }
985
+
986
+    /**
987
+     * @param string $appId
988
+     * @return \OC\Files\View|false
989
+     */
990
+    public static function getStorage(string $appId) {
991
+        if (\OC::$server->getAppManager()->isEnabledForUser($appId)) { //sanity check
992
+            if (\OC::$server->getUserSession()->isLoggedIn()) {
993
+                $view = new \OC\Files\View('/' . OC_User::getUser());
994
+                if (!$view->file_exists($appId)) {
995
+                    $view->mkdir($appId);
996
+                }
997
+                return new \OC\Files\View('/' . OC_User::getUser() . '/' . $appId);
998
+            } else {
999
+                \OCP\Util::writeLog('core', 'Can\'t get app storage, app ' . $appId . ', user not logged in', ILogger::ERROR);
1000
+                return false;
1001
+            }
1002
+        } else {
1003
+            \OCP\Util::writeLog('core', 'Can\'t get app storage, app ' . $appId . ' not enabled', ILogger::ERROR);
1004
+            return false;
1005
+        }
1006
+    }
1007
+
1008
+    protected static function findBestL10NOption(array $options, string $lang): string {
1009
+        // only a single option
1010
+        if (isset($options['@value'])) {
1011
+            return $options['@value'];
1012
+        }
1013
+
1014
+        $fallback = $similarLangFallback = $englishFallback = false;
1015
+
1016
+        $lang = strtolower($lang);
1017
+        $similarLang = $lang;
1018
+        if (strpos($similarLang, '_')) {
1019
+            // For "de_DE" we want to find "de" and the other way around
1020
+            $similarLang = substr($lang, 0, strpos($lang, '_'));
1021
+        }
1022
+
1023
+        foreach ($options as $option) {
1024
+            if (is_array($option)) {
1025
+                if ($fallback === false) {
1026
+                    $fallback = $option['@value'];
1027
+                }
1028
+
1029
+                if (!isset($option['@attributes']['lang'])) {
1030
+                    continue;
1031
+                }
1032
+
1033
+                $attributeLang = strtolower($option['@attributes']['lang']);
1034
+                if ($attributeLang === $lang) {
1035
+                    return $option['@value'];
1036
+                }
1037
+
1038
+                if ($attributeLang === $similarLang) {
1039
+                    $similarLangFallback = $option['@value'];
1040
+                } else if (strpos($attributeLang, $similarLang . '_') === 0) {
1041
+                    if ($similarLangFallback === false) {
1042
+                        $similarLangFallback =  $option['@value'];
1043
+                    }
1044
+                }
1045
+            } else {
1046
+                $englishFallback = $option;
1047
+            }
1048
+        }
1049
+
1050
+        if ($similarLangFallback !== false) {
1051
+            return $similarLangFallback;
1052
+        } else if ($englishFallback !== false) {
1053
+            return $englishFallback;
1054
+        }
1055
+        return (string) $fallback;
1056
+    }
1057
+
1058
+    /**
1059
+     * parses the app data array and enhanced the 'description' value
1060
+     *
1061
+     * @param array $data the app data
1062
+     * @param string $lang
1063
+     * @return array improved app data
1064
+     */
1065
+    public static function parseAppInfo(array $data, $lang = null): array {
1066
+
1067
+        if ($lang && isset($data['name']) && is_array($data['name'])) {
1068
+            $data['name'] = self::findBestL10NOption($data['name'], $lang);
1069
+        }
1070
+        if ($lang && isset($data['summary']) && is_array($data['summary'])) {
1071
+            $data['summary'] = self::findBestL10NOption($data['summary'], $lang);
1072
+        }
1073
+        if ($lang && isset($data['description']) && is_array($data['description'])) {
1074
+            $data['description'] = trim(self::findBestL10NOption($data['description'], $lang));
1075
+        } else if (isset($data['description']) && is_string($data['description'])) {
1076
+            $data['description'] = trim($data['description']);
1077
+        } else  {
1078
+            $data['description'] = '';
1079
+        }
1080
+
1081
+        return $data;
1082
+    }
1083
+
1084
+    /**
1085
+     * @param \OCP\IConfig $config
1086
+     * @param \OCP\IL10N $l
1087
+     * @param array $info
1088
+     * @throws \Exception
1089
+     */
1090
+    public static function checkAppDependencies(\OCP\IConfig $config, \OCP\IL10N $l, array $info) {
1091
+        $dependencyAnalyzer = new DependencyAnalyzer(new Platform($config), $l);
1092
+        $missing = $dependencyAnalyzer->analyze($info);
1093
+        if (!empty($missing)) {
1094
+            $missingMsg = implode(PHP_EOL, $missing);
1095
+            throw new \Exception(
1096
+                $l->t('App "%s" cannot be installed because the following dependencies are not fulfilled: %s',
1097
+                    [$info['name'], $missingMsg]
1098
+                )
1099
+            );
1100
+        }
1101
+    }
1102 1102
 }
Please login to merge, or discard this patch.