PageRenderTime 93ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/db.php

https://github.com/jlgg/simple_trash
PHP | 863 lines | 540 code | 79 blank | 244 comment | 75 complexity | c0641289136fc8621f299f9cdd5cbf24 MD5 | raw file
Possible License(s): AGPL-3.0, AGPL-1.0, MPL-2.0-no-copyleft-exception
  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. class DatabaseException extends Exception{
  23. private $query;
  24. public function __construct($message, $query){
  25. parent::__construct($message);
  26. $this->query = $query;
  27. }
  28. public function getQuery(){
  29. return $this->query;
  30. }
  31. }
  32. /**
  33. * This class manages the access to the database. It basically is a wrapper for
  34. * MDB2 with some adaptions.
  35. */
  36. class OC_DB {
  37. const BACKEND_PDO=0;
  38. const BACKEND_MDB2=1;
  39. /**
  40. * @var MDB2_Driver_Common
  41. */
  42. static private $connection; //the prefered connection to use, either PDO or MDB2
  43. static private $backend=null;
  44. /**
  45. * @var MDB2_Driver_Common
  46. */
  47. static private $MDB2=null;
  48. /**
  49. * @var PDO
  50. */
  51. static private $PDO=null;
  52. /**
  53. * @var MDB2_Schema
  54. */
  55. static private $schema=null;
  56. static private $inTransaction=false;
  57. static private $prefix=null;
  58. static private $type=null;
  59. /**
  60. * check which backend we should use
  61. * @return int BACKEND_MDB2 or BACKEND_PDO
  62. */
  63. private static function getDBBackend() {
  64. //check if we can use PDO, else use MDB2 (installation always needs to be done my mdb2)
  65. if(class_exists('PDO') && OC_Config::getValue('installed', false)) {
  66. $type = OC_Config::getValue( "dbtype", "sqlite" );
  67. if($type=='oci') { //oracle also always needs mdb2
  68. return self::BACKEND_MDB2;
  69. }
  70. if($type=='sqlite3') $type='sqlite';
  71. $drivers=PDO::getAvailableDrivers();
  72. if(array_search($type, $drivers)!==false) {
  73. return self::BACKEND_PDO;
  74. }
  75. }
  76. return self::BACKEND_MDB2;
  77. }
  78. /**
  79. * @brief connects to the database
  80. * @param int $backend
  81. * @return bool true if connection can be established or false on error
  82. *
  83. * Connects to the database as specified in config.php
  84. */
  85. public static function connect($backend=null) {
  86. if(self::$connection) {
  87. return true;
  88. }
  89. if(is_null($backend)) {
  90. $backend=self::getDBBackend();
  91. }
  92. if($backend==self::BACKEND_PDO) {
  93. $success = self::connectPDO();
  94. self::$connection=self::$PDO;
  95. self::$backend=self::BACKEND_PDO;
  96. }else{
  97. $success = self::connectMDB2();
  98. self::$connection=self::$MDB2;
  99. self::$backend=self::BACKEND_MDB2;
  100. }
  101. return $success;
  102. }
  103. /**
  104. * connect to the database using pdo
  105. *
  106. * @return bool
  107. */
  108. public static function connectPDO() {
  109. if(self::$connection) {
  110. if(self::$backend==self::BACKEND_MDB2) {
  111. self::disconnect();
  112. }else{
  113. return true;
  114. }
  115. }
  116. // The global data we need
  117. $name = OC_Config::getValue( "dbname", "owncloud" );
  118. $host = OC_Config::getValue( "dbhost", "" );
  119. $user = OC_Config::getValue( "dbuser", "" );
  120. $pass = OC_Config::getValue( "dbpassword", "" );
  121. $type = OC_Config::getValue( "dbtype", "sqlite" );
  122. if(strpos($host, ':')) {
  123. list($host, $port)=explode(':', $host, 2);
  124. }else{
  125. $port=false;
  126. }
  127. $opts = array();
  128. $datadir=OC_Config::getValue( "datadirectory", OC::$SERVERROOT.'/data' );
  129. // do nothing if the connection already has been established
  130. if(!self::$PDO) {
  131. // Add the dsn according to the database type
  132. switch($type) {
  133. case 'sqlite':
  134. $dsn='sqlite2:'.$datadir.'/'.$name.'.db';
  135. break;
  136. case 'sqlite3':
  137. $dsn='sqlite:'.$datadir.'/'.$name.'.db';
  138. break;
  139. case 'mysql':
  140. if($port) {
  141. $dsn='mysql:dbname='.$name.';host='.$host.';port='.$port;
  142. }else{
  143. $dsn='mysql:dbname='.$name.';host='.$host;
  144. }
  145. $opts[PDO::MYSQL_ATTR_INIT_COMMAND] = "SET NAMES 'UTF8'";
  146. break;
  147. case 'pgsql':
  148. if($port) {
  149. $dsn='pgsql:dbname='.$name.';host='.$host.';port='.$port;
  150. }else{
  151. $dsn='pgsql:dbname='.$name.';host='.$host;
  152. }
  153. /**
  154. * Ugly fix for pg connections pbm when password use spaces
  155. */
  156. $e_user = addslashes($user);
  157. $e_password = addslashes($pass);
  158. $pass = $user = null;
  159. $dsn .= ";user='$e_user';password='$e_password'";
  160. /** END OF FIX***/
  161. break;
  162. case 'oci': // Oracle with PDO is unsupported
  163. if ($port) {
  164. $dsn = 'oci:dbname=//' . $host . ':' . $port . '/' . $name;
  165. } else {
  166. $dsn = 'oci:dbname=//' . $host . '/' . $name;
  167. }
  168. break;
  169. default:
  170. return false;
  171. }
  172. try{
  173. self::$PDO=new PDO($dsn, $user, $pass, $opts);
  174. }catch(PDOException $e) {
  175. OC_Template::printErrorPage( 'can not connect to database, using '.$type.'. ('.$e->getMessage().')' );
  176. }
  177. // We always, really always want associative arrays
  178. self::$PDO->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
  179. self::$PDO->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  180. }
  181. return true;
  182. }
  183. /**
  184. * connect to the database using mdb2
  185. */
  186. public static function connectMDB2() {
  187. if(self::$connection) {
  188. if(self::$backend==self::BACKEND_PDO) {
  189. self::disconnect();
  190. }else{
  191. return true;
  192. }
  193. }
  194. // The global data we need
  195. $name = OC_Config::getValue( "dbname", "owncloud" );
  196. $host = OC_Config::getValue( "dbhost", "" );
  197. $user = OC_Config::getValue( "dbuser", "" );
  198. $pass = OC_Config::getValue( "dbpassword", "" );
  199. $type = OC_Config::getValue( "dbtype", "sqlite" );
  200. $SERVERROOT=OC::$SERVERROOT;
  201. $datadir=OC_Config::getValue( "datadirectory", "$SERVERROOT/data" );
  202. // do nothing if the connection already has been established
  203. if(!self::$MDB2) {
  204. // Require MDB2.php (not required in the head of the file so we only load it when needed)
  205. require_once 'MDB2.php';
  206. // Prepare options array
  207. $options = array(
  208. 'portability' => MDB2_PORTABILITY_ALL - MDB2_PORTABILITY_FIX_CASE,
  209. 'log_line_break' => '<br>',
  210. 'idxname_format' => '%s',
  211. 'debug' => true,
  212. 'quote_identifier' => true );
  213. // Add the dsn according to the database type
  214. switch($type) {
  215. case 'sqlite':
  216. case 'sqlite3':
  217. $dsn = array(
  218. 'phptype' => $type,
  219. 'database' => "$datadir/$name.db",
  220. 'mode' => '0644'
  221. );
  222. break;
  223. case 'mysql':
  224. $dsn = array(
  225. 'phptype' => 'mysql',
  226. 'username' => $user,
  227. 'password' => $pass,
  228. 'hostspec' => $host,
  229. 'database' => $name
  230. );
  231. break;
  232. case 'pgsql':
  233. $dsn = array(
  234. 'phptype' => 'pgsql',
  235. 'username' => $user,
  236. 'password' => $pass,
  237. 'hostspec' => $host,
  238. 'database' => $name
  239. );
  240. break;
  241. case 'oci':
  242. $dsn = array(
  243. 'phptype' => 'oci8',
  244. 'username' => $user,
  245. 'password' => $pass,
  246. 'charset' => 'AL32UTF8',
  247. );
  248. if ($host != '') {
  249. $dsn['hostspec'] = $host;
  250. $dsn['database'] = $name;
  251. } else { // use dbname for hostspec
  252. $dsn['hostspec'] = $name;
  253. $dsn['database'] = $user;
  254. }
  255. break;
  256. default:
  257. return false;
  258. }
  259. // Try to establish connection
  260. self::$MDB2 = MDB2::factory( $dsn, $options );
  261. // Die if we could not connect
  262. if( PEAR::isError( self::$MDB2 )) {
  263. OC_Log::write('core', self::$MDB2->getUserInfo(), OC_Log::FATAL);
  264. OC_Log::write('core', self::$MDB2->getMessage(), OC_Log::FATAL);
  265. OC_Template::printErrorPage( 'can not connect to database, using '.$type.'. ('.self::$MDB2->getUserInfo().')' );
  266. }
  267. // We always, really always want associative arrays
  268. self::$MDB2->setFetchMode(MDB2_FETCHMODE_ASSOC);
  269. }
  270. // we are done. great!
  271. return true;
  272. }
  273. /**
  274. * @brief Prepare a SQL query
  275. * @param string $query Query string
  276. * @param int $limit
  277. * @param int $offset
  278. * @return MDB2_Statement_Common prepared SQL query
  279. *
  280. * SQL query via MDB2 prepare(), needs to be execute()'d!
  281. */
  282. static public function prepare( $query , $limit=null, $offset=null ) {
  283. if (!is_null($limit) && $limit != -1) {
  284. if (self::$backend == self::BACKEND_MDB2) {
  285. //MDB2 uses or emulates limits & offset internally
  286. self::$MDB2->setLimit($limit, $offset);
  287. } else {
  288. //PDO does not handle limit and offset.
  289. //FIXME: check limit notation for other dbs
  290. //the following sql thus might needs to take into account db ways of representing it
  291. //(oracle has no LIMIT / OFFSET)
  292. $limit = (int)$limit;
  293. $limitsql = ' LIMIT ' . $limit;
  294. if (!is_null($offset)) {
  295. $offset = (int)$offset;
  296. $limitsql .= ' OFFSET ' . $offset;
  297. }
  298. //insert limitsql
  299. if (substr($query, -1) == ';') { //if query ends with ;
  300. $query = substr($query, 0, -1) . $limitsql . ';';
  301. } else {
  302. $query.=$limitsql;
  303. }
  304. }
  305. }
  306. // Optimize the query
  307. $query = self::processQuery( $query );
  308. self::connect();
  309. // return the result
  310. if(self::$backend==self::BACKEND_MDB2) {
  311. $result = self::$connection->prepare( $query );
  312. // Die if we have an error (error means: bad query, not 0 results!)
  313. if( PEAR::isError($result)) {
  314. throw new DatabaseException($result->getMessage(), $query);
  315. }
  316. }else{
  317. try{
  318. $result=self::$connection->prepare($query);
  319. }catch(PDOException $e) {
  320. throw new DatabaseException($e->getMessage(), $query);
  321. }
  322. $result=new PDOStatementWrapper($result);
  323. }
  324. return $result;
  325. }
  326. /**
  327. * @brief gets last value of autoincrement
  328. * @param string $table The optional table name (will replace *PREFIX*) and add sequence suffix
  329. * @return int id
  330. *
  331. * MDB2 lastInsertID()
  332. *
  333. * Call this method right after the insert command or other functions may
  334. * cause trouble!
  335. */
  336. public static function insertid($table=null) {
  337. self::connect();
  338. $type = OC_Config::getValue( "dbtype", "sqlite" );
  339. if( $type == 'pgsql' ) {
  340. $query = self::prepare('SELECT lastval() AS id');
  341. $row = $query->execute()->fetchRow();
  342. return $row['id'];
  343. }else{
  344. if($table !== null) {
  345. $prefix = OC_Config::getValue( "dbtableprefix", "oc_" );
  346. $suffix = OC_Config::getValue( "dbsequencesuffix", "_id_seq" );
  347. $table = str_replace( '*PREFIX*', $prefix, $table ).$suffix;
  348. }
  349. return self::$connection->lastInsertId($table);
  350. }
  351. }
  352. /**
  353. * @brief Disconnect
  354. * @return bool
  355. *
  356. * This is good bye, good bye, yeah!
  357. */
  358. public static function disconnect() {
  359. // Cut connection if required
  360. if(self::$connection) {
  361. if(self::$backend==self::BACKEND_MDB2) {
  362. self::$connection->disconnect();
  363. }
  364. self::$connection=false;
  365. self::$MDB2=false;
  366. self::$PDO=false;
  367. }
  368. return true;
  369. }
  370. /**
  371. * @brief saves database scheme to xml file
  372. * @param string $file name of file
  373. * @param int $mode
  374. * @return bool
  375. *
  376. * TODO: write more documentation
  377. */
  378. public static function getDbStructure( $file, $mode=MDB2_SCHEMA_DUMP_STRUCTURE) {
  379. self::connectScheme();
  380. // write the scheme
  381. $definition = self::$schema->getDefinitionFromDatabase();
  382. $dump_options = array(
  383. 'output_mode' => 'file',
  384. 'output' => $file,
  385. 'end_of_line' => "\n"
  386. );
  387. self::$schema->dumpDatabase( $definition, $dump_options, $mode );
  388. return true;
  389. }
  390. /**
  391. * @brief Creates tables from XML file
  392. * @param string $file file to read structure from
  393. * @return bool
  394. *
  395. * TODO: write more documentation
  396. */
  397. public static function createDbFromStructure( $file ) {
  398. $CONFIG_DBNAME = OC_Config::getValue( "dbname", "owncloud" );
  399. $CONFIG_DBTABLEPREFIX = OC_Config::getValue( "dbtableprefix", "oc_" );
  400. $CONFIG_DBTYPE = OC_Config::getValue( "dbtype", "sqlite" );
  401. self::connectScheme();
  402. // read file
  403. $content = file_get_contents( $file );
  404. // Make changes and save them to an in-memory file
  405. $file2 = 'static://db_scheme';
  406. $content = str_replace( '*dbname*', $CONFIG_DBNAME, $content );
  407. $content = str_replace( '*dbprefix*', $CONFIG_DBTABLEPREFIX, $content );
  408. /* FIXME: use CURRENT_TIMESTAMP for all databases. mysql supports it as a default for DATETIME since 5.6.5 [1]
  409. * as a fallback we could use <default>0000-01-01 00:00:00</default> everywhere
  410. * [1] http://bugs.mysql.com/bug.php?id=27645
  411. * http://dev.mysql.com/doc/refman/5.0/en/timestamp-initialization.html
  412. * http://www.postgresql.org/docs/8.1/static/functions-datetime.html
  413. * http://www.sqlite.org/lang_createtable.html
  414. * http://docs.oracle.com/cd/B19306_01/server.102/b14200/functions037.htm
  415. */
  416. if( $CONFIG_DBTYPE == 'pgsql' ) { //mysql support it too but sqlite doesn't
  417. $content = str_replace( '<default>0000-00-00 00:00:00</default>', '<default>CURRENT_TIMESTAMP</default>', $content );
  418. }
  419. file_put_contents( $file2, $content );
  420. // Try to create tables
  421. $definition = self::$schema->parseDatabaseDefinitionFile( $file2 );
  422. //clean up memory
  423. unlink( $file2 );
  424. // Die in case something went wrong
  425. if( $definition instanceof MDB2_Schema_Error ) {
  426. OC_Template::printErrorPage( $definition->getMessage().': '.$definition->getUserInfo() );
  427. }
  428. if(OC_Config::getValue('dbtype', 'sqlite')==='oci') {
  429. unset($definition['charset']); //or MDB2 tries SHUTDOWN IMMEDIATE
  430. $oldname = $definition['name'];
  431. $definition['name']=OC_Config::getValue( "dbuser", $oldname );
  432. }
  433. $ret=self::$schema->createDatabase( $definition );
  434. // Die in case something went wrong
  435. if( $ret instanceof MDB2_Error ) {
  436. OC_Template::printErrorPage( self::$MDB2->getDebugOutput().' '.$ret->getMessage() . ': ' . $ret->getUserInfo() );
  437. }
  438. return true;
  439. }
  440. /**
  441. * @brief update the database scheme
  442. * @param string $file file to read structure from
  443. * @return bool
  444. */
  445. public static function updateDbFromStructure($file) {
  446. $CONFIG_DBTABLEPREFIX = OC_Config::getValue( "dbtableprefix", "oc_" );
  447. $CONFIG_DBTYPE = OC_Config::getValue( "dbtype", "sqlite" );
  448. self::connectScheme();
  449. // read file
  450. $content = file_get_contents( $file );
  451. $previousSchema = self::$schema->getDefinitionFromDatabase();
  452. if (PEAR::isError($previousSchema)) {
  453. $error = $previousSchema->getMessage();
  454. $detail = $previousSchema->getDebugInfo();
  455. OC_Log::write('core', 'Failed to get existing database structure for upgrading ('.$error.', '.$detail.')', OC_Log::FATAL);
  456. return false;
  457. }
  458. // Make changes and save them to an in-memory file
  459. $file2 = 'static://db_scheme';
  460. $content = str_replace( '*dbname*', $previousSchema['name'], $content );
  461. $content = str_replace( '*dbprefix*', $CONFIG_DBTABLEPREFIX, $content );
  462. /* FIXME: use CURRENT_TIMESTAMP for all databases. mysql supports it as a default for DATETIME since 5.6.5 [1]
  463. * as a fallback we could use <default>0000-01-01 00:00:00</default> everywhere
  464. * [1] http://bugs.mysql.com/bug.php?id=27645
  465. * http://dev.mysql.com/doc/refman/5.0/en/timestamp-initialization.html
  466. * http://www.postgresql.org/docs/8.1/static/functions-datetime.html
  467. * http://www.sqlite.org/lang_createtable.html
  468. * http://docs.oracle.com/cd/B19306_01/server.102/b14200/functions037.htm
  469. */
  470. if( $CONFIG_DBTYPE == 'pgsql' ) { //mysql support it too but sqlite doesn't
  471. $content = str_replace( '<default>0000-00-00 00:00:00</default>', '<default>CURRENT_TIMESTAMP</default>', $content );
  472. }
  473. file_put_contents( $file2, $content );
  474. $op = self::$schema->updateDatabase($file2, $previousSchema, array(), false);
  475. //clean up memory
  476. unlink( $file2 );
  477. if (PEAR::isError($op)) {
  478. $error = $op->getMessage();
  479. $detail = $op->getDebugInfo();
  480. OC_Log::write('core', 'Failed to update database structure ('.$error.', '.$detail.')', OC_Log::FATAL);
  481. return false;
  482. }
  483. return true;
  484. }
  485. /**
  486. * @brief connects to a MDB2 database scheme
  487. * @returns bool
  488. *
  489. * Connects to a MDB2 database scheme
  490. */
  491. private static function connectScheme() {
  492. // We need a mdb2 database connection
  493. self::connectMDB2();
  494. self::$MDB2->loadModule('Manager');
  495. self::$MDB2->loadModule('Reverse');
  496. // Connect if this did not happen before
  497. if(!self::$schema) {
  498. require_once 'MDB2/Schema.php';
  499. self::$schema=MDB2_Schema::factory(self::$MDB2);
  500. }
  501. return true;
  502. }
  503. /**
  504. * @brief Insert a row if a matching row doesn't exists.
  505. * @param string $table. The table to insert into in the form '*PREFIX*tableName'
  506. * @param array $input. An array of fieldname/value pairs
  507. * @returns The return value from PDOStatementWrapper->execute()
  508. */
  509. public static function insertIfNotExist($table, $input) {
  510. self::connect();
  511. $prefix = OC_Config::getValue( "dbtableprefix", "oc_" );
  512. $table = str_replace( '*PREFIX*', $prefix, $table );
  513. if(is_null(self::$type)) {
  514. self::$type=OC_Config::getValue( "dbtype", "sqlite" );
  515. }
  516. $type = self::$type;
  517. $query = '';
  518. // differences in escaping of table names ('`' for mysql) and getting the current timestamp
  519. if( $type == 'sqlite' || $type == 'sqlite3' ) {
  520. // NOTE: For SQLite we have to use this clumsy approach
  521. // otherwise all fieldnames used must have a unique key.
  522. $query = 'SELECT * FROM "' . $table . '" WHERE ';
  523. foreach($input as $key => $value) {
  524. $query .= $key . " = '" . $value . '\' AND ';
  525. }
  526. $query = substr($query, 0, strlen($query) - 5);
  527. try {
  528. $stmt = self::prepare($query);
  529. $result = $stmt->execute();
  530. } catch(PDOException $e) {
  531. $entry = 'DB Error: "'.$e->getMessage() . '"<br />';
  532. $entry .= 'Offending command was: ' . $query . '<br />';
  533. OC_Log::write('core', $entry, OC_Log::FATAL);
  534. error_log('DB error: '.$entry);
  535. OC_Template::printErrorPage( $entry );
  536. }
  537. if($result->numRows() == 0) {
  538. $query = 'INSERT INTO "' . $table . '" ("'
  539. . implode('","', array_keys($input)) . '") VALUES("'
  540. . implode('","', array_values($input)) . '")';
  541. } else {
  542. return true;
  543. }
  544. } elseif( $type == 'pgsql' || $type == 'oci' || $type == 'mysql') {
  545. $query = 'INSERT INTO `' .$table . '` ('
  546. . implode(',', array_keys($input)) . ') SELECT \''
  547. . implode('\',\'', array_values($input)) . '\' FROM ' . $table . ' WHERE ';
  548. foreach($input as $key => $value) {
  549. $query .= $key . " = '" . $value . '\' AND ';
  550. }
  551. $query = substr($query, 0, strlen($query) - 5);
  552. $query .= ' HAVING COUNT(*) = 0';
  553. }
  554. // TODO: oci should be use " (quote) instead of ` (backtick).
  555. //OC_Log::write('core', __METHOD__ . ', type: ' . $type . ', query: ' . $query, OC_Log::DEBUG);
  556. try {
  557. $result = self::prepare($query);
  558. } catch(PDOException $e) {
  559. $entry = 'DB Error: "'.$e->getMessage() . '"<br />';
  560. $entry .= 'Offending command was: ' . $query.'<br />';
  561. OC_Log::write('core', $entry, OC_Log::FATAL);
  562. error_log('DB error: ' . $entry);
  563. OC_Template::printErrorPage( $entry );
  564. }
  565. return $result->execute();
  566. }
  567. /**
  568. * @brief does minor changes to query
  569. * @param string $query Query string
  570. * @return string corrected query string
  571. *
  572. * This function replaces *PREFIX* with the value of $CONFIG_DBTABLEPREFIX
  573. * and replaces the ` with ' or " according to the database driver.
  574. */
  575. private static function processQuery( $query ) {
  576. self::connect();
  577. // We need Database type and table prefix
  578. if(is_null(self::$type)) {
  579. self::$type=OC_Config::getValue( "dbtype", "sqlite" );
  580. }
  581. $type = self::$type;
  582. if(is_null(self::$prefix)) {
  583. self::$prefix=OC_Config::getValue( "dbtableprefix", "oc_" );
  584. }
  585. $prefix = self::$prefix;
  586. // differences in escaping of table names ('`' for mysql) and getting the current timestamp
  587. if( $type == 'sqlite' || $type == 'sqlite3' ) {
  588. $query = str_replace( '`', '"', $query );
  589. $query = str_ireplace( 'NOW()', 'datetime(\'now\')', $query );
  590. $query = str_ireplace( 'UNIX_TIMESTAMP()', 'strftime(\'%s\',\'now\')', $query );
  591. }elseif( $type == 'pgsql' ) {
  592. $query = str_replace( '`', '"', $query );
  593. $query = str_ireplace( 'UNIX_TIMESTAMP()', 'cast(extract(epoch from current_timestamp) as integer)', $query );
  594. }elseif( $type == 'oci' ) {
  595. $query = str_replace( '`', '"', $query );
  596. $query = str_ireplace( 'NOW()', 'CURRENT_TIMESTAMP', $query );
  597. }
  598. // replace table name prefix
  599. $query = str_replace( '*PREFIX*', $prefix, $query );
  600. return $query;
  601. }
  602. /**
  603. * @brief drop a table
  604. * @param string $tableName the table to drop
  605. */
  606. public static function dropTable($tableName) {
  607. self::connectMDB2();
  608. self::$MDB2->loadModule('Manager');
  609. self::$MDB2->dropTable($tableName);
  610. }
  611. /**
  612. * remove all tables defined in a database structure xml file
  613. * @param string $file the xml file describing the tables
  614. */
  615. public static function removeDBStructure($file) {
  616. $CONFIG_DBNAME = OC_Config::getValue( "dbname", "owncloud" );
  617. $CONFIG_DBTABLEPREFIX = OC_Config::getValue( "dbtableprefix", "oc_" );
  618. self::connectScheme();
  619. // read file
  620. $content = file_get_contents( $file );
  621. // Make changes and save them to a temporary file
  622. $file2 = tempnam( get_temp_dir(), 'oc_db_scheme_' );
  623. $content = str_replace( '*dbname*', $CONFIG_DBNAME, $content );
  624. $content = str_replace( '*dbprefix*', $CONFIG_DBTABLEPREFIX, $content );
  625. file_put_contents( $file2, $content );
  626. // get the tables
  627. $definition = self::$schema->parseDatabaseDefinitionFile( $file2 );
  628. // Delete our temporary file
  629. unlink( $file2 );
  630. $tables=array_keys($definition['tables']);
  631. foreach($tables as $table) {
  632. self::dropTable($table);
  633. }
  634. }
  635. /**
  636. * @brief replaces the owncloud tables with a new set
  637. * @param $file string path to the MDB2 xml db export file
  638. */
  639. public static function replaceDB( $file ) {
  640. $apps = OC_App::getAllApps();
  641. self::beginTransaction();
  642. // Delete the old tables
  643. self::removeDBStructure( OC::$SERVERROOT . '/db_structure.xml' );
  644. foreach($apps as $app) {
  645. $path = OC_App::getAppPath($app).'/appinfo/database.xml';
  646. if(file_exists($path)) {
  647. self::removeDBStructure( $path );
  648. }
  649. }
  650. // Create new tables
  651. self::createDBFromStructure( $file );
  652. self::commit();
  653. }
  654. /**
  655. * Start a transaction
  656. * @return bool
  657. */
  658. public static function beginTransaction() {
  659. self::connect();
  660. if (self::$backend==self::BACKEND_MDB2 && !self::$connection->supports('transactions')) {
  661. return false;
  662. }
  663. self::$connection->beginTransaction();
  664. self::$inTransaction=true;
  665. return true;
  666. }
  667. /**
  668. * Commit the database changes done during a transaction that is in progress
  669. * @return bool
  670. */
  671. public static function commit() {
  672. self::connect();
  673. if(!self::$inTransaction) {
  674. return false;
  675. }
  676. self::$connection->commit();
  677. self::$inTransaction=false;
  678. return true;
  679. }
  680. /**
  681. * check if a result is an error, works with MDB2 and PDOException
  682. * @param mixed $result
  683. * @return bool
  684. */
  685. public static function isError($result) {
  686. if(!$result) {
  687. return true;
  688. }elseif(self::$backend==self::BACKEND_MDB2 and PEAR::isError($result)) {
  689. return true;
  690. }else{
  691. return false;
  692. }
  693. }
  694. /**
  695. * returns the error code and message as a string for logging
  696. * works with MDB2 and PDOException
  697. * @param mixed $error
  698. * @return string
  699. */
  700. public static function getErrorMessage($error) {
  701. if ( self::$backend==self::BACKEND_MDB2 and PEAR::isError($error) ) {
  702. $msg = $error->getCode() . ': ' . $error->getMessage();
  703. if (defined('DEBUG') && DEBUG) {
  704. $msg .= '(' . $error->getDebugInfo() . ')';
  705. }
  706. } elseif (self::$backend==self::BACKEND_PDO and self::$PDO) {
  707. $msg = self::$PDO->errorCode() . ': ';
  708. $errorInfo = self::$PDO->errorInfo();
  709. if (is_array($errorInfo)) {
  710. $msg .= 'SQLSTATE = '.$errorInfo[0] . ', ';
  711. $msg .= 'Driver Code = '.$errorInfo[1] . ', ';
  712. $msg .= 'Driver Message = '.$errorInfo[2];
  713. }else{
  714. $msg = '';
  715. }
  716. }else{
  717. $msg = '';
  718. }
  719. return $msg;
  720. }
  721. }
  722. /**
  723. * small wrapper around PDOStatement to make it behave ,more like an MDB2 Statement
  724. */
  725. class PDOStatementWrapper{
  726. /**
  727. * @var PDOStatement
  728. */
  729. private $statement=null;
  730. private $lastArguments=array();
  731. public function __construct($statement) {
  732. $this->statement=$statement;
  733. }
  734. /**
  735. * make execute return the result instead of a bool
  736. */
  737. public function execute($input=array()) {
  738. $this->lastArguments=$input;
  739. if(count($input)>0) {
  740. $result=$this->statement->execute($input);
  741. }else{
  742. $result=$this->statement->execute();
  743. }
  744. if($result) {
  745. return $this;
  746. }else{
  747. return false;
  748. }
  749. }
  750. /**
  751. * provide numRows
  752. */
  753. public function numRows() {
  754. $regex = '/^SELECT\s+(?:ALL\s+|DISTINCT\s+)?(?:.*?)\s+FROM\s+(.*)$/i';
  755. if (preg_match($regex, $this->statement->queryString, $output) > 0) {
  756. $query = OC_DB::prepare("SELECT COUNT(*) FROM {$output[1]}", PDO::FETCH_NUM);
  757. return $query->execute($this->lastArguments)->fetchColumn();
  758. }else{
  759. return $this->statement->rowCount();
  760. }
  761. }
  762. /**
  763. * provide an alias for fetch
  764. */
  765. public function fetchRow() {
  766. return $this->statement->fetch();
  767. }
  768. /**
  769. * pass all other function directly to the PDOStatement
  770. */
  771. public function __call($name, $arguments) {
  772. return call_user_func_array(array($this->statement, $name), $arguments);
  773. }
  774. /**
  775. * Provide a simple fetchOne.
  776. * fetch single column from the next row
  777. * @param int $colnum the column number to fetch
  778. */
  779. public function fetchOne($colnum = 0) {
  780. return $this->statement->fetchColumn($colnum);
  781. }
  782. }