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

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

Fix return value of affected_rows()

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