source: trunk/lib/DB.inc.php @ 172

Last change on this file since 172 was 172, checked in by scdev, 18 years ago

Q - added caching to ACL, and flush command to acl.cli.php

File size: 11.3 KB
Line 
1<?php
2/**
3 * DB.inc.php
4 * code by strangecode :: www.strangecode.com :: this document contains copyrighted information
5 *
6 * Very lightweight DB semi-abstraction layer. Mainly to catch errors with mysql_query, with some goodies.
7 *
8 * @author  Quinn Comendant <quinn@strangecode.com>
9 * @version 2.1
10 */
11
12class DB {
13
14    // If $db->connect has successfully opened a db connection.
15    var $_connected = false;
16
17    // Database handle.
18    var $dbh;
19   
20    // Count how many queries run during the whole instance.
21    var $_query_count = 0;
22
23    // Hash of DB parameters.
24    var $_params = array();
25
26    // Default parameters.
27    var $_param_defaults = array(
28
29        // DB passwords should be set as apache environment variables in httpd.conf, readable only by root.
30        'db_server' => 'localhost',
31        'db_name' => null,
32        'db_user' => null,
33        'db_pass' => null,
34
35        // Display all SQL queries.
36        'db_always_debug' => false,
37
38        // Display db errors.
39        'db_debug' => false,
40       
41        // Script stops on db error.
42        'db_die_on_failure' => false,
43    );
44
45    // Translate between HTML and MySQL character set names.
46    var $mysql_character_sets = array(
47        'utf-8' => 'utf8',
48        'iso-8859-1' => 'latin1',
49    );
50
51    // Caches.
52    var $existing_tables;
53    var $table_columns;
54
55    /**
56     * This method enforces the singleton pattern for this class.
57     *
58     * @return  object  Reference to the global DB object.
59     * @access  public
60     * @static
61     */
62    function &getInstance()
63    {
64        static $instance = null;
65
66        if ($instance === null) {
67            $instance = new DB();
68        }
69
70        return $instance;
71    }
72
73    /**
74     * Set (or overwrite existing) parameters by passing an array of new parameters.
75     *
76     * @access public
77     *
78     * @param  array    $params     Array of parameters (key => val pairs).
79     */
80    function setParam($params)
81    {
82        $app =& App::getInstance();
83   
84        if (isset($params) && is_array($params)) {
85            // Merge new parameters with old overriding only those passed.
86            $this->_params = array_merge($this->_params, $params);
87        } else {
88            $app->logMsg(sprintf('Parameters are not an array: %s', $params), LOG_ERR, __FILE__, __LINE__);
89        }
90    }
91
92    /**
93     * Return the value of a parameter, if it exists.
94     *
95     * @access public
96     * @param string $param        Which parameter to return.
97     * @return mixed               Configured parameter value.
98     */
99    function getParam($param)
100    {
101        $app =& App::getInstance();
102   
103        if (isset($this->_params[$param])) {
104            return $this->_params[$param];
105        } else {
106            $app->logMsg(sprintf('Parameter is not set: %s', $param), LOG_DEBUG, __FILE__, __LINE__);
107            return null;
108        }
109    }
110
111    /**
112     * Connect to database with credentials in params.
113     *
114     * @access  public
115     * @author  Quinn Comendant <quinn@strangecode.com>
116     * @since   28 Aug 2005 14:02:49
117     */
118    function connect()
119    {
120        $app =& App::getInstance();
121   
122        if (!$this->getParam('db_name') || !$this->getParam('db_user') || !$this->getParam('db_pass')) {
123            $app->logMsg('Database credentials missing.', LOG_EMERG, __FILE__, __LINE__);
124            return false;
125        }
126
127        // Connect to database. Always create a new link to the server.
128        if ($this->dbh = mysql_connect($this->getParam('db_server'), $this->getParam('db_user'), $this->getParam('db_pass'), true)) {
129            // Select database
130            mysql_select_db($this->getParam('db_name'), $this->dbh);
131        }
132
133        // Test for connection errors.
134        if (!$this->dbh || mysql_error($this->dbh)) {
135            $mysql_error_msg = $this->dbh ? 'Codebase MySQL error: (' . mysql_errno($this->dbh) . ') ' . mysql_error($this->dbh) : 'Codebase MySQL error: Could not connect to server.';
136            $app->logMsg($mysql_error_msg, LOG_EMERG, __FILE__, __LINE__);
137
138            // Print helpful or pretty error?
139            if ($this->getParam('db_debug')) {
140                echo $mysql_error_msg . "\n";
141            }
142
143            // Die or continue without connection?
144            if ($this->getParam('db_die_on_failure')) {
145                echo "\n\n<!-- Script execution stopped out of embarrassment. -->";
146                die;
147            } else {
148                return false;
149            }
150        }
151
152        // DB connection success!
153        $this->_connected = true;
154
155        // Tell MySQL what character set we're useing. Available only on MySQL verions > 4.01.01.
156        $this->query("/*!40101 SET NAMES '" . $this->mysql_character_sets[strtolower($app->getParam('character_set'))] . "' */");
157
158        return true;
159    }
160
161    /**
162     * Close db connection.
163     *
164     * @access  public
165     * @author  Quinn Comendant <quinn@strangecode.com>
166     * @since   28 Aug 2005 14:32:01
167     */
168    function close()
169    {
170        if (!$this->_connected) {
171            return false;
172        }
173
174        return mysql_close($this->dbh);
175    }
176
177    /**
178     * Return the current database handler.
179     *
180     * @access  public
181     * @return  resource Current value of $this->dbh.
182     * @author  Quinn Comendant <quinn@strangecode.com>
183     * @since   20 Aug 2005 13:50:36
184     */
185    function getDBH()
186    {
187        if (!$this->_connected) {
188            return false;
189        }
190
191        return $this->dbh;
192    }
193
194    /**
195     * Returns connection status
196     *
197     * @access  public
198     * @author  Quinn Comendant <quinn@strangecode.com>
199     * @since   28 Aug 2005 14:58:09
200     */
201    function isConnected()
202    {
203        return (true === $this->_connected);
204    }
205   
206    /**
207     * Returns a properly escaped string using mysql_real_escape_string() with the current connection's charset.
208     *
209     * @access  public
210     * @param   string  $string     Input string to be sent as SQL query.
211     * @return  string              Escaped string from mysql_real_escape_string()
212     * @author  Quinn Comendant <quinn@strangecode.com>
213     * @since   06 Mar 2006 16:41:32
214     */
215    function escapeString($string)
216    {
217        if (!$this->_connected) {
218            return false;
219        }
220
221        return mysql_real_escape_string($string, $this->dbh);
222    }
223
224    /**
225     * A wrapper for mysql_query. Allows us to set the database link_identifier,
226     * to trap errors and ease debugging.
227     *
228     * @param  string  $query   The SQL query to execute
229     * @param  bool    $debug   If true, prints debugging info
230     * @return resource         Query identifier
231     */
232    function query($query, $debug=false)
233    {   
234        $app =& App::getInstance();
235
236        if (!$this->_connected) {
237           return false;
238        }
239
240        $this->_query_count++;
241
242        $debugqry = preg_replace("/\n[\t ]+/", "\n", $query);
243        if ($this->getParam('db_always_debug') || $debug) {
244            echo "<!-- ----------------- Query $this->_query_count ---------------------\n$debugqry\n-->\n";
245        }
246
247        // Execute!
248        $qid = mysql_query($query, $this->dbh);
249
250        // Error checking.
251        if (!$qid || mysql_error($this->dbh)) {
252            if ($this->getParam('db_debug')) {
253                echo '<pre style="padding:2em; background:#ddd; font:9px monaco;">' . wordwrap(mysql_error($this->dbh)) . '<hr>' . htmlspecialchars($debugqry) . '</pre>';
254            } else {
255                echo _("This page is temporarily unavailable. It should be back up in a few minutes.");
256            }
257            $app->logMsg(sprintf('MySQL error %s: %s in query: %s', mysql_errno($this->dbh), mysql_error($this->dbh), $debugqry), LOG_EMERG, __FILE__, __LINE__);
258            if ($this->getParam('db_die_on_failure')) {
259                echo "\n\n<!-- Script execution stopped out of embarrassment. -->";
260                die;
261            }
262        }
263
264        return $qid;
265    }
266
267    /**
268     * Loads a list of tables in the current database into an array, and returns
269     * true if the requested table is found. Use this function to enable/disable
270     * funtionality based upon the current available db tables or to dynamically
271     * create tables if missing.
272     *
273     * @param  string $table    The name of the table to search.
274     * @param  bool   $strict   Get fresh table info (in case DB changed).
275     * @return bool    true if given $table exists.
276     */
277    function tableExists($table, $use_cached_results=true)
278    {
279        $app =& App::getInstance();
280   
281        if (!$this->_connected) {
282            return false;
283        }
284
285        if (!isset($this->existing_tables) || !$use_cached_results) {
286            $this->existing_tables = array();
287            $qid = $this->query("SHOW TABLES");
288            while (list($row) = mysql_fetch_row($qid)) {
289                $this->existing_tables[] = $row;
290            }
291        }
292        if (in_array($table, $this->existing_tables)) {
293            return true;
294        } else {
295            $app->logMsg(sprintf('Nonexistent DB table: %s.%s', $this->getParam('db_name'), $table), LOG_ALERT, __FILE__, __LINE__);
296            return false;
297        }
298    }
299
300    /**
301     * Tests if the given array of columns exists in the specified table.
302     *
303     * @param  string $table    The name of the table to search.
304     * @param  array  $columns  An array of column names.
305     * @param  bool   $strict   Exact schema match, or are additional fields in the table okay?
306     * @param  bool   $strict   Get fresh table info (in case DB changed).
307     * @return bool    true if given $table exists.
308     */
309    function columnExists($table, $columns, $strict=true, $use_cached_results=true)
310    {
311        if (!$this->_connected) {
312            return false;
313        }
314
315        // Ensure the table exists.
316        if (!$this->tableExists($table, $use_cached_results)) {
317            return false;
318        }
319
320        // For single-value columns.
321        if (!is_array($columns)) {
322            $columns = array($columns);
323        }
324
325        if (!isset($this->table_columns[$table]) || !$use_cached_results) {
326            // Populate and cache array of current columns for this table.
327            $this->table_columns[$table] = array();
328            $qid = $this->query("DESCRIBE $table");
329            while ($row = mysql_fetch_row($qid)) {
330                $this->table_columns[$table][] = $row[0];
331            }
332        }
333
334        if ($strict) {
335            // Do an exact comparison of table schemas.
336            sort($columns);
337            sort($this->table_columns[$table]);
338            return $this->table_columns[$table] == $columns;
339        } else {
340            // Only check that the specified columns are available in the table.
341            $match_columns = array_intersect($this->table_columns[$table], $columns);
342            sort($columns);
343            sort($match_columns);
344            return $match_columns == $columns;
345        }
346    }
347   
348    /*
349    * Return the total number of queries run this for.
350    *
351    * @access   public
352    * @return   int Number of queries
353    * @author   Quinn Comendant <quinn@strangecode.com>
354    * @version  1.0
355    * @since    15 Jun 2006 11:46:05
356    */
357    function numQueries()
358    {
359        return $this->_query_count;
360    }
361
362    /**
363     * Reset cached items.
364     *
365     * @access  public
366     * @author  Quinn Comendant <quinn@strangecode.com>
367     * @since   28 Aug 2005 22:10:50
368     */
369    function resetCache()
370    {
371        $this->existing_tables = null;
372        $this->table_columns = null;
373    }
374
375} // End.
376
377?>
Note: See TracBrowser for help on using the repository browser.