Completed
Pull Request — master (#8097)
by Julius
27:13 queued 08:28
created
lib/private/legacy/app.php 3 patches
Doc Comments   +5 added lines patch added patch discarded remove patch
@@ -1047,6 +1047,11 @@
 block discarded – undo
1047 1047
 		}
1048 1048
 	}
1049 1049
 
1050
+	/**
1051
+	 * @param string $lang
1052
+	 *
1053
+	 * @return string
1054
+	 */
1050 1055
 	protected static function findBestL10NOption($options, $lang) {
1051 1056
 		$fallback = $similarLangFallback = $englishFallback = false;
1052 1057
 
Please login to merge, or discard this patch.
Indentation   +1074 added lines, -1074 removed lines patch added patch discarded remove patch
@@ -62,1078 +62,1078 @@
 block discarded – undo
62 62
  * upgrading and removing apps.
63 63
  */
64 64
 class OC_App {
65
-	static private $adminForms = array();
66
-	static private $personalForms = array();
67
-	static private $appTypes = array();
68
-	static private $loadedApps = array();
69
-	static private $altLogin = array();
70
-	static private $alreadyRegistered = [];
71
-	const officialApp = 200;
72
-
73
-	/**
74
-	 * clean the appId
75
-	 *
76
-	 * @param string|boolean $app AppId that needs to be cleaned
77
-	 * @return string
78
-	 */
79
-	public static function cleanAppId($app) {
80
-		return str_replace(array('\0', '/', '\\', '..'), '', $app);
81
-	}
82
-
83
-	/**
84
-	 * Check if an app is loaded
85
-	 *
86
-	 * @param string $app
87
-	 * @return bool
88
-	 */
89
-	public static function isAppLoaded($app) {
90
-		return in_array($app, self::$loadedApps, true);
91
-	}
92
-
93
-	/**
94
-	 * loads all apps
95
-	 *
96
-	 * @param string[] | string | null $types
97
-	 * @return bool
98
-	 *
99
-	 * This function walks through the ownCloud directory and loads all apps
100
-	 * it can find. A directory contains an app if the file /appinfo/info.xml
101
-	 * exists.
102
-	 *
103
-	 * if $types is set, only apps of those types will be loaded
104
-	 */
105
-	public static function loadApps($types = null) {
106
-		if (\OC::$server->getSystemConfig()->getValue('maintenance', false)) {
107
-			return false;
108
-		}
109
-		// Load the enabled apps here
110
-		$apps = self::getEnabledApps();
111
-
112
-		// Add each apps' folder as allowed class path
113
-		foreach($apps as $app) {
114
-			$path = self::getAppPath($app);
115
-			if($path !== false) {
116
-				self::registerAutoloading($app, $path);
117
-			}
118
-		}
119
-
120
-		// prevent app.php from printing output
121
-		ob_start();
122
-		foreach ($apps as $app) {
123
-			if ((is_null($types) or self::isType($app, $types)) && !in_array($app, self::$loadedApps)) {
124
-				self::loadApp($app);
125
-			}
126
-		}
127
-		ob_end_clean();
128
-
129
-		return true;
130
-	}
131
-
132
-	/**
133
-	 * load a single app
134
-	 *
135
-	 * @param string $app
136
-	 */
137
-	public static function loadApp($app) {
138
-		self::$loadedApps[] = $app;
139
-		$appPath = self::getAppPath($app);
140
-		if($appPath === false) {
141
-			return;
142
-		}
143
-
144
-		// in case someone calls loadApp() directly
145
-		self::registerAutoloading($app, $appPath);
146
-
147
-		if (is_file($appPath . '/appinfo/app.php')) {
148
-			\OC::$server->getEventLogger()->start('load_app_' . $app, 'Load app: ' . $app);
149
-			self::requireAppFile($app);
150
-			if (self::isType($app, array('authentication'))) {
151
-				// since authentication apps affect the "is app enabled for group" check,
152
-				// the enabled apps cache needs to be cleared to make sure that the
153
-				// next time getEnableApps() is called it will also include apps that were
154
-				// enabled for groups
155
-				self::$enabledAppsCache = array();
156
-			}
157
-			\OC::$server->getEventLogger()->end('load_app_' . $app);
158
-		}
159
-
160
-		$info = self::getAppInfo($app);
161
-		if (!empty($info['activity']['filters'])) {
162
-			foreach ($info['activity']['filters'] as $filter) {
163
-				\OC::$server->getActivityManager()->registerFilter($filter);
164
-			}
165
-		}
166
-		if (!empty($info['activity']['settings'])) {
167
-			foreach ($info['activity']['settings'] as $setting) {
168
-				\OC::$server->getActivityManager()->registerSetting($setting);
169
-			}
170
-		}
171
-		if (!empty($info['activity']['providers'])) {
172
-			foreach ($info['activity']['providers'] as $provider) {
173
-				\OC::$server->getActivityManager()->registerProvider($provider);
174
-			}
175
-		}
176
-		if (!empty($info['collaboration']['plugins'])) {
177
-			// deal with one or many plugin entries
178
-			$plugins = isset($info['collaboration']['plugins']['plugin']['@value']) ?
179
-				[$info['collaboration']['plugins']['plugin']] : $info['collaboration']['plugins']['plugin'];
180
-			foreach ($plugins as $plugin) {
181
-				if($plugin['@attributes']['type'] === 'collaborator-search') {
182
-					$pluginInfo = [
183
-						'shareType' => $plugin['@attributes']['share-type'],
184
-						'class' => $plugin['@value'],
185
-					];
186
-					\OC::$server->getCollaboratorSearch()->registerPlugin($pluginInfo);
187
-				} else if ($plugin['@attributes']['type'] === 'autocomplete-sort') {
188
-					\OC::$server->getAutoCompleteManager()->registerSorter($plugin['@value']);
189
-				}
190
-			}
191
-		}
192
-	}
193
-
194
-	/**
195
-	 * @internal
196
-	 * @param string $app
197
-	 * @param string $path
198
-	 */
199
-	public static function registerAutoloading($app, $path) {
200
-		$key = $app . '-' . $path;
201
-		if(isset(self::$alreadyRegistered[$key])) {
202
-			return;
203
-		}
204
-
205
-		self::$alreadyRegistered[$key] = true;
206
-
207
-		// Register on PSR-4 composer autoloader
208
-		$appNamespace = \OC\AppFramework\App::buildAppNamespace($app);
209
-		\OC::$server->registerNamespace($app, $appNamespace);
210
-
211
-		if (file_exists($path . '/composer/autoload.php')) {
212
-			require_once $path . '/composer/autoload.php';
213
-		} else {
214
-			\OC::$composerAutoloader->addPsr4($appNamespace . '\\', $path . '/lib/', true);
215
-			// Register on legacy autoloader
216
-			\OC::$loader->addValidRoot($path);
217
-		}
218
-
219
-		// Register Test namespace only when testing
220
-		if (defined('PHPUNIT_RUN') || defined('CLI_TEST_RUN')) {
221
-			\OC::$composerAutoloader->addPsr4($appNamespace . '\\Tests\\', $path . '/tests/', true);
222
-		}
223
-	}
224
-
225
-	/**
226
-	 * Load app.php from the given app
227
-	 *
228
-	 * @param string $app app name
229
-	 */
230
-	private static function requireAppFile($app) {
231
-		try {
232
-			// encapsulated here to avoid variable scope conflicts
233
-			require_once $app . '/appinfo/app.php';
234
-		} catch (Error $ex) {
235
-			\OC::$server->getLogger()->logException($ex);
236
-			if (!\OC::$server->getAppManager()->isShipped($app)) {
237
-				// Only disable apps which are not shipped
238
-				self::disable($app);
239
-			}
240
-		}
241
-	}
242
-
243
-	/**
244
-	 * check if an app is of a specific type
245
-	 *
246
-	 * @param string $app
247
-	 * @param string|array $types
248
-	 * @return bool
249
-	 */
250
-	public static function isType($app, $types) {
251
-		if (is_string($types)) {
252
-			$types = array($types);
253
-		}
254
-		$appTypes = self::getAppTypes($app);
255
-		foreach ($types as $type) {
256
-			if (array_search($type, $appTypes) !== false) {
257
-				return true;
258
-			}
259
-		}
260
-		return false;
261
-	}
262
-
263
-	/**
264
-	 * get the types of an app
265
-	 *
266
-	 * @param string $app
267
-	 * @return array
268
-	 */
269
-	private static function getAppTypes($app) {
270
-		//load the cache
271
-		if (count(self::$appTypes) == 0) {
272
-			self::$appTypes = \OC::$server->getAppConfig()->getValues(false, 'types');
273
-		}
274
-
275
-		if (isset(self::$appTypes[$app])) {
276
-			return explode(',', self::$appTypes[$app]);
277
-		} else {
278
-			return array();
279
-		}
280
-	}
281
-
282
-	/**
283
-	 * read app types from info.xml and cache them in the database
284
-	 */
285
-	public static function setAppTypes($app) {
286
-		$appData = self::getAppInfo($app);
287
-		if(!is_array($appData)) {
288
-			return;
289
-		}
290
-
291
-		if (isset($appData['types'])) {
292
-			$appTypes = implode(',', $appData['types']);
293
-		} else {
294
-			$appTypes = '';
295
-			$appData['types'] = [];
296
-		}
297
-
298
-		\OC::$server->getConfig()->setAppValue($app, 'types', $appTypes);
299
-
300
-		if (\OC::$server->getAppManager()->hasProtectedAppType($appData['types'])) {
301
-			$enabled = \OC::$server->getConfig()->getAppValue($app, 'enabled', 'yes');
302
-			if ($enabled !== 'yes' && $enabled !== 'no') {
303
-				\OC::$server->getConfig()->setAppValue($app, 'enabled', 'yes');
304
-			}
305
-		}
306
-	}
307
-
308
-	/**
309
-	 * get all enabled apps
310
-	 */
311
-	protected static $enabledAppsCache = array();
312
-
313
-	/**
314
-	 * Returns apps enabled for the current user.
315
-	 *
316
-	 * @param bool $forceRefresh whether to refresh the cache
317
-	 * @param bool $all whether to return apps for all users, not only the
318
-	 * currently logged in one
319
-	 * @return string[]
320
-	 */
321
-	public static function getEnabledApps($forceRefresh = false, $all = false) {
322
-		if (!\OC::$server->getSystemConfig()->getValue('installed', false)) {
323
-			return array();
324
-		}
325
-		// in incognito mode or when logged out, $user will be false,
326
-		// which is also the case during an upgrade
327
-		$appManager = \OC::$server->getAppManager();
328
-		if ($all) {
329
-			$user = null;
330
-		} else {
331
-			$user = \OC::$server->getUserSession()->getUser();
332
-		}
333
-
334
-		if (is_null($user)) {
335
-			$apps = $appManager->getInstalledApps();
336
-		} else {
337
-			$apps = $appManager->getEnabledAppsForUser($user);
338
-		}
339
-		$apps = array_filter($apps, function ($app) {
340
-			return $app !== 'files';//we add this manually
341
-		});
342
-		sort($apps);
343
-		array_unshift($apps, 'files');
344
-		return $apps;
345
-	}
346
-
347
-	/**
348
-	 * checks whether or not an app is enabled
349
-	 *
350
-	 * @param string $app app
351
-	 * @return bool
352
-	 * @deprecated 13.0.0 use \OC::$server->getAppManager()->isEnabledForUser($appId)
353
-	 *
354
-	 * This function checks whether or not an app is enabled.
355
-	 */
356
-	public static function isEnabled($app) {
357
-		return \OC::$server->getAppManager()->isEnabledForUser($app);
358
-	}
359
-
360
-	/**
361
-	 * enables an app
362
-	 *
363
-	 * @param string $appId
364
-	 * @param array $groups (optional) when set, only these groups will have access to the app
365
-	 * @throws \Exception
366
-	 * @return void
367
-	 *
368
-	 * This function set an app as enabled in appconfig.
369
-	 */
370
-	public function enable($appId,
371
-						   $groups = null) {
372
-		self::$enabledAppsCache = []; // flush
373
-
374
-		// Check if app is already downloaded
375
-		$installer = \OC::$server->query(Installer::class);
376
-		$isDownloaded = $installer->isDownloaded($appId);
377
-
378
-		if(!$isDownloaded) {
379
-			$installer->downloadApp($appId);
380
-		}
381
-
382
-		$installer->installApp($appId);
383
-
384
-		$appManager = \OC::$server->getAppManager();
385
-		if (!is_null($groups)) {
386
-			$groupManager = \OC::$server->getGroupManager();
387
-			$groupsList = [];
388
-			foreach ($groups as $group) {
389
-				$groupItem = $groupManager->get($group);
390
-				if ($groupItem instanceof \OCP\IGroup) {
391
-					$groupsList[] = $groupManager->get($group);
392
-				}
393
-			}
394
-			$appManager->enableAppForGroups($appId, $groupsList);
395
-		} else {
396
-			$appManager->enableApp($appId);
397
-		}
398
-	}
399
-
400
-	/**
401
-	 * This function set an app as disabled in appconfig.
402
-	 *
403
-	 * @param string $app app
404
-	 * @throws Exception
405
-	 */
406
-	public static function disable($app) {
407
-		// flush
408
-		self::$enabledAppsCache = array();
409
-
410
-		// run uninstall steps
411
-		$appData = OC_App::getAppInfo($app);
412
-		if (!is_null($appData)) {
413
-			OC_App::executeRepairSteps($app, $appData['repair-steps']['uninstall']);
414
-		}
415
-
416
-		// emit disable hook - needed anymore ?
417
-		\OC_Hook::emit('OC_App', 'pre_disable', array('app' => $app));
418
-
419
-		// finally disable it
420
-		$appManager = \OC::$server->getAppManager();
421
-		$appManager->disableApp($app);
422
-	}
423
-
424
-	// This is private as well. It simply works, so don't ask for more details
425
-	private static function proceedNavigation($list) {
426
-		usort($list, function($a, $b) {
427
-			if (isset($a['order']) && isset($b['order'])) {
428
-				return ($a['order'] < $b['order']) ? -1 : 1;
429
-			} else if (isset($a['order']) || isset($b['order'])) {
430
-				return isset($a['order']) ? -1 : 1;
431
-			} else {
432
-				return ($a['name'] < $b['name']) ? -1 : 1;
433
-			}
434
-		});
435
-
436
-		$activeApp = OC::$server->getNavigationManager()->getActiveEntry();
437
-		foreach ($list as $index => &$navEntry) {
438
-			if ($navEntry['id'] == $activeApp) {
439
-				$navEntry['active'] = true;
440
-			} else {
441
-				$navEntry['active'] = false;
442
-			}
443
-		}
444
-		unset($navEntry);
445
-
446
-		return $list;
447
-	}
448
-
449
-	/**
450
-	 * Get the path where to install apps
451
-	 *
452
-	 * @return string|false
453
-	 */
454
-	public static function getInstallPath() {
455
-		if (\OC::$server->getSystemConfig()->getValue('appstoreenabled', true) == false) {
456
-			return false;
457
-		}
458
-
459
-		foreach (OC::$APPSROOTS as $dir) {
460
-			if (isset($dir['writable']) && $dir['writable'] === true) {
461
-				return $dir['path'];
462
-			}
463
-		}
464
-
465
-		\OCP\Util::writeLog('core', 'No application directories are marked as writable.', \OCP\Util::ERROR);
466
-		return null;
467
-	}
468
-
469
-
470
-	/**
471
-	 * search for an app in all app-directories
472
-	 *
473
-	 * @param string $appId
474
-	 * @return false|string
475
-	 */
476
-	public static function findAppInDirectories($appId) {
477
-		$sanitizedAppId = self::cleanAppId($appId);
478
-		if($sanitizedAppId !== $appId) {
479
-			return false;
480
-		}
481
-		static $app_dir = array();
482
-
483
-		if (isset($app_dir[$appId])) {
484
-			return $app_dir[$appId];
485
-		}
486
-
487
-		$possibleApps = array();
488
-		foreach (OC::$APPSROOTS as $dir) {
489
-			if (file_exists($dir['path'] . '/' . $appId)) {
490
-				$possibleApps[] = $dir;
491
-			}
492
-		}
493
-
494
-		if (empty($possibleApps)) {
495
-			return false;
496
-		} elseif (count($possibleApps) === 1) {
497
-			$dir = array_shift($possibleApps);
498
-			$app_dir[$appId] = $dir;
499
-			return $dir;
500
-		} else {
501
-			$versionToLoad = array();
502
-			foreach ($possibleApps as $possibleApp) {
503
-				$version = self::getAppVersionByPath($possibleApp['path']);
504
-				if (empty($versionToLoad) || version_compare($version, $versionToLoad['version'], '>')) {
505
-					$versionToLoad = array(
506
-						'dir' => $possibleApp,
507
-						'version' => $version,
508
-					);
509
-				}
510
-			}
511
-			$app_dir[$appId] = $versionToLoad['dir'];
512
-			return $versionToLoad['dir'];
513
-			//TODO - write test
514
-		}
515
-	}
516
-
517
-	/**
518
-	 * Get the directory for the given app.
519
-	 * If the app is defined in multiple directories, the first one is taken. (false if not found)
520
-	 *
521
-	 * @param string $appId
522
-	 * @return string|false
523
-	 */
524
-	public static function getAppPath($appId) {
525
-		if ($appId === null || trim($appId) === '') {
526
-			return false;
527
-		}
528
-
529
-		if (($dir = self::findAppInDirectories($appId)) != false) {
530
-			return $dir['path'] . '/' . $appId;
531
-		}
532
-		return false;
533
-	}
534
-
535
-	/**
536
-	 * Get the path for the given app on the access
537
-	 * If the app is defined in multiple directories, the first one is taken. (false if not found)
538
-	 *
539
-	 * @param string $appId
540
-	 * @return string|false
541
-	 */
542
-	public static function getAppWebPath($appId) {
543
-		if (($dir = self::findAppInDirectories($appId)) != false) {
544
-			return OC::$WEBROOT . $dir['url'] . '/' . $appId;
545
-		}
546
-		return false;
547
-	}
548
-
549
-	/**
550
-	 * get the last version of the app from appinfo/info.xml
551
-	 *
552
-	 * @param string $appId
553
-	 * @param bool $useCache
554
-	 * @return string
555
-	 * @deprecated 14.0.0 use \OC::$server->getAppManager()->getAppVersion()
556
-	 */
557
-	public static function getAppVersion($appId, $useCache = true) {
558
-		return \OC::$server->getAppManager()->getAppVersion($appId, $useCache);
559
-	}
560
-
561
-	/**
562
-	 * get app's version based on it's path
563
-	 *
564
-	 * @param string $path
565
-	 * @return string
566
-	 */
567
-	public static function getAppVersionByPath($path) {
568
-		$infoFile = $path . '/appinfo/info.xml';
569
-		$appData = \OC::$server->getAppManager()->getAppInfo($infoFile, true);
570
-		return isset($appData['version']) ? $appData['version'] : '';
571
-	}
572
-
573
-
574
-	/**
575
-	 * Read all app metadata from the info.xml file
576
-	 *
577
-	 * @param string $appId id of the app or the path of the info.xml file
578
-	 * @param bool $path
579
-	 * @param string $lang
580
-	 * @return array|null
581
-	 * @note all data is read from info.xml, not just pre-defined fields
582
-	 * @deprecated 14.0.0 use \OC::$server->getAppManager()->getAppInfo()
583
-	 */
584
-	public static function getAppInfo($appId, $path = false, $lang = null) {
585
-		return \OC::$server->getAppManager()->getAppInfo($appId, $path, $lang);
586
-	}
587
-
588
-	/**
589
-	 * Returns the navigation
590
-	 *
591
-	 * @return array
592
-	 *
593
-	 * This function returns an array containing all entries added. The
594
-	 * entries are sorted by the key 'order' ascending. Additional to the keys
595
-	 * given for each app the following keys exist:
596
-	 *   - active: boolean, signals if the user is on this navigation entry
597
-	 */
598
-	public static function getNavigation() {
599
-		$entries = OC::$server->getNavigationManager()->getAll();
600
-		return self::proceedNavigation($entries);
601
-	}
602
-
603
-	/**
604
-	 * Returns the Settings Navigation
605
-	 *
606
-	 * @return string[]
607
-	 *
608
-	 * This function returns an array containing all settings pages added. The
609
-	 * entries are sorted by the key 'order' ascending.
610
-	 */
611
-	public static function getSettingsNavigation() {
612
-		$entries = OC::$server->getNavigationManager()->getAll('settings');
613
-		return self::proceedNavigation($entries);
614
-	}
615
-
616
-	/**
617
-	 * get the id of loaded app
618
-	 *
619
-	 * @return string
620
-	 */
621
-	public static function getCurrentApp() {
622
-		$request = \OC::$server->getRequest();
623
-		$script = substr($request->getScriptName(), strlen(OC::$WEBROOT) + 1);
624
-		$topFolder = substr($script, 0, strpos($script, '/') ?: 0);
625
-		if (empty($topFolder)) {
626
-			$path_info = $request->getPathInfo();
627
-			if ($path_info) {
628
-				$topFolder = substr($path_info, 1, strpos($path_info, '/', 1) - 1);
629
-			}
630
-		}
631
-		if ($topFolder == 'apps') {
632
-			$length = strlen($topFolder);
633
-			return substr($script, $length + 1, strpos($script, '/', $length + 1) - $length - 1);
634
-		} else {
635
-			return $topFolder;
636
-		}
637
-	}
638
-
639
-	/**
640
-	 * @param string $type
641
-	 * @return array
642
-	 */
643
-	public static function getForms($type) {
644
-		$forms = array();
645
-		switch ($type) {
646
-			case 'admin':
647
-				$source = self::$adminForms;
648
-				break;
649
-			case 'personal':
650
-				$source = self::$personalForms;
651
-				break;
652
-			default:
653
-				return array();
654
-		}
655
-		foreach ($source as $form) {
656
-			$forms[] = include $form;
657
-		}
658
-		return $forms;
659
-	}
660
-
661
-	/**
662
-	 * register an admin form to be shown
663
-	 *
664
-	 * @param string $app
665
-	 * @param string $page
666
-	 */
667
-	public static function registerAdmin($app, $page) {
668
-		self::$adminForms[] = $app . '/' . $page . '.php';
669
-	}
670
-
671
-	/**
672
-	 * register a personal form to be shown
673
-	 * @param string $app
674
-	 * @param string $page
675
-	 */
676
-	public static function registerPersonal($app, $page) {
677
-		self::$personalForms[] = $app . '/' . $page . '.php';
678
-	}
679
-
680
-	/**
681
-	 * @param array $entry
682
-	 */
683
-	public static function registerLogIn(array $entry) {
684
-		self::$altLogin[] = $entry;
685
-	}
686
-
687
-	/**
688
-	 * @return array
689
-	 */
690
-	public static function getAlternativeLogIns() {
691
-		return self::$altLogin;
692
-	}
693
-
694
-	/**
695
-	 * get a list of all apps in the apps folder
696
-	 *
697
-	 * @return array an array of app names (string IDs)
698
-	 * @todo: change the name of this method to getInstalledApps, which is more accurate
699
-	 */
700
-	public static function getAllApps() {
701
-
702
-		$apps = array();
703
-
704
-		foreach (OC::$APPSROOTS as $apps_dir) {
705
-			if (!is_readable($apps_dir['path'])) {
706
-				\OCP\Util::writeLog('core', 'unable to read app folder : ' . $apps_dir['path'], \OCP\Util::WARN);
707
-				continue;
708
-			}
709
-			$dh = opendir($apps_dir['path']);
710
-
711
-			if (is_resource($dh)) {
712
-				while (($file = readdir($dh)) !== false) {
713
-
714
-					if ($file[0] != '.' and is_dir($apps_dir['path'] . '/' . $file) and is_file($apps_dir['path'] . '/' . $file . '/appinfo/info.xml')) {
715
-
716
-						$apps[] = $file;
717
-					}
718
-				}
719
-			}
720
-		}
721
-
722
-		$apps = array_unique($apps);
723
-
724
-		return $apps;
725
-	}
726
-
727
-	/**
728
-	 * List all apps, this is used in apps.php
729
-	 *
730
-	 * @return array
731
-	 */
732
-	public function listAllApps() {
733
-		$installedApps = OC_App::getAllApps();
734
-
735
-		$appManager = \OC::$server->getAppManager();
736
-		//we don't want to show configuration for these
737
-		$blacklist = $appManager->getAlwaysEnabledApps();
738
-		$appList = array();
739
-		$langCode = \OC::$server->getL10N('core')->getLanguageCode();
740
-		$urlGenerator = \OC::$server->getURLGenerator();
741
-
742
-		foreach ($installedApps as $app) {
743
-			if (array_search($app, $blacklist) === false) {
744
-
745
-				$info = OC_App::getAppInfo($app, false, $langCode);
746
-				if (!is_array($info)) {
747
-					\OCP\Util::writeLog('core', 'Could not read app info file for app "' . $app . '"', \OCP\Util::ERROR);
748
-					continue;
749
-				}
750
-
751
-				if (!isset($info['name'])) {
752
-					\OCP\Util::writeLog('core', 'App id "' . $app . '" has no name in appinfo', \OCP\Util::ERROR);
753
-					continue;
754
-				}
755
-
756
-				$enabled = \OC::$server->getConfig()->getAppValue($app, 'enabled', 'no');
757
-				$info['groups'] = null;
758
-				if ($enabled === 'yes') {
759
-					$active = true;
760
-				} else if ($enabled === 'no') {
761
-					$active = false;
762
-				} else {
763
-					$active = true;
764
-					$info['groups'] = $enabled;
765
-				}
766
-
767
-				$info['active'] = $active;
768
-
769
-				if ($appManager->isShipped($app)) {
770
-					$info['internal'] = true;
771
-					$info['level'] = self::officialApp;
772
-					$info['removable'] = false;
773
-				} else {
774
-					$info['internal'] = false;
775
-					$info['removable'] = true;
776
-				}
777
-
778
-				$appPath = self::getAppPath($app);
779
-				if($appPath !== false) {
780
-					$appIcon = $appPath . '/img/' . $app . '.svg';
781
-					if (file_exists($appIcon)) {
782
-						$info['preview'] = $urlGenerator->imagePath($app, $app . '.svg');
783
-						$info['previewAsIcon'] = true;
784
-					} else {
785
-						$appIcon = $appPath . '/img/app.svg';
786
-						if (file_exists($appIcon)) {
787
-							$info['preview'] = $urlGenerator->imagePath($app, 'app.svg');
788
-							$info['previewAsIcon'] = true;
789
-						}
790
-					}
791
-				}
792
-				// fix documentation
793
-				if (isset($info['documentation']) && is_array($info['documentation'])) {
794
-					foreach ($info['documentation'] as $key => $url) {
795
-						// If it is not an absolute URL we assume it is a key
796
-						// i.e. admin-ldap will get converted to go.php?to=admin-ldap
797
-						if (stripos($url, 'https://') !== 0 && stripos($url, 'http://') !== 0) {
798
-							$url = $urlGenerator->linkToDocs($url);
799
-						}
800
-
801
-						$info['documentation'][$key] = $url;
802
-					}
803
-				}
804
-
805
-				$info['version'] = OC_App::getAppVersion($app);
806
-				$appList[] = $info;
807
-			}
808
-		}
809
-
810
-		return $appList;
811
-	}
812
-
813
-	public static function shouldUpgrade($app) {
814
-		$versions = self::getAppVersions();
815
-		$currentVersion = OC_App::getAppVersion($app);
816
-		if ($currentVersion && isset($versions[$app])) {
817
-			$installedVersion = $versions[$app];
818
-			if (!version_compare($currentVersion, $installedVersion, '=')) {
819
-				return true;
820
-			}
821
-		}
822
-		return false;
823
-	}
824
-
825
-	/**
826
-	 * Adjust the number of version parts of $version1 to match
827
-	 * the number of version parts of $version2.
828
-	 *
829
-	 * @param string $version1 version to adjust
830
-	 * @param string $version2 version to take the number of parts from
831
-	 * @return string shortened $version1
832
-	 */
833
-	private static function adjustVersionParts($version1, $version2) {
834
-		$version1 = explode('.', $version1);
835
-		$version2 = explode('.', $version2);
836
-		// reduce $version1 to match the number of parts in $version2
837
-		while (count($version1) > count($version2)) {
838
-			array_pop($version1);
839
-		}
840
-		// if $version1 does not have enough parts, add some
841
-		while (count($version1) < count($version2)) {
842
-			$version1[] = '0';
843
-		}
844
-		return implode('.', $version1);
845
-	}
846
-
847
-	/**
848
-	 * Check whether the current ownCloud version matches the given
849
-	 * application's version requirements.
850
-	 *
851
-	 * The comparison is made based on the number of parts that the
852
-	 * app info version has. For example for ownCloud 6.0.3 if the
853
-	 * app info version is expecting version 6.0, the comparison is
854
-	 * made on the first two parts of the ownCloud version.
855
-	 * This means that it's possible to specify "requiremin" => 6
856
-	 * and "requiremax" => 6 and it will still match ownCloud 6.0.3.
857
-	 *
858
-	 * @param string $ocVersion ownCloud version to check against
859
-	 * @param array $appInfo app info (from xml)
860
-	 *
861
-	 * @return boolean true if compatible, otherwise false
862
-	 */
863
-	public static function isAppCompatible($ocVersion, $appInfo) {
864
-		$requireMin = '';
865
-		$requireMax = '';
866
-		if (isset($appInfo['dependencies']['nextcloud']['@attributes']['min-version'])) {
867
-			$requireMin = $appInfo['dependencies']['nextcloud']['@attributes']['min-version'];
868
-		} elseif (isset($appInfo['dependencies']['owncloud']['@attributes']['min-version'])) {
869
-			$requireMin = $appInfo['dependencies']['owncloud']['@attributes']['min-version'];
870
-		} else if (isset($appInfo['requiremin'])) {
871
-			$requireMin = $appInfo['requiremin'];
872
-		} else if (isset($appInfo['require'])) {
873
-			$requireMin = $appInfo['require'];
874
-		}
875
-
876
-		if (isset($appInfo['dependencies']['nextcloud']['@attributes']['max-version'])) {
877
-			$requireMax = $appInfo['dependencies']['nextcloud']['@attributes']['max-version'];
878
-		} elseif (isset($appInfo['dependencies']['owncloud']['@attributes']['max-version'])) {
879
-			$requireMax = $appInfo['dependencies']['owncloud']['@attributes']['max-version'];
880
-		} else if (isset($appInfo['requiremax'])) {
881
-			$requireMax = $appInfo['requiremax'];
882
-		}
883
-
884
-		if (is_array($ocVersion)) {
885
-			$ocVersion = implode('.', $ocVersion);
886
-		}
887
-
888
-		if (!empty($requireMin)
889
-			&& version_compare(self::adjustVersionParts($ocVersion, $requireMin), $requireMin, '<')
890
-		) {
891
-
892
-			return false;
893
-		}
894
-
895
-		if (!empty($requireMax)
896
-			&& version_compare(self::adjustVersionParts($ocVersion, $requireMax), $requireMax, '>')
897
-		) {
898
-			return false;
899
-		}
900
-
901
-		return true;
902
-	}
903
-
904
-	/**
905
-	 * get the installed version of all apps
906
-	 */
907
-	public static function getAppVersions() {
908
-		static $versions;
909
-
910
-		if(!$versions) {
911
-			$appConfig = \OC::$server->getAppConfig();
912
-			$versions = $appConfig->getValues(false, 'installed_version');
913
-		}
914
-		return $versions;
915
-	}
916
-
917
-	/**
918
-	 * update the database for the app and call the update script
919
-	 *
920
-	 * @param string $appId
921
-	 * @return bool
922
-	 */
923
-	public static function updateApp($appId) {
924
-		$appPath = self::getAppPath($appId);
925
-		if($appPath === false) {
926
-			return false;
927
-		}
928
-		self::registerAutoloading($appId, $appPath);
929
-
930
-		$appData = self::getAppInfo($appId);
931
-		self::executeRepairSteps($appId, $appData['repair-steps']['pre-migration']);
932
-
933
-		if (file_exists($appPath . '/appinfo/database.xml')) {
934
-			OC_DB::updateDbFromStructure($appPath . '/appinfo/database.xml');
935
-		} else {
936
-			$ms = new MigrationService($appId, \OC::$server->getDatabaseConnection());
937
-			$ms->migrate();
938
-		}
939
-
940
-		self::executeRepairSteps($appId, $appData['repair-steps']['post-migration']);
941
-		self::setupLiveMigrations($appId, $appData['repair-steps']['live-migration']);
942
-		// update appversion in app manager
943
-		\OC::$server->getAppManager()->getAppVersion($appId, false);
944
-
945
-		// run upgrade code
946
-		if (file_exists($appPath . '/appinfo/update.php')) {
947
-			self::loadApp($appId);
948
-			include $appPath . '/appinfo/update.php';
949
-		}
950
-		self::setupBackgroundJobs($appData['background-jobs']);
951
-		if(isset($appData['settings']) && is_array($appData['settings'])) {
952
-			\OC::$server->getSettingsManager()->setupSettings($appData['settings']);
953
-		}
954
-
955
-		//set remote/public handlers
956
-		if (array_key_exists('ocsid', $appData)) {
957
-			\OC::$server->getConfig()->setAppValue($appId, 'ocsid', $appData['ocsid']);
958
-		} elseif(\OC::$server->getConfig()->getAppValue($appId, 'ocsid', null) !== null) {
959
-			\OC::$server->getConfig()->deleteAppValue($appId, 'ocsid');
960
-		}
961
-		foreach ($appData['remote'] as $name => $path) {
962
-			\OC::$server->getConfig()->setAppValue('core', 'remote_' . $name, $appId . '/' . $path);
963
-		}
964
-		foreach ($appData['public'] as $name => $path) {
965
-			\OC::$server->getConfig()->setAppValue('core', 'public_' . $name, $appId . '/' . $path);
966
-		}
967
-
968
-		self::setAppTypes($appId);
969
-
970
-		$version = \OC_App::getAppVersion($appId);
971
-		\OC::$server->getConfig()->setAppValue($appId, 'installed_version', $version);
972
-
973
-		\OC::$server->getEventDispatcher()->dispatch(ManagerEvent::EVENT_APP_UPDATE, new ManagerEvent(
974
-			ManagerEvent::EVENT_APP_UPDATE, $appId
975
-		));
976
-
977
-		return true;
978
-	}
979
-
980
-	/**
981
-	 * @param string $appId
982
-	 * @param string[] $steps
983
-	 * @throws \OC\NeedsUpdateException
984
-	 */
985
-	public static function executeRepairSteps($appId, array $steps) {
986
-		if (empty($steps)) {
987
-			return;
988
-		}
989
-		// load the app
990
-		self::loadApp($appId);
991
-
992
-		$dispatcher = OC::$server->getEventDispatcher();
993
-
994
-		// load the steps
995
-		$r = new Repair([], $dispatcher);
996
-		foreach ($steps as $step) {
997
-			try {
998
-				$r->addStep($step);
999
-			} catch (Exception $ex) {
1000
-				$r->emit('\OC\Repair', 'error', [$ex->getMessage()]);
1001
-				\OC::$server->getLogger()->logException($ex);
1002
-			}
1003
-		}
1004
-		// run the steps
1005
-		$r->run();
1006
-	}
1007
-
1008
-	public static function setupBackgroundJobs(array $jobs) {
1009
-		$queue = \OC::$server->getJobList();
1010
-		foreach ($jobs as $job) {
1011
-			$queue->add($job);
1012
-		}
1013
-	}
1014
-
1015
-	/**
1016
-	 * @param string $appId
1017
-	 * @param string[] $steps
1018
-	 */
1019
-	private static function setupLiveMigrations($appId, array $steps) {
1020
-		$queue = \OC::$server->getJobList();
1021
-		foreach ($steps as $step) {
1022
-			$queue->add('OC\Migration\BackgroundRepair', [
1023
-				'app' => $appId,
1024
-				'step' => $step]);
1025
-		}
1026
-	}
1027
-
1028
-	/**
1029
-	 * @param string $appId
1030
-	 * @return \OC\Files\View|false
1031
-	 */
1032
-	public static function getStorage($appId) {
1033
-		if (\OC::$server->getAppManager()->isEnabledForUser($appId)) { //sanity check
1034
-			if (\OC::$server->getUserSession()->isLoggedIn()) {
1035
-				$view = new \OC\Files\View('/' . OC_User::getUser());
1036
-				if (!$view->file_exists($appId)) {
1037
-					$view->mkdir($appId);
1038
-				}
1039
-				return new \OC\Files\View('/' . OC_User::getUser() . '/' . $appId);
1040
-			} else {
1041
-				\OCP\Util::writeLog('core', 'Can\'t get app storage, app ' . $appId . ', user not logged in', \OCP\Util::ERROR);
1042
-				return false;
1043
-			}
1044
-		} else {
1045
-			\OCP\Util::writeLog('core', 'Can\'t get app storage, app ' . $appId . ' not enabled', \OCP\Util::ERROR);
1046
-			return false;
1047
-		}
1048
-	}
1049
-
1050
-	protected static function findBestL10NOption($options, $lang) {
1051
-		$fallback = $similarLangFallback = $englishFallback = false;
1052
-
1053
-		$lang = strtolower($lang);
1054
-		$similarLang = $lang;
1055
-		if (strpos($similarLang, '_')) {
1056
-			// For "de_DE" we want to find "de" and the other way around
1057
-			$similarLang = substr($lang, 0, strpos($lang, '_'));
1058
-		}
1059
-
1060
-		foreach ($options as $option) {
1061
-			if (is_array($option)) {
1062
-				if ($fallback === false) {
1063
-					$fallback = $option['@value'];
1064
-				}
1065
-
1066
-				if (!isset($option['@attributes']['lang'])) {
1067
-					continue;
1068
-				}
1069
-
1070
-				$attributeLang = strtolower($option['@attributes']['lang']);
1071
-				if ($attributeLang === $lang) {
1072
-					return $option['@value'];
1073
-				}
1074
-
1075
-				if ($attributeLang === $similarLang) {
1076
-					$similarLangFallback = $option['@value'];
1077
-				} else if (strpos($attributeLang, $similarLang . '_') === 0) {
1078
-					if ($similarLangFallback === false) {
1079
-						$similarLangFallback =  $option['@value'];
1080
-					}
1081
-				}
1082
-			} else {
1083
-				$englishFallback = $option;
1084
-			}
1085
-		}
1086
-
1087
-		if ($similarLangFallback !== false) {
1088
-			return $similarLangFallback;
1089
-		} else if ($englishFallback !== false) {
1090
-			return $englishFallback;
1091
-		}
1092
-		return (string) $fallback;
1093
-	}
1094
-
1095
-	/**
1096
-	 * parses the app data array and enhanced the 'description' value
1097
-	 *
1098
-	 * @param array $data the app data
1099
-	 * @param string $lang
1100
-	 * @return array improved app data
1101
-	 */
1102
-	public static function parseAppInfo(array $data, $lang = null) {
1103
-
1104
-		if ($lang && isset($data['name']) && is_array($data['name'])) {
1105
-			$data['name'] = self::findBestL10NOption($data['name'], $lang);
1106
-		}
1107
-		if ($lang && isset($data['summary']) && is_array($data['summary'])) {
1108
-			$data['summary'] = self::findBestL10NOption($data['summary'], $lang);
1109
-		}
1110
-		if ($lang && isset($data['description']) && is_array($data['description'])) {
1111
-			$data['description'] = trim(self::findBestL10NOption($data['description'], $lang));
1112
-		} else if (isset($data['description']) && is_string($data['description'])) {
1113
-			$data['description'] = trim($data['description']);
1114
-		} else  {
1115
-			$data['description'] = '';
1116
-		}
1117
-
1118
-		return $data;
1119
-	}
1120
-
1121
-	/**
1122
-	 * @param \OCP\IConfig $config
1123
-	 * @param \OCP\IL10N $l
1124
-	 * @param array $info
1125
-	 * @throws \Exception
1126
-	 */
1127
-	public static function checkAppDependencies($config, $l, $info) {
1128
-		$dependencyAnalyzer = new DependencyAnalyzer(new Platform($config), $l);
1129
-		$missing = $dependencyAnalyzer->analyze($info);
1130
-		if (!empty($missing)) {
1131
-			$missingMsg = implode(PHP_EOL, $missing);
1132
-			throw new \Exception(
1133
-				$l->t('App "%s" cannot be installed because the following dependencies are not fulfilled: %s',
1134
-					[$info['name'], $missingMsg]
1135
-				)
1136
-			);
1137
-		}
1138
-	}
65
+    static private $adminForms = array();
66
+    static private $personalForms = array();
67
+    static private $appTypes = array();
68
+    static private $loadedApps = array();
69
+    static private $altLogin = array();
70
+    static private $alreadyRegistered = [];
71
+    const officialApp = 200;
72
+
73
+    /**
74
+     * clean the appId
75
+     *
76
+     * @param string|boolean $app AppId that needs to be cleaned
77
+     * @return string
78
+     */
79
+    public static function cleanAppId($app) {
80
+        return str_replace(array('\0', '/', '\\', '..'), '', $app);
81
+    }
82
+
83
+    /**
84
+     * Check if an app is loaded
85
+     *
86
+     * @param string $app
87
+     * @return bool
88
+     */
89
+    public static function isAppLoaded($app) {
90
+        return in_array($app, self::$loadedApps, true);
91
+    }
92
+
93
+    /**
94
+     * loads all apps
95
+     *
96
+     * @param string[] | string | null $types
97
+     * @return bool
98
+     *
99
+     * This function walks through the ownCloud directory and loads all apps
100
+     * it can find. A directory contains an app if the file /appinfo/info.xml
101
+     * exists.
102
+     *
103
+     * if $types is set, only apps of those types will be loaded
104
+     */
105
+    public static function loadApps($types = null) {
106
+        if (\OC::$server->getSystemConfig()->getValue('maintenance', false)) {
107
+            return false;
108
+        }
109
+        // Load the enabled apps here
110
+        $apps = self::getEnabledApps();
111
+
112
+        // Add each apps' folder as allowed class path
113
+        foreach($apps as $app) {
114
+            $path = self::getAppPath($app);
115
+            if($path !== false) {
116
+                self::registerAutoloading($app, $path);
117
+            }
118
+        }
119
+
120
+        // prevent app.php from printing output
121
+        ob_start();
122
+        foreach ($apps as $app) {
123
+            if ((is_null($types) or self::isType($app, $types)) && !in_array($app, self::$loadedApps)) {
124
+                self::loadApp($app);
125
+            }
126
+        }
127
+        ob_end_clean();
128
+
129
+        return true;
130
+    }
131
+
132
+    /**
133
+     * load a single app
134
+     *
135
+     * @param string $app
136
+     */
137
+    public static function loadApp($app) {
138
+        self::$loadedApps[] = $app;
139
+        $appPath = self::getAppPath($app);
140
+        if($appPath === false) {
141
+            return;
142
+        }
143
+
144
+        // in case someone calls loadApp() directly
145
+        self::registerAutoloading($app, $appPath);
146
+
147
+        if (is_file($appPath . '/appinfo/app.php')) {
148
+            \OC::$server->getEventLogger()->start('load_app_' . $app, 'Load app: ' . $app);
149
+            self::requireAppFile($app);
150
+            if (self::isType($app, array('authentication'))) {
151
+                // since authentication apps affect the "is app enabled for group" check,
152
+                // the enabled apps cache needs to be cleared to make sure that the
153
+                // next time getEnableApps() is called it will also include apps that were
154
+                // enabled for groups
155
+                self::$enabledAppsCache = array();
156
+            }
157
+            \OC::$server->getEventLogger()->end('load_app_' . $app);
158
+        }
159
+
160
+        $info = self::getAppInfo($app);
161
+        if (!empty($info['activity']['filters'])) {
162
+            foreach ($info['activity']['filters'] as $filter) {
163
+                \OC::$server->getActivityManager()->registerFilter($filter);
164
+            }
165
+        }
166
+        if (!empty($info['activity']['settings'])) {
167
+            foreach ($info['activity']['settings'] as $setting) {
168
+                \OC::$server->getActivityManager()->registerSetting($setting);
169
+            }
170
+        }
171
+        if (!empty($info['activity']['providers'])) {
172
+            foreach ($info['activity']['providers'] as $provider) {
173
+                \OC::$server->getActivityManager()->registerProvider($provider);
174
+            }
175
+        }
176
+        if (!empty($info['collaboration']['plugins'])) {
177
+            // deal with one or many plugin entries
178
+            $plugins = isset($info['collaboration']['plugins']['plugin']['@value']) ?
179
+                [$info['collaboration']['plugins']['plugin']] : $info['collaboration']['plugins']['plugin'];
180
+            foreach ($plugins as $plugin) {
181
+                if($plugin['@attributes']['type'] === 'collaborator-search') {
182
+                    $pluginInfo = [
183
+                        'shareType' => $plugin['@attributes']['share-type'],
184
+                        'class' => $plugin['@value'],
185
+                    ];
186
+                    \OC::$server->getCollaboratorSearch()->registerPlugin($pluginInfo);
187
+                } else if ($plugin['@attributes']['type'] === 'autocomplete-sort') {
188
+                    \OC::$server->getAutoCompleteManager()->registerSorter($plugin['@value']);
189
+                }
190
+            }
191
+        }
192
+    }
193
+
194
+    /**
195
+     * @internal
196
+     * @param string $app
197
+     * @param string $path
198
+     */
199
+    public static function registerAutoloading($app, $path) {
200
+        $key = $app . '-' . $path;
201
+        if(isset(self::$alreadyRegistered[$key])) {
202
+            return;
203
+        }
204
+
205
+        self::$alreadyRegistered[$key] = true;
206
+
207
+        // Register on PSR-4 composer autoloader
208
+        $appNamespace = \OC\AppFramework\App::buildAppNamespace($app);
209
+        \OC::$server->registerNamespace($app, $appNamespace);
210
+
211
+        if (file_exists($path . '/composer/autoload.php')) {
212
+            require_once $path . '/composer/autoload.php';
213
+        } else {
214
+            \OC::$composerAutoloader->addPsr4($appNamespace . '\\', $path . '/lib/', true);
215
+            // Register on legacy autoloader
216
+            \OC::$loader->addValidRoot($path);
217
+        }
218
+
219
+        // Register Test namespace only when testing
220
+        if (defined('PHPUNIT_RUN') || defined('CLI_TEST_RUN')) {
221
+            \OC::$composerAutoloader->addPsr4($appNamespace . '\\Tests\\', $path . '/tests/', true);
222
+        }
223
+    }
224
+
225
+    /**
226
+     * Load app.php from the given app
227
+     *
228
+     * @param string $app app name
229
+     */
230
+    private static function requireAppFile($app) {
231
+        try {
232
+            // encapsulated here to avoid variable scope conflicts
233
+            require_once $app . '/appinfo/app.php';
234
+        } catch (Error $ex) {
235
+            \OC::$server->getLogger()->logException($ex);
236
+            if (!\OC::$server->getAppManager()->isShipped($app)) {
237
+                // Only disable apps which are not shipped
238
+                self::disable($app);
239
+            }
240
+        }
241
+    }
242
+
243
+    /**
244
+     * check if an app is of a specific type
245
+     *
246
+     * @param string $app
247
+     * @param string|array $types
248
+     * @return bool
249
+     */
250
+    public static function isType($app, $types) {
251
+        if (is_string($types)) {
252
+            $types = array($types);
253
+        }
254
+        $appTypes = self::getAppTypes($app);
255
+        foreach ($types as $type) {
256
+            if (array_search($type, $appTypes) !== false) {
257
+                return true;
258
+            }
259
+        }
260
+        return false;
261
+    }
262
+
263
+    /**
264
+     * get the types of an app
265
+     *
266
+     * @param string $app
267
+     * @return array
268
+     */
269
+    private static function getAppTypes($app) {
270
+        //load the cache
271
+        if (count(self::$appTypes) == 0) {
272
+            self::$appTypes = \OC::$server->getAppConfig()->getValues(false, 'types');
273
+        }
274
+
275
+        if (isset(self::$appTypes[$app])) {
276
+            return explode(',', self::$appTypes[$app]);
277
+        } else {
278
+            return array();
279
+        }
280
+    }
281
+
282
+    /**
283
+     * read app types from info.xml and cache them in the database
284
+     */
285
+    public static function setAppTypes($app) {
286
+        $appData = self::getAppInfo($app);
287
+        if(!is_array($appData)) {
288
+            return;
289
+        }
290
+
291
+        if (isset($appData['types'])) {
292
+            $appTypes = implode(',', $appData['types']);
293
+        } else {
294
+            $appTypes = '';
295
+            $appData['types'] = [];
296
+        }
297
+
298
+        \OC::$server->getConfig()->setAppValue($app, 'types', $appTypes);
299
+
300
+        if (\OC::$server->getAppManager()->hasProtectedAppType($appData['types'])) {
301
+            $enabled = \OC::$server->getConfig()->getAppValue($app, 'enabled', 'yes');
302
+            if ($enabled !== 'yes' && $enabled !== 'no') {
303
+                \OC::$server->getConfig()->setAppValue($app, 'enabled', 'yes');
304
+            }
305
+        }
306
+    }
307
+
308
+    /**
309
+     * get all enabled apps
310
+     */
311
+    protected static $enabledAppsCache = array();
312
+
313
+    /**
314
+     * Returns apps enabled for the current user.
315
+     *
316
+     * @param bool $forceRefresh whether to refresh the cache
317
+     * @param bool $all whether to return apps for all users, not only the
318
+     * currently logged in one
319
+     * @return string[]
320
+     */
321
+    public static function getEnabledApps($forceRefresh = false, $all = false) {
322
+        if (!\OC::$server->getSystemConfig()->getValue('installed', false)) {
323
+            return array();
324
+        }
325
+        // in incognito mode or when logged out, $user will be false,
326
+        // which is also the case during an upgrade
327
+        $appManager = \OC::$server->getAppManager();
328
+        if ($all) {
329
+            $user = null;
330
+        } else {
331
+            $user = \OC::$server->getUserSession()->getUser();
332
+        }
333
+
334
+        if (is_null($user)) {
335
+            $apps = $appManager->getInstalledApps();
336
+        } else {
337
+            $apps = $appManager->getEnabledAppsForUser($user);
338
+        }
339
+        $apps = array_filter($apps, function ($app) {
340
+            return $app !== 'files';//we add this manually
341
+        });
342
+        sort($apps);
343
+        array_unshift($apps, 'files');
344
+        return $apps;
345
+    }
346
+
347
+    /**
348
+     * checks whether or not an app is enabled
349
+     *
350
+     * @param string $app app
351
+     * @return bool
352
+     * @deprecated 13.0.0 use \OC::$server->getAppManager()->isEnabledForUser($appId)
353
+     *
354
+     * This function checks whether or not an app is enabled.
355
+     */
356
+    public static function isEnabled($app) {
357
+        return \OC::$server->getAppManager()->isEnabledForUser($app);
358
+    }
359
+
360
+    /**
361
+     * enables an app
362
+     *
363
+     * @param string $appId
364
+     * @param array $groups (optional) when set, only these groups will have access to the app
365
+     * @throws \Exception
366
+     * @return void
367
+     *
368
+     * This function set an app as enabled in appconfig.
369
+     */
370
+    public function enable($appId,
371
+                            $groups = null) {
372
+        self::$enabledAppsCache = []; // flush
373
+
374
+        // Check if app is already downloaded
375
+        $installer = \OC::$server->query(Installer::class);
376
+        $isDownloaded = $installer->isDownloaded($appId);
377
+
378
+        if(!$isDownloaded) {
379
+            $installer->downloadApp($appId);
380
+        }
381
+
382
+        $installer->installApp($appId);
383
+
384
+        $appManager = \OC::$server->getAppManager();
385
+        if (!is_null($groups)) {
386
+            $groupManager = \OC::$server->getGroupManager();
387
+            $groupsList = [];
388
+            foreach ($groups as $group) {
389
+                $groupItem = $groupManager->get($group);
390
+                if ($groupItem instanceof \OCP\IGroup) {
391
+                    $groupsList[] = $groupManager->get($group);
392
+                }
393
+            }
394
+            $appManager->enableAppForGroups($appId, $groupsList);
395
+        } else {
396
+            $appManager->enableApp($appId);
397
+        }
398
+    }
399
+
400
+    /**
401
+     * This function set an app as disabled in appconfig.
402
+     *
403
+     * @param string $app app
404
+     * @throws Exception
405
+     */
406
+    public static function disable($app) {
407
+        // flush
408
+        self::$enabledAppsCache = array();
409
+
410
+        // run uninstall steps
411
+        $appData = OC_App::getAppInfo($app);
412
+        if (!is_null($appData)) {
413
+            OC_App::executeRepairSteps($app, $appData['repair-steps']['uninstall']);
414
+        }
415
+
416
+        // emit disable hook - needed anymore ?
417
+        \OC_Hook::emit('OC_App', 'pre_disable', array('app' => $app));
418
+
419
+        // finally disable it
420
+        $appManager = \OC::$server->getAppManager();
421
+        $appManager->disableApp($app);
422
+    }
423
+
424
+    // This is private as well. It simply works, so don't ask for more details
425
+    private static function proceedNavigation($list) {
426
+        usort($list, function($a, $b) {
427
+            if (isset($a['order']) && isset($b['order'])) {
428
+                return ($a['order'] < $b['order']) ? -1 : 1;
429
+            } else if (isset($a['order']) || isset($b['order'])) {
430
+                return isset($a['order']) ? -1 : 1;
431
+            } else {
432
+                return ($a['name'] < $b['name']) ? -1 : 1;
433
+            }
434
+        });
435
+
436
+        $activeApp = OC::$server->getNavigationManager()->getActiveEntry();
437
+        foreach ($list as $index => &$navEntry) {
438
+            if ($navEntry['id'] == $activeApp) {
439
+                $navEntry['active'] = true;
440
+            } else {
441
+                $navEntry['active'] = false;
442
+            }
443
+        }
444
+        unset($navEntry);
445
+
446
+        return $list;
447
+    }
448
+
449
+    /**
450
+     * Get the path where to install apps
451
+     *
452
+     * @return string|false
453
+     */
454
+    public static function getInstallPath() {
455
+        if (\OC::$server->getSystemConfig()->getValue('appstoreenabled', true) == false) {
456
+            return false;
457
+        }
458
+
459
+        foreach (OC::$APPSROOTS as $dir) {
460
+            if (isset($dir['writable']) && $dir['writable'] === true) {
461
+                return $dir['path'];
462
+            }
463
+        }
464
+
465
+        \OCP\Util::writeLog('core', 'No application directories are marked as writable.', \OCP\Util::ERROR);
466
+        return null;
467
+    }
468
+
469
+
470
+    /**
471
+     * search for an app in all app-directories
472
+     *
473
+     * @param string $appId
474
+     * @return false|string
475
+     */
476
+    public static function findAppInDirectories($appId) {
477
+        $sanitizedAppId = self::cleanAppId($appId);
478
+        if($sanitizedAppId !== $appId) {
479
+            return false;
480
+        }
481
+        static $app_dir = array();
482
+
483
+        if (isset($app_dir[$appId])) {
484
+            return $app_dir[$appId];
485
+        }
486
+
487
+        $possibleApps = array();
488
+        foreach (OC::$APPSROOTS as $dir) {
489
+            if (file_exists($dir['path'] . '/' . $appId)) {
490
+                $possibleApps[] = $dir;
491
+            }
492
+        }
493
+
494
+        if (empty($possibleApps)) {
495
+            return false;
496
+        } elseif (count($possibleApps) === 1) {
497
+            $dir = array_shift($possibleApps);
498
+            $app_dir[$appId] = $dir;
499
+            return $dir;
500
+        } else {
501
+            $versionToLoad = array();
502
+            foreach ($possibleApps as $possibleApp) {
503
+                $version = self::getAppVersionByPath($possibleApp['path']);
504
+                if (empty($versionToLoad) || version_compare($version, $versionToLoad['version'], '>')) {
505
+                    $versionToLoad = array(
506
+                        'dir' => $possibleApp,
507
+                        'version' => $version,
508
+                    );
509
+                }
510
+            }
511
+            $app_dir[$appId] = $versionToLoad['dir'];
512
+            return $versionToLoad['dir'];
513
+            //TODO - write test
514
+        }
515
+    }
516
+
517
+    /**
518
+     * Get the directory for the given app.
519
+     * If the app is defined in multiple directories, the first one is taken. (false if not found)
520
+     *
521
+     * @param string $appId
522
+     * @return string|false
523
+     */
524
+    public static function getAppPath($appId) {
525
+        if ($appId === null || trim($appId) === '') {
526
+            return false;
527
+        }
528
+
529
+        if (($dir = self::findAppInDirectories($appId)) != false) {
530
+            return $dir['path'] . '/' . $appId;
531
+        }
532
+        return false;
533
+    }
534
+
535
+    /**
536
+     * Get the path for the given app on the access
537
+     * If the app is defined in multiple directories, the first one is taken. (false if not found)
538
+     *
539
+     * @param string $appId
540
+     * @return string|false
541
+     */
542
+    public static function getAppWebPath($appId) {
543
+        if (($dir = self::findAppInDirectories($appId)) != false) {
544
+            return OC::$WEBROOT . $dir['url'] . '/' . $appId;
545
+        }
546
+        return false;
547
+    }
548
+
549
+    /**
550
+     * get the last version of the app from appinfo/info.xml
551
+     *
552
+     * @param string $appId
553
+     * @param bool $useCache
554
+     * @return string
555
+     * @deprecated 14.0.0 use \OC::$server->getAppManager()->getAppVersion()
556
+     */
557
+    public static function getAppVersion($appId, $useCache = true) {
558
+        return \OC::$server->getAppManager()->getAppVersion($appId, $useCache);
559
+    }
560
+
561
+    /**
562
+     * get app's version based on it's path
563
+     *
564
+     * @param string $path
565
+     * @return string
566
+     */
567
+    public static function getAppVersionByPath($path) {
568
+        $infoFile = $path . '/appinfo/info.xml';
569
+        $appData = \OC::$server->getAppManager()->getAppInfo($infoFile, true);
570
+        return isset($appData['version']) ? $appData['version'] : '';
571
+    }
572
+
573
+
574
+    /**
575
+     * Read all app metadata from the info.xml file
576
+     *
577
+     * @param string $appId id of the app or the path of the info.xml file
578
+     * @param bool $path
579
+     * @param string $lang
580
+     * @return array|null
581
+     * @note all data is read from info.xml, not just pre-defined fields
582
+     * @deprecated 14.0.0 use \OC::$server->getAppManager()->getAppInfo()
583
+     */
584
+    public static function getAppInfo($appId, $path = false, $lang = null) {
585
+        return \OC::$server->getAppManager()->getAppInfo($appId, $path, $lang);
586
+    }
587
+
588
+    /**
589
+     * Returns the navigation
590
+     *
591
+     * @return array
592
+     *
593
+     * This function returns an array containing all entries added. The
594
+     * entries are sorted by the key 'order' ascending. Additional to the keys
595
+     * given for each app the following keys exist:
596
+     *   - active: boolean, signals if the user is on this navigation entry
597
+     */
598
+    public static function getNavigation() {
599
+        $entries = OC::$server->getNavigationManager()->getAll();
600
+        return self::proceedNavigation($entries);
601
+    }
602
+
603
+    /**
604
+     * Returns the Settings Navigation
605
+     *
606
+     * @return string[]
607
+     *
608
+     * This function returns an array containing all settings pages added. The
609
+     * entries are sorted by the key 'order' ascending.
610
+     */
611
+    public static function getSettingsNavigation() {
612
+        $entries = OC::$server->getNavigationManager()->getAll('settings');
613
+        return self::proceedNavigation($entries);
614
+    }
615
+
616
+    /**
617
+     * get the id of loaded app
618
+     *
619
+     * @return string
620
+     */
621
+    public static function getCurrentApp() {
622
+        $request = \OC::$server->getRequest();
623
+        $script = substr($request->getScriptName(), strlen(OC::$WEBROOT) + 1);
624
+        $topFolder = substr($script, 0, strpos($script, '/') ?: 0);
625
+        if (empty($topFolder)) {
626
+            $path_info = $request->getPathInfo();
627
+            if ($path_info) {
628
+                $topFolder = substr($path_info, 1, strpos($path_info, '/', 1) - 1);
629
+            }
630
+        }
631
+        if ($topFolder == 'apps') {
632
+            $length = strlen($topFolder);
633
+            return substr($script, $length + 1, strpos($script, '/', $length + 1) - $length - 1);
634
+        } else {
635
+            return $topFolder;
636
+        }
637
+    }
638
+
639
+    /**
640
+     * @param string $type
641
+     * @return array
642
+     */
643
+    public static function getForms($type) {
644
+        $forms = array();
645
+        switch ($type) {
646
+            case 'admin':
647
+                $source = self::$adminForms;
648
+                break;
649
+            case 'personal':
650
+                $source = self::$personalForms;
651
+                break;
652
+            default:
653
+                return array();
654
+        }
655
+        foreach ($source as $form) {
656
+            $forms[] = include $form;
657
+        }
658
+        return $forms;
659
+    }
660
+
661
+    /**
662
+     * register an admin form to be shown
663
+     *
664
+     * @param string $app
665
+     * @param string $page
666
+     */
667
+    public static function registerAdmin($app, $page) {
668
+        self::$adminForms[] = $app . '/' . $page . '.php';
669
+    }
670
+
671
+    /**
672
+     * register a personal form to be shown
673
+     * @param string $app
674
+     * @param string $page
675
+     */
676
+    public static function registerPersonal($app, $page) {
677
+        self::$personalForms[] = $app . '/' . $page . '.php';
678
+    }
679
+
680
+    /**
681
+     * @param array $entry
682
+     */
683
+    public static function registerLogIn(array $entry) {
684
+        self::$altLogin[] = $entry;
685
+    }
686
+
687
+    /**
688
+     * @return array
689
+     */
690
+    public static function getAlternativeLogIns() {
691
+        return self::$altLogin;
692
+    }
693
+
694
+    /**
695
+     * get a list of all apps in the apps folder
696
+     *
697
+     * @return array an array of app names (string IDs)
698
+     * @todo: change the name of this method to getInstalledApps, which is more accurate
699
+     */
700
+    public static function getAllApps() {
701
+
702
+        $apps = array();
703
+
704
+        foreach (OC::$APPSROOTS as $apps_dir) {
705
+            if (!is_readable($apps_dir['path'])) {
706
+                \OCP\Util::writeLog('core', 'unable to read app folder : ' . $apps_dir['path'], \OCP\Util::WARN);
707
+                continue;
708
+            }
709
+            $dh = opendir($apps_dir['path']);
710
+
711
+            if (is_resource($dh)) {
712
+                while (($file = readdir($dh)) !== false) {
713
+
714
+                    if ($file[0] != '.' and is_dir($apps_dir['path'] . '/' . $file) and is_file($apps_dir['path'] . '/' . $file . '/appinfo/info.xml')) {
715
+
716
+                        $apps[] = $file;
717
+                    }
718
+                }
719
+            }
720
+        }
721
+
722
+        $apps = array_unique($apps);
723
+
724
+        return $apps;
725
+    }
726
+
727
+    /**
728
+     * List all apps, this is used in apps.php
729
+     *
730
+     * @return array
731
+     */
732
+    public function listAllApps() {
733
+        $installedApps = OC_App::getAllApps();
734
+
735
+        $appManager = \OC::$server->getAppManager();
736
+        //we don't want to show configuration for these
737
+        $blacklist = $appManager->getAlwaysEnabledApps();
738
+        $appList = array();
739
+        $langCode = \OC::$server->getL10N('core')->getLanguageCode();
740
+        $urlGenerator = \OC::$server->getURLGenerator();
741
+
742
+        foreach ($installedApps as $app) {
743
+            if (array_search($app, $blacklist) === false) {
744
+
745
+                $info = OC_App::getAppInfo($app, false, $langCode);
746
+                if (!is_array($info)) {
747
+                    \OCP\Util::writeLog('core', 'Could not read app info file for app "' . $app . '"', \OCP\Util::ERROR);
748
+                    continue;
749
+                }
750
+
751
+                if (!isset($info['name'])) {
752
+                    \OCP\Util::writeLog('core', 'App id "' . $app . '" has no name in appinfo', \OCP\Util::ERROR);
753
+                    continue;
754
+                }
755
+
756
+                $enabled = \OC::$server->getConfig()->getAppValue($app, 'enabled', 'no');
757
+                $info['groups'] = null;
758
+                if ($enabled === 'yes') {
759
+                    $active = true;
760
+                } else if ($enabled === 'no') {
761
+                    $active = false;
762
+                } else {
763
+                    $active = true;
764
+                    $info['groups'] = $enabled;
765
+                }
766
+
767
+                $info['active'] = $active;
768
+
769
+                if ($appManager->isShipped($app)) {
770
+                    $info['internal'] = true;
771
+                    $info['level'] = self::officialApp;
772
+                    $info['removable'] = false;
773
+                } else {
774
+                    $info['internal'] = false;
775
+                    $info['removable'] = true;
776
+                }
777
+
778
+                $appPath = self::getAppPath($app);
779
+                if($appPath !== false) {
780
+                    $appIcon = $appPath . '/img/' . $app . '.svg';
781
+                    if (file_exists($appIcon)) {
782
+                        $info['preview'] = $urlGenerator->imagePath($app, $app . '.svg');
783
+                        $info['previewAsIcon'] = true;
784
+                    } else {
785
+                        $appIcon = $appPath . '/img/app.svg';
786
+                        if (file_exists($appIcon)) {
787
+                            $info['preview'] = $urlGenerator->imagePath($app, 'app.svg');
788
+                            $info['previewAsIcon'] = true;
789
+                        }
790
+                    }
791
+                }
792
+                // fix documentation
793
+                if (isset($info['documentation']) && is_array($info['documentation'])) {
794
+                    foreach ($info['documentation'] as $key => $url) {
795
+                        // If it is not an absolute URL we assume it is a key
796
+                        // i.e. admin-ldap will get converted to go.php?to=admin-ldap
797
+                        if (stripos($url, 'https://') !== 0 && stripos($url, 'http://') !== 0) {
798
+                            $url = $urlGenerator->linkToDocs($url);
799
+                        }
800
+
801
+                        $info['documentation'][$key] = $url;
802
+                    }
803
+                }
804
+
805
+                $info['version'] = OC_App::getAppVersion($app);
806
+                $appList[] = $info;
807
+            }
808
+        }
809
+
810
+        return $appList;
811
+    }
812
+
813
+    public static function shouldUpgrade($app) {
814
+        $versions = self::getAppVersions();
815
+        $currentVersion = OC_App::getAppVersion($app);
816
+        if ($currentVersion && isset($versions[$app])) {
817
+            $installedVersion = $versions[$app];
818
+            if (!version_compare($currentVersion, $installedVersion, '=')) {
819
+                return true;
820
+            }
821
+        }
822
+        return false;
823
+    }
824
+
825
+    /**
826
+     * Adjust the number of version parts of $version1 to match
827
+     * the number of version parts of $version2.
828
+     *
829
+     * @param string $version1 version to adjust
830
+     * @param string $version2 version to take the number of parts from
831
+     * @return string shortened $version1
832
+     */
833
+    private static function adjustVersionParts($version1, $version2) {
834
+        $version1 = explode('.', $version1);
835
+        $version2 = explode('.', $version2);
836
+        // reduce $version1 to match the number of parts in $version2
837
+        while (count($version1) > count($version2)) {
838
+            array_pop($version1);
839
+        }
840
+        // if $version1 does not have enough parts, add some
841
+        while (count($version1) < count($version2)) {
842
+            $version1[] = '0';
843
+        }
844
+        return implode('.', $version1);
845
+    }
846
+
847
+    /**
848
+     * Check whether the current ownCloud version matches the given
849
+     * application's version requirements.
850
+     *
851
+     * The comparison is made based on the number of parts that the
852
+     * app info version has. For example for ownCloud 6.0.3 if the
853
+     * app info version is expecting version 6.0, the comparison is
854
+     * made on the first two parts of the ownCloud version.
855
+     * This means that it's possible to specify "requiremin" => 6
856
+     * and "requiremax" => 6 and it will still match ownCloud 6.0.3.
857
+     *
858
+     * @param string $ocVersion ownCloud version to check against
859
+     * @param array $appInfo app info (from xml)
860
+     *
861
+     * @return boolean true if compatible, otherwise false
862
+     */
863
+    public static function isAppCompatible($ocVersion, $appInfo) {
864
+        $requireMin = '';
865
+        $requireMax = '';
866
+        if (isset($appInfo['dependencies']['nextcloud']['@attributes']['min-version'])) {
867
+            $requireMin = $appInfo['dependencies']['nextcloud']['@attributes']['min-version'];
868
+        } elseif (isset($appInfo['dependencies']['owncloud']['@attributes']['min-version'])) {
869
+            $requireMin = $appInfo['dependencies']['owncloud']['@attributes']['min-version'];
870
+        } else if (isset($appInfo['requiremin'])) {
871
+            $requireMin = $appInfo['requiremin'];
872
+        } else if (isset($appInfo['require'])) {
873
+            $requireMin = $appInfo['require'];
874
+        }
875
+
876
+        if (isset($appInfo['dependencies']['nextcloud']['@attributes']['max-version'])) {
877
+            $requireMax = $appInfo['dependencies']['nextcloud']['@attributes']['max-version'];
878
+        } elseif (isset($appInfo['dependencies']['owncloud']['@attributes']['max-version'])) {
879
+            $requireMax = $appInfo['dependencies']['owncloud']['@attributes']['max-version'];
880
+        } else if (isset($appInfo['requiremax'])) {
881
+            $requireMax = $appInfo['requiremax'];
882
+        }
883
+
884
+        if (is_array($ocVersion)) {
885
+            $ocVersion = implode('.', $ocVersion);
886
+        }
887
+
888
+        if (!empty($requireMin)
889
+            && version_compare(self::adjustVersionParts($ocVersion, $requireMin), $requireMin, '<')
890
+        ) {
891
+
892
+            return false;
893
+        }
894
+
895
+        if (!empty($requireMax)
896
+            && version_compare(self::adjustVersionParts($ocVersion, $requireMax), $requireMax, '>')
897
+        ) {
898
+            return false;
899
+        }
900
+
901
+        return true;
902
+    }
903
+
904
+    /**
905
+     * get the installed version of all apps
906
+     */
907
+    public static function getAppVersions() {
908
+        static $versions;
909
+
910
+        if(!$versions) {
911
+            $appConfig = \OC::$server->getAppConfig();
912
+            $versions = $appConfig->getValues(false, 'installed_version');
913
+        }
914
+        return $versions;
915
+    }
916
+
917
+    /**
918
+     * update the database for the app and call the update script
919
+     *
920
+     * @param string $appId
921
+     * @return bool
922
+     */
923
+    public static function updateApp($appId) {
924
+        $appPath = self::getAppPath($appId);
925
+        if($appPath === false) {
926
+            return false;
927
+        }
928
+        self::registerAutoloading($appId, $appPath);
929
+
930
+        $appData = self::getAppInfo($appId);
931
+        self::executeRepairSteps($appId, $appData['repair-steps']['pre-migration']);
932
+
933
+        if (file_exists($appPath . '/appinfo/database.xml')) {
934
+            OC_DB::updateDbFromStructure($appPath . '/appinfo/database.xml');
935
+        } else {
936
+            $ms = new MigrationService($appId, \OC::$server->getDatabaseConnection());
937
+            $ms->migrate();
938
+        }
939
+
940
+        self::executeRepairSteps($appId, $appData['repair-steps']['post-migration']);
941
+        self::setupLiveMigrations($appId, $appData['repair-steps']['live-migration']);
942
+        // update appversion in app manager
943
+        \OC::$server->getAppManager()->getAppVersion($appId, false);
944
+
945
+        // run upgrade code
946
+        if (file_exists($appPath . '/appinfo/update.php')) {
947
+            self::loadApp($appId);
948
+            include $appPath . '/appinfo/update.php';
949
+        }
950
+        self::setupBackgroundJobs($appData['background-jobs']);
951
+        if(isset($appData['settings']) && is_array($appData['settings'])) {
952
+            \OC::$server->getSettingsManager()->setupSettings($appData['settings']);
953
+        }
954
+
955
+        //set remote/public handlers
956
+        if (array_key_exists('ocsid', $appData)) {
957
+            \OC::$server->getConfig()->setAppValue($appId, 'ocsid', $appData['ocsid']);
958
+        } elseif(\OC::$server->getConfig()->getAppValue($appId, 'ocsid', null) !== null) {
959
+            \OC::$server->getConfig()->deleteAppValue($appId, 'ocsid');
960
+        }
961
+        foreach ($appData['remote'] as $name => $path) {
962
+            \OC::$server->getConfig()->setAppValue('core', 'remote_' . $name, $appId . '/' . $path);
963
+        }
964
+        foreach ($appData['public'] as $name => $path) {
965
+            \OC::$server->getConfig()->setAppValue('core', 'public_' . $name, $appId . '/' . $path);
966
+        }
967
+
968
+        self::setAppTypes($appId);
969
+
970
+        $version = \OC_App::getAppVersion($appId);
971
+        \OC::$server->getConfig()->setAppValue($appId, 'installed_version', $version);
972
+
973
+        \OC::$server->getEventDispatcher()->dispatch(ManagerEvent::EVENT_APP_UPDATE, new ManagerEvent(
974
+            ManagerEvent::EVENT_APP_UPDATE, $appId
975
+        ));
976
+
977
+        return true;
978
+    }
979
+
980
+    /**
981
+     * @param string $appId
982
+     * @param string[] $steps
983
+     * @throws \OC\NeedsUpdateException
984
+     */
985
+    public static function executeRepairSteps($appId, array $steps) {
986
+        if (empty($steps)) {
987
+            return;
988
+        }
989
+        // load the app
990
+        self::loadApp($appId);
991
+
992
+        $dispatcher = OC::$server->getEventDispatcher();
993
+
994
+        // load the steps
995
+        $r = new Repair([], $dispatcher);
996
+        foreach ($steps as $step) {
997
+            try {
998
+                $r->addStep($step);
999
+            } catch (Exception $ex) {
1000
+                $r->emit('\OC\Repair', 'error', [$ex->getMessage()]);
1001
+                \OC::$server->getLogger()->logException($ex);
1002
+            }
1003
+        }
1004
+        // run the steps
1005
+        $r->run();
1006
+    }
1007
+
1008
+    public static function setupBackgroundJobs(array $jobs) {
1009
+        $queue = \OC::$server->getJobList();
1010
+        foreach ($jobs as $job) {
1011
+            $queue->add($job);
1012
+        }
1013
+    }
1014
+
1015
+    /**
1016
+     * @param string $appId
1017
+     * @param string[] $steps
1018
+     */
1019
+    private static function setupLiveMigrations($appId, array $steps) {
1020
+        $queue = \OC::$server->getJobList();
1021
+        foreach ($steps as $step) {
1022
+            $queue->add('OC\Migration\BackgroundRepair', [
1023
+                'app' => $appId,
1024
+                'step' => $step]);
1025
+        }
1026
+    }
1027
+
1028
+    /**
1029
+     * @param string $appId
1030
+     * @return \OC\Files\View|false
1031
+     */
1032
+    public static function getStorage($appId) {
1033
+        if (\OC::$server->getAppManager()->isEnabledForUser($appId)) { //sanity check
1034
+            if (\OC::$server->getUserSession()->isLoggedIn()) {
1035
+                $view = new \OC\Files\View('/' . OC_User::getUser());
1036
+                if (!$view->file_exists($appId)) {
1037
+                    $view->mkdir($appId);
1038
+                }
1039
+                return new \OC\Files\View('/' . OC_User::getUser() . '/' . $appId);
1040
+            } else {
1041
+                \OCP\Util::writeLog('core', 'Can\'t get app storage, app ' . $appId . ', user not logged in', \OCP\Util::ERROR);
1042
+                return false;
1043
+            }
1044
+        } else {
1045
+            \OCP\Util::writeLog('core', 'Can\'t get app storage, app ' . $appId . ' not enabled', \OCP\Util::ERROR);
1046
+            return false;
1047
+        }
1048
+    }
1049
+
1050
+    protected static function findBestL10NOption($options, $lang) {
1051
+        $fallback = $similarLangFallback = $englishFallback = false;
1052
+
1053
+        $lang = strtolower($lang);
1054
+        $similarLang = $lang;
1055
+        if (strpos($similarLang, '_')) {
1056
+            // For "de_DE" we want to find "de" and the other way around
1057
+            $similarLang = substr($lang, 0, strpos($lang, '_'));
1058
+        }
1059
+
1060
+        foreach ($options as $option) {
1061
+            if (is_array($option)) {
1062
+                if ($fallback === false) {
1063
+                    $fallback = $option['@value'];
1064
+                }
1065
+
1066
+                if (!isset($option['@attributes']['lang'])) {
1067
+                    continue;
1068
+                }
1069
+
1070
+                $attributeLang = strtolower($option['@attributes']['lang']);
1071
+                if ($attributeLang === $lang) {
1072
+                    return $option['@value'];
1073
+                }
1074
+
1075
+                if ($attributeLang === $similarLang) {
1076
+                    $similarLangFallback = $option['@value'];
1077
+                } else if (strpos($attributeLang, $similarLang . '_') === 0) {
1078
+                    if ($similarLangFallback === false) {
1079
+                        $similarLangFallback =  $option['@value'];
1080
+                    }
1081
+                }
1082
+            } else {
1083
+                $englishFallback = $option;
1084
+            }
1085
+        }
1086
+
1087
+        if ($similarLangFallback !== false) {
1088
+            return $similarLangFallback;
1089
+        } else if ($englishFallback !== false) {
1090
+            return $englishFallback;
1091
+        }
1092
+        return (string) $fallback;
1093
+    }
1094
+
1095
+    /**
1096
+     * parses the app data array and enhanced the 'description' value
1097
+     *
1098
+     * @param array $data the app data
1099
+     * @param string $lang
1100
+     * @return array improved app data
1101
+     */
1102
+    public static function parseAppInfo(array $data, $lang = null) {
1103
+
1104
+        if ($lang && isset($data['name']) && is_array($data['name'])) {
1105
+            $data['name'] = self::findBestL10NOption($data['name'], $lang);
1106
+        }
1107
+        if ($lang && isset($data['summary']) && is_array($data['summary'])) {
1108
+            $data['summary'] = self::findBestL10NOption($data['summary'], $lang);
1109
+        }
1110
+        if ($lang && isset($data['description']) && is_array($data['description'])) {
1111
+            $data['description'] = trim(self::findBestL10NOption($data['description'], $lang));
1112
+        } else if (isset($data['description']) && is_string($data['description'])) {
1113
+            $data['description'] = trim($data['description']);
1114
+        } else  {
1115
+            $data['description'] = '';
1116
+        }
1117
+
1118
+        return $data;
1119
+    }
1120
+
1121
+    /**
1122
+     * @param \OCP\IConfig $config
1123
+     * @param \OCP\IL10N $l
1124
+     * @param array $info
1125
+     * @throws \Exception
1126
+     */
1127
+    public static function checkAppDependencies($config, $l, $info) {
1128
+        $dependencyAnalyzer = new DependencyAnalyzer(new Platform($config), $l);
1129
+        $missing = $dependencyAnalyzer->analyze($info);
1130
+        if (!empty($missing)) {
1131
+            $missingMsg = implode(PHP_EOL, $missing);
1132
+            throw new \Exception(
1133
+                $l->t('App "%s" cannot be installed because the following dependencies are not fulfilled: %s',
1134
+                    [$info['name'], $missingMsg]
1135
+                )
1136
+            );
1137
+        }
1138
+    }
1139 1139
 }
Please login to merge, or discard this patch.
Spacing   +50 added lines, -50 removed lines patch added patch discarded remove patch
@@ -110,9 +110,9 @@  discard block
 block discarded – undo
110 110
 		$apps = self::getEnabledApps();
111 111
 
112 112
 		// Add each apps' folder as allowed class path
113
-		foreach($apps as $app) {
113
+		foreach ($apps as $app) {
114 114
 			$path = self::getAppPath($app);
115
-			if($path !== false) {
115
+			if ($path !== false) {
116 116
 				self::registerAutoloading($app, $path);
117 117
 			}
118 118
 		}
@@ -137,15 +137,15 @@  discard block
 block discarded – undo
137 137
 	public static function loadApp($app) {
138 138
 		self::$loadedApps[] = $app;
139 139
 		$appPath = self::getAppPath($app);
140
-		if($appPath === false) {
140
+		if ($appPath === false) {
141 141
 			return;
142 142
 		}
143 143
 
144 144
 		// in case someone calls loadApp() directly
145 145
 		self::registerAutoloading($app, $appPath);
146 146
 
147
-		if (is_file($appPath . '/appinfo/app.php')) {
148
-			\OC::$server->getEventLogger()->start('load_app_' . $app, 'Load app: ' . $app);
147
+		if (is_file($appPath.'/appinfo/app.php')) {
148
+			\OC::$server->getEventLogger()->start('load_app_'.$app, 'Load app: '.$app);
149 149
 			self::requireAppFile($app);
150 150
 			if (self::isType($app, array('authentication'))) {
151 151
 				// since authentication apps affect the "is app enabled for group" check,
@@ -154,7 +154,7 @@  discard block
 block discarded – undo
154 154
 				// enabled for groups
155 155
 				self::$enabledAppsCache = array();
156 156
 			}
157
-			\OC::$server->getEventLogger()->end('load_app_' . $app);
157
+			\OC::$server->getEventLogger()->end('load_app_'.$app);
158 158
 		}
159 159
 
160 160
 		$info = self::getAppInfo($app);
@@ -178,7 +178,7 @@  discard block
 block discarded – undo
178 178
 			$plugins = isset($info['collaboration']['plugins']['plugin']['@value']) ?
179 179
 				[$info['collaboration']['plugins']['plugin']] : $info['collaboration']['plugins']['plugin'];
180 180
 			foreach ($plugins as $plugin) {
181
-				if($plugin['@attributes']['type'] === 'collaborator-search') {
181
+				if ($plugin['@attributes']['type'] === 'collaborator-search') {
182 182
 					$pluginInfo = [
183 183
 						'shareType' => $plugin['@attributes']['share-type'],
184 184
 						'class' => $plugin['@value'],
@@ -197,8 +197,8 @@  discard block
 block discarded – undo
197 197
 	 * @param string $path
198 198
 	 */
199 199
 	public static function registerAutoloading($app, $path) {
200
-		$key = $app . '-' . $path;
201
-		if(isset(self::$alreadyRegistered[$key])) {
200
+		$key = $app.'-'.$path;
201
+		if (isset(self::$alreadyRegistered[$key])) {
202 202
 			return;
203 203
 		}
204 204
 
@@ -208,17 +208,17 @@  discard block
 block discarded – undo
208 208
 		$appNamespace = \OC\AppFramework\App::buildAppNamespace($app);
209 209
 		\OC::$server->registerNamespace($app, $appNamespace);
210 210
 
211
-		if (file_exists($path . '/composer/autoload.php')) {
212
-			require_once $path . '/composer/autoload.php';
211
+		if (file_exists($path.'/composer/autoload.php')) {
212
+			require_once $path.'/composer/autoload.php';
213 213
 		} else {
214
-			\OC::$composerAutoloader->addPsr4($appNamespace . '\\', $path . '/lib/', true);
214
+			\OC::$composerAutoloader->addPsr4($appNamespace.'\\', $path.'/lib/', true);
215 215
 			// Register on legacy autoloader
216 216
 			\OC::$loader->addValidRoot($path);
217 217
 		}
218 218
 
219 219
 		// Register Test namespace only when testing
220 220
 		if (defined('PHPUNIT_RUN') || defined('CLI_TEST_RUN')) {
221
-			\OC::$composerAutoloader->addPsr4($appNamespace . '\\Tests\\', $path . '/tests/', true);
221
+			\OC::$composerAutoloader->addPsr4($appNamespace.'\\Tests\\', $path.'/tests/', true);
222 222
 		}
223 223
 	}
224 224
 
@@ -230,7 +230,7 @@  discard block
 block discarded – undo
230 230
 	private static function requireAppFile($app) {
231 231
 		try {
232 232
 			// encapsulated here to avoid variable scope conflicts
233
-			require_once $app . '/appinfo/app.php';
233
+			require_once $app.'/appinfo/app.php';
234 234
 		} catch (Error $ex) {
235 235
 			\OC::$server->getLogger()->logException($ex);
236 236
 			if (!\OC::$server->getAppManager()->isShipped($app)) {
@@ -284,7 +284,7 @@  discard block
 block discarded – undo
284 284
 	 */
285 285
 	public static function setAppTypes($app) {
286 286
 		$appData = self::getAppInfo($app);
287
-		if(!is_array($appData)) {
287
+		if (!is_array($appData)) {
288 288
 			return;
289 289
 		}
290 290
 
@@ -336,8 +336,8 @@  discard block
 block discarded – undo
336 336
 		} else {
337 337
 			$apps = $appManager->getEnabledAppsForUser($user);
338 338
 		}
339
-		$apps = array_filter($apps, function ($app) {
340
-			return $app !== 'files';//we add this manually
339
+		$apps = array_filter($apps, function($app) {
340
+			return $app !== 'files'; //we add this manually
341 341
 		});
342 342
 		sort($apps);
343 343
 		array_unshift($apps, 'files');
@@ -375,7 +375,7 @@  discard block
 block discarded – undo
375 375
 		$installer = \OC::$server->query(Installer::class);
376 376
 		$isDownloaded = $installer->isDownloaded($appId);
377 377
 
378
-		if(!$isDownloaded) {
378
+		if (!$isDownloaded) {
379 379
 			$installer->downloadApp($appId);
380 380
 		}
381 381
 
@@ -475,7 +475,7 @@  discard block
 block discarded – undo
475 475
 	 */
476 476
 	public static function findAppInDirectories($appId) {
477 477
 		$sanitizedAppId = self::cleanAppId($appId);
478
-		if($sanitizedAppId !== $appId) {
478
+		if ($sanitizedAppId !== $appId) {
479 479
 			return false;
480 480
 		}
481 481
 		static $app_dir = array();
@@ -486,7 +486,7 @@  discard block
 block discarded – undo
486 486
 
487 487
 		$possibleApps = array();
488 488
 		foreach (OC::$APPSROOTS as $dir) {
489
-			if (file_exists($dir['path'] . '/' . $appId)) {
489
+			if (file_exists($dir['path'].'/'.$appId)) {
490 490
 				$possibleApps[] = $dir;
491 491
 			}
492 492
 		}
@@ -527,7 +527,7 @@  discard block
 block discarded – undo
527 527
 		}
528 528
 
529 529
 		if (($dir = self::findAppInDirectories($appId)) != false) {
530
-			return $dir['path'] . '/' . $appId;
530
+			return $dir['path'].'/'.$appId;
531 531
 		}
532 532
 		return false;
533 533
 	}
@@ -541,7 +541,7 @@  discard block
 block discarded – undo
541 541
 	 */
542 542
 	public static function getAppWebPath($appId) {
543 543
 		if (($dir = self::findAppInDirectories($appId)) != false) {
544
-			return OC::$WEBROOT . $dir['url'] . '/' . $appId;
544
+			return OC::$WEBROOT.$dir['url'].'/'.$appId;
545 545
 		}
546 546
 		return false;
547 547
 	}
@@ -565,7 +565,7 @@  discard block
 block discarded – undo
565 565
 	 * @return string
566 566
 	 */
567 567
 	public static function getAppVersionByPath($path) {
568
-		$infoFile = $path . '/appinfo/info.xml';
568
+		$infoFile = $path.'/appinfo/info.xml';
569 569
 		$appData = \OC::$server->getAppManager()->getAppInfo($infoFile, true);
570 570
 		return isset($appData['version']) ? $appData['version'] : '';
571 571
 	}
@@ -665,7 +665,7 @@  discard block
 block discarded – undo
665 665
 	 * @param string $page
666 666
 	 */
667 667
 	public static function registerAdmin($app, $page) {
668
-		self::$adminForms[] = $app . '/' . $page . '.php';
668
+		self::$adminForms[] = $app.'/'.$page.'.php';
669 669
 	}
670 670
 
671 671
 	/**
@@ -674,7 +674,7 @@  discard block
 block discarded – undo
674 674
 	 * @param string $page
675 675
 	 */
676 676
 	public static function registerPersonal($app, $page) {
677
-		self::$personalForms[] = $app . '/' . $page . '.php';
677
+		self::$personalForms[] = $app.'/'.$page.'.php';
678 678
 	}
679 679
 
680 680
 	/**
@@ -703,7 +703,7 @@  discard block
 block discarded – undo
703 703
 
704 704
 		foreach (OC::$APPSROOTS as $apps_dir) {
705 705
 			if (!is_readable($apps_dir['path'])) {
706
-				\OCP\Util::writeLog('core', 'unable to read app folder : ' . $apps_dir['path'], \OCP\Util::WARN);
706
+				\OCP\Util::writeLog('core', 'unable to read app folder : '.$apps_dir['path'], \OCP\Util::WARN);
707 707
 				continue;
708 708
 			}
709 709
 			$dh = opendir($apps_dir['path']);
@@ -711,7 +711,7 @@  discard block
 block discarded – undo
711 711
 			if (is_resource($dh)) {
712 712
 				while (($file = readdir($dh)) !== false) {
713 713
 
714
-					if ($file[0] != '.' and is_dir($apps_dir['path'] . '/' . $file) and is_file($apps_dir['path'] . '/' . $file . '/appinfo/info.xml')) {
714
+					if ($file[0] != '.' and is_dir($apps_dir['path'].'/'.$file) and is_file($apps_dir['path'].'/'.$file.'/appinfo/info.xml')) {
715 715
 
716 716
 						$apps[] = $file;
717 717
 					}
@@ -744,12 +744,12 @@  discard block
 block discarded – undo
744 744
 
745 745
 				$info = OC_App::getAppInfo($app, false, $langCode);
746 746
 				if (!is_array($info)) {
747
-					\OCP\Util::writeLog('core', 'Could not read app info file for app "' . $app . '"', \OCP\Util::ERROR);
747
+					\OCP\Util::writeLog('core', 'Could not read app info file for app "'.$app.'"', \OCP\Util::ERROR);
748 748
 					continue;
749 749
 				}
750 750
 
751 751
 				if (!isset($info['name'])) {
752
-					\OCP\Util::writeLog('core', 'App id "' . $app . '" has no name in appinfo', \OCP\Util::ERROR);
752
+					\OCP\Util::writeLog('core', 'App id "'.$app.'" has no name in appinfo', \OCP\Util::ERROR);
753 753
 					continue;
754 754
 				}
755 755
 
@@ -776,13 +776,13 @@  discard block
 block discarded – undo
776 776
 				}
777 777
 
778 778
 				$appPath = self::getAppPath($app);
779
-				if($appPath !== false) {
780
-					$appIcon = $appPath . '/img/' . $app . '.svg';
779
+				if ($appPath !== false) {
780
+					$appIcon = $appPath.'/img/'.$app.'.svg';
781 781
 					if (file_exists($appIcon)) {
782
-						$info['preview'] = $urlGenerator->imagePath($app, $app . '.svg');
782
+						$info['preview'] = $urlGenerator->imagePath($app, $app.'.svg');
783 783
 						$info['previewAsIcon'] = true;
784 784
 					} else {
785
-						$appIcon = $appPath . '/img/app.svg';
785
+						$appIcon = $appPath.'/img/app.svg';
786 786
 						if (file_exists($appIcon)) {
787 787
 							$info['preview'] = $urlGenerator->imagePath($app, 'app.svg');
788 788
 							$info['previewAsIcon'] = true;
@@ -907,7 +907,7 @@  discard block
 block discarded – undo
907 907
 	public static function getAppVersions() {
908 908
 		static $versions;
909 909
 
910
-		if(!$versions) {
910
+		if (!$versions) {
911 911
 			$appConfig = \OC::$server->getAppConfig();
912 912
 			$versions = $appConfig->getValues(false, 'installed_version');
913 913
 		}
@@ -922,7 +922,7 @@  discard block
 block discarded – undo
922 922
 	 */
923 923
 	public static function updateApp($appId) {
924 924
 		$appPath = self::getAppPath($appId);
925
-		if($appPath === false) {
925
+		if ($appPath === false) {
926 926
 			return false;
927 927
 		}
928 928
 		self::registerAutoloading($appId, $appPath);
@@ -930,8 +930,8 @@  discard block
 block discarded – undo
930 930
 		$appData = self::getAppInfo($appId);
931 931
 		self::executeRepairSteps($appId, $appData['repair-steps']['pre-migration']);
932 932
 
933
-		if (file_exists($appPath . '/appinfo/database.xml')) {
934
-			OC_DB::updateDbFromStructure($appPath . '/appinfo/database.xml');
933
+		if (file_exists($appPath.'/appinfo/database.xml')) {
934
+			OC_DB::updateDbFromStructure($appPath.'/appinfo/database.xml');
935 935
 		} else {
936 936
 			$ms = new MigrationService($appId, \OC::$server->getDatabaseConnection());
937 937
 			$ms->migrate();
@@ -943,26 +943,26 @@  discard block
 block discarded – undo
943 943
 		\OC::$server->getAppManager()->getAppVersion($appId, false);
944 944
 
945 945
 		// run upgrade code
946
-		if (file_exists($appPath . '/appinfo/update.php')) {
946
+		if (file_exists($appPath.'/appinfo/update.php')) {
947 947
 			self::loadApp($appId);
948
-			include $appPath . '/appinfo/update.php';
948
+			include $appPath.'/appinfo/update.php';
949 949
 		}
950 950
 		self::setupBackgroundJobs($appData['background-jobs']);
951
-		if(isset($appData['settings']) && is_array($appData['settings'])) {
951
+		if (isset($appData['settings']) && is_array($appData['settings'])) {
952 952
 			\OC::$server->getSettingsManager()->setupSettings($appData['settings']);
953 953
 		}
954 954
 
955 955
 		//set remote/public handlers
956 956
 		if (array_key_exists('ocsid', $appData)) {
957 957
 			\OC::$server->getConfig()->setAppValue($appId, 'ocsid', $appData['ocsid']);
958
-		} elseif(\OC::$server->getConfig()->getAppValue($appId, 'ocsid', null) !== null) {
958
+		} elseif (\OC::$server->getConfig()->getAppValue($appId, 'ocsid', null) !== null) {
959 959
 			\OC::$server->getConfig()->deleteAppValue($appId, 'ocsid');
960 960
 		}
961 961
 		foreach ($appData['remote'] as $name => $path) {
962
-			\OC::$server->getConfig()->setAppValue('core', 'remote_' . $name, $appId . '/' . $path);
962
+			\OC::$server->getConfig()->setAppValue('core', 'remote_'.$name, $appId.'/'.$path);
963 963
 		}
964 964
 		foreach ($appData['public'] as $name => $path) {
965
-			\OC::$server->getConfig()->setAppValue('core', 'public_' . $name, $appId . '/' . $path);
965
+			\OC::$server->getConfig()->setAppValue('core', 'public_'.$name, $appId.'/'.$path);
966 966
 		}
967 967
 
968 968
 		self::setAppTypes($appId);
@@ -1032,17 +1032,17 @@  discard block
 block discarded – undo
1032 1032
 	public static function getStorage($appId) {
1033 1033
 		if (\OC::$server->getAppManager()->isEnabledForUser($appId)) { //sanity check
1034 1034
 			if (\OC::$server->getUserSession()->isLoggedIn()) {
1035
-				$view = new \OC\Files\View('/' . OC_User::getUser());
1035
+				$view = new \OC\Files\View('/'.OC_User::getUser());
1036 1036
 				if (!$view->file_exists($appId)) {
1037 1037
 					$view->mkdir($appId);
1038 1038
 				}
1039
-				return new \OC\Files\View('/' . OC_User::getUser() . '/' . $appId);
1039
+				return new \OC\Files\View('/'.OC_User::getUser().'/'.$appId);
1040 1040
 			} else {
1041
-				\OCP\Util::writeLog('core', 'Can\'t get app storage, app ' . $appId . ', user not logged in', \OCP\Util::ERROR);
1041
+				\OCP\Util::writeLog('core', 'Can\'t get app storage, app '.$appId.', user not logged in', \OCP\Util::ERROR);
1042 1042
 				return false;
1043 1043
 			}
1044 1044
 		} else {
1045
-			\OCP\Util::writeLog('core', 'Can\'t get app storage, app ' . $appId . ' not enabled', \OCP\Util::ERROR);
1045
+			\OCP\Util::writeLog('core', 'Can\'t get app storage, app '.$appId.' not enabled', \OCP\Util::ERROR);
1046 1046
 			return false;
1047 1047
 		}
1048 1048
 	}
@@ -1074,9 +1074,9 @@  discard block
 block discarded – undo
1074 1074
 
1075 1075
 				if ($attributeLang === $similarLang) {
1076 1076
 					$similarLangFallback = $option['@value'];
1077
-				} else if (strpos($attributeLang, $similarLang . '_') === 0) {
1077
+				} else if (strpos($attributeLang, $similarLang.'_') === 0) {
1078 1078
 					if ($similarLangFallback === false) {
1079
-						$similarLangFallback =  $option['@value'];
1079
+						$similarLangFallback = $option['@value'];
1080 1080
 					}
1081 1081
 				}
1082 1082
 			} else {
@@ -1111,7 +1111,7 @@  discard block
 block discarded – undo
1111 1111
 			$data['description'] = trim(self::findBestL10NOption($data['description'], $lang));
1112 1112
 		} else if (isset($data['description']) && is_string($data['description'])) {
1113 1113
 			$data['description'] = trim($data['description']);
1114
-		} else  {
1114
+		} else {
1115 1115
 			$data['description'] = '';
1116 1116
 		}
1117 1117
 
Please login to merge, or discard this patch.
apps/files_trashbin/lib/Storage.php 1 patch
Indentation   +279 added lines, -279 removed lines patch added patch discarded remove patch
@@ -40,284 +40,284 @@
 block discarded – undo
40 40
 
41 41
 class Storage extends Wrapper {
42 42
 
43
-	private $mountPoint;
44
-	// remember already deleted files to avoid infinite loops if the trash bin
45
-	// move files across storages
46
-	private $deletedFiles = array();
47
-
48
-	/**
49
-	 * Disable trash logic
50
-	 *
51
-	 * @var bool
52
-	 */
53
-	private static $disableTrash = false;
54
-
55
-	/**
56
-	 * remember which file/folder was moved out of s shared folder
57
-	 * in this case we want to add a copy to the owners trash bin
58
-	 *
59
-	 * @var array
60
-	 */
61
-	private static $moveOutOfSharedFolder = [];
62
-
63
-	/** @var  IUserManager */
64
-	private $userManager;
65
-
66
-	/** @var ILogger */
67
-	private $logger;
68
-
69
-	/** @var EventDispatcher */
70
-	private $eventDispatcher;
71
-
72
-	/** @var IRootFolder */
73
-	private $rootFolder;
74
-
75
-	/**
76
-	 * Storage constructor.
77
-	 *
78
-	 * @param array $parameters
79
-	 * @param IUserManager|null $userManager
80
-	 * @param ILogger|null $logger
81
-	 * @param EventDispatcher|null $eventDispatcher
82
-	 * @param IRootFolder|null $rootFolder
83
-	 */
84
-	public function __construct($parameters,
85
-								IUserManager $userManager = null,
86
-								ILogger $logger = null,
87
-								EventDispatcher $eventDispatcher = null,
88
-								IRootFolder $rootFolder = null) {
89
-		$this->mountPoint = $parameters['mountPoint'];
90
-		$this->userManager = $userManager;
91
-		$this->logger = $logger;
92
-		$this->eventDispatcher = $eventDispatcher;
93
-		$this->rootFolder = $rootFolder;
94
-		parent::__construct($parameters);
95
-	}
96
-
97
-	/**
98
-	 * @internal
99
-	 */
100
-	public static function preRenameHook($params) {
101
-		// in cross-storage cases, a rename is a copy + unlink,
102
-		// that last unlink must not go to trash, only exception:
103
-		// if the file was moved from a shared storage to a local folder,
104
-		// in this case the owner should get a copy in his trash bin so that
105
-		// they can restore the files again
106
-
107
-		$oldPath = $params['oldpath'];
108
-		$newPath = dirname($params['newpath']);
109
-		$currentUser = \OC::$server->getUserSession()->getUser();
110
-
111
-		$fileMovedOutOfSharedFolder = false;
112
-
113
-		try {
114
-			if ($currentUser) {
115
-				$currentUserId = $currentUser->getUID();
116
-
117
-				$view = new View($currentUserId . '/files');
118
-				$fileInfo = $view->getFileInfo($oldPath);
119
-				if ($fileInfo) {
120
-					$sourceStorage = $fileInfo->getStorage();
121
-					$sourceOwner = $view->getOwner($oldPath);
122
-					$targetOwner = $view->getOwner($newPath);
123
-
124
-					if ($sourceOwner !== $targetOwner
125
-						&& $sourceStorage->instanceOfStorage('OCA\Files_Sharing\SharedStorage')
126
-					) {
127
-						$fileMovedOutOfSharedFolder = true;
128
-					}
129
-				}
130
-			}
131
-		} catch (\Exception $e) {
132
-			// do nothing, in this case we just disable the trashbin and continue
133
-			\OC::$server->getLogger()->logException($e, [
134
-				'message' => 'Trashbin storage could not check if a file was moved out of a shared folder.',
135
-				'level' => \OCP\Util::DEBUG,
136
-				'app' => 'files_trashbin',
137
-			]);
138
-		}
139
-
140
-		if($fileMovedOutOfSharedFolder) {
141
-			self::$moveOutOfSharedFolder['/' . $currentUserId . '/files' . $oldPath] = true;
142
-		} else {
143
-			self::$disableTrash = true;
144
-		}
145
-
146
-	}
147
-
148
-	/**
149
-	 * @internal
150
-	 */
151
-	public static function postRenameHook($params) {
152
-		self::$disableTrash = false;
153
-	}
154
-
155
-	/**
156
-	 * Rename path1 to path2 by calling the wrapped storage.
157
-	 *
158
-	 * @param string $path1 first path
159
-	 * @param string $path2 second path
160
-	 * @return bool
161
-	 */
162
-	public function rename($path1, $path2) {
163
-		$result = $this->storage->rename($path1, $path2);
164
-		if ($result === false) {
165
-			// when rename failed, the post_rename hook isn't triggered,
166
-			// but we still want to reenable the trash logic
167
-			self::$disableTrash = false;
168
-		}
169
-		return $result;
170
-	}
171
-
172
-	/**
173
-	 * Deletes the given file by moving it into the trashbin.
174
-	 *
175
-	 * @param string $path path of file or folder to delete
176
-	 *
177
-	 * @return bool true if the operation succeeded, false otherwise
178
-	 */
179
-	public function unlink($path) {
180
-		try {
181
-			if (isset(self::$moveOutOfSharedFolder[$this->mountPoint . $path])) {
182
-				$result = $this->doDelete($path, 'unlink', true);
183
-				unset(self::$moveOutOfSharedFolder[$this->mountPoint . $path]);
184
-			} else {
185
-				$result = $this->doDelete($path, 'unlink');
186
-			}
187
-		} catch (GenericEncryptionException $e) {
188
-			// in case of a encryption exception we delete the file right away
189
-			$this->logger->info(
190
-				"Can't move file" .  $path .
191
-				"to the trash bin, therefore it was deleted right away");
192
-
193
-			$result = $this->storage->unlink($path);
194
-		}
195
-
196
-		return $result;
197
-	}
198
-
199
-	/**
200
-	 * Deletes the given folder by moving it into the trashbin.
201
-	 *
202
-	 * @param string $path path of folder to delete
203
-	 *
204
-	 * @return bool true if the operation succeeded, false otherwise
205
-	 */
206
-	public function rmdir($path) {
207
-		if (isset(self::$moveOutOfSharedFolder[$this->mountPoint . $path])) {
208
-			$result = $this->doDelete($path, 'rmdir', true);
209
-			unset(self::$moveOutOfSharedFolder[$this->mountPoint . $path]);
210
-		} else {
211
-			$result = $this->doDelete($path, 'rmdir');
212
-		}
213
-
214
-		return $result;
215
-	}
216
-
217
-	/**
218
-	 * check if it is a file located in data/user/files only files in the
219
-	 * 'files' directory should be moved to the trash
220
-	 *
221
-	 * @param $path
222
-	 * @return bool
223
-	 */
224
-	protected function shouldMoveToTrash($path){
225
-
226
-		// check if there is a app which want to disable the trash bin for this file
227
-		$fileId = $this->storage->getCache()->getId($path);
228
-		$nodes = $this->rootFolder->getById($fileId);
229
-		foreach ($nodes as $node) {
230
-			$event = $this->createMoveToTrashEvent($node);
231
-			$this->eventDispatcher->dispatch('OCA\Files_Trashbin::moveToTrash', $event);
232
-			if ($event->shouldMoveToTrashBin() === false) {
233
-				return false;
234
-			}
235
-		}
236
-
237
-		$normalized = Filesystem::normalizePath($this->mountPoint . '/' . $path);
238
-		$parts = explode('/', $normalized);
239
-		if (count($parts) < 4) {
240
-			return false;
241
-		}
242
-
243
-		if ($parts[2] === 'files' && $this->userManager->userExists($parts[1])) {
244
-			return true;
245
-		}
246
-
247
-		return false;
248
-	}
249
-
250
-	/**
251
-	 * get move to trash event
252
-	 *
253
-	 * @param Node $node
254
-	 * @return MoveToTrashEvent
255
-	 */
256
-	protected function createMoveToTrashEvent(Node $node) {
257
-		return new MoveToTrashEvent($node);
258
-	}
259
-
260
-	/**
261
-	 * Run the delete operation with the given method
262
-	 *
263
-	 * @param string $path path of file or folder to delete
264
-	 * @param string $method either "unlink" or "rmdir"
265
-	 * @param bool $ownerOnly delete for owner only (if file gets moved out of a shared folder)
266
-	 *
267
-	 * @return bool true if the operation succeeded, false otherwise
268
-	 */
269
-	private function doDelete($path, $method, $ownerOnly = false) {
270
-		if (self::$disableTrash
271
-			|| !\OC::$server->getAppManager()->isEnabledForUser('files_trashbin')
272
-			|| (pathinfo($path, PATHINFO_EXTENSION) === 'part')
273
-			|| $this->shouldMoveToTrash($path) === false
274
-		) {
275
-			return call_user_func_array([$this->storage, $method], [$path]);
276
-		}
277
-
278
-		// check permissions before we continue, this is especially important for
279
-		// shared files
280
-		if (!$this->isDeletable($path)) {
281
-			return false;
282
-		}
283
-
284
-		$normalized = Filesystem::normalizePath($this->mountPoint . '/' . $path, true, false, true);
285
-		$result = true;
286
-		$view = Filesystem::getView();
287
-		if (!isset($this->deletedFiles[$normalized]) && $view instanceof View) {
288
-			$this->deletedFiles[$normalized] = $normalized;
289
-			if ($filesPath = $view->getRelativePath($normalized)) {
290
-				$filesPath = trim($filesPath, '/');
291
-				$result = \OCA\Files_Trashbin\Trashbin::move2trash($filesPath, $ownerOnly);
292
-				// in cross-storage cases the file will be copied
293
-				// but not deleted, so we delete it here
294
-				if ($result) {
295
-					call_user_func_array([$this->storage, $method], [$path]);
296
-				}
297
-			} else {
298
-				$result = call_user_func_array([$this->storage, $method], [$path]);
299
-			}
300
-			unset($this->deletedFiles[$normalized]);
301
-		} else if ($this->storage->file_exists($path)) {
302
-			$result = call_user_func_array([$this->storage, $method], [$path]);
303
-		}
304
-
305
-		return $result;
306
-	}
307
-
308
-	/**
309
-	 * Setup the storate wrapper callback
310
-	 */
311
-	public static function setupStorage() {
312
-		\OC\Files\Filesystem::addStorageWrapper('oc_trashbin', function ($mountPoint, $storage) {
313
-			return new \OCA\Files_Trashbin\Storage(
314
-				array('storage' => $storage, 'mountPoint' => $mountPoint),
315
-				\OC::$server->getUserManager(),
316
-				\OC::$server->getLogger(),
317
-				\OC::$server->getEventDispatcher(),
318
-				\OC::$server->getLazyRootFolder()
319
-			);
320
-		}, 1);
321
-	}
43
+    private $mountPoint;
44
+    // remember already deleted files to avoid infinite loops if the trash bin
45
+    // move files across storages
46
+    private $deletedFiles = array();
47
+
48
+    /**
49
+     * Disable trash logic
50
+     *
51
+     * @var bool
52
+     */
53
+    private static $disableTrash = false;
54
+
55
+    /**
56
+     * remember which file/folder was moved out of s shared folder
57
+     * in this case we want to add a copy to the owners trash bin
58
+     *
59
+     * @var array
60
+     */
61
+    private static $moveOutOfSharedFolder = [];
62
+
63
+    /** @var  IUserManager */
64
+    private $userManager;
65
+
66
+    /** @var ILogger */
67
+    private $logger;
68
+
69
+    /** @var EventDispatcher */
70
+    private $eventDispatcher;
71
+
72
+    /** @var IRootFolder */
73
+    private $rootFolder;
74
+
75
+    /**
76
+     * Storage constructor.
77
+     *
78
+     * @param array $parameters
79
+     * @param IUserManager|null $userManager
80
+     * @param ILogger|null $logger
81
+     * @param EventDispatcher|null $eventDispatcher
82
+     * @param IRootFolder|null $rootFolder
83
+     */
84
+    public function __construct($parameters,
85
+                                IUserManager $userManager = null,
86
+                                ILogger $logger = null,
87
+                                EventDispatcher $eventDispatcher = null,
88
+                                IRootFolder $rootFolder = null) {
89
+        $this->mountPoint = $parameters['mountPoint'];
90
+        $this->userManager = $userManager;
91
+        $this->logger = $logger;
92
+        $this->eventDispatcher = $eventDispatcher;
93
+        $this->rootFolder = $rootFolder;
94
+        parent::__construct($parameters);
95
+    }
96
+
97
+    /**
98
+     * @internal
99
+     */
100
+    public static function preRenameHook($params) {
101
+        // in cross-storage cases, a rename is a copy + unlink,
102
+        // that last unlink must not go to trash, only exception:
103
+        // if the file was moved from a shared storage to a local folder,
104
+        // in this case the owner should get a copy in his trash bin so that
105
+        // they can restore the files again
106
+
107
+        $oldPath = $params['oldpath'];
108
+        $newPath = dirname($params['newpath']);
109
+        $currentUser = \OC::$server->getUserSession()->getUser();
110
+
111
+        $fileMovedOutOfSharedFolder = false;
112
+
113
+        try {
114
+            if ($currentUser) {
115
+                $currentUserId = $currentUser->getUID();
116
+
117
+                $view = new View($currentUserId . '/files');
118
+                $fileInfo = $view->getFileInfo($oldPath);
119
+                if ($fileInfo) {
120
+                    $sourceStorage = $fileInfo->getStorage();
121
+                    $sourceOwner = $view->getOwner($oldPath);
122
+                    $targetOwner = $view->getOwner($newPath);
123
+
124
+                    if ($sourceOwner !== $targetOwner
125
+                        && $sourceStorage->instanceOfStorage('OCA\Files_Sharing\SharedStorage')
126
+                    ) {
127
+                        $fileMovedOutOfSharedFolder = true;
128
+                    }
129
+                }
130
+            }
131
+        } catch (\Exception $e) {
132
+            // do nothing, in this case we just disable the trashbin and continue
133
+            \OC::$server->getLogger()->logException($e, [
134
+                'message' => 'Trashbin storage could not check if a file was moved out of a shared folder.',
135
+                'level' => \OCP\Util::DEBUG,
136
+                'app' => 'files_trashbin',
137
+            ]);
138
+        }
139
+
140
+        if($fileMovedOutOfSharedFolder) {
141
+            self::$moveOutOfSharedFolder['/' . $currentUserId . '/files' . $oldPath] = true;
142
+        } else {
143
+            self::$disableTrash = true;
144
+        }
145
+
146
+    }
147
+
148
+    /**
149
+     * @internal
150
+     */
151
+    public static function postRenameHook($params) {
152
+        self::$disableTrash = false;
153
+    }
154
+
155
+    /**
156
+     * Rename path1 to path2 by calling the wrapped storage.
157
+     *
158
+     * @param string $path1 first path
159
+     * @param string $path2 second path
160
+     * @return bool
161
+     */
162
+    public function rename($path1, $path2) {
163
+        $result = $this->storage->rename($path1, $path2);
164
+        if ($result === false) {
165
+            // when rename failed, the post_rename hook isn't triggered,
166
+            // but we still want to reenable the trash logic
167
+            self::$disableTrash = false;
168
+        }
169
+        return $result;
170
+    }
171
+
172
+    /**
173
+     * Deletes the given file by moving it into the trashbin.
174
+     *
175
+     * @param string $path path of file or folder to delete
176
+     *
177
+     * @return bool true if the operation succeeded, false otherwise
178
+     */
179
+    public function unlink($path) {
180
+        try {
181
+            if (isset(self::$moveOutOfSharedFolder[$this->mountPoint . $path])) {
182
+                $result = $this->doDelete($path, 'unlink', true);
183
+                unset(self::$moveOutOfSharedFolder[$this->mountPoint . $path]);
184
+            } else {
185
+                $result = $this->doDelete($path, 'unlink');
186
+            }
187
+        } catch (GenericEncryptionException $e) {
188
+            // in case of a encryption exception we delete the file right away
189
+            $this->logger->info(
190
+                "Can't move file" .  $path .
191
+                "to the trash bin, therefore it was deleted right away");
192
+
193
+            $result = $this->storage->unlink($path);
194
+        }
195
+
196
+        return $result;
197
+    }
198
+
199
+    /**
200
+     * Deletes the given folder by moving it into the trashbin.
201
+     *
202
+     * @param string $path path of folder to delete
203
+     *
204
+     * @return bool true if the operation succeeded, false otherwise
205
+     */
206
+    public function rmdir($path) {
207
+        if (isset(self::$moveOutOfSharedFolder[$this->mountPoint . $path])) {
208
+            $result = $this->doDelete($path, 'rmdir', true);
209
+            unset(self::$moveOutOfSharedFolder[$this->mountPoint . $path]);
210
+        } else {
211
+            $result = $this->doDelete($path, 'rmdir');
212
+        }
213
+
214
+        return $result;
215
+    }
216
+
217
+    /**
218
+     * check if it is a file located in data/user/files only files in the
219
+     * 'files' directory should be moved to the trash
220
+     *
221
+     * @param $path
222
+     * @return bool
223
+     */
224
+    protected function shouldMoveToTrash($path){
225
+
226
+        // check if there is a app which want to disable the trash bin for this file
227
+        $fileId = $this->storage->getCache()->getId($path);
228
+        $nodes = $this->rootFolder->getById($fileId);
229
+        foreach ($nodes as $node) {
230
+            $event = $this->createMoveToTrashEvent($node);
231
+            $this->eventDispatcher->dispatch('OCA\Files_Trashbin::moveToTrash', $event);
232
+            if ($event->shouldMoveToTrashBin() === false) {
233
+                return false;
234
+            }
235
+        }
236
+
237
+        $normalized = Filesystem::normalizePath($this->mountPoint . '/' . $path);
238
+        $parts = explode('/', $normalized);
239
+        if (count($parts) < 4) {
240
+            return false;
241
+        }
242
+
243
+        if ($parts[2] === 'files' && $this->userManager->userExists($parts[1])) {
244
+            return true;
245
+        }
246
+
247
+        return false;
248
+    }
249
+
250
+    /**
251
+     * get move to trash event
252
+     *
253
+     * @param Node $node
254
+     * @return MoveToTrashEvent
255
+     */
256
+    protected function createMoveToTrashEvent(Node $node) {
257
+        return new MoveToTrashEvent($node);
258
+    }
259
+
260
+    /**
261
+     * Run the delete operation with the given method
262
+     *
263
+     * @param string $path path of file or folder to delete
264
+     * @param string $method either "unlink" or "rmdir"
265
+     * @param bool $ownerOnly delete for owner only (if file gets moved out of a shared folder)
266
+     *
267
+     * @return bool true if the operation succeeded, false otherwise
268
+     */
269
+    private function doDelete($path, $method, $ownerOnly = false) {
270
+        if (self::$disableTrash
271
+            || !\OC::$server->getAppManager()->isEnabledForUser('files_trashbin')
272
+            || (pathinfo($path, PATHINFO_EXTENSION) === 'part')
273
+            || $this->shouldMoveToTrash($path) === false
274
+        ) {
275
+            return call_user_func_array([$this->storage, $method], [$path]);
276
+        }
277
+
278
+        // check permissions before we continue, this is especially important for
279
+        // shared files
280
+        if (!$this->isDeletable($path)) {
281
+            return false;
282
+        }
283
+
284
+        $normalized = Filesystem::normalizePath($this->mountPoint . '/' . $path, true, false, true);
285
+        $result = true;
286
+        $view = Filesystem::getView();
287
+        if (!isset($this->deletedFiles[$normalized]) && $view instanceof View) {
288
+            $this->deletedFiles[$normalized] = $normalized;
289
+            if ($filesPath = $view->getRelativePath($normalized)) {
290
+                $filesPath = trim($filesPath, '/');
291
+                $result = \OCA\Files_Trashbin\Trashbin::move2trash($filesPath, $ownerOnly);
292
+                // in cross-storage cases the file will be copied
293
+                // but not deleted, so we delete it here
294
+                if ($result) {
295
+                    call_user_func_array([$this->storage, $method], [$path]);
296
+                }
297
+            } else {
298
+                $result = call_user_func_array([$this->storage, $method], [$path]);
299
+            }
300
+            unset($this->deletedFiles[$normalized]);
301
+        } else if ($this->storage->file_exists($path)) {
302
+            $result = call_user_func_array([$this->storage, $method], [$path]);
303
+        }
304
+
305
+        return $result;
306
+    }
307
+
308
+    /**
309
+     * Setup the storate wrapper callback
310
+     */
311
+    public static function setupStorage() {
312
+        \OC\Files\Filesystem::addStorageWrapper('oc_trashbin', function ($mountPoint, $storage) {
313
+            return new \OCA\Files_Trashbin\Storage(
314
+                array('storage' => $storage, 'mountPoint' => $mountPoint),
315
+                \OC::$server->getUserManager(),
316
+                \OC::$server->getLogger(),
317
+                \OC::$server->getEventDispatcher(),
318
+                \OC::$server->getLazyRootFolder()
319
+            );
320
+        }, 1);
321
+    }
322 322
 
323 323
 }
Please login to merge, or discard this patch.
settings/ajax/uninstallapp.php 2 patches
Indentation   +11 added lines, -11 removed lines patch added patch discarded remove patch
@@ -27,14 +27,14 @@  discard block
 block discarded – undo
27 27
 
28 28
 $lastConfirm = (int) \OC::$server->getSession()->get('last-password-confirm');
29 29
 if ($lastConfirm < (time() - 30 * 60 + 15)) { // allow 15 seconds delay
30
-	$l = \OC::$server->getL10N('core');
31
-	OC_JSON::error(array( 'data' => array( 'message' => $l->t('Password confirmation is required'))));
32
-	exit();
30
+    $l = \OC::$server->getL10N('core');
31
+    OC_JSON::error(array( 'data' => array( 'message' => $l->t('Password confirmation is required'))));
32
+    exit();
33 33
 }
34 34
 
35 35
 if (!array_key_exists('appid', $_POST)) {
36
-	OC_JSON::error();
37
-	exit;
36
+    OC_JSON::error();
37
+    exit;
38 38
 }
39 39
 
40 40
 $appId = (string)$_POST['appid'];
@@ -45,11 +45,11 @@  discard block
 block discarded – undo
45 45
 $installer = \OC::$server->query(\OC\Installer::class);
46 46
 $result = $installer->removeApp($app);
47 47
 if($result !== false) {
48
-	// FIXME: Clear the cache - move that into some sane helper method
49
-	\OC::$server->getMemCacheFactory()->createDistributed('settings')->remove('listApps-0');
50
-	\OC::$server->getMemCacheFactory()->createDistributed('settings')->remove('listApps-1');
51
-	OC_JSON::success(array('data' => array('appid' => $appId)));
48
+    // FIXME: Clear the cache - move that into some sane helper method
49
+    \OC::$server->getMemCacheFactory()->createDistributed('settings')->remove('listApps-0');
50
+    \OC::$server->getMemCacheFactory()->createDistributed('settings')->remove('listApps-1');
51
+    OC_JSON::success(array('data' => array('appid' => $appId)));
52 52
 } else {
53
-	$l = \OC::$server->getL10N('settings');
54
-	OC_JSON::error(array('data' => array( 'message' => $l->t("Couldn't remove app.") )));
53
+    $l = \OC::$server->getL10N('settings');
54
+    OC_JSON::error(array('data' => array( 'message' => $l->t("Couldn't remove app.") )));
55 55
 }
Please login to merge, or discard this patch.
Spacing   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -28,7 +28,7 @@  discard block
 block discarded – undo
28 28
 $lastConfirm = (int) \OC::$server->getSession()->get('last-password-confirm');
29 29
 if ($lastConfirm < (time() - 30 * 60 + 15)) { // allow 15 seconds delay
30 30
 	$l = \OC::$server->getL10N('core');
31
-	OC_JSON::error(array( 'data' => array( 'message' => $l->t('Password confirmation is required'))));
31
+	OC_JSON::error(array('data' => array('message' => $l->t('Password confirmation is required'))));
32 32
 	exit();
33 33
 }
34 34
 
@@ -37,19 +37,19 @@  discard block
 block discarded – undo
37 37
 	exit;
38 38
 }
39 39
 
40
-$appId = (string)$_POST['appid'];
40
+$appId = (string) $_POST['appid'];
41 41
 $appId = OC_App::cleanAppId($appId);
42 42
 
43 43
 // FIXME: move to controller
44 44
 /** @var \OC\Installer $installer */
45 45
 $installer = \OC::$server->query(\OC\Installer::class);
46 46
 $result = $installer->removeApp($app);
47
-if($result !== false) {
47
+if ($result !== false) {
48 48
 	// FIXME: Clear the cache - move that into some sane helper method
49 49
 	\OC::$server->getMemCacheFactory()->createDistributed('settings')->remove('listApps-0');
50 50
 	\OC::$server->getMemCacheFactory()->createDistributed('settings')->remove('listApps-1');
51 51
 	OC_JSON::success(array('data' => array('appid' => $appId)));
52 52
 } else {
53 53
 	$l = \OC::$server->getL10N('settings');
54
-	OC_JSON::error(array('data' => array( 'message' => $l->t("Couldn't remove app.") )));
54
+	OC_JSON::error(array('data' => array('message' => $l->t("Couldn't remove app."))));
55 55
 }
Please login to merge, or discard this patch.
lib/private/App/AppManager.php 2 patches
Indentation   +397 added lines, -397 removed lines patch added patch discarded remove patch
@@ -45,401 +45,401 @@
 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 AppConfig */
64
-	private $appConfig;
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 AppConfig $appConfig
93
-	 * @param IGroupManager $groupManager
94
-	 * @param ICacheFactory $memCacheFactory
95
-	 * @param EventDispatcherInterface $dispatcher
96
-	 */
97
-	public function __construct(IUserSession $userSession,
98
-								IAppConfig $appConfig = null,
99
-								IGroupManager $groupManager,
100
-								ICacheFactory $memCacheFactory,
101
-								EventDispatcherInterface $dispatcher) {
102
-		$this->userSession = $userSession;
103
-		$this->appConfig = $appConfig;
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 = $this->appConfig->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 installed in the instance
209
-	 *
210
-	 * @param string $appId
211
-	 * @return bool
212
-	 */
213
-	public function isInstalled($appId) {
214
-		$installedApps = $this->getInstalledAppsValues();
215
-		return isset($installedApps[$appId]);
216
-	}
217
-
218
-	/**
219
-	 * Enable an app for every user
220
-	 *
221
-	 * @param string $appId
222
-	 * @throws AppPathNotFoundException
223
-	 */
224
-	public function enableApp($appId) {
225
-		// Check if app exists
226
-		$this->getAppPath($appId);
227
-
228
-		$this->installedAppsCache[$appId] = 'yes';
229
-		$this->appConfig->setValue($appId, 'enabled', 'yes');
230
-		$this->dispatcher->dispatch(ManagerEvent::EVENT_APP_ENABLE, new ManagerEvent(
231
-			ManagerEvent::EVENT_APP_ENABLE, $appId
232
-		));
233
-		$this->clearAppsCache();
234
-	}
235
-
236
-	/**
237
-	 * Whether a list of types contains a protected app type
238
-	 *
239
-	 * @param string[] $types
240
-	 * @return bool
241
-	 */
242
-	public function hasProtectedAppType($types) {
243
-		if (empty($types)) {
244
-			return false;
245
-		}
246
-
247
-		$protectedTypes = array_intersect($this->protectedAppTypes, $types);
248
-		return !empty($protectedTypes);
249
-	}
250
-
251
-	/**
252
-	 * Enable an app only for specific groups
253
-	 *
254
-	 * @param string $appId
255
-	 * @param \OCP\IGroup[] $groups
256
-	 * @throws \Exception if app can't be enabled for groups
257
-	 */
258
-	public function enableAppForGroups($appId, $groups) {
259
-		$info = $this->getAppInfo($appId);
260
-		if (!empty($info['types'])) {
261
-			$protectedTypes = array_intersect($this->protectedAppTypes, $info['types']);
262
-			if (!empty($protectedTypes)) {
263
-				throw new \Exception("$appId can't be enabled for groups.");
264
-			}
265
-		}
266
-
267
-		$groupIds = array_map(function ($group) {
268
-			/** @var \OCP\IGroup $group */
269
-			return $group->getGID();
270
-		}, $groups);
271
-		$this->installedAppsCache[$appId] = json_encode($groupIds);
272
-		$this->appConfig->setValue($appId, 'enabled', json_encode($groupIds));
273
-		$this->dispatcher->dispatch(ManagerEvent::EVENT_APP_ENABLE_FOR_GROUPS, new ManagerEvent(
274
-			ManagerEvent::EVENT_APP_ENABLE_FOR_GROUPS, $appId, $groups
275
-		));
276
-		$this->clearAppsCache();
277
-	}
278
-
279
-	/**
280
-	 * Disable an app for every user
281
-	 *
282
-	 * @param string $appId
283
-	 * @throws \Exception if app can't be disabled
284
-	 */
285
-	public function disableApp($appId) {
286
-		if ($this->isAlwaysEnabled($appId)) {
287
-			throw new \Exception("$appId can't be disabled.");
288
-		}
289
-		unset($this->installedAppsCache[$appId]);
290
-		$this->appConfig->setValue($appId, 'enabled', 'no');
291
-		$this->dispatcher->dispatch(ManagerEvent::EVENT_APP_DISABLE, new ManagerEvent(
292
-			ManagerEvent::EVENT_APP_DISABLE, $appId
293
-		));
294
-		$this->clearAppsCache();
295
-	}
296
-
297
-	/**
298
-	 * Get the directory for the given app.
299
-	 *
300
-	 * @param string $appId
301
-	 * @return string
302
-	 * @throws AppPathNotFoundException if app folder can't be found
303
-	 */
304
-	public function getAppPath($appId) {
305
-		$appPath = \OC_App::getAppPath($appId);
306
-		if($appPath === false) {
307
-			throw new AppPathNotFoundException('Could not find path for ' . $appId);
308
-		}
309
-		return $appPath;
310
-	}
311
-
312
-	/**
313
-	 * Clear the cached list of apps when enabling/disabling an app
314
-	 */
315
-	public function clearAppsCache() {
316
-		$settingsMemCache = $this->memCacheFactory->createDistributed('settings');
317
-		$settingsMemCache->clear('listApps');
318
-	}
319
-
320
-	/**
321
-	 * Returns a list of apps that need upgrade
322
-	 *
323
-	 * @param string $version Nextcloud version as array of version components
324
-	 * @return array list of app info from apps that need an upgrade
325
-	 *
326
-	 * @internal
327
-	 */
328
-	public function getAppsNeedingUpgrade($version) {
329
-		$appsToUpgrade = [];
330
-		$apps = $this->getInstalledApps();
331
-		foreach ($apps as $appId) {
332
-			$appInfo = $this->getAppInfo($appId);
333
-			$appDbVersion = $this->appConfig->getValue($appId, 'installed_version');
334
-			if ($appDbVersion
335
-				&& isset($appInfo['version'])
336
-				&& version_compare($appInfo['version'], $appDbVersion, '>')
337
-				&& \OC_App::isAppCompatible($version, $appInfo)
338
-			) {
339
-				$appsToUpgrade[] = $appInfo;
340
-			}
341
-		}
342
-
343
-		return $appsToUpgrade;
344
-	}
345
-
346
-	/**
347
-	 * Returns the app information from "appinfo/info.xml".
348
-	 *
349
-	 * @param string $appId app id
350
-	 *
351
-	 * @param bool $path
352
-	 * @param null $lang
353
-	 * @return array app info
354
-	 */
355
-	public function getAppInfo(string $appId, bool $path = false, $lang = null) {
356
-		if ($path) {
357
-			$file = $appId;
358
-		} else {
359
-			if ($lang === null && isset($this->appInfos[$appId])) {
360
-				return $this->appInfos[$appId];
361
-			}
362
-			try {
363
-				$appPath = $this->getAppPath($appId);
364
-			} catch (AppPathNotFoundException $e) {
365
-				return null;
366
-			}
367
-			$file = $appPath . '/appinfo/info.xml';
368
-		}
369
-
370
-		$parser = new InfoParser($this->memCacheFactory->createLocal('core.appinfo'));
371
-		$data = $parser->parse($file);
372
-
373
-		if (is_array($data)) {
374
-			$data = \OC_App::parseAppInfo($data, $lang);
375
-		}
376
-
377
-		if ($lang === null) {
378
-			$this->appInfos[$appId] = $data;
379
-		}
380
-
381
-		return $data;
382
-	}
383
-
384
-	public function getAppVersion(string $appId, bool $useCache = true) {
385
-		if(!$useCache || !isset($this->appVersions[$appId])) {
386
-			$appInfo = \OC::$server->getAppManager()->getAppInfo($appId);
387
-			$this->appVersions[$appId] = ($appInfo !== null) ? $appInfo['version'] : '0';
388
-		}
389
-		return $this->appVersions[$appId];
390
-	}
391
-
392
-	/**
393
-	 * Returns a list of apps incompatible with the given version
394
-	 *
395
-	 * @param string $version Nextcloud version as array of version components
396
-	 *
397
-	 * @return array list of app info from incompatible apps
398
-	 *
399
-	 * @internal
400
-	 */
401
-	public function getIncompatibleApps($version) {
402
-		$apps = $this->getInstalledApps();
403
-		$incompatibleApps = array();
404
-		foreach ($apps as $appId) {
405
-			$info = $this->getAppInfo($appId);
406
-			if (!\OC_App::isAppCompatible($version, $info)) {
407
-				$incompatibleApps[] = $info;
408
-			}
409
-		}
410
-		return $incompatibleApps;
411
-	}
412
-
413
-	/**
414
-	 * @inheritdoc
415
-	 */
416
-	public function isShipped($appId) {
417
-		$this->loadShippedJson();
418
-		return in_array($appId, $this->shippedApps, true);
419
-	}
420
-
421
-	private function isAlwaysEnabled($appId) {
422
-		$alwaysEnabled = $this->getAlwaysEnabledApps();
423
-		return in_array($appId, $alwaysEnabled, true);
424
-	}
425
-
426
-	private function loadShippedJson() {
427
-		if ($this->shippedApps === null) {
428
-			$shippedJson = \OC::$SERVERROOT . '/core/shipped.json';
429
-			if (!file_exists($shippedJson)) {
430
-				throw new \Exception("File not found: $shippedJson");
431
-			}
432
-			$content = json_decode(file_get_contents($shippedJson), true);
433
-			$this->shippedApps = $content['shippedApps'];
434
-			$this->alwaysEnabled = $content['alwaysEnabled'];
435
-		}
436
-	}
437
-
438
-	/**
439
-	 * @inheritdoc
440
-	 */
441
-	public function getAlwaysEnabledApps() {
442
-		$this->loadShippedJson();
443
-		return $this->alwaysEnabled;
444
-	}
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 AppConfig */
64
+    private $appConfig;
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 AppConfig $appConfig
93
+     * @param IGroupManager $groupManager
94
+     * @param ICacheFactory $memCacheFactory
95
+     * @param EventDispatcherInterface $dispatcher
96
+     */
97
+    public function __construct(IUserSession $userSession,
98
+                                IAppConfig $appConfig = null,
99
+                                IGroupManager $groupManager,
100
+                                ICacheFactory $memCacheFactory,
101
+                                EventDispatcherInterface $dispatcher) {
102
+        $this->userSession = $userSession;
103
+        $this->appConfig = $appConfig;
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 = $this->appConfig->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 installed in the instance
209
+     *
210
+     * @param string $appId
211
+     * @return bool
212
+     */
213
+    public function isInstalled($appId) {
214
+        $installedApps = $this->getInstalledAppsValues();
215
+        return isset($installedApps[$appId]);
216
+    }
217
+
218
+    /**
219
+     * Enable an app for every user
220
+     *
221
+     * @param string $appId
222
+     * @throws AppPathNotFoundException
223
+     */
224
+    public function enableApp($appId) {
225
+        // Check if app exists
226
+        $this->getAppPath($appId);
227
+
228
+        $this->installedAppsCache[$appId] = 'yes';
229
+        $this->appConfig->setValue($appId, 'enabled', 'yes');
230
+        $this->dispatcher->dispatch(ManagerEvent::EVENT_APP_ENABLE, new ManagerEvent(
231
+            ManagerEvent::EVENT_APP_ENABLE, $appId
232
+        ));
233
+        $this->clearAppsCache();
234
+    }
235
+
236
+    /**
237
+     * Whether a list of types contains a protected app type
238
+     *
239
+     * @param string[] $types
240
+     * @return bool
241
+     */
242
+    public function hasProtectedAppType($types) {
243
+        if (empty($types)) {
244
+            return false;
245
+        }
246
+
247
+        $protectedTypes = array_intersect($this->protectedAppTypes, $types);
248
+        return !empty($protectedTypes);
249
+    }
250
+
251
+    /**
252
+     * Enable an app only for specific groups
253
+     *
254
+     * @param string $appId
255
+     * @param \OCP\IGroup[] $groups
256
+     * @throws \Exception if app can't be enabled for groups
257
+     */
258
+    public function enableAppForGroups($appId, $groups) {
259
+        $info = $this->getAppInfo($appId);
260
+        if (!empty($info['types'])) {
261
+            $protectedTypes = array_intersect($this->protectedAppTypes, $info['types']);
262
+            if (!empty($protectedTypes)) {
263
+                throw new \Exception("$appId can't be enabled for groups.");
264
+            }
265
+        }
266
+
267
+        $groupIds = array_map(function ($group) {
268
+            /** @var \OCP\IGroup $group */
269
+            return $group->getGID();
270
+        }, $groups);
271
+        $this->installedAppsCache[$appId] = json_encode($groupIds);
272
+        $this->appConfig->setValue($appId, 'enabled', json_encode($groupIds));
273
+        $this->dispatcher->dispatch(ManagerEvent::EVENT_APP_ENABLE_FOR_GROUPS, new ManagerEvent(
274
+            ManagerEvent::EVENT_APP_ENABLE_FOR_GROUPS, $appId, $groups
275
+        ));
276
+        $this->clearAppsCache();
277
+    }
278
+
279
+    /**
280
+     * Disable an app for every user
281
+     *
282
+     * @param string $appId
283
+     * @throws \Exception if app can't be disabled
284
+     */
285
+    public function disableApp($appId) {
286
+        if ($this->isAlwaysEnabled($appId)) {
287
+            throw new \Exception("$appId can't be disabled.");
288
+        }
289
+        unset($this->installedAppsCache[$appId]);
290
+        $this->appConfig->setValue($appId, 'enabled', 'no');
291
+        $this->dispatcher->dispatch(ManagerEvent::EVENT_APP_DISABLE, new ManagerEvent(
292
+            ManagerEvent::EVENT_APP_DISABLE, $appId
293
+        ));
294
+        $this->clearAppsCache();
295
+    }
296
+
297
+    /**
298
+     * Get the directory for the given app.
299
+     *
300
+     * @param string $appId
301
+     * @return string
302
+     * @throws AppPathNotFoundException if app folder can't be found
303
+     */
304
+    public function getAppPath($appId) {
305
+        $appPath = \OC_App::getAppPath($appId);
306
+        if($appPath === false) {
307
+            throw new AppPathNotFoundException('Could not find path for ' . $appId);
308
+        }
309
+        return $appPath;
310
+    }
311
+
312
+    /**
313
+     * Clear the cached list of apps when enabling/disabling an app
314
+     */
315
+    public function clearAppsCache() {
316
+        $settingsMemCache = $this->memCacheFactory->createDistributed('settings');
317
+        $settingsMemCache->clear('listApps');
318
+    }
319
+
320
+    /**
321
+     * Returns a list of apps that need upgrade
322
+     *
323
+     * @param string $version Nextcloud version as array of version components
324
+     * @return array list of app info from apps that need an upgrade
325
+     *
326
+     * @internal
327
+     */
328
+    public function getAppsNeedingUpgrade($version) {
329
+        $appsToUpgrade = [];
330
+        $apps = $this->getInstalledApps();
331
+        foreach ($apps as $appId) {
332
+            $appInfo = $this->getAppInfo($appId);
333
+            $appDbVersion = $this->appConfig->getValue($appId, 'installed_version');
334
+            if ($appDbVersion
335
+                && isset($appInfo['version'])
336
+                && version_compare($appInfo['version'], $appDbVersion, '>')
337
+                && \OC_App::isAppCompatible($version, $appInfo)
338
+            ) {
339
+                $appsToUpgrade[] = $appInfo;
340
+            }
341
+        }
342
+
343
+        return $appsToUpgrade;
344
+    }
345
+
346
+    /**
347
+     * Returns the app information from "appinfo/info.xml".
348
+     *
349
+     * @param string $appId app id
350
+     *
351
+     * @param bool $path
352
+     * @param null $lang
353
+     * @return array app info
354
+     */
355
+    public function getAppInfo(string $appId, bool $path = false, $lang = null) {
356
+        if ($path) {
357
+            $file = $appId;
358
+        } else {
359
+            if ($lang === null && isset($this->appInfos[$appId])) {
360
+                return $this->appInfos[$appId];
361
+            }
362
+            try {
363
+                $appPath = $this->getAppPath($appId);
364
+            } catch (AppPathNotFoundException $e) {
365
+                return null;
366
+            }
367
+            $file = $appPath . '/appinfo/info.xml';
368
+        }
369
+
370
+        $parser = new InfoParser($this->memCacheFactory->createLocal('core.appinfo'));
371
+        $data = $parser->parse($file);
372
+
373
+        if (is_array($data)) {
374
+            $data = \OC_App::parseAppInfo($data, $lang);
375
+        }
376
+
377
+        if ($lang === null) {
378
+            $this->appInfos[$appId] = $data;
379
+        }
380
+
381
+        return $data;
382
+    }
383
+
384
+    public function getAppVersion(string $appId, bool $useCache = true) {
385
+        if(!$useCache || !isset($this->appVersions[$appId])) {
386
+            $appInfo = \OC::$server->getAppManager()->getAppInfo($appId);
387
+            $this->appVersions[$appId] = ($appInfo !== null) ? $appInfo['version'] : '0';
388
+        }
389
+        return $this->appVersions[$appId];
390
+    }
391
+
392
+    /**
393
+     * Returns a list of apps incompatible with the given version
394
+     *
395
+     * @param string $version Nextcloud version as array of version components
396
+     *
397
+     * @return array list of app info from incompatible apps
398
+     *
399
+     * @internal
400
+     */
401
+    public function getIncompatibleApps($version) {
402
+        $apps = $this->getInstalledApps();
403
+        $incompatibleApps = array();
404
+        foreach ($apps as $appId) {
405
+            $info = $this->getAppInfo($appId);
406
+            if (!\OC_App::isAppCompatible($version, $info)) {
407
+                $incompatibleApps[] = $info;
408
+            }
409
+        }
410
+        return $incompatibleApps;
411
+    }
412
+
413
+    /**
414
+     * @inheritdoc
415
+     */
416
+    public function isShipped($appId) {
417
+        $this->loadShippedJson();
418
+        return in_array($appId, $this->shippedApps, true);
419
+    }
420
+
421
+    private function isAlwaysEnabled($appId) {
422
+        $alwaysEnabled = $this->getAlwaysEnabledApps();
423
+        return in_array($appId, $alwaysEnabled, true);
424
+    }
425
+
426
+    private function loadShippedJson() {
427
+        if ($this->shippedApps === null) {
428
+            $shippedJson = \OC::$SERVERROOT . '/core/shipped.json';
429
+            if (!file_exists($shippedJson)) {
430
+                throw new \Exception("File not found: $shippedJson");
431
+            }
432
+            $content = json_decode(file_get_contents($shippedJson), true);
433
+            $this->shippedApps = $content['shippedApps'];
434
+            $this->alwaysEnabled = $content['alwaysEnabled'];
435
+        }
436
+    }
437
+
438
+    /**
439
+     * @inheritdoc
440
+     */
441
+    public function getAlwaysEnabledApps() {
442
+        $this->loadShippedJson();
443
+        return $this->alwaysEnabled;
444
+    }
445 445
 }
Please login to merge, or discard this patch.
Spacing   +11 added lines, -11 removed lines patch added patch discarded remove patch
@@ -114,11 +114,11 @@  discard block
 block discarded – undo
114 114
 			$values = $this->appConfig->getValues(false, 'enabled');
115 115
 
116 116
 			$alwaysEnabledApps = $this->getAlwaysEnabledApps();
117
-			foreach($alwaysEnabledApps as $appId) {
117
+			foreach ($alwaysEnabledApps as $appId) {
118 118
 				$values[$appId] = 'yes';
119 119
 			}
120 120
 
121
-			$this->installedAppsCache = array_filter($values, function ($value) {
121
+			$this->installedAppsCache = array_filter($values, function($value) {
122 122
 				return $value !== 'no';
123 123
 			});
124 124
 			ksort($this->installedAppsCache);
@@ -143,7 +143,7 @@  discard block
 block discarded – undo
143 143
 	 */
144 144
 	public function getEnabledAppsForUser(IUser $user) {
145 145
 		$apps = $this->getInstalledAppsValues();
146
-		$appsForUser = array_filter($apps, function ($enabled) use ($user) {
146
+		$appsForUser = array_filter($apps, function($enabled) use ($user) {
147 147
 			return $this->checkAppForUser($enabled, $user);
148 148
 		});
149 149
 		return array_keys($appsForUser);
@@ -182,7 +182,7 @@  discard block
 block discarded – undo
182 182
 		} elseif ($user === null) {
183 183
 			return false;
184 184
 		} else {
185
-			if(empty($enabled)){
185
+			if (empty($enabled)) {
186 186
 				return false;
187 187
 			}
188 188
 
@@ -190,7 +190,7 @@  discard block
 block discarded – undo
190 190
 
191 191
 			if (!is_array($groupIds)) {
192 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']);
193
+				\OC::$server->getLogger()->warning('AppManger::checkAppForUser - can\'t decode group IDs: '.print_r($enabled, true).' - json error code: '.$jsonError, ['app' => 'lib']);
194 194
 				return false;
195 195
 			}
196 196
 
@@ -264,7 +264,7 @@  discard block
 block discarded – undo
264 264
 			}
265 265
 		}
266 266
 
267
-		$groupIds = array_map(function ($group) {
267
+		$groupIds = array_map(function($group) {
268 268
 			/** @var \OCP\IGroup $group */
269 269
 			return $group->getGID();
270 270
 		}, $groups);
@@ -303,8 +303,8 @@  discard block
 block discarded – undo
303 303
 	 */
304 304
 	public function getAppPath($appId) {
305 305
 		$appPath = \OC_App::getAppPath($appId);
306
-		if($appPath === false) {
307
-			throw new AppPathNotFoundException('Could not find path for ' . $appId);
306
+		if ($appPath === false) {
307
+			throw new AppPathNotFoundException('Could not find path for '.$appId);
308 308
 		}
309 309
 		return $appPath;
310 310
 	}
@@ -364,7 +364,7 @@  discard block
 block discarded – undo
364 364
 			} catch (AppPathNotFoundException $e) {
365 365
 				return null;
366 366
 			}
367
-			$file = $appPath . '/appinfo/info.xml';
367
+			$file = $appPath.'/appinfo/info.xml';
368 368
 		}
369 369
 
370 370
 		$parser = new InfoParser($this->memCacheFactory->createLocal('core.appinfo'));
@@ -382,7 +382,7 @@  discard block
 block discarded – undo
382 382
 	}
383 383
 
384 384
 	public function getAppVersion(string $appId, bool $useCache = true) {
385
-		if(!$useCache || !isset($this->appVersions[$appId])) {
385
+		if (!$useCache || !isset($this->appVersions[$appId])) {
386 386
 			$appInfo = \OC::$server->getAppManager()->getAppInfo($appId);
387 387
 			$this->appVersions[$appId] = ($appInfo !== null) ? $appInfo['version'] : '0';
388 388
 		}
@@ -425,7 +425,7 @@  discard block
 block discarded – undo
425 425
 
426 426
 	private function loadShippedJson() {
427 427
 		if ($this->shippedApps === null) {
428
-			$shippedJson = \OC::$SERVERROOT . '/core/shipped.json';
428
+			$shippedJson = \OC::$SERVERROOT.'/core/shipped.json';
429 429
 			if (!file_exists($shippedJson)) {
430 430
 				throw new \Exception("File not found: $shippedJson");
431 431
 			}
Please login to merge, or discard this patch.
lib/private/Server.php 2 patches
Indentation   +1825 added lines, -1825 removed lines patch added patch discarded remove patch
@@ -146,1834 +146,1834 @@
 block discarded – undo
146 146
  * TODO: hookup all manager classes
147 147
  */
148 148
 class Server extends ServerContainer implements IServerContainer {
149
-	/** @var string */
150
-	private $webRoot;
151
-
152
-	/**
153
-	 * @param string $webRoot
154
-	 * @param \OC\Config $config
155
-	 */
156
-	public function __construct($webRoot, \OC\Config $config) {
157
-		parent::__construct();
158
-		$this->webRoot = $webRoot;
159
-
160
-		$this->registerService(\OCP\IServerContainer::class, function (IServerContainer $c) {
161
-			return $c;
162
-		});
163
-
164
-		$this->registerAlias(\OCP\Calendar\IManager::class, \OC\Calendar\Manager::class);
165
-		$this->registerAlias('CalendarManager', \OC\Calendar\Manager::class);
166
-
167
-		$this->registerAlias(\OCP\Contacts\IManager::class, \OC\ContactsManager::class);
168
-		$this->registerAlias('ContactsManager', \OCP\Contacts\IManager::class);
169
-
170
-		$this->registerAlias(IActionFactory::class, ActionFactory::class);
171
-
172
-
173
-		$this->registerService(\OCP\IPreview::class, function (Server $c) {
174
-			return new PreviewManager(
175
-				$c->getConfig(),
176
-				$c->getRootFolder(),
177
-				$c->getAppDataDir('preview'),
178
-				$c->getEventDispatcher(),
179
-				$c->getSession()->get('user_id')
180
-			);
181
-		});
182
-		$this->registerAlias('PreviewManager', \OCP\IPreview::class);
183
-
184
-		$this->registerService(\OC\Preview\Watcher::class, function (Server $c) {
185
-			return new \OC\Preview\Watcher(
186
-				$c->getAppDataDir('preview')
187
-			);
188
-		});
189
-
190
-		$this->registerService('EncryptionManager', function (Server $c) {
191
-			$view = new View();
192
-			$util = new Encryption\Util(
193
-				$view,
194
-				$c->getUserManager(),
195
-				$c->getGroupManager(),
196
-				$c->getConfig()
197
-			);
198
-			return new Encryption\Manager(
199
-				$c->getConfig(),
200
-				$c->getLogger(),
201
-				$c->getL10N('core'),
202
-				new View(),
203
-				$util,
204
-				new ArrayCache()
205
-			);
206
-		});
207
-
208
-		$this->registerService('EncryptionFileHelper', function (Server $c) {
209
-			$util = new Encryption\Util(
210
-				new View(),
211
-				$c->getUserManager(),
212
-				$c->getGroupManager(),
213
-				$c->getConfig()
214
-			);
215
-			return new Encryption\File(
216
-				$util,
217
-				$c->getRootFolder(),
218
-				$c->getShareManager()
219
-			);
220
-		});
221
-
222
-		$this->registerService('EncryptionKeyStorage', function (Server $c) {
223
-			$view = new View();
224
-			$util = new Encryption\Util(
225
-				$view,
226
-				$c->getUserManager(),
227
-				$c->getGroupManager(),
228
-				$c->getConfig()
229
-			);
230
-
231
-			return new Encryption\Keys\Storage($view, $util);
232
-		});
233
-		$this->registerService('TagMapper', function (Server $c) {
234
-			return new TagMapper($c->getDatabaseConnection());
235
-		});
236
-
237
-		$this->registerService(\OCP\ITagManager::class, function (Server $c) {
238
-			$tagMapper = $c->query('TagMapper');
239
-			return new TagManager($tagMapper, $c->getUserSession());
240
-		});
241
-		$this->registerAlias('TagManager', \OCP\ITagManager::class);
242
-
243
-		$this->registerService('SystemTagManagerFactory', function (Server $c) {
244
-			$config = $c->getConfig();
245
-			$factoryClass = $config->getSystemValue('systemtags.managerFactory', '\OC\SystemTag\ManagerFactory');
246
-			return new $factoryClass($this);
247
-		});
248
-		$this->registerService(\OCP\SystemTag\ISystemTagManager::class, function (Server $c) {
249
-			return $c->query('SystemTagManagerFactory')->getManager();
250
-		});
251
-		$this->registerAlias('SystemTagManager', \OCP\SystemTag\ISystemTagManager::class);
252
-
253
-		$this->registerService(\OCP\SystemTag\ISystemTagObjectMapper::class, function (Server $c) {
254
-			return $c->query('SystemTagManagerFactory')->getObjectMapper();
255
-		});
256
-		$this->registerService('RootFolder', function (Server $c) {
257
-			$manager = \OC\Files\Filesystem::getMountManager(null);
258
-			$view = new View();
259
-			$root = new Root(
260
-				$manager,
261
-				$view,
262
-				null,
263
-				$c->getUserMountCache(),
264
-				$this->getLogger(),
265
-				$this->getUserManager()
266
-			);
267
-			$connector = new HookConnector($root, $view);
268
-			$connector->viewToNode();
269
-
270
-			$previewConnector = new \OC\Preview\WatcherConnector($root, $c->getSystemConfig());
271
-			$previewConnector->connectWatcher();
272
-
273
-			return $root;
274
-		});
275
-		$this->registerAlias('SystemTagObjectMapper', \OCP\SystemTag\ISystemTagObjectMapper::class);
276
-
277
-		$this->registerService(\OCP\Files\IRootFolder::class, function (Server $c) {
278
-			return new LazyRoot(function () use ($c) {
279
-				return $c->query('RootFolder');
280
-			});
281
-		});
282
-		$this->registerAlias('LazyRootFolder', \OCP\Files\IRootFolder::class);
283
-
284
-		$this->registerService(\OC\User\Manager::class, function (Server $c) {
285
-			$config = $c->getConfig();
286
-			return new \OC\User\Manager($config);
287
-		});
288
-		$this->registerAlias('UserManager', \OC\User\Manager::class);
289
-		$this->registerAlias(\OCP\IUserManager::class, \OC\User\Manager::class);
290
-
291
-		$this->registerService(\OCP\IGroupManager::class, function (Server $c) {
292
-			$groupManager = new \OC\Group\Manager($this->getUserManager(), $this->getLogger());
293
-			$groupManager->listen('\OC\Group', 'preCreate', function ($gid) {
294
-				\OC_Hook::emit('OC_Group', 'pre_createGroup', array('run' => true, 'gid' => $gid));
295
-			});
296
-			$groupManager->listen('\OC\Group', 'postCreate', function (\OC\Group\Group $gid) {
297
-				\OC_Hook::emit('OC_User', 'post_createGroup', array('gid' => $gid->getGID()));
298
-			});
299
-			$groupManager->listen('\OC\Group', 'preDelete', function (\OC\Group\Group $group) {
300
-				\OC_Hook::emit('OC_Group', 'pre_deleteGroup', array('run' => true, 'gid' => $group->getGID()));
301
-			});
302
-			$groupManager->listen('\OC\Group', 'postDelete', function (\OC\Group\Group $group) {
303
-				\OC_Hook::emit('OC_User', 'post_deleteGroup', array('gid' => $group->getGID()));
304
-			});
305
-			$groupManager->listen('\OC\Group', 'preAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
306
-				\OC_Hook::emit('OC_Group', 'pre_addToGroup', array('run' => true, 'uid' => $user->getUID(), 'gid' => $group->getGID()));
307
-			});
308
-			$groupManager->listen('\OC\Group', 'postAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
309
-				\OC_Hook::emit('OC_Group', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
310
-				//Minimal fix to keep it backward compatible TODO: clean up all the GroupManager hooks
311
-				\OC_Hook::emit('OC_User', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
312
-			});
313
-			return $groupManager;
314
-		});
315
-		$this->registerAlias('GroupManager', \OCP\IGroupManager::class);
316
-
317
-		$this->registerService(Store::class, function (Server $c) {
318
-			$session = $c->getSession();
319
-			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
320
-				$tokenProvider = $c->query('OC\Authentication\Token\IProvider');
321
-			} else {
322
-				$tokenProvider = null;
323
-			}
324
-			$logger = $c->getLogger();
325
-			return new Store($session, $logger, $tokenProvider);
326
-		});
327
-		$this->registerAlias(IStore::class, Store::class);
328
-		$this->registerService('OC\Authentication\Token\DefaultTokenMapper', function (Server $c) {
329
-			$dbConnection = $c->getDatabaseConnection();
330
-			return new Authentication\Token\DefaultTokenMapper($dbConnection);
331
-		});
332
-		$this->registerService('OC\Authentication\Token\DefaultTokenProvider', function (Server $c) {
333
-			$mapper = $c->query('OC\Authentication\Token\DefaultTokenMapper');
334
-			$crypto = $c->getCrypto();
335
-			$config = $c->getConfig();
336
-			$logger = $c->getLogger();
337
-			$timeFactory = new TimeFactory();
338
-			return new \OC\Authentication\Token\DefaultTokenProvider($mapper, $crypto, $config, $logger, $timeFactory);
339
-		});
340
-		$this->registerAlias('OC\Authentication\Token\IProvider', 'OC\Authentication\Token\DefaultTokenProvider');
341
-
342
-		$this->registerService(\OCP\IUserSession::class, function (Server $c) {
343
-			$manager = $c->getUserManager();
344
-			$session = new \OC\Session\Memory('');
345
-			$timeFactory = new TimeFactory();
346
-			// Token providers might require a working database. This code
347
-			// might however be called when ownCloud is not yet setup.
348
-			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
349
-				$defaultTokenProvider = $c->query('OC\Authentication\Token\IProvider');
350
-			} else {
351
-				$defaultTokenProvider = null;
352
-			}
353
-
354
-			$dispatcher = $c->getEventDispatcher();
355
-
356
-			$userSession = new \OC\User\Session(
357
-				$manager,
358
-				$session,
359
-				$timeFactory,
360
-				$defaultTokenProvider,
361
-				$c->getConfig(),
362
-				$c->getSecureRandom(),
363
-				$c->getLockdownManager(),
364
-				$c->getLogger()
365
-			);
366
-			$userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
367
-				\OC_Hook::emit('OC_User', 'pre_createUser', array('run' => true, 'uid' => $uid, 'password' => $password));
368
-			});
369
-			$userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
370
-				/** @var $user \OC\User\User */
371
-				\OC_Hook::emit('OC_User', 'post_createUser', array('uid' => $user->getUID(), 'password' => $password));
372
-			});
373
-			$userSession->listen('\OC\User', 'preDelete', function ($user) use ($dispatcher) {
374
-				/** @var $user \OC\User\User */
375
-				\OC_Hook::emit('OC_User', 'pre_deleteUser', array('run' => true, 'uid' => $user->getUID()));
376
-				$dispatcher->dispatch('OCP\IUser::preDelete', new GenericEvent($user));
377
-			});
378
-			$userSession->listen('\OC\User', 'postDelete', function ($user) {
379
-				/** @var $user \OC\User\User */
380
-				\OC_Hook::emit('OC_User', 'post_deleteUser', array('uid' => $user->getUID()));
381
-			});
382
-			$userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
383
-				/** @var $user \OC\User\User */
384
-				\OC_Hook::emit('OC_User', 'pre_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
385
-			});
386
-			$userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
387
-				/** @var $user \OC\User\User */
388
-				\OC_Hook::emit('OC_User', 'post_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
389
-			});
390
-			$userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
391
-				\OC_Hook::emit('OC_User', 'pre_login', array('run' => true, 'uid' => $uid, 'password' => $password));
392
-			});
393
-			$userSession->listen('\OC\User', 'postLogin', function ($user, $password) {
394
-				/** @var $user \OC\User\User */
395
-				\OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
396
-			});
397
-			$userSession->listen('\OC\User', 'postRememberedLogin', function ($user, $password) {
398
-				/** @var $user \OC\User\User */
399
-				\OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
400
-			});
401
-			$userSession->listen('\OC\User', 'logout', function () {
402
-				\OC_Hook::emit('OC_User', 'logout', array());
403
-			});
404
-			$userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value, $oldValue) use ($dispatcher) {
405
-				/** @var $user \OC\User\User */
406
-				\OC_Hook::emit('OC_User', 'changeUser', array('run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value, 'old_value' => $oldValue));
407
-				$dispatcher->dispatch('OCP\IUser::changeUser', new GenericEvent($user, ['feature' => $feature, 'oldValue' => $oldValue, 'value' => $value]));
408
-			});
409
-			return $userSession;
410
-		});
411
-		$this->registerAlias('UserSession', \OCP\IUserSession::class);
412
-
413
-		$this->registerService(\OC\Authentication\TwoFactorAuth\Manager::class, function (Server $c) {
414
-			return new \OC\Authentication\TwoFactorAuth\Manager(
415
-				$c->getAppManager(),
416
-				$c->getSession(),
417
-				$c->getConfig(),
418
-				$c->getActivityManager(),
419
-				$c->getLogger(),
420
-				$c->query(\OC\Authentication\Token\IProvider::class),
421
-				$c->query(ITimeFactory::class),
422
-				$c->query(EventDispatcherInterface::class)
423
-			);
424
-		});
425
-
426
-		$this->registerAlias(\OCP\INavigationManager::class, \OC\NavigationManager::class);
427
-		$this->registerAlias('NavigationManager', \OCP\INavigationManager::class);
428
-
429
-		$this->registerService(\OC\AllConfig::class, function (Server $c) {
430
-			return new \OC\AllConfig(
431
-				$c->getSystemConfig()
432
-			);
433
-		});
434
-		$this->registerAlias('AllConfig', \OC\AllConfig::class);
435
-		$this->registerAlias(\OCP\IConfig::class, \OC\AllConfig::class);
436
-
437
-		$this->registerService('SystemConfig', function ($c) use ($config) {
438
-			return new \OC\SystemConfig($config);
439
-		});
440
-
441
-		$this->registerService(\OC\AppConfig::class, function (Server $c) {
442
-			return new \OC\AppConfig($c->getDatabaseConnection());
443
-		});
444
-		$this->registerAlias('AppConfig', \OC\AppConfig::class);
445
-		$this->registerAlias(\OCP\IAppConfig::class, \OC\AppConfig::class);
446
-
447
-		$this->registerService(\OCP\L10N\IFactory::class, function (Server $c) {
448
-			return new \OC\L10N\Factory(
449
-				$c->getConfig(),
450
-				$c->getRequest(),
451
-				$c->getUserSession(),
452
-				\OC::$SERVERROOT
453
-			);
454
-		});
455
-		$this->registerAlias('L10NFactory', \OCP\L10N\IFactory::class);
456
-
457
-		$this->registerService(\OCP\IURLGenerator::class, function (Server $c) {
458
-			$config = $c->getConfig();
459
-			$cacheFactory = $c->getMemCacheFactory();
460
-			$request = $c->getRequest();
461
-			return new \OC\URLGenerator(
462
-				$config,
463
-				$cacheFactory,
464
-				$request
465
-			);
466
-		});
467
-		$this->registerAlias('URLGenerator', \OCP\IURLGenerator::class);
468
-
469
-		$this->registerService('AppHelper', function ($c) {
470
-			return new \OC\AppHelper();
471
-		});
472
-		$this->registerAlias('AppFetcher', AppFetcher::class);
473
-		$this->registerAlias('CategoryFetcher', CategoryFetcher::class);
474
-
475
-		$this->registerService(\OCP\ICache::class, function ($c) {
476
-			return new Cache\File();
477
-		});
478
-		$this->registerAlias('UserCache', \OCP\ICache::class);
479
-
480
-		$this->registerService(Factory::class, function (Server $c) {
481
-
482
-			$arrayCacheFactory = new \OC\Memcache\Factory('', $c->getLogger(),
483
-				'\\OC\\Memcache\\ArrayCache',
484
-				'\\OC\\Memcache\\ArrayCache',
485
-				'\\OC\\Memcache\\ArrayCache'
486
-			);
487
-			$config = $c->getConfig();
488
-			$request = $c->getRequest();
489
-			$urlGenerator = new URLGenerator($config, $arrayCacheFactory, $request);
490
-
491
-			if ($config->getSystemValue('installed', false) && !(defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
492
-				$v = \OC_App::getAppVersions();
493
-				$v['core'] = implode(',', \OC_Util::getVersion());
494
-				$version = implode(',', $v);
495
-				$instanceId = \OC_Util::getInstanceId();
496
-				$path = \OC::$SERVERROOT;
497
-				$prefix = md5($instanceId . '-' . $version . '-' . $path . '-' . $urlGenerator->getBaseUrl());
498
-				return new \OC\Memcache\Factory($prefix, $c->getLogger(),
499
-					$config->getSystemValue('memcache.local', null),
500
-					$config->getSystemValue('memcache.distributed', null),
501
-					$config->getSystemValue('memcache.locking', null)
502
-				);
503
-			}
504
-			return $arrayCacheFactory;
505
-
506
-		});
507
-		$this->registerAlias('MemCacheFactory', Factory::class);
508
-		$this->registerAlias(ICacheFactory::class, Factory::class);
509
-
510
-		$this->registerService('RedisFactory', function (Server $c) {
511
-			$systemConfig = $c->getSystemConfig();
512
-			return new RedisFactory($systemConfig);
513
-		});
514
-
515
-		$this->registerService(\OCP\Activity\IManager::class, function (Server $c) {
516
-			return new \OC\Activity\Manager(
517
-				$c->getRequest(),
518
-				$c->getUserSession(),
519
-				$c->getConfig(),
520
-				$c->query(IValidator::class)
521
-			);
522
-		});
523
-		$this->registerAlias('ActivityManager', \OCP\Activity\IManager::class);
524
-
525
-		$this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
526
-			return new \OC\Activity\EventMerger(
527
-				$c->getL10N('lib')
528
-			);
529
-		});
530
-		$this->registerAlias(IValidator::class, Validator::class);
531
-
532
-		$this->registerService(\OCP\IAvatarManager::class, function (Server $c) {
533
-			return new AvatarManager(
534
-				$c->query(\OC\User\Manager::class),
535
-				$c->getAppDataDir('avatar'),
536
-				$c->getL10N('lib'),
537
-				$c->getLogger(),
538
-				$c->getConfig()
539
-			);
540
-		});
541
-		$this->registerAlias('AvatarManager', \OCP\IAvatarManager::class);
542
-
543
-		$this->registerAlias(\OCP\Support\CrashReport\IRegistry::class, \OC\Support\CrashReport\Registry::class);
544
-
545
-		$this->registerService(\OCP\ILogger::class, function (Server $c) {
546
-			$logType = $c->query('AllConfig')->getSystemValue('log_type', 'file');
547
-			$logger = Log::getLogClass($logType);
548
-			call_user_func(array($logger, 'init'));
549
-			$config = $this->getSystemConfig();
550
-			$registry = $c->query(\OCP\Support\CrashReport\IRegistry::class);
551
-
552
-			return new Log($logger, $config, null, $registry);
553
-		});
554
-		$this->registerAlias('Logger', \OCP\ILogger::class);
555
-
556
-		$this->registerService(\OCP\BackgroundJob\IJobList::class, function (Server $c) {
557
-			$config = $c->getConfig();
558
-			return new \OC\BackgroundJob\JobList(
559
-				$c->getDatabaseConnection(),
560
-				$config,
561
-				new TimeFactory()
562
-			);
563
-		});
564
-		$this->registerAlias('JobList', \OCP\BackgroundJob\IJobList::class);
565
-
566
-		$this->registerService(\OCP\Route\IRouter::class, function (Server $c) {
567
-			$cacheFactory = $c->getMemCacheFactory();
568
-			$logger = $c->getLogger();
569
-			if ($cacheFactory->isAvailableLowLatency()) {
570
-				$router = new \OC\Route\CachingRouter($cacheFactory->createLocal('route'), $logger);
571
-			} else {
572
-				$router = new \OC\Route\Router($logger);
573
-			}
574
-			return $router;
575
-		});
576
-		$this->registerAlias('Router', \OCP\Route\IRouter::class);
577
-
578
-		$this->registerService(\OCP\ISearch::class, function ($c) {
579
-			return new Search();
580
-		});
581
-		$this->registerAlias('Search', \OCP\ISearch::class);
582
-
583
-		$this->registerService(\OC\Security\RateLimiting\Limiter::class, function ($c) {
584
-			return new \OC\Security\RateLimiting\Limiter(
585
-				$this->getUserSession(),
586
-				$this->getRequest(),
587
-				new \OC\AppFramework\Utility\TimeFactory(),
588
-				$c->query(\OC\Security\RateLimiting\Backend\IBackend::class)
589
-			);
590
-		});
591
-		$this->registerService(\OC\Security\RateLimiting\Backend\IBackend::class, function ($c) {
592
-			return new \OC\Security\RateLimiting\Backend\MemoryCache(
593
-				$this->getMemCacheFactory(),
594
-				new \OC\AppFramework\Utility\TimeFactory()
595
-			);
596
-		});
597
-
598
-		$this->registerService(\OCP\Security\ISecureRandom::class, function ($c) {
599
-			return new SecureRandom();
600
-		});
601
-		$this->registerAlias('SecureRandom', \OCP\Security\ISecureRandom::class);
602
-
603
-		$this->registerService(\OCP\Security\ICrypto::class, function (Server $c) {
604
-			return new Crypto($c->getConfig(), $c->getSecureRandom());
605
-		});
606
-		$this->registerAlias('Crypto', \OCP\Security\ICrypto::class);
607
-
608
-		$this->registerService(\OCP\Security\IHasher::class, function (Server $c) {
609
-			return new Hasher($c->getConfig());
610
-		});
611
-		$this->registerAlias('Hasher', \OCP\Security\IHasher::class);
612
-
613
-		$this->registerService(\OCP\Security\ICredentialsManager::class, function (Server $c) {
614
-			return new CredentialsManager($c->getCrypto(), $c->getDatabaseConnection());
615
-		});
616
-		$this->registerAlias('CredentialsManager', \OCP\Security\ICredentialsManager::class);
617
-
618
-		$this->registerService(IDBConnection::class, function (Server $c) {
619
-			$systemConfig = $c->getSystemConfig();
620
-			$factory = new \OC\DB\ConnectionFactory($systemConfig);
621
-			$type = $systemConfig->getValue('dbtype', 'sqlite');
622
-			if (!$factory->isValidType($type)) {
623
-				throw new \OC\DatabaseException('Invalid database type');
624
-			}
625
-			$connectionParams = $factory->createConnectionParams();
626
-			$connection = $factory->getConnection($type, $connectionParams);
627
-			$connection->getConfiguration()->setSQLLogger($c->getQueryLogger());
628
-			return $connection;
629
-		});
630
-		$this->registerAlias('DatabaseConnection', IDBConnection::class);
631
-
632
-		$this->registerService('HTTPHelper', function (Server $c) {
633
-			$config = $c->getConfig();
634
-			return new HTTPHelper(
635
-				$config,
636
-				$c->getHTTPClientService()
637
-			);
638
-		});
639
-
640
-		$this->registerService(\OCP\Http\Client\IClientService::class, function (Server $c) {
641
-			$user = \OC_User::getUser();
642
-			$uid = $user ? $user : null;
643
-			return new ClientService(
644
-				$c->getConfig(),
645
-				new \OC\Security\CertificateManager(
646
-					$uid,
647
-					new View(),
648
-					$c->getConfig(),
649
-					$c->getLogger(),
650
-					$c->getSecureRandom()
651
-				)
652
-			);
653
-		});
654
-		$this->registerAlias('HttpClientService', \OCP\Http\Client\IClientService::class);
655
-		$this->registerService(\OCP\Diagnostics\IEventLogger::class, function (Server $c) {
656
-			$eventLogger = new EventLogger();
657
-			if ($c->getSystemConfig()->getValue('debug', false)) {
658
-				// In debug mode, module is being activated by default
659
-				$eventLogger->activate();
660
-			}
661
-			return $eventLogger;
662
-		});
663
-		$this->registerAlias('EventLogger', \OCP\Diagnostics\IEventLogger::class);
664
-
665
-		$this->registerService(\OCP\Diagnostics\IQueryLogger::class, function (Server $c) {
666
-			$queryLogger = new QueryLogger();
667
-			if ($c->getSystemConfig()->getValue('debug', false)) {
668
-				// In debug mode, module is being activated by default
669
-				$queryLogger->activate();
670
-			}
671
-			return $queryLogger;
672
-		});
673
-		$this->registerAlias('QueryLogger', \OCP\Diagnostics\IQueryLogger::class);
674
-
675
-		$this->registerService(TempManager::class, function (Server $c) {
676
-			return new TempManager(
677
-				$c->getLogger(),
678
-				$c->getConfig()
679
-			);
680
-		});
681
-		$this->registerAlias('TempManager', TempManager::class);
682
-		$this->registerAlias(ITempManager::class, TempManager::class);
683
-
684
-		$this->registerService(AppManager::class, function (Server $c) {
685
-			return new \OC\App\AppManager(
686
-				$c->getUserSession(),
687
-				$this->getAppConfig(),
688
-				$c->getGroupManager(),
689
-				$c->getMemCacheFactory(),
690
-				$c->getEventDispatcher()
691
-			);
692
-		});
693
-		$this->registerAlias('AppManager', AppManager::class);
694
-		$this->registerAlias(IAppManager::class, AppManager::class);
695
-
696
-		$this->registerService(\OCP\IDateTimeZone::class, function (Server $c) {
697
-			return new DateTimeZone(
698
-				$c->getConfig(),
699
-				$c->getSession()
700
-			);
701
-		});
702
-		$this->registerAlias('DateTimeZone', \OCP\IDateTimeZone::class);
703
-
704
-		$this->registerService(\OCP\IDateTimeFormatter::class, function (Server $c) {
705
-			$language = $c->getConfig()->getUserValue($c->getSession()->get('user_id'), 'core', 'lang', null);
706
-
707
-			return new DateTimeFormatter(
708
-				$c->getDateTimeZone()->getTimeZone(),
709
-				$c->getL10N('lib', $language)
710
-			);
711
-		});
712
-		$this->registerAlias('DateTimeFormatter', \OCP\IDateTimeFormatter::class);
713
-
714
-		$this->registerService(\OCP\Files\Config\IUserMountCache::class, function (Server $c) {
715
-			$mountCache = new UserMountCache($c->getDatabaseConnection(), $c->getUserManager(), $c->getLogger());
716
-			$listener = new UserMountCacheListener($mountCache);
717
-			$listener->listen($c->getUserManager());
718
-			return $mountCache;
719
-		});
720
-		$this->registerAlias('UserMountCache', \OCP\Files\Config\IUserMountCache::class);
721
-
722
-		$this->registerService(\OCP\Files\Config\IMountProviderCollection::class, function (Server $c) {
723
-			$loader = \OC\Files\Filesystem::getLoader();
724
-			$mountCache = $c->query('UserMountCache');
725
-			$manager = new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
726
-
727
-			// builtin providers
728
-
729
-			$config = $c->getConfig();
730
-			$manager->registerProvider(new CacheMountProvider($config));
731
-			$manager->registerHomeProvider(new LocalHomeMountProvider());
732
-			$manager->registerHomeProvider(new ObjectHomeMountProvider($config));
733
-
734
-			return $manager;
735
-		});
736
-		$this->registerAlias('MountConfigManager', \OCP\Files\Config\IMountProviderCollection::class);
737
-
738
-		$this->registerService('IniWrapper', function ($c) {
739
-			return new IniGetWrapper();
740
-		});
741
-		$this->registerService('AsyncCommandBus', function (Server $c) {
742
-			$busClass = $c->getConfig()->getSystemValue('commandbus');
743
-			if ($busClass) {
744
-				list($app, $class) = explode('::', $busClass, 2);
745
-				if ($c->getAppManager()->isInstalled($app)) {
746
-					\OC_App::loadApp($app);
747
-					return $c->query($class);
748
-				} else {
749
-					throw new ServiceUnavailableException("The app providing the command bus ($app) is not enabled");
750
-				}
751
-			} else {
752
-				$jobList = $c->getJobList();
753
-				return new CronBus($jobList);
754
-			}
755
-		});
756
-		$this->registerService('TrustedDomainHelper', function ($c) {
757
-			return new TrustedDomainHelper($this->getConfig());
758
-		});
759
-		$this->registerService('Throttler', function (Server $c) {
760
-			return new Throttler(
761
-				$c->getDatabaseConnection(),
762
-				new TimeFactory(),
763
-				$c->getLogger(),
764
-				$c->getConfig()
765
-			);
766
-		});
767
-		$this->registerService('IntegrityCodeChecker', function (Server $c) {
768
-			// IConfig and IAppManager requires a working database. This code
769
-			// might however be called when ownCloud is not yet setup.
770
-			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
771
-				$config = $c->getConfig();
772
-				$appManager = $c->getAppManager();
773
-			} else {
774
-				$config = null;
775
-				$appManager = null;
776
-			}
777
-
778
-			return new Checker(
779
-				new EnvironmentHelper(),
780
-				new FileAccessHelper(),
781
-				new AppLocator(),
782
-				$config,
783
-				$c->getMemCacheFactory(),
784
-				$appManager,
785
-				$c->getTempManager()
786
-			);
787
-		});
788
-		$this->registerService(\OCP\IRequest::class, function ($c) {
789
-			if (isset($this['urlParams'])) {
790
-				$urlParams = $this['urlParams'];
791
-			} else {
792
-				$urlParams = [];
793
-			}
794
-
795
-			if (defined('PHPUNIT_RUN') && PHPUNIT_RUN
796
-				&& in_array('fakeinput', stream_get_wrappers())
797
-			) {
798
-				$stream = 'fakeinput://data';
799
-			} else {
800
-				$stream = 'php://input';
801
-			}
802
-
803
-			return new Request(
804
-				[
805
-					'get' => $_GET,
806
-					'post' => $_POST,
807
-					'files' => $_FILES,
808
-					'server' => $_SERVER,
809
-					'env' => $_ENV,
810
-					'cookies' => $_COOKIE,
811
-					'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
812
-						? $_SERVER['REQUEST_METHOD']
813
-						: null,
814
-					'urlParams' => $urlParams,
815
-				],
816
-				$this->getSecureRandom(),
817
-				$this->getConfig(),
818
-				$this->getCsrfTokenManager(),
819
-				$stream
820
-			);
821
-		});
822
-		$this->registerAlias('Request', \OCP\IRequest::class);
823
-
824
-		$this->registerService(\OCP\Mail\IMailer::class, function (Server $c) {
825
-			return new Mailer(
826
-				$c->getConfig(),
827
-				$c->getLogger(),
828
-				$c->query(Defaults::class),
829
-				$c->getURLGenerator(),
830
-				$c->getL10N('lib')
831
-			);
832
-		});
833
-		$this->registerAlias('Mailer', \OCP\Mail\IMailer::class);
834
-
835
-		$this->registerService('LDAPProvider', function (Server $c) {
836
-			$config = $c->getConfig();
837
-			$factoryClass = $config->getSystemValue('ldapProviderFactory', null);
838
-			if (is_null($factoryClass)) {
839
-				throw new \Exception('ldapProviderFactory not set');
840
-			}
841
-			/** @var \OCP\LDAP\ILDAPProviderFactory $factory */
842
-			$factory = new $factoryClass($this);
843
-			return $factory->getLDAPProvider();
844
-		});
845
-		$this->registerService(ILockingProvider::class, function (Server $c) {
846
-			$ini = $c->getIniWrapper();
847
-			$config = $c->getConfig();
848
-			$ttl = $config->getSystemValue('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
849
-			if ($config->getSystemValue('filelocking.enabled', true) or (defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
850
-				/** @var \OC\Memcache\Factory $memcacheFactory */
851
-				$memcacheFactory = $c->getMemCacheFactory();
852
-				$memcache = $memcacheFactory->createLocking('lock');
853
-				if (!($memcache instanceof \OC\Memcache\NullCache)) {
854
-					return new MemcacheLockingProvider($memcache, $ttl);
855
-				}
856
-				return new DBLockingProvider($c->getDatabaseConnection(), $c->getLogger(), new TimeFactory(), $ttl);
857
-			}
858
-			return new NoopLockingProvider();
859
-		});
860
-		$this->registerAlias('LockingProvider', ILockingProvider::class);
861
-
862
-		$this->registerService(\OCP\Files\Mount\IMountManager::class, function () {
863
-			return new \OC\Files\Mount\Manager();
864
-		});
865
-		$this->registerAlias('MountManager', \OCP\Files\Mount\IMountManager::class);
866
-
867
-		$this->registerService(\OCP\Files\IMimeTypeDetector::class, function (Server $c) {
868
-			return new \OC\Files\Type\Detection(
869
-				$c->getURLGenerator(),
870
-				\OC::$configDir,
871
-				\OC::$SERVERROOT . '/resources/config/'
872
-			);
873
-		});
874
-		$this->registerAlias('MimeTypeDetector', \OCP\Files\IMimeTypeDetector::class);
875
-
876
-		$this->registerService(\OCP\Files\IMimeTypeLoader::class, function (Server $c) {
877
-			return new \OC\Files\Type\Loader(
878
-				$c->getDatabaseConnection()
879
-			);
880
-		});
881
-		$this->registerAlias('MimeTypeLoader', \OCP\Files\IMimeTypeLoader::class);
882
-		$this->registerService(BundleFetcher::class, function () {
883
-			return new BundleFetcher($this->getL10N('lib'));
884
-		});
885
-		$this->registerService(\OCP\Notification\IManager::class, function (Server $c) {
886
-			return new Manager(
887
-				$c->query(IValidator::class)
888
-			);
889
-		});
890
-		$this->registerAlias('NotificationManager', \OCP\Notification\IManager::class);
891
-
892
-		$this->registerService(\OC\CapabilitiesManager::class, function (Server $c) {
893
-			$manager = new \OC\CapabilitiesManager($c->getLogger());
894
-			$manager->registerCapability(function () use ($c) {
895
-				return new \OC\OCS\CoreCapabilities($c->getConfig());
896
-			});
897
-			$manager->registerCapability(function () use ($c) {
898
-				return $c->query(\OC\Security\Bruteforce\Capabilities::class);
899
-			});
900
-			return $manager;
901
-		});
902
-		$this->registerAlias('CapabilitiesManager', \OC\CapabilitiesManager::class);
903
-
904
-		$this->registerService(\OCP\Comments\ICommentsManager::class, function (Server $c) {
905
-			$config = $c->getConfig();
906
-			$factoryClass = $config->getSystemValue('comments.managerFactory', '\OC\Comments\ManagerFactory');
907
-			/** @var \OCP\Comments\ICommentsManagerFactory $factory */
908
-			$factory = new $factoryClass($this);
909
-			$manager = $factory->getManager();
910
-
911
-			$manager->registerDisplayNameResolver('user', function($id) use ($c) {
912
-				$manager = $c->getUserManager();
913
-				$user = $manager->get($id);
914
-				if(is_null($user)) {
915
-					$l = $c->getL10N('core');
916
-					$displayName = $l->t('Unknown user');
917
-				} else {
918
-					$displayName = $user->getDisplayName();
919
-				}
920
-				return $displayName;
921
-			});
922
-
923
-			return $manager;
924
-		});
925
-		$this->registerAlias('CommentsManager', \OCP\Comments\ICommentsManager::class);
926
-
927
-		$this->registerService('ThemingDefaults', function (Server $c) {
928
-			/*
149
+    /** @var string */
150
+    private $webRoot;
151
+
152
+    /**
153
+     * @param string $webRoot
154
+     * @param \OC\Config $config
155
+     */
156
+    public function __construct($webRoot, \OC\Config $config) {
157
+        parent::__construct();
158
+        $this->webRoot = $webRoot;
159
+
160
+        $this->registerService(\OCP\IServerContainer::class, function (IServerContainer $c) {
161
+            return $c;
162
+        });
163
+
164
+        $this->registerAlias(\OCP\Calendar\IManager::class, \OC\Calendar\Manager::class);
165
+        $this->registerAlias('CalendarManager', \OC\Calendar\Manager::class);
166
+
167
+        $this->registerAlias(\OCP\Contacts\IManager::class, \OC\ContactsManager::class);
168
+        $this->registerAlias('ContactsManager', \OCP\Contacts\IManager::class);
169
+
170
+        $this->registerAlias(IActionFactory::class, ActionFactory::class);
171
+
172
+
173
+        $this->registerService(\OCP\IPreview::class, function (Server $c) {
174
+            return new PreviewManager(
175
+                $c->getConfig(),
176
+                $c->getRootFolder(),
177
+                $c->getAppDataDir('preview'),
178
+                $c->getEventDispatcher(),
179
+                $c->getSession()->get('user_id')
180
+            );
181
+        });
182
+        $this->registerAlias('PreviewManager', \OCP\IPreview::class);
183
+
184
+        $this->registerService(\OC\Preview\Watcher::class, function (Server $c) {
185
+            return new \OC\Preview\Watcher(
186
+                $c->getAppDataDir('preview')
187
+            );
188
+        });
189
+
190
+        $this->registerService('EncryptionManager', function (Server $c) {
191
+            $view = new View();
192
+            $util = new Encryption\Util(
193
+                $view,
194
+                $c->getUserManager(),
195
+                $c->getGroupManager(),
196
+                $c->getConfig()
197
+            );
198
+            return new Encryption\Manager(
199
+                $c->getConfig(),
200
+                $c->getLogger(),
201
+                $c->getL10N('core'),
202
+                new View(),
203
+                $util,
204
+                new ArrayCache()
205
+            );
206
+        });
207
+
208
+        $this->registerService('EncryptionFileHelper', function (Server $c) {
209
+            $util = new Encryption\Util(
210
+                new View(),
211
+                $c->getUserManager(),
212
+                $c->getGroupManager(),
213
+                $c->getConfig()
214
+            );
215
+            return new Encryption\File(
216
+                $util,
217
+                $c->getRootFolder(),
218
+                $c->getShareManager()
219
+            );
220
+        });
221
+
222
+        $this->registerService('EncryptionKeyStorage', function (Server $c) {
223
+            $view = new View();
224
+            $util = new Encryption\Util(
225
+                $view,
226
+                $c->getUserManager(),
227
+                $c->getGroupManager(),
228
+                $c->getConfig()
229
+            );
230
+
231
+            return new Encryption\Keys\Storage($view, $util);
232
+        });
233
+        $this->registerService('TagMapper', function (Server $c) {
234
+            return new TagMapper($c->getDatabaseConnection());
235
+        });
236
+
237
+        $this->registerService(\OCP\ITagManager::class, function (Server $c) {
238
+            $tagMapper = $c->query('TagMapper');
239
+            return new TagManager($tagMapper, $c->getUserSession());
240
+        });
241
+        $this->registerAlias('TagManager', \OCP\ITagManager::class);
242
+
243
+        $this->registerService('SystemTagManagerFactory', function (Server $c) {
244
+            $config = $c->getConfig();
245
+            $factoryClass = $config->getSystemValue('systemtags.managerFactory', '\OC\SystemTag\ManagerFactory');
246
+            return new $factoryClass($this);
247
+        });
248
+        $this->registerService(\OCP\SystemTag\ISystemTagManager::class, function (Server $c) {
249
+            return $c->query('SystemTagManagerFactory')->getManager();
250
+        });
251
+        $this->registerAlias('SystemTagManager', \OCP\SystemTag\ISystemTagManager::class);
252
+
253
+        $this->registerService(\OCP\SystemTag\ISystemTagObjectMapper::class, function (Server $c) {
254
+            return $c->query('SystemTagManagerFactory')->getObjectMapper();
255
+        });
256
+        $this->registerService('RootFolder', function (Server $c) {
257
+            $manager = \OC\Files\Filesystem::getMountManager(null);
258
+            $view = new View();
259
+            $root = new Root(
260
+                $manager,
261
+                $view,
262
+                null,
263
+                $c->getUserMountCache(),
264
+                $this->getLogger(),
265
+                $this->getUserManager()
266
+            );
267
+            $connector = new HookConnector($root, $view);
268
+            $connector->viewToNode();
269
+
270
+            $previewConnector = new \OC\Preview\WatcherConnector($root, $c->getSystemConfig());
271
+            $previewConnector->connectWatcher();
272
+
273
+            return $root;
274
+        });
275
+        $this->registerAlias('SystemTagObjectMapper', \OCP\SystemTag\ISystemTagObjectMapper::class);
276
+
277
+        $this->registerService(\OCP\Files\IRootFolder::class, function (Server $c) {
278
+            return new LazyRoot(function () use ($c) {
279
+                return $c->query('RootFolder');
280
+            });
281
+        });
282
+        $this->registerAlias('LazyRootFolder', \OCP\Files\IRootFolder::class);
283
+
284
+        $this->registerService(\OC\User\Manager::class, function (Server $c) {
285
+            $config = $c->getConfig();
286
+            return new \OC\User\Manager($config);
287
+        });
288
+        $this->registerAlias('UserManager', \OC\User\Manager::class);
289
+        $this->registerAlias(\OCP\IUserManager::class, \OC\User\Manager::class);
290
+
291
+        $this->registerService(\OCP\IGroupManager::class, function (Server $c) {
292
+            $groupManager = new \OC\Group\Manager($this->getUserManager(), $this->getLogger());
293
+            $groupManager->listen('\OC\Group', 'preCreate', function ($gid) {
294
+                \OC_Hook::emit('OC_Group', 'pre_createGroup', array('run' => true, 'gid' => $gid));
295
+            });
296
+            $groupManager->listen('\OC\Group', 'postCreate', function (\OC\Group\Group $gid) {
297
+                \OC_Hook::emit('OC_User', 'post_createGroup', array('gid' => $gid->getGID()));
298
+            });
299
+            $groupManager->listen('\OC\Group', 'preDelete', function (\OC\Group\Group $group) {
300
+                \OC_Hook::emit('OC_Group', 'pre_deleteGroup', array('run' => true, 'gid' => $group->getGID()));
301
+            });
302
+            $groupManager->listen('\OC\Group', 'postDelete', function (\OC\Group\Group $group) {
303
+                \OC_Hook::emit('OC_User', 'post_deleteGroup', array('gid' => $group->getGID()));
304
+            });
305
+            $groupManager->listen('\OC\Group', 'preAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
306
+                \OC_Hook::emit('OC_Group', 'pre_addToGroup', array('run' => true, 'uid' => $user->getUID(), 'gid' => $group->getGID()));
307
+            });
308
+            $groupManager->listen('\OC\Group', 'postAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
309
+                \OC_Hook::emit('OC_Group', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
310
+                //Minimal fix to keep it backward compatible TODO: clean up all the GroupManager hooks
311
+                \OC_Hook::emit('OC_User', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
312
+            });
313
+            return $groupManager;
314
+        });
315
+        $this->registerAlias('GroupManager', \OCP\IGroupManager::class);
316
+
317
+        $this->registerService(Store::class, function (Server $c) {
318
+            $session = $c->getSession();
319
+            if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
320
+                $tokenProvider = $c->query('OC\Authentication\Token\IProvider');
321
+            } else {
322
+                $tokenProvider = null;
323
+            }
324
+            $logger = $c->getLogger();
325
+            return new Store($session, $logger, $tokenProvider);
326
+        });
327
+        $this->registerAlias(IStore::class, Store::class);
328
+        $this->registerService('OC\Authentication\Token\DefaultTokenMapper', function (Server $c) {
329
+            $dbConnection = $c->getDatabaseConnection();
330
+            return new Authentication\Token\DefaultTokenMapper($dbConnection);
331
+        });
332
+        $this->registerService('OC\Authentication\Token\DefaultTokenProvider', function (Server $c) {
333
+            $mapper = $c->query('OC\Authentication\Token\DefaultTokenMapper');
334
+            $crypto = $c->getCrypto();
335
+            $config = $c->getConfig();
336
+            $logger = $c->getLogger();
337
+            $timeFactory = new TimeFactory();
338
+            return new \OC\Authentication\Token\DefaultTokenProvider($mapper, $crypto, $config, $logger, $timeFactory);
339
+        });
340
+        $this->registerAlias('OC\Authentication\Token\IProvider', 'OC\Authentication\Token\DefaultTokenProvider');
341
+
342
+        $this->registerService(\OCP\IUserSession::class, function (Server $c) {
343
+            $manager = $c->getUserManager();
344
+            $session = new \OC\Session\Memory('');
345
+            $timeFactory = new TimeFactory();
346
+            // Token providers might require a working database. This code
347
+            // might however be called when ownCloud is not yet setup.
348
+            if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
349
+                $defaultTokenProvider = $c->query('OC\Authentication\Token\IProvider');
350
+            } else {
351
+                $defaultTokenProvider = null;
352
+            }
353
+
354
+            $dispatcher = $c->getEventDispatcher();
355
+
356
+            $userSession = new \OC\User\Session(
357
+                $manager,
358
+                $session,
359
+                $timeFactory,
360
+                $defaultTokenProvider,
361
+                $c->getConfig(),
362
+                $c->getSecureRandom(),
363
+                $c->getLockdownManager(),
364
+                $c->getLogger()
365
+            );
366
+            $userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
367
+                \OC_Hook::emit('OC_User', 'pre_createUser', array('run' => true, 'uid' => $uid, 'password' => $password));
368
+            });
369
+            $userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
370
+                /** @var $user \OC\User\User */
371
+                \OC_Hook::emit('OC_User', 'post_createUser', array('uid' => $user->getUID(), 'password' => $password));
372
+            });
373
+            $userSession->listen('\OC\User', 'preDelete', function ($user) use ($dispatcher) {
374
+                /** @var $user \OC\User\User */
375
+                \OC_Hook::emit('OC_User', 'pre_deleteUser', array('run' => true, 'uid' => $user->getUID()));
376
+                $dispatcher->dispatch('OCP\IUser::preDelete', new GenericEvent($user));
377
+            });
378
+            $userSession->listen('\OC\User', 'postDelete', function ($user) {
379
+                /** @var $user \OC\User\User */
380
+                \OC_Hook::emit('OC_User', 'post_deleteUser', array('uid' => $user->getUID()));
381
+            });
382
+            $userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
383
+                /** @var $user \OC\User\User */
384
+                \OC_Hook::emit('OC_User', 'pre_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
385
+            });
386
+            $userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
387
+                /** @var $user \OC\User\User */
388
+                \OC_Hook::emit('OC_User', 'post_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
389
+            });
390
+            $userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
391
+                \OC_Hook::emit('OC_User', 'pre_login', array('run' => true, 'uid' => $uid, 'password' => $password));
392
+            });
393
+            $userSession->listen('\OC\User', 'postLogin', function ($user, $password) {
394
+                /** @var $user \OC\User\User */
395
+                \OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
396
+            });
397
+            $userSession->listen('\OC\User', 'postRememberedLogin', function ($user, $password) {
398
+                /** @var $user \OC\User\User */
399
+                \OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
400
+            });
401
+            $userSession->listen('\OC\User', 'logout', function () {
402
+                \OC_Hook::emit('OC_User', 'logout', array());
403
+            });
404
+            $userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value, $oldValue) use ($dispatcher) {
405
+                /** @var $user \OC\User\User */
406
+                \OC_Hook::emit('OC_User', 'changeUser', array('run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value, 'old_value' => $oldValue));
407
+                $dispatcher->dispatch('OCP\IUser::changeUser', new GenericEvent($user, ['feature' => $feature, 'oldValue' => $oldValue, 'value' => $value]));
408
+            });
409
+            return $userSession;
410
+        });
411
+        $this->registerAlias('UserSession', \OCP\IUserSession::class);
412
+
413
+        $this->registerService(\OC\Authentication\TwoFactorAuth\Manager::class, function (Server $c) {
414
+            return new \OC\Authentication\TwoFactorAuth\Manager(
415
+                $c->getAppManager(),
416
+                $c->getSession(),
417
+                $c->getConfig(),
418
+                $c->getActivityManager(),
419
+                $c->getLogger(),
420
+                $c->query(\OC\Authentication\Token\IProvider::class),
421
+                $c->query(ITimeFactory::class),
422
+                $c->query(EventDispatcherInterface::class)
423
+            );
424
+        });
425
+
426
+        $this->registerAlias(\OCP\INavigationManager::class, \OC\NavigationManager::class);
427
+        $this->registerAlias('NavigationManager', \OCP\INavigationManager::class);
428
+
429
+        $this->registerService(\OC\AllConfig::class, function (Server $c) {
430
+            return new \OC\AllConfig(
431
+                $c->getSystemConfig()
432
+            );
433
+        });
434
+        $this->registerAlias('AllConfig', \OC\AllConfig::class);
435
+        $this->registerAlias(\OCP\IConfig::class, \OC\AllConfig::class);
436
+
437
+        $this->registerService('SystemConfig', function ($c) use ($config) {
438
+            return new \OC\SystemConfig($config);
439
+        });
440
+
441
+        $this->registerService(\OC\AppConfig::class, function (Server $c) {
442
+            return new \OC\AppConfig($c->getDatabaseConnection());
443
+        });
444
+        $this->registerAlias('AppConfig', \OC\AppConfig::class);
445
+        $this->registerAlias(\OCP\IAppConfig::class, \OC\AppConfig::class);
446
+
447
+        $this->registerService(\OCP\L10N\IFactory::class, function (Server $c) {
448
+            return new \OC\L10N\Factory(
449
+                $c->getConfig(),
450
+                $c->getRequest(),
451
+                $c->getUserSession(),
452
+                \OC::$SERVERROOT
453
+            );
454
+        });
455
+        $this->registerAlias('L10NFactory', \OCP\L10N\IFactory::class);
456
+
457
+        $this->registerService(\OCP\IURLGenerator::class, function (Server $c) {
458
+            $config = $c->getConfig();
459
+            $cacheFactory = $c->getMemCacheFactory();
460
+            $request = $c->getRequest();
461
+            return new \OC\URLGenerator(
462
+                $config,
463
+                $cacheFactory,
464
+                $request
465
+            );
466
+        });
467
+        $this->registerAlias('URLGenerator', \OCP\IURLGenerator::class);
468
+
469
+        $this->registerService('AppHelper', function ($c) {
470
+            return new \OC\AppHelper();
471
+        });
472
+        $this->registerAlias('AppFetcher', AppFetcher::class);
473
+        $this->registerAlias('CategoryFetcher', CategoryFetcher::class);
474
+
475
+        $this->registerService(\OCP\ICache::class, function ($c) {
476
+            return new Cache\File();
477
+        });
478
+        $this->registerAlias('UserCache', \OCP\ICache::class);
479
+
480
+        $this->registerService(Factory::class, function (Server $c) {
481
+
482
+            $arrayCacheFactory = new \OC\Memcache\Factory('', $c->getLogger(),
483
+                '\\OC\\Memcache\\ArrayCache',
484
+                '\\OC\\Memcache\\ArrayCache',
485
+                '\\OC\\Memcache\\ArrayCache'
486
+            );
487
+            $config = $c->getConfig();
488
+            $request = $c->getRequest();
489
+            $urlGenerator = new URLGenerator($config, $arrayCacheFactory, $request);
490
+
491
+            if ($config->getSystemValue('installed', false) && !(defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
492
+                $v = \OC_App::getAppVersions();
493
+                $v['core'] = implode(',', \OC_Util::getVersion());
494
+                $version = implode(',', $v);
495
+                $instanceId = \OC_Util::getInstanceId();
496
+                $path = \OC::$SERVERROOT;
497
+                $prefix = md5($instanceId . '-' . $version . '-' . $path . '-' . $urlGenerator->getBaseUrl());
498
+                return new \OC\Memcache\Factory($prefix, $c->getLogger(),
499
+                    $config->getSystemValue('memcache.local', null),
500
+                    $config->getSystemValue('memcache.distributed', null),
501
+                    $config->getSystemValue('memcache.locking', null)
502
+                );
503
+            }
504
+            return $arrayCacheFactory;
505
+
506
+        });
507
+        $this->registerAlias('MemCacheFactory', Factory::class);
508
+        $this->registerAlias(ICacheFactory::class, Factory::class);
509
+
510
+        $this->registerService('RedisFactory', function (Server $c) {
511
+            $systemConfig = $c->getSystemConfig();
512
+            return new RedisFactory($systemConfig);
513
+        });
514
+
515
+        $this->registerService(\OCP\Activity\IManager::class, function (Server $c) {
516
+            return new \OC\Activity\Manager(
517
+                $c->getRequest(),
518
+                $c->getUserSession(),
519
+                $c->getConfig(),
520
+                $c->query(IValidator::class)
521
+            );
522
+        });
523
+        $this->registerAlias('ActivityManager', \OCP\Activity\IManager::class);
524
+
525
+        $this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
526
+            return new \OC\Activity\EventMerger(
527
+                $c->getL10N('lib')
528
+            );
529
+        });
530
+        $this->registerAlias(IValidator::class, Validator::class);
531
+
532
+        $this->registerService(\OCP\IAvatarManager::class, function (Server $c) {
533
+            return new AvatarManager(
534
+                $c->query(\OC\User\Manager::class),
535
+                $c->getAppDataDir('avatar'),
536
+                $c->getL10N('lib'),
537
+                $c->getLogger(),
538
+                $c->getConfig()
539
+            );
540
+        });
541
+        $this->registerAlias('AvatarManager', \OCP\IAvatarManager::class);
542
+
543
+        $this->registerAlias(\OCP\Support\CrashReport\IRegistry::class, \OC\Support\CrashReport\Registry::class);
544
+
545
+        $this->registerService(\OCP\ILogger::class, function (Server $c) {
546
+            $logType = $c->query('AllConfig')->getSystemValue('log_type', 'file');
547
+            $logger = Log::getLogClass($logType);
548
+            call_user_func(array($logger, 'init'));
549
+            $config = $this->getSystemConfig();
550
+            $registry = $c->query(\OCP\Support\CrashReport\IRegistry::class);
551
+
552
+            return new Log($logger, $config, null, $registry);
553
+        });
554
+        $this->registerAlias('Logger', \OCP\ILogger::class);
555
+
556
+        $this->registerService(\OCP\BackgroundJob\IJobList::class, function (Server $c) {
557
+            $config = $c->getConfig();
558
+            return new \OC\BackgroundJob\JobList(
559
+                $c->getDatabaseConnection(),
560
+                $config,
561
+                new TimeFactory()
562
+            );
563
+        });
564
+        $this->registerAlias('JobList', \OCP\BackgroundJob\IJobList::class);
565
+
566
+        $this->registerService(\OCP\Route\IRouter::class, function (Server $c) {
567
+            $cacheFactory = $c->getMemCacheFactory();
568
+            $logger = $c->getLogger();
569
+            if ($cacheFactory->isAvailableLowLatency()) {
570
+                $router = new \OC\Route\CachingRouter($cacheFactory->createLocal('route'), $logger);
571
+            } else {
572
+                $router = new \OC\Route\Router($logger);
573
+            }
574
+            return $router;
575
+        });
576
+        $this->registerAlias('Router', \OCP\Route\IRouter::class);
577
+
578
+        $this->registerService(\OCP\ISearch::class, function ($c) {
579
+            return new Search();
580
+        });
581
+        $this->registerAlias('Search', \OCP\ISearch::class);
582
+
583
+        $this->registerService(\OC\Security\RateLimiting\Limiter::class, function ($c) {
584
+            return new \OC\Security\RateLimiting\Limiter(
585
+                $this->getUserSession(),
586
+                $this->getRequest(),
587
+                new \OC\AppFramework\Utility\TimeFactory(),
588
+                $c->query(\OC\Security\RateLimiting\Backend\IBackend::class)
589
+            );
590
+        });
591
+        $this->registerService(\OC\Security\RateLimiting\Backend\IBackend::class, function ($c) {
592
+            return new \OC\Security\RateLimiting\Backend\MemoryCache(
593
+                $this->getMemCacheFactory(),
594
+                new \OC\AppFramework\Utility\TimeFactory()
595
+            );
596
+        });
597
+
598
+        $this->registerService(\OCP\Security\ISecureRandom::class, function ($c) {
599
+            return new SecureRandom();
600
+        });
601
+        $this->registerAlias('SecureRandom', \OCP\Security\ISecureRandom::class);
602
+
603
+        $this->registerService(\OCP\Security\ICrypto::class, function (Server $c) {
604
+            return new Crypto($c->getConfig(), $c->getSecureRandom());
605
+        });
606
+        $this->registerAlias('Crypto', \OCP\Security\ICrypto::class);
607
+
608
+        $this->registerService(\OCP\Security\IHasher::class, function (Server $c) {
609
+            return new Hasher($c->getConfig());
610
+        });
611
+        $this->registerAlias('Hasher', \OCP\Security\IHasher::class);
612
+
613
+        $this->registerService(\OCP\Security\ICredentialsManager::class, function (Server $c) {
614
+            return new CredentialsManager($c->getCrypto(), $c->getDatabaseConnection());
615
+        });
616
+        $this->registerAlias('CredentialsManager', \OCP\Security\ICredentialsManager::class);
617
+
618
+        $this->registerService(IDBConnection::class, function (Server $c) {
619
+            $systemConfig = $c->getSystemConfig();
620
+            $factory = new \OC\DB\ConnectionFactory($systemConfig);
621
+            $type = $systemConfig->getValue('dbtype', 'sqlite');
622
+            if (!$factory->isValidType($type)) {
623
+                throw new \OC\DatabaseException('Invalid database type');
624
+            }
625
+            $connectionParams = $factory->createConnectionParams();
626
+            $connection = $factory->getConnection($type, $connectionParams);
627
+            $connection->getConfiguration()->setSQLLogger($c->getQueryLogger());
628
+            return $connection;
629
+        });
630
+        $this->registerAlias('DatabaseConnection', IDBConnection::class);
631
+
632
+        $this->registerService('HTTPHelper', function (Server $c) {
633
+            $config = $c->getConfig();
634
+            return new HTTPHelper(
635
+                $config,
636
+                $c->getHTTPClientService()
637
+            );
638
+        });
639
+
640
+        $this->registerService(\OCP\Http\Client\IClientService::class, function (Server $c) {
641
+            $user = \OC_User::getUser();
642
+            $uid = $user ? $user : null;
643
+            return new ClientService(
644
+                $c->getConfig(),
645
+                new \OC\Security\CertificateManager(
646
+                    $uid,
647
+                    new View(),
648
+                    $c->getConfig(),
649
+                    $c->getLogger(),
650
+                    $c->getSecureRandom()
651
+                )
652
+            );
653
+        });
654
+        $this->registerAlias('HttpClientService', \OCP\Http\Client\IClientService::class);
655
+        $this->registerService(\OCP\Diagnostics\IEventLogger::class, function (Server $c) {
656
+            $eventLogger = new EventLogger();
657
+            if ($c->getSystemConfig()->getValue('debug', false)) {
658
+                // In debug mode, module is being activated by default
659
+                $eventLogger->activate();
660
+            }
661
+            return $eventLogger;
662
+        });
663
+        $this->registerAlias('EventLogger', \OCP\Diagnostics\IEventLogger::class);
664
+
665
+        $this->registerService(\OCP\Diagnostics\IQueryLogger::class, function (Server $c) {
666
+            $queryLogger = new QueryLogger();
667
+            if ($c->getSystemConfig()->getValue('debug', false)) {
668
+                // In debug mode, module is being activated by default
669
+                $queryLogger->activate();
670
+            }
671
+            return $queryLogger;
672
+        });
673
+        $this->registerAlias('QueryLogger', \OCP\Diagnostics\IQueryLogger::class);
674
+
675
+        $this->registerService(TempManager::class, function (Server $c) {
676
+            return new TempManager(
677
+                $c->getLogger(),
678
+                $c->getConfig()
679
+            );
680
+        });
681
+        $this->registerAlias('TempManager', TempManager::class);
682
+        $this->registerAlias(ITempManager::class, TempManager::class);
683
+
684
+        $this->registerService(AppManager::class, function (Server $c) {
685
+            return new \OC\App\AppManager(
686
+                $c->getUserSession(),
687
+                $this->getAppConfig(),
688
+                $c->getGroupManager(),
689
+                $c->getMemCacheFactory(),
690
+                $c->getEventDispatcher()
691
+            );
692
+        });
693
+        $this->registerAlias('AppManager', AppManager::class);
694
+        $this->registerAlias(IAppManager::class, AppManager::class);
695
+
696
+        $this->registerService(\OCP\IDateTimeZone::class, function (Server $c) {
697
+            return new DateTimeZone(
698
+                $c->getConfig(),
699
+                $c->getSession()
700
+            );
701
+        });
702
+        $this->registerAlias('DateTimeZone', \OCP\IDateTimeZone::class);
703
+
704
+        $this->registerService(\OCP\IDateTimeFormatter::class, function (Server $c) {
705
+            $language = $c->getConfig()->getUserValue($c->getSession()->get('user_id'), 'core', 'lang', null);
706
+
707
+            return new DateTimeFormatter(
708
+                $c->getDateTimeZone()->getTimeZone(),
709
+                $c->getL10N('lib', $language)
710
+            );
711
+        });
712
+        $this->registerAlias('DateTimeFormatter', \OCP\IDateTimeFormatter::class);
713
+
714
+        $this->registerService(\OCP\Files\Config\IUserMountCache::class, function (Server $c) {
715
+            $mountCache = new UserMountCache($c->getDatabaseConnection(), $c->getUserManager(), $c->getLogger());
716
+            $listener = new UserMountCacheListener($mountCache);
717
+            $listener->listen($c->getUserManager());
718
+            return $mountCache;
719
+        });
720
+        $this->registerAlias('UserMountCache', \OCP\Files\Config\IUserMountCache::class);
721
+
722
+        $this->registerService(\OCP\Files\Config\IMountProviderCollection::class, function (Server $c) {
723
+            $loader = \OC\Files\Filesystem::getLoader();
724
+            $mountCache = $c->query('UserMountCache');
725
+            $manager = new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
726
+
727
+            // builtin providers
728
+
729
+            $config = $c->getConfig();
730
+            $manager->registerProvider(new CacheMountProvider($config));
731
+            $manager->registerHomeProvider(new LocalHomeMountProvider());
732
+            $manager->registerHomeProvider(new ObjectHomeMountProvider($config));
733
+
734
+            return $manager;
735
+        });
736
+        $this->registerAlias('MountConfigManager', \OCP\Files\Config\IMountProviderCollection::class);
737
+
738
+        $this->registerService('IniWrapper', function ($c) {
739
+            return new IniGetWrapper();
740
+        });
741
+        $this->registerService('AsyncCommandBus', function (Server $c) {
742
+            $busClass = $c->getConfig()->getSystemValue('commandbus');
743
+            if ($busClass) {
744
+                list($app, $class) = explode('::', $busClass, 2);
745
+                if ($c->getAppManager()->isInstalled($app)) {
746
+                    \OC_App::loadApp($app);
747
+                    return $c->query($class);
748
+                } else {
749
+                    throw new ServiceUnavailableException("The app providing the command bus ($app) is not enabled");
750
+                }
751
+            } else {
752
+                $jobList = $c->getJobList();
753
+                return new CronBus($jobList);
754
+            }
755
+        });
756
+        $this->registerService('TrustedDomainHelper', function ($c) {
757
+            return new TrustedDomainHelper($this->getConfig());
758
+        });
759
+        $this->registerService('Throttler', function (Server $c) {
760
+            return new Throttler(
761
+                $c->getDatabaseConnection(),
762
+                new TimeFactory(),
763
+                $c->getLogger(),
764
+                $c->getConfig()
765
+            );
766
+        });
767
+        $this->registerService('IntegrityCodeChecker', function (Server $c) {
768
+            // IConfig and IAppManager requires a working database. This code
769
+            // might however be called when ownCloud is not yet setup.
770
+            if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
771
+                $config = $c->getConfig();
772
+                $appManager = $c->getAppManager();
773
+            } else {
774
+                $config = null;
775
+                $appManager = null;
776
+            }
777
+
778
+            return new Checker(
779
+                new EnvironmentHelper(),
780
+                new FileAccessHelper(),
781
+                new AppLocator(),
782
+                $config,
783
+                $c->getMemCacheFactory(),
784
+                $appManager,
785
+                $c->getTempManager()
786
+            );
787
+        });
788
+        $this->registerService(\OCP\IRequest::class, function ($c) {
789
+            if (isset($this['urlParams'])) {
790
+                $urlParams = $this['urlParams'];
791
+            } else {
792
+                $urlParams = [];
793
+            }
794
+
795
+            if (defined('PHPUNIT_RUN') && PHPUNIT_RUN
796
+                && in_array('fakeinput', stream_get_wrappers())
797
+            ) {
798
+                $stream = 'fakeinput://data';
799
+            } else {
800
+                $stream = 'php://input';
801
+            }
802
+
803
+            return new Request(
804
+                [
805
+                    'get' => $_GET,
806
+                    'post' => $_POST,
807
+                    'files' => $_FILES,
808
+                    'server' => $_SERVER,
809
+                    'env' => $_ENV,
810
+                    'cookies' => $_COOKIE,
811
+                    'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
812
+                        ? $_SERVER['REQUEST_METHOD']
813
+                        : null,
814
+                    'urlParams' => $urlParams,
815
+                ],
816
+                $this->getSecureRandom(),
817
+                $this->getConfig(),
818
+                $this->getCsrfTokenManager(),
819
+                $stream
820
+            );
821
+        });
822
+        $this->registerAlias('Request', \OCP\IRequest::class);
823
+
824
+        $this->registerService(\OCP\Mail\IMailer::class, function (Server $c) {
825
+            return new Mailer(
826
+                $c->getConfig(),
827
+                $c->getLogger(),
828
+                $c->query(Defaults::class),
829
+                $c->getURLGenerator(),
830
+                $c->getL10N('lib')
831
+            );
832
+        });
833
+        $this->registerAlias('Mailer', \OCP\Mail\IMailer::class);
834
+
835
+        $this->registerService('LDAPProvider', function (Server $c) {
836
+            $config = $c->getConfig();
837
+            $factoryClass = $config->getSystemValue('ldapProviderFactory', null);
838
+            if (is_null($factoryClass)) {
839
+                throw new \Exception('ldapProviderFactory not set');
840
+            }
841
+            /** @var \OCP\LDAP\ILDAPProviderFactory $factory */
842
+            $factory = new $factoryClass($this);
843
+            return $factory->getLDAPProvider();
844
+        });
845
+        $this->registerService(ILockingProvider::class, function (Server $c) {
846
+            $ini = $c->getIniWrapper();
847
+            $config = $c->getConfig();
848
+            $ttl = $config->getSystemValue('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
849
+            if ($config->getSystemValue('filelocking.enabled', true) or (defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
850
+                /** @var \OC\Memcache\Factory $memcacheFactory */
851
+                $memcacheFactory = $c->getMemCacheFactory();
852
+                $memcache = $memcacheFactory->createLocking('lock');
853
+                if (!($memcache instanceof \OC\Memcache\NullCache)) {
854
+                    return new MemcacheLockingProvider($memcache, $ttl);
855
+                }
856
+                return new DBLockingProvider($c->getDatabaseConnection(), $c->getLogger(), new TimeFactory(), $ttl);
857
+            }
858
+            return new NoopLockingProvider();
859
+        });
860
+        $this->registerAlias('LockingProvider', ILockingProvider::class);
861
+
862
+        $this->registerService(\OCP\Files\Mount\IMountManager::class, function () {
863
+            return new \OC\Files\Mount\Manager();
864
+        });
865
+        $this->registerAlias('MountManager', \OCP\Files\Mount\IMountManager::class);
866
+
867
+        $this->registerService(\OCP\Files\IMimeTypeDetector::class, function (Server $c) {
868
+            return new \OC\Files\Type\Detection(
869
+                $c->getURLGenerator(),
870
+                \OC::$configDir,
871
+                \OC::$SERVERROOT . '/resources/config/'
872
+            );
873
+        });
874
+        $this->registerAlias('MimeTypeDetector', \OCP\Files\IMimeTypeDetector::class);
875
+
876
+        $this->registerService(\OCP\Files\IMimeTypeLoader::class, function (Server $c) {
877
+            return new \OC\Files\Type\Loader(
878
+                $c->getDatabaseConnection()
879
+            );
880
+        });
881
+        $this->registerAlias('MimeTypeLoader', \OCP\Files\IMimeTypeLoader::class);
882
+        $this->registerService(BundleFetcher::class, function () {
883
+            return new BundleFetcher($this->getL10N('lib'));
884
+        });
885
+        $this->registerService(\OCP\Notification\IManager::class, function (Server $c) {
886
+            return new Manager(
887
+                $c->query(IValidator::class)
888
+            );
889
+        });
890
+        $this->registerAlias('NotificationManager', \OCP\Notification\IManager::class);
891
+
892
+        $this->registerService(\OC\CapabilitiesManager::class, function (Server $c) {
893
+            $manager = new \OC\CapabilitiesManager($c->getLogger());
894
+            $manager->registerCapability(function () use ($c) {
895
+                return new \OC\OCS\CoreCapabilities($c->getConfig());
896
+            });
897
+            $manager->registerCapability(function () use ($c) {
898
+                return $c->query(\OC\Security\Bruteforce\Capabilities::class);
899
+            });
900
+            return $manager;
901
+        });
902
+        $this->registerAlias('CapabilitiesManager', \OC\CapabilitiesManager::class);
903
+
904
+        $this->registerService(\OCP\Comments\ICommentsManager::class, function (Server $c) {
905
+            $config = $c->getConfig();
906
+            $factoryClass = $config->getSystemValue('comments.managerFactory', '\OC\Comments\ManagerFactory');
907
+            /** @var \OCP\Comments\ICommentsManagerFactory $factory */
908
+            $factory = new $factoryClass($this);
909
+            $manager = $factory->getManager();
910
+
911
+            $manager->registerDisplayNameResolver('user', function($id) use ($c) {
912
+                $manager = $c->getUserManager();
913
+                $user = $manager->get($id);
914
+                if(is_null($user)) {
915
+                    $l = $c->getL10N('core');
916
+                    $displayName = $l->t('Unknown user');
917
+                } else {
918
+                    $displayName = $user->getDisplayName();
919
+                }
920
+                return $displayName;
921
+            });
922
+
923
+            return $manager;
924
+        });
925
+        $this->registerAlias('CommentsManager', \OCP\Comments\ICommentsManager::class);
926
+
927
+        $this->registerService('ThemingDefaults', function (Server $c) {
928
+            /*
929 929
 			 * Dark magic for autoloader.
930 930
 			 * If we do a class_exists it will try to load the class which will
931 931
 			 * make composer cache the result. Resulting in errors when enabling
932 932
 			 * the theming app.
933 933
 			 */
934
-			$prefixes = \OC::$composerAutoloader->getPrefixesPsr4();
935
-			if (isset($prefixes['OCA\\Theming\\'])) {
936
-				$classExists = true;
937
-			} else {
938
-				$classExists = false;
939
-			}
940
-
941
-			if ($classExists && $c->getConfig()->getSystemValue('installed', false) && $c->getAppManager()->isInstalled('theming') && $c->getTrustedDomainHelper()->isTrustedDomain($c->getRequest()->getInsecureServerHost())) {
942
-				return new ThemingDefaults(
943
-					$c->getConfig(),
944
-					$c->getL10N('theming'),
945
-					$c->getURLGenerator(),
946
-					$c->getAppDataDir('theming'),
947
-					$c->getMemCacheFactory(),
948
-					new Util($c->getConfig(), $this->getAppManager(), $this->getAppDataDir('theming')),
949
-					$this->getAppManager()
950
-				);
951
-			}
952
-			return new \OC_Defaults();
953
-		});
954
-		$this->registerService(SCSSCacher::class, function (Server $c) {
955
-			/** @var Factory $cacheFactory */
956
-			$cacheFactory = $c->query(Factory::class);
957
-			return new SCSSCacher(
958
-				$c->getLogger(),
959
-				$c->query(\OC\Files\AppData\Factory::class),
960
-				$c->getURLGenerator(),
961
-				$c->getConfig(),
962
-				$c->getThemingDefaults(),
963
-				\OC::$SERVERROOT,
964
-				$cacheFactory->createDistributed('SCSS')
965
-			);
966
-		});
967
-		$this->registerService(EventDispatcher::class, function () {
968
-			return new EventDispatcher();
969
-		});
970
-		$this->registerAlias('EventDispatcher', EventDispatcher::class);
971
-		$this->registerAlias(EventDispatcherInterface::class, EventDispatcher::class);
972
-
973
-		$this->registerService('CryptoWrapper', function (Server $c) {
974
-			// FIXME: Instantiiated here due to cyclic dependency
975
-			$request = new Request(
976
-				[
977
-					'get' => $_GET,
978
-					'post' => $_POST,
979
-					'files' => $_FILES,
980
-					'server' => $_SERVER,
981
-					'env' => $_ENV,
982
-					'cookies' => $_COOKIE,
983
-					'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
984
-						? $_SERVER['REQUEST_METHOD']
985
-						: null,
986
-				],
987
-				$c->getSecureRandom(),
988
-				$c->getConfig()
989
-			);
990
-
991
-			return new CryptoWrapper(
992
-				$c->getConfig(),
993
-				$c->getCrypto(),
994
-				$c->getSecureRandom(),
995
-				$request
996
-			);
997
-		});
998
-		$this->registerService('CsrfTokenManager', function (Server $c) {
999
-			$tokenGenerator = new CsrfTokenGenerator($c->getSecureRandom());
1000
-
1001
-			return new CsrfTokenManager(
1002
-				$tokenGenerator,
1003
-				$c->query(SessionStorage::class)
1004
-			);
1005
-		});
1006
-		$this->registerService(SessionStorage::class, function (Server $c) {
1007
-			return new SessionStorage($c->getSession());
1008
-		});
1009
-		$this->registerService(\OCP\Security\IContentSecurityPolicyManager::class, function (Server $c) {
1010
-			return new ContentSecurityPolicyManager();
1011
-		});
1012
-		$this->registerAlias('ContentSecurityPolicyManager', \OCP\Security\IContentSecurityPolicyManager::class);
1013
-
1014
-		$this->registerService('ContentSecurityPolicyNonceManager', function (Server $c) {
1015
-			return new ContentSecurityPolicyNonceManager(
1016
-				$c->getCsrfTokenManager(),
1017
-				$c->getRequest()
1018
-			);
1019
-		});
1020
-
1021
-		$this->registerService(\OCP\Share\IManager::class, function (Server $c) {
1022
-			$config = $c->getConfig();
1023
-			$factoryClass = $config->getSystemValue('sharing.managerFactory', '\OC\Share20\ProviderFactory');
1024
-			/** @var \OCP\Share\IProviderFactory $factory */
1025
-			$factory = new $factoryClass($this);
1026
-
1027
-			$manager = new \OC\Share20\Manager(
1028
-				$c->getLogger(),
1029
-				$c->getConfig(),
1030
-				$c->getSecureRandom(),
1031
-				$c->getHasher(),
1032
-				$c->getMountManager(),
1033
-				$c->getGroupManager(),
1034
-				$c->getL10N('lib'),
1035
-				$c->getL10NFactory(),
1036
-				$factory,
1037
-				$c->getUserManager(),
1038
-				$c->getLazyRootFolder(),
1039
-				$c->getEventDispatcher(),
1040
-				$c->getMailer(),
1041
-				$c->getURLGenerator(),
1042
-				$c->getThemingDefaults()
1043
-			);
1044
-
1045
-			return $manager;
1046
-		});
1047
-		$this->registerAlias('ShareManager', \OCP\Share\IManager::class);
1048
-
1049
-		$this->registerService(\OCP\Collaboration\Collaborators\ISearch::class, function(Server $c) {
1050
-			$instance = new Collaboration\Collaborators\Search($c);
1051
-
1052
-			// register default plugins
1053
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_USER', 'class' => UserPlugin::class]);
1054
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_GROUP', 'class' => GroupPlugin::class]);
1055
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_EMAIL', 'class' => MailPlugin::class]);
1056
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_REMOTE', 'class' => RemotePlugin::class]);
1057
-
1058
-			return $instance;
1059
-		});
1060
-		$this->registerAlias('CollaboratorSearch', \OCP\Collaboration\Collaborators\ISearch::class);
1061
-
1062
-		$this->registerAlias(\OCP\Collaboration\AutoComplete\IManager::class, \OC\Collaboration\AutoComplete\Manager::class);
1063
-
1064
-		$this->registerService('SettingsManager', function (Server $c) {
1065
-			$manager = new \OC\Settings\Manager(
1066
-				$c->getLogger(),
1067
-				$c->getDatabaseConnection(),
1068
-				$c->getL10N('lib'),
1069
-				$c->getConfig(),
1070
-				$c->getEncryptionManager(),
1071
-				$c->getUserManager(),
1072
-				$c->getLockingProvider(),
1073
-				$c->getRequest(),
1074
-				new \OC\Settings\Mapper($c->getDatabaseConnection()),
1075
-				$c->getURLGenerator(),
1076
-				$c->query(AccountManager::class),
1077
-				$c->getGroupManager(),
1078
-				$c->getL10NFactory(),
1079
-				$c->getThemingDefaults(),
1080
-				$c->getAppManager()
1081
-			);
1082
-			return $manager;
1083
-		});
1084
-		$this->registerService(\OC\Files\AppData\Factory::class, function (Server $c) {
1085
-			return new \OC\Files\AppData\Factory(
1086
-				$c->getRootFolder(),
1087
-				$c->getSystemConfig()
1088
-			);
1089
-		});
1090
-
1091
-		$this->registerService('LockdownManager', function (Server $c) {
1092
-			return new LockdownManager(function () use ($c) {
1093
-				return $c->getSession();
1094
-			});
1095
-		});
1096
-
1097
-		$this->registerService(\OCP\OCS\IDiscoveryService::class, function (Server $c) {
1098
-			return new DiscoveryService($c->getMemCacheFactory(), $c->getHTTPClientService());
1099
-		});
1100
-
1101
-		$this->registerService(ICloudIdManager::class, function (Server $c) {
1102
-			return new CloudIdManager();
1103
-		});
1104
-
1105
-		$this->registerAlias(\OCP\AppFramework\Utility\IControllerMethodReflector::class, \OC\AppFramework\Utility\ControllerMethodReflector::class);
1106
-		$this->registerAlias('ControllerMethodReflector', \OCP\AppFramework\Utility\IControllerMethodReflector::class);
1107
-
1108
-		$this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
1109
-		$this->registerAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
1110
-
1111
-		$this->registerService(Defaults::class, function (Server $c) {
1112
-			return new Defaults(
1113
-				$c->getThemingDefaults()
1114
-			);
1115
-		});
1116
-		$this->registerAlias('Defaults', \OCP\Defaults::class);
1117
-
1118
-		$this->registerService(\OCP\ISession::class, function (SimpleContainer $c) {
1119
-			return $c->query(\OCP\IUserSession::class)->getSession();
1120
-		});
1121
-
1122
-		$this->registerService(IShareHelper::class, function (Server $c) {
1123
-			return new ShareHelper(
1124
-				$c->query(\OCP\Share\IManager::class)
1125
-			);
1126
-		});
1127
-
1128
-		$this->registerService(Installer::class, function(Server $c) {
1129
-			return new Installer(
1130
-				$c->getAppFetcher(),
1131
-				$c->getHTTPClientService(),
1132
-				$c->getTempManager(),
1133
-				$c->getLogger(),
1134
-				$c->getConfig()
1135
-			);
1136
-		});
1137
-
1138
-		$this->registerService(IApiFactory::class, function(Server $c) {
1139
-			return new ApiFactory($c->getHTTPClientService());
1140
-		});
1141
-
1142
-		$this->registerService(IInstanceFactory::class, function(Server $c) {
1143
-			$memcacheFactory = $c->getMemCacheFactory();
1144
-			return new InstanceFactory($memcacheFactory->createLocal('remoteinstance.'), $c->getHTTPClientService());
1145
-		});
1146
-
1147
-		$this->registerService(IContactsStore::class, function(Server $c) {
1148
-			return new ContactsStore(
1149
-				$c->getContactsManager(),
1150
-				$c->getConfig(),
1151
-				$c->getUserManager(),
1152
-				$c->getGroupManager()
1153
-			);
1154
-		});
1155
-		$this->registerAlias(IContactsStore::class, ContactsStore::class);
1156
-
1157
-		$this->connectDispatcher();
1158
-	}
1159
-
1160
-	/**
1161
-	 * @return \OCP\Calendar\IManager
1162
-	 */
1163
-	public function getCalendarManager() {
1164
-		return $this->query('CalendarManager');
1165
-	}
1166
-
1167
-	private function connectDispatcher() {
1168
-		$dispatcher = $this->getEventDispatcher();
1169
-
1170
-		// Delete avatar on user deletion
1171
-		$dispatcher->addListener('OCP\IUser::preDelete', function(GenericEvent $e) {
1172
-			$logger = $this->getLogger();
1173
-			$manager = $this->getAvatarManager();
1174
-			/** @var IUser $user */
1175
-			$user = $e->getSubject();
1176
-
1177
-			try {
1178
-				$avatar = $manager->getAvatar($user->getUID());
1179
-				$avatar->remove();
1180
-			} catch (NotFoundException $e) {
1181
-				// no avatar to remove
1182
-			} catch (\Exception $e) {
1183
-				// Ignore exceptions
1184
-				$logger->info('Could not cleanup avatar of ' . $user->getUID());
1185
-			}
1186
-		});
1187
-
1188
-		$dispatcher->addListener('OCP\IUser::changeUser', function (GenericEvent $e) {
1189
-			$manager = $this->getAvatarManager();
1190
-			/** @var IUser $user */
1191
-			$user = $e->getSubject();
1192
-			$feature = $e->getArgument('feature');
1193
-			$oldValue = $e->getArgument('oldValue');
1194
-			$value = $e->getArgument('value');
1195
-
1196
-			try {
1197
-				$avatar = $manager->getAvatar($user->getUID());
1198
-				$avatar->userChanged($feature, $oldValue, $value);
1199
-			} catch (NotFoundException $e) {
1200
-				// no avatar to remove
1201
-			}
1202
-		});
1203
-	}
1204
-
1205
-	/**
1206
-	 * @return \OCP\Contacts\IManager
1207
-	 */
1208
-	public function getContactsManager() {
1209
-		return $this->query('ContactsManager');
1210
-	}
1211
-
1212
-	/**
1213
-	 * @return \OC\Encryption\Manager
1214
-	 */
1215
-	public function getEncryptionManager() {
1216
-		return $this->query('EncryptionManager');
1217
-	}
1218
-
1219
-	/**
1220
-	 * @return \OC\Encryption\File
1221
-	 */
1222
-	public function getEncryptionFilesHelper() {
1223
-		return $this->query('EncryptionFileHelper');
1224
-	}
1225
-
1226
-	/**
1227
-	 * @return \OCP\Encryption\Keys\IStorage
1228
-	 */
1229
-	public function getEncryptionKeyStorage() {
1230
-		return $this->query('EncryptionKeyStorage');
1231
-	}
1232
-
1233
-	/**
1234
-	 * The current request object holding all information about the request
1235
-	 * currently being processed is returned from this method.
1236
-	 * In case the current execution was not initiated by a web request null is returned
1237
-	 *
1238
-	 * @return \OCP\IRequest
1239
-	 */
1240
-	public function getRequest() {
1241
-		return $this->query('Request');
1242
-	}
1243
-
1244
-	/**
1245
-	 * Returns the preview manager which can create preview images for a given file
1246
-	 *
1247
-	 * @return \OCP\IPreview
1248
-	 */
1249
-	public function getPreviewManager() {
1250
-		return $this->query('PreviewManager');
1251
-	}
1252
-
1253
-	/**
1254
-	 * Returns the tag manager which can get and set tags for different object types
1255
-	 *
1256
-	 * @see \OCP\ITagManager::load()
1257
-	 * @return \OCP\ITagManager
1258
-	 */
1259
-	public function getTagManager() {
1260
-		return $this->query('TagManager');
1261
-	}
1262
-
1263
-	/**
1264
-	 * Returns the system-tag manager
1265
-	 *
1266
-	 * @return \OCP\SystemTag\ISystemTagManager
1267
-	 *
1268
-	 * @since 9.0.0
1269
-	 */
1270
-	public function getSystemTagManager() {
1271
-		return $this->query('SystemTagManager');
1272
-	}
1273
-
1274
-	/**
1275
-	 * Returns the system-tag object mapper
1276
-	 *
1277
-	 * @return \OCP\SystemTag\ISystemTagObjectMapper
1278
-	 *
1279
-	 * @since 9.0.0
1280
-	 */
1281
-	public function getSystemTagObjectMapper() {
1282
-		return $this->query('SystemTagObjectMapper');
1283
-	}
1284
-
1285
-	/**
1286
-	 * Returns the avatar manager, used for avatar functionality
1287
-	 *
1288
-	 * @return \OCP\IAvatarManager
1289
-	 */
1290
-	public function getAvatarManager() {
1291
-		return $this->query('AvatarManager');
1292
-	}
1293
-
1294
-	/**
1295
-	 * Returns the root folder of ownCloud's data directory
1296
-	 *
1297
-	 * @return \OCP\Files\IRootFolder
1298
-	 */
1299
-	public function getRootFolder() {
1300
-		return $this->query('LazyRootFolder');
1301
-	}
1302
-
1303
-	/**
1304
-	 * Returns the root folder of ownCloud's data directory
1305
-	 * This is the lazy variant so this gets only initialized once it
1306
-	 * is actually used.
1307
-	 *
1308
-	 * @return \OCP\Files\IRootFolder
1309
-	 */
1310
-	public function getLazyRootFolder() {
1311
-		return $this->query('LazyRootFolder');
1312
-	}
1313
-
1314
-	/**
1315
-	 * Returns a view to ownCloud's files folder
1316
-	 *
1317
-	 * @param string $userId user ID
1318
-	 * @return \OCP\Files\Folder|null
1319
-	 */
1320
-	public function getUserFolder($userId = null) {
1321
-		if ($userId === null) {
1322
-			$user = $this->getUserSession()->getUser();
1323
-			if (!$user) {
1324
-				return null;
1325
-			}
1326
-			$userId = $user->getUID();
1327
-		}
1328
-		$root = $this->getRootFolder();
1329
-		return $root->getUserFolder($userId);
1330
-	}
1331
-
1332
-	/**
1333
-	 * Returns an app-specific view in ownClouds data directory
1334
-	 *
1335
-	 * @return \OCP\Files\Folder
1336
-	 * @deprecated since 9.2.0 use IAppData
1337
-	 */
1338
-	public function getAppFolder() {
1339
-		$dir = '/' . \OC_App::getCurrentApp();
1340
-		$root = $this->getRootFolder();
1341
-		if (!$root->nodeExists($dir)) {
1342
-			$folder = $root->newFolder($dir);
1343
-		} else {
1344
-			$folder = $root->get($dir);
1345
-		}
1346
-		return $folder;
1347
-	}
1348
-
1349
-	/**
1350
-	 * @return \OC\User\Manager
1351
-	 */
1352
-	public function getUserManager() {
1353
-		return $this->query('UserManager');
1354
-	}
1355
-
1356
-	/**
1357
-	 * @return \OC\Group\Manager
1358
-	 */
1359
-	public function getGroupManager() {
1360
-		return $this->query('GroupManager');
1361
-	}
1362
-
1363
-	/**
1364
-	 * @return \OC\User\Session
1365
-	 */
1366
-	public function getUserSession() {
1367
-		return $this->query('UserSession');
1368
-	}
1369
-
1370
-	/**
1371
-	 * @return \OCP\ISession
1372
-	 */
1373
-	public function getSession() {
1374
-		return $this->query('UserSession')->getSession();
1375
-	}
1376
-
1377
-	/**
1378
-	 * @param \OCP\ISession $session
1379
-	 */
1380
-	public function setSession(\OCP\ISession $session) {
1381
-		$this->query(SessionStorage::class)->setSession($session);
1382
-		$this->query('UserSession')->setSession($session);
1383
-		$this->query(Store::class)->setSession($session);
1384
-	}
1385
-
1386
-	/**
1387
-	 * @return \OC\Authentication\TwoFactorAuth\Manager
1388
-	 */
1389
-	public function getTwoFactorAuthManager() {
1390
-		return $this->query('\OC\Authentication\TwoFactorAuth\Manager');
1391
-	}
1392
-
1393
-	/**
1394
-	 * @return \OC\NavigationManager
1395
-	 */
1396
-	public function getNavigationManager() {
1397
-		return $this->query('NavigationManager');
1398
-	}
1399
-
1400
-	/**
1401
-	 * @return \OCP\IConfig
1402
-	 */
1403
-	public function getConfig() {
1404
-		return $this->query('AllConfig');
1405
-	}
1406
-
1407
-	/**
1408
-	 * @return \OC\SystemConfig
1409
-	 */
1410
-	public function getSystemConfig() {
1411
-		return $this->query('SystemConfig');
1412
-	}
1413
-
1414
-	/**
1415
-	 * Returns the app config manager
1416
-	 *
1417
-	 * @return \OCP\IAppConfig
1418
-	 */
1419
-	public function getAppConfig() {
1420
-		return $this->query('AppConfig');
1421
-	}
1422
-
1423
-	/**
1424
-	 * @return \OCP\L10N\IFactory
1425
-	 */
1426
-	public function getL10NFactory() {
1427
-		return $this->query('L10NFactory');
1428
-	}
1429
-
1430
-	/**
1431
-	 * get an L10N instance
1432
-	 *
1433
-	 * @param string $app appid
1434
-	 * @param string $lang
1435
-	 * @return IL10N
1436
-	 */
1437
-	public function getL10N($app, $lang = null) {
1438
-		return $this->getL10NFactory()->get($app, $lang);
1439
-	}
1440
-
1441
-	/**
1442
-	 * @return \OCP\IURLGenerator
1443
-	 */
1444
-	public function getURLGenerator() {
1445
-		return $this->query('URLGenerator');
1446
-	}
1447
-
1448
-	/**
1449
-	 * @return \OCP\IHelper
1450
-	 */
1451
-	public function getHelper() {
1452
-		return $this->query('AppHelper');
1453
-	}
1454
-
1455
-	/**
1456
-	 * @return AppFetcher
1457
-	 */
1458
-	public function getAppFetcher() {
1459
-		return $this->query(AppFetcher::class);
1460
-	}
1461
-
1462
-	/**
1463
-	 * Returns an ICache instance. Since 8.1.0 it returns a fake cache. Use
1464
-	 * getMemCacheFactory() instead.
1465
-	 *
1466
-	 * @return \OCP\ICache
1467
-	 * @deprecated 8.1.0 use getMemCacheFactory to obtain a proper cache
1468
-	 */
1469
-	public function getCache() {
1470
-		return $this->query('UserCache');
1471
-	}
1472
-
1473
-	/**
1474
-	 * Returns an \OCP\CacheFactory instance
1475
-	 *
1476
-	 * @return \OCP\ICacheFactory
1477
-	 */
1478
-	public function getMemCacheFactory() {
1479
-		return $this->query('MemCacheFactory');
1480
-	}
1481
-
1482
-	/**
1483
-	 * Returns an \OC\RedisFactory instance
1484
-	 *
1485
-	 * @return \OC\RedisFactory
1486
-	 */
1487
-	public function getGetRedisFactory() {
1488
-		return $this->query('RedisFactory');
1489
-	}
1490
-
1491
-
1492
-	/**
1493
-	 * Returns the current session
1494
-	 *
1495
-	 * @return \OCP\IDBConnection
1496
-	 */
1497
-	public function getDatabaseConnection() {
1498
-		return $this->query('DatabaseConnection');
1499
-	}
1500
-
1501
-	/**
1502
-	 * Returns the activity manager
1503
-	 *
1504
-	 * @return \OCP\Activity\IManager
1505
-	 */
1506
-	public function getActivityManager() {
1507
-		return $this->query('ActivityManager');
1508
-	}
1509
-
1510
-	/**
1511
-	 * Returns an job list for controlling background jobs
1512
-	 *
1513
-	 * @return \OCP\BackgroundJob\IJobList
1514
-	 */
1515
-	public function getJobList() {
1516
-		return $this->query('JobList');
1517
-	}
1518
-
1519
-	/**
1520
-	 * Returns a logger instance
1521
-	 *
1522
-	 * @return \OCP\ILogger
1523
-	 */
1524
-	public function getLogger() {
1525
-		return $this->query('Logger');
1526
-	}
1527
-
1528
-	/**
1529
-	 * Returns a router for generating and matching urls
1530
-	 *
1531
-	 * @return \OCP\Route\IRouter
1532
-	 */
1533
-	public function getRouter() {
1534
-		return $this->query('Router');
1535
-	}
1536
-
1537
-	/**
1538
-	 * Returns a search instance
1539
-	 *
1540
-	 * @return \OCP\ISearch
1541
-	 */
1542
-	public function getSearch() {
1543
-		return $this->query('Search');
1544
-	}
1545
-
1546
-	/**
1547
-	 * Returns a SecureRandom instance
1548
-	 *
1549
-	 * @return \OCP\Security\ISecureRandom
1550
-	 */
1551
-	public function getSecureRandom() {
1552
-		return $this->query('SecureRandom');
1553
-	}
1554
-
1555
-	/**
1556
-	 * Returns a Crypto instance
1557
-	 *
1558
-	 * @return \OCP\Security\ICrypto
1559
-	 */
1560
-	public function getCrypto() {
1561
-		return $this->query('Crypto');
1562
-	}
1563
-
1564
-	/**
1565
-	 * Returns a Hasher instance
1566
-	 *
1567
-	 * @return \OCP\Security\IHasher
1568
-	 */
1569
-	public function getHasher() {
1570
-		return $this->query('Hasher');
1571
-	}
1572
-
1573
-	/**
1574
-	 * Returns a CredentialsManager instance
1575
-	 *
1576
-	 * @return \OCP\Security\ICredentialsManager
1577
-	 */
1578
-	public function getCredentialsManager() {
1579
-		return $this->query('CredentialsManager');
1580
-	}
1581
-
1582
-	/**
1583
-	 * Returns an instance of the HTTP helper class
1584
-	 *
1585
-	 * @deprecated Use getHTTPClientService()
1586
-	 * @return \OC\HTTPHelper
1587
-	 */
1588
-	public function getHTTPHelper() {
1589
-		return $this->query('HTTPHelper');
1590
-	}
1591
-
1592
-	/**
1593
-	 * Get the certificate manager for the user
1594
-	 *
1595
-	 * @param string $userId (optional) if not specified the current loggedin user is used, use null to get the system certificate manager
1596
-	 * @return \OCP\ICertificateManager | null if $uid is null and no user is logged in
1597
-	 */
1598
-	public function getCertificateManager($userId = '') {
1599
-		if ($userId === '') {
1600
-			$userSession = $this->getUserSession();
1601
-			$user = $userSession->getUser();
1602
-			if (is_null($user)) {
1603
-				return null;
1604
-			}
1605
-			$userId = $user->getUID();
1606
-		}
1607
-		return new CertificateManager(
1608
-			$userId,
1609
-			new View(),
1610
-			$this->getConfig(),
1611
-			$this->getLogger(),
1612
-			$this->getSecureRandom()
1613
-		);
1614
-	}
1615
-
1616
-	/**
1617
-	 * Returns an instance of the HTTP client service
1618
-	 *
1619
-	 * @return \OCP\Http\Client\IClientService
1620
-	 */
1621
-	public function getHTTPClientService() {
1622
-		return $this->query('HttpClientService');
1623
-	}
1624
-
1625
-	/**
1626
-	 * Create a new event source
1627
-	 *
1628
-	 * @return \OCP\IEventSource
1629
-	 */
1630
-	public function createEventSource() {
1631
-		return new \OC_EventSource();
1632
-	}
1633
-
1634
-	/**
1635
-	 * Get the active event logger
1636
-	 *
1637
-	 * The returned logger only logs data when debug mode is enabled
1638
-	 *
1639
-	 * @return \OCP\Diagnostics\IEventLogger
1640
-	 */
1641
-	public function getEventLogger() {
1642
-		return $this->query('EventLogger');
1643
-	}
1644
-
1645
-	/**
1646
-	 * Get the active query logger
1647
-	 *
1648
-	 * The returned logger only logs data when debug mode is enabled
1649
-	 *
1650
-	 * @return \OCP\Diagnostics\IQueryLogger
1651
-	 */
1652
-	public function getQueryLogger() {
1653
-		return $this->query('QueryLogger');
1654
-	}
1655
-
1656
-	/**
1657
-	 * Get the manager for temporary files and folders
1658
-	 *
1659
-	 * @return \OCP\ITempManager
1660
-	 */
1661
-	public function getTempManager() {
1662
-		return $this->query('TempManager');
1663
-	}
1664
-
1665
-	/**
1666
-	 * Get the app manager
1667
-	 *
1668
-	 * @return \OCP\App\IAppManager
1669
-	 */
1670
-	public function getAppManager() {
1671
-		return $this->query('AppManager');
1672
-	}
1673
-
1674
-	/**
1675
-	 * Creates a new mailer
1676
-	 *
1677
-	 * @return \OCP\Mail\IMailer
1678
-	 */
1679
-	public function getMailer() {
1680
-		return $this->query('Mailer');
1681
-	}
1682
-
1683
-	/**
1684
-	 * Get the webroot
1685
-	 *
1686
-	 * @return string
1687
-	 */
1688
-	public function getWebRoot() {
1689
-		return $this->webRoot;
1690
-	}
1691
-
1692
-	/**
1693
-	 * @return \OC\OCSClient
1694
-	 */
1695
-	public function getOcsClient() {
1696
-		return $this->query('OcsClient');
1697
-	}
1698
-
1699
-	/**
1700
-	 * @return \OCP\IDateTimeZone
1701
-	 */
1702
-	public function getDateTimeZone() {
1703
-		return $this->query('DateTimeZone');
1704
-	}
1705
-
1706
-	/**
1707
-	 * @return \OCP\IDateTimeFormatter
1708
-	 */
1709
-	public function getDateTimeFormatter() {
1710
-		return $this->query('DateTimeFormatter');
1711
-	}
1712
-
1713
-	/**
1714
-	 * @return \OCP\Files\Config\IMountProviderCollection
1715
-	 */
1716
-	public function getMountProviderCollection() {
1717
-		return $this->query('MountConfigManager');
1718
-	}
1719
-
1720
-	/**
1721
-	 * Get the IniWrapper
1722
-	 *
1723
-	 * @return IniGetWrapper
1724
-	 */
1725
-	public function getIniWrapper() {
1726
-		return $this->query('IniWrapper');
1727
-	}
1728
-
1729
-	/**
1730
-	 * @return \OCP\Command\IBus
1731
-	 */
1732
-	public function getCommandBus() {
1733
-		return $this->query('AsyncCommandBus');
1734
-	}
1735
-
1736
-	/**
1737
-	 * Get the trusted domain helper
1738
-	 *
1739
-	 * @return TrustedDomainHelper
1740
-	 */
1741
-	public function getTrustedDomainHelper() {
1742
-		return $this->query('TrustedDomainHelper');
1743
-	}
1744
-
1745
-	/**
1746
-	 * Get the locking provider
1747
-	 *
1748
-	 * @return \OCP\Lock\ILockingProvider
1749
-	 * @since 8.1.0
1750
-	 */
1751
-	public function getLockingProvider() {
1752
-		return $this->query('LockingProvider');
1753
-	}
1754
-
1755
-	/**
1756
-	 * @return \OCP\Files\Mount\IMountManager
1757
-	 **/
1758
-	function getMountManager() {
1759
-		return $this->query('MountManager');
1760
-	}
1761
-
1762
-	/** @return \OCP\Files\Config\IUserMountCache */
1763
-	function getUserMountCache() {
1764
-		return $this->query('UserMountCache');
1765
-	}
1766
-
1767
-	/**
1768
-	 * Get the MimeTypeDetector
1769
-	 *
1770
-	 * @return \OCP\Files\IMimeTypeDetector
1771
-	 */
1772
-	public function getMimeTypeDetector() {
1773
-		return $this->query('MimeTypeDetector');
1774
-	}
1775
-
1776
-	/**
1777
-	 * Get the MimeTypeLoader
1778
-	 *
1779
-	 * @return \OCP\Files\IMimeTypeLoader
1780
-	 */
1781
-	public function getMimeTypeLoader() {
1782
-		return $this->query('MimeTypeLoader');
1783
-	}
1784
-
1785
-	/**
1786
-	 * Get the manager of all the capabilities
1787
-	 *
1788
-	 * @return \OC\CapabilitiesManager
1789
-	 */
1790
-	public function getCapabilitiesManager() {
1791
-		return $this->query('CapabilitiesManager');
1792
-	}
1793
-
1794
-	/**
1795
-	 * Get the EventDispatcher
1796
-	 *
1797
-	 * @return EventDispatcherInterface
1798
-	 * @since 8.2.0
1799
-	 */
1800
-	public function getEventDispatcher() {
1801
-		return $this->query('EventDispatcher');
1802
-	}
1803
-
1804
-	/**
1805
-	 * Get the Notification Manager
1806
-	 *
1807
-	 * @return \OCP\Notification\IManager
1808
-	 * @since 8.2.0
1809
-	 */
1810
-	public function getNotificationManager() {
1811
-		return $this->query('NotificationManager');
1812
-	}
1813
-
1814
-	/**
1815
-	 * @return \OCP\Comments\ICommentsManager
1816
-	 */
1817
-	public function getCommentsManager() {
1818
-		return $this->query('CommentsManager');
1819
-	}
1820
-
1821
-	/**
1822
-	 * @return \OCA\Theming\ThemingDefaults
1823
-	 */
1824
-	public function getThemingDefaults() {
1825
-		return $this->query('ThemingDefaults');
1826
-	}
1827
-
1828
-	/**
1829
-	 * @return \OC\IntegrityCheck\Checker
1830
-	 */
1831
-	public function getIntegrityCodeChecker() {
1832
-		return $this->query('IntegrityCodeChecker');
1833
-	}
1834
-
1835
-	/**
1836
-	 * @return \OC\Session\CryptoWrapper
1837
-	 */
1838
-	public function getSessionCryptoWrapper() {
1839
-		return $this->query('CryptoWrapper');
1840
-	}
1841
-
1842
-	/**
1843
-	 * @return CsrfTokenManager
1844
-	 */
1845
-	public function getCsrfTokenManager() {
1846
-		return $this->query('CsrfTokenManager');
1847
-	}
1848
-
1849
-	/**
1850
-	 * @return Throttler
1851
-	 */
1852
-	public function getBruteForceThrottler() {
1853
-		return $this->query('Throttler');
1854
-	}
1855
-
1856
-	/**
1857
-	 * @return IContentSecurityPolicyManager
1858
-	 */
1859
-	public function getContentSecurityPolicyManager() {
1860
-		return $this->query('ContentSecurityPolicyManager');
1861
-	}
1862
-
1863
-	/**
1864
-	 * @return ContentSecurityPolicyNonceManager
1865
-	 */
1866
-	public function getContentSecurityPolicyNonceManager() {
1867
-		return $this->query('ContentSecurityPolicyNonceManager');
1868
-	}
1869
-
1870
-	/**
1871
-	 * Not a public API as of 8.2, wait for 9.0
1872
-	 *
1873
-	 * @return \OCA\Files_External\Service\BackendService
1874
-	 */
1875
-	public function getStoragesBackendService() {
1876
-		return $this->query('OCA\\Files_External\\Service\\BackendService');
1877
-	}
1878
-
1879
-	/**
1880
-	 * Not a public API as of 8.2, wait for 9.0
1881
-	 *
1882
-	 * @return \OCA\Files_External\Service\GlobalStoragesService
1883
-	 */
1884
-	public function getGlobalStoragesService() {
1885
-		return $this->query('OCA\\Files_External\\Service\\GlobalStoragesService');
1886
-	}
1887
-
1888
-	/**
1889
-	 * Not a public API as of 8.2, wait for 9.0
1890
-	 *
1891
-	 * @return \OCA\Files_External\Service\UserGlobalStoragesService
1892
-	 */
1893
-	public function getUserGlobalStoragesService() {
1894
-		return $this->query('OCA\\Files_External\\Service\\UserGlobalStoragesService');
1895
-	}
1896
-
1897
-	/**
1898
-	 * Not a public API as of 8.2, wait for 9.0
1899
-	 *
1900
-	 * @return \OCA\Files_External\Service\UserStoragesService
1901
-	 */
1902
-	public function getUserStoragesService() {
1903
-		return $this->query('OCA\\Files_External\\Service\\UserStoragesService');
1904
-	}
1905
-
1906
-	/**
1907
-	 * @return \OCP\Share\IManager
1908
-	 */
1909
-	public function getShareManager() {
1910
-		return $this->query('ShareManager');
1911
-	}
1912
-
1913
-	/**
1914
-	 * @return \OCP\Collaboration\Collaborators\ISearch
1915
-	 */
1916
-	public function getCollaboratorSearch() {
1917
-		return $this->query('CollaboratorSearch');
1918
-	}
1919
-
1920
-	/**
1921
-	 * @return \OCP\Collaboration\AutoComplete\IManager
1922
-	 */
1923
-	public function getAutoCompleteManager(){
1924
-		return $this->query(IManager::class);
1925
-	}
1926
-
1927
-	/**
1928
-	 * Returns the LDAP Provider
1929
-	 *
1930
-	 * @return \OCP\LDAP\ILDAPProvider
1931
-	 */
1932
-	public function getLDAPProvider() {
1933
-		return $this->query('LDAPProvider');
1934
-	}
1935
-
1936
-	/**
1937
-	 * @return \OCP\Settings\IManager
1938
-	 */
1939
-	public function getSettingsManager() {
1940
-		return $this->query('SettingsManager');
1941
-	}
1942
-
1943
-	/**
1944
-	 * @return \OCP\Files\IAppData
1945
-	 */
1946
-	public function getAppDataDir($app) {
1947
-		/** @var \OC\Files\AppData\Factory $factory */
1948
-		$factory = $this->query(\OC\Files\AppData\Factory::class);
1949
-		return $factory->get($app);
1950
-	}
1951
-
1952
-	/**
1953
-	 * @return \OCP\Lockdown\ILockdownManager
1954
-	 */
1955
-	public function getLockdownManager() {
1956
-		return $this->query('LockdownManager');
1957
-	}
1958
-
1959
-	/**
1960
-	 * @return \OCP\Federation\ICloudIdManager
1961
-	 */
1962
-	public function getCloudIdManager() {
1963
-		return $this->query(ICloudIdManager::class);
1964
-	}
1965
-
1966
-	/**
1967
-	 * @return \OCP\Remote\Api\IApiFactory
1968
-	 */
1969
-	public function getRemoteApiFactory() {
1970
-		return $this->query(IApiFactory::class);
1971
-	}
1972
-
1973
-	/**
1974
-	 * @return \OCP\Remote\IInstanceFactory
1975
-	 */
1976
-	public function getRemoteInstanceFactory() {
1977
-		return $this->query(IInstanceFactory::class);
1978
-	}
934
+            $prefixes = \OC::$composerAutoloader->getPrefixesPsr4();
935
+            if (isset($prefixes['OCA\\Theming\\'])) {
936
+                $classExists = true;
937
+            } else {
938
+                $classExists = false;
939
+            }
940
+
941
+            if ($classExists && $c->getConfig()->getSystemValue('installed', false) && $c->getAppManager()->isInstalled('theming') && $c->getTrustedDomainHelper()->isTrustedDomain($c->getRequest()->getInsecureServerHost())) {
942
+                return new ThemingDefaults(
943
+                    $c->getConfig(),
944
+                    $c->getL10N('theming'),
945
+                    $c->getURLGenerator(),
946
+                    $c->getAppDataDir('theming'),
947
+                    $c->getMemCacheFactory(),
948
+                    new Util($c->getConfig(), $this->getAppManager(), $this->getAppDataDir('theming')),
949
+                    $this->getAppManager()
950
+                );
951
+            }
952
+            return new \OC_Defaults();
953
+        });
954
+        $this->registerService(SCSSCacher::class, function (Server $c) {
955
+            /** @var Factory $cacheFactory */
956
+            $cacheFactory = $c->query(Factory::class);
957
+            return new SCSSCacher(
958
+                $c->getLogger(),
959
+                $c->query(\OC\Files\AppData\Factory::class),
960
+                $c->getURLGenerator(),
961
+                $c->getConfig(),
962
+                $c->getThemingDefaults(),
963
+                \OC::$SERVERROOT,
964
+                $cacheFactory->createDistributed('SCSS')
965
+            );
966
+        });
967
+        $this->registerService(EventDispatcher::class, function () {
968
+            return new EventDispatcher();
969
+        });
970
+        $this->registerAlias('EventDispatcher', EventDispatcher::class);
971
+        $this->registerAlias(EventDispatcherInterface::class, EventDispatcher::class);
972
+
973
+        $this->registerService('CryptoWrapper', function (Server $c) {
974
+            // FIXME: Instantiiated here due to cyclic dependency
975
+            $request = new Request(
976
+                [
977
+                    'get' => $_GET,
978
+                    'post' => $_POST,
979
+                    'files' => $_FILES,
980
+                    'server' => $_SERVER,
981
+                    'env' => $_ENV,
982
+                    'cookies' => $_COOKIE,
983
+                    'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
984
+                        ? $_SERVER['REQUEST_METHOD']
985
+                        : null,
986
+                ],
987
+                $c->getSecureRandom(),
988
+                $c->getConfig()
989
+            );
990
+
991
+            return new CryptoWrapper(
992
+                $c->getConfig(),
993
+                $c->getCrypto(),
994
+                $c->getSecureRandom(),
995
+                $request
996
+            );
997
+        });
998
+        $this->registerService('CsrfTokenManager', function (Server $c) {
999
+            $tokenGenerator = new CsrfTokenGenerator($c->getSecureRandom());
1000
+
1001
+            return new CsrfTokenManager(
1002
+                $tokenGenerator,
1003
+                $c->query(SessionStorage::class)
1004
+            );
1005
+        });
1006
+        $this->registerService(SessionStorage::class, function (Server $c) {
1007
+            return new SessionStorage($c->getSession());
1008
+        });
1009
+        $this->registerService(\OCP\Security\IContentSecurityPolicyManager::class, function (Server $c) {
1010
+            return new ContentSecurityPolicyManager();
1011
+        });
1012
+        $this->registerAlias('ContentSecurityPolicyManager', \OCP\Security\IContentSecurityPolicyManager::class);
1013
+
1014
+        $this->registerService('ContentSecurityPolicyNonceManager', function (Server $c) {
1015
+            return new ContentSecurityPolicyNonceManager(
1016
+                $c->getCsrfTokenManager(),
1017
+                $c->getRequest()
1018
+            );
1019
+        });
1020
+
1021
+        $this->registerService(\OCP\Share\IManager::class, function (Server $c) {
1022
+            $config = $c->getConfig();
1023
+            $factoryClass = $config->getSystemValue('sharing.managerFactory', '\OC\Share20\ProviderFactory');
1024
+            /** @var \OCP\Share\IProviderFactory $factory */
1025
+            $factory = new $factoryClass($this);
1026
+
1027
+            $manager = new \OC\Share20\Manager(
1028
+                $c->getLogger(),
1029
+                $c->getConfig(),
1030
+                $c->getSecureRandom(),
1031
+                $c->getHasher(),
1032
+                $c->getMountManager(),
1033
+                $c->getGroupManager(),
1034
+                $c->getL10N('lib'),
1035
+                $c->getL10NFactory(),
1036
+                $factory,
1037
+                $c->getUserManager(),
1038
+                $c->getLazyRootFolder(),
1039
+                $c->getEventDispatcher(),
1040
+                $c->getMailer(),
1041
+                $c->getURLGenerator(),
1042
+                $c->getThemingDefaults()
1043
+            );
1044
+
1045
+            return $manager;
1046
+        });
1047
+        $this->registerAlias('ShareManager', \OCP\Share\IManager::class);
1048
+
1049
+        $this->registerService(\OCP\Collaboration\Collaborators\ISearch::class, function(Server $c) {
1050
+            $instance = new Collaboration\Collaborators\Search($c);
1051
+
1052
+            // register default plugins
1053
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_USER', 'class' => UserPlugin::class]);
1054
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_GROUP', 'class' => GroupPlugin::class]);
1055
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_EMAIL', 'class' => MailPlugin::class]);
1056
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_REMOTE', 'class' => RemotePlugin::class]);
1057
+
1058
+            return $instance;
1059
+        });
1060
+        $this->registerAlias('CollaboratorSearch', \OCP\Collaboration\Collaborators\ISearch::class);
1061
+
1062
+        $this->registerAlias(\OCP\Collaboration\AutoComplete\IManager::class, \OC\Collaboration\AutoComplete\Manager::class);
1063
+
1064
+        $this->registerService('SettingsManager', function (Server $c) {
1065
+            $manager = new \OC\Settings\Manager(
1066
+                $c->getLogger(),
1067
+                $c->getDatabaseConnection(),
1068
+                $c->getL10N('lib'),
1069
+                $c->getConfig(),
1070
+                $c->getEncryptionManager(),
1071
+                $c->getUserManager(),
1072
+                $c->getLockingProvider(),
1073
+                $c->getRequest(),
1074
+                new \OC\Settings\Mapper($c->getDatabaseConnection()),
1075
+                $c->getURLGenerator(),
1076
+                $c->query(AccountManager::class),
1077
+                $c->getGroupManager(),
1078
+                $c->getL10NFactory(),
1079
+                $c->getThemingDefaults(),
1080
+                $c->getAppManager()
1081
+            );
1082
+            return $manager;
1083
+        });
1084
+        $this->registerService(\OC\Files\AppData\Factory::class, function (Server $c) {
1085
+            return new \OC\Files\AppData\Factory(
1086
+                $c->getRootFolder(),
1087
+                $c->getSystemConfig()
1088
+            );
1089
+        });
1090
+
1091
+        $this->registerService('LockdownManager', function (Server $c) {
1092
+            return new LockdownManager(function () use ($c) {
1093
+                return $c->getSession();
1094
+            });
1095
+        });
1096
+
1097
+        $this->registerService(\OCP\OCS\IDiscoveryService::class, function (Server $c) {
1098
+            return new DiscoveryService($c->getMemCacheFactory(), $c->getHTTPClientService());
1099
+        });
1100
+
1101
+        $this->registerService(ICloudIdManager::class, function (Server $c) {
1102
+            return new CloudIdManager();
1103
+        });
1104
+
1105
+        $this->registerAlias(\OCP\AppFramework\Utility\IControllerMethodReflector::class, \OC\AppFramework\Utility\ControllerMethodReflector::class);
1106
+        $this->registerAlias('ControllerMethodReflector', \OCP\AppFramework\Utility\IControllerMethodReflector::class);
1107
+
1108
+        $this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
1109
+        $this->registerAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
1110
+
1111
+        $this->registerService(Defaults::class, function (Server $c) {
1112
+            return new Defaults(
1113
+                $c->getThemingDefaults()
1114
+            );
1115
+        });
1116
+        $this->registerAlias('Defaults', \OCP\Defaults::class);
1117
+
1118
+        $this->registerService(\OCP\ISession::class, function (SimpleContainer $c) {
1119
+            return $c->query(\OCP\IUserSession::class)->getSession();
1120
+        });
1121
+
1122
+        $this->registerService(IShareHelper::class, function (Server $c) {
1123
+            return new ShareHelper(
1124
+                $c->query(\OCP\Share\IManager::class)
1125
+            );
1126
+        });
1127
+
1128
+        $this->registerService(Installer::class, function(Server $c) {
1129
+            return new Installer(
1130
+                $c->getAppFetcher(),
1131
+                $c->getHTTPClientService(),
1132
+                $c->getTempManager(),
1133
+                $c->getLogger(),
1134
+                $c->getConfig()
1135
+            );
1136
+        });
1137
+
1138
+        $this->registerService(IApiFactory::class, function(Server $c) {
1139
+            return new ApiFactory($c->getHTTPClientService());
1140
+        });
1141
+
1142
+        $this->registerService(IInstanceFactory::class, function(Server $c) {
1143
+            $memcacheFactory = $c->getMemCacheFactory();
1144
+            return new InstanceFactory($memcacheFactory->createLocal('remoteinstance.'), $c->getHTTPClientService());
1145
+        });
1146
+
1147
+        $this->registerService(IContactsStore::class, function(Server $c) {
1148
+            return new ContactsStore(
1149
+                $c->getContactsManager(),
1150
+                $c->getConfig(),
1151
+                $c->getUserManager(),
1152
+                $c->getGroupManager()
1153
+            );
1154
+        });
1155
+        $this->registerAlias(IContactsStore::class, ContactsStore::class);
1156
+
1157
+        $this->connectDispatcher();
1158
+    }
1159
+
1160
+    /**
1161
+     * @return \OCP\Calendar\IManager
1162
+     */
1163
+    public function getCalendarManager() {
1164
+        return $this->query('CalendarManager');
1165
+    }
1166
+
1167
+    private function connectDispatcher() {
1168
+        $dispatcher = $this->getEventDispatcher();
1169
+
1170
+        // Delete avatar on user deletion
1171
+        $dispatcher->addListener('OCP\IUser::preDelete', function(GenericEvent $e) {
1172
+            $logger = $this->getLogger();
1173
+            $manager = $this->getAvatarManager();
1174
+            /** @var IUser $user */
1175
+            $user = $e->getSubject();
1176
+
1177
+            try {
1178
+                $avatar = $manager->getAvatar($user->getUID());
1179
+                $avatar->remove();
1180
+            } catch (NotFoundException $e) {
1181
+                // no avatar to remove
1182
+            } catch (\Exception $e) {
1183
+                // Ignore exceptions
1184
+                $logger->info('Could not cleanup avatar of ' . $user->getUID());
1185
+            }
1186
+        });
1187
+
1188
+        $dispatcher->addListener('OCP\IUser::changeUser', function (GenericEvent $e) {
1189
+            $manager = $this->getAvatarManager();
1190
+            /** @var IUser $user */
1191
+            $user = $e->getSubject();
1192
+            $feature = $e->getArgument('feature');
1193
+            $oldValue = $e->getArgument('oldValue');
1194
+            $value = $e->getArgument('value');
1195
+
1196
+            try {
1197
+                $avatar = $manager->getAvatar($user->getUID());
1198
+                $avatar->userChanged($feature, $oldValue, $value);
1199
+            } catch (NotFoundException $e) {
1200
+                // no avatar to remove
1201
+            }
1202
+        });
1203
+    }
1204
+
1205
+    /**
1206
+     * @return \OCP\Contacts\IManager
1207
+     */
1208
+    public function getContactsManager() {
1209
+        return $this->query('ContactsManager');
1210
+    }
1211
+
1212
+    /**
1213
+     * @return \OC\Encryption\Manager
1214
+     */
1215
+    public function getEncryptionManager() {
1216
+        return $this->query('EncryptionManager');
1217
+    }
1218
+
1219
+    /**
1220
+     * @return \OC\Encryption\File
1221
+     */
1222
+    public function getEncryptionFilesHelper() {
1223
+        return $this->query('EncryptionFileHelper');
1224
+    }
1225
+
1226
+    /**
1227
+     * @return \OCP\Encryption\Keys\IStorage
1228
+     */
1229
+    public function getEncryptionKeyStorage() {
1230
+        return $this->query('EncryptionKeyStorage');
1231
+    }
1232
+
1233
+    /**
1234
+     * The current request object holding all information about the request
1235
+     * currently being processed is returned from this method.
1236
+     * In case the current execution was not initiated by a web request null is returned
1237
+     *
1238
+     * @return \OCP\IRequest
1239
+     */
1240
+    public function getRequest() {
1241
+        return $this->query('Request');
1242
+    }
1243
+
1244
+    /**
1245
+     * Returns the preview manager which can create preview images for a given file
1246
+     *
1247
+     * @return \OCP\IPreview
1248
+     */
1249
+    public function getPreviewManager() {
1250
+        return $this->query('PreviewManager');
1251
+    }
1252
+
1253
+    /**
1254
+     * Returns the tag manager which can get and set tags for different object types
1255
+     *
1256
+     * @see \OCP\ITagManager::load()
1257
+     * @return \OCP\ITagManager
1258
+     */
1259
+    public function getTagManager() {
1260
+        return $this->query('TagManager');
1261
+    }
1262
+
1263
+    /**
1264
+     * Returns the system-tag manager
1265
+     *
1266
+     * @return \OCP\SystemTag\ISystemTagManager
1267
+     *
1268
+     * @since 9.0.0
1269
+     */
1270
+    public function getSystemTagManager() {
1271
+        return $this->query('SystemTagManager');
1272
+    }
1273
+
1274
+    /**
1275
+     * Returns the system-tag object mapper
1276
+     *
1277
+     * @return \OCP\SystemTag\ISystemTagObjectMapper
1278
+     *
1279
+     * @since 9.0.0
1280
+     */
1281
+    public function getSystemTagObjectMapper() {
1282
+        return $this->query('SystemTagObjectMapper');
1283
+    }
1284
+
1285
+    /**
1286
+     * Returns the avatar manager, used for avatar functionality
1287
+     *
1288
+     * @return \OCP\IAvatarManager
1289
+     */
1290
+    public function getAvatarManager() {
1291
+        return $this->query('AvatarManager');
1292
+    }
1293
+
1294
+    /**
1295
+     * Returns the root folder of ownCloud's data directory
1296
+     *
1297
+     * @return \OCP\Files\IRootFolder
1298
+     */
1299
+    public function getRootFolder() {
1300
+        return $this->query('LazyRootFolder');
1301
+    }
1302
+
1303
+    /**
1304
+     * Returns the root folder of ownCloud's data directory
1305
+     * This is the lazy variant so this gets only initialized once it
1306
+     * is actually used.
1307
+     *
1308
+     * @return \OCP\Files\IRootFolder
1309
+     */
1310
+    public function getLazyRootFolder() {
1311
+        return $this->query('LazyRootFolder');
1312
+    }
1313
+
1314
+    /**
1315
+     * Returns a view to ownCloud's files folder
1316
+     *
1317
+     * @param string $userId user ID
1318
+     * @return \OCP\Files\Folder|null
1319
+     */
1320
+    public function getUserFolder($userId = null) {
1321
+        if ($userId === null) {
1322
+            $user = $this->getUserSession()->getUser();
1323
+            if (!$user) {
1324
+                return null;
1325
+            }
1326
+            $userId = $user->getUID();
1327
+        }
1328
+        $root = $this->getRootFolder();
1329
+        return $root->getUserFolder($userId);
1330
+    }
1331
+
1332
+    /**
1333
+     * Returns an app-specific view in ownClouds data directory
1334
+     *
1335
+     * @return \OCP\Files\Folder
1336
+     * @deprecated since 9.2.0 use IAppData
1337
+     */
1338
+    public function getAppFolder() {
1339
+        $dir = '/' . \OC_App::getCurrentApp();
1340
+        $root = $this->getRootFolder();
1341
+        if (!$root->nodeExists($dir)) {
1342
+            $folder = $root->newFolder($dir);
1343
+        } else {
1344
+            $folder = $root->get($dir);
1345
+        }
1346
+        return $folder;
1347
+    }
1348
+
1349
+    /**
1350
+     * @return \OC\User\Manager
1351
+     */
1352
+    public function getUserManager() {
1353
+        return $this->query('UserManager');
1354
+    }
1355
+
1356
+    /**
1357
+     * @return \OC\Group\Manager
1358
+     */
1359
+    public function getGroupManager() {
1360
+        return $this->query('GroupManager');
1361
+    }
1362
+
1363
+    /**
1364
+     * @return \OC\User\Session
1365
+     */
1366
+    public function getUserSession() {
1367
+        return $this->query('UserSession');
1368
+    }
1369
+
1370
+    /**
1371
+     * @return \OCP\ISession
1372
+     */
1373
+    public function getSession() {
1374
+        return $this->query('UserSession')->getSession();
1375
+    }
1376
+
1377
+    /**
1378
+     * @param \OCP\ISession $session
1379
+     */
1380
+    public function setSession(\OCP\ISession $session) {
1381
+        $this->query(SessionStorage::class)->setSession($session);
1382
+        $this->query('UserSession')->setSession($session);
1383
+        $this->query(Store::class)->setSession($session);
1384
+    }
1385
+
1386
+    /**
1387
+     * @return \OC\Authentication\TwoFactorAuth\Manager
1388
+     */
1389
+    public function getTwoFactorAuthManager() {
1390
+        return $this->query('\OC\Authentication\TwoFactorAuth\Manager');
1391
+    }
1392
+
1393
+    /**
1394
+     * @return \OC\NavigationManager
1395
+     */
1396
+    public function getNavigationManager() {
1397
+        return $this->query('NavigationManager');
1398
+    }
1399
+
1400
+    /**
1401
+     * @return \OCP\IConfig
1402
+     */
1403
+    public function getConfig() {
1404
+        return $this->query('AllConfig');
1405
+    }
1406
+
1407
+    /**
1408
+     * @return \OC\SystemConfig
1409
+     */
1410
+    public function getSystemConfig() {
1411
+        return $this->query('SystemConfig');
1412
+    }
1413
+
1414
+    /**
1415
+     * Returns the app config manager
1416
+     *
1417
+     * @return \OCP\IAppConfig
1418
+     */
1419
+    public function getAppConfig() {
1420
+        return $this->query('AppConfig');
1421
+    }
1422
+
1423
+    /**
1424
+     * @return \OCP\L10N\IFactory
1425
+     */
1426
+    public function getL10NFactory() {
1427
+        return $this->query('L10NFactory');
1428
+    }
1429
+
1430
+    /**
1431
+     * get an L10N instance
1432
+     *
1433
+     * @param string $app appid
1434
+     * @param string $lang
1435
+     * @return IL10N
1436
+     */
1437
+    public function getL10N($app, $lang = null) {
1438
+        return $this->getL10NFactory()->get($app, $lang);
1439
+    }
1440
+
1441
+    /**
1442
+     * @return \OCP\IURLGenerator
1443
+     */
1444
+    public function getURLGenerator() {
1445
+        return $this->query('URLGenerator');
1446
+    }
1447
+
1448
+    /**
1449
+     * @return \OCP\IHelper
1450
+     */
1451
+    public function getHelper() {
1452
+        return $this->query('AppHelper');
1453
+    }
1454
+
1455
+    /**
1456
+     * @return AppFetcher
1457
+     */
1458
+    public function getAppFetcher() {
1459
+        return $this->query(AppFetcher::class);
1460
+    }
1461
+
1462
+    /**
1463
+     * Returns an ICache instance. Since 8.1.0 it returns a fake cache. Use
1464
+     * getMemCacheFactory() instead.
1465
+     *
1466
+     * @return \OCP\ICache
1467
+     * @deprecated 8.1.0 use getMemCacheFactory to obtain a proper cache
1468
+     */
1469
+    public function getCache() {
1470
+        return $this->query('UserCache');
1471
+    }
1472
+
1473
+    /**
1474
+     * Returns an \OCP\CacheFactory instance
1475
+     *
1476
+     * @return \OCP\ICacheFactory
1477
+     */
1478
+    public function getMemCacheFactory() {
1479
+        return $this->query('MemCacheFactory');
1480
+    }
1481
+
1482
+    /**
1483
+     * Returns an \OC\RedisFactory instance
1484
+     *
1485
+     * @return \OC\RedisFactory
1486
+     */
1487
+    public function getGetRedisFactory() {
1488
+        return $this->query('RedisFactory');
1489
+    }
1490
+
1491
+
1492
+    /**
1493
+     * Returns the current session
1494
+     *
1495
+     * @return \OCP\IDBConnection
1496
+     */
1497
+    public function getDatabaseConnection() {
1498
+        return $this->query('DatabaseConnection');
1499
+    }
1500
+
1501
+    /**
1502
+     * Returns the activity manager
1503
+     *
1504
+     * @return \OCP\Activity\IManager
1505
+     */
1506
+    public function getActivityManager() {
1507
+        return $this->query('ActivityManager');
1508
+    }
1509
+
1510
+    /**
1511
+     * Returns an job list for controlling background jobs
1512
+     *
1513
+     * @return \OCP\BackgroundJob\IJobList
1514
+     */
1515
+    public function getJobList() {
1516
+        return $this->query('JobList');
1517
+    }
1518
+
1519
+    /**
1520
+     * Returns a logger instance
1521
+     *
1522
+     * @return \OCP\ILogger
1523
+     */
1524
+    public function getLogger() {
1525
+        return $this->query('Logger');
1526
+    }
1527
+
1528
+    /**
1529
+     * Returns a router for generating and matching urls
1530
+     *
1531
+     * @return \OCP\Route\IRouter
1532
+     */
1533
+    public function getRouter() {
1534
+        return $this->query('Router');
1535
+    }
1536
+
1537
+    /**
1538
+     * Returns a search instance
1539
+     *
1540
+     * @return \OCP\ISearch
1541
+     */
1542
+    public function getSearch() {
1543
+        return $this->query('Search');
1544
+    }
1545
+
1546
+    /**
1547
+     * Returns a SecureRandom instance
1548
+     *
1549
+     * @return \OCP\Security\ISecureRandom
1550
+     */
1551
+    public function getSecureRandom() {
1552
+        return $this->query('SecureRandom');
1553
+    }
1554
+
1555
+    /**
1556
+     * Returns a Crypto instance
1557
+     *
1558
+     * @return \OCP\Security\ICrypto
1559
+     */
1560
+    public function getCrypto() {
1561
+        return $this->query('Crypto');
1562
+    }
1563
+
1564
+    /**
1565
+     * Returns a Hasher instance
1566
+     *
1567
+     * @return \OCP\Security\IHasher
1568
+     */
1569
+    public function getHasher() {
1570
+        return $this->query('Hasher');
1571
+    }
1572
+
1573
+    /**
1574
+     * Returns a CredentialsManager instance
1575
+     *
1576
+     * @return \OCP\Security\ICredentialsManager
1577
+     */
1578
+    public function getCredentialsManager() {
1579
+        return $this->query('CredentialsManager');
1580
+    }
1581
+
1582
+    /**
1583
+     * Returns an instance of the HTTP helper class
1584
+     *
1585
+     * @deprecated Use getHTTPClientService()
1586
+     * @return \OC\HTTPHelper
1587
+     */
1588
+    public function getHTTPHelper() {
1589
+        return $this->query('HTTPHelper');
1590
+    }
1591
+
1592
+    /**
1593
+     * Get the certificate manager for the user
1594
+     *
1595
+     * @param string $userId (optional) if not specified the current loggedin user is used, use null to get the system certificate manager
1596
+     * @return \OCP\ICertificateManager | null if $uid is null and no user is logged in
1597
+     */
1598
+    public function getCertificateManager($userId = '') {
1599
+        if ($userId === '') {
1600
+            $userSession = $this->getUserSession();
1601
+            $user = $userSession->getUser();
1602
+            if (is_null($user)) {
1603
+                return null;
1604
+            }
1605
+            $userId = $user->getUID();
1606
+        }
1607
+        return new CertificateManager(
1608
+            $userId,
1609
+            new View(),
1610
+            $this->getConfig(),
1611
+            $this->getLogger(),
1612
+            $this->getSecureRandom()
1613
+        );
1614
+    }
1615
+
1616
+    /**
1617
+     * Returns an instance of the HTTP client service
1618
+     *
1619
+     * @return \OCP\Http\Client\IClientService
1620
+     */
1621
+    public function getHTTPClientService() {
1622
+        return $this->query('HttpClientService');
1623
+    }
1624
+
1625
+    /**
1626
+     * Create a new event source
1627
+     *
1628
+     * @return \OCP\IEventSource
1629
+     */
1630
+    public function createEventSource() {
1631
+        return new \OC_EventSource();
1632
+    }
1633
+
1634
+    /**
1635
+     * Get the active event logger
1636
+     *
1637
+     * The returned logger only logs data when debug mode is enabled
1638
+     *
1639
+     * @return \OCP\Diagnostics\IEventLogger
1640
+     */
1641
+    public function getEventLogger() {
1642
+        return $this->query('EventLogger');
1643
+    }
1644
+
1645
+    /**
1646
+     * Get the active query logger
1647
+     *
1648
+     * The returned logger only logs data when debug mode is enabled
1649
+     *
1650
+     * @return \OCP\Diagnostics\IQueryLogger
1651
+     */
1652
+    public function getQueryLogger() {
1653
+        return $this->query('QueryLogger');
1654
+    }
1655
+
1656
+    /**
1657
+     * Get the manager for temporary files and folders
1658
+     *
1659
+     * @return \OCP\ITempManager
1660
+     */
1661
+    public function getTempManager() {
1662
+        return $this->query('TempManager');
1663
+    }
1664
+
1665
+    /**
1666
+     * Get the app manager
1667
+     *
1668
+     * @return \OCP\App\IAppManager
1669
+     */
1670
+    public function getAppManager() {
1671
+        return $this->query('AppManager');
1672
+    }
1673
+
1674
+    /**
1675
+     * Creates a new mailer
1676
+     *
1677
+     * @return \OCP\Mail\IMailer
1678
+     */
1679
+    public function getMailer() {
1680
+        return $this->query('Mailer');
1681
+    }
1682
+
1683
+    /**
1684
+     * Get the webroot
1685
+     *
1686
+     * @return string
1687
+     */
1688
+    public function getWebRoot() {
1689
+        return $this->webRoot;
1690
+    }
1691
+
1692
+    /**
1693
+     * @return \OC\OCSClient
1694
+     */
1695
+    public function getOcsClient() {
1696
+        return $this->query('OcsClient');
1697
+    }
1698
+
1699
+    /**
1700
+     * @return \OCP\IDateTimeZone
1701
+     */
1702
+    public function getDateTimeZone() {
1703
+        return $this->query('DateTimeZone');
1704
+    }
1705
+
1706
+    /**
1707
+     * @return \OCP\IDateTimeFormatter
1708
+     */
1709
+    public function getDateTimeFormatter() {
1710
+        return $this->query('DateTimeFormatter');
1711
+    }
1712
+
1713
+    /**
1714
+     * @return \OCP\Files\Config\IMountProviderCollection
1715
+     */
1716
+    public function getMountProviderCollection() {
1717
+        return $this->query('MountConfigManager');
1718
+    }
1719
+
1720
+    /**
1721
+     * Get the IniWrapper
1722
+     *
1723
+     * @return IniGetWrapper
1724
+     */
1725
+    public function getIniWrapper() {
1726
+        return $this->query('IniWrapper');
1727
+    }
1728
+
1729
+    /**
1730
+     * @return \OCP\Command\IBus
1731
+     */
1732
+    public function getCommandBus() {
1733
+        return $this->query('AsyncCommandBus');
1734
+    }
1735
+
1736
+    /**
1737
+     * Get the trusted domain helper
1738
+     *
1739
+     * @return TrustedDomainHelper
1740
+     */
1741
+    public function getTrustedDomainHelper() {
1742
+        return $this->query('TrustedDomainHelper');
1743
+    }
1744
+
1745
+    /**
1746
+     * Get the locking provider
1747
+     *
1748
+     * @return \OCP\Lock\ILockingProvider
1749
+     * @since 8.1.0
1750
+     */
1751
+    public function getLockingProvider() {
1752
+        return $this->query('LockingProvider');
1753
+    }
1754
+
1755
+    /**
1756
+     * @return \OCP\Files\Mount\IMountManager
1757
+     **/
1758
+    function getMountManager() {
1759
+        return $this->query('MountManager');
1760
+    }
1761
+
1762
+    /** @return \OCP\Files\Config\IUserMountCache */
1763
+    function getUserMountCache() {
1764
+        return $this->query('UserMountCache');
1765
+    }
1766
+
1767
+    /**
1768
+     * Get the MimeTypeDetector
1769
+     *
1770
+     * @return \OCP\Files\IMimeTypeDetector
1771
+     */
1772
+    public function getMimeTypeDetector() {
1773
+        return $this->query('MimeTypeDetector');
1774
+    }
1775
+
1776
+    /**
1777
+     * Get the MimeTypeLoader
1778
+     *
1779
+     * @return \OCP\Files\IMimeTypeLoader
1780
+     */
1781
+    public function getMimeTypeLoader() {
1782
+        return $this->query('MimeTypeLoader');
1783
+    }
1784
+
1785
+    /**
1786
+     * Get the manager of all the capabilities
1787
+     *
1788
+     * @return \OC\CapabilitiesManager
1789
+     */
1790
+    public function getCapabilitiesManager() {
1791
+        return $this->query('CapabilitiesManager');
1792
+    }
1793
+
1794
+    /**
1795
+     * Get the EventDispatcher
1796
+     *
1797
+     * @return EventDispatcherInterface
1798
+     * @since 8.2.0
1799
+     */
1800
+    public function getEventDispatcher() {
1801
+        return $this->query('EventDispatcher');
1802
+    }
1803
+
1804
+    /**
1805
+     * Get the Notification Manager
1806
+     *
1807
+     * @return \OCP\Notification\IManager
1808
+     * @since 8.2.0
1809
+     */
1810
+    public function getNotificationManager() {
1811
+        return $this->query('NotificationManager');
1812
+    }
1813
+
1814
+    /**
1815
+     * @return \OCP\Comments\ICommentsManager
1816
+     */
1817
+    public function getCommentsManager() {
1818
+        return $this->query('CommentsManager');
1819
+    }
1820
+
1821
+    /**
1822
+     * @return \OCA\Theming\ThemingDefaults
1823
+     */
1824
+    public function getThemingDefaults() {
1825
+        return $this->query('ThemingDefaults');
1826
+    }
1827
+
1828
+    /**
1829
+     * @return \OC\IntegrityCheck\Checker
1830
+     */
1831
+    public function getIntegrityCodeChecker() {
1832
+        return $this->query('IntegrityCodeChecker');
1833
+    }
1834
+
1835
+    /**
1836
+     * @return \OC\Session\CryptoWrapper
1837
+     */
1838
+    public function getSessionCryptoWrapper() {
1839
+        return $this->query('CryptoWrapper');
1840
+    }
1841
+
1842
+    /**
1843
+     * @return CsrfTokenManager
1844
+     */
1845
+    public function getCsrfTokenManager() {
1846
+        return $this->query('CsrfTokenManager');
1847
+    }
1848
+
1849
+    /**
1850
+     * @return Throttler
1851
+     */
1852
+    public function getBruteForceThrottler() {
1853
+        return $this->query('Throttler');
1854
+    }
1855
+
1856
+    /**
1857
+     * @return IContentSecurityPolicyManager
1858
+     */
1859
+    public function getContentSecurityPolicyManager() {
1860
+        return $this->query('ContentSecurityPolicyManager');
1861
+    }
1862
+
1863
+    /**
1864
+     * @return ContentSecurityPolicyNonceManager
1865
+     */
1866
+    public function getContentSecurityPolicyNonceManager() {
1867
+        return $this->query('ContentSecurityPolicyNonceManager');
1868
+    }
1869
+
1870
+    /**
1871
+     * Not a public API as of 8.2, wait for 9.0
1872
+     *
1873
+     * @return \OCA\Files_External\Service\BackendService
1874
+     */
1875
+    public function getStoragesBackendService() {
1876
+        return $this->query('OCA\\Files_External\\Service\\BackendService');
1877
+    }
1878
+
1879
+    /**
1880
+     * Not a public API as of 8.2, wait for 9.0
1881
+     *
1882
+     * @return \OCA\Files_External\Service\GlobalStoragesService
1883
+     */
1884
+    public function getGlobalStoragesService() {
1885
+        return $this->query('OCA\\Files_External\\Service\\GlobalStoragesService');
1886
+    }
1887
+
1888
+    /**
1889
+     * Not a public API as of 8.2, wait for 9.0
1890
+     *
1891
+     * @return \OCA\Files_External\Service\UserGlobalStoragesService
1892
+     */
1893
+    public function getUserGlobalStoragesService() {
1894
+        return $this->query('OCA\\Files_External\\Service\\UserGlobalStoragesService');
1895
+    }
1896
+
1897
+    /**
1898
+     * Not a public API as of 8.2, wait for 9.0
1899
+     *
1900
+     * @return \OCA\Files_External\Service\UserStoragesService
1901
+     */
1902
+    public function getUserStoragesService() {
1903
+        return $this->query('OCA\\Files_External\\Service\\UserStoragesService');
1904
+    }
1905
+
1906
+    /**
1907
+     * @return \OCP\Share\IManager
1908
+     */
1909
+    public function getShareManager() {
1910
+        return $this->query('ShareManager');
1911
+    }
1912
+
1913
+    /**
1914
+     * @return \OCP\Collaboration\Collaborators\ISearch
1915
+     */
1916
+    public function getCollaboratorSearch() {
1917
+        return $this->query('CollaboratorSearch');
1918
+    }
1919
+
1920
+    /**
1921
+     * @return \OCP\Collaboration\AutoComplete\IManager
1922
+     */
1923
+    public function getAutoCompleteManager(){
1924
+        return $this->query(IManager::class);
1925
+    }
1926
+
1927
+    /**
1928
+     * Returns the LDAP Provider
1929
+     *
1930
+     * @return \OCP\LDAP\ILDAPProvider
1931
+     */
1932
+    public function getLDAPProvider() {
1933
+        return $this->query('LDAPProvider');
1934
+    }
1935
+
1936
+    /**
1937
+     * @return \OCP\Settings\IManager
1938
+     */
1939
+    public function getSettingsManager() {
1940
+        return $this->query('SettingsManager');
1941
+    }
1942
+
1943
+    /**
1944
+     * @return \OCP\Files\IAppData
1945
+     */
1946
+    public function getAppDataDir($app) {
1947
+        /** @var \OC\Files\AppData\Factory $factory */
1948
+        $factory = $this->query(\OC\Files\AppData\Factory::class);
1949
+        return $factory->get($app);
1950
+    }
1951
+
1952
+    /**
1953
+     * @return \OCP\Lockdown\ILockdownManager
1954
+     */
1955
+    public function getLockdownManager() {
1956
+        return $this->query('LockdownManager');
1957
+    }
1958
+
1959
+    /**
1960
+     * @return \OCP\Federation\ICloudIdManager
1961
+     */
1962
+    public function getCloudIdManager() {
1963
+        return $this->query(ICloudIdManager::class);
1964
+    }
1965
+
1966
+    /**
1967
+     * @return \OCP\Remote\Api\IApiFactory
1968
+     */
1969
+    public function getRemoteApiFactory() {
1970
+        return $this->query(IApiFactory::class);
1971
+    }
1972
+
1973
+    /**
1974
+     * @return \OCP\Remote\IInstanceFactory
1975
+     */
1976
+    public function getRemoteInstanceFactory() {
1977
+        return $this->query(IInstanceFactory::class);
1978
+    }
1979 1979
 }
Please login to merge, or discard this patch.
Spacing   +114 added lines, -114 removed lines patch added patch discarded remove patch
@@ -157,7 +157,7 @@  discard block
 block discarded – undo
157 157
 		parent::__construct();
158 158
 		$this->webRoot = $webRoot;
159 159
 
160
-		$this->registerService(\OCP\IServerContainer::class, function (IServerContainer $c) {
160
+		$this->registerService(\OCP\IServerContainer::class, function(IServerContainer $c) {
161 161
 			return $c;
162 162
 		});
163 163
 
@@ -170,7 +170,7 @@  discard block
 block discarded – undo
170 170
 		$this->registerAlias(IActionFactory::class, ActionFactory::class);
171 171
 
172 172
 
173
-		$this->registerService(\OCP\IPreview::class, function (Server $c) {
173
+		$this->registerService(\OCP\IPreview::class, function(Server $c) {
174 174
 			return new PreviewManager(
175 175
 				$c->getConfig(),
176 176
 				$c->getRootFolder(),
@@ -181,13 +181,13 @@  discard block
 block discarded – undo
181 181
 		});
182 182
 		$this->registerAlias('PreviewManager', \OCP\IPreview::class);
183 183
 
184
-		$this->registerService(\OC\Preview\Watcher::class, function (Server $c) {
184
+		$this->registerService(\OC\Preview\Watcher::class, function(Server $c) {
185 185
 			return new \OC\Preview\Watcher(
186 186
 				$c->getAppDataDir('preview')
187 187
 			);
188 188
 		});
189 189
 
190
-		$this->registerService('EncryptionManager', function (Server $c) {
190
+		$this->registerService('EncryptionManager', function(Server $c) {
191 191
 			$view = new View();
192 192
 			$util = new Encryption\Util(
193 193
 				$view,
@@ -205,7 +205,7 @@  discard block
 block discarded – undo
205 205
 			);
206 206
 		});
207 207
 
208
-		$this->registerService('EncryptionFileHelper', function (Server $c) {
208
+		$this->registerService('EncryptionFileHelper', function(Server $c) {
209 209
 			$util = new Encryption\Util(
210 210
 				new View(),
211 211
 				$c->getUserManager(),
@@ -219,7 +219,7 @@  discard block
 block discarded – undo
219 219
 			);
220 220
 		});
221 221
 
222
-		$this->registerService('EncryptionKeyStorage', function (Server $c) {
222
+		$this->registerService('EncryptionKeyStorage', function(Server $c) {
223 223
 			$view = new View();
224 224
 			$util = new Encryption\Util(
225 225
 				$view,
@@ -230,30 +230,30 @@  discard block
 block discarded – undo
230 230
 
231 231
 			return new Encryption\Keys\Storage($view, $util);
232 232
 		});
233
-		$this->registerService('TagMapper', function (Server $c) {
233
+		$this->registerService('TagMapper', function(Server $c) {
234 234
 			return new TagMapper($c->getDatabaseConnection());
235 235
 		});
236 236
 
237
-		$this->registerService(\OCP\ITagManager::class, function (Server $c) {
237
+		$this->registerService(\OCP\ITagManager::class, function(Server $c) {
238 238
 			$tagMapper = $c->query('TagMapper');
239 239
 			return new TagManager($tagMapper, $c->getUserSession());
240 240
 		});
241 241
 		$this->registerAlias('TagManager', \OCP\ITagManager::class);
242 242
 
243
-		$this->registerService('SystemTagManagerFactory', function (Server $c) {
243
+		$this->registerService('SystemTagManagerFactory', function(Server $c) {
244 244
 			$config = $c->getConfig();
245 245
 			$factoryClass = $config->getSystemValue('systemtags.managerFactory', '\OC\SystemTag\ManagerFactory');
246 246
 			return new $factoryClass($this);
247 247
 		});
248
-		$this->registerService(\OCP\SystemTag\ISystemTagManager::class, function (Server $c) {
248
+		$this->registerService(\OCP\SystemTag\ISystemTagManager::class, function(Server $c) {
249 249
 			return $c->query('SystemTagManagerFactory')->getManager();
250 250
 		});
251 251
 		$this->registerAlias('SystemTagManager', \OCP\SystemTag\ISystemTagManager::class);
252 252
 
253
-		$this->registerService(\OCP\SystemTag\ISystemTagObjectMapper::class, function (Server $c) {
253
+		$this->registerService(\OCP\SystemTag\ISystemTagObjectMapper::class, function(Server $c) {
254 254
 			return $c->query('SystemTagManagerFactory')->getObjectMapper();
255 255
 		});
256
-		$this->registerService('RootFolder', function (Server $c) {
256
+		$this->registerService('RootFolder', function(Server $c) {
257 257
 			$manager = \OC\Files\Filesystem::getMountManager(null);
258 258
 			$view = new View();
259 259
 			$root = new Root(
@@ -274,38 +274,38 @@  discard block
 block discarded – undo
274 274
 		});
275 275
 		$this->registerAlias('SystemTagObjectMapper', \OCP\SystemTag\ISystemTagObjectMapper::class);
276 276
 
277
-		$this->registerService(\OCP\Files\IRootFolder::class, function (Server $c) {
278
-			return new LazyRoot(function () use ($c) {
277
+		$this->registerService(\OCP\Files\IRootFolder::class, function(Server $c) {
278
+			return new LazyRoot(function() use ($c) {
279 279
 				return $c->query('RootFolder');
280 280
 			});
281 281
 		});
282 282
 		$this->registerAlias('LazyRootFolder', \OCP\Files\IRootFolder::class);
283 283
 
284
-		$this->registerService(\OC\User\Manager::class, function (Server $c) {
284
+		$this->registerService(\OC\User\Manager::class, function(Server $c) {
285 285
 			$config = $c->getConfig();
286 286
 			return new \OC\User\Manager($config);
287 287
 		});
288 288
 		$this->registerAlias('UserManager', \OC\User\Manager::class);
289 289
 		$this->registerAlias(\OCP\IUserManager::class, \OC\User\Manager::class);
290 290
 
291
-		$this->registerService(\OCP\IGroupManager::class, function (Server $c) {
291
+		$this->registerService(\OCP\IGroupManager::class, function(Server $c) {
292 292
 			$groupManager = new \OC\Group\Manager($this->getUserManager(), $this->getLogger());
293
-			$groupManager->listen('\OC\Group', 'preCreate', function ($gid) {
293
+			$groupManager->listen('\OC\Group', 'preCreate', function($gid) {
294 294
 				\OC_Hook::emit('OC_Group', 'pre_createGroup', array('run' => true, 'gid' => $gid));
295 295
 			});
296
-			$groupManager->listen('\OC\Group', 'postCreate', function (\OC\Group\Group $gid) {
296
+			$groupManager->listen('\OC\Group', 'postCreate', function(\OC\Group\Group $gid) {
297 297
 				\OC_Hook::emit('OC_User', 'post_createGroup', array('gid' => $gid->getGID()));
298 298
 			});
299
-			$groupManager->listen('\OC\Group', 'preDelete', function (\OC\Group\Group $group) {
299
+			$groupManager->listen('\OC\Group', 'preDelete', function(\OC\Group\Group $group) {
300 300
 				\OC_Hook::emit('OC_Group', 'pre_deleteGroup', array('run' => true, 'gid' => $group->getGID()));
301 301
 			});
302
-			$groupManager->listen('\OC\Group', 'postDelete', function (\OC\Group\Group $group) {
302
+			$groupManager->listen('\OC\Group', 'postDelete', function(\OC\Group\Group $group) {
303 303
 				\OC_Hook::emit('OC_User', 'post_deleteGroup', array('gid' => $group->getGID()));
304 304
 			});
305
-			$groupManager->listen('\OC\Group', 'preAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
305
+			$groupManager->listen('\OC\Group', 'preAddUser', function(\OC\Group\Group $group, \OC\User\User $user) {
306 306
 				\OC_Hook::emit('OC_Group', 'pre_addToGroup', array('run' => true, 'uid' => $user->getUID(), 'gid' => $group->getGID()));
307 307
 			});
308
-			$groupManager->listen('\OC\Group', 'postAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
308
+			$groupManager->listen('\OC\Group', 'postAddUser', function(\OC\Group\Group $group, \OC\User\User $user) {
309 309
 				\OC_Hook::emit('OC_Group', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
310 310
 				//Minimal fix to keep it backward compatible TODO: clean up all the GroupManager hooks
311 311
 				\OC_Hook::emit('OC_User', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
@@ -314,7 +314,7 @@  discard block
 block discarded – undo
314 314
 		});
315 315
 		$this->registerAlias('GroupManager', \OCP\IGroupManager::class);
316 316
 
317
-		$this->registerService(Store::class, function (Server $c) {
317
+		$this->registerService(Store::class, function(Server $c) {
318 318
 			$session = $c->getSession();
319 319
 			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
320 320
 				$tokenProvider = $c->query('OC\Authentication\Token\IProvider');
@@ -325,11 +325,11 @@  discard block
 block discarded – undo
325 325
 			return new Store($session, $logger, $tokenProvider);
326 326
 		});
327 327
 		$this->registerAlias(IStore::class, Store::class);
328
-		$this->registerService('OC\Authentication\Token\DefaultTokenMapper', function (Server $c) {
328
+		$this->registerService('OC\Authentication\Token\DefaultTokenMapper', function(Server $c) {
329 329
 			$dbConnection = $c->getDatabaseConnection();
330 330
 			return new Authentication\Token\DefaultTokenMapper($dbConnection);
331 331
 		});
332
-		$this->registerService('OC\Authentication\Token\DefaultTokenProvider', function (Server $c) {
332
+		$this->registerService('OC\Authentication\Token\DefaultTokenProvider', function(Server $c) {
333 333
 			$mapper = $c->query('OC\Authentication\Token\DefaultTokenMapper');
334 334
 			$crypto = $c->getCrypto();
335 335
 			$config = $c->getConfig();
@@ -339,7 +339,7 @@  discard block
 block discarded – undo
339 339
 		});
340 340
 		$this->registerAlias('OC\Authentication\Token\IProvider', 'OC\Authentication\Token\DefaultTokenProvider');
341 341
 
342
-		$this->registerService(\OCP\IUserSession::class, function (Server $c) {
342
+		$this->registerService(\OCP\IUserSession::class, function(Server $c) {
343 343
 			$manager = $c->getUserManager();
344 344
 			$session = new \OC\Session\Memory('');
345 345
 			$timeFactory = new TimeFactory();
@@ -363,45 +363,45 @@  discard block
 block discarded – undo
363 363
 				$c->getLockdownManager(),
364 364
 				$c->getLogger()
365 365
 			);
366
-			$userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
366
+			$userSession->listen('\OC\User', 'preCreateUser', function($uid, $password) {
367 367
 				\OC_Hook::emit('OC_User', 'pre_createUser', array('run' => true, 'uid' => $uid, 'password' => $password));
368 368
 			});
369
-			$userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
369
+			$userSession->listen('\OC\User', 'postCreateUser', function($user, $password) {
370 370
 				/** @var $user \OC\User\User */
371 371
 				\OC_Hook::emit('OC_User', 'post_createUser', array('uid' => $user->getUID(), 'password' => $password));
372 372
 			});
373
-			$userSession->listen('\OC\User', 'preDelete', function ($user) use ($dispatcher) {
373
+			$userSession->listen('\OC\User', 'preDelete', function($user) use ($dispatcher) {
374 374
 				/** @var $user \OC\User\User */
375 375
 				\OC_Hook::emit('OC_User', 'pre_deleteUser', array('run' => true, 'uid' => $user->getUID()));
376 376
 				$dispatcher->dispatch('OCP\IUser::preDelete', new GenericEvent($user));
377 377
 			});
378
-			$userSession->listen('\OC\User', 'postDelete', function ($user) {
378
+			$userSession->listen('\OC\User', 'postDelete', function($user) {
379 379
 				/** @var $user \OC\User\User */
380 380
 				\OC_Hook::emit('OC_User', 'post_deleteUser', array('uid' => $user->getUID()));
381 381
 			});
382
-			$userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
382
+			$userSession->listen('\OC\User', 'preSetPassword', function($user, $password, $recoveryPassword) {
383 383
 				/** @var $user \OC\User\User */
384 384
 				\OC_Hook::emit('OC_User', 'pre_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
385 385
 			});
386
-			$userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
386
+			$userSession->listen('\OC\User', 'postSetPassword', function($user, $password, $recoveryPassword) {
387 387
 				/** @var $user \OC\User\User */
388 388
 				\OC_Hook::emit('OC_User', 'post_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
389 389
 			});
390
-			$userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
390
+			$userSession->listen('\OC\User', 'preLogin', function($uid, $password) {
391 391
 				\OC_Hook::emit('OC_User', 'pre_login', array('run' => true, 'uid' => $uid, 'password' => $password));
392 392
 			});
393
-			$userSession->listen('\OC\User', 'postLogin', function ($user, $password) {
393
+			$userSession->listen('\OC\User', 'postLogin', function($user, $password) {
394 394
 				/** @var $user \OC\User\User */
395 395
 				\OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
396 396
 			});
397
-			$userSession->listen('\OC\User', 'postRememberedLogin', function ($user, $password) {
397
+			$userSession->listen('\OC\User', 'postRememberedLogin', function($user, $password) {
398 398
 				/** @var $user \OC\User\User */
399 399
 				\OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
400 400
 			});
401
-			$userSession->listen('\OC\User', 'logout', function () {
401
+			$userSession->listen('\OC\User', 'logout', function() {
402 402
 				\OC_Hook::emit('OC_User', 'logout', array());
403 403
 			});
404
-			$userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value, $oldValue) use ($dispatcher) {
404
+			$userSession->listen('\OC\User', 'changeUser', function($user, $feature, $value, $oldValue) use ($dispatcher) {
405 405
 				/** @var $user \OC\User\User */
406 406
 				\OC_Hook::emit('OC_User', 'changeUser', array('run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value, 'old_value' => $oldValue));
407 407
 				$dispatcher->dispatch('OCP\IUser::changeUser', new GenericEvent($user, ['feature' => $feature, 'oldValue' => $oldValue, 'value' => $value]));
@@ -410,7 +410,7 @@  discard block
 block discarded – undo
410 410
 		});
411 411
 		$this->registerAlias('UserSession', \OCP\IUserSession::class);
412 412
 
413
-		$this->registerService(\OC\Authentication\TwoFactorAuth\Manager::class, function (Server $c) {
413
+		$this->registerService(\OC\Authentication\TwoFactorAuth\Manager::class, function(Server $c) {
414 414
 			return new \OC\Authentication\TwoFactorAuth\Manager(
415 415
 				$c->getAppManager(),
416 416
 				$c->getSession(),
@@ -426,7 +426,7 @@  discard block
 block discarded – undo
426 426
 		$this->registerAlias(\OCP\INavigationManager::class, \OC\NavigationManager::class);
427 427
 		$this->registerAlias('NavigationManager', \OCP\INavigationManager::class);
428 428
 
429
-		$this->registerService(\OC\AllConfig::class, function (Server $c) {
429
+		$this->registerService(\OC\AllConfig::class, function(Server $c) {
430 430
 			return new \OC\AllConfig(
431 431
 				$c->getSystemConfig()
432 432
 			);
@@ -434,17 +434,17 @@  discard block
 block discarded – undo
434 434
 		$this->registerAlias('AllConfig', \OC\AllConfig::class);
435 435
 		$this->registerAlias(\OCP\IConfig::class, \OC\AllConfig::class);
436 436
 
437
-		$this->registerService('SystemConfig', function ($c) use ($config) {
437
+		$this->registerService('SystemConfig', function($c) use ($config) {
438 438
 			return new \OC\SystemConfig($config);
439 439
 		});
440 440
 
441
-		$this->registerService(\OC\AppConfig::class, function (Server $c) {
441
+		$this->registerService(\OC\AppConfig::class, function(Server $c) {
442 442
 			return new \OC\AppConfig($c->getDatabaseConnection());
443 443
 		});
444 444
 		$this->registerAlias('AppConfig', \OC\AppConfig::class);
445 445
 		$this->registerAlias(\OCP\IAppConfig::class, \OC\AppConfig::class);
446 446
 
447
-		$this->registerService(\OCP\L10N\IFactory::class, function (Server $c) {
447
+		$this->registerService(\OCP\L10N\IFactory::class, function(Server $c) {
448 448
 			return new \OC\L10N\Factory(
449 449
 				$c->getConfig(),
450 450
 				$c->getRequest(),
@@ -454,7 +454,7 @@  discard block
 block discarded – undo
454 454
 		});
455 455
 		$this->registerAlias('L10NFactory', \OCP\L10N\IFactory::class);
456 456
 
457
-		$this->registerService(\OCP\IURLGenerator::class, function (Server $c) {
457
+		$this->registerService(\OCP\IURLGenerator::class, function(Server $c) {
458 458
 			$config = $c->getConfig();
459 459
 			$cacheFactory = $c->getMemCacheFactory();
460 460
 			$request = $c->getRequest();
@@ -466,18 +466,18 @@  discard block
 block discarded – undo
466 466
 		});
467 467
 		$this->registerAlias('URLGenerator', \OCP\IURLGenerator::class);
468 468
 
469
-		$this->registerService('AppHelper', function ($c) {
469
+		$this->registerService('AppHelper', function($c) {
470 470
 			return new \OC\AppHelper();
471 471
 		});
472 472
 		$this->registerAlias('AppFetcher', AppFetcher::class);
473 473
 		$this->registerAlias('CategoryFetcher', CategoryFetcher::class);
474 474
 
475
-		$this->registerService(\OCP\ICache::class, function ($c) {
475
+		$this->registerService(\OCP\ICache::class, function($c) {
476 476
 			return new Cache\File();
477 477
 		});
478 478
 		$this->registerAlias('UserCache', \OCP\ICache::class);
479 479
 
480
-		$this->registerService(Factory::class, function (Server $c) {
480
+		$this->registerService(Factory::class, function(Server $c) {
481 481
 
482 482
 			$arrayCacheFactory = new \OC\Memcache\Factory('', $c->getLogger(),
483 483
 				'\\OC\\Memcache\\ArrayCache',
@@ -494,7 +494,7 @@  discard block
 block discarded – undo
494 494
 				$version = implode(',', $v);
495 495
 				$instanceId = \OC_Util::getInstanceId();
496 496
 				$path = \OC::$SERVERROOT;
497
-				$prefix = md5($instanceId . '-' . $version . '-' . $path . '-' . $urlGenerator->getBaseUrl());
497
+				$prefix = md5($instanceId.'-'.$version.'-'.$path.'-'.$urlGenerator->getBaseUrl());
498 498
 				return new \OC\Memcache\Factory($prefix, $c->getLogger(),
499 499
 					$config->getSystemValue('memcache.local', null),
500 500
 					$config->getSystemValue('memcache.distributed', null),
@@ -507,12 +507,12 @@  discard block
 block discarded – undo
507 507
 		$this->registerAlias('MemCacheFactory', Factory::class);
508 508
 		$this->registerAlias(ICacheFactory::class, Factory::class);
509 509
 
510
-		$this->registerService('RedisFactory', function (Server $c) {
510
+		$this->registerService('RedisFactory', function(Server $c) {
511 511
 			$systemConfig = $c->getSystemConfig();
512 512
 			return new RedisFactory($systemConfig);
513 513
 		});
514 514
 
515
-		$this->registerService(\OCP\Activity\IManager::class, function (Server $c) {
515
+		$this->registerService(\OCP\Activity\IManager::class, function(Server $c) {
516 516
 			return new \OC\Activity\Manager(
517 517
 				$c->getRequest(),
518 518
 				$c->getUserSession(),
@@ -522,14 +522,14 @@  discard block
 block discarded – undo
522 522
 		});
523 523
 		$this->registerAlias('ActivityManager', \OCP\Activity\IManager::class);
524 524
 
525
-		$this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
525
+		$this->registerService(\OCP\Activity\IEventMerger::class, function(Server $c) {
526 526
 			return new \OC\Activity\EventMerger(
527 527
 				$c->getL10N('lib')
528 528
 			);
529 529
 		});
530 530
 		$this->registerAlias(IValidator::class, Validator::class);
531 531
 
532
-		$this->registerService(\OCP\IAvatarManager::class, function (Server $c) {
532
+		$this->registerService(\OCP\IAvatarManager::class, function(Server $c) {
533 533
 			return new AvatarManager(
534 534
 				$c->query(\OC\User\Manager::class),
535 535
 				$c->getAppDataDir('avatar'),
@@ -542,7 +542,7 @@  discard block
 block discarded – undo
542 542
 
543 543
 		$this->registerAlias(\OCP\Support\CrashReport\IRegistry::class, \OC\Support\CrashReport\Registry::class);
544 544
 
545
-		$this->registerService(\OCP\ILogger::class, function (Server $c) {
545
+		$this->registerService(\OCP\ILogger::class, function(Server $c) {
546 546
 			$logType = $c->query('AllConfig')->getSystemValue('log_type', 'file');
547 547
 			$logger = Log::getLogClass($logType);
548 548
 			call_user_func(array($logger, 'init'));
@@ -553,7 +553,7 @@  discard block
 block discarded – undo
553 553
 		});
554 554
 		$this->registerAlias('Logger', \OCP\ILogger::class);
555 555
 
556
-		$this->registerService(\OCP\BackgroundJob\IJobList::class, function (Server $c) {
556
+		$this->registerService(\OCP\BackgroundJob\IJobList::class, function(Server $c) {
557 557
 			$config = $c->getConfig();
558 558
 			return new \OC\BackgroundJob\JobList(
559 559
 				$c->getDatabaseConnection(),
@@ -563,7 +563,7 @@  discard block
 block discarded – undo
563 563
 		});
564 564
 		$this->registerAlias('JobList', \OCP\BackgroundJob\IJobList::class);
565 565
 
566
-		$this->registerService(\OCP\Route\IRouter::class, function (Server $c) {
566
+		$this->registerService(\OCP\Route\IRouter::class, function(Server $c) {
567 567
 			$cacheFactory = $c->getMemCacheFactory();
568 568
 			$logger = $c->getLogger();
569 569
 			if ($cacheFactory->isAvailableLowLatency()) {
@@ -575,12 +575,12 @@  discard block
 block discarded – undo
575 575
 		});
576 576
 		$this->registerAlias('Router', \OCP\Route\IRouter::class);
577 577
 
578
-		$this->registerService(\OCP\ISearch::class, function ($c) {
578
+		$this->registerService(\OCP\ISearch::class, function($c) {
579 579
 			return new Search();
580 580
 		});
581 581
 		$this->registerAlias('Search', \OCP\ISearch::class);
582 582
 
583
-		$this->registerService(\OC\Security\RateLimiting\Limiter::class, function ($c) {
583
+		$this->registerService(\OC\Security\RateLimiting\Limiter::class, function($c) {
584 584
 			return new \OC\Security\RateLimiting\Limiter(
585 585
 				$this->getUserSession(),
586 586
 				$this->getRequest(),
@@ -588,34 +588,34 @@  discard block
 block discarded – undo
588 588
 				$c->query(\OC\Security\RateLimiting\Backend\IBackend::class)
589 589
 			);
590 590
 		});
591
-		$this->registerService(\OC\Security\RateLimiting\Backend\IBackend::class, function ($c) {
591
+		$this->registerService(\OC\Security\RateLimiting\Backend\IBackend::class, function($c) {
592 592
 			return new \OC\Security\RateLimiting\Backend\MemoryCache(
593 593
 				$this->getMemCacheFactory(),
594 594
 				new \OC\AppFramework\Utility\TimeFactory()
595 595
 			);
596 596
 		});
597 597
 
598
-		$this->registerService(\OCP\Security\ISecureRandom::class, function ($c) {
598
+		$this->registerService(\OCP\Security\ISecureRandom::class, function($c) {
599 599
 			return new SecureRandom();
600 600
 		});
601 601
 		$this->registerAlias('SecureRandom', \OCP\Security\ISecureRandom::class);
602 602
 
603
-		$this->registerService(\OCP\Security\ICrypto::class, function (Server $c) {
603
+		$this->registerService(\OCP\Security\ICrypto::class, function(Server $c) {
604 604
 			return new Crypto($c->getConfig(), $c->getSecureRandom());
605 605
 		});
606 606
 		$this->registerAlias('Crypto', \OCP\Security\ICrypto::class);
607 607
 
608
-		$this->registerService(\OCP\Security\IHasher::class, function (Server $c) {
608
+		$this->registerService(\OCP\Security\IHasher::class, function(Server $c) {
609 609
 			return new Hasher($c->getConfig());
610 610
 		});
611 611
 		$this->registerAlias('Hasher', \OCP\Security\IHasher::class);
612 612
 
613
-		$this->registerService(\OCP\Security\ICredentialsManager::class, function (Server $c) {
613
+		$this->registerService(\OCP\Security\ICredentialsManager::class, function(Server $c) {
614 614
 			return new CredentialsManager($c->getCrypto(), $c->getDatabaseConnection());
615 615
 		});
616 616
 		$this->registerAlias('CredentialsManager', \OCP\Security\ICredentialsManager::class);
617 617
 
618
-		$this->registerService(IDBConnection::class, function (Server $c) {
618
+		$this->registerService(IDBConnection::class, function(Server $c) {
619 619
 			$systemConfig = $c->getSystemConfig();
620 620
 			$factory = new \OC\DB\ConnectionFactory($systemConfig);
621 621
 			$type = $systemConfig->getValue('dbtype', 'sqlite');
@@ -629,7 +629,7 @@  discard block
 block discarded – undo
629 629
 		});
630 630
 		$this->registerAlias('DatabaseConnection', IDBConnection::class);
631 631
 
632
-		$this->registerService('HTTPHelper', function (Server $c) {
632
+		$this->registerService('HTTPHelper', function(Server $c) {
633 633
 			$config = $c->getConfig();
634 634
 			return new HTTPHelper(
635 635
 				$config,
@@ -637,7 +637,7 @@  discard block
 block discarded – undo
637 637
 			);
638 638
 		});
639 639
 
640
-		$this->registerService(\OCP\Http\Client\IClientService::class, function (Server $c) {
640
+		$this->registerService(\OCP\Http\Client\IClientService::class, function(Server $c) {
641 641
 			$user = \OC_User::getUser();
642 642
 			$uid = $user ? $user : null;
643 643
 			return new ClientService(
@@ -652,7 +652,7 @@  discard block
 block discarded – undo
652 652
 			);
653 653
 		});
654 654
 		$this->registerAlias('HttpClientService', \OCP\Http\Client\IClientService::class);
655
-		$this->registerService(\OCP\Diagnostics\IEventLogger::class, function (Server $c) {
655
+		$this->registerService(\OCP\Diagnostics\IEventLogger::class, function(Server $c) {
656 656
 			$eventLogger = new EventLogger();
657 657
 			if ($c->getSystemConfig()->getValue('debug', false)) {
658 658
 				// In debug mode, module is being activated by default
@@ -662,7 +662,7 @@  discard block
 block discarded – undo
662 662
 		});
663 663
 		$this->registerAlias('EventLogger', \OCP\Diagnostics\IEventLogger::class);
664 664
 
665
-		$this->registerService(\OCP\Diagnostics\IQueryLogger::class, function (Server $c) {
665
+		$this->registerService(\OCP\Diagnostics\IQueryLogger::class, function(Server $c) {
666 666
 			$queryLogger = new QueryLogger();
667 667
 			if ($c->getSystemConfig()->getValue('debug', false)) {
668 668
 				// In debug mode, module is being activated by default
@@ -672,7 +672,7 @@  discard block
 block discarded – undo
672 672
 		});
673 673
 		$this->registerAlias('QueryLogger', \OCP\Diagnostics\IQueryLogger::class);
674 674
 
675
-		$this->registerService(TempManager::class, function (Server $c) {
675
+		$this->registerService(TempManager::class, function(Server $c) {
676 676
 			return new TempManager(
677 677
 				$c->getLogger(),
678 678
 				$c->getConfig()
@@ -681,7 +681,7 @@  discard block
 block discarded – undo
681 681
 		$this->registerAlias('TempManager', TempManager::class);
682 682
 		$this->registerAlias(ITempManager::class, TempManager::class);
683 683
 
684
-		$this->registerService(AppManager::class, function (Server $c) {
684
+		$this->registerService(AppManager::class, function(Server $c) {
685 685
 			return new \OC\App\AppManager(
686 686
 				$c->getUserSession(),
687 687
 				$this->getAppConfig(),
@@ -693,7 +693,7 @@  discard block
 block discarded – undo
693 693
 		$this->registerAlias('AppManager', AppManager::class);
694 694
 		$this->registerAlias(IAppManager::class, AppManager::class);
695 695
 
696
-		$this->registerService(\OCP\IDateTimeZone::class, function (Server $c) {
696
+		$this->registerService(\OCP\IDateTimeZone::class, function(Server $c) {
697 697
 			return new DateTimeZone(
698 698
 				$c->getConfig(),
699 699
 				$c->getSession()
@@ -701,7 +701,7 @@  discard block
 block discarded – undo
701 701
 		});
702 702
 		$this->registerAlias('DateTimeZone', \OCP\IDateTimeZone::class);
703 703
 
704
-		$this->registerService(\OCP\IDateTimeFormatter::class, function (Server $c) {
704
+		$this->registerService(\OCP\IDateTimeFormatter::class, function(Server $c) {
705 705
 			$language = $c->getConfig()->getUserValue($c->getSession()->get('user_id'), 'core', 'lang', null);
706 706
 
707 707
 			return new DateTimeFormatter(
@@ -711,7 +711,7 @@  discard block
 block discarded – undo
711 711
 		});
712 712
 		$this->registerAlias('DateTimeFormatter', \OCP\IDateTimeFormatter::class);
713 713
 
714
-		$this->registerService(\OCP\Files\Config\IUserMountCache::class, function (Server $c) {
714
+		$this->registerService(\OCP\Files\Config\IUserMountCache::class, function(Server $c) {
715 715
 			$mountCache = new UserMountCache($c->getDatabaseConnection(), $c->getUserManager(), $c->getLogger());
716 716
 			$listener = new UserMountCacheListener($mountCache);
717 717
 			$listener->listen($c->getUserManager());
@@ -719,7 +719,7 @@  discard block
 block discarded – undo
719 719
 		});
720 720
 		$this->registerAlias('UserMountCache', \OCP\Files\Config\IUserMountCache::class);
721 721
 
722
-		$this->registerService(\OCP\Files\Config\IMountProviderCollection::class, function (Server $c) {
722
+		$this->registerService(\OCP\Files\Config\IMountProviderCollection::class, function(Server $c) {
723 723
 			$loader = \OC\Files\Filesystem::getLoader();
724 724
 			$mountCache = $c->query('UserMountCache');
725 725
 			$manager = new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
@@ -735,10 +735,10 @@  discard block
 block discarded – undo
735 735
 		});
736 736
 		$this->registerAlias('MountConfigManager', \OCP\Files\Config\IMountProviderCollection::class);
737 737
 
738
-		$this->registerService('IniWrapper', function ($c) {
738
+		$this->registerService('IniWrapper', function($c) {
739 739
 			return new IniGetWrapper();
740 740
 		});
741
-		$this->registerService('AsyncCommandBus', function (Server $c) {
741
+		$this->registerService('AsyncCommandBus', function(Server $c) {
742 742
 			$busClass = $c->getConfig()->getSystemValue('commandbus');
743 743
 			if ($busClass) {
744 744
 				list($app, $class) = explode('::', $busClass, 2);
@@ -753,10 +753,10 @@  discard block
 block discarded – undo
753 753
 				return new CronBus($jobList);
754 754
 			}
755 755
 		});
756
-		$this->registerService('TrustedDomainHelper', function ($c) {
756
+		$this->registerService('TrustedDomainHelper', function($c) {
757 757
 			return new TrustedDomainHelper($this->getConfig());
758 758
 		});
759
-		$this->registerService('Throttler', function (Server $c) {
759
+		$this->registerService('Throttler', function(Server $c) {
760 760
 			return new Throttler(
761 761
 				$c->getDatabaseConnection(),
762 762
 				new TimeFactory(),
@@ -764,7 +764,7 @@  discard block
 block discarded – undo
764 764
 				$c->getConfig()
765 765
 			);
766 766
 		});
767
-		$this->registerService('IntegrityCodeChecker', function (Server $c) {
767
+		$this->registerService('IntegrityCodeChecker', function(Server $c) {
768 768
 			// IConfig and IAppManager requires a working database. This code
769 769
 			// might however be called when ownCloud is not yet setup.
770 770
 			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
@@ -785,7 +785,7 @@  discard block
 block discarded – undo
785 785
 				$c->getTempManager()
786 786
 			);
787 787
 		});
788
-		$this->registerService(\OCP\IRequest::class, function ($c) {
788
+		$this->registerService(\OCP\IRequest::class, function($c) {
789 789
 			if (isset($this['urlParams'])) {
790 790
 				$urlParams = $this['urlParams'];
791 791
 			} else {
@@ -821,7 +821,7 @@  discard block
 block discarded – undo
821 821
 		});
822 822
 		$this->registerAlias('Request', \OCP\IRequest::class);
823 823
 
824
-		$this->registerService(\OCP\Mail\IMailer::class, function (Server $c) {
824
+		$this->registerService(\OCP\Mail\IMailer::class, function(Server $c) {
825 825
 			return new Mailer(
826 826
 				$c->getConfig(),
827 827
 				$c->getLogger(),
@@ -832,7 +832,7 @@  discard block
 block discarded – undo
832 832
 		});
833 833
 		$this->registerAlias('Mailer', \OCP\Mail\IMailer::class);
834 834
 
835
-		$this->registerService('LDAPProvider', function (Server $c) {
835
+		$this->registerService('LDAPProvider', function(Server $c) {
836 836
 			$config = $c->getConfig();
837 837
 			$factoryClass = $config->getSystemValue('ldapProviderFactory', null);
838 838
 			if (is_null($factoryClass)) {
@@ -842,7 +842,7 @@  discard block
 block discarded – undo
842 842
 			$factory = new $factoryClass($this);
843 843
 			return $factory->getLDAPProvider();
844 844
 		});
845
-		$this->registerService(ILockingProvider::class, function (Server $c) {
845
+		$this->registerService(ILockingProvider::class, function(Server $c) {
846 846
 			$ini = $c->getIniWrapper();
847 847
 			$config = $c->getConfig();
848 848
 			$ttl = $config->getSystemValue('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
@@ -859,49 +859,49 @@  discard block
 block discarded – undo
859 859
 		});
860 860
 		$this->registerAlias('LockingProvider', ILockingProvider::class);
861 861
 
862
-		$this->registerService(\OCP\Files\Mount\IMountManager::class, function () {
862
+		$this->registerService(\OCP\Files\Mount\IMountManager::class, function() {
863 863
 			return new \OC\Files\Mount\Manager();
864 864
 		});
865 865
 		$this->registerAlias('MountManager', \OCP\Files\Mount\IMountManager::class);
866 866
 
867
-		$this->registerService(\OCP\Files\IMimeTypeDetector::class, function (Server $c) {
867
+		$this->registerService(\OCP\Files\IMimeTypeDetector::class, function(Server $c) {
868 868
 			return new \OC\Files\Type\Detection(
869 869
 				$c->getURLGenerator(),
870 870
 				\OC::$configDir,
871
-				\OC::$SERVERROOT . '/resources/config/'
871
+				\OC::$SERVERROOT.'/resources/config/'
872 872
 			);
873 873
 		});
874 874
 		$this->registerAlias('MimeTypeDetector', \OCP\Files\IMimeTypeDetector::class);
875 875
 
876
-		$this->registerService(\OCP\Files\IMimeTypeLoader::class, function (Server $c) {
876
+		$this->registerService(\OCP\Files\IMimeTypeLoader::class, function(Server $c) {
877 877
 			return new \OC\Files\Type\Loader(
878 878
 				$c->getDatabaseConnection()
879 879
 			);
880 880
 		});
881 881
 		$this->registerAlias('MimeTypeLoader', \OCP\Files\IMimeTypeLoader::class);
882
-		$this->registerService(BundleFetcher::class, function () {
882
+		$this->registerService(BundleFetcher::class, function() {
883 883
 			return new BundleFetcher($this->getL10N('lib'));
884 884
 		});
885
-		$this->registerService(\OCP\Notification\IManager::class, function (Server $c) {
885
+		$this->registerService(\OCP\Notification\IManager::class, function(Server $c) {
886 886
 			return new Manager(
887 887
 				$c->query(IValidator::class)
888 888
 			);
889 889
 		});
890 890
 		$this->registerAlias('NotificationManager', \OCP\Notification\IManager::class);
891 891
 
892
-		$this->registerService(\OC\CapabilitiesManager::class, function (Server $c) {
892
+		$this->registerService(\OC\CapabilitiesManager::class, function(Server $c) {
893 893
 			$manager = new \OC\CapabilitiesManager($c->getLogger());
894
-			$manager->registerCapability(function () use ($c) {
894
+			$manager->registerCapability(function() use ($c) {
895 895
 				return new \OC\OCS\CoreCapabilities($c->getConfig());
896 896
 			});
897
-			$manager->registerCapability(function () use ($c) {
897
+			$manager->registerCapability(function() use ($c) {
898 898
 				return $c->query(\OC\Security\Bruteforce\Capabilities::class);
899 899
 			});
900 900
 			return $manager;
901 901
 		});
902 902
 		$this->registerAlias('CapabilitiesManager', \OC\CapabilitiesManager::class);
903 903
 
904
-		$this->registerService(\OCP\Comments\ICommentsManager::class, function (Server $c) {
904
+		$this->registerService(\OCP\Comments\ICommentsManager::class, function(Server $c) {
905 905
 			$config = $c->getConfig();
906 906
 			$factoryClass = $config->getSystemValue('comments.managerFactory', '\OC\Comments\ManagerFactory');
907 907
 			/** @var \OCP\Comments\ICommentsManagerFactory $factory */
@@ -911,7 +911,7 @@  discard block
 block discarded – undo
911 911
 			$manager->registerDisplayNameResolver('user', function($id) use ($c) {
912 912
 				$manager = $c->getUserManager();
913 913
 				$user = $manager->get($id);
914
-				if(is_null($user)) {
914
+				if (is_null($user)) {
915 915
 					$l = $c->getL10N('core');
916 916
 					$displayName = $l->t('Unknown user');
917 917
 				} else {
@@ -924,7 +924,7 @@  discard block
 block discarded – undo
924 924
 		});
925 925
 		$this->registerAlias('CommentsManager', \OCP\Comments\ICommentsManager::class);
926 926
 
927
-		$this->registerService('ThemingDefaults', function (Server $c) {
927
+		$this->registerService('ThemingDefaults', function(Server $c) {
928 928
 			/*
929 929
 			 * Dark magic for autoloader.
930 930
 			 * If we do a class_exists it will try to load the class which will
@@ -951,7 +951,7 @@  discard block
 block discarded – undo
951 951
 			}
952 952
 			return new \OC_Defaults();
953 953
 		});
954
-		$this->registerService(SCSSCacher::class, function (Server $c) {
954
+		$this->registerService(SCSSCacher::class, function(Server $c) {
955 955
 			/** @var Factory $cacheFactory */
956 956
 			$cacheFactory = $c->query(Factory::class);
957 957
 			return new SCSSCacher(
@@ -964,13 +964,13 @@  discard block
 block discarded – undo
964 964
 				$cacheFactory->createDistributed('SCSS')
965 965
 			);
966 966
 		});
967
-		$this->registerService(EventDispatcher::class, function () {
967
+		$this->registerService(EventDispatcher::class, function() {
968 968
 			return new EventDispatcher();
969 969
 		});
970 970
 		$this->registerAlias('EventDispatcher', EventDispatcher::class);
971 971
 		$this->registerAlias(EventDispatcherInterface::class, EventDispatcher::class);
972 972
 
973
-		$this->registerService('CryptoWrapper', function (Server $c) {
973
+		$this->registerService('CryptoWrapper', function(Server $c) {
974 974
 			// FIXME: Instantiiated here due to cyclic dependency
975 975
 			$request = new Request(
976 976
 				[
@@ -995,7 +995,7 @@  discard block
 block discarded – undo
995 995
 				$request
996 996
 			);
997 997
 		});
998
-		$this->registerService('CsrfTokenManager', function (Server $c) {
998
+		$this->registerService('CsrfTokenManager', function(Server $c) {
999 999
 			$tokenGenerator = new CsrfTokenGenerator($c->getSecureRandom());
1000 1000
 
1001 1001
 			return new CsrfTokenManager(
@@ -1003,22 +1003,22 @@  discard block
 block discarded – undo
1003 1003
 				$c->query(SessionStorage::class)
1004 1004
 			);
1005 1005
 		});
1006
-		$this->registerService(SessionStorage::class, function (Server $c) {
1006
+		$this->registerService(SessionStorage::class, function(Server $c) {
1007 1007
 			return new SessionStorage($c->getSession());
1008 1008
 		});
1009
-		$this->registerService(\OCP\Security\IContentSecurityPolicyManager::class, function (Server $c) {
1009
+		$this->registerService(\OCP\Security\IContentSecurityPolicyManager::class, function(Server $c) {
1010 1010
 			return new ContentSecurityPolicyManager();
1011 1011
 		});
1012 1012
 		$this->registerAlias('ContentSecurityPolicyManager', \OCP\Security\IContentSecurityPolicyManager::class);
1013 1013
 
1014
-		$this->registerService('ContentSecurityPolicyNonceManager', function (Server $c) {
1014
+		$this->registerService('ContentSecurityPolicyNonceManager', function(Server $c) {
1015 1015
 			return new ContentSecurityPolicyNonceManager(
1016 1016
 				$c->getCsrfTokenManager(),
1017 1017
 				$c->getRequest()
1018 1018
 			);
1019 1019
 		});
1020 1020
 
1021
-		$this->registerService(\OCP\Share\IManager::class, function (Server $c) {
1021
+		$this->registerService(\OCP\Share\IManager::class, function(Server $c) {
1022 1022
 			$config = $c->getConfig();
1023 1023
 			$factoryClass = $config->getSystemValue('sharing.managerFactory', '\OC\Share20\ProviderFactory');
1024 1024
 			/** @var \OCP\Share\IProviderFactory $factory */
@@ -1061,7 +1061,7 @@  discard block
 block discarded – undo
1061 1061
 
1062 1062
 		$this->registerAlias(\OCP\Collaboration\AutoComplete\IManager::class, \OC\Collaboration\AutoComplete\Manager::class);
1063 1063
 
1064
-		$this->registerService('SettingsManager', function (Server $c) {
1064
+		$this->registerService('SettingsManager', function(Server $c) {
1065 1065
 			$manager = new \OC\Settings\Manager(
1066 1066
 				$c->getLogger(),
1067 1067
 				$c->getDatabaseConnection(),
@@ -1081,24 +1081,24 @@  discard block
 block discarded – undo
1081 1081
 			);
1082 1082
 			return $manager;
1083 1083
 		});
1084
-		$this->registerService(\OC\Files\AppData\Factory::class, function (Server $c) {
1084
+		$this->registerService(\OC\Files\AppData\Factory::class, function(Server $c) {
1085 1085
 			return new \OC\Files\AppData\Factory(
1086 1086
 				$c->getRootFolder(),
1087 1087
 				$c->getSystemConfig()
1088 1088
 			);
1089 1089
 		});
1090 1090
 
1091
-		$this->registerService('LockdownManager', function (Server $c) {
1092
-			return new LockdownManager(function () use ($c) {
1091
+		$this->registerService('LockdownManager', function(Server $c) {
1092
+			return new LockdownManager(function() use ($c) {
1093 1093
 				return $c->getSession();
1094 1094
 			});
1095 1095
 		});
1096 1096
 
1097
-		$this->registerService(\OCP\OCS\IDiscoveryService::class, function (Server $c) {
1097
+		$this->registerService(\OCP\OCS\IDiscoveryService::class, function(Server $c) {
1098 1098
 			return new DiscoveryService($c->getMemCacheFactory(), $c->getHTTPClientService());
1099 1099
 		});
1100 1100
 
1101
-		$this->registerService(ICloudIdManager::class, function (Server $c) {
1101
+		$this->registerService(ICloudIdManager::class, function(Server $c) {
1102 1102
 			return new CloudIdManager();
1103 1103
 		});
1104 1104
 
@@ -1108,18 +1108,18 @@  discard block
 block discarded – undo
1108 1108
 		$this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
1109 1109
 		$this->registerAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
1110 1110
 
1111
-		$this->registerService(Defaults::class, function (Server $c) {
1111
+		$this->registerService(Defaults::class, function(Server $c) {
1112 1112
 			return new Defaults(
1113 1113
 				$c->getThemingDefaults()
1114 1114
 			);
1115 1115
 		});
1116 1116
 		$this->registerAlias('Defaults', \OCP\Defaults::class);
1117 1117
 
1118
-		$this->registerService(\OCP\ISession::class, function (SimpleContainer $c) {
1118
+		$this->registerService(\OCP\ISession::class, function(SimpleContainer $c) {
1119 1119
 			return $c->query(\OCP\IUserSession::class)->getSession();
1120 1120
 		});
1121 1121
 
1122
-		$this->registerService(IShareHelper::class, function (Server $c) {
1122
+		$this->registerService(IShareHelper::class, function(Server $c) {
1123 1123
 			return new ShareHelper(
1124 1124
 				$c->query(\OCP\Share\IManager::class)
1125 1125
 			);
@@ -1181,11 +1181,11 @@  discard block
 block discarded – undo
1181 1181
 				// no avatar to remove
1182 1182
 			} catch (\Exception $e) {
1183 1183
 				// Ignore exceptions
1184
-				$logger->info('Could not cleanup avatar of ' . $user->getUID());
1184
+				$logger->info('Could not cleanup avatar of '.$user->getUID());
1185 1185
 			}
1186 1186
 		});
1187 1187
 
1188
-		$dispatcher->addListener('OCP\IUser::changeUser', function (GenericEvent $e) {
1188
+		$dispatcher->addListener('OCP\IUser::changeUser', function(GenericEvent $e) {
1189 1189
 			$manager = $this->getAvatarManager();
1190 1190
 			/** @var IUser $user */
1191 1191
 			$user = $e->getSubject();
@@ -1336,7 +1336,7 @@  discard block
 block discarded – undo
1336 1336
 	 * @deprecated since 9.2.0 use IAppData
1337 1337
 	 */
1338 1338
 	public function getAppFolder() {
1339
-		$dir = '/' . \OC_App::getCurrentApp();
1339
+		$dir = '/'.\OC_App::getCurrentApp();
1340 1340
 		$root = $this->getRootFolder();
1341 1341
 		if (!$root->nodeExists($dir)) {
1342 1342
 			$folder = $root->newFolder($dir);
@@ -1920,7 +1920,7 @@  discard block
 block discarded – undo
1920 1920
 	/**
1921 1921
 	 * @return \OCP\Collaboration\AutoComplete\IManager
1922 1922
 	 */
1923
-	public function getAutoCompleteManager(){
1923
+	public function getAutoCompleteManager() {
1924 1924
 		return $this->query(IManager::class);
1925 1925
 	}
1926 1926
 
Please login to merge, or discard this patch.
lib/private/Installer.php 2 patches
Indentation   +568 added lines, -568 removed lines patch added patch discarded remove patch
@@ -57,572 +57,572 @@
 block discarded – undo
57 57
  * This class provides the functionality needed to install, update and remove apps
58 58
  */
59 59
 class Installer {
60
-	/** @var AppFetcher */
61
-	private $appFetcher;
62
-	/** @var IClientService */
63
-	private $clientService;
64
-	/** @var ITempManager */
65
-	private $tempManager;
66
-	/** @var ILogger */
67
-	private $logger;
68
-	/** @var IConfig */
69
-	private $config;
70
-	/** @var array - for caching the result of app fetcher */
71
-	private $apps = null;
72
-	/** @var bool|null - for caching the result of the ready status */
73
-	private $isInstanceReadyForUpdates = null;
74
-
75
-	/**
76
-	 * @param AppFetcher $appFetcher
77
-	 * @param IClientService $clientService
78
-	 * @param ITempManager $tempManager
79
-	 * @param ILogger $logger
80
-	 * @param IConfig $config
81
-	 */
82
-	public function __construct(AppFetcher $appFetcher,
83
-								IClientService $clientService,
84
-								ITempManager $tempManager,
85
-								ILogger $logger,
86
-								IConfig $config) {
87
-		$this->appFetcher = $appFetcher;
88
-		$this->clientService = $clientService;
89
-		$this->tempManager = $tempManager;
90
-		$this->logger = $logger;
91
-		$this->config = $config;
92
-	}
93
-
94
-	/**
95
-	 * Installs an app that is located in one of the app folders already
96
-	 *
97
-	 * @param string $appId App to install
98
-	 * @throws \Exception
99
-	 * @return string app ID
100
-	 */
101
-	public function installApp($appId) {
102
-		$app = \OC_App::findAppInDirectories($appId);
103
-		if($app === false) {
104
-			throw new \Exception('App not found in any app directory');
105
-		}
106
-
107
-		$basedir = $app['path'].'/'.$appId;
108
-		$info = OC_App::getAppInfo($basedir.'/appinfo/info.xml', true);
109
-
110
-		$l = \OC::$server->getL10N('core');
111
-
112
-		if(!is_array($info)) {
113
-			throw new \Exception(
114
-				$l->t('App "%s" cannot be installed because appinfo file cannot be read.',
115
-					[$info['name']]
116
-				)
117
-			);
118
-		}
119
-
120
-		$version = \OCP\Util::getVersion();
121
-		if (!\OC_App::isAppCompatible($version, $info)) {
122
-			throw new \Exception(
123
-				// TODO $l
124
-				$l->t('App "%s" cannot be installed because it is not compatible with this version of the server.',
125
-					[$info['name']]
126
-				)
127
-			);
128
-		}
129
-
130
-		// check for required dependencies
131
-		\OC_App::checkAppDependencies($this->config, $l, $info);
132
-		\OC_App::registerAutoloading($appId, $basedir);
133
-
134
-		//install the database
135
-		if(is_file($basedir.'/appinfo/database.xml')) {
136
-			if (\OC::$server->getConfig()->getAppValue($info['id'], 'installed_version') === null) {
137
-				OC_DB::createDbFromStructure($basedir.'/appinfo/database.xml');
138
-			} else {
139
-				OC_DB::updateDbFromStructure($basedir.'/appinfo/database.xml');
140
-			}
141
-		} else {
142
-			$ms = new \OC\DB\MigrationService($info['id'], \OC::$server->getDatabaseConnection());
143
-			$ms->migrate();
144
-		}
145
-
146
-		\OC_App::setupBackgroundJobs($info['background-jobs']);
147
-		if(isset($info['settings']) && is_array($info['settings'])) {
148
-			\OC::$server->getSettingsManager()->setupSettings($info['settings']);
149
-		}
150
-
151
-		//run appinfo/install.php
152
-		if(!isset($data['noinstall']) or $data['noinstall']==false) {
153
-			self::includeAppScript($basedir . '/appinfo/install.php');
154
-		}
155
-
156
-		$appData = OC_App::getAppInfo($appId);
157
-		OC_App::executeRepairSteps($appId, $appData['repair-steps']['install']);
158
-
159
-		//set the installed version
160
-		\OC::$server->getConfig()->setAppValue($info['id'], 'installed_version', OC_App::getAppVersion($info['id'], false));
161
-		\OC::$server->getConfig()->setAppValue($info['id'], 'enabled', 'no');
162
-
163
-		//set remote/public handlers
164
-		foreach($info['remote'] as $name=>$path) {
165
-			\OC::$server->getConfig()->setAppValue('core', 'remote_'.$name, $info['id'].'/'.$path);
166
-		}
167
-		foreach($info['public'] as $name=>$path) {
168
-			\OC::$server->getConfig()->setAppValue('core', 'public_'.$name, $info['id'].'/'.$path);
169
-		}
170
-
171
-		OC_App::setAppTypes($info['id']);
172
-
173
-		return $info['id'];
174
-	}
175
-
176
-	/**
177
-	 * @brief checks whether or not an app is installed
178
-	 * @param string $app app
179
-	 * @returns bool
180
-	 *
181
-	 * Checks whether or not an app is installed, i.e. registered in apps table.
182
-	 */
183
-	public static function isInstalled( $app ) {
184
-		return (\OC::$server->getConfig()->getAppValue($app, "installed_version", null) !== null);
185
-	}
186
-
187
-	/**
188
-	 * Updates the specified app from the appstore
189
-	 *
190
-	 * @param string $appId
191
-	 * @return bool
192
-	 */
193
-	public function updateAppstoreApp($appId) {
194
-		if($this->isUpdateAvailable($appId)) {
195
-			try {
196
-				$this->downloadApp($appId);
197
-			} catch (\Exception $e) {
198
-				$this->logger->logException($e, [
199
-					'level' => \OCP\Util::ERROR,
200
-					'app' => 'core',
201
-				]);
202
-				return false;
203
-			}
204
-			return OC_App::updateApp($appId);
205
-		}
206
-
207
-		return false;
208
-	}
209
-
210
-	/**
211
-	 * Downloads an app and puts it into the app directory
212
-	 *
213
-	 * @param string $appId
214
-	 *
215
-	 * @throws \Exception If the installation was not successful
216
-	 */
217
-	public function downloadApp($appId) {
218
-		$appId = strtolower($appId);
219
-
220
-		$apps = $this->appFetcher->get();
221
-		foreach($apps as $app) {
222
-			if($app['id'] === $appId) {
223
-				// Load the certificate
224
-				$certificate = new X509();
225
-				$certificate->loadCA(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crt'));
226
-				$loadedCertificate = $certificate->loadX509($app['certificate']);
227
-
228
-				// Verify if the certificate has been revoked
229
-				$crl = new X509();
230
-				$crl->loadCA(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crt'));
231
-				$crl->loadCRL(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crl'));
232
-				if($crl->validateSignature() !== true) {
233
-					throw new \Exception('Could not validate CRL signature');
234
-				}
235
-				$csn = $loadedCertificate['tbsCertificate']['serialNumber']->toString();
236
-				$revoked = $crl->getRevoked($csn);
237
-				if ($revoked !== false) {
238
-					throw new \Exception(
239
-						sprintf(
240
-							'Certificate "%s" has been revoked',
241
-							$csn
242
-						)
243
-					);
244
-				}
245
-
246
-				// Verify if the certificate has been issued by the Nextcloud Code Authority CA
247
-				if($certificate->validateSignature() !== true) {
248
-					throw new \Exception(
249
-						sprintf(
250
-							'App with id %s has a certificate not issued by a trusted Code Signing Authority',
251
-							$appId
252
-						)
253
-					);
254
-				}
255
-
256
-				// Verify if the certificate is issued for the requested app id
257
-				$certInfo = openssl_x509_parse($app['certificate']);
258
-				if(!isset($certInfo['subject']['CN'])) {
259
-					throw new \Exception(
260
-						sprintf(
261
-							'App with id %s has a cert with no CN',
262
-							$appId
263
-						)
264
-					);
265
-				}
266
-				if($certInfo['subject']['CN'] !== $appId) {
267
-					throw new \Exception(
268
-						sprintf(
269
-							'App with id %s has a cert issued to %s',
270
-							$appId,
271
-							$certInfo['subject']['CN']
272
-						)
273
-					);
274
-				}
275
-
276
-				// Download the release
277
-				$tempFile = $this->tempManager->getTemporaryFile('.tar.gz');
278
-				$client = $this->clientService->newClient();
279
-				$client->get($app['releases'][0]['download'], ['save_to' => $tempFile]);
280
-
281
-				// Check if the signature actually matches the downloaded content
282
-				$certificate = openssl_get_publickey($app['certificate']);
283
-				$verified = (bool)openssl_verify(file_get_contents($tempFile), base64_decode($app['releases'][0]['signature']), $certificate, OPENSSL_ALGO_SHA512);
284
-				openssl_free_key($certificate);
285
-
286
-				if($verified === true) {
287
-					// Seems to match, let's proceed
288
-					$extractDir = $this->tempManager->getTemporaryFolder();
289
-					$archive = new TAR($tempFile);
290
-
291
-					if($archive) {
292
-						if (!$archive->extract($extractDir)) {
293
-							throw new \Exception(
294
-								sprintf(
295
-									'Could not extract app %s',
296
-									$appId
297
-								)
298
-							);
299
-						}
300
-						$allFiles = scandir($extractDir);
301
-						$folders = array_diff($allFiles, ['.', '..']);
302
-						$folders = array_values($folders);
303
-
304
-						if(count($folders) > 1) {
305
-							throw new \Exception(
306
-								sprintf(
307
-									'Extracted app %s has more than 1 folder',
308
-									$appId
309
-								)
310
-							);
311
-						}
312
-
313
-						// Check if appinfo/info.xml has the same app ID as well
314
-						$loadEntities = libxml_disable_entity_loader(false);
315
-						$xml = simplexml_load_file($extractDir . '/' . $folders[0] . '/appinfo/info.xml');
316
-						libxml_disable_entity_loader($loadEntities);
317
-						if((string)$xml->id !== $appId) {
318
-							throw new \Exception(
319
-								sprintf(
320
-									'App for id %s has a wrong app ID in info.xml: %s',
321
-									$appId,
322
-									(string)$xml->id
323
-								)
324
-							);
325
-						}
326
-
327
-						// Check if the version is lower than before
328
-						$currentVersion = OC_App::getAppVersion($appId);
329
-						$newVersion = (string)$xml->version;
330
-						if(version_compare($currentVersion, $newVersion) === 1) {
331
-							throw new \Exception(
332
-								sprintf(
333
-									'App for id %s has version %s and tried to update to lower version %s',
334
-									$appId,
335
-									$currentVersion,
336
-									$newVersion
337
-								)
338
-							);
339
-						}
340
-
341
-						$baseDir = OC_App::getInstallPath() . '/' . $appId;
342
-						// Remove old app with the ID if existent
343
-						OC_Helper::rmdirr($baseDir);
344
-						// Move to app folder
345
-						if(@mkdir($baseDir)) {
346
-							$extractDir .= '/' . $folders[0];
347
-							OC_Helper::copyr($extractDir, $baseDir);
348
-						}
349
-						OC_Helper::copyr($extractDir, $baseDir);
350
-						OC_Helper::rmdirr($extractDir);
351
-						return;
352
-					} else {
353
-						throw new \Exception(
354
-							sprintf(
355
-								'Could not extract app with ID %s to %s',
356
-								$appId,
357
-								$extractDir
358
-							)
359
-						);
360
-					}
361
-				} else {
362
-					// Signature does not match
363
-					throw new \Exception(
364
-						sprintf(
365
-							'App with id %s has invalid signature',
366
-							$appId
367
-						)
368
-					);
369
-				}
370
-			}
371
-		}
372
-
373
-		throw new \Exception(
374
-			sprintf(
375
-				'Could not download app %s',
376
-				$appId
377
-			)
378
-		);
379
-	}
380
-
381
-	/**
382
-	 * Check if an update for the app is available
383
-	 *
384
-	 * @param string $appId
385
-	 * @return string|false false or the version number of the update
386
-	 */
387
-	public function isUpdateAvailable($appId) {
388
-		if ($this->isInstanceReadyForUpdates === null) {
389
-			$installPath = OC_App::getInstallPath();
390
-			if ($installPath === false || $installPath === null) {
391
-				$this->isInstanceReadyForUpdates = false;
392
-			} else {
393
-				$this->isInstanceReadyForUpdates = true;
394
-			}
395
-		}
396
-
397
-		if ($this->isInstanceReadyForUpdates === false) {
398
-			return false;
399
-		}
400
-
401
-		if ($this->isInstalledFromGit($appId) === true) {
402
-			return false;
403
-		}
404
-
405
-		if ($this->apps === null) {
406
-			$this->apps = $this->appFetcher->get();
407
-		}
408
-
409
-		foreach($this->apps as $app) {
410
-			if($app['id'] === $appId) {
411
-				$currentVersion = OC_App::getAppVersion($appId);
412
-				$newestVersion = $app['releases'][0]['version'];
413
-				if (version_compare($newestVersion, $currentVersion, '>')) {
414
-					return $newestVersion;
415
-				} else {
416
-					return false;
417
-				}
418
-			}
419
-		}
420
-
421
-		return false;
422
-	}
423
-
424
-	/**
425
-	 * Check if app has been installed from git
426
-	 * @param string $name name of the application to remove
427
-	 * @return boolean
428
-	 *
429
-	 * The function will check if the path contains a .git folder
430
-	 */
431
-	private function isInstalledFromGit($appId) {
432
-		$app = \OC_App::findAppInDirectories($appId);
433
-		if($app === false) {
434
-			return false;
435
-		}
436
-		$basedir = $app['path'].'/'.$appId;
437
-		return file_exists($basedir.'/.git/');
438
-	}
439
-
440
-	/**
441
-	 * Check if app is already downloaded
442
-	 * @param string $name name of the application to remove
443
-	 * @return boolean
444
-	 *
445
-	 * The function will check if the app is already downloaded in the apps repository
446
-	 */
447
-	public function isDownloaded($name) {
448
-		foreach(\OC::$APPSROOTS as $dir) {
449
-			$dirToTest  = $dir['path'];
450
-			$dirToTest .= '/';
451
-			$dirToTest .= $name;
452
-			$dirToTest .= '/';
453
-
454
-			if (is_dir($dirToTest)) {
455
-				return true;
456
-			}
457
-		}
458
-
459
-		return false;
460
-	}
461
-
462
-	/**
463
-	 * Removes an app
464
-	 * @param string $appId ID of the application to remove
465
-	 * @return boolean
466
-	 *
467
-	 *
468
-	 * This function works as follows
469
-	 *   -# call uninstall repair steps
470
-	 *   -# removing the files
471
-	 *
472
-	 * The function will not delete preferences, tables and the configuration,
473
-	 * this has to be done by the function oc_app_uninstall().
474
-	 */
475
-	public function removeApp($appId) {
476
-		if($this->isDownloaded( $appId )) {
477
-			if (\OC::$server->getAppManager()->isShipped($appId)) {
478
-				return false;
479
-			}
480
-			$appDir = OC_App::getInstallPath() . '/' . $appId;
481
-			OC_Helper::rmdirr($appDir);
482
-			return true;
483
-		}else{
484
-			\OCP\Util::writeLog('core', 'can\'t remove app '.$appId.'. It is not installed.', \OCP\Util::ERROR);
485
-
486
-			return false;
487
-		}
488
-
489
-	}
490
-
491
-	/**
492
-	 * Installs the app within the bundle and marks the bundle as installed
493
-	 *
494
-	 * @param Bundle $bundle
495
-	 * @throws \Exception If app could not get installed
496
-	 */
497
-	public function installAppBundle(Bundle $bundle) {
498
-		$appIds = $bundle->getAppIdentifiers();
499
-		foreach($appIds as $appId) {
500
-			if(!$this->isDownloaded($appId)) {
501
-				$this->downloadApp($appId);
502
-			}
503
-			$this->installApp($appId);
504
-			$app = new OC_App();
505
-			$app->enable($appId);
506
-		}
507
-		$bundles = json_decode($this->config->getAppValue('core', 'installed.bundles', json_encode([])), true);
508
-		$bundles[] = $bundle->getIdentifier();
509
-		$this->config->setAppValue('core', 'installed.bundles', json_encode($bundles));
510
-	}
511
-
512
-	/**
513
-	 * Installs shipped apps
514
-	 *
515
-	 * This function installs all apps found in the 'apps' directory that should be enabled by default;
516
-	 * @param bool $softErrors When updating we ignore errors and simply log them, better to have a
517
-	 *                         working ownCloud at the end instead of an aborted update.
518
-	 * @return array Array of error messages (appid => Exception)
519
-	 */
520
-	public static function installShippedApps($softErrors = false) {
521
-		$errors = [];
522
-		foreach(\OC::$APPSROOTS as $app_dir) {
523
-			if($dir = opendir( $app_dir['path'] )) {
524
-				while( false !== ( $filename = readdir( $dir ))) {
525
-					if( $filename[0] !== '.' and is_dir($app_dir['path']."/$filename") ) {
526
-						if( file_exists( $app_dir['path']."/$filename/appinfo/info.xml" )) {
527
-							if(!Installer::isInstalled($filename)) {
528
-								$info=OC_App::getAppInfo($filename);
529
-								$enabled = isset($info['default_enable']);
530
-								if (($enabled || in_array($filename, \OC::$server->getAppManager()->getAlwaysEnabledApps()))
531
-									  && \OC::$server->getConfig()->getAppValue($filename, 'enabled') !== 'no') {
532
-									if ($softErrors) {
533
-										try {
534
-											Installer::installShippedApp($filename);
535
-										} catch (HintException $e) {
536
-											if ($e->getPrevious() instanceof TableExistsException) {
537
-												$errors[$filename] = $e;
538
-												continue;
539
-											}
540
-											throw $e;
541
-										}
542
-									} else {
543
-										Installer::installShippedApp($filename);
544
-									}
545
-									\OC::$server->getConfig()->setAppValue($filename, 'enabled', 'yes');
546
-								}
547
-							}
548
-						}
549
-					}
550
-				}
551
-				closedir( $dir );
552
-			}
553
-		}
554
-
555
-		return $errors;
556
-	}
557
-
558
-	/**
559
-	 * install an app already placed in the app folder
560
-	 * @param string $app id of the app to install
561
-	 * @return integer
562
-	 */
563
-	public static function installShippedApp($app) {
564
-		//install the database
565
-		$appPath = OC_App::getAppPath($app);
566
-		\OC_App::registerAutoloading($app, $appPath);
567
-
568
-		if(is_file("$appPath/appinfo/database.xml")) {
569
-			try {
570
-				OC_DB::createDbFromStructure("$appPath/appinfo/database.xml");
571
-			} catch (TableExistsException $e) {
572
-				throw new HintException(
573
-					'Failed to enable app ' . $app,
574
-					'Please ask for help via one of our <a href="https://nextcloud.com/support/" target="_blank" rel="noreferrer noopener">support channels</a>.',
575
-					0, $e
576
-				);
577
-			}
578
-		} else {
579
-			$ms = new \OC\DB\MigrationService($app, \OC::$server->getDatabaseConnection());
580
-			$ms->migrate();
581
-		}
582
-
583
-		//run appinfo/install.php
584
-		self::includeAppScript("$appPath/appinfo/install.php");
585
-
586
-		$info = OC_App::getAppInfo($app);
587
-		if (is_null($info)) {
588
-			return false;
589
-		}
590
-		\OC_App::setupBackgroundJobs($info['background-jobs']);
591
-
592
-		OC_App::executeRepairSteps($app, $info['repair-steps']['install']);
593
-
594
-		$config = \OC::$server->getConfig();
595
-
596
-		$config->setAppValue($app, 'installed_version', OC_App::getAppVersion($app));
597
-		if (array_key_exists('ocsid', $info)) {
598
-			$config->setAppValue($app, 'ocsid', $info['ocsid']);
599
-		}
600
-
601
-		//set remote/public handlers
602
-		foreach($info['remote'] as $name=>$path) {
603
-			$config->setAppValue('core', 'remote_'.$name, $app.'/'.$path);
604
-		}
605
-		foreach($info['public'] as $name=>$path) {
606
-			$config->setAppValue('core', 'public_'.$name, $app.'/'.$path);
607
-		}
608
-
609
-		OC_App::setAppTypes($info['id']);
610
-
611
-		if(isset($info['settings']) && is_array($info['settings'])) {
612
-			// requires that autoloading was registered for the app,
613
-			// as happens before running the install.php some lines above
614
-			\OC::$server->getSettingsManager()->setupSettings($info['settings']);
615
-		}
616
-
617
-		return $info['id'];
618
-	}
619
-
620
-	/**
621
-	 * @param string $script
622
-	 */
623
-	private static function includeAppScript($script) {
624
-		if ( file_exists($script) ){
625
-			include $script;
626
-		}
627
-	}
60
+    /** @var AppFetcher */
61
+    private $appFetcher;
62
+    /** @var IClientService */
63
+    private $clientService;
64
+    /** @var ITempManager */
65
+    private $tempManager;
66
+    /** @var ILogger */
67
+    private $logger;
68
+    /** @var IConfig */
69
+    private $config;
70
+    /** @var array - for caching the result of app fetcher */
71
+    private $apps = null;
72
+    /** @var bool|null - for caching the result of the ready status */
73
+    private $isInstanceReadyForUpdates = null;
74
+
75
+    /**
76
+     * @param AppFetcher $appFetcher
77
+     * @param IClientService $clientService
78
+     * @param ITempManager $tempManager
79
+     * @param ILogger $logger
80
+     * @param IConfig $config
81
+     */
82
+    public function __construct(AppFetcher $appFetcher,
83
+                                IClientService $clientService,
84
+                                ITempManager $tempManager,
85
+                                ILogger $logger,
86
+                                IConfig $config) {
87
+        $this->appFetcher = $appFetcher;
88
+        $this->clientService = $clientService;
89
+        $this->tempManager = $tempManager;
90
+        $this->logger = $logger;
91
+        $this->config = $config;
92
+    }
93
+
94
+    /**
95
+     * Installs an app that is located in one of the app folders already
96
+     *
97
+     * @param string $appId App to install
98
+     * @throws \Exception
99
+     * @return string app ID
100
+     */
101
+    public function installApp($appId) {
102
+        $app = \OC_App::findAppInDirectories($appId);
103
+        if($app === false) {
104
+            throw new \Exception('App not found in any app directory');
105
+        }
106
+
107
+        $basedir = $app['path'].'/'.$appId;
108
+        $info = OC_App::getAppInfo($basedir.'/appinfo/info.xml', true);
109
+
110
+        $l = \OC::$server->getL10N('core');
111
+
112
+        if(!is_array($info)) {
113
+            throw new \Exception(
114
+                $l->t('App "%s" cannot be installed because appinfo file cannot be read.',
115
+                    [$info['name']]
116
+                )
117
+            );
118
+        }
119
+
120
+        $version = \OCP\Util::getVersion();
121
+        if (!\OC_App::isAppCompatible($version, $info)) {
122
+            throw new \Exception(
123
+                // TODO $l
124
+                $l->t('App "%s" cannot be installed because it is not compatible with this version of the server.',
125
+                    [$info['name']]
126
+                )
127
+            );
128
+        }
129
+
130
+        // check for required dependencies
131
+        \OC_App::checkAppDependencies($this->config, $l, $info);
132
+        \OC_App::registerAutoloading($appId, $basedir);
133
+
134
+        //install the database
135
+        if(is_file($basedir.'/appinfo/database.xml')) {
136
+            if (\OC::$server->getConfig()->getAppValue($info['id'], 'installed_version') === null) {
137
+                OC_DB::createDbFromStructure($basedir.'/appinfo/database.xml');
138
+            } else {
139
+                OC_DB::updateDbFromStructure($basedir.'/appinfo/database.xml');
140
+            }
141
+        } else {
142
+            $ms = new \OC\DB\MigrationService($info['id'], \OC::$server->getDatabaseConnection());
143
+            $ms->migrate();
144
+        }
145
+
146
+        \OC_App::setupBackgroundJobs($info['background-jobs']);
147
+        if(isset($info['settings']) && is_array($info['settings'])) {
148
+            \OC::$server->getSettingsManager()->setupSettings($info['settings']);
149
+        }
150
+
151
+        //run appinfo/install.php
152
+        if(!isset($data['noinstall']) or $data['noinstall']==false) {
153
+            self::includeAppScript($basedir . '/appinfo/install.php');
154
+        }
155
+
156
+        $appData = OC_App::getAppInfo($appId);
157
+        OC_App::executeRepairSteps($appId, $appData['repair-steps']['install']);
158
+
159
+        //set the installed version
160
+        \OC::$server->getConfig()->setAppValue($info['id'], 'installed_version', OC_App::getAppVersion($info['id'], false));
161
+        \OC::$server->getConfig()->setAppValue($info['id'], 'enabled', 'no');
162
+
163
+        //set remote/public handlers
164
+        foreach($info['remote'] as $name=>$path) {
165
+            \OC::$server->getConfig()->setAppValue('core', 'remote_'.$name, $info['id'].'/'.$path);
166
+        }
167
+        foreach($info['public'] as $name=>$path) {
168
+            \OC::$server->getConfig()->setAppValue('core', 'public_'.$name, $info['id'].'/'.$path);
169
+        }
170
+
171
+        OC_App::setAppTypes($info['id']);
172
+
173
+        return $info['id'];
174
+    }
175
+
176
+    /**
177
+     * @brief checks whether or not an app is installed
178
+     * @param string $app app
179
+     * @returns bool
180
+     *
181
+     * Checks whether or not an app is installed, i.e. registered in apps table.
182
+     */
183
+    public static function isInstalled( $app ) {
184
+        return (\OC::$server->getConfig()->getAppValue($app, "installed_version", null) !== null);
185
+    }
186
+
187
+    /**
188
+     * Updates the specified app from the appstore
189
+     *
190
+     * @param string $appId
191
+     * @return bool
192
+     */
193
+    public function updateAppstoreApp($appId) {
194
+        if($this->isUpdateAvailable($appId)) {
195
+            try {
196
+                $this->downloadApp($appId);
197
+            } catch (\Exception $e) {
198
+                $this->logger->logException($e, [
199
+                    'level' => \OCP\Util::ERROR,
200
+                    'app' => 'core',
201
+                ]);
202
+                return false;
203
+            }
204
+            return OC_App::updateApp($appId);
205
+        }
206
+
207
+        return false;
208
+    }
209
+
210
+    /**
211
+     * Downloads an app and puts it into the app directory
212
+     *
213
+     * @param string $appId
214
+     *
215
+     * @throws \Exception If the installation was not successful
216
+     */
217
+    public function downloadApp($appId) {
218
+        $appId = strtolower($appId);
219
+
220
+        $apps = $this->appFetcher->get();
221
+        foreach($apps as $app) {
222
+            if($app['id'] === $appId) {
223
+                // Load the certificate
224
+                $certificate = new X509();
225
+                $certificate->loadCA(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crt'));
226
+                $loadedCertificate = $certificate->loadX509($app['certificate']);
227
+
228
+                // Verify if the certificate has been revoked
229
+                $crl = new X509();
230
+                $crl->loadCA(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crt'));
231
+                $crl->loadCRL(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crl'));
232
+                if($crl->validateSignature() !== true) {
233
+                    throw new \Exception('Could not validate CRL signature');
234
+                }
235
+                $csn = $loadedCertificate['tbsCertificate']['serialNumber']->toString();
236
+                $revoked = $crl->getRevoked($csn);
237
+                if ($revoked !== false) {
238
+                    throw new \Exception(
239
+                        sprintf(
240
+                            'Certificate "%s" has been revoked',
241
+                            $csn
242
+                        )
243
+                    );
244
+                }
245
+
246
+                // Verify if the certificate has been issued by the Nextcloud Code Authority CA
247
+                if($certificate->validateSignature() !== true) {
248
+                    throw new \Exception(
249
+                        sprintf(
250
+                            'App with id %s has a certificate not issued by a trusted Code Signing Authority',
251
+                            $appId
252
+                        )
253
+                    );
254
+                }
255
+
256
+                // Verify if the certificate is issued for the requested app id
257
+                $certInfo = openssl_x509_parse($app['certificate']);
258
+                if(!isset($certInfo['subject']['CN'])) {
259
+                    throw new \Exception(
260
+                        sprintf(
261
+                            'App with id %s has a cert with no CN',
262
+                            $appId
263
+                        )
264
+                    );
265
+                }
266
+                if($certInfo['subject']['CN'] !== $appId) {
267
+                    throw new \Exception(
268
+                        sprintf(
269
+                            'App with id %s has a cert issued to %s',
270
+                            $appId,
271
+                            $certInfo['subject']['CN']
272
+                        )
273
+                    );
274
+                }
275
+
276
+                // Download the release
277
+                $tempFile = $this->tempManager->getTemporaryFile('.tar.gz');
278
+                $client = $this->clientService->newClient();
279
+                $client->get($app['releases'][0]['download'], ['save_to' => $tempFile]);
280
+
281
+                // Check if the signature actually matches the downloaded content
282
+                $certificate = openssl_get_publickey($app['certificate']);
283
+                $verified = (bool)openssl_verify(file_get_contents($tempFile), base64_decode($app['releases'][0]['signature']), $certificate, OPENSSL_ALGO_SHA512);
284
+                openssl_free_key($certificate);
285
+
286
+                if($verified === true) {
287
+                    // Seems to match, let's proceed
288
+                    $extractDir = $this->tempManager->getTemporaryFolder();
289
+                    $archive = new TAR($tempFile);
290
+
291
+                    if($archive) {
292
+                        if (!$archive->extract($extractDir)) {
293
+                            throw new \Exception(
294
+                                sprintf(
295
+                                    'Could not extract app %s',
296
+                                    $appId
297
+                                )
298
+                            );
299
+                        }
300
+                        $allFiles = scandir($extractDir);
301
+                        $folders = array_diff($allFiles, ['.', '..']);
302
+                        $folders = array_values($folders);
303
+
304
+                        if(count($folders) > 1) {
305
+                            throw new \Exception(
306
+                                sprintf(
307
+                                    'Extracted app %s has more than 1 folder',
308
+                                    $appId
309
+                                )
310
+                            );
311
+                        }
312
+
313
+                        // Check if appinfo/info.xml has the same app ID as well
314
+                        $loadEntities = libxml_disable_entity_loader(false);
315
+                        $xml = simplexml_load_file($extractDir . '/' . $folders[0] . '/appinfo/info.xml');
316
+                        libxml_disable_entity_loader($loadEntities);
317
+                        if((string)$xml->id !== $appId) {
318
+                            throw new \Exception(
319
+                                sprintf(
320
+                                    'App for id %s has a wrong app ID in info.xml: %s',
321
+                                    $appId,
322
+                                    (string)$xml->id
323
+                                )
324
+                            );
325
+                        }
326
+
327
+                        // Check if the version is lower than before
328
+                        $currentVersion = OC_App::getAppVersion($appId);
329
+                        $newVersion = (string)$xml->version;
330
+                        if(version_compare($currentVersion, $newVersion) === 1) {
331
+                            throw new \Exception(
332
+                                sprintf(
333
+                                    'App for id %s has version %s and tried to update to lower version %s',
334
+                                    $appId,
335
+                                    $currentVersion,
336
+                                    $newVersion
337
+                                )
338
+                            );
339
+                        }
340
+
341
+                        $baseDir = OC_App::getInstallPath() . '/' . $appId;
342
+                        // Remove old app with the ID if existent
343
+                        OC_Helper::rmdirr($baseDir);
344
+                        // Move to app folder
345
+                        if(@mkdir($baseDir)) {
346
+                            $extractDir .= '/' . $folders[0];
347
+                            OC_Helper::copyr($extractDir, $baseDir);
348
+                        }
349
+                        OC_Helper::copyr($extractDir, $baseDir);
350
+                        OC_Helper::rmdirr($extractDir);
351
+                        return;
352
+                    } else {
353
+                        throw new \Exception(
354
+                            sprintf(
355
+                                'Could not extract app with ID %s to %s',
356
+                                $appId,
357
+                                $extractDir
358
+                            )
359
+                        );
360
+                    }
361
+                } else {
362
+                    // Signature does not match
363
+                    throw new \Exception(
364
+                        sprintf(
365
+                            'App with id %s has invalid signature',
366
+                            $appId
367
+                        )
368
+                    );
369
+                }
370
+            }
371
+        }
372
+
373
+        throw new \Exception(
374
+            sprintf(
375
+                'Could not download app %s',
376
+                $appId
377
+            )
378
+        );
379
+    }
380
+
381
+    /**
382
+     * Check if an update for the app is available
383
+     *
384
+     * @param string $appId
385
+     * @return string|false false or the version number of the update
386
+     */
387
+    public function isUpdateAvailable($appId) {
388
+        if ($this->isInstanceReadyForUpdates === null) {
389
+            $installPath = OC_App::getInstallPath();
390
+            if ($installPath === false || $installPath === null) {
391
+                $this->isInstanceReadyForUpdates = false;
392
+            } else {
393
+                $this->isInstanceReadyForUpdates = true;
394
+            }
395
+        }
396
+
397
+        if ($this->isInstanceReadyForUpdates === false) {
398
+            return false;
399
+        }
400
+
401
+        if ($this->isInstalledFromGit($appId) === true) {
402
+            return false;
403
+        }
404
+
405
+        if ($this->apps === null) {
406
+            $this->apps = $this->appFetcher->get();
407
+        }
408
+
409
+        foreach($this->apps as $app) {
410
+            if($app['id'] === $appId) {
411
+                $currentVersion = OC_App::getAppVersion($appId);
412
+                $newestVersion = $app['releases'][0]['version'];
413
+                if (version_compare($newestVersion, $currentVersion, '>')) {
414
+                    return $newestVersion;
415
+                } else {
416
+                    return false;
417
+                }
418
+            }
419
+        }
420
+
421
+        return false;
422
+    }
423
+
424
+    /**
425
+     * Check if app has been installed from git
426
+     * @param string $name name of the application to remove
427
+     * @return boolean
428
+     *
429
+     * The function will check if the path contains a .git folder
430
+     */
431
+    private function isInstalledFromGit($appId) {
432
+        $app = \OC_App::findAppInDirectories($appId);
433
+        if($app === false) {
434
+            return false;
435
+        }
436
+        $basedir = $app['path'].'/'.$appId;
437
+        return file_exists($basedir.'/.git/');
438
+    }
439
+
440
+    /**
441
+     * Check if app is already downloaded
442
+     * @param string $name name of the application to remove
443
+     * @return boolean
444
+     *
445
+     * The function will check if the app is already downloaded in the apps repository
446
+     */
447
+    public function isDownloaded($name) {
448
+        foreach(\OC::$APPSROOTS as $dir) {
449
+            $dirToTest  = $dir['path'];
450
+            $dirToTest .= '/';
451
+            $dirToTest .= $name;
452
+            $dirToTest .= '/';
453
+
454
+            if (is_dir($dirToTest)) {
455
+                return true;
456
+            }
457
+        }
458
+
459
+        return false;
460
+    }
461
+
462
+    /**
463
+     * Removes an app
464
+     * @param string $appId ID of the application to remove
465
+     * @return boolean
466
+     *
467
+     *
468
+     * This function works as follows
469
+     *   -# call uninstall repair steps
470
+     *   -# removing the files
471
+     *
472
+     * The function will not delete preferences, tables and the configuration,
473
+     * this has to be done by the function oc_app_uninstall().
474
+     */
475
+    public function removeApp($appId) {
476
+        if($this->isDownloaded( $appId )) {
477
+            if (\OC::$server->getAppManager()->isShipped($appId)) {
478
+                return false;
479
+            }
480
+            $appDir = OC_App::getInstallPath() . '/' . $appId;
481
+            OC_Helper::rmdirr($appDir);
482
+            return true;
483
+        }else{
484
+            \OCP\Util::writeLog('core', 'can\'t remove app '.$appId.'. It is not installed.', \OCP\Util::ERROR);
485
+
486
+            return false;
487
+        }
488
+
489
+    }
490
+
491
+    /**
492
+     * Installs the app within the bundle and marks the bundle as installed
493
+     *
494
+     * @param Bundle $bundle
495
+     * @throws \Exception If app could not get installed
496
+     */
497
+    public function installAppBundle(Bundle $bundle) {
498
+        $appIds = $bundle->getAppIdentifiers();
499
+        foreach($appIds as $appId) {
500
+            if(!$this->isDownloaded($appId)) {
501
+                $this->downloadApp($appId);
502
+            }
503
+            $this->installApp($appId);
504
+            $app = new OC_App();
505
+            $app->enable($appId);
506
+        }
507
+        $bundles = json_decode($this->config->getAppValue('core', 'installed.bundles', json_encode([])), true);
508
+        $bundles[] = $bundle->getIdentifier();
509
+        $this->config->setAppValue('core', 'installed.bundles', json_encode($bundles));
510
+    }
511
+
512
+    /**
513
+     * Installs shipped apps
514
+     *
515
+     * This function installs all apps found in the 'apps' directory that should be enabled by default;
516
+     * @param bool $softErrors When updating we ignore errors and simply log them, better to have a
517
+     *                         working ownCloud at the end instead of an aborted update.
518
+     * @return array Array of error messages (appid => Exception)
519
+     */
520
+    public static function installShippedApps($softErrors = false) {
521
+        $errors = [];
522
+        foreach(\OC::$APPSROOTS as $app_dir) {
523
+            if($dir = opendir( $app_dir['path'] )) {
524
+                while( false !== ( $filename = readdir( $dir ))) {
525
+                    if( $filename[0] !== '.' and is_dir($app_dir['path']."/$filename") ) {
526
+                        if( file_exists( $app_dir['path']."/$filename/appinfo/info.xml" )) {
527
+                            if(!Installer::isInstalled($filename)) {
528
+                                $info=OC_App::getAppInfo($filename);
529
+                                $enabled = isset($info['default_enable']);
530
+                                if (($enabled || in_array($filename, \OC::$server->getAppManager()->getAlwaysEnabledApps()))
531
+                                      && \OC::$server->getConfig()->getAppValue($filename, 'enabled') !== 'no') {
532
+                                    if ($softErrors) {
533
+                                        try {
534
+                                            Installer::installShippedApp($filename);
535
+                                        } catch (HintException $e) {
536
+                                            if ($e->getPrevious() instanceof TableExistsException) {
537
+                                                $errors[$filename] = $e;
538
+                                                continue;
539
+                                            }
540
+                                            throw $e;
541
+                                        }
542
+                                    } else {
543
+                                        Installer::installShippedApp($filename);
544
+                                    }
545
+                                    \OC::$server->getConfig()->setAppValue($filename, 'enabled', 'yes');
546
+                                }
547
+                            }
548
+                        }
549
+                    }
550
+                }
551
+                closedir( $dir );
552
+            }
553
+        }
554
+
555
+        return $errors;
556
+    }
557
+
558
+    /**
559
+     * install an app already placed in the app folder
560
+     * @param string $app id of the app to install
561
+     * @return integer
562
+     */
563
+    public static function installShippedApp($app) {
564
+        //install the database
565
+        $appPath = OC_App::getAppPath($app);
566
+        \OC_App::registerAutoloading($app, $appPath);
567
+
568
+        if(is_file("$appPath/appinfo/database.xml")) {
569
+            try {
570
+                OC_DB::createDbFromStructure("$appPath/appinfo/database.xml");
571
+            } catch (TableExistsException $e) {
572
+                throw new HintException(
573
+                    'Failed to enable app ' . $app,
574
+                    'Please ask for help via one of our <a href="https://nextcloud.com/support/" target="_blank" rel="noreferrer noopener">support channels</a>.',
575
+                    0, $e
576
+                );
577
+            }
578
+        } else {
579
+            $ms = new \OC\DB\MigrationService($app, \OC::$server->getDatabaseConnection());
580
+            $ms->migrate();
581
+        }
582
+
583
+        //run appinfo/install.php
584
+        self::includeAppScript("$appPath/appinfo/install.php");
585
+
586
+        $info = OC_App::getAppInfo($app);
587
+        if (is_null($info)) {
588
+            return false;
589
+        }
590
+        \OC_App::setupBackgroundJobs($info['background-jobs']);
591
+
592
+        OC_App::executeRepairSteps($app, $info['repair-steps']['install']);
593
+
594
+        $config = \OC::$server->getConfig();
595
+
596
+        $config->setAppValue($app, 'installed_version', OC_App::getAppVersion($app));
597
+        if (array_key_exists('ocsid', $info)) {
598
+            $config->setAppValue($app, 'ocsid', $info['ocsid']);
599
+        }
600
+
601
+        //set remote/public handlers
602
+        foreach($info['remote'] as $name=>$path) {
603
+            $config->setAppValue('core', 'remote_'.$name, $app.'/'.$path);
604
+        }
605
+        foreach($info['public'] as $name=>$path) {
606
+            $config->setAppValue('core', 'public_'.$name, $app.'/'.$path);
607
+        }
608
+
609
+        OC_App::setAppTypes($info['id']);
610
+
611
+        if(isset($info['settings']) && is_array($info['settings'])) {
612
+            // requires that autoloading was registered for the app,
613
+            // as happens before running the install.php some lines above
614
+            \OC::$server->getSettingsManager()->setupSettings($info['settings']);
615
+        }
616
+
617
+        return $info['id'];
618
+    }
619
+
620
+    /**
621
+     * @param string $script
622
+     */
623
+    private static function includeAppScript($script) {
624
+        if ( file_exists($script) ){
625
+            include $script;
626
+        }
627
+    }
628 628
 }
Please login to merge, or discard this patch.
Spacing   +54 added lines, -54 removed lines patch added patch discarded remove patch
@@ -100,7 +100,7 @@  discard block
 block discarded – undo
100 100
 	 */
101 101
 	public function installApp($appId) {
102 102
 		$app = \OC_App::findAppInDirectories($appId);
103
-		if($app === false) {
103
+		if ($app === false) {
104 104
 			throw new \Exception('App not found in any app directory');
105 105
 		}
106 106
 
@@ -109,7 +109,7 @@  discard block
 block discarded – undo
109 109
 
110 110
 		$l = \OC::$server->getL10N('core');
111 111
 
112
-		if(!is_array($info)) {
112
+		if (!is_array($info)) {
113 113
 			throw new \Exception(
114 114
 				$l->t('App "%s" cannot be installed because appinfo file cannot be read.',
115 115
 					[$info['name']]
@@ -132,7 +132,7 @@  discard block
 block discarded – undo
132 132
 		\OC_App::registerAutoloading($appId, $basedir);
133 133
 
134 134
 		//install the database
135
-		if(is_file($basedir.'/appinfo/database.xml')) {
135
+		if (is_file($basedir.'/appinfo/database.xml')) {
136 136
 			if (\OC::$server->getConfig()->getAppValue($info['id'], 'installed_version') === null) {
137 137
 				OC_DB::createDbFromStructure($basedir.'/appinfo/database.xml');
138 138
 			} else {
@@ -144,13 +144,13 @@  discard block
 block discarded – undo
144 144
 		}
145 145
 
146 146
 		\OC_App::setupBackgroundJobs($info['background-jobs']);
147
-		if(isset($info['settings']) && is_array($info['settings'])) {
147
+		if (isset($info['settings']) && is_array($info['settings'])) {
148 148
 			\OC::$server->getSettingsManager()->setupSettings($info['settings']);
149 149
 		}
150 150
 
151 151
 		//run appinfo/install.php
152
-		if(!isset($data['noinstall']) or $data['noinstall']==false) {
153
-			self::includeAppScript($basedir . '/appinfo/install.php');
152
+		if (!isset($data['noinstall']) or $data['noinstall'] == false) {
153
+			self::includeAppScript($basedir.'/appinfo/install.php');
154 154
 		}
155 155
 
156 156
 		$appData = OC_App::getAppInfo($appId);
@@ -161,10 +161,10 @@  discard block
 block discarded – undo
161 161
 		\OC::$server->getConfig()->setAppValue($info['id'], 'enabled', 'no');
162 162
 
163 163
 		//set remote/public handlers
164
-		foreach($info['remote'] as $name=>$path) {
164
+		foreach ($info['remote'] as $name=>$path) {
165 165
 			\OC::$server->getConfig()->setAppValue('core', 'remote_'.$name, $info['id'].'/'.$path);
166 166
 		}
167
-		foreach($info['public'] as $name=>$path) {
167
+		foreach ($info['public'] as $name=>$path) {
168 168
 			\OC::$server->getConfig()->setAppValue('core', 'public_'.$name, $info['id'].'/'.$path);
169 169
 		}
170 170
 
@@ -180,7 +180,7 @@  discard block
 block discarded – undo
180 180
 	 *
181 181
 	 * Checks whether or not an app is installed, i.e. registered in apps table.
182 182
 	 */
183
-	public static function isInstalled( $app ) {
183
+	public static function isInstalled($app) {
184 184
 		return (\OC::$server->getConfig()->getAppValue($app, "installed_version", null) !== null);
185 185
 	}
186 186
 
@@ -191,7 +191,7 @@  discard block
 block discarded – undo
191 191
 	 * @return bool
192 192
 	 */
193 193
 	public function updateAppstoreApp($appId) {
194
-		if($this->isUpdateAvailable($appId)) {
194
+		if ($this->isUpdateAvailable($appId)) {
195 195
 			try {
196 196
 				$this->downloadApp($appId);
197 197
 			} catch (\Exception $e) {
@@ -218,18 +218,18 @@  discard block
 block discarded – undo
218 218
 		$appId = strtolower($appId);
219 219
 
220 220
 		$apps = $this->appFetcher->get();
221
-		foreach($apps as $app) {
222
-			if($app['id'] === $appId) {
221
+		foreach ($apps as $app) {
222
+			if ($app['id'] === $appId) {
223 223
 				// Load the certificate
224 224
 				$certificate = new X509();
225
-				$certificate->loadCA(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crt'));
225
+				$certificate->loadCA(file_get_contents(__DIR__.'/../../resources/codesigning/root.crt'));
226 226
 				$loadedCertificate = $certificate->loadX509($app['certificate']);
227 227
 
228 228
 				// Verify if the certificate has been revoked
229 229
 				$crl = new X509();
230
-				$crl->loadCA(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crt'));
231
-				$crl->loadCRL(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crl'));
232
-				if($crl->validateSignature() !== true) {
230
+				$crl->loadCA(file_get_contents(__DIR__.'/../../resources/codesigning/root.crt'));
231
+				$crl->loadCRL(file_get_contents(__DIR__.'/../../resources/codesigning/root.crl'));
232
+				if ($crl->validateSignature() !== true) {
233 233
 					throw new \Exception('Could not validate CRL signature');
234 234
 				}
235 235
 				$csn = $loadedCertificate['tbsCertificate']['serialNumber']->toString();
@@ -244,7 +244,7 @@  discard block
 block discarded – undo
244 244
 				}
245 245
 
246 246
 				// Verify if the certificate has been issued by the Nextcloud Code Authority CA
247
-				if($certificate->validateSignature() !== true) {
247
+				if ($certificate->validateSignature() !== true) {
248 248
 					throw new \Exception(
249 249
 						sprintf(
250 250
 							'App with id %s has a certificate not issued by a trusted Code Signing Authority',
@@ -255,7 +255,7 @@  discard block
 block discarded – undo
255 255
 
256 256
 				// Verify if the certificate is issued for the requested app id
257 257
 				$certInfo = openssl_x509_parse($app['certificate']);
258
-				if(!isset($certInfo['subject']['CN'])) {
258
+				if (!isset($certInfo['subject']['CN'])) {
259 259
 					throw new \Exception(
260 260
 						sprintf(
261 261
 							'App with id %s has a cert with no CN',
@@ -263,7 +263,7 @@  discard block
 block discarded – undo
263 263
 						)
264 264
 					);
265 265
 				}
266
-				if($certInfo['subject']['CN'] !== $appId) {
266
+				if ($certInfo['subject']['CN'] !== $appId) {
267 267
 					throw new \Exception(
268 268
 						sprintf(
269 269
 							'App with id %s has a cert issued to %s',
@@ -280,15 +280,15 @@  discard block
 block discarded – undo
280 280
 
281 281
 				// Check if the signature actually matches the downloaded content
282 282
 				$certificate = openssl_get_publickey($app['certificate']);
283
-				$verified = (bool)openssl_verify(file_get_contents($tempFile), base64_decode($app['releases'][0]['signature']), $certificate, OPENSSL_ALGO_SHA512);
283
+				$verified = (bool) openssl_verify(file_get_contents($tempFile), base64_decode($app['releases'][0]['signature']), $certificate, OPENSSL_ALGO_SHA512);
284 284
 				openssl_free_key($certificate);
285 285
 
286
-				if($verified === true) {
286
+				if ($verified === true) {
287 287
 					// Seems to match, let's proceed
288 288
 					$extractDir = $this->tempManager->getTemporaryFolder();
289 289
 					$archive = new TAR($tempFile);
290 290
 
291
-					if($archive) {
291
+					if ($archive) {
292 292
 						if (!$archive->extract($extractDir)) {
293 293
 							throw new \Exception(
294 294
 								sprintf(
@@ -301,7 +301,7 @@  discard block
 block discarded – undo
301 301
 						$folders = array_diff($allFiles, ['.', '..']);
302 302
 						$folders = array_values($folders);
303 303
 
304
-						if(count($folders) > 1) {
304
+						if (count($folders) > 1) {
305 305
 							throw new \Exception(
306 306
 								sprintf(
307 307
 									'Extracted app %s has more than 1 folder',
@@ -312,22 +312,22 @@  discard block
 block discarded – undo
312 312
 
313 313
 						// Check if appinfo/info.xml has the same app ID as well
314 314
 						$loadEntities = libxml_disable_entity_loader(false);
315
-						$xml = simplexml_load_file($extractDir . '/' . $folders[0] . '/appinfo/info.xml');
315
+						$xml = simplexml_load_file($extractDir.'/'.$folders[0].'/appinfo/info.xml');
316 316
 						libxml_disable_entity_loader($loadEntities);
317
-						if((string)$xml->id !== $appId) {
317
+						if ((string) $xml->id !== $appId) {
318 318
 							throw new \Exception(
319 319
 								sprintf(
320 320
 									'App for id %s has a wrong app ID in info.xml: %s',
321 321
 									$appId,
322
-									(string)$xml->id
322
+									(string) $xml->id
323 323
 								)
324 324
 							);
325 325
 						}
326 326
 
327 327
 						// Check if the version is lower than before
328 328
 						$currentVersion = OC_App::getAppVersion($appId);
329
-						$newVersion = (string)$xml->version;
330
-						if(version_compare($currentVersion, $newVersion) === 1) {
329
+						$newVersion = (string) $xml->version;
330
+						if (version_compare($currentVersion, $newVersion) === 1) {
331 331
 							throw new \Exception(
332 332
 								sprintf(
333 333
 									'App for id %s has version %s and tried to update to lower version %s',
@@ -338,12 +338,12 @@  discard block
 block discarded – undo
338 338
 							);
339 339
 						}
340 340
 
341
-						$baseDir = OC_App::getInstallPath() . '/' . $appId;
341
+						$baseDir = OC_App::getInstallPath().'/'.$appId;
342 342
 						// Remove old app with the ID if existent
343 343
 						OC_Helper::rmdirr($baseDir);
344 344
 						// Move to app folder
345
-						if(@mkdir($baseDir)) {
346
-							$extractDir .= '/' . $folders[0];
345
+						if (@mkdir($baseDir)) {
346
+							$extractDir .= '/'.$folders[0];
347 347
 							OC_Helper::copyr($extractDir, $baseDir);
348 348
 						}
349 349
 						OC_Helper::copyr($extractDir, $baseDir);
@@ -406,8 +406,8 @@  discard block
 block discarded – undo
406 406
 			$this->apps = $this->appFetcher->get();
407 407
 		}
408 408
 
409
-		foreach($this->apps as $app) {
410
-			if($app['id'] === $appId) {
409
+		foreach ($this->apps as $app) {
410
+			if ($app['id'] === $appId) {
411 411
 				$currentVersion = OC_App::getAppVersion($appId);
412 412
 				$newestVersion = $app['releases'][0]['version'];
413 413
 				if (version_compare($newestVersion, $currentVersion, '>')) {
@@ -430,7 +430,7 @@  discard block
 block discarded – undo
430 430
 	 */
431 431
 	private function isInstalledFromGit($appId) {
432 432
 		$app = \OC_App::findAppInDirectories($appId);
433
-		if($app === false) {
433
+		if ($app === false) {
434 434
 			return false;
435 435
 		}
436 436
 		$basedir = $app['path'].'/'.$appId;
@@ -445,7 +445,7 @@  discard block
 block discarded – undo
445 445
 	 * The function will check if the app is already downloaded in the apps repository
446 446
 	 */
447 447
 	public function isDownloaded($name) {
448
-		foreach(\OC::$APPSROOTS as $dir) {
448
+		foreach (\OC::$APPSROOTS as $dir) {
449 449
 			$dirToTest  = $dir['path'];
450 450
 			$dirToTest .= '/';
451 451
 			$dirToTest .= $name;
@@ -473,14 +473,14 @@  discard block
 block discarded – undo
473 473
 	 * this has to be done by the function oc_app_uninstall().
474 474
 	 */
475 475
 	public function removeApp($appId) {
476
-		if($this->isDownloaded( $appId )) {
476
+		if ($this->isDownloaded($appId)) {
477 477
 			if (\OC::$server->getAppManager()->isShipped($appId)) {
478 478
 				return false;
479 479
 			}
480
-			$appDir = OC_App::getInstallPath() . '/' . $appId;
480
+			$appDir = OC_App::getInstallPath().'/'.$appId;
481 481
 			OC_Helper::rmdirr($appDir);
482 482
 			return true;
483
-		}else{
483
+		} else {
484 484
 			\OCP\Util::writeLog('core', 'can\'t remove app '.$appId.'. It is not installed.', \OCP\Util::ERROR);
485 485
 
486 486
 			return false;
@@ -496,8 +496,8 @@  discard block
 block discarded – undo
496 496
 	 */
497 497
 	public function installAppBundle(Bundle $bundle) {
498 498
 		$appIds = $bundle->getAppIdentifiers();
499
-		foreach($appIds as $appId) {
500
-			if(!$this->isDownloaded($appId)) {
499
+		foreach ($appIds as $appId) {
500
+			if (!$this->isDownloaded($appId)) {
501 501
 				$this->downloadApp($appId);
502 502
 			}
503 503
 			$this->installApp($appId);
@@ -519,13 +519,13 @@  discard block
 block discarded – undo
519 519
 	 */
520 520
 	public static function installShippedApps($softErrors = false) {
521 521
 		$errors = [];
522
-		foreach(\OC::$APPSROOTS as $app_dir) {
523
-			if($dir = opendir( $app_dir['path'] )) {
524
-				while( false !== ( $filename = readdir( $dir ))) {
525
-					if( $filename[0] !== '.' and is_dir($app_dir['path']."/$filename") ) {
526
-						if( file_exists( $app_dir['path']."/$filename/appinfo/info.xml" )) {
527
-							if(!Installer::isInstalled($filename)) {
528
-								$info=OC_App::getAppInfo($filename);
522
+		foreach (\OC::$APPSROOTS as $app_dir) {
523
+			if ($dir = opendir($app_dir['path'])) {
524
+				while (false !== ($filename = readdir($dir))) {
525
+					if ($filename[0] !== '.' and is_dir($app_dir['path']."/$filename")) {
526
+						if (file_exists($app_dir['path']."/$filename/appinfo/info.xml")) {
527
+							if (!Installer::isInstalled($filename)) {
528
+								$info = OC_App::getAppInfo($filename);
529 529
 								$enabled = isset($info['default_enable']);
530 530
 								if (($enabled || in_array($filename, \OC::$server->getAppManager()->getAlwaysEnabledApps()))
531 531
 									  && \OC::$server->getConfig()->getAppValue($filename, 'enabled') !== 'no') {
@@ -548,7 +548,7 @@  discard block
 block discarded – undo
548 548
 						}
549 549
 					}
550 550
 				}
551
-				closedir( $dir );
551
+				closedir($dir);
552 552
 			}
553 553
 		}
554 554
 
@@ -565,12 +565,12 @@  discard block
 block discarded – undo
565 565
 		$appPath = OC_App::getAppPath($app);
566 566
 		\OC_App::registerAutoloading($app, $appPath);
567 567
 
568
-		if(is_file("$appPath/appinfo/database.xml")) {
568
+		if (is_file("$appPath/appinfo/database.xml")) {
569 569
 			try {
570 570
 				OC_DB::createDbFromStructure("$appPath/appinfo/database.xml");
571 571
 			} catch (TableExistsException $e) {
572 572
 				throw new HintException(
573
-					'Failed to enable app ' . $app,
573
+					'Failed to enable app '.$app,
574 574
 					'Please ask for help via one of our <a href="https://nextcloud.com/support/" target="_blank" rel="noreferrer noopener">support channels</a>.',
575 575
 					0, $e
576 576
 				);
@@ -599,16 +599,16 @@  discard block
 block discarded – undo
599 599
 		}
600 600
 
601 601
 		//set remote/public handlers
602
-		foreach($info['remote'] as $name=>$path) {
602
+		foreach ($info['remote'] as $name=>$path) {
603 603
 			$config->setAppValue('core', 'remote_'.$name, $app.'/'.$path);
604 604
 		}
605
-		foreach($info['public'] as $name=>$path) {
605
+		foreach ($info['public'] as $name=>$path) {
606 606
 			$config->setAppValue('core', 'public_'.$name, $app.'/'.$path);
607 607
 		}
608 608
 
609 609
 		OC_App::setAppTypes($info['id']);
610 610
 
611
-		if(isset($info['settings']) && is_array($info['settings'])) {
611
+		if (isset($info['settings']) && is_array($info['settings'])) {
612 612
 			// requires that autoloading was registered for the app,
613 613
 			// as happens before running the install.php some lines above
614 614
 			\OC::$server->getSettingsManager()->setupSettings($info['settings']);
@@ -621,7 +621,7 @@  discard block
 block discarded – undo
621 621
 	 * @param string $script
622 622
 	 */
623 623
 	private static function includeAppScript($script) {
624
-		if ( file_exists($script) ){
624
+		if (file_exists($script)) {
625 625
 			include $script;
626 626
 		}
627 627
 	}
Please login to merge, or discard this patch.
lib/public/App/IAppManager.php 1 patch
Indentation   +118 added lines, -118 removed lines patch added patch discarded remove patch
@@ -37,122 +37,122 @@
 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 mixed
55
-	 * @since 14.0.0
56
-	 */
57
-	public function getAppVersion(string $appId, bool $useCache = true);
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 installed in the instance
71
-	 *
72
-	 * @param string $appId
73
-	 * @return bool
74
-	 * @since 8.0.0
75
-	 */
76
-	public function isInstalled($appId);
77
-
78
-	/**
79
-	 * Enable an app for every user
80
-	 *
81
-	 * @param string $appId
82
-	 * @throws AppPathNotFoundException
83
-	 * @since 8.0.0
84
-	 */
85
-	public function enableApp($appId);
86
-
87
-	/**
88
-	 * Whether a list of types contains a protected app type
89
-	 *
90
-	 * @param string[] $types
91
-	 * @return bool
92
-	 * @since 12.0.0
93
-	 */
94
-	public function hasProtectedAppType($types);
95
-
96
-	/**
97
-	 * Enable an app only for specific groups
98
-	 *
99
-	 * @param string $appId
100
-	 * @param \OCP\IGroup[] $groups
101
-	 * @since 8.0.0
102
-	 */
103
-	public function enableAppForGroups($appId, $groups);
104
-
105
-	/**
106
-	 * Disable an app for every user
107
-	 *
108
-	 * @param string $appId
109
-	 * @since 8.0.0
110
-	 */
111
-	public function disableApp($appId);
112
-
113
-	/**
114
-	 * Get the directory for the given app.
115
-	 *
116
-	 * @param string $appId
117
-	 * @return string
118
-	 * @since 11.0.0
119
-	 * @throws AppPathNotFoundException
120
-	 */
121
-	public function getAppPath($appId);
122
-
123
-	/**
124
-	 * List all apps enabled for a user
125
-	 *
126
-	 * @param \OCP\IUser $user
127
-	 * @return string[]
128
-	 * @since 8.1.0
129
-	 */
130
-	public function getEnabledAppsForUser(IUser $user);
131
-
132
-	/**
133
-	 * List all installed apps
134
-	 *
135
-	 * @return string[]
136
-	 * @since 8.1.0
137
-	 */
138
-	public function getInstalledApps();
139
-
140
-	/**
141
-	 * Clear the cached list of apps when enabling/disabling an app
142
-	 * @since 8.1.0
143
-	 */
144
-	public function clearAppsCache();
145
-
146
-	/**
147
-	 * @param string $appId
148
-	 * @return boolean
149
-	 * @since 9.0.0
150
-	 */
151
-	public function isShipped($appId);
152
-
153
-	/**
154
-	 * @return string[]
155
-	 * @since 9.0.0
156
-	 */
157
-	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 mixed
55
+     * @since 14.0.0
56
+     */
57
+    public function getAppVersion(string $appId, bool $useCache = true);
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 installed in the instance
71
+     *
72
+     * @param string $appId
73
+     * @return bool
74
+     * @since 8.0.0
75
+     */
76
+    public function isInstalled($appId);
77
+
78
+    /**
79
+     * Enable an app for every user
80
+     *
81
+     * @param string $appId
82
+     * @throws AppPathNotFoundException
83
+     * @since 8.0.0
84
+     */
85
+    public function enableApp($appId);
86
+
87
+    /**
88
+     * Whether a list of types contains a protected app type
89
+     *
90
+     * @param string[] $types
91
+     * @return bool
92
+     * @since 12.0.0
93
+     */
94
+    public function hasProtectedAppType($types);
95
+
96
+    /**
97
+     * Enable an app only for specific groups
98
+     *
99
+     * @param string $appId
100
+     * @param \OCP\IGroup[] $groups
101
+     * @since 8.0.0
102
+     */
103
+    public function enableAppForGroups($appId, $groups);
104
+
105
+    /**
106
+     * Disable an app for every user
107
+     *
108
+     * @param string $appId
109
+     * @since 8.0.0
110
+     */
111
+    public function disableApp($appId);
112
+
113
+    /**
114
+     * Get the directory for the given app.
115
+     *
116
+     * @param string $appId
117
+     * @return string
118
+     * @since 11.0.0
119
+     * @throws AppPathNotFoundException
120
+     */
121
+    public function getAppPath($appId);
122
+
123
+    /**
124
+     * List all apps enabled for a user
125
+     *
126
+     * @param \OCP\IUser $user
127
+     * @return string[]
128
+     * @since 8.1.0
129
+     */
130
+    public function getEnabledAppsForUser(IUser $user);
131
+
132
+    /**
133
+     * List all installed apps
134
+     *
135
+     * @return string[]
136
+     * @since 8.1.0
137
+     */
138
+    public function getInstalledApps();
139
+
140
+    /**
141
+     * Clear the cached list of apps when enabling/disabling an app
142
+     * @since 8.1.0
143
+     */
144
+    public function clearAppsCache();
145
+
146
+    /**
147
+     * @param string $appId
148
+     * @return boolean
149
+     * @since 9.0.0
150
+     */
151
+    public function isShipped($appId);
152
+
153
+    /**
154
+     * @return string[]
155
+     * @since 9.0.0
156
+     */
157
+    public function getAlwaysEnabledApps();
158 158
 }
Please login to merge, or discard this patch.
lib/public/App.php 2 patches
Indentation   +64 added lines, -64 removed lines patch added patch discarded remove patch
@@ -45,73 +45,73 @@
 block discarded – undo
45 45
 class App {
46 46
 
47 47
 
48
-	/**
49
-	 * Register a Configuration Screen that should appear in the personal settings section.
50
-	 * @param string $app appid
51
-	 * @param string $page page to be included
52
-	 * @return void
53
-	 * @since 4.0.0
54
-	 * @deprecated 14.0.0 Use settings section in appinfo.xml to register personal admin sections
55
-	*/
56
-	public static function registerPersonal( $app, $page ) {
57
-		\OC_App::registerPersonal( $app, $page );
58
-	}
48
+    /**
49
+     * Register a Configuration Screen that should appear in the personal settings section.
50
+     * @param string $app appid
51
+     * @param string $page page to be included
52
+     * @return void
53
+     * @since 4.0.0
54
+     * @deprecated 14.0.0 Use settings section in appinfo.xml to register personal admin sections
55
+     */
56
+    public static function registerPersonal( $app, $page ) {
57
+        \OC_App::registerPersonal( $app, $page );
58
+    }
59 59
 
60
-	/**
61
-	 * Register a Configuration Screen that should appear in the Admin section.
62
-	 * @param string $app string appid
63
-	 * @param string $page string page to be included
64
-	 * @return void
65
-	 * @since 4.0.0
66
-	 * @deprecated 14.0.0 Use settings section in appinfo.xml to register admin sections
67
-	 */
68
-	public static function registerAdmin( $app, $page ) {
69
-		\OC_App::registerAdmin( $app, $page );
70
-	}
60
+    /**
61
+     * Register a Configuration Screen that should appear in the Admin section.
62
+     * @param string $app string appid
63
+     * @param string $page string page to be included
64
+     * @return void
65
+     * @since 4.0.0
66
+     * @deprecated 14.0.0 Use settings section in appinfo.xml to register admin sections
67
+     */
68
+    public static function registerAdmin( $app, $page ) {
69
+        \OC_App::registerAdmin( $app, $page );
70
+    }
71 71
 
72
-	/**
73
-	 * Read app metadata from the info.xml file
74
-	 * @param string $app id of the app or the path of the info.xml file
75
-	 * @param boolean $path (optional)
76
-	 * @return array|null
77
-	 * @deprecated 14.0.0 ise \OC::$server->getAppManager()->getAppInfo($appId)
78
-	 * @since 4.0.0
79
-	*/
80
-	public static function getAppInfo( $app, $path=false ) {
81
-		return \OC_App::getAppInfo( $app, $path);
82
-	}
72
+    /**
73
+     * Read app metadata from the info.xml file
74
+     * @param string $app id of the app or the path of the info.xml file
75
+     * @param boolean $path (optional)
76
+     * @return array|null
77
+     * @deprecated 14.0.0 ise \OC::$server->getAppManager()->getAppInfo($appId)
78
+     * @since 4.0.0
79
+     */
80
+    public static function getAppInfo( $app, $path=false ) {
81
+        return \OC_App::getAppInfo( $app, $path);
82
+    }
83 83
 
84
-	/**
85
-	 * checks whether or not an app is enabled
86
-	 * @param string $app
87
-	 * @return boolean
88
-	 *
89
-	 * This function checks whether or not an app is enabled.
90
-	 * @since 4.0.0
91
-	 * @deprecated 13.0.0 use \OC::$server->getAppManager()->isEnabledForUser($appId)
92
-	 */
93
-	public static function isEnabled( $app ) {
94
-		return \OC::$server->getAppManager()->isEnabledForUser( $app );
95
-	}
84
+    /**
85
+     * checks whether or not an app is enabled
86
+     * @param string $app
87
+     * @return boolean
88
+     *
89
+     * This function checks whether or not an app is enabled.
90
+     * @since 4.0.0
91
+     * @deprecated 13.0.0 use \OC::$server->getAppManager()->isEnabledForUser($appId)
92
+     */
93
+    public static function isEnabled( $app ) {
94
+        return \OC::$server->getAppManager()->isEnabledForUser( $app );
95
+    }
96 96
 
97
-	/**
98
-	 * Check if the app is enabled, redirects to home if not
99
-	 * @param string $app
100
-	 * @return void
101
-	 * @since 4.0.0
102
-	 * @deprecated 9.0.0 ownCloud core will handle disabled apps and redirects to valid URLs
103
-	*/
104
-	public static function checkAppEnabled( $app ) {
105
-	}
97
+    /**
98
+     * Check if the app is enabled, redirects to home if not
99
+     * @param string $app
100
+     * @return void
101
+     * @since 4.0.0
102
+     * @deprecated 9.0.0 ownCloud core will handle disabled apps and redirects to valid URLs
103
+     */
104
+    public static function checkAppEnabled( $app ) {
105
+    }
106 106
 
107
-	/**
108
-	 * Get the last version of the app from appinfo/info.xml
109
-	 * @param string $app
110
-	 * @return string
111
-	 * @since 4.0.0
112
-	 * @deprecated 14.0.0 use \OC::$server->getAppManager()->getAppVersion($appId)
113
-	 */
114
-	public static function getAppVersion( $app ) {
115
-		return \OC::$server->getAppManager()->getAppVersion($app);
116
-	}
107
+    /**
108
+     * Get the last version of the app from appinfo/info.xml
109
+     * @param string $app
110
+     * @return string
111
+     * @since 4.0.0
112
+     * @deprecated 14.0.0 use \OC::$server->getAppManager()->getAppVersion($appId)
113
+     */
114
+    public static function getAppVersion( $app ) {
115
+        return \OC::$server->getAppManager()->getAppVersion($app);
116
+    }
117 117
 }
Please login to merge, or discard this patch.
Spacing   +10 added lines, -10 removed lines patch added patch discarded remove patch
@@ -53,8 +53,8 @@  discard block
 block discarded – undo
53 53
 	 * @since 4.0.0
54 54
 	 * @deprecated 14.0.0 Use settings section in appinfo.xml to register personal admin sections
55 55
 	*/
56
-	public static function registerPersonal( $app, $page ) {
57
-		\OC_App::registerPersonal( $app, $page );
56
+	public static function registerPersonal($app, $page) {
57
+		\OC_App::registerPersonal($app, $page);
58 58
 	}
59 59
 
60 60
 	/**
@@ -65,8 +65,8 @@  discard block
 block discarded – undo
65 65
 	 * @since 4.0.0
66 66
 	 * @deprecated 14.0.0 Use settings section in appinfo.xml to register admin sections
67 67
 	 */
68
-	public static function registerAdmin( $app, $page ) {
69
-		\OC_App::registerAdmin( $app, $page );
68
+	public static function registerAdmin($app, $page) {
69
+		\OC_App::registerAdmin($app, $page);
70 70
 	}
71 71
 
72 72
 	/**
@@ -77,8 +77,8 @@  discard block
 block discarded – undo
77 77
 	 * @deprecated 14.0.0 ise \OC::$server->getAppManager()->getAppInfo($appId)
78 78
 	 * @since 4.0.0
79 79
 	*/
80
-	public static function getAppInfo( $app, $path=false ) {
81
-		return \OC_App::getAppInfo( $app, $path);
80
+	public static function getAppInfo($app, $path = false) {
81
+		return \OC_App::getAppInfo($app, $path);
82 82
 	}
83 83
 
84 84
 	/**
@@ -90,8 +90,8 @@  discard block
 block discarded – undo
90 90
 	 * @since 4.0.0
91 91
 	 * @deprecated 13.0.0 use \OC::$server->getAppManager()->isEnabledForUser($appId)
92 92
 	 */
93
-	public static function isEnabled( $app ) {
94
-		return \OC::$server->getAppManager()->isEnabledForUser( $app );
93
+	public static function isEnabled($app) {
94
+		return \OC::$server->getAppManager()->isEnabledForUser($app);
95 95
 	}
96 96
 
97 97
 	/**
@@ -101,7 +101,7 @@  discard block
 block discarded – undo
101 101
 	 * @since 4.0.0
102 102
 	 * @deprecated 9.0.0 ownCloud core will handle disabled apps and redirects to valid URLs
103 103
 	*/
104
-	public static function checkAppEnabled( $app ) {
104
+	public static function checkAppEnabled($app) {
105 105
 	}
106 106
 
107 107
 	/**
@@ -111,7 +111,7 @@  discard block
 block discarded – undo
111 111
 	 * @since 4.0.0
112 112
 	 * @deprecated 14.0.0 use \OC::$server->getAppManager()->getAppVersion($appId)
113 113
 	 */
114
-	public static function getAppVersion( $app ) {
114
+	public static function getAppVersion($app) {
115 115
 		return \OC::$server->getAppManager()->getAppVersion($app);
116 116
 	}
117 117
 }
Please login to merge, or discard this patch.
lib/base.php 1 patch
Indentation   +1009 added lines, -1009 removed lines patch added patch discarded remove patch
@@ -62,1015 +62,1015 @@
 block discarded – undo
62 62
  * OC_autoload!
63 63
  */
64 64
 class OC {
65
-	/**
66
-	 * Associative array for autoloading. classname => filename
67
-	 */
68
-	public static $CLASSPATH = array();
69
-	/**
70
-	 * The installation path for Nextcloud  on the server (e.g. /srv/http/nextcloud)
71
-	 */
72
-	public static $SERVERROOT = '';
73
-	/**
74
-	 * the current request path relative to the Nextcloud root (e.g. files/index.php)
75
-	 */
76
-	private static $SUBURI = '';
77
-	/**
78
-	 * the Nextcloud root path for http requests (e.g. nextcloud/)
79
-	 */
80
-	public static $WEBROOT = '';
81
-	/**
82
-	 * The installation path array of the apps folder on the server (e.g. /srv/http/nextcloud) 'path' and
83
-	 * web path in 'url'
84
-	 */
85
-	public static $APPSROOTS = array();
86
-
87
-	/**
88
-	 * @var string
89
-	 */
90
-	public static $configDir;
91
-
92
-	/**
93
-	 * requested app
94
-	 */
95
-	public static $REQUESTEDAPP = '';
96
-
97
-	/**
98
-	 * check if Nextcloud runs in cli mode
99
-	 */
100
-	public static $CLI = false;
101
-
102
-	/**
103
-	 * @var \OC\Autoloader $loader
104
-	 */
105
-	public static $loader = null;
106
-
107
-	/** @var \Composer\Autoload\ClassLoader $composerAutoloader */
108
-	public static $composerAutoloader = null;
109
-
110
-	/**
111
-	 * @var \OC\Server
112
-	 */
113
-	public static $server = null;
114
-
115
-	/**
116
-	 * @var \OC\Config
117
-	 */
118
-	private static $config = null;
119
-
120
-	/**
121
-	 * @throws \RuntimeException when the 3rdparty directory is missing or
122
-	 * the app path list is empty or contains an invalid path
123
-	 */
124
-	public static function initPaths() {
125
-		if(defined('PHPUNIT_CONFIG_DIR')) {
126
-			self::$configDir = OC::$SERVERROOT . '/' . PHPUNIT_CONFIG_DIR . '/';
127
-		} elseif(defined('PHPUNIT_RUN') and PHPUNIT_RUN and is_dir(OC::$SERVERROOT . '/tests/config/')) {
128
-			self::$configDir = OC::$SERVERROOT . '/tests/config/';
129
-		} elseif($dir = getenv('NEXTCLOUD_CONFIG_DIR')) {
130
-			self::$configDir = rtrim($dir, '/') . '/';
131
-		} else {
132
-			self::$configDir = OC::$SERVERROOT . '/config/';
133
-		}
134
-		self::$config = new \OC\Config(self::$configDir);
135
-
136
-		OC::$SUBURI = str_replace("\\", "/", substr(realpath($_SERVER["SCRIPT_FILENAME"]), strlen(OC::$SERVERROOT)));
137
-		/**
138
-		 * FIXME: The following lines are required because we can't yet instantiate
139
-		 *        \OC::$server->getRequest() since \OC::$server does not yet exist.
140
-		 */
141
-		$params = [
142
-			'server' => [
143
-				'SCRIPT_NAME' => $_SERVER['SCRIPT_NAME'],
144
-				'SCRIPT_FILENAME' => $_SERVER['SCRIPT_FILENAME'],
145
-			],
146
-		];
147
-		$fakeRequest = new \OC\AppFramework\Http\Request($params, null, new \OC\AllConfig(new \OC\SystemConfig(self::$config)));
148
-		$scriptName = $fakeRequest->getScriptName();
149
-		if (substr($scriptName, -1) == '/') {
150
-			$scriptName .= 'index.php';
151
-			//make sure suburi follows the same rules as scriptName
152
-			if (substr(OC::$SUBURI, -9) != 'index.php') {
153
-				if (substr(OC::$SUBURI, -1) != '/') {
154
-					OC::$SUBURI = OC::$SUBURI . '/';
155
-				}
156
-				OC::$SUBURI = OC::$SUBURI . 'index.php';
157
-			}
158
-		}
159
-
160
-
161
-		if (OC::$CLI) {
162
-			OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
163
-		} else {
164
-			if (substr($scriptName, 0 - strlen(OC::$SUBURI)) === OC::$SUBURI) {
165
-				OC::$WEBROOT = substr($scriptName, 0, 0 - strlen(OC::$SUBURI));
166
-
167
-				if (OC::$WEBROOT != '' && OC::$WEBROOT[0] !== '/') {
168
-					OC::$WEBROOT = '/' . OC::$WEBROOT;
169
-				}
170
-			} else {
171
-				// The scriptName is not ending with OC::$SUBURI
172
-				// This most likely means that we are calling from CLI.
173
-				// However some cron jobs still need to generate
174
-				// a web URL, so we use overwritewebroot as a fallback.
175
-				OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
176
-			}
177
-
178
-			// Resolve /nextcloud to /nextcloud/ to ensure to always have a trailing
179
-			// slash which is required by URL generation.
180
-			if (isset($_SERVER['REQUEST_URI']) && $_SERVER['REQUEST_URI'] === \OC::$WEBROOT &&
181
-					substr($_SERVER['REQUEST_URI'], -1) !== '/') {
182
-				header('Location: '.\OC::$WEBROOT.'/');
183
-				exit();
184
-			}
185
-		}
186
-
187
-		// search the apps folder
188
-		$config_paths = self::$config->getValue('apps_paths', array());
189
-		if (!empty($config_paths)) {
190
-			foreach ($config_paths as $paths) {
191
-				if (isset($paths['url']) && isset($paths['path'])) {
192
-					$paths['url'] = rtrim($paths['url'], '/');
193
-					$paths['path'] = rtrim($paths['path'], '/');
194
-					OC::$APPSROOTS[] = $paths;
195
-				}
196
-			}
197
-		} elseif (file_exists(OC::$SERVERROOT . '/apps')) {
198
-			OC::$APPSROOTS[] = array('path' => OC::$SERVERROOT . '/apps', 'url' => '/apps', 'writable' => true);
199
-		} elseif (file_exists(OC::$SERVERROOT . '/../apps')) {
200
-			OC::$APPSROOTS[] = array(
201
-				'path' => rtrim(dirname(OC::$SERVERROOT), '/') . '/apps',
202
-				'url' => '/apps',
203
-				'writable' => true
204
-			);
205
-		}
206
-
207
-		if (empty(OC::$APPSROOTS)) {
208
-			throw new \RuntimeException('apps directory not found! Please put the Nextcloud apps folder in the Nextcloud folder'
209
-				. ' or the folder above. You can also configure the location in the config.php file.');
210
-		}
211
-		$paths = array();
212
-		foreach (OC::$APPSROOTS as $path) {
213
-			$paths[] = $path['path'];
214
-			if (!is_dir($path['path'])) {
215
-				throw new \RuntimeException(sprintf('App directory "%s" not found! Please put the Nextcloud apps folder in the'
216
-					. ' Nextcloud folder or the folder above. You can also configure the location in the'
217
-					. ' config.php file.', $path['path']));
218
-			}
219
-		}
220
-
221
-		// set the right include path
222
-		set_include_path(
223
-			implode(PATH_SEPARATOR, $paths)
224
-		);
225
-	}
226
-
227
-	public static function checkConfig() {
228
-		$l = \OC::$server->getL10N('lib');
229
-
230
-		// Create config if it does not already exist
231
-		$configFilePath = self::$configDir .'/config.php';
232
-		if(!file_exists($configFilePath)) {
233
-			@touch($configFilePath);
234
-		}
235
-
236
-		// Check if config is writable
237
-		$configFileWritable = is_writable($configFilePath);
238
-		if (!$configFileWritable && !OC_Helper::isReadOnlyConfigEnabled()
239
-			|| !$configFileWritable && \OCP\Util::needUpgrade()) {
240
-
241
-			$urlGenerator = \OC::$server->getURLGenerator();
242
-
243
-			if (self::$CLI) {
244
-				echo $l->t('Cannot write into "config" directory!')."\n";
245
-				echo $l->t('This can usually be fixed by giving the webserver write access to the config directory')."\n";
246
-				echo "\n";
247
-				echo $l->t('See %s', [ $urlGenerator->linkToDocs('admin-dir_permissions') ])."\n";
248
-				exit;
249
-			} else {
250
-				OC_Template::printErrorPage(
251
-					$l->t('Cannot write into "config" directory!'),
252
-					$l->t('This can usually be fixed by giving the webserver write access to the config directory. See %s',
253
-					 [ $urlGenerator->linkToDocs('admin-dir_permissions') ])
254
-				);
255
-			}
256
-		}
257
-	}
258
-
259
-	public static function checkInstalled() {
260
-		if (defined('OC_CONSOLE')) {
261
-			return;
262
-		}
263
-		// Redirect to installer if not installed
264
-		if (!\OC::$server->getSystemConfig()->getValue('installed', false) && OC::$SUBURI !== '/index.php' && OC::$SUBURI !== '/status.php') {
265
-			if (OC::$CLI) {
266
-				throw new Exception('Not installed');
267
-			} else {
268
-				$url = OC::$WEBROOT . '/index.php';
269
-				header('Location: ' . $url);
270
-			}
271
-			exit();
272
-		}
273
-	}
274
-
275
-	public static function checkMaintenanceMode() {
276
-		// Allow ajax update script to execute without being stopped
277
-		if (\OC::$server->getSystemConfig()->getValue('maintenance', false) && OC::$SUBURI != '/core/ajax/update.php') {
278
-			// send http status 503
279
-			header('HTTP/1.1 503 Service Temporarily Unavailable');
280
-			header('Status: 503 Service Temporarily Unavailable');
281
-			header('Retry-After: 120');
282
-
283
-			// render error page
284
-			$template = new OC_Template('', 'update.user', 'guest');
285
-			OC_Util::addScript('maintenance-check');
286
-			OC_Util::addStyle('core', 'guest');
287
-			$template->printPage();
288
-			die();
289
-		}
290
-	}
291
-
292
-	/**
293
-	 * Prints the upgrade page
294
-	 *
295
-	 * @param \OC\SystemConfig $systemConfig
296
-	 */
297
-	private static function printUpgradePage(\OC\SystemConfig $systemConfig) {
298
-		$disableWebUpdater = $systemConfig->getValue('upgrade.disable-web', false);
299
-		$tooBig = false;
300
-		if (!$disableWebUpdater) {
301
-			$apps = \OC::$server->getAppManager();
302
-			if ($apps->isInstalled('user_ldap')) {
303
-				$qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
304
-
305
-				$result = $qb->selectAlias($qb->createFunction('COUNT(*)'), 'user_count')
306
-					->from('ldap_user_mapping')
307
-					->execute();
308
-				$row = $result->fetch();
309
-				$result->closeCursor();
310
-
311
-				$tooBig = ($row['user_count'] > 50);
312
-			}
313
-			if (!$tooBig && $apps->isInstalled('user_saml')) {
314
-				$qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
315
-
316
-				$result = $qb->selectAlias($qb->createFunction('COUNT(*)'), 'user_count')
317
-					->from('user_saml_users')
318
-					->execute();
319
-				$row = $result->fetch();
320
-				$result->closeCursor();
321
-
322
-				$tooBig = ($row['user_count'] > 50);
323
-			}
324
-			if (!$tooBig) {
325
-				// count users
326
-				$stats = \OC::$server->getUserManager()->countUsers();
327
-				$totalUsers = array_sum($stats);
328
-				$tooBig = ($totalUsers > 50);
329
-			}
330
-		}
331
-		$ignoreTooBigWarning = isset($_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup']) &&
332
-			$_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup'] === 'IAmSuperSureToDoThis';
333
-
334
-		if ($disableWebUpdater || ($tooBig && !$ignoreTooBigWarning)) {
335
-			// send http status 503
336
-			header('HTTP/1.1 503 Service Temporarily Unavailable');
337
-			header('Status: 503 Service Temporarily Unavailable');
338
-			header('Retry-After: 120');
339
-
340
-			// render error page
341
-			$template = new OC_Template('', 'update.use-cli', 'guest');
342
-			$template->assign('productName', 'nextcloud'); // for now
343
-			$template->assign('version', OC_Util::getVersionString());
344
-			$template->assign('tooBig', $tooBig);
345
-
346
-			$template->printPage();
347
-			die();
348
-		}
349
-
350
-		// check whether this is a core update or apps update
351
-		$installedVersion = $systemConfig->getValue('version', '0.0.0');
352
-		$currentVersion = implode('.', \OCP\Util::getVersion());
353
-
354
-		// if not a core upgrade, then it's apps upgrade
355
-		$isAppsOnlyUpgrade = version_compare($currentVersion, $installedVersion, '=');
356
-
357
-		$oldTheme = $systemConfig->getValue('theme');
358
-		$systemConfig->setValue('theme', '');
359
-		OC_Util::addScript('config'); // needed for web root
360
-		OC_Util::addScript('update');
361
-
362
-		/** @var \OC\App\AppManager $appManager */
363
-		$appManager = \OC::$server->getAppManager();
364
-
365
-		$tmpl = new OC_Template('', 'update.admin', 'guest');
366
-		$tmpl->assign('version', OC_Util::getVersionString());
367
-		$tmpl->assign('isAppsOnlyUpgrade', $isAppsOnlyUpgrade);
368
-
369
-		// get third party apps
370
-		$ocVersion = \OCP\Util::getVersion();
371
-		$incompatibleApps = $appManager->getIncompatibleApps($ocVersion);
372
-		$incompatibleShippedApps = [];
373
-		foreach ($incompatibleApps as $appInfo) {
374
-			if ($appManager->isShipped($appInfo['id'])) {
375
-				$incompatibleShippedApps[] = $appInfo['name'] . ' (' . $appInfo['id'] . ')';
376
-			}
377
-		}
378
-
379
-		if (!empty($incompatibleShippedApps)) {
380
-			$l = \OC::$server->getL10N('core');
381
-			$hint = $l->t('The files of the app %$1s were not replaced correctly. Make sure it is a version compatible with the server.', [implode(', ', $incompatibleShippedApps)]);
382
-			throw new \OC\HintException('The files of the app ' . implode(', ', $incompatibleShippedApps) . ' were not replaced correctly. Make sure it is a version compatible with the server.', $hint);
383
-		}
384
-
385
-		$tmpl->assign('appsToUpgrade', $appManager->getAppsNeedingUpgrade($ocVersion));
386
-		$tmpl->assign('incompatibleAppsList', $incompatibleApps);
387
-		$tmpl->assign('productName', 'Nextcloud'); // for now
388
-		$tmpl->assign('oldTheme', $oldTheme);
389
-		$tmpl->printPage();
390
-	}
391
-
392
-	public static function initSession() {
393
-		if(self::$server->getRequest()->getServerProtocol() === 'https') {
394
-			ini_set('session.cookie_secure', true);
395
-		}
396
-
397
-		// prevents javascript from accessing php session cookies
398
-		ini_set('session.cookie_httponly', 'true');
399
-
400
-		// set the cookie path to the Nextcloud directory
401
-		$cookie_path = OC::$WEBROOT ? : '/';
402
-		ini_set('session.cookie_path', $cookie_path);
403
-
404
-		// Let the session name be changed in the initSession Hook
405
-		$sessionName = OC_Util::getInstanceId();
406
-
407
-		try {
408
-			// Allow session apps to create a custom session object
409
-			$useCustomSession = false;
410
-			$session = self::$server->getSession();
411
-			OC_Hook::emit('OC', 'initSession', array('session' => &$session, 'sessionName' => &$sessionName, 'useCustomSession' => &$useCustomSession));
412
-			if (!$useCustomSession) {
413
-				// set the session name to the instance id - which is unique
414
-				$session = new \OC\Session\Internal($sessionName);
415
-			}
416
-
417
-			$cryptoWrapper = \OC::$server->getSessionCryptoWrapper();
418
-			$session = $cryptoWrapper->wrapSession($session);
419
-			self::$server->setSession($session);
420
-
421
-			// if session can't be started break with http 500 error
422
-		} catch (Exception $e) {
423
-			\OCP\Util::logException('base', $e);
424
-			//show the user a detailed error page
425
-			OC_Response::setStatus(OC_Response::STATUS_INTERNAL_SERVER_ERROR);
426
-			OC_Template::printExceptionErrorPage($e);
427
-			die();
428
-		}
429
-
430
-		$sessionLifeTime = self::getSessionLifeTime();
431
-
432
-		// session timeout
433
-		if ($session->exists('LAST_ACTIVITY') && (time() - $session->get('LAST_ACTIVITY') > $sessionLifeTime)) {
434
-			if (isset($_COOKIE[session_name()])) {
435
-				setcookie(session_name(), null, -1, self::$WEBROOT ? : '/');
436
-			}
437
-			\OC::$server->getUserSession()->logout();
438
-		}
439
-
440
-		$session->set('LAST_ACTIVITY', time());
441
-	}
442
-
443
-	/**
444
-	 * @return string
445
-	 */
446
-	private static function getSessionLifeTime() {
447
-		return \OC::$server->getConfig()->getSystemValue('session_lifetime', 60 * 60 * 24);
448
-	}
449
-
450
-	public static function loadAppClassPaths() {
451
-		foreach (OC_App::getEnabledApps() as $app) {
452
-			$appPath = OC_App::getAppPath($app);
453
-			if ($appPath === false) {
454
-				continue;
455
-			}
456
-
457
-			$file = $appPath . '/appinfo/classpath.php';
458
-			if (file_exists($file)) {
459
-				require_once $file;
460
-			}
461
-		}
462
-	}
463
-
464
-	/**
465
-	 * Try to set some values to the required Nextcloud default
466
-	 */
467
-	public static function setRequiredIniValues() {
468
-		@ini_set('default_charset', 'UTF-8');
469
-		@ini_set('gd.jpeg_ignore_warning', '1');
470
-	}
471
-
472
-	/**
473
-	 * Send the same site cookies
474
-	 */
475
-	private static function sendSameSiteCookies() {
476
-		$cookieParams = session_get_cookie_params();
477
-		$secureCookie = ($cookieParams['secure'] === true) ? 'secure; ' : '';
478
-		$policies = [
479
-			'lax',
480
-			'strict',
481
-		];
482
-
483
-		// Append __Host to the cookie if it meets the requirements
484
-		$cookiePrefix = '';
485
-		if($cookieParams['secure'] === true && $cookieParams['path'] === '/') {
486
-			$cookiePrefix = '__Host-';
487
-		}
488
-
489
-		foreach($policies as $policy) {
490
-			header(
491
-				sprintf(
492
-					'Set-Cookie: %snc_sameSiteCookie%s=true; path=%s; httponly;' . $secureCookie . 'expires=Fri, 31-Dec-2100 23:59:59 GMT; SameSite=%s',
493
-					$cookiePrefix,
494
-					$policy,
495
-					$cookieParams['path'],
496
-					$policy
497
-				),
498
-				false
499
-			);
500
-		}
501
-	}
502
-
503
-	/**
504
-	 * Same Site cookie to further mitigate CSRF attacks. This cookie has to
505
-	 * be set in every request if cookies are sent to add a second level of
506
-	 * defense against CSRF.
507
-	 *
508
-	 * If the cookie is not sent this will set the cookie and reload the page.
509
-	 * We use an additional cookie since we want to protect logout CSRF and
510
-	 * also we can't directly interfere with PHP's session mechanism.
511
-	 */
512
-	private static function performSameSiteCookieProtection() {
513
-		$request = \OC::$server->getRequest();
514
-
515
-		// Some user agents are notorious and don't really properly follow HTTP
516
-		// specifications. For those, have an automated opt-out. Since the protection
517
-		// for remote.php is applied in base.php as starting point we need to opt out
518
-		// here.
519
-		$incompatibleUserAgents = [
520
-			// OS X Finder
521
-			'/^WebDAVFS/',
522
-		];
523
-		if($request->isUserAgent($incompatibleUserAgents)) {
524
-			return;
525
-		}
526
-
527
-		if(count($_COOKIE) > 0) {
528
-			$requestUri = $request->getScriptName();
529
-			$processingScript = explode('/', $requestUri);
530
-			$processingScript = $processingScript[count($processingScript)-1];
531
-
532
-			// index.php routes are handled in the middleware
533
-			if($processingScript === 'index.php') {
534
-				return;
535
-			}
536
-
537
-			// All other endpoints require the lax and the strict cookie
538
-			if(!$request->passesStrictCookieCheck()) {
539
-				self::sendSameSiteCookies();
540
-				// Debug mode gets access to the resources without strict cookie
541
-				// due to the fact that the SabreDAV browser also lives there.
542
-				if(!\OC::$server->getConfig()->getSystemValue('debug', false)) {
543
-					http_response_code(\OCP\AppFramework\Http::STATUS_SERVICE_UNAVAILABLE);
544
-					exit();
545
-				}
546
-			}
547
-		} elseif(!isset($_COOKIE['nc_sameSiteCookielax']) || !isset($_COOKIE['nc_sameSiteCookiestrict'])) {
548
-			self::sendSameSiteCookies();
549
-		}
550
-	}
551
-
552
-	public static function init() {
553
-		// calculate the root directories
554
-		OC::$SERVERROOT = str_replace("\\", '/', substr(__DIR__, 0, -4));
555
-
556
-		// register autoloader
557
-		$loaderStart = microtime(true);
558
-		require_once __DIR__ . '/autoloader.php';
559
-		self::$loader = new \OC\Autoloader([
560
-			OC::$SERVERROOT . '/lib/private/legacy',
561
-		]);
562
-		if (defined('PHPUNIT_RUN')) {
563
-			self::$loader->addValidRoot(OC::$SERVERROOT . '/tests');
564
-		}
565
-		spl_autoload_register(array(self::$loader, 'load'));
566
-		$loaderEnd = microtime(true);
567
-
568
-		self::$CLI = (php_sapi_name() == 'cli');
569
-
570
-		// Add default composer PSR-4 autoloader
571
-		self::$composerAutoloader = require_once OC::$SERVERROOT . '/lib/composer/autoload.php';
572
-
573
-		try {
574
-			self::initPaths();
575
-			// setup 3rdparty autoloader
576
-			$vendorAutoLoad = OC::$SERVERROOT. '/3rdparty/autoload.php';
577
-			if (!file_exists($vendorAutoLoad)) {
578
-				throw new \RuntimeException('Composer autoloader not found, unable to continue. Check the folder "3rdparty". Running "git submodule update --init" will initialize the git submodule that handles the subfolder "3rdparty".');
579
-			}
580
-			require_once $vendorAutoLoad;
581
-
582
-		} catch (\RuntimeException $e) {
583
-			if (!self::$CLI) {
584
-				$claimedProtocol = strtoupper($_SERVER['SERVER_PROTOCOL']);
585
-				$protocol = in_array($claimedProtocol, ['HTTP/1.0', 'HTTP/1.1', 'HTTP/2']) ? $claimedProtocol : 'HTTP/1.1';
586
-				header($protocol . ' ' . OC_Response::STATUS_SERVICE_UNAVAILABLE);
587
-			}
588
-			// we can't use the template error page here, because this needs the
589
-			// DI container which isn't available yet
590
-			print($e->getMessage());
591
-			exit();
592
-		}
593
-
594
-		// setup the basic server
595
-		self::$server = new \OC\Server(\OC::$WEBROOT, self::$config);
596
-		\OC::$server->getEventLogger()->log('autoloader', 'Autoloader', $loaderStart, $loaderEnd);
597
-		\OC::$server->getEventLogger()->start('boot', 'Initialize');
598
-
599
-		// Don't display errors and log them
600
-		error_reporting(E_ALL | E_STRICT);
601
-		@ini_set('display_errors', '0');
602
-		@ini_set('log_errors', '1');
603
-
604
-		if(!date_default_timezone_set('UTC')) {
605
-			throw new \RuntimeException('Could not set timezone to UTC');
606
-		}
607
-
608
-		//try to configure php to enable big file uploads.
609
-		//this doesn´t work always depending on the webserver and php configuration.
610
-		//Let´s try to overwrite some defaults anyway
611
-
612
-		//try to set the maximum execution time to 60min
613
-		if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
614
-			@set_time_limit(3600);
615
-		}
616
-		@ini_set('max_execution_time', '3600');
617
-		@ini_set('max_input_time', '3600');
618
-
619
-		//try to set the maximum filesize to 10G
620
-		@ini_set('upload_max_filesize', '10G');
621
-		@ini_set('post_max_size', '10G');
622
-		@ini_set('file_uploads', '50');
623
-
624
-		self::setRequiredIniValues();
625
-		self::handleAuthHeaders();
626
-		self::registerAutoloaderCache();
627
-
628
-		// initialize intl fallback is necessary
629
-		\Patchwork\Utf8\Bootup::initIntl();
630
-		OC_Util::isSetLocaleWorking();
631
-
632
-		if (!defined('PHPUNIT_RUN')) {
633
-			OC\Log\ErrorHandler::setLogger(\OC::$server->getLogger());
634
-			$debug = \OC::$server->getConfig()->getSystemValue('debug', false);
635
-			OC\Log\ErrorHandler::register($debug);
636
-		}
637
-
638
-		\OC::$server->getEventLogger()->start('init_session', 'Initialize session');
639
-		OC_App::loadApps(array('session'));
640
-		if (!self::$CLI) {
641
-			self::initSession();
642
-		}
643
-		\OC::$server->getEventLogger()->end('init_session');
644
-		self::checkConfig();
645
-		self::checkInstalled();
646
-
647
-		OC_Response::addSecurityHeaders();
648
-
649
-		self::performSameSiteCookieProtection();
650
-
651
-		if (!defined('OC_CONSOLE')) {
652
-			$errors = OC_Util::checkServer(\OC::$server->getSystemConfig());
653
-			if (count($errors) > 0) {
654
-				if (self::$CLI) {
655
-					// Convert l10n string into regular string for usage in database
656
-					$staticErrors = [];
657
-					foreach ($errors as $error) {
658
-						echo $error['error'] . "\n";
659
-						echo $error['hint'] . "\n\n";
660
-						$staticErrors[] = [
661
-							'error' => (string)$error['error'],
662
-							'hint' => (string)$error['hint'],
663
-						];
664
-					}
665
-
666
-					try {
667
-						\OC::$server->getConfig()->setAppValue('core', 'cronErrors', json_encode($staticErrors));
668
-					} catch (\Exception $e) {
669
-						echo('Writing to database failed');
670
-					}
671
-					exit(1);
672
-				} else {
673
-					OC_Response::setStatus(OC_Response::STATUS_SERVICE_UNAVAILABLE);
674
-					OC_Util::addStyle('guest');
675
-					OC_Template::printGuestPage('', 'error', array('errors' => $errors));
676
-					exit;
677
-				}
678
-			} elseif (self::$CLI && \OC::$server->getConfig()->getSystemValue('installed', false)) {
679
-				\OC::$server->getConfig()->deleteAppValue('core', 'cronErrors');
680
-			}
681
-		}
682
-		//try to set the session lifetime
683
-		$sessionLifeTime = self::getSessionLifeTime();
684
-		@ini_set('gc_maxlifetime', (string)$sessionLifeTime);
685
-
686
-		$systemConfig = \OC::$server->getSystemConfig();
687
-
688
-		// User and Groups
689
-		if (!$systemConfig->getValue("installed", false)) {
690
-			self::$server->getSession()->set('user_id', '');
691
-		}
692
-
693
-		OC_User::useBackend(new \OC\User\Database());
694
-		\OC::$server->getGroupManager()->addBackend(new \OC\Group\Database());
695
-
696
-		// Subscribe to the hook
697
-		\OCP\Util::connectHook(
698
-			'\OCA\Files_Sharing\API\Server2Server',
699
-			'preLoginNameUsedAsUserName',
700
-			'\OC\User\Database',
701
-			'preLoginNameUsedAsUserName'
702
-		);
703
-
704
-		//setup extra user backends
705
-		if (!\OCP\Util::needUpgrade()) {
706
-			OC_User::setupBackends();
707
-		} else {
708
-			// Run upgrades in incognito mode
709
-			OC_User::setIncognitoMode(true);
710
-		}
711
-
712
-		self::registerCleanupHooks();
713
-		self::registerFilesystemHooks();
714
-		self::registerShareHooks();
715
-		self::registerEncryptionWrapper();
716
-		self::registerEncryptionHooks();
717
-		self::registerAccountHooks();
718
-		self::registerSettingsHooks();
719
-
720
-		// Make sure that the application class is not loaded before the database is setup
721
-		if ($systemConfig->getValue("installed", false)) {
722
-			// Load settings application to make sure hooks are also cached when running occ
723
-			// FIXME: This should probably be moved somewhere else
724
-			$settings = new \OC\Settings\Application();
725
-			$settings->register();
726
-		}
727
-
728
-		//make sure temporary files are cleaned up
729
-		$tmpManager = \OC::$server->getTempManager();
730
-		register_shutdown_function(array($tmpManager, 'clean'));
731
-		$lockProvider = \OC::$server->getLockingProvider();
732
-		register_shutdown_function(array($lockProvider, 'releaseAll'));
733
-
734
-		// Check whether the sample configuration has been copied
735
-		if($systemConfig->getValue('copied_sample_config', false)) {
736
-			$l = \OC::$server->getL10N('lib');
737
-			header('HTTP/1.1 503 Service Temporarily Unavailable');
738
-			header('Status: 503 Service Temporarily Unavailable');
739
-			OC_Template::printErrorPage(
740
-				$l->t('Sample configuration detected'),
741
-				$l->t('It has been detected that the sample configuration has been copied. This can break your installation and is unsupported. Please read the documentation before performing changes on config.php')
742
-			);
743
-			return;
744
-		}
745
-
746
-		$request = \OC::$server->getRequest();
747
-		$host = $request->getInsecureServerHost();
748
-		/**
749
-		 * if the host passed in headers isn't trusted
750
-		 * FIXME: Should not be in here at all :see_no_evil:
751
-		 */
752
-		if (!OC::$CLI
753
-			// overwritehost is always trusted, workaround to not have to make
754
-			// \OC\AppFramework\Http\Request::getOverwriteHost public
755
-			&& self::$server->getConfig()->getSystemValue('overwritehost') === ''
756
-			&& !\OC::$server->getTrustedDomainHelper()->isTrustedDomain($host)
757
-			&& self::$server->getConfig()->getSystemValue('installed', false)
758
-		) {
759
-			// Allow access to CSS resources
760
-			$isScssRequest = false;
761
-			if(strpos($request->getPathInfo(), '/css/') === 0) {
762
-				$isScssRequest = true;
763
-			}
764
-
765
-			if(substr($request->getRequestUri(), -11) === '/status.php') {
766
-				OC_Response::setStatus(\OC_Response::STATUS_BAD_REQUEST);
767
-				header('Status: 400 Bad Request');
768
-				header('Content-Type: application/json');
769
-				echo '{"error": "Trusted domain error.", "code": 15}';
770
-				exit();
771
-			}
772
-
773
-			if (!$isScssRequest) {
774
-				OC_Response::setStatus(\OC_Response::STATUS_BAD_REQUEST);
775
-				header('Status: 400 Bad Request');
776
-
777
-				\OC::$server->getLogger()->warning(
778
-					'Trusted domain error. "{remoteAddress}" tried to access using "{host}" as host.',
779
-					[
780
-						'app' => 'core',
781
-						'remoteAddress' => $request->getRemoteAddress(),
782
-						'host' => $host,
783
-					]
784
-				);
785
-
786
-				$tmpl = new OCP\Template('core', 'untrustedDomain', 'guest');
787
-				$tmpl->assign('domain', $host);
788
-				$tmpl->printPage();
789
-
790
-				exit();
791
-			}
792
-		}
793
-		\OC::$server->getEventLogger()->end('boot');
794
-	}
795
-
796
-	/**
797
-	 * register hooks for the cleanup of cache and bruteforce protection
798
-	 */
799
-	public static function registerCleanupHooks() {
800
-		//don't try to do this before we are properly setup
801
-		if (\OC::$server->getSystemConfig()->getValue('installed', false) && !\OCP\Util::needUpgrade()) {
802
-
803
-			// NOTE: This will be replaced to use OCP
804
-			$userSession = self::$server->getUserSession();
805
-			$userSession->listen('\OC\User', 'postLogin', function () use ($userSession) {
806
-				if (!defined('PHPUNIT_RUN')) {
807
-					// reset brute force delay for this IP address and username
808
-					$uid = \OC::$server->getUserSession()->getUser()->getUID();
809
-					$request = \OC::$server->getRequest();
810
-					$throttler = \OC::$server->getBruteForceThrottler();
811
-					$throttler->resetDelay($request->getRemoteAddress(), 'login', ['user' => $uid]);
812
-				}
813
-
814
-				try {
815
-					$cache = new \OC\Cache\File();
816
-					$cache->gc();
817
-				} catch (\OC\ServerNotAvailableException $e) {
818
-					// not a GC exception, pass it on
819
-					throw $e;
820
-				} catch (\OC\ForbiddenException $e) {
821
-					// filesystem blocked for this request, ignore
822
-				} catch (\Exception $e) {
823
-					// a GC exception should not prevent users from using OC,
824
-					// so log the exception
825
-					\OC::$server->getLogger()->logException($e, [
826
-						'message' => 'Exception when running cache gc.',
827
-						'level' => \OCP\Util::WARN,
828
-						'app' => 'core',
829
-					]);
830
-				}
831
-			});
832
-		}
833
-	}
834
-
835
-	public static function registerSettingsHooks() {
836
-		$dispatcher = \OC::$server->getEventDispatcher();
837
-		$dispatcher->addListener(OCP\App\ManagerEvent::EVENT_APP_DISABLE, function($event) {
838
-			/** @var \OCP\App\ManagerEvent $event */
839
-			\OC::$server->getSettingsManager()->onAppDisabled($event->getAppID());
840
-		});
841
-		$dispatcher->addListener(OCP\App\ManagerEvent::EVENT_APP_UPDATE, function($event) {
842
-			/** @var \OCP\App\ManagerEvent $event */
843
-			$jobList = \OC::$server->getJobList();
844
-			$job = 'OC\\Settings\\RemoveOrphaned';
845
-			if(!$jobList->has($job, null)) {
846
-				$jobList->add($job);
847
-			}
848
-		});
849
-	}
850
-
851
-	private static function registerEncryptionWrapper() {
852
-		$manager = self::$server->getEncryptionManager();
853
-		\OCP\Util::connectHook('OC_Filesystem', 'preSetup', $manager, 'setupStorage');
854
-	}
855
-
856
-	private static function registerEncryptionHooks() {
857
-		$enabled = self::$server->getEncryptionManager()->isEnabled();
858
-		if ($enabled) {
859
-			\OCP\Util::connectHook('OCP\Share', 'post_shared', 'OC\Encryption\HookManager', 'postShared');
860
-			\OCP\Util::connectHook('OCP\Share', 'post_unshare', 'OC\Encryption\HookManager', 'postUnshared');
861
-			\OCP\Util::connectHook('OC_Filesystem', 'post_rename', 'OC\Encryption\HookManager', 'postRename');
862
-			\OCP\Util::connectHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', 'OC\Encryption\HookManager', 'postRestore');
863
-		}
864
-	}
865
-
866
-	private static function registerAccountHooks() {
867
-		$hookHandler = new \OC\Accounts\Hooks(\OC::$server->getLogger());
868
-		\OCP\Util::connectHook('OC_User', 'changeUser', $hookHandler, 'changeUserHook');
869
-	}
870
-
871
-	/**
872
-	 * register hooks for the filesystem
873
-	 */
874
-	public static function registerFilesystemHooks() {
875
-		// Check for blacklisted files
876
-		OC_Hook::connect('OC_Filesystem', 'write', 'OC\Files\Filesystem', 'isBlacklisted');
877
-		OC_Hook::connect('OC_Filesystem', 'rename', 'OC\Files\Filesystem', 'isBlacklisted');
878
-	}
879
-
880
-	/**
881
-	 * register hooks for sharing
882
-	 */
883
-	public static function registerShareHooks() {
884
-		if (\OC::$server->getSystemConfig()->getValue('installed')) {
885
-			OC_Hook::connect('OC_User', 'post_deleteUser', 'OC\Share20\Hooks', 'post_deleteUser');
886
-			OC_Hook::connect('OC_User', 'post_removeFromGroup', 'OC\Share20\Hooks', 'post_removeFromGroup');
887
-			OC_Hook::connect('OC_User', 'post_deleteGroup', 'OC\Share20\Hooks', 'post_deleteGroup');
888
-		}
889
-	}
890
-
891
-	protected static function registerAutoloaderCache() {
892
-		// The class loader takes an optional low-latency cache, which MUST be
893
-		// namespaced. The instanceid is used for namespacing, but might be
894
-		// unavailable at this point. Furthermore, it might not be possible to
895
-		// generate an instanceid via \OC_Util::getInstanceId() because the
896
-		// config file may not be writable. As such, we only register a class
897
-		// loader cache if instanceid is available without trying to create one.
898
-		$instanceId = \OC::$server->getSystemConfig()->getValue('instanceid', null);
899
-		if ($instanceId) {
900
-			try {
901
-				$memcacheFactory = \OC::$server->getMemCacheFactory();
902
-				self::$loader->setMemoryCache($memcacheFactory->createLocal('Autoloader'));
903
-			} catch (\Exception $ex) {
904
-			}
905
-		}
906
-	}
907
-
908
-	/**
909
-	 * Handle the request
910
-	 */
911
-	public static function handleRequest() {
912
-
913
-		\OC::$server->getEventLogger()->start('handle_request', 'Handle request');
914
-		$systemConfig = \OC::$server->getSystemConfig();
915
-		// load all the classpaths from the enabled apps so they are available
916
-		// in the routing files of each app
917
-		OC::loadAppClassPaths();
918
-
919
-		// Check if Nextcloud is installed or in maintenance (update) mode
920
-		if (!$systemConfig->getValue('installed', false)) {
921
-			\OC::$server->getSession()->clear();
922
-			$setupHelper = new OC\Setup(
923
-				$systemConfig,
924
-				\OC::$server->getIniWrapper(),
925
-				\OC::$server->getL10N('lib'),
926
-				\OC::$server->query(\OCP\Defaults::class),
927
-				\OC::$server->getLogger(),
928
-				\OC::$server->getSecureRandom(),
929
-				\OC::$server->query(\OC\Installer::class)
930
-			);
931
-			$controller = new OC\Core\Controller\SetupController($setupHelper);
932
-			$controller->run($_POST);
933
-			exit();
934
-		}
935
-
936
-		$request = \OC::$server->getRequest();
937
-		$requestPath = $request->getRawPathInfo();
938
-		if ($requestPath === '/heartbeat') {
939
-			return;
940
-		}
941
-		if (substr($requestPath, -3) !== '.js') { // we need these files during the upgrade
942
-			self::checkMaintenanceMode();
943
-
944
-			if (\OCP\Util::needUpgrade()) {
945
-				if (function_exists('opcache_reset')) {
946
-					opcache_reset();
947
-				}
948
-				if (!$systemConfig->getValue('maintenance', false)) {
949
-					self::printUpgradePage($systemConfig);
950
-					exit();
951
-				}
952
-			}
953
-		}
954
-
955
-		// emergency app disabling
956
-		if ($requestPath === '/disableapp'
957
-			&& $request->getMethod() === 'POST'
958
-			&& ((array)$request->getParam('appid')) !== ''
959
-		) {
960
-			\OCP\JSON::callCheck();
961
-			\OCP\JSON::checkAdminUser();
962
-			$appIds = (array)$request->getParam('appid');
963
-			foreach($appIds as $appId) {
964
-				$appId = \OC_App::cleanAppId($appId);
965
-				\OC_App::disable($appId);
966
-			}
967
-			\OC_JSON::success();
968
-			exit();
969
-		}
970
-
971
-		// Always load authentication apps
972
-		OC_App::loadApps(['authentication']);
973
-
974
-		// Load minimum set of apps
975
-		if (!\OCP\Util::needUpgrade()
976
-			&& !$systemConfig->getValue('maintenance', false)) {
977
-			// For logged-in users: Load everything
978
-			if(\OC::$server->getUserSession()->isLoggedIn()) {
979
-				OC_App::loadApps();
980
-			} else {
981
-				// For guests: Load only filesystem and logging
982
-				OC_App::loadApps(array('filesystem', 'logging'));
983
-				self::handleLogin($request);
984
-			}
985
-		}
986
-
987
-		if (!self::$CLI) {
988
-			try {
989
-				if (!$systemConfig->getValue('maintenance', false) && !\OCP\Util::needUpgrade()) {
990
-					OC_App::loadApps(array('filesystem', 'logging'));
991
-					OC_App::loadApps();
992
-				}
993
-				OC_Util::setupFS();
994
-				OC::$server->getRouter()->match(\OC::$server->getRequest()->getRawPathInfo());
995
-				return;
996
-			} catch (Symfony\Component\Routing\Exception\ResourceNotFoundException $e) {
997
-				//header('HTTP/1.0 404 Not Found');
998
-			} catch (Symfony\Component\Routing\Exception\MethodNotAllowedException $e) {
999
-				OC_Response::setStatus(405);
1000
-				return;
1001
-			}
1002
-		}
1003
-
1004
-		// Handle WebDAV
1005
-		if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'PROPFIND') {
1006
-			// not allowed any more to prevent people
1007
-			// mounting this root directly.
1008
-			// Users need to mount remote.php/webdav instead.
1009
-			header('HTTP/1.1 405 Method Not Allowed');
1010
-			header('Status: 405 Method Not Allowed');
1011
-			return;
1012
-		}
1013
-
1014
-		// Someone is logged in
1015
-		if (\OC::$server->getUserSession()->isLoggedIn()) {
1016
-			OC_App::loadApps();
1017
-			OC_User::setupBackends();
1018
-			OC_Util::setupFS();
1019
-			// FIXME
1020
-			// Redirect to default application
1021
-			OC_Util::redirectToDefaultPage();
1022
-		} else {
1023
-			// Not handled and not logged in
1024
-			header('Location: '.\OC::$server->getURLGenerator()->linkToRouteAbsolute('core.login.showLoginForm'));
1025
-		}
1026
-	}
1027
-
1028
-	/**
1029
-	 * Check login: apache auth, auth token, basic auth
1030
-	 *
1031
-	 * @param OCP\IRequest $request
1032
-	 * @return boolean
1033
-	 */
1034
-	static function handleLogin(OCP\IRequest $request) {
1035
-		$userSession = self::$server->getUserSession();
1036
-		if (OC_User::handleApacheAuth()) {
1037
-			return true;
1038
-		}
1039
-		if ($userSession->tryTokenLogin($request)) {
1040
-			return true;
1041
-		}
1042
-		if (isset($_COOKIE['nc_username'])
1043
-			&& isset($_COOKIE['nc_token'])
1044
-			&& isset($_COOKIE['nc_session_id'])
1045
-			&& $userSession->loginWithCookie($_COOKIE['nc_username'], $_COOKIE['nc_token'], $_COOKIE['nc_session_id'])) {
1046
-			return true;
1047
-		}
1048
-		if ($userSession->tryBasicAuthLogin($request, \OC::$server->getBruteForceThrottler())) {
1049
-			return true;
1050
-		}
1051
-		return false;
1052
-	}
1053
-
1054
-	protected static function handleAuthHeaders() {
1055
-		//copy http auth headers for apache+php-fcgid work around
1056
-		if (isset($_SERVER['HTTP_XAUTHORIZATION']) && !isset($_SERVER['HTTP_AUTHORIZATION'])) {
1057
-			$_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['HTTP_XAUTHORIZATION'];
1058
-		}
1059
-
1060
-		// Extract PHP_AUTH_USER/PHP_AUTH_PW from other headers if necessary.
1061
-		$vars = array(
1062
-			'HTTP_AUTHORIZATION', // apache+php-cgi work around
1063
-			'REDIRECT_HTTP_AUTHORIZATION', // apache+php-cgi alternative
1064
-		);
1065
-		foreach ($vars as $var) {
1066
-			if (isset($_SERVER[$var]) && preg_match('/Basic\s+(.*)$/i', $_SERVER[$var], $matches)) {
1067
-				list($name, $password) = explode(':', base64_decode($matches[1]), 2);
1068
-				$_SERVER['PHP_AUTH_USER'] = $name;
1069
-				$_SERVER['PHP_AUTH_PW'] = $password;
1070
-				break;
1071
-			}
1072
-		}
1073
-	}
65
+    /**
66
+     * Associative array for autoloading. classname => filename
67
+     */
68
+    public static $CLASSPATH = array();
69
+    /**
70
+     * The installation path for Nextcloud  on the server (e.g. /srv/http/nextcloud)
71
+     */
72
+    public static $SERVERROOT = '';
73
+    /**
74
+     * the current request path relative to the Nextcloud root (e.g. files/index.php)
75
+     */
76
+    private static $SUBURI = '';
77
+    /**
78
+     * the Nextcloud root path for http requests (e.g. nextcloud/)
79
+     */
80
+    public static $WEBROOT = '';
81
+    /**
82
+     * The installation path array of the apps folder on the server (e.g. /srv/http/nextcloud) 'path' and
83
+     * web path in 'url'
84
+     */
85
+    public static $APPSROOTS = array();
86
+
87
+    /**
88
+     * @var string
89
+     */
90
+    public static $configDir;
91
+
92
+    /**
93
+     * requested app
94
+     */
95
+    public static $REQUESTEDAPP = '';
96
+
97
+    /**
98
+     * check if Nextcloud runs in cli mode
99
+     */
100
+    public static $CLI = false;
101
+
102
+    /**
103
+     * @var \OC\Autoloader $loader
104
+     */
105
+    public static $loader = null;
106
+
107
+    /** @var \Composer\Autoload\ClassLoader $composerAutoloader */
108
+    public static $composerAutoloader = null;
109
+
110
+    /**
111
+     * @var \OC\Server
112
+     */
113
+    public static $server = null;
114
+
115
+    /**
116
+     * @var \OC\Config
117
+     */
118
+    private static $config = null;
119
+
120
+    /**
121
+     * @throws \RuntimeException when the 3rdparty directory is missing or
122
+     * the app path list is empty or contains an invalid path
123
+     */
124
+    public static function initPaths() {
125
+        if(defined('PHPUNIT_CONFIG_DIR')) {
126
+            self::$configDir = OC::$SERVERROOT . '/' . PHPUNIT_CONFIG_DIR . '/';
127
+        } elseif(defined('PHPUNIT_RUN') and PHPUNIT_RUN and is_dir(OC::$SERVERROOT . '/tests/config/')) {
128
+            self::$configDir = OC::$SERVERROOT . '/tests/config/';
129
+        } elseif($dir = getenv('NEXTCLOUD_CONFIG_DIR')) {
130
+            self::$configDir = rtrim($dir, '/') . '/';
131
+        } else {
132
+            self::$configDir = OC::$SERVERROOT . '/config/';
133
+        }
134
+        self::$config = new \OC\Config(self::$configDir);
135
+
136
+        OC::$SUBURI = str_replace("\\", "/", substr(realpath($_SERVER["SCRIPT_FILENAME"]), strlen(OC::$SERVERROOT)));
137
+        /**
138
+         * FIXME: The following lines are required because we can't yet instantiate
139
+         *        \OC::$server->getRequest() since \OC::$server does not yet exist.
140
+         */
141
+        $params = [
142
+            'server' => [
143
+                'SCRIPT_NAME' => $_SERVER['SCRIPT_NAME'],
144
+                'SCRIPT_FILENAME' => $_SERVER['SCRIPT_FILENAME'],
145
+            ],
146
+        ];
147
+        $fakeRequest = new \OC\AppFramework\Http\Request($params, null, new \OC\AllConfig(new \OC\SystemConfig(self::$config)));
148
+        $scriptName = $fakeRequest->getScriptName();
149
+        if (substr($scriptName, -1) == '/') {
150
+            $scriptName .= 'index.php';
151
+            //make sure suburi follows the same rules as scriptName
152
+            if (substr(OC::$SUBURI, -9) != 'index.php') {
153
+                if (substr(OC::$SUBURI, -1) != '/') {
154
+                    OC::$SUBURI = OC::$SUBURI . '/';
155
+                }
156
+                OC::$SUBURI = OC::$SUBURI . 'index.php';
157
+            }
158
+        }
159
+
160
+
161
+        if (OC::$CLI) {
162
+            OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
163
+        } else {
164
+            if (substr($scriptName, 0 - strlen(OC::$SUBURI)) === OC::$SUBURI) {
165
+                OC::$WEBROOT = substr($scriptName, 0, 0 - strlen(OC::$SUBURI));
166
+
167
+                if (OC::$WEBROOT != '' && OC::$WEBROOT[0] !== '/') {
168
+                    OC::$WEBROOT = '/' . OC::$WEBROOT;
169
+                }
170
+            } else {
171
+                // The scriptName is not ending with OC::$SUBURI
172
+                // This most likely means that we are calling from CLI.
173
+                // However some cron jobs still need to generate
174
+                // a web URL, so we use overwritewebroot as a fallback.
175
+                OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
176
+            }
177
+
178
+            // Resolve /nextcloud to /nextcloud/ to ensure to always have a trailing
179
+            // slash which is required by URL generation.
180
+            if (isset($_SERVER['REQUEST_URI']) && $_SERVER['REQUEST_URI'] === \OC::$WEBROOT &&
181
+                    substr($_SERVER['REQUEST_URI'], -1) !== '/') {
182
+                header('Location: '.\OC::$WEBROOT.'/');
183
+                exit();
184
+            }
185
+        }
186
+
187
+        // search the apps folder
188
+        $config_paths = self::$config->getValue('apps_paths', array());
189
+        if (!empty($config_paths)) {
190
+            foreach ($config_paths as $paths) {
191
+                if (isset($paths['url']) && isset($paths['path'])) {
192
+                    $paths['url'] = rtrim($paths['url'], '/');
193
+                    $paths['path'] = rtrim($paths['path'], '/');
194
+                    OC::$APPSROOTS[] = $paths;
195
+                }
196
+            }
197
+        } elseif (file_exists(OC::$SERVERROOT . '/apps')) {
198
+            OC::$APPSROOTS[] = array('path' => OC::$SERVERROOT . '/apps', 'url' => '/apps', 'writable' => true);
199
+        } elseif (file_exists(OC::$SERVERROOT . '/../apps')) {
200
+            OC::$APPSROOTS[] = array(
201
+                'path' => rtrim(dirname(OC::$SERVERROOT), '/') . '/apps',
202
+                'url' => '/apps',
203
+                'writable' => true
204
+            );
205
+        }
206
+
207
+        if (empty(OC::$APPSROOTS)) {
208
+            throw new \RuntimeException('apps directory not found! Please put the Nextcloud apps folder in the Nextcloud folder'
209
+                . ' or the folder above. You can also configure the location in the config.php file.');
210
+        }
211
+        $paths = array();
212
+        foreach (OC::$APPSROOTS as $path) {
213
+            $paths[] = $path['path'];
214
+            if (!is_dir($path['path'])) {
215
+                throw new \RuntimeException(sprintf('App directory "%s" not found! Please put the Nextcloud apps folder in the'
216
+                    . ' Nextcloud folder or the folder above. You can also configure the location in the'
217
+                    . ' config.php file.', $path['path']));
218
+            }
219
+        }
220
+
221
+        // set the right include path
222
+        set_include_path(
223
+            implode(PATH_SEPARATOR, $paths)
224
+        );
225
+    }
226
+
227
+    public static function checkConfig() {
228
+        $l = \OC::$server->getL10N('lib');
229
+
230
+        // Create config if it does not already exist
231
+        $configFilePath = self::$configDir .'/config.php';
232
+        if(!file_exists($configFilePath)) {
233
+            @touch($configFilePath);
234
+        }
235
+
236
+        // Check if config is writable
237
+        $configFileWritable = is_writable($configFilePath);
238
+        if (!$configFileWritable && !OC_Helper::isReadOnlyConfigEnabled()
239
+            || !$configFileWritable && \OCP\Util::needUpgrade()) {
240
+
241
+            $urlGenerator = \OC::$server->getURLGenerator();
242
+
243
+            if (self::$CLI) {
244
+                echo $l->t('Cannot write into "config" directory!')."\n";
245
+                echo $l->t('This can usually be fixed by giving the webserver write access to the config directory')."\n";
246
+                echo "\n";
247
+                echo $l->t('See %s', [ $urlGenerator->linkToDocs('admin-dir_permissions') ])."\n";
248
+                exit;
249
+            } else {
250
+                OC_Template::printErrorPage(
251
+                    $l->t('Cannot write into "config" directory!'),
252
+                    $l->t('This can usually be fixed by giving the webserver write access to the config directory. See %s',
253
+                        [ $urlGenerator->linkToDocs('admin-dir_permissions') ])
254
+                );
255
+            }
256
+        }
257
+    }
258
+
259
+    public static function checkInstalled() {
260
+        if (defined('OC_CONSOLE')) {
261
+            return;
262
+        }
263
+        // Redirect to installer if not installed
264
+        if (!\OC::$server->getSystemConfig()->getValue('installed', false) && OC::$SUBURI !== '/index.php' && OC::$SUBURI !== '/status.php') {
265
+            if (OC::$CLI) {
266
+                throw new Exception('Not installed');
267
+            } else {
268
+                $url = OC::$WEBROOT . '/index.php';
269
+                header('Location: ' . $url);
270
+            }
271
+            exit();
272
+        }
273
+    }
274
+
275
+    public static function checkMaintenanceMode() {
276
+        // Allow ajax update script to execute without being stopped
277
+        if (\OC::$server->getSystemConfig()->getValue('maintenance', false) && OC::$SUBURI != '/core/ajax/update.php') {
278
+            // send http status 503
279
+            header('HTTP/1.1 503 Service Temporarily Unavailable');
280
+            header('Status: 503 Service Temporarily Unavailable');
281
+            header('Retry-After: 120');
282
+
283
+            // render error page
284
+            $template = new OC_Template('', 'update.user', 'guest');
285
+            OC_Util::addScript('maintenance-check');
286
+            OC_Util::addStyle('core', 'guest');
287
+            $template->printPage();
288
+            die();
289
+        }
290
+    }
291
+
292
+    /**
293
+     * Prints the upgrade page
294
+     *
295
+     * @param \OC\SystemConfig $systemConfig
296
+     */
297
+    private static function printUpgradePage(\OC\SystemConfig $systemConfig) {
298
+        $disableWebUpdater = $systemConfig->getValue('upgrade.disable-web', false);
299
+        $tooBig = false;
300
+        if (!$disableWebUpdater) {
301
+            $apps = \OC::$server->getAppManager();
302
+            if ($apps->isInstalled('user_ldap')) {
303
+                $qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
304
+
305
+                $result = $qb->selectAlias($qb->createFunction('COUNT(*)'), 'user_count')
306
+                    ->from('ldap_user_mapping')
307
+                    ->execute();
308
+                $row = $result->fetch();
309
+                $result->closeCursor();
310
+
311
+                $tooBig = ($row['user_count'] > 50);
312
+            }
313
+            if (!$tooBig && $apps->isInstalled('user_saml')) {
314
+                $qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
315
+
316
+                $result = $qb->selectAlias($qb->createFunction('COUNT(*)'), 'user_count')
317
+                    ->from('user_saml_users')
318
+                    ->execute();
319
+                $row = $result->fetch();
320
+                $result->closeCursor();
321
+
322
+                $tooBig = ($row['user_count'] > 50);
323
+            }
324
+            if (!$tooBig) {
325
+                // count users
326
+                $stats = \OC::$server->getUserManager()->countUsers();
327
+                $totalUsers = array_sum($stats);
328
+                $tooBig = ($totalUsers > 50);
329
+            }
330
+        }
331
+        $ignoreTooBigWarning = isset($_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup']) &&
332
+            $_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup'] === 'IAmSuperSureToDoThis';
333
+
334
+        if ($disableWebUpdater || ($tooBig && !$ignoreTooBigWarning)) {
335
+            // send http status 503
336
+            header('HTTP/1.1 503 Service Temporarily Unavailable');
337
+            header('Status: 503 Service Temporarily Unavailable');
338
+            header('Retry-After: 120');
339
+
340
+            // render error page
341
+            $template = new OC_Template('', 'update.use-cli', 'guest');
342
+            $template->assign('productName', 'nextcloud'); // for now
343
+            $template->assign('version', OC_Util::getVersionString());
344
+            $template->assign('tooBig', $tooBig);
345
+
346
+            $template->printPage();
347
+            die();
348
+        }
349
+
350
+        // check whether this is a core update or apps update
351
+        $installedVersion = $systemConfig->getValue('version', '0.0.0');
352
+        $currentVersion = implode('.', \OCP\Util::getVersion());
353
+
354
+        // if not a core upgrade, then it's apps upgrade
355
+        $isAppsOnlyUpgrade = version_compare($currentVersion, $installedVersion, '=');
356
+
357
+        $oldTheme = $systemConfig->getValue('theme');
358
+        $systemConfig->setValue('theme', '');
359
+        OC_Util::addScript('config'); // needed for web root
360
+        OC_Util::addScript('update');
361
+
362
+        /** @var \OC\App\AppManager $appManager */
363
+        $appManager = \OC::$server->getAppManager();
364
+
365
+        $tmpl = new OC_Template('', 'update.admin', 'guest');
366
+        $tmpl->assign('version', OC_Util::getVersionString());
367
+        $tmpl->assign('isAppsOnlyUpgrade', $isAppsOnlyUpgrade);
368
+
369
+        // get third party apps
370
+        $ocVersion = \OCP\Util::getVersion();
371
+        $incompatibleApps = $appManager->getIncompatibleApps($ocVersion);
372
+        $incompatibleShippedApps = [];
373
+        foreach ($incompatibleApps as $appInfo) {
374
+            if ($appManager->isShipped($appInfo['id'])) {
375
+                $incompatibleShippedApps[] = $appInfo['name'] . ' (' . $appInfo['id'] . ')';
376
+            }
377
+        }
378
+
379
+        if (!empty($incompatibleShippedApps)) {
380
+            $l = \OC::$server->getL10N('core');
381
+            $hint = $l->t('The files of the app %$1s were not replaced correctly. Make sure it is a version compatible with the server.', [implode(', ', $incompatibleShippedApps)]);
382
+            throw new \OC\HintException('The files of the app ' . implode(', ', $incompatibleShippedApps) . ' were not replaced correctly. Make sure it is a version compatible with the server.', $hint);
383
+        }
384
+
385
+        $tmpl->assign('appsToUpgrade', $appManager->getAppsNeedingUpgrade($ocVersion));
386
+        $tmpl->assign('incompatibleAppsList', $incompatibleApps);
387
+        $tmpl->assign('productName', 'Nextcloud'); // for now
388
+        $tmpl->assign('oldTheme', $oldTheme);
389
+        $tmpl->printPage();
390
+    }
391
+
392
+    public static function initSession() {
393
+        if(self::$server->getRequest()->getServerProtocol() === 'https') {
394
+            ini_set('session.cookie_secure', true);
395
+        }
396
+
397
+        // prevents javascript from accessing php session cookies
398
+        ini_set('session.cookie_httponly', 'true');
399
+
400
+        // set the cookie path to the Nextcloud directory
401
+        $cookie_path = OC::$WEBROOT ? : '/';
402
+        ini_set('session.cookie_path', $cookie_path);
403
+
404
+        // Let the session name be changed in the initSession Hook
405
+        $sessionName = OC_Util::getInstanceId();
406
+
407
+        try {
408
+            // Allow session apps to create a custom session object
409
+            $useCustomSession = false;
410
+            $session = self::$server->getSession();
411
+            OC_Hook::emit('OC', 'initSession', array('session' => &$session, 'sessionName' => &$sessionName, 'useCustomSession' => &$useCustomSession));
412
+            if (!$useCustomSession) {
413
+                // set the session name to the instance id - which is unique
414
+                $session = new \OC\Session\Internal($sessionName);
415
+            }
416
+
417
+            $cryptoWrapper = \OC::$server->getSessionCryptoWrapper();
418
+            $session = $cryptoWrapper->wrapSession($session);
419
+            self::$server->setSession($session);
420
+
421
+            // if session can't be started break with http 500 error
422
+        } catch (Exception $e) {
423
+            \OCP\Util::logException('base', $e);
424
+            //show the user a detailed error page
425
+            OC_Response::setStatus(OC_Response::STATUS_INTERNAL_SERVER_ERROR);
426
+            OC_Template::printExceptionErrorPage($e);
427
+            die();
428
+        }
429
+
430
+        $sessionLifeTime = self::getSessionLifeTime();
431
+
432
+        // session timeout
433
+        if ($session->exists('LAST_ACTIVITY') && (time() - $session->get('LAST_ACTIVITY') > $sessionLifeTime)) {
434
+            if (isset($_COOKIE[session_name()])) {
435
+                setcookie(session_name(), null, -1, self::$WEBROOT ? : '/');
436
+            }
437
+            \OC::$server->getUserSession()->logout();
438
+        }
439
+
440
+        $session->set('LAST_ACTIVITY', time());
441
+    }
442
+
443
+    /**
444
+     * @return string
445
+     */
446
+    private static function getSessionLifeTime() {
447
+        return \OC::$server->getConfig()->getSystemValue('session_lifetime', 60 * 60 * 24);
448
+    }
449
+
450
+    public static function loadAppClassPaths() {
451
+        foreach (OC_App::getEnabledApps() as $app) {
452
+            $appPath = OC_App::getAppPath($app);
453
+            if ($appPath === false) {
454
+                continue;
455
+            }
456
+
457
+            $file = $appPath . '/appinfo/classpath.php';
458
+            if (file_exists($file)) {
459
+                require_once $file;
460
+            }
461
+        }
462
+    }
463
+
464
+    /**
465
+     * Try to set some values to the required Nextcloud default
466
+     */
467
+    public static function setRequiredIniValues() {
468
+        @ini_set('default_charset', 'UTF-8');
469
+        @ini_set('gd.jpeg_ignore_warning', '1');
470
+    }
471
+
472
+    /**
473
+     * Send the same site cookies
474
+     */
475
+    private static function sendSameSiteCookies() {
476
+        $cookieParams = session_get_cookie_params();
477
+        $secureCookie = ($cookieParams['secure'] === true) ? 'secure; ' : '';
478
+        $policies = [
479
+            'lax',
480
+            'strict',
481
+        ];
482
+
483
+        // Append __Host to the cookie if it meets the requirements
484
+        $cookiePrefix = '';
485
+        if($cookieParams['secure'] === true && $cookieParams['path'] === '/') {
486
+            $cookiePrefix = '__Host-';
487
+        }
488
+
489
+        foreach($policies as $policy) {
490
+            header(
491
+                sprintf(
492
+                    'Set-Cookie: %snc_sameSiteCookie%s=true; path=%s; httponly;' . $secureCookie . 'expires=Fri, 31-Dec-2100 23:59:59 GMT; SameSite=%s',
493
+                    $cookiePrefix,
494
+                    $policy,
495
+                    $cookieParams['path'],
496
+                    $policy
497
+                ),
498
+                false
499
+            );
500
+        }
501
+    }
502
+
503
+    /**
504
+     * Same Site cookie to further mitigate CSRF attacks. This cookie has to
505
+     * be set in every request if cookies are sent to add a second level of
506
+     * defense against CSRF.
507
+     *
508
+     * If the cookie is not sent this will set the cookie and reload the page.
509
+     * We use an additional cookie since we want to protect logout CSRF and
510
+     * also we can't directly interfere with PHP's session mechanism.
511
+     */
512
+    private static function performSameSiteCookieProtection() {
513
+        $request = \OC::$server->getRequest();
514
+
515
+        // Some user agents are notorious and don't really properly follow HTTP
516
+        // specifications. For those, have an automated opt-out. Since the protection
517
+        // for remote.php is applied in base.php as starting point we need to opt out
518
+        // here.
519
+        $incompatibleUserAgents = [
520
+            // OS X Finder
521
+            '/^WebDAVFS/',
522
+        ];
523
+        if($request->isUserAgent($incompatibleUserAgents)) {
524
+            return;
525
+        }
526
+
527
+        if(count($_COOKIE) > 0) {
528
+            $requestUri = $request->getScriptName();
529
+            $processingScript = explode('/', $requestUri);
530
+            $processingScript = $processingScript[count($processingScript)-1];
531
+
532
+            // index.php routes are handled in the middleware
533
+            if($processingScript === 'index.php') {
534
+                return;
535
+            }
536
+
537
+            // All other endpoints require the lax and the strict cookie
538
+            if(!$request->passesStrictCookieCheck()) {
539
+                self::sendSameSiteCookies();
540
+                // Debug mode gets access to the resources without strict cookie
541
+                // due to the fact that the SabreDAV browser also lives there.
542
+                if(!\OC::$server->getConfig()->getSystemValue('debug', false)) {
543
+                    http_response_code(\OCP\AppFramework\Http::STATUS_SERVICE_UNAVAILABLE);
544
+                    exit();
545
+                }
546
+            }
547
+        } elseif(!isset($_COOKIE['nc_sameSiteCookielax']) || !isset($_COOKIE['nc_sameSiteCookiestrict'])) {
548
+            self::sendSameSiteCookies();
549
+        }
550
+    }
551
+
552
+    public static function init() {
553
+        // calculate the root directories
554
+        OC::$SERVERROOT = str_replace("\\", '/', substr(__DIR__, 0, -4));
555
+
556
+        // register autoloader
557
+        $loaderStart = microtime(true);
558
+        require_once __DIR__ . '/autoloader.php';
559
+        self::$loader = new \OC\Autoloader([
560
+            OC::$SERVERROOT . '/lib/private/legacy',
561
+        ]);
562
+        if (defined('PHPUNIT_RUN')) {
563
+            self::$loader->addValidRoot(OC::$SERVERROOT . '/tests');
564
+        }
565
+        spl_autoload_register(array(self::$loader, 'load'));
566
+        $loaderEnd = microtime(true);
567
+
568
+        self::$CLI = (php_sapi_name() == 'cli');
569
+
570
+        // Add default composer PSR-4 autoloader
571
+        self::$composerAutoloader = require_once OC::$SERVERROOT . '/lib/composer/autoload.php';
572
+
573
+        try {
574
+            self::initPaths();
575
+            // setup 3rdparty autoloader
576
+            $vendorAutoLoad = OC::$SERVERROOT. '/3rdparty/autoload.php';
577
+            if (!file_exists($vendorAutoLoad)) {
578
+                throw new \RuntimeException('Composer autoloader not found, unable to continue. Check the folder "3rdparty". Running "git submodule update --init" will initialize the git submodule that handles the subfolder "3rdparty".');
579
+            }
580
+            require_once $vendorAutoLoad;
581
+
582
+        } catch (\RuntimeException $e) {
583
+            if (!self::$CLI) {
584
+                $claimedProtocol = strtoupper($_SERVER['SERVER_PROTOCOL']);
585
+                $protocol = in_array($claimedProtocol, ['HTTP/1.0', 'HTTP/1.1', 'HTTP/2']) ? $claimedProtocol : 'HTTP/1.1';
586
+                header($protocol . ' ' . OC_Response::STATUS_SERVICE_UNAVAILABLE);
587
+            }
588
+            // we can't use the template error page here, because this needs the
589
+            // DI container which isn't available yet
590
+            print($e->getMessage());
591
+            exit();
592
+        }
593
+
594
+        // setup the basic server
595
+        self::$server = new \OC\Server(\OC::$WEBROOT, self::$config);
596
+        \OC::$server->getEventLogger()->log('autoloader', 'Autoloader', $loaderStart, $loaderEnd);
597
+        \OC::$server->getEventLogger()->start('boot', 'Initialize');
598
+
599
+        // Don't display errors and log them
600
+        error_reporting(E_ALL | E_STRICT);
601
+        @ini_set('display_errors', '0');
602
+        @ini_set('log_errors', '1');
603
+
604
+        if(!date_default_timezone_set('UTC')) {
605
+            throw new \RuntimeException('Could not set timezone to UTC');
606
+        }
607
+
608
+        //try to configure php to enable big file uploads.
609
+        //this doesn´t work always depending on the webserver and php configuration.
610
+        //Let´s try to overwrite some defaults anyway
611
+
612
+        //try to set the maximum execution time to 60min
613
+        if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
614
+            @set_time_limit(3600);
615
+        }
616
+        @ini_set('max_execution_time', '3600');
617
+        @ini_set('max_input_time', '3600');
618
+
619
+        //try to set the maximum filesize to 10G
620
+        @ini_set('upload_max_filesize', '10G');
621
+        @ini_set('post_max_size', '10G');
622
+        @ini_set('file_uploads', '50');
623
+
624
+        self::setRequiredIniValues();
625
+        self::handleAuthHeaders();
626
+        self::registerAutoloaderCache();
627
+
628
+        // initialize intl fallback is necessary
629
+        \Patchwork\Utf8\Bootup::initIntl();
630
+        OC_Util::isSetLocaleWorking();
631
+
632
+        if (!defined('PHPUNIT_RUN')) {
633
+            OC\Log\ErrorHandler::setLogger(\OC::$server->getLogger());
634
+            $debug = \OC::$server->getConfig()->getSystemValue('debug', false);
635
+            OC\Log\ErrorHandler::register($debug);
636
+        }
637
+
638
+        \OC::$server->getEventLogger()->start('init_session', 'Initialize session');
639
+        OC_App::loadApps(array('session'));
640
+        if (!self::$CLI) {
641
+            self::initSession();
642
+        }
643
+        \OC::$server->getEventLogger()->end('init_session');
644
+        self::checkConfig();
645
+        self::checkInstalled();
646
+
647
+        OC_Response::addSecurityHeaders();
648
+
649
+        self::performSameSiteCookieProtection();
650
+
651
+        if (!defined('OC_CONSOLE')) {
652
+            $errors = OC_Util::checkServer(\OC::$server->getSystemConfig());
653
+            if (count($errors) > 0) {
654
+                if (self::$CLI) {
655
+                    // Convert l10n string into regular string for usage in database
656
+                    $staticErrors = [];
657
+                    foreach ($errors as $error) {
658
+                        echo $error['error'] . "\n";
659
+                        echo $error['hint'] . "\n\n";
660
+                        $staticErrors[] = [
661
+                            'error' => (string)$error['error'],
662
+                            'hint' => (string)$error['hint'],
663
+                        ];
664
+                    }
665
+
666
+                    try {
667
+                        \OC::$server->getConfig()->setAppValue('core', 'cronErrors', json_encode($staticErrors));
668
+                    } catch (\Exception $e) {
669
+                        echo('Writing to database failed');
670
+                    }
671
+                    exit(1);
672
+                } else {
673
+                    OC_Response::setStatus(OC_Response::STATUS_SERVICE_UNAVAILABLE);
674
+                    OC_Util::addStyle('guest');
675
+                    OC_Template::printGuestPage('', 'error', array('errors' => $errors));
676
+                    exit;
677
+                }
678
+            } elseif (self::$CLI && \OC::$server->getConfig()->getSystemValue('installed', false)) {
679
+                \OC::$server->getConfig()->deleteAppValue('core', 'cronErrors');
680
+            }
681
+        }
682
+        //try to set the session lifetime
683
+        $sessionLifeTime = self::getSessionLifeTime();
684
+        @ini_set('gc_maxlifetime', (string)$sessionLifeTime);
685
+
686
+        $systemConfig = \OC::$server->getSystemConfig();
687
+
688
+        // User and Groups
689
+        if (!$systemConfig->getValue("installed", false)) {
690
+            self::$server->getSession()->set('user_id', '');
691
+        }
692
+
693
+        OC_User::useBackend(new \OC\User\Database());
694
+        \OC::$server->getGroupManager()->addBackend(new \OC\Group\Database());
695
+
696
+        // Subscribe to the hook
697
+        \OCP\Util::connectHook(
698
+            '\OCA\Files_Sharing\API\Server2Server',
699
+            'preLoginNameUsedAsUserName',
700
+            '\OC\User\Database',
701
+            'preLoginNameUsedAsUserName'
702
+        );
703
+
704
+        //setup extra user backends
705
+        if (!\OCP\Util::needUpgrade()) {
706
+            OC_User::setupBackends();
707
+        } else {
708
+            // Run upgrades in incognito mode
709
+            OC_User::setIncognitoMode(true);
710
+        }
711
+
712
+        self::registerCleanupHooks();
713
+        self::registerFilesystemHooks();
714
+        self::registerShareHooks();
715
+        self::registerEncryptionWrapper();
716
+        self::registerEncryptionHooks();
717
+        self::registerAccountHooks();
718
+        self::registerSettingsHooks();
719
+
720
+        // Make sure that the application class is not loaded before the database is setup
721
+        if ($systemConfig->getValue("installed", false)) {
722
+            // Load settings application to make sure hooks are also cached when running occ
723
+            // FIXME: This should probably be moved somewhere else
724
+            $settings = new \OC\Settings\Application();
725
+            $settings->register();
726
+        }
727
+
728
+        //make sure temporary files are cleaned up
729
+        $tmpManager = \OC::$server->getTempManager();
730
+        register_shutdown_function(array($tmpManager, 'clean'));
731
+        $lockProvider = \OC::$server->getLockingProvider();
732
+        register_shutdown_function(array($lockProvider, 'releaseAll'));
733
+
734
+        // Check whether the sample configuration has been copied
735
+        if($systemConfig->getValue('copied_sample_config', false)) {
736
+            $l = \OC::$server->getL10N('lib');
737
+            header('HTTP/1.1 503 Service Temporarily Unavailable');
738
+            header('Status: 503 Service Temporarily Unavailable');
739
+            OC_Template::printErrorPage(
740
+                $l->t('Sample configuration detected'),
741
+                $l->t('It has been detected that the sample configuration has been copied. This can break your installation and is unsupported. Please read the documentation before performing changes on config.php')
742
+            );
743
+            return;
744
+        }
745
+
746
+        $request = \OC::$server->getRequest();
747
+        $host = $request->getInsecureServerHost();
748
+        /**
749
+         * if the host passed in headers isn't trusted
750
+         * FIXME: Should not be in here at all :see_no_evil:
751
+         */
752
+        if (!OC::$CLI
753
+            // overwritehost is always trusted, workaround to not have to make
754
+            // \OC\AppFramework\Http\Request::getOverwriteHost public
755
+            && self::$server->getConfig()->getSystemValue('overwritehost') === ''
756
+            && !\OC::$server->getTrustedDomainHelper()->isTrustedDomain($host)
757
+            && self::$server->getConfig()->getSystemValue('installed', false)
758
+        ) {
759
+            // Allow access to CSS resources
760
+            $isScssRequest = false;
761
+            if(strpos($request->getPathInfo(), '/css/') === 0) {
762
+                $isScssRequest = true;
763
+            }
764
+
765
+            if(substr($request->getRequestUri(), -11) === '/status.php') {
766
+                OC_Response::setStatus(\OC_Response::STATUS_BAD_REQUEST);
767
+                header('Status: 400 Bad Request');
768
+                header('Content-Type: application/json');
769
+                echo '{"error": "Trusted domain error.", "code": 15}';
770
+                exit();
771
+            }
772
+
773
+            if (!$isScssRequest) {
774
+                OC_Response::setStatus(\OC_Response::STATUS_BAD_REQUEST);
775
+                header('Status: 400 Bad Request');
776
+
777
+                \OC::$server->getLogger()->warning(
778
+                    'Trusted domain error. "{remoteAddress}" tried to access using "{host}" as host.',
779
+                    [
780
+                        'app' => 'core',
781
+                        'remoteAddress' => $request->getRemoteAddress(),
782
+                        'host' => $host,
783
+                    ]
784
+                );
785
+
786
+                $tmpl = new OCP\Template('core', 'untrustedDomain', 'guest');
787
+                $tmpl->assign('domain', $host);
788
+                $tmpl->printPage();
789
+
790
+                exit();
791
+            }
792
+        }
793
+        \OC::$server->getEventLogger()->end('boot');
794
+    }
795
+
796
+    /**
797
+     * register hooks for the cleanup of cache and bruteforce protection
798
+     */
799
+    public static function registerCleanupHooks() {
800
+        //don't try to do this before we are properly setup
801
+        if (\OC::$server->getSystemConfig()->getValue('installed', false) && !\OCP\Util::needUpgrade()) {
802
+
803
+            // NOTE: This will be replaced to use OCP
804
+            $userSession = self::$server->getUserSession();
805
+            $userSession->listen('\OC\User', 'postLogin', function () use ($userSession) {
806
+                if (!defined('PHPUNIT_RUN')) {
807
+                    // reset brute force delay for this IP address and username
808
+                    $uid = \OC::$server->getUserSession()->getUser()->getUID();
809
+                    $request = \OC::$server->getRequest();
810
+                    $throttler = \OC::$server->getBruteForceThrottler();
811
+                    $throttler->resetDelay($request->getRemoteAddress(), 'login', ['user' => $uid]);
812
+                }
813
+
814
+                try {
815
+                    $cache = new \OC\Cache\File();
816
+                    $cache->gc();
817
+                } catch (\OC\ServerNotAvailableException $e) {
818
+                    // not a GC exception, pass it on
819
+                    throw $e;
820
+                } catch (\OC\ForbiddenException $e) {
821
+                    // filesystem blocked for this request, ignore
822
+                } catch (\Exception $e) {
823
+                    // a GC exception should not prevent users from using OC,
824
+                    // so log the exception
825
+                    \OC::$server->getLogger()->logException($e, [
826
+                        'message' => 'Exception when running cache gc.',
827
+                        'level' => \OCP\Util::WARN,
828
+                        'app' => 'core',
829
+                    ]);
830
+                }
831
+            });
832
+        }
833
+    }
834
+
835
+    public static function registerSettingsHooks() {
836
+        $dispatcher = \OC::$server->getEventDispatcher();
837
+        $dispatcher->addListener(OCP\App\ManagerEvent::EVENT_APP_DISABLE, function($event) {
838
+            /** @var \OCP\App\ManagerEvent $event */
839
+            \OC::$server->getSettingsManager()->onAppDisabled($event->getAppID());
840
+        });
841
+        $dispatcher->addListener(OCP\App\ManagerEvent::EVENT_APP_UPDATE, function($event) {
842
+            /** @var \OCP\App\ManagerEvent $event */
843
+            $jobList = \OC::$server->getJobList();
844
+            $job = 'OC\\Settings\\RemoveOrphaned';
845
+            if(!$jobList->has($job, null)) {
846
+                $jobList->add($job);
847
+            }
848
+        });
849
+    }
850
+
851
+    private static function registerEncryptionWrapper() {
852
+        $manager = self::$server->getEncryptionManager();
853
+        \OCP\Util::connectHook('OC_Filesystem', 'preSetup', $manager, 'setupStorage');
854
+    }
855
+
856
+    private static function registerEncryptionHooks() {
857
+        $enabled = self::$server->getEncryptionManager()->isEnabled();
858
+        if ($enabled) {
859
+            \OCP\Util::connectHook('OCP\Share', 'post_shared', 'OC\Encryption\HookManager', 'postShared');
860
+            \OCP\Util::connectHook('OCP\Share', 'post_unshare', 'OC\Encryption\HookManager', 'postUnshared');
861
+            \OCP\Util::connectHook('OC_Filesystem', 'post_rename', 'OC\Encryption\HookManager', 'postRename');
862
+            \OCP\Util::connectHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', 'OC\Encryption\HookManager', 'postRestore');
863
+        }
864
+    }
865
+
866
+    private static function registerAccountHooks() {
867
+        $hookHandler = new \OC\Accounts\Hooks(\OC::$server->getLogger());
868
+        \OCP\Util::connectHook('OC_User', 'changeUser', $hookHandler, 'changeUserHook');
869
+    }
870
+
871
+    /**
872
+     * register hooks for the filesystem
873
+     */
874
+    public static function registerFilesystemHooks() {
875
+        // Check for blacklisted files
876
+        OC_Hook::connect('OC_Filesystem', 'write', 'OC\Files\Filesystem', 'isBlacklisted');
877
+        OC_Hook::connect('OC_Filesystem', 'rename', 'OC\Files\Filesystem', 'isBlacklisted');
878
+    }
879
+
880
+    /**
881
+     * register hooks for sharing
882
+     */
883
+    public static function registerShareHooks() {
884
+        if (\OC::$server->getSystemConfig()->getValue('installed')) {
885
+            OC_Hook::connect('OC_User', 'post_deleteUser', 'OC\Share20\Hooks', 'post_deleteUser');
886
+            OC_Hook::connect('OC_User', 'post_removeFromGroup', 'OC\Share20\Hooks', 'post_removeFromGroup');
887
+            OC_Hook::connect('OC_User', 'post_deleteGroup', 'OC\Share20\Hooks', 'post_deleteGroup');
888
+        }
889
+    }
890
+
891
+    protected static function registerAutoloaderCache() {
892
+        // The class loader takes an optional low-latency cache, which MUST be
893
+        // namespaced. The instanceid is used for namespacing, but might be
894
+        // unavailable at this point. Furthermore, it might not be possible to
895
+        // generate an instanceid via \OC_Util::getInstanceId() because the
896
+        // config file may not be writable. As such, we only register a class
897
+        // loader cache if instanceid is available without trying to create one.
898
+        $instanceId = \OC::$server->getSystemConfig()->getValue('instanceid', null);
899
+        if ($instanceId) {
900
+            try {
901
+                $memcacheFactory = \OC::$server->getMemCacheFactory();
902
+                self::$loader->setMemoryCache($memcacheFactory->createLocal('Autoloader'));
903
+            } catch (\Exception $ex) {
904
+            }
905
+        }
906
+    }
907
+
908
+    /**
909
+     * Handle the request
910
+     */
911
+    public static function handleRequest() {
912
+
913
+        \OC::$server->getEventLogger()->start('handle_request', 'Handle request');
914
+        $systemConfig = \OC::$server->getSystemConfig();
915
+        // load all the classpaths from the enabled apps so they are available
916
+        // in the routing files of each app
917
+        OC::loadAppClassPaths();
918
+
919
+        // Check if Nextcloud is installed or in maintenance (update) mode
920
+        if (!$systemConfig->getValue('installed', false)) {
921
+            \OC::$server->getSession()->clear();
922
+            $setupHelper = new OC\Setup(
923
+                $systemConfig,
924
+                \OC::$server->getIniWrapper(),
925
+                \OC::$server->getL10N('lib'),
926
+                \OC::$server->query(\OCP\Defaults::class),
927
+                \OC::$server->getLogger(),
928
+                \OC::$server->getSecureRandom(),
929
+                \OC::$server->query(\OC\Installer::class)
930
+            );
931
+            $controller = new OC\Core\Controller\SetupController($setupHelper);
932
+            $controller->run($_POST);
933
+            exit();
934
+        }
935
+
936
+        $request = \OC::$server->getRequest();
937
+        $requestPath = $request->getRawPathInfo();
938
+        if ($requestPath === '/heartbeat') {
939
+            return;
940
+        }
941
+        if (substr($requestPath, -3) !== '.js') { // we need these files during the upgrade
942
+            self::checkMaintenanceMode();
943
+
944
+            if (\OCP\Util::needUpgrade()) {
945
+                if (function_exists('opcache_reset')) {
946
+                    opcache_reset();
947
+                }
948
+                if (!$systemConfig->getValue('maintenance', false)) {
949
+                    self::printUpgradePage($systemConfig);
950
+                    exit();
951
+                }
952
+            }
953
+        }
954
+
955
+        // emergency app disabling
956
+        if ($requestPath === '/disableapp'
957
+            && $request->getMethod() === 'POST'
958
+            && ((array)$request->getParam('appid')) !== ''
959
+        ) {
960
+            \OCP\JSON::callCheck();
961
+            \OCP\JSON::checkAdminUser();
962
+            $appIds = (array)$request->getParam('appid');
963
+            foreach($appIds as $appId) {
964
+                $appId = \OC_App::cleanAppId($appId);
965
+                \OC_App::disable($appId);
966
+            }
967
+            \OC_JSON::success();
968
+            exit();
969
+        }
970
+
971
+        // Always load authentication apps
972
+        OC_App::loadApps(['authentication']);
973
+
974
+        // Load minimum set of apps
975
+        if (!\OCP\Util::needUpgrade()
976
+            && !$systemConfig->getValue('maintenance', false)) {
977
+            // For logged-in users: Load everything
978
+            if(\OC::$server->getUserSession()->isLoggedIn()) {
979
+                OC_App::loadApps();
980
+            } else {
981
+                // For guests: Load only filesystem and logging
982
+                OC_App::loadApps(array('filesystem', 'logging'));
983
+                self::handleLogin($request);
984
+            }
985
+        }
986
+
987
+        if (!self::$CLI) {
988
+            try {
989
+                if (!$systemConfig->getValue('maintenance', false) && !\OCP\Util::needUpgrade()) {
990
+                    OC_App::loadApps(array('filesystem', 'logging'));
991
+                    OC_App::loadApps();
992
+                }
993
+                OC_Util::setupFS();
994
+                OC::$server->getRouter()->match(\OC::$server->getRequest()->getRawPathInfo());
995
+                return;
996
+            } catch (Symfony\Component\Routing\Exception\ResourceNotFoundException $e) {
997
+                //header('HTTP/1.0 404 Not Found');
998
+            } catch (Symfony\Component\Routing\Exception\MethodNotAllowedException $e) {
999
+                OC_Response::setStatus(405);
1000
+                return;
1001
+            }
1002
+        }
1003
+
1004
+        // Handle WebDAV
1005
+        if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'PROPFIND') {
1006
+            // not allowed any more to prevent people
1007
+            // mounting this root directly.
1008
+            // Users need to mount remote.php/webdav instead.
1009
+            header('HTTP/1.1 405 Method Not Allowed');
1010
+            header('Status: 405 Method Not Allowed');
1011
+            return;
1012
+        }
1013
+
1014
+        // Someone is logged in
1015
+        if (\OC::$server->getUserSession()->isLoggedIn()) {
1016
+            OC_App::loadApps();
1017
+            OC_User::setupBackends();
1018
+            OC_Util::setupFS();
1019
+            // FIXME
1020
+            // Redirect to default application
1021
+            OC_Util::redirectToDefaultPage();
1022
+        } else {
1023
+            // Not handled and not logged in
1024
+            header('Location: '.\OC::$server->getURLGenerator()->linkToRouteAbsolute('core.login.showLoginForm'));
1025
+        }
1026
+    }
1027
+
1028
+    /**
1029
+     * Check login: apache auth, auth token, basic auth
1030
+     *
1031
+     * @param OCP\IRequest $request
1032
+     * @return boolean
1033
+     */
1034
+    static function handleLogin(OCP\IRequest $request) {
1035
+        $userSession = self::$server->getUserSession();
1036
+        if (OC_User::handleApacheAuth()) {
1037
+            return true;
1038
+        }
1039
+        if ($userSession->tryTokenLogin($request)) {
1040
+            return true;
1041
+        }
1042
+        if (isset($_COOKIE['nc_username'])
1043
+            && isset($_COOKIE['nc_token'])
1044
+            && isset($_COOKIE['nc_session_id'])
1045
+            && $userSession->loginWithCookie($_COOKIE['nc_username'], $_COOKIE['nc_token'], $_COOKIE['nc_session_id'])) {
1046
+            return true;
1047
+        }
1048
+        if ($userSession->tryBasicAuthLogin($request, \OC::$server->getBruteForceThrottler())) {
1049
+            return true;
1050
+        }
1051
+        return false;
1052
+    }
1053
+
1054
+    protected static function handleAuthHeaders() {
1055
+        //copy http auth headers for apache+php-fcgid work around
1056
+        if (isset($_SERVER['HTTP_XAUTHORIZATION']) && !isset($_SERVER['HTTP_AUTHORIZATION'])) {
1057
+            $_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['HTTP_XAUTHORIZATION'];
1058
+        }
1059
+
1060
+        // Extract PHP_AUTH_USER/PHP_AUTH_PW from other headers if necessary.
1061
+        $vars = array(
1062
+            'HTTP_AUTHORIZATION', // apache+php-cgi work around
1063
+            'REDIRECT_HTTP_AUTHORIZATION', // apache+php-cgi alternative
1064
+        );
1065
+        foreach ($vars as $var) {
1066
+            if (isset($_SERVER[$var]) && preg_match('/Basic\s+(.*)$/i', $_SERVER[$var], $matches)) {
1067
+                list($name, $password) = explode(':', base64_decode($matches[1]), 2);
1068
+                $_SERVER['PHP_AUTH_USER'] = $name;
1069
+                $_SERVER['PHP_AUTH_PW'] = $password;
1070
+                break;
1071
+            }
1072
+        }
1073
+    }
1074 1074
 }
1075 1075
 
1076 1076
 OC::init();
Please login to merge, or discard this patch.