4 +-----------------------------------------------------------------------+
5 | program/include/rcube_mdb2.php |
7 | This file is part of the Roundcube Webmail client |
8 | Copyright (C) 2005-2009, The Roundcube Dev Team |
9 | Licensed under the GNU GPL |
12 | PEAR:DB wrapper class that implements PEAR MDB2 functions |
13 | See http://pear.php.net/package/MDB2 |
15 +-----------------------------------------------------------------------+
16 | Author: Lukas Kahwe Smith <smith@pooteeweet.org> |
17 +-----------------------------------------------------------------------+
19 $Id: rcube_mdb2.php 5872 2012-02-11 11:38:46Z thomasb $
25 * Database independent query interface
27 * This is a wrapper for the PEAR::MDB2 class
30 * @author David Saez Padros <david@ols.es>
31 * @author Thomas Bruederli <roundcube@gmail.com>
32 * @author Lukas Kahwe Smith <smith@pooteeweet.org>
34 * @link http://pear.php.net/package/MDB2
38 public $db_dsnw; // DSN for write operations
39 public $db_dsnr; // DSN for read operations
40 public $db_connected = false; // Already connected ?
41 public $db_mode = ''; // Connection mode
42 public $db_handle = 0; // Connection handle
43 public $db_error = false;
44 public $db_error_msg = '';
46 private $debug_mode = false;
47 private $conn_failure = false;
48 private $a_query_results = array('dummy');
49 private $last_res_id = 0;
56 * @param string $db_dsnw DSN for read/write operations
57 * @param string $db_dsnr Optional DSN for read only operations
59 function __construct($db_dsnw, $db_dsnr='', $pconn=false)
64 $this->db_dsnw = $db_dsnw;
65 $this->db_dsnr = $db_dsnr;
66 $this->db_pconn = $pconn;
68 $dsn_array = MDB2::parseDSN($db_dsnw);
69 $this->db_provider = $dsn_array['phptype'];
74 * Connect to specific database
76 * @param string $dsn DSN for DB connections
77 * @return MDB2 PEAR database handle
80 private function dsn_connect($dsn)
82 // Use persistent connections if available
84 'persistent' => $this->db_pconn,
85 'emulate_prepared' => $this->debug_mode,
86 'debug' => $this->debug_mode,
87 'debug_handler' => array($this, 'debug_handler'),
88 'portability' => MDB2_PORTABILITY_ALL ^ MDB2_PORTABILITY_EMPTY_TO_NULL);
90 if ($this->db_provider == 'pgsql') {
91 $db_options['disable_smart_seqname'] = true;
92 $db_options['seqname_format'] = '%s';
94 $this->db_error = false;
95 $this->db_error_msg = null;
97 $dbh = MDB2::connect($dsn, $db_options);
99 if (MDB2::isError($dbh)) {
100 $this->db_error = true;
101 $this->db_error_msg = $dbh->getMessage();
103 raise_error(array('code' => 500, 'type' => 'db',
104 'line' => __LINE__, 'file' => __FILE__,
105 'message' => $dbh->getUserInfo()), true, false);
107 else if ($this->db_provider == 'sqlite') {
108 $dsn_array = MDB2::parseDSN($dsn);
109 if (!filesize($dsn_array['database']) && !empty($this->sqlite_initials))
110 $this->_sqlite_create_database($dbh, $this->sqlite_initials);
112 else if ($this->db_provider!='mssql' && $this->db_provider!='sqlsrv')
113 $dbh->setCharset('utf8');
120 * Connect to appropiate database depending on the operation
122 * @param string $mode Connection mode (r|w)
125 function db_connect($mode)
127 // previous connection failed, don't attempt to connect again
128 if ($this->conn_failure) {
133 if ($this->db_dsnw == $this->db_dsnr) {
138 if ($this->db_connected) {
139 // connected to db with the same or "higher" mode
140 if ($this->db_mode == 'w' || $this->db_mode == $mode) {
145 $dsn = ($mode == 'r') ? $this->db_dsnr : $this->db_dsnw;
147 $this->db_handle = $this->dsn_connect($dsn);
148 $this->db_connected = !PEAR::isError($this->db_handle);
150 // use write-master when read-only fails
151 if (!$this->db_connected && $mode == 'r') {
153 $this->db_handle = $this->dsn_connect($this->db_dsnw);
154 $this->db_connected = !PEAR::isError($this->db_handle);
157 if ($this->db_connected)
158 $this->db_mode = $mode;
160 $this->conn_failure = true;
165 * Activate/deactivate debug mode
167 * @param boolean $dbg True if SQL queries should be logged
170 function set_debug($dbg = true)
172 $this->debug_mode = $dbg;
173 if ($this->db_connected) {
174 $this->db_handle->setOption('debug', $dbg);
175 $this->db_handle->setOption('emulate_prepared', $dbg);
181 * Getter for error state
183 * @param boolean True on error
188 return $this->db_error ? $this->db_error_msg : false;
193 * Connection state checker
195 * @param boolean True if in connected state
198 function is_connected()
200 return PEAR::isError($this->db_handle) ? false : $this->db_connected;
205 * Is database replication configured?
206 * This returns true if dsnw != dsnr
208 function is_replicated()
210 return !empty($this->db_dsnr) && $this->db_dsnw != $this->db_dsnr;
215 * Execute a SQL query
217 * @param string SQL query to execute
218 * @param mixed Values to be inserted in query
219 * @return number Query handle identifier
224 $params = func_get_args();
225 $query = array_shift($params);
227 // Support one argument of type array, instead of n arguments
228 if (count($params) == 1 && is_array($params[0]))
229 $params = $params[0];
231 return $this->_query($query, 0, 0, $params);
236 * Execute a SQL query with limits
238 * @param string SQL query to execute
239 * @param number Offset for LIMIT statement
240 * @param number Number of rows for LIMIT statement
241 * @param mixed Values to be inserted in query
242 * @return number Query handle identifier
245 function limitquery()
247 $params = func_get_args();
248 $query = array_shift($params);
249 $offset = array_shift($params);
250 $numrows = array_shift($params);
252 return $this->_query($query, $offset, $numrows, $params);
257 * Execute a SQL query with limits
259 * @param string $query SQL query to execute
260 * @param number $offset Offset for LIMIT statement
261 * @param number $numrows Number of rows for LIMIT statement
262 * @param array $params Values to be inserted in query
263 * @return number Query handle identifier
266 private function _query($query, $offset, $numrows, $params)
269 $mode = (strtolower(substr(trim($query),0,6)) == 'select') ? 'r' : 'w';
271 $this->db_connect($mode);
273 // check connection before proceeding
274 if (!$this->is_connected())
277 if ($this->db_provider == 'sqlite')
278 $this->_sqlite_prepare();
280 if ($numrows || $offset)
281 $result = $this->db_handle->setLimit($numrows,$offset);
284 $result = $mode == 'r' ? $this->db_handle->query($query) : $this->db_handle->exec($query);
286 $params = (array)$params;
287 $q = $this->db_handle->prepare($query, null, $mode=='w' ? MDB2_PREPARE_MANIP : null);
288 if ($this->db_handle->isError($q)) {
289 $this->db_error = true;
290 $this->db_error_msg = $q->userinfo;
292 raise_error(array('code' => 500, 'type' => 'db',
293 'line' => __LINE__, 'file' => __FILE__,
294 'message' => $this->db_error_msg), true, false);
299 $result = $q->execute($params);
304 // add result, even if it's an error
305 return $this->_add_result($result);
310 * Get number of rows for a SQL query
311 * If no query handle is specified, the last query will be taken as reference
313 * @param number $res_id Optional query handle identifier
314 * @return mixed Number of rows or false on failure
317 function num_rows($res_id=null)
319 if (!$this->db_connected)
322 if ($result = $this->_get_result($res_id))
323 return $result->numRows();
330 * Get number of affected rows for the last query
332 * @param number $res_id Optional query handle identifier
333 * @return mixed Number of rows or false on failure
336 function affected_rows($res_id = null)
338 if (!$this->db_connected)
341 return $this->_get_result($res_id);
346 * Get last inserted record ID
347 * For Postgres databases, a sequence name is required
349 * @param string $table Table name (to find the incremented sequence)
350 * @return mixed ID or false on failure
353 function insert_id($table = '')
355 if (!$this->db_connected || $this->db_mode == 'r')
359 if ($this->db_provider == 'pgsql')
360 // find sequence name
361 $table = get_sequence_name($table);
363 // resolve table name
364 $table = get_table_name($table);
367 $id = $this->db_handle->lastInsertID($table);
369 return $this->db_handle->isError($id) ? null : $id;
374 * Get an associative array for one row
375 * If no query handle is specified, the last query will be taken as reference
377 * @param number $res_id Optional query handle identifier
378 * @return mixed Array with col values or false on failure
381 function fetch_assoc($res_id=null)
383 $result = $this->_get_result($res_id);
384 return $this->_fetch_row($result, MDB2_FETCHMODE_ASSOC);
389 * Get an index array for one row
390 * If no query handle is specified, the last query will be taken as reference
392 * @param number $res_id Optional query handle identifier
393 * @return mixed Array with col values or false on failure
396 function fetch_array($res_id=null)
398 $result = $this->_get_result($res_id);
399 return $this->_fetch_row($result, MDB2_FETCHMODE_ORDERED);
404 * Get col values for a result row
406 * @param MDB2_Result_Common Query $result result handle
407 * @param number $mode Fetch mode identifier
408 * @return mixed Array with col values or false on failure
411 private function _fetch_row($result, $mode)
413 if ($result === false || PEAR::isError($result) || !$this->is_connected())
416 return $result->fetchRow($mode);
421 * Wrapper for the SHOW TABLES command
423 * @return array List of all tables of the current database
427 function list_tables()
429 // get tables if not cached
430 if (!$this->tables) {
431 $this->db_handle->loadModule('Manager');
432 if (!PEAR::isError($result = $this->db_handle->listTables()))
433 $this->tables = $result;
435 $this->tables = array();
438 return $this->tables;
443 * Wrapper for SHOW COLUMNS command
445 * @param string Table name
446 * @return array List of table cols
448 function list_cols($table)
450 $this->db_handle->loadModule('Manager');
451 if (!PEAR::isError($result = $this->db_handle->listTableFields($table))) {
460 * Formats input so it can be safely used in a query
462 * @param mixed $input Value to quote
463 * @param string $type Type of data
464 * @return string Quoted/converted string for use in query
467 function quote($input, $type = null)
469 // handle int directly for better performance
470 if ($type == 'integer')
471 return intval($input);
473 // create DB handle if not available
474 if (!$this->db_handle)
475 $this->db_connect('r');
477 return $this->db_connected ? $this->db_handle->quote($input, $type) : addslashes($input);
482 * Quotes a string so it can be safely used as a table or column name
484 * @param string $str Value to quote
485 * @return string Quoted string for use in query
486 * @deprecated Replaced by rcube_MDB2::quote_identifier
487 * @see rcube_mdb2::quote_identifier
490 function quoteIdentifier($str)
492 return $this->quote_identifier($str);
497 * Quotes a string so it can be safely used as a table or column name
499 * @param string $str Value to quote
500 * @return string Quoted string for use in query
503 function quote_identifier($str)
505 if (!$this->db_handle)
506 $this->db_connect('r');
508 return $this->db_connected ? $this->db_handle->quoteIdentifier($str) : $str;
515 * @param string $str The string to be escaped
516 * @return string The escaped string
520 function escapeSimple($str)
522 if (!$this->db_handle)
523 $this->db_connect('r');
525 return $this->db_handle->escape($str);
530 * Return SQL function for current time and date
532 * @return string SQL function to use in query
537 switch ($this->db_provider) {
549 * Return list of elements for use with SQL's IN clause
551 * @param array $arr Input array
552 * @param string $type Type of data
553 * @return string Comma-separated list of quoted values for use in query
556 function array2list($arr, $type = null)
559 return $this->quote($arr, $type);
561 foreach ($arr as $idx => $item)
562 $arr[$idx] = $this->quote($item, $type);
564 return implode(',', $arr);
569 * Return SQL statement to convert a field value into a unix timestamp
571 * This method is deprecated and should not be used anymore due to limitations
572 * of timestamp functions in Mysql (year 2038 problem)
574 * @param string $field Field name
575 * @return string SQL statement to use in query
578 function unixtimestamp($field)
580 switch($this->db_provider) {
582 return "EXTRACT (EPOCH FROM $field)";
586 return "DATEDIFF(second, '19700101', $field) + DATEDIFF(second, GETDATE(), GETUTCDATE())";
589 return "UNIX_TIMESTAMP($field)";
595 * Return SQL statement to convert from a unix timestamp
597 * @param string $timestamp Field name
598 * @return string SQL statement to use in query
601 function fromunixtime($timestamp)
603 return date("'Y-m-d H:i:s'", $timestamp);
608 * Return SQL statement for case insensitive LIKE
610 * @param string $column Field name
611 * @param string $value Search value
612 * @return string SQL statement to use in query
615 function ilike($column, $value)
617 // TODO: use MDB2's matchPattern() function
618 switch($this->db_provider) {
620 return $this->quote_identifier($column).' ILIKE '.$this->quote($value);
622 return $this->quote_identifier($column).' LIKE '.$this->quote($value);
627 * Abstract SQL statement for value concatenation
629 * @return string SQL statement to be used in query
632 function concat(/* col1, col2, ... */)
635 $args = func_get_args();
636 if (is_array($args[0]))
639 switch($this->db_provider) {
653 return $func . '(' . join($delim, $args) . ')';
658 * Encodes non-UTF-8 characters in string/array/object (recursive)
660 * @param mixed $input Data to fix
661 * @return mixed Properly UTF-8 encoded data
664 function encode($input)
666 if (is_object($input)) {
667 foreach (get_object_vars($input) as $idx => $value)
668 $input->$idx = $this->encode($value);
671 else if (is_array($input)) {
672 foreach ($input as $idx => $value)
673 $input[$idx] = $this->encode($value);
677 return utf8_encode($input);
682 * Decodes encoded UTF-8 string/object/array (recursive)
684 * @param mixed $input Input data
685 * @return mixed Decoded data
688 function decode($input)
690 if (is_object($input)) {
691 foreach (get_object_vars($input) as $idx => $value)
692 $input->$idx = $this->decode($value);
695 else if (is_array($input)) {
696 foreach ($input as $idx => $value)
697 $input[$idx] = $this->decode($value);
701 return utf8_decode($input);
706 * Adds a query result and returns a handle ID
708 * @param object $res Query handle
709 * @return mixed Handle ID
712 private function _add_result($res)
715 if (PEAR::isError($res)) {
716 $this->db_error = true;
717 $this->db_error_msg = $res->getMessage();
718 raise_error(array('code' => 500, 'type' => 'db',
719 'line' => __LINE__, 'file' => __FILE__,
720 'message' => $res->getMessage() . " Query: "
721 . substr(preg_replace('/[\r\n]+\s*/', ' ', $res->userinfo), 0, 512)),
725 $res_id = sizeof($this->a_query_results);
726 $this->last_res_id = $res_id;
727 $this->a_query_results[$res_id] = $res;
733 * Resolves a given handle ID and returns the according query handle
734 * If no ID is specified, the last resource handle will be returned
736 * @param number $res_id Handle ID
737 * @return mixed Resource handle or false on failure
740 private function _get_result($res_id = null)
743 $res_id = $this->last_res_id;
745 if (isset($this->a_query_results[$res_id]))
746 if (!PEAR::isError($this->a_query_results[$res_id]))
747 return $this->a_query_results[$res_id];
754 * Create a sqlite database from a file
756 * @param MDB2 $dbh SQLite database handle
757 * @param string $file_name File path to use for DB creation
760 private function _sqlite_create_database($dbh, $file_name)
762 if (empty($file_name) || !is_string($file_name))
765 $data = file_get_contents($file_name);
768 if (!sqlite_exec($dbh->connection, $data, $error) || MDB2::isError($dbh))
769 raise_error(array('code' => 500, 'type' => 'db',
770 'line' => __LINE__, 'file' => __FILE__,
771 'message' => $error), true, false);
776 * Add some proprietary database functions to the current SQLite handle
777 * in order to make it MySQL compatible
781 private function _sqlite_prepare()
783 include_once(INSTALL_PATH . 'program/include/rcube_sqlite.inc');
785 // we emulate via callback some missing MySQL function
786 sqlite_create_function($this->db_handle->connection,
787 'from_unixtime', 'rcube_sqlite_from_unixtime');
788 sqlite_create_function($this->db_handle->connection,
789 'unix_timestamp', 'rcube_sqlite_unix_timestamp');
790 sqlite_create_function($this->db_handle->connection,
791 'now', 'rcube_sqlite_now');
792 sqlite_create_function($this->db_handle->connection,
793 'md5', 'rcube_sqlite_md5');
798 * Debug handler for the MDB2
800 function debug_handler(&$db, $scope, $message, $context = array())
802 if ($scope != 'prepare') {
803 $debug_output = sprintf('%s(%d): %s;',
804 $scope, $db->db_index, rtrim($message, ';'));
805 write_log('sql', $debug_output);
809 } // end class rcube_db