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

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