You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

db.php 25KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865
  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. $message = 'Failed to get existing database structure for updating ('.$error.', '.$detail.')';
  456. OC_Log::write('core', $message, OC_Log::FATAL);
  457. throw new Exception($message);
  458. }
  459. // Make changes and save them to an in-memory file
  460. $file2 = 'static://db_scheme';
  461. $content = str_replace( '*dbname*', $previousSchema['name'], $content );
  462. $content = str_replace( '*dbprefix*', $CONFIG_DBTABLEPREFIX, $content );
  463. /* FIXME: use CURRENT_TIMESTAMP for all databases. mysql supports it as a default for DATETIME since 5.6.5 [1]
  464. * as a fallback we could use <default>0000-01-01 00:00:00</default> everywhere
  465. * [1] http://bugs.mysql.com/bug.php?id=27645
  466. * http://dev.mysql.com/doc/refman/5.0/en/timestamp-initialization.html
  467. * http://www.postgresql.org/docs/8.1/static/functions-datetime.html
  468. * http://www.sqlite.org/lang_createtable.html
  469. * http://docs.oracle.com/cd/B19306_01/server.102/b14200/functions037.htm
  470. */
  471. if( $CONFIG_DBTYPE == 'pgsql' ) { //mysql support it too but sqlite doesn't
  472. $content = str_replace( '<default>0000-00-00 00:00:00</default>', '<default>CURRENT_TIMESTAMP</default>', $content );
  473. }
  474. file_put_contents( $file2, $content );
  475. $op = self::$schema->updateDatabase($file2, $previousSchema, array(), false);
  476. //clean up memory
  477. unlink( $file2 );
  478. if (PEAR::isError($op)) {
  479. $error = $op->getMessage();
  480. $detail = $op->getDebugInfo();
  481. $message = 'Failed to update database structure ('.$error.', '.$detail.')';
  482. OC_Log::write('core', $message, OC_Log::FATAL);
  483. throw new Exception($message);
  484. }
  485. return true;
  486. }
  487. /**
  488. * @brief connects to a MDB2 database scheme
  489. * @returns bool
  490. *
  491. * Connects to a MDB2 database scheme
  492. */
  493. private static function connectScheme() {
  494. // We need a mdb2 database connection
  495. self::connectMDB2();
  496. self::$MDB2->loadModule('Manager');
  497. self::$MDB2->loadModule('Reverse');
  498. // Connect if this did not happen before
  499. if(!self::$schema) {
  500. require_once 'MDB2/Schema.php';
  501. self::$schema=MDB2_Schema::factory(self::$MDB2);
  502. }
  503. return true;
  504. }
  505. /**
  506. * @brief Insert a row if a matching row doesn't exists.
  507. * @param string $table. The table to insert into in the form '*PREFIX*tableName'
  508. * @param array $input. An array of fieldname/value pairs
  509. * @returns The return value from PDOStatementWrapper->execute()
  510. */
  511. public static function insertIfNotExist($table, $input) {
  512. self::connect();
  513. $prefix = OC_Config::getValue( "dbtableprefix", "oc_" );
  514. $table = str_replace( '*PREFIX*', $prefix, $table );
  515. if(is_null(self::$type)) {
  516. self::$type=OC_Config::getValue( "dbtype", "sqlite" );
  517. }
  518. $type = self::$type;
  519. $query = '';
  520. // differences in escaping of table names ('`' for mysql) and getting the current timestamp
  521. if( $type == 'sqlite' || $type == 'sqlite3' ) {
  522. // NOTE: For SQLite we have to use this clumsy approach
  523. // otherwise all fieldnames used must have a unique key.
  524. $query = 'SELECT * FROM "' . $table . '" WHERE ';
  525. foreach($input as $key => $value) {
  526. $query .= $key . " = '" . $value . '\' AND ';
  527. }
  528. $query = substr($query, 0, strlen($query) - 5);
  529. try {
  530. $stmt = self::prepare($query);
  531. $result = $stmt->execute();
  532. } catch(PDOException $e) {
  533. $entry = 'DB Error: "'.$e->getMessage() . '"<br />';
  534. $entry .= 'Offending command was: ' . $query . '<br />';
  535. OC_Log::write('core', $entry, OC_Log::FATAL);
  536. error_log('DB error: '.$entry);
  537. OC_Template::printErrorPage( $entry );
  538. }
  539. if($result->numRows() == 0) {
  540. $query = 'INSERT INTO "' . $table . '" ("'
  541. . implode('","', array_keys($input)) . '") VALUES("'
  542. . implode('","', array_values($input)) . '")';
  543. } else {
  544. return true;
  545. }
  546. } elseif( $type == 'pgsql' || $type == 'oci' || $type == 'mysql') {
  547. $query = 'INSERT INTO `' .$table . '` ('
  548. . implode(',', array_keys($input)) . ') SELECT \''
  549. . implode('\',\'', array_values($input)) . '\' FROM ' . $table . ' WHERE ';
  550. foreach($input as $key => $value) {
  551. $query .= $key . " = '" . $value . '\' AND ';
  552. }
  553. $query = substr($query, 0, strlen($query) - 5);
  554. $query .= ' HAVING COUNT(*) = 0';
  555. }
  556. // TODO: oci should be use " (quote) instead of ` (backtick).
  557. //OC_Log::write('core', __METHOD__ . ', type: ' . $type . ', query: ' . $query, OC_Log::DEBUG);
  558. try {
  559. $result = self::prepare($query);
  560. } catch(PDOException $e) {
  561. $entry = 'DB Error: "'.$e->getMessage() . '"<br />';
  562. $entry .= 'Offending command was: ' . $query.'<br />';
  563. OC_Log::write('core', $entry, OC_Log::FATAL);
  564. error_log('DB error: ' . $entry);
  565. OC_Template::printErrorPage( $entry );
  566. }
  567. return $result->execute();
  568. }
  569. /**
  570. * @brief does minor changes to query
  571. * @param string $query Query string
  572. * @return string corrected query string
  573. *
  574. * This function replaces *PREFIX* with the value of $CONFIG_DBTABLEPREFIX
  575. * and replaces the ` with ' or " according to the database driver.
  576. */
  577. private static function processQuery( $query ) {
  578. self::connect();
  579. // We need Database type and table prefix
  580. if(is_null(self::$type)) {
  581. self::$type=OC_Config::getValue( "dbtype", "sqlite" );
  582. }
  583. $type = self::$type;
  584. if(is_null(self::$prefix)) {
  585. self::$prefix=OC_Config::getValue( "dbtableprefix", "oc_" );
  586. }
  587. $prefix = self::$prefix;
  588. // differences in escaping of table names ('`' for mysql) and getting the current timestamp
  589. if( $type == 'sqlite' || $type == 'sqlite3' ) {
  590. $query = str_replace( '`', '"', $query );
  591. $query = str_ireplace( 'NOW()', 'datetime(\'now\')', $query );
  592. $query = str_ireplace( 'UNIX_TIMESTAMP()', 'strftime(\'%s\',\'now\')', $query );
  593. }elseif( $type == 'pgsql' ) {
  594. $query = str_replace( '`', '"', $query );
  595. $query = str_ireplace( 'UNIX_TIMESTAMP()', 'cast(extract(epoch from current_timestamp) as integer)', $query );
  596. }elseif( $type == 'oci' ) {
  597. $query = str_replace( '`', '"', $query );
  598. $query = str_ireplace( 'NOW()', 'CURRENT_TIMESTAMP', $query );
  599. }
  600. // replace table name prefix
  601. $query = str_replace( '*PREFIX*', $prefix, $query );
  602. return $query;
  603. }
  604. /**
  605. * @brief drop a table
  606. * @param string $tableName the table to drop
  607. */
  608. public static function dropTable($tableName) {
  609. self::connectMDB2();
  610. self::$MDB2->loadModule('Manager');
  611. self::$MDB2->dropTable($tableName);
  612. }
  613. /**
  614. * remove all tables defined in a database structure xml file
  615. * @param string $file the xml file describing the tables
  616. */
  617. public static function removeDBStructure($file) {
  618. $CONFIG_DBNAME = OC_Config::getValue( "dbname", "owncloud" );
  619. $CONFIG_DBTABLEPREFIX = OC_Config::getValue( "dbtableprefix", "oc_" );
  620. self::connectScheme();
  621. // read file
  622. $content = file_get_contents( $file );
  623. // Make changes and save them to a temporary file
  624. $file2 = tempnam( get_temp_dir(), 'oc_db_scheme_' );
  625. $content = str_replace( '*dbname*', $CONFIG_DBNAME, $content );
  626. $content = str_replace( '*dbprefix*', $CONFIG_DBTABLEPREFIX, $content );
  627. file_put_contents( $file2, $content );
  628. // get the tables
  629. $definition = self::$schema->parseDatabaseDefinitionFile( $file2 );
  630. // Delete our temporary file
  631. unlink( $file2 );
  632. $tables=array_keys($definition['tables']);
  633. foreach($tables as $table) {
  634. self::dropTable($table);
  635. }
  636. }
  637. /**
  638. * @brief replaces the owncloud tables with a new set
  639. * @param $file string path to the MDB2 xml db export file
  640. */
  641. public static function replaceDB( $file ) {
  642. $apps = OC_App::getAllApps();
  643. self::beginTransaction();
  644. // Delete the old tables
  645. self::removeDBStructure( OC::$SERVERROOT . '/db_structure.xml' );
  646. foreach($apps as $app) {
  647. $path = OC_App::getAppPath($app).'/appinfo/database.xml';
  648. if(file_exists($path)) {
  649. self::removeDBStructure( $path );
  650. }
  651. }
  652. // Create new tables
  653. self::createDBFromStructure( $file );
  654. self::commit();
  655. }
  656. /**
  657. * Start a transaction
  658. * @return bool
  659. */
  660. public static function beginTransaction() {
  661. self::connect();
  662. if (self::$backend==self::BACKEND_MDB2 && !self::$connection->supports('transactions')) {
  663. return false;
  664. }
  665. self::$connection->beginTransaction();
  666. self::$inTransaction=true;
  667. return true;
  668. }
  669. /**
  670. * Commit the database changes done during a transaction that is in progress
  671. * @return bool
  672. */
  673. public static function commit() {
  674. self::connect();
  675. if(!self::$inTransaction) {
  676. return false;
  677. }
  678. self::$connection->commit();
  679. self::$inTransaction=false;
  680. return true;
  681. }
  682. /**
  683. * check if a result is an error, works with MDB2 and PDOException
  684. * @param mixed $result
  685. * @return bool
  686. */
  687. public static function isError($result) {
  688. if(!$result) {
  689. return true;
  690. }elseif(self::$backend==self::BACKEND_MDB2 and PEAR::isError($result)) {
  691. return true;
  692. }else{
  693. return false;
  694. }
  695. }
  696. /**
  697. * returns the error code and message as a string for logging
  698. * works with MDB2 and PDOException
  699. * @param mixed $error
  700. * @return string
  701. */
  702. public static function getErrorMessage($error) {
  703. if ( self::$backend==self::BACKEND_MDB2 and PEAR::isError($error) ) {
  704. $msg = $error->getCode() . ': ' . $error->getMessage();
  705. if (defined('DEBUG') && DEBUG) {
  706. $msg .= '(' . $error->getDebugInfo() . ')';
  707. }
  708. } elseif (self::$backend==self::BACKEND_PDO and self::$PDO) {
  709. $msg = self::$PDO->errorCode() . ': ';
  710. $errorInfo = self::$PDO->errorInfo();
  711. if (is_array($errorInfo)) {
  712. $msg .= 'SQLSTATE = '.$errorInfo[0] . ', ';
  713. $msg .= 'Driver Code = '.$errorInfo[1] . ', ';
  714. $msg .= 'Driver Message = '.$errorInfo[2];
  715. }else{
  716. $msg = '';
  717. }
  718. }else{
  719. $msg = '';
  720. }
  721. return $msg;
  722. }
  723. }
  724. /**
  725. * small wrapper around PDOStatement to make it behave ,more like an MDB2 Statement
  726. */
  727. class PDOStatementWrapper{
  728. /**
  729. * @var PDOStatement
  730. */
  731. private $statement=null;
  732. private $lastArguments=array();
  733. public function __construct($statement) {
  734. $this->statement=$statement;
  735. }
  736. /**
  737. * make execute return the result instead of a bool
  738. */
  739. public function execute($input=array()) {
  740. $this->lastArguments=$input;
  741. if(count($input)>0) {
  742. $result=$this->statement->execute($input);
  743. }else{
  744. $result=$this->statement->execute();
  745. }
  746. if($result) {
  747. return $this;
  748. }else{
  749. return false;
  750. }
  751. }
  752. /**
  753. * provide numRows
  754. */
  755. public function numRows() {
  756. $regex = '/^SELECT\s+(?:ALL\s+|DISTINCT\s+)?(?:.*?)\s+FROM\s+(.*)$/i';
  757. if (preg_match($regex, $this->statement->queryString, $output) > 0) {
  758. $query = OC_DB::prepare("SELECT COUNT(*) FROM {$output[1]}", PDO::FETCH_NUM);
  759. return $query->execute($this->lastArguments)->fetchColumn();
  760. }else{
  761. return $this->statement->rowCount();
  762. }
  763. }
  764. /**
  765. * provide an alias for fetch
  766. */
  767. public function fetchRow() {
  768. return $this->statement->fetch();
  769. }
  770. /**
  771. * pass all other function directly to the PDOStatement
  772. */
  773. public function __call($name, $arguments) {
  774. return call_user_func_array(array($this->statement, $name), $arguments);
  775. }
  776. /**
  777. * Provide a simple fetchOne.
  778. * fetch single column from the next row
  779. * @param int $colnum the column number to fetch
  780. */
  781. public function fetchOne($colnum = 0) {
  782. return $this->statement->fetchColumn($colnum);
  783. }
  784. }