1
0

MySQL.php 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Bart Visscher <bartv@thisnet.nl>
  6. * @author Joas Schilling <coding@schilljs.com>
  7. * @author Michael Göhler <somebody.here@gmx.de>
  8. * @author Robin McCorkell <robin@mccorkell.me.uk>
  9. * @author Roeland Jago Douma <roeland@famdouma.nl>
  10. * @author Stefan Weil <sw@weilnetz.de>
  11. * @author Thomas Müller <thomas.mueller@tmit.eu>
  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. use OCP\IDBConnection;
  30. class MySQL extends AbstractDatabase {
  31. public $dbprettyname = 'MySQL/MariaDB';
  32. public function setupDatabase($username) {
  33. //check if the database user has admin right
  34. $connection = $this->connect(['dbname' => null]);
  35. $this->createSpecificUser($username, $connection);
  36. //create the database
  37. $this->createDatabase($connection);
  38. //fill the database if needed
  39. $query='select count(*) from information_schema.tables where table_schema=? AND table_name = ?';
  40. $result = $connection->executeQuery($query, [$this->dbName, $this->tablePrefix.'users']);
  41. $row = $result->fetch();
  42. if (!$row or $row['count(*)'] === '0') {
  43. \OC_DB::createDbFromStructure($this->dbDefinitionFile);
  44. }
  45. }
  46. /**
  47. * @param \OC\DB\Connection $connection
  48. */
  49. private function createDatabase($connection) {
  50. try{
  51. $name = $this->dbName;
  52. $user = $this->dbUser;
  53. //we can't use OC_DB functions here because we need to connect as the administrative user.
  54. $characterSet = $this->config->getValue('mysql.utf8mb4', false) ? 'utf8mb4' : 'utf8';
  55. $query = "CREATE DATABASE IF NOT EXISTS `$name` CHARACTER SET $characterSet COLLATE ${characterSet}_bin;";
  56. $connection->executeUpdate($query);
  57. } catch (\Exception $ex) {
  58. $this->logger->error('Database creation failed: {error}', [
  59. 'app' => 'mysql.setup',
  60. 'error' => $ex->getMessage()
  61. ]);
  62. return;
  63. }
  64. try {
  65. //this query will fail if there aren't the right permissions, ignore the error
  66. $query="GRANT ALL PRIVILEGES ON `$name` . * TO '$user'";
  67. $connection->executeUpdate($query);
  68. } catch (\Exception $ex) {
  69. $this->logger->debug('Could not automatically grant privileges, this can be ignored if database user already had privileges: {error}', [
  70. 'app' => 'mysql.setup',
  71. 'error' => $ex->getMessage()
  72. ]);
  73. }
  74. }
  75. /**
  76. * @param IDBConnection $connection
  77. * @throws \OC\DatabaseSetupException
  78. */
  79. private function createDBUser($connection) {
  80. try{
  81. $name = $this->dbUser;
  82. $password = $this->dbPassword;
  83. // we need to create 2 accounts, one for global use and one for local user. if we don't specify the local one,
  84. // the anonymous user would take precedence when there is one.
  85. $query = "CREATE USER '$name'@'localhost' IDENTIFIED BY '$password'";
  86. $connection->executeUpdate($query);
  87. $query = "CREATE USER '$name'@'%' IDENTIFIED BY '$password'";
  88. $connection->executeUpdate($query);
  89. }
  90. catch (\Exception $ex){
  91. $this->logger->error('Database User creation failed: {error}', [
  92. 'app' => 'mysql.setup',
  93. 'error' => $ex->getMessage()
  94. ]);
  95. }
  96. }
  97. /**
  98. * @param $username
  99. * @param IDBConnection $connection
  100. * @return array
  101. */
  102. private function createSpecificUser($username, $connection) {
  103. try {
  104. //user already specified in config
  105. $oldUser = $this->config->getValue('dbuser', false);
  106. //we don't have a dbuser specified in config
  107. if ($this->dbUser !== $oldUser) {
  108. //add prefix to the admin username to prevent collisions
  109. $adminUser = substr('oc_' . $username, 0, 16);
  110. $i = 1;
  111. while (true) {
  112. //this should be enough to check for admin rights in mysql
  113. $query = 'SELECT user FROM mysql.user WHERE user=?';
  114. $result = $connection->executeQuery($query, [$adminUser]);
  115. //current dbuser has admin rights
  116. if ($result) {
  117. $data = $result->fetchAll();
  118. //new dbuser does not exist
  119. if (count($data) === 0) {
  120. //use the admin login data for the new database user
  121. $this->dbUser = $adminUser;
  122. //create a random password so we don't need to store the admin password in the config file
  123. $this->dbPassword = $this->random->generate(30);
  124. $this->createDBUser($connection);
  125. break;
  126. } else {
  127. //repeat with different username
  128. $length = strlen((string)$i);
  129. $adminUser = substr('oc_' . $username, 0, 16 - $length) . $i;
  130. $i++;
  131. }
  132. } else {
  133. break;
  134. }
  135. };
  136. }
  137. } catch (\Exception $ex) {
  138. $this->logger->info('Can not create a new MySQL user, will continue with the provided user: {error}', [
  139. 'app' => 'mysql.setup',
  140. 'error' => $ex->getMessage()
  141. ]);
  142. }
  143. $this->config->setValues([
  144. 'dbuser' => $this->dbUser,
  145. 'dbpassword' => $this->dbPassword,
  146. ]);
  147. }
  148. }