Passed
Push — master ( cfe098...80ed31 )
by Roeland
28:14 queued 12:09
created
lib/private/Setup/MySQL.php 2 patches
Indentation   +153 added lines, -153 removed lines patch added patch discarded remove patch
@@ -39,157 +39,157 @@
 block discarded – undo
39 39
 use OCP\Security\ISecureRandom;
40 40
 
41 41
 class MySQL extends AbstractDatabase {
42
-	public $dbprettyname = 'MySQL/MariaDB';
43
-
44
-	public function setupDatabase($username) {
45
-		//check if the database user has admin right
46
-		$connection = $this->connect(['dbname' => null]);
47
-
48
-		// detect mb4
49
-		$tools = new MySqlTools();
50
-		if ($tools->supports4ByteCharset(new ConnectionAdapter($connection))) {
51
-			$this->config->setValue('mysql.utf8mb4', true);
52
-			$connection = $this->connect(['dbname' => null]);
53
-		}
54
-
55
-		$this->createSpecificUser($username, new ConnectionAdapter($connection));
56
-
57
-		//create the database
58
-		$this->createDatabase($connection);
59
-
60
-		//fill the database if needed
61
-		$query = 'select count(*) from information_schema.tables where table_schema=? AND table_name = ?';
62
-		$connection->executeQuery($query, [$this->dbName, $this->tablePrefix.'users']);
63
-
64
-		$connection->close();
65
-		$connection = $this->connect();
66
-		try {
67
-			$connection->connect();
68
-		} catch (\Exception $e) {
69
-			$this->logger->logException($e);
70
-			throw new \OC\DatabaseSetupException($this->trans->t('MySQL username and/or password not valid'),
71
-				$this->trans->t('You need to enter details of an existing account.'), 0, $e);
72
-		}
73
-	}
74
-
75
-	/**
76
-	 * @param \OC\DB\Connection $connection
77
-	 */
78
-	private function createDatabase($connection) {
79
-		try {
80
-			$name = $this->dbName;
81
-			$user = $this->dbUser;
82
-			//we can't use OC_DB functions here because we need to connect as the administrative user.
83
-			$characterSet = $this->config->getValue('mysql.utf8mb4', false) ? 'utf8mb4' : 'utf8';
84
-			$query = "CREATE DATABASE IF NOT EXISTS `$name` CHARACTER SET $characterSet COLLATE ${characterSet}_bin;";
85
-			$connection->executeUpdate($query);
86
-		} catch (\Exception $ex) {
87
-			$this->logger->logException($ex, [
88
-				'message' => 'Database creation failed.',
89
-				'level' => ILogger::ERROR,
90
-				'app' => 'mysql.setup',
91
-			]);
92
-			return;
93
-		}
94
-
95
-		try {
96
-			//this query will fail if there aren't the right permissions, ignore the error
97
-			$query = "GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, REFERENCES, INDEX, ALTER, CREATE TEMPORARY TABLES, LOCK TABLES, EXECUTE, CREATE VIEW, SHOW VIEW, CREATE ROUTINE, ALTER ROUTINE, EVENT, TRIGGER ON `$name` . * TO '$user'";
98
-			$connection->executeUpdate($query);
99
-		} catch (\Exception $ex) {
100
-			$this->logger->logException($ex, [
101
-				'message' => 'Could not automatically grant privileges, this can be ignored if database user already had privileges.',
102
-				'level' => ILogger::DEBUG,
103
-				'app' => 'mysql.setup',
104
-			]);
105
-		}
106
-	}
107
-
108
-	/**
109
-	 * @param IDBConnection $connection
110
-	 * @throws \OC\DatabaseSetupException
111
-	 */
112
-	private function createDBUser($connection) {
113
-		try {
114
-			$name = $this->dbUser;
115
-			$password = $this->dbPassword;
116
-			// we need to create 2 accounts, one for global use and one for local user. if we don't specify the local one,
117
-			// the anonymous user would take precedence when there is one.
118
-
119
-			if ($connection->getDatabasePlatform() instanceof Mysql80Platform) {
120
-				$query = "CREATE USER '$name'@'localhost' IDENTIFIED WITH mysql_native_password BY '$password'";
121
-				$connection->executeUpdate($query);
122
-				$query = "CREATE USER '$name'@'%' IDENTIFIED WITH mysql_native_password BY '$password'";
123
-				$connection->executeUpdate($query);
124
-			} else {
125
-				$query = "CREATE USER '$name'@'localhost' IDENTIFIED BY '$password'";
126
-				$connection->executeUpdate($query);
127
-				$query = "CREATE USER '$name'@'%' IDENTIFIED BY '$password'";
128
-				$connection->executeUpdate($query);
129
-			}
130
-		} catch (\Exception $ex) {
131
-			$this->logger->logException($ex, [
132
-				'message' => 'Database user creation failed.',
133
-				'level' => ILogger::ERROR,
134
-				'app' => 'mysql.setup',
135
-			]);
136
-		}
137
-	}
138
-
139
-	/**
140
-	 * @param $username
141
-	 * @param IDBConnection $connection
142
-	 * @return array
143
-	 */
144
-	private function createSpecificUser($username, $connection) {
145
-		try {
146
-			//user already specified in config
147
-			$oldUser = $this->config->getValue('dbuser', false);
148
-
149
-			//we don't have a dbuser specified in config
150
-			if ($this->dbUser !== $oldUser) {
151
-				//add prefix to the admin username to prevent collisions
152
-				$adminUser = substr('oc_' . $username, 0, 16);
153
-
154
-				$i = 1;
155
-				while (true) {
156
-					//this should be enough to check for admin rights in mysql
157
-					$query = 'SELECT user FROM mysql.user WHERE user=?';
158
-					$result = $connection->executeQuery($query, [$adminUser]);
159
-
160
-					//current dbuser has admin rights
161
-					$data = $result->fetchAll();
162
-					$result->closeCursor();
163
-					//new dbuser does not exist
164
-					if (count($data) === 0) {
165
-						//use the admin login data for the new database user
166
-						$this->dbUser = $adminUser;
167
-
168
-						//create a random password so we don't need to store the admin password in the config file
169
-						$this->dbPassword = $this->random->generate(30, ISecureRandom::CHAR_DIGITS . ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_UPPER);
170
-
171
-						$this->createDBUser($connection);
172
-
173
-						break;
174
-					} else {
175
-						//repeat with different username
176
-						$length = strlen((string)$i);
177
-						$adminUser = substr('oc_' . $username, 0, 16 - $length) . $i;
178
-						$i++;
179
-					}
180
-				}
181
-			}
182
-		} catch (\Exception $ex) {
183
-			$this->logger->logException($ex, [
184
-				'message' => 'Can not create a new MySQL user, will continue with the provided user.',
185
-				'level' => ILogger::INFO,
186
-				'app' => 'mysql.setup',
187
-			]);
188
-		}
189
-
190
-		$this->config->setValues([
191
-			'dbuser' => $this->dbUser,
192
-			'dbpassword' => $this->dbPassword,
193
-		]);
194
-	}
42
+    public $dbprettyname = 'MySQL/MariaDB';
43
+
44
+    public function setupDatabase($username) {
45
+        //check if the database user has admin right
46
+        $connection = $this->connect(['dbname' => null]);
47
+
48
+        // detect mb4
49
+        $tools = new MySqlTools();
50
+        if ($tools->supports4ByteCharset(new ConnectionAdapter($connection))) {
51
+            $this->config->setValue('mysql.utf8mb4', true);
52
+            $connection = $this->connect(['dbname' => null]);
53
+        }
54
+
55
+        $this->createSpecificUser($username, new ConnectionAdapter($connection));
56
+
57
+        //create the database
58
+        $this->createDatabase($connection);
59
+
60
+        //fill the database if needed
61
+        $query = 'select count(*) from information_schema.tables where table_schema=? AND table_name = ?';
62
+        $connection->executeQuery($query, [$this->dbName, $this->tablePrefix.'users']);
63
+
64
+        $connection->close();
65
+        $connection = $this->connect();
66
+        try {
67
+            $connection->connect();
68
+        } catch (\Exception $e) {
69
+            $this->logger->logException($e);
70
+            throw new \OC\DatabaseSetupException($this->trans->t('MySQL username and/or password not valid'),
71
+                $this->trans->t('You need to enter details of an existing account.'), 0, $e);
72
+        }
73
+    }
74
+
75
+    /**
76
+     * @param \OC\DB\Connection $connection
77
+     */
78
+    private function createDatabase($connection) {
79
+        try {
80
+            $name = $this->dbName;
81
+            $user = $this->dbUser;
82
+            //we can't use OC_DB functions here because we need to connect as the administrative user.
83
+            $characterSet = $this->config->getValue('mysql.utf8mb4', false) ? 'utf8mb4' : 'utf8';
84
+            $query = "CREATE DATABASE IF NOT EXISTS `$name` CHARACTER SET $characterSet COLLATE ${characterSet}_bin;";
85
+            $connection->executeUpdate($query);
86
+        } catch (\Exception $ex) {
87
+            $this->logger->logException($ex, [
88
+                'message' => 'Database creation failed.',
89
+                'level' => ILogger::ERROR,
90
+                'app' => 'mysql.setup',
91
+            ]);
92
+            return;
93
+        }
94
+
95
+        try {
96
+            //this query will fail if there aren't the right permissions, ignore the error
97
+            $query = "GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, REFERENCES, INDEX, ALTER, CREATE TEMPORARY TABLES, LOCK TABLES, EXECUTE, CREATE VIEW, SHOW VIEW, CREATE ROUTINE, ALTER ROUTINE, EVENT, TRIGGER ON `$name` . * TO '$user'";
98
+            $connection->executeUpdate($query);
99
+        } catch (\Exception $ex) {
100
+            $this->logger->logException($ex, [
101
+                'message' => 'Could not automatically grant privileges, this can be ignored if database user already had privileges.',
102
+                'level' => ILogger::DEBUG,
103
+                'app' => 'mysql.setup',
104
+            ]);
105
+        }
106
+    }
107
+
108
+    /**
109
+     * @param IDBConnection $connection
110
+     * @throws \OC\DatabaseSetupException
111
+     */
112
+    private function createDBUser($connection) {
113
+        try {
114
+            $name = $this->dbUser;
115
+            $password = $this->dbPassword;
116
+            // we need to create 2 accounts, one for global use and one for local user. if we don't specify the local one,
117
+            // the anonymous user would take precedence when there is one.
118
+
119
+            if ($connection->getDatabasePlatform() instanceof Mysql80Platform) {
120
+                $query = "CREATE USER '$name'@'localhost' IDENTIFIED WITH mysql_native_password BY '$password'";
121
+                $connection->executeUpdate($query);
122
+                $query = "CREATE USER '$name'@'%' IDENTIFIED WITH mysql_native_password BY '$password'";
123
+                $connection->executeUpdate($query);
124
+            } else {
125
+                $query = "CREATE USER '$name'@'localhost' IDENTIFIED BY '$password'";
126
+                $connection->executeUpdate($query);
127
+                $query = "CREATE USER '$name'@'%' IDENTIFIED BY '$password'";
128
+                $connection->executeUpdate($query);
129
+            }
130
+        } catch (\Exception $ex) {
131
+            $this->logger->logException($ex, [
132
+                'message' => 'Database user creation failed.',
133
+                'level' => ILogger::ERROR,
134
+                'app' => 'mysql.setup',
135
+            ]);
136
+        }
137
+    }
138
+
139
+    /**
140
+     * @param $username
141
+     * @param IDBConnection $connection
142
+     * @return array
143
+     */
144
+    private function createSpecificUser($username, $connection) {
145
+        try {
146
+            //user already specified in config
147
+            $oldUser = $this->config->getValue('dbuser', false);
148
+
149
+            //we don't have a dbuser specified in config
150
+            if ($this->dbUser !== $oldUser) {
151
+                //add prefix to the admin username to prevent collisions
152
+                $adminUser = substr('oc_' . $username, 0, 16);
153
+
154
+                $i = 1;
155
+                while (true) {
156
+                    //this should be enough to check for admin rights in mysql
157
+                    $query = 'SELECT user FROM mysql.user WHERE user=?';
158
+                    $result = $connection->executeQuery($query, [$adminUser]);
159
+
160
+                    //current dbuser has admin rights
161
+                    $data = $result->fetchAll();
162
+                    $result->closeCursor();
163
+                    //new dbuser does not exist
164
+                    if (count($data) === 0) {
165
+                        //use the admin login data for the new database user
166
+                        $this->dbUser = $adminUser;
167
+
168
+                        //create a random password so we don't need to store the admin password in the config file
169
+                        $this->dbPassword = $this->random->generate(30, ISecureRandom::CHAR_DIGITS . ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_UPPER);
170
+
171
+                        $this->createDBUser($connection);
172
+
173
+                        break;
174
+                    } else {
175
+                        //repeat with different username
176
+                        $length = strlen((string)$i);
177
+                        $adminUser = substr('oc_' . $username, 0, 16 - $length) . $i;
178
+                        $i++;
179
+                    }
180
+                }
181
+            }
182
+        } catch (\Exception $ex) {
183
+            $this->logger->logException($ex, [
184
+                'message' => 'Can not create a new MySQL user, will continue with the provided user.',
185
+                'level' => ILogger::INFO,
186
+                'app' => 'mysql.setup',
187
+            ]);
188
+        }
189
+
190
+        $this->config->setValues([
191
+            'dbuser' => $this->dbUser,
192
+            'dbpassword' => $this->dbPassword,
193
+        ]);
194
+    }
195 195
 }
