setup.php 30.8 KB
Newer Older
Robin Appelman's avatar
Robin Appelman committed
1
2
<?php

3
class DatabaseSetupException extends Exception
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
{
	private $hint;

	public function __construct($message, $hint, $code = 0, Exception $previous = null) {
		$this->hint = $hint;
		parent::__construct($message, $code, $previous);
	}

	public function __toString() {
		return __CLASS__ . ": [{$this->code}]: {$this->message} ({$this->hint})\n";
	}

	public function getHint() {
		return $this->hint;
	}
}

Jakob Sack's avatar
Jakob Sack committed
21
class OC_Setup {
22
23
24
25
26

	public static function getTrans(){
		return OC_L10N::get('lib');
	}

François Kubler's avatar
François Kubler committed
27
	public static function install($options) {
28
29
		$l = self::getTrans();

François Kubler's avatar
François Kubler committed
30
31
		$error = array();
		$dbtype = $options['dbtype'];
Bart Visscher's avatar
Bart Visscher committed
32

François Kubler's avatar
François Kubler committed
33
		if(empty($options['adminlogin'])) {
34
			$error[] = $l->t('Set an admin username.');
François Kubler's avatar
François Kubler committed
35
36
		}
		if(empty($options['adminpass'])) {
37
			$error[] = $l->t('Set an admin password.');
François Kubler's avatar
François Kubler committed
38
39
		}
		if(empty($options['directory'])) {
kondou's avatar
kondou committed
40
			$options['directory'] = OC::$SERVERROOT."/data";
François Kubler's avatar
François Kubler committed
41
		}
Serge Martin's avatar
Serge Martin committed
42

Tobias Ramforth's avatar
Tobias Ramforth committed
43
44
		if($dbtype == 'mysql' or $dbtype == 'pgsql' or $dbtype == 'oci' or $dbtype == 'mssql') { //mysql and postgresql needs more config options
			if($dbtype == 'mysql')
45
				$dbprettyname = 'MySQL';
Tobias Ramforth's avatar
Tobias Ramforth committed
46
			else if($dbtype == 'pgsql')
47
				$dbprettyname = 'PostgreSQL';
Tobias Ramforth's avatar
Tobias Ramforth committed
48
			else if ($dbtype == 'mssql')
Thomas Mueller's avatar
Thomas Mueller committed
49
50
				$dbprettyname = 'MS SQL Server';
			else
51
				$dbprettyname = 'Oracle';
52

53

François Kubler's avatar
François Kubler committed
54
			if(empty($options['dbuser'])) {
55
				$error[] = $l->t("%s enter the database username.", array($dbprettyname));
François Kubler's avatar
François Kubler committed
56
57
			}
			if(empty($options['dbname'])) {
58
				$error[] = $l->t("%s enter the database name.", array($dbprettyname));
François Kubler's avatar
François Kubler committed
59
			}
60
			if(substr_count($options['dbname'], '.') >= 1) {
61
				$error[] = $l->t("%s you may not use dots in the database name", array($dbprettyname));
62
			}
63
			if($dbtype != 'oci' && empty($options['dbhost'])) {
64
				$error[] = $l->t("%s set the database host.", array($dbprettyname));
François Kubler's avatar
François Kubler committed
65
			}
Serge Martin's avatar
Serge Martin committed
66
67
		}

François Kubler's avatar
François Kubler committed
68
69
70
71
		if(count($error) == 0) { //no errors, good
			$username = htmlspecialchars_decode($options['adminlogin']);
			$password = htmlspecialchars_decode($options['adminpass']);
			$datadir = htmlspecialchars_decode($options['directory']);
Bart Visscher's avatar
Bart Visscher committed
72

Thomas Mueller's avatar
Thomas Mueller committed
73
			if (OC_Util::runningOnWindows()) {
Thomas Mueller's avatar
Thomas Mueller committed
74
				$datadir = rtrim(realpath($datadir), '\\');
Thomas Mueller's avatar
Thomas Mueller committed
75
76
			}

77
			//use sqlite3 when available, otherise sqlite2 will be used.
Thomas Mueller's avatar
Thomas Mueller committed
78
			if($dbtype=='sqlite' and class_exists('SQLite3')) {
79
80
				$dbtype='sqlite3';
			}
81

82
			//generate a random salt that is used to salt the local user passwords
83
			$salt = OC_Util::generate_random_bytes(30);
84
85
			OC_Config::setValue('passwordsalt', $salt);

Robin Appelman's avatar
Robin Appelman committed
86
			//write the config file
Jakob Sack's avatar
Jakob Sack committed
87
			OC_Config::setValue('datadirectory', $datadir);
Bart Visscher's avatar
Bart Visscher committed
88
			OC_Config::setValue('dbtype', $dbtype);
89
			OC_Config::setValue('version', implode('.', OC_Util::getVersion()));
François Kubler's avatar
François Kubler committed
90
91
92
93
94
			if($dbtype == 'mysql') {
				$dbuser = $options['dbuser'];
				$dbpass = $options['dbpass'];
				$dbname = $options['dbname'];
				$dbhost = $options['dbhost'];
95
				$dbtableprefix = isset($options['dbtableprefix']) ? $options['dbtableprefix'] : 'oc_';
96

Jakob Sack's avatar
Jakob Sack committed
97
98
				OC_Config::setValue('dbname', $dbname);
				OC_Config::setValue('dbhost', $dbhost);
99
				OC_Config::setValue('dbtableprefix', $dbtableprefix);
100

101
102
				try {
					self::setupMySQLDatabase($dbhost, $dbuser, $dbpass, $dbname, $dbtableprefix, $username);
103
				} catch (DatabaseSetupException $e) {
104
105
106
					$error[] = array(
						'error' => $e->getMessage(),
						'hint' => $e->getHint()
Thomas Mueller's avatar
Thomas Mueller committed
107
					);
108
					return($error);
109
				} catch (Exception $e) {
François Kubler's avatar
François Kubler committed
110
					$error[] = array(
111
112
						'error' => $e->getMessage(),
						'hint' => ''
François Kubler's avatar
François Kubler committed
113
					);
Frank Karlitschek's avatar
Frank Karlitschek committed
114
					return($error);
François Kubler's avatar
François Kubler committed
115
116
				}
			}
Serge Martin's avatar
Serge Martin committed
117
			elseif($dbtype == 'pgsql') {
118
119
120
121
				$dbuser = $options['dbuser'];
				$dbpass = $options['dbpass'];
				$dbname = $options['dbname'];
				$dbhost = $options['dbhost'];
122
				$dbtableprefix = isset($options['dbtableprefix']) ? $options['dbtableprefix'] : 'oc_';
123
124
125
126
127
128
129
130

				OC_Config::setValue('dbname', $dbname);
				OC_Config::setValue('dbhost', $dbhost);
				OC_Config::setValue('dbtableprefix', $dbtableprefix);

				try {
					self::setupPostgreSQLDatabase($dbhost, $dbuser, $dbpass, $dbname, $dbtableprefix, $username);
				} catch (Exception $e) {
Serge Martin's avatar
Serge Martin committed
131
					$error[] = array(
132
133
						'error' => $l->t('PostgreSQL username and/or password not valid'),
						'hint' => $l->t('You need to enter either an existing account or the administrator.')
Serge Martin's avatar
Serge Martin committed
134
					);
135
					return $error;
Serge Martin's avatar
Serge Martin committed
136
137
				}
			}
138
139
140
141
142
			elseif($dbtype == 'oci') {
				$dbuser = $options['dbuser'];
				$dbpass = $options['dbpass'];
				$dbname = $options['dbname'];
				$dbtablespace = $options['dbtablespace'];
143
				$dbhost = isset($options['dbhost'])?$options['dbhost']:'';
144
				$dbtableprefix = isset($options['dbtableprefix']) ? $options['dbtableprefix'] : 'oc_';
145
146
147
148
149
150
151
152
153

				OC_Config::setValue('dbname', $dbname);
				OC_Config::setValue('dbtablespace', $dbtablespace);
				OC_Config::setValue('dbhost', $dbhost);
				OC_Config::setValue('dbtableprefix', $dbtableprefix);

				try {
					self::setupOCIDatabase($dbhost, $dbuser, $dbpass, $dbname, $dbtableprefix, $dbtablespace, $username);
				} catch (Exception $e) {
154
					$error[] = array(
155
156
						'error' => $l->t('Oracle username and/or password not valid'),
						'hint' => $l->t('You need to enter either an existing account or the administrator.')
157
158
159
160
					);
					return $error;
				}
			}
Thomas Mueller's avatar
Thomas Mueller committed
161
			elseif ($dbtype == 'mssql') {
Tobias Ramforth's avatar
Tobias Ramforth committed
162
163
164
165
166
				$dbuser = $options['dbuser'];
				$dbpass = $options['dbpass'];
				$dbname = $options['dbname'];
				$dbhost = $options['dbhost'];
				$dbtableprefix = isset($options['dbtableprefix']) ? $options['dbtableprefix'] : 'oc_';
Thomas Mueller's avatar
Thomas Mueller committed
167

Tobias Ramforth's avatar
Tobias Ramforth committed
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
				OC_Config::setValue('dbname', $dbname);
				OC_Config::setValue('dbhost', $dbhost);
				OC_Config::setValue('dbuser', $dbuser);
				OC_Config::setValue('dbpassword', $dbpass);
				OC_Config::setValue('dbtableprefix', $dbtableprefix);

				try {
					self::setupMSSQLDatabase($dbhost, $dbuser, $dbpass, $dbname, $dbtableprefix);
				} catch (Exception $e) {
					$error[] = array(
						'error' => 'MS SQL username and/or password not valid',
						'hint' => 'You need to enter either an existing account or the administrator.'
					);
					return $error;
				}
Thomas Mueller's avatar
Thomas Mueller committed
183
			}
François Kubler's avatar
François Kubler committed
184
			else {
185
				//delete the old sqlite database first, might cause infinte loops otherwise
Thomas Mueller's avatar
Thomas Mueller committed
186
				if(file_exists("$datadir/owncloud.db")) {
187
188
					unlink("$datadir/owncloud.db");
				}
189
190
				//in case of sqlite, we can always fill the database
				OC_DB::createDbFromStructure('db_structure.xml');
Robin Appelman's avatar
Robin Appelman committed
191
			}
François Kubler's avatar
François Kubler committed
192

193
194
195
196
197
198
199
200
			//create the user and group
			try {
				OC_User::createUser($username, $password);
			}
			catch(Exception $exception) {
				$error[] = $exception->getMessage();
			}

François Kubler's avatar
François Kubler committed
201
			if(count($error) == 0) {
Felix Moeller's avatar
Felix Moeller committed
202
203
				OC_Appconfig::setValue('core', 'installedat', microtime(true));
				OC_Appconfig::setValue('core', 'lastupdatedat', microtime(true));
204
205
				OC_AppConfig::setValue('core', 'remote_core.css', '/core/minimizer.php');
				OC_AppConfig::setValue('core', 'remote_core.js', '/core/minimizer.php');
Thomas Mueller's avatar
Thomas Mueller committed
206

Jakob Sack's avatar
Jakob Sack committed
207
208
				OC_Group::createGroup('admin');
				OC_Group::addToGroup($username, 'admin');
209
				OC_User::login($username, $password);
210

211
				//guess what this does
212
				OC_Installer::installShippedApps();
213

214
				//create htaccess files for apache hosts
215
				if (isset($_SERVER['SERVER_SOFTWARE']) && strstr($_SERVER['SERVER_SOFTWARE'], 'Apache')) {
216
217
					self::createHtaccess();
				}
Bart Visscher's avatar
Bart Visscher committed
218

219
				//and we are done
Jakob Sack's avatar
Jakob Sack committed
220
				OC_Config::setValue('installed', true);
221
			}
Robin Appelman's avatar
Robin Appelman committed
222
		}
François Kubler's avatar
François Kubler committed
223

Robin Appelman's avatar
Robin Appelman committed
224
225
		return $error;
	}
226

227
	private static function setupMySQLDatabase($dbhost, $dbuser, $dbpass, $dbname, $dbtableprefix, $username) {
228
		//check if the database user has admin right
229
		$l = self::getTrans();
230
231
		$connection = @mysql_connect($dbhost, $dbuser, $dbpass);
		if(!$connection) {
232
233
			throw new DatabaseSetupException($l->t('MySQL username and/or password not valid'),
				$l->t('You need to enter either an existing account or the administrator.'));
234
235
236
		}
		$oldUser=OC_Config::getValue('dbuser', false);

Bart Visscher's avatar
Bart Visscher committed
237
238
		//this should be enough to check for admin rights in mysql
		$query="SELECT user FROM mysql.user WHERE user='$dbuser'";
239
240
241
242
243
244
245
		if(mysql_query($query, $connection)) {
			//use the admin login data for the new database user

			//add prefix to the mysql user name to prevent collisions
			$dbusername=substr('oc_'.$username, 0, 16);
			if($dbusername!=$oldUser) {
				//hash the password so we don't need to store the admin config in the config file
246
				$dbpassword=OC_Util::generate_random_bytes(30);
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267

				self::createDBUser($dbusername, $dbpassword, $connection);

				OC_Config::setValue('dbuser', $dbusername);
				OC_Config::setValue('dbpassword', $dbpassword);
			}

			//create the database
			self::createMySQLDatabase($dbname, $dbusername, $connection);
		}
		else {
			if($dbuser!=$oldUser) {
				OC_Config::setValue('dbuser', $dbuser);
				OC_Config::setValue('dbpassword', $dbpass);
			}

			//create the database
			self::createMySQLDatabase($dbname, $dbuser, $connection);
		}

		//fill the database if needed
268
269
		$query='select count(*) from information_schema.tables'
			." where table_schema='$dbname' AND table_name = '{$dbtableprefix}users';";
270
271
272
273
274
275
276
277
278
279
		$result = mysql_query($query, $connection);
		if($result) {
			$row=mysql_fetch_row($result);
		}
		if(!$result or $row[0]==0) {
			OC_DB::createDbFromStructure('db_structure.xml');
		}
		mysql_close($connection);
	}

Felix Moeller's avatar
Felix Moeller committed
280
	private static function createMySQLDatabase($name, $user, $connection) {
Robin Appelman's avatar
Robin Appelman committed
281
		//we cant use OC_BD functions here because we need to connect as the administrative user.
282
		$l = self::getTrans();
François Kubler's avatar
François Kubler committed
283
284
285
		$query = "CREATE DATABASE IF NOT EXISTS  `$name`";
		$result = mysql_query($query, $connection);
		if(!$result) {
286
287
			$entry = $l->t('DB Error: "%s"', array(mysql_error($connection))) . '<br />';
			$entry .= $l->t('Offending command was: "%s"', array($query)) . '<br />';
288
			\OC_Log::write('setup.mssql', $entry, \OC_Log::WARN);
Robin Appelman's avatar
Robin Appelman committed
289
290
		}
		$query="GRANT ALL PRIVILEGES ON  `$name` . * TO  '$user'";
291

292
293
		//this query will fail if there aren't the right permissions, ignore the error
		mysql_query($query, $connection);
Robin Appelman's avatar
Robin Appelman committed
294
	}
295

Felix Moeller's avatar
Felix Moeller committed
296
	private static function createDBUser($name, $password, $connection) {
Bart Visscher's avatar
Bart Visscher committed
297
		// we need to create 2 accounts, one for global use and one for local user. if we don't specify the local one,
François Kubler's avatar
François Kubler committed
298
		// the anonymous user would take precedence when there is one.
299
		$l = self::getTrans();
François Kubler's avatar
François Kubler committed
300
301
		$query = "CREATE USER '$name'@'localhost' IDENTIFIED BY '$password'";
		$result = mysql_query($query, $connection);
302
		if (!$result) {
303
304
			throw new DatabaseSetupException($l->t("MySQL user '%s'@'localhost' exists already.",
				array($name)), $l->t("Drop this user from MySQL", array($name)));
305
		}
François Kubler's avatar
François Kubler committed
306
307
		$query = "CREATE USER '$name'@'%' IDENTIFIED BY '$password'";
		$result = mysql_query($query, $connection);
308
		if (!$result) {
Thomas Mueller's avatar
Thomas Mueller committed
309
			throw new DatabaseSetupException($l->t("MySQL user '%s'@'%%' already exists", array($name)),
310
				$l->t("Drop this user from MySQL."));
311
		}
Robin Appelman's avatar
Robin Appelman committed
312
	}
313

314
315
316
317
	private static function setupPostgreSQLDatabase($dbhost, $dbuser, $dbpass, $dbname, $dbtableprefix, $username) {
		$e_host = addslashes($dbhost);
		$e_user = addslashes($dbuser);
		$e_password = addslashes($dbpass);
318
		$l = self::getTrans();
319
320
321
322
323

		//check if the database user has admin rights
		$connection_string = "host='$e_host' dbname=postgres user='$e_user' password='$e_password'";
		$connection = @pg_connect($connection_string);
		if(!$connection) {
324
			throw new Exception($l->t('PostgreSQL username and/or password not valid'));
325
326
327
328
329
330
331
332
333
334
335
		}
		$e_user = pg_escape_string($dbuser);
		//check for roles creation rights in postgresql
		$query="SELECT 1 FROM pg_roles WHERE rolcreaterole=TRUE AND rolname='$e_user'";
		$result = pg_query($connection, $query);
		if($result and pg_num_rows($result) > 0) {
			//use the admin login data for the new database user

			//add prefix to the postgresql user name to prevent collisions
			$dbusername='oc_'.$username;
			//create a new password so we don't need to store the admin config in the config file
336
			$dbpassword=OC_Util::generate_random_bytes(30);
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368

			self::pg_createDBUser($dbusername, $dbpassword, $connection);

			OC_Config::setValue('dbuser', $dbusername);
			OC_Config::setValue('dbpassword', $dbpassword);

			//create the database
			self::pg_createDatabase($dbname, $dbusername, $connection);
		}
		else {
			OC_Config::setValue('dbuser', $dbuser);
			OC_Config::setValue('dbpassword', $dbpass);

			//create the database
			self::pg_createDatabase($dbname, $dbuser, $connection);
		}

		// the connection to dbname=postgres is not needed anymore
		pg_close($connection);

		// connect to the ownCloud database (dbname=$dbname) and check if it needs to be filled
		$dbuser = OC_Config::getValue('dbuser');
		$dbpass = OC_Config::getValue('dbpassword');

		$e_host = addslashes($dbhost);
		$e_dbname = addslashes($dbname);
		$e_user = addslashes($dbuser);
		$e_password = addslashes($dbpass);

		$connection_string = "host='$e_host' dbname='$e_dbname' user='$e_user' password='$e_password'";
		$connection = @pg_connect($connection_string);
		if(!$connection) {
369
			throw new Exception($l->t('PostgreSQL username and/or password not valid'));
370
371
372
373
374
375
376
377
378
379
380
		}
		$query = "select count(*) FROM pg_class WHERE relname='{$dbtableprefix}users' limit 1";
		$result = pg_query($connection, $query);
		if($result) {
			$row = pg_fetch_row($result);
		}
		if(!$result or $row[0]==0) {
			OC_DB::createDbFromStructure('db_structure.xml');
		}
	}

Felix Moeller's avatar
Felix Moeller committed
381
	private static function pg_createDatabase($name, $user, $connection) {
382

Robin Appelman's avatar
Robin Appelman committed
383
		//we cant use OC_BD functions here because we need to connect as the administrative user.
384
		$l = self::getTrans();
385
386
		$e_name = pg_escape_string($name);
		$e_user = pg_escape_string($user);
Brice Maron's avatar
Brice Maron committed
387
		$query = "select datname from pg_database where datname = '$e_name'";
Serge Martin's avatar
Serge Martin committed
388
389
		$result = pg_query($connection, $query);
		if(!$result) {
390
391
			$entry = $l->t('DB Error: "%s"', array(pg_last_error($connection))) . '<br />';
			$entry .= $l->t('Offending command was: "%s"', array($query)) . '<br />';
392
			\OC_Log::write('setup.pg', $entry, \OC_Log::WARN);
Serge Martin's avatar
Serge Martin committed
393
		}
Brice Maron's avatar
Brice Maron committed
394
395
396
397
398
		if(! pg_fetch_row($result)) {
			//The database does not exists... let's create it
			$query = "CREATE DATABASE \"$e_name\" OWNER \"$e_user\"";
			$result = pg_query($connection, $query);
			if(!$result) {
399
400
				$entry = $l->t('DB Error: "%s"', array(pg_last_error($connection))) . '<br />';
				$entry .= $l->t('Offending command was: "%s"', array($query)) . '<br />';
401
				\OC_Log::write('setup.pg', $entry, \OC_Log::WARN);
Brice Maron's avatar
Brice Maron committed
402
			}
403
404
			else {
				$query = "REVOKE ALL PRIVILEGES ON DATABASE \"$e_name\" FROM PUBLIC";
405
				pg_query($connection, $query);
406
			}
Brice Maron's avatar
Brice Maron committed
407
		}
Serge Martin's avatar
Serge Martin committed
408
409
	}

Felix Moeller's avatar
Felix Moeller committed
410
	private static function pg_createDBUser($name, $password, $connection) {
411
		$l = self::getTrans();
412
413
		$e_name = pg_escape_string($name);
		$e_password = pg_escape_string($password);
Brice Maron's avatar
Brice Maron committed
414
		$query = "select * from pg_roles where rolname='$e_name';";
Serge Martin's avatar
Serge Martin committed
415
416
		$result = pg_query($connection, $query);
		if(!$result) {
417
			$entry = $l->t('DB Error: "%s"', array(pg_last_error($connection))) . '<br />';
Thomas Mueller's avatar
Thomas Mueller committed
418
			$entry .= $l->t('Offending command was: "%s"', array($query)) . '<br />';
419
			\OC_Log::write('setup.pg', $entry, \OC_Log::WARN);
Serge Martin's avatar
Serge Martin committed
420
		}
Brice Maron's avatar
Brice Maron committed
421
422
423
424
425
426

		if(! pg_fetch_row($result)) {
			//user does not exists let's create it :)
			$query = "CREATE USER \"$e_name\" CREATEDB PASSWORD '$e_password';";
			$result = pg_query($connection, $query);
			if(!$result) {
427
428
				$entry = $l->t('DB Error: "%s"', array(pg_last_error($connection))) . '<br />';
				$entry .= $l->t('Offending command was: "%s"', array($query)) . '<br />';
429
				\OC_Log::write('setup.pg', $entry, \OC_Log::WARN);
Brice Maron's avatar
Brice Maron committed
430
431
432
433
434
435
			}
		}
		else { // change password of the existing role
			$query = "ALTER ROLE \"$e_name\" WITH PASSWORD '$e_password';";
			$result = pg_query($connection, $query);
			if(!$result) {
436
437
				$entry = $l->t('DB Error: "%s"', array(pg_last_error($connection))) . '<br />';
				$entry .= $l->t('Offending command was: "%s"', array($query)) . '<br />';
438
				\OC_Log::write('setup.pg', $entry, \OC_Log::WARN);
Brice Maron's avatar
Brice Maron committed
439
440
			}
		}
Serge Martin's avatar
Serge Martin committed
441
	}
442

Bart Visscher's avatar
Bart Visscher committed
443
444
	private static function setupOCIDatabase($dbhost, $dbuser, $dbpass, $dbname, $dbtableprefix, $dbtablespace,
		$username) {
445
		$l = self::getTrans();
446
447
448
449
450
451
452
453
454
455
456
		$e_host = addslashes($dbhost);
		$e_dbname = addslashes($dbname);
		//check if the database user has admin right
		if ($e_host == '') {
			$easy_connect_string = $e_dbname; // use dbname as easy connect name
		} else {
			$easy_connect_string = '//'.$e_host.'/'.$e_dbname;
		}
		$connection = @oci_connect($dbuser, $dbpass, $easy_connect_string);
		if(!$connection) {
			$e = oci_error();
457
			throw new Exception($l->t('Oracle username and/or password not valid'));
458
459
460
		}
		//check for roles creation rights in oracle

461
462
		$query='SELECT count(*) FROM user_role_privs, role_sys_privs'
			." WHERE user_role_privs.granted_role = role_sys_privs.role AND privilege = 'CREATE ROLE'";
463
464
		$stmt = oci_parse($connection, $query);
		if (!$stmt) {
465
466
			$entry = $l->t('DB Error: "%s"', array(oci_last_error($connection))) . '<br />';
			$entry .= $l->t('Offending command was: "%s"', array($query)) . '<br />';
467
			\OC_Log::write('setup.oci', $entry, \OC_Log::WARN);
468
469
470
471
472
473
474
475
476
477
478
		}
		$result = oci_execute($stmt);
		if($result) {
			$row = oci_fetch_row($stmt);
		}
		if($result and $row[0] > 0) {
			//use the admin login data for the new database user

			//add prefix to the oracle user name to prevent collisions
			$dbusername='oc_'.$username;
			//create a new password so we don't need to store the admin config in the config file
479
			$dbpassword=OC_Util::generate_random_bytes(30);
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523

			//oracle passwords are treated as identifiers:
			//  must start with aphanumeric char
			//  needs to be shortened to 30 bytes, as the two " needed to escape the identifier count towards the identifier length.
			$dbpassword=substr($dbpassword, 0, 30);

			self::oci_createDBUser($dbusername, $dbpassword, $dbtablespace, $connection);

			OC_Config::setValue('dbuser', $dbusername);
			OC_Config::setValue('dbname', $dbusername);
			OC_Config::setValue('dbpassword', $dbpassword);

			//create the database not neccessary, oracle implies user = schema
			//self::oci_createDatabase($dbname, $dbusername, $connection);
		} else {

			OC_Config::setValue('dbuser', $dbuser);
			OC_Config::setValue('dbname', $dbname);
			OC_Config::setValue('dbpassword', $dbpass);

			//create the database not neccessary, oracle implies user = schema
			//self::oci_createDatabase($dbname, $dbuser, $connection);
		}

		//FIXME check tablespace exists: select * from user_tablespaces

		// the connection to dbname=oracle is not needed anymore
		oci_close($connection);

		// connect to the oracle database (schema=$dbuser) an check if the schema needs to be filled
		$dbuser = OC_Config::getValue('dbuser');
		//$dbname = OC_Config::getValue('dbname');
		$dbpass = OC_Config::getValue('dbpassword');

		$e_host = addslashes($dbhost);
		$e_dbname = addslashes($dbname);

		if ($e_host == '') {
			$easy_connect_string = $e_dbname; // use dbname as easy connect name
		} else {
			$easy_connect_string = '//'.$e_host.'/'.$e_dbname;
		}
		$connection = @oci_connect($dbuser, $dbpass, $easy_connect_string);
		if(!$connection) {
524
			throw new Exception($l->t('Oracle username and/or password not valid'));
525
526
527
528
529
530
		}
		$query = "SELECT count(*) FROM user_tables WHERE table_name = :un";
		$stmt = oci_parse($connection, $query);
		$un = $dbtableprefix.'users';
		oci_bind_by_name($stmt, ':un', $un);
		if (!$stmt) {
531
			$entry = $l->t('DB Error: "%s"', array(oci_error($connection))) . '<br />';
532
			$entry .= $l->t('Offending command was: "%s"', array($query)) . '<br />';
533
			\OC_Log::write('setup.oci', $entry, \OC_Log::WARN);
534
535
536
537
538
539
540
541
542
543
544
		}
		$result = oci_execute($stmt);

		if($result) {
			$row = oci_fetch_row($stmt);
		}
		if(!$result or $row[0]==0) {
			OC_DB::createDbFromStructure('db_structure.xml');
		}
	}

545
546
547
548
549
550
551
552
	/**
	 *
	 * @param String $name
	 * @param String $password
	 * @param String $tablespace
	 * @param resource $connection
	 */
	private static function oci_createDBUser($name, $password, $tablespace, $connection) {
553
		$l = self::getTrans();
554
555
556
		$query = "SELECT * FROM all_users WHERE USERNAME = :un";
		$stmt = oci_parse($connection, $query);
		if (!$stmt) {
557
			$entry = $l->t('DB Error: "%s"', array(oci_error($connection))) . '<br />';
Thomas Mueller's avatar
Thomas Mueller committed
558
			$entry .= $l->t('Offending command was: "%s"', array($query)) . '<br />';
559
			\OC_Log::write('setup.oci', $entry, \OC_Log::WARN);
560
561
562
563
		}
		oci_bind_by_name($stmt, ':un', $name);
		$result = oci_execute($stmt);
		if(!$result) {
564
			$entry = $l->t('DB Error: "%s"', array(oci_error($connection))) . '<br />';
Thomas Mueller's avatar
Thomas Mueller committed
565
			$entry .= $l->t('Offending command was: "%s"', array($query)) . '<br />';
566
			\OC_Log::write('setup.oci', $entry, \OC_Log::WARN);
567
568
569
570
571
572
573
574
		}

		if(! oci_fetch_row($stmt)) {
			//user does not exists let's create it :)
			//password must start with alphabetic character in oracle
			$query = 'CREATE USER '.$name.' IDENTIFIED BY "'.$password.'" DEFAULT TABLESPACE '.$tablespace; //TODO set default tablespace
			$stmt = oci_parse($connection, $query);
			if (!$stmt) {
575
576
				$entry = $l->t('DB Error: "%s"', array(oci_error($connection))) . '<br />';
				$entry .= $l->t('Offending command was: "%s"', array($query)) . '<br />';
577
				\OC_Log::write('setup.oci', $entry, \OC_Log::WARN);
578
579
580
581
			}
			//oci_bind_by_name($stmt, ':un', $name);
			$result = oci_execute($stmt);
			if(!$result) {
582
				$entry = $l->t('DB Error: "%s"', array(oci_error($connection))) . '<br />';
Thomas Mueller's avatar
Thomas Mueller committed
583
				$entry .= $l->t('Offending command was: "%s", name: %s, password: %s',
584
					array($query, $name, $password)) . '<br />';
585
				\OC_Log::write('setup.oci', $entry, \OC_Log::WARN);
586
587
588
589
590
			}
		} else { // change password of the existing role
			$query = "ALTER USER :un IDENTIFIED BY :pw";
			$stmt = oci_parse($connection, $query);
			if (!$stmt) {
591
592
				$entry = $l->t('DB Error: "%s"', array(oci_error($connection))) . '<br />';
				$entry .= $l->t('Offending command was: "%s"', array($query)) . '<br />';
593
				\OC_Log::write('setup.oci', $entry, \OC_Log::WARN);
594
595
596
597
598
			}
			oci_bind_by_name($stmt, ':un', $name);
			oci_bind_by_name($stmt, ':pw', $password);
			$result = oci_execute($stmt);
			if(!$result) {
599
600
				$entry = $l->t('DB Error: "%s"', array(oci_error($connection))) . '<br />';
				$entry .= $l->t('Offending command was: "%s"', array($query)) . '<br />';
601
				\OC_Log::write('setup.oci', $entry, \OC_Log::WARN);
602
603
			}
		}
Thomas Mueller's avatar
Thomas Mueller committed
604
		// grant necessary roles
605
606
607
		$query = 'GRANT CREATE SESSION, CREATE TABLE, CREATE SEQUENCE, CREATE TRIGGER, UNLIMITED TABLESPACE TO '.$name;
		$stmt = oci_parse($connection, $query);
		if (!$stmt) {
608
609
			$entry = $l->t('DB Error: "%s"', array(oci_error($connection))) . '<br />';
			$entry .= $l->t('Offending command was: "%s"', array($query)) . '<br />';
610
			\OC_Log::write('setup.oci', $entry, \OC_Log::WARN);
611
612
613
		}
		$result = oci_execute($stmt);
		if(!$result) {
614
			$entry = $l->t('DB Error: "%s"', array(oci_error($connection))) . '<br />';
Thomas Mueller's avatar
Thomas Mueller committed
615
			$entry .= $l->t('Offending command was: "%s", name: %s, password: %s',
616
				array($query, $name, $password)) . '<br />';
617
			\OC_Log::write('setup.oci', $entry, \OC_Log::WARN);
618
619
		}
	}
Serge Martin's avatar
Serge Martin committed
620

Tobias Ramforth's avatar
Tobias Ramforth committed
621
	private static function setupMSSQLDatabase($dbhost, $dbuser, $dbpass, $dbname, $dbtableprefix) {
622
623
		$l = self::getTrans();

Tobias Ramforth's avatar
Tobias Ramforth committed
624
625
		//check if the database user has admin right
		$masterConnectionInfo = array( "Database" => "master", "UID" => $dbuser, "PWD" => $dbpass);
Thomas Mueller's avatar
Thomas Mueller committed
626

Tobias Ramforth's avatar
Tobias Ramforth committed
627
628
		$masterConnection = @sqlsrv_connect($dbhost, $masterConnectionInfo);
		if(!$masterConnection) {
Thomas Mueller's avatar
Thomas Mueller committed
629
630
631
632
633
634
			$entry = null;
			if( ($errors = sqlsrv_errors() ) != null) {
				$entry='DB Error: "'.print_r(sqlsrv_errors()).'"<br />';
			} else {
				$entry = '';
			}
635
			throw new Exception($l->t('MS SQL username and/or password not valid: %s', array($entry)));
Tobias Ramforth's avatar
Tobias Ramforth committed
636
637
638
639
640
641
		}

		OC_Config::setValue('dbuser', $dbuser);
		OC_Config::setValue('dbpassword', $dbpass);

		self::mssql_createDBLogin($dbuser, $dbpass, $masterConnection);
Thomas Mueller's avatar
Thomas Mueller committed
642

Tobias Ramforth's avatar
Tobias Ramforth committed
643
		self::mssql_createDatabase($dbname, $masterConnection);
Thomas Mueller's avatar
Thomas Mueller committed
644

645
		self::mssql_createDBUser($dbuser, $dbname, $masterConnection);
Tobias Ramforth's avatar
Tobias Ramforth committed
646
647
648

		sqlsrv_close($masterConnection);

Thomas Mueller's avatar
Thomas Mueller committed
649
		self::mssql_createDatabaseStructure($dbhost, $dbname, $dbuser, $dbpass, $dbtableprefix);
Thomas Mueller's avatar
Thomas Mueller committed
650
	}
Tobias Ramforth's avatar
Tobias Ramforth committed
651

Thomas Mueller's avatar
Thomas Mueller committed
652
	private static function mssql_createDBLogin($name, $password, $connection) {
Tobias Ramforth's avatar
Tobias Ramforth committed
653
654
		$query = "SELECT * FROM master.sys.server_principals WHERE name = '".$name."';";
		$result = sqlsrv_query($connection, $query);
655
656
657
658
659
660
661
		if ($result === false) {
			if ( ($errors = sqlsrv_errors() ) != null) {
				$entry='DB Error: "'.print_r(sqlsrv_errors()).'"<br />';
			} else {
				$entry = '';
			}
			$entry.='Offending command was: '.$query.'<br />';
662
			\OC_Log::write('setup.mssql', $entry, \OC_Log::WARN);
663
		} else {
Tobias Ramforth's avatar
Tobias Ramforth committed
664
			$row = sqlsrv_fetch_array($result);
Thomas Mueller's avatar
Thomas Mueller committed
665

666
667
668
669
670
671
672
			if ($row === false) {
				if ( ($errors = sqlsrv_errors() ) != null) {
					$entry='DB Error: "'.print_r(sqlsrv_errors()).'"<br />';
				} else {
					$entry = '';
				}
				$entry.='Offending command was: '.$query.'<br />';
673
				\OC_Log::write('setup.mssql', $entry, \OC_Log::WARN);
674
675
676
677
678
679
680
681
682
683
684
			} else {
				if ($row == null) {
					$query = "CREATE LOGIN [".$name."] WITH PASSWORD = '".$password."';";
					$result = sqlsrv_query($connection, $query);
					if (!$result or $result === false) {
						if ( ($errors = sqlsrv_errors() ) != null) {
							$entry='DB Error: "'.print_r(sqlsrv_errors()).'"<br />';
						} else {
							$entry = '';
						}
						$entry.='Offending command was: '.$query.'<br />';
685
						\OC_Log::write('setup.mssql', $entry, \OC_Log::WARN);
Thomas Mueller's avatar
Thomas Mueller committed
686
					}
687
688
				}
			}
Tobias Ramforth's avatar
Tobias Ramforth committed
689
690
691
692
693
694
		}
	}

