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

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