4 +-----------------------------------------------------------------------+
5 | program/include/rcube_mdb2.php |
7 | This file is part of the RoundCube Webmail client |
8 | Copyright (C) 2005-2009, RoundCube Dev. - Switzerland |
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 2834 2009-08-04 08:22:41Z alec $
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 var $db_dsnw; // DSN for write operations
39 var $db_dsnr; // DSN for read operations
40 var $db_connected = false; // Already connected ?
41 var $db_mode = ''; // Connection mode
42 var $db_handle = 0; // Connection handle
43 var $db_error = false;
44 var $db_error_msg = '';
45 var $debug_mode = false;
47 var $a_query_results = array('dummy');
54 * @param string DSN for read/write operations
55 * @param string Optional DSN for read only operations
57 function __construct($db_dsnw, $db_dsnr='', $pconn=false)
62 $this->db_dsnw = $db_dsnw;
63 $this->db_dsnr = $db_dsnr;
64 $this->db_pconn = $pconn;
66 $dsn_array = MDB2::parseDSN($db_dsnw);
67 $this->db_provider = $dsn_array['phptype'];
72 * Connect to specific database
74 * @param string DSN for DB connections
75 * @return object PEAR database handle
78 function dsn_connect($dsn)
80 // Use persistent connections if available
82 'persistent' => $this->db_pconn,
83 'emulate_prepared' => $this->debug_mode,
84 'debug' => $this->debug_mode,
85 'debug_handler' => 'mdb2_debug_handler',
86 'portability' => MDB2_PORTABILITY_ALL ^ MDB2_PORTABILITY_EMPTY_TO_NULL);
88 if ($this->db_provider == 'pgsql') {
89 $db_options['disable_smart_seqname'] = true;
90 $db_options['seqname_format'] = '%s';
93 $dbh = MDB2::connect($dsn, $db_options);
95 if (MDB2::isError($dbh))
97 $this->db_error = TRUE;
98 $this->db_error_msg = $dbh->getMessage();
100 raise_error(array('code' => 500, 'type' => 'db', 'line' => __LINE__,
101 'file' => __FILE__, 'message' => $dbh->getUserInfo()), TRUE, FALSE);
103 else if ($this->db_provider=='sqlite')
105 $dsn_array = MDB2::parseDSN($dsn);
106 if (!filesize($dsn_array['database']) && !empty($this->sqlite_initials))
107 $this->_sqlite_create_database($dbh, $this->sqlite_initials);
109 else if ($this->db_provider!='mssql')
110 $dbh->setCharset('utf8');
117 * Connect to appropiate databse
118 * depending on the operation
120 * @param string Connection mode (r|w)
123 function db_connect($mode)
125 $this->db_mode = $mode;
128 if ($this->db_connected)
130 // no replication, current connection is ok
131 if ($this->db_dsnw==$this->db_dsnr)
134 // connected to master, current connection is ok
135 if ($this->db_mode=='w')
138 // Same mode, current connection is ok
139 if ($this->db_mode==$mode)
144 $dsn = $this->db_dsnr;
146 $dsn = $this->db_dsnw;
148 $this->db_handle = $this->dsn_connect($dsn);
149 $this->db_connected = true;
154 * Activate/deactivate debug mode
156 * @param boolean True if SQL queries should be logged
158 function set_debug($dbg = true)
160 $this->debug_mode = $dbg;
161 if ($this->db_connected)
163 $this->db_handle->setOption('debug', $dbg);
164 $this->db_handle->setOption('emulate_prepared', $dbg);
170 * Getter for error state
172 * @param boolean True on error
176 return $this->db_error ? $this->db_error_msg : FALSE;
181 * Connection state checker
183 * @param boolean True if in connected state
185 function is_connected()
187 return PEAR::isError($this->db_handle) ? false : true;
192 * Execute a SQL query
194 * @param string SQL query to execute
195 * @param mixed Values to be inserted in query
196 * @return number Query handle identifier
201 if (!$this->is_connected())
204 $params = func_get_args();
205 $query = array_shift($params);
207 return $this->_query($query, 0, 0, $params);
212 * Execute a SQL query with limits
214 * @param string SQL query to execute
215 * @param number Offset for LIMIT statement
216 * @param number Number of rows for LIMIT statement
217 * @param mixed Values to be inserted in query
218 * @return number Query handle identifier
221 function limitquery()
223 $params = func_get_args();
224 $query = array_shift($params);
225 $offset = array_shift($params);
226 $numrows = array_shift($params);
228 return $this->_query($query, $offset, $numrows, $params);
233 * Execute a SQL query with limits
235 * @param string SQL query to execute
236 * @param number Offset for LIMIT statement
237 * @param number Number of rows for LIMIT statement
238 * @param array Values to be inserted in query
239 * @return number Query handle identifier
242 function _query($query, $offset, $numrows, $params)
245 if (strtolower(substr(trim($query),0,6))=='select')
250 $this->db_connect($mode);
252 if ($this->db_provider == 'sqlite')
253 $this->_sqlite_prepare();
255 if ($numrows || $offset)
256 $result = $this->db_handle->setLimit($numrows,$offset);
259 $result = $this->db_handle->query($query);
262 $params = (array)$params;
263 $q = $this->db_handle->prepare($query);
264 if ($this->db_handle->isError($q))
266 $this->db_error = TRUE;
267 $this->db_error_msg = $q->userinfo;
269 raise_error(array('code' => 500, 'type' => 'db', 'line' => __LINE__, 'file' => __FILE__,
270 'message' => $this->db_error_msg), TRUE, TRUE);
274 $result = $q->execute($params);
279 // add result, even if it's an error
280 return $this->_add_result($result);
285 * Get number of rows for a SQL query
286 * If no query handle is specified, the last query will be taken as reference
288 * @param number Optional query handle identifier
289 * @return mixed Number of rows or FALSE on failure
292 function num_rows($res_id=NULL)
294 if (!$this->db_handle)
297 if ($result = $this->_get_result($res_id))
298 return $result->numRows();
305 * Get number of affected rows for the last query
307 * @param number Optional query handle identifier
308 * @return mixed Number of rows or FALSE on failure
311 function affected_rows($res_id = null)
313 if (!$this->db_handle)
316 return (int) $this->_get_result($res_id);
321 * Get last inserted record ID
322 * For Postgres databases, a sequence name is required
324 * @param string Table name (to find the incremented sequence)
325 * @return mixed ID or FALSE on failure
328 function insert_id($table = '')
330 if (!$this->db_handle || $this->db_mode=='r')
333 // find sequence name
334 if ($table && $this->db_provider == 'pgsql')
335 $table = get_sequence_name($table);
337 $id = $this->db_handle->lastInsertID($table);
339 return $this->db_handle->isError($id) ? null : $id;
344 * Get an associative array for one row
345 * If no query handle is specified, the last query will be taken as reference
347 * @param number Optional query handle identifier
348 * @return mixed Array with col values or FALSE on failure
351 function fetch_assoc($res_id=NULL)
353 $result = $this->_get_result($res_id);
354 return $this->_fetch_row($result, MDB2_FETCHMODE_ASSOC);
359 * Get an index array for one row
360 * If no query handle is specified, the last query will be taken as reference
362 * @param number Optional query handle identifier
363 * @return mixed Array with col values or FALSE on failure
366 function fetch_array($res_id=NULL)
368 $result = $this->_get_result($res_id);
369 return $this->_fetch_row($result, MDB2_FETCHMODE_ORDERED);
374 * Get col values for a result row
376 * @param object Query result handle
377 * @param number Fetch mode identifier
378 * @return mixed Array with col values or FALSE on failure
381 function _fetch_row($result, $mode)
383 if ($result === FALSE || PEAR::isError($result) || !$this->is_connected())
386 return $result->fetchRow($mode);
391 * Formats input so it can be safely used in a query
393 * @param mixed Value to quote
394 * @return string Quoted/converted string for use in query
397 function quote($input, $type = null)
399 // create DB handle if not available
400 if (!$this->db_handle)
401 $this->db_connect('r');
403 // escape pear identifier chars
404 $rep_chars = array('?' => '\?',
408 return $this->db_handle->quote($input, $type);
413 * Quotes a string so it can be safely used as a table or column name
415 * @param string Value to quote
416 * @return string Quoted string for use in query
417 * @deprecated Replaced by rcube_MDB2::quote_identifier
418 * @see rcube_mdb2::quote_identifier
421 function quoteIdentifier($str)
423 return $this->quote_identifier($str);
428 * Quotes a string so it can be safely used as a table or column name
430 * @param string Value to quote
431 * @return string Quoted string for use in query
434 function quote_identifier($str)
436 if (!$this->db_handle)
437 $this->db_connect('r');
439 return $this->db_handle->quoteIdentifier($str);
445 * @param string The string to be escaped
446 * @return string The escaped string
450 function escapeSimple($str)
452 if (!$this->db_handle)
453 $this->db_connect('r');
455 return $this->db_handle->escape($str);
460 * Return SQL function for current time and date
462 * @return string SQL function to use in query
467 switch($this->db_provider)
479 * Return list of elements for use with SQL's IN clause
481 * @param string Input array
482 * @return string Elements list string
485 function array2list($arr, $type=null)
488 return $this->quote($arr, $type);
491 foreach ($arr as $item)
492 $res[] = $this->quote($item, $type);
494 return implode(',', $res);
499 * Return SQL statement to convert a field value into a unix timestamp
501 * @param string Field name
502 * @return string SQL statement to use in query
505 function unixtimestamp($field)
507 switch($this->db_provider)
510 return "EXTRACT (EPOCH FROM $field)";
514 return "DATEDIFF(second, '19700101', $field) + DATEDIFF(second, GETDATE(), GETUTCDATE())";
517 return "UNIX_TIMESTAMP($field)";
523 * Return SQL statement to convert from a unix timestamp
525 * @param string Field name
526 * @return string SQL statement to use in query
529 function fromunixtime($timestamp)
531 switch($this->db_provider)
536 return sprintf("FROM_UNIXTIME(%d)", $timestamp);
539 return date("'Y-m-d H:i:s'", $timestamp);
545 * Return SQL statement for case insensitive LIKE
547 * @param string Field name
548 * @param string Search value
549 * @return string SQL statement to use in query
552 function ilike($column, $value)
554 // TODO: use MDB2's matchPattern() function
555 switch($this->db_provider)
558 return $this->quote_identifier($column).' ILIKE '.$this->quote($value);
560 return $this->quote_identifier($column).' LIKE '.$this->quote($value);
566 * Encodes non-UTF-8 characters in string/array/object (recursive)
568 * @param mixed Data to fix
569 * @return mixed Properly UTF-8 encoded data
572 function encode($input)
574 if (is_object($input)) {
575 foreach (get_object_vars($input) as $idx => $value)
576 $input->$idx = $this->encode($value);
579 else if (is_array($input)) {
580 foreach ($input as $idx => $value)
581 $input[$idx] = $this->encode($value);
585 return utf8_encode($input);
590 * Decodes encoded UTF-8 string/object/array (recursive)
592 * @param mixed Input data
593 * @return mixed Decoded data
596 function decode($input)
598 if (is_object($input)) {
599 foreach (get_object_vars($input) as $idx => $value)
600 $input->$idx = $this->decode($value);
603 else if (is_array($input)) {
604 foreach ($input as $idx => $value)
605 $input[$idx] = $this->decode($value);
609 return utf8_decode($input);
614 * Adds a query result and returns a handle ID
616 * @param object Query handle
617 * @return mixed Handle ID
620 function _add_result($res)
623 if (PEAR::isError($res))
625 $this->db_error = TRUE;
626 $this->db_error_msg = $res->getMessage();
627 raise_error(array('code' => 500, 'type' => 'db', 'line' => __LINE__, 'file' => __FILE__,
628 'message' => $res->getMessage() . " Query: "
629 . substr(preg_replace('/[\r\n]+\s*/', ' ', $res->userinfo), 0, 512)),
633 $res_id = sizeof($this->a_query_results);
634 $this->last_res_id = $res_id;
635 $this->a_query_results[$res_id] = $res;
641 * Resolves a given handle ID and returns the according query handle
642 * If no ID is specified, the last resource handle will be returned
644 * @param number Handle ID
645 * @return mixed Resource handle or FALSE on failure
648 function _get_result($res_id=NULL)
651 $res_id = $this->last_res_id;
653 if (isset($this->a_query_results[$res_id]))
654 if (!PEAR::isError($this->a_query_results[$res_id]))
655 return $this->a_query_results[$res_id];
662 * Create a sqlite database from a file
664 * @param object SQLite database handle
665 * @param string File path to use for DB creation
668 function _sqlite_create_database($dbh, $file_name)
670 if (empty($file_name) || !is_string($file_name))
673 $data = file_get_contents($file_name);
676 if (!sqlite_exec($dbh->connection, $data, $error) || MDB2::isError($dbh))
677 raise_error(array('code' => 500, 'type' => 'db',
678 'line' => __LINE__, 'file' => __FILE__, 'message' => $error), TRUE, FALSE);
683 * Add some proprietary database functions to the current SQLite handle
684 * in order to make it MySQL compatible
688 function _sqlite_prepare()
690 include_once('include/rcube_sqlite.inc');
692 // we emulate via callback some missing MySQL function
693 sqlite_create_function($this->db_handle->connection, "from_unixtime", "rcube_sqlite_from_unixtime");
694 sqlite_create_function($this->db_handle->connection, "unix_timestamp", "rcube_sqlite_unix_timestamp");
695 sqlite_create_function($this->db_handle->connection, "now", "rcube_sqlite_now");
696 sqlite_create_function($this->db_handle->connection, "md5", "rcube_sqlite_md5");
700 } // end class rcube_db
703 /* this is our own debug handler for the MDB2 connection */
704 function mdb2_debug_handler(&$db, $scope, $message, $context = array())
706 if ($scope != 'prepare')
708 $debug_output = $scope . '('.$db->db_index.'): ';
709 $debug_output .= $message . $db->getOption('log_line_break');
710 write_log('sql', $debug_output);