Passed
Push — master ( c27223...b70cf4 )
by Morris
21:02 queued 09:41
created
lib/private/legacy/OC_App.php 1 patch
Indentation   +1109 added lines, -1109 removed lines patch added patch discarded remove patch
@@ -68,1113 +68,1113 @@
 block discarded – undo
68 68
  * upgrading and removing apps.
69 69
  */
70 70
 class OC_App {
71
-	private static $adminForms = [];
72
-	private static $personalForms = [];
73
-	private static $appTypes = [];
74
-	private static $loadedApps = [];
75
-	private static $altLogin = [];
76
-	private static $alreadyRegistered = [];
77
-	public const supportedApp = 300;
78
-	public const officialApp = 200;
79
-
80
-	/**
81
-	 * clean the appId
82
-	 *
83
-	 * @param string $app AppId that needs to be cleaned
84
-	 * @return string
85
-	 */
86
-	public static function cleanAppId(string $app): string {
87
-		return str_replace(['\0', '/', '\\', '..'], '', $app);
88
-	}
89
-
90
-	/**
91
-	 * Check if an app is loaded
92
-	 *
93
-	 * @param string $app
94
-	 * @return bool
95
-	 */
96
-	public static function isAppLoaded(string $app): bool {
97
-		return isset(self::$loadedApps[$app]);
98
-	}
99
-
100
-	/**
101
-	 * loads all apps
102
-	 *
103
-	 * @param string[] $types
104
-	 * @return bool
105
-	 *
106
-	 * This function walks through the ownCloud directory and loads all apps
107
-	 * it can find. A directory contains an app if the file /appinfo/info.xml
108
-	 * exists.
109
-	 *
110
-	 * if $types is set to non-empty array, only apps of those types will be loaded
111
-	 */
112
-	public static function loadApps(array $types = []): bool {
113
-		if ((bool) \OC::$server->getSystemConfig()->getValue('maintenance', false)) {
114
-			return false;
115
-		}
116
-		// Load the enabled apps here
117
-		$apps = self::getEnabledApps();
118
-
119
-		// Add each apps' folder as allowed class path
120
-		foreach ($apps as $app) {
121
-			$path = self::getAppPath($app);
122
-			if ($path !== false) {
123
-				self::registerAutoloading($app, $path);
124
-			}
125
-		}
126
-
127
-		// prevent app.php from printing output
128
-		ob_start();
129
-		foreach ($apps as $app) {
130
-			if (!isset(self::$loadedApps[$app]) && ($types === [] || self::isType($app, $types))) {
131
-				self::loadApp($app);
132
-			}
133
-		}
134
-		ob_end_clean();
135
-
136
-		return true;
137
-	}
138
-
139
-	/**
140
-	 * load a single app
141
-	 *
142
-	 * @param string $app
143
-	 * @throws Exception
144
-	 */
145
-	public static function loadApp(string $app) {
146
-		self::$loadedApps[$app] = true;
147
-		$appPath = self::getAppPath($app);
148
-		if ($appPath === false) {
149
-			return;
150
-		}
151
-
152
-		// in case someone calls loadApp() directly
153
-		self::registerAutoloading($app, $appPath);
154
-
155
-		/** @var Coordinator $coordinator */
156
-		$coordinator = \OC::$server->query(Coordinator::class);
157
-		$isBootable = $coordinator->isBootable($app);
158
-
159
-		$hasAppPhpFile = is_file($appPath . '/appinfo/app.php');
160
-
161
-		if ($isBootable && $hasAppPhpFile) {
162
-			\OC::$server->getLogger()->error('/appinfo/app.php is not loaded when \OCP\AppFramework\Bootstrap\IBootstrap on the application class is used. Migrate everything from app.php to the Application class.', [
163
-				'app' => $app,
164
-			]);
165
-		} elseif ($hasAppPhpFile) {
166
-			\OC::$server->getLogger()->debug('/appinfo/app.php is deprecated, use \OCP\AppFramework\Bootstrap\IBootstrap on the application class instead.', [
167
-				'app' => $app,
168
-			]);
169
-			\OC::$server->getEventLogger()->start('load_app_' . $app, 'Load app: ' . $app);
170
-			try {
171
-				self::requireAppFile($app);
172
-			} catch (Throwable $ex) {
173
-				if ($ex instanceof ServerNotAvailableException) {
174
-					throw $ex;
175
-				}
176
-				if (!\OC::$server->getAppManager()->isShipped($app) && !self::isType($app, ['authentication'])) {
177
-					\OC::$server->getLogger()->logException($ex, [
178
-						'message' => "App $app threw an error during app.php load and will be disabled: " . $ex->getMessage(),
179
-					]);
180
-
181
-					// Only disable apps which are not shipped and that are not authentication apps
182
-					\OC::$server->getAppManager()->disableApp($app, true);
183
-				} else {
184
-					\OC::$server->getLogger()->logException($ex, [
185
-						'message' => "App $app threw an error during app.php load: " . $ex->getMessage(),
186
-					]);
187
-				}
188
-			}
189
-			\OC::$server->getEventLogger()->end('load_app_' . $app);
190
-		}
191
-		$coordinator->bootApp($app);
192
-
193
-		$info = self::getAppInfo($app);
194
-		if (!empty($info['activity']['filters'])) {
195
-			foreach ($info['activity']['filters'] as $filter) {
196
-				\OC::$server->getActivityManager()->registerFilter($filter);
197
-			}
198
-		}
199
-		if (!empty($info['activity']['settings'])) {
200
-			foreach ($info['activity']['settings'] as $setting) {
201
-				\OC::$server->getActivityManager()->registerSetting($setting);
202
-			}
203
-		}
204
-		if (!empty($info['activity']['providers'])) {
205
-			foreach ($info['activity']['providers'] as $provider) {
206
-				\OC::$server->getActivityManager()->registerProvider($provider);
207
-			}
208
-		}
209
-
210
-		if (!empty($info['settings']['admin'])) {
211
-			foreach ($info['settings']['admin'] as $setting) {
212
-				\OC::$server->getSettingsManager()->registerSetting('admin', $setting);
213
-			}
214
-		}
215
-		if (!empty($info['settings']['admin-section'])) {
216
-			foreach ($info['settings']['admin-section'] as $section) {
217
-				\OC::$server->getSettingsManager()->registerSection('admin', $section);
218
-			}
219
-		}
220
-		if (!empty($info['settings']['personal'])) {
221
-			foreach ($info['settings']['personal'] as $setting) {
222
-				\OC::$server->getSettingsManager()->registerSetting('personal', $setting);
223
-			}
224
-		}
225
-		if (!empty($info['settings']['personal-section'])) {
226
-			foreach ($info['settings']['personal-section'] as $section) {
227
-				\OC::$server->getSettingsManager()->registerSection('personal', $section);
228
-			}
229
-		}
230
-
231
-		if (!empty($info['collaboration']['plugins'])) {
232
-			// deal with one or many plugin entries
233
-			$plugins = isset($info['collaboration']['plugins']['plugin']['@value']) ?
234
-				[$info['collaboration']['plugins']['plugin']] : $info['collaboration']['plugins']['plugin'];
235
-			foreach ($plugins as $plugin) {
236
-				if ($plugin['@attributes']['type'] === 'collaborator-search') {
237
-					$pluginInfo = [
238
-						'shareType' => $plugin['@attributes']['share-type'],
239
-						'class' => $plugin['@value'],
240
-					];
241
-					\OC::$server->getCollaboratorSearch()->registerPlugin($pluginInfo);
242
-				} elseif ($plugin['@attributes']['type'] === 'autocomplete-sort') {
243
-					\OC::$server->getAutoCompleteManager()->registerSorter($plugin['@value']);
244
-				}
245
-			}
246
-		}
247
-	}
248
-
249
-	/**
250
-	 * @internal
251
-	 * @param string $app
252
-	 * @param string $path
253
-	 * @param bool $force
254
-	 */
255
-	public static function registerAutoloading(string $app, string $path, bool $force = false) {
256
-		$key = $app . '-' . $path;
257
-		if (!$force && isset(self::$alreadyRegistered[$key])) {
258
-			return;
259
-		}
260
-
261
-		self::$alreadyRegistered[$key] = true;
262
-
263
-		// Register on PSR-4 composer autoloader
264
-		$appNamespace = \OC\AppFramework\App::buildAppNamespace($app);
265
-		\OC::$server->registerNamespace($app, $appNamespace);
266
-
267
-		if (file_exists($path . '/composer/autoload.php')) {
268
-			require_once $path . '/composer/autoload.php';
269
-		} else {
270
-			\OC::$composerAutoloader->addPsr4($appNamespace . '\\', $path . '/lib/', true);
271
-			// Register on legacy autoloader
272
-			\OC::$loader->addValidRoot($path);
273
-		}
274
-
275
-		// Register Test namespace only when testing
276
-		if (defined('PHPUNIT_RUN') || defined('CLI_TEST_RUN')) {
277
-			\OC::$composerAutoloader->addPsr4($appNamespace . '\\Tests\\', $path . '/tests/', true);
278
-		}
279
-	}
280
-
281
-	/**
282
-	 * Load app.php from the given app
283
-	 *
284
-	 * @param string $app app name
285
-	 * @throws Error
286
-	 */
287
-	private static function requireAppFile(string $app) {
288
-		// encapsulated here to avoid variable scope conflicts
289
-		require_once $app . '/appinfo/app.php';
290
-	}
291
-
292
-	/**
293
-	 * check if an app is of a specific type
294
-	 *
295
-	 * @param string $app
296
-	 * @param array $types
297
-	 * @return bool
298
-	 */
299
-	public static function isType(string $app, array $types): bool {
300
-		$appTypes = self::getAppTypes($app);
301
-		foreach ($types as $type) {
302
-			if (array_search($type, $appTypes) !== false) {
303
-				return true;
304
-			}
305
-		}
306
-		return false;
307
-	}
308
-
309
-	/**
310
-	 * get the types of an app
311
-	 *
312
-	 * @param string $app
313
-	 * @return array
314
-	 */
315
-	private static function getAppTypes(string $app): array {
316
-		//load the cache
317
-		if (count(self::$appTypes) == 0) {
318
-			self::$appTypes = \OC::$server->getAppConfig()->getValues(false, 'types');
319
-		}
320
-
321
-		if (isset(self::$appTypes[$app])) {
322
-			return explode(',', self::$appTypes[$app]);
323
-		}
324
-
325
-		return [];
326
-	}
327
-
328
-	/**
329
-	 * read app types from info.xml and cache them in the database
330
-	 */
331
-	public static function setAppTypes(string $app) {
332
-		$appManager = \OC::$server->getAppManager();
333
-		$appData = $appManager->getAppInfo($app);
334
-		if (!is_array($appData)) {
335
-			return;
336
-		}
337
-
338
-		if (isset($appData['types'])) {
339
-			$appTypes = implode(',', $appData['types']);
340
-		} else {
341
-			$appTypes = '';
342
-			$appData['types'] = [];
343
-		}
344
-
345
-		$config = \OC::$server->getConfig();
346
-		$config->setAppValue($app, 'types', $appTypes);
347
-
348
-		if ($appManager->hasProtectedAppType($appData['types'])) {
349
-			$enabled = $config->getAppValue($app, 'enabled', 'yes');
350
-			if ($enabled !== 'yes' && $enabled !== 'no') {
351
-				$config->setAppValue($app, 'enabled', 'yes');
352
-			}
353
-		}
354
-	}
355
-
356
-	/**
357
-	 * Returns apps enabled for the current user.
358
-	 *
359
-	 * @param bool $forceRefresh whether to refresh the cache
360
-	 * @param bool $all whether to return apps for all users, not only the
361
-	 * currently logged in one
362
-	 * @return string[]
363
-	 */
364
-	public static function getEnabledApps(bool $forceRefresh = false, bool $all = false): array {
365
-		if (!\OC::$server->getSystemConfig()->getValue('installed', false)) {
366
-			return [];
367
-		}
368
-		// in incognito mode or when logged out, $user will be false,
369
-		// which is also the case during an upgrade
370
-		$appManager = \OC::$server->getAppManager();
371
-		if ($all) {
372
-			$user = null;
373
-		} else {
374
-			$user = \OC::$server->getUserSession()->getUser();
375
-		}
376
-
377
-		if (is_null($user)) {
378
-			$apps = $appManager->getInstalledApps();
379
-		} else {
380
-			$apps = $appManager->getEnabledAppsForUser($user);
381
-		}
382
-		$apps = array_filter($apps, function ($app) {
383
-			return $app !== 'files';//we add this manually
384
-		});
385
-		sort($apps);
386
-		array_unshift($apps, 'files');
387
-		return $apps;
388
-	}
389
-
390
-	/**
391
-	 * checks whether or not an app is enabled
392
-	 *
393
-	 * @param string $app app
394
-	 * @return bool
395
-	 * @deprecated 13.0.0 use \OC::$server->getAppManager()->isEnabledForUser($appId)
396
-	 *
397
-	 * This function checks whether or not an app is enabled.
398
-	 */
399
-	public static function isEnabled(string $app): bool {
400
-		return \OC::$server->getAppManager()->isEnabledForUser($app);
401
-	}
402
-
403
-	/**
404
-	 * enables an app
405
-	 *
406
-	 * @param string $appId
407
-	 * @param array $groups (optional) when set, only these groups will have access to the app
408
-	 * @throws \Exception
409
-	 * @return void
410
-	 *
411
-	 * This function set an app as enabled in appconfig.
412
-	 */
413
-	public function enable(string $appId,
414
-						   array $groups = []) {
415
-
416
-		// Check if app is already downloaded
417
-		/** @var Installer $installer */
418
-		$installer = \OC::$server->query(Installer::class);
419
-		$isDownloaded = $installer->isDownloaded($appId);
420
-
421
-		if (!$isDownloaded) {
422
-			$installer->downloadApp($appId);
423
-		}
424
-
425
-		$installer->installApp($appId);
426
-
427
-		$appManager = \OC::$server->getAppManager();
428
-		if ($groups !== []) {
429
-			$groupManager = \OC::$server->getGroupManager();
430
-			$groupsList = [];
431
-			foreach ($groups as $group) {
432
-				$groupItem = $groupManager->get($group);
433
-				if ($groupItem instanceof \OCP\IGroup) {
434
-					$groupsList[] = $groupManager->get($group);
435
-				}
436
-			}
437
-			$appManager->enableAppForGroups($appId, $groupsList);
438
-		} else {
439
-			$appManager->enableApp($appId);
440
-		}
441
-	}
442
-
443
-	/**
444
-	 * Get the path where to install apps
445
-	 *
446
-	 * @return string|false
447
-	 */
448
-	public static function getInstallPath() {
449
-		if (\OC::$server->getSystemConfig()->getValue('appstoreenabled', true) == false) {
450
-			return false;
451
-		}
452
-
453
-		foreach (OC::$APPSROOTS as $dir) {
454
-			if (isset($dir['writable']) && $dir['writable'] === true) {
455
-				return $dir['path'];
456
-			}
457
-		}
458
-
459
-		\OCP\Util::writeLog('core', 'No application directories are marked as writable.', ILogger::ERROR);
460
-		return null;
461
-	}
462
-
463
-
464
-	/**
465
-	 * search for an app in all app-directories
466
-	 *
467
-	 * @param string $appId
468
-	 * @return false|string
469
-	 */
470
-	public static function findAppInDirectories(string $appId) {
471
-		$sanitizedAppId = self::cleanAppId($appId);
472
-		if ($sanitizedAppId !== $appId) {
473
-			return false;
474
-		}
475
-		static $app_dir = [];
476
-
477
-		if (isset($app_dir[$appId])) {
478
-			return $app_dir[$appId];
479
-		}
480
-
481
-		$possibleApps = [];
482
-		foreach (OC::$APPSROOTS as $dir) {
483
-			if (file_exists($dir['path'] . '/' . $appId)) {
484
-				$possibleApps[] = $dir;
485
-			}
486
-		}
487
-
488
-		if (empty($possibleApps)) {
489
-			return false;
490
-		} elseif (count($possibleApps) === 1) {
491
-			$dir = array_shift($possibleApps);
492
-			$app_dir[$appId] = $dir;
493
-			return $dir;
494
-		} else {
495
-			$versionToLoad = [];
496
-			foreach ($possibleApps as $possibleApp) {
497
-				$version = self::getAppVersionByPath($possibleApp['path'] . '/' . $appId);
498
-				if (empty($versionToLoad) || version_compare($version, $versionToLoad['version'], '>')) {
499
-					$versionToLoad = [
500
-						'dir' => $possibleApp,
501
-						'version' => $version,
502
-					];
503
-				}
504
-			}
505
-			$app_dir[$appId] = $versionToLoad['dir'];
506
-			return $versionToLoad['dir'];
507
-			//TODO - write test
508
-		}
509
-	}
510
-
511
-	/**
512
-	 * Get the directory for the given app.
513
-	 * If the app is defined in multiple directories, the first one is taken. (false if not found)
514
-	 *
515
-	 * @param string $appId
516
-	 * @return string|false
517
-	 * @deprecated 11.0.0 use \OC::$server->getAppManager()->getAppPath()
518
-	 */
519
-	public static function getAppPath(string $appId) {
520
-		if ($appId === null || trim($appId) === '') {
521
-			return false;
522
-		}
523
-
524
-		if (($dir = self::findAppInDirectories($appId)) != false) {
525
-			return $dir['path'] . '/' . $appId;
526
-		}
527
-		return false;
528
-	}
529
-
530
-	/**
531
-	 * Get the path for the given app on the access
532
-	 * If the app is defined in multiple directories, the first one is taken. (false if not found)
533
-	 *
534
-	 * @param string $appId
535
-	 * @return string|false
536
-	 * @deprecated 18.0.0 use \OC::$server->getAppManager()->getAppWebPath()
537
-	 */
538
-	public static function getAppWebPath(string $appId) {
539
-		if (($dir = self::findAppInDirectories($appId)) != false) {
540
-			return OC::$WEBROOT . $dir['url'] . '/' . $appId;
541
-		}
542
-		return false;
543
-	}
544
-
545
-	/**
546
-	 * get the last version of the app from appinfo/info.xml
547
-	 *
548
-	 * @param string $appId
549
-	 * @param bool $useCache
550
-	 * @return string
551
-	 * @deprecated 14.0.0 use \OC::$server->getAppManager()->getAppVersion()
552
-	 */
553
-	public static function getAppVersion(string $appId, bool $useCache = true): string {
554
-		return \OC::$server->getAppManager()->getAppVersion($appId, $useCache);
555
-	}
556
-
557
-	/**
558
-	 * get app's version based on it's path
559
-	 *
560
-	 * @param string $path
561
-	 * @return string
562
-	 */
563
-	public static function getAppVersionByPath(string $path): string {
564
-		$infoFile = $path . '/appinfo/info.xml';
565
-		$appData = \OC::$server->getAppManager()->getAppInfo($infoFile, true);
566
-		return isset($appData['version']) ? $appData['version'] : '';
567
-	}
568
-
569
-
570
-	/**
571
-	 * Read all app metadata from the info.xml file
572
-	 *
573
-	 * @param string $appId id of the app or the path of the info.xml file
574
-	 * @param bool $path
575
-	 * @param string $lang
576
-	 * @return array|null
577
-	 * @note all data is read from info.xml, not just pre-defined fields
578
-	 * @deprecated 14.0.0 use \OC::$server->getAppManager()->getAppInfo()
579
-	 */
580
-	public static function getAppInfo(string $appId, bool $path = false, string $lang = null) {
581
-		return \OC::$server->getAppManager()->getAppInfo($appId, $path, $lang);
582
-	}
583
-
584
-	/**
585
-	 * Returns the navigation
586
-	 *
587
-	 * @return array
588
-	 * @deprecated 14.0.0 use \OC::$server->getNavigationManager()->getAll()
589
-	 *
590
-	 * This function returns an array containing all entries added. The
591
-	 * entries are sorted by the key 'order' ascending. Additional to the keys
592
-	 * given for each app the following keys exist:
593
-	 *   - active: boolean, signals if the user is on this navigation entry
594
-	 */
595
-	public static function getNavigation(): array {
596
-		return OC::$server->getNavigationManager()->getAll();
597
-	}
598
-
599
-	/**
600
-	 * Returns the Settings Navigation
601
-	 *
602
-	 * @return string[]
603
-	 * @deprecated 14.0.0 use \OC::$server->getNavigationManager()->getAll('settings')
604
-	 *
605
-	 * This function returns an array containing all settings pages added. The
606
-	 * entries are sorted by the key 'order' ascending.
607
-	 */
608
-	public static function getSettingsNavigation(): array {
609
-		return OC::$server->getNavigationManager()->getAll('settings');
610
-	}
611
-
612
-	/**
613
-	 * get the id of loaded app
614
-	 *
615
-	 * @return string
616
-	 */
617
-	public static function getCurrentApp(): string {
618
-		$request = \OC::$server->getRequest();
619
-		$script = substr($request->getScriptName(), strlen(OC::$WEBROOT) + 1);
620
-		$topFolder = substr($script, 0, strpos($script, '/') ?: 0);
621
-		if (empty($topFolder)) {
622
-			$path_info = $request->getPathInfo();
623
-			if ($path_info) {
624
-				$topFolder = substr($path_info, 1, strpos($path_info, '/', 1) - 1);
625
-			}
626
-		}
627
-		if ($topFolder == 'apps') {
628
-			$length = strlen($topFolder);
629
-			return substr($script, $length + 1, strpos($script, '/', $length + 1) - $length - 1) ?: '';
630
-		} else {
631
-			return $topFolder;
632
-		}
633
-	}
634
-
635
-	/**
636
-	 * @param string $type
637
-	 * @return array
638
-	 */
639
-	public static function getForms(string $type): array {
640
-		$forms = [];
641
-		switch ($type) {
642
-			case 'admin':
643
-				$source = self::$adminForms;
644
-				break;
645
-			case 'personal':
646
-				$source = self::$personalForms;
647
-				break;
648
-			default:
649
-				return [];
650
-		}
651
-		foreach ($source as $form) {
652
-			$forms[] = include $form;
653
-		}
654
-		return $forms;
655
-	}
656
-
657
-	/**
658
-	 * register an admin form to be shown
659
-	 *
660
-	 * @param string $app
661
-	 * @param string $page
662
-	 */
663
-	public static function registerAdmin(string $app, string $page) {
664
-		self::$adminForms[] = $app . '/' . $page . '.php';
665
-	}
666
-
667
-	/**
668
-	 * register a personal form to be shown
669
-	 * @param string $app
670
-	 * @param string $page
671
-	 */
672
-	public static function registerPersonal(string $app, string $page) {
673
-		self::$personalForms[] = $app . '/' . $page . '.php';
674
-	}
675
-
676
-	/**
677
-	 * @param array $entry
678
-	 * @deprecated 20.0.0 Please register your alternative login option using the registerAlternativeLogin() on the RegistrationContext in your Application class implementing the OCP\Authentication\IAlternativeLogin interface
679
-	 */
680
-	public static function registerLogIn(array $entry) {
681
-		\OC::$server->getLogger()->debug('OC_App::registerLogIn() is deprecated, please register your alternative login option using the registerAlternativeLogin() on the RegistrationContext in your Application class implementing the OCP\Authentication\IAlternativeLogin interface');
682
-		self::$altLogin[] = $entry;
683
-	}
684
-
685
-	/**
686
-	 * @return array
687
-	 */
688
-	public static function getAlternativeLogIns(): array {
689
-		/** @var Coordinator $bootstrapCoordinator */
690
-		$bootstrapCoordinator = \OC::$server->query(Coordinator::class);
691
-
692
-		foreach ($bootstrapCoordinator->getRegistrationContext()->getAlternativeLogins() as $registration) {
693
-			if (!in_array(IAlternativeLogin::class, class_implements($registration['class']), true)) {
694
-				\OC::$server->getLogger()->error('Alternative login option {option} does not implement {interface} and is therefore ignored.', [
695
-					'option' => $registration['class'],
696
-					'interface' => IAlternativeLogin::class,
697
-					'app' => $registration['app'],
698
-				]);
699
-				continue;
700
-			}
701
-
702
-			try {
703
-				/** @var IAlternativeLogin $provider */
704
-				$provider = \OC::$server->query($registration['class']);
705
-			} catch (QueryException $e) {
706
-				\OC::$server->getLogger()->logException($e, [
707
-					'message' => 'Alternative login option {option} can not be initialised.',
708
-					'option' => $registration['class'],
709
-					'app' => $registration['app'],
710
-				]);
711
-			}
712
-
713
-			try {
714
-				$provider->load();
715
-
716
-				self::$altLogin[] = [
717
-					'name' => $provider->getLabel(),
718
-					'href' => $provider->getLink(),
719
-					'style' => $provider->getClass(),
720
-				];
721
-			} catch (Throwable $e) {
722
-				\OC::$server->getLogger()->logException($e, [
723
-					'message' => 'Alternative login option {option} had an error while loading.',
724
-					'option' => $registration['class'],
725
-					'app' => $registration['app'],
726
-				]);
727
-			}
728
-		}
729
-
730
-		return self::$altLogin;
731
-	}
732
-
733
-	/**
734
-	 * get a list of all apps in the apps folder
735
-	 *
736
-	 * @return string[] an array of app names (string IDs)
737
-	 * @todo: change the name of this method to getInstalledApps, which is more accurate
738
-	 */
739
-	public static function getAllApps(): array {
740
-		$apps = [];
741
-
742
-		foreach (OC::$APPSROOTS as $apps_dir) {
743
-			if (!is_readable($apps_dir['path'])) {
744
-				\OCP\Util::writeLog('core', 'unable to read app folder : ' . $apps_dir['path'], ILogger::WARN);
745
-				continue;
746
-			}
747
-			$dh = opendir($apps_dir['path']);
748
-
749
-			if (is_resource($dh)) {
750
-				while (($file = readdir($dh)) !== false) {
751
-					if ($file[0] != '.' and is_dir($apps_dir['path'] . '/' . $file) and is_file($apps_dir['path'] . '/' . $file . '/appinfo/info.xml')) {
752
-						$apps[] = $file;
753
-					}
754
-				}
755
-			}
756
-		}
757
-
758
-		$apps = array_unique($apps);
759
-
760
-		return $apps;
761
-	}
762
-
763
-	/**
764
-	 * List all apps, this is used in apps.php
765
-	 *
766
-	 * @return array
767
-	 */
768
-	public function listAllApps(): array {
769
-		$installedApps = OC_App::getAllApps();
770
-
771
-		$appManager = \OC::$server->getAppManager();
772
-		//we don't want to show configuration for these
773
-		$blacklist = $appManager->getAlwaysEnabledApps();
774
-		$appList = [];
775
-		$langCode = \OC::$server->getL10N('core')->getLanguageCode();
776
-		$urlGenerator = \OC::$server->getURLGenerator();
777
-		/** @var \OCP\Support\Subscription\IRegistry $subscriptionRegistry */
778
-		$subscriptionRegistry = \OC::$server->query(\OCP\Support\Subscription\IRegistry::class);
779
-		$supportedApps = $subscriptionRegistry->delegateGetSupportedApps();
780
-
781
-		foreach ($installedApps as $app) {
782
-			if (array_search($app, $blacklist) === false) {
783
-				$info = OC_App::getAppInfo($app, false, $langCode);
784
-				if (!is_array($info)) {
785
-					\OCP\Util::writeLog('core', 'Could not read app info file for app "' . $app . '"', ILogger::ERROR);
786
-					continue;
787
-				}
788
-
789
-				if (!isset($info['name'])) {
790
-					\OCP\Util::writeLog('core', 'App id "' . $app . '" has no name in appinfo', ILogger::ERROR);
791
-					continue;
792
-				}
793
-
794
-				$enabled = \OC::$server->getConfig()->getAppValue($app, 'enabled', 'no');
795
-				$info['groups'] = null;
796
-				if ($enabled === 'yes') {
797
-					$active = true;
798
-				} elseif ($enabled === 'no') {
799
-					$active = false;
800
-				} else {
801
-					$active = true;
802
-					$info['groups'] = $enabled;
803
-				}
804
-
805
-				$info['active'] = $active;
806
-
807
-				if ($appManager->isShipped($app)) {
808
-					$info['internal'] = true;
809
-					$info['level'] = self::officialApp;
810
-					$info['removable'] = false;
811
-				} else {
812
-					$info['internal'] = false;
813
-					$info['removable'] = true;
814
-				}
815
-
816
-				if (in_array($app, $supportedApps)) {
817
-					$info['level'] = self::supportedApp;
818
-				}
819
-
820
-				$appPath = self::getAppPath($app);
821
-				if ($appPath !== false) {
822
-					$appIcon = $appPath . '/img/' . $app . '.svg';
823
-					if (file_exists($appIcon)) {
824
-						$info['preview'] = $urlGenerator->imagePath($app, $app . '.svg');
825
-						$info['previewAsIcon'] = true;
826
-					} else {
827
-						$appIcon = $appPath . '/img/app.svg';
828
-						if (file_exists($appIcon)) {
829
-							$info['preview'] = $urlGenerator->imagePath($app, 'app.svg');
830
-							$info['previewAsIcon'] = true;
831
-						}
832
-					}
833
-				}
834
-				// fix documentation
835
-				if (isset($info['documentation']) && is_array($info['documentation'])) {
836
-					foreach ($info['documentation'] as $key => $url) {
837
-						// If it is not an absolute URL we assume it is a key
838
-						// i.e. admin-ldap will get converted to go.php?to=admin-ldap
839
-						if (stripos($url, 'https://') !== 0 && stripos($url, 'http://') !== 0) {
840
-							$url = $urlGenerator->linkToDocs($url);
841
-						}
842
-
843
-						$info['documentation'][$key] = $url;
844
-					}
845
-				}
846
-
847
-				$info['version'] = OC_App::getAppVersion($app);
848
-				$appList[] = $info;
849
-			}
850
-		}
851
-
852
-		return $appList;
853
-	}
854
-
855
-	public static function shouldUpgrade(string $app): bool {
856
-		$versions = self::getAppVersions();
857
-		$currentVersion = OC_App::getAppVersion($app);
858
-		if ($currentVersion && isset($versions[$app])) {
859
-			$installedVersion = $versions[$app];
860
-			if (!version_compare($currentVersion, $installedVersion, '=')) {
861
-				return true;
862
-			}
863
-		}
864
-		return false;
865
-	}
866
-
867
-	/**
868
-	 * Adjust the number of version parts of $version1 to match
869
-	 * the number of version parts of $version2.
870
-	 *
871
-	 * @param string $version1 version to adjust
872
-	 * @param string $version2 version to take the number of parts from
873
-	 * @return string shortened $version1
874
-	 */
875
-	private static function adjustVersionParts(string $version1, string $version2): string {
876
-		$version1 = explode('.', $version1);
877
-		$version2 = explode('.', $version2);
878
-		// reduce $version1 to match the number of parts in $version2
879
-		while (count($version1) > count($version2)) {
880
-			array_pop($version1);
881
-		}
882
-		// if $version1 does not have enough parts, add some
883
-		while (count($version1) < count($version2)) {
884
-			$version1[] = '0';
885
-		}
886
-		return implode('.', $version1);
887
-	}
888
-
889
-	/**
890
-	 * Check whether the current ownCloud version matches the given
891
-	 * application's version requirements.
892
-	 *
893
-	 * The comparison is made based on the number of parts that the
894
-	 * app info version has. For example for ownCloud 6.0.3 if the
895
-	 * app info version is expecting version 6.0, the comparison is
896
-	 * made on the first two parts of the ownCloud version.
897
-	 * This means that it's possible to specify "requiremin" => 6
898
-	 * and "requiremax" => 6 and it will still match ownCloud 6.0.3.
899
-	 *
900
-	 * @param string $ocVersion ownCloud version to check against
901
-	 * @param array $appInfo app info (from xml)
902
-	 *
903
-	 * @return boolean true if compatible, otherwise false
904
-	 */
905
-	public static function isAppCompatible(string $ocVersion, array $appInfo, bool $ignoreMax = false): bool {
906
-		$requireMin = '';
907
-		$requireMax = '';
908
-		if (isset($appInfo['dependencies']['nextcloud']['@attributes']['min-version'])) {
909
-			$requireMin = $appInfo['dependencies']['nextcloud']['@attributes']['min-version'];
910
-		} elseif (isset($appInfo['dependencies']['owncloud']['@attributes']['min-version'])) {
911
-			$requireMin = $appInfo['dependencies']['owncloud']['@attributes']['min-version'];
912
-		} elseif (isset($appInfo['requiremin'])) {
913
-			$requireMin = $appInfo['requiremin'];
914
-		} elseif (isset($appInfo['require'])) {
915
-			$requireMin = $appInfo['require'];
916
-		}
917
-
918
-		if (isset($appInfo['dependencies']['nextcloud']['@attributes']['max-version'])) {
919
-			$requireMax = $appInfo['dependencies']['nextcloud']['@attributes']['max-version'];
920
-		} elseif (isset($appInfo['dependencies']['owncloud']['@attributes']['max-version'])) {
921
-			$requireMax = $appInfo['dependencies']['owncloud']['@attributes']['max-version'];
922
-		} elseif (isset($appInfo['requiremax'])) {
923
-			$requireMax = $appInfo['requiremax'];
924
-		}
925
-
926
-		if (!empty($requireMin)
927
-			&& version_compare(self::adjustVersionParts($ocVersion, $requireMin), $requireMin, '<')
928
-		) {
929
-			return false;
930
-		}
931
-
932
-		if (!$ignoreMax && !empty($requireMax)
933
-			&& version_compare(self::adjustVersionParts($ocVersion, $requireMax), $requireMax, '>')
934
-		) {
935
-			return false;
936
-		}
937
-
938
-		return true;
939
-	}
940
-
941
-	/**
942
-	 * get the installed version of all apps
943
-	 */
944
-	public static function getAppVersions() {
945
-		static $versions;
946
-
947
-		if (!$versions) {
948
-			$appConfig = \OC::$server->getAppConfig();
949
-			$versions = $appConfig->getValues(false, 'installed_version');
950
-		}
951
-		return $versions;
952
-	}
953
-
954
-	/**
955
-	 * update the database for the app and call the update script
956
-	 *
957
-	 * @param string $appId
958
-	 * @return bool
959
-	 */
960
-	public static function updateApp(string $appId): bool {
961
-		$appPath = self::getAppPath($appId);
962
-		if ($appPath === false) {
963
-			return false;
964
-		}
965
-
966
-		\OC::$server->getAppManager()->clearAppsCache();
967
-		$appData = self::getAppInfo($appId);
968
-
969
-		self::registerAutoloading($appId, $appPath, true);
970
-		self::executeRepairSteps($appId, $appData['repair-steps']['pre-migration']);
971
-
972
-		if (file_exists($appPath . '/appinfo/database.xml')) {
973
-			OC_DB::updateDbFromStructure($appPath . '/appinfo/database.xml');
974
-		} else {
975
-			$ms = new MigrationService($appId, \OC::$server->getDatabaseConnection());
976
-			$ms->migrate();
977
-		}
978
-
979
-		self::executeRepairSteps($appId, $appData['repair-steps']['post-migration']);
980
-		self::setupLiveMigrations($appId, $appData['repair-steps']['live-migration']);
981
-		// update appversion in app manager
982
-		\OC::$server->getAppManager()->clearAppsCache();
983
-		\OC::$server->getAppManager()->getAppVersion($appId, false);
984
-
985
-		// run upgrade code
986
-		if (file_exists($appPath . '/appinfo/update.php')) {
987
-			self::loadApp($appId);
988
-			include $appPath . '/appinfo/update.php';
989
-		}
990
-		self::setupBackgroundJobs($appData['background-jobs']);
991
-
992
-		//set remote/public handlers
993
-		if (array_key_exists('ocsid', $appData)) {
994
-			\OC::$server->getConfig()->setAppValue($appId, 'ocsid', $appData['ocsid']);
995
-		} elseif (\OC::$server->getConfig()->getAppValue($appId, 'ocsid', null) !== null) {
996
-			\OC::$server->getConfig()->deleteAppValue($appId, 'ocsid');
997
-		}
998
-		foreach ($appData['remote'] as $name => $path) {
999
-			\OC::$server->getConfig()->setAppValue('core', 'remote_' . $name, $appId . '/' . $path);
1000
-		}
1001
-		foreach ($appData['public'] as $name => $path) {
1002
-			\OC::$server->getConfig()->setAppValue('core', 'public_' . $name, $appId . '/' . $path);
1003
-		}
1004
-
1005
-		self::setAppTypes($appId);
1006
-
1007
-		$version = \OC_App::getAppVersion($appId);
1008
-		\OC::$server->getConfig()->setAppValue($appId, 'installed_version', $version);
1009
-
1010
-		\OC::$server->getEventDispatcher()->dispatch(ManagerEvent::EVENT_APP_UPDATE, new ManagerEvent(
1011
-			ManagerEvent::EVENT_APP_UPDATE, $appId
1012
-		));
1013
-
1014
-		return true;
1015
-	}
1016
-
1017
-	/**
1018
-	 * @param string $appId
1019
-	 * @param string[] $steps
1020
-	 * @throws \OC\NeedsUpdateException
1021
-	 */
1022
-	public static function executeRepairSteps(string $appId, array $steps) {
1023
-		if (empty($steps)) {
1024
-			return;
1025
-		}
1026
-		// load the app
1027
-		self::loadApp($appId);
1028
-
1029
-		$dispatcher = OC::$server->getEventDispatcher();
1030
-
1031
-		// load the steps
1032
-		$r = new Repair([], $dispatcher);
1033
-		foreach ($steps as $step) {
1034
-			try {
1035
-				$r->addStep($step);
1036
-			} catch (Exception $ex) {
1037
-				$r->emit('\OC\Repair', 'error', [$ex->getMessage()]);
1038
-				\OC::$server->getLogger()->logException($ex);
1039
-			}
1040
-		}
1041
-		// run the steps
1042
-		$r->run();
1043
-	}
1044
-
1045
-	public static function setupBackgroundJobs(array $jobs) {
1046
-		$queue = \OC::$server->getJobList();
1047
-		foreach ($jobs as $job) {
1048
-			$queue->add($job);
1049
-		}
1050
-	}
1051
-
1052
-	/**
1053
-	 * @param string $appId
1054
-	 * @param string[] $steps
1055
-	 */
1056
-	private static function setupLiveMigrations(string $appId, array $steps) {
1057
-		$queue = \OC::$server->getJobList();
1058
-		foreach ($steps as $step) {
1059
-			$queue->add('OC\Migration\BackgroundRepair', [
1060
-				'app' => $appId,
1061
-				'step' => $step]);
1062
-		}
1063
-	}
1064
-
1065
-	/**
1066
-	 * @param string $appId
1067
-	 * @return \OC\Files\View|false
1068
-	 */
1069
-	public static function getStorage(string $appId) {
1070
-		if (\OC::$server->getAppManager()->isEnabledForUser($appId)) { //sanity check
1071
-			if (\OC::$server->getUserSession()->isLoggedIn()) {
1072
-				$view = new \OC\Files\View('/' . OC_User::getUser());
1073
-				if (!$view->file_exists($appId)) {
1074
-					$view->mkdir($appId);
1075
-				}
1076
-				return new \OC\Files\View('/' . OC_User::getUser() . '/' . $appId);
1077
-			} else {
1078
-				\OCP\Util::writeLog('core', 'Can\'t get app storage, app ' . $appId . ', user not logged in', ILogger::ERROR);
1079
-				return false;
1080
-			}
1081
-		} else {
1082
-			\OCP\Util::writeLog('core', 'Can\'t get app storage, app ' . $appId . ' not enabled', ILogger::ERROR);
1083
-			return false;
1084
-		}
1085
-	}
1086
-
1087
-	protected static function findBestL10NOption(array $options, string $lang): string {
1088
-		// only a single option
1089
-		if (isset($options['@value'])) {
1090
-			return $options['@value'];
1091
-		}
1092
-
1093
-		$fallback = $similarLangFallback = $englishFallback = false;
1094
-
1095
-		$lang = strtolower($lang);
1096
-		$similarLang = $lang;
1097
-		if (strpos($similarLang, '_')) {
1098
-			// For "de_DE" we want to find "de" and the other way around
1099
-			$similarLang = substr($lang, 0, strpos($lang, '_'));
1100
-		}
1101
-
1102
-		foreach ($options as $option) {
1103
-			if (is_array($option)) {
1104
-				if ($fallback === false) {
1105
-					$fallback = $option['@value'];
1106
-				}
1107
-
1108
-				if (!isset($option['@attributes']['lang'])) {
1109
-					continue;
1110
-				}
1111
-
1112
-				$attributeLang = strtolower($option['@attributes']['lang']);
1113
-				if ($attributeLang === $lang) {
1114
-					return $option['@value'];
1115
-				}
1116
-
1117
-				if ($attributeLang === $similarLang) {
1118
-					$similarLangFallback = $option['@value'];
1119
-				} elseif (strpos($attributeLang, $similarLang . '_') === 0) {
1120
-					if ($similarLangFallback === false) {
1121
-						$similarLangFallback = $option['@value'];
1122
-					}
1123
-				}
1124
-			} else {
1125
-				$englishFallback = $option;
1126
-			}
1127
-		}
1128
-
1129
-		if ($similarLangFallback !== false) {
1130
-			return $similarLangFallback;
1131
-		} elseif ($englishFallback !== false) {
1132
-			return $englishFallback;
1133
-		}
1134
-		return (string) $fallback;
1135
-	}
1136
-
1137
-	/**
1138
-	 * parses the app data array and enhanced the 'description' value
1139
-	 *
1140
-	 * @param array $data the app data
1141
-	 * @param string $lang
1142
-	 * @return array improved app data
1143
-	 */
1144
-	public static function parseAppInfo(array $data, $lang = null): array {
1145
-		if ($lang && isset($data['name']) && is_array($data['name'])) {
1146
-			$data['name'] = self::findBestL10NOption($data['name'], $lang);
1147
-		}
1148
-		if ($lang && isset($data['summary']) && is_array($data['summary'])) {
1149
-			$data['summary'] = self::findBestL10NOption($data['summary'], $lang);
1150
-		}
1151
-		if ($lang && isset($data['description']) && is_array($data['description'])) {
1152
-			$data['description'] = trim(self::findBestL10NOption($data['description'], $lang));
1153
-		} elseif (isset($data['description']) && is_string($data['description'])) {
1154
-			$data['description'] = trim($data['description']);
1155
-		} else {
1156
-			$data['description'] = '';
1157
-		}
1158
-
1159
-		return $data;
1160
-	}
1161
-
1162
-	/**
1163
-	 * @param \OCP\IConfig $config
1164
-	 * @param \OCP\IL10N $l
1165
-	 * @param array $info
1166
-	 * @throws \Exception
1167
-	 */
1168
-	public static function checkAppDependencies(\OCP\IConfig $config, \OCP\IL10N $l, array $info, bool $ignoreMax) {
1169
-		$dependencyAnalyzer = new DependencyAnalyzer(new Platform($config), $l);
1170
-		$missing = $dependencyAnalyzer->analyze($info, $ignoreMax);
1171
-		if (!empty($missing)) {
1172
-			$missingMsg = implode(PHP_EOL, $missing);
1173
-			throw new \Exception(
1174
-				$l->t('App "%1$s" cannot be installed because the following dependencies are not fulfilled: %2$s',
1175
-					[$info['name'], $missingMsg]
1176
-				)
1177
-			);
1178
-		}
1179
-	}
71
+    private static $adminForms = [];
72
+    private static $personalForms = [];
73
+    private static $appTypes = [];
74
+    private static $loadedApps = [];
75
+    private static $altLogin = [];
76
+    private static $alreadyRegistered = [];
77
+    public const supportedApp = 300;
78
+    public const officialApp = 200;
79
+
80
+    /**
81
+     * clean the appId
82
+     *
83
+     * @param string $app AppId that needs to be cleaned
84
+     * @return string
85
+     */
86
+    public static function cleanAppId(string $app): string {
87
+        return str_replace(['\0', '/', '\\', '..'], '', $app);
88
+    }
89
+
90
+    /**
91
+     * Check if an app is loaded
92
+     *
93
+     * @param string $app
94
+     * @return bool
95
+     */
96
+    public static function isAppLoaded(string $app): bool {
97
+        return isset(self::$loadedApps[$app]);
98
+    }
99
+
100
+    /**
101
+     * loads all apps
102
+     *
103
+     * @param string[] $types
104
+     * @return bool
105
+     *
106
+     * This function walks through the ownCloud directory and loads all apps
107
+     * it can find. A directory contains an app if the file /appinfo/info.xml
108
+     * exists.
109
+     *
110
+     * if $types is set to non-empty array, only apps of those types will be loaded
111
+     */
112
+    public static function loadApps(array $types = []): bool {
113
+        if ((bool) \OC::$server->getSystemConfig()->getValue('maintenance', false)) {
114
+            return false;
115
+        }
116
+        // Load the enabled apps here
117
+        $apps = self::getEnabledApps();
118
+
119
+        // Add each apps' folder as allowed class path
120
+        foreach ($apps as $app) {
121
+            $path = self::getAppPath($app);
122
+            if ($path !== false) {
123
+                self::registerAutoloading($app, $path);
124
+            }
125
+        }
126
+
127
+        // prevent app.php from printing output
128
+        ob_start();
129
+        foreach ($apps as $app) {
130
+            if (!isset(self::$loadedApps[$app]) && ($types === [] || self::isType($app, $types))) {
131
+                self::loadApp($app);
132
+            }
133
+        }
134
+        ob_end_clean();
135
+
136
+        return true;
137
+    }
138
+
139
+    /**
140
+     * load a single app
141
+     *
142
+     * @param string $app
143
+     * @throws Exception
144
+     */
145
+    public static function loadApp(string $app) {
146
+        self::$loadedApps[$app] = true;
147
+        $appPath = self::getAppPath($app);
148
+        if ($appPath === false) {
149
+            return;
150
+        }
151
+
152
+        // in case someone calls loadApp() directly
153
+        self::registerAutoloading($app, $appPath);
154
+
155
+        /** @var Coordinator $coordinator */
156
+        $coordinator = \OC::$server->query(Coordinator::class);
157
+        $isBootable = $coordinator->isBootable($app);
158
+
159
+        $hasAppPhpFile = is_file($appPath . '/appinfo/app.php');
160
+
161
+        if ($isBootable && $hasAppPhpFile) {
162
+            \OC::$server->getLogger()->error('/appinfo/app.php is not loaded when \OCP\AppFramework\Bootstrap\IBootstrap on the application class is used. Migrate everything from app.php to the Application class.', [
163
+                'app' => $app,
164
+            ]);
165
+        } elseif ($hasAppPhpFile) {
166
+            \OC::$server->getLogger()->debug('/appinfo/app.php is deprecated, use \OCP\AppFramework\Bootstrap\IBootstrap on the application class instead.', [
167
+                'app' => $app,
168
+            ]);
169
+            \OC::$server->getEventLogger()->start('load_app_' . $app, 'Load app: ' . $app);
170
+            try {
171
+                self::requireAppFile($app);
172
+            } catch (Throwable $ex) {
173
+                if ($ex instanceof ServerNotAvailableException) {
174
+                    throw $ex;
175
+                }
176
+                if (!\OC::$server->getAppManager()->isShipped($app) && !self::isType($app, ['authentication'])) {
177
+                    \OC::$server->getLogger()->logException($ex, [
178
+                        'message' => "App $app threw an error during app.php load and will be disabled: " . $ex->getMessage(),
179
+                    ]);
180
+
181
+                    // Only disable apps which are not shipped and that are not authentication apps
182
+                    \OC::$server->getAppManager()->disableApp($app, true);
183
+                } else {
184
+                    \OC::$server->getLogger()->logException($ex, [
185
+                        'message' => "App $app threw an error during app.php load: " . $ex->getMessage(),
186
+                    ]);
187
+                }
188
+            }
189
+            \OC::$server->getEventLogger()->end('load_app_' . $app);
190
+        }
191
+        $coordinator->bootApp($app);
192
+
193
+        $info = self::getAppInfo($app);
194
+        if (!empty($info['activity']['filters'])) {
195
+            foreach ($info['activity']['filters'] as $filter) {
196
+                \OC::$server->getActivityManager()->registerFilter($filter);
197
+            }
198
+        }
199
+        if (!empty($info['activity']['settings'])) {
200
+            foreach ($info['activity']['settings'] as $setting) {
201
+                \OC::$server->getActivityManager()->registerSetting($setting);
202
+            }
203
+        }
204
+        if (!empty($info['activity']['providers'])) {
205
+            foreach ($info['activity']['providers'] as $provider) {
206
+                \OC::$server->getActivityManager()->registerProvider($provider);
207
+            }
208
+        }
209
+
210
+        if (!empty($info['settings']['admin'])) {
211
+            foreach ($info['settings']['admin'] as $setting) {
212
+                \OC::$server->getSettingsManager()->registerSetting('admin', $setting);
213
+            }
214
+        }
215
+        if (!empty($info['settings']['admin-section'])) {
216
+            foreach ($info['settings']['admin-section'] as $section) {
217
+                \OC::$server->getSettingsManager()->registerSection('admin', $section);
218
+            }
219
+        }
220
+        if (!empty($info['settings']['personal'])) {
221
+            foreach ($info['settings']['personal'] as $setting) {
222
+                \OC::$server->getSettingsManager()->registerSetting('personal', $setting);
223
+            }
224
+        }
225
+        if (!empty($info['settings']['personal-section'])) {
226
+            foreach ($info['settings']['personal-section'] as $section) {
227
+                \OC::$server->getSettingsManager()->registerSection('personal', $section);
228
+            }
229
+        }
230
+
231
+        if (!empty($info['collaboration']['plugins'])) {
232
+            // deal with one or many plugin entries
233
+            $plugins = isset($info['collaboration']['plugins']['plugin']['@value']) ?
234
+                [$info['collaboration']['plugins']['plugin']] : $info['collaboration']['plugins']['plugin'];
235
+            foreach ($plugins as $plugin) {
236
+                if ($plugin['@attributes']['type'] === 'collaborator-search') {
237
+                    $pluginInfo = [
238
+                        'shareType' => $plugin['@attributes']['share-type'],
239
+                        'class' => $plugin['@value'],
240
+                    ];
241
+                    \OC::$server->getCollaboratorSearch()->registerPlugin($pluginInfo);
242
+                } elseif ($plugin['@attributes']['type'] === 'autocomplete-sort') {
243
+                    \OC::$server->getAutoCompleteManager()->registerSorter($plugin['@value']);
244
+                }
245
+            }
246
+        }
247
+    }
248
+
249
+    /**
250
+     * @internal
251
+     * @param string $app
252
+     * @param string $path
253
+     * @param bool $force
254
+     */
255
+    public static function registerAutoloading(string $app, string $path, bool $force = false) {
256
+        $key = $app . '-' . $path;
257
+        if (!$force && isset(self::$alreadyRegistered[$key])) {
258
+            return;
259
+        }
260
+
261
+        self::$alreadyRegistered[$key] = true;
262
+
263
+        // Register on PSR-4 composer autoloader
264
+        $appNamespace = \OC\AppFramework\App::buildAppNamespace($app);
265
+        \OC::$server->registerNamespace($app, $appNamespace);
266
+
267
+        if (file_exists($path . '/composer/autoload.php')) {
268
+            require_once $path . '/composer/autoload.php';
269
+        } else {
270
+            \OC::$composerAutoloader->addPsr4($appNamespace . '\\', $path . '/lib/', true);
271
+            // Register on legacy autoloader
272
+            \OC::$loader->addValidRoot($path);
273
+        }
274
+
275
+        // Register Test namespace only when testing
276
+        if (defined('PHPUNIT_RUN') || defined('CLI_TEST_RUN')) {
277
+            \OC::$composerAutoloader->addPsr4($appNamespace . '\\Tests\\', $path . '/tests/', true);
278
+        }
279
+    }
280
+
281
+    /**
282
+     * Load app.php from the given app
283
+     *
284
+     * @param string $app app name
285
+     * @throws Error
286
+     */
287
+    private static function requireAppFile(string $app) {
288
+        // encapsulated here to avoid variable scope conflicts
289
+        require_once $app . '/appinfo/app.php';
290
+    }
291
+
292
+    /**
293
+     * check if an app is of a specific type
294
+     *
295
+     * @param string $app
296
+     * @param array $types
297
+     * @return bool
298
+     */
299
+    public static function isType(string $app, array $types): bool {
300
+        $appTypes = self::getAppTypes($app);
301
+        foreach ($types as $type) {
302
+            if (array_search($type, $appTypes) !== false) {
303
+                return true;
304
+            }
305
+        }
306
+        return false;
307
+    }
308
+
309
+    /**
310
+     * get the types of an app
311
+     *
312
+     * @param string $app
313
+     * @return array
314
+     */
315
+    private static function getAppTypes(string $app): array {
316
+        //load the cache
317
+        if (count(self::$appTypes) == 0) {
318
+            self::$appTypes = \OC::$server->getAppConfig()->getValues(false, 'types');
319
+        }
320
+
321
+        if (isset(self::$appTypes[$app])) {
322
+            return explode(',', self::$appTypes[$app]);
323
+        }
324
+
325
+        return [];
326
+    }
327
+
328
+    /**
329
+     * read app types from info.xml and cache them in the database
330
+     */
331
+    public static function setAppTypes(string $app) {
332
+        $appManager = \OC::$server->getAppManager();
333
+        $appData = $appManager->getAppInfo($app);
334
+        if (!is_array($appData)) {
335
+            return;
336
+        }
337
+
338
+        if (isset($appData['types'])) {
339
+            $appTypes = implode(',', $appData['types']);
340
+        } else {
341
+            $appTypes = '';
342
+            $appData['types'] = [];
343
+        }
344
+
345
+        $config = \OC::$server->getConfig();
346
+        $config->setAppValue($app, 'types', $appTypes);
347
+
348
+        if ($appManager->hasProtectedAppType($appData['types'])) {
349
+            $enabled = $config->getAppValue($app, 'enabled', 'yes');
350
+            if ($enabled !== 'yes' && $enabled !== 'no') {
351
+                $config->setAppValue($app, 'enabled', 'yes');
352
+            }
353
+        }
354
+    }
355
+
356
+    /**
357
+     * Returns apps enabled for the current user.
358
+     *
359
+     * @param bool $forceRefresh whether to refresh the cache
360
+     * @param bool $all whether to return apps for all users, not only the
361
+     * currently logged in one
362
+     * @return string[]
363
+     */
364
+    public static function getEnabledApps(bool $forceRefresh = false, bool $all = false): array {
365
+        if (!\OC::$server->getSystemConfig()->getValue('installed', false)) {
366
+            return [];
367
+        }
368
+        // in incognito mode or when logged out, $user will be false,
369
+        // which is also the case during an upgrade
370
+        $appManager = \OC::$server->getAppManager();
371
+        if ($all) {
372
+            $user = null;
373
+        } else {
374
+            $user = \OC::$server->getUserSession()->getUser();
375
+        }
376
+
377
+        if (is_null($user)) {
378
+            $apps = $appManager->getInstalledApps();
379
+        } else {
380
+            $apps = $appManager->getEnabledAppsForUser($user);
381
+        }
382
+        $apps = array_filter($apps, function ($app) {
383
+            return $app !== 'files';//we add this manually
384
+        });
385
+        sort($apps);
386
+        array_unshift($apps, 'files');
387
+        return $apps;
388
+    }
389
+
390
+    /**
391
+     * checks whether or not an app is enabled
392
+     *
393
+     * @param string $app app
394
+     * @return bool
395
+     * @deprecated 13.0.0 use \OC::$server->getAppManager()->isEnabledForUser($appId)
396
+     *
397
+     * This function checks whether or not an app is enabled.
398
+     */
399
+    public static function isEnabled(string $app): bool {
400
+        return \OC::$server->getAppManager()->isEnabledForUser($app);
401
+    }
402
+
403
+    /**
404
+     * enables an app
405
+     *
406
+     * @param string $appId
407
+     * @param array $groups (optional) when set, only these groups will have access to the app
408
+     * @throws \Exception
409
+     * @return void
410
+     *
411
+     * This function set an app as enabled in appconfig.
412
+     */
413
+    public function enable(string $appId,
414
+                            array $groups = []) {
415
+
416
+        // Check if app is already downloaded
417
+        /** @var Installer $installer */
418
+        $installer = \OC::$server->query(Installer::class);
419
+        $isDownloaded = $installer->isDownloaded($appId);
420
+
421
+        if (!$isDownloaded) {
422
+            $installer->downloadApp($appId);
423
+        }
424
+
425
+        $installer->installApp($appId);
426
+
427
+        $appManager = \OC::$server->getAppManager();
428
+        if ($groups !== []) {
429
+            $groupManager = \OC::$server->getGroupManager();
430
+            $groupsList = [];
431
+            foreach ($groups as $group) {
432
+                $groupItem = $groupManager->get($group);
433
+                if ($groupItem instanceof \OCP\IGroup) {
434
+                    $groupsList[] = $groupManager->get($group);
435
+                }
436
+            }
437
+            $appManager->enableAppForGroups($appId, $groupsList);
438
+        } else {
439
+            $appManager->enableApp($appId);
440
+        }
441
+    }
442
+
443
+    /**
444
+     * Get the path where to install apps
445
+     *
446
+     * @return string|false
447
+     */
448
+    public static function getInstallPath() {
449
+        if (\OC::$server->getSystemConfig()->getValue('appstoreenabled', true) == false) {
450
+            return false;
451
+        }
452
+
453
+        foreach (OC::$APPSROOTS as $dir) {
454
+            if (isset($dir['writable']) && $dir['writable'] === true) {
455
+                return $dir['path'];
456
+            }
457
+        }
458
+
459
+        \OCP\Util::writeLog('core', 'No application directories are marked as writable.', ILogger::ERROR);
460
+        return null;
461
+    }
462
+
463
+
464
+    /**
465
+     * search for an app in all app-directories
466
+     *
467
+     * @param string $appId
468
+     * @return false|string
469
+     */
470
+    public static function findAppInDirectories(string $appId) {
471
+        $sanitizedAppId = self::cleanAppId($appId);
472
+        if ($sanitizedAppId !== $appId) {
473
+            return false;
474
+        }
475
+        static $app_dir = [];
476
+
477
+        if (isset($app_dir[$appId])) {
478
+            return $app_dir[$appId];
479
+        }
480
+
481
+        $possibleApps = [];
482
+        foreach (OC::$APPSROOTS as $dir) {
483
+            if (file_exists($dir['path'] . '/' . $appId)) {
484
+                $possibleApps[] = $dir;
485
+            }
486
+        }
487
+
488
+        if (empty($possibleApps)) {
489
+            return false;
490
+        } elseif (count($possibleApps) === 1) {
491
+            $dir = array_shift($possibleApps);
492
+            $app_dir[$appId] = $dir;
493
+            return $dir;
494
+        } else {
495
+            $versionToLoad = [];
496
+            foreach ($possibleApps as $possibleApp) {
497
+                $version = self::getAppVersionByPath($possibleApp['path'] . '/' . $appId);
498
+                if (empty($versionToLoad) || version_compare($version, $versionToLoad['version'], '>')) {
499
+                    $versionToLoad = [
500
+                        'dir' => $possibleApp,
501
+                        'version' => $version,
502
+                    ];
503
+                }
504
+            }
505
+            $app_dir[$appId] = $versionToLoad['dir'];
506
+            return $versionToLoad['dir'];
507
+            //TODO - write test
508
+        }
509
+    }
510
+
511
+    /**
512
+     * Get the directory for the given app.
513
+     * If the app is defined in multiple directories, the first one is taken. (false if not found)
514
+     *
515
+     * @param string $appId
516
+     * @return string|false
517
+     * @deprecated 11.0.0 use \OC::$server->getAppManager()->getAppPath()
518
+     */
519
+    public static function getAppPath(string $appId) {
520
+        if ($appId === null || trim($appId) === '') {
521
+            return false;
522
+        }
523
+
524
+        if (($dir = self::findAppInDirectories($appId)) != false) {
525
+            return $dir['path'] . '/' . $appId;
526
+        }
527
+        return false;
528
+    }
529
+
530
+    /**
531
+     * Get the path for the given app on the access
532
+     * If the app is defined in multiple directories, the first one is taken. (false if not found)
533
+     *
534
+     * @param string $appId
535
+     * @return string|false
536
+     * @deprecated 18.0.0 use \OC::$server->getAppManager()->getAppWebPath()
537
+     */
538
+    public static function getAppWebPath(string $appId) {
539
+        if (($dir = self::findAppInDirectories($appId)) != false) {
540
+            return OC::$WEBROOT . $dir['url'] . '/' . $appId;
541
+        }
542
+        return false;
543
+    }
544
+
545
+    /**
546
+     * get the last version of the app from appinfo/info.xml
547
+     *
548
+     * @param string $appId
549
+     * @param bool $useCache
550
+     * @return string
551
+     * @deprecated 14.0.0 use \OC::$server->getAppManager()->getAppVersion()
552
+     */
553
+    public static function getAppVersion(string $appId, bool $useCache = true): string {
554
+        return \OC::$server->getAppManager()->getAppVersion($appId, $useCache);
555
+    }
556
+
557
+    /**
558
+     * get app's version based on it's path
559
+     *
560
+     * @param string $path
561
+     * @return string
562
+     */
563
+    public static function getAppVersionByPath(string $path): string {
564
+        $infoFile = $path . '/appinfo/info.xml';
565
+        $appData = \OC::$server->getAppManager()->getAppInfo($infoFile, true);
566
+        return isset($appData['version']) ? $appData['version'] : '';
567
+    }
568
+
569
+
570
+    /**
571
+     * Read all app metadata from the info.xml file
572
+     *
573
+     * @param string $appId id of the app or the path of the info.xml file
574
+     * @param bool $path
575
+     * @param string $lang
576
+     * @return array|null
577
+     * @note all data is read from info.xml, not just pre-defined fields
578
+     * @deprecated 14.0.0 use \OC::$server->getAppManager()->getAppInfo()
579
+     */
580
+    public static function getAppInfo(string $appId, bool $path = false, string $lang = null) {
581
+        return \OC::$server->getAppManager()->getAppInfo($appId, $path, $lang);
582
+    }
583
+
584
+    /**
585
+     * Returns the navigation
586
+     *
587
+     * @return array
588
+     * @deprecated 14.0.0 use \OC::$server->getNavigationManager()->getAll()
589
+     *
590
+     * This function returns an array containing all entries added. The
591
+     * entries are sorted by the key 'order' ascending. Additional to the keys
592
+     * given for each app the following keys exist:
593
+     *   - active: boolean, signals if the user is on this navigation entry
594
+     */
595
+    public static function getNavigation(): array {
596
+        return OC::$server->getNavigationManager()->getAll();
597
+    }
598
+
599
+    /**
600
+     * Returns the Settings Navigation
601
+     *
602
+     * @return string[]
603
+     * @deprecated 14.0.0 use \OC::$server->getNavigationManager()->getAll('settings')
604
+     *
605
+     * This function returns an array containing all settings pages added. The
606
+     * entries are sorted by the key 'order' ascending.
607
+     */
608
+    public static function getSettingsNavigation(): array {
609
+        return OC::$server->getNavigationManager()->getAll('settings');
610
+    }
611
+
612
+    /**
613
+     * get the id of loaded app
614
+     *
615
+     * @return string
616
+     */
617
+    public static function getCurrentApp(): string {
618
+        $request = \OC::$server->getRequest();
619
+        $script = substr($request->getScriptName(), strlen(OC::$WEBROOT) + 1);
620
+        $topFolder = substr($script, 0, strpos($script, '/') ?: 0);
621
+        if (empty($topFolder)) {
622
+            $path_info = $request->getPathInfo();
623
+            if ($path_info) {
624
+                $topFolder = substr($path_info, 1, strpos($path_info, '/', 1) - 1);
625
+            }
626
+        }
627
+        if ($topFolder == 'apps') {
628
+            $length = strlen($topFolder);
629
+            return substr($script, $length + 1, strpos($script, '/', $length + 1) - $length - 1) ?: '';
630
+        } else {
631
+            return $topFolder;
632
+        }
633
+    }
634
+
635
+    /**
636
+     * @param string $type
637
+     * @return array
638
+     */
639
+    public static function getForms(string $type): array {
640
+        $forms = [];
641
+        switch ($type) {
642
+            case 'admin':
643
+                $source = self::$adminForms;
644
+                break;
645
+            case 'personal':
646
+                $source = self::$personalForms;
647
+                break;
648
+            default:
649
+                return [];
650
+        }
651
+        foreach ($source as $form) {
652
+            $forms[] = include $form;
653
+        }
654
+        return $forms;
655
+    }
656
+
657
+    /**
658
+     * register an admin form to be shown
659
+     *
660
+     * @param string $app
661
+     * @param string $page
662
+     */
663
+    public static function registerAdmin(string $app, string $page) {
664
+        self::$adminForms[] = $app . '/' . $page . '.php';
665
+    }
666
+
667
+    /**
668
+     * register a personal form to be shown
669
+     * @param string $app
670
+     * @param string $page
671
+     */
672
+    public static function registerPersonal(string $app, string $page) {
673
+        self::$personalForms[] = $app . '/' . $page . '.php';
674
+    }
675
+
676
+    /**
677
+     * @param array $entry
678
+     * @deprecated 20.0.0 Please register your alternative login option using the registerAlternativeLogin() on the RegistrationContext in your Application class implementing the OCP\Authentication\IAlternativeLogin interface
679
+     */
680
+    public static function registerLogIn(array $entry) {
681
+        \OC::$server->getLogger()->debug('OC_App::registerLogIn() is deprecated, please register your alternative login option using the registerAlternativeLogin() on the RegistrationContext in your Application class implementing the OCP\Authentication\IAlternativeLogin interface');
682
+        self::$altLogin[] = $entry;
683
+    }
684
+
685
+    /**
686
+     * @return array
687
+     */
688
+    public static function getAlternativeLogIns(): array {
689
+        /** @var Coordinator $bootstrapCoordinator */
690
+        $bootstrapCoordinator = \OC::$server->query(Coordinator::class);
691
+
692
+        foreach ($bootstrapCoordinator->getRegistrationContext()->getAlternativeLogins() as $registration) {
693
+            if (!in_array(IAlternativeLogin::class, class_implements($registration['class']), true)) {
694
+                \OC::$server->getLogger()->error('Alternative login option {option} does not implement {interface} and is therefore ignored.', [
695
+                    'option' => $registration['class'],
696
+                    'interface' => IAlternativeLogin::class,
697
+                    'app' => $registration['app'],
698
+                ]);
699
+                continue;
700
+            }
701
+
702
+            try {
703
+                /** @var IAlternativeLogin $provider */
704
+                $provider = \OC::$server->query($registration['class']);
705
+            } catch (QueryException $e) {
706
+                \OC::$server->getLogger()->logException($e, [
707
+                    'message' => 'Alternative login option {option} can not be initialised.',
708
+                    'option' => $registration['class'],
709
+                    'app' => $registration['app'],
710
+                ]);
711
+            }
712
+
713
+            try {
714
+                $provider->load();
715
+
716
+                self::$altLogin[] = [
717
+                    'name' => $provider->getLabel(),
718
+                    'href' => $provider->getLink(),
719
+                    'style' => $provider->getClass(),
720
+                ];
721
+            } catch (Throwable $e) {
722
+                \OC::$server->getLogger()->logException($e, [
723
+                    'message' => 'Alternative login option {option} had an error while loading.',
724
+                    'option' => $registration['class'],
725
+                    'app' => $registration['app'],
726
+                ]);
727
+            }
728
+        }
729
+
730
+        return self::$altLogin;
731
+    }
732
+
733
+    /**
734
+     * get a list of all apps in the apps folder
735
+     *
736
+     * @return string[] an array of app names (string IDs)
737
+     * @todo: change the name of this method to getInstalledApps, which is more accurate
738
+     */
739
+    public static function getAllApps(): array {
740
+        $apps = [];
741
+
742
+        foreach (OC::$APPSROOTS as $apps_dir) {
743
+            if (!is_readable($apps_dir['path'])) {
744
+                \OCP\Util::writeLog('core', 'unable to read app folder : ' . $apps_dir['path'], ILogger::WARN);
745
+                continue;
746
+            }
747
+            $dh = opendir($apps_dir['path']);
748
+
749
+            if (is_resource($dh)) {
750
+                while (($file = readdir($dh)) !== false) {
751
+                    if ($file[0] != '.' and is_dir($apps_dir['path'] . '/' . $file) and is_file($apps_dir['path'] . '/' . $file . '/appinfo/info.xml')) {
752
+                        $apps[] = $file;
753
+                    }
754
+                }
755
+            }
756
+        }
757
+
758
+        $apps = array_unique($apps);
759
+
760
+        return $apps;
761
+    }
762
+
763
+    /**
764
+     * List all apps, this is used in apps.php
765
+     *
766
+     * @return array
767
+     */
768
+    public function listAllApps(): array {
769
+        $installedApps = OC_App::getAllApps();
770
+
771
+        $appManager = \OC::$server->getAppManager();
772
+        //we don't want to show configuration for these
773
+        $blacklist = $appManager->getAlwaysEnabledApps();
774
+        $appList = [];
775
+        $langCode = \OC::$server->getL10N('core')->getLanguageCode();
776
+        $urlGenerator = \OC::$server->getURLGenerator();
777
+        /** @var \OCP\Support\Subscription\IRegistry $subscriptionRegistry */
778
+        $subscriptionRegistry = \OC::$server->query(\OCP\Support\Subscription\IRegistry::class);
779
+        $supportedApps = $subscriptionRegistry->delegateGetSupportedApps();
780
+
781
+        foreach ($installedApps as $app) {
782
+            if (array_search($app, $blacklist) === false) {
783
+                $info = OC_App::getAppInfo($app, false, $langCode);
784
+                if (!is_array($info)) {
785
+                    \OCP\Util::writeLog('core', 'Could not read app info file for app "' . $app . '"', ILogger::ERROR);
786
+                    continue;
787
+                }
788
+
789
+                if (!isset($info['name'])) {
790
+                    \OCP\Util::writeLog('core', 'App id "' . $app . '" has no name in appinfo', ILogger::ERROR);
791
+                    continue;
792
+                }
793
+
794
+                $enabled = \OC::$server->getConfig()->getAppValue($app, 'enabled', 'no');
795
+                $info['groups'] = null;
796
+                if ($enabled === 'yes') {
797
+                    $active = true;
798
+                } elseif ($enabled === 'no') {
799
+                    $active = false;
800
+                } else {
801
+                    $active = true;
802
+                    $info['groups'] = $enabled;
803
+                }
804
+
805
+                $info['active'] = $active;
806
+
807
+                if ($appManager->isShipped($app)) {
808
+                    $info['internal'] = true;
809
+                    $info['level'] = self::officialApp;
810
+                    $info['removable'] = false;
811
+                } else {
812
+                    $info['internal'] = false;
813
+                    $info['removable'] = true;
814
+                }
815
+
816
+                if (in_array($app, $supportedApps)) {
817
+                    $info['level'] = self::supportedApp;
818
+                }
819
+
820
+                $appPath = self::getAppPath($app);
821
+                if ($appPath !== false) {
822
+                    $appIcon = $appPath . '/img/' . $app . '.svg';
823
+                    if (file_exists($appIcon)) {
824
+                        $info['preview'] = $urlGenerator->imagePath($app, $app . '.svg');
825
+                        $info['previewAsIcon'] = true;
826
+                    } else {
827
+                        $appIcon = $appPath . '/img/app.svg';
828
+                        if (file_exists($appIcon)) {
829
+                            $info['preview'] = $urlGenerator->imagePath($app, 'app.svg');
830
+                            $info['previewAsIcon'] = true;
831
+                        }
832
+                    }
833
+                }
834
+                // fix documentation
835
+                if (isset($info['documentation']) && is_array($info['documentation'])) {
836
+                    foreach ($info['documentation'] as $key => $url) {
837
+                        // If it is not an absolute URL we assume it is a key
838
+                        // i.e. admin-ldap will get converted to go.php?to=admin-ldap
839
+                        if (stripos($url, 'https://') !== 0 && stripos($url, 'http://') !== 0) {
840
+                            $url = $urlGenerator->linkToDocs($url);
841
+                        }
842
+
843
+                        $info['documentation'][$key] = $url;
844
+                    }
845
+                }
846
+
847
+                $info['version'] = OC_App::getAppVersion($app);
848
+                $appList[] = $info;
849
+            }
850
+        }
851
+
852
+        return $appList;
853
+    }
854
+
855
+    public static function shouldUpgrade(string $app): bool {
856
+        $versions = self::getAppVersions();
857
+        $currentVersion = OC_App::getAppVersion($app);
858
+        if ($currentVersion && isset($versions[$app])) {
859
+            $installedVersion = $versions[$app];
860
+            if (!version_compare($currentVersion, $installedVersion, '=')) {
861
+                return true;
862
+            }
863
+        }
864
+        return false;
865
+    }
866
+
867
+    /**
868
+     * Adjust the number of version parts of $version1 to match
869
+     * the number of version parts of $version2.
870
+     *
871
+     * @param string $version1 version to adjust
872
+     * @param string $version2 version to take the number of parts from
873
+     * @return string shortened $version1
874
+     */
875
+    private static function adjustVersionParts(string $version1, string $version2): string {
876
+        $version1 = explode('.', $version1);
877
+        $version2 = explode('.', $version2);
878
+        // reduce $version1 to match the number of parts in $version2
879
+        while (count($version1) > count($version2)) {
880
+            array_pop($version1);
881
+        }
882
+        // if $version1 does not have enough parts, add some
883
+        while (count($version1) < count($version2)) {
884
+            $version1[] = '0';
885
+        }
886
+        return implode('.', $version1);
887
+    }
888
+
889
+    /**
890
+     * Check whether the current ownCloud version matches the given
891
+     * application's version requirements.
892
+     *
893
+     * The comparison is made based on the number of parts that the
894
+     * app info version has. For example for ownCloud 6.0.3 if the
895
+     * app info version is expecting version 6.0, the comparison is
896
+     * made on the first two parts of the ownCloud version.
897
+     * This means that it's possible to specify "requiremin" => 6
898
+     * and "requiremax" => 6 and it will still match ownCloud 6.0.3.
899
+     *
900
+     * @param string $ocVersion ownCloud version to check against
901
+     * @param array $appInfo app info (from xml)
902
+     *
903
+     * @return boolean true if compatible, otherwise false
904
+     */
905
+    public static function isAppCompatible(string $ocVersion, array $appInfo, bool $ignoreMax = false): bool {
906
+        $requireMin = '';
907
+        $requireMax = '';
908
+        if (isset($appInfo['dependencies']['nextcloud']['@attributes']['min-version'])) {
909
+            $requireMin = $appInfo['dependencies']['nextcloud']['@attributes']['min-version'];
910
+        } elseif (isset($appInfo['dependencies']['owncloud']['@attributes']['min-version'])) {
911
+            $requireMin = $appInfo['dependencies']['owncloud']['@attributes']['min-version'];
912
+        } elseif (isset($appInfo['requiremin'])) {
913
+            $requireMin = $appInfo['requiremin'];
914
+        } elseif (isset($appInfo['require'])) {
915
+            $requireMin = $appInfo['require'];
916
+        }
917
+
918
+        if (isset($appInfo['dependencies']['nextcloud']['@attributes']['max-version'])) {
919
+            $requireMax = $appInfo['dependencies']['nextcloud']['@attributes']['max-version'];
920
+        } elseif (isset($appInfo['dependencies']['owncloud']['@attributes']['max-version'])) {
921
+            $requireMax = $appInfo['dependencies']['owncloud']['@attributes']['max-version'];
922
+        } elseif (isset($appInfo['requiremax'])) {
923
+            $requireMax = $appInfo['requiremax'];
924
+        }
925
+
926
+        if (!empty($requireMin)
927
+            && version_compare(self::adjustVersionParts($ocVersion, $requireMin), $requireMin, '<')
928
+        ) {
929
+            return false;
930
+        }
931
+
932
+        if (!$ignoreMax && !empty($requireMax)
933
+            && version_compare(self::adjustVersionParts($ocVersion, $requireMax), $requireMax, '>')
934
+        ) {
935
+            return false;
936
+        }
937
+
938
+        return true;
939
+    }
940
+
941
+    /**
942
+     * get the installed version of all apps
943
+     */
944
+    public static function getAppVersions() {
945
+        static $versions;
946
+
947
+        if (!$versions) {
948
+            $appConfig = \OC::$server->getAppConfig();
949
+            $versions = $appConfig->getValues(false, 'installed_version');
950
+        }
951
+        return $versions;
952
+    }
953
+
954
+    /**
955
+     * update the database for the app and call the update script
956
+     *
957
+     * @param string $appId
958
+     * @return bool
959
+     */
960
+    public static function updateApp(string $appId): bool {
961
+        $appPath = self::getAppPath($appId);
962
+        if ($appPath === false) {
963
+            return false;
964
+        }
965
+
966
+        \OC::$server->getAppManager()->clearAppsCache();
967
+        $appData = self::getAppInfo($appId);
968
+
969
+        self::registerAutoloading($appId, $appPath, true);
970
+        self::executeRepairSteps($appId, $appData['repair-steps']['pre-migration']);
971
+
972
+        if (file_exists($appPath . '/appinfo/database.xml')) {
973
+            OC_DB::updateDbFromStructure($appPath . '/appinfo/database.xml');
974
+        } else {
975
+            $ms = new MigrationService($appId, \OC::$server->getDatabaseConnection());
976
+            $ms->migrate();
977
+        }
978
+
979
+        self::executeRepairSteps($appId, $appData['repair-steps']['post-migration']);
980
+        self::setupLiveMigrations($appId, $appData['repair-steps']['live-migration']);
981
+        // update appversion in app manager
982
+        \OC::$server->getAppManager()->clearAppsCache();
983
+        \OC::$server->getAppManager()->getAppVersion($appId, false);
984
+
985
+        // run upgrade code
986
+        if (file_exists($appPath . '/appinfo/update.php')) {
987
+            self::loadApp($appId);
988
+            include $appPath . '/appinfo/update.php';
989
+        }
990
+        self::setupBackgroundJobs($appData['background-jobs']);
991
+
992
+        //set remote/public handlers
993
+        if (array_key_exists('ocsid', $appData)) {
994
+            \OC::$server->getConfig()->setAppValue($appId, 'ocsid', $appData['ocsid']);
995
+        } elseif (\OC::$server->getConfig()->getAppValue($appId, 'ocsid', null) !== null) {
996
+            \OC::$server->getConfig()->deleteAppValue($appId, 'ocsid');
997
+        }
998
+        foreach ($appData['remote'] as $name => $path) {
999
+            \OC::$server->getConfig()->setAppValue('core', 'remote_' . $name, $appId . '/' . $path);
1000
+        }
1001
+        foreach ($appData['public'] as $name => $path) {
1002
+            \OC::$server->getConfig()->setAppValue('core', 'public_' . $name, $appId . '/' . $path);
1003
+        }
1004
+
1005
+        self::setAppTypes($appId);
1006
+
1007
+        $version = \OC_App::getAppVersion($appId);
1008
+        \OC::$server->getConfig()->setAppValue($appId, 'installed_version', $version);
1009
+
1010
+        \OC::$server->getEventDispatcher()->dispatch(ManagerEvent::EVENT_APP_UPDATE, new ManagerEvent(
1011
+            ManagerEvent::EVENT_APP_UPDATE, $appId
1012
+        ));
1013
+
1014
+        return true;
1015
+    }
1016
+
1017
+    /**
1018
+     * @param string $appId
1019
+     * @param string[] $steps
1020
+     * @throws \OC\NeedsUpdateException
1021
+     */
1022
+    public static function executeRepairSteps(string $appId, array $steps) {
1023
+        if (empty($steps)) {
1024
+            return;
1025
+        }
1026
+        // load the app
1027
+        self::loadApp($appId);
1028
+
1029
+        $dispatcher = OC::$server->getEventDispatcher();
1030
+
1031
+        // load the steps
1032
+        $r = new Repair([], $dispatcher);
1033
+        foreach ($steps as $step) {
1034
+            try {
1035
+                $r->addStep($step);
1036
+            } catch (Exception $ex) {
1037
+                $r->emit('\OC\Repair', 'error', [$ex->getMessage()]);
1038
+                \OC::$server->getLogger()->logException($ex);
1039
+            }
1040
+        }
1041
+        // run the steps
1042
+        $r->run();
1043
+    }
1044
+
1045
+    public static function setupBackgroundJobs(array $jobs) {
1046
+        $queue = \OC::$server->getJobList();
1047
+        foreach ($jobs as $job) {
1048
+            $queue->add($job);
1049
+        }
1050
+    }
1051
+
1052
+    /**
1053
+     * @param string $appId
1054
+     * @param string[] $steps
1055
+     */
1056
+    private static function setupLiveMigrations(string $appId, array $steps) {
1057
+        $queue = \OC::$server->getJobList();
1058
+        foreach ($steps as $step) {
1059
+            $queue->add('OC\Migration\BackgroundRepair', [
1060
+                'app' => $appId,
1061
+                'step' => $step]);
1062
+        }
1063
+    }
1064
+
1065
+    /**
1066
+     * @param string $appId
1067
+     * @return \OC\Files\View|false
1068
+     */
1069
+    public static function getStorage(string $appId) {
1070
+        if (\OC::$server->getAppManager()->isEnabledForUser($appId)) { //sanity check
1071
+            if (\OC::$server->getUserSession()->isLoggedIn()) {
1072
+                $view = new \OC\Files\View('/' . OC_User::getUser());
1073
+                if (!$view->file_exists($appId)) {
1074
+                    $view->mkdir($appId);
1075
+                }
1076
+                return new \OC\Files\View('/' . OC_User::getUser() . '/' . $appId);
1077
+            } else {
1078
+                \OCP\Util::writeLog('core', 'Can\'t get app storage, app ' . $appId . ', user not logged in', ILogger::ERROR);
1079
+                return false;
1080
+            }
1081
+        } else {
1082
+            \OCP\Util::writeLog('core', 'Can\'t get app storage, app ' . $appId . ' not enabled', ILogger::ERROR);
1083
+            return false;
1084
+        }
1085
+    }
1086
+
1087
+    protected static function findBestL10NOption(array $options, string $lang): string {
1088
+        // only a single option
1089
+        if (isset($options['@value'])) {
1090
+            return $options['@value'];
1091
+        }
1092
+
1093
+        $fallback = $similarLangFallback = $englishFallback = false;
1094
+
1095
+        $lang = strtolower($lang);
1096
+        $similarLang = $lang;
1097
+        if (strpos($similarLang, '_')) {
1098
+            // For "de_DE" we want to find "de" and the other way around
1099
+            $similarLang = substr($lang, 0, strpos($lang, '_'));
1100
+        }
1101
+
1102
+        foreach ($options as $option) {
1103
+            if (is_array($option)) {
1104
+                if ($fallback === false) {
1105
+                    $fallback = $option['@value'];
1106
+                }
1107
+
1108
+                if (!isset($option['@attributes']['lang'])) {
1109
+                    continue;
1110
+                }
1111
+
1112
+                $attributeLang = strtolower($option['@attributes']['lang']);
1113
+                if ($attributeLang === $lang) {
1114
+                    return $option['@value'];
1115
+                }
1116
+
1117
+                if ($attributeLang === $similarLang) {
1118
+                    $similarLangFallback = $option['@value'];
1119
+                } elseif (strpos($attributeLang, $similarLang . '_') === 0) {
1120
+                    if ($similarLangFallback === false) {
1121
+                        $similarLangFallback = $option['@value'];
1122
+                    }
1123
+                }
1124
+            } else {
1125
+                $englishFallback = $option;
1126
+            }
1127
+        }
1128
+
1129
+        if ($similarLangFallback !== false) {
1130
+            return $similarLangFallback;
1131
+        } elseif ($englishFallback !== false) {
1132
+            return $englishFallback;
1133
+        }
1134
+        return (string) $fallback;
1135
+    }
1136
+
1137
+    /**
1138
+     * parses the app data array and enhanced the 'description' value
1139
+     *
1140
+     * @param array $data the app data
1141
+     * @param string $lang
1142
+     * @return array improved app data
1143
+     */
1144
+    public static function parseAppInfo(array $data, $lang = null): array {
1145
+        if ($lang && isset($data['name']) && is_array($data['name'])) {
1146
+            $data['name'] = self::findBestL10NOption($data['name'], $lang);
1147
+        }
1148
+        if ($lang && isset($data['summary']) && is_array($data['summary'])) {
1149
+            $data['summary'] = self::findBestL10NOption($data['summary'], $lang);
1150
+        }
1151
+        if ($lang && isset($data['description']) && is_array($data['description'])) {
1152
+            $data['description'] = trim(self::findBestL10NOption($data['description'], $lang));
1153
+        } elseif (isset($data['description']) && is_string($data['description'])) {
1154
+            $data['description'] = trim($data['description']);
1155
+        } else {
1156
+            $data['description'] = '';
1157
+        }
1158
+
1159
+        return $data;
1160
+    }
1161
+
1162
+    /**
1163
+     * @param \OCP\IConfig $config
1164
+     * @param \OCP\IL10N $l
1165
+     * @param array $info
1166
+     * @throws \Exception
1167
+     */
1168
+    public static function checkAppDependencies(\OCP\IConfig $config, \OCP\IL10N $l, array $info, bool $ignoreMax) {
1169
+        $dependencyAnalyzer = new DependencyAnalyzer(new Platform($config), $l);
1170
+        $missing = $dependencyAnalyzer->analyze($info, $ignoreMax);
1171
+        if (!empty($missing)) {
1172
+            $missingMsg = implode(PHP_EOL, $missing);
1173
+            throw new \Exception(
1174
+                $l->t('App "%1$s" cannot be installed because the following dependencies are not fulfilled: %2$s',
1175
+                    [$info['name'], $missingMsg]
1176
+                )
1177
+            );
1178
+        }
1179
+    }
1180 1180
 }
Please login to merge, or discard this patch.