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