source: github/program/include/rcube_mdb2.inc @ ccfda89

HEADcourier-fixdev-browser-capabilitiespdorelease-0.6release-0.7release-0.8
Last change on this file since ccfda89 was ccfda89, checked in by thomascube <thomas@…>, 8 years ago

Fixed session expiration issue with SQLite

  • Property mode set to 100755
File size: 7.8 KB
Line 
1<?php
2
3/*
4 +-----------------------------------------------------------------------+
5 | program/include/rcube_db.inc                                          |
6 |                                                                       |
7 | This file is part of the RoundCube Webmail client                     |
8 | Copyright (C) 2005, RoundCube Dev. - Switzerland                      |
9 | Licensed under the GNU GPL                                            |
10 |                                                                       |
11 | PURPOSE:                                                              |
12 |   PEAR:DB wrapper class that implements PEAR DB functions             |
13 |   See http://pear.php.net/package/DB                                  |
14 |                                                                       |
15 +-----------------------------------------------------------------------+
16 | Author: David Saez Padros <david@ols.es>                              |
17 +-----------------------------------------------------------------------+
18
19 $Id$
20
21*/
22
23require_once('MDB2.php');
24
25class rcube_db
26{
27    var $db_dsnw;               // DSN for write operations
28    var $db_dsnr;               // DSN for read operations
29    var $db_connected=false;    // Already connected ?
30    var $db_mode='';            // Connection mode
31    var $db_handle=0;           // Connection handle
32
33    var $a_query_results = array('dummy');
34    var $last_res_id = 0;
35
36    // PHP 5 constructor
37    function __construct($db_dsnw,$db_dsnr='')
38    {
39        if ($db_dsnr=='') $db_dsnr=$db_dsnw;
40       
41        $this->db_dsnw = $db_dsnw;
42        $this->db_dsnr = $db_dsnr;
43       
44        $dsn_array = MDB2::parseDSN($db_dsnw);
45        $this->db_provider = $dsn_array['phptype'];
46    }
47
48    // PHP 4 compatibility
49    function rcube_db($db_dsnw,$db_dsnr='')
50    {
51        $this->__construct($db_dsnw,$db_dsnr);
52    }
53
54    // Connect to specific database
55    function dsn_connect($dsn)
56    {
57        // Use persistent connections if available
58        $dbh = MDB2::factory($dsn, array('persistent' => $true));
59       
60        if (PEAR::isError($dbh))
61            raise_error(array('code' => 500,
62                        'type' => 'db',
63                        'line' => __LINE__,
64                        'file' => __FILE__,
65                        'message' => $dbh->getMessage()), TRUE, FALSE);
66
67        else if ($this->db_provider=='sqlite')
68        {
69            $dsn_array = MDB2::parseDSN($dsn);
70            if (!filesize($dsn_array['database']) && !empty($this->sqlite_initials))
71                $this->_sqlite_create_database($dbh, $this->sqlite_initials);
72        }
73       
74        return $dbh;
75    }
76
77    // Connect to appropiate databse   
78    function db_connect ($mode)
79    {
80        $this->db_mode = $mode;
81
82        // Already connected
83        if ($this->db_connected)
84            {
85            // no replication, current connection is ok
86            if ($this->db_dsnw==$this->db_dsnr) return;
87           
88            // connected to master, current connection is ok
89            if ($this->db_mode=='w') return;
90
91            // Same mode, current connection is ok
92            if ($this->db_mode==$mode) return;
93            }
94           
95        if ($mode=='r')
96            $dsn=$this->db_dsnr;
97        else
98            $dsn=$this->db_dsnw;
99
100        $this->db_handle = $this->dsn_connect($dsn);
101        $this->db_connected = true;
102    }
103
104    // Query database
105   
106    function query()
107
108    {
109
110                $params = func_get_args();
111
112                $query = array_shift($params);
113
114               
115
116                return $this->_query($query, 0, 0, $params);
117
118    }
119
120   
121
122        function limitquery()
123
124    {
125
126                $params = func_get_args();
127
128                $query = array_shift($params);
129
130                $offset = array_shift($params);
131
132                $numrows = array_shift($params);
133
134               
135
136                return $this->_query($query, $offset, $numrows, $params);
137
138    }
139   
140    function _query($query, $offset, $numrows, $params)
141    {
142        // Read or write ?
143        if (strtolower(trim(substr($query,0,6)))=='select')
144            $mode='r';
145        else
146            $mode='w';
147       
148        $this->db_connect($mode);
149
150        if ($this->db_provider == 'sqlite')
151            $query = $this->_sqlite_prepare_query($query);
152
153        $this->db_handle->row_offset = $offset;
154                $this->db_handle->row_limit = $numrows;
155
156        $result = $this->db_handle->query($query,$params);
157        //$q = $this->db_handle->prepare($query);
158        //$q->bindParamArray($params);
159        //$result = $q->execute();
160
161        if (PEAR::isError($result))
162            raise_error(array('code' => 500,
163                              'type' => 'db',
164                              'line' => __LINE__,
165                              'file' => __FILE__,
166                              'message' => $result->getMessage()), TRUE, FALSE);
167       
168        return $this->_add_result($result, $query);
169    }
170
171    function num_rows($res_id=NULL)
172    {
173        if (!$this->db_handle)
174            return FALSE;
175
176        $result = $this->_get_result($res_id);
177   
178        if ($result)   
179              return $result->numRows();
180        else
181              return FALSE;
182    }
183
184    function affected_rows($res_id=NULL)
185    {
186        if (!$this->db_handle)
187            return FALSE;
188   
189        return $this->db_handle->affectedRows();
190    }
191
192    function insert_id($sequence = '')
193    {
194        if (!$this->db_handle || $this->db_mode=='r')
195            return FALSE;
196
197        return $this->db_handle->lastInsertID();
198    }
199
200
201    function fetch_assoc($res_id=NULL)
202    {
203        $result = $this->_get_result($res_id);
204
205        if (PEAR::isError($result))
206        {
207            raise_error( array('code' => 500, 'type' => 'db', 'line' => __LINE__, 'file' => __FILE__,
208                         'message' => $this->db_link->getMessage()), TRUE, FALSE);
209            return FALSE;
210        }
211                         
212        return $result->fetchRow(MDB2_FETCHMODE_ASSOC);
213    }
214
215        function quoteIdentifier ( $str )
216
217        {
218
219                if (!$this->db_handle)
220
221                        $this->db_connect('r');
222
223                       
224
225                return $this->db_handle->quoteIdentifier($str);
226
227        }
228       
229        function unixtimestamp($field)
230
231        {
232
233                switch($this->db_provider)
234
235                        {
236
237                        case 'pgsql':
238
239                                return "EXTRACT (EPOCH FROM $field)";
240
241                                break;
242
243                        default:
244
245                                return "UNIX_TIMESTAMP($field)";
246
247                        }
248
249        }
250       
251    function _add_result($res, $query)
252    {
253        // sql error occured
254        if (PEAR::isError($res))
255        {
256            raise_error(array('code' => 500, 'type' => 'db', 'line' => __LINE__, 'file' => __FILE__, 'message' => $res->getMessage() . " Query: " . substr(preg_replace('/[\r\n]+\s*/', ' ', $query), 0, 1024)), TRUE, FALSE);
257             return FALSE;
258        }
259        else
260        {
261            $res_id = sizeof($this->a_query_results);
262            $this->a_query_results[$res_id] = $res;
263            $this->last_res_id = $res_id;
264            return $res_id;
265        }
266    }
267
268
269    function _get_result($res_id)
270    {
271        if ($res_id==NULL)
272            $res_id = $this->last_res_id;
273   
274        if ($res_id && isset($this->a_query_results[$res_id]))
275            return $this->a_query_results[$res_id];
276        else
277        return FALSE;
278    }
279
280
281    // create a sqlite database from a file
282    function _sqlite_create_database($dbh, $fileName)
283    {
284        if (empty($fileName) || !is_string($fileName))
285            return ;
286
287        $data = '';
288        if ($fd = fopen($fileName, 'r'))
289          {
290          $data = fread($fd, filesize($fileName));
291          fclose($fd);
292          }
293
294        if (strlen($data))
295          sqlite_exec($dbh->connection, $data);
296    }
297
298    // transform a query so that it is sqlite2 compliant
299    function _sqlite_prepare_query($query)
300    {
301        if (!is_string($query))
302            return ($query);
303
304        $search = array('/NOW\(\)/i', '/`/');
305        $replace = array("datetime('now')", '"');
306        $query = preg_replace($search, $replace, $query);
307
308        return ($query);
309    }
310   
311}
312
313?>
Note: See TracBrowser for help on using the repository browser.