source: github/program/include/rcube_mdb2.php @ 8b8512f

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