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 32KB

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