db.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  1. <?php
  2. /**
  3. * ownCloud
  4. *
  5. * @author Frank Karlitschek
  6. * @copyright 2012 Frank Karlitschek frank@owncloud.org
  7. *
  8. * This library is free software; you can redistribute it and/or
  9. * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
  10. * License as published by the Free Software Foundation; either
  11. * version 3 of the License, or any later version.
  12. *
  13. * This library is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU AFFERO GENERAL PUBLIC LICENSE for more details.
  17. *
  18. * You should have received a copy of the GNU Affero General Public
  19. * License along with this library. If not, see <http://www.gnu.org/licenses/>.
  20. *
  21. */
  22. define('MDB2_SCHEMA_DUMP_STRUCTURE', '1');
  23. class DatabaseException extends Exception {
  24. private $query;
  25. //FIXME getQuery seems to be unused, maybe use parent constructor with $message, $code and $previous
  26. public function __construct($message, $query = null){
  27. parent::__construct($message);
  28. $this->query = $query;
  29. }
  30. public function getQuery() {
  31. return $this->query;
  32. }
  33. }
  34. /**
  35. * This class manages the access to the database. It basically is a wrapper for
  36. * Doctrine with some adaptions.
  37. */
  38. class OC_DB {
  39. /**
  40. * @var \OC\DB\Connection $connection
  41. */
  42. static private $connection; //the preferred connection to use, only Doctrine
  43. /**
  44. * connects to the database
  45. * @return boolean|null true if connection can be established or false on error
  46. *
  47. * Connects to the database as specified in config.php
  48. */
  49. public static function connect() {
  50. if(self::$connection) {
  51. return true;
  52. }
  53. $type = OC_Config::getValue('dbtype', 'sqlite');
  54. $factory = new \OC\DB\ConnectionFactory();
  55. if (!$factory->isValidType($type)) {
  56. return false;
  57. }
  58. $connectionParams = array(
  59. 'user' => OC_Config::getValue('dbuser', ''),
  60. 'password' => OC_Config::getValue('dbpassword', ''),
  61. );
  62. $name = OC_Config::getValue('dbname', 'owncloud');
  63. if ($factory->normalizeType($type) === 'sqlite3') {
  64. $datadir = OC_Config::getValue("datadirectory", OC::$SERVERROOT.'/data');
  65. $connectionParams['path'] = $datadir.'/'.$name.'.db';
  66. } else {
  67. $host = OC_Config::getValue('dbhost', '');
  68. if (strpos($host, ':')) {
  69. // Host variable may carry a port or socket.
  70. list($host, $portOrSocket) = explode(':', $host, 2);
  71. if (ctype_digit($portOrSocket)) {
  72. $connectionParams['port'] = $portOrSocket;
  73. } else {
  74. $connectionParams['unix_socket'] = $portOrSocket;
  75. }
  76. }
  77. $connectionParams['host'] = $host;
  78. $connectionParams['dbname'] = $name;
  79. }
  80. $connectionParams['tablePrefix'] = OC_Config::getValue('dbtableprefix', 'oc_');
  81. try {
  82. self::$connection = $factory->getConnection($type, $connectionParams);
  83. } catch(\Doctrine\DBAL\DBALException $e) {
  84. OC_Log::write('core', $e->getMessage(), OC_Log::FATAL);
  85. OC_User::setUserId(null);
  86. // send http status 503
  87. header('HTTP/1.1 503 Service Temporarily Unavailable');
  88. header('Status: 503 Service Temporarily Unavailable');
  89. OC_Template::printErrorPage('Failed to connect to database');
  90. die();
  91. }
  92. return true;
  93. }
  94. /**
  95. * The existing database connection is closed and connected again
  96. */
  97. public static function reconnect() {
  98. if(self::$connection) {
  99. self::$connection->close();
  100. self::$connection->connect();
  101. }
  102. }
  103. /**
  104. * @return \OC\DB\Connection
  105. */
  106. static public function getConnection() {
  107. self::connect();
  108. return self::$connection;
  109. }
  110. /**
  111. * get MDB2 schema manager
  112. *
  113. * @return \OC\DB\MDB2SchemaManager
  114. */
  115. private static function getMDB2SchemaManager()
  116. {
  117. return new \OC\DB\MDB2SchemaManager(self::getConnection());
  118. }
  119. /**
  120. * Prepare a SQL query
  121. * @param string $query Query string
  122. * @param int $limit
  123. * @param int $offset
  124. * @param bool $isManipulation
  125. * @throws DatabaseException
  126. * @return OC_DB_StatementWrapper prepared SQL query
  127. *
  128. * SQL query via Doctrine prepare(), needs to be execute()'d!
  129. */
  130. static public function prepare( $query , $limit = null, $offset = null, $isManipulation = null) {
  131. self::connect();
  132. if ($isManipulation === null) {
  133. //try to guess, so we return the number of rows on manipulations
  134. $isManipulation = self::isManipulation($query);
  135. }
  136. // return the result
  137. try {
  138. $result = self::$connection->prepare($query, $limit, $offset);
  139. } catch (\Doctrine\DBAL\DBALException $e) {
  140. throw new \DatabaseException($e->getMessage(), $query);
  141. }
  142. // differentiate between query and manipulation
  143. $result = new OC_DB_StatementWrapper($result, $isManipulation);
  144. return $result;
  145. }
  146. /**
  147. * tries to guess the type of statement based on the first 10 characters
  148. * the current check allows some whitespace but does not work with IF EXISTS or other more complex statements
  149. *
  150. * @param string $sql
  151. * @return bool
  152. */
  153. static public function isManipulation( $sql ) {
  154. $selectOccurrence = stripos($sql, 'SELECT');
  155. if ($selectOccurrence !== false && $selectOccurrence < 10) {
  156. return false;
  157. }
  158. $insertOccurrence = stripos($sql, 'INSERT');
  159. if ($insertOccurrence !== false && $insertOccurrence < 10) {
  160. return true;
  161. }
  162. $updateOccurrence = stripos($sql, 'UPDATE');
  163. if ($updateOccurrence !== false && $updateOccurrence < 10) {
  164. return true;
  165. }
  166. $deleteOccurrence = stripos($sql, 'DELETE');
  167. if ($deleteOccurrence !== false && $deleteOccurrence < 10) {
  168. return true;
  169. }
  170. return false;
  171. }
  172. /**
  173. * execute a prepared statement, on error write log and throw exception
  174. * @param mixed $stmt OC_DB_StatementWrapper,
  175. * an array with 'sql' and optionally 'limit' and 'offset' keys
  176. * .. or a simple sql query string
  177. * @param array $parameters
  178. * @return OC_DB_StatementWrapper
  179. * @throws DatabaseException
  180. */
  181. static public function executeAudited( $stmt, array $parameters = null) {
  182. if (is_string($stmt)) {
  183. // convert to an array with 'sql'
  184. if (stripos($stmt, 'LIMIT') !== false) { //OFFSET requires LIMIT, so we only need to check for LIMIT
  185. // TODO try to convert LIMIT OFFSET notation to parameters, see fixLimitClauseForMSSQL
  186. $message = 'LIMIT and OFFSET are forbidden for portability reasons,'
  187. . ' pass an array with \'limit\' and \'offset\' instead';
  188. throw new DatabaseException($message);
  189. }
  190. $stmt = array('sql' => $stmt, 'limit' => null, 'offset' => null);
  191. }
  192. if (is_array($stmt)) {
  193. // convert to prepared statement
  194. if ( ! array_key_exists('sql', $stmt) ) {
  195. $message = 'statement array must at least contain key \'sql\'';
  196. throw new DatabaseException($message);
  197. }
  198. if ( ! array_key_exists('limit', $stmt) ) {
  199. $stmt['limit'] = null;
  200. }
  201. if ( ! array_key_exists('limit', $stmt) ) {
  202. $stmt['offset'] = null;
  203. }
  204. $stmt = self::prepare($stmt['sql'], $stmt['limit'], $stmt['offset']);
  205. }
  206. self::raiseExceptionOnError($stmt, 'Could not prepare statement');
  207. if ($stmt instanceof OC_DB_StatementWrapper) {
  208. $result = $stmt->execute($parameters);
  209. self::raiseExceptionOnError($result, 'Could not execute statement');
  210. } else {
  211. if (is_object($stmt)) {
  212. $message = 'Expected a prepared statement or array got ' . get_class($stmt);
  213. } else {
  214. $message = 'Expected a prepared statement or array got ' . gettype($stmt);
  215. }
  216. throw new DatabaseException($message);
  217. }
  218. return $result;
  219. }
  220. /**
  221. * gets last value of autoincrement
  222. * @param string $table The optional table name (will replace *PREFIX*) and add sequence suffix
  223. * @return string id
  224. * @throws DatabaseException
  225. *
  226. * \Doctrine\DBAL\Connection lastInsertId
  227. *
  228. * Call this method right after the insert command or other functions may
  229. * cause trouble!
  230. */
  231. public static function insertid($table=null) {
  232. self::connect();
  233. return self::$connection->lastInsertId($table);
  234. }
  235. /**
  236. * Insert a row if a matching row doesn't exists.
  237. * @param string $table The table to insert into in the form '*PREFIX*tableName'
  238. * @param array $input An array of fieldname/value pairs
  239. * @return boolean number of updated rows
  240. */
  241. public static function insertIfNotExist($table, $input) {
  242. self::connect();
  243. return self::$connection->insertIfNotExist($table, $input);
  244. }
  245. /**
  246. * Start a transaction
  247. */
  248. public static function beginTransaction() {
  249. self::connect();
  250. self::$connection->beginTransaction();
  251. }
  252. /**
  253. * Commit the database changes done during a transaction that is in progress
  254. */
  255. public static function commit() {
  256. self::connect();
  257. self::$connection->commit();
  258. }
  259. /**
  260. * saves database schema to xml file
  261. * @param string $file name of file
  262. * @param int $mode
  263. * @return bool
  264. *
  265. * TODO: write more documentation
  266. */
  267. public static function getDbStructure( $file, $mode = 0) {
  268. $schemaManager = self::getMDB2SchemaManager();
  269. return $schemaManager->getDbStructure($file);
  270. }
  271. /**
  272. * Creates tables from XML file
  273. * @param string $file file to read structure from
  274. * @return bool
  275. *
  276. * TODO: write more documentation
  277. */
  278. public static function createDbFromStructure( $file ) {
  279. $schemaManager = self::getMDB2SchemaManager();
  280. $result = $schemaManager->createDbFromStructure($file);
  281. return $result;
  282. }
  283. /**
  284. * update the database schema
  285. * @param string $file file to read structure from
  286. * @throws Exception
  287. * @return string|boolean
  288. */
  289. public static function updateDbFromStructure($file) {
  290. $schemaManager = self::getMDB2SchemaManager();
  291. try {
  292. $result = $schemaManager->updateDbFromStructure($file);
  293. } catch (Exception $e) {
  294. OC_Log::write('core', 'Failed to update database structure ('.$e.')', OC_Log::FATAL);
  295. throw $e;
  296. }
  297. return $result;
  298. }
  299. /**
  300. * simulate the database schema update
  301. * @param string $file file to read structure from
  302. * @throws Exception
  303. * @return string|boolean
  304. */
  305. public static function simulateUpdateDbFromStructure($file) {
  306. $schemaManager = self::getMDB2SchemaManager();
  307. try {
  308. $result = $schemaManager->simulateUpdateDbFromStructure($file);
  309. } catch (Exception $e) {
  310. OC_Log::write('core', 'Simulated database structure update failed ('.$e.')', OC_Log::FATAL);
  311. throw $e;
  312. }
  313. return $result;
  314. }
  315. /**
  316. * drop a table - the database prefix will be prepended
  317. * @param string $tableName the table to drop
  318. */
  319. public static function dropTable($tableName) {
  320. $tableName = OC_Config::getValue('dbtableprefix', 'oc_' ) . trim($tableName);
  321. self::$connection->beginTransaction();
  322. $platform = self::$connection->getDatabasePlatform();
  323. $sql = $platform->getDropTableSQL($platform->quoteIdentifier($tableName));
  324. self::$connection->query($sql);
  325. self::$connection->commit();
  326. }
  327. /**
  328. * remove all tables defined in a database structure xml file
  329. * @param string $file the xml file describing the tables
  330. */
  331. public static function removeDBStructure($file) {
  332. $schemaManager = self::getMDB2SchemaManager();
  333. $schemaManager->removeDBStructure($file);
  334. }
  335. /**
  336. * check if a result is an error, works with Doctrine
  337. * @param mixed $result
  338. * @return bool
  339. */
  340. public static function isError($result) {
  341. //Doctrine returns false on error (and throws an exception)
  342. return $result === false;
  343. }
  344. /**
  345. * check if a result is an error and throws an exception, works with \Doctrine\DBAL\DBALException
  346. * @param mixed $result
  347. * @param string $message
  348. * @return void
  349. * @throws DatabaseException
  350. */
  351. public static function raiseExceptionOnError($result, $message = null) {
  352. if(self::isError($result)) {
  353. if ($message === null) {
  354. $message = self::getErrorMessage($result);
  355. } else {
  356. $message .= ', Root cause:' . self::getErrorMessage($result);
  357. }
  358. throw new DatabaseException($message, self::getErrorCode($result));
  359. }
  360. }
  361. public static function getErrorCode($error) {
  362. $code = self::$connection->errorCode();
  363. return $code;
  364. }
  365. /**
  366. * returns the error code and message as a string for logging
  367. * works with DoctrineException
  368. * @param mixed $error
  369. * @return string
  370. */
  371. public static function getErrorMessage($error) {
  372. if (self::$connection) {
  373. return self::$connection->getError();
  374. }
  375. return '';
  376. }
  377. /**
  378. * @param bool $enabled
  379. */
  380. static public function enableCaching($enabled) {
  381. if ($enabled) {
  382. self::$connection->enableQueryStatementCaching();
  383. } else {
  384. self::$connection->disableQueryStatementCaching();
  385. }
  386. }
  387. /**
  388. * Checks if a table exists in the database - the database prefix will be prepended
  389. *
  390. * @param string $table
  391. * @return bool
  392. * @throws DatabaseException
  393. */
  394. public static function tableExists($table) {
  395. $table = OC_Config::getValue('dbtableprefix', 'oc_' ) . trim($table);
  396. $dbType = OC_Config::getValue( 'dbtype', 'sqlite' );
  397. switch ($dbType) {
  398. case 'sqlite':
  399. case 'sqlite3':
  400. $sql = "SELECT name FROM sqlite_master "
  401. . "WHERE type = 'table' AND name = ? "
  402. . "UNION ALL SELECT name FROM sqlite_temp_master "
  403. . "WHERE type = 'table' AND name = ?";
  404. $result = \OC_DB::executeAudited($sql, array($table, $table));
  405. break;
  406. case 'mysql':
  407. $sql = 'SHOW TABLES LIKE ?';
  408. $result = \OC_DB::executeAudited($sql, array($table));
  409. break;
  410. case 'pgsql':
  411. $sql = 'SELECT tablename AS table_name, schemaname AS schema_name '
  412. . 'FROM pg_tables WHERE schemaname NOT LIKE \'pg_%\' '
  413. . 'AND schemaname != \'information_schema\' '
  414. . 'AND tablename = ?';
  415. $result = \OC_DB::executeAudited($sql, array($table));
  416. break;
  417. case 'oci':
  418. $sql = 'SELECT TABLE_NAME FROM USER_TABLES WHERE TABLE_NAME = ?';
  419. $result = \OC_DB::executeAudited($sql, array($table));
  420. break;
  421. case 'mssql':
  422. $sql = 'SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = ?';
  423. $result = \OC_DB::executeAudited($sql, array($table));
  424. break;
  425. default:
  426. throw new DatabaseException("Unknown database type: $dbType");
  427. }
  428. return $result->fetchOne() === $table;
  429. }
  430. }