db.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781
  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. echo( '<b>can not connect to database, using '.$type.'. ('.$e->getMessage().')</center>');
  166. die();
  167. }
  168. // We always, really always want associative arrays
  169. self::$PDO->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
  170. self::$PDO->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  171. }
  172. return true;
  173. }
  174. /**
  175. * connect to the database using mdb2
  176. */
  177. public static function connectMDB2() {
  178. if(self::$connection) {
  179. if(self::$backend==self::BACKEND_PDO) {
  180. self::disconnect();
  181. }else{
  182. return true;
  183. }
  184. }
  185. // The global data we need
  186. $name = OC_Config::getValue( "dbname", "owncloud" );
  187. $host = OC_Config::getValue( "dbhost", "" );
  188. $user = OC_Config::getValue( "dbuser", "" );
  189. $pass = OC_Config::getValue( "dbpassword", "" );
  190. $type = OC_Config::getValue( "dbtype", "sqlite" );
  191. $SERVERROOT=OC::$SERVERROOT;
  192. $datadir=OC_Config::getValue( "datadirectory", "$SERVERROOT/data" );
  193. // do nothing if the connection already has been established
  194. if(!self::$MDB2) {
  195. // Require MDB2.php (not required in the head of the file so we only load it when needed)
  196. require_once 'MDB2.php';
  197. // Prepare options array
  198. $options = array(
  199. 'portability' => MDB2_PORTABILITY_ALL - MDB2_PORTABILITY_FIX_CASE,
  200. 'log_line_break' => '<br>',
  201. 'idxname_format' => '%s',
  202. 'debug' => true,
  203. 'quote_identifier' => true );
  204. // Add the dsn according to the database type
  205. switch($type) {
  206. case 'sqlite':
  207. case 'sqlite3':
  208. $dsn = array(
  209. 'phptype' => $type,
  210. 'database' => "$datadir/$name.db",
  211. 'mode' => '0644'
  212. );
  213. break;
  214. case 'mysql':
  215. $dsn = array(
  216. 'phptype' => 'mysql',
  217. 'username' => $user,
  218. 'password' => $pass,
  219. 'hostspec' => $host,
  220. 'database' => $name
  221. );
  222. break;
  223. case 'pgsql':
  224. $dsn = array(
  225. 'phptype' => 'pgsql',
  226. 'username' => $user,
  227. 'password' => $pass,
  228. 'hostspec' => $host,
  229. 'database' => $name
  230. );
  231. break;
  232. case 'oci':
  233. $dsn = array(
  234. 'phptype' => 'oci8',
  235. 'username' => $user,
  236. 'password' => $pass,
  237. 'charset' => 'AL32UTF8',
  238. );
  239. if ($host != '') {
  240. $dsn['hostspec'] = $host;
  241. $dsn['database'] = $name;
  242. } else { // use dbname for hostspec
  243. $dsn['hostspec'] = $name;
  244. $dsn['database'] = $user;
  245. }
  246. break;
  247. default:
  248. return false;
  249. }
  250. // Try to establish connection
  251. self::$MDB2 = MDB2::factory( $dsn, $options );
  252. // Die if we could not connect
  253. if( PEAR::isError( self::$MDB2 )) {
  254. echo( '<b>can not connect to database, using '.$type.'. ('.self::$MDB2->getUserInfo().')</center>');
  255. OC_Log::write('core', self::$MDB2->getUserInfo(), OC_Log::FATAL);
  256. OC_Log::write('core', self::$MDB2->getMessage(), OC_Log::FATAL);
  257. die();
  258. }
  259. // We always, really always want associative arrays
  260. self::$MDB2->setFetchMode(MDB2_FETCHMODE_ASSOC);
  261. }
  262. // we are done. great!
  263. return true;
  264. }
  265. /**
  266. * @brief Prepare a SQL query
  267. * @param string $query Query string
  268. * @param int $limit
  269. * @param int $offset
  270. * @return MDB2_Statement_Common prepared SQL query
  271. *
  272. * SQL query via MDB2 prepare(), needs to be execute()'d!
  273. */
  274. static public function prepare( $query , $limit=null, $offset=null ) {
  275. if (!is_null($limit) && $limit != -1) {
  276. if (self::$backend == self::BACKEND_MDB2) {
  277. //MDB2 uses or emulates limits & offset internally
  278. self::$MDB2->setLimit($limit, $offset);
  279. } else {
  280. //PDO does not handle limit and offset.
  281. //FIXME: check limit notation for other dbs
  282. //the following sql thus might needs to take into account db ways of representing it
  283. //(oracle has no LIMIT / OFFSET)
  284. $limit = (int)$limit;
  285. $limitsql = ' LIMIT ' . $limit;
  286. if (!is_null($offset)) {
  287. $offset = (int)$offset;
  288. $limitsql .= ' OFFSET ' . $offset;
  289. }
  290. //insert limitsql
  291. if (substr($query, -1) == ';') { //if query ends with ;
  292. $query = substr($query, 0, -1) . $limitsql . ';';
  293. } else {
  294. $query.=$limitsql;
  295. }
  296. }
  297. }
  298. // Optimize the query
  299. $query = self::processQuery( $query );
  300. self::connect();
  301. // return the result
  302. if(self::$backend==self::BACKEND_MDB2) {
  303. $result = self::$connection->prepare( $query );
  304. // Die if we have an error (error means: bad query, not 0 results!)
  305. if( PEAR::isError($result)) {
  306. $entry = 'DB Error: "'.$result->getMessage().'"<br />';
  307. $entry .= 'Offending command was: '.htmlentities($query).'<br />';
  308. OC_Log::write('core', $entry,OC_Log::FATAL);
  309. error_log('DB error: '.$entry);
  310. die( $entry );
  311. }
  312. }else{
  313. try{
  314. $result=self::$connection->prepare($query);
  315. }catch(PDOException $e) {
  316. $entry = 'DB Error: "'.$e->getMessage().'"<br />';
  317. $entry .= 'Offending command was: '.htmlentities($query).'<br />';
  318. OC_Log::write('core', $entry,OC_Log::FATAL);
  319. error_log('DB error: '.$entry);
  320. die( $entry );
  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. if($table !== null) {
  339. $prefix = OC_Config::getValue( "dbtableprefix", "oc_" );
  340. $suffix = OC_Config::getValue( "dbsequencesuffix", "_id_seq" );
  341. $table = str_replace( '*PREFIX*', $prefix, $table ).$suffix;
  342. }
  343. return self::$connection->lastInsertId($table);
  344. }
  345. /**
  346. * @brief Disconnect
  347. * @return bool
  348. *
  349. * This is good bye, good bye, yeah!
  350. */
  351. public static function disconnect() {
  352. // Cut connection if required
  353. if(self::$connection) {
  354. if(self::$backend==self::BACKEND_MDB2) {
  355. self::$connection->disconnect();
  356. }
  357. self::$connection=false;
  358. self::$MDB2=false;
  359. self::$PDO=false;
  360. }
  361. return true;
  362. }
  363. /**
  364. * @brief saves database scheme to xml file
  365. * @param string $file name of file
  366. * @param int $mode
  367. * @return bool
  368. *
  369. * TODO: write more documentation
  370. */
  371. public static function getDbStructure( $file ,$mode=MDB2_SCHEMA_DUMP_STRUCTURE) {
  372. self::connectScheme();
  373. // write the scheme
  374. $definition = self::$schema->getDefinitionFromDatabase();
  375. $dump_options = array(
  376. 'output_mode' => 'file',
  377. 'output' => $file,
  378. 'end_of_line' => "\n"
  379. );
  380. self::$schema->dumpDatabase( $definition, $dump_options, $mode );
  381. return true;
  382. }
  383. /**
  384. * @brief Creates tables from XML file
  385. * @param string $file file to read structure from
  386. * @return bool
  387. *
  388. * TODO: write more documentation
  389. */
  390. public static function createDbFromStructure( $file ) {
  391. $CONFIG_DBNAME = OC_Config::getValue( "dbname", "owncloud" );
  392. $CONFIG_DBTABLEPREFIX = OC_Config::getValue( "dbtableprefix", "oc_" );
  393. $CONFIG_DBTYPE = OC_Config::getValue( "dbtype", "sqlite" );
  394. self::connectScheme();
  395. // read file
  396. $content = file_get_contents( $file );
  397. // Make changes and save them to an in-memory file
  398. $file2 = 'static://db_scheme';
  399. $content = str_replace( '*dbname*', $CONFIG_DBNAME, $content );
  400. $content = str_replace( '*dbprefix*', $CONFIG_DBTABLEPREFIX, $content );
  401. /* FIXME: REMOVE this commented code
  402. * actually mysql, postgresql, sqlite and oracle support CURRENT_TIMESTAMP
  403. * http://dev.mysql.com/doc/refman/5.0/en/timestamp-initialization.html
  404. * http://www.postgresql.org/docs/8.1/static/functions-datetime.html
  405. * http://www.sqlite.org/lang_createtable.html
  406. * http://docs.oracle.com/cd/B19306_01/server.102/b14200/functions037.htm
  407. */
  408. if( $CONFIG_DBTYPE == 'pgsql' ) { //mysql support it too but sqlite doesn't
  409. $content = str_replace( '<default>0000-00-00 00:00:00</default>', '<default>CURRENT_TIMESTAMP</default>', $content );
  410. }
  411. file_put_contents( $file2, $content );
  412. // Try to create tables
  413. $definition = self::$schema->parseDatabaseDefinitionFile( $file2 );
  414. //clean up memory
  415. unlink( $file2 );
  416. // Die in case something went wrong
  417. if( $definition instanceof MDB2_Schema_Error ) {
  418. die( $definition->getMessage().': '.$definition->getUserInfo());
  419. }
  420. if(OC_Config::getValue('dbtype', 'sqlite')==='oci') {
  421. unset($definition['charset']); //or MDB2 tries SHUTDOWN IMMEDIATE
  422. $oldname = $definition['name'];
  423. $definition['name']=OC_Config::getValue( "dbuser", $oldname );
  424. }
  425. $ret=self::$schema->createDatabase( $definition );
  426. // Die in case something went wrong
  427. if( $ret instanceof MDB2_Error ) {
  428. echo (self::$MDB2->getDebugOutput());
  429. die ($ret->getMessage() . ': ' . $ret->getUserInfo());
  430. }
  431. return true;
  432. }
  433. /**
  434. * @brief update the database scheme
  435. * @param string $file file to read structure from
  436. * @return bool
  437. */
  438. public static function updateDbFromStructure($file) {
  439. $CONFIG_DBTABLEPREFIX = OC_Config::getValue( "dbtableprefix", "oc_" );
  440. self::connectScheme();
  441. // read file
  442. $content = file_get_contents( $file );
  443. $previousSchema = self::$schema->getDefinitionFromDatabase();
  444. if (PEAR::isError($previousSchema)) {
  445. $error = $previousSchema->getMessage();
  446. $detail = $previousSchema->getDebugInfo();
  447. OC_Log::write('core', 'Failed to get existing database structure for upgrading ('.$error.', '.$detail.')', OC_Log::FATAL);
  448. return false;
  449. }
  450. // Make changes and save them to an in-memory file
  451. $file2 = 'static://db_scheme';
  452. $content = str_replace( '*dbname*', $previousSchema['name'], $content );
  453. $content = str_replace( '*dbprefix*', $CONFIG_DBTABLEPREFIX, $content );
  454. /* FIXME: REMOVE this commented code
  455. * actually mysql, postgresql, sqlite and oracle support CUURENT_TIMESTAMP
  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. if( $CONFIG_DBTYPE == 'pgsql' ) { //mysql support it too but sqlite doesn't
  461. $content = str_replace( '<default>0000-00-00 00:00:00</default>', '<default>CURRENT_TIMESTAMP</default>', $content );
  462. }
  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 does minor changes to query
  496. * @param string $query Query string
  497. * @return string corrected query string
  498. *
  499. * This function replaces *PREFIX* with the value of $CONFIG_DBTABLEPREFIX
  500. * and replaces the ` with ' or " according to the database driver.
  501. */
  502. private static function processQuery( $query ) {
  503. self::connect();
  504. // We need Database type and table prefix
  505. if(is_null(self::$type)) {
  506. self::$type=OC_Config::getValue( "dbtype", "sqlite" );
  507. }
  508. $type = self::$type;
  509. if(is_null(self::$prefix)) {
  510. self::$prefix=OC_Config::getValue( "dbtableprefix", "oc_" );
  511. }
  512. $prefix = self::$prefix;
  513. // differences in escaping of table names ('`' for mysql) and getting the current timestamp
  514. if( $type == 'sqlite' || $type == 'sqlite3' ) {
  515. $query = str_replace( '`', '"', $query );
  516. $query = str_ireplace( 'NOW()', 'datetime(\'now\')', $query );
  517. $query = str_ireplace( 'UNIX_TIMESTAMP()', 'strftime(\'%s\',\'now\')', $query );
  518. }elseif( $type == 'pgsql' ) {
  519. $query = str_replace( '`', '"', $query );
  520. $query = str_ireplace( 'UNIX_TIMESTAMP()', 'cast(extract(epoch from current_timestamp) as integer)', $query );
  521. }elseif( $type == 'oci' ) {
  522. $query = str_replace( '`', '"', $query );
  523. $query = str_ireplace( 'NOW()', 'CURRENT_TIMESTAMP', $query );
  524. }
  525. // replace table name prefix
  526. $query = str_replace( '*PREFIX*', $prefix, $query );
  527. return $query;
  528. }
  529. /**
  530. * @brief drop a table
  531. * @param string $tableName the table to drop
  532. */
  533. public static function dropTable($tableName) {
  534. self::connectMDB2();
  535. self::$MDB2->loadModule('Manager');
  536. self::$MDB2->dropTable($tableName);
  537. }
  538. /**
  539. * remove all tables defined in a database structure xml file
  540. * @param string $file the xml file describing the tables
  541. */
  542. public static function removeDBStructure($file) {
  543. $CONFIG_DBNAME = OC_Config::getValue( "dbname", "owncloud" );
  544. $CONFIG_DBTABLEPREFIX = OC_Config::getValue( "dbtableprefix", "oc_" );
  545. self::connectScheme();
  546. // read file
  547. $content = file_get_contents( $file );
  548. // Make changes and save them to a temporary file
  549. $file2 = tempnam( get_temp_dir(), 'oc_db_scheme_' );
  550. $content = str_replace( '*dbname*', $CONFIG_DBNAME, $content );
  551. $content = str_replace( '*dbprefix*', $CONFIG_DBTABLEPREFIX, $content );
  552. file_put_contents( $file2, $content );
  553. // get the tables
  554. $definition = self::$schema->parseDatabaseDefinitionFile( $file2 );
  555. // Delete our temporary file
  556. unlink( $file2 );
  557. $tables=array_keys($definition['tables']);
  558. foreach($tables as $table) {
  559. self::dropTable($table);
  560. }
  561. }
  562. /**
  563. * @brief replaces the owncloud tables with a new set
  564. * @param $file string path to the MDB2 xml db export file
  565. */
  566. public static function replaceDB( $file ) {
  567. $apps = OC_App::getAllApps();
  568. self::beginTransaction();
  569. // Delete the old tables
  570. self::removeDBStructure( OC::$SERVERROOT . '/db_structure.xml' );
  571. foreach($apps as $app) {
  572. $path = OC_App::getAppPath($app).'/appinfo/database.xml';
  573. if(file_exists($path)) {
  574. self::removeDBStructure( $path );
  575. }
  576. }
  577. // Create new tables
  578. self::createDBFromStructure( $file );
  579. self::commit();
  580. }
  581. /**
  582. * Start a transaction
  583. * @return bool
  584. */
  585. public static function beginTransaction() {
  586. self::connect();
  587. if (self::$backend==self::BACKEND_MDB2 && !self::$connection->supports('transactions')) {
  588. return false;
  589. }
  590. self::$connection->beginTransaction();
  591. self::$inTransaction=true;
  592. return true;
  593. }
  594. /**
  595. * Commit the database changes done during a transaction that is in progress
  596. * @return bool
  597. */
  598. public static function commit() {
  599. self::connect();
  600. if(!self::$inTransaction) {
  601. return false;
  602. }
  603. self::$connection->commit();
  604. self::$inTransaction=false;
  605. return true;
  606. }
  607. /**
  608. * check if a result is an error, works with MDB2 and PDOException
  609. * @param mixed $result
  610. * @return bool
  611. */
  612. public static function isError($result) {
  613. if(!$result) {
  614. return true;
  615. }elseif(self::$backend==self::BACKEND_MDB2 and PEAR::isError($result)) {
  616. return true;
  617. }else{
  618. return false;
  619. }
  620. }
  621. /**
  622. * returns the error code and message as a string for logging
  623. * works with MDB2 and PDOException
  624. * @param mixed $error
  625. * @return string
  626. */
  627. public static function getErrorMessage($error) {
  628. if ( self::$backend==self::BACKEND_MDB2 and PEAR::isError($error) ) {
  629. $msg = $error->getCode() . ': ' . $error->getMessage();
  630. if (defined('DEBUG') && DEBUG) {
  631. $msg .= '(' . $error->getDebugInfo() . ')';
  632. }
  633. } elseif (self::$backend==self::BACKEND_PDO and self::$PDO) {
  634. $msg = self::$PDO->errorCode() . ': ';
  635. $errorInfo = self::$PDO->errorInfo();
  636. if (is_array($errorInfo)) {
  637. $msg .= 'SQLSTATE = '.$errorInfo[0] . ', ';
  638. $msg .= 'Driver Code = '.$errorInfo[1] . ', ';
  639. $msg .= 'Driver Message = '.$errorInfo[2];
  640. }else{
  641. $msg = '';
  642. }
  643. }else{
  644. $msg = '';
  645. }
  646. return $msg;
  647. }
  648. }
  649. /**
  650. * small wrapper around PDOStatement to make it behave ,more like an MDB2 Statement
  651. */
  652. class PDOStatementWrapper{
  653. /**
  654. * @var PDOStatement
  655. */
  656. private $statement=null;
  657. private $lastArguments=array();
  658. public function __construct($statement) {
  659. $this->statement=$statement;
  660. }
  661. /**
  662. * make execute return the result instead of a bool
  663. */
  664. public function execute($input=array()) {
  665. $this->lastArguments=$input;
  666. if(count($input)>0) {
  667. $result=$this->statement->execute($input);
  668. }else{
  669. $result=$this->statement->execute();
  670. }
  671. if($result) {
  672. return $this;
  673. }else{
  674. return false;
  675. }
  676. }
  677. /**
  678. * provide numRows
  679. */
  680. public function numRows() {
  681. $regex = '/^SELECT\s+(?:ALL\s+|DISTINCT\s+)?(?:.*?)\s+FROM\s+(.*)$/i';
  682. if (preg_match($regex, $this->statement->queryString, $output) > 0) {
  683. $query = OC_DB::prepare("SELECT COUNT(*) FROM {$output[1]}", PDO::FETCH_NUM);
  684. return $query->execute($this->lastArguments)->fetchColumn();
  685. }else{
  686. return $this->statement->rowCount();
  687. }
  688. }
  689. /**
  690. * provide an alias for fetch
  691. */
  692. public function fetchRow() {
  693. return $this->statement->fetch();
  694. }
  695. /**
  696. * pass all other function directly to the PDOStatement
  697. */
  698. public function __call($name,$arguments) {
  699. return call_user_func_array(array($this->statement,$name), $arguments);
  700. }
  701. /**
  702. * Provide a simple fetchOne.
  703. * fetch single column from the next row
  704. * @param int $colnum the column number to fetch
  705. */
  706. public function fetchOne($colnum = 0) {
  707. return $this->statement->fetchColumn($colnum);
  708. }
  709. }