Completed
Pull Request — master (#4454)
by Lukas
15:45
created
lib/private/App/AppStore/Bundles/CoreBundle.php 2 patches
Indentation   +20 added lines, -20 removed lines patch added patch discarded remove patch
@@ -23,27 +23,27 @@
 block discarded – undo
23 23
 
24 24
 class CoreBundle extends Bundle {
25 25
 
26
-	/**
27
-	 * {@inheritDoc}
28
-	 */
29
-	public function getName() {
30
-		return (string)$this->l10n->t('Core bundle');
31
-	}
26
+    /**
27
+     * {@inheritDoc}
28
+     */
29
+    public function getName() {
30
+        return (string)$this->l10n->t('Core bundle');
31
+    }
32 32
 
33
-	/**
34
-	 * {@inheritDoc}
35
-	 */
36
-	public function getDescription() {
37
-		return (string)$this->l10n->t('Default apps required by Nextcloud');
38
-	}
33
+    /**
34
+     * {@inheritDoc}
35
+     */
36
+    public function getDescription() {
37
+        return (string)$this->l10n->t('Default apps required by Nextcloud');
38
+    }
39 39
 
40
-	/**
41
-	 * {@inheritDoc}
42
-	 */
43
-	public function getAppIdentifiers() {
44
-		return [
45
-			'bruteforcesettings',
46
-		];
47
-	}
40
+    /**
41
+     * {@inheritDoc}
42
+     */
43
+    public function getAppIdentifiers() {
44
+        return [
45
+            'bruteforcesettings',
46
+        ];
47
+    }
48 48
 
49 49
 }
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -27,14 +27,14 @@
 block discarded – undo
27 27
 	 * {@inheritDoc}
28 28
 	 */
29 29
 	public function getName() {
30
-		return (string)$this->l10n->t('Core bundle');
30
+		return (string) $this->l10n->t('Core bundle');
31 31
 	}
32 32
 
33 33
 	/**
34 34
 	 * {@inheritDoc}
35 35
 	 */
36 36
 	public function getDescription() {
37
-		return (string)$this->l10n->t('Default apps required by Nextcloud');
37
+		return (string) $this->l10n->t('Default apps required by Nextcloud');
38 38
 	}
39 39
 
40 40
 	/**
Please login to merge, or discard this patch.
lib/private/App/AppStore/Bundles/Bundle.php 1 patch
Indentation   +34 added lines, -34 removed lines patch added patch discarded remove patch
@@ -24,43 +24,43 @@
 block discarded – undo
24 24
 use OCP\IL10N;
25 25
 
26 26
 abstract class Bundle {
27
-	/** @var IL10N */
28
-	protected $l10n;
27
+    /** @var IL10N */
28
+    protected $l10n;
29 29
 
30
-	/**
31
-	 * @param IL10N $l10n
32
-	 */
33
-	public function __construct(IL10N $l10n) {
34
-		$this->l10n = $l10n;
35
-	}
30
+    /**
31
+     * @param IL10N $l10n
32
+     */
33
+    public function __construct(IL10N $l10n) {
34
+        $this->l10n = $l10n;
35
+    }
36 36
 
37
-	/**
38
-	 * Get the identifier of the bundle
39
-	 *
40
-	 * @return string
41
-	 */
42
-	public final function getIdentifier() {
43
-		return substr(strrchr(get_class($this), '\\'), 1);
44
-	}
37
+    /**
38
+     * Get the identifier of the bundle
39
+     *
40
+     * @return string
41
+     */
42
+    public final function getIdentifier() {
43
+        return substr(strrchr(get_class($this), '\\'), 1);
44
+    }
45 45
 
46
-	/**
47
-	 * Get the name of the bundle
48
-	 *
49
-	 * @return string
50
-	 */
51
-	public abstract function getName();
46
+    /**
47
+     * Get the name of the bundle
48
+     *
49
+     * @return string
50
+     */
51
+    public abstract function getName();
52 52
 
53
-	/**
54
-	 * Get the description of the bundle
55
-	 *
56
-	 * @return string
57
-	 */
58
-	public abstract function getDescription();
53
+    /**
54
+     * Get the description of the bundle
55
+     *
56
+     * @return string
57
+     */
58
+    public abstract function getDescription();
59 59
 
60
-	/**
61
-	 * Get the list of app identifiers in the bundle
62
-	 *
63
-	 * @return array
64
-	 */
65
-	public abstract function getAppIdentifiers();
60
+    /**
61
+     * Get the list of app identifiers in the bundle
62
+     *
63
+     * @return array
64
+     */
65
+    public abstract function getAppIdentifiers();
66 66
 }
Please login to merge, or discard this patch.
lib/private/Setup.php 2 patches
Indentation   +480 added lines, -480 removed lines patch added patch discarded remove patch
@@ -48,484 +48,484 @@
 block discarded – undo
48 48
 use OCP\Security\ISecureRandom;
49 49
 
