source: subversion/branches/devel-framework/roundcubemail/program/include/rcube_mdb2.php

Last change on this file was 5881, checked in by thomasb, 15 months ago

Split rcmail functionality into rcube base class (framework) and keep application specific stuff in rcmail

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 24.0 KB
Line 
1<?php
2
3/*
4 +-----------------------------------------------------------------------+
5 | program/include/rcube_mdb2.php                                        |
6 |                                                                       |
7 | This file is part of the Roundcube Webmail client                     |
8 | Copyright (C) 2005-2009, The Roundcube Dev Team                       |
9 | Licensed under the GNU GPL                                            |
10 |                                                                       |
11 | PURPOSE:                                                              |
12 |   PEAR:DB wrapper class that implements PEAR MDB2 functions           |
13 |   See http://pear.php.net/package/MDB2                                |
14 |                                                                       |
15 +-----------------------------------------------------------------------+
16 | Author: Lukas Kahwe Smith <smith@pooteeweet.org>                      |
17 +-----------------------------------------------------------------------+
18
19 $Id$
20
21*/
22
23
24/**
25 * Database independent query interface
26 *
27 * This is a wrapper for the PEAR::MDB2 class
28 *
29 * @package    Database
30 * @author     David Saez Padros <david@ols.es>
31 * @author     Thomas Bruederli <roundcube@gmail.com>
32 * @author     Lukas Kahwe Smith <smith@pooteeweet.org>
33 * @version    1.18
34 * @link       http://pear.php.net/package/MDB2
35 */
36class rcube_mdb2
37{
38    public $db_dsnw;               // DSN for write operations
39    public $db_dsnr;               // DSN for read operations
40    public $db_connected = false;  // Already connected ?
41    public $db_mode = '';          // Connection mode
42    public $db_handle = 0;         // Connection handle
43    public $db_error = false;
44    public $db_error_msg = '';
45
46    private $debug_mode = false;
47    private $conn_failure = false;
48    private $a_query_results = array('dummy');
49    private $last_res_id = 0;
50    private $tables;
51
52
53    /**
54     * Object constructor
55     *
56     * @param  string $db_dsnw DSN for read/write operations
57     * @param  string $db_dsnr Optional DSN for read only operations
58     */
59    public function __construct($db_dsnw, $db_dsnr='', $pconn=false)
60    {
61        if (empty($db_dsnr)) {
62            $db_dsnr = $db_dsnw;
63        }
64
65        $this->db_dsnw = $db_dsnw;
66        $this->db_dsnr = $db_dsnr;
67        $this->db_pconn = $pconn;
68
69        $dsn_array = MDB2::parseDSN($db_dsnw);
70        $this->db_provider = $dsn_array['phptype'];
71    }
72
73
74    /**
75     * Connect to specific database
76     *
77     * @param  string $dsn  DSN for DB connections
78     * @return MDB2 PEAR database handle
79     * @access private
80     */
81    private function dsn_connect($dsn)
82    {
83        // Use persistent connections if available
84        $db_options = array(
85            'persistent'       => $this->db_pconn,
86            'emulate_prepared' => $this->debug_mode,
87            'debug'            => $this->debug_mode,
88            'debug_handler'    => array($this, 'debug_handler'),
89            'portability'      => MDB2_PORTABILITY_ALL ^ MDB2_PORTABILITY_EMPTY_TO_NULL,
90        );
91
92        if ($this->db_provider == 'pgsql') {
93            $db_options['disable_smart_seqname'] = true;
94            $db_options['seqname_format'] = '%s';
95        }
96        $this->db_error     = false;
97        $this->db_error_msg = null;
98
99        $dbh = MDB2::connect($dsn, $db_options);
100
101        if (MDB2::isError($dbh)) {
102            $this->db_error = true;
103            $this->db_error_msg = $dbh->getMessage();
104
105            rcube::raise_error(array('code' => 500, 'type' => 'db',
106                'line' => __LINE__, 'file' => __FILE__,
107                'message' => $dbh->getUserInfo()), true, false);
108        }
109        else if ($this->db_provider == 'sqlite') {
110            $dsn_array = MDB2::parseDSN($dsn);
111            if (!filesize($dsn_array['database']) && !empty($this->sqlite_initials)) {
112                $this->sqlite_create_database($dbh, $this->sqlite_initials);
113            }
114        }
115        else if ($this->db_provider != 'mssql' && $this->db_provider != 'sqlsrv') {
116            $dbh->setCharset('utf8');
117        }
118
119        return $dbh;
120    }
121
122
123    /**
124     * Connect to appropiate database depending on the operation
125     *
126     * @param  string $mode Connection mode (r|w)
127     */
128    public function db_connect($mode)
129    {
130        // previous connection failed, don't attempt to connect again
131        if ($this->conn_failure) {
132            return;
133        }
134
135        // no replication
136        if ($this->db_dsnw == $this->db_dsnr) {
137            $mode = 'w';
138        }
139
140        // Already connected
141        if ($this->db_connected) {
142            // connected to db with the same or "higher" mode
143            if ($this->db_mode == 'w' || $this->db_mode == $mode) {
144                return;
145            }
146        }
147
148        $dsn = ($mode == 'r') ? $this->db_dsnr : $this->db_dsnw;
149
150        $this->db_handle    = $this->dsn_connect($dsn);
151        $this->db_connected = !PEAR::isError($this->db_handle);
152
153        // use write-master when read-only fails
154        if (!$this->db_connected && $mode == 'r') {
155            $mode = 'w';
156            $this->db_handle    = $this->dsn_connect($this->db_dsnw);
157            $this->db_connected = !PEAR::isError($this->db_handle);
158        }
159
160        if ($this->db_connected) {
161            $this->db_mode = $mode;
162        }
163        else {
164            $this->conn_failure = true;
165        }
166    }
167
168
169    /**
170     * Activate/deactivate debug mode
171     *
172     * @param boolean $dbg True if SQL queries should be logged
173     */
174    public function set_debug($dbg = true)
175    {
176        $this->debug_mode = $dbg;
177        if ($this->db_connected) {
178            $this->db_handle->setOption('debug', $dbg);
179            $this->db_handle->setOption('emulate_prepared', $dbg);
180        }
181    }
182
183
184    /**
185     * Getter for error state
186     *
187     * @param  boolean  True on error
188     */
189    public function is_error()
190    {
191        return $this->db_error ? $this->db_error_msg : false;
192    }
193
194
195    /**
196     * Connection state checker
197     *
198     * @param  boolean  True if in connected state
199     */
200    public function is_connected()
201    {
202        return PEAR::isError($this->db_handle) ? false : $this->db_connected;
203    }
204
205
206    /**
207     * Is database replication configured?
208     * This returns true if dsnw != dsnr
209     */
210    public function is_replicated()
211    {
212      return !empty($this->db_dsnr) && $this->db_dsnw != $this->db_dsnr;
213    }
214
215
216    /**
217     * Execute a SQL query
218     *
219     * @param  string  SQL query to execute
220     * @param  mixed   Values to be inserted in query
221     *
222     * @return number  Query handle identifier
223     */
224    public function query()
225    {
226        $params = func_get_args();
227        $query = array_shift($params);
228
229        // Support one argument of type array, instead of n arguments
230        if (count($params) == 1 && is_array($params[0])) {
231            $params = $params[0];
232        }
233
234        return $this->_query($query, 0, 0, $params);
235    }
236
237
238    /**
239     * Execute a SQL query with limits
240     *
241     * @param  string  SQL query to execute
242     * @param  number  Offset for LIMIT statement
243     * @param  number  Number of rows for LIMIT statement
244     * @param  mixed   Values to be inserted in query
245     *
246     * @return number  Query handle identifier
247     */
248    public function limitquery()
249    {
250        $params  = func_get_args();
251        $query   = array_shift($params);
252        $offset  = array_shift($params);
253        $numrows = array_shift($params);
254
255        return $this->_query($query, $offset, $numrows, $params);
256    }
257
258
259    /**
260     * Execute a SQL query with limits
261     *
262     * @param  string $query   SQL query to execute
263     * @param  number $offset  Offset for LIMIT statement
264     * @param  number $numrows Number of rows for LIMIT statement
265     * @param  array  $params  Values to be inserted in query
266     * @return number  Query handle identifier
267     * @access private
268     */
269    private function _query($query, $offset, $numrows, $params)
270    {
271        // Read or write ?
272        $mode = (strtolower(substr(trim($query),0,6)) == 'select') ? 'r' : 'w';
273
274        $this->db_connect($mode);
275
276        // check connection before proceeding
277        if (!$this->is_connected()) {
278            return null;
279        }
280
281        if ($this->db_provider == 'sqlite') {
282            $this->sqlite_prepare();
283        }
284
285        if ($numrows || $offset) {
286            $result = $this->db_handle->setLimit($numrows,$offset);
287        }
288
289        if (empty($params)) {
290            $result = $mode == 'r' ? $this->db_handle->query($query) : $this->db_handle->exec($query);
291        }
292        else {
293            $params = (array)$params;
294            $q = $this->db_handle->prepare($query, null, $mode=='w' ? MDB2_PREPARE_MANIP : null);
295            if ($this->db_handle->isError($q)) {
296                $this->db_error = true;
297                $this->db_error_msg = $q->userinfo;
298
299                rcube::raise_error(array('code' => 500, 'type' => 'db',
300                    'line' => __LINE__, 'file' => __FILE__,
301                    'message' => $this->db_error_msg), true, false);
302
303                $result = false;
304            }
305            else {
306                $result = $q->execute($params);
307                $q->free();
308            }
309        }
310
311        // add result, even if it's an error
312        return $this->_add_result($result);
313    }
314
315
316    /**
317     * Get number of rows for a SQL query
318     * If no query handle is specified, the last query will be taken as reference
319     *
320     * @param  number $res_id  Optional query handle identifier
321     * @return mixed   Number of rows or false on failure
322     */
323    public function num_rows($res_id=null)
324    {
325        if (!$this->db_connected) {
326            return false;
327        }
328
329        if ($result = $this->_get_result($res_id)) {
330            return $result->numRows();
331        }
332
333        return false;
334    }
335
336
337    /**
338     * Get number of affected rows for the last query
339     *
340     * @param  number $res_id Optional query handle identifier
341     * @return mixed   Number of rows or false on failure
342     */
343    public function affected_rows($res_id = null)
344    {
345        if (!$this->db_connected) {
346            return false;
347        }
348
349        return $this->_get_result($res_id);
350    }
351
352
353    /**
354     * Get last inserted record ID
355     * For Postgres databases, a sequence name is required
356     *
357     * @param  string $table  Table name (to find the incremented sequence)
358     *
359     * @return mixed   ID or false on failure
360     */
361    public function insert_id($table = '')
362    {
363        if (!$this->db_connected || $this->db_mode == 'r') {
364            return false;
365        }
366
367        if ($table) {
368            if ($this->db_provider == 'pgsql') {
369                // find sequence name
370                $table = $this->sequence_name($table);
371            }
372            else {
373                // resolve table name
374                $table = $this->table_name($table);
375            }
376        }
377
378        $id = $this->db_handle->lastInsertID($table);
379
380        return $this->db_handle->isError($id) ? null : $id;
381    }
382
383
384    /**
385     * Get an associative array for one row
386     * If no query handle is specified, the last query will be taken as reference
387     *
388     * @param  number $res_id Optional query handle identifier
389     *
390     * @return mixed   Array with col values or false on failure
391     */
392    public function fetch_assoc($res_id = null)
393    {
394        $result = $this->_get_result($res_id);
395        return $this->_fetch_row($result, MDB2_FETCHMODE_ASSOC);
396    }
397
398
399    /**
400     * Get an index array for one row
401     * If no query handle is specified, the last query will be taken as reference
402     *
403     * @param  number $res_id  Optional query handle identifier
404     *
405     * @return mixed   Array with col values or false on failure
406     */
407    public function fetch_array($res_id = null)
408    {
409        $result = $this->_get_result($res_id);
410        return $this->_fetch_row($result, MDB2_FETCHMODE_ORDERED);
411    }
412
413
414    /**
415     * Get col values for a result row
416     *
417     * @param  MDB2_Result_Common Query $result result handle
418     * @param  number                   $mode   Fetch mode identifier
419     *
420     * @return mixed  Array with col values or false on failure
421     */
422    private function _fetch_row($result, $mode)
423    {
424        if ($result === false || PEAR::isError($result) || !$this->is_connected()) {
425            return false;
426        }
427
428        return $result->fetchRow($mode);
429    }
430
431
432    /**
433     * Wrapper for the SHOW TABLES command
434     *
435     * @return array List of all tables of the current database
436     * @since 0.4-beta
437     */
438    public function list_tables()
439    {
440        // get tables if not cached
441        if (!$this->tables) {
442            $this->db_handle->loadModule('Manager');
443            if (!PEAR::isError($result = $this->db_handle->listTables())) {
444                $this->tables = $result;
445            }
446            else {
447                $this->tables = array();
448            }
449        }
450
451        return $this->tables;
452    }
453
454
455    /**
456     * Wrapper for SHOW COLUMNS command
457     *
458     * @param string Table name
459     *
460     * @return array List of table cols
461     */
462    public function list_cols($table)
463    {
464        $this->db_handle->loadModule('Manager');
465        if (!PEAR::isError($result = $this->db_handle->listTableFields($table))) {
466            return $result;
467        }
468
469        return null;
470    }
471
472
473    /**
474     * Formats input so it can be safely used in a query
475     *
476     * @param  mixed  $input  Value to quote
477     * @param  string $type   Type of data
478     *
479     * @return string  Quoted/converted string for use in query
480     */
481    public function quote($input, $type = null)
482    {
483        // handle int directly for better performance
484        if ($type == 'integer') {
485            return intval($input);
486        }
487
488        // create DB handle if not available
489        if (!$this->db_handle) {
490            $this->db_connect('r');
491        }
492
493        return $this->db_connected ? $this->db_handle->quote($input, $type) : addslashes($input);
494    }
495
496
497    /**
498     * Quotes a string so it can be safely used as a table or column name
499     *
500     * @param  string $str Value to quote
501     *
502     * @return string  Quoted string for use in query
503     * @deprecated     Replaced by rcube_MDB2::quote_identifier
504     * @see            rcube_mdb2::quote_identifier
505     */
506    public function quoteIdentifier($str)
507    {
508        return $this->quote_identifier($str);
509    }
510
511
512    /**
513     * Quotes a string so it can be safely used as a table or column name
514     *
515     * @param  string $str Value to quote
516     *
517     * @return string  Quoted string for use in query
518     */
519    public function quote_identifier($str)
520    {
521        if (!$this->db_handle) {
522            $this->db_connect('r');
523        }
524
525        return $this->db_connected ? $this->db_handle->quoteIdentifier($str) : $str;
526    }
527
528
529    /**
530     * Escapes a string
531     *
532     * @param  string $str The string to be escaped
533     *
534     * @return string  The escaped string
535     * @since  0.1.1
536     */
537    public function escapeSimple($str)
538    {
539        if (!$this->db_handle) {
540            $this->db_connect('r');
541        }
542
543        return $this->db_handle->escape($str);
544    }
545
546
547    /**
548     * Return SQL function for current time and date
549     *
550     * @return string SQL function to use in query
551     */
552    public function now()
553    {
554        switch ($this->db_provider) {
555            case 'mssql':
556            case 'sqlsrv':
557                return "getdate()";
558
559            default:
560                return "now()";
561        }
562    }
563
564
565    /**
566     * Return list of elements for use with SQL's IN clause
567     *
568     * @param  array  $arr  Input array
569     * @param  string $type Type of data
570     *
571     * @return string Comma-separated list of quoted values for use in query
572     */
573    public function array2list($arr, $type = null)
574    {
575        if (!is_array($arr)) {
576            return $this->quote($arr, $type);
577        }
578
579        foreach ($arr as $idx => $item) {
580            $arr[$idx] = $this->quote($item, $type);
581        }
582
583        return implode(',', $arr);
584    }
585
586
587    /**
588     * Return SQL statement to convert a field value into a unix timestamp
589     *
590     * This method is deprecated and should not be used anymore due to limitations
591     * of timestamp functions in Mysql (year 2038 problem)
592     *
593     * @param  string $field Field name
594     *
595     * @return string  SQL statement to use in query
596     * @deprecated
597     */
598    public function unixtimestamp($field)
599    {
600        switch($this->db_provider) {
601            case 'pgsql':
602                return "EXTRACT (EPOCH FROM $field)";
603
604            case 'mssql':
605            case 'sqlsrv':
606                return "DATEDIFF(second, '19700101', $field) + DATEDIFF(second, GETDATE(), GETUTCDATE())";
607
608            default:
609                return "UNIX_TIMESTAMP($field)";
610        }
611    }
612
613
614    /**
615     * Return SQL statement to convert from a unix timestamp
616     *
617     * @param  string $timestamp Field name
618     *
619     * @return string  SQL statement to use in query
620     */
621    public function fromunixtime($timestamp)
622    {
623        return date("'Y-m-d H:i:s'", $timestamp);
624    }
625
626
627    /**
628     * Return SQL statement for case insensitive LIKE
629     *
630     * @param  string $column  Field name
631     * @param  string $value   Search value
632     *
633     * @return string  SQL statement to use in query
634     */
635    public function ilike($column, $value)
636    {
637        // TODO: use MDB2's matchPattern() function
638        switch ($this->db_provider) {
639            case 'pgsql':
640                return $this->quote_identifier($column).' ILIKE '.$this->quote($value);
641            default:
642                return $this->quote_identifier($column).' LIKE '.$this->quote($value);
643        }
644    }
645
646
647    /**
648     * Abstract SQL statement for value concatenation
649     *
650     * @return string SQL statement to be used in query
651     */
652    public function concat(/* col1, col2, ... */)
653    {
654        $func = '';
655        $args = func_get_args();
656
657        switch ($this->db_provider) {
658            case 'mysql':
659            case 'mysqli':
660                $func = 'CONCAT';
661                $delim = ', ';
662                break;
663            case 'mssql':
664            case 'sqlsrv':
665                $delim = ' + ';
666                break;
667            default:
668                $delim = ' || ';
669        }
670
671        return $func . '(' . join($delim, $args) . ')';
672    }
673
674
675    /**
676     * Encodes non-UTF-8 characters in string/array/object (recursive)
677     *
678     * @param  mixed  $input Data to fix
679     *
680     * @return mixed  Properly UTF-8 encoded data
681     */
682    public static function encode($input)
683    {
684        if (is_object($input)) {
685            foreach (get_object_vars($input) as $idx => $value) {
686                $input->$idx = self::encode($value);
687            }
688            return $input;
689        }
690        else if (is_array($input)) {
691            foreach ($input as $idx => $value) {
692                $input[$idx] = self::encode($value);
693            }
694            return $input;
695        }
696
697        return utf8_encode($input);
698    }
699
700
701    /**
702     * Decodes encoded UTF-8 string/object/array (recursive)
703     *
704     * @param  mixed $input Input data
705     *
706     * @return mixed  Decoded data
707     */
708    public static function decode($input)
709    {
710        if (is_object($input)) {
711            foreach (get_object_vars($input) as $idx => $value) {
712                $input->$idx = self::decode($value);
713            }
714            return $input;
715        }
716        else if (is_array($input)) {
717            foreach ($input as $idx => $value) {
718                $input[$idx] = self::decode($value);
719            }
720            return $input;
721        }
722
723        return utf8_decode($input);
724    }
725
726
727    /**
728     * Adds a query result and returns a handle ID
729     *
730     * @param  object $res Query handle
731     *
732     * @return mixed   Handle ID
733     */
734    private function _add_result($res)
735    {
736        // sql error occured
737        if (PEAR::isError($res)) {
738            $this->db_error = true;
739            $this->db_error_msg = $res->getMessage();
740            rcube::raise_error(array('code' => 500, 'type' => 'db',
741                'line' => __LINE__, 'file' => __FILE__,
742                'message' => $res->getMessage() . " Query: " 
743                . substr(preg_replace('/[\r\n]+\s*/', ' ', $res->userinfo), 0, 512)),
744                true, false);
745        }
746
747        $res_id = sizeof($this->a_query_results);
748        $this->last_res_id = $res_id;
749        $this->a_query_results[$res_id] = $res;
750        return $res_id;
751    }
752
753
754    /**
755     * Resolves a given handle ID and returns the according query handle
756     * If no ID is specified, the last resource handle will be returned
757     *
758     * @param  number $res_id Handle ID
759     *
760     * @return mixed   Resource handle or false on failure
761     */
762    private function _get_result($res_id = null)
763    {
764        if ($res_id == null) {
765            $res_id = $this->last_res_id;
766        }
767
768        if (isset($this->a_query_results[$res_id])) {
769            if (!PEAR::isError($this->a_query_results[$res_id])) {
770                return $this->a_query_results[$res_id];
771            }
772        }
773
774        return false;
775    }
776
777
778    /**
779     * Create a sqlite database from a file
780     *
781     * @param  MDB2   $dbh       SQLite database handle
782     * @param  string $file_name File path to use for DB creation
783     */
784    private function sqlite_create_database($dbh, $file_name)
785    {
786        if (empty($file_name) || !is_string($file_name)) {
787            return;
788        }
789
790        $data = file_get_contents($file_name);
791
792        if (strlen($data)) {
793            if (!sqlite_exec($dbh->connection, $data, $error) || MDB2::isError($dbh)) {
794                rcube::raise_error(array('code' => 500, 'type' => 'db',
795                    'line' => __LINE__, 'file' => __FILE__,
796                    'message' => $error), true, false);
797            }
798        }
799    }
800
801
802    /**
803     * Add some proprietary database functions to the current SQLite handle
804     * in order to make it MySQL compatible
805     */
806    private function sqlite_prepare()
807    {
808        // we emulate via callback some missing MySQL functions
809        sqlite_create_function($this->db_handle->connection,
810            'unix_timestamp', array('rcube_mdb2', 'sqlite_unix_timestamp'));
811        sqlite_create_function($this->db_handle->connection,
812            'now', array('rcube_mdb2', 'sqlite_now'));
813    }
814
815
816    /**
817     * Debug handler for the MDB2
818     */
819    function debug_handler(&$db, $scope, $message, $context = array())
820    {
821        if ($scope != 'prepare') {
822            $debug_output = sprintf('%s(%d): %s;',
823                $scope, $db->db_index, rtrim($message, ';'));
824            rcmail::write_log('sql', $debug_output);
825        }
826    }
827
828
829    /**
830     * Return correct name for a specific database table
831     *
832     * @param string $table Table name
833     *
834     * @return string Translated table name
835     */
836    public function table_name($table)
837    {
838        $rcmail = rcube::get_instance();
839
840        // return table name if configured
841        $config_key = 'db_table_'.$table;
842
843        if ($name = $rcmail->config->get($config_key)) {
844            return $name;
845        }
846
847        return $table;
848    }
849
850
851    /**
852     * Return correct name for a specific database sequence
853     * (used for Postgres only)
854     *
855     * @param string $sequence Secuence name
856     *
857     * @return string Translated sequence name
858     */
859    public function sequence_name($sequence)
860    {
861        $rcmail = rcube::get_instance();
862
863        // return sequence name if configured
864        $config_key = 'db_sequence_'.$sequence;
865
866        if ($name = $rcmail->config->get($config_key)) {
867            return $name;
868        }
869
870        return $sequence;
871    }
872
873
874    /**
875     * Callback for sqlite: unix_timestamp()
876     */
877    public static function sqlite_unix_timestamp($timestamp = '')
878    {
879        $timestamp = trim($timestamp);
880        if (!$timestamp) {
881            $ret = time();
882        }
883        else if (!preg_match('/^[0-9]+$/s', $timestamp)) {
884            $ret = strtotime($timestamp);
885        }
886        else {
887            $ret = $timestamp;
888        }
889
890        return $ret;
891    }
892
893
894    /**
895     * Callback for sqlite: now()
896     */
897    public static function sqlite_now()
898    {
899        return date("Y-m-d H:i:s");
900    }
901
902}
Note: See TracBrowser for help on using the repository browser.