source: subversion/trunk/roundcubemail/program/include/rcube_mdb2.php @ 4668

Last change on this file since 4668 was 4668, checked in by thomasb, 2 years ago

Gracefully shrug on database errors

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