50 50
 class Setup {
51
-	/** @var SystemConfig */
52
-	protected $config;
53
-	/** @var IniGetWrapper */
54
-	protected $iniWrapper;
55
-	/** @var IL10N */
56
-	protected $l10n;
57
-	/** @var Defaults */
58
-	protected $defaults;
59
-	/** @var ILogger */
60
-	protected $logger;
61
-	/** @var ISecureRandom */
62
-	protected $random;
63
-
64
-	/**
65
-	 * @param SystemConfig $config
66
-	 * @param IniGetWrapper $iniWrapper
67
-	 * @param IL10N $l10n
68
-	 * @param Defaults $defaults
69
-	 * @param ILogger $logger
70
-	 * @param ISecureRandom $random
71
-	 */
72
-	public function __construct(SystemConfig $config,
73
-						 IniGetWrapper $iniWrapper,
74
-						 IL10N $l10n,
75
-						 Defaults $defaults,
76
-						 ILogger $logger,
77
-						 ISecureRandom $random
78
-		) {
79
-		$this->config = $config;
80
-		$this->iniWrapper = $iniWrapper;
81
-		$this->l10n = $l10n;
82
-		$this->defaults = $defaults;
83
-		$this->logger = $logger;
84
-		$this->random = $random;
85
-	}
86
-
87
-	static $dbSetupClasses = [
88
-		'mysql' => \OC\Setup\MySQL::class,
89
-		'pgsql' => \OC\Setup\PostgreSQL::class,
90
-		'oci'   => \OC\Setup\OCI::class,
91
-		'sqlite' => \OC\Setup\Sqlite::class,
92
-		'sqlite3' => \OC\Setup\Sqlite::class,
93
-	];
94
-
95
-	/**
96
-	 * Wrapper around the "class_exists" PHP function to be able to mock it
97
-	 * @param string $name
98
-	 * @return bool
99
-	 */
100
-	protected function class_exists($name) {
101
-		return class_exists($name);
102
-	}
103
-
104
-	/**
105
-	 * Wrapper around the "is_callable" PHP function to be able to mock it
106
-	 * @param string $name
107
-	 * @return bool
108
-	 */
109
-	protected function is_callable($name) {
110
-		return is_callable($name);
111
-	}
112
-
113
-	/**
114
-	 * Wrapper around \PDO::getAvailableDrivers
115
-	 *
116
-	 * @return array
117
-	 */
118
-	protected function getAvailableDbDriversForPdo() {
119
-		return \PDO::getAvailableDrivers();
120
-	}
121
-
122
-	/**
123
-	 * Get the available and supported databases of this instance
124
-	 *
125
-	 * @param bool $allowAllDatabases
126
-	 * @return array
127
-	 * @throws Exception
128
-	 */
129
-	public function getSupportedDatabases($allowAllDatabases = false) {
130
-		$availableDatabases = array(
131
-			'sqlite' =>  array(
132
-				'type' => 'pdo',
133
-				'call' => 'sqlite',
134
-				'name' => 'SQLite'
135
-			),
136
-			'mysql' => array(
137
-				'type' => 'pdo',
138
-				'call' => 'mysql',
139
-				'name' => 'MySQL/MariaDB'
140
-			),
141
-			'pgsql' => array(
142
-				'type' => 'pdo',
143
-				'call' => 'pgsql',
144
-				'name' => 'PostgreSQL'
145
-			),
146
-			'oci' => array(
147
-				'type' => 'function',
148
-				'call' => 'oci_connect',
149
-				'name' => 'Oracle'
150
-			)
151
-		);
152
-		if ($allowAllDatabases) {
153
-			$configuredDatabases = array_keys($availableDatabases);
154
-		} else {
155
-			$configuredDatabases = $this->config->getValue('supportedDatabases',
156
-				array('sqlite', 'mysql', 'pgsql'));
157
-		}
158
-		if(!is_array($configuredDatabases)) {
159
-			throw new Exception('Supported databases are not properly configured.');
160
-		}
161
-
162
-		$supportedDatabases = array();
163
-
164
-		foreach($configuredDatabases as $database) {
165
-			if(array_key_exists($database, $availableDatabases)) {
166
-				$working = false;
167
-				$type = $availableDatabases[$database]['type'];
168
-				$call = $availableDatabases[$database]['call'];
169
-
170
-				if ($type === 'function') {
171
-					$working = $this->is_callable($call);
172
-				} elseif($type === 'pdo') {
173
-					$working = in_array($call, $this->getAvailableDbDriversForPdo(), TRUE);
174
-				}
175
-				if($working) {
176
-					$supportedDatabases[$database] = $availableDatabases[$database]['name'];
177
-				}
178
-			}
179
-		}
180
-
181
-		return $supportedDatabases;
182
-	}
183
-
184
-	/**
185
-	 * Gathers system information like database type and does
186
-	 * a few system checks.
187
-	 *
188
-	 * @return array of system info, including an "errors" value
189
-	 * in case of errors/warnings
190
-	 */
191
-	public function getSystemInfo($allowAllDatabases = false) {
192
-		$databases = $this->getSupportedDatabases($allowAllDatabases);
193
-
194
-		$dataDir = $this->config->getValue('datadirectory', \OC::$SERVERROOT.'/data');
195
-
196
-		$errors = array();
197
-
198
-		// Create data directory to test whether the .htaccess works
199
-		// Notice that this is not necessarily the same data directory as the one
200
-		// that will effectively be used.
201
-		if(!file_exists($dataDir)) {
202
-			@mkdir($dataDir);
203
-		}
204
-		$htAccessWorking = true;
205
-		if (is_dir($dataDir) && is_writable($dataDir)) {
206
-			// Protect data directory here, so we can test if the protection is working
207
-			\OC\Setup::protectDataDirectory();
208
-
209
-			try {
210
-				$util = new \OC_Util();
211
-				$htAccessWorking = $util->isHtaccessWorking(\OC::$server->getConfig());
212
-			} catch (\OC\HintException $e) {
213
-				$errors[] = array(
214
-					'error' => $e->getMessage(),
215
-					'hint' => $e->getHint()
216
-				);
217
-				$htAccessWorking = false;
218
-			}
219
-		}
220
-
221
-		if (\OC_Util::runningOnMac()) {
222
-			$errors[] = array(
223
-				'error' => $this->l10n->t(
224
-					'Mac OS X is not supported and %s will not work properly on this platform. ' .
225
-					'Use it at your own risk! ',
226
-					$this->defaults->getName()
227
-				),
228
-				'hint' => $this->l10n->t('For the best results, please consider using a GNU/Linux server instead.')
229
-			);
230
-		}
231
-
232
-		if($this->iniWrapper->getString('open_basedir') !== '' && PHP_INT_SIZE === 4) {
233
-			$errors[] = array(
234
-				'error' => $this->l10n->t(
235
-					'It seems that this %s instance is running on a 32-bit PHP environment and the open_basedir has been configured in php.ini. ' .
236
-					'This will lead to problems with files over 4 GB and is highly discouraged.',
237
-					$this->defaults->getName()
238
-				),
239
-				'hint' => $this->l10n->t('Please remove the open_basedir setting within your php.ini or switch to 64-bit PHP.')
240
-			);
241
-		}
242
-
243
-		return array(
244
-			'hasSQLite' => isset($databases['sqlite']),
245
-			'hasMySQL' => isset($databases['mysql']),
246
-			'hasPostgreSQL' => isset($databases['pgsql']),
247
-			'hasOracle' => isset($databases['oci']),
248
-			'databases' => $databases,
249
-			'directory' => $dataDir,
250
-			'htaccessWorking' => $htAccessWorking,
251
-			'errors' => $errors,
252
-		);
253
-	}
254
-
255
-	/**
256
-	 * @param $options
257
-	 * @return array
258
-	 */
259
-	public function install($options) {
260
-		$l = $this->l10n;
261
-
262
-		$error = array();
263
-		$dbType = $options['dbtype'];
264
-
265
-		if(empty($options['adminlogin'])) {
266
-			$error[] = $l->t('Set an admin username.');
267
-		}
268
-		if(empty($options['adminpass'])) {
269
-			$error[] = $l->t('Set an admin password.');
270
-		}
271
-		if(empty($options['directory'])) {
272
-			$options['directory'] = \OC::$SERVERROOT."/data";
273
-		}
274
-
275
-		if (!isset(self::$dbSetupClasses[$dbType])) {
276
-			$dbType = 'sqlite';
277
-		}
278
-
279
-		$username = htmlspecialchars_decode($options['adminlogin']);
280
-		$password = htmlspecialchars_decode($options['adminpass']);
281
-		$dataDir = htmlspecialchars_decode($options['directory']);
282
-
283
-		$class = self::$dbSetupClasses[$dbType];
284
-		/** @var \OC\Setup\AbstractDatabase $dbSetup */
285
-		$dbSetup = new $class($l, 'db_structure.xml', $this->config,
286
-			$this->logger, $this->random);
287
-		$error = array_merge($error, $dbSetup->validate($options));
288
-
289
-		// validate the data directory
290
-		if (
291
-			(!is_dir($dataDir) and !mkdir($dataDir)) or
292
-			!is_writable($dataDir)
293
-		) {
294
-			$error[] = $l->t("Can't create or write into the data directory %s", array($dataDir));
295
-		}
296
-
297
-		if(count($error) != 0) {
298
-			return $error;
299
-		}
300
-
301
-		$request = \OC::$server->getRequest();
302
-
303
-		//no errors, good
304
-		if(isset($options['trusted_domains'])
305
-		    && is_array($options['trusted_domains'])) {
306
-			$trustedDomains = $options['trusted_domains'];
307
-		} else {
308
-			$trustedDomains = [$request->getInsecureServerHost()];
309
-		}
310
-
311
-		//use sqlite3 when available, otherwise sqlite2 will be used.
312
-		if($dbType=='sqlite' and class_exists('SQLite3')) {
313
-			$dbType='sqlite3';
314
-		}
315
-
316
-		//generate a random salt that is used to salt the local user passwords
317
-		$salt = $this->random->generate(30);
318
-		// generate a secret
319
-		$secret = $this->random->generate(48);
320
-
321
-		//write the config file
322
-		$this->config->setValues([
323
-			'passwordsalt'		=> $salt,
324
-			'secret'			=> $secret,
325
-			'trusted_domains'	=> $trustedDomains,
326
-			'datadirectory'		=> $dataDir,
327
-			'overwrite.cli.url'	=> $request->getServerProtocol() . '://' . $request->getInsecureServerHost() . \OC::$WEBROOT,
328
-			'dbtype'			=> $dbType,
329
-			'version'			=> implode('.', \OCP\Util::getVersion()),
330
-		]);
331
-
332
-		try {
333
-			$dbSetup->initialize($options);
334
-			$dbSetup->setupDatabase($username);
335
-		} catch (\OC\DatabaseSetupException $e) {
336
-			$error[] = array(
337
-				'error' => $e->getMessage(),
338
-				'hint' => $e->getHint()
339
-			);
340
-			return($error);
341
-		} catch (Exception $e) {
342
-			$error[] = array(
343
-				'error' => 'Error while trying to create admin user: ' . $e->getMessage(),
344
-				'hint' => ''
345
-			);
346
-			return($error);
347
-		}
348
-
349
-		//create the user and group
350
-		$user =  null;
351
-		try {
352
-			$user = \OC::$server->getUserManager()->createUser($username, $password);
353
-			if (!$user) {
354
-				$error[] = "User <$username> could not be created.";
355
-			}
356
-		} catch(Exception $exception) {
357
-			$error[] = $exception->getMessage();
358
-		}
359
-
360
-		if(count($error) == 0) {
361
-			$config = \OC::$server->getConfig();
362
-			$config->setAppValue('core', 'installedat', microtime(true));
363
-			$config->setAppValue('core', 'lastupdatedat', microtime(true));
364
-			$config->setAppValue('core', 'vendor', $this->getVendor());
365
-
366
-			$group =\OC::$server->getGroupManager()->createGroup('admin');
367
-			$group->addUser($user);
368
-
369
-			// Install shipped apps and specified app bundles
370
-			Installer::installShippedApps();
371
-			$installer = new Installer(
372
-				\OC::$server->getAppFetcher(),
373
-				\OC::$server->getHTTPClientService(),
374
-				\OC::$server->getTempManager(),
375
-				\OC::$server->getLogger(),
376
-				\OC::$server->getConfig()
377
-			);
378
-			$bundleFetcher = new BundleFetcher(\OC::$server->getL10N('lib'));
379
-			$defaultInstallationBundles = $bundleFetcher->getDefaultInstallationBundle();
380
-			foreach($defaultInstallationBundles as $bundle) {
381
-				try {
382
-					$installer->installAppBundle($bundle);
383
-				} catch (Exception $e) {}
384
-			}
385
-
386
-			// create empty file in data dir, so we can later find
387
-			// out that this is indeed an ownCloud data directory
388
-			file_put_contents($config->getSystemValue('datadirectory', \OC::$SERVERROOT.'/data').'/.ocdata', '');
389
-
390
-			// Update .htaccess files
391
-			Setup::updateHtaccess();
392
-			Setup::protectDataDirectory();
393
-
394
-			self::installBackgroundJobs();
395
-
396
-			//and we are done
397
-			$config->setSystemValue('installed', true);
398
-
399
-			// Create a session token for the newly created user
400
-			// The token provider requires a working db, so it's not injected on setup
401
-			/* @var $userSession User\Session */
402
-			$userSession = \OC::$server->getUserSession();
403
-			$defaultTokenProvider = \OC::$server->query('OC\Authentication\Token\DefaultTokenProvider');
404
-			$userSession->setTokenProvider($defaultTokenProvider);
405
-			$userSession->login($username, $password);
406
-			$userSession->createSessionToken($request, $userSession->getUser()->getUID(), $username, $password);
407
-		}
408
-
409
-		return $error;
410
-	}
411
-
412
-	public static function installBackgroundJobs() {
413
-		\OC::$server->getJobList()->add('\OC\Authentication\Token\DefaultTokenCleanupJob');
414
-	}
415
-
416
-	/**
417
-	 * @return string Absolute path to htaccess
418
-	 */
419
-	private function pathToHtaccess() {
420
-		return \OC::$SERVERROOT.'/.htaccess';
421
-	}
422
-
423
-	/**
424
-	 * Append the correct ErrorDocument path for Apache hosts
425
-	 * @return bool True when success, False otherwise
426
-	 */
427
-	public static function updateHtaccess() {
428
-		$config = \OC::$server->getSystemConfig();
429
-
430
-		// For CLI read the value from overwrite.cli.url
431
-		if(\OC::$CLI) {
432
-			$webRoot = $config->getValue('overwrite.cli.url', '');
433
-			if($webRoot === '') {
434
-				return false;
435
-			}
436
-			$webRoot = parse_url($webRoot, PHP_URL_PATH);
437
-			$webRoot = rtrim($webRoot, '/');
438
-		} else {
439
-			$webRoot = !empty(\OC::$WEBROOT) ? \OC::$WEBROOT : '/';
440
-		}
441
-
442
-		$setupHelper = new \OC\Setup($config, \OC::$server->getIniWrapper(),
443
-			\OC::$server->getL10N('lib'), \OC::$server->query(Defaults::class), \OC::$server->getLogger(),
444
-			\OC::$server->getSecureRandom());
445
-
446
-		$htaccessContent = file_get_contents($setupHelper->pathToHtaccess());
447
-		$content = "#### DO NOT CHANGE ANYTHING ABOVE THIS LINE ####\n";
448
-		$htaccessContent = explode($content, $htaccessContent, 2)[0];
449
-
450
-		//custom 403 error page
451
-		$content.= "\nErrorDocument 403 ".$webRoot."/core/templates/403.php";
452
-
453
-		//custom 404 error page
454
-		$content.= "\nErrorDocument 404 ".$webRoot."/core/templates/404.php";
455
-
456
-		// Add rewrite rules if the RewriteBase is configured
457
-		$rewriteBase = $config->getValue('htaccess.RewriteBase', '');
458
-		if($rewriteBase !== '') {
459
-			$content .= "\n<IfModule mod_rewrite.c>";
460
-			$content .= "\n  Options -MultiViews";
461
-			$content .= "\n  RewriteRule ^core/js/oc.js$ index.php [PT,E=PATH_INFO:$1]";
462
-			$content .= "\n  RewriteRule ^core/preview.png$ index.php [PT,E=PATH_INFO:$1]";
463
-			$content .= "\n  RewriteCond %{REQUEST_FILENAME} !\\.(css|js|svg|gif|png|html|ttf|woff|ico|jpg|jpeg)$";
464
-			$content .= "\n  RewriteCond %{REQUEST_FILENAME} !core/img/favicon.ico$";
465
-			$content .= "\n  RewriteCond %{REQUEST_FILENAME} !/remote.php";
466
-			$content .= "\n  RewriteCond %{REQUEST_FILENAME} !/public.php";
467
-			$content .= "\n  RewriteCond %{REQUEST_FILENAME} !/cron.php";
468
-			$content .= "\n  RewriteCond %{REQUEST_FILENAME} !/core/ajax/update.php";
469
-			$content .= "\n  RewriteCond %{REQUEST_FILENAME} !/status.php";
470
-			$content .= "\n  RewriteCond %{REQUEST_FILENAME} !/ocs/v1.php";
471
-			$content .= "\n  RewriteCond %{REQUEST_FILENAME} !/ocs/v2.php";
472
-			$content .= "\n  RewriteCond %{REQUEST_FILENAME} !/robots.txt";
473
-			$content .= "\n  RewriteCond %{REQUEST_FILENAME} !/updater/";
474
-			$content .= "\n  RewriteCond %{REQUEST_FILENAME} !/ocs-provider/";
475
-			$content .= "\n  RewriteCond %{REQUEST_URI} !^/.well-known/acme-challenge/.*";
476
-			$content .= "\n  RewriteRule . index.php [PT,E=PATH_INFO:$1]";
477
-			$content .= "\n  RewriteBase " . $rewriteBase;
478
-			$content .= "\n  <IfModule mod_env.c>";
479
-			$content .= "\n    SetEnv front_controller_active true";
480
-			$content .= "\n    <IfModule mod_dir.c>";
481
-			$content .= "\n      DirectorySlash off";
482
-			$content .= "\n    </IfModule>";
483
-			$content .= "\n  </IfModule>";
484
-			$content .= "\n</IfModule>";
485
-		}
486
-
487
-		if ($content !== '') {
488
-			//suppress errors in case we don't have permissions for it
489
-			return (bool) @file_put_contents($setupHelper->pathToHtaccess(), $htaccessContent.$content . "\n");
490
-		}
491
-
492
-		return false;
493
-	}
494
-
495
-	public static function protectDataDirectory() {
496
-		//Require all denied
497
-		$now =  date('Y-m-d H:i:s');
498
-		$content = "# Generated by Nextcloud on $now\n";
499
-		$content.= "# line below if for Apache 2.4\n";
500
-		$content.= "<ifModule mod_authz_core.c>\n";
501
-		$content.= "Require all denied\n";
502
-		$content.= "</ifModule>\n\n";
503
-		$content.= "# line below if for Apache 2.2\n";
504
-		$content.= "<ifModule !mod_authz_core.c>\n";
505
-		$content.= "deny from all\n";
506
-		$content.= "Satisfy All\n";
507
-		$content.= "</ifModule>\n\n";
508
-		$content.= "# section for Apache 2.2 and 2.4\n";
509
-		$content.= "<ifModule mod_autoindex.c>\n";
510
-		$content.= "IndexIgnore *\n";
511
-		$content.= "</ifModule>\n";
512
-
513
-		$baseDir = \OC::$server->getConfig()->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data');
514
-		file_put_contents($baseDir . '/.htaccess', $content);
515
-		file_put_contents($baseDir . '/index.html', '');
516
-	}
517
-
518
-	/**
519
-	 * Return vendor from which this version was published
520
-	 *
521
-	 * @return string Get the vendor
522
-	 *
523
-	 * Copy of \OC\Updater::getVendor()
524
-	 */
525
-	private function getVendor() {
526
-		// this should really be a JSON file
527
-		require \OC::$SERVERROOT . '/version.php';
528
-		/** @var string $vendor */
529
-		return (string) $vendor;
530
-	}
51
+    /** @var SystemConfig */
52
+    protected $config;
53
+    /** @var IniGetWrapper */
54
+    protected $iniWrapper;
55
+    /** @var IL10N */
56
+    protected $l10n;
57
+    /** @var Defaults */
58
+    protected $defaults;
59
+    /** @var ILogger */
60
+    protected $logger;
61
+    /** @var ISecureRandom */
62
+    protected $random;
63
+
64
+    /**
65
+     * @param SystemConfig $config
66
+     * @param IniGetWrapper $iniWrapper
67
+     * @param IL10N $l10n
68
+     * @param Defaults $defaults
69
+     * @param ILogger $logger
70
+     * @param ISecureRandom $random
71
+     */
72
+    public function __construct(SystemConfig $config,
73
+                            IniGetWrapper $iniWrapper,
74
+                            IL10N $l10n,
75
+                            Defaults $defaults,
76
+                            ILogger $logger,
77
+                            ISecureRandom $random
78
+        ) {
79
+        $this->config = $config;
80
+        $this->iniWrapper = $iniWrapper;
81
+        $this->l10n = $l10n;
82
+        $this->defaults = $defaults;
83
+        $this->logger = $logger;
84
+        $this->random = $random;
85
+    }
86
+
87
+    static $dbSetupClasses = [
88
+        'mysql' => \OC\Setup\MySQL::class,
89
+        'pgsql' => \OC\Setup\PostgreSQL::class,
90
+        'oci'   => \OC\Setup\OCI::class,
91
+        'sqlite' => \OC\Setup\Sqlite::class,
92
+        'sqlite3' => \OC\Setup\Sqlite::class,
93
+    ];
94
+
95
+    /**
96
+     * Wrapper around the "class_exists" PHP function to be able to mock it
97
+     * @param string $name
98
+     * @return bool
99
+     */
100
+    protected function class_exists($name) {
101
+        return class_exists($name);
102
+    }
103
+
104
+    /**
105
+     * Wrapper around the "is_callable" PHP function to be able to mock it
106
+     * @param string $name
107
+     * @return bool
108
+     */
109
+    protected function is_callable($name) {
110
+        return is_callable($name);
111
+    }
112
+
113
+    /**
114
+     * Wrapper around \PDO::getAvailableDrivers
115
+     *
116
+     * @return array
117
+     */
118
+    protected function getAvailableDbDriversForPdo() {
119
+        return \PDO::getAvailableDrivers();
120
+    }
121
+
122
+    /**
123
+     * Get the available and supported databases of this instance
124
+     *
125
+     * @param bool $allowAllDatabases
126
+     * @return array
127
+     * @throws Exception
128
+     */
129
+    public function getSupportedDatabases($allowAllDatabases = false) {
130
+        $availableDatabases = array(
131
+            'sqlite' =>  array(
132
+                'type' => 'pdo',
133
+                'call' => 'sqlite',
134
+                'name' => 'SQLite'
135
+            ),
136
+            'mysql' => array(
137
+                'type' => 'pdo',
138
+                'call' => 'mysql',
139
+                'name' => 'MySQL/MariaDB'
140
+            ),
141
+            'pgsql' => array(
142
+                'type' => 'pdo',
143
+                'call' => 'pgsql',
144
+                'name' => 'PostgreSQL'
145
+            ),
146
+            'oci' => array(
147
+                'type' => 'function',
148
+                'call' => 'oci_connect',
149
+                'name' => 'Oracle'
150
+            )
151
+        );
152
+        if ($allowAllDatabases) {
153
+            $configuredDatabases = array_keys($availableDatabases);
154
+        } else {
155
+            $configuredDatabases = $this->config->getValue('supportedDatabases',
156
+                array('sqlite', 'mysql', 'pgsql'));
157
+        }
158
+        if(!is_array($configuredDatabases)) {
159
+            throw new Exception('Supported databases are not properly configured.');
160
+        }
161
+
162
+        $supportedDatabases = array();
163
+
164
+        foreach($configuredDatabases as $database) {
165
+            if(array_key_exists($database, $availableDatabases)) {
166
+                $working = false;
167
+                $type = $availableDatabases[$database]['type'];
168
+                $call = $availableDatabases[$database]['call'];
169
+
170
+                if ($type === 'function') {
171
+                    $working = $this->is_callable($call);
172
+                } elseif($type === 'pdo') {
173
+                    $working = in_array($call, $this->getAvailableDbDriversForPdo(), TRUE);
174
+                }
175
+                if($working) {
176
+                    $supportedDatabases[$database] = $availableDatabases[$database]['name'];
177
+                }
178
+            }
179
+        }
180
+
181
+        return $supportedDatabases;
182
+    }
183
+
184
+    /**
185
+     * Gathers system information like database type and does
186
+     * a few system checks.
187
+     *
188
+     * @return array of system info, including an "errors" value
189
+     * in case of errors/warnings
190
+     */
191
+    public function getSystemInfo($allowAllDatabases = false) {
192
+        $databases = $this->getSupportedDatabases($allowAllDatabases);
193
+
194
+        $dataDir = $this->config->getValue('datadirectory', \OC::$SERVERROOT.'/data');
195
+
196
+        $errors = array();
197
+
198
+        // Create data directory to test whether the .htaccess works
199
+        // Notice that this is not necessarily the same data directory as the one
200
+        // that will effectively be used.
201
+        if(!file_exists($dataDir)) {
202
+            @mkdir($dataDir);
203
+        }
204
+        $htAccessWorking = true;
205
+        if (is_dir($dataDir) && is_writable($dataDir)) {
206
+            // Protect data directory here, so we can test if the protection is working
207
+            \OC\Setup::protectDataDirectory();
208
+
209
+            try {
210
+                $util = new \OC_Util();
211
+                $htAccessWorking = $util->isHtaccessWorking(\OC::$server->getConfig());
212
+            } catch (\OC\HintException $e) {
213
+                $errors[] = array(
214
+                    'error' => $e->getMessage(),
215
+                    'hint' => $e->getHint()
216
+                );
217
+                $htAccessWorking = false;
218
+            }
219
+        }
220
+
221
+        if (\OC_Util::runningOnMac()) {
222
+            $errors[] = array(
223
+                'error' => $this->l10n->t(
224
+                    'Mac OS X is not supported and %s will not work properly on this platform. ' .
225
+                    'Use it at your own risk! ',
226
+                    $this->defaults->getName()
227
+                ),
228
+                'hint' => $this->l10n->t('For the best results, please consider using a GNU/Linux server instead.')
229
+            );
230
+        }
231
+
232
+        if($this->iniWrapper->getString('open_basedir') !== '' && PHP_INT_SIZE === 4) {
233
+            $errors[] = array(
234
+                'error' => $this->l10n->t(
235
+                    'It seems that this %s instance is running on a 32-bit PHP environment and the open_basedir has been configured in php.ini. ' .
236
+                    'This will lead to problems with files over 4 GB and is highly discouraged.',
237
+                    $this->defaults->getName()
238
+                ),
239
+                'hint' => $this->l10n->t('Please remove the open_basedir setting within your php.ini or switch to 64-bit PHP.')
240
+            );
241
+        }
242
+
243
+        return array(
244
+            'hasSQLite' => isset($databases['sqlite']),
245
+            'hasMySQL' => isset($databases['mysql']),
246
+            'hasPostgreSQL' => isset($databases['pgsql']),
247
+            'hasOracle' => isset($databases['oci']),
248
+            'databases' => $databases,
249
+            'directory' => $dataDir,
250
+            'htaccessWorking' => $htAccessWorking,
251
+            'errors' => $errors,
252
+        );
253
+    }
254
+
255
+    /**
256
+     * @param $options
257
+     * @return array
258
+     */
259
+    public function install($options) {
260
+        $l = $this->l10n;
261
+
262
+        $error = array();
263
+        $dbType = $options['dbtype'];
264
+
265
+        if(empty($options['adminlogin'])) {
266
+            $error[] = $l->t('Set an admin username.');
267
+        }
268
+        if(empty($options['adminpass'])) {
269
+            $error[] = $l->t('Set an admin password.');
270
+        }
271
+        if(empty($options['directory'])) {
272
+            $options['directory'] = \OC::$SERVERROOT."/data";
273
+        }
274
+
275
+        if (!isset(self::$dbSetupClasses[$dbType])) {
276
+            $dbType = 'sqlite';
277
+        }
278
+
279
+        $username = htmlspecialchars_decode($options['adminlogin']);
280
+        $password = htmlspecialchars_decode($options['adminpass']);
281
+        $dataDir = htmlspecialchars_decode($options['directory']);
282
+
283
+        $class = self::$dbSetupClasses[$dbType];
284
+        /** @var \OC\Setup\AbstractDatabase $dbSetup */
285
+        $dbSetup = new $class($l, 'db_structure.xml', $this->config,
286
+            $this->logger, $this->random);
287
+        $error = array_merge($error, $dbSetup->validate($options));
288
+
289
+        // validate the data directory
290
+        if (
291
+            (!is_dir($dataDir) and !mkdir($dataDir)) or
292
+            !is_writable($dataDir)
293
+        ) {
294
+            $error[] = $l->t("Can't create or write into the data directory %s", array($dataDir));
295
+        }
296
+
297
+        if(count($error) != 0) {
298
+            return $error;
299
+        }
300
+
301
+        $request = \OC::$server->getRequest();
302
+
303
+        //no errors, good
304
+        if(isset($options['trusted_domains'])
305
+            && is_array($options['trusted_domains'])) {
306
+            $trustedDomains = $options['trusted_domains'];
307
+        } else {
308
+            $trustedDomains = [$request->getInsecureServerHost()];
309
+        }
310
+
311
+        //use sqlite3 when available, otherwise sqlite2 will be used.
312
+        if($dbType=='sqlite' and class_exists('SQLite3')) {
313
+            $dbType='sqlite3';
314
+        }
315
+
316
+        //generate a random salt that is used to salt the local user passwords
317
+        $salt = $this->random->generate(30);
318
+        // generate a secret
319
+        $secret = $this->random->generate(48);
320
+
321
+        //write the config file
322
+        $this->config->setValues([
323
+            'passwordsalt'		=> $salt,
324
+            'secret'			=> $secret,
325
+            'trusted_domains'	=> $trustedDomains,
326
+            'datadirectory'		=> $dataDir,
327
+            'overwrite.cli.url'	=> $request->getServerProtocol() . '://' . $request->getInsecureServerHost() . \OC::$WEBROOT,
328
+            'dbtype'			=> $dbType,
329
+            'version'			=> implode('.', \OCP\Util::getVersion()),
330
+        ]);
331
+
332
+        try {
333
+            $dbSetup->initialize($options);
334
+            $dbSetup->setupDatabase($username);
335
+        } catch (\OC\DatabaseSetupException $e) {
336
+            $error[] = array(
337
+                'error' => $e->getMessage(),
338
+                'hint' => $e->getHint()
339
+            );
340
+            return($error);
341
+        } catch (Exception $e) {
342
+            $error[] = array(
343
+                'error' => 'Error while trying to create admin user: ' . $e->getMessage(),
344
+                'hint' => ''
345
+            );
346
+            return($error);
347
+        }
348
+
349
+        //create the user and group
350
+        $user =  null;
351
+        try {
352
+            $user = \OC::$server->getUserManager()->createUser($username, $password);
353
+            if (!$user) {
354
+                $error[] = "User <$username> could not be created.";
355
+            }
356
+        } catch(Exception $exception) {
357
+            $error[] = $exception->getMessage();
358
+        }
359
+
360
+        if(count($error) == 0) {
361
+            $config = \OC::$server->getConfig();
362
+            $config->setAppValue('core', 'installedat', microtime(true));
363
+            $config->setAppValue('core', 'lastupdatedat', microtime(true));
364
+            $config->setAppValue('core', 'vendor', $this->getVendor());
365
+
366
+            $group =\OC::$server->getGroupManager()->createGroup('admin');
367
+            $group->addUser($user);
368
+
369
+            // Install shipped apps and specified app bundles
370
+            Installer::installShippedApps();
371
+            $installer = new Installer(
372
+                \OC::$server->getAppFetcher(),
373
+                \OC::$server->getHTTPClientService(),
374
+                \OC::$server->getTempManager(),
375
+                \OC::$server->getLogger(),
376
+                \OC::$server->getConfig()
377
+            );
378
+            $bundleFetcher = new BundleFetcher(\OC::$server->getL10N('lib'));
379
+            $defaultInstallationBundles = $bundleFetcher->getDefaultInstallationBundle();
380
+            foreach($defaultInstallationBundles as $bundle) {
381
+                try {
382
+                    $installer->installAppBundle($bundle);
383
+                } catch (Exception $e) {}
384
+            }
385
+
386
+            // create empty file in data dir, so we can later find
387
+            // out that this is indeed an ownCloud data directory
388
+            file_put_contents($config->getSystemValue('datadirectory', \OC::$SERVERROOT.'/data').'/.ocdata', '');
389
+
390
+            // Update .htaccess files
391
+            Setup::updateHtaccess();
392
+            Setup::protectDataDirectory();
393
+
394
+            self::installBackgroundJobs();
395
+
396
+            //and we are done
397
+            $config->setSystemValue('installed', true);
398
+
399
+            // Create a session token for the newly created user
400
+            // The token provider requires a working db, so it's not injected on setup
401
+            /* @var $userSession User\Session */
402
+            $userSession = \OC::$server->getUserSession();
403
+            $defaultTokenProvider = \OC::$server->query('OC\Authentication\Token\DefaultTokenProvider');
404
+            $userSession->setTokenProvider($defaultTokenProvider);
405
+            $userSession->login($username, $password);
406
+            $userSession->createSessionToken($request, $userSession->getUser()->getUID(), $username, $password);
407
+        }
408
+
409
+        return $error;
410
+    }
411
+
412
+    public static function installBackgroundJobs() {
413
+        \OC::$server->getJobList()->add('\OC\Authentication\Token\DefaultTokenCleanupJob');
414
+    }
415
+
416
+    /**
417
+     * @return string Absolute path to htaccess
418
+     */
419
+    private function pathToHtaccess() {
420
+        return \OC::$SERVERROOT.'/.htaccess';
421
+    }
422
+
423
+    /**
424
+     * Append the correct ErrorDocument path for Apache hosts
425
+     * @return bool True when success, False otherwise
426
+     */
427
+    public static function updateHtaccess() {
428
+        $config = \OC::$server->getSystemConfig();
429
+
430
+        // For CLI read the value from overwrite.cli.url
431
+        if(\OC::$CLI) {
432
+            $webRoot = $config->getValue('overwrite.cli.url', '');
433
+            if($webRoot === '') {
434
+                return false;
435
+            }
436
+            $webRoot = parse_url($webRoot, PHP_URL_PATH);
437
+            $webRoot = rtrim($webRoot, '/');
438
+        } else {
439
+            $webRoot = !empty(\OC::$WEBROOT) ? \OC::$WEBROOT : '/';
440
+        }
441
+
442
+        $setupHelper = new \OC\Setup($config, \OC::$server->getIniWrapper(),
443
+            \OC::$server->getL10N('lib'), \OC::$server->query(Defaults::class), \OC::$server->getLogger(),
444
+            \OC::$server->getSecureRandom());
445
+
446
+        $htaccessContent = file_get_contents($setupHelper->pathToHtaccess());
447
+        $content = "#### DO NOT CHANGE ANYTHING ABOVE THIS LINE ####\n";
448
+        $htaccessContent = explode($content, $htaccessContent, 2)[0];
449
+
450
+        //custom 403 error page
451
+        $content.= "\nErrorDocument 403 ".$webRoot."/core/templates/403.php";
452
+
453
+        //custom 404 error page
454
+        $content.= "\nErrorDocument 404 ".$webRoot."/core/templates/404.php";
455
+
456
+        // Add rewrite rules if the RewriteBase is configured
457
+        $rewriteBase = $config->getValue('htaccess.RewriteBase', '');
458
+        if($rewriteBase !== '') {
459
+            $content .= "\n<IfModule mod_rewrite.c>";
460
+            $content .= "\n  Options -MultiViews";
461
+            $content .= "\n  RewriteRule ^core/js/oc.js$ index.php [PT,E=PATH_INFO:$1]";
462
+            $content .= "\n  RewriteRule ^core/preview.png$ index.php [PT,E=PATH_INFO:$1]";
463
+            $content .= "\n  RewriteCond %{REQUEST_FILENAME} !\\.(css|js|svg|gif|png|html|ttf|woff|ico|jpg|jpeg)$";
464
+            $content .= "\n  RewriteCond %{REQUEST_FILENAME} !core/img/favicon.ico$";
465
+            $content .= "\n  RewriteCond %{REQUEST_FILENAME} !/remote.php";
466
+            $content .= "\n  RewriteCond %{REQUEST_FILENAME} !/public.php";
467
+            $content .= "\n  RewriteCond %{REQUEST_FILENAME} !/cron.php";
468
+            $content .= "\n  RewriteCond %{REQUEST_FILENAME} !/core/ajax/update.php";
469
+            $content .= "\n  RewriteCond %{REQUEST_FILENAME} !/status.php";
470
+            $content .= "\n  RewriteCond %{REQUEST_FILENAME} !/ocs/v1.php";
471
+            $content .= "\n  RewriteCond %{REQUEST_FILENAME} !/ocs/v2.php";
472
+            $content .= "\n  RewriteCond %{REQUEST_FILENAME} !/robots.txt";
473
+            $content .= "\n  RewriteCond %{REQUEST_FILENAME} !/updater/";
474
+            $content .= "\n  RewriteCond %{REQUEST_FILENAME} !/ocs-provider/";
475
+            $content .= "\n  RewriteCond %{REQUEST_URI} !^/.well-known/acme-challenge/.*";
476
+            $content .= "\n  RewriteRule . index.php [PT,E=PATH_INFO:$1]";
477
+            $content .= "\n  RewriteBase " . $rewriteBase;
478
+            $content .= "\n  <IfModule mod_env.c>";
479
+            $content .= "\n    SetEnv front_controller_active true";
480
+            $content .= "\n    <IfModule mod_dir.c>";
481
+            $content .= "\n      DirectorySlash off";
482
+            $content .= "\n    </IfModule>";
483
+            $content .= "\n  </IfModule>";
484
+            $content .= "\n</IfModule>";
485
+        }
486
+
487
+        if ($content !== '') {
488
+            //suppress errors in case we don't have permissions for it
489
+            return (bool) @file_put_contents($setupHelper->pathToHtaccess(), $htaccessContent.$content . "\n");
490
+        }
491
+
492
+        return false;
493
+    }
494
+
495
+    public static function protectDataDirectory() {
496
+        //Require all denied
497
+        $now =  date('Y-m-d H:i:s');
498
+        $content = "# Generated by Nextcloud on $now\n";
499
+        $content.= "# line below if for Apache 2.4\n";
500
+        $content.= "<ifModule mod_authz_core.c>\n";
501
+        $content.= "Require all denied\n";
502
+        $content.= "</ifModule>\n\n";
503
+        $content.= "# line below if for Apache 2.2\n";
504
+        $content.= "<ifModule !mod_authz_core.c>\n";
505
+        $content.= "deny from all\n";
506
+        $content.= "Satisfy All\n";
507
+        $content.= "</ifModule>\n\n";
508
+        $content.= "# section for Apache 2.2 and 2.4\n";
509
+        $content.= "<ifModule mod_autoindex.c>\n";
510
+        $content.= "IndexIgnore *\n";
511
+        $content.= "</ifModule>\n";
512
+
513
+        $baseDir = \OC::$server->getConfig()->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data');
514
+        file_put_contents($baseDir . '/.htaccess', $content);
515
+        file_put_contents($baseDir . '/index.html', '');
516
+    }
517
+
518
+    /**
519
+     * Return vendor from which this version was published
520
+     *
521
+     * @return string Get the vendor
522
+     *
523
+     * Copy of \OC\Updater::getVendor()
524
+     */
525
+    private function getVendor() {
526
+        // this should really be a JSON file
527
+        require \OC::$SERVERROOT . '/version.php';
528
+        /** @var string $vendor */
529
+        return (string) $vendor;
530
+    }
531 531
 }
