db.php 25 KB

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