	private static function mssql_createDBUser($name, $dbname, $connection) {
		$query = "SELECT * FROM [".$dbname."].sys.database_principals WHERE name = '".$name."';";
		$result = sqlsrv_query($connection, $query);
695
696
697
698
699
700
701
		if ($result === false) {
			if ( ($errors = sqlsrv_errors() ) != null) {
				$entry='DB Error: "'.print_r(sqlsrv_errors()).'"<br />';
			} else {
				$entry = '';
			}
			$entry.='Offending command was: '.$query.'<br />';
702
			\OC_Log::write('setup.mssql', $entry, \OC_Log::WARN);
703
704
		} else {
			$row = sqlsrv_fetch_array($result);
Thomas Mueller's avatar
Thomas Mueller committed
705

706
707
708
709
710
711
712
			if ($row === false) {
				if ( ($errors = sqlsrv_errors() ) != null) {
					$entry='DB Error: "'.print_r(sqlsrv_errors()).'"<br />';
				} else {
					$entry = '';
				}
				$entry.='Offending command was: '.$query.'<br />';
713
				\OC_Log::write('setup.mssql', $entry, \OC_Log::WARN);
714
715
716
717
718
719
720
721
722
723
724
			} else {
				if ($row == null) {
					$query = "USE [".$dbname."]; CREATE USER [".$name."] FOR LOGIN [".$name."];";
					$result = sqlsrv_query($connection, $query);
					if (!$result || $result === false) {
						if ( ($errors = sqlsrv_errors() ) != null) {
							$entry = 'DB Error: "'.print_r(sqlsrv_errors()).'"<br />';
						} else {
							$entry = '';
						}
						$entry.='Offending command was: '.$query.'<br />';
725
						\OC_Log::write('setup.mssql', $entry, \OC_Log::WARN);
Thomas Mueller's avatar
Thomas Mueller committed
726
					}
727
728
729
730
731
732
733
734
735
736
737
				}

				$query = "USE [".$dbname."]; EXEC sp_addrolemember 'db_owner', '".$name."';";
				$result = sqlsrv_query($connection, $query);
				if (!$result || $result === false) {
					if ( ($errors = sqlsrv_errors() ) != null) {
						$entry='DB Error: "'.print_r(sqlsrv_errors()).'"<br />';
					} else {
						$entry = '';
					}
					$entry.='Offending command was: '.$query.'<br />';
738
					\OC_Log::write('setup.mssql', $entry, \OC_Log::WARN);
739
740
				}
			}
Thomas Mueller's avatar
Thomas Mueller committed
741
		}
Tobias Ramforth's avatar
Tobias Ramforth committed
742
	}
Thomas Mueller's avatar
Thomas Mueller committed
743

Tobias Ramforth's avatar
Tobias Ramforth committed
744
	private static function mssql_createDatabase($dbname, $connection) {
745
		$query = "CREATE DATABASE [".$dbname."];";
Tobias Ramforth's avatar
Tobias Ramforth committed
746
		$result = sqlsrv_query($connection, $query);
747
748
749
750
		if (!$result || $result === false) {
			if ( ($errors = sqlsrv_errors() ) != null) {
				$entry='DB Error: "'.print_r(sqlsrv_errors()).'"<br />';
			} else {
Thomas Mueller's avatar
Thomas Mueller committed
751
				$entry = '';
752
753
			}
			$entry.='Offending command was: '.$query.'<br />';
754
			\OC_Log::write('setup.mssql', $entry, \OC_Log::WARN);
Tobias Ramforth's avatar
Tobias Ramforth committed
755
		}
Thomas Mueller's avatar
Thomas Mueller committed
756
	}
Thomas Mueller's avatar
Thomas Mueller committed
757
758

