Completed
Push — master ( 6b730b...126a82 )
by Morris
11:40
created
lib/private/Setup.php 1 patch
Indentation   +518 added lines, -518 removed lines patch added patch discarded remove patch
@@ -56,522 +56,522 @@
 block discarded – undo
56 56
 use OCP\Security\ISecureRandom;
57 57
 
58 58
 class Setup {
59
-	/** @var SystemConfig */
60
-	protected $config;
61
-	/** @var IniGetWrapper */
62
-	protected $iniWrapper;
63
-	/** @var IL10N */
64
-	protected $l10n;
65
-	/** @var Defaults */
66
-	protected $defaults;
67
-	/** @var ILogger */
68
-	protected $logger;
69
-	/** @var ISecureRandom */
70
-	protected $random;
71
-	/** @var Installer */
72
-	protected $installer;
73
-
74
-	/**
75
-	 * @param SystemConfig $config
76
-	 * @param IniGetWrapper $iniWrapper
77
-	 * @param IL10N $l10n
78
-	 * @param Defaults $defaults
79
-	 * @param ILogger $logger
80
-	 * @param ISecureRandom $random
81
-	 * @param Installer $installer
82
-	 */
83
-	public function __construct(SystemConfig $config,
84
-						 IniGetWrapper $iniWrapper,
85
-						 IL10N $l10n,
86
-						 Defaults $defaults,
87
-						 ILogger $logger,
88
-						 ISecureRandom $random,
89
-						 Installer $installer
90
-		) {
91
-		$this->config = $config;
92
-		$this->iniWrapper = $iniWrapper;
93
-		$this->l10n = $l10n;
94
-		$this->defaults = $defaults;
95
-		$this->logger = $logger;
96
-		$this->random = $random;
97
-		$this->installer = $installer;
98
-	}
99
-
100
-	static protected $dbSetupClasses = [
101
-		'mysql' => \OC\Setup\MySQL::class,
102
-		'pgsql' => \OC\Setup\PostgreSQL::class,
103
-		'oci'   => \OC\Setup\OCI::class,
104
-		'sqlite' => \OC\Setup\Sqlite::class,
105
-		'sqlite3' => \OC\Setup\Sqlite::class,
106
-	];
107
-
108
-	/**
109
-	 * Wrapper around the "class_exists" PHP function to be able to mock it
110
-	 * @param string $name
111
-	 * @return bool
112
-	 */
113
-	protected function class_exists($name) {
114
-		return class_exists($name);
115
-	}
116
-
117
-	/**
118
-	 * Wrapper around the "is_callable" PHP function to be able to mock it
119
-	 * @param string $name
120
-	 * @return bool
121
-	 */
122
-	protected function is_callable($name) {
123
-		return is_callable($name);
124
-	}
125
-
126
-	/**
127
-	 * Wrapper around \PDO::getAvailableDrivers
128
-	 *
129
-	 * @return array
130
-	 */
131
-	protected function getAvailableDbDriversForPdo() {
132
-		return \PDO::getAvailableDrivers();
133
-	}
134
-
135
-	/**
136
-	 * Get the available and supported databases of this instance
137
-	 *
138
-	 * @param bool $allowAllDatabases
139
-	 * @return array
140
-	 * @throws Exception
141
-	 */
142
-	public function getSupportedDatabases($allowAllDatabases = false) {
143
-		$availableDatabases = [
144
-			'sqlite' =>  [
145
-				'type' => 'pdo',
146
-				'call' => 'sqlite',
147
-				'name' => 'SQLite',
148
-			],
149
-			'mysql' => [
150
-				'type' => 'pdo',
151
-				'call' => 'mysql',
152
-				'name' => 'MySQL/MariaDB',
153
-			],
154
-			'pgsql' => [
155
-				'type' => 'pdo',
156
-				'call' => 'pgsql',
157
-				'name' => 'PostgreSQL',
158
-			],
159
-			'oci' => [
160
-				'type' => 'function',
161
-				'call' => 'oci_connect',
162
-				'name' => 'Oracle',
163
-			],
164
-		];
165
-		if ($allowAllDatabases) {
166
-			$configuredDatabases = array_keys($availableDatabases);
167
-		} else {
168
-			$configuredDatabases = $this->config->getValue('supportedDatabases',
169
-				['sqlite', 'mysql', 'pgsql']);
170
-		}
171
-		if(!is_array($configuredDatabases)) {
172
-			throw new Exception('Supported databases are not properly configured.');
173
-		}
174
-
175
-		$supportedDatabases = array();
176
-
177
-		foreach($configuredDatabases as $database) {
178
-			if(array_key_exists($database, $availableDatabases)) {
179
-				$working = false;
180
-				$type = $availableDatabases[$database]['type'];
181
-				$call = $availableDatabases[$database]['call'];
182
-
183
-				if ($type === 'function') {
184
-					$working = $this->is_callable($call);
185
-				} elseif($type === 'pdo') {
186
-					$working = in_array($call, $this->getAvailableDbDriversForPdo(), true);
187
-				}
188
-				if($working) {
189
-					$supportedDatabases[$database] = $availableDatabases[$database]['name'];
190
-				}
191
-			}
192
-		}
193
-
194
-		return $supportedDatabases;
195
-	}
196
-
197
-	/**
198
-	 * Gathers system information like database type and does
199
-	 * a few system checks.
200
-	 *
201
-	 * @return array of system info, including an "errors" value
202
-	 * in case of errors/warnings
203
-	 */
204
-	public function getSystemInfo($allowAllDatabases = false) {
205
-		$databases = $this->getSupportedDatabases($allowAllDatabases);
206
-
207
-		$dataDir = $this->config->getValue('datadirectory', \OC::$SERVERROOT.'/data');
208
-
209
-		$errors = [];
210
-
211
-		// Create data directory to test whether the .htaccess works
212
-		// Notice that this is not necessarily the same data directory as the one
213
-		// that will effectively be used.
214
-		if(!file_exists($dataDir)) {
215
-			@mkdir($dataDir);
216
-		}
217
-		$htAccessWorking = true;
218
-		if (is_dir($dataDir) && is_writable($dataDir)) {
219
-			// Protect data directory here, so we can test if the protection is working
220
-			self::protectDataDirectory();
221
-
222
-			try {
223
-				$util = new \OC_Util();
224
-				$htAccessWorking = $util->isHtaccessWorking(\OC::$server->getConfig());
225
-			} catch (\OC\HintException $e) {
226
-				$errors[] = [
227
-					'error' => $e->getMessage(),
228
-					'hint' => $e->getHint(),
229
-				];
230
-				$htAccessWorking = false;
231
-			}
232
-		}
233
-
234
-		if (\OC_Util::runningOnMac()) {
235
-			$errors[] = [
236
-				'error' => $this->l10n->t(
237
-					'Mac OS X is not supported and %s will not work properly on this platform. ' .
238
-					'Use it at your own risk! ',
239
-					[$this->defaults->getName()]
240
-				),
241
-				'hint' => $this->l10n->t('For the best results, please consider using a GNU/Linux server instead.'),
242
-			];
243
-		}
244
-
245
-		if($this->iniWrapper->getString('open_basedir') !== '' && PHP_INT_SIZE === 4) {
246
-			$errors[] = [
247
-				'error' => $this->l10n->t(
248
-					'It seems that this %s instance is running on a 32-bit PHP environment and the open_basedir has been configured in php.ini. ' .
249
-					'This will lead to problems with files over 4 GB and is highly discouraged.',
250
-					[$this->defaults->getName()]
251
-				),
252
-				'hint' => $this->l10n->t('Please remove the open_basedir setting within your php.ini or switch to 64-bit PHP.'),
253
-			];
254
-		}
255
-
256
-		return array(
257
-			'hasSQLite' => isset($databases['sqlite']),
258
-			'hasMySQL' => isset($databases['mysql']),
259
-			'hasPostgreSQL' => isset($databases['pgsql']),
260
-			'hasOracle' => isset($databases['oci']),
261
-			'databases' => $databases,
262
-			'directory' => $dataDir,
263
-			'htaccessWorking' => $htAccessWorking,
264
-			'errors' => $errors,
265
-		);
266
-	}
267
-
268
-	/**
269
-	 * @param $options
270
-	 * @return array
271
-	 */
272
-	public function install($options) {
273
-		$l = $this->l10n;
274
-
275
-		$error = array();
276
-		$dbType = $options['dbtype'];
277
-
278
-		if(empty($options['adminlogin'])) {
279
-			$error[] = $l->t('Set an admin username.');
280
-		}
281
-		if(empty($options['adminpass'])) {
282
-			$error[] = $l->t('Set an admin password.');
283
-		}
284
-		if(empty($options['directory'])) {
285
-			$options['directory'] = \OC::$SERVERROOT."/data";
286
-		}
287
-
288
-		if (!isset(self::$dbSetupClasses[$dbType])) {
289
-			$dbType = 'sqlite';
290
-		}
291
-
292
-		$username = htmlspecialchars_decode($options['adminlogin']);
293
-		$password = htmlspecialchars_decode($options['adminpass']);
294
-		$dataDir = htmlspecialchars_decode($options['directory']);
295
-
296
-		$class = self::$dbSetupClasses[$dbType];
297
-		/** @var \OC\Setup\AbstractDatabase $dbSetup */
298
-		$dbSetup = new $class($l, $this->config, $this->logger, $this->random);
299
-		$error = array_merge($error, $dbSetup->validate($options));
300
-
301
-		// validate the data directory
302
-		if ((!is_dir($dataDir) && !mkdir($dataDir)) || !is_writable($dataDir)) {
303
-			$error[] = $l->t("Can't create or write into the data directory %s", array($dataDir));
304
-		}
305
-
306
-		if (!empty($error)) {
307
-			return $error;
308
-		}
309
-
310
-		$request = \OC::$server->getRequest();
311
-
312
-		//no errors, good
313
-		if(isset($options['trusted_domains'])
314
-		    && is_array($options['trusted_domains'])) {
315
-			$trustedDomains = $options['trusted_domains'];
316
-		} else {
317
-			$trustedDomains = [$request->getInsecureServerHost()];
318
-		}
319
-
320
-		//use sqlite3 when available, otherwise sqlite2 will be used.
321
-		if ($dbType === 'sqlite' && class_exists('SQLite3')) {
322
-			$dbType = 'sqlite3';
323
-		}
324
-
325
-		//generate a random salt that is used to salt the local user passwords
326
-		$salt = $this->random->generate(30);
327
-		// generate a secret
328
-		$secret = $this->random->generate(48);
329
-
330
-		//write the config file
331
-		$newConfigValues = [
332
-			'passwordsalt'		=> $salt,
333
-			'secret'			=> $secret,
334
-			'trusted_domains'	=> $trustedDomains,
335
-			'datadirectory'		=> $dataDir,
336
-			'dbtype'			=> $dbType,
337
-			'version'			=> implode('.', \OCP\Util::getVersion()),
338
-		];
339
-
340
-		if ($this->config->getValue('overwrite.cli.url', null) === null) {
341
-			$newConfigValues['overwrite.cli.url'] = $request->getServerProtocol() . '://' . $request->getInsecureServerHost() . \OC::$WEBROOT;
342
-		}
343
-
344
-		$this->config->setValues($newConfigValues);
345
-
346
-		try {
347
-			$dbSetup->initialize($options);
348
-			$dbSetup->setupDatabase($username);
349
-			// apply necessary migrations
350
-			$dbSetup->runMigrations();
351
-		} catch (\OC\DatabaseSetupException $e) {
352
-			$error[] = [
353
-				'error' => $e->getMessage(),
354
-				'hint' => $e->getHint(),
355
-			];
356
-			return $error;
357
-		} catch (Exception $e) {
358
-			$error[] = [
359
-				'error' => 'Error while trying to create admin user: ' . $e->getMessage(),
360
-				'hint' => '',
361
-			];
362
-			return $error;
363
-		}
364
-
365
-		//create the user and group
366
-		$user =  null;
367
-		try {
368
-			$user = \OC::$server->getUserManager()->createUser($username, $password);
369
-			if (!$user) {
370
-				$error[] = "User <$username> could not be created.";
371
-			}
372
-		} catch(Exception $exception) {
373
-			$error[] = $exception->getMessage();
374
-		}
375
-
376
-		if (empty($error)) {
377
-			$config = \OC::$server->getConfig();
378
-			$config->setAppValue('core', 'installedat', microtime(true));
379
-			$config->setAppValue('core', 'lastupdatedat', microtime(true));
380
-			$config->setAppValue('core', 'vendor', $this->getVendor());
381
-
382
-			$group =\OC::$server->getGroupManager()->createGroup('admin');
383
-			$group->addUser($user);
384
-
385
-			// Install shipped apps and specified app bundles
386
-			Installer::installShippedApps();
387
-			$bundleFetcher = new BundleFetcher(\OC::$server->getL10N('lib'));
388
-			$defaultInstallationBundles = $bundleFetcher->getDefaultInstallationBundle();
389
-			foreach($defaultInstallationBundles as $bundle) {
390
-				try {
391
-					$this->installer->installAppBundle($bundle);
392
-				} catch (Exception $e) {}
393
-			}
394
-
395
-			// create empty file in data dir, so we can later find
396
-			// out that this is indeed an ownCloud data directory
397
-			file_put_contents($config->getSystemValue('datadirectory', \OC::$SERVERROOT.'/data').'/.ocdata', '');
398
-
399
-			// Update .htaccess files
400
-			self::updateHtaccess();
401
-			self::protectDataDirectory();
402
-
403
-			self::installBackgroundJobs();
404
-
405
-			//and we are done
406
-			$config->setSystemValue('installed', true);
407
-
408
-			// Create a session token for the newly created user
409
-			// The token provider requires a working db, so it's not injected on setup
410
-			/* @var $userSession User\Session */
411
-			$userSession = \OC::$server->getUserSession();
412
-			$defaultTokenProvider = \OC::$server->query(DefaultTokenProvider::class);
413
-			$userSession->setTokenProvider($defaultTokenProvider);
414
-			$userSession->login($username, $password);
415
-			$userSession->createSessionToken($request, $userSession->getUser()->getUID(), $username, $password);
416
-
417
-			// Set email for admin
418
-			if (!empty($options['adminemail'])) {
419
-				$config->setUserValue($user->getUID(), 'settings', 'email', $options['adminemail']);
420
-			}
421
-		}
422
-
423
-		return $error;
424
-	}
425
-
426
-	public static function installBackgroundJobs() {
427
-		$jobList = \OC::$server->getJobList();
428
-		$jobList->add(DefaultTokenCleanupJob::class);
429
-		$jobList->add(Rotate::class);
430
-		$jobList->add(BackgroundCleanupJob::class);
431
-	}
432
-
433
-	/**
434
-	 * @return string Absolute path to htaccess
435
-	 */
436
-	private function pathToHtaccess() {
437
-		return \OC::$SERVERROOT.'/.htaccess';
438
-	}
439
-
440
-	/**
441
-	 * Find webroot from config
442
-	 *
443
-	 * @param SystemConfig $config
444
-	 * @return string
445
-	 * @throws InvalidArgumentException when invalid value for overwrite.cli.url
446
-	 */
447
-	private static function findWebRoot(SystemConfig $config): string {
448
-		// For CLI read the value from overwrite.cli.url
449
-		if (\OC::$CLI) {
450
-			$webRoot = $config->getValue('overwrite.cli.url', '');
451
-			if ($webRoot === '') {
452
-				throw new InvalidArgumentException('overwrite.cli.url is empty');
453
-			}
454
-			$webRoot = parse_url($webRoot, PHP_URL_PATH);
455
-			if ($webRoot === null) {
456
-				throw new InvalidArgumentException('invalid value for overwrite.cli.url');
457
-			}
458
-			$webRoot = rtrim($webRoot, '/');
459
-		} else {
460
-			$webRoot = !empty(\OC::$WEBROOT) ? \OC::$WEBROOT : '/';
461
-		}
462
-
463
-		return $webRoot;
464
-	}
465
-
466
-	/**
467
-	 * Append the correct ErrorDocument path for Apache hosts
468
-	 *
469
-	 * @return bool True when success, False otherwise
470
-	 * @throws \OCP\AppFramework\QueryException
471
-	 */
472
-	public static function updateHtaccess() {
473
-		$config = \OC::$server->getSystemConfig();
474
-
475
-		try {
476
-			$webRoot = self::findWebRoot($config);
477
-		} catch (InvalidArgumentException $e) {
478
-			return false;
479
-		}
480
-
481
-		$setupHelper = new \OC\Setup(
482
-			$config,
483
-			\OC::$server->getIniWrapper(),
484
-			\OC::$server->getL10N('lib'),
485
-			\OC::$server->query(Defaults::class),
486
-			\OC::$server->getLogger(),
487
-			\OC::$server->getSecureRandom(),
488
-			\OC::$server->query(Installer::class)
489
-		);
490
-
491
-		$htaccessContent = file_get_contents($setupHelper->pathToHtaccess());
492
-		$content = "#### DO NOT CHANGE ANYTHING ABOVE THIS LINE ####\n";
493
-		$htaccessContent = explode($content, $htaccessContent, 2)[0];
494
-
495
-		//custom 403 error page
496
-		$content .= "\nErrorDocument 403 " . $webRoot . '/';
497
-
498
-		//custom 404 error page
499
-		$content .= "\nErrorDocument 404 " . $webRoot . '/';
500
-
501
-		// Add rewrite rules if the RewriteBase is configured
502
-		$rewriteBase = $config->getValue('htaccess.RewriteBase', '');
503
-		if($rewriteBase !== '') {
504
-			$content .= "\n<IfModule mod_rewrite.c>";
505
-			$content .= "\n  Options -MultiViews";
506
-			$content .= "\n  RewriteRule ^core/js/oc.js$ index.php [PT,E=PATH_INFO:$1]";
507
-			$content .= "\n  RewriteRule ^core/preview.png$ index.php [PT,E=PATH_INFO:$1]";
508
-			$content .= "\n  RewriteCond %{REQUEST_FILENAME} !\\.(css|js|svg|gif|png|html|ttf|woff|ico|jpg|jpeg)$";
509
-			$content .= "\n  RewriteCond %{REQUEST_FILENAME} !core/img/favicon.ico$";
510
-			$content .= "\n  RewriteCond %{REQUEST_FILENAME} !core/img/manifest.json$";
511
-			$content .= "\n  RewriteCond %{REQUEST_FILENAME} !/remote.php";
512
-			$content .= "\n  RewriteCond %{REQUEST_FILENAME} !/public.php";
513
-			$content .= "\n  RewriteCond %{REQUEST_FILENAME} !/cron.php";
514
-			$content .= "\n  RewriteCond %{REQUEST_FILENAME} !/core/ajax/update.php";
515
-			$content .= "\n  RewriteCond %{REQUEST_FILENAME} !/status.php";
516
-			$content .= "\n  RewriteCond %{REQUEST_FILENAME} !/ocs/v1.php";
517
-			$content .= "\n  RewriteCond %{REQUEST_FILENAME} !/ocs/v2.php";
518
-			$content .= "\n  RewriteCond %{REQUEST_FILENAME} !/robots.txt";
519
-			$content .= "\n  RewriteCond %{REQUEST_FILENAME} !/updater/";
520
-			$content .= "\n  RewriteCond %{REQUEST_FILENAME} !/ocs-provider/";
521
-			$content .= "\n  RewriteCond %{REQUEST_URI} !^/\\.well-known/(acme-challenge|pki-validation)/.*";
522
-			$content .= "\n  RewriteRule . index.php [PT,E=PATH_INFO:$1]";
523
-			$content .= "\n  RewriteBase " . $rewriteBase;
524
-			$content .= "\n  <IfModule mod_env.c>";
525
-			$content .= "\n    SetEnv front_controller_active true";
526
-			$content .= "\n    <IfModule mod_dir.c>";
527
-			$content .= "\n      DirectorySlash off";
528
-			$content .= "\n    </IfModule>";
529
-			$content .= "\n  </IfModule>";
530
-			$content .= "\n</IfModule>";
531
-		}
532
-
533
-		if ($content !== '') {
534
-			//suppress errors in case we don't have permissions for it
535
-			return (bool) @file_put_contents($setupHelper->pathToHtaccess(), $htaccessContent.$content . "\n");
536
-		}
537
-
538
-		return false;
539
-	}
540
-
541
-	public static function protectDataDirectory() {
542
-		//Require all denied
543
-		$now =  date('Y-m-d H:i:s');
544
-		$content = "# Generated by Nextcloud on $now\n";
545
-		$content.= "# line below if for Apache 2.4\n";
546
-		$content.= "<ifModule mod_authz_core.c>\n";
547
-		$content.= "Require all denied\n";
548
-		$content.= "</ifModule>\n\n";
549
-		$content.= "# line below if for Apache 2.2\n";
550
-		$content.= "<ifModule !mod_authz_core.c>\n";
551
-		$content.= "deny from all\n";
552
-		$content.= "Satisfy All\n";
553
-		$content.= "</ifModule>\n\n";
554
-		$content.= "# section for Apache 2.2 and 2.4\n";
555
-		$content.= "<ifModule mod_autoindex.c>\n";
556
-		$content.= "IndexIgnore *\n";
557
-		$content.= "</ifModule>\n";
558
-
559
-		$baseDir = \OC::$server->getConfig()->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data');
560
-		file_put_contents($baseDir . '/.htaccess', $content);
561
-		file_put_contents($baseDir . '/index.html', '');
562
-	}
563
-
564
-	/**
565
-	 * Return vendor from which this version was published
566
-	 *
567
-	 * @return string Get the vendor
568
-	 *
569
-	 * Copy of \OC\Updater::getVendor()
570
-	 */
571
-	private function getVendor() {
572
-		// this should really be a JSON file
573
-		require \OC::$SERVERROOT . '/version.php';
574
-		/** @var string $vendor */
575
-		return (string) $vendor;
576
-	}
59
+    /** @var SystemConfig */
60
+    protected $config;
61
+    /** @var IniGetWrapper */
62
+    protected $iniWrapper;
63
+    /** @var IL10N */
64
+    protected $l10n;
65
+    /** @var Defaults */
66
+    protected $defaults;
67
+    /** @var ILogger */
68
+    protected $logger;
69
+    /** @var ISecureRandom */
70
+    protected $random;
71
+    /** @var Installer */
72
+    protected $installer;
73
+
74
+    /**
75
+     * @param SystemConfig $config
76
+     * @param IniGetWrapper $iniWrapper
77
+     * @param IL10N $l10n
78
+     * @param Defaults $defaults
79
+     * @param ILogger $logger
80
+     * @param ISecureRandom $random
81
+     * @param Installer $installer
82
+     */
83
+    public function __construct(SystemConfig $config,
84
+                            IniGetWrapper $iniWrapper,
85
+                            IL10N $l10n,
86
+                            Defaults $defaults,
87
+                            ILogger $logger,
88
+                            ISecureRandom $random,
89
+                            Installer $installer
90
+        ) {
91
+        $this->config = $config;
92
+        $this->iniWrapper = $iniWrapper;
93
+        $this->l10n = $l10n;
94
+        $this->defaults = $defaults;
95
+        $this->logger = $logger;
96
+        $this->random = $random;
97
+        $this->installer = $installer;
98
+    }
99
+
100
+    static protected $dbSetupClasses = [
101
+        'mysql' => \OC\Setup\MySQL::class,
102
+        'pgsql' => \OC\Setup\PostgreSQL::class,
103
+        'oci'   => \OC\Setup\OCI::class,
104
+        'sqlite' => \OC\Setup\Sqlite::class,
105
+        'sqlite3' => \OC\Setup\Sqlite::class,
106
+    ];
107
+
108
+    /**
109
+     * Wrapper around the "class_exists" PHP function to be able to mock it
110
+     * @param string $name
111
+     * @return bool
112
+     */
113
+    protected function class_exists($name) {
114
+        return class_exists($name);
115
+    }
116
+
117
+    /**
118
+     * Wrapper around the "is_callable" PHP function to be able to mock it
119
+     * @param string $name
120
+     * @return bool
121
+     */
122
+    protected function is_callable($name) {
123
+        return is_callable($name);
124
+    }
125
+
126
+    /**
127
+     * Wrapper around \PDO::getAvailableDrivers
128
+     *
129
+     * @return array
130
+     */
131
+    protected function getAvailableDbDriversForPdo() {
132
+        return \PDO::getAvailableDrivers();
133
+    }
134
+
135
+    /**
136
+     * Get the available and supported databases of this instance
137
+     *
138
+     * @param bool $allowAllDatabases
139
+     * @return array
140
+     * @throws Exception
141
+     */
142
+    public function getSupportedDatabases($allowAllDatabases = false) {
143
+        $availableDatabases = [
144
+            'sqlite' =>  [
145
+                'type' => 'pdo',
146
+                'call' => 'sqlite',
147
+                'name' => 'SQLite',
148
+            ],
149
+            'mysql' => [
150
+                'type' => 'pdo',
151
+                'call' => 'mysql',
152
+                'name' => 'MySQL/MariaDB',
153
+            ],
154
+            'pgsql' => [
155
+                'type' => 'pdo',
156
+                'call' => 'pgsql',
157
+                'name' => 'PostgreSQL',
158
+            ],
159
+            'oci' => [
160
+                'type' => 'function',
161
+                'call' => 'oci_connect',
162
+                'name' => 'Oracle',
163
+            ],
164
+        ];
165
+        if ($allowAllDatabases) {
166
+            $configuredDatabases = array_keys($availableDatabases);
167
+        } else {
168
+            $configuredDatabases = $this->config->getValue('supportedDatabases',
169
+                ['sqlite', 'mysql', 'pgsql']);
170
+        }
171
+        if(!is_array($configuredDatabases)) {
172
+            throw new Exception('Supported databases are not properly configured.');
173
+        }
174
+
175
+        $supportedDatabases = array();
176
+
177
+        foreach($configuredDatabases as $database) {
178
+            if(array_key_exists($database, $availableDatabases)) {
179
+                $working = false;
180
+                $type = $availableDatabases[$database]['type'];
181
+                $call = $availableDatabases[$database]['call'];
182
+
183
+                if ($type === 'function') {
184
+                    $working = $this->is_callable($call);
185
+                } elseif($type === 'pdo') {
186
+                    $working = in_array($call, $this->getAvailableDbDriversForPdo(), true);
187
+                }
188
+                if($working) {
189
+                    $supportedDatabases[$database] = $availableDatabases[$database]['name'];
190
+                }
191
+            }
192
+        }
193
+
194
+        return $supportedDatabases;
195
+    }
196
+
197
+    /**
198
+     * Gathers system information like database type and does
199
+     * a few system checks.
200
+     *
201
+     * @return array of system info, including an "errors" value
202
+     * in case of errors/warnings
203
+     */
204
+    public function getSystemInfo($allowAllDatabases = false) {
205
+        $databases = $this->getSupportedDatabases($allowAllDatabases);
206
+
207
+        $dataDir = $this->config->getValue('datadirectory', \OC::$SERVERROOT.'/data');
208
+
209
+        $errors = [];
210
+
211
+        // Create data directory to test whether the .htaccess works
212
+        // Notice that this is not necessarily the same data directory as the one
213
+        // that will effectively be used.
214
+        if(!file_exists($dataDir)) {
215
+            @mkdir($dataDir);
216
+        }
217
+        $htAccessWorking = true;
218
+        if (is_dir($dataDir) && is_writable($dataDir)) {
219
+            // Protect data directory here, so we can test if the protection is working
220
+            self::protectDataDirectory();
221
+
222
+            try {
223
+                $util = new \OC_Util();
224
+                $htAccessWorking = $util->isHtaccessWorking(\OC::$server->getConfig());
225
+            } catch (\OC\HintException $e) {
226
+                $errors[] = [
227
+                    'error' => $e->getMessage(),
228
+                    'hint' => $e->getHint(),
229
+                ];
230
+                $htAccessWorking = false;
231
+            }
232
+        }
233
+
234
+        if (\OC_Util::runningOnMac()) {
235
+            $errors[] = [
236
+                'error' => $this->l10n->t(
237
+                    'Mac OS X is not supported and %s will not work properly on this platform. ' .
238
+                    'Use it at your own risk! ',
239
+                    [$this->defaults->getName()]
240
+                ),
241
+                'hint' => $this->l10n->t('For the best results, please consider using a GNU/Linux server instead.'),
242
+            ];
243
+        }
244
+
245
+        if($this->iniWrapper->getString('open_basedir') !== '' && PHP_INT_SIZE === 4) {
246
+            $errors[] = [
247
+                'error' => $this->l10n->t(
248
+                    'It seems that this %s instance is running on a 32-bit PHP environment and the open_basedir has been configured in php.ini. ' .
249
+                    'This will lead to problems with files over 4 GB and is highly discouraged.',
250
+                    [$this->defaults->getName()]
251
+                ),
252
+                'hint' => $this->l10n->t('Please remove the open_basedir setting within your php.ini or switch to 64-bit PHP.'),
253
+            ];
254
+        }
255
+
256
+        return array(
257
+            'hasSQLite' => isset($databases['sqlite']),
258
+            'hasMySQL' => isset($databases['mysql']),
259
+            'hasPostgreSQL' => isset($databases['pgsql']),
260
+            'hasOracle' => isset($databases['oci']),
261
+            'databases' => $databases,
262
+            'directory' => $dataDir,
263
+            'htaccessWorking' => $htAccessWorking,
264
+            'errors' => $errors,
265
+        );
266
+    }
267
+
268
+    /**
269
+     * @param $options
270
+     * @return array
271
+     */
272
+    public function install($options) {
273
+        $l = $this->l10n;
274
+
275
+        $error = array();
276
+        $dbType = $options['dbtype'];
277
+
278
+        if(empty($options['adminlogin'])) {
279
+            $error[] = $l->t('Set an admin username.');
280
+        }
281
+        if(empty($options['adminpass'])) {
282
+            $error[] = $l->t('Set an admin password.');
283
+        }
284
+        if(empty($options['directory'])) {
285
+            $options['directory'] = \OC::$SERVERROOT."/data";
286
+        }
287
+
288
+        if (!isset(self::$dbSetupClasses[$dbType])) {
289
+            $dbType = 'sqlite';
290
+        }
291
+
292
+        $username = htmlspecialchars_decode($options['adminlogin']);
293
+        $password = htmlspecialchars_decode($options['adminpass']);
294
+        $dataDir = htmlspecialchars_decode($options['directory']);
295
+
296
+        $class = self::$dbSetupClasses[$dbType];
297
+        /** @var \OC\Setup\AbstractDatabase $dbSetup */
298
+        $dbSetup = new $class($l, $this->config, $this->logger, $this->random);
299
+        $error = array_merge($error, $dbSetup->validate($options));
300
+
301
+        // validate the data directory
302
+        if ((!is_dir($dataDir) && !mkdir($dataDir)) || !is_writable($dataDir)) {
303
+            $error[] = $l->t("Can't create or write into the data directory %s", array($dataDir));
304
+        }
305
+
306
+        if (!empty($error)) {
307
+            return $error;
308
+        }
309
+
310
+        $request = \OC::$server->getRequest();
311
+
312
+        //no errors, good
313
+        if(isset($options['trusted_domains'])
314
+            && is_array($options['trusted_domains'])) {
315
+            $trustedDomains = $options['trusted_domains'];
316
+        } else {
317
+            $trustedDomains = [$request->getInsecureServerHost()];
318
+        }
319
+
320
+        //use sqlite3 when available, otherwise sqlite2 will be used.
321
+        if ($dbType === 'sqlite' && class_exists('SQLite3')) {
322
+            $dbType = 'sqlite3';
323
+        }
324
+
325
+        //generate a random salt that is used to salt the local user passwords
326
+        $salt = $this->random->generate(30);
327
+        // generate a secret
328
+        $secret = $this->random->generate(48);
329
+
330
+        //write the config file
331
+        $newConfigValues = [
332
+            'passwordsalt'		=> $salt,
333
+            'secret'			=> $secret,
334
+            'trusted_domains'	=> $trustedDomains,
335
+            'datadirectory'		=> $dataDir,
336
+            'dbtype'			=> $dbType,
337
+            'version'			=> implode('.', \OCP\Util::getVersion()),
338
+        ];
339
+
340
+        if ($this->config->getValue('overwrite.cli.url', null) === null) {
341
+            $newConfigValues['overwrite.cli.url'] = $request->getServerProtocol() . '://' . $request->getInsecureServerHost() . \OC::$WEBROOT;
342
+        }
343
+
344
+        $this->config->setValues($newConfigValues);
345
+
346
+        try {
347
+            $dbSetup->initialize($options);
348
+            $dbSetup->setupDatabase($username);
349
+            // apply necessary migrations
350
+            $dbSetup->runMigrations();
351
+        } catch (\OC\DatabaseSetupException $e) {
352
+            $error[] = [
353
+                'error' => $e->getMessage(),
354
+                'hint' => $e->getHint(),
355
+            ];
356
+            return $error;
357
+        } catch (Exception $e) {
358
+            $error[] = [
359
+                'error' => 'Error while trying to create admin user: ' . $e->getMessage(),
360
+                'hint' => '',
361
+            ];
362
+            return $error;
363
+        }
364
+
365
+        //create the user and group
366
+        $user =  null;
367
+        try {
368
+            $user = \OC::$server->getUserManager()->createUser($username, $password);
369
+            if (!$user) {
370
+                $error[] = "User <$username> could not be created.";
371
+            }
372
+        } catch(Exception $exception) {
373
+            $error[] = $exception->getMessage();
374
+        }
375
+
376
+        if (empty($error)) {
377
+            $config = \OC::$server->getConfig();
378
+            $config->setAppValue('core', 'installedat', microtime(true));
379
+            $config->setAppValue('core', 'lastupdatedat', microtime(true));
380
+            $config->setAppValue('core', 'vendor', $this->getVendor());
381
+
382
+            $group =\OC::$server->getGroupManager()->createGroup('admin');
383
+            $group->addUser($user);
384
+
385
+            // Install shipped apps and specified app bundles
386
+            Installer::installShippedApps();
387
+            $bundleFetcher = new BundleFetcher(\OC::$server->getL10N('lib'));
388
+            $defaultInstallationBundles = $bundleFetcher->getDefaultInstallationBundle();
389
+            foreach($defaultInstallationBundles as $bundle) {
390
+                try {
391
+                    $this->installer->installAppBundle($bundle);
392
+                } catch (Exception $e) {}
393
+            }
394
+
395
+            // create empty file in data dir, so we can later find
396
+            // out that this is indeed an ownCloud data directory
397
+            file_put_contents($config->getSystemValue('datadirectory', \OC::$SERVERROOT.'/data').'/.ocdata', '');
398
+
399
+            // Update .htaccess files
400
+            self::updateHtaccess();
401
+            self::protectDataDirectory();
402
+
403
+            self::installBackgroundJobs();
404
+
405
+            //and we are done
406
+            $config->setSystemValue('installed', true);
407
+
408
+            // Create a session token for the newly created user
409
+            // The token provider requires a working db, so it's not injected on setup
410
+            /* @var $userSession User\Session */
411
+            $userSession = \OC::$server->getUserSession();
412
+            $defaultTokenProvider = \OC::$server->query(DefaultTokenProvider::class);
413
+            $userSession->setTokenProvider($defaultTokenProvider);
414
+            $userSession->login($username, $password);
415
+            $userSession->createSessionToken($request, $userSession->getUser()->getUID(), $username, $password);
416
+
417
+            // Set email for admin
418
+            if (!empty($options['adminemail'])) {
419
+                $config->setUserValue($user->getUID(), 'settings', 'email', $options['adminemail']);
420
+            }
421
+        }
422
+
423
+        return $error;
424
+    }
425
+
426
+    public static function installBackgroundJobs() {
427
+        $jobList = \OC::$server->getJobList();
428
+        $jobList->add(DefaultTokenCleanupJob::class);
429
+        $jobList->add(Rotate::class);
430
+        $jobList->add(BackgroundCleanupJob::class);
431
+    }
432
+
433
+    /**
434
+     * @return string Absolute path to htaccess
435
+     */
436
+    private function pathToHtaccess() {
437
+        return \OC::$SERVERROOT.'/.htaccess';
438
+    }
439
+
440
+    /**
441
+     * Find webroot from config
442
+     *
443
+     * @param SystemConfig $config
444
+     * @return string
445
+     * @throws InvalidArgumentException when invalid value for overwrite.cli.url
446
+     */
447
+    private static function findWebRoot(SystemConfig $config): string {
448
+        // For CLI read the value from overwrite.cli.url
449
+        if (\OC::$CLI) {
450
+            $webRoot = $config->getValue('overwrite.cli.url', '');
451
+            if ($webRoot === '') {
452
+                throw new InvalidArgumentException('overwrite.cli.url is empty');
453
+            }
454
+            $webRoot = parse_url($webRoot, PHP_URL_PATH);
455
+            if ($webRoot === null) {
456
+                throw new InvalidArgumentException('invalid value for overwrite.cli.url');
457
+            }
458
+            $webRoot = rtrim($webRoot, '/');
459
+        } else {
460
+            $webRoot = !empty(\OC::$WEBROOT) ? \OC::$WEBROOT : '/';
461
+        }
462
+
463
+        return $webRoot;
464
+    }
465
+
466
+    /**
467
+     * Append the correct ErrorDocument path for Apache hosts
468
+     *
469
+     * @return bool True when success, False otherwise
470
+     * @throws \OCP\AppFramework\QueryException
471
+     */
472
+    public static function updateHtaccess() {
473
+        $config = \OC::$server->getSystemConfig();
474
+
475
+        try {
476
+            $webRoot = self::findWebRoot($config);
477
+        } catch (InvalidArgumentException $e) {
478
+            return false;
479
+        }
480
+
481
+        $setupHelper = new \OC\Setup(
482
+            $config,
483
+            \OC::$server->getIniWrapper(),
484
+            \OC::$server->getL10N('lib'),
485
+            \OC::$server->query(Defaults::class),
486
+            \OC::$server->getLogger(),
487
+            \OC::$server->getSecureRandom(),
488
+            \OC::$server->query(Installer::class)
489
+        );
490
+
491
+        $htaccessContent = file_get_contents($setupHelper->pathToHtaccess());
492
+        $content = "#### DO NOT CHANGE ANYTHING ABOVE THIS LINE ####\n";
493
+        $htaccessContent = explode($content, $htaccessContent, 2)[0];
494
+
495
+        //custom 403 error page
496
+        $content .= "\nErrorDocument 403 " . $webRoot . '/';
497
+
498
+        //custom 404 error page
499
+        $content .= "\nErrorDocument 404 " . $webRoot . '/';
500
+
501
+        // Add rewrite rules if the RewriteBase is configured
502
+        $rewriteBase = $config->getValue('htaccess.RewriteBase', '');
503
+        if($rewriteBase !== '') {
504
+            $content .= "\n<IfModule mod_rewrite.c>";
505
+            $content .= "\n  Options -MultiViews";
506
+            $content .= "\n  RewriteRule ^core/js/oc.js$ index.php [PT,E=PATH_INFO:$1]";
507
+            $content .= "\n  RewriteRule ^core/preview.png$ index.php [PT,E=PATH_INFO:$1]";
508
+            $content .= "\n  RewriteCond %{REQUEST_FILENAME} !\\.(css|js|svg|gif|png|html|ttf|woff|ico|jpg|jpeg)$";
509
+            $content .= "\n  RewriteCond %{REQUEST_FILENAME} !core/img/favicon.ico$";
510
+            $content .= "\n  RewriteCond %{REQUEST_FILENAME} !core/img/manifest.json$";
511
+            $content .= "\n  RewriteCond %{REQUEST_FILENAME} !/remote.php";
512
+            $content .= "\n  RewriteCond %{REQUEST_FILENAME} !/public.php";
513
+            $content .= "\n  RewriteCond %{REQUEST_FILENAME} !/cron.php";
514
+            $content .= "\n  RewriteCond %{REQUEST_FILENAME} !/core/ajax/update.php";
515
+            $content .= "\n  RewriteCond %{REQUEST_FILENAME} !/status.php";
516
+            $content .= "\n  RewriteCond %{REQUEST_FILENAME} !/ocs/v1.php";
517
+            $content .= "\n  RewriteCond %{REQUEST_FILENAME} !/ocs/v2.php";
518
+            $content .= "\n  RewriteCond %{REQUEST_FILENAME} !/robots.txt";
519
+            $content .= "\n  RewriteCond %{REQUEST_FILENAME} !/updater/";
520
+            $content .= "\n  RewriteCond %{REQUEST_FILENAME} !/ocs-provider/";
521
+            $content .= "\n  RewriteCond %{REQUEST_URI} !^/\\.well-known/(acme-challenge|pki-validation)/.*";
522
+            $content .= "\n  RewriteRule . index.php [PT,E=PATH_INFO:$1]";
523
+            $content .= "\n  RewriteBase " . $rewriteBase;
524
+            $content .= "\n  <IfModule mod_env.c>";
525
+            $content .= "\n    SetEnv front_controller_active true";
526
+            $content .= "\n    <IfModule mod_dir.c>";
527
+            $content .= "\n      DirectorySlash off";
528
+            $content .= "\n    </IfModule>";
529
+            $content .= "\n  </IfModule>";
530
+            $content .= "\n</IfModule>";
531
+        }
532
+
533
+        if ($content !== '') {
534
+            //suppress errors in case we don't have permissions for it
535
+            return (bool) @file_put_contents($setupHelper->pathToHtaccess(), $htaccessContent.$content . "\n");
536
+        }
537
+
538
+        return false;
539
+    }
540
+
541
+    public static function protectDataDirectory() {
542
+        //Require all denied
543
+        $now =  date('Y-m-d H:i:s');
544
+        $content = "# Generated by Nextcloud on $now\n";
545
+        $content.= "# line below if for Apache 2.4\n";
546
+        $content.= "<ifModule mod_authz_core.c>\n";
547
+        $content.= "Require all denied\n";
548
+        $content.= "</ifModule>\n\n";
549
+        $content.= "# line below if for Apache 2.2\n";
550
+        $content.= "<ifModule !mod_authz_core.c>\n";
551
+        $content.= "deny from all\n";
552
+        $content.= "Satisfy All\n";
553
+        $content.= "</ifModule>\n\n";
554
+        $content.= "# section for Apache 2.2 and 2.4\n";
555
+        $content.= "<ifModule mod_autoindex.c>\n";
556
+        $content.= "IndexIgnore *\n";
557
+        $content.= "</ifModule>\n";
558
+
559
+        $baseDir = \OC::$server->getConfig()->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data');
560
+        file_put_contents($baseDir . '/.htaccess', $content);
561
+        file_put_contents($baseDir . '/index.html', '');
562
+    }
563
+
564
+    /**
565
+     * Return vendor from which this version was published
566
+     *
567
+     * @return string Get the vendor
568
+     *
569
+     * Copy of \OC\Updater::getVendor()
570
+     */
571
+    private function getVendor() {
572
+        // this should really be a JSON file
573
+        require \OC::$SERVERROOT . '/version.php';
574
+        /** @var string $vendor */
575
+        return (string) $vendor;
576
+    }
577 577
 }
