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