rcube_db.php 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367
  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 Query that triggered the error
  452. *
  453. * @return mixed Result to be stored and returned
  454. */
  455. protected function handle_error($query)
  456. {
  457. $error = $this->dbh->errorInfo();
  458. if (empty($this->options['ignore_key_errors']) || !in_array($error[0], array('23000', '23505'))) {
  459. $this->db_error = true;
  460. $this->db_error_msg = sprintf('[%s] %s', $error[1], $error[2]);
  461. rcube::raise_error(array('code' => 500, 'type' => 'db',
  462. 'line' => __LINE__, 'file' => __FILE__,
  463. 'message' => $this->db_error_msg . " (SQL Query: $query)"
  464. ), true, false);
  465. }
  466. return false;
  467. }
  468. /**
  469. * Get number of affected rows for the last query
  470. *
  471. * @param mixed $result Optional query handle
  472. *
  473. * @return int Number of (matching) rows
  474. */
  475. public function affected_rows($result = null)
  476. {
  477. if ($result || ($result === null && ($result = $this->last_result))) {
  478. if ($result !== true) {
  479. return $result->rowCount();
  480. }
  481. }
  482. return 0;
  483. }
  484. /**
  485. * Get number of rows for a SQL query
  486. * If no query handle is specified, the last query will be taken as reference
  487. *
  488. * @param mixed $result Optional query handle
  489. *
  490. * @return mixed Number of rows or false on failure
  491. * @deprecated This method shows very poor performance and should be avoided.
  492. */
  493. public function num_rows($result = null)
  494. {
  495. if (($result || ($result === null && ($result = $this->last_result))) && $result !== true) {
  496. // repeat query with SELECT COUNT(*) ...
  497. if (preg_match('/^SELECT\s+(?:ALL\s+|DISTINCT\s+)?(?:.*?)\s+FROM\s+(.*)$/ims', $result->queryString, $m)) {
  498. $query = $this->dbh->query('SELECT COUNT(*) FROM ' . $m[1], PDO::FETCH_NUM);
  499. return $query ? intval($query->fetchColumn(0)) : false;
  500. }
  501. else {
  502. $num = count($result->fetchAll());
  503. $result->execute(); // re-execute query because there's no seek(0)
  504. return $num;
  505. }
  506. }
  507. return false;
  508. }
  509. /**
  510. * Get last inserted record ID
  511. *
  512. * @param string $table Table name (to find the incremented sequence)
  513. *
  514. * @return mixed ID or false on failure
  515. */
  516. public function insert_id($table = '')
  517. {
  518. if (!$this->db_connected || $this->db_mode == 'r') {
  519. return false;
  520. }
  521. if ($table) {
  522. // resolve table name
  523. $table = $this->table_name($table);
  524. }
  525. $id = $this->dbh->lastInsertId($table);
  526. return $id;
  527. }
  528. /**
  529. * Get an associative array for one row
  530. * If no query handle is specified, the last query will be taken as reference
  531. *
  532. * @param mixed $result Optional query handle
  533. *
  534. * @return mixed Array with col values or false on failure
  535. */
  536. public function fetch_assoc($result = null)
  537. {
  538. return $this->_fetch_row($result, PDO::FETCH_ASSOC);
  539. }
  540. /**
  541. * Get an index array for one row
  542. * If no query handle is specified, the last query will be taken as reference
  543. *
  544. * @param mixed $result Optional query handle
  545. *
  546. * @return mixed Array with col values or false on failure
  547. */
  548. public function fetch_array($result = null)
  549. {
  550. return $this->_fetch_row($result, PDO::FETCH_NUM);
  551. }
  552. /**
  553. * Get col values for a result row
  554. *
  555. * @param mixed $result Optional query handle
  556. * @param int $mode Fetch mode identifier
  557. *
  558. * @return mixed Array with col values or false on failure
  559. */
  560. protected function _fetch_row($result, $mode)
  561. {
  562. if ($result || ($result === null && ($result = $this->last_result))) {
  563. if ($result !== true) {
  564. return $result->fetch($mode);
  565. }
  566. }
  567. return false;
  568. }
  569. /**
  570. * Adds LIMIT,OFFSET clauses to the query
  571. *
  572. * @param string $query SQL query
  573. * @param int $limit Number of rows
  574. * @param int $offset Offset
  575. *
  576. * @return string SQL query
  577. */
  578. protected function set_limit($query, $limit = 0, $offset = 0)
  579. {
  580. if ($limit) {
  581. $query .= ' LIMIT ' . intval($limit);
  582. }
  583. if ($offset) {
  584. $query .= ' OFFSET ' . intval($offset);
  585. }
  586. return $query;
  587. }
  588. /**
  589. * Returns list of tables in a database
  590. *
  591. * @return array List of all tables of the current database
  592. */
  593. public function list_tables()
  594. {
  595. // get tables if not cached
  596. if ($this->tables === null) {
  597. $q = $this->query("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES"
  598. . " WHERE TABLE_TYPE = 'BASE TABLE'"
  599. . " ORDER BY TABLE_NAME");
  600. $this->tables = $q ? $q->fetchAll(PDO::FETCH_COLUMN, 0) : array();
  601. }
  602. return $this->tables;
  603. }
  604. /**
  605. * Returns list of columns in database table
  606. *
  607. * @param string $table Table name
  608. *
  609. * @return array List of table cols
  610. */
  611. public function list_cols($table)
  612. {
  613. $q = $this->query('SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ?',
  614. array($table));
  615. if ($q) {
  616. return $q->fetchAll(PDO::FETCH_COLUMN, 0);
  617. }
  618. return array();
  619. }
  620. /**
  621. * Start transaction
  622. *
  623. * @return bool True on success, False on failure
  624. */
  625. public function startTransaction()
  626. {
  627. $this->db_connect('w', true);
  628. // check connection before proceeding
  629. if (!$this->is_connected()) {
  630. return $this->last_result = false;
  631. }
  632. $this->debug('BEGIN TRANSACTION');
  633. return $this->last_result = $this->dbh->beginTransaction();
  634. }
  635. /**
  636. * Commit transaction
  637. *
  638. * @return bool True on success, False on failure
  639. */
  640. public function endTransaction()
  641. {
  642. $this->db_connect('w', true);
  643. // check connection before proceeding
  644. if (!$this->is_connected()) {
  645. return $this->last_result = false;
  646. }
  647. $this->debug('COMMIT TRANSACTION');
  648. return $this->last_result = $this->dbh->commit();
  649. }
  650. /**
  651. * Rollback transaction
  652. *
  653. * @return bool True on success, False on failure
  654. */
  655. public function rollbackTransaction()
  656. {
  657. $this->db_connect('w', true);
  658. // check connection before proceeding
  659. if (!$this->is_connected()) {
  660. return $this->last_result = false;
  661. }
  662. $this->debug('ROLLBACK TRANSACTION');
  663. return $this->last_result = $this->dbh->rollBack();
  664. }
  665. /**
  666. * Release resources related to the last query result.
  667. * When we know we don't need to access the last query result we can destroy it
  668. * and release memory. Usefull especially if the query returned big chunk of data.
  669. */
  670. public function reset()
  671. {
  672. $this->last_result = null;
  673. }
  674. /**
  675. * Terminate database connection.
  676. */
  677. public function closeConnection()
  678. {
  679. $this->db_connected = false;
  680. $this->db_index = 0;
  681. // release statement and connection resources
  682. $this->last_result = null;
  683. $this->dbh = null;
  684. $this->dbhs = array();
  685. }
  686. /**
  687. * Formats input so it can be safely used in a query
  688. *
  689. * @param mixed $input Value to quote
  690. * @param string $type Type of data (integer, bool, ident)
  691. *
  692. * @return string Quoted/converted string for use in query
  693. */
  694. public function quote($input, $type = null)
  695. {
  696. // handle int directly for better performance
  697. if ($type == 'integer' || $type == 'int') {
  698. return intval($input);
  699. }
  700. if (is_null($input)) {
  701. return 'NULL';
  702. }
  703. if ($type == 'ident') {
  704. return $this->quote_identifier($input);
  705. }
  706. // create DB handle if not available
  707. if (!$this->dbh) {
  708. $this->db_connect('r');
  709. }
  710. if ($this->dbh) {
  711. $map = array(
  712. 'bool' => PDO::PARAM_BOOL,
  713. 'integer' => PDO::PARAM_INT,
  714. );
  715. $type = isset($map[$type]) ? $map[$type] : PDO::PARAM_STR;
  716. return strtr($this->dbh->quote($input, $type),
  717. // escape ? and `
  718. array('?' => '??', self::DEFAULT_QUOTE => self::DEFAULT_QUOTE.self::DEFAULT_QUOTE)
  719. );
  720. }
  721. return 'NULL';
  722. }
  723. /**
  724. * Escapes a string so it can be safely used in a query
  725. *
  726. * @param string $str A string to escape
  727. *
  728. * @return string Escaped string for use in a query
  729. */
  730. public function escape($str)
  731. {
  732. if (is_null($str)) {
  733. return 'NULL';
  734. }
  735. return substr($this->quote($str), 1, -1);
  736. }
  737. /**
  738. * Quotes a string so it can be safely used as a table or column name
  739. *
  740. * @param string $str Value to quote
  741. *
  742. * @return string Quoted string for use in query
  743. * @deprecated Replaced by rcube_db::quote_identifier
  744. * @see rcube_db::quote_identifier
  745. */
  746. public function quoteIdentifier($str)
  747. {
  748. return $this->quote_identifier($str);
  749. }
  750. /**
  751. * Escapes a string so it can be safely used in a query
  752. *
  753. * @param string $str A string to escape
  754. *
  755. * @return string Escaped string for use in a query
  756. * @deprecated Replaced by rcube_db::escape
  757. * @see rcube_db::escape
  758. */
  759. public function escapeSimple($str)
  760. {
  761. return $this->escape($str);
  762. }
  763. /**
  764. * Quotes a string so it can be safely used as a table or column name
  765. *
  766. * @param string $str Value to quote
  767. *
  768. * @return string Quoted string for use in query
  769. */
  770. public function quote_identifier($str)
  771. {
  772. $start = $this->options['identifier_start'];
  773. $end = $this->options['identifier_end'];
  774. $name = array();
  775. foreach (explode('.', $str) as $elem) {
  776. $elem = str_replace(array($start, $end), '', $elem);
  777. $name[] = $start . $elem . $end;
  778. }
  779. return implode($name, '.');
  780. }
  781. /**
  782. * Return SQL function for current time and date
  783. *
  784. * @param int $interval Optional interval (in seconds) to add/subtract
  785. *
  786. * @return string SQL function to use in query
  787. */
  788. public function now($interval = 0)
  789. {
  790. if ($interval) {
  791. $add = ' ' . ($interval > 0 ? '+' : '-') . ' INTERVAL ';
  792. $add .= $interval > 0 ? intval($interval) : intval($interval) * -1;
  793. $add .= ' SECOND';
  794. }
  795. return "now()" . $add;
  796. }
  797. /**
  798. * Return list of elements for use with SQL's IN clause
  799. *
  800. * @param array $arr Input array
  801. * @param string $type Type of data (integer, bool, ident)
  802. *
  803. * @return string Comma-separated list of quoted values for use in query
  804. */
  805. public function array2list($arr, $type = null)
  806. {
  807. if (!is_array($arr)) {
  808. return $this->quote($arr, $type);
  809. }
  810. foreach ($arr as $idx => $item) {
  811. $arr[$idx] = $this->quote($item, $type);
  812. }
  813. return implode(',', $arr);
  814. }
  815. /**
  816. * Return SQL statement to convert a field value into a unix timestamp
  817. *
  818. * This method is deprecated and should not be used anymore due to limitations
  819. * of timestamp functions in Mysql (year 2038 problem)
  820. *
  821. * @param string $field Field name
  822. *
  823. * @return string SQL statement to use in query
  824. * @deprecated
  825. */
  826. public function unixtimestamp($field)
  827. {
  828. return "UNIX_TIMESTAMP($field)";
  829. }
  830. /**
  831. * Return SQL statement to convert from a unix timestamp
  832. *
  833. * @param int $timestamp Unix timestamp
  834. *
  835. * @return string Date string in db-specific format
  836. */
  837. public function fromunixtime($timestamp)
  838. {
  839. return date("'Y-m-d H:i:s'", $timestamp);
  840. }
  841. /**
  842. * Return SQL statement for case insensitive LIKE
  843. *
  844. * @param string $column Field name
  845. * @param string $value Search value
  846. *
  847. * @return string SQL statement to use in query
  848. */
  849. public function ilike($column, $value)
  850. {
  851. return $this->quote_identifier($column).' LIKE '.$this->quote($value);
  852. }
  853. /**
  854. * Abstract SQL statement for value concatenation
  855. *
  856. * @return string SQL statement to be used in query
  857. */
  858. public function concat(/* col1, col2, ... */)
  859. {
  860. $args = func_get_args();
  861. if (is_array($args[0])) {
  862. $args = $args[0];
  863. }
  864. return '(' . join(' || ', $args) . ')';
  865. }
  866. /**
  867. * Encodes non-UTF-8 characters in string/array/object (recursive)
  868. *
  869. * @param mixed $input Data to fix
  870. * @param bool $serialized Enable serialization
  871. *
  872. * @return mixed Properly UTF-8 encoded data
  873. */
  874. public static function encode($input, $serialized = false)
  875. {
  876. // use Base64 encoding to workaround issues with invalid
  877. // or null characters in serialized string (#1489142)
  878. if ($serialized) {
  879. return base64_encode(serialize($input));
  880. }
  881. if (is_object($input)) {
  882. foreach (get_object_vars($input) as $idx => $value) {
  883. $input->$idx = self::encode($value);
  884. }
  885. return $input;
  886. }
  887. else if (is_array($input)) {
  888. foreach ($input as $idx => $value) {
  889. $input[$idx] = self::encode($value);
  890. }
  891. return $input;
  892. }
  893. return utf8_encode($input);
  894. }
  895. /**
  896. * Decodes encoded UTF-8 string/object/array (recursive)
  897. *
  898. * @param mixed $input Input data
  899. * @param bool $serialized Enable serialization
  900. *
  901. * @return mixed Decoded data
  902. */
  903. public static function decode($input, $serialized = false)
  904. {
  905. // use Base64 encoding to workaround issues with invalid
  906. // or null characters in serialized string (#1489142)
  907. if ($serialized) {
  908. // Keep backward compatybility where base64 wasn't used
  909. if (strpos(substr($input, 0, 16), ':') !== false) {
  910. return self::decode(@unserialize($input));
  911. }
  912. return @unserialize(base64_decode($input));
  913. }
  914. if (is_object($input)) {
  915. foreach (get_object_vars($input) as $idx => $value) {
  916. $input->$idx = self::decode($value);
  917. }
  918. return $input;
  919. }
  920. else if (is_array($input)) {
  921. foreach ($input as $idx => $value) {
  922. $input[$idx] = self::decode($value);
  923. }
  924. return $input;
  925. }
  926. return utf8_decode($input);
  927. }
  928. /**
  929. * Return correct name for a specific database table
  930. *
  931. * @param string $table Table name
  932. * @param bool $quoted Quote table identifier
  933. *
  934. * @return string Translated table name
  935. */
  936. public function table_name($table, $quoted = false)
  937. {
  938. // let plugins alter the table name (#1489837)
  939. $plugin = rcube::get_instance()->plugins->exec_hook('db_table_name', array('table' => $table));
  940. $table = $plugin['table'];
  941. // add prefix to the table name if configured
  942. if (($prefix = $this->options['table_prefix']) && strpos($table, $prefix) !== 0) {
  943. $table = $prefix . $table;
  944. }
  945. if ($quoted) {
  946. $table = $this->quote_identifier($table);
  947. }
  948. return $table;
  949. }
  950. /**
  951. * Set class option value
  952. *
  953. * @param string $name Option name
  954. * @param mixed $value Option value
  955. */
  956. public function set_option($name, $value)
  957. {
  958. $this->options[$name] = $value;
  959. }
  960. /**
  961. * Set DSN connection to be used for the given table
  962. *
  963. * @param string $table Table name
  964. * @param string $mode DSN connection ('r' or 'w') to be used
  965. */
  966. public function set_table_dsn($table, $mode)
  967. {
  968. $this->options['table_dsn_map'][$this->table_name($table)] = $mode;
  969. }
  970. /**
  971. * MDB2 DSN string parser
  972. *
  973. * @param string $sequence Secuence name
  974. *
  975. * @return array DSN parameters
  976. */
  977. public static function parse_dsn($dsn)
  978. {
  979. if (empty($dsn)) {
  980. return null;
  981. }
  982. // Find phptype and dbsyntax
  983. if (($pos = strpos($dsn, '://')) !== false) {
  984. $str = substr($dsn, 0, $pos);
  985. $dsn = substr($dsn, $pos + 3);
  986. }
  987. else {
  988. $str = $dsn;
  989. $dsn = null;
  990. }
  991. // Get phptype and dbsyntax
  992. // $str => phptype(dbsyntax)
  993. if (preg_match('|^(.+?)\((.*?)\)$|', $str, $arr)) {
  994. $parsed['phptype'] = $arr[1];
  995. $parsed['dbsyntax'] = !$arr[2] ? $arr[1] : $arr[2];
  996. }
  997. else {
  998. $parsed['phptype'] = $str;
  999. $parsed['dbsyntax'] = $str;
  1000. }
  1001. if (empty($dsn)) {
  1002. return $parsed;
  1003. }
  1004. // Get (if found): username and password
  1005. // $dsn => username:password@protocol+hostspec/database
  1006. if (($at = strrpos($dsn,'@')) !== false) {
  1007. $str = substr($dsn, 0, $at);
  1008. $dsn = substr($dsn, $at + 1);
  1009. if (($pos = strpos($str, ':')) !== false) {
  1010. $parsed['username'] = rawurldecode(substr($str, 0, $pos));
  1011. $parsed['password'] = rawurldecode(substr($str, $pos + 1));
  1012. }
  1013. else {
  1014. $parsed['username'] = rawurldecode($str);
  1015. }
  1016. }
  1017. // Find protocol and hostspec
  1018. // $dsn => proto(proto_opts)/database
  1019. if (preg_match('|^([^(]+)\((.*?)\)/?(.*?)$|', $dsn, $match)) {
  1020. $proto = $match[1];
  1021. $proto_opts = $match[2] ? $match[2] : false;
  1022. $dsn = $match[3];
  1023. }
  1024. // $dsn => protocol+hostspec/database (old format)
  1025. else {
  1026. if (strpos($dsn, '+') !== false) {
  1027. list($proto, $dsn) = explode('+', $dsn, 2);
  1028. }
  1029. if ( strpos($dsn, '//') === 0
  1030. && strpos($dsn, '/', 2) !== false
  1031. && $parsed['phptype'] == 'oci8'
  1032. ) {
  1033. //oracle's "Easy Connect" syntax:
  1034. //"username/password@[//]host[:port][/service_name]"
  1035. //e.g. "scott/tiger@//mymachine:1521/oracle"
  1036. $proto_opts = $dsn;
  1037. $pos = strrpos($proto_opts, '/');
  1038. $dsn = substr($proto_opts, $pos + 1);
  1039. $proto_opts = substr($proto_opts, 0, $pos);
  1040. }
  1041. else if (strpos($dsn, '/') !== false) {
  1042. list($proto_opts, $dsn) = explode('/', $dsn, 2);
  1043. }
  1044. else {
  1045. $proto_opts = $dsn;
  1046. $dsn = null;
  1047. }
  1048. }
  1049. // process the different protocol options
  1050. $parsed['protocol'] = $proto ?: 'tcp';
  1051. $proto_opts = rawurldecode($proto_opts);
  1052. if (strpos($proto_opts, ':') !== false) {
  1053. list($proto_opts, $parsed['port']) = explode(':', $proto_opts);
  1054. }
  1055. if ($parsed['protocol'] == 'tcp') {
  1056. $parsed['hostspec'] = $proto_opts;
  1057. }
  1058. else if ($parsed['protocol'] == 'unix') {
  1059. $parsed['socket'] = $proto_opts;
  1060. }
  1061. // Get dabase if any
  1062. // $dsn => database
  1063. if ($dsn) {
  1064. // /database
  1065. if (($pos = strpos($dsn, '?')) === false) {
  1066. $parsed['database'] = rawurldecode($dsn);
  1067. // /database?param1=value1&param2=value2
  1068. }
  1069. else {
  1070. $parsed['database'] = rawurldecode(substr($dsn, 0, $pos));
  1071. $dsn = substr($dsn, $pos + 1);
  1072. if (strpos($dsn, '&') !== false) {
  1073. $opts = explode('&', $dsn);
  1074. }
  1075. else { // database?param1=value1
  1076. $opts = array($dsn);
  1077. }
  1078. foreach ($opts as $opt) {
  1079. list($key, $value) = explode('=', $opt);
  1080. if (!array_key_exists($key, $parsed) || false === $parsed[$key]) {
  1081. // don't allow params overwrite
  1082. $parsed[$key] = rawurldecode($value);
  1083. }
  1084. }
  1085. }
  1086. }
  1087. return $parsed;
  1088. }
  1089. /**
  1090. * Returns PDO DSN string from DSN array
  1091. *
  1092. * @param array $dsn DSN parameters
  1093. *
  1094. * @return string DSN string
  1095. */
  1096. protected function dsn_string($dsn)
  1097. {
  1098. $params = array();
  1099. $result = $dsn['phptype'] . ':';
  1100. if ($dsn['hostspec']) {
  1101. $params[] = 'host=' . $dsn['hostspec'];
  1102. }
  1103. if ($dsn['port']) {
  1104. $params[] = 'port=' . $dsn['port'];
  1105. }
  1106. if ($dsn['database']) {
  1107. $params[] = 'dbname=' . $dsn['database'];
  1108. }
  1109. if (!empty($params)) {
  1110. $result .= implode(';', $params);
  1111. }
  1112. return $result;
  1113. }
  1114. /**
  1115. * Returns driver-specific connection options
  1116. *
  1117. * @param array $dsn DSN parameters
  1118. *
  1119. * @return array Connection options
  1120. */
  1121. protected function dsn_options($dsn)
  1122. {
  1123. $result = array();
  1124. if ($this->db_pconn) {
  1125. $result[PDO::ATTR_PERSISTENT] = true;
  1126. }
  1127. if (!empty($dsn['prefetch'])) {
  1128. $result[PDO::ATTR_PREFETCH] = (int) $dsn['prefetch'];
  1129. }
  1130. if (!empty($dsn['timeout'])) {
  1131. $result[PDO::ATTR_TIMEOUT] = (int) $dsn['timeout'];
  1132. }
  1133. return $result;
  1134. }
  1135. /**
  1136. * Execute the given SQL script
  1137. *
  1138. * @param string $sql SQL queries to execute
  1139. *
  1140. * @return boolen True on success, False on error
  1141. */
  1142. public function exec_script($sql)
  1143. {
  1144. $sql = $this->fix_table_names($sql);
  1145. $buff = '';
  1146. foreach (explode("\n", $sql) as $line) {
  1147. if (preg_match('/^--/', $line) || trim($line) == '')
  1148. continue;
  1149. $buff .= $line . "\n";
  1150. if (preg_match('/(;|^GO)$/', trim($line))) {
  1151. $this->query($buff);
  1152. $buff = '';
  1153. if ($this->db_error) {
  1154. break;
  1155. }
  1156. }
  1157. }
  1158. return !$this->db_error;
  1159. }
  1160. /**
  1161. * Parse SQL file and fix table names according to table prefix
  1162. */
  1163. protected function fix_table_names($sql)
  1164. {
  1165. if (!$this->options['table_prefix']) {
  1166. return $sql;
  1167. }
  1168. $sql = preg_replace_callback(
  1169. '/((TABLE|TRUNCATE|(?<!ON )UPDATE|INSERT INTO|FROM'
  1170. . '| ON(?! (DELETE|UPDATE))|REFERENCES|CONSTRAINT|FOREIGN KEY|INDEX)'
  1171. . '\s+(IF (NOT )?EXISTS )?[`"]*)([^`"\( \r\n]+)/',
  1172. array($this, 'fix_table_names_callback'),
  1173. $sql
  1174. );
  1175. return $sql;
  1176. }
  1177. /**
  1178. * Preg_replace callback for fix_table_names()
  1179. */
  1180. protected function fix_table_names_callback($matches)
  1181. {
  1182. return $matches[1] . $this->options['table_prefix'] . $matches[count($matches)-1];
  1183. }
  1184. }