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