mysql.php 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Bart Visscher <bartv@thisnet.nl>
  6. * @author Daniel Hansson <daniel@techandme.se>
  7. * @author Joas Schilling <coding@schilljs.com>
  8. * @author Michael Göhler <somebody.here@gmx.de>
  9. * @author Roeland Jago Douma <roeland@famdouma.nl>
  10. * @author Thomas Müller <thomas.mueller@tmit.eu>
  11. *
  12. * @license AGPL-3.0
  13. *
  14. * This code is free software: you can redistribute it and/or modify
  15. * it under the terms of the GNU Affero General Public License, version 3,
  16. * as published by the Free Software Foundation.
  17. *
  18. * This program is distributed in the hope that it will be useful,
  19. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  20. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  21. * GNU Affero General Public License for more details.
  22. *
  23. * You should have received a copy of the GNU Affero General Public License, version 3,
  24. * along with this program. If not, see <http://www.gnu.org/licenses/>
  25. *
  26. */
  27. namespace OC\Setup;
  28. use OC\DB\ConnectionFactory;
  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();
  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 cant use OC_BD functions here because we need to connect as the administrative user.
  54. $query = "CREATE DATABASE IF NOT EXISTS `$name` CHARACTER SET utf8 COLLATE utf8_bin;";
  55. $connection->executeUpdate($query);
  56. //this query will fail if there aren't the right permissions, ignore the error
  57. $query="GRANT ALL PRIVILEGES ON `$name` . * TO '$user'";
  58. $connection->executeUpdate($query);
  59. } catch (\Exception $ex) {
  60. $this->logger->error('Database creation failed: {error}', [
  61. 'app' => 'mysql.setup',
  62. 'error' => $ex->getMessage()
  63. ]);
  64. }
  65. }
  66. /**
  67. * @param IDBConnection $connection
  68. * @throws \OC\DatabaseSetupException
  69. */
  70. private function createDBUser($connection) {
  71. $name = $this->dbUser;
  72. $password = $this->dbPassword;
  73. // we need to create 2 accounts, one for global use and one for local user. if we don't specify the local one,
  74. // the anonymous user would take precedence when there is one.
  75. $query = "CREATE USER '$name'@'localhost' IDENTIFIED BY '$password'";
  76. $connection->executeUpdate($query);
  77. $query = "CREATE USER '$name'@'%' IDENTIFIED BY '$password'";
  78. $connection->executeUpdate($query);
  79. }
  80. /**
  81. * @return \OC\DB\Connection
  82. * @throws \OC\DatabaseSetupException
  83. */
  84. private function connect() {
  85. $connectionParams = array(
  86. 'host' => $this->dbHost,
  87. 'user' => $this->dbUser,
  88. 'password' => $this->dbPassword,
  89. 'tablePrefix' => $this->tablePrefix,
  90. );
  91. // adding port support
  92. if (strpos($this->dbHost, ':')) {
  93. // Host variable may carry a port or socket.
  94. list($host, $portOrSocket) = explode(':', $this->dbHost, 2);
  95. if (ctype_digit($portOrSocket)) {
  96. $connectionParams['port'] = $portOrSocket;
  97. } else {
  98. $connectionParams['unix_socket'] = $portOrSocket;
  99. }
  100. $connectionParams['host'] = $host;
  101. }
  102. $cf = new ConnectionFactory();
  103. return $cf->getConnection('mysql', $connectionParams);
  104. }
  105. /**
  106. * @param $username
  107. * @param IDBConnection $connection
  108. * @return array
  109. */
  110. private function createSpecificUser($username, $connection) {
  111. try {
  112. //user already specified in config
  113. $oldUser = $this->config->getSystemValue('dbuser', false);
  114. //we don't have a dbuser specified in config
  115. if ($this->dbUser !== $oldUser) {
  116. //add prefix to the admin username to prevent collisions
  117. $adminUser = substr('oc_' . $username, 0, 16);
  118. $i = 1;
  119. while (true) {
  120. //this should be enough to check for admin rights in mysql
  121. $query = 'SELECT user FROM mysql.user WHERE user=?';
  122. $result = $connection->executeQuery($query, [$adminUser]);
  123. //current dbuser has admin rights
  124. if ($result) {
  125. $data = $result->fetchAll();
  126. //new dbuser does not exist
  127. if (count($data) === 0) {
  128. //use the admin login data for the new database user
  129. $this->dbUser = $adminUser;
  130. //create a random password so we don't need to store the admin password in the config file
  131. $this->dbPassword = $this->random->generate(30);
  132. $this->createDBUser($connection);
  133. break;
  134. } else {
  135. //repeat with different username
  136. $length = strlen((string)$i);
  137. $adminUser = substr('oc_' . $username, 0, 16 - $length) . $i;
  138. $i++;
  139. }
  140. } else {
  141. break;
  142. }
  143. };
  144. }
  145. } catch (\Exception $ex) {
  146. $this->logger->error('Specific user creation failed: {error}', [
  147. 'app' => 'mysql.setup',
  148. 'error' => $ex->getMessage()
  149. ]);
  150. }
  151. $this->config->setSystemValues([
  152. 'dbuser' => $this->dbUser,
  153. 'dbpassword' => $this->dbPassword,
  154. ]);
  155. }
  156. }