Thomas Bruederli
2012-11-17 6ddb16d181e285d4f0ef0ef55bdd0ba787f1b583
program/include/rcube_db.php
@@ -1,6 +1,6 @@
<?php
/*
/**
 +-----------------------------------------------------------------------+
 | program/include/rcube_db.php                                          |
 |                                                                       |
@@ -21,28 +21,30 @@
/**
 * Database independent query interface
 * Database independent query interface.
 * This is a wrapper for the PHP PDO.
 *
 * This is a wrapper for the PHP PDO
 *
 * @package    Database
 * @version    1.0
 * @package   Framework
 * @sbpackage Database
 */
class rcube_db
{
    public $db_provider;
    protected $db_dsnw;               // DSN for write operations
    protected $db_dsnr;               // DSN for read operations
    protected $db_connected = false;  // Already connected ?
    protected $db_mode;               // Connection mode
    protected $dbh;                   // Connection handle
    protected $db_error = false;
    protected $db_error_msg = '';
    protected $conn_failure = false;
    protected $db_error        = false;
    protected $db_error_msg    = '';
    protected $conn_failure    = false;
    protected $a_query_results = array('dummy');
    protected $last_res_id = 0;
    protected $last_res_id     = 0;
    protected $db_index        = 0;
    protected $tables;
    protected $db_index = 0;
    protected $variables;
    protected $options = array(
        // column/table quotes
@@ -54,11 +56,11 @@
    /**
     * Factory, returns driver-specific instance of the class
     *
     * @param string $db_dsnw  DSN for read/write operations
     * @param string $db_dsnr  Optional DSN for read only operations
     * @param bool   $pconn    Enables persistent connections
     * @param string $db_dsnw DSN for read/write operations
     * @param string $db_dsnr Optional DSN for read only operations
     * @param bool   $pconn   Enables persistent connections
     *
     * @return rcube_db  Object instance
     * @return rcube_db Object instance
     */
    public static function factory($db_dsnw, $db_dsnr = '', $pconn = false)
    {
@@ -86,9 +88,9 @@
    /**
     * Object constructor
     *
     * @param  string $db_dsnw  DSN for read/write operations
     * @param  string $db_dsnr  Optional DSN for read only operations
     * @param  bool   $pconn    Enables persistent connections
     * @param string $db_dsnw DSN for read/write operations
     * @param string $db_dsnr Optional DSN for read only operations
     * @param bool   $pconn   Enables persistent connections
     */
    public function __construct($db_dsnw, $db_dsnr = '', $pconn = false)
    {
@@ -118,7 +120,7 @@
    /**
     * Connect to specific database
     *
     * @param  array $dsn  DSN for DB connections
     * @param array $dsn DSN for DB connections
     *
     * @return PDO database handle
     */
@@ -137,6 +139,11 @@
        // Connect
        try {
            // with this check we skip fatal error on PDO object creation
            if (!class_exists('PDO', false)) {
                throw new Exception('PDO extension not loaded. See http://php.net/manual/en/intro.pdo.php');
            }
            $this->conn_prepare($dsn);
            $dbh = new PDO($dsn_string, $dsn['username'], $dsn['password'], $dsn_options);
@@ -144,7 +151,7 @@
            // don't throw exceptions or warnings
            $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT);
        }
        catch (PDOException $e) {
        catch (Exception $e) {
            $this->db_error     = true;
            $this->db_error_msg = $e->getMessage();
@@ -163,7 +170,7 @@
    /**
     * Driver-specific preparation of database connection
     *
     * @param  array $dsn  DSN for DB connections
     * @param array $dsn DSN for DB connections
     */
    protected function conn_prepare($dsn)
    {
@@ -172,8 +179,8 @@
    /**
     * Driver-specific configuration of database connection
     *
     * @param  array $dsn  DSN for DB connections
     * @param  PDO   $dbh  Connection handler
     * @param array $dsn DSN for DB connections
     * @param PDO   $dbh Connection handler
     */
    protected function conn_configure($dsn, $dbh)
    {
@@ -182,7 +189,7 @@
    /**
     * Driver-specific database character set setting
     *
     * @param  string $charset  Character set name
     * @param string $charset Character set name
     */
    protected function set_charset($charset)
    {
@@ -190,9 +197,9 @@
    }
    /**
     * Connect to appropiate database depending on the operation
     * Connect to appropriate database depending on the operation
     *
     * @param  string $mode Connection mode (r|w)
     * @param string $mode Connection mode (r|w)
     */
    public function db_connect($mode)
    {
@@ -246,19 +253,37 @@
    }
    /**
     * Writes debug information/query to 'sql' log file
     *
     * @param string $query SQL query
     */
    protected function debug($query)
    {
        if ($this->options['debug_mode']) {
            rcube::write_log('sql', '[' . (++$this->db_index) . '] ' . $query . ';');
        }
    }
    /**
     * Getter for error state
     *
     * @param  boolean  True on error
     * @param int $res_id Optional query result identifier
     *
     * @return string Error message
     */
    public function is_error()
    public function is_error($res_id = null)
    {
        return $this->db_error ? $this->db_error_msg : false;
        if ($res_id !== null) {
            return $this->_get_result($res_id) === false ? $this->db_error_msg : null;
        }
        return $this->db_error ? $this->db_error_msg : null;
    }
    /**
     * Connection state checker
     *
     * @param  boolean  True if in connected state
     * @return boolean True if in connected state
     */
    public function is_connected()
    {
@@ -267,7 +292,8 @@
    /**
     * Is database replication configured?
     * This returns true if dsnw != dsnr
     *
     * @return bool Returns true if dsnw != dsnr
     */
    public function is_replicated()
    {
@@ -275,10 +301,24 @@
    }
    /**
     * Get database runtime variables
     *
     * @param string $varname Variable name
     * @param mixed  $default Default value if variable is not set
     *
     * @return mixed Variable value or default
     */
    public function get_variable($varname, $default = null)
    {
        // to be implemented by driver class
        return $default;
    }
    /**
     * Execute a SQL query
     *
     * @param  string  SQL query to execute
     * @param  mixed   Values to be inserted in query
     * @param string SQL query to execute
     * @param mixed  Values to be inserted in query
     *
     * @return number  Query handle identifier
     */
@@ -298,12 +338,12 @@
    /**
     * Execute a SQL query with limits
     *
     * @param  string  SQL query to execute
     * @param  number  Offset for LIMIT statement
     * @param  number  Number of rows for LIMIT statement
     * @param  mixed   Values to be inserted in query
     * @param string SQL query to execute
     * @param int    Offset for LIMIT statement
     * @param int    Number of rows for LIMIT statement
     * @param mixed  Values to be inserted in query
     *
     * @return number  Query handle identifier
     * @return int Query handle identifier
     */
    public function limitquery()
    {
@@ -318,16 +358,17 @@
    /**
     * Execute a SQL query with limits
     *
     * @param  string $query   SQL query to execute
     * @param  number $offset  Offset for LIMIT statement
     * @param  number $numrows Number of rows for LIMIT statement
     * @param  array  $params  Values to be inserted in query
     * @return number  Query handle identifier
     * @param string $query   SQL query to execute
     * @param int    $offset  Offset for LIMIT statement
     * @param int    $numrows Number of rows for LIMIT statement
     * @param array  $params  Values to be inserted in query
     *
     * @return int Query handle identifier
     */
    protected function _query($query, $offset, $numrows, $params)
    {
        // Read or write ?
        $mode = preg_match('/^select/i', ltrim($query)) ? 'r' : 'w';
        $mode = preg_match('/^(select|show)/i', ltrim($query)) ? 'r' : 'w';
        $this->db_connect($mode);
@@ -348,17 +389,21 @@
        $idx = 0;
        while ($pos = strpos($query, '?', $pos)) {
            $val = $this->quote($params[$idx++]);
            unset($params[$idx-1]);
            $query = substr_replace($query, $val, $pos, 1);
            $pos += strlen($val);
            if ($query[$pos+1] == '?') {  // skip escaped ?
                $pos += 2;
            }
            else {
                $val = $this->quote($params[$idx++]);
                unset($params[$idx-1]);
                $query = substr_replace($query, $val, $pos, 1);
                $pos += strlen($val);
            }
        }
        $query = rtrim($query, ';');
        // replace escaped ? back to normal
        $query = rtrim(strtr($query, array('??' => '?')), ';');
        if ($this->options['debug_mode']) {
            rcube::write_log('sql', '[' . (++$this->db_index) . '] ' . $query . ';');
        }
        $this->debug($query);
        $query = $this->dbh->query($query);
@@ -380,7 +425,8 @@
     * Get number of affected rows for the last query
     *
     * @param  number $res_id Optional query handle identifier
     * @return mixed   Number of rows or false on failure
     *
     * @return int Number of rows or false on failure
     */
    public function affected_rows($res_id = null)
    {
@@ -393,11 +439,10 @@
    /**
     * Get last inserted record ID
     * For Postgres databases, a sequence name is required
     *
     * @param  string $table  Table name (to find the incremented sequence)
     * @param string $table Table name (to find the incremented sequence)
     *
     * @return mixed   ID or false on failure
     * @return mixed ID or false on failure
     */
    public function insert_id($table = '')
    {
@@ -419,9 +464,9 @@
     * Get an associative array for one row
     * If no query handle is specified, the last query will be taken as reference
     *
     * @param  number $res_id Optional query handle identifier
     * @param int $res_id Optional query handle identifier
     *
     * @return mixed   Array with col values or false on failure
     * @return mixed Array with col values or false on failure
     */
    public function fetch_assoc($res_id = null)
    {
@@ -433,9 +478,9 @@
     * Get an index array for one row
     * If no query handle is specified, the last query will be taken as reference
     *
     * @param  number $res_id  Optional query handle identifier
     * @param int $res_id Optional query handle identifier
     *
     * @return mixed   Array with col values or false on failure
     * @return mixed Array with col values or false on failure
     */
    public function fetch_array($res_id = null)
    {
@@ -446,10 +491,10 @@
    /**
     * Get col values for a result row
     *
     * @param  PDOStatement $result Result handle
     * @param  number       $mode   Fetch mode identifier
     * @param PDOStatement $result Result handle
     * @param int          $mode   Fetch mode identifier
     *
     * @return mixed  Array with col values or false on failure
     * @return mixed Array with col values or false on failure
     */
    protected function _fetch_row($result, $mode)
    {
@@ -463,6 +508,11 @@
    /**
     * Adds LIMIT,OFFSET clauses to the query
     *
     * @param string $query  SQL query
     * @param int    $limit  Number of rows
     * @param int    $offset Offset
     *
     * @return string SQL query
     */
    protected function set_limit($query, $limit = 0, $offset = 0)
    {
@@ -502,7 +552,7 @@
    /**
     * Returns list of columns in database table
     *
     * @param string Table name
     * @param string $table Table name
     *
     * @return array List of table cols
     */
@@ -521,16 +571,20 @@
    /**
     * Formats input so it can be safely used in a query
     *
     * @param  mixed  $input  Value to quote
     * @param  string $type   Type of data
     * @param mixed  $input Value to quote
     * @param string $type  Type of data
     *
     * @return string  Quoted/converted string for use in query
     * @return string Quoted/converted string for use in query
     */
    public function quote($input, $type = null)
    {
        // handle int directly for better performance
        if ($type == 'integer' || $type == 'int') {
            return intval($input);
        }
        if (is_null($input)) {
            return 'NULL';
        }
        // create DB handle if not available
@@ -544,7 +598,7 @@
                'integer' => PDO::PARAM_INT,
            );
            $type = isset($map[$type]) ? $map[$type] : PDO::PARAM_STR;
            return $this->dbh->quote($input, $type);
            return strtr($this->dbh->quote($input, $type), array('?' => '??'));  // escape ?
        }
        return 'NULL';
@@ -553,11 +607,11 @@
    /**
     * Quotes a string so it can be safely used as a table or column name
     *
     * @param  string $str Value to quote
     * @param string $str Value to quote
     *
     * @return string  Quoted string for use in query
     * @deprecated     Replaced by rcube_db::quote_identifier
     * @see            rcube_db::quote_identifier
     * @return string Quoted string for use in query
     * @deprecated    Replaced by rcube_db::quote_identifier
     * @see           rcube_db::quote_identifier
     */
    public function quoteIdentifier($str)
    {
@@ -567,9 +621,9 @@
    /**
     * Quotes a string so it can be safely used as a table or column name
     *
     * @param  string $str Value to quote
     * @param string $str Value to quote
     *
     * @return string  Quoted string for use in query
     * @return string Quoted string for use in query
     */
    public function quote_identifier($str)
    {
@@ -598,8 +652,8 @@
    /**
     * Return list of elements for use with SQL's IN clause
     *
     * @param  array  $arr  Input array
     * @param  string $type Type of data
     * @param array  $arr  Input array
     * @param string $type Type of data
     *
     * @return string Comma-separated list of quoted values for use in query
     */
@@ -622,7 +676,7 @@
     * This method is deprecated and should not be used anymore due to limitations
     * of timestamp functions in Mysql (year 2038 problem)
     *
     * @param  string $field Field name
     * @param string $field Field name
     *
     * @return string  SQL statement to use in query
     * @deprecated
@@ -635,9 +689,9 @@
    /**
     * Return SQL statement to convert from a unix timestamp
     *
     * @param  string $timestamp Field name
     * @param int $timestamp Unix timestamp
     *
     * @return string  SQL statement to use in query
     * @return string Date string in db-specific format
     */
    public function fromunixtime($timestamp)
    {
@@ -647,10 +701,10 @@
    /**
     * Return SQL statement for case insensitive LIKE
     *
     * @param  string $column  Field name
     * @param  string $value   Search value
     * @param string $column Field name
     * @param string $value  Search value
     *
     * @return string  SQL statement to use in query
     * @return string SQL statement to use in query
     */
    public function ilike($column, $value)
    {
@@ -675,9 +729,9 @@
    /**
     * Encodes non-UTF-8 characters in string/array/object (recursive)
     *
     * @param  mixed  $input Data to fix
     * @param mixed $input Data to fix
     *
     * @return mixed  Properly UTF-8 encoded data
     * @return mixed Properly UTF-8 encoded data
     */
    public static function encode($input)
    {
@@ -700,9 +754,9 @@
    /**
     * Decodes encoded UTF-8 string/object/array (recursive)
     *
     * @param  mixed $input Input data
     * @param mixed $input Input data
     *
     * @return mixed  Decoded data
     * @return mixed Decoded data
     */
    public static function decode($input)
    {
@@ -725,26 +779,25 @@
    /**
     * Adds a query result and returns a handle ID
     *
     * @param  object $res Query handle
     * @param object $res Query handle
     *
     * @return mixed   Handle ID
     * @return int Handle ID
     */
    protected function _add_result($res)
    {
        $res_id = sizeof($this->a_query_results);
        $this->last_res_id = $res_id;
        $this->a_query_results[$res_id] = $res;
        $this->last_res_id = sizeof($this->a_query_results);
        $this->a_query_results[$this->last_res_id] = $res;
        return $res_id;
        return $this->last_res_id;
    }
    /**
     * Resolves a given handle ID and returns the according query handle
     * If no ID is specified, the last resource handle will be returned
     *
     * @param  number $res_id Handle ID
     * @param int $res_id Handle ID
     *
     * @return mixed   Resource handle or false on failure
     * @return mixed Resource handle or false on failure
     */
    protected function _get_result($res_id = null)
    {
@@ -781,28 +834,6 @@
    }
    /**
     * Return correct name for a specific database sequence
     * (used for Postgres only)
     *
     * @param string $sequence Secuence name
     *
     * @return string Translated sequence name
     */
    public function sequence_name($sequence)
    {
        $rcube = rcube::get_instance();
        // return sequence name if configured
        $config_key = 'db_sequence_'.$sequence;
        if ($name = $rcube->config->get($config_key)) {
            return $name;
        }
        return $sequence;
    }
    /**
     * MDB2 DSN string parser
     *
     * @param string $sequence Secuence name
@@ -819,7 +850,8 @@
        if (($pos = strpos($dsn, '://')) !== false) {
            $str = substr($dsn, 0, $pos);
            $dsn = substr($dsn, $pos + 3);
        } else {
        }
        else {
            $str = $dsn;
            $dsn = null;
        }
@@ -829,7 +861,8 @@
        if (preg_match('|^(.+?)\((.*?)\)$|', $str, $arr)) {
            $parsed['phptype']  = $arr[1];
            $parsed['dbsyntax'] = !$arr[2] ? $arr[1] : $arr[2];
        } else {
        }
        else {
            $parsed['phptype']  = $str;
            $parsed['dbsyntax'] = $str;
        }
@@ -846,7 +879,8 @@
            if (($pos = strpos($str, ':')) !== false) {
                $parsed['username'] = rawurldecode(substr($str, 0, $pos));
                $parsed['password'] = rawurldecode(substr($str, $pos + 1));
            } else {
            }
            else {
                $parsed['username'] = rawurldecode($str);
            }
        }
@@ -875,9 +909,11 @@
                $pos = strrpos($proto_opts, '/');
                $dsn = substr($proto_opts, $pos + 1);
                $proto_opts = substr($proto_opts, 0, $pos);
            } elseif (strpos($dsn, '/') !== false) {
            }
            else if (strpos($dsn, '/') !== false) {
                list($proto_opts, $dsn) = explode('/', $dsn, 2);
            } else {
            }
            else {
                $proto_opts = $dsn;
                $dsn = null;
            }
@@ -909,7 +945,8 @@
                $dsn = substr($dsn, $pos + 1);
                if (strpos($dsn, '&') !== false) {
                    $opts = explode('&', $dsn);
                } else { // database?param1=value1
                }
                else { // database?param1=value1
                    $opts = array($dsn);
                }
                foreach ($opts as $opt) {
@@ -928,7 +965,7 @@
    /**
     * Returns PDO DSN string from DSN array
     *
     * @param array $dsn  DSN parameters
     * @param array $dsn DSN parameters
     *
     * @return string DSN string
     */
@@ -959,7 +996,7 @@
    /**
     * Returns driver-specific connection options
     *
     * @param array  $dsn  DSN parameters
     * @param array $dsn DSN parameters
     *
     * @return array Connection options
     */