source: github/program/include/rcube_mdb2.php @ 69f00be

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