4 +-----------------------------------------------------------------------+
5 | program/include/rcube_mdb2.php |
7 | This file is part of the RoundCube Webmail client |
8 | Copyright (C) 2005-2008, 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 1390 2008-05-15 11:15:58Z 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 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 * PHP 4 object constructor
74 * @see rcube_mdb2::__construct
76 function rcube_db($db_dsnw,$db_dsnr='')
78 $this->__construct($db_dsnw,$db_dsnr);
83 * Connect to specific database
85 * @param string DSN for DB connections
86 * @return object PEAR database handle
89 function dsn_connect($dsn)
91 // Use persistent connections if available
92 $dbh = MDB2::connect($dsn, array(
93 'persistent' => $this->db_pconn,
94 'emulate_prepared' => $this->debug_mode,
95 'debug' => $this->debug_mode,
96 'debug_handler' => 'mdb2_debug_handler',
97 'portability' => MDB2_PORTABILITY_ALL ^ MDB2_PORTABILITY_EMPTY_TO_NULL));
99 if (MDB2::isError($dbh))
101 $this->db_error = TRUE;
102 $this->db_error_msg = $dbh->getMessage();
104 raise_error(array('code' => 500, 'type' => 'db', 'line' => __LINE__,
105 'file' => __FILE__, 'message' => $dbh->getUserInfo()), TRUE, FALSE);
107 else if ($this->db_provider=='sqlite')
109 $dsn_array = MDB2::parseDSN($dsn);
110 if (!filesize($dsn_array['database']) && !empty($this->sqlite_initials))
111 $this->_sqlite_create_database($dbh, $this->sqlite_initials);
114 $dbh->setCharset('utf8');
121 * Connect to appropiate databse
122 * depending on the operation
124 * @param string Connection mode (r|w)
127 function db_connect($mode)
129 $this->db_mode = $mode;
132 if ($this->db_connected)
134 // no replication, current connection is ok
135 if ($this->db_dsnw==$this->db_dsnr)
138 // connected to master, current connection is ok
139 if ($this->db_mode=='w')
142 // Same mode, current connection is ok
143 if ($this->db_mode==$mode)
148 $dsn = $this->db_dsnr;
150 $dsn = $this->db_dsnw;
152 $this->db_handle = $this->dsn_connect($dsn);
153 $this->db_connected = true;
158 * Activate/deactivate debug mode
160 * @param boolean True if SQL queries should be logged
162 function set_debug($dbg = true)
164 $this->debug_mode = $dbg;
165 if ($this->db_connected)
167 $this->db_handle->setOption('debug', $dbg);
168 $this->db_handle->setOption('emulate_prepared', $dbg);
174 * Getter for error state
176 * @param boolean True on error
180 return $this->db_error ? $this->db_error_msg : FALSE;
185 * Execute a SQL query
187 * @param string SQL query to execute
188 * @param mixed Values to be inserted in query
189 * @return number Query handle identifier
194 $params = func_get_args();
195 $query = array_shift($params);
197 return $this->_query($query, 0, 0, $params);
202 * Execute a SQL query with limits
204 * @param string SQL query to execute
205 * @param number Offset for LIMIT statement
206 * @param number Number of rows for LIMIT statement
207 * @param mixed Values to be inserted in query
208 * @return number Query handle identifier
211 function limitquery()
213 $params = func_get_args();
214 $query = array_shift($params);
215 $offset = array_shift($params);
216 $numrows = array_shift($params);
218 return $this->_query($query, $offset, $numrows, $params);
223 * Execute a SQL query with limits
225 * @param string SQL query to execute
226 * @param number Offset for LIMIT statement
227 * @param number Number of rows for LIMIT statement
228 * @param array Values to be inserted in query
229 * @return number Query handle identifier
232 function _query($query, $offset, $numrows, $params)
235 if (strtolower(trim(substr($query,0,6)))=='select')
240 $this->db_connect($mode);
242 if ($this->db_provider == 'sqlite')
243 $this->_sqlite_prepare();
245 if ($numrows || $offset)
246 $result = $this->db_handle->setLimit($numrows,$offset);
249 $result = $this->db_handle->query($query);
252 $params = (array)$params;
253 $q = $this->db_handle->prepare($query);
254 if ($this->db_handle->isError($q))
256 $this->db_error = TRUE;
257 $this->db_error_msg = $q->userinfo;
259 raise_error(array('code' => 500, 'type' => 'db', 'line' => __LINE__, 'file' => __FILE__,
260 'message' => $this->db_error_msg), TRUE, TRUE);
264 $result = $q->execute($params);
269 // add result, even if it's an error
270 return $this->_add_result($result);
275 * Get number of rows for a SQL query
276 * If no query handle is specified, the last query will be taken as reference
278 * @param number Optional query handle identifier
279 * @return mixed Number of rows or FALSE on failure
282 function num_rows($res_id=NULL)
284 if (!$this->db_handle)
287 if ($result = $this->_get_result($res_id))
288 return $result->numRows();
295 * Get number of affected rows fort he last query
297 * @return mixed Number of rows or FALSE on failure
300 function affected_rows($result = null)
302 if (!$this->db_handle)
305 return $this->_get_result($result);
310 * Get last inserted record ID
311 * For Postgres databases, a sequence name is required
313 * @param string Sequence name for increment
314 * @return mixed ID or FALSE on failure
317 function insert_id($sequence = '')
319 if (!$this->db_handle || $this->db_mode=='r')
322 return $this->db_handle->lastInsertID($sequence);
327 * Get an associative array for one row
328 * If no query handle is specified, the last query will be taken as reference
330 * @param number Optional query handle identifier
331 * @return mixed Array with col values or FALSE on failure
334 function fetch_assoc($res_id=NULL)
336 $result = $this->_get_result($res_id);
337 return $this->_fetch_row($result, MDB2_FETCHMODE_ASSOC);
342 * Get an index array for one row
343 * If no query handle is specified, the last query will be taken as reference
345 * @param number Optional query handle identifier
346 * @return mixed Array with col values or FALSE on failure
349 function fetch_array($res_id=NULL)
351 $result = $this->_get_result($res_id);
352 return $this->_fetch_row($result, MDB2_FETCHMODE_ORDERED);
357 * Get co values for a result row
359 * @param object Query result handle
360 * @param number Fetch mode identifier
361 * @return mixed Array with col values or FALSE on failure
364 function _fetch_row($result, $mode)
366 if (PEAR::isError($result))
368 raise_error(array('code' => 500, 'type' => 'db', 'line' => __LINE__, 'file' => __FILE__,
369 'message' => $this->db_link->getMessage()), TRUE, FALSE);
373 return $result->fetchRow($mode);
378 * Formats input so it can be safely used in a query
380 * @param mixed Value to quote
381 * @return string Quoted/converted string for use in query
384 function quote($input, $type = null)
386 // create DB handle if not available
387 if (!$this->db_handle)
388 $this->db_connect('r');
390 // escape pear identifier chars
391 $rep_chars = array('?' => '\?',
395 return $this->db_handle->quote($input, $type);
400 * Quotes a string so it can be safely used as a table or column name
402 * @param string Value to quote
403 * @return string Quoted string for use in query
404 * @deprecated Replaced by rcube_MDB2::quote_identifier
405 * @see rcube_MDB2::quote_identifier
408 function quoteIdentifier($str)
410 return $this->quote_identifier($str);
415 * Quotes a string so it can be safely used as a table or column name
417 * @param string Value to quote
418 * @return string Quoted string for use in query
421 function quote_identifier($str)
423 if (!$this->db_handle)
424 $this->db_connect('r');
426 return $this->db_handle->quoteIdentifier($str);
432 * @param string The string to be escaped
433 * @return string The escaped string
437 function escapeSimple($str)
439 if (!$this->db_handle)
440 $this->db_connect('r');
442 return $this->db_handle->escape($str);
447 * Return SQL function for current time and date
449 * @return string SQL function to use in query
454 switch($this->db_provider)
466 * Return SQL statement to convert a field value into a unix timestamp
468 * @param string Field name
469 * @return string SQL statement to use in query
472 function unixtimestamp($field)
474 switch($this->db_provider)
477 return "EXTRACT (EPOCH FROM $field)";
481 return "datediff(s, '1970-01-01 00:00:00', $field)";
484 return "UNIX_TIMESTAMP($field)";
490 * Return SQL statement to convert from a unix timestamp
492 * @param string Field name
493 * @return string SQL statement to use in query
496 function fromunixtime($timestamp)
498 switch($this->db_provider)
503 return sprintf("FROM_UNIXTIME(%d)", $timestamp);
506 return date("'Y-m-d H:i:s'", $timestamp);
512 * Adds a query result and returns a handle ID
514 * @param object Query handle
515 * @return mixed Handle ID or FALE on failure
518 function _add_result($res)
521 if (PEAR::isError($res))
523 raise_error(array('code' => 500, 'type' => 'db', 'line' => __LINE__, 'file' => __FILE__,
524 'message' => $res->getMessage() . " Query: " . substr(preg_replace('/[\r\n]+\s*/', ' ', $res->userinfo), 0, 512)), TRUE, FALSE);
529 $res_id = sizeof($this->a_query_results);
530 $this->a_query_results[$res_id] = $res;
531 $this->last_res_id = $res_id;
538 * Resolves a given handle ID and returns the according query handle
539 * If no ID is specified, the last ressource handle will be returned
541 * @param number Handle ID
542 * @return mixed Ressource handle or FALE on failure
545 function _get_result($res_id=NULL)
548 $res_id = $this->last_res_id;
550 if ($res_id && isset($this->a_query_results[$res_id]))
551 return $this->a_query_results[$res_id];
558 * Create a sqlite database from a file
560 * @param object SQLite database handle
561 * @param string File path to use for DB creation
564 function _sqlite_create_database($dbh, $file_name)
566 if (empty($file_name) || !is_string($file_name))
570 if ($fd = fopen($file_name, 'r'))
572 $data = fread($fd, filesize($file_name));
577 sqlite_exec($dbh->connection, $data);
582 * Add some proprietary database functions to the current SQLite handle
583 * in order to make it MySQL compatible
587 function _sqlite_prepare()
589 include_once('include/rcube_sqlite.inc');
591 // we emulate via callback some missing MySQL function
592 sqlite_create_function($this->db_handle->connection, "from_unixtime", "rcube_sqlite_from_unixtime");
593 sqlite_create_function($this->db_handle->connection, "unix_timestamp", "rcube_sqlite_unix_timestamp");
594 sqlite_create_function($this->db_handle->connection, "now", "rcube_sqlite_now");
595 sqlite_create_function($this->db_handle->connection, "md5", "rcube_sqlite_md5");
599 } // end class rcube_db
602 /* this is our own debug handler for the MDB2 connection */
603 function mdb2_debug_handler(&$db, $scope, $message, $context = array())
605 if ($scope != 'prepare')
607 $debug_output = $scope . '('.$db->db_index.'): ';
608 $debug_output .= $message . $db->getOption('log_line_break');
609 write_log('sqllog', $debug_output);