Completed
Push — master ( 599977...a7d112 )
by Thomas
10:10
created

MySQL::setupDatabase()   B

Complexity

Conditions 5
Paths 6

Size

Total Lines 26
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

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