	private static function mssql_createDatabaseStructure($dbhost, $dbname, $dbuser, $dbpass, $dbtableprefix) {
759
760
761
762
763
764
765
766
767
768
769
770
771
772
		$connectionInfo = array( "Database" => $dbname, "UID" => $dbuser, "PWD" => $dbpass);

		$connection = @sqlsrv_connect($dbhost, $connectionInfo);

		//fill the database if needed
		$query = "SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = '{$dbname}' AND TABLE_NAME = '{$dbtableprefix}users'";
		$result = sqlsrv_query($connection, $query);
		if ($result === false) {
			if ( ($errors = sqlsrv_errors() ) != null) {
				$entry='DB Error: "'.print_r(sqlsrv_errors()).'"<br />';
			} else {
				$entry = '';
			}
			$entry.='Offending command was: '.$query.'<br />';
773
			\OC_Log::write('setup.mssql', $entry, \OC_Log::WARN);
774
775
		} else {
			$row = sqlsrv_fetch_array($result);
Thomas Mueller's avatar
Thomas Mueller committed
776

777
778
779
780
781
782
783
			if ($row === false) {
				if ( ($errors = sqlsrv_errors() ) != null) {
					$entry='DB Error: "'.print_r(sqlsrv_errors()).'"<br />';
				} else {
					$entry = '';
				}
				$entry.='Offending command was: '.$query.'<br />';
784
				\OC_Log::write('setup.mssql', $entry, \OC_Log::WARN);
785
786
787
788
789
790
			} else {
				if ($row == null) {
					OC_DB::createDbFromStructure('db_structure.xml');
				}
			}
		}
Thomas Mueller's avatar
Thomas Mueller committed
791

792
793
		sqlsrv_close($connection);
	}
Thomas Mueller's avatar
Thomas Mueller committed
794

795
796
797
	/**
	 * create .htaccess files for apache hosts
	 */
François Kubler's avatar
François Kubler committed
798
	private static function createHtaccess() {
799
800
801
802
803
804
805
806
807
		$content = "<IfModule mod_fcgid.c>\n";
		$content.= "<IfModule mod_setenvif.c>\n";
		$content.= "<IfModule mod_headers.c>\n";
		$content.= "SetEnvIfNoCase ^Authorization$ \"(.+)\" XAUTHORIZATION=$1\n";
		$content.= "RequestHeader set XAuthorization %{XAUTHORIZATION}e env=XAUTHORIZATION\n";
		$content.= "</IfModule>\n";
		$content.= "</IfModule>\n";
		$content.= "</IfModule>\n";
		$content.= "ErrorDocument 403 ".OC::$WEBROOT."/core/templates/403.php\n";//custom 403 error page
808
		$content.= "ErrorDocument 404 ".OC::$WEBROOT."/core/templates/404.php\n";//custom 404 error page
809
810
811
		$content.= "<IfModule mod_php5.c>\n";
		$content.= "php_value upload_max_filesize 512M\n";//upload limit
		$content.= "php_value post_max_size 512M\n";
812
813
814
815
		$content.= "php_value memory_limit 512M\n";
		$content.= "<IfModule env_module>\n";
		$content.= "  SetEnv htaccessWorking true\n";
		$content.= "</IfModule>\n";
816
		$content.= "</IfModule>\n";
Tom Needham's avatar
Tom Needham committed
817
		$content.= "<IfModule mod_rewrite.c>\n";
818
		$content.= "RewriteEngine on\n";
Bart Visscher's avatar
Bart Visscher committed
819
		$content.= "RewriteRule .* - [env=HTTP_AUTHORIZATION:%{HTTP:Authorization}]\n";
820
821
822
		$content.= "RewriteRule ^.well-known/host-meta /public.php?service=host-meta [QSA,L]\n";
		$content.= "RewriteRule ^.well-known/carddav /remote.php/carddav/ [R]\n";
		$content.= "RewriteRule ^.well-known/caldav /remote.php/caldav/ [R]\n";
Michiel de Jong's avatar
Michiel de Jong committed
823
		$content.= "RewriteRule ^apps/([^/]*)/(.*\.(css|php))$ index.php?app=$1&getfile=$2 [QSA,L]\n";
824
		$content.= "RewriteRule ^remote/(.*) remote.php [QSA,L]\n";
825
		$content.= "</IfModule>\n";
826
827
828
829
		$content.= "<IfModule mod_mime.c>\n";
		$content.= "AddType image/svg+xml svg svgz\n";
		$content.= "AddEncoding gzip svgz\n";
		$content.= "</IfModule>\n";
830
		$content.= "Options -Indexes\n";
831
		@file_put_contents(OC::$SERVERROOT.'/.htaccess', $content); //supress errors in case we don't have permissions for it
832

833
834
835
836
		self::protectDataDirectory();
	}

