4 +-----------------------------------------------------------------------+
5 | program/include/rcube_mdb2.inc |
7 | This file is part of the RoundCube Webmail client |
8 | Copyright (C) 2005, 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 420 2006-12-20 14:07:46Z 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
35 * @package RoundCube Webmail
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 = '';
52 var $a_query_results = array('dummy');
59 * @param string DSN for read/write operations
60 * @param string Optional DSN for read only operations
62 function __construct($db_dsnw, $db_dsnr='', $pconn=false)
67 $this->db_dsnw = $db_dsnw;
68 $this->db_dsnr = $db_dsnr;
69 $this->db_pconn = $pconn;
71 $dsn_array = MDB2::parseDSN($db_dsnw);
72 $this->db_provider = $dsn_array['phptype'];
77 * PHP 4 object constructor
79 * @see rcube_MDB2::__construct
81 function rcube_db($db_dsnw,$db_dsnr='')
83 $this->__construct($db_dsnw,$db_dsnr);
88 * Connect to specific database
90 * @param string DSN for DB connections
91 * @return object PEAR database handle
94 function dsn_connect($dsn)
96 // Use persistent connections if available
97 $dbh = MDB2::connect($dsn, array('persistent' => $this->db_pconn, 'portability' => MDB2_PORTABILITY_ALL ^ MDB2_PORTABILITY_EMPTY_TO_NULL));
99 if (PEAR::isError($dbh))
101 $this->db_error = TRUE;
102 $this->db_error_msg = $dbh->getMessage();
104 raise_error(array('code' => 500, 'type' => 'db', 'line' => __LINE__, 'file' => __FILE__,
105 'message' => $dbh->getMessage()), 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;
159 * Getter for error state
161 * @param boolean True on error
165 return $this->db_error ? $this->db_error_msg : FALSE;
170 * Execute a SQL query
172 * @param string SQL query to execute
173 * @param mixed Values to be inserted in query
174 * @return number Query handle identifier
179 $params = func_get_args();
180 $query = array_shift($params);
182 return $this->_query($query, 0, 0, $params);
187 * Execute a SQL query with limits
189 * @param string SQL query to execute
190 * @param number Offset for LIMIT statement
191 * @param number Number of rows for LIMIT statement
192 * @param mixed Values to be inserted in query
193 * @return number Query handle identifier
196 function limitquery()
198 $params = func_get_args();
199 $query = array_shift($params);
200 $offset = array_shift($params);
201 $numrows = array_shift($params);
203 return $this->_query($query, $offset, $numrows, $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 array Values to be inserted in query
214 * @return number Query handle identifier
217 function _query($query, $offset, $numrows, $params)
220 if (strtolower(trim(substr($query,0,6)))=='select')
225 $this->db_connect($mode);
227 if ($this->db_provider == 'sqlite')
228 $this->_sqlite_prepare();
230 if ($numrows || $offset)
231 $result = $this->db_handle->setLimit($numrows,$offset);
234 $result = $this->db_handle->query($query);
237 $params = (array)$params;
238 $q = $this->db_handle->prepare($query);
239 if ($this->db_handle->isError($q))
241 $this->db_error = TRUE;
242 $this->db_error_msg = $q->userinfo;
244 raise_error(array('code' => 500, 'type' => 'db', 'line' => __LINE__, 'file' => __FILE__,
245 'message' => $this->db_error_msg), TRUE, TRUE);
249 $result = $q->execute($params);
254 // add result, even if it's an error
255 return $this->_add_result($result);
260 * Get number of rows for a SQL query
261 * If no query handle is specified, the last query will be taken as reference
263 * @param number Optional query handle identifier
264 * @return mixed Number of rows or FALSE on failure
267 function num_rows($res_id=NULL)
269 if (!$this->db_handle)
272 if ($result = $this->_get_result($res_id))
273 return $result->numRows();
280 * Get number of affected rows fort he last query
282 * @return mixed Number of rows or FALSE on failure
285 function affected_rows($result = null)
287 if (!$this->db_handle)
290 return $this->_get_result($result);
295 * Get last inserted record ID
296 * For Postgres databases, a sequence name is required
298 * @param string Sequence name for increment
299 * @return mixed ID or FALSE on failure
302 function insert_id($sequence = '')
304 if (!$this->db_handle || $this->db_mode=='r')
307 return $this->db_handle->lastInsertID($sequence);
312 * Get an associative array for one row
313 * If no query handle is specified, the last query will be taken as reference
315 * @param number Optional query handle identifier
316 * @return mixed Array with col values or FALSE on failure
319 function fetch_assoc($res_id=NULL)
321 $result = $this->_get_result($res_id);
322 return $this->_fetch_row($result, MDB2_FETCHMODE_ASSOC);
327 * Get an index 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_array($res_id=NULL)
336 $result = $this->_get_result($res_id);
337 return $this->_fetch_row($result, MDB2_FETCHMODE_ORDERED);
342 * Get co values for a result row
344 * @param object Query result handle
345 * @param number Fetch mode identifier
346 * @return mixed Array with col values or FALSE on failure
349 function _fetch_row($result, $mode)
351 if (PEAR::isError($result))
353 raise_error(array('code' => 500, 'type' => 'db', 'line' => __LINE__, 'file' => __FILE__,
354 'message' => $this->db_link->getMessage()), TRUE, FALSE);
358 return $result->fetchRow($mode);
363 * Formats input so it can be safely used in a query
365 * @param mixed Value to quote
366 * @return string Quoted/converted string for use in query
369 function quote($input, $type = null)
371 // create DB handle if not available
372 if (!$this->db_handle)
373 $this->db_connect('r');
375 // escape pear identifier chars
376 $rep_chars = array('?' => '\?',
380 return $this->db_handle->quote($input, $type);
385 * Quotes a string so it can be safely used as a table or column name
387 * @param string Value to quote
388 * @return string Quoted string for use in query
389 * @deprecated Replaced by rcube_MDB2::quote_identifier
390 * @see rcube_MDB2::quote_identifier
393 function quoteIdentifier($str)
395 return $this->quote_identifier($str);
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
406 function quote_identifier($str)
408 if (!$this->db_handle)
409 $this->db_connect('r');
411 return $this->db_handle->quoteIdentifier($str);
416 * Return SQL function for current time and date
418 * @return string SQL function to use in query
423 switch($this->db_provider)
435 * Return SQL statement to convert a field value into a unix timestamp
437 * @param string Field name
438 * @return string SQL statement to use in query
441 function unixtimestamp($field)
443 switch($this->db_provider)
446 return "EXTRACT (EPOCH FROM $field)";
450 return "datediff(s, '1970-01-01 00:00:00', $field)";
453 return "UNIX_TIMESTAMP($field)";
459 * Return SQL statement to convert from a unix timestamp
461 * @param string Field name
462 * @return string SQL statement to use in query
465 function fromunixtime($timestamp)
467 switch($this->db_provider)
472 return "FROM_UNIXTIME($timestamp)";
475 return date("'Y-m-d H:i:s'", $timestamp);
481 * Adds a query result and returns a handle ID
483 * @param object Query handle
484 * @return mixed Handle ID or FALE on failure
487 function _add_result($res)
490 if (PEAR::isError($res))
492 raise_error(array('code' => 500, 'type' => 'db', 'line' => __LINE__, 'file' => __FILE__,
493 'message' => $res->getMessage() . " Query: " . substr(preg_replace('/[\r\n]+\s*/', ' ', $res->userinfo), 0, 512)), TRUE, FALSE);
498 $res_id = sizeof($this->a_query_results);
499 $this->a_query_results[$res_id] = $res;
500 $this->last_res_id = $res_id;
507 * Resolves a given handle ID and returns the according query handle
508 * If no ID is specified, the last ressource handle will be returned
510 * @param number Handle ID
511 * @return mixed Ressource handle or FALE on failure
514 function _get_result($res_id=NULL)
517 $res_id = $this->last_res_id;
519 if ($res_id && isset($this->a_query_results[$res_id]))
520 return $this->a_query_results[$res_id];
527 * Create a sqlite database from a file
529 * @param object SQLite database handle
530 * @param string File path to use for DB creation
533 function _sqlite_create_database($dbh, $file_name)
535 if (empty($file_name) || !is_string($file_name))
539 if ($fd = fopen($file_name, 'r'))
541 $data = fread($fd, filesize($file_name));
546 sqlite_exec($dbh->connection, $data);
551 * Add some proprietary database functions to the current SQLite handle
552 * in order to make it MySQL compatible
556 function _sqlite_prepare()
558 include_once('include/rcube_sqlite.inc');
560 // we emulate via callback some missing MySQL function
561 sqlite_create_function($this->db_handle->connection, "from_unixtime", "rcube_sqlite_from_unixtime");
562 sqlite_create_function($this->db_handle->connection, "unix_timestamp", "rcube_sqlite_unix_timestamp");
563 sqlite_create_function($this->db_handle->connection, "now", "rcube_sqlite_now");
564 sqlite_create_function($this->db_handle->connection, "md5", "rcube_sqlite_md5");
568 } // end class rcube_db