Completed
Push — master ( 4d101c...278637 )
by Lukas
18:49 queued 06:10
created

MySQL::setupDatabase()   B

Complexity

Conditions 4
Paths 4

Size

Total Lines 24
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 13
nc 4
nop 1
dl 0
loc 24
rs 8.6845
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();
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
		$result = $connection->executeQuery($query, [$this->dbName, $this->tablePrefix.'users']);
55
		$row = $result->fetch();
56
		if (!$row or $row['count(*)'] === '0') {
57
			\OC_DB::createDbFromStructure($this->dbDefinitionFile);
58
		}
59
	}
60
61
	/**
62
	 * @param \OC\DB\Connection $connection
63
	 */
64
	private function createDatabase($connection) {
65
		try{
66
			$name = $this->dbName;
67
			$user = $this->dbUser;
68
			//we can't use OC_DB functions here because we need to connect as the administrative user.
69
			$characterSet = $this->config->getValue('mysql.utf8mb4', false) ? 'utf8mb4' : 'utf8';
70
			$query = "CREATE DATABASE IF NOT EXISTS `$name` CHARACTER SET $characterSet COLLATE ${characterSet}_bin;";
71
			$connection->executeUpdate($query);
72
		} catch (\Exception $ex) {
73
			$this->logger->error('Database creation failed: {error}', [
74
				'app' => 'mysql.setup',
75
				'error' => $ex->getMessage()
76
			]);
77
			return;
78
		}
79
80
		try {
81
			//this query will fail if there aren't the right permissions, ignore the error
82
			$query="GRANT ALL PRIVILEGES ON `$name` . * TO '$user'";
83
			$connection->executeUpdate($query);
84
		} catch (\Exception $ex) {
85
			$this->logger->debug('Could not automatically grant privileges, this can be ignored if database user already had privileges: {error}', [
86
				'app' => 'mysql.setup',
87
				'error' => $ex->getMessage()
88
			]);
89
		}
90
	}
91
92
	/**
93
	 * @param IDBConnection $connection
94
	 * @throws \OC\DatabaseSetupException
95
	 */
96
	private function createDBUser($connection) {
97
		try{
98
			$name = $this->dbUser;
99
			$password = $this->dbPassword;
100
			// we need to create 2 accounts, one for global use and one for local user. if we don't specify the local one,
101
			// the anonymous user would take precedence when there is one.
102
			$query = "CREATE USER '$name'@'localhost' IDENTIFIED BY '$password'";
103
			$connection->executeUpdate($query);
104
			$query = "CREATE USER '$name'@'%' IDENTIFIED BY '$password'";
105
			$connection->executeUpdate($query);
106
		}
107
		catch (\Exception $ex){
108
			$this->logger->error('Database User creation failed: {error}', [
109
                                'app' => 'mysql.setup',
110
                                'error' => $ex->getMessage()
111
                        ]);
112
		}
113
	}
114
115
	/**
116
	 * @param $username
117
	 * @param IDBConnection $connection
118
	 * @return array
119
	 */
120
	private function createSpecificUser($username, $connection) {
121
		try {
122
			//user already specified in config
123
			$oldUser = $this->config->getValue('dbuser', false);
124
125
			//we don't have a dbuser specified in config
126
			if ($this->dbUser !== $oldUser) {
127
				//add prefix to the admin username to prevent collisions
128
				$adminUser = substr('oc_' . $username, 0, 16);
129
130
				$i = 1;
131
				while (true) {
132
					//this should be enough to check for admin rights in mysql
133
					$query = 'SELECT user FROM mysql.user WHERE user=?';
134
					$result = $connection->executeQuery($query, [$adminUser]);
135
136
					//current dbuser has admin rights
137
					if ($result) {
138
						$data = $result->fetchAll();
139
						//new dbuser does not exist
140
						if (count($data) === 0) {
141
							//use the admin login data for the new database user
142
							$this->dbUser = $adminUser;
143
144
							//create a random password so we don't need to store the admin password in the config file
145
							$this->dbPassword =  $this->random->generate(30);
146
147
							$this->createDBUser($connection);
148
149
							break;
150
						} else {
151
							//repeat with different username
152
							$length = strlen((string)$i);
153
							$adminUser = substr('oc_' . $username, 0, 16 - $length) . $i;
154
							$i++;
155
						}
156
					} else {
157
						break;
158
					}
159
				};
160
			}
161
		} catch (\Exception $ex) {
162
			$this->logger->info('Can not create a new MySQL user, will continue with the provided user: {error}', [
163
				'app' => 'mysql.setup',
164
				'error' => $ex->getMessage()
165
			]);
166
		}
167
168
		$this->config->setValues([
169
			'dbuser' => $this->dbUser,
170
			'dbpassword' => $this->dbPassword,
171
		]);
172
	}
173
}
174