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