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.

197 lines
6.5 KiB

3 years ago
  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 Oliver Salzburg <oliver.salzburg@gmail.com>
  13. * @author Roeland Jago Douma <roeland@famdouma.nl>
  14. * @author Thomas Müller <thomas.mueller@tmit.eu>
  15. * @author Vincent Petry <pvince81@owncloud.com>
  16. *
  17. * @license AGPL-3.0
  18. *
  19. * This code is free software: you can redistribute it and/or modify
  20. * it under the terms of the GNU Affero General Public License, version 3,
  21. * as published by the Free Software Foundation.
  22. *
  23. * This program is distributed in the hope that it will be useful,
  24. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  25. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  26. * GNU Affero General Public License for more details.
  27. *
  28. * You should have received a copy of the GNU Affero General Public License, version 3,
  29. * along with this program. If not, see <http://www.gnu.org/licenses/>
  30. *
  31. */
  32. namespace OC\Setup;
  33. use OC\DB\MySqlTools;
  34. use OCP\IDBConnection;
  35. use OCP\ILogger;
  36. use Doctrine\DBAL\Platforms\MySQL80Platform;
  37. class MySQL extends AbstractDatabase {
  38. public $dbprettyname = 'MySQL/MariaDB';
  39. public function setupDatabase($username) {
  40. //check if the database user has admin right
  41. $connection = $this->connect(['dbname' => null]);
  42. // detect mb4
  43. $tools = new MySqlTools();
  44. if ($tools->supports4ByteCharset($connection)) {
  45. $this->config->setValue('mysql.utf8mb4', true);
  46. $connection = $this->connect(['dbname' => null]);
  47. }
  48. $this->createSpecificUser($username, $connection);
  49. //create the database
  50. $this->createDatabase($connection);
  51. //fill the database if needed
  52. $query='select count(*) from information_schema.tables where table_schema=? AND table_name = ?';
  53. $connection->executeQuery($query, [$this->dbName, $this->tablePrefix.'users']);
  54. $connection->close();
  55. $connection = $this->connect();
  56. try {
  57. $connection->connect();
  58. } catch (\Exception $e) {
  59. $this->logger->logException($e);
  60. throw new \OC\DatabaseSetupException($this->trans->t('MySQL username and/or password not valid'),
  61. $this->trans->t('You need to enter details of an existing account.'));
  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->getValue('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->logException($ex, [
  77. 'message' => 'Database creation failed.',
  78. 'level' => ILogger::ERROR,
  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->logException($ex, [
  89. 'message' => 'Could not automatically grant privileges, this can be ignored if database user already had privileges.',
  90. 'level' => ILogger::DEBUG,
  91. 'app' => 'mysql.setup',
  92. ]);
  93. }
  94. }
  95. /**
  96. * @param IDBConnection $connection
  97. * @throws \OC\DatabaseSetupException
  98. */
  99. private function createDBUser($connection) {
  100. try {
  101. $name = $this->dbUser;
  102. $password = $this->dbPassword;
  103. // we need to create 2 accounts, one for global use and one for local user. if we don't specify the local one,
  104. // the anonymous user would take precedence when there is one.
  105. if ($connection->getDatabasePlatform() instanceof Mysql80Platform) {
  106. $query = "CREATE USER '$name'@'localhost' IDENTIFIED WITH mysql_native_password BY '$password'";
  107. $connection->executeUpdate($query);
  108. $query = "CREATE USER '$name'@'%' IDENTIFIED WITH mysql_native_password BY '$password'";
  109. $connection->executeUpdate($query);
  110. } else {
  111. $query = "CREATE USER '$name'@'localhost' IDENTIFIED BY '$password'";
  112. $connection->executeUpdate($query);
  113. $query = "CREATE USER '$name'@'%' IDENTIFIED BY '$password'";
  114. $connection->executeUpdate($query);
  115. }
  116. } catch (\Exception $ex) {
  117. $this->logger->logException($ex, [
  118. 'message' => 'Database user creation failed.',
  119. 'level' => ILogger::ERROR,
  120. 'app' => 'mysql.setup',
  121. ]);
  122. }
  123. }
  124. /**
  125. * @param $username
  126. * @param IDBConnection $connection
  127. * @return array
  128. */
  129. private function createSpecificUser($username, $connection) {
  130. try {
  131. //user already specified in config
  132. $oldUser = $this->config->getValue('dbuser', false);
  133. //we don't have a dbuser specified in config
  134. if ($this->dbUser !== $oldUser) {
  135. //add prefix to the admin username to prevent collisions
  136. $adminUser = substr('oc_' . $username, 0, 16);
  137. $i = 1;
  138. while (true) {
  139. //this should be enough to check for admin rights in mysql
  140. $query = 'SELECT user FROM mysql.user WHERE user=?';
  141. $result = $connection->executeQuery($query, [$adminUser]);
  142. //current dbuser has admin rights
  143. if ($result) {
  144. $data = $result->fetchAll();
  145. //new dbuser does not exist
  146. if (count($data) === 0) {
  147. //use the admin login data for the new database user
  148. $this->dbUser = $adminUser;
  149. //create a random password so we don't need to store the admin password in the config file
  150. $this->dbPassword = $this->random->generate(30);
  151. $this->createDBUser($connection);
  152. break;
  153. } else {
  154. //repeat with different username
  155. $length = strlen((string)$i);
  156. $adminUser = substr('oc_' . $username, 0, 16 - $length) . $i;
  157. $i++;
  158. }
  159. } else {
  160. break;
  161. }
  162. }
  163. }
  164. } catch (\Exception $ex) {
  165. $this->logger->logException($ex, [
  166. 'message' => 'Can not create a new MySQL user, will continue with the provided user.',
  167. 'level' => ILogger::INFO,
  168. 'app' => 'mysql.setup',
  169. ]);
  170. }
  171. $this->config->setValues([
  172. 'dbuser' => $this->dbUser,
  173. 'dbpassword' => $this->dbPassword,
  174. ]);
  175. }
  176. }