Please login to merge, or discard this patch.
Spacing   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -149,7 +149,7 @@  discard block
 block discarded – undo
149 149
 			//we don't have a dbuser specified in config
150 150
 			if ($this->dbUser !== $oldUser) {
151 151
 				//add prefix to the admin username to prevent collisions
152
-				$adminUser = substr('oc_' . $username, 0, 16);
152
+				$adminUser = substr('oc_'.$username, 0, 16);
153 153
 
154 154
 				$i = 1;
155 155
 				while (true) {
@@ -166,15 +166,15 @@  discard block
 block discarded – undo
166 166
 						$this->dbUser = $adminUser;
167 167
 
168 168
 						//create a random password so we don't need to store the admin password in the config file
169
-						$this->dbPassword = $this->random->generate(30, ISecureRandom::CHAR_DIGITS . ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_UPPER);
169
+						$this->dbPassword = $this->random->generate(30, ISecureRandom::CHAR_DIGITS.ISecureRandom::CHAR_LOWER.ISecureRandom::CHAR_UPPER);
170 170
 
171 171
 						$this->createDBUser($connection);
172 172
 
173 173
 						break;
174 174
 					} else {
175 175
 						//repeat with different username
176
-						$length = strlen((string)$i);
177
-						$adminUser = substr('oc_' . $username, 0, 16 - $length) . $i;
176
+						$length = strlen((string) $i);
177
+						$adminUser = substr('oc_'.$username, 0, 16 - $length).$i;
178 178
 						$i++;
179 179
 					}
180 180
 				}
Please login to merge, or discard this patch.