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.

rcube_db.php 39KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389
  1. <?php
  2. /**
  3. +-----------------------------------------------------------------------+
  4. | This file is part of the Roundcube Webmail client |
  5. | Copyright (C) 2005-2012, The Roundcube Dev Team |
  6. | |
  7. | Licensed under the GNU General Public License version 3 or |
  8. | any later version with exceptions for skins & plugins. |
  9. | See the README file for a full license statement. |
  10. | |
  11. | PURPOSE: |
  12. | Database wrapper class that implements PHP PDO functions |
  13. +-----------------------------------------------------------------------+
  14. | Author: Aleksander Machniak <alec@alec.pl> |
  15. +-----------------------------------------------------------------------+
  16. */
  17. /**
  18. * Database independent query interface.
  19. * This is a wrapper for the PHP PDO.
  20. *
  21. * @package Framework
  22. * @subpackage Database
  23. */
  24. class rcube_db
  25. {
  26. public $db_provider;
  27. protected $db_dsnw; // DSN for write operations
  28. protected $db_dsnr; // DSN for read operations
  29. protected $db_connected = false; // Already connected ?
  30. protected $db_mode; // Connection mode
  31. protected $dbh; // Connection handle
  32. protected $dbhs = array();
  33. protected $table_connections = array();
  34. protected $db_error = false;
  35. protected $db_error_msg = '';
  36. protected $conn_failure = false;
  37. protected $db_index = 0;
  38. protected $last_result;
  39. protected $tables;
  40. protected $variables;
  41. protected $options = array(
  42. // column/table quotes
  43. 'identifier_start' => '"',
  44. 'identifier_end' => '"',
  45. // date/time input format
  46. 'datetime_format' => 'Y-m-d H:i:s',
  47. );
  48. const DEBUG_LINE_LENGTH = 4096;
  49. const DEFAULT_QUOTE = '`';
  50. /**
  51. * Factory, returns driver-specific instance of the class
  52. *
  53. * @param string $db_dsnw DSN for read/write operations
  54. * @param string $db_dsnr Optional DSN for read only operations
  55. * @param bool $pconn Enables persistent connections
  56. *
  57. * @return rcube_db Object instance
  58. */
  59. public static function factory($db_dsnw, $db_dsnr = '', $pconn = false)
  60. {
  61. $driver = strtolower(substr($db_dsnw, 0, strpos($db_dsnw, ':')));
  62. $driver_map = array(
  63. 'sqlite2' => 'sqlite',
  64. 'sybase' => 'mssql',
  65. 'dblib' => 'mssql',
  66. 'mysqli' => 'mysql',
  67. 'oci' => 'oracle',
  68. 'oci8' => 'oracle',
  69. );
  70. $driver = isset($driver_map[$driver]) ? $driver_map[$driver] : $driver;
  71. $class = "rcube_db_$driver";
  72. if (!$driver || !class_exists($class)) {
  73. rcube::raise_error(array('code' => 600, 'type' => 'db',
  74. 'line' => __LINE__, 'file' => __FILE__,
  75. 'message' => "Configuration error. Unsupported database driver: $driver"),
  76. true, true);
  77. }
  78. return new $class($db_dsnw, $db_dsnr, $pconn);
  79. }
  80. /**
  81. * Object constructor
  82. *
  83. * @param string $db_dsnw DSN for read/write operations
  84. * @param string $db_dsnr Optional DSN for read only operations
  85. * @param bool $pconn Enables persistent connections
  86. */
  87. public function __construct($db_dsnw, $db_dsnr = '', $pconn = false)
  88. {
  89. if (empty($db_dsnr)) {
  90. $db_dsnr = $db_dsnw;
  91. }
  92. $this->db_dsnw = $db_dsnw;
  93. $this->db_dsnr = $db_dsnr;
  94. $this->db_pconn = $pconn;
  95. $this->db_dsnw_array = self::parse_dsn($db_dsnw);
  96. $this->db_dsnr_array = self::parse_dsn($db_dsnr);
  97. $config = rcube::get_instance()->config;
  98. $this->options['table_prefix'] = $config->get('db_prefix');
  99. $this->options['dsnw_noread'] = $config->get('db_dsnw_noread', false);
  100. $this->options['table_dsn_map'] = array_map(array($this, 'table_name'), $config->get('db_table_dsn', array()));
  101. }
  102. /**
  103. * Connect to specific database
  104. *
  105. * @param array $dsn DSN for DB connections
  106. * @param string $mode Connection mode (r|w)
  107. */
  108. protected function dsn_connect($dsn, $mode)
  109. {
  110. $this->db_error = false;
  111. $this->db_error_msg = null;
  112. // return existing handle
  113. if ($this->dbhs[$mode]) {
  114. $this->dbh = $this->dbhs[$mode];
  115. $this->db_mode = $mode;
  116. return $this->dbh;
  117. }
  118. // connect to database
  119. if ($dbh = $this->conn_create($dsn)) {
  120. $this->dbh = $dbh;
  121. $this->dbhs[$mode] = $dbh;
  122. $this->db_mode = $mode;
  123. $this->db_connected = true;
  124. }
  125. }
  126. /**
  127. * Create PDO connection
  128. */
  129. protected function conn_create($dsn)
  130. {
  131. // Get database specific connection options
  132. $dsn_string = $this->dsn_string($dsn);
  133. $dsn_options = $this->dsn_options($dsn);
  134. // Connect
  135. try {
  136. // with this check we skip fatal error on PDO object creation
  137. if (!class_exists('PDO', false)) {
  138. throw new Exception('PDO extension not loaded. See http://php.net/manual/en/intro.pdo.php');
  139. }
  140. $this->conn_prepare($dsn);
  141. $dbh = new PDO($dsn_string, $dsn['username'], $dsn['password'], $dsn_options);
  142. // don't throw exceptions or warnings
  143. $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT);
  144. $this->conn_configure($dsn, $dbh);
  145. }
  146. catch (Exception $e) {
  147. $this->db_error = true;
  148. $this->db_error_msg = $e->getMessage();
  149. rcube::raise_error(array('code' => 500, 'type' => 'db',
  150. 'line' => __LINE__, 'file' => __FILE__,
  151. 'message' => $this->db_error_msg), true, false);
  152. return null;
  153. }
  154. return $dbh;
  155. }
  156. /**
  157. * Driver-specific preparation of database connection
  158. *
  159. * @param array $dsn DSN for DB connections
  160. */
  161. protected function conn_prepare($dsn)
  162. {
  163. }
  164. /**
  165. * Driver-specific configuration of database connection
  166. *
  167. * @param array $dsn DSN for DB connections
  168. * @param PDO $dbh Connection handler
  169. */
  170. protected function conn_configure($dsn, $dbh)
  171. {
  172. }
  173. /**
  174. * Connect to appropriate database depending on the operation
  175. *
  176. * @param string $mode Connection mode (r|w)
  177. * @param boolean $force Enforce using the given mode
  178. */
  179. public function db_connect($mode, $force = false)
  180. {
  181. // previous connection failed, don't attempt to connect again
  182. if ($this->conn_failure) {
  183. return;
  184. }
  185. // no replication
  186. if ($this->db_dsnw == $this->db_dsnr) {
  187. $mode = 'w';
  188. }
  189. // Already connected
  190. if ($this->db_connected) {
  191. // connected to db with the same or "higher" mode (if allowed)
  192. if ($this->db_mode == $mode || $this->db_mode == 'w' && !$force && !$this->options['dsnw_noread']) {
  193. return;
  194. }
  195. }
  196. $dsn = ($mode == 'r') ? $this->db_dsnr_array : $this->db_dsnw_array;
  197. $this->dsn_connect($dsn, $mode);
  198. // use write-master when read-only fails
  199. if (!$this->db_connected && $mode == 'r' && $this->is_replicated()) {
  200. $this->dsn_connect($this->db_dsnw_array, 'w');
  201. }
  202. $this->conn_failure = !$this->db_connected;
  203. }
  204. /**
  205. * Analyze the given SQL statement and select the appropriate connection to use
  206. */
  207. protected function dsn_select($query)
  208. {
  209. // no replication
  210. if ($this->db_dsnw == $this->db_dsnr) {
  211. return 'w';
  212. }
  213. // Read or write ?
  214. $mode = preg_match('/^(select|show|set)/i', $query) ? 'r' : 'w';
  215. $start = '[' . $this->options['identifier_start'] . self::DEFAULT_QUOTE . ']';
  216. $end = '[' . $this->options['identifier_end'] . self::DEFAULT_QUOTE . ']';
  217. $regex = '/(?:^|\s)(from|update|into|join)\s+'.$start.'?([a-z0-9._]+)'.$end.'?\s+/i';
  218. // find tables involved in this query
  219. if (preg_match_all($regex, $query, $matches, PREG_SET_ORDER)) {
  220. foreach ($matches as $m) {
  221. $table = $m[2];
  222. // always use direct mapping
  223. if ($this->options['table_dsn_map'][$table]) {
  224. $mode = $this->options['table_dsn_map'][$table];
  225. break; // primary table rules
  226. }
  227. else if ($mode == 'r') {
  228. // connected to db with the same or "higher" mode for this table
  229. $db_mode = $this->table_connections[$table];
  230. if ($db_mode == 'w' && !$this->options['dsnw_noread']) {
  231. $mode = $db_mode;
  232. }
  233. }
  234. }
  235. // remember mode chosen (for primary table)
  236. $table = $matches[0][2];
  237. $this->table_connections[$table] = $mode;
  238. }
  239. return $mode;
  240. }
  241. /**
  242. * Activate/deactivate debug mode
  243. *
  244. * @param boolean $dbg True if SQL queries should be logged
  245. */
  246. public function set_debug($dbg = true)
  247. {
  248. $this->options['debug_mode'] = $dbg;
  249. }
  250. /**
  251. * Writes debug information/query to 'sql' log file
  252. *
  253. * @param string $query SQL query
  254. */
  255. protected function debug($query)
  256. {
  257. if ($this->options['debug_mode']) {
  258. if (($len = strlen($query)) > self::DEBUG_LINE_LENGTH) {
  259. $diff = $len - self::DEBUG_LINE_LENGTH;
  260. $query = substr($query, 0, self::DEBUG_LINE_LENGTH)
  261. . "... [truncated $diff bytes]";
  262. }
  263. rcube::write_log('sql', '[' . (++$this->db_index) . '] ' . $query . ';');
  264. }
  265. }
  266. /**
  267. * Getter for error state
  268. *
  269. * @param mixed $result Optional query result
  270. *
  271. * @return string Error message
  272. */
  273. public function is_error($result = null)
  274. {
  275. if ($result !== null) {
  276. return $result === false ? $this->db_error_msg : null;
  277. }
  278. return $this->db_error ? $this->db_error_msg : null;
  279. }
  280. /**
  281. * Connection state checker
  282. *
  283. * @return boolean True if in connected state
  284. */
  285. public function is_connected()
  286. {
  287. return !is_object($this->dbh) ? false : $this->db_connected;
  288. }
  289. /**
  290. * Is database replication configured?
  291. *
  292. * @return bool Returns true if dsnw != dsnr
  293. */
  294. public function is_replicated()
  295. {
  296. return !empty($this->db_dsnr) && $this->db_dsnw != $this->db_dsnr;
  297. }
  298. /**
  299. * Get database runtime variables
  300. *
  301. * @param string $varname Variable name
  302. * @param mixed $default Default value if variable is not set
  303. *
  304. * @return mixed Variable value or default
  305. */
  306. public function get_variable($varname, $default = null)
  307. {
  308. // to be implemented by driver class
  309. return rcube::get_instance()->config->get('db_' . $varname, $default);
  310. }
  311. /**
  312. * Execute a SQL query
  313. *
  314. * @param string SQL query to execute
  315. * @param mixed Values to be inserted in query
  316. *
  317. * @return number Query handle identifier
  318. */
  319. public function query()
  320. {
  321. $params = func_get_args();
  322. $query = array_shift($params);
  323. // Support one argument of type array, instead of n arguments
  324. if (count($params) == 1 && is_array($params[0])) {
  325. $params = $params[0];
  326. }
  327. return $this->_query($query, 0, 0, $params);
  328. }
  329. /**
  330. * Execute a SQL query with limits
  331. *
  332. * @param string SQL query to execute
  333. * @param int Offset for LIMIT statement
  334. * @param int Number of rows for LIMIT statement
  335. * @param mixed Values to be inserted in query
  336. *
  337. * @return PDOStatement|bool Query handle or False on error
  338. */
  339. public function limitquery()
  340. {
  341. $params = func_get_args();
  342. $query = array_shift($params);
  343. $offset = array_shift($params);
  344. $numrows = array_shift($params);
  345. return $this->_query($query, $offset, $numrows, $params);
  346. }
  347. /**
  348. * Execute a SQL query with limits
  349. *
  350. * @param string $query SQL query to execute
  351. * @param int $offset Offset for LIMIT statement
  352. * @param int $numrows Number of rows for LIMIT statement
  353. * @param array $params Values to be inserted in query
  354. *
  355. * @return PDOStatement|bool Query handle or False on error
  356. */
  357. protected function _query($query, $offset, $numrows, $params)
  358. {
  359. $query = ltrim($query);
  360. $this->db_connect($this->dsn_select($query), true);
  361. // check connection before proceeding
  362. if (!$this->is_connected()) {
  363. return $this->last_result = false;
  364. }
  365. if ($numrows || $offset) {
  366. $query = $this->set_limit($query, $numrows, $offset);
  367. }
  368. // replace self::DEFAULT_QUOTE with driver-specific quoting
  369. $query = $this->query_parse($query);
  370. // Because in Roundcube we mostly use queries that are
  371. // executed only once, we will not use prepared queries
  372. $pos = 0;
  373. $idx = 0;
  374. if (count($params)) {
  375. while ($pos = strpos($query, '?', $pos)) {
  376. if ($query[$pos+1] == '?') { // skip escaped '?'
  377. $pos += 2;
  378. }
  379. else {
  380. $val = $this->quote($params[$idx++]);
  381. unset($params[$idx-1]);
  382. $query = substr_replace($query, $val, $pos, 1);
  383. $pos += strlen($val);
  384. }
  385. }
  386. }
  387. $query = rtrim($query, " \t\n\r\0\x0B;");
  388. // replace escaped '?' and quotes back to normal, see self::quote()
  389. $query = str_replace(
  390. array('??', self::DEFAULT_QUOTE.self::DEFAULT_QUOTE),
  391. array('?', self::DEFAULT_QUOTE),
  392. $query
  393. );
  394. // log query
  395. $this->debug($query);
  396. return $this->query_execute($query);
  397. }
  398. /**
  399. * Query execution
  400. */
  401. protected function query_execute($query)
  402. {
  403. // destroy reference to previous result, required for SQLite driver (#1488874)
  404. $this->last_result = null;
  405. $this->db_error_msg = null;
  406. // send query
  407. $result = $this->dbh->query($query);
  408. if ($result === false) {
  409. $result = $this->handle_error($query);
  410. }
  411. return $this->last_result = $result;
  412. }
  413. /**
  414. * Parse SQL query and replace identifier quoting
  415. *
  416. * @param string $query SQL query
  417. *
  418. * @return string SQL query
  419. */
  420. protected function query_parse($query)
  421. {
  422. $start = $this->options['identifier_start'];
  423. $end = $this->options['identifier_end'];
  424. $quote = self::DEFAULT_QUOTE;
  425. if ($start == $quote) {
  426. return $query;
  427. }
  428. $pos = 0;
  429. $in = false;
  430. while ($pos = strpos($query, $quote, $pos)) {
  431. if ($query[$pos+1] == $quote) { // skip escaped quote
  432. $pos += 2;
  433. }
  434. else {
  435. if ($in) {
  436. $q = $end;
  437. $in = false;
  438. }
  439. else {
  440. $q = $start;
  441. $in = true;
  442. }
  443. $query = substr_replace($query, $q, $pos, 1);
  444. $pos++;
  445. }
  446. }
  447. return $query;
  448. }
  449. /**
  450. * Helper method to handle DB errors.
  451. * This by default logs the error but could be overridden by a driver implementation
  452. *
  453. * @param string $query Query that triggered the error
  454. *
  455. * @return mixed Result to be stored and returned
  456. */
  457. protected function handle_error($query)
  458. {
  459. $error = $this->dbh->errorInfo();
  460. if (empty($this->options['ignore_key_errors']) || !in_array($error[0], array('23000', '23505'))) {
  461. $this->db_error = true;
  462. $this->db_error_msg = sprintf('[%s] %s', $error[1], $error[2]);
  463. if (empty($this->options['ignore_errors'])) {
  464. rcube::raise_error(array(
  465. 'code' => 500, 'type' => 'db', 'line' => __LINE__, 'file' => __FILE__,
  466. 'message' => $this->db_error_msg . " (SQL Query: $query)"
  467. ), true, false);
  468. }
  469. }
  470. return false;
  471. }
  472. /**
  473. * Get number of affected rows for the last query
  474. *
  475. * @param mixed $result Optional query handle
  476. *
  477. * @return int Number of (matching) rows
  478. */
  479. public function affected_rows($result = null)
  480. {
  481. if ($result || ($result === null && ($result = $this->last_result))) {
  482. if ($result !== true) {
  483. return $result->rowCount();
  484. }
  485. }
  486. return 0;
  487. }
  488. /**
  489. * Get number of rows for a SQL query
  490. * If no query handle is specified, the last query will be taken as reference
  491. *
  492. * @param mixed $result Optional query handle
  493. *
  494. * @return mixed Number of rows or false on failure
  495. * @deprecated This method shows very poor performance and should be avoided.
  496. */
  497. public function num_rows($result = null)
  498. {
  499. if (($result || ($result === null && ($result = $this->last_result))) && $result !== true) {
  500. // repeat query with SELECT COUNT(*) ...
  501. if (preg_match('/^SELECT\s+(?:ALL\s+|DISTINCT\s+)?(?:.*?)\s+FROM\s+(.*)$/ims', $result->queryString, $m)) {
  502. $query = $this->dbh->query('SELECT COUNT(*) FROM ' . $m[1], PDO::FETCH_NUM);
  503. return $query ? intval($query->fetchColumn(0)) : false;
  504. }
  505. else {
  506. $num = count($result->fetchAll());
  507. $result->execute(); // re-execute query because there's no seek(0)
  508. return $num;
  509. }
  510. }
  511. return false;
  512. }
  513. /**
  514. * Get last inserted record ID
  515. *
  516. * @param string $table Table name (to find the incremented sequence)
  517. *
  518. * @return mixed ID or false on failure
  519. */
  520. public function insert_id($table = '')
  521. {
  522. if (!$this->db_connected || $this->db_mode == 'r') {
  523. return false;
  524. }
  525. if ($table) {
  526. // resolve table name
  527. $table = $this->table_name($table);
  528. }
  529. $id = $this->dbh->lastInsertId($table);
  530. return $id;
  531. }
  532. /**
  533. * Get an associative array for one row
  534. * If no query handle is specified, the last query will be taken as reference
  535. *
  536. * @param mixed $result Optional query handle
  537. *
  538. * @return mixed Array with col values or false on failure
  539. */
  540. public function fetch_assoc($result = null)
  541. {
  542. return $this->_fetch_row($result, PDO::FETCH_ASSOC);
  543. }
  544. /**
  545. * Get an index array for one row
  546. * If no query handle is specified, the last query will be taken as reference
  547. *
  548. * @param mixed $result Optional query handle
  549. *
  550. * @return mixed Array with col values or false on failure
  551. */
  552. public function fetch_array($result = null)
  553. {
  554. return $this->_fetch_row($result, PDO::FETCH_NUM);
  555. }
  556. /**
  557. * Get col values for a result row
  558. *
  559. * @param mixed $result Optional query handle
  560. * @param int $mode Fetch mode identifier
  561. *
  562. * @return mixed Array with col values or false on failure
  563. */
  564. protected function _fetch_row($result, $mode)
  565. {
  566. if ($result || ($result === null && ($result = $this->last_result))) {
  567. if ($result !== true) {
  568. return $result->fetch($mode);
  569. }
  570. }
  571. return false;
  572. }
  573. /**
  574. * Adds LIMIT,OFFSET clauses to the query
  575. *
  576. * @param string $query SQL query
  577. * @param int $limit Number of rows
  578. * @param int $offset Offset
  579. *
  580. * @return string SQL query
  581. */
  582. protected function set_limit($query, $limit = 0, $offset = 0)
  583. {
  584. if ($limit) {
  585. $query .= ' LIMIT ' . intval($limit);
  586. }
  587. if ($offset) {
  588. $query .= ' OFFSET ' . intval($offset);
  589. }
  590. return $query;
  591. }
  592. /**
  593. * Returns list of tables in a database
  594. *
  595. * @return array List of all tables of the current database
  596. */
  597. public function list_tables()
  598. {
  599. // get tables if not cached
  600. if ($this->tables === null) {
  601. $q = $this->query("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES"
  602. . " WHERE TABLE_TYPE = 'BASE TABLE'"
  603. . " ORDER BY TABLE_NAME");
  604. $this->tables = $q ? $q->fetchAll(PDO::FETCH_COLUMN, 0) : array();
  605. }
  606. return $this->tables;
  607. }
  608. /**
  609. * Returns list of columns in database table
  610. *
  611. * @param string $table Table name
  612. *
  613. * @return array List of table cols
  614. */
  615. public function list_cols($table)
  616. {
  617. $q = $this->query('SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ?',
  618. array($table));
  619. if ($q) {
  620. return $q->fetchAll(PDO::FETCH_COLUMN, 0);
  621. }
  622. return array();
  623. }
  624. /**
  625. * Start transaction
  626. *
  627. * @return bool True on success, False on failure
  628. */
  629. public function startTransaction()
  630. {
  631. $this->db_connect('w', true);
  632. // check connection before proceeding
  633. if (!$this->is_connected()) {
  634. return $this->last_result = false;
  635. }
  636. $this->debug('BEGIN TRANSACTION');
  637. return $this->last_result = $this->dbh->beginTransaction();
  638. }
  639. /**
  640. * Commit transaction
  641. *
  642. * @return bool True on success, False on failure
  643. */
  644. public function endTransaction()
  645. {
  646. $this->db_connect('w', true);
  647. // check connection before proceeding
  648. if (!$this->is_connected()) {
  649. return $this->last_result = false;
  650. }
  651. $this->debug('COMMIT TRANSACTION');
  652. return $this->last_result = $this->dbh->commit();
  653. }
  654. /**
  655. * Rollback transaction
  656. *
  657. * @return bool True on success, False on failure
  658. */
  659. public function rollbackTransaction()
  660. {
  661. $this->db_connect('w', true);
  662. // check connection before proceeding
  663. if (!$this->is_connected()) {
  664. return $this->last_result = false;
  665. }
  666. $this->debug('ROLLBACK TRANSACTION');
  667. return $this->last_result = $this->dbh->rollBack();
  668. }
  669. /**
  670. * Release resources related to the last query result.
  671. * When we know we don't need to access the last query result we can destroy it
  672. * and release memory. Useful especially if the query returned big chunk of data.
  673. */
  674. public function reset()
  675. {
  676. $this->last_result = null;
  677. }
  678. /**
  679. * Terminate database connection.
  680. */
  681. public function closeConnection()
  682. {
  683. $this->db_connected = false;
  684. $this->db_index = 0;
  685. // release statement and connection resources
  686. $this->last_result = null;
  687. $this->dbh = null;
  688. $this->dbhs = array();
  689. }
  690. /**
  691. * Formats input so it can be safely used in a query
  692. *
  693. * @param mixed $input Value to quote
  694. * @param string $type Type of data (integer, bool, ident)
  695. *
  696. * @return string Quoted/converted string for use in query
  697. */
  698. public function quote($input, $type = null)
  699. {
  700. // handle int directly for better performance
  701. if ($type == 'integer' || $type == 'int') {
  702. return intval($input);
  703. }
  704. if (is_null($input)) {
  705. return 'NULL';
  706. }
  707. if ($input instanceof DateTime) {
  708. return $this->quote($input->format($this->options['datetime_format']));
  709. }
  710. if ($type == 'ident') {
  711. return $this->quote_identifier($input);
  712. }
  713. // create DB handle if not available
  714. if (!$this->dbh) {
  715. $this->db_connect('r');
  716. }
  717. if ($this->dbh) {
  718. $map = array(
  719. 'bool' => PDO::PARAM_BOOL,
  720. 'integer' => PDO::PARAM_INT,
  721. );
  722. $type = isset($map[$type]) ? $map[$type] : PDO::PARAM_STR;
  723. return strtr($this->dbh->quote($input, $type),
  724. // escape ? and `
  725. array('?' => '??', self::DEFAULT_QUOTE => self::DEFAULT_QUOTE.self::DEFAULT_QUOTE)
  726. );
  727. }
  728. return 'NULL';
  729. }
  730. /**
  731. * Escapes a string so it can be safely used in a query
  732. *
  733. * @param string $str A string to escape
  734. *
  735. * @return string Escaped string for use in a query
  736. */
  737. public function escape($str)
  738. {
  739. if (is_null($str)) {
  740. return 'NULL';
  741. }
  742. return substr($this->quote($str), 1, -1);
  743. }
  744. /**
  745. * Quotes a string so it can be safely used as a table or column name
  746. *
  747. * @param string $str Value to quote
  748. *
  749. * @return string Quoted string for use in query
  750. * @deprecated Replaced by rcube_db::quote_identifier
  751. * @see rcube_db::quote_identifier
  752. */
  753. public function quoteIdentifier($str)
  754. {
  755. return $this->quote_identifier($str);
  756. }
  757. /**
  758. * Escapes a string so it can be safely used in a query
  759. *
  760. * @param string $str A string to escape
  761. *
  762. * @return string Escaped string for use in a query
  763. * @deprecated Replaced by rcube_db::escape
  764. * @see rcube_db::escape
  765. */
  766. public function escapeSimple($str)
  767. {
  768. return $this->escape($str);
  769. }
  770. /**
  771. * Quotes a string so it can be safely used as a table or column name
  772. *
  773. * @param string $str Value to quote
  774. *
  775. * @return string Quoted string for use in query
  776. */
  777. public function quote_identifier($str)
  778. {
  779. $start = $this->options['identifier_start'];
  780. $end = $this->options['identifier_end'];
  781. $name = array();
  782. foreach (explode('.', $str) as $elem) {
  783. $elem = str_replace(array($start, $end), '', $elem);
  784. $name[] = $start . $elem . $end;
  785. }
  786. return implode($name, '.');
  787. }
  788. /**
  789. * Return SQL function for current time and date
  790. *
  791. * @param int $interval Optional interval (in seconds) to add/subtract
  792. *
  793. * @return string SQL function to use in query
  794. */
  795. public function now($interval = 0)
  796. {
  797. if ($interval) {
  798. $add = ' ' . ($interval > 0 ? '+' : '-') . ' INTERVAL ';
  799. $add .= $interval > 0 ? intval($interval) : intval($interval) * -1;
  800. $add .= ' SECOND';
  801. }
  802. return "now()" . $add;
  803. }
  804. /**
  805. * Return list of elements for use with SQL's IN clause
  806. *
  807. * @param array $arr Input array
  808. * @param string $type Type of data (integer, bool, ident)
  809. *
  810. * @return string Comma-separated list of quoted values for use in query
  811. */
  812. public function array2list($arr, $type = null)
  813. {
  814. if (!is_array($arr)) {
  815. return $this->quote($arr, $type);
  816. }
  817. foreach ($arr as $idx => $item) {
  818. $arr[$idx] = $this->quote($item, $type);
  819. }
  820. return implode(',', $arr);
  821. }
  822. /**
  823. * Return SQL statement to convert a field value into a unix timestamp
  824. *
  825. * This method is deprecated and should not be used anymore due to limitations
  826. * of timestamp functions in Mysql (year 2038 problem)
  827. *
  828. * @param string $field Field name
  829. *
  830. * @return string SQL statement to use in query
  831. * @deprecated
  832. */
  833. public function unixtimestamp($field)
  834. {
  835. return "UNIX_TIMESTAMP($field)";
  836. }
  837. /**
  838. * Return SQL statement to convert from a unix timestamp
  839. *
  840. * @param int $timestamp Unix timestamp
  841. *
  842. * @return string Date string in db-specific format
  843. * @deprecated
  844. */
  845. public function fromunixtime($timestamp)
  846. {
  847. return $this->quote(date($this->options['datetime_format'], $timestamp));
  848. }
  849. /**
  850. * Return SQL statement for case insensitive LIKE
  851. *
  852. * @param string $column Field name
  853. * @param string $value Search value
  854. *
  855. * @return string SQL statement to use in query
  856. */
  857. public function ilike($column, $value)
  858. {
  859. return $this->quote_identifier($column).' LIKE '.$this->quote($value);
  860. }
  861. /**
  862. * Abstract SQL statement for value concatenation
  863. *
  864. * @return string SQL statement to be used in query
  865. */
  866. public function concat(/* col1, col2, ... */)
  867. {
  868. $args = func_get_args();
  869. if (is_array($args[0])) {
  870. $args = $args[0];
  871. }
  872. return '(' . join(' || ', $args) . ')';
  873. }
  874. /**
  875. * Encodes non-UTF-8 characters in string/array/object (recursive)
  876. *
  877. * @param mixed $input Data to fix
  878. * @param bool $serialized Enable serialization
  879. *
  880. * @return mixed Properly UTF-8 encoded data
  881. */
  882. public static function encode($input, $serialized = false)
  883. {
  884. // use Base64 encoding to workaround issues with invalid
  885. // or null characters in serialized string (#1489142)
  886. if ($serialized) {
  887. return base64_encode(serialize($input));
  888. }
  889. if (is_object($input)) {
  890. foreach (get_object_vars($input) as $idx => $value) {
  891. $input->$idx = self::encode($value);
  892. }
  893. return $input;
  894. }
  895. else if (is_array($input)) {
  896. foreach ($input as $idx => $value) {
  897. $input[$idx] = self::encode($value);
  898. }
  899. return $input;
  900. }
  901. return utf8_encode($input);
  902. }
  903. /**
  904. * Decodes encoded UTF-8 string/object/array (recursive)
  905. *
  906. * @param mixed $input Input data
  907. * @param bool $serialized Enable serialization
  908. *
  909. * @return mixed Decoded data
  910. */
  911. public static function decode($input, $serialized = false)
  912. {
  913. // use Base64 encoding to workaround issues with invalid
  914. // or null characters in serialized string (#1489142)
  915. if ($serialized) {
  916. // Keep backward compatybility where base64 wasn't used
  917. if (strpos(substr($input, 0, 16), ':') !== false) {
  918. return self::decode(@unserialize($input));
  919. }
  920. return @unserialize(base64_decode($input));
  921. }
  922. if (is_object($input)) {
  923. foreach (get_object_vars($input) as $idx => $value) {
  924. $input->$idx = self::decode($value);
  925. }
  926. return $input;
  927. }
  928. else if (is_array($input)) {
  929. foreach ($input as $idx => $value) {
  930. $input[$idx] = self::decode($value);
  931. }
  932. return $input;
  933. }
  934. return utf8_decode($input);
  935. }
  936. /**
  937. * Return correct name for a specific database table
  938. *
  939. * @param string $table Table name
  940. * @param bool $quoted Quote table identifier
  941. *
  942. * @return string Translated table name
  943. */
  944. public function table_name($table, $quoted = false)
  945. {
  946. // let plugins alter the table name (#1489837)
  947. $plugin = rcube::get_instance()->plugins->exec_hook('db_table_name', array('table' => $table));
  948. $table = $plugin['table'];
  949. // add prefix to the table name if configured
  950. if (($prefix = $this->options['table_prefix']) && strpos($table, $prefix) !== 0) {
  951. $table = $prefix . $table;
  952. }
  953. if ($quoted) {
  954. $table = $this->quote_identifier($table);
  955. }
  956. return $table;
  957. }
  958. /**
  959. * Set class option value
  960. *
  961. * @param string $name Option name
  962. * @param mixed $value Option value
  963. */
  964. public function set_option($name, $value)
  965. {
  966. $this->options[$name] = $value;
  967. }
  968. /**
  969. * Set DSN connection to be used for the given table
  970. *
  971. * @param string $table Table name
  972. * @param string $mode DSN connection ('r' or 'w') to be used
  973. */
  974. public function set_table_dsn($table, $mode)
  975. {
  976. $this->options['table_dsn_map'][$this->table_name($table)] = $mode;
  977. }
  978. /**
  979. * MDB2 DSN string parser
  980. *
  981. * @param string $sequence Secuence name
  982. *
  983. * @return array DSN parameters
  984. */
  985. public static function parse_dsn($dsn)
  986. {
  987. if (empty($dsn)) {
  988. return null;
  989. }
  990. // Find phptype and dbsyntax
  991. if (($pos = strpos($dsn, '://')) !== false) {
  992. $str = substr($dsn, 0, $pos);
  993. $dsn = substr($dsn, $pos + 3);
  994. }
  995. else {
  996. $str = $dsn;
  997. $dsn = null;
  998. }
  999. // Get phptype and dbsyntax
  1000. // $str => phptype(dbsyntax)
  1001. if (preg_match('|^(.+?)\((.*?)\)$|', $str, $arr)) {
  1002. $parsed['phptype'] = $arr[1];
  1003. $parsed['dbsyntax'] = !$arr[2] ? $arr[1] : $arr[2];
  1004. }
  1005. else {
  1006. $parsed['phptype'] = $str;
  1007. $parsed['dbsyntax'] = $str;
  1008. }
  1009. if (empty($dsn)) {
  1010. return $parsed;
  1011. }
  1012. // Get (if found): username and password
  1013. // $dsn => username:password@protocol+hostspec/database
  1014. if (($at = strrpos($dsn,'@')) !== false) {
  1015. $str = substr($dsn, 0, $at);
  1016. $dsn = substr($dsn, $at + 1);
  1017. if (($pos = strpos($str, ':')) !== false) {
  1018. $parsed['username'] = rawurldecode(substr($str, 0, $pos));
  1019. $parsed['password'] = rawurldecode(substr($str, $pos + 1));
  1020. }
  1021. else {
  1022. $parsed['username'] = rawurldecode($str);
  1023. }
  1024. }
  1025. // Find protocol and hostspec
  1026. // $dsn => proto(proto_opts)/database
  1027. if (preg_match('|^([^(]+)\((.*?)\)/?(.*?)$|', $dsn, $match)) {
  1028. $proto = $match[1];
  1029. $proto_opts = $match[2] ? $match[2] : false;
  1030. $dsn = $match[3];
  1031. }
  1032. // $dsn => protocol+hostspec/database (old format)
  1033. else {
  1034. if (strpos($dsn, '+') !== false) {
  1035. list($proto, $dsn) = explode('+', $dsn, 2);
  1036. }
  1037. if ( strpos($dsn, '//') === 0
  1038. && strpos($dsn, '/', 2) !== false
  1039. && $parsed['phptype'] == 'oci8'
  1040. ) {
  1041. //oracle's "Easy Connect" syntax:
  1042. //"username/password@[//]host[:port][/service_name]"
  1043. //e.g. "scott/tiger@//mymachine:1521/oracle"
  1044. $proto_opts = $dsn;
  1045. $pos = strrpos($proto_opts, '/');
  1046. $dsn = substr($proto_opts, $pos + 1);
  1047. $proto_opts = substr($proto_opts, 0, $pos);
  1048. }
  1049. else if (strpos($dsn, '/') !== false) {
  1050. list($proto_opts, $dsn) = explode('/', $dsn, 2);
  1051. }
  1052. else {
  1053. $proto_opts = $dsn;
  1054. $dsn = null;
  1055. }
  1056. }
  1057. // process the different protocol options
  1058. $parsed['protocol'] = $proto ?: 'tcp';
  1059. $proto_opts = rawurldecode($proto_opts);
  1060. if (strpos($proto_opts, ':') !== false) {
  1061. list($proto_opts, $parsed['port']) = explode(':', $proto_opts);
  1062. }
  1063. if ($parsed['protocol'] == 'tcp') {
  1064. $parsed['hostspec'] = $proto_opts;
  1065. }
  1066. else if ($parsed['protocol'] == 'unix') {
  1067. $parsed['socket'] = $proto_opts;
  1068. }
  1069. // Get dabase if any
  1070. // $dsn => database
  1071. if ($dsn) {
  1072. // /database
  1073. if (($pos = strpos($dsn, '?')) === false) {
  1074. $parsed['database'] = rawurldecode($dsn);
  1075. // /database?param1=value1&param2=value2
  1076. }
  1077. else {
  1078. $parsed['database'] = rawurldecode(substr($dsn, 0, $pos));
  1079. $dsn = substr($dsn, $pos + 1);
  1080. if (strpos($dsn, '&') !== false) {
  1081. $opts = explode('&', $dsn);
  1082. }
  1083. else { // database?param1=value1
  1084. $opts = array($dsn);
  1085. }
  1086. foreach ($opts as $opt) {
  1087. list($key, $value) = explode('=', $opt);
  1088. if (!array_key_exists($key, $parsed) || false === $parsed[$key]) {
  1089. // don't allow params overwrite
  1090. $parsed[$key] = rawurldecode($value);
  1091. }
  1092. }
  1093. }
  1094. }
  1095. return $parsed;
  1096. }
  1097. /**
  1098. * Returns PDO DSN string from DSN array
  1099. *
  1100. * @param array $dsn DSN parameters
  1101. *
  1102. * @return string DSN string
  1103. */
  1104. protected function dsn_string($dsn)
  1105. {
  1106. $params = array();
  1107. $result = $dsn['phptype'] . ':';
  1108. if ($dsn['hostspec']) {
  1109. $params[] = 'host=' . $dsn['hostspec'];
  1110. }
  1111. if ($dsn['port']) {
  1112. $params[] = 'port=' . $dsn['port'];
  1113. }
  1114. if ($dsn['database']) {
  1115. $params[] = 'dbname=' . $dsn['database'];
  1116. }
  1117. if (!empty($params)) {
  1118. $result .= implode(';', $params);
  1119. }
  1120. return $result;
  1121. }
  1122. /**
  1123. * Returns driver-specific connection options
  1124. *
  1125. * @param array $dsn DSN parameters
  1126. *
  1127. * @return array Connection options
  1128. */
  1129. protected function dsn_options($dsn)
  1130. {
  1131. $result = array();
  1132. if ($this->db_pconn) {
  1133. $result[PDO::ATTR_PERSISTENT] = true;
  1134. }
  1135. if (!empty($dsn['prefetch'])) {
  1136. $result[PDO::ATTR_PREFETCH] = (int) $dsn['prefetch'];
  1137. }
  1138. if (!empty($dsn['timeout'])) {
  1139. $result[PDO::ATTR_TIMEOUT] = (int) $dsn['timeout'];
  1140. }
  1141. return $result;
  1142. }
  1143. /**
  1144. * Execute the given SQL script
  1145. *
  1146. * @param string $sql SQL queries to execute
  1147. *
  1148. * @return boolen True on success, False on error
  1149. */
  1150. public function exec_script($sql)
  1151. {
  1152. $sql = $this->fix_table_names($sql);
  1153. $buff = '';
  1154. $exec = '';
  1155. foreach (explode("\n", $sql) as $line) {
  1156. $trimmed = trim($line);
  1157. if ($trimmed == '' || preg_match('/^--/', $trimmed)) {
  1158. continue;
  1159. }
  1160. if ($trimmed == 'GO') {
  1161. $exec = $buff;
  1162. }
  1163. else if ($trimmed[strlen($trimmed)-1] == ';') {
  1164. $exec = $buff . substr(rtrim($line), 0, -1);
  1165. }
  1166. if ($exec) {
  1167. $this->query($exec);
  1168. $buff = '';
  1169. $exec = '';
  1170. if ($this->db_error) {
  1171. break;
  1172. }
  1173. }
  1174. else {
  1175. $buff .= $line . "\n";
  1176. }
  1177. }
  1178. return !$this->db_error;
  1179. }
  1180. /**
  1181. * Parse SQL file and fix table names according to table prefix
  1182. */
  1183. protected function fix_table_names($sql)
  1184. {
  1185. if (!$this->options['table_prefix']) {
  1186. return $sql;
  1187. }
  1188. $sql = preg_replace_callback(
  1189. '/((TABLE|TRUNCATE|(?<!ON )UPDATE|INSERT INTO|FROM'
  1190. . '| ON(?! (DELETE|UPDATE))|REFERENCES|CONSTRAINT|FOREIGN KEY|INDEX)'
  1191. . '\s+(IF (NOT )?EXISTS )?[`"]*)([^`"\( \r\n]+)/',
  1192. array($this, 'fix_table_names_callback'),
  1193. $sql
  1194. );
  1195. return $sql;
  1196. }
  1197. /**
  1198. * Preg_replace callback for fix_table_names()
  1199. */
  1200. protected function fix_table_names_callback($matches)
  1201. {
  1202. return $matches[1] . $this->options['table_prefix'] . $matches[count($matches)-1];
  1203. }
  1204. }