You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

MySQL.php 6.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
  6. * @author Bart Visscher <bartv@thisnet.nl>
  7. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  8. * @author Hemanth Kumar Veeranki <hems.india1997@gmail.com>
  9. * @author Joas Schilling <coding@schilljs.com>
  10. * @author Michael Göhler <somebody.here@gmx.de>
  11. * @author Morris Jobke <hey@morrisjobke.de>
  12. * @author Thomas Müller <thomas.mueller@tmit.eu>
  13. * @author Vincent Petry <vincent@nextcloud.com>
  14. *
  15. * @license AGPL-3.0
  16. *
  17. * This code is free software: you can redistribute it and/or modify
  18. * it under the terms of the GNU Affero General Public License, version 3,
  19. * as published by the Free Software Foundation.
  20. *
  21. * This program is distributed in the hope that it will be useful,
  22. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  23. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  24. * GNU Affero General Public License for more details.
  25. *
  26. * You should have received a copy of the GNU Affero General Public License, version 3,
  27. * along with this program. If not, see <http://www.gnu.org/licenses/>
  28. *
  29. */
  30. namespace OC\Setup;
  31. use OC\DB\ConnectionAdapter;
  32. use OC\DB\MySqlTools;
  33. use OCP\IDBConnection;
  34. use Doctrine\DBAL\Platforms\MySQL80Platform;
  35. use OCP\Security\ISecureRandom;
  36. class MySQL extends AbstractDatabase {
  37. public $dbprettyname = 'MySQL/MariaDB';
  38. public function setupDatabase($username) {
  39. //check if the database user has admin right
  40. $connection = $this->connect(['dbname' => null]);
  41. // detect mb4
  42. $tools = new MySqlTools();
  43. if ($tools->supports4ByteCharset(new ConnectionAdapter($connection))) {
  44. $this->config->setValue('mysql.utf8mb4', true);
  45. $connection = $this->connect(['dbname' => null]);
  46. }
  47. $this->createSpecificUser($username, new ConnectionAdapter($connection));
  48. //create the database
  49. $this->createDatabase($connection);
  50. //fill the database if needed
  51. $query = 'select count(*) from information_schema.tables where table_schema=? AND table_name = ?';
  52. $connection->executeQuery($query, [$this->dbName, $this->tablePrefix.'users']);
  53. $connection->close();
  54. $connection = $this->connect();
  55. try {
  56. $connection->connect();
  57. } catch (\Exception $e) {
  58. $this->logger->error($e->getMessage(), [
  59. 'exception' => $e,
  60. ]);
  61. throw new \OC\DatabaseSetupException($this->trans->t('MySQL username and/or password not valid'),
  62. $this->trans->t('You need to enter details of an existing account.'), 0, $e);
  63. }
  64. }
  65. /**
  66. * @param \OC\DB\Connection $connection
  67. */
  68. private function createDatabase($connection) {
  69. try {
  70. $name = $this->dbName;
  71. $user = $this->dbUser;
  72. //we can't use OC_DB functions here because we need to connect as the administrative user.
  73. $characterSet = $this->config->getValue('mysql.utf8mb4', false) ? 'utf8mb4' : 'utf8';
  74. $query = "CREATE DATABASE IF NOT EXISTS `$name` CHARACTER SET $characterSet COLLATE ${characterSet}_bin;";
  75. $connection->executeUpdate($query);
  76. } catch (\Exception $ex) {
  77. $this->logger->error('Database creation failed.', [
  78. 'exception' => $ex,
  79. 'app' => 'mysql.setup',
  80. ]);
  81. return;
  82. }
  83. try {
  84. //this query will fail if there aren't the right permissions, ignore the error
  85. $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'";
  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.', [
  89. 'exception' => $ex,
  90. 'app' => 'mysql.setup',
  91. ]);
  92. }
  93. }
  94. /**
  95. * @param IDBConnection $connection
  96. * @throws \OC\DatabaseSetupException
  97. */
  98. private function createDBUser($connection) {
  99. try {
  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. if ($connection->getDatabasePlatform() instanceof Mysql80Platform) {
  105. $query = "CREATE USER '$name'@'localhost' IDENTIFIED WITH mysql_native_password BY '$password'";
  106. $connection->executeUpdate($query);
  107. $query = "CREATE USER '$name'@'%' IDENTIFIED WITH mysql_native_password BY '$password'";
  108. $connection->executeUpdate($query);
  109. } else {
  110. $query = "CREATE USER '$name'@'localhost' IDENTIFIED BY '$password'";
  111. $connection->executeUpdate($query);
  112. $query = "CREATE USER '$name'@'%' IDENTIFIED BY '$password'";
  113. $connection->executeUpdate($query);
  114. }
  115. } catch (\Exception $ex) {
  116. $this->logger->error('Database user creation failed.', [
  117. 'exception' => $ex,
  118. 'app' => 'mysql.setup',
  119. ]);
  120. }
  121. }
  122. /**
  123. * @param $username
  124. * @param IDBConnection $connection
  125. * @return array
  126. */
  127. private function createSpecificUser($username, $connection) {
  128. try {
  129. //user already specified in config
  130. $oldUser = $this->config->getValue('dbuser', false);
  131. //we don't have a dbuser specified in config
  132. if ($this->dbUser !== $oldUser) {
  133. //add prefix to the admin username to prevent collisions
  134. $adminUser = substr('oc_' . $username, 0, 16);
  135. $i = 1;
  136. while (true) {
  137. //this should be enough to check for admin rights in mysql
  138. $query = 'SELECT user FROM mysql.user WHERE user=?';
  139. $result = $connection->executeQuery($query, [$adminUser]);
  140. //current dbuser has admin rights
  141. $data = $result->fetchAll();
  142. $result->closeCursor();
  143. //new dbuser does not exist
  144. if (count($data) === 0) {
  145. //use the admin login data for the new database user
  146. $this->dbUser = $adminUser;
  147. //create a random password so we don't need to store the admin password in the config file
  148. $this->dbPassword = $this->random->generate(30, ISecureRandom::CHAR_ALPHANUMERIC);
  149. $this->createDBUser($connection);
  150. break;
  151. } else {
  152. //repeat with different username
  153. $length = strlen((string)$i);
  154. $adminUser = substr('oc_' . $username, 0, 16 - $length) . $i;
  155. $i++;
  156. }
  157. }
  158. }
  159. } catch (\Exception $ex) {
  160. $this->logger->info('Can not create a new MySQL user, will continue with the provided user.', [
  161. 'exception' => $ex,
  162. 'app' => 'mysql.setup',
  163. ]);
  164. }
  165. $this->config->setValues([
  166. 'dbuser' => $this->dbUser,
  167. 'dbpassword' => $this->dbPassword,
  168. ]);
  169. }
  170. }