Completed
Pull Request — master (#4454)
by Lukas
15:46
created
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/Controller/AppSettingsController.php 2 patches
Indentation   +355 added lines, -355 removed lines patch added patch discarded remove patch
@@ -48,359 +48,359 @@
 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
-	/**
131
-	 * Get all available categories
132
-	 *
133
-	 * @return JSONResponse
134
-	 */
135
-	public function listCategories() {
136
-		$currentLanguage = substr($this->l10nFactory->findLanguage(), 0, 2);
137
-
138
-		$formattedCategories = [
139
-			['id' => self::CAT_ALL_INSTALLED, 'ident' => 'installed', 'displayName' => (string)$this->l10n->t('Your apps')],
140
-			['id' => self::CAT_ENABLED, 'ident' => 'enabled', 'displayName' => (string)$this->l10n->t('Enabled apps')],
141
-			['id' => self::CAT_APP_BUNDLES, 'ident' => 'app-bundles', 'displayName' => (string)$this->l10n->t('App bundles')],
142
-			['id' => self::CAT_DISABLED, 'ident' => 'disabled', 'displayName' => (string)$this->l10n->t('Disabled apps')],
143
-		];
144
-		$categories = $this->categoryFetcher->get();
145
-		foreach($categories as $category) {
146
-			$formattedCategories[] = [
147
-				'id' => $category['id'],
148
-				'ident' => $category['id'],
149
-				'displayName' => isset($category['translations'][$currentLanguage]['name']) ? $category['translations'][$currentLanguage]['name'] : $category['translations']['en']['name'],
150
-			];
151
-		}
152
-
153
-		return new JSONResponse($formattedCategories);
154
-	}
155
-
156
-	/**
157
-	 * Get all apps for a category
158
-	 *
159
-	 * @param string $requestedCategory
160
-	 * @return array
161
-	 */
162
-	private function getAppsForCategory($requestedCategory) {
163
-		$versionParser = new VersionParser();
164
-		$formattedApps = [];
165
-		$apps = $this->appFetcher->get();
166
-		foreach($apps as $app) {
167
-			if (isset($app['isFeatured'])) {
168
-				$app['featured'] = $app['isFeatured'];
169
-			}
170
-
171
-			// Skip all apps not in the requested category
172
-			$isInCategory = false;
173
-			foreach($app['categories'] as $category) {
174
-				if($category === $requestedCategory) {
175
-					$isInCategory = true;
176
-				}
177
-			}
178
-			if(!$isInCategory) {
179
-				continue;
180
-			}
181
-
182
-			$nextCloudVersion = $versionParser->getVersion($app['releases'][0]['rawPlatformVersionSpec']);
183
-			$nextCloudVersionDependencies = [];
184
-			if($nextCloudVersion->getMinimumVersion() !== '') {
185
-				$nextCloudVersionDependencies['nextcloud']['@attributes']['min-version'] = $nextCloudVersion->getMinimumVersion();
186
-			}
187
-			if($nextCloudVersion->getMaximumVersion() !== '') {
188
-				$nextCloudVersionDependencies['nextcloud']['@attributes']['max-version'] = $nextCloudVersion->getMaximumVersion();
189
-			}
190
-			$phpVersion = $versionParser->getVersion($app['releases'][0]['rawPhpVersionSpec']);
191
-			$existsLocally = (\OC_App::getAppPath($app['id']) !== false) ? true : false;
192
-			$phpDependencies = [];
193
-			if($phpVersion->getMinimumVersion() !== '') {
194
-				$phpDependencies['php']['@attributes']['min-version'] = $phpVersion->getMinimumVersion();
195
-			}
196
-			if($phpVersion->getMaximumVersion() !== '') {
197
-				$phpDependencies['php']['@attributes']['max-version'] = $phpVersion->getMaximumVersion();
198
-			}
199
-			if(isset($app['releases'][0]['minIntSize'])) {
200
-				$phpDependencies['php']['@attributes']['min-int-size'] = $app['releases'][0]['minIntSize'];
201
-			}
202
-			$authors = '';
203
-			foreach($app['authors'] as $key => $author) {
204
-				$authors .= $author['name'];
205
-				if($key !== count($app['authors']) - 1) {
206
-					$authors .= ', ';
207
-				}
208
-			}
209
-
210
-			$currentLanguage = substr(\OC::$server->getL10NFactory()->findLanguage(), 0, 2);
211
-			$enabledValue = $this->config->getAppValue($app['id'], 'enabled', 'no');
212
-			$groups = null;
213
-			if($enabledValue !== 'no' && $enabledValue !== 'yes') {
214
-				$groups = $enabledValue;
215
-			}
216
-
217
-			$currentVersion = '';
218
-			if($this->appManager->isInstalled($app['id'])) {
219
-				$currentVersion = \OC_App::getAppVersion($app['id']);
220
-			} else {
221
-				$currentLanguage = $app['releases'][0]['version'];
222
-			}
223
-
224
-			$formattedApps[] = [
225
-				'id' => $app['id'],
226
-				'name' => isset($app['translations'][$currentLanguage]['name']) ? $app['translations'][$currentLanguage]['name'] : $app['translations']['en']['name'],
227
-				'description' => isset($app['translations'][$currentLanguage]['description']) ? $app['translations'][$currentLanguage]['description'] : $app['translations']['en']['description'],
228
-				'license' => $app['releases'][0]['licenses'],
229
-				'author' => $authors,
230
-				'shipped' => false,
231
-				'version' => $currentVersion,
232
-				'default_enable' => '',
233
-				'types' => [],
234
-				'documentation' => [
235
-					'admin' => $app['adminDocs'],
236
-					'user' => $app['userDocs'],
237
-					'developer' => $app['developerDocs']
238
-				],
239
-				'website' => $app['website'],
240
-				'bugs' => $app['issueTracker'],
241
-				'detailpage' => $app['website'],
242
-				'dependencies' => array_merge(
243
-					$nextCloudVersionDependencies,
244
-					$phpDependencies
245
-				),
246
-				'level' => ($app['featured'] === true) ? 200 : 100,
247
-				'missingMaxOwnCloudVersion' => false,
248
-				'missingMinOwnCloudVersion' => false,
249
-				'canInstall' => true,
250
-				'preview' => isset($app['screenshots'][0]['url']) ? 'https://usercontent.apps.nextcloud.com/'.base64_encode($app['screenshots'][0]['url']) : '',
251
-				'score' => $app['ratingOverall'],
252
-				'ratingNumOverall' => $app['ratingNumOverall'],
253
-				'ratingNumThresholdReached' => $app['ratingNumOverall'] > 5 ? true : false,
254
-				'removable' => $existsLocally,
255
-				'active' => $this->appManager->isEnabledForUser($app['id']),
256
-				'needsDownload' => !$existsLocally,
257
-				'groups' => $groups,
258
-				'fromAppStore' => true,
259
-			];
260
-
261
-
262
-			$appFetcher = \OC::$server->getAppFetcher();
263
-			$newVersion = \OC\Installer::isUpdateAvailable($app['id'], $appFetcher);
264
-			if($newVersion && $this->appManager->isInstalled($app['id'])) {
265
-				$formattedApps[count($formattedApps)-1]['update'] = $newVersion;
266
-			}
267
-		}
268
-
269
-		return $formattedApps;
270
-	}
271
-
272
-	/**
273
-	 * Get all available apps in a category
274
-	 *
275
-	 * @param string $category
276
-	 * @return JSONResponse
277
-	 */
278
-	public function listApps($category = '') {
279
-		$appClass = new \OC_App();
280
-
281
-		switch ($category) {
282
-			// installed apps
283
-			case 'installed':
284
-				$apps = $appClass->listAllApps();
285
-
286
-				foreach($apps as $key => $app) {
287
-					$newVersion = \OC\Installer::isUpdateAvailable($app['id'], $this->appFetcher);
288
-					$apps[$key]['update'] = $newVersion;
289
-				}
290
-
291
-				usort($apps, function ($a, $b) {
292
-					$a = (string)$a['name'];
293
-					$b = (string)$b['name'];
294
-					if ($a === $b) {
295
-						return 0;
296
-					}
297
-					return ($a < $b) ? -1 : 1;
298
-				});
299
-				break;
300
-			// enabled apps
301
-			case 'enabled':
302
-				$apps = $appClass->listAllApps();
303
-				$apps = array_filter($apps, function ($app) {
304
-					return $app['active'];
305
-				});
306
-
307
-				foreach($apps as $key => $app) {
308
-					$newVersion = \OC\Installer::isUpdateAvailable($app['id'], $this->appFetcher);
309
-					$apps[$key]['update'] = $newVersion;
310
-				}
311
-
312
-				usort($apps, function ($a, $b) {
313
-					$a = (string)$a['name'];
314
-					$b = (string)$b['name'];
315
-					if ($a === $b) {
316
-						return 0;
317
-					}
318
-					return ($a < $b) ? -1 : 1;
319
-				});
320
-				break;
321
-			// disabled  apps
322
-			case 'disabled':
323
-				$apps = $appClass->listAllApps();
324
-				$apps = array_filter($apps, function ($app) {
325
-					return !$app['active'];
326
-				});
327
-
328
-				$apps = array_map(function ($app) {
329
-					$newVersion = \OC\Installer::isUpdateAvailable($app['id'], $this->appFetcher);
330
-					if ($newVersion !== false) {
331
-						$app['update'] = $newVersion;
332
-					}
333
-					return $app;
334
-				}, $apps);
335
-
336
-				usort($apps, function ($a, $b) {
337
-					$a = (string)$a['name'];
338
-					$b = (string)$b['name'];
339
-					if ($a === $b) {
340
-						return 0;
341
-					}
342
-					return ($a < $b) ? -1 : 1;
343
-				});
344
-				break;
345
-			case 'app-bundles':
346
-				$bundles = $this->bundleFetcher->getBundles();
347
-				$apps = [];
348
-				foreach($bundles as $bundle) {
349
-					$apps[] = [
350
-						'id' => $bundle->getIdentifier(),
351
-						'author' => 'Nextcloud',
352
-						'name' => $bundle->getName() . ' (' . $bundle->getDescription() .')',
353
-						'description' => '',
354
-						'internal' => true,
355
-						'active' => false,
356
-						'groups' => [],
357
-						'apps' => $bundle->getAppIdentifiers(),
358
-					];
359
-				}
360
-				break;
361
-			default:
362
-				$apps = $this->getAppsForCategory($category);
363
-
364
-				// sort by score
365
-				usort($apps, function ($a, $b) {
366
-					$a = (int)$a['score'];
367
-					$b = (int)$b['score'];
368
-					if ($a === $b) {
369
-						return 0;
370
-					}
371
-					return ($a > $b) ? -1 : 1;
372
-				});
373
-				break;
374
-		}
375
-
376
-		// fix groups to be an array
377
-		$dependencyAnalyzer = new DependencyAnalyzer(new Platform($this->config), $this->l10n);
378
-		$apps = array_map(function($app) use ($dependencyAnalyzer) {
379
-
380
-			// fix groups
381
-			$groups = array();
382
-			if (is_string($app['groups'])) {
383
-				$groups = json_decode($app['groups']);
384
-			}
385
-			$app['groups'] = $groups;
386
-			$app['canUnInstall'] = !$app['active'] && $app['removable'];
387
-
388
-			// fix licence vs license
389
-			if (isset($app['license']) && !isset($app['licence'])) {
390
-				$app['licence'] = $app['license'];
391
-			}
392
-
393
-			// analyse dependencies
394
-			$missing = $dependencyAnalyzer->analyze($app);
395
-			$app['canInstall'] = empty($missing);
396
-			$app['missingDependencies'] = $missing;
397
-
398
-			$app['missingMinOwnCloudVersion'] = !isset($app['dependencies']['nextcloud']['@attributes']['min-version']);
399
-			$app['missingMaxOwnCloudVersion'] = !isset($app['dependencies']['nextcloud']['@attributes']['max-version']);
400
-
401
-			return $app;
402
-		}, $apps);
403
-
404
-		return new JSONResponse(['apps' => $apps, 'status' => 'success']);
405
-	}
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
+    /**
131
+     * Get all available categories
132
+     *
133
+     * @return JSONResponse
134
+     */
135
+    public function listCategories() {
136
+        $currentLanguage = substr($this->l10nFactory->findLanguage(), 0, 2);
137
+
138
+        $formattedCategories = [
139
+            ['id' => self::CAT_ALL_INSTALLED, 'ident' => 'installed', 'displayName' => (string)$this->l10n->t('Your apps')],
140
+            ['id' => self::CAT_ENABLED, 'ident' => 'enabled', 'displayName' => (string)$this->l10n->t('Enabled apps')],
141
+            ['id' => self::CAT_APP_BUNDLES, 'ident' => 'app-bundles', 'displayName' => (string)$this->l10n->t('App bundles')],
142
+            ['id' => self::CAT_DISABLED, 'ident' => 'disabled', 'displayName' => (string)$this->l10n->t('Disabled apps')],
143
+        ];
144
+        $categories = $this->categoryFetcher->get();
145
+        foreach($categories as $category) {
146
+            $formattedCategories[] = [
147
+                'id' => $category['id'],
148
+                'ident' => $category['id'],
149
+                'displayName' => isset($category['translations'][$currentLanguage]['name']) ? $category['translations'][$currentLanguage]['name'] : $category['translations']['en']['name'],
150
+            ];
151
+        }
152
+
153
+        return new JSONResponse($formattedCategories);
154
+    }
155
+
156
+    /**
157
+     * Get all apps for a category
158
+     *
159
+     * @param string $requestedCategory
160
+     * @return array
161
+     */
162
+    private function getAppsForCategory($requestedCategory) {
163
+        $versionParser = new VersionParser();
164
+        $formattedApps = [];
165
+        $apps = $this->appFetcher->get();
166
+        foreach($apps as $app) {
167
+            if (isset($app['isFeatured'])) {
168
+                $app['featured'] = $app['isFeatured'];
169
+            }
170
+
171
+            // Skip all apps not in the requested category
172
+            $isInCategory = false;
173
+            foreach($app['categories'] as $category) {
174
+                if($category === $requestedCategory) {
175
+                    $isInCategory = true;
176
+                }
177
+            }
178
+            if(!$isInCategory) {
179
+                continue;
180
+            }
181
+
182
+            $nextCloudVersion = $versionParser->getVersion($app['releases'][0]['rawPlatformVersionSpec']);
183
+            $nextCloudVersionDependencies = [];
184
+            if($nextCloudVersion->getMinimumVersion() !== '') {
185
+                $nextCloudVersionDependencies['nextcloud']['@attributes']['min-version'] = $nextCloudVersion->getMinimumVersion();
186
+            }
187
+            if($nextCloudVersion->getMaximumVersion() !== '') {
188
+                $nextCloudVersionDependencies['nextcloud']['@attributes']['max-version'] = $nextCloudVersion->getMaximumVersion();
189
+            }
190
+            $phpVersion = $versionParser->getVersion($app['releases'][0]['rawPhpVersionSpec']);
191
+            $existsLocally = (\OC_App::getAppPath($app['id']) !== false) ? true : false;
192
+            $phpDependencies = [];
193
+            if($phpVersion->getMinimumVersion() !== '') {
194
+                $phpDependencies['php']['@attributes']['min-version'] = $phpVersion->getMinimumVersion();
195
+            }
196
+            if($phpVersion->getMaximumVersion() !== '') {
197
+                $phpDependencies['php']['@attributes']['max-version'] = $phpVersion->getMaximumVersion();
198
+            }
199
+            if(isset($app['releases'][0]['minIntSize'])) {
200
+                $phpDependencies['php']['@attributes']['min-int-size'] = $app['releases'][0]['minIntSize'];
201
+            }
202
+            $authors = '';
203
+            foreach($app['authors'] as $key => $author) {
204
+                $authors .= $author['name'];
205
+                if($key !== count($app['authors']) - 1) {
206
+                    $authors .= ', ';
207
+                }
208
+            }
209
+
210
+            $currentLanguage = substr(\OC::$server->getL10NFactory()->findLanguage(), 0, 2);
211
+            $enabledValue = $this->config->getAppValue($app['id'], 'enabled', 'no');
212
+            $groups = null;
213
+            if($enabledValue !== 'no' && $enabledValue !== 'yes') {
214
+                $groups = $enabledValue;
215
+            }
216
+
217
+            $currentVersion = '';
218
+            if($this->appManager->isInstalled($app['id'])) {
219
+                $currentVersion = \OC_App::getAppVersion($app['id']);
220
+            } else {
221
+                $currentLanguage = $app['releases'][0]['version'];
222
+            }
223
+
224
+            $formattedApps[] = [
225
+                'id' => $app['id'],
226
+                'name' => isset($app['translations'][$currentLanguage]['name']) ? $app['translations'][$currentLanguage]['name'] : $app['translations']['en']['name'],
227
+                'description' => isset($app['translations'][$currentLanguage]['description']) ? $app['translations'][$currentLanguage]['description'] : $app['translations']['en']['description'],
228
+                'license' => $app['releases'][0]['licenses'],
229
+                'author' => $authors,
230
+                'shipped' => false,
231
+                'version' => $currentVersion,
232
+                'default_enable' => '',
233
+                'types' => [],
234
+                'documentation' => [
235
+                    'admin' => $app['adminDocs'],
236
+                    'user' => $app['userDocs'],
237
+                    'developer' => $app['developerDocs']
238
+                ],
239
+                'website' => $app['website'],
240
+                'bugs' => $app['issueTracker'],
241
+                'detailpage' => $app['website'],
242
+                'dependencies' => array_merge(
243
+                    $nextCloudVersionDependencies,
244
+                    $phpDependencies
245
+                ),
246
+                'level' => ($app['featured'] === true) ? 200 : 100,
247
+                'missingMaxOwnCloudVersion' => false,
248
+                'missingMinOwnCloudVersion' => false,
249
+                'canInstall' => true,
250
+                'preview' => isset($app['screenshots'][0]['url']) ? 'https://usercontent.apps.nextcloud.com/'.base64_encode($app['screenshots'][0]['url']) : '',
251
+                'score' => $app['ratingOverall'],
252
+                'ratingNumOverall' => $app['ratingNumOverall'],
253
+                'ratingNumThresholdReached' => $app['ratingNumOverall'] > 5 ? true : false,
254
+                'removable' => $existsLocally,
255
+                'active' => $this->appManager->isEnabledForUser($app['id']),
256
+                'needsDownload' => !$existsLocally,
257
+                'groups' => $groups,
258
+                'fromAppStore' => true,
259
+            ];
260
+
261
+
262
+            $appFetcher = \OC::$server->getAppFetcher();
263
+            $newVersion = \OC\Installer::isUpdateAvailable($app['id'], $appFetcher);
264
+            if($newVersion && $this->appManager->isInstalled($app['id'])) {
265
+                $formattedApps[count($formattedApps)-1]['update'] = $newVersion;
266
+            }
267
+        }
268
+
269
+        return $formattedApps;
270
+    }
271
+
272
+    /**
273
+     * Get all available apps in a category
274
+     *
275
+     * @param string $category
276
+     * @return JSONResponse
277
+     */
278
+    public function listApps($category = '') {
279
+        $appClass = new \OC_App();
280
+
281
+        switch ($category) {
282
+            // installed apps
283
+            case 'installed':
284
+                $apps = $appClass->listAllApps();
285
+
286
+                foreach($apps as $key => $app) {
287
+                    $newVersion = \OC\Installer::isUpdateAvailable($app['id'], $this->appFetcher);
288
+                    $apps[$key]['update'] = $newVersion;
289
+                }
290
+
291
+                usort($apps, function ($a, $b) {
292
+                    $a = (string)$a['name'];
293
+                    $b = (string)$b['name'];
294
+                    if ($a === $b) {
295
+                        return 0;
296
+                    }
297
+                    return ($a < $b) ? -1 : 1;
298
+                });
299
+                break;
300
+            // enabled apps
301
+            case 'enabled':
302
+                $apps = $appClass->listAllApps();
303
+                $apps = array_filter($apps, function ($app) {
304
+                    return $app['active'];
305
+                });
306
+
307
+                foreach($apps as $key => $app) {
308
+                    $newVersion = \OC\Installer::isUpdateAvailable($app['id'], $this->appFetcher);
309
+                    $apps[$key]['update'] = $newVersion;
310
+                }
311
+
312
+                usort($apps, function ($a, $b) {
313
+                    $a = (string)$a['name'];
314
+                    $b = (string)$b['name'];
315
+                    if ($a === $b) {
316
+                        return 0;
317
+                    }
318
+                    return ($a < $b) ? -1 : 1;
319
+                });
320
+                break;
321
+            // disabled  apps
322
+            case 'disabled':
323
+                $apps = $appClass->listAllApps();
324
+                $apps = array_filter($apps, function ($app) {
325
+                    return !$app['active'];
326
+                });
327
+
328
+                $apps = array_map(function ($app) {
329
+                    $newVersion = \OC\Installer::isUpdateAvailable($app['id'], $this->appFetcher);
330
+                    if ($newVersion !== false) {
331
+                        $app['update'] = $newVersion;
332
+                    }
333
+                    return $app;
334
+                }, $apps);
335
+
336
+                usort($apps, function ($a, $b) {
337
+                    $a = (string)$a['name'];
338
+                    $b = (string)$b['name'];
339
+                    if ($a === $b) {
340
+                        return 0;
341
+                    }
342
+                    return ($a < $b) ? -1 : 1;
343
+                });
344
+                break;
345
+            case 'app-bundles':
346
+                $bundles = $this->bundleFetcher->getBundles();
347
+                $apps = [];
348
+                foreach($bundles as $bundle) {
349
+                    $apps[] = [
350
+                        'id' => $bundle->getIdentifier(),
351
+                        'author' => 'Nextcloud',
352
+                        'name' => $bundle->getName() . ' (' . $bundle->getDescription() .')',
353
+                        'description' => '',
354
+                        'internal' => true,
355
+                        'active' => false,
356
+                        'groups' => [],
357
+                        'apps' => $bundle->getAppIdentifiers(),
358
+                    ];
359
+                }
360
+                break;
361
+            default:
362
+                $apps = $this->getAppsForCategory($category);
363
+
364
+                // sort by score
365
+                usort($apps, function ($a, $b) {
366
+                    $a = (int)$a['score'];
367
+                    $b = (int)$b['score'];
368
+                    if ($a === $b) {
369
+                        return 0;
370
+                    }
371
+                    return ($a > $b) ? -1 : 1;
372
+                });
373
+                break;
374
+        }
375
+
376
+        // fix groups to be an array
377
+        $dependencyAnalyzer = new DependencyAnalyzer(new Platform($this->config), $this->l10n);
378
+        $apps = array_map(function($app) use ($dependencyAnalyzer) {
379
+
380
+            // fix groups
381
+            $groups = array();
382
+            if (is_string($app['groups'])) {
383
+                $groups = json_decode($app['groups']);
384
+            }
385
+            $app['groups'] = $groups;
386
+            $app['canUnInstall'] = !$app['active'] && $app['removable'];
387
+
388
+            // fix licence vs license
389
+            if (isset($app['license']) && !isset($app['licence'])) {
390
+                $app['licence'] = $app['license'];
391
+            }
392
+
393
+            // analyse dependencies
394
+            $missing = $dependencyAnalyzer->analyze($app);
395
+            $app['canInstall'] = empty($missing);
396
+            $app['missingDependencies'] = $missing;
397
+
398
+            $app['missingMinOwnCloudVersion'] = !isset($app['dependencies']['nextcloud']['@attributes']['min-version']);
399
+            $app['missingMaxOwnCloudVersion'] = !isset($app['dependencies']['nextcloud']['@attributes']['max-version']);
400
+
401
+            return $app;
402
+        }, $apps);
403
+
404
+        return new JSONResponse(['apps' => $apps, 'status' => 'success']);
405
+    }
406 406
 }
