Completed
Push — master ( 63676d...3faef6 )
by Lukas
28:10 queued 12:28
created

MySQL::setupDatabase()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 20
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 10
nc 2
nop 1
dl 0
loc 20
rs 9.4285
c 0
b 0
f 0
1
<?php
2
/**
3
 * @copyright Copyright (c) 2016, ownCloud, Inc.
4
 *
5
 * @author Bart Visscher <[email protected]>
6
 * @author Joas Schilling <[email protected]>
7
 * @author Michael Göhler <[email protected]>
8
 * @author Robin McCorkell <[email protected]>
9
 * @author Roeland Jago Douma <[email protected]>
10
 * @author Stefan Weil <[email protected]>
11
 * @author Thomas Müller <[email protected]>
12
 *
13
 * @license AGPL-3.0
14
 *
15
 * This code is free software: you can redistribute it and/or modify
16
 * it under the terms of the GNU Affero General Public License, version 3,
17
 * as published by the Free Software Foundation.
18
 *
19
 * This program is distributed in the hope that it will be useful,
20
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
21
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22
 * GNU Affero General Public License for more details.
23
 *
24
 * You should have received a copy of the GNU Affero General Public License, version 3,
25
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
26
 *
27
 */
28
namespace OC\Setup;
29
30
use OC\DB\MySqlTools;
31
use OCP\IDBConnection;
32
33
class MySQL extends AbstractDatabase {
34
	public $dbprettyname = 'MySQL/MariaDB';
35
36
	public function setupDatabase($username) {
37
		//check if the database user has admin right
38
		$connection = $this->connect(['dbname' => null]);
39
40
		// detect mb4
41
		$tools = new MySqlTools();
42
		if ($tools->supports4ByteCharset($connection)) {
43
			$this->config->setValue('mysql.utf8mb4', true);
44
			$connection = $this->connect(['dbname' => null]);
45
		}
46
47
		$this->createSpecificUser($username, $connection);
48
49
		//create the database
50
		$this->createDatabase($connection);
51
52
		//fill the database if needed
53
		$query='select count(*) from information_schema.tables where table_schema=? AND table_name = ?';
54
		$connection->executeQuery($query, [$this->dbName, $this->tablePrefix.'users']);
55
	}
56
57
	/**
58
	 * @param \OC\DB\Connection $connection
59
	 */
60
	private function createDatabase($connection) {
61
		try{
62
			$name = $this->dbName;
63
			$user = $this->dbUser;
64
			//we can't use OC_DB functions here because we need to connect as the administrative user.
65
			$characterSet = $this->config->getValue('mysql.utf8mb4', false) ? 'utf8mb4' : 'utf8';
66
			$query = "CREATE DATABASE IF NOT EXISTS `$name` CHARACTER SET $characterSet COLLATE ${characterSet}_bin;";
67
			$connection->executeUpdate($query);
68
		} catch (\Exception $ex) {
69
			$this->logger->error('Database creation failed: {error}', [
70
				'app' => 'mysql.setup',
71
				'error' => $ex->getMessage()
72
			]);
73
			return;
74
		}
75
76
		try {
77
			//this query will fail if there aren't the right permissions, ignore the error
78
			$query="GRANT ALL PRIVILEGES ON `$name` . * TO '$user'";
79
			$connection->executeUpdate($query);
80
		} catch (\Exception $ex) {
81
			$this->logger->debug('Could not automatically grant privileges, this can be ignored if database user already had privileges: {error}', [
82
				'app' => 'mysql.setup',
83
				'error' => $ex->getMessage()
84
			]);
85
		}
86
	}
87
88
	/**
89
	 * @param IDBConnection $connection
90
	 * @throws \OC\DatabaseSetupException
91
	 */
92
	private function createDBUser($connection) {
93
		try{
94
			$name = $this->dbUser;
95
			$password = $this->dbPassword;
96
			// we need to create 2 accounts, one for global use and one for local user. if we don't specify the local one,
97
			// the anonymous user would take precedence when there is one.
98
			$query = "CREATE USER '$name'@'localhost' IDENTIFIED BY '$password'";
99
			$connection->executeUpdate($query);
100
			$query = "CREATE USER '$name'@'%' IDENTIFIED BY '$password'";
101
			$connection->executeUpdate($query);
102
		}
103
		catch (\Exception $ex){
104
			$this->logger->error('Database User creation failed: {error}', [
105
                                'app' => 'mysql.setup',
106
                                'error' => $ex->getMessage()
107
                        ]);
108
		}
109
	}
110
111
	/**
112
	 * @param $username
113
	 * @param IDBConnection $connection
114
	 * @return array
115
	 */
116
	private function createSpecificUser($username, $connection) {
117
		try {
118
			//user already specified in config
119
			$oldUser = $this->config->getValue('dbuser', false);
120
121
			//we don't have a dbuser specified in config
122
			if ($this->dbUser !== $oldUser) {
123
				//add prefix to the admin username to prevent collisions
124
				$adminUser = substr('oc_' . $username, 0, 16);
125
126
				$i = 1;
127
				while (true) {
128
					//this should be enough to check for admin rights in mysql
129
					$query = 'SELECT user FROM mysql.user WHERE user=?';
130
					$result = $connection->executeQuery($query, [$adminUser]);
131
132
					//current dbuser has admin rights
133
					if ($result) {
134
						$data = $result->fetchAll();
135
						//new dbuser does not exist
136
						if (count($data) === 0) {
137
							//use the admin login data for the new database user
138
							$this->dbUser = $adminUser;
139
140
							//create a random password so we don't need to store the admin password in the config file
141
							$this->dbPassword =  $this->random->generate(30);
142
143
							$this->createDBUser($connection);
144
145
							break;
146
						} else {
147
							//repeat with different username
148
							$length = strlen((string)$i);
149
							$adminUser = substr('oc_' . $username, 0, 16 - $length) . $i;
150
							$i++;
151
						}
152
					} else {
153
						break;
154
					}
155
				};
156
			}
157
		} catch (\Exception $ex) {
158
			$this->logger->info('Can not create a new MySQL user, will continue with the provided user: {error}', [
159
				'app' => 'mysql.setup',
160
				'error' => $ex->getMessage()
161
			]);
162
		}
163
164
		$this->config->setValues([
165
			'dbuser' => $this->dbUser,
166
			'dbpassword' => $this->dbPassword,
167
		]);
168
	}
169
}
170