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.

258 lines
8.1 KiB

3 years ago
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Andreas Fischer <bantu@owncloud.com>
  6. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  7. * @author Daniel Kesselberg <mail@danielkesselberg.de>
  8. * @author Joas Schilling <coding@schilljs.com>
  9. * @author Jörn Friedrich Dreyer <jfd@butonic.de>
  10. * @author Morris Jobke <hey@morrisjobke.de>
  11. * @author Robin Appelman <robin@icewind.nl>
  12. * @author Thomas Müller <thomas.mueller@tmit.eu>
  13. *
  14. * @license AGPL-3.0
  15. *
  16. * This code is free software: you can redistribute it and/or modify
  17. * it under the terms of the GNU Affero General Public License, version 3,
  18. * as published by the Free Software Foundation.
  19. *
  20. * This program is distributed in the hope that it will be useful,
  21. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  22. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  23. * GNU Affero General Public License for more details.
  24. *
  25. * You should have received a copy of the GNU Affero General Public License, version 3,
  26. * along with this program. If not, see <http://www.gnu.org/licenses/>
  27. *
  28. */
  29. namespace OC\DB;
  30. use Doctrine\Common\EventManager;
  31. use Doctrine\DBAL\Configuration;
  32. use Doctrine\DBAL\DriverManager;
  33. use Doctrine\DBAL\Event\Listeners\OracleSessionInit;
  34. use Doctrine\DBAL\Event\Listeners\SQLSessionInit;
  35. use OC\SystemConfig;
  36. /**
  37. * Takes care of creating and configuring Doctrine connections.
  38. */
  39. class ConnectionFactory {
  40. /** @var string default database name */
  41. public const DEFAULT_DBNAME = 'owncloud';
  42. /** @var string default database table prefix */
  43. public const DEFAULT_DBTABLEPREFIX = 'oc_';
  44. /**
  45. * @var array
  46. *
  47. * Array mapping DBMS type to default connection parameters passed to
  48. * \Doctrine\DBAL\DriverManager::getConnection().
  49. */
  50. protected $defaultConnectionParams = [
  51. 'mysql' => [
  52. 'adapter' => AdapterMySQL::class,
  53. 'charset' => 'UTF8',
  54. 'driver' => 'pdo_mysql',
  55. 'wrapperClass' => Connection::class,
  56. ],
  57. 'oci' => [
  58. 'adapter' => AdapterOCI8::class,
  59. 'charset' => 'AL32UTF8',
  60. 'driver' => 'oci8',
  61. 'wrapperClass' => OracleConnection::class,
  62. ],
  63. 'pgsql' => [
  64. 'adapter' => AdapterPgSql::class,
  65. 'driver' => 'pdo_pgsql',
  66. 'wrapperClass' => Connection::class,
  67. ],
  68. 'sqlite3' => [
  69. 'adapter' => AdapterSqlite::class,
  70. 'driver' => 'pdo_sqlite',
  71. 'wrapperClass' => Connection::class,
  72. ],
  73. ];
  74. /** @var SystemConfig */
  75. private $config;
  76. /**
  77. * ConnectionFactory constructor.
  78. *
  79. * @param SystemConfig $systemConfig
  80. */
  81. public function __construct(SystemConfig $systemConfig) {
  82. $this->config = $systemConfig;
  83. if ($this->config->getValue('mysql.utf8mb4', false)) {
  84. $this->defaultConnectionParams['mysql']['charset'] = 'utf8mb4';
  85. }
  86. }
  87. /**
  88. * @brief Get default connection parameters for a given DBMS.
  89. * @param string $type DBMS type
  90. * @throws \InvalidArgumentException If $type is invalid
  91. * @return array Default connection parameters.
  92. */
  93. public function getDefaultConnectionParams($type) {
  94. $normalizedType = $this->normalizeType($type);
  95. if (!isset($this->defaultConnectionParams[$normalizedType])) {
  96. throw new \InvalidArgumentException("Unsupported type: $type");
  97. }
  98. $result = $this->defaultConnectionParams[$normalizedType];
  99. // \PDO::MYSQL_ATTR_FOUND_ROWS may not be defined, e.g. when the MySQL
  100. // driver is missing. In this case, we won't be able to connect anyway.
  101. if ($normalizedType === 'mysql' && defined('\PDO::MYSQL_ATTR_FOUND_ROWS')) {
  102. $result['driverOptions'] = [
  103. \PDO::MYSQL_ATTR_FOUND_ROWS => true,
  104. ];
  105. }
  106. return $result;
  107. }
  108. /**
  109. * @brief Get default connection parameters for a given DBMS.
  110. * @param string $type DBMS type
  111. * @param array $additionalConnectionParams Additional connection parameters
  112. * @return \OC\DB\Connection
  113. */
  114. public function getConnection($type, $additionalConnectionParams) {
  115. $normalizedType = $this->normalizeType($type);
  116. $eventManager = new EventManager();
  117. $eventManager->addEventSubscriber(new SetTransactionIsolationLevel());
  118. switch ($normalizedType) {
  119. case 'mysql':
  120. $eventManager->addEventSubscriber(
  121. new SQLSessionInit("SET SESSION AUTOCOMMIT=1"));
  122. break;
  123. case 'oci':
  124. $eventManager->addEventSubscriber(new OracleSessionInit);
  125. // the driverOptions are unused in dbal and need to be mapped to the parameters
  126. if (isset($additionalConnectionParams['driverOptions'])) {
  127. $additionalConnectionParams = array_merge($additionalConnectionParams, $additionalConnectionParams['driverOptions']);
  128. }
  129. $host = $additionalConnectionParams['host'];
  130. $port = isset($additionalConnectionParams['port']) ? $additionalConnectionParams['port'] : null;
  131. $dbName = $additionalConnectionParams['dbname'];
  132. // we set the connect string as dbname and unset the host to coerce doctrine into using it as connect string
  133. if ($host === '') {
  134. $additionalConnectionParams['dbname'] = $dbName; // use dbname as easy connect name
  135. } else {
  136. $additionalConnectionParams['dbname'] = '//' . $host . (!empty($port) ? ":{$port}" : "") . '/' . $dbName;
  137. }
  138. unset($additionalConnectionParams['host']);
  139. break;
  140. case 'sqlite3':
  141. $journalMode = $additionalConnectionParams['sqlite.journal_mode'];
  142. $additionalConnectionParams['platform'] = new OCSqlitePlatform();
  143. $eventManager->addEventSubscriber(new SQLiteSessionInit(true, $journalMode));
  144. break;
  145. }
  146. /** @var Connection $connection */
  147. $connection = DriverManager::getConnection(
  148. array_merge($this->getDefaultConnectionParams($type), $additionalConnectionParams),
  149. new Configuration(),
  150. $eventManager
  151. );
  152. return $connection;
  153. }
  154. /**
  155. * @brief Normalize DBMS type
  156. * @param string $type DBMS type
  157. * @return string Normalized DBMS type
  158. */
  159. public function normalizeType($type) {
  160. return $type === 'sqlite' ? 'sqlite3' : $type;
  161. }
  162. /**
  163. * Checks whether the specified DBMS type is valid.
  164. *
  165. * @param string $type
  166. * @return bool
  167. */
  168. public function isValidType($type) {
  169. $normalizedType = $this->normalizeType($type);
  170. return isset($this->defaultConnectionParams[$normalizedType]);
  171. }
  172. /**
  173. * Create the connection parameters for the config
  174. *
  175. * @return array
  176. */
  177. public function createConnectionParams() {
  178. $type = $this->config->getValue('dbtype', 'sqlite');
  179. $connectionParams = [
  180. 'user' => $this->config->getValue('dbuser', ''),
  181. 'password' => $this->config->getValue('dbpassword', ''),
  182. ];
  183. $name = $this->config->getValue('dbname', self::DEFAULT_DBNAME);
  184. if ($this->normalizeType($type) === 'sqlite3') {
  185. $dataDir = $this->config->getValue("datadirectory", \OC::$SERVERROOT . '/data');
  186. $connectionParams['path'] = $dataDir . '/' . $name . '.db';
  187. } else {
  188. $host = $this->config->getValue('dbhost', '');
  189. $connectionParams = array_merge($connectionParams, $this->splitHostFromPortAndSocket($host));
  190. $connectionParams['dbname'] = $name;
  191. }
  192. $connectionParams['tablePrefix'] = $this->config->getValue('dbtableprefix', self::DEFAULT_DBTABLEPREFIX);
  193. $connectionParams['sqlite.journal_mode'] = $this->config->getValue('sqlite.journal_mode', 'WAL');
  194. //additional driver options, eg. for mysql ssl
  195. $driverOptions = $this->config->getValue('dbdriveroptions', null);
  196. if ($driverOptions) {
  197. $connectionParams['driverOptions'] = $driverOptions;
  198. }
  199. // set default table creation options
  200. $connectionParams['defaultTableOptions'] = [
  201. 'collate' => 'utf8_bin',
  202. 'tablePrefix' => $connectionParams['tablePrefix']
  203. ];
  204. if ($this->config->getValue('mysql.utf8mb4', false)) {
  205. $connectionParams['defaultTableOptions'] = [
  206. 'collate' => 'utf8mb4_bin',
  207. 'charset' => 'utf8mb4',
  208. 'row_format' => 'compressed',
  209. 'tablePrefix' => $connectionParams['tablePrefix']
  210. ];
  211. }
  212. return $connectionParams;
  213. }
  214. /**
  215. * @param string $host
  216. * @return array
  217. */
  218. protected function splitHostFromPortAndSocket($host): array {
  219. $params = [
  220. 'host' => $host,
  221. ];
  222. $matches = [];
  223. if (preg_match('/^(.*):([^\]:]+)$/', $host, $matches)) {
  224. // Host variable carries a port or socket.
  225. $params['host'] = $matches[1];
  226. if (is_numeric($matches[2])) {
  227. $params['port'] = (int) $matches[2];
  228. } else {
  229. $params['unix_socket'] = $matches[2];
  230. }
  231. }
  232. return $params;
  233. }
  234. }