Please login to merge, or discard this patch.
core/Command/Maintenance/Install.php 1 patch
Indentation   +165 added lines, -165 removed lines patch added patch discarded remove patch
@@ -43,169 +43,169 @@
 block discarded – undo
43 43
 
44 44
 class Install extends Command {
45 45
 
46
-	/**
47
-	 * @var SystemConfig
48
-	 */
49
-	private $config;
50
-
51
-	public function __construct(SystemConfig $config) {
52
-		parent::__construct();
53
-		$this->config = $config;
54
-	}
55
-
56
-	protected function configure() {
57
-		$this
58
-			->setName('maintenance:install')
59
-			->setDescription('install Nextcloud')
60
-			->addOption('database', null, InputOption::VALUE_REQUIRED, 'Supported database type', 'sqlite')
61
-			->addOption('database-name', null, InputOption::VALUE_REQUIRED, 'Name of the database')
62
-			->addOption('database-host', null, InputOption::VALUE_REQUIRED, 'Hostname of the database', 'localhost')
63
-			->addOption('database-port', null, InputOption::VALUE_REQUIRED, 'Port the database is listening on')
64
-			->addOption('database-user', null, InputOption::VALUE_REQUIRED, 'User name to connect to the database')
65
-			->addOption('database-pass', null, InputOption::VALUE_OPTIONAL, 'Password of the database user', null)
66
-			->addOption('database-table-prefix', null, InputOption::VALUE_OPTIONAL, 'Prefix for all tables (default: oc_)', null)
67
-			->addOption('database-table-space', null, InputOption::VALUE_OPTIONAL, 'Table space of the database (oci only)', null)
68
-			->addOption('admin-user', null, InputOption::VALUE_REQUIRED, 'User name of the admin account', 'admin')
69
-			->addOption('admin-pass', null, InputOption::VALUE_REQUIRED, 'Password of the admin account')
70
-			->addOption('admin-email', null, InputOption::VALUE_OPTIONAL, 'E-Mail of the admin account')
71
-			->addOption('data-dir', null, InputOption::VALUE_REQUIRED, 'Path to data directory', \OC::$SERVERROOT."/data");
72
-	}
73
-
74
-	protected function execute(InputInterface $input, OutputInterface $output) {
75
-
76
-		// validate the environment
77
-		$server = \OC::$server;
78
-		$setupHelper = new Setup(
79
-			$this->config,
80
-			$server->getIniWrapper(),
81
-			$server->getL10N('lib'),
82
-			$server->query(Defaults::class),
83
-			$server->getLogger(),
84
-			$server->getSecureRandom(),
85
-			\OC::$server->query(Installer::class)
86
-		);
87
-		$sysInfo = $setupHelper->getSystemInfo(true);
88
-		$errors = $sysInfo['errors'];
89
-		if (count($errors) > 0) {
90
-			$this->printErrors($output, $errors);
91
-
92
-			// ignore the OS X setup warning
93
-			if(count($errors) !== 1 ||
94
-				(string)$errors[0]['error'] !== 'Mac OS X is not supported and Nextcloud will not work properly on this platform. Use it at your own risk! ') {
95
-				return 1;
96
-			}
97
-		}
98
-
99
-		// validate user input
100
-		$options = $this->validateInput($input, $output, array_keys($sysInfo['databases']));
101
-
102
-		// perform installation
103
-		$errors = $setupHelper->install($options);
104
-		if (count($errors) > 0) {
105
-			$this->printErrors($output, $errors);
106
-			return 1;
107
-		}
108
-		$output->writeln("Nextcloud was successfully installed");
109
-		return 0;
110
-	}
111
-
112
-	/**
113
-	 * @param InputInterface $input
114
-	 * @param OutputInterface $output
115
-	 * @param string[] $supportedDatabases
116
-	 * @return array
117
-	 */
118
-	protected function validateInput(InputInterface $input, OutputInterface $output, $supportedDatabases) {
119
-		$db = strtolower($input->getOption('database'));
120
-
121
-		if (!in_array($db, $supportedDatabases)) {
122
-			throw new InvalidArgumentException("Database <$db> is not supported.");
123
-		}
124
-
125
-		$dbUser = $input->getOption('database-user');
126
-		$dbPass = $input->getOption('database-pass');
127
-		$dbName = $input->getOption('database-name');
128
-		$dbPort = $input->getOption('database-port');
129
-		if ($db === 'oci') {
130
-			// an empty hostname needs to be read from the raw parameters
131
-			$dbHost = $input->getParameterOption('--database-host', '');
132
-		} else {
133
-			$dbHost = $input->getOption('database-host');
134
-		}
135
-		$dbTablePrefix = 'oc_';
136
-		if ($input->hasParameterOption('--database-table-prefix')) {
137
-			$dbTablePrefix = (string) $input->getOption('database-table-prefix');
138
-			$dbTablePrefix = trim($dbTablePrefix);
139
-		}
140
-		if ($input->hasParameterOption('--database-pass')) {
141
-			$dbPass = (string) $input->getOption('database-pass');
142
-		}
143
-		$adminLogin = $input->getOption('admin-user');
144
-		$adminPassword = $input->getOption('admin-pass');
145
-		$adminEmail = $input->getOption('admin-email');
146
-		$dataDir = $input->getOption('data-dir');
147
-
148
-		if ($db !== 'sqlite') {
149
-			if (is_null($dbUser)) {
150
-				throw new InvalidArgumentException("Database user not provided.");
151
-			}
152
-			if (is_null($dbName)) {
153
-				throw new InvalidArgumentException("Database name not provided.");
154
-			}
155
-			if (is_null($dbPass)) {
156
-				/** @var QuestionHelper $helper */
157
-				$helper = $this->getHelper('question');
158
-				$question = new Question('What is the password to access the database with user <'.$dbUser.'>?');
159
-				$question->setHidden(true);
160
-				$question->setHiddenFallback(false);
161
-				$dbPass = $helper->ask($input, $output, $question);
162
-			}
163
-		}
164
-
165
-		if (is_null($adminPassword)) {
166
-			/** @var QuestionHelper $helper */
167
-			$helper = $this->getHelper('question');
168
-			$question = new Question('What is the password you like to use for the admin account <'.$adminLogin.'>?');
169
-			$question->setHidden(true);
170
-			$question->setHiddenFallback(false);
171
-			$adminPassword = $helper->ask($input, $output, $question);
172
-		}
173
-
174
-		if ($adminEmail !== null && !filter_var($adminEmail, FILTER_VALIDATE_EMAIL)) {
175
-			throw new InvalidArgumentException('Invalid e-mail-address <' . $adminEmail . '> for <' . $adminLogin . '>.');
176
-		}
177
-
178
-		$options = [
179
-			'dbtype' => $db,
180
-			'dbuser' => $dbUser,
181
-			'dbpass' => $dbPass,
182
-			'dbname' => $dbName,
183
-			'dbhost' => $dbHost,
184
-			'dbport' => $dbPort,
185
-			'dbtableprefix' => $dbTablePrefix,
186
-			'adminlogin' => $adminLogin,
187
-			'adminpass' => $adminPassword,
188
-			'adminemail' => $adminEmail,
189
-			'directory' => $dataDir
190
-		];
191
-		if ($db === 'oci') {
192
-			$options['dbtablespace'] = $input->getParameterOption('--database-table-space', '');
193
-		}
194
-		return $options;
195
-	}
196
-
197
-	/**
198
-	 * @param OutputInterface $output
199
-	 * @param $errors
200
-	 */
201
-	protected function printErrors(OutputInterface $output, $errors) {
202
-		foreach ($errors as $error) {
203
-			if (is_array($error)) {
204
-				$output->writeln('<error>' . (string)$error['error'] . '</error>');
205
-				$output->writeln('<info> -> ' . (string)$error['hint'] . '</info>');
206
-			} else {
207
-				$output->writeln('<error>' . (string)$error . '</error>');
208
-			}
209
-		}
210
-	}
46
+    /**
47
+     * @var SystemConfig
48
+     */
49
+    private $config;
50
+
51
+    public function __construct(SystemConfig $config) {
52
+        parent::__construct();
53
+        $this->config = $config;
54
+    }
55
+
56
+    protected function configure() {
57
+        $this
58
+            ->setName('maintenance:install')
59
+            ->setDescription('install Nextcloud')
60
+            ->addOption('database', null, InputOption::VALUE_REQUIRED, 'Supported database type', 'sqlite')
61
+            ->addOption('database-name', null, InputOption::VALUE_REQUIRED, 'Name of the database')
62
+            ->addOption('database-host', null, InputOption::VALUE_REQUIRED, 'Hostname of the database', 'localhost')
63
+            ->addOption('database-port', null, InputOption::VALUE_REQUIRED, 'Port the database is listening on')
64
+            ->addOption('database-user', null, InputOption::VALUE_REQUIRED, 'User name to connect to the database')
65
+            ->addOption('database-pass', null, InputOption::VALUE_OPTIONAL, 'Password of the database user', null)
66
+            ->addOption('database-table-prefix', null, InputOption::VALUE_OPTIONAL, 'Prefix for all tables (default: oc_)', null)
67
+            ->addOption('database-table-space', null, InputOption::VALUE_OPTIONAL, 'Table space of the database (oci only)', null)
68
+            ->addOption('admin-user', null, InputOption::VALUE_REQUIRED, 'User name of the admin account', 'admin')
69
+            ->addOption('admin-pass', null, InputOption::VALUE_REQUIRED, 'Password of the admin account')
70
+            ->addOption('admin-email', null, InputOption::VALUE_OPTIONAL, 'E-Mail of the admin account')
71
+            ->addOption('data-dir', null, InputOption::VALUE_REQUIRED, 'Path to data directory', \OC::$SERVERROOT."/data");
72
+    }
73
+
74
+    protected function execute(InputInterface $input, OutputInterface $output) {
75
+
76
+        // validate the environment
77
+        $server = \OC::$server;
78
+        $setupHelper = new Setup(
79
+            $this->config,
80
+            $server->getIniWrapper(),
81
+            $server->getL10N('lib'),
82
+            $server->query(Defaults::class),
83
+            $server->getLogger(),
84
+            $server->getSecureRandom(),
85
+            \OC::$server->query(Installer::class)
86
+        );
87
+        $sysInfo = $setupHelper->getSystemInfo(true);
88
+        $errors = $sysInfo['errors'];
89
+        if (count($errors) > 0) {
90
+            $this->printErrors($output, $errors);
91
+
92
+            // ignore the OS X setup warning
93
+            if(count($errors) !== 1 ||
94
+                (string)$errors[0]['error'] !== 'Mac OS X is not supported and Nextcloud will not work properly on this platform. Use it at your own risk! ') {
95
+                return 1;
96
+            }
97
+        }
98
+
99
+        // validate user input
100
+        $options = $this->validateInput($input, $output, array_keys($sysInfo['databases']));
101
+
102
+        // perform installation
103
+        $errors = $setupHelper->install($options);
104
+        if (count($errors) > 0) {
105
+            $this->printErrors($output, $errors);
106
+            return 1;
107
+        }
108
+        $output->writeln("Nextcloud was successfully installed");
109
+        return 0;
110
+    }
111
+
112
+    /**
113
+     * @param InputInterface $input
114
+     * @param OutputInterface $output
115
+     * @param string[] $supportedDatabases
116
+     * @return array
117
+     */
118
+    protected function validateInput(InputInterface $input, OutputInterface $output, $supportedDatabases) {
119
+        $db = strtolower($input->getOption('database'));
120
+
121
+        if (!in_array($db, $supportedDatabases)) {
122
+            throw new InvalidArgumentException("Database <$db> is not supported.");
123
+        }
124
+
125
+        $dbUser = $input->getOption('database-user');
126
+        $dbPass = $input->getOption('database-pass');
127
+        $dbName = $input->getOption('database-name');
128
+        $dbPort = $input->getOption('database-port');
129
+        if ($db === 'oci') {
130
+            // an empty hostname needs to be read from the raw parameters
131
+            $dbHost = $input->getParameterOption('--database-host', '');
132
+        } else {
133
+            $dbHost = $input->getOption('database-host');
134
+        }
135
+        $dbTablePrefix = 'oc_';
136
+        if ($input->hasParameterOption('--database-table-prefix')) {
137
+            $dbTablePrefix = (string) $input->getOption('database-table-prefix');
138
+            $dbTablePrefix = trim($dbTablePrefix);
139
+        }
140
+        if ($input->hasParameterOption('--database-pass')) {
141
+            $dbPass = (string) $input->getOption('database-pass');
142
+        }
143
+        $adminLogin = $input->getOption('admin-user');
144
+        $adminPassword = $input->getOption('admin-pass');
145
+        $adminEmail = $input->getOption('admin-email');
146
+        $dataDir = $input->getOption('data-dir');
147
+
148
+        if ($db !== 'sqlite') {
149
+            if (is_null($dbUser)) {
150
+                throw new InvalidArgumentException("Database user not provided.");
151
+            }
152
+            if (is_null($dbName)) {
153
+                throw new InvalidArgumentException("Database name not provided.");
154
+            }
155
+            if (is_null($dbPass)) {
156
+                /** @var QuestionHelper $helper */
157
+                $helper = $this->getHelper('question');
158
+                $question = new Question('What is the password to access the database with user <'.$dbUser.'>?');
159
+                $question->setHidden(true);
160
+                $question->setHiddenFallback(false);
161
+                $dbPass = $helper->ask($input, $output, $question);
162
+            }
163
+        }
164
+
165
+        if (is_null($adminPassword)) {
166
+            /** @var QuestionHelper $helper */
167
+            $helper = $this->getHelper('question');
168
+            $question = new Question('What is the password you like to use for the admin account <'.$adminLogin.'>?');
169
+            $question->setHidden(true);
170
+            $question->setHiddenFallback(false);
171
+            $adminPassword = $helper->ask($input, $output, $question);
172
+        }
173
+
174
+        if ($adminEmail !== null && !filter_var($adminEmail, FILTER_VALIDATE_EMAIL)) {
175
+            throw new InvalidArgumentException('Invalid e-mail-address <' . $adminEmail . '> for <' . $adminLogin . '>.');
176
+        }
177
+
178
+        $options = [
179
+            'dbtype' => $db,
180
+            'dbuser' => $dbUser,
181
+            'dbpass' => $dbPass,
182
+            'dbname' => $dbName,
183
+            'dbhost' => $dbHost,
184
+            'dbport' => $dbPort,
185
+            'dbtableprefix' => $dbTablePrefix,
186
+            'adminlogin' => $adminLogin,
187
+            'adminpass' => $adminPassword,
188
+            'adminemail' => $adminEmail,
189
+            'directory' => $dataDir
190
+        ];
191
+        if ($db === 'oci') {
192
+            $options['dbtablespace'] = $input->getParameterOption('--database-table-space', '');
193
+        }
194
+        return $options;
195
+    }
196
+
197
+    /**
198
+     * @param OutputInterface $output
199
+     * @param $errors
200
+     */
201
+    protected function printErrors(OutputInterface $output, $errors) {
202
+        foreach ($errors as $error) {
203
+            if (is_array($error)) {
204
+                $output->writeln('<error>' . (string)$error['error'] . '</error>');
205
+                $output->writeln('<info> -> ' . (string)$error['hint'] . '</info>');
206
+            } else {
207
+                $output->writeln('<error>' . (string)$error . '</error>');
208
+            }
209
+        }
210
+    }
211 211
 }
Please login to merge, or discard this patch.