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