db.php 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105
  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. static private $preparedQueries = array();
  40. static private $cachingEnabled = true;
  41. /**
  42. * @var MDB2_Driver_Common
  43. */
  44. static private $connection; //the prefered connection to use, either PDO or MDB2
  45. static private $backend=null;
  46. /**
  47. * @var MDB2_Driver_Common
  48. */
  49. static private $MDB2=null;
  50. /**
  51. * @var PDO
  52. */
  53. static private $PDO=null;
  54. /**
  55. * @var MDB2_Schema
  56. */
  57. static private $schema=null;
  58. static private $inTransaction=false;
  59. static private $prefix=null;
  60. static private $type=null;
  61. /**
  62. * check which backend we should use
  63. * @return int BACKEND_MDB2 or BACKEND_PDO
  64. */
  65. private static function getDBBackend() {
  66. //check if we can use PDO, else use MDB2 (installation always needs to be done my mdb2)
  67. if(class_exists('PDO') && OC_Config::getValue('installed', false)) {
  68. $type = OC_Config::getValue( "dbtype", "sqlite" );
  69. if($type=='oci') { //oracle also always needs mdb2
  70. return self::BACKEND_MDB2;
  71. }
  72. if($type=='sqlite3') $type='sqlite';
  73. $drivers=PDO::getAvailableDrivers();
  74. if(array_search($type, $drivers)!==false) {
  75. return self::BACKEND_PDO;
  76. }
  77. }
  78. return self::BACKEND_MDB2;
  79. }
  80. /**
  81. * @brief connects to the database
  82. * @param int $backend
  83. * @return bool true if connection can be established or false on error
  84. *
  85. * Connects to the database as specified in config.php
  86. */
  87. public static function connect($backend=null) {
  88. if(self::$connection) {
  89. return true;
  90. }
  91. if(is_null($backend)) {
  92. $backend=self::getDBBackend();
  93. }
  94. if($backend==self::BACKEND_PDO) {
  95. $success = self::connectPDO();
  96. self::$connection=self::$PDO;
  97. self::$backend=self::BACKEND_PDO;
  98. }else{
  99. $success = self::connectMDB2();
  100. self::$connection=self::$MDB2;
  101. self::$backend=self::BACKEND_MDB2;
  102. }
  103. return $success;
  104. }
  105. /**
  106. * connect to the database using pdo
  107. *
  108. * @return bool
  109. */
  110. public static function connectPDO() {
  111. if(self::$connection) {
  112. if(self::$backend==self::BACKEND_MDB2) {
  113. self::disconnect();
  114. }else{
  115. return true;
  116. }
  117. }
  118. self::$preparedQueries = array();
  119. // The global data we need
  120. $name = OC_Config::getValue( "dbname", "owncloud" );
  121. $host = OC_Config::getValue( "dbhost", "" );
  122. $user = OC_Config::getValue( "dbuser", "" );
  123. $pass = OC_Config::getValue( "dbpassword", "" );
  124. $type = OC_Config::getValue( "dbtype", "sqlite" );
  125. if(strpos($host, ':')) {
  126. list($host, $port)=explode(':', $host, 2);
  127. }else{
  128. $port=false;
  129. }
  130. $opts = array();
  131. $datadir=OC_Config::getValue( "datadirectory", OC::$SERVERROOT.'/data' );
  132. // do nothing if the connection already has been established
  133. if(!self::$PDO) {
  134. // Add the dsn according to the database type
  135. switch($type) {
  136. case 'sqlite':
  137. $dsn='sqlite2:'.$datadir.'/'.$name.'.db';
  138. break;
  139. case 'sqlite3':
  140. $dsn='sqlite:'.$datadir.'/'.$name.'.db';
  141. break;
  142. case 'mysql':
  143. if($port) {
  144. $dsn='mysql:dbname='.$name.';host='.$host.';port='.$port;
  145. }else{
  146. $dsn='mysql:dbname='.$name.';host='.$host;
  147. }
  148. $opts[PDO::MYSQL_ATTR_INIT_COMMAND] = "SET NAMES 'UTF8'";
  149. break;
  150. case 'pgsql':
  151. if($port) {
  152. $dsn='pgsql:dbname='.$name.';host='.$host.';port='.$port;
  153. }else{
  154. $dsn='pgsql:dbname='.$name.';host='.$host;
  155. }
  156. /**
  157. * Ugly fix for pg connections pbm when password use spaces
  158. */
  159. $e_user = addslashes($user);
  160. $e_password = addslashes($pass);
  161. $pass = $user = null;
  162. $dsn .= ";user='$e_user';password='$e_password'";
  163. /** END OF FIX***/
  164. break;
  165. case 'oci': // Oracle with PDO is unsupported
  166. if ($port) {
  167. $dsn = 'oci:dbname=//' . $host . ':' . $port . '/' . $name;
  168. } else {
  169. $dsn = 'oci:dbname=//' . $host . '/' . $name;
  170. }
  171. break;
  172. case 'mssql':
  173. if ($port) {
  174. $dsn='sqlsrv:Server='.$host.','.$port.';Database='.$name;
  175. } else {
  176. $dsn='sqlsrv:Server='.$host.';Database='.$name;
  177. }
  178. break;
  179. default:
  180. return false;
  181. }
  182. try{
  183. self::$PDO=new PDO($dsn, $user, $pass, $opts);
  184. }catch(PDOException $e) {
  185. OC_Log::write('core', $e->getMessage(), OC_Log::FATAL);
  186. OC_User::setUserId(null);
  187. // send http status 503
  188. header('HTTP/1.1 503 Service Temporarily Unavailable');
  189. header('Status: 503 Service Temporarily Unavailable');
  190. OC_Template::printErrorPage('Failed to connect to database');
  191. die();
  192. }
  193. // We always, really always want associative arrays
  194. self::$PDO->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
  195. self::$PDO->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  196. }
  197. return true;
  198. }
  199. /**
  200. * connect to the database using mdb2
  201. */
  202. public static function connectMDB2() {
  203. if(self::$connection) {
  204. if(self::$backend==self::BACKEND_PDO) {
  205. self::disconnect();
  206. }else{
  207. return true;
  208. }
  209. }
  210. self::$preparedQueries = array();
  211. // The global data we need
  212. $name = OC_Config::getValue( "dbname", "owncloud" );
  213. $host = OC_Config::getValue( "dbhost", "" );
  214. $user = OC_Config::getValue( "dbuser", "" );
  215. $pass = OC_Config::getValue( "dbpassword", "" );
  216. $type = OC_Config::getValue( "dbtype", "sqlite" );
  217. $SERVERROOT=OC::$SERVERROOT;
  218. $datadir=OC_Config::getValue( "datadirectory", "$SERVERROOT/data" );
  219. // do nothing if the connection already has been established
  220. if(!self::$MDB2) {
  221. // Require MDB2.php (not required in the head of the file so we only load it when needed)
  222. require_once 'MDB2.php';
  223. // Prepare options array
  224. $options = array(
  225. 'portability' => MDB2_PORTABILITY_ALL - MDB2_PORTABILITY_FIX_CASE,
  226. 'log_line_break' => '<br>',
  227. 'idxname_format' => '%s',
  228. 'debug' => true,
  229. 'quote_identifier' => true
  230. );
  231. // Add the dsn according to the database type
  232. switch($type) {
  233. case 'sqlite':
  234. case 'sqlite3':
  235. $dsn = array(
  236. 'phptype' => $type,
  237. 'database' => "$datadir/$name.db",
  238. 'mode' => '0644'
  239. );
  240. break;
  241. case 'mysql':
  242. $dsn = array(
  243. 'phptype' => 'mysql',
  244. 'username' => $user,
  245. 'password' => $pass,
  246. 'hostspec' => $host,
  247. 'database' => $name
  248. );
  249. break;
  250. case 'pgsql':
  251. $dsn = array(
  252. 'phptype' => 'pgsql',
  253. 'username' => $user,
  254. 'password' => $pass,
  255. 'hostspec' => $host,
  256. 'database' => $name
  257. );
  258. break;
  259. case 'oci':
  260. $dsn = array(
  261. 'phptype' => 'oci8',
  262. 'username' => $user,
  263. 'password' => $pass,
  264. 'service' => $name,
  265. 'hostspec' => $host,
  266. 'charset' => 'AL32UTF8',
  267. );
  268. break;
  269. case 'mssql':
  270. $dsn = array(
  271. 'phptype' => 'sqlsrv',
  272. 'username' => $user,
  273. 'password' => $pass,
  274. 'hostspec' => $host,
  275. 'database' => $name,
  276. 'charset' => 'UTF-8'
  277. );
  278. $options['portability'] = $options['portability'] - MDB2_PORTABILITY_EMPTY_TO_NULL;
  279. break;
  280. default:
  281. return false;
  282. }
  283. // Try to establish connection
  284. self::$MDB2 = MDB2::factory( $dsn, $options );
  285. // Die if we could not connect
  286. if( PEAR::isError( self::$MDB2 )) {
  287. OC_Log::write('core', self::$MDB2->getUserInfo(), OC_Log::FATAL);
  288. OC_Log::write('core', self::$MDB2->getMessage(), OC_Log::FATAL);
  289. OC_User::setUserId(null);
  290. // send http status 503
  291. header('HTTP/1.1 503 Service Temporarily Unavailable');
  292. header('Status: 503 Service Temporarily Unavailable');
  293. OC_Template::printErrorPage('Failed to connect to database');
  294. die();
  295. }
  296. // We always, really always want associative arrays
  297. self::$MDB2->setFetchMode(MDB2_FETCHMODE_ASSOC);
  298. }
  299. // we are done. great!
  300. return true;
  301. }
  302. /**
  303. * @brief Prepare a SQL query
  304. * @param string $query Query string
  305. * @param int $limit
  306. * @param int $offset
  307. * @return MDB2_Statement_Common prepared SQL query
  308. *
  309. * SQL query via MDB2 prepare(), needs to be execute()'d!
  310. */
  311. static public function prepare( $query , $limit=null, $offset=null ) {
  312. if (!is_null($limit) && $limit != -1) {
  313. if (self::$backend == self::BACKEND_MDB2) {
  314. //MDB2 uses or emulates limits & offset internally
  315. self::$MDB2->setLimit($limit, $offset);
  316. } else {
  317. //PDO does not handle limit and offset.
  318. //FIXME: check limit notation for other dbs
  319. //the following sql thus might needs to take into account db ways of representing it
  320. //(oracle has no LIMIT / OFFSET)
  321. $limit = (int)$limit;
  322. $limitsql = ' LIMIT ' . $limit;
  323. if (!is_null($offset)) {
  324. $offset = (int)$offset;
  325. $limitsql .= ' OFFSET ' . $offset;
  326. }
  327. //insert limitsql
  328. if (substr($query, -1) == ';') { //if query ends with ;
  329. $query = substr($query, 0, -1) . $limitsql . ';';
  330. } else {
  331. $query.=$limitsql;
  332. }
  333. }
  334. } else {
  335. if (isset(self::$preparedQueries[$query]) and self::$cachingEnabled) {
  336. return self::$preparedQueries[$query];
  337. }
  338. }
  339. $rawQuery = $query;
  340. // Optimize the query
  341. $query = self::processQuery( $query );
  342. if(OC_Config::getValue( "log_query", false)) {
  343. OC_Log::write('core', 'DB prepare : '.$query, OC_Log::DEBUG);
  344. }
  345. self::connect();
  346. // return the result
  347. if(self::$backend==self::BACKEND_MDB2) {
  348. $result = self::$connection->prepare( $query );
  349. // Die if we have an error (error means: bad query, not 0 results!)
  350. if( PEAR::isError($result)) {
  351. throw new DatabaseException($result->getMessage(), $query);
  352. }
  353. }else{
  354. try{
  355. $result=self::$connection->prepare($query);
  356. }catch(PDOException $e) {
  357. throw new DatabaseException($e->getMessage(), $query);
  358. }
  359. $result=new PDOStatementWrapper($result);
  360. }
  361. if ((is_null($limit) || $limit == -1) and self::$cachingEnabled ) {
  362. $type = OC_Config::getValue( "dbtype", "sqlite" );
  363. if( $type != 'sqlite' && $type != 'sqlite3' ) {
  364. self::$preparedQueries[$rawQuery] = $result;
  365. }
  366. }
  367. return $result;
  368. }
  369. /**
  370. * @brief gets last value of autoincrement
  371. * @param string $table The optional table name (will replace *PREFIX*) and add sequence suffix
  372. * @return int id
  373. *
  374. * MDB2 lastInsertID()
  375. *
  376. * Call this method right after the insert command or other functions may
  377. * cause trouble!
  378. */
  379. public static function insertid($table=null) {
  380. self::connect();
  381. $type = OC_Config::getValue( "dbtype", "sqlite" );
  382. if( $type == 'pgsql' ) {
  383. $query = self::prepare('SELECT lastval() AS id');
  384. $row = $query->execute()->fetchRow();
  385. return $row['id'];
  386. }
  387. if( $type == 'mssql' ) {
  388. if($table !== null) {
  389. $prefix = OC_Config::getValue( "dbtableprefix", "oc_" );
  390. $table = str_replace( '*PREFIX*', $prefix, $table );
  391. }
  392. return self::$connection->lastInsertId($table);
  393. }else{
  394. if($table !== null) {
  395. $prefix = OC_Config::getValue( "dbtableprefix", "oc_" );
  396. $suffix = OC_Config::getValue( "dbsequencesuffix", "_id_seq" );
  397. $table = str_replace( '*PREFIX*', $prefix, $table ).$suffix;
  398. }
  399. return self::$connection->lastInsertId($table);
  400. }
  401. }
  402. /**
  403. * @brief Disconnect
  404. * @return bool
  405. *
  406. * This is good bye, good bye, yeah!
  407. */
  408. public static function disconnect() {
  409. // Cut connection if required
  410. if(self::$connection) {
  411. if(self::$backend==self::BACKEND_MDB2) {
  412. self::$connection->disconnect();
  413. }
  414. self::$connection=false;
  415. self::$MDB2=false;
  416. self::$PDO=false;
  417. }
  418. return true;
  419. }
  420. /**
  421. * @brief saves database scheme to xml file
  422. * @param string $file name of file
  423. * @param int $mode
  424. * @return bool
  425. *
  426. * TODO: write more documentation
  427. */
  428. public static function getDbStructure( $file, $mode=MDB2_SCHEMA_DUMP_STRUCTURE) {
  429. self::connectScheme();
  430. // write the scheme
  431. $definition = self::$schema->getDefinitionFromDatabase();
  432. $dump_options = array(
  433. 'output_mode' => 'file',
  434. 'output' => $file,
  435. 'end_of_line' => "\n"
  436. );
  437. self::$schema->dumpDatabase( $definition, $dump_options, $mode );
  438. return true;
  439. }
  440. /**
  441. * @brief Creates tables from XML file
  442. * @param string $file file to read structure from
  443. * @return bool
  444. *
  445. * TODO: write more documentation
  446. */
  447. public static function createDbFromStructure( $file ) {
  448. $CONFIG_DBNAME = OC_Config::getValue( "dbname", "owncloud" );
  449. $CONFIG_DBTABLEPREFIX = OC_Config::getValue( "dbtableprefix", "oc_" );
  450. $CONFIG_DBTYPE = OC_Config::getValue( "dbtype", "sqlite" );
  451. // cleanup the cached queries
  452. self::$preparedQueries = array();
  453. self::connectScheme();
  454. // read file
  455. $content = file_get_contents( $file );
  456. // Make changes and save them to an in-memory file
  457. $file2 = 'static://db_scheme';
  458. $content = str_replace( '*dbname*', $CONFIG_DBNAME, $content );
  459. $content = str_replace( '*dbprefix*', $CONFIG_DBTABLEPREFIX, $content );
  460. /* FIXME: use CURRENT_TIMESTAMP for all databases. mysql supports it as a default for DATETIME since 5.6.5 [1]
  461. * as a fallback we could use <default>0000-01-01 00:00:00</default> everywhere
  462. * [1] http://bugs.mysql.com/bug.php?id=27645
  463. * http://dev.mysql.com/doc/refman/5.0/en/timestamp-initialization.html
  464. * http://www.postgresql.org/docs/8.1/static/functions-datetime.html
  465. * http://www.sqlite.org/lang_createtable.html
  466. * http://docs.oracle.com/cd/B19306_01/server.102/b14200/functions037.htm
  467. */
  468. if( $CONFIG_DBTYPE == 'pgsql' ) { //mysql support it too but sqlite doesn't
  469. $content = str_replace( '<default>0000-00-00 00:00:00</default>',
  470. '<default>CURRENT_TIMESTAMP</default>', $content );
  471. }
  472. file_put_contents( $file2, $content );
  473. // Try to create tables
  474. $definition = self::$schema->parseDatabaseDefinitionFile( $file2 );
  475. //clean up memory
  476. unlink( $file2 );
  477. // Die in case something went wrong
  478. if( $definition instanceof MDB2_Schema_Error ) {
  479. OC_Template::printErrorPage( $definition->getMessage().': '.$definition->getUserInfo() );
  480. }
  481. if(OC_Config::getValue('dbtype', 'sqlite')==='oci') {
  482. unset($definition['charset']); //or MDB2 tries SHUTDOWN IMMEDIATE
  483. $oldname = $definition['name'];
  484. $definition['name']=OC_Config::getValue( "dbuser", $oldname );
  485. }
  486. // we should never drop a database
  487. $definition['overwrite'] = false;
  488. $ret=self::$schema->createDatabase( $definition );
  489. // Die in case something went wrong
  490. if( $ret instanceof MDB2_Error ) {
  491. OC_Template::printErrorPage( self::$MDB2->getDebugOutput().' '.$ret->getMessage() . ': '
  492. . $ret->getUserInfo() );
  493. }
  494. return true;
  495. }
  496. /**
  497. * @brief update the database scheme
  498. * @param string $file file to read structure from
  499. * @return bool
  500. */
  501. public static function updateDbFromStructure($file) {
  502. $CONFIG_DBTABLEPREFIX = OC_Config::getValue( "dbtableprefix", "oc_" );
  503. $CONFIG_DBTYPE = OC_Config::getValue( "dbtype", "sqlite" );
  504. self::connectScheme();
  505. // read file
  506. $content = file_get_contents( $file );
  507. $previousSchema = self::$schema->getDefinitionFromDatabase();
  508. if (PEAR::isError($previousSchema)) {
  509. $error = $previousSchema->getMessage();
  510. $detail = $previousSchema->getDebugInfo();
  511. $message = 'Failed to get existing database structure for updating ('.$error.', '.$detail.')';
  512. OC_Log::write('core', $message, OC_Log::FATAL);
  513. throw new Exception($message);
  514. }
  515. // Make changes and save them to an in-memory file
  516. $file2 = 'static://db_scheme';
  517. $content = str_replace( '*dbname*', $previousSchema['name'], $content );
  518. $content = str_replace( '*dbprefix*', $CONFIG_DBTABLEPREFIX, $content );
  519. /* FIXME: use CURRENT_TIMESTAMP for all databases. mysql supports it as a default for DATETIME since 5.6.5 [1]
  520. * as a fallback we could use <default>0000-01-01 00:00:00</default> everywhere
  521. * [1] http://bugs.mysql.com/bug.php?id=27645
  522. * http://dev.mysql.com/doc/refman/5.0/en/timestamp-initialization.html
  523. * http://www.postgresql.org/docs/8.1/static/functions-datetime.html
  524. * http://www.sqlite.org/lang_createtable.html
  525. * http://docs.oracle.com/cd/B19306_01/server.102/b14200/functions037.htm
  526. */
  527. if( $CONFIG_DBTYPE == 'pgsql' ) { //mysql support it too but sqlite doesn't
  528. $content = str_replace( '<default>0000-00-00 00:00:00</default>',
  529. '<default>CURRENT_TIMESTAMP</default>', $content );
  530. }
  531. file_put_contents( $file2, $content );
  532. $op = self::$schema->updateDatabase($file2, $previousSchema, array(), false);
  533. //clean up memory
  534. unlink( $file2 );
  535. if (PEAR::isError($op)) {
  536. $error = $op->getMessage();
  537. $detail = $op->getDebugInfo();
  538. $message = 'Failed to update database structure ('.$error.', '.$detail.')';
  539. OC_Log::write('core', $message, OC_Log::FATAL);
  540. throw new Exception($message);
  541. }
  542. return true;
  543. }
  544. /**
  545. * @brief connects to a MDB2 database scheme
  546. * @returns bool
  547. *
  548. * Connects to a MDB2 database scheme
  549. */
  550. private static function connectScheme() {
  551. // We need a mdb2 database connection
  552. self::connectMDB2();
  553. self::$MDB2->loadModule('Manager');
  554. self::$MDB2->loadModule('Reverse');
  555. // Connect if this did not happen before
  556. if(!self::$schema) {
  557. require_once 'MDB2/Schema.php';
  558. self::$schema=MDB2_Schema::factory(self::$MDB2);
  559. }
  560. return true;
  561. }
  562. /**
  563. * @brief Insert a row if a matching row doesn't exists.
  564. * @param string $table. The table to insert into in the form '*PREFIX*tableName'
  565. * @param array $input. An array of fieldname/value pairs
  566. * @returns The return value from PDOStatementWrapper->execute()
  567. */
  568. public static function insertIfNotExist($table, $input) {
  569. self::connect();
  570. $prefix = OC_Config::getValue( "dbtableprefix", "oc_" );
  571. $table = str_replace( '*PREFIX*', $prefix, $table );
  572. if(is_null(self::$type)) {
  573. self::$type=OC_Config::getValue( "dbtype", "sqlite" );
  574. }
  575. $type = self::$type;
  576. $query = '';
  577. $inserts = array_values($input);
  578. // differences in escaping of table names ('`' for mysql) and getting the current timestamp
  579. if( $type == 'sqlite' || $type == 'sqlite3' ) {
  580. // NOTE: For SQLite we have to use this clumsy approach
  581. // otherwise all fieldnames used must have a unique key.
  582. $query = 'SELECT * FROM `' . $table . '` WHERE ';
  583. foreach($input as $key => $value) {
  584. $query .= '`' . $key . '` = ? AND ';
  585. }
  586. $query = substr($query, 0, strlen($query) - 5);
  587. try {
  588. $stmt = self::prepare($query);
  589. $result = $stmt->execute($inserts);
  590. } catch(PDOException $e) {
  591. $entry = 'DB Error: "'.$e->getMessage() . '"<br />';
  592. $entry .= 'Offending command was: ' . $query . '<br />';
  593. OC_Log::write('core', $entry, OC_Log::FATAL);
  594. error_log('DB error: '.$entry);
  595. OC_Template::printErrorPage( $entry );
  596. }
  597. if((int)$result->numRows() === 0) {
  598. $query = 'INSERT INTO `' . $table . '` (`'
  599. . implode('`,`', array_keys($input)) . '`) VALUES('
  600. . str_repeat('?,', count($input)-1).'? ' . ')';
  601. } else {
  602. return true;
  603. }
  604. } elseif( $type == 'pgsql' || $type == 'oci' || $type == 'mysql' || $type == 'mssql') {
  605. $query = 'INSERT INTO `' .$table . '` (`'
  606. . implode('`,`', array_keys($input)) . '`) SELECT '
  607. . str_repeat('?,', count($input)-1).'? ' // Is there a prettier alternative?
  608. . 'FROM `' . $table . '` WHERE ';
  609. foreach($input as $key => $value) {
  610. $query .= '`' . $key . '` = ? AND ';
  611. }
  612. $query = substr($query, 0, strlen($query) - 5);
  613. $query .= ' HAVING COUNT(*) = 0';
  614. $inserts = array_merge($inserts, $inserts);
  615. }
  616. try {
  617. $result = self::prepare($query);
  618. } catch(PDOException $e) {
  619. $entry = 'DB Error: "'.$e->getMessage() . '"<br />';
  620. $entry .= 'Offending command was: ' . $query.'<br />';
  621. OC_Log::write('core', $entry, OC_Log::FATAL);
  622. error_log('DB error: ' . $entry);
  623. OC_Template::printErrorPage( $entry );
  624. }
  625. return $result->execute($inserts);
  626. }
  627. /**
  628. * @brief does minor changes to query
  629. * @param string $query Query string
  630. * @return string corrected query string
  631. *
  632. * This function replaces *PREFIX* with the value of $CONFIG_DBTABLEPREFIX
  633. * and replaces the ` with ' or " according to the database driver.
  634. */
  635. private static function processQuery( $query ) {
  636. self::connect();
  637. // We need Database type and table prefix
  638. if(is_null(self::$type)) {
  639. self::$type=OC_Config::getValue( "dbtype", "sqlite" );
  640. }
  641. $type = self::$type;
  642. if(is_null(self::$prefix)) {
  643. self::$prefix=OC_Config::getValue( "dbtableprefix", "oc_" );
  644. }
  645. $prefix = self::$prefix;
  646. // differences in escaping of table names ('`' for mysql) and getting the current timestamp
  647. if( $type == 'sqlite' || $type == 'sqlite3' ) {
  648. $query = str_replace( '`', '"', $query );
  649. $query = str_ireplace( 'NOW()', 'datetime(\'now\')', $query );
  650. $query = str_ireplace( 'UNIX_TIMESTAMP()', 'strftime(\'%s\',\'now\')', $query );
  651. }elseif( $type == 'pgsql' ) {
  652. $query = str_replace( '`', '"', $query );
  653. $query = str_ireplace( 'UNIX_TIMESTAMP()', 'cast(extract(epoch from current_timestamp) as integer)',
  654. $query );
  655. }elseif( $type == 'oci' ) {
  656. $query = str_replace( '`', '"', $query );
  657. $query = str_ireplace( 'NOW()', 'CURRENT_TIMESTAMP', $query );
  658. }elseif( $type == 'mssql' ) {
  659. $query = preg_replace( "/\`(.*?)`/", "[$1]", $query );
  660. $query = str_replace( 'NOW()', 'CURRENT_TIMESTAMP', $query );
  661. $query = str_replace( 'now()', 'CURRENT_TIMESTAMP', $query );
  662. $query = str_replace( 'LENGTH(', 'LEN(', $query );
  663. $query = str_replace( 'SUBSTR(', 'SUBSTRING(', $query );
  664. $query = self::fixLimitClauseForMSSQL($query);
  665. }
  666. // replace table name prefix
  667. $query = str_replace( '*PREFIX*', $prefix, $query );
  668. return $query;
  669. }
  670. private static function fixLimitClauseForMSSQL($query) {
  671. $limitLocation = stripos ($query, "LIMIT");
  672. if ( $limitLocation === false ) {
  673. return $query;
  674. }
  675. // total == 0 means all results - not zero results
  676. //
  677. // First number is either total or offset, locate it by first space
  678. //
  679. $offset = substr ($query, $limitLocation + 5);
  680. $offset = substr ($offset, 0, stripos ($offset, ' '));
  681. $offset = trim ($offset);
  682. // check for another parameter
  683. if (stripos ($offset, ',') === false) {
  684. // no more parameters
  685. $offset = 0;
  686. $total = intval ($offset);
  687. } else {
  688. // found another parameter
  689. $offset = intval ($offset);
  690. $total = substr ($query, $limitLocation + 5);
  691. $total = substr ($total, stripos ($total, ','));
  692. $total = substr ($total, 0, stripos ($total, ' '));
  693. $total = intval ($total);
  694. }
  695. $query = trim (substr ($query, 0, $limitLocation));
  696. if ($offset == 0 && $total !== 0) {
  697. if (strpos($query, "SELECT") === false) {
  698. $query = "TOP {$total} " . $query;
  699. } else {
  700. $query = preg_replace('/SELECT(\s*DISTINCT)?/Dsi', 'SELECT$1 TOP '.$total, $query);
  701. }
  702. } else if ($offset > 0) {
  703. $query = preg_replace('/SELECT(\s*DISTINCT)?/Dsi', 'SELECT$1 TOP(10000000) ', $query);
  704. $query = 'SELECT *
  705. FROM (SELECT sub2.*, ROW_NUMBER() OVER(ORDER BY sub2.line2) AS line3
  706. FROM (SELECT 1 AS line2, sub1.* FROM (' . $query . ') AS sub1) as sub2) AS sub3';
  707. if ($total > 0) {
  708. $query .= ' WHERE line3 BETWEEN ' . ($offset + 1) . ' AND ' . ($offset + $total);
  709. } else {
  710. $query .= ' WHERE line3 > ' . $offset;
  711. }
  712. }
  713. return $query;
  714. }
  715. /**
  716. * @brief drop a table
  717. * @param string $tableName the table to drop
  718. */
  719. public static function dropTable($tableName) {
  720. self::connectMDB2();
  721. self::$MDB2->loadModule('Manager');
  722. self::$MDB2->dropTable($tableName);
  723. }
  724. /**
  725. * remove all tables defined in a database structure xml file
  726. * @param string $file the xml file describing the tables
  727. */
  728. public static function removeDBStructure($file) {
  729. $CONFIG_DBNAME = OC_Config::getValue( "dbname", "owncloud" );
  730. $CONFIG_DBTABLEPREFIX = OC_Config::getValue( "dbtableprefix", "oc_" );
  731. self::connectScheme();
  732. // read file
  733. $content = file_get_contents( $file );
  734. // Make changes and save them to a temporary file
  735. $file2 = tempnam( get_temp_dir(), 'oc_db_scheme_' );
  736. $content = str_replace( '*dbname*', $CONFIG_DBNAME, $content );
  737. $content = str_replace( '*dbprefix*', $CONFIG_DBTABLEPREFIX, $content );
  738. file_put_contents( $file2, $content );
  739. // get the tables
  740. $definition = self::$schema->parseDatabaseDefinitionFile( $file2 );
  741. // Delete our temporary file
  742. unlink( $file2 );
  743. $tables=array_keys($definition['tables']);
  744. foreach($tables as $table) {
  745. self::dropTable($table);
  746. }
  747. }
  748. /**
  749. * @brief replaces the owncloud tables with a new set
  750. * @param $file string path to the MDB2 xml db export file
  751. */
  752. public static function replaceDB( $file ) {
  753. $apps = OC_App::getAllApps();
  754. self::beginTransaction();
  755. // Delete the old tables
  756. self::removeDBStructure( OC::$SERVERROOT . '/db_structure.xml' );
  757. foreach($apps as $app) {
  758. $path = OC_App::getAppPath($app).'/appinfo/database.xml';
  759. if(file_exists($path)) {
  760. self::removeDBStructure( $path );
  761. }
  762. }
  763. // Create new tables
  764. self::createDBFromStructure( $file );
  765. self::commit();
  766. }
  767. /**
  768. * Start a transaction
  769. * @return bool
  770. */
  771. public static function beginTransaction() {
  772. self::connect();
  773. if (self::$backend==self::BACKEND_MDB2 && !self::$connection->supports('transactions')) {
  774. return false;
  775. }
  776. self::$connection->beginTransaction();
  777. self::$inTransaction=true;
  778. return true;
  779. }
  780. /**
  781. * Commit the database changes done during a transaction that is in progress
  782. * @return bool
  783. */
  784. public static function commit() {
  785. self::connect();
  786. if(!self::$inTransaction) {
  787. return false;
  788. }
  789. self::$connection->commit();
  790. self::$inTransaction=false;
  791. return true;
  792. }
  793. /**
  794. * check if a result is an error, works with MDB2 and PDOException
  795. * @param mixed $result
  796. * @return bool
  797. */
  798. public static function isError($result) {
  799. if(!$result) {
  800. return true;
  801. }elseif(self::$backend==self::BACKEND_MDB2 and PEAR::isError($result)) {
  802. return true;
  803. }else{
  804. return false;
  805. }
  806. }
  807. /**
  808. * returns the error code and message as a string for logging
  809. * works with MDB2 and PDOException
  810. * @param mixed $error
  811. * @return string
  812. */
  813. public static function getErrorMessage($error) {
  814. if ( self::$backend==self::BACKEND_MDB2 and PEAR::isError($error) ) {
  815. $msg = $error->getCode() . ': ' . $error->getMessage();
  816. if (defined('DEBUG') && DEBUG) {
  817. $msg .= '(' . $error->getDebugInfo() . ')';
  818. }
  819. } elseif (self::$backend==self::BACKEND_PDO and self::$PDO) {
  820. $msg = self::$PDO->errorCode() . ': ';
  821. $errorInfo = self::$PDO->errorInfo();
  822. if (is_array($errorInfo)) {
  823. $msg .= 'SQLSTATE = '.$errorInfo[0] . ', ';
  824. $msg .= 'Driver Code = '.$errorInfo[1] . ', ';
  825. $msg .= 'Driver Message = '.$errorInfo[2];
  826. }else{
  827. $msg = '';
  828. }
  829. }else{
  830. $msg = '';
  831. }
  832. return $msg;
  833. }
  834. /**
  835. * @param bool $enabled
  836. */
  837. static public function enableCaching($enabled) {
  838. if (!$enabled) {
  839. self::$preparedQueries = array();
  840. }
  841. self::$cachingEnabled = $enabled;
  842. }
  843. }
  844. /**
  845. * small wrapper around PDOStatement to make it behave ,more like an MDB2 Statement
  846. */
  847. class PDOStatementWrapper{
  848. /**
  849. * @var PDOStatement
  850. */
  851. private $statement=null;
  852. private $lastArguments=array();
  853. public function __construct($statement) {
  854. $this->statement=$statement;
  855. }
  856. /**
  857. * make execute return the result instead of a bool
  858. */
  859. public function execute($input=array()) {
  860. if(OC_Config::getValue( "log_query", false)) {
  861. $params_str = str_replace("\n"," ",var_export($input,true));
  862. OC_Log::write('core', 'DB execute with arguments : '.$params_str, OC_Log::DEBUG);
  863. }
  864. $this->lastArguments = $input;
  865. if (count($input) > 0) {
  866. if (!isset($type)) {
  867. $type = OC_Config::getValue( "dbtype", "sqlite" );
  868. }
  869. if ($type == 'mssql') {
  870. $input = $this->tryFixSubstringLastArgumentDataForMSSQL($input);
  871. }
  872. $result=$this->statement->execute($input);
  873. } else {
  874. $result=$this->statement->execute();
  875. }
  876. if ($result) {
  877. return $this;
  878. } else {
  879. return false;
  880. }
  881. }
  882. private function tryFixSubstringLastArgumentDataForMSSQL($input) {
  883. $query = $this->statement->queryString;
  884. $pos = stripos ($query, 'SUBSTRING');
  885. if ( $pos === false) {
  886. return;
  887. }
  888. try {
  889. $newQuery = '';
  890. $cArg = 0;
  891. $inSubstring = false;
  892. // Create new query
  893. for ($i = 0; $i < strlen ($query); $i++) {
  894. if ($inSubstring == false) {
  895. // Defines when we should start inserting values
  896. if (substr ($query, $i, 9) == 'SUBSTRING') {
  897. $inSubstring = true;
  898. }
  899. } else {
  900. // Defines when we should stop inserting values
  901. if (substr ($query, $i, 1) == ')') {
  902. $inSubstring = false;
  903. }
  904. }
  905. if (substr ($query, $i, 1) == '?') {
  906. // We found a question mark
  907. if ($inSubstring) {
  908. $newQuery .= $input[$cArg];
  909. //
  910. // Remove from input array
  911. //
  912. array_splice ($input, $cArg, 1);
  913. } else {
  914. $newQuery .= substr ($query, $i, 1);
  915. $cArg++;
  916. }
  917. } else {
  918. $newQuery .= substr ($query, $i, 1);
  919. }
  920. }
  921. // The global data we need
  922. $name = OC_Config::getValue( "dbname", "owncloud" );
  923. $host = OC_Config::getValue( "dbhost", "" );
  924. $user = OC_Config::getValue( "dbuser", "" );
  925. $pass = OC_Config::getValue( "dbpassword", "" );
  926. if (strpos($host,':')) {
  927. list($host, $port) = explode(':', $host, 2);
  928. } else {
  929. $port = false;
  930. }
  931. $opts = array();
  932. if ($port) {
  933. $dsn = 'sqlsrv:Server='.$host.','.$port.';Database='.$name;
  934. } else {
  935. $dsn = 'sqlsrv:Server='.$host.';Database='.$name;
  936. }
  937. $PDO = new PDO($dsn, $user, $pass, $opts);
  938. $PDO->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
  939. $PDO->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  940. $this->statement = $PDO->prepare($newQuery);
  941. $this->lastArguments = $input;
  942. return $input;
  943. } catch (PDOException $e){
  944. $entry = 'PDO DB Error: "'.$e->getMessage().'"<br />';
  945. $entry .= 'Offending command was: '.$this->statement->queryString .'<br />';
  946. $entry .= 'Input parameters: ' .print_r($input, true).'<br />';
  947. $entry .= 'Stack trace: ' .$e->getTraceAsString().'<br />';
  948. OC_Log::write('core', $entry, OC_Log::FATAL);
  949. OC_User::setUserId(null);
  950. // send http status 503
  951. header('HTTP/1.1 503 Service Temporarily Unavailable');
  952. header('Status: 503 Service Temporarily Unavailable');
  953. OC_Template::printErrorPage('Failed to connect to database');
  954. die ($entry);
  955. }
  956. }
  957. /**
  958. * provide numRows
  959. */
  960. public function numRows() {
  961. $regex = '/^SELECT\s+(?:ALL\s+|DISTINCT\s+)?(?:.*?)\s+FROM\s+(.*)$/i';
  962. if (preg_match($regex, $this->statement->queryString, $output) > 0) {
  963. $query = OC_DB::prepare("SELECT COUNT(*) FROM {$output[1]}");
  964. return $query->execute($this->lastArguments)->fetchColumn();
  965. }else{
  966. return $this->statement->rowCount();
  967. }
  968. }
  969. /**
  970. * provide an alias for fetch
  971. */
  972. public function fetchRow() {
  973. return $this->statement->fetch();
  974. }
  975. /**
  976. * pass all other function directly to the PDOStatement
  977. */
  978. public function __call($name, $arguments) {
  979. return call_user_func_array(array($this->statement, $name), $arguments);
  980. }
  981. /**
  982. * Provide a simple fetchOne.
  983. * fetch single column from the next row
  984. * @param int $colnum the column number to fetch
  985. */
  986. public function fetchOne($colnum = 0) {
  987. return $this->statement->fetchColumn($colnum);
  988. }
  989. }