Passed
Push — master ( 8bf7ec...14f7b2 )
by Roeland
09:58
created
lib/private/Setup.php 1 patch
Indentation   +517 added lines, -517 removed lines patch added patch discarded remove patch
@@ -56,521 +56,521 @@
 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
-			if (!filter_var($webRoot, FILTER_VALIDATE_URL)) {
455
-				throw new InvalidArgumentException('invalid value for overwrite.cli.url');
456
-			}
457
-			$webRoot = rtrim(parse_url($webRoot, PHP_URL_PATH), '/');
458
-		} else {
459
-			$webRoot = !empty(\OC::$WEBROOT) ? \OC::$WEBROOT : '/';
460
-		}
461
-
462
-		return $webRoot;
463
-	}
464
-
465
-	/**
466
-	 * Append the correct ErrorDocument path for Apache hosts
467
-	 *
468
-	 * @return bool True when success, False otherwise
469
-	 * @throws \OCP\AppFramework\QueryException
470
-	 */
471
-	public static function updateHtaccess() {
472
-		$config = \OC::$server->getSystemConfig();
473
-
474
-		try {
475
-			$webRoot = self::findWebRoot($config);
476
-		} catch (InvalidArgumentException $e) {
477
-			return false;
478
-		}
479
-
480
-		$setupHelper = new \OC\Setup(
481
-			$config,
482
-			\OC::$server->getIniWrapper(),
483
-			\OC::$server->getL10N('lib'),
484
-			\OC::$server->query(Defaults::class),
485
-			\OC::$server->getLogger(),
486
-			\OC::$server->getSecureRandom(),
487
-			\OC::$server->query(Installer::class)
488
-		);
489
-
490
-		$htaccessContent = file_get_contents($setupHelper->pathToHtaccess());
491
-		$content = "#### DO NOT CHANGE ANYTHING ABOVE THIS LINE ####\n";
492
-		$htaccessContent = explode($content, $htaccessContent, 2)[0];
493
-
494
-		//custom 403 error page
495
-		$content .= "\nErrorDocument 403 " . $webRoot . '/';
496
-
497
-		//custom 404 error page
498
-		$content .= "\nErrorDocument 404 " . $webRoot . '/';
499
-
500
-		// Add rewrite rules if the RewriteBase is configured
501
-		$rewriteBase = $config->getValue('htaccess.RewriteBase', '');
502
-		if($rewriteBase !== '') {
503
-			$content .= "\n<IfModule mod_rewrite.c>";
504
-			$content .= "\n  Options -MultiViews";
505
-			$content .= "\n  RewriteRule ^core/js/oc.js$ index.php [PT,E=PATH_INFO:$1]";
506
-			$content .= "\n  RewriteRule ^core/preview.png$ index.php [PT,E=PATH_INFO:$1]";
507
-			$content .= "\n  RewriteCond %{REQUEST_FILENAME} !\\.(css|js|svg|gif|png|html|ttf|woff2?|ico|jpg|jpeg)$";
508
-			$content .= "\n  RewriteCond %{REQUEST_FILENAME} !core/img/favicon.ico$";
509
-			$content .= "\n  RewriteCond %{REQUEST_FILENAME} !core/img/manifest.json$";
510
-			$content .= "\n  RewriteCond %{REQUEST_FILENAME} !/remote.php";
511
-			$content .= "\n  RewriteCond %{REQUEST_FILENAME} !/public.php";
512
-			$content .= "\n  RewriteCond %{REQUEST_FILENAME} !/cron.php";
513
-			$content .= "\n  RewriteCond %{REQUEST_FILENAME} !/core/ajax/update.php";
514
-			$content .= "\n  RewriteCond %{REQUEST_FILENAME} !/status.php";
515
-			$content .= "\n  RewriteCond %{REQUEST_FILENAME} !/ocs/v1.php";
516
-			$content .= "\n  RewriteCond %{REQUEST_FILENAME} !/ocs/v2.php";
517
-			$content .= "\n  RewriteCond %{REQUEST_FILENAME} !/robots.txt";
518
-			$content .= "\n  RewriteCond %{REQUEST_FILENAME} !/updater/";
519
-			$content .= "\n  RewriteCond %{REQUEST_FILENAME} !/ocs-provider/";
520
-			$content .= "\n  RewriteCond %{REQUEST_URI} !^/\\.well-known/(acme-challenge|pki-validation)/.*";
521
-			$content .= "\n  RewriteRule . index.php [PT,E=PATH_INFO:$1]";
522
-			$content .= "\n  RewriteBase " . $rewriteBase;
523
-			$content .= "\n  <IfModule mod_env.c>";
524
-			$content .= "\n    SetEnv front_controller_active true";
525
-			$content .= "\n    <IfModule mod_dir.c>";
526
-			$content .= "\n      DirectorySlash off";
527
-			$content .= "\n    </IfModule>";
528
-			$content .= "\n  </IfModule>";
529
-			$content .= "\n</IfModule>";
530
-		}
531
-
532
-		if ($content !== '') {
533
-			//suppress errors in case we don't have permissions for it
534
-			return (bool) @file_put_contents($setupHelper->pathToHtaccess(), $htaccessContent.$content . "\n");
535
-		}
536
-
537
-		return false;
538
-	}
539
-
540
-	public static function protectDataDirectory() {
541
-		//Require all denied
542
-		$now =  date('Y-m-d H:i:s');
543
-		$content = "# Generated by Nextcloud on $now\n";
544
-		$content.= "# line below if for Apache 2.4\n";
545
-		$content.= "<ifModule mod_authz_core.c>\n";
546
-		$content.= "Require all denied\n";
547
-		$content.= "</ifModule>\n\n";
548
-		$content.= "# line below if for Apache 2.2\n";
549
-		$content.= "<ifModule !mod_authz_core.c>\n";
550
-		$content.= "deny from all\n";
551
-		$content.= "Satisfy All\n";
552
-		$content.= "</ifModule>\n\n";
553
-		$content.= "# section for Apache 2.2 and 2.4\n";
554
-		$content.= "<ifModule mod_autoindex.c>\n";
555
-		$content.= "IndexIgnore *\n";
556
-		$content.= "</ifModule>\n";
557
-
558
-		$baseDir = \OC::$server->getConfig()->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data');
559
-		file_put_contents($baseDir . '/.htaccess', $content);
560
-		file_put_contents($baseDir . '/index.html', '');
561
-	}
562
-
563
-	/**
564
-	 * Return vendor from which this version was published
565
-	 *
566
-	 * @return string Get the vendor
567
-	 *
568
-	 * Copy of \OC\Updater::getVendor()
569
-	 */
570
-	private function getVendor() {
571
-		// this should really be a JSON file
572
-		require \OC::$SERVERROOT . '/version.php';
573
-		/** @var string $vendor */
574
-		return (string) $vendor;
575
-	}
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
+            if (!filter_var($webRoot, FILTER_VALIDATE_URL)) {
455
+                throw new InvalidArgumentException('invalid value for overwrite.cli.url');
456
+            }
457
+            $webRoot = rtrim(parse_url($webRoot, PHP_URL_PATH), '/');
458
+        } else {
459
+            $webRoot = !empty(\OC::$WEBROOT) ? \OC::$WEBROOT : '/';
460
+        }
461
+
462
+        return $webRoot;
463
+    }
464
+
465
+    /**
466
+     * Append the correct ErrorDocument path for Apache hosts
467
+     *
468
+     * @return bool True when success, False otherwise
469
+     * @throws \OCP\AppFramework\QueryException
470
+     */
471
+    public static function updateHtaccess() {
472
+        $config = \OC::$server->getSystemConfig();
473
+
474
+        try {
475
+            $webRoot = self::findWebRoot($config);
476
+        } catch (InvalidArgumentException $e) {
477
+            return false;
478
+        }
479
+
480
+        $setupHelper = new \OC\Setup(
481
+            $config,
482
+            \OC::$server->getIniWrapper(),
483
+            \OC::$server->getL10N('lib'),
484
+            \OC::$server->query(Defaults::class),
485
+            \OC::$server->getLogger(),
486
+            \OC::$server->getSecureRandom(),
487
+            \OC::$server->query(Installer::class)
488
+        );
489
+
490
+        $htaccessContent = file_get_contents($setupHelper->pathToHtaccess());
491
+        $content = "#### DO NOT CHANGE ANYTHING ABOVE THIS LINE ####\n";
492
+        $htaccessContent = explode($content, $htaccessContent, 2)[0];
493
+
494
+        //custom 403 error page
495
+        $content .= "\nErrorDocument 403 " . $webRoot . '/';
496
+
497
+        //custom 404 error page
498
+        $content .= "\nErrorDocument 404 " . $webRoot . '/';
499
+
500
+        // Add rewrite rules if the RewriteBase is configured
501
+        $rewriteBase = $config->getValue('htaccess.RewriteBase', '');
502
+        if($rewriteBase !== '') {
503
+            $content .= "\n<IfModule mod_rewrite.c>";
504
+            $content .= "\n  Options -MultiViews";
505
+            $content .= "\n  RewriteRule ^core/js/oc.js$ index.php [PT,E=PATH_INFO:$1]";
506
+            $content .= "\n  RewriteRule ^core/preview.png$ index.php [PT,E=PATH_INFO:$1]";
507
+            $content .= "\n  RewriteCond %{REQUEST_FILENAME} !\\.(css|js|svg|gif|png|html|ttf|woff2?|ico|jpg|jpeg)$";
508
+            $content .= "\n  RewriteCond %{REQUEST_FILENAME} !core/img/favicon.ico$";
509
+            $content .= "\n  RewriteCond %{REQUEST_FILENAME} !core/img/manifest.json$";
510
+            $content .= "\n  RewriteCond %{REQUEST_FILENAME} !/remote.php";
511
+            $content .= "\n  RewriteCond %{REQUEST_FILENAME} !/public.php";
512
+            $content .= "\n  RewriteCond %{REQUEST_FILENAME} !/cron.php";
513
+            $content .= "\n  RewriteCond %{REQUEST_FILENAME} !/core/ajax/update.php";
514
+            $content .= "\n  RewriteCond %{REQUEST_FILENAME} !/status.php";
515
+            $content .= "\n  RewriteCond %{REQUEST_FILENAME} !/ocs/v1.php";
516
+            $content .= "\n  RewriteCond %{REQUEST_FILENAME} !/ocs/v2.php";
517
+            $content .= "\n  RewriteCond %{REQUEST_FILENAME} !/robots.txt";
518
+            $content .= "\n  RewriteCond %{REQUEST_FILENAME} !/updater/";
519
+            $content .= "\n  RewriteCond %{REQUEST_FILENAME} !/ocs-provider/";
520
+            $content .= "\n  RewriteCond %{REQUEST_URI} !^/\\.well-known/(acme-challenge|pki-validation)/.*";
521
+            $content .= "\n  RewriteRule . index.php [PT,E=PATH_INFO:$1]";
522
+            $content .= "\n  RewriteBase " . $rewriteBase;
523
+            $content .= "\n  <IfModule mod_env.c>";
524
+            $content .= "\n    SetEnv front_controller_active true";
525
+            $content .= "\n    <IfModule mod_dir.c>";
526
+            $content .= "\n      DirectorySlash off";
527
+            $content .= "\n    </IfModule>";
528
+            $content .= "\n  </IfModule>";
529
+            $content .= "\n</IfModule>";
530
+        }
531
+
532
+        if ($content !== '') {
533
+            //suppress errors in case we don't have permissions for it
534
+            return (bool) @file_put_contents($setupHelper->pathToHtaccess(), $htaccessContent.$content . "\n");
535
+        }
536
+
537
+        return false;
538
+    }
539
+
540
+    public static function protectDataDirectory() {
541
+        //Require all denied
542
+        $now =  date('Y-m-d H:i:s');
543
+        $content = "# Generated by Nextcloud on $now\n";
544
+        $content.= "# line below if for Apache 2.4\n";
545
+        $content.= "<ifModule mod_authz_core.c>\n";
546
+        $content.= "Require all denied\n";
547
+        $content.= "</ifModule>\n\n";
548
+        $content.= "# line below if for Apache 2.2\n";
549
+        $content.= "<ifModule !mod_authz_core.c>\n";
550
+        $content.= "deny from all\n";
551
+        $content.= "Satisfy All\n";
552
+        $content.= "</ifModule>\n\n";
553
+        $content.= "# section for Apache 2.2 and 2.4\n";
554
+        $content.= "<ifModule mod_autoindex.c>\n";
555
+        $content.= "IndexIgnore *\n";
556
+        $content.= "</ifModule>\n";
557
+
558
+        $baseDir = \OC::$server->getConfig()->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data');
559
+        file_put_contents($baseDir . '/.htaccess', $content);
560
+        file_put_contents($baseDir . '/index.html', '');
561
+    }
562
+
563
+    /**
564
+     * Return vendor from which this version was published
565
+     *
566
+     * @return string Get the vendor
567
+     *
568
+     * Copy of \OC\Updater::getVendor()
569
+     */
570
+    private function getVendor() {
571
+        // this should really be a JSON file
572
+        require \OC::$SERVERROOT . '/version.php';
573
+        /** @var string $vendor */
574
+        return (string) $vendor;
575
+    }
576 576
 }
Please login to merge, or discard this patch.