4 +-----------------------------------------------------------------------+
5 | program/include/rcube_mdb2.inc |
7 | This file is part of the RoundCube Webmail client |
8 | Copyright (C) 2005-2007, 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.inc 1255 2008-04-05 12:49:21Z thomasb $
25 * Obtain the PEAR::DB class that is used for abstraction
27 require_once('MDB2.php');
31 * Database independent query interface
33 * This is a wrapper for the PEAR::MDB2 class
36 * @author David Saez Padros <david@ols.es>
37 * @author Thomas Bruederli <roundcube@gmail.com>
38 * @author Lukas Kahwe Smith <smith@pooteeweet.org>
40 * @link http://pear.php.net/package/MDB2
44 var $db_dsnw; // DSN for write operations
45 var $db_dsnr; // DSN for read operations
46 var $db_connected = false; // Already connected ?
47 var $db_mode = ''; // Connection mode
48 var $db_handle = 0; // Connection handle
49 var $db_error = false;
50 var $db_error_msg = '';
51 var $debug_mode = false;
53 var $a_query_results = array('dummy');
60 * @param string DSN for read/write operations
61 * @param string Optional DSN for read only operations
63 function __construct($db_dsnw, $db_dsnr='', $pconn=false)
68 $this->db_dsnw = $db_dsnw;
69 $this->db_dsnr = $db_dsnr;
70 $this->db_pconn = $pconn;
72 $dsn_array = MDB2::parseDSN($db_dsnw);
73 $this->db_provider = $dsn_array['phptype'];
78 * PHP 4 object constructor
80 * @see rcube_mdb2::__construct
82 function rcube_db($db_dsnw,$db_dsnr='')
84 $this->__construct($db_dsnw,$db_dsnr);
89 * Connect to specific database
91 * @param string DSN for DB connections
92 * @return object PEAR database handle
95 function dsn_connect($dsn)
97 // Use persistent connections if available
98 $dbh = MDB2::connect($dsn, array(
99 'persistent' => $this->db_pconn,
100 'emulate_prepared' => $this->debug_mode,
101 'debug' => $this->debug_mode,
102 'debug_handler' => 'mdb2_debug_handler',
103 'portability' => MDB2_PORTABILITY_ALL ^ MDB2_PORTABILITY_EMPTY_TO_NULL));
105 if (MDB2::isError($dbh))
107 $this->db_error = TRUE;
108 $this->db_error_msg = $dbh->getMessage();
110 raise_error(array('code' => 500, 'type' => 'db', 'line' => __LINE__,
111 'file' => __FILE__, 'message' => $dbh->getUserInfo()), TRUE, FALSE);
113 else if ($this->db_provider=='sqlite')
115 $dsn_array = MDB2::parseDSN($dsn);
116 if (!filesize($dsn_array['database']) && !empty($this->sqlite_initials))
117 $this->_sqlite_create_database($dbh, $this->sqlite_initials);
120 $dbh->setCharset('utf8');
127 * Connect to appropiate databse
128 * depending on the operation
130 * @param string Connection mode (r|w)
133 function db_connect($mode)
135 $this->db_mode = $mode;
138 if ($this->db_connected)
140 // no replication, current connection is ok
141 if ($this->db_dsnw==$this->db_dsnr)
144 // connected to master, current connection is ok
145 if ($this->db_mode=='w')
148 // Same mode, current connection is ok
149 if ($this->db_mode==$mode)
154 $dsn = $this->db_dsnr;
156 $dsn = $this->db_dsnw;
158 $this->db_handle = $this->dsn_connect($dsn);
159 $this->db_connected = true;
164 * Activate/deactivate debug mode
166 * @param boolean True if SQL queries should be logged
168 function set_debug($dbg = true)
170 $this->debug_mode = $dbg;
171 if ($this->db_connected)
173 $this->db_handle->setOption('debug', $dbg);
174 $this->db_handle->setOption('emulate_prepared', $dbg);
180 * Getter for error state
182 * @param boolean True on error
186 return $this->db_error ? $this->db_error_msg : FALSE;
191 * Execute a SQL query
193 * @param string SQL query to execute
194 * @param mixed Values to be inserted in query
195 * @return number Query handle identifier
200 $params = func_get_args();
201 $query = array_shift($params);
203 return $this->_query($query, 0, 0, $params);
208 * Execute a SQL query with limits
210 * @param string SQL query to execute
211 * @param number Offset for LIMIT statement
212 * @param number Number of rows for LIMIT statement
213 * @param mixed Values to be inserted in query
214 * @return number Query handle identifier
217 function limitquery()
219 $params = func_get_args();
220 $query = array_shift($params);
221 $offset = array_shift($params);
222 $numrows = array_shift($params);
224 return $this->_query($query, $offset, $numrows, $params);
229 * Execute a SQL query with limits
231 * @param string SQL query to execute
232 * @param number Offset for LIMIT statement
233 * @param number Number of rows for LIMIT statement
234 * @param array Values to be inserted in query
235 * @return number Query handle identifier
238 function _query($query, $offset, $numrows, $params)
241 if (strtolower(trim(substr($query,0,6)))=='select')
246 $this->db_connect($mode);
248 if ($this->db_provider == 'sqlite')
249 $this->_sqlite_prepare();
251 if ($numrows || $offset)
252 $result = $this->db_handle->setLimit($numrows,$offset);
255 $result = $this->db_handle->query($query);
258 $params = (array)$params;
259 $q = $this->db_handle->prepare($query);
260 if ($this->db_handle->isError($q))
262 $this->db_error = TRUE;
263 $this->db_error_msg = $q->userinfo;
265 raise_error(array('code' => 500, 'type' => 'db', 'line' => __LINE__, 'file' => __FILE__,
266 'message' => $this->db_error_msg), TRUE, TRUE);
270 $result = $q->execute($params);
275 // add result, even if it's an error
276 return $this->_add_result($result);
281 * Get number of rows for a SQL query
282 * If no query handle is specified, the last query will be taken as reference
284 * @param number Optional query handle identifier
285 * @return mixed Number of rows or FALSE on failure
288 function num_rows($res_id=NULL)
290 if (!$this->db_handle)
293 if ($result = $this->_get_result($res_id))
294 return $result->numRows();
301 * Get number of affected rows fort he last query
303 * @return mixed Number of rows or FALSE on failure
306 function affected_rows($result = null)
308 if (!$this->db_handle)
311 return $this->_get_result($result);
316 * Get last inserted record ID
317 * For Postgres databases, a sequence name is required
319 * @param string Sequence name for increment
320 * @return mixed ID or FALSE on failure
323 function insert_id($sequence = '')
325 if (!$this->db_handle || $this->db_mode=='r')
328 return $this->db_handle->lastInsertID($sequence);
333 * Get an associative array for one row
334 * If no query handle is specified, the last query will be taken as reference
336 * @param number Optional query handle identifier
337 * @return mixed Array with col values or FALSE on failure
340 function fetch_assoc($res_id=NULL)
342 $result = $this->_get_result($res_id);
343 return $this->_fetch_row($result, MDB2_FETCHMODE_ASSOC);
348 * Get an index array for one row
349 * If no query handle is specified, the last query will be taken as reference
351 * @param number Optional query handle identifier
352 * @return mixed Array with col values or FALSE on failure
355 function fetch_array($res_id=NULL)
357 $result = $this->_get_result($res_id);
358 return $this->_fetch_row($result, MDB2_FETCHMODE_ORDERED);
363 * Get co values for a result row
365 * @param object Query result handle
366 * @param number Fetch mode identifier
367 * @return mixed Array with col values or FALSE on failure
370 function _fetch_row($result, $mode)
372 if (PEAR::isError($result))
374 raise_error(array('code' => 500, 'type' => 'db', 'line' => __LINE__, 'file' => __FILE__,
375 'message' => $this->db_link->getMessage()), TRUE, FALSE);
379 return $result->fetchRow($mode);
384 * Formats input so it can be safely used in a query
386 * @param mixed Value to quote
387 * @return string Quoted/converted string for use in query
390 function quote($input, $type = null)
392 // create DB handle if not available
393 if (!$this->db_handle)
394 $this->db_connect('r');
396 // escape pear identifier chars
397 $rep_chars = array('?' => '\?',
401 return $this->db_handle->quote($input, $type);
406 * Quotes a string so it can be safely used as a table or column name
408 * @param string Value to quote
409 * @return string Quoted string for use in query
410 * @deprecated Replaced by rcube_MDB2::quote_identifier
411 * @see rcube_MDB2::quote_identifier
414 function quoteIdentifier($str)
416 return $this->quote_identifier($str);
421 * Quotes a string so it can be safely used as a table or column name
423 * @param string Value to quote
424 * @return string Quoted string for use in query
427 function quote_identifier($str)
429 if (!$this->db_handle)
430 $this->db_connect('r');
432 return $this->db_handle->quoteIdentifier($str);
438 * @param string The string to be escaped
439 * @return string The escaped string
443 function escapeSimple($str)
445 if (!$this->db_handle)
446 $this->db_connect('r');
448 return $this->db_handle->escape($str);
453 * Return SQL function for current time and date
455 * @return string SQL function to use in query
460 switch($this->db_provider)
472 * Return SQL statement to convert a field value into a unix timestamp
474 * @param string Field name
475 * @return string SQL statement to use in query
478 function unixtimestamp($field)
480 switch($this->db_provider)
483 return "EXTRACT (EPOCH FROM $field)";
487 return "datediff(s, '1970-01-01 00:00:00', $field)";
490 return "UNIX_TIMESTAMP($field)";
496 * Return SQL statement to convert from a unix timestamp
498 * @param string Field name
499 * @return string SQL statement to use in query
502 function fromunixtime($timestamp)
504 switch($this->db_provider)
509 return "FROM_UNIXTIME($timestamp)";
512 return date("'Y-m-d H:i:s'", $timestamp);
518 * Adds a query result and returns a handle ID
520 * @param object Query handle
521 * @return mixed Handle ID or FALE on failure
524 function _add_result($res)
527 if (PEAR::isError($res))
529 raise_error(array('code' => 500, 'type' => 'db', 'line' => __LINE__, 'file' => __FILE__,
530 'message' => $res->getMessage() . " Query: " . substr(preg_replace('/[\r\n]+\s*/', ' ', $res->userinfo), 0, 512)), TRUE, FALSE);
535 $res_id = sizeof($this->a_query_results);
536 $this->a_query_results[$res_id] = $res;
537 $this->last_res_id = $res_id;
544 * Resolves a given handle ID and returns the according query handle
545 * If no ID is specified, the last ressource handle will be returned
547 * @param number Handle ID
548 * @return mixed Ressource handle or FALE on failure
551 function _get_result($res_id=NULL)
554 $res_id = $this->last_res_id;
556 if ($res_id && isset($this->a_query_results[$res_id]))
557 return $this->a_query_results[$res_id];
564 * Create a sqlite database from a file
566 * @param object SQLite database handle
567 * @param string File path to use for DB creation
570 function _sqlite_create_database($dbh, $file_name)
572 if (empty($file_name) || !is_string($file_name))
576 if ($fd = fopen($file_name, 'r'))
578 $data = fread($fd, filesize($file_name));
583 sqlite_exec($dbh->connection, $data);
588 * Add some proprietary database functions to the current SQLite handle
589 * in order to make it MySQL compatible
593 function _sqlite_prepare()
595 include_once('include/rcube_sqlite.inc');
597 // we emulate via callback some missing MySQL function
598 sqlite_create_function($this->db_handle->connection, "from_unixtime", "rcube_sqlite_from_unixtime");
599 sqlite_create_function($this->db_handle->connection, "unix_timestamp", "rcube_sqlite_unix_timestamp");
600 sqlite_create_function($this->db_handle->connection, "now", "rcube_sqlite_now");
601 sqlite_create_function($this->db_handle->connection, "md5", "rcube_sqlite_md5");
605 } // end class rcube_db
608 /* this is our own debug handler for the MDB2 connection */
609 function mdb2_debug_handler(&$db, $scope, $message, $context = array())
611 if ($scope != 'prepare')
613 $debug_output = $scope . '('.$db->db_index.'): ';
614 $debug_output .= $message . $db->getOption('log_line_break');
615 write_log('sqllog', $debug_output);