Please login to merge, or discard this patch.
Spacing   +39 added lines, -39 removed lines patch added patch discarded remove patch
@@ -136,13 +136,13 @@  discard block
 block discarded – undo
136 136
 		$currentLanguage = substr($this->l10nFactory->findLanguage(), 0, 2);
137 137
 
138 138
 		$formattedCategories = [
139
-			['id' => self::CAT_ALL_INSTALLED, 'ident' => 'installed', 'displayName' => (string)$this->l10n->t('Your apps')],
140
-			['id' => self::CAT_ENABLED, 'ident' => 'enabled', 'displayName' => (string)$this->l10n->t('Enabled apps')],
141
-			['id' => self::CAT_APP_BUNDLES, 'ident' => 'app-bundles', 'displayName' => (string)$this->l10n->t('App bundles')],
142
-			['id' => self::CAT_DISABLED, 'ident' => 'disabled', 'displayName' => (string)$this->l10n->t('Disabled apps')],
139
+			['id' => self::CAT_ALL_INSTALLED, 'ident' => 'installed', 'displayName' => (string) $this->l10n->t('Your apps')],
140
+			['id' => self::CAT_ENABLED, 'ident' => 'enabled', 'displayName' => (string) $this->l10n->t('Enabled apps')],
141
+			['id' => self::CAT_APP_BUNDLES, 'ident' => 'app-bundles', 'displayName' => (string) $this->l10n->t('App bundles')],
142
+			['id' => self::CAT_DISABLED, 'ident' => 'disabled', 'displayName' => (string) $this->l10n->t('Disabled apps')],
143 143
 		];