	public static function protectDataDirectory() {
837
838
		$content = "deny from all\n";
		$content.= "IndexIgnore *";
839
840
		file_put_contents(OC_Config::getValue('datadirectory', OC::$SERVERROOT.'/data').'/.htaccess', $content);
		file_put_contents(OC_Config::getValue('datadirectory', OC::$SERVERROOT.'/data').'/index.html', '');
841
	}
842
843
844
845
846
847

	/**
	 * @brief Post installation checks
	 */
	public static function postSetupCheck($params) {
		// setup was successful -> webdav testing now
848
		$l = self::getTrans();
849
850
851
852
		if (OC_Util::isWebDAVWorking()) {
			header("Location: ".OC::$WEBROOT.'/');
		} else {

Bart Visscher's avatar
Bart Visscher committed
853
			$error = $l->t('Your web server is not yet properly setup to allow files synchronization because the WebDAV interface seems to be broken.');
Bart Visscher's avatar
Bart Visscher committed
854
855
			$hint = $l->t('Please double check the <a href=\'%s\'>installation guides</a>.',
				'http://doc.owncloud.org/server/5.0/admin_manual/installation.html');
856
857

			$tmpl = new OC_Template('', 'error', 'guest');
Lukas Reschke's avatar
Lukas Reschke committed
858
			$tmpl->assign('errors', array(1 => array('error' => $error, 'hint' => $hint)));
859
860
861
862
			$tmpl->printPage();
			exit();
		}
	}
Robin Appelman's avatar
Robin Appelman committed
863
}