Please login to merge, or discard this patch.
Spacing   +49 added lines, -49 removed lines patch added patch discarded remove patch
@@ -155,24 +155,24 @@  discard block
 block discarded – undo
155 155
 			$configuredDatabases = $this->config->getValue('supportedDatabases',
156 156
 				array('sqlite', 'mysql', 'pgsql'));
157 157
 		}
158
-		if(!is_array($configuredDatabases)) {
158
+		if (!is_array($configuredDatabases)) {
159 159
 			throw new Exception('Supported databases are not properly configured.');
160 160
 		}
161 161
 
162 162
 		$supportedDatabases = array();
163 163
 
164
-		foreach($configuredDatabases as $database) {
165
-			if(array_key_exists($database, $availableDatabases)) {
164
+		foreach ($configuredDatabases as $database) {
165
+			if (array_key_exists($database, $availableDatabases)) {
166 166
 				$working = false;
167 167
 				$type = $availableDatabases[$database]['type'];
168 168
 				$call = $availableDatabases[$database]['call'];
169 169
 
170 170
 				if ($type === 'function') {
171 171
 					$working = $this->is_callable($call);
172
-				} elseif($type === 'pdo') {
172
+				} elseif ($type === 'pdo') {
173 173
 					$working = in_array($call, $this->getAvailableDbDriversForPdo(), TRUE);
174 174
 				}
175
-				if($working) {
175
+				if ($working) {
176 176
 					$supportedDatabases[$database] = $availableDatabases[$database]['name'];
177 177
 				}
178 178
 			}
@@ -198,7 +198,7 @@  discard block
 block discarded – undo
198 198
 		// Create data directory to test whether the .htaccess works
199 199
 		// Notice that this is not necessarily the same data directory as the one
200 200
 		// that will effectively be used.
201
-		if(!file_exists($dataDir)) {
201
+		if (!file_exists($dataDir)) {
202 202
 			@mkdir($dataDir);
203 203
 		}
204 204
 		$htAccessWorking = true;
@@ -221,7 +221,7 @@  discard block
 block discarded – undo
221 221
 		if (\OC_Util::runningOnMac()) {
222 222
 			$errors[] = array(
223 223
 				'error' => $this->l10n->t(
224
-					'Mac OS X is not supported and %s will not work properly on this platform. ' .
224
+					'Mac OS X is not supported and %s will not work properly on this platform. '.
225 225
 					'Use it at your own risk! ',
226 226
 					$this->defaults->getName()
227 227
 				),
@@ -229,10 +229,10 @@  discard block
 block discarded – undo
229 229
 			);
230 230
 		}
231 231
 
232
-		if($this->iniWrapper->getString('open_basedir') !== '' && PHP_INT_SIZE === 4) {
232
+		if ($this->iniWrapper->getString('open_basedir') !== '' && PHP_INT_SIZE === 4) {
233 233
 			$errors[] = array(
234 234
 				'error' => $this->l10n->t(
235
-					'It seems that this %s instance is running on a 32-bit PHP environment and the open_basedir has been configured in php.ini. ' .
235
+					'It seems that this %s instance is running on a 32-bit PHP environment and the open_basedir has been configured in php.ini. '.
236 236
 					'This will lead to problems with files over 4 GB and is highly discouraged.',
237 237
 					$this->defaults->getName()
238 238
 				),
@@ -262,13 +262,13 @@  discard block
 block discarded – undo
262 262
 		$error = array();
263 263
 		$dbType = $options['dbtype'];
264 264
 
265
-		if(empty($options['adminlogin'])) {
265
+		if (empty($options['adminlogin'])) {
266 266
 			$error[] = $l->t('Set an admin username.');
267 267
 		}
268
-		if(empty($options['adminpass'])) {
268
+		if (empty($options['adminpass'])) {
269 269
 			$error[] = $l->t('Set an admin password.');
270 270
 		}
271
-		if(empty($options['directory'])) {
271
+		if (empty($options['directory'])) {
272 272
 			$options['directory'] = \OC::$SERVERROOT."/data";
273 273
 		}
274 274
 
@@ -294,14 +294,14 @@  discard block
 block discarded – undo
294 294
 			$error[] = $l->t("Can't create or write into the data directory %s", array($dataDir));
295 295
 		}
296 296
 
297
-		if(count($error) != 0) {
297
+		if (count($error) != 0) {
298 298
 			return $error;
299 299
 		}
300 300
 
301 301
 		$request = \OC::$server->getRequest();
302 302
 
303 303
 		//no errors, good
304
-		if(isset($options['trusted_domains'])
304
+		if (isset($options['trusted_domains'])
305 305
 		    && is_array($options['trusted_domains'])) {
306 306
 			$trustedDomains = $options['trusted_domains'];
307 307
 		} else {
@@ -309,8 +309,8 @@  discard block
 block discarded – undo
309 309
 		}
310 310
 
311 311
 		//use sqlite3 when available, otherwise sqlite2 will be used.
312
-		if($dbType=='sqlite' and class_exists('SQLite3')) {
313
-			$dbType='sqlite3';
312
+		if ($dbType == 'sqlite' and class_exists('SQLite3')) {
313
+			$dbType = 'sqlite3';
314 314
 		}
315 315
 
316 316
 		//generate a random salt that is used to salt the local user passwords
@@ -324,7 +324,7 @@  discard block
 block discarded – undo
324 324
 			'secret'			=> $secret,
325 325
 			'trusted_domains'	=> $trustedDomains,
326 326
 			'datadirectory'		=> $dataDir,
327
-			'overwrite.cli.url'	=> $request->getServerProtocol() . '://' . $request->getInsecureServerHost() . \OC::$WEBROOT,
327
+			'overwrite.cli.url'	=> $request->getServerProtocol().'://'.$request->getInsecureServerHost().\OC::$WEBROOT,
328 328
 			'dbtype'			=> $dbType,
329 329
 			'version'			=> implode('.', \OCP\Util::getVersion()),
330 330
 		]);
@@ -340,30 +340,30 @@  discard block
 block discarded – undo
340 340
 			return($error);
341 341
 		} catch (Exception $e) {
342 342
 			$error[] = array(
343
-				'error' => 'Error while trying to create admin user: ' . $e->getMessage(),
343
+				'error' => 'Error while trying to create admin user: '.$e->getMessage(),
344 344
 				'hint' => ''
345 345
 			);
346 346
 			return($error);
347 347
 		}
348 348
 
349 349
 		//create the user and group
350
-		$user =  null;
350
+		$user = null;
351 351
 		try {
352 352
 			$user = \OC::$server->getUserManager()->createUser($username, $password);
353 353
 			if (!$user) {
354 354
 				$error[] = "User <$username> could not be created.";
355 355
 			}
356
-		} catch(Exception $exception) {
356
+		} catch (Exception $exception) {
357 357
 			$error[] = $exception->getMessage();
358 358
 		}
359 359
 
360
-		if(count($error) == 0) {
360
+		if (count($error) == 0) {
361 361
 			$config = \OC::$server->getConfig();
362 362
 			$config->setAppValue('core', 'installedat', microtime(true));
363 363
 			$config->setAppValue('core', 'lastupdatedat', microtime(true));
364 364
 			$config->setAppValue('core', 'vendor', $this->getVendor());
365 365
 
366
-			$group =\OC::$server->getGroupManager()->createGroup('admin');
366
+			$group = \OC::$server->getGroupManager()->createGroup('admin');
367 367
 			$group->addUser($user);
368 368
 
369 369
 			// Install shipped apps and specified app bundles
@@ -377,7 +377,7 @@  discard block
 block discarded – undo
377 377
 			);
378 378
 			$bundleFetcher = new BundleFetcher(\OC::$server->getL10N('lib'));
379 379
 			$defaultInstallationBundles = $bundleFetcher->getDefaultInstallationBundle();
380
-			foreach($defaultInstallationBundles as $bundle) {
380
+			foreach ($defaultInstallationBundles as $bundle) {
381 381
 				try {
382 382
 					$installer->installAppBundle($bundle);
383 383
 				} catch (Exception $e) {}
@@ -428,9 +428,9 @@  discard block
 block discarded – undo
428 428
 		$config = \OC::$server->getSystemConfig();
429 429
 
430 430
 		// For CLI read the value from overwrite.cli.url
431
-		if(\OC::$CLI) {
431
+		if (\OC::$CLI) {
432 432
 			$webRoot = $config->getValue('overwrite.cli.url', '');
433
-			if($webRoot === '') {
433
+			if ($webRoot === '') {
434 434
 				return false;
435 435
 			}
436 436
 			$webRoot = parse_url($webRoot, PHP_URL_PATH);
@@ -448,14 +448,14 @@  discard block
 block discarded – undo
448 448
 		$htaccessContent = explode($content, $htaccessContent, 2)[0];
449 449
 
450 450
 		//custom 403 error page
451
-		$content.= "\nErrorDocument 403 ".$webRoot."/core/templates/403.php";
451
+		$content .= "\nErrorDocument 403 ".$webRoot."/core/templates/403.php";
452 452
 
453 453
 		//custom 404 error page
454
-		$content.= "\nErrorDocument 404 ".$webRoot."/core/templates/404.php";
454
+		$content .= "\nErrorDocument 404 ".$webRoot."/core/templates/404.php";
455 455
 
456 456
 		// Add rewrite rules if the RewriteBase is configured
457 457
 		$rewriteBase = $config->getValue('htaccess.RewriteBase', '');
458
-		if($rewriteBase !== '') {
458
+		if ($rewriteBase !== '') {
459 459
 			$content .= "\n<IfModule mod_rewrite.c>";
460 460
 			$content .= "\n  Options -MultiViews";
461 461
 			$content .= "\n  RewriteRule ^core/js/oc.js$ index.php [PT,E=PATH_INFO:$1]";
@@ -474,7 +474,7 @@  discard block
 block discarded – undo
474 474
 			$content .= "\n  RewriteCond %{REQUEST_FILENAME} !/ocs-provider/";
475 475
 			$content .= "\n  RewriteCond %{REQUEST_URI} !^/.well-known/acme-challenge/.*";
476 476
 			$content .= "\n  RewriteRule . index.php [PT,E=PATH_INFO:$1]";
477
-			$content .= "\n  RewriteBase " . $rewriteBase;
477
+			$content .= "\n  RewriteBase ".$rewriteBase;
478 478
 			$content .= "\n  <IfModule mod_env.c>";
479 479
 			$content .= "\n    SetEnv front_controller_active true";
480 480
 			$content .= "\n    <IfModule mod_dir.c>";
@@ -486,7 +486,7 @@  discard block
 block discarded – undo
486 486
 
487 487
 		if ($content !== '') {
488 488
 			//suppress errors in case we don't have permissions for it
489
-			return (bool) @file_put_contents($setupHelper->pathToHtaccess(), $htaccessContent.$content . "\n");
489
+			return (bool) @file_put_contents($setupHelper->pathToHtaccess(), $htaccessContent.$content."\n");
490 490
 		}
491 491
 
492 492
 		return false;
@@ -494,25 +494,25 @@  discard block
 block discarded – undo
494 494
 
495 495
 	public static function protectDataDirectory() {
496 496
 		//Require all denied
497
-		$now =  date('Y-m-d H:i:s');
497
+		$now = date('Y-m-d H:i:s');
498 498
 		$content = "# Generated by Nextcloud on $now\n";
499
-		$content.= "# line below if for Apache 2.4\n";
500
-		$content.= "<ifModule mod_authz_core.c>\n";
501
-		$content.= "Require all denied\n";
502
-		$content.= "</ifModule>\n\n";
503
-		$content.= "# line below if for Apache 2.2\n";
504
-		$content.= "<ifModule !mod_authz_core.c>\n";
505
-		$content.= "deny from all\n";
506
-		$content.= "Satisfy All\n";
507
-		$content.= "</ifModule>\n\n";
508
-		$content.= "# section for Apache 2.2 and 2.4\n";
509
-		$content.= "<ifModule mod_autoindex.c>\n";
510
-		$content.= "IndexIgnore *\n";
511
-		$content.= "</ifModule>\n";
512
-
513
-		$baseDir = \OC::$server->getConfig()->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data');
514
-		file_put_contents($baseDir . '/.htaccess', $content);
515
-		file_put_contents($baseDir . '/index.html', '');
499
+		$content .= "# line below if for Apache 2.4\n";
500
+		$content .= "<ifModule mod_authz_core.c>\n";
501
+		$content .= "Require all denied\n";
502
+		$content .= "</ifModule>\n\n";
503
+		$content .= "# line below if for Apache 2.2\n";
504
+		$content .= "<ifModule !mod_authz_core.c>\n";
505
+		$content .= "deny from all\n";
506
+		$content .= "Satisfy All\n";
507
+		$content .= "</ifModule>\n\n";
508
+		$content .= "# section for Apache 2.2 and 2.4\n";
509
+		$content .= "<ifModule mod_autoindex.c>\n";
510
+		$content .= "IndexIgnore *\n";
511
+		$content .= "</ifModule>\n";
512
+
513
+		$baseDir = \OC::$server->getConfig()->getSystemValue('datadirectory', \OC::$SERVERROOT.'/data');
514
+		file_put_contents($baseDir.'/.htaccess', $content);
515
+		file_put_contents($baseDir.'/index.html', '');
516 516
 	}
517 517
 
518 518
 	/**
@@ -524,7 +524,7 @@  discard block
 block discarded – undo
524 524
 	 */
525 525
 	private function getVendor() {
526 526
 		// this should really be a JSON file
527
-		require \OC::$SERVERROOT . '/version.php';
527
+		require \OC::$SERVERROOT.'/version.php';
528 528
 		/** @var string $vendor */
529 529
 		return (string) $vendor;
530 530
 	}
Please login to merge, or discard this patch.
settings/ajax/enableapp.php 2 patches
Indentation   +15 added lines, -15 removed lines patch added patch discarded remove patch
@@ -30,27 +30,27 @@
 block discarded – undo
30 30
 
31 31
 $lastConfirm = (int) \OC::$server->getSession()->get('last-password-confirm');
32 32
 if ($lastConfirm < (time() - 30 * 60 + 15)) { // allow 15 seconds delay
33
-	$l = \OC::$server->getL10N('core');
34
-	OC_JSON::error(array( 'data' => array( 'message' => $l->t('Password confirmation is required'))));
35
-	exit();
33
+    $l = \OC::$server->getL10N('core');
34
+    OC_JSON::error(array( 'data' => array( 'message' => $l->t('Password confirmation is required'))));
35
+    exit();
36 36
 }
37 37
 
38 38
 $groups = isset($_POST['groups']) ? (array)$_POST['groups'] : null;
39 39
 $appIds = isset($_POST['appIds']) ? (array)$_POST['appIds'] : [];
40 40
 
41 41
 try {
42
-	$updateRequired = false;
43
-	foreach($appIds as $appId) {
44
-		$app = new OC_App();
45
-		$appId = OC_App::cleanAppId($appId);
46
-		$app->enable($appId, $groups);
47
-		if(\OC_App::shouldUpgrade($appId)) {
48
-			$updateRequired = true;
49
-		}
50
-	}
42
+    $updateRequired = false;
43
+    foreach($appIds as $appId) {
44
+        $app = new OC_App();
45
+        $appId = OC_App::cleanAppId($appId);
46
+        $app->enable($appId, $groups);
47
+        if(\OC_App::shouldUpgrade($appId)) {
48
+            $updateRequired = true;
49
+        }
50
+    }
51 51
 
52
-	OC_JSON::success(['data' => ['update_required' => $updateRequired]]);
52
+    OC_JSON::success(['data' => ['update_required' => $updateRequired]]);
53 53
 } catch (Exception $e) {
54
-	\OCP\Util::writeLog('core', $e->getMessage(), \OCP\Util::ERROR);
55
-	OC_JSON::error(array("data" => array("message" => $e->getMessage()) ));
54
+    \OCP\Util::writeLog('core', $e->getMessage(), \OCP\Util::ERROR);
55
+    OC_JSON::error(array("data" => array("message" => $e->getMessage()) ));
56 56
 }
Please login to merge, or discard this patch.
Spacing   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -31,20 +31,20 @@  discard block
 block discarded – undo
31 31
 $lastConfirm = (int) \OC::$server->getSession()->get('last-password-confirm');
32 32
 if ($lastConfirm < (time() - 30 * 60 + 15)) { // allow 15 seconds delay
33 33
 	$l = \OC::$server->getL10N('core');
34
-	OC_JSON::error(array( 'data' => array( 'message' => $l->t('Password confirmation is required'))));
34
+	OC_JSON::error(array('data' => array('message' => $l->t('Password confirmation is required'))));
35 35
 	exit();
36 36
 }
37 37
 
38
-$groups = isset($_POST['groups']) ? (array)$_POST['groups'] : null;
39
-$appIds = isset($_POST['appIds']) ? (array)$_POST['appIds'] : [];
38
+$groups = isset($_POST['groups']) ? (array) $_POST['groups'] : null;
39
+$appIds = isset($_POST['appIds']) ? (array) $_POST['appIds'] : [];
40 40
 
41 41
 try {
42 42
 	$updateRequired = false;
43
-	foreach($appIds as $appId) {
43
+	foreach ($appIds as $appId) {
44 44
 		$app = new OC_App();
45 45
 		$appId = OC_App::cleanAppId($appId);
46 46
 		$app->enable($appId, $groups);
47
-		if(\OC_App::shouldUpgrade($appId)) {
47
+		if (\OC_App::shouldUpgrade($appId)) {
48 48
 			$updateRequired = true;
49 49
 		}
50 50
 	}
@@ -52,5 +52,5 @@  discard block
 block discarded – undo
52 52
 	OC_JSON::success(['data' => ['update_required' => $updateRequired]]);
53 53
 } catch (Exception $e) {
54 54
 	\OCP\Util::writeLog('core', $e->getMessage(), \OCP\Util::ERROR);
55
-	OC_JSON::error(array("data" => array("message" => $e->getMessage()) ));
55
+	OC_JSON::error(array("data" => array("message" => $e->getMessage())));
56 56
 }
Please login to merge, or discard this patch.
settings/ajax/updateapp.php 1 patch
Indentation   +19 added lines, -19 removed lines patch added patch discarded remove patch
@@ -28,10 +28,10 @@  discard block
 block discarded – undo
28 28
 OCP\JSON::callCheck();
29 29
 
30 30
 if (!array_key_exists('appid', $_POST)) {
31
-	OCP\JSON::error(array(
32
-		'message' => 'No AppId given!'
33
-	));
34
-	return;
31
+    OCP\JSON::error(array(
32
+        'message' => 'No AppId given!'
33
+    ));
34
+    return;
35 35
 }
36 36
 
37 37
 $appId = (string)$_POST['appid'];
@@ -40,24 +40,24 @@  discard block
 block discarded – undo
40 40
 $config = \OC::$server->getConfig();
41 41
 $config->setSystemValue('maintenance', true);
42 42
 try {
43
-	$installer = new \OC\Installer(
44
-		\OC::$server->getAppFetcher(),
45
-		\OC::$server->getHTTPClientService(),
46
-		\OC::$server->getTempManager(),
47
-		\OC::$server->getLogger(),
48
-		\OC::$server->getConfig()
49
-	);
50
-	$result = $installer->updateAppstoreApp($appId);
51
-	$config->setSystemValue('maintenance', false);
43
+    $installer = new \OC\Installer(
44
+        \OC::$server->getAppFetcher(),
45
+        \OC::$server->getHTTPClientService(),
46
+        \OC::$server->getTempManager(),
47
+        \OC::$server->getLogger(),
48
+        \OC::$server->getConfig()
49
+    );
50
+    $result = $installer->updateAppstoreApp($appId);
51
+    $config->setSystemValue('maintenance', false);
52 52
 } catch(Exception $ex) {
53
-	$config->setSystemValue('maintenance', false);
54
-	OC_JSON::error(array("data" => array( "message" => $ex->getMessage() )));
55
-	return;
53
+    $config->setSystemValue('maintenance', false);
54
+    OC_JSON::error(array("data" => array( "message" => $ex->getMessage() )));
55
+    return;
56 56
 }
57 57
 
58 58
 if($result !== false) {
59
-	OC_JSON::success(array('data' => array('appid' => $appId)));
59
+    OC_JSON::success(array('data' => array('appid' => $appId)));
60 60
 } else {
61
-	$l = \OC::$server->getL10N('settings');
62
-	OC_JSON::error(array("data" => array( "message" => $l->t("Couldn't update app.") )));
61
+    $l = \OC::$server->getL10N('settings');
62
+    OC_JSON::error(array("data" => array( "message" => $l->t("Couldn't update app.") )));
63 63
 }
Please login to merge, or discard this patch.
lib/private/Updater.php 2 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -431,7 +431,7 @@
 block discarded – undo
431 431
 	}
432 432
 
433 433
 	/**
434
-	 * @param array $disabledApps
434
+	 * @param string[] $disabledApps
435 435
 	 * @throws \Exception
436 436
 	 */
437 437
 	private function upgradeAppStoreApps(array $disabledApps) {
Please login to merge, or discard this patch.
Indentation   +559 added lines, -559 removed lines patch added patch discarded remove patch
@@ -51,565 +51,565 @@
 block discarded – undo
51 51
  */
52 52
 class Updater extends BasicEmitter {
53 53
 
54
-	/** @var ILogger $log */
55
-	private $log;
56
-
57
-	/** @var IConfig */
58
-	private $config;
59
-
60
-	/** @var Checker */
61
-	private $checker;
62
-
63
-	/** @var bool */
64
-	private $skip3rdPartyAppsDisable;
65
-
66
-	private $logLevelNames = [
67
-		0 => 'Debug',
68
-		1 => 'Info',
69
-		2 => 'Warning',
70
-		3 => 'Error',
71
-		4 => 'Fatal',
72
-	];
73
-
74
-	/**
75
-	 * @param IConfig $config
76
-	 * @param Checker $checker
77
-	 * @param ILogger $log
78
-	 */
79
-	public function __construct(IConfig $config,
80
-								Checker $checker,
81
-								ILogger $log = null) {
82
-		$this->log = $log;
83
-		$this->config = $config;
84
-		$this->checker = $checker;
85
-
86
-		// If at least PHP 7.0.0 is used we don't need to disable apps as we catch
87
-		// fatal errors and exceptions and disable the app just instead.
88
-		if(version_compare(phpversion(), '7.0.0', '>=')) {
89
-			$this->skip3rdPartyAppsDisable = true;
90
-		}
91
-	}
92
-
93
-	/**
94
-	 * Sets whether the update disables 3rd party apps.
95
-	 * This can be set to true to skip the disable.
96
-	 *
97
-	 * @param bool $flag false to not disable, true otherwise
98
-	 */
99
-	public function setSkip3rdPartyAppsDisable($flag) {
100
-		$this->skip3rdPartyAppsDisable = $flag;
101
-	}
102
-
103
-	/**
104
-	 * runs the update actions in maintenance mode, does not upgrade the source files
105
-	 * except the main .htaccess file
106
-	 *
107
-	 * @return bool true if the operation succeeded, false otherwise
108
-	 */
109
-	public function upgrade() {
110
-		$this->emitRepairEvents();
111
-		$this->logAllEvents();
112
-
113
-		$logLevel = $this->config->getSystemValue('loglevel', Util::WARN);
114
-		$this->emit('\OC\Updater', 'setDebugLogLevel', [ $logLevel, $this->logLevelNames[$logLevel] ]);
115
-		$this->config->setSystemValue('loglevel', Util::DEBUG);
116
-
117
-		$wasMaintenanceModeEnabled = $this->config->getSystemValue('maintenance', false);
118
-
119
-		if(!$wasMaintenanceModeEnabled) {
120
-			$this->config->setSystemValue('maintenance', true);
121
-			$this->emit('\OC\Updater', 'maintenanceEnabled');
122
-		}
123
-
124
-		$installedVersion = $this->config->getSystemValue('version', '0.0.0');
125
-		$currentVersion = implode('.', \OCP\Util::getVersion());
126
-		$this->log->debug('starting upgrade from ' . $installedVersion . ' to ' . $currentVersion, array('app' => 'core'));
127
-
128
-		$success = true;
129
-		try {
130
-			$this->doUpgrade($currentVersion, $installedVersion);
131
-		} catch (HintException $exception) {
132
-			$this->log->logException($exception, ['app' => 'core']);
133
-			$this->emit('\OC\Updater', 'failure', array($exception->getMessage() . ': ' .$exception->getHint()));
134
-			$success = false;
135
-		} catch (\Exception $exception) {
136
-			$this->log->logException($exception, ['app' => 'core']);
137
-			$this->emit('\OC\Updater', 'failure', array(get_class($exception) . ': ' .$exception->getMessage()));
138
-			$success = false;
139
-		}
140
-
141
-		$this->emit('\OC\Updater', 'updateEnd', array($success));
142
-
143
-		if(!$wasMaintenanceModeEnabled && $success) {
144
-			$this->config->setSystemValue('maintenance', false);
145
-			$this->emit('\OC\Updater', 'maintenanceDisabled');
146
-		} else {
147
-			$this->emit('\OC\Updater', 'maintenanceActive');
148
-		}
149
-
150
-		$this->emit('\OC\Updater', 'resetLogLevel', [ $logLevel, $this->logLevelNames[$logLevel] ]);
151
-		$this->config->setSystemValue('loglevel', $logLevel);
152
-		$this->config->setSystemValue('installed', true);
153
-
154
-		return $success;
155
-	}
156
-
157
-	/**
158
-	 * Return version from which this version is allowed to upgrade from
159
-	 *
160
-	 * @return array allowed previous versions per vendor
161
-	 */
162
-	private function getAllowedPreviousVersions() {
163
-		// this should really be a JSON file
164
-		require \OC::$SERVERROOT . '/version.php';
165
-		/** @var array $OC_VersionCanBeUpgradedFrom */
166
-		return $OC_VersionCanBeUpgradedFrom;
167
-	}
168
-
169
-	/**
170
-	 * Return vendor from which this version was published
171
-	 *
172
-	 * @return string Get the vendor
173
-	 */
174
-	private function getVendor() {
175
-		// this should really be a JSON file
176
-		require \OC::$SERVERROOT . '/version.php';
177
-		/** @var string $vendor */
178
-		return (string) $vendor;
179
-	}
180
-
181
-	/**
182
-	 * Whether an upgrade to a specified version is possible
183
-	 * @param string $oldVersion
184
-	 * @param string $newVersion
185
-	 * @param array $allowedPreviousVersions
186
-	 * @return bool
187
-	 */
188
-	public function isUpgradePossible($oldVersion, $newVersion, array $allowedPreviousVersions) {
189
-		$version = explode('.', $oldVersion);
190
-		$majorMinor = $version[0] . '.' . $version[1];
191
-
192
-		$currentVendor = $this->config->getAppValue('core', 'vendor', '');
193
-		if ($currentVendor === 'nextcloud') {
194
-			return isset($allowedPreviousVersions[$currentVendor][$majorMinor])
195
-				&& (version_compare($oldVersion, $newVersion, '<=') ||
196
-					$this->config->getSystemValue('debug', false));
197
-		}
198
-
199
-		// Check if the instance can be migrated
200
-		return isset($allowedPreviousVersions[$currentVendor][$majorMinor]);
201
-	}
202
-
203
-	/**
204
-	 * runs the update actions in maintenance mode, does not upgrade the source files
205
-	 * except the main .htaccess file
206
-	 *
207
-	 * @param string $currentVersion current version to upgrade to
208
-	 * @param string $installedVersion previous version from which to upgrade from
209
-	 *
210
-	 * @throws \Exception
211
-	 */
212
-	private function doUpgrade($currentVersion, $installedVersion) {
213
-		// Stop update if the update is over several major versions
214
-		$allowedPreviousVersions = $this->getAllowedPreviousVersions();
215
-		if (!$this->isUpgradePossible($installedVersion, $currentVersion, $allowedPreviousVersions)) {
216
-			throw new \Exception('Updates between multiple major versions and downgrades are unsupported.');
217
-		}
218
-
219
-		// Update .htaccess files
220
-		try {
221
-			Setup::updateHtaccess();
222
-			Setup::protectDataDirectory();
223
-		} catch (\Exception $e) {
224
-			throw new \Exception($e->getMessage());
225
-		}
226
-
227
-		// create empty file in data dir, so we can later find
228
-		// out that this is indeed an ownCloud data directory
229
-		// (in case it didn't exist before)
230
-		file_put_contents($this->config->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data') . '/.ocdata', '');
231
-
232
-		// pre-upgrade repairs
233
-		$repair = new Repair(Repair::getBeforeUpgradeRepairSteps(), \OC::$server->getEventDispatcher());
234
-		$repair->run();
235
-
236
-		$this->doCoreUpgrade();
237
-
238
-		try {
239
-			// TODO: replace with the new repair step mechanism https://github.com/owncloud/core/pull/24378
240
-			Setup::installBackgroundJobs();
241
-		} catch (\Exception $e) {
242
-			throw new \Exception($e->getMessage());
243
-		}
244
-
245
-		// update all shipped apps
246
-		$this->checkAppsRequirements();
247
-		$this->doAppUpgrade();
248
-
249
-		// upgrade appstore apps
250
-		$this->upgradeAppStoreApps(\OC::$server->getAppManager()->getInstalledApps());
251
-
252
-		// install new shipped apps on upgrade
253
-		OC_App::loadApps('authentication');
254
-		$errors = Installer::installShippedApps(true);
255
-		foreach ($errors as $appId => $exception) {
256
-			/** @var \Exception $exception */
257
-			$this->log->logException($exception, ['app' => $appId]);
258
-			$this->emit('\OC\Updater', 'failure', [$appId . ': ' . $exception->getMessage()]);
259
-		}
260
-
261
-		// post-upgrade repairs
262
-		$repair = new Repair(Repair::getRepairSteps(), \OC::$server->getEventDispatcher());
263
-		$repair->run();
264
-
265
-		//Invalidate update feed
266
-		$this->config->setAppValue('core', 'lastupdatedat', 0);
267
-
268
-		// Check for code integrity if not disabled
269
-		if(\OC::$server->getIntegrityCodeChecker()->isCodeCheckEnforced()) {
270
-			$this->emit('\OC\Updater', 'startCheckCodeIntegrity');
271
-			$this->checker->runInstanceVerification();
272
-			$this->emit('\OC\Updater', 'finishedCheckCodeIntegrity');
273
-		}
274
-
275
-		// only set the final version if everything went well
276
-		$this->config->setSystemValue('version', implode('.', Util::getVersion()));
277
-		$this->config->setAppValue('core', 'vendor', $this->getVendor());
278
-	}
279
-
280
-	protected function doCoreUpgrade() {
281
-		$this->emit('\OC\Updater', 'dbUpgradeBefore');
282
-
283
-		// do the real upgrade
284
-		\OC_DB::updateDbFromStructure(\OC::$SERVERROOT . '/db_structure.xml');
285
-
286
-		$this->emit('\OC\Updater', 'dbUpgrade');
287
-	}
288
-
289
-	/**
290
-	 * @param string $version the oc version to check app compatibility with
291
-	 */
292
-	protected function checkAppUpgrade($version) {
293
-		$apps = \OC_App::getEnabledApps();
294
-		$this->emit('\OC\Updater', 'appUpgradeCheckBefore');
295
-
296
-		foreach ($apps as $appId) {
297
-			$info = \OC_App::getAppInfo($appId);
298
-			$compatible = \OC_App::isAppCompatible($version, $info);
299
-			$isShipped = \OC_App::isShipped($appId);
300
-
301
-			if ($compatible && $isShipped && \OC_App::shouldUpgrade($appId)) {
302
-				/**
303
-				 * FIXME: The preupdate check is performed before the database migration, otherwise database changes
304
-				 * are not possible anymore within it. - Consider this when touching the code.
305
-				 * @link https://github.com/owncloud/core/issues/10980
306
-				 * @see \OC_App::updateApp
307
-				 */
308
-				if (file_exists(\OC_App::getAppPath($appId) . '/appinfo/preupdate.php')) {
309
-					$this->includePreUpdate($appId);
310
-				}
311
-				if (file_exists(\OC_App::getAppPath($appId) . '/appinfo/database.xml')) {
312
-					$this->emit('\OC\Updater', 'appSimulateUpdate', array($appId));
313
-					\OC_DB::simulateUpdateDbFromStructure(\OC_App::getAppPath($appId) . '/appinfo/database.xml');
314
-				}
315
-			}
316
-		}
317
-
318
-		$this->emit('\OC\Updater', 'appUpgradeCheck');
319
-	}
320
-
321
-	/**
322
-	 * Includes the pre-update file. Done here to prevent namespace mixups.
323
-	 * @param string $appId
324
-	 */
325
-	private function includePreUpdate($appId) {
326
-		include \OC_App::getAppPath($appId) . '/appinfo/preupdate.php';
327
-	}
328
-
329
-	/**
330
-	 * upgrades all apps within a major ownCloud upgrade. Also loads "priority"
331
-	 * (types authentication, filesystem, logging, in that order) afterwards.
332
-	 *
333
-	 * @throws NeedsUpdateException
334
-	 */
335
-	protected function doAppUpgrade() {
336
-		$apps = \OC_App::getEnabledApps();
337
-		$priorityTypes = array('authentication', 'filesystem', 'logging');
338
-		$pseudoOtherType = 'other';
339
-		$stacks = array($pseudoOtherType => array());
340
-
341
-		foreach ($apps as $appId) {
342
-			$priorityType = false;
343
-			foreach ($priorityTypes as $type) {
344
-				if(!isset($stacks[$type])) {
345
-					$stacks[$type] = array();
346
-				}
347
-				if (\OC_App::isType($appId, $type)) {
348
-					$stacks[$type][] = $appId;
349
-					$priorityType = true;
350
-					break;
351
-				}
352
-			}
353
-			if (!$priorityType) {
354
-				$stacks[$pseudoOtherType][] = $appId;
355
-			}
356
-		}
357
-		foreach ($stacks as $type => $stack) {
358
-			foreach ($stack as $appId) {
359
-				if (\OC_App::shouldUpgrade($appId)) {
360
-					$this->emit('\OC\Updater', 'appUpgradeStarted', [$appId, \OC_App::getAppVersion($appId)]);
361
-					\OC_App::updateApp($appId);
362
-					$this->emit('\OC\Updater', 'appUpgrade', [$appId, \OC_App::getAppVersion($appId)]);
363
-				}
364
-				if($type !== $pseudoOtherType) {
365
-					// load authentication, filesystem and logging apps after
366
-					// upgrading them. Other apps my need to rely on modifying
367
-					// user and/or filesystem aspects.
368
-					\OC_App::loadApp($appId);
369
-				}
370
-			}
371
-		}
372
-	}
373
-
374
-	/**
375
-	 * check if the current enabled apps are compatible with the current
376
-	 * ownCloud version. disable them if not.
377
-	 * This is important if you upgrade ownCloud and have non ported 3rd
378
-	 * party apps installed.
379
-	 *
380
-	 * @return array
381
-	 * @throws \Exception
382
-	 */
383
-	private function checkAppsRequirements() {
384
-		$isCoreUpgrade = $this->isCodeUpgrade();
385
-		$apps = OC_App::getEnabledApps();
386
-		$version = Util::getVersion();
387
-		$disabledApps = [];
388
-		foreach ($apps as $app) {
389
-			// check if the app is compatible with this version of ownCloud
390
-			$info = OC_App::getAppInfo($app);
391
-			if(!OC_App::isAppCompatible($version, $info)) {
392
-				if (OC_App::isShipped($app)) {
393
-					throw new \UnexpectedValueException('The files of the app "' . $app . '" were not correctly replaced before running the update');
394
-				}
395
-				OC_App::disable($app);
396
-				$this->emit('\OC\Updater', 'incompatibleAppDisabled', array($app));
397
-			}
398
-			// no need to disable any app in case this is a non-core upgrade
399
-			if (!$isCoreUpgrade) {
400
-				continue;
401
-			}
402
-			// shipped apps will remain enabled
403
-			if (OC_App::isShipped($app)) {
404
-				continue;
405
-			}
406
-			// authentication and session apps will remain enabled as well
407
-			if (OC_App::isType($app, ['session', 'authentication'])) {
408
-				continue;
409
-			}
410
-
411
-			// disable any other 3rd party apps if not overriden
412
-			if(!$this->skip3rdPartyAppsDisable) {
413
-				\OC_App::disable($app);
414
-				$disabledApps[]= $app;
415
-				$this->emit('\OC\Updater', 'thirdPartyAppDisabled', array($app));
416
-			};
417
-		}
418
-		return $disabledApps;
419
-	}
420
-
421
-	/**
422
-	 * @return bool
423
-	 */
424
-	private function isCodeUpgrade() {
425
-		$installedVersion = $this->config->getSystemValue('version', '0.0.0');
426
-		$currentVersion = implode('.', Util::getVersion());
427
-		if (version_compare($currentVersion, $installedVersion, '>')) {
428
-			return true;
429
-		}
430
-		return false;
431
-	}
432
-
433
-	/**
434
-	 * @param array $disabledApps
435
-	 * @throws \Exception
436
-	 */
437
-	private function upgradeAppStoreApps(array $disabledApps) {
438
-		foreach($disabledApps as $app) {
439
-			try {
440
-				$installer = new Installer(
441
-					\OC::$server->getAppFetcher(),
442
-					\OC::$server->getHTTPClientService(),
443
-					\OC::$server->getTempManager(),
444
-					$this->log,
445
-					\OC::$server->getConfig()
446
-				);
447
-				if (Installer::isUpdateAvailable($app, \OC::$server->getAppFetcher())) {
448
-					$this->emit('\OC\Updater', 'upgradeAppStoreApp', [$app]);
449
-					$installer->updateAppstoreApp($app);
450
-				}
451
-			} catch (\Exception $ex) {
452
-				$this->log->logException($ex, ['app' => 'core']);
453
-			}
454
-		}
455
-	}
456
-
457
-	/**
458
-	 * Forward messages emitted by the repair routine
459
-	 */
460
-	private function emitRepairEvents() {
461
-		$dispatcher = \OC::$server->getEventDispatcher();
462
-		$dispatcher->addListener('\OC\Repair::warning', function ($event) {
463
-			if ($event instanceof GenericEvent) {
464
-				$this->emit('\OC\Updater', 'repairWarning', $event->getArguments());
465
-			}
466
-		});
467
-		$dispatcher->addListener('\OC\Repair::error', function ($event) {
468
-			if ($event instanceof GenericEvent) {
469
-				$this->emit('\OC\Updater', 'repairError', $event->getArguments());
470
-			}
471
-		});
472
-		$dispatcher->addListener('\OC\Repair::info', function ($event) {
473
-			if ($event instanceof GenericEvent) {
474
-				$this->emit('\OC\Updater', 'repairInfo', $event->getArguments());
475
-			}
476
-		});
477
-		$dispatcher->addListener('\OC\Repair::step', function ($event) {
478
-			if ($event instanceof GenericEvent) {
479
-				$this->emit('\OC\Updater', 'repairStep', $event->getArguments());
480
-			}
481
-		});
482
-	}
483
-
484
-	private function logAllEvents() {
485
-		$log = $this->log;
486
-
487
-		$dispatcher = \OC::$server->getEventDispatcher();
488
-		$dispatcher->addListener('\OC\DB\Migrator::executeSql', function($event) use ($log) {
489
-			if (!$event instanceof GenericEvent) {
490
-				return;
491
-			}
492
-			$log->info('\OC\DB\Migrator::executeSql: ' . $event->getSubject() . ' (' . $event->getArgument(0) . ' of ' . $event->getArgument(1) . ')', ['app' => 'updater']);
493
-		});
494
-		$dispatcher->addListener('\OC\DB\Migrator::checkTable', function($event) use ($log) {
495
-			if (!$event instanceof GenericEvent) {
496
-				return;
497
-			}
498
-			$log->info('\OC\DB\Migrator::checkTable: ' . $event->getSubject() . ' (' . $event->getArgument(0) . ' of ' . $event->getArgument(1) . ')', ['app' => 'updater']);
499
-		});
500
-
501
-		$repairListener = function($event) use ($log) {
502
-			if (!$event instanceof GenericEvent) {
503
-				return;
504
-			}
505
-			switch ($event->getSubject()) {
506
-				case '\OC\Repair::startProgress':
507
-					$log->info('\OC\Repair::startProgress: Starting ... ' . $event->getArgument(1) .  ' (' . $event->getArgument(0) . ')', ['app' => 'updater']);
508
-					break;
509
-				case '\OC\Repair::advance':
510
-					$desc = $event->getArgument(1);
511
-					if (empty($desc)) {
512
-						$desc = '';
513
-					}
514
-					$log->info('\OC\Repair::advance: ' . $desc . ' (' . $event->getArgument(0) . ')', ['app' => 'updater']);
515
-
516
-					break;
517
-				case '\OC\Repair::finishProgress':
518
-					$log->info('\OC\Repair::finishProgress', ['app' => 'updater']);
519
-					break;
520
-				case '\OC\Repair::step':
521
-					$log->info('\OC\Repair::step: Repair step: ' . $event->getArgument(0), ['app' => 'updater']);
522
-					break;
523
-				case '\OC\Repair::info':
524
-					$log->info('\OC\Repair::info: Repair info: ' . $event->getArgument(0), ['app' => 'updater']);
525
-					break;
526
-				case '\OC\Repair::warning':
527
-					$log->warning('\OC\Repair::warning: Repair warning: ' . $event->getArgument(0), ['app' => 'updater']);
528
-					break;
529
-				case '\OC\Repair::error':
530
-					$log->error('\OC\Repair::error: Repair error: ' . $event->getArgument(0), ['app' => 'updater']);
531
-					break;
532
-			}
533
-		};
534
-
535
-		$dispatcher->addListener('\OC\Repair::startProgress', $repairListener);
536
-		$dispatcher->addListener('\OC\Repair::advance', $repairListener);
537
-		$dispatcher->addListener('\OC\Repair::finishProgress', $repairListener);
538
-		$dispatcher->addListener('\OC\Repair::step', $repairListener);
539
-		$dispatcher->addListener('\OC\Repair::info', $repairListener);
540
-		$dispatcher->addListener('\OC\Repair::warning', $repairListener);
541
-		$dispatcher->addListener('\OC\Repair::error', $repairListener);
542
-
543
-
544
-		$this->listen('\OC\Updater', 'maintenanceEnabled', function () use($log) {
545
-			$log->info('\OC\Updater::maintenanceEnabled: Turned on maintenance mode', ['app' => 'updater']);
546
-		});
547
-		$this->listen('\OC\Updater', 'maintenanceDisabled', function () use($log) {
548
-			$log->info('\OC\Updater::maintenanceDisabled: Turned off maintenance mode', ['app' => 'updater']);
549
-		});
550
-		$this->listen('\OC\Updater', 'maintenanceActive', function () use($log) {
551
-			$log->info('\OC\Updater::maintenanceActive: Maintenance mode is kept active', ['app' => 'updater']);
552
-		});
553
-		$this->listen('\OC\Updater', 'updateEnd', function ($success) use($log) {
554
-			if ($success) {
555
-				$log->info('\OC\Updater::updateEnd: Update successful', ['app' => 'updater']);
556
-			} else {
557
-				$log->error('\OC\Updater::updateEnd: Update failed', ['app' => 'updater']);
558
-			}
559
-		});
560
-		$this->listen('\OC\Updater', 'dbUpgradeBefore', function () use($log) {
561
-			$log->info('\OC\Updater::dbUpgradeBefore: Updating database schema', ['app' => 'updater']);
562
-		});
563
-		$this->listen('\OC\Updater', 'dbUpgrade', function () use($log) {
564
-			$log->info('\OC\Updater::dbUpgrade: Updated database', ['app' => 'updater']);
565
-		});
566
-		$this->listen('\OC\Updater', 'dbSimulateUpgradeBefore', function () use($log) {
567
-			$log->info('\OC\Updater::dbSimulateUpgradeBefore: Checking whether the database schema can be updated (this can take a long time depending on the database size)', ['app' => 'updater']);
568
-		});
569
-		$this->listen('\OC\Updater', 'dbSimulateUpgrade', function () use($log) {
570
-			$log->info('\OC\Updater::dbSimulateUpgrade: Checked database schema update', ['app' => 'updater']);
571
-		});
572
-		$this->listen('\OC\Updater', 'incompatibleAppDisabled', function ($app) use($log) {
573
-			$log->info('\OC\Updater::incompatibleAppDisabled: Disabled incompatible app: ' . $app, ['app' => 'updater']);
574
-		});
575
-		$this->listen('\OC\Updater', 'thirdPartyAppDisabled', function ($app) use ($log) {
576
-			$log->info('\OC\Updater::thirdPartyAppDisabled: Disabled 3rd-party app: ' . $app, ['app' => 'updater']);
577
-		});
578
-		$this->listen('\OC\Updater', 'upgradeAppStoreApp', function ($app) use($log) {
579
-			$log->info('\OC\Updater::upgradeAppStoreApp: Update 3rd-party app: ' . $app, ['app' => 'updater']);
580
-		});
581
-		$this->listen('\OC\Updater', 'appUpgradeCheckBefore', function () use ($log) {
582
-			$log->info('\OC\Updater::appUpgradeCheckBefore: Checking updates of apps', ['app' => 'updater']);
583
-		});
584
-		$this->listen('\OC\Updater', 'appSimulateUpdate', function ($app) use ($log) {
585
-			$log->info('\OC\Updater::appSimulateUpdate: Checking whether the database schema for <' . $app . '> can be updated (this can take a long time depending on the database size)', ['app' => 'updater']);
586
-		});
587
-		$this->listen('\OC\Updater', 'appUpgradeCheck', function () use ($log) {
588
-			$log->info('\OC\Updater::appUpgradeCheck: Checked database schema update for apps', ['app' => 'updater']);
589
-		});
590
-		$this->listen('\OC\Updater', 'appUpgradeStarted', function ($app) use ($log) {
591
-			$log->info('\OC\Updater::appUpgradeStarted: Updating <' . $app . '> ...', ['app' => 'updater']);
592
-		});
593
-		$this->listen('\OC\Updater', 'appUpgrade', function ($app, $version) use ($log) {
594
-			$log->info('\OC\Updater::appUpgrade: Updated <' . $app . '> to ' . $version, ['app' => 'updater']);
595
-		});
596
-		$this->listen('\OC\Updater', 'failure', function ($message) use($log) {
597
-			$log->error('\OC\Updater::failure: ' . $message, ['app' => 'updater']);
598
-		});
599
-		$this->listen('\OC\Updater', 'setDebugLogLevel', function () use($log) {
600
-			$log->info('\OC\Updater::setDebugLogLevel: Set log level to debug', ['app' => 'updater']);
601
-		});
602
-		$this->listen('\OC\Updater', 'resetLogLevel', function ($logLevel, $logLevelName) use($log) {
603
-			$log->info('\OC\Updater::resetLogLevel: Reset log level to ' . $logLevelName . '(' . $logLevel . ')', ['app' => 'updater']);
604
-		});
605
-		$this->listen('\OC\Updater', 'startCheckCodeIntegrity', function () use($log) {
606
-			$log->info('\OC\Updater::startCheckCodeIntegrity: Starting code integrity check...', ['app' => 'updater']);
607
-		});
608
-		$this->listen('\OC\Updater', 'finishedCheckCodeIntegrity', function () use($log) {
609
-			$log->info('\OC\Updater::finishedCheckCodeIntegrity: Finished code integrity check', ['app' => 'updater']);
610
-		});
611
-
612
-	}
54
+    /** @var ILogger $log */
55
+    private $log;
56
+
57
+    /** @var IConfig */
58
+    private $config;
59
+
60
+    /** @var Checker */
61
+    private $checker;
62
+
63
+    /** @var bool */
64
+    private $skip3rdPartyAppsDisable;
65
+
66
+    private $logLevelNames = [
67
+        0 => 'Debug',
68
+        1 => 'Info',
69
+        2 => 'Warning',
70
+        3 => 'Error',
71
+        4 => 'Fatal',
72
+    ];
73
+
74
+    /**
75
+     * @param IConfig $config
76
+     * @param Checker $checker
77
+     * @param ILogger $log
78
+     */
79
+    public function __construct(IConfig $config,
80
+                                Checker $checker,
81
+                                ILogger $log = null) {
82
+        $this->log = $log;
83
+        $this->config = $config;
84
+        $this->checker = $checker;
85
+
86
+        // If at least PHP 7.0.0 is used we don't need to disable apps as we catch
87
+        // fatal errors and exceptions and disable the app just instead.
88
+        if(version_compare(phpversion(), '7.0.0', '>=')) {
89
+            $this->skip3rdPartyAppsDisable = true;
90
+        }
91
+    }
92
+
93
+    /**
94
+     * Sets whether the update disables 3rd party apps.
95
+     * This can be set to true to skip the disable.
96
+     *
97
+     * @param bool $flag false to not disable, true otherwise
98
+     */
99
+    public function setSkip3rdPartyAppsDisable($flag) {
100
+        $this->skip3rdPartyAppsDisable = $flag;
101
+    }
102
+
103
+    /**
104
+     * runs the update actions in maintenance mode, does not upgrade the source files
105
+     * except the main .htaccess file
106
+     *
107
+     * @return bool true if the operation succeeded, false otherwise
108
+     */
109
+    public function upgrade() {
110
+        $this->emitRepairEvents();
111
+        $this->logAllEvents();
112
+
113
+        $logLevel = $this->config->getSystemValue('loglevel', Util::WARN);
114
+        $this->emit('\OC\Updater', 'setDebugLogLevel', [ $logLevel, $this->logLevelNames[$logLevel] ]);
115
+        $this->config->setSystemValue('loglevel', Util::DEBUG);
116
+
117
+        $wasMaintenanceModeEnabled = $this->config->getSystemValue('maintenance', false);
118
+
119
+        if(!$wasMaintenanceModeEnabled) {
120
+            $this->config->setSystemValue('maintenance', true);
121
+            $this->emit('\OC\Updater', 'maintenanceEnabled');
122
+        }
123
+
124
+        $installedVersion = $this->config->getSystemValue('version', '0.0.0');
125
+        $currentVersion = implode('.', \OCP\Util::getVersion());
126
+        $this->log->debug('starting upgrade from ' . $installedVersion . ' to ' . $currentVersion, array('app' => 'core'));
127
+
128
+        $success = true;
129
+        try {
130
+            $this->doUpgrade($currentVersion, $installedVersion);
131
+        } catch (HintException $exception) {
132
+            $this->log->logException($exception, ['app' => 'core']);
133
+            $this->emit('\OC\Updater', 'failure', array($exception->getMessage() . ': ' .$exception->getHint()));
134
+            $success = false;
135
+        } catch (\Exception $exception) {
136
+            $this->log->logException($exception, ['app' => 'core']);
137
+            $this->emit('\OC\Updater', 'failure', array(get_class($exception) . ': ' .$exception->getMessage()));
138
+            $success = false;
139
+        }
140
+
141
+        $this->emit('\OC\Updater', 'updateEnd', array($success));
142
+
143
+        if(!$wasMaintenanceModeEnabled && $success) {
144
+            $this->config->setSystemValue('maintenance', false);
145
+            $this->emit('\OC\Updater', 'maintenanceDisabled');
146
+        } else {
147
+            $this->emit('\OC\Updater', 'maintenanceActive');
148
+        }
149
+
150
+        $this->emit('\OC\Updater', 'resetLogLevel', [ $logLevel, $this->logLevelNames[$logLevel] ]);
151
+        $this->config->setSystemValue('loglevel', $logLevel);
152
+        $this->config->setSystemValue('installed', true);
153
+
154
+        return $success;
155
+    }
156
+
157
+    /**
158
+     * Return version from which this version is allowed to upgrade from
159
+     *
160
+     * @return array allowed previous versions per vendor
161
+     */
162
+    private function getAllowedPreviousVersions() {
163
+        // this should really be a JSON file
164
+        require \OC::$SERVERROOT . '/version.php';
165
+        /** @var array $OC_VersionCanBeUpgradedFrom */
166
+        return $OC_VersionCanBeUpgradedFrom;
167
+    }
168
+
169
+    /**
170
+     * Return vendor from which this version was published
171
+     *
172
+     * @return string Get the vendor
173
+     */
174
+    private function getVendor() {
175
+        // this should really be a JSON file
176
+        require \OC::$SERVERROOT . '/version.php';
177
+        /** @var string $vendor */
178
+        return (string) $vendor;
179
+    }
180
+
181
+    /**
182
+     * Whether an upgrade to a specified version is possible
183
+     * @param string $oldVersion
184
+     * @param string $newVersion
185
+     * @param array $allowedPreviousVersions
186
+     * @return bool
187
+     */
188
+    public function isUpgradePossible($oldVersion, $newVersion, array $allowedPreviousVersions) {
189
+        $version = explode('.', $oldVersion);
190
+        $majorMinor = $version[0] . '.' . $version[1];
191
+
192
+        $currentVendor = $this->config->getAppValue('core', 'vendor', '');
193
+        if ($currentVendor === 'nextcloud') {
194
+            return isset($allowedPreviousVersions[$currentVendor][$majorMinor])
195
+                && (version_compare($oldVersion, $newVersion, '<=') ||
196
+                    $this->config->getSystemValue('debug', false));
197
+        }
198
+
199
+        // Check if the instance can be migrated
200
+        return isset($allowedPreviousVersions[$currentVendor][$majorMinor]);
201
+    }
202
+
203
+    /**
204
+     * runs the update actions in maintenance mode, does not upgrade the source files
205
+     * except the main .htaccess file
206
+     *
207
+     * @param string $currentVersion current version to upgrade to
208
+     * @param string $installedVersion previous version from which to upgrade from
209
+     *
210
+     * @throws \Exception
211
+     */
212
+    private function doUpgrade($currentVersion, $installedVersion) {
213
+        // Stop update if the update is over several major versions
214
+        $allowedPreviousVersions = $this->getAllowedPreviousVersions();
215
+        if (!$this->isUpgradePossible($installedVersion, $currentVersion, $allowedPreviousVersions)) {
216
+            throw new \Exception('Updates between multiple major versions and downgrades are unsupported.');
217
+        }
218
+
219
+        // Update .htaccess files
220
+        try {
221
+            Setup::updateHtaccess();
222
+            Setup::protectDataDirectory();
223
+        } catch (\Exception $e) {
224
+            throw new \Exception($e->getMessage());
225
+        }
226
+
227
+        // create empty file in data dir, so we can later find
228
+        // out that this is indeed an ownCloud data directory
229
+        // (in case it didn't exist before)
230
+        file_put_contents($this->config->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data') . '/.ocdata', '');
231
+
232
+        // pre-upgrade repairs
233
+        $repair = new Repair(Repair::getBeforeUpgradeRepairSteps(), \OC::$server->getEventDispatcher());
234
+        $repair->run();
235
+
236
+        $this->doCoreUpgrade();
237
+
238
+        try {
239
+            // TODO: replace with the new repair step mechanism https://github.com/owncloud/core/pull/24378
240
+            Setup::installBackgroundJobs();
241
+        } catch (\Exception $e) {
242
+            throw new \Exception($e->getMessage());
243
+        }
244
+
245
+        // update all shipped apps
246
+        $this->checkAppsRequirements();
247
+        $this->doAppUpgrade();
248
+
249
+        // upgrade appstore apps
250
+        $this->upgradeAppStoreApps(\OC::$server->getAppManager()->getInstalledApps());
251
+
252
+        // install new shipped apps on upgrade
253
+        OC_App::loadApps('authentication');
254
+        $errors = Installer::installShippedApps(true);
255
+        foreach ($errors as $appId => $exception) {
256
+            /** @var \Exception $exception */
257
+            $this->log->logException($exception, ['app' => $appId]);
258
+            $this->emit('\OC\Updater', 'failure', [$appId . ': ' . $exception->getMessage()]);
259
+        }
260
+
261
+        // post-upgrade repairs
262
+        $repair = new Repair(Repair::getRepairSteps(), \OC::$server->getEventDispatcher());
263
+        $repair->run();
264
+
265
+        //Invalidate update feed
266
+        $this->config->setAppValue('core', 'lastupdatedat', 0);
267
+
268
+        // Check for code integrity if not disabled
269
+        if(\OC::$server->getIntegrityCodeChecker()->isCodeCheckEnforced()) {
270
+            $this->emit('\OC\Updater', 'startCheckCodeIntegrity');
271
+            $this->checker->runInstanceVerification();
272
+            $this->emit('\OC\Updater', 'finishedCheckCodeIntegrity');
273
+        }
274
+
275
+        // only set the final version if everything went well
276
+        $this->config->setSystemValue('version', implode('.', Util::getVersion()));
277
+        $this->config->setAppValue('core', 'vendor', $this->getVendor());
278
+    }
279
+
280
+    protected function doCoreUpgrade() {
281
+        $this->emit('\OC\Updater', 'dbUpgradeBefore');
282
+
283
+        // do the real upgrade
284
+        \OC_DB::updateDbFromStructure(\OC::$SERVERROOT . '/db_structure.xml');
285
+
286
+        $this->emit('\OC\Updater', 'dbUpgrade');
287
+    }
288
+
289
+    /**
290
+     * @param string $version the oc version to check app compatibility with
291
+     */
292
+    protected function checkAppUpgrade($version) {
293
+        $apps = \OC_App::getEnabledApps();
294
+        $this->emit('\OC\Updater', 'appUpgradeCheckBefore');
295
+
296
+        foreach ($apps as $appId) {
297
+            $info = \OC_App::getAppInfo($appId);
298
+            $compatible = \OC_App::isAppCompatible($version, $info);
299
+            $isShipped = \OC_App::isShipped($appId);
300
+
301
+            if ($compatible && $isShipped && \OC_App::shouldUpgrade($appId)) {
302
+                /**
303
+                 * FIXME: The preupdate check is performed before the database migration, otherwise database changes
304
+                 * are not possible anymore within it. - Consider this when touching the code.
305
+                 * @link https://github.com/owncloud/core/issues/10980
306
+                 * @see \OC_App::updateApp
307
+                 */
308
+                if (file_exists(\OC_App::getAppPath($appId) . '/appinfo/preupdate.php')) {
309
+                    $this->includePreUpdate($appId);
310
+                }
311
+                if (file_exists(\OC_App::getAppPath($appId) . '/appinfo/database.xml')) {
312
+                    $this->emit('\OC\Updater', 'appSimulateUpdate', array($appId));
313
+                    \OC_DB::simulateUpdateDbFromStructure(\OC_App::getAppPath($appId) . '/appinfo/database.xml');
314
+                }
315
+            }
316
+        }
317
+
318
+        $this->emit('\OC\Updater', 'appUpgradeCheck');
319
+    }
320
+
321
+    /**
322
+     * Includes the pre-update file. Done here to prevent namespace mixups.
323
+     * @param string $appId
324
+     */
325
+    private function includePreUpdate($appId) {
326
+        include \OC_App::getAppPath($appId) . '/appinfo/preupdate.php';
327
+    }
328
+
329
+    /**
330
+     * upgrades all apps within a major ownCloud upgrade. Also loads "priority"
331
+     * (types authentication, filesystem, logging, in that order) afterwards.
332
+     *
333
+     * @throws NeedsUpdateException
334
+     */
335
+    protected function doAppUpgrade() {
336
+        $apps = \OC_App::getEnabledApps();
337
+        $priorityTypes = array('authentication', 'filesystem', 'logging');
338
+        $pseudoOtherType = 'other';
339
+        $stacks = array($pseudoOtherType => array());
340
+
341
+        foreach ($apps as $appId) {
342
+            $priorityType = false;
343
+            foreach ($priorityTypes as $type) {
344
+                if(!isset($stacks[$type])) {
345
+                    $stacks[$type] = array();
346
+                }
347
+                if (\OC_App::isType($appId, $type)) {
348
+                    $stacks[$type][] = $appId;
349
+                    $priorityType = true;
350
+                    break;
351
+                }
352
+            }
353
+            if (!$priorityType) {
354
+                $stacks[$pseudoOtherType][] = $appId;
355
+            }
356
+        }
357
+        foreach ($stacks as $type => $stack) {
358
+            foreach ($stack as $appId) {
359
+                if (\OC_App::shouldUpgrade($appId)) {
360
+                    $this->emit('\OC\Updater', 'appUpgradeStarted', [$appId, \OC_App::getAppVersion($appId)]);
361
+                    \OC_App::updateApp($appId);
362
+                    $this->emit('\OC\Updater', 'appUpgrade', [$appId, \OC_App::getAppVersion($appId)]);
363
+                }
364
+                if($type !== $pseudoOtherType) {
365
+                    // load authentication, filesystem and logging apps after
366
+                    // upgrading them. Other apps my need to rely on modifying
367
+                    // user and/or filesystem aspects.
368
+                    \OC_App::loadApp($appId);
369
+                }
370
+            }
371
+        }
372
+    }
373
+
374
+    /**
375
+     * check if the current enabled apps are compatible with the current
376
+     * ownCloud version. disable them if not.
377
+     * This is important if you upgrade ownCloud and have non ported 3rd
378
+     * party apps installed.
379
+     *
380
+     * @return array
381
+     * @throws \Exception
382
+     */
383
+    private function checkAppsRequirements() {
384
+        $isCoreUpgrade = $this->isCodeUpgrade();
385
+        $apps = OC_App::getEnabledApps();
386
+        $version = Util::getVersion();
387
+        $disabledApps = [];
388
+        foreach ($apps as $app) {
389
+            // check if the app is compatible with this version of ownCloud
390
+            $info = OC_App::getAppInfo($app);
391
+            if(!OC_App::isAppCompatible($version, $info)) {
392
+                if (OC_App::isShipped($app)) {
393
+                    throw new \UnexpectedValueException('The files of the app "' . $app . '" were not correctly replaced before running the update');
394
+                }
395
+                OC_App::disable($app);
396
+                $this->emit('\OC\Updater', 'incompatibleAppDisabled', array($app));
397
+            }
398
+            // no need to disable any app in case this is a non-core upgrade
399
+            if (!$isCoreUpgrade) {
400
+                continue;
401
+            }
402
+            // shipped apps will remain enabled
403
+            if (OC_App::isShipped($app)) {
404
+                continue;
405
+            }
406
+            // authentication and session apps will remain enabled as well
407
+            if (OC_App::isType($app, ['session', 'authentication'])) {
408
+                continue;
409
+            }
410
+
411
+            // disable any other 3rd party apps if not overriden
412
+            if(!$this->skip3rdPartyAppsDisable) {
413
+                \OC_App::disable($app);
414
+                $disabledApps[]= $app;
415
+                $this->emit('\OC\Updater', 'thirdPartyAppDisabled', array($app));
416
+            };
417
+        }
418
+        return $disabledApps;
419
+    }
420
+
421
+    /**
422
+     * @return bool
423
+     */
424
+    private function isCodeUpgrade() {
425
+        $installedVersion = $this->config->getSystemValue('version', '0.0.0');
426
+        $currentVersion = implode('.', Util::getVersion());
427
+        if (version_compare($currentVersion, $installedVersion, '>')) {
428
+            return true;
429
+        }
430
+        return false;
431
+    }
432
+
433
+    /**
434
+     * @param array $disabledApps
435
+     * @throws \Exception
436
+     */
437
+    private function upgradeAppStoreApps(array $disabledApps) {
438
+        foreach($disabledApps as $app) {
439
+            try {
440
+                $installer = new Installer(
441
+                    \OC::$server->getAppFetcher(),
442
+                    \OC::$server->getHTTPClientService(),
443
+                    \OC::$server->getTempManager(),
444
+                    $this->log,
445
+                    \OC::$server->getConfig()
446
+                );
447
+                if (Installer::isUpdateAvailable($app, \OC::$server->getAppFetcher())) {
448
+                    $this->emit('\OC\Updater', 'upgradeAppStoreApp', [$app]);
449
+                    $installer->updateAppstoreApp($app);
450
+                }
451
+            } catch (\Exception $ex) {
452
+                $this->log->logException($ex, ['app' => 'core']);
453
+            }
454
+        }
455
+    }
456
+
457
+    /**
458
+     * Forward messages emitted by the repair routine
459
+     */
460
+    private function emitRepairEvents() {
461
+        $dispatcher = \OC::$server->getEventDispatcher();
462
+        $dispatcher->addListener('\OC\Repair::warning', function ($event) {
463
+            if ($event instanceof GenericEvent) {
464
+                $this->emit('\OC\Updater', 'repairWarning', $event->getArguments());
465
+            }
466
+        });
467
+        $dispatcher->addListener('\OC\Repair::error', function ($event) {
468
+            if ($event instanceof GenericEvent) {
469
+                $this->emit('\OC\Updater', 'repairError', $event->getArguments());
470
+            }
471
+        });
472
+        $dispatcher->addListener('\OC\Repair::info', function ($event) {
473
+            if ($event instanceof GenericEvent) {
474
+                $this->emit('\OC\Updater', 'repairInfo', $event->getArguments());
475
+            }
476
+        });
477
+        $dispatcher->addListener('\OC\Repair::step', function ($event) {
478
+            if ($event instanceof GenericEvent) {
479
+                $this->emit('\OC\Updater', 'repairStep', $event->getArguments());
480
+            }
481
+        });
482
+    }
483
+
484
+    private function logAllEvents() {
485
+        $log = $this->log;
486
+
487
+        $dispatcher = \OC::$server->getEventDispatcher();
488
+        $dispatcher->addListener('\OC\DB\Migrator::executeSql', function($event) use ($log) {
489
+            if (!$event instanceof GenericEvent) {
490
+                return;
491
+            }
492
+            $log->info('\OC\DB\Migrator::executeSql: ' . $event->getSubject() . ' (' . $event->getArgument(0) . ' of ' . $event->getArgument(1) . ')', ['app' => 'updater']);
493
+        });
494
+        $dispatcher->addListener('\OC\DB\Migrator::checkTable', function($event) use ($log) {
495
+            if (!$event instanceof GenericEvent) {
496
+                return;
497
+            }
498
+            $log->info('\OC\DB\Migrator::checkTable: ' . $event->getSubject() . ' (' . $event->getArgument(0) . ' of ' . $event->getArgument(1) . ')', ['app' => 'updater']);
499
+        });
500
+
501
+        $repairListener = function($event) use ($log) {
502
+            if (!$event instanceof GenericEvent) {
503
+                return;
504
+            }
505
+            switch ($event->getSubject()) {
506
+                case '\OC\Repair::startProgress':
507
+                    $log->info('\OC\Repair::startProgress: Starting ... ' . $event->getArgument(1) .  ' (' . $event->getArgument(0) . ')', ['app' => 'updater']);
508
+                    break;
509
+                case '\OC\Repair::advance':
510
+                    $desc = $event->getArgument(1);
511
+                    if (empty($desc)) {
512
+                        $desc = '';
513
+                    }
514
+                    $log->info('\OC\Repair::advance: ' . $desc . ' (' . $event->getArgument(0) . ')', ['app' => 'updater']);
515
+
516
+                    break;
517
+                case '\OC\Repair::finishProgress':
518
+                    $log->info('\OC\Repair::finishProgress', ['app' => 'updater']);
519
+                    break;
520
+                case '\OC\Repair::step':
521
+                    $log->info('\OC\Repair::step: Repair step: ' . $event->getArgument(0), ['app' => 'updater']);
522
+                    break;
523
+                case '\OC\Repair::info':
524
+                    $log->info('\OC\Repair::info: Repair info: ' . $event->getArgument(0), ['app' => 'updater']);
525
+                    break;
526
+                case '\OC\Repair::warning':
527
+                    $log->warning('\OC\Repair::warning: Repair warning: ' . $event->getArgument(0), ['app' => 'updater']);
528
+                    break;
529
+                case '\OC\Repair::error':
530
+                    $log->error('\OC\Repair::error: Repair error: ' . $event->getArgument(0), ['app' => 'updater']);
531
+                    break;
532
+            }
533
+        };
534
+
535
+        $dispatcher->addListener('\OC\Repair::startProgress', $repairListener);
536
+        $dispatcher->addListener('\OC\Repair::advance', $repairListener);
537
+        $dispatcher->addListener('\OC\Repair::finishProgress', $repairListener);
538
+        $dispatcher->addListener('\OC\Repair::step', $repairListener);
539
+        $dispatcher->addListener('\OC\Repair::info', $repairListener);
540
+        $dispatcher->addListener('\OC\Repair::warning', $repairListener);
541
+        $dispatcher->addListener('\OC\Repair::error', $repairListener);
542
+
543
+
544
+        $this->listen('\OC\Updater', 'maintenanceEnabled', function () use($log) {
545
+            $log->info('\OC\Updater::maintenanceEnabled: Turned on maintenance mode', ['app' => 'updater']);
546
+        });
547
+        $this->listen('\OC\Updater', 'maintenanceDisabled', function () use($log) {
548
+            $log->info('\OC\Updater::maintenanceDisabled: Turned off maintenance mode', ['app' => 'updater']);
549
+        });
550
+        $this->listen('\OC\Updater', 'maintenanceActive', function () use($log) {
551
+            $log->info('\OC\Updater::maintenanceActive: Maintenance mode is kept active', ['app' => 'updater']);
552
+        });
553
+        $this->listen('\OC\Updater', 'updateEnd', function ($success) use($log) {
554
+            if ($success) {
555
+                $log->info('\OC\Updater::updateEnd: Update successful', ['app' => 'updater']);
556
+            } else {
557
+                $log->error('\OC\Updater::updateEnd: Update failed', ['app' => 'updater']);
558
+            }
559
+        });
560
+        $this->listen('\OC\Updater', 'dbUpgradeBefore', function () use($log) {
561
+            $log->info('\OC\Updater::dbUpgradeBefore: Updating database schema', ['app' => 'updater']);
562
+        });
563
+        $this->listen('\OC\Updater', 'dbUpgrade', function () use($log) {
564
+            $log->info('\OC\Updater::dbUpgrade: Updated database', ['app' => 'updater']);
565
+        });
566
+        $this->listen('\OC\Updater', 'dbSimulateUpgradeBefore', function () use($log) {
567
+            $log->info('\OC\Updater::dbSimulateUpgradeBefore: Checking whether the database schema can be updated (this can take a long time depending on the database size)', ['app' => 'updater']);
568
+        });
569
+        $this->listen('\OC\Updater', 'dbSimulateUpgrade', function () use($log) {
570
+            $log->info('\OC\Updater::dbSimulateUpgrade: Checked database schema update', ['app' => 'updater']);
571
+        });
572
+        $this->listen('\OC\Updater', 'incompatibleAppDisabled', function ($app) use($log) {
573
+            $log->info('\OC\Updater::incompatibleAppDisabled: Disabled incompatible app: ' . $app, ['app' => 'updater']);
574
+        });
575
+        $this->listen('\OC\Updater', 'thirdPartyAppDisabled', function ($app) use ($log) {
576
+            $log->info('\OC\Updater::thirdPartyAppDisabled: Disabled 3rd-party app: ' . $app, ['app' => 'updater']);
577
+        });
578
+        $this->listen('\OC\Updater', 'upgradeAppStoreApp', function ($app) use($log) {
579
+            $log->info('\OC\Updater::upgradeAppStoreApp: Update 3rd-party app: ' . $app, ['app' => 'updater']);
580
+        });
581
+        $this->listen('\OC\Updater', 'appUpgradeCheckBefore', function () use ($log) {
582
+            $log->info('\OC\Updater::appUpgradeCheckBefore: Checking updates of apps', ['app' => 'updater']);
583
+        });
584
+        $this->listen('\OC\Updater', 'appSimulateUpdate', function ($app) use ($log) {
585
+            $log->info('\OC\Updater::appSimulateUpdate: Checking whether the database schema for <' . $app . '> can be updated (this can take a long time depending on the database size)', ['app' => 'updater']);
586
+        });
587
+        $this->listen('\OC\Updater', 'appUpgradeCheck', function () use ($log) {
588
+            $log->info('\OC\Updater::appUpgradeCheck: Checked database schema update for apps', ['app' => 'updater']);
589
+        });
590
+        $this->listen('\OC\Updater', 'appUpgradeStarted', function ($app) use ($log) {
591
+            $log->info('\OC\Updater::appUpgradeStarted: Updating <' . $app . '> ...', ['app' => 'updater']);
592
+        });
593
+        $this->listen('\OC\Updater', 'appUpgrade', function ($app, $version) use ($log) {
594
+            $log->info('\OC\Updater::appUpgrade: Updated <' . $app . '> to ' . $version, ['app' => 'updater']);
595
+        });
596
+        $this->listen('\OC\Updater', 'failure', function ($message) use($log) {
597
+            $log->error('\OC\Updater::failure: ' . $message, ['app' => 'updater']);
598
+        });
599
+        $this->listen('\OC\Updater', 'setDebugLogLevel', function () use($log) {
600
+            $log->info('\OC\Updater::setDebugLogLevel: Set log level to debug', ['app' => 'updater']);
601
+        });
602
+        $this->listen('\OC\Updater', 'resetLogLevel', function ($logLevel, $logLevelName) use($log) {
603
+            $log->info('\OC\Updater::resetLogLevel: Reset log level to ' . $logLevelName . '(' . $logLevel . ')', ['app' => 'updater']);
604
+        });
605
+        $this->listen('\OC\Updater', 'startCheckCodeIntegrity', function () use($log) {
606
+            $log->info('\OC\Updater::startCheckCodeIntegrity: Starting code integrity check...', ['app' => 'updater']);
607
+        });
608
+        $this->listen('\OC\Updater', 'finishedCheckCodeIntegrity', function () use($log) {
609
+            $log->info('\OC\Updater::finishedCheckCodeIntegrity: Finished code integrity check', ['app' => 'updater']);
610
+        });
611
+
612
+    }
613 613
 
614 614
 }
615 615
 
Please login to merge, or discard this patch.
settings/Controller/AppSettingsController.php 2 patches
Indentation   +377 added lines, -377 removed lines patch added patch discarded remove patch
@@ -48,381 +48,381 @@
 block discarded – undo
48 48
  * @package OC\Settings\Controller
49 49
  */
50 50
 class AppSettingsController extends Controller {
51
-	const CAT_ENABLED = 0;
52
-	const CAT_DISABLED = 1;
53
-	const CAT_ALL_INSTALLED = 2;
54
-	const CAT_APP_BUNDLES = 3;
55
-
56
-	/** @var \OCP\IL10N */
57
-	private $l10n;
58
-	/** @var IConfig */
59
-	private $config;
60
-	/** @var INavigationManager */
61
-	private $navigationManager;
62
-	/** @var IAppManager */
63
-	private $appManager;
64
-	/** @var CategoryFetcher */
65
-	private $categoryFetcher;
66
-	/** @var AppFetcher */
67
-	private $appFetcher;
68
-	/** @var IFactory */
69
-	private $l10nFactory;
70
-	/** @var BundleFetcher */
71
-	private $bundleFetcher;
72
-
73
-	/**
74
-	 * @param string $appName
75
-	 * @param IRequest $request
76
-	 * @param IL10N $l10n
77
-	 * @param IConfig $config
78
-	 * @param INavigationManager $navigationManager
79
-	 * @param IAppManager $appManager
80
-	 * @param CategoryFetcher $categoryFetcher
81
-	 * @param AppFetcher $appFetcher
82
-	 * @param IFactory $l10nFactory
83
-	 * @param BundleFetcher $bundleFetcher
84
-	 */
85
-	public function __construct($appName,
86
-								IRequest $request,
87
-								IL10N $l10n,
88
-								IConfig $config,
89
-								INavigationManager $navigationManager,
90
-								IAppManager $appManager,
91
-								CategoryFetcher $categoryFetcher,
92
-								AppFetcher $appFetcher,
93
-								IFactory $l10nFactory,
94
-								BundleFetcher $bundleFetcher) {
95
-		parent::__construct($appName, $request);
96
-		$this->l10n = $l10n;
97
-		$this->config = $config;
98
-		$this->navigationManager = $navigationManager;
99
-		$this->appManager = $appManager;
100
-		$this->categoryFetcher = $categoryFetcher;
101
-		$this->appFetcher = $appFetcher;
102
-		$this->l10nFactory = $l10nFactory;
103
-		$this->bundleFetcher = $bundleFetcher;
104
-	}
105
-
106
-	/**
107
-	 * @NoCSRFRequired
108
-	 *
109
-	 * @param string $category
110
-	 * @return TemplateResponse
111
-	 */
112
-	public function viewApps($category = '') {
113
-		if ($category === '') {
114
-			$category = 'installed';
115
-		}
116
-
117
-		$params = [];
118
-		$params['category'] = $category;
119
-		$params['appstoreEnabled'] = $this->config->getSystemValue('appstoreenabled', true) === true;
120
-		$this->navigationManager->setActiveEntry('core_apps');
121
-
122
-		$templateResponse = new TemplateResponse($this->appName, 'apps', $params, 'user');
123
-		$policy = new ContentSecurityPolicy();
124
-		$policy->addAllowedImageDomain('https://usercontent.apps.nextcloud.com');
125
-		$templateResponse->setContentSecurityPolicy($policy);
126
-
127
-		return $templateResponse;
128
-	}
129
-
130
-	private function getAllCategories() {
131
-		$currentLanguage = substr($this->l10nFactory->findLanguage(), 0, 2);
132
-
133
-		$formattedCategories = [
134
-			['id' => self::CAT_ALL_INSTALLED, 'ident' => 'installed', 'displayName' => (string)$this->l10n->t('Your apps')],
135
-			['id' => self::CAT_ENABLED, 'ident' => 'enabled', 'displayName' => (string)$this->l10n->t('Enabled apps')],
136
-			['id' => self::CAT_APP_BUNDLES, 'ident' => 'app-bundles', 'displayName' => (string)$this->l10n->t('App bundles')],
137
-			['id' => self::CAT_DISABLED, 'ident' => 'disabled', 'displayName' => (string)$this->l10n->t('Disabled apps')],
138
-		];
139
-		$categories = $this->categoryFetcher->get();
140
-		foreach($categories as $category) {
141
-			$formattedCategories[] = [
142
-				'id' => $category['id'],
143
-				'ident' => $category['id'],
144
-				'displayName' => isset($category['translations'][$currentLanguage]['name']) ? $category['translations'][$currentLanguage]['name'] : $category['translations']['en']['name'],
145
-			];
146
-		}
147
-
148
-		return $formattedCategories;
149
-	}
150
-
151
-	/**
152
-	 * Get all available categories
153
-	 *
154
-	 * @return JSONResponse
155
-	 */
156
-	public function listCategories() {
157
-		return new JSONResponse($this->getAllCategories());
158
-	}
159
-
160
-	/**
161
-	 * Get all apps for a category
162
-	 *
163
-	 * @param string $requestedCategory
164
-	 * @return array
165
-	 */
166
-	private function getAppsForCategory($requestedCategory) {
167
-		$versionParser = new VersionParser();
168
-		$formattedApps = [];
169
-		$apps = $this->appFetcher->get();
170
-		foreach($apps as $app) {
171
-			if (isset($app['isFeatured'])) {
172
-				$app['featured'] = $app['isFeatured'];
173
-			}
174
-
175
-			// Skip all apps not in the requested category
176
-			$isInCategory = false;
177
-			foreach($app['categories'] as $category) {
178
-				if($category === $requestedCategory) {
179
-					$isInCategory = true;
180
-				}
181
-			}
182
-			if(!$isInCategory) {
183
-				continue;
184
-			}
185
-
186
-			$nextCloudVersion = $versionParser->getVersion($app['releases'][0]['rawPlatformVersionSpec']);
187
-			$nextCloudVersionDependencies = [];
188
-			if($nextCloudVersion->getMinimumVersion() !== '') {
189
-				$nextCloudVersionDependencies['nextcloud']['@attributes']['min-version'] = $nextCloudVersion->getMinimumVersion();
190
-			}
191
-			if($nextCloudVersion->getMaximumVersion() !== '') {
192
-				$nextCloudVersionDependencies['nextcloud']['@attributes']['max-version'] = $nextCloudVersion->getMaximumVersion();
193
-			}
194
-			$phpVersion = $versionParser->getVersion($app['releases'][0]['rawPhpVersionSpec']);
195
-			$existsLocally = (\OC_App::getAppPath($app['id']) !== false) ? true : false;
196
-			$phpDependencies = [];
197
-			if($phpVersion->getMinimumVersion() !== '') {
198
-				$phpDependencies['php']['@attributes']['min-version'] = $phpVersion->getMinimumVersion();
199
-			}
200
-			if($phpVersion->getMaximumVersion() !== '') {
201
-				$phpDependencies['php']['@attributes']['max-version'] = $phpVersion->getMaximumVersion();
202
-			}
203
-			if(isset($app['releases'][0]['minIntSize'])) {
204
-				$phpDependencies['php']['@attributes']['min-int-size'] = $app['releases'][0]['minIntSize'];
205
-			}
206
-			$authors = '';
207
-			foreach($app['authors'] as $key => $author) {
208
-				$authors .= $author['name'];
209
-				if($key !== count($app['authors']) - 1) {
210
-					$authors .= ', ';
211
-				}
212
-			}
213
-
214
-			$currentLanguage = substr(\OC::$server->getL10NFactory()->findLanguage(), 0, 2);
215
-			$enabledValue = $this->config->getAppValue($app['id'], 'enabled', 'no');
216
-			$groups = null;
217
-			if($enabledValue !== 'no' && $enabledValue !== 'yes') {
218
-				$groups = $enabledValue;
219
-			}
220
-
221
-			$currentVersion = '';
222
-			if($this->appManager->isInstalled($app['id'])) {
223
-				$currentVersion = \OC_App::getAppVersion($app['id']);
224
-			} else {
225
-				$currentLanguage = $app['releases'][0]['version'];
226
-			}
227
-
228
-			$formattedApps[] = [
229
-				'id' => $app['id'],
230
-				'name' => isset($app['translations'][$currentLanguage]['name']) ? $app['translations'][$currentLanguage]['name'] : $app['translations']['en']['name'],
231
-				'description' => isset($app['translations'][$currentLanguage]['description']) ? $app['translations'][$currentLanguage]['description'] : $app['translations']['en']['description'],
232
-				'license' => $app['releases'][0]['licenses'],
233
-				'author' => $authors,
234
-				'shipped' => false,
235
-				'version' => $currentVersion,
236
-				'default_enable' => '',
237
-				'types' => [],
238
-				'documentation' => [
239
-					'admin' => $app['adminDocs'],
240
-					'user' => $app['userDocs'],
241
-					'developer' => $app['developerDocs']
242
-				],
243
-				'website' => $app['website'],
244
-				'bugs' => $app['issueTracker'],
245
-				'detailpage' => $app['website'],
246
-				'dependencies' => array_merge(
247
-					$nextCloudVersionDependencies,
248
-					$phpDependencies
249
-				),
250
-				'level' => ($app['featured'] === true) ? 200 : 100,
251
-				'missingMaxOwnCloudVersion' => false,
252
-				'missingMinOwnCloudVersion' => false,
253
-				'canInstall' => true,
254
-				'preview' => isset($app['screenshots'][0]['url']) ? 'https://usercontent.apps.nextcloud.com/'.base64_encode($app['screenshots'][0]['url']) : '',
255
-				'score' => $app['ratingOverall'],
256
-				'ratingNumOverall' => $app['ratingNumOverall'],
257
-				'ratingNumThresholdReached' => $app['ratingNumOverall'] > 5 ? true : false,
258
-				'removable' => $existsLocally,
259
-				'active' => $this->appManager->isEnabledForUser($app['id']),
260
-				'needsDownload' => !$existsLocally,
261
-				'groups' => $groups,
262
-				'fromAppStore' => true,
263
-			];
264
-
265
-
266
-			$appFetcher = \OC::$server->getAppFetcher();
267
-			$newVersion = \OC\Installer::isUpdateAvailable($app['id'], $appFetcher);
268
-			if($newVersion && $this->appManager->isInstalled($app['id'])) {
269
-				$formattedApps[count($formattedApps)-1]['update'] = $newVersion;
270
-			}
271
-		}
272
-
273
-		return $formattedApps;
274
-	}
275
-
276
-	/**
277
-	 * Get all available apps in a category
278
-	 *
279
-	 * @param string $category
280
-	 * @return JSONResponse
281
-	 */
282
-	public function listApps($category = '') {
283
-		$appClass = new \OC_App();
284
-
285
-		switch ($category) {
286
-			// installed apps
287
-			case 'installed':
288
-				$apps = $appClass->listAllApps();
289
-
290
-				foreach($apps as $key => $app) {
291
-					$newVersion = \OC\Installer::isUpdateAvailable($app['id'], $this->appFetcher);
292
-					$apps[$key]['update'] = $newVersion;
293
-				}
294
-
295
-				usort($apps, function ($a, $b) {
296
-					$a = (string)$a['name'];
297
-					$b = (string)$b['name'];
298
-					if ($a === $b) {
299
-						return 0;
300
-					}
301
-					return ($a < $b) ? -1 : 1;
302
-				});
303
-				break;
304
-			// enabled apps
305
-			case 'enabled':
306
-				$apps = $appClass->listAllApps();
307
-				$apps = array_filter($apps, function ($app) {
308
-					return $app['active'];
309
-				});
310
-
311
-				foreach($apps as $key => $app) {
312
-					$newVersion = \OC\Installer::isUpdateAvailable($app['id'], $this->appFetcher);
313
-					$apps[$key]['update'] = $newVersion;
314
-				}
315
-
316
-				usort($apps, function ($a, $b) {
317
-					$a = (string)$a['name'];
318
-					$b = (string)$b['name'];
319
-					if ($a === $b) {
320
-						return 0;
321
-					}
322
-					return ($a < $b) ? -1 : 1;
323
-				});
324
-				break;
325
-			// disabled  apps
326
-			case 'disabled':
327
-				$apps = $appClass->listAllApps();
328
-				$apps = array_filter($apps, function ($app) {
329
-					return !$app['active'];
330
-				});
331
-
332
-				$apps = array_map(function ($app) {
333
-					$newVersion = \OC\Installer::isUpdateAvailable($app['id'], $this->appFetcher);
334
-					if ($newVersion !== false) {
335
-						$app['update'] = $newVersion;
336
-					}
337
-					return $app;
338
-				}, $apps);
339
-
340
-				usort($apps, function ($a, $b) {
341
-					$a = (string)$a['name'];
342
-					$b = (string)$b['name'];
343
-					if ($a === $b) {
344
-						return 0;
345
-					}
346
-					return ($a < $b) ? -1 : 1;
347
-				});
348
-				break;
349
-			case 'app-bundles':
350
-				$bundles = $this->bundleFetcher->getBundles();
351
-				$apps = [];
352
-				foreach($bundles as $bundle) {
353
-					$newCategory = true;
354
-					$allApps = $appClass->listAllApps();
355
-					$categories = $this->getAllCategories();
356
-					foreach($categories as $singleCategory) {
357
-						$newApps = $this->getAppsForCategory($singleCategory['id']);
358
-						foreach($allApps as $app) {
359
-							foreach($newApps as $key => $newApp) {
360
-								if($app['id'] === $newApp['id']) {
361
-									unset($newApps[$key]);
362
-								}
363
-							}
364
-						}
365
-						$allApps = array_merge($allApps, $newApps);
366
-					}
367
-
368
-					foreach($bundle->getAppIdentifiers() as $identifier) {
369
-						foreach($allApps as $app) {
370
-							if($app['id'] === $identifier) {
371
-								if($newCategory) {
372
-									$app['newCategory'] = true;
373
-									$app['categoryName'] = $bundle->getName();
374
-								}
375
-								$newCategory = false;
376
-								$apps[] = $app;
377
-								continue;
378
-							}
379
-						}
380
-					}
381
-				}
382
-				break;
383
-			default:
384
-				$apps = $this->getAppsForCategory($category);
385
-
386
-				// sort by score
387
-				usort($apps, function ($a, $b) {
388
-					$a = (int)$a['score'];
389
-					$b = (int)$b['score'];
390
-					if ($a === $b) {
391
-						return 0;
392
-					}
393
-					return ($a > $b) ? -1 : 1;
394
-				});
395
-				break;
396
-		}
397
-
398
-		// fix groups to be an array
399
-		$dependencyAnalyzer = new DependencyAnalyzer(new Platform($this->config), $this->l10n);
400
-		$apps = array_map(function($app) use ($dependencyAnalyzer) {
401
-
402
-			// fix groups
403
-			$groups = array();
404
-			if (is_string($app['groups'])) {
405
-				$groups = json_decode($app['groups']);
406
-			}
407
-			$app['groups'] = $groups;
408
-			$app['canUnInstall'] = !$app['active'] && $app['removable'];
409
-
410
-			// fix licence vs license
411
-			if (isset($app['license']) && !isset($app['licence'])) {
412
-				$app['licence'] = $app['license'];
413
-			}
414
-
415
-			// analyse dependencies
416
-			$missing = $dependencyAnalyzer->analyze($app);
417
-			$app['canInstall'] = empty($missing);
418
-			$app['missingDependencies'] = $missing;
419
-
420
-			$app['missingMinOwnCloudVersion'] = !isset($app['dependencies']['nextcloud']['@attributes']['min-version']);
421
-			$app['missingMaxOwnCloudVersion'] = !isset($app['dependencies']['nextcloud']['@attributes']['max-version']);
422
-
423
-			return $app;
424
-		}, $apps);
425
-
426
-		return new JSONResponse(['apps' => $apps, 'status' => 'success']);
427
-	}
51
+    const CAT_ENABLED = 0;
52
+    const CAT_DISABLED = 1;
53
+    const CAT_ALL_INSTALLED = 2;
54
+    const CAT_APP_BUNDLES = 3;
55
+
56
+    /** @var \OCP\IL10N */
57
+    private $l10n;
58
+    /** @var IConfig */
59
+    private $config;
60
+    /** @var INavigationManager */
61
+    private $navigationManager;
62
+    /** @var IAppManager */
63
+    private $appManager;
64
+    /** @var CategoryFetcher */
65
+    private $categoryFetcher;
66
+    /** @var AppFetcher */
67
+    private $appFetcher;
68
+    /** @var IFactory */
69
+    private $l10nFactory;
70
+    /** @var BundleFetcher */
71
+    private $bundleFetcher;
72
+
73
+    /**
74
+     * @param string $appName
75
+     * @param IRequest $request
76
+     * @param IL10N $l10n
77
+     * @param IConfig $config
78
+     * @param INavigationManager $navigationManager
79
+     * @param IAppManager $appManager
80
+     * @param CategoryFetcher $categoryFetcher
81
+     * @param AppFetcher $appFetcher
82
+     * @param IFactory $l10nFactory
83
+     * @param BundleFetcher $bundleFetcher
84
+     */
85
+    public function __construct($appName,
86
+                                IRequest $request,
87
+                                IL10N $l10n,
88
+                                IConfig $config,
89
+                                INavigationManager $navigationManager,
90
+                                IAppManager $appManager,
91
+                                CategoryFetcher $categoryFetcher,
92
+                                AppFetcher $appFetcher,
93
+                                IFactory $l10nFactory,
94
+                                BundleFetcher $bundleFetcher) {
95
+        parent::__construct($appName, $request);
96
+        $this->l10n = $l10n;
97
+        $this->config = $config;
98
+        $this->navigationManager = $navigationManager;
99
+        $this->appManager = $appManager;
100
+        $this->categoryFetcher = $categoryFetcher;
101
+        $this->appFetcher = $appFetcher;
102
+        $this->l10nFactory = $l10nFactory;
103
+        $this->bundleFetcher = $bundleFetcher;
104
+    }
105
+
106
+    /**
107
+     * @NoCSRFRequired
108
+     *
109
+     * @param string $category
110
+     * @return TemplateResponse
111
+     */
112
+    public function viewApps($category = '') {
113
+        if ($category === '') {
114
+            $category = 'installed';
115
+        }
116
+
117
+        $params = [];
118
+        $params['category'] = $category;
119
+        $params['appstoreEnabled'] = $this->config->getSystemValue('appstoreenabled', true) === true;
120
+        $this->navigationManager->setActiveEntry('core_apps');
121
+
122
+        $templateResponse = new TemplateResponse($this->appName, 'apps', $params, 'user');
123
+        $policy = new ContentSecurityPolicy();
124
+        $policy->addAllowedImageDomain('https://usercontent.apps.nextcloud.com');
125
+        $templateResponse->setContentSecurityPolicy($policy);
126
+
127
+        return $templateResponse;
128
+    }
129
+
130
+    private function getAllCategories() {
131
+        $currentLanguage = substr($this->l10nFactory->findLanguage(), 0, 2);
132
+
133
+        $formattedCategories = [
134
+            ['id' => self::CAT_ALL_INSTALLED, 'ident' => 'installed', 'displayName' => (string)$this->l10n->t('Your apps')],
135
+            ['id' => self::CAT_ENABLED, 'ident' => 'enabled', 'displayName' => (string)$this->l10n->t('Enabled apps')],
136
+            ['id' => self::CAT_APP_BUNDLES, 'ident' => 'app-bundles', 'displayName' => (string)$this->l10n->t('App bundles')],
137
+            ['id' => self::CAT_DISABLED, 'ident' => 'disabled', 'displayName' => (string)$this->l10n->t('Disabled apps')],
138
+        ];
139
+        $categories = $this->categoryFetcher->get();
140
+        foreach($categories as $category) {
141
+            $formattedCategories[] = [
142
+                'id' => $category['id'],
143
+                'ident' => $category['id'],
144
+                'displayName' => isset($category['translations'][$currentLanguage]['name']) ? $category['translations'][$currentLanguage]['name'] : $category['translations']['en']['name'],
145
+            ];
146
+        }
147
+
148
+        return $formattedCategories;
149
+    }
150
+
151
+    /**
152
+     * Get all available categories
153
+     *
154
+     * @return JSONResponse
155
+     */
156
+    public function listCategories() {
157
+        return new JSONResponse($this->getAllCategories());
158
+    }
159
+
160
+    /**
161
+     * Get all apps for a category
162
+     *
163
+     * @param string $requestedCategory
164
+     * @return array
165
+     */
166
+    private function getAppsForCategory($requestedCategory) {
167
+        $versionParser = new VersionParser();
168
+        $formattedApps = [];
169
+        $apps = $this->appFetcher->get();
170
+        foreach($apps as $app) {
171
+            if (isset($app['isFeatured'])) {
172
+                $app['featured'] = $app['isFeatured'];
173
+            }
174
+
175
+            // Skip all apps not in the requested category
176
+            $isInCategory = false;
177
+            foreach($app['categories'] as $category) {
178
+                if($category === $requestedCategory) {
179
+                    $isInCategory = true;
180
+                }
181
+            }
182
+            if(!$isInCategory) {
183
+                continue;
184
+            }
185
+
186
+            $nextCloudVersion = $versionParser->getVersion($app['releases'][0]['rawPlatformVersionSpec']);
187
+            $nextCloudVersionDependencies = [];
188
+            if($nextCloudVersion->getMinimumVersion() !== '') {
189
+                $nextCloudVersionDependencies['nextcloud']['@attributes']['min-version'] = $nextCloudVersion->getMinimumVersion();
190
+            }
191
+            if($nextCloudVersion->getMaximumVersion() !== '') {
192
+                $nextCloudVersionDependencies['nextcloud']['@attributes']['max-version'] = $nextCloudVersion->getMaximumVersion();
193
+            }
194
+            $phpVersion = $versionParser->getVersion($app['releases'][0]['rawPhpVersionSpec']);
195
+            $existsLocally = (\OC_App::getAppPath($app['id']) !== false) ? true : false;
196
+            $phpDependencies = [];
197
+            if($phpVersion->getMinimumVersion() !== '') {
198
+                $phpDependencies['php']['@attributes']['min-version'] = $phpVersion->getMinimumVersion();
199
+            }
200
+            if($phpVersion->getMaximumVersion() !== '') {
201
+                $phpDependencies['php']['@attributes']['max-version'] = $phpVersion->getMaximumVersion();
202
+            }
203
+            if(isset($app['releases'][0]['minIntSize'])) {
204
+                $phpDependencies['php']['@attributes']['min-int-size'] = $app['releases'][0]['minIntSize'];
205
+            }
206
+            $authors = '';
207
+            foreach($app['authors'] as $key => $author) {
208
+                $authors .= $author['name'];
209
+                if($key !== count($app['authors']) - 1) {
210
+                    $authors .= ', ';
211
+                }
212
+            }
213
+
214
+            $currentLanguage = substr(\OC::$server->getL10NFactory()->findLanguage(), 0, 2);
215
+            $enabledValue = $this->config->getAppValue($app['id'], 'enabled', 'no');
216
+            $groups = null;
217
+            if($enabledValue !== 'no' && $enabledValue !== 'yes') {
218
+                $groups = $enabledValue;
219
+            }
220
+
221
+            $currentVersion = '';
222
+            if($this->appManager->isInstalled($app['id'])) {
223
+                $currentVersion = \OC_App::getAppVersion($app['id']);
224
+            } else {
225
+                $currentLanguage = $app['releases'][0]['version'];
226
+            }
227
+
228
+            $formattedApps[] = [
229
+                'id' => $app['id'],
230
+                'name' => isset($app['translations'][$currentLanguage]['name']) ? $app['translations'][$currentLanguage]['name'] : $app['translations']['en']['name'],
231
+                'description' => isset($app['translations'][$currentLanguage]['description']) ? $app['translations'][$currentLanguage]['description'] : $app['translations']['en']['description'],
232
+                'license' => $app['releases'][0]['licenses'],
233
+                'author' => $authors,
234
+                'shipped' => false,
235
+                'version' => $currentVersion,
236
+                'default_enable' => '',
237
+                'types' => [],
238
+                'documentation' => [
239
+                    'admin' => $app['adminDocs'],
240
+                    'user' => $app['userDocs'],
241
+                    'developer' => $app['developerDocs']
242
+                ],
243
+                'website' => $app['website'],
244
+                'bugs' => $app['issueTracker'],
245
+                'detailpage' => $app['website'],
246
+                'dependencies' => array_merge(
247
+                    $nextCloudVersionDependencies,
248
+                    $phpDependencies
249
+                ),
250
+                'level' => ($app['featured'] === true) ? 200 : 100,
251
+                'missingMaxOwnCloudVersion' => false,
252
+                'missingMinOwnCloudVersion' => false,
253
+                'canInstall' => true,
254
+                'preview' => isset($app['screenshots'][0]['url']) ? 'https://usercontent.apps.nextcloud.com/'.base64_encode($app['screenshots'][0]['url']) : '',
255
+                'score' => $app['ratingOverall'],
256
+                'ratingNumOverall' => $app['ratingNumOverall'],
257
+                'ratingNumThresholdReached' => $app['ratingNumOverall'] > 5 ? true : false,
258
+                'removable' => $existsLocally,
259
+                'active' => $this->appManager->isEnabledForUser($app['id']),
260
+                'needsDownload' => !$existsLocally,
261
+                'groups' => $groups,
262
+                'fromAppStore' => true,
263
+            ];
264
+
265
+
266
+            $appFetcher = \OC::$server->getAppFetcher();
267
+            $newVersion = \OC\Installer::isUpdateAvailable($app['id'], $appFetcher);
268
+            if($newVersion && $this->appManager->isInstalled($app['id'])) {
269
+                $formattedApps[count($formattedApps)-1]['update'] = $newVersion;
270
+            }
271
+        }
272
+
273
+        return $formattedApps;
274
+    }
275
+
276
+    /**
277
+     * Get all available apps in a category
278
+     *
279
+     * @param string $category
280
+     * @return JSONResponse
281
+     */
282
+    public function listApps($category = '') {
283
+        $appClass = new \OC_App();
284
+
285
+        switch ($category) {
286
+            // installed apps
287
+            case 'installed':
288
+                $apps = $appClass->listAllApps();
289
+
290
+                foreach($apps as $key => $app) {
291
+                    $newVersion = \OC\Installer::isUpdateAvailable($app['id'], $this->appFetcher);
292
+                    $apps[$key]['update'] = $newVersion;
293
+                }
294
+
295
+                usort($apps, function ($a, $b) {
296
+                    $a = (string)$a['name'];
297
+                    $b = (string)$b['name'];
298
+                    if ($a === $b) {
299
+                        return 0;
300
+                    }
301
+                    return ($a < $b) ? -1 : 1;
302
+                });
303
+                break;
304
+            // enabled apps
305
+            case 'enabled':
306
+                $apps = $appClass->listAllApps();
307
+                $apps = array_filter($apps, function ($app) {
308
+                    return $app['active'];
309
+                });
310
+
311
+                foreach($apps as $key => $app) {
312
+                    $newVersion = \OC\Installer::isUpdateAvailable($app['id'], $this->appFetcher);
313
+                    $apps[$key]['update'] = $newVersion;
314
+                }
315
+
316
+                usort($apps, function ($a, $b) {
317
+                    $a = (string)$a['name'];
318
+                    $b = (string)$b['name'];
319
+                    if ($a === $b) {
320
+                        return 0;
321
+                    }
322
+                    return ($a < $b) ? -1 : 1;
323
+                });
324
+                break;
325
+            // disabled  apps
326
+            case 'disabled':
327
+                $apps = $appClass->listAllApps();
328
+                $apps = array_filter($apps, function ($app) {
329
+                    return !$app['active'];
330
+                });
331
+
332
+                $apps = array_map(function ($app) {
333
+                    $newVersion = \OC\Installer::isUpdateAvailable($app['id'], $this->appFetcher);
334
+                    if ($newVersion !== false) {
335
+                        $app['update'] = $newVersion;
336
+                    }
337
+                    return $app;
338
+                }, $apps);
339
+
340
+                usort($apps, function ($a, $b) {
341
+                    $a = (string)$a['name'];
342
+                    $b = (string)$b['name'];
343
+                    if ($a === $b) {
344
+                        return 0;
345
+                    }
346
+                    return ($a < $b) ? -1 : 1;
347
+                });
348
+                break;
349
+            case 'app-bundles':
350
+                $bundles = $this->bundleFetcher->getBundles();
351
+                $apps = [];
352
+                foreach($bundles as $bundle) {
353
+                    $newCategory = true;
354
+                    $allApps = $appClass->listAllApps();
355
+                    $categories = $this->getAllCategories();
356
+                    foreach($categories as $singleCategory) {
357
+                        $newApps = $this->getAppsForCategory($singleCategory['id']);
358
+                        foreach($allApps as $app) {
359
+                            foreach($newApps as $key => $newApp) {
360
+                                if($app['id'] === $newApp['id']) {
361
+                                    unset($newApps[$key]);
362
+                                }
363
+                            }
364
+                        }
365
+                        $allApps = array_merge($allApps, $newApps);
366
+                    }
367
+
368
+                    foreach($bundle->getAppIdentifiers() as $identifier) {
369
+                        foreach($allApps as $app) {
370
+                            if($app['id'] === $identifier) {
371
+                                if($newCategory) {
372
+                                    $app['newCategory'] = true;
373
+                                    $app['categoryName'] = $bundle->getName();
374
+                                }
375
+                                $newCategory = false;
376
+                                $apps[] = $app;
377
+                                continue;
378
+                            }
379
+                        }
380
+                    }
381
+                }
382
+                break;
383
+            default:
384
+                $apps = $this->getAppsForCategory($category);
385
+
386
+                // sort by score
387
+                usort($apps, function ($a, $b) {
388
+                    $a = (int)$a['score'];
389
+                    $b = (int)$b['score'];
390
+                    if ($a === $b) {
391
+                        return 0;
392
+                    }
393
+                    return ($a > $b) ? -1 : 1;
394
+                });
395
+                break;
396
+        }
397
+
398
+        // fix groups to be an array
399
+        $dependencyAnalyzer = new DependencyAnalyzer(new Platform($this->config), $this->l10n);
400
+        $apps = array_map(function($app) use ($dependencyAnalyzer) {
401
+
402
+            // fix groups
403
+            $groups = array();
404
+            if (is_string($app['groups'])) {
405
+                $groups = json_decode($app['groups']);
406
+            }
407
+            $app['groups'] = $groups;
408
+            $app['canUnInstall'] = !$app['active'] && $app['removable'];
409
+
410
+            // fix licence vs license
411
+            if (isset($app['license']) && !isset($app['licence'])) {
412
+                $app['licence'] = $app['license'];
413
+            }
414
+
415
+            // analyse dependencies
416
+            $missing = $dependencyAnalyzer->analyze($app);
417
+            $app['canInstall'] = empty($missing);
418
+            $app['missingDependencies'] = $missing;
419
+
420
+            $app['missingMinOwnCloudVersion'] = !isset($app['dependencies']['nextcloud']['@attributes']['min-version']);
421
+            $app['missingMaxOwnCloudVersion'] = !isset($app['dependencies']['nextcloud']['@attributes']['max-version']);
422
+
423
+            return $app;
424
+        }, $apps);
425
+
426
+        return new JSONResponse(['apps' => $apps, 'status' => 'success']);
427
+    }
428 428
 }
Please login to merge, or discard this patch.
Spacing   +46 added lines, -46 removed lines patch added patch discarded remove patch
@@ -131,13 +131,13 @@  discard block
 block discarded – undo
131 131
 		$currentLanguage = substr($this->l10nFactory->findLanguage(), 0, 2);
132 132
 
133 133
 		$formattedCategories = [
134
-			['id' => self::CAT_ALL_INSTALLED, 'ident' => 'installed', 'displayName' => (string)$this->l10n->t('Your apps')],
135
-			['id' => self::CAT_ENABLED, 'ident' => 'enabled', 'displayName' => (string)$this->l10n->t('Enabled apps')],
136
-			['id' => self::CAT_APP_BUNDLES, 'ident' => 'app-bundles', 'displayName' => (string)$this->l10n->t('App bundles')],
137
-			['id' => self::CAT_DISABLED, 'ident' => 'disabled', 'displayName' => (string)$this->l10n->t('Disabled apps')],
134
+			['id' => self::CAT_ALL_INSTALLED, 'ident' => 'installed', 'displayName' => (string) $this->l10n->t('Your apps')],
135
+			['id' => self::CAT_ENABLED, 'ident' => 'enabled', 'displayName' => (string) $this->l10n->t('Enabled apps')],
136
+			['id' => self::CAT_APP_BUNDLES, 'ident' => 'app-bundles', 'displayName' => (string) $this->l10n->t('App bundles')],
137
+			['id' => self::CAT_DISABLED, 'ident' => 'disabled', 'displayName' => (string) $this->l10n->t('Disabled apps')],
138 138
 		];
139 139
 		$categories = $this->categoryFetcher->get();
140
-		foreach($categories as $category) {
140
+		foreach ($categories as $category) {
141 141
 			$formattedCategories[] = [
142 142
 				'id' => $category['id'],
143 143
 				'ident' => $category['id'],
@@ -167,46 +167,46 @@  discard block
 block discarded – undo
167 167
 		$versionParser = new VersionParser();
168 168
 		$formattedApps = [];
169 169
 		$apps = $this->appFetcher->get();
170
-		foreach($apps as $app) {
170
+		foreach ($apps as $app) {
171 171
 			if (isset($app['isFeatured'])) {
172 172
 				$app['featured'] = $app['isFeatured'];
173 173
 			}
174 174
 
175 175
 			// Skip all apps not in the requested category
176 176
 			$isInCategory = false;
177
-			foreach($app['categories'] as $category) {
178
-				if($category === $requestedCategory) {
177
+			foreach ($app['categories'] as $category) {
178
+				if ($category === $requestedCategory) {
179 179
 					$isInCategory = true;
180 180
 				}
181 181
 			}
182
-			if(!$isInCategory) {
182
+			if (!$isInCategory) {
183 183
 				continue;
184 184
 			}
185 185
 
186 186
 			$nextCloudVersion = $versionParser->getVersion($app['releases'][0]['rawPlatformVersionSpec']);
187 187
 			$nextCloudVersionDependencies = [];
188
-			if($nextCloudVersion->getMinimumVersion() !== '') {
188
+			if ($nextCloudVersion->getMinimumVersion() !== '') {
189 189
 				$nextCloudVersionDependencies['nextcloud']['@attributes']['min-version'] = $nextCloudVersion->getMinimumVersion();
190 190
 			}
191
-			if($nextCloudVersion->getMaximumVersion() !== '') {
191
+			if ($nextCloudVersion->getMaximumVersion() !== '') {
192 192
 				$nextCloudVersionDependencies['nextcloud']['@attributes']['max-version'] = $nextCloudVersion->getMaximumVersion();
193 193
 			}
194 194
 			$phpVersion = $versionParser->getVersion($app['releases'][0]['rawPhpVersionSpec']);
195 195
 			$existsLocally = (\OC_App::getAppPath($app['id']) !== false) ? true : false;
196 196
 			$phpDependencies = [];
197
-			if($phpVersion->getMinimumVersion() !== '') {
197
+			if ($phpVersion->getMinimumVersion() !== '') {
198 198
 				$phpDependencies['php']['@attributes']['min-version'] = $phpVersion->getMinimumVersion();
199 199
 			}
200
-			if($phpVersion->getMaximumVersion() !== '') {
200
+			if ($phpVersion->getMaximumVersion() !== '') {
201 201
 				$phpDependencies['php']['@attributes']['max-version'] = $phpVersion->getMaximumVersion();
202 202
 			}
203
-			if(isset($app['releases'][0]['minIntSize'])) {
203
+			if (isset($app['releases'][0]['minIntSize'])) {
204 204
 				$phpDependencies['php']['@attributes']['min-int-size'] = $app['releases'][0]['minIntSize'];
205 205
 			}
206 206
 			$authors = '';
207
-			foreach($app['authors'] as $key => $author) {
207
+			foreach ($app['authors'] as $key => $author) {
208 208
 				$authors .= $author['name'];
209
-				if($key !== count($app['authors']) - 1) {
209
+				if ($key !== count($app['authors']) - 1) {
210 210
 					$authors .= ', ';
211 211
 				}
212 212
 			}
@@ -214,12 +214,12 @@  discard block
 block discarded – undo
214 214
 			$currentLanguage = substr(\OC::$server->getL10NFactory()->findLanguage(), 0, 2);
215 215
 			$enabledValue = $this->config->getAppValue($app['id'], 'enabled', 'no');
216 216
 			$groups = null;
217
-			if($enabledValue !== 'no' && $enabledValue !== 'yes') {
217
+			if ($enabledValue !== 'no' && $enabledValue !== 'yes') {
218 218
 				$groups = $enabledValue;
219 219
 			}
220 220
 
221 221
 			$currentVersion = '';
222
-			if($this->appManager->isInstalled($app['id'])) {
222
+			if ($this->appManager->isInstalled($app['id'])) {
223 223
 				$currentVersion = \OC_App::getAppVersion($app['id']);
224 224
 			} else {
225 225
 				$currentLanguage = $app['releases'][0]['version'];
@@ -265,8 +265,8 @@  discard block
 block discarded – undo
265 265
 
266 266
 			$appFetcher = \OC::$server->getAppFetcher();
267 267
 			$newVersion = \OC\Installer::isUpdateAvailable($app['id'], $appFetcher);
268
-			if($newVersion && $this->appManager->isInstalled($app['id'])) {
269
-				$formattedApps[count($formattedApps)-1]['update'] = $newVersion;
268
+			if ($newVersion && $this->appManager->isInstalled($app['id'])) {
269
+				$formattedApps[count($formattedApps) - 1]['update'] = $newVersion;
270 270
 			}
271 271
 		}
272 272
 
@@ -287,14 +287,14 @@  discard block
 block discarded – undo
287 287
 			case 'installed':
288 288
 				$apps = $appClass->listAllApps();
289 289
 
290
-				foreach($apps as $key => $app) {
290
+				foreach ($apps as $key => $app) {
291 291
 					$newVersion = \OC\Installer::isUpdateAvailable($app['id'], $this->appFetcher);
292 292
 					$apps[$key]['update'] = $newVersion;
293 293
 				}
294 294
 
295
-				usort($apps, function ($a, $b) {
296
-					$a = (string)$a['name'];
297
-					$b = (string)$b['name'];
295
+				usort($apps, function($a, $b) {
296
+					$a = (string) $a['name'];
297
+					$b = (string) $b['name'];
298 298
 					if ($a === $b) {
299 299
 						return 0;
300 300
 					}
@@ -304,18 +304,18 @@  discard block
 block discarded – undo
304 304
 			// enabled apps
305 305
 			case 'enabled':
306 306
 				$apps = $appClass->listAllApps();
307
-				$apps = array_filter($apps, function ($app) {
307
+				$apps = array_filter($apps, function($app) {
308 308
 					return $app['active'];
309 309
 				});
310 310
 
311
-				foreach($apps as $key => $app) {
311
+				foreach ($apps as $key => $app) {
312 312
 					$newVersion = \OC\Installer::isUpdateAvailable($app['id'], $this->appFetcher);
313 313
 					$apps[$key]['update'] = $newVersion;
314 314
 				}
315 315
 
316
-				usort($apps, function ($a, $b) {
317
-					$a = (string)$a['name'];
318
-					$b = (string)$b['name'];
316
+				usort($apps, function($a, $b) {
317
+					$a = (string) $a['name'];
318
+					$b = (string) $b['name'];
319 319
 					if ($a === $b) {
320 320
 						return 0;
321 321
 					}
@@ -325,11 +325,11 @@  discard block
 block discarded – undo
325 325
 			// disabled  apps
326 326
 			case 'disabled':
327 327
 				$apps = $appClass->listAllApps();
328
-				$apps = array_filter($apps, function ($app) {
328
+				$apps = array_filter($apps, function($app) {
329 329
 					return !$app['active'];
330 330
 				});
331 331
 
332
-				$apps = array_map(function ($app) {
332
+				$apps = array_map(function($app) {
333 333
 					$newVersion = \OC\Installer::isUpdateAvailable($app['id'], $this->appFetcher);
334 334
 					if ($newVersion !== false) {
335 335
 						$app['update'] = $newVersion;
@@ -337,9 +337,9 @@  discard block
 block discarded – undo
337 337
 					return $app;
338 338
 				}, $apps);
339 339
 
340
-				usort($apps, function ($a, $b) {
341
-					$a = (string)$a['name'];
342
-					$b = (string)$b['name'];
340
+				usort($apps, function($a, $b) {
341
+					$a = (string) $a['name'];
342
+					$b = (string) $b['name'];
343 343
 					if ($a === $b) {
344 344
 						return 0;
345 345
 					}
@@ -349,15 +349,15 @@  discard block
 block discarded – undo
349 349
 			case 'app-bundles':
350 350
 				$bundles = $this->bundleFetcher->getBundles();
351 351
 				$apps = [];
352
-				foreach($bundles as $bundle) {
352
+				foreach ($bundles as $bundle) {
353 353
 					$newCategory = true;
354 354
 					$allApps = $appClass->listAllApps();
355 355
 					$categories = $this->getAllCategories();
356
-					foreach($categories as $singleCategory) {
356
+					foreach ($categories as $singleCategory) {
357 357
 						$newApps = $this->getAppsForCategory($singleCategory['id']);
358
-						foreach($allApps as $app) {
359
-							foreach($newApps as $key => $newApp) {
360
-								if($app['id'] === $newApp['id']) {
358
+						foreach ($allApps as $app) {
359
+							foreach ($newApps as $key => $newApp) {
360
+								if ($app['id'] === $newApp['id']) {
361 361
 									unset($newApps[$key]);
362 362
 								}
363 363
 							}
@@ -365,10 +365,10 @@  discard block
 block discarded – undo
365 365
 						$allApps = array_merge($allApps, $newApps);
366 366
 					}
367 367
 
368
-					foreach($bundle->getAppIdentifiers() as $identifier) {
369
-						foreach($allApps as $app) {
370
-							if($app['id'] === $identifier) {
371
-								if($newCategory) {
368
+					foreach ($bundle->getAppIdentifiers() as $identifier) {
369
+						foreach ($allApps as $app) {
370
+							if ($app['id'] === $identifier) {
371
+								if ($newCategory) {
372 372
 									$app['newCategory'] = true;
373 373
 									$app['categoryName'] = $bundle->getName();
374 374
 								}
@@ -384,9 +384,9 @@  discard block
 block discarded – undo
384 384
 				$apps = $this->getAppsForCategory($category);
385 385
 
386 386
 				// sort by score
387
-				usort($apps, function ($a, $b) {
388
-					$a = (int)$a['score'];
389
-					$b = (int)$b['score'];
387
+				usort($apps, function($a, $b) {
388
+					$a = (int) $a['score'];
389
+					$b = (int) $b['score'];
390 390
 					if ($a === $b) {
391 391
 						return 0;
392 392
 					}
Please login to merge, or discard this patch.