144 144
 		$categories = $this->categoryFetcher->get();
145
-		foreach($categories as $category) {
145
+		foreach ($categories as $category) {
146 146
 			$formattedCategories[] = [
147 147
 				'id' => $category['id'],
148 148
 				'ident' => $category['id'],
@@ -163,46 +163,46 @@  discard block
 block discarded – undo
163 163
 		$versionParser = new VersionParser();
164 164
 		$formattedApps = [];
165 165
 		$apps = $this->appFetcher->get();
166
-		foreach($apps as $app) {
166
+		foreach ($apps as $app) {
167 167
 			if (isset($app['isFeatured'])) {
168 168
 				$app['featured'] = $app['isFeatured'];
169 169
 			}
170 170
 
171 171
 			// Skip all apps not in the requested category
172 172
 			$isInCategory = false;
173
-			foreach($app['categories'] as $category) {
174
-				if($category === $requestedCategory) {
173
+			foreach ($app['categories'] as $category) {
174
+				if ($category === $requestedCategory) {
175 175
 					$isInCategory = true;
176 176
 				}
177 177
 			}
178
-			if(!$isInCategory) {
178
+			if (!$isInCategory) {
179 179
 				continue;
180 180
 			}
181 181
 
182 182
 			$nextCloudVersion = $versionParser->getVersion($app['releases'][0]['rawPlatformVersionSpec']);
183 183
 			$nextCloudVersionDependencies = [];
184
-			if($nextCloudVersion->getMinimumVersion() !== '') {
184
+			if ($nextCloudVersion->getMinimumVersion() !== '') {
185 185
 				$nextCloudVersionDependencies['nextcloud']['@attributes']['min-version'] = $nextCloudVersion->getMinimumVersion();
186 186
 			}
187
-			if($nextCloudVersion->getMaximumVersion() !== '') {
187
+			if ($nextCloudVersion->getMaximumVersion() !== '') {
188 188
 				$nextCloudVersionDependencies['nextcloud']['@attributes']['max-version'] = $nextCloudVersion->getMaximumVersion();
189 189
 			}
190 190
 			$phpVersion = $versionParser->getVersion($app['releases'][0]['rawPhpVersionSpec']);
191 191
 			$existsLocally = (\OC_App::getAppPath($app['id']) !== false) ? true : false;
192 192
 			$phpDependencies = [];
193
-			if($phpVersion->getMinimumVersion() !== '') {
193
+			if ($phpVersion->getMinimumVersion() !== '') {
194 194
 				$phpDependencies['php']['@attributes']['min-version'] = $phpVersion->getMinimumVersion();
195 195
 			}
196
-			if($phpVersion->getMaximumVersion() !== '') {
196
+			if ($phpVersion->getMaximumVersion() !== '') {
197 197
 				$phpDependencies['php']['@attributes']['max-version'] = $phpVersion->getMaximumVersion();
198 198
 			}
199
-			if(isset($app['releases'][0]['minIntSize'])) {
199
+			if (isset($app['releases'][0]['minIntSize'])) {
200 200
 				$phpDependencies['php']['@attributes']['min-int-size'] = $app['releases'][0]['minIntSize'];
201 201
 			}
202 202
 			$authors = '';
203
-			foreach($app['authors'] as $key => $author) {
203
+			foreach ($app['authors'] as $key => $author) {
204 204
 				$authors .= $author['name'];
205
-				if($key !== count($app['authors']) - 1) {
205
+				if ($key !== count($app['authors']) - 1) {
206 206
 					$authors .= ', ';
207 207
 				}
208 208
 			}
@@ -210,12 +210,12 @@  discard block
 block discarded – undo
210 210
 			$currentLanguage = substr(\OC::$server->getL10NFactory()->findLanguage(), 0, 2);
211 211
 			$enabledValue = $this->config->getAppValue($app['id'], 'enabled', 'no');
212 212
 			$groups = null;
213
-			if($enabledValue !== 'no' && $enabledValue !== 'yes') {
213
+			if ($enabledValue !== 'no' && $enabledValue !== 'yes') {
214 214
 				$groups = $enabledValue;
215 215
 			}
216 216
 
217 217
 			$currentVersion = '';
218
-			if($this->appManager->isInstalled($app['id'])) {
218
+			if ($this->appManager->isInstalled($app['id'])) {
219 219
 				$currentVersion = \OC_App::getAppVersion($app['id']);
220 220
 			} else {
221 221
 				$currentLanguage = $app['releases'][0]['version'];
@@ -261,8 +261,8 @@  discard block
 block discarded – undo
261 261
 
262 262
 			$appFetcher = \OC::$server->getAppFetcher();
263 263
 			$newVersion = \OC\Installer::isUpdateAvailable($app['id'], $appFetcher);
264
-			if($newVersion && $this->appManager->isInstalled($app['id'])) {
265
-				$formattedApps[count($formattedApps)-1]['update'] = $newVersion;
264
+			if ($newVersion && $this->appManager->isInstalled($app['id'])) {
265
+				$formattedApps[count($formattedApps) - 1]['update'] = $newVersion;
266 266
 			}
267 267
 		}
268 268
 
@@ -283,14 +283,14 @@  discard block
 block discarded – undo
283 283
 			case 'installed':
284 284
 				$apps = $appClass->listAllApps();
285 285
 
286
-				foreach($apps as $key => $app) {
286
+				foreach ($apps as $key => $app) {
287 287
 					$newVersion = \OC\Installer::isUpdateAvailable($app['id'], $this->appFetcher);
288 288
 					$apps[$key]['update'] = $newVersion;
289 289
 				}
290 290
 
291
-				usort($apps, function ($a, $b) {
292
-					$a = (string)$a['name'];
293
-					$b = (string)$b['name'];
291
+				usort($apps, function($a, $b) {
292
+					$a = (string) $a['name'];
293
+					$b = (string) $b['name'];
294 294
 					if ($a === $b) {
295 295
 						return 0;
296 296
 					}
@@ -300,18 +300,18 @@  discard block
 block discarded – undo
300 300
 			// enabled apps
301 301
 			case 'enabled':
302 302
 				$apps = $appClass->listAllApps();
303
-				$apps = array_filter($apps, function ($app) {
303
+				$apps = array_filter($apps, function($app) {
304 304
 					return $app['active'];
305 305
 				});
306 306
 
307
-				foreach($apps as $key => $app) {
307
+				foreach ($apps as $key => $app) {
308 308
 					$newVersion = \OC\Installer::isUpdateAvailable($app['id'], $this->appFetcher);
309 309
 					$apps[$key]['update'] = $newVersion;
310 310
 				}
311 311
 
312
-				usort($apps, function ($a, $b) {
313
-					$a = (string)$a['name'];
314
-					$b = (string)$b['name'];
312
+				usort($apps, function($a, $b) {
313
+					$a = (string) $a['name'];
314
+					$b = (string) $b['name'];
315 315
 					if ($a === $b) {
316 316
 						return 0;
317 317
 					}
@@ -321,11 +321,11 @@  discard block
 block discarded – undo
321 321
 			// disabled  apps
322 322
 			case 'disabled':
323 323
 				$apps = $appClass->listAllApps();
324
-				$apps = array_filter($apps, function ($app) {
324
+				$apps = array_filter($apps, function($app) {
325 325
 					return !$app['active'];
326 326
 				});
327 327
 
328
-				$apps = array_map(function ($app) {
328
+				$apps = array_map(function($app) {
329 329
 					$newVersion = \OC\Installer::isUpdateAvailable($app['id'], $this->appFetcher);
330 330
 					if ($newVersion !== false) {
331 331
 						$app['update'] = $newVersion;
@@ -333,9 +333,9 @@  discard block
 block discarded – undo
333 333
 					return $app;
334 334
 				}, $apps);
335 335
 
336
-				usort($apps, function ($a, $b) {
337
-					$a = (string)$a['name'];
338
-					$b = (string)$b['name'];
336
+				usort($apps, function($a, $b) {
337
+					$a = (string) $a['name'];
338
+					$b = (string) $b['name'];
339 339
 					if ($a === $b) {
340 340
 						return 0;
341 341
 					}
@@ -345,11 +345,11 @@  discard block
 block discarded – undo
345 345
 			case 'app-bundles':
346 346
 				$bundles = $this->bundleFetcher->getBundles();
347 347
 				$apps = [];
348
-				foreach($bundles as $bundle) {
348
+				foreach ($bundles as $bundle) {
349 349
 					$apps[] = [
350 350
 						'id' => $bundle->getIdentifier(),
351 351
 						'author' => 'Nextcloud',
352
-						'name' => $bundle->getName() . ' (' . $bundle->getDescription() .')',
352
+						'name' => $bundle->getName().' ('.$bundle->getDescription().')',
353 353
 						'description' => '',
354 354
 						'internal' => true,
355 355
 						'active' => false,
@@ -362,9 +362,9 @@  discard block
 block discarded – undo
362 362
 				$apps = $this->getAppsForCategory($category);
363 363
 
364 364
 				// sort by score
365
-				usort($apps, function ($a, $b) {
366
-					$a = (int)$a['score'];
367
-					$b = (int)$b['score'];
365
+				usort($apps, function($a, $b) {
366
+					$a = (int) $a['score'];
367
+					$b = (int) $b['score'];
368 368
 					if ($a === $b) {
369 369
 						return 0;
370 370
 					}
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.