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

Last change on this file since 185 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
RevLine 
[1]1<?php
2/**
3 * DB.inc.php
4 * code by strangecode :: www.strangecode.com :: this document contains copyrighted information
5 *
[136]6 * Very lightweight DB semi-abstraction layer. Mainly to catch errors with mysql_query, with some goodies.
[1]7 *
8 * @author  Quinn Comendant <quinn@strangecode.com>
[136]9 * @version 2.1
[1]10 */
[42]11
[1]12class DB {
13
[136]14    // If $db->connect has successfully opened a db connection.
[1]15    var $_connected = false;
16
[136]17    // Database handle.
[1]18    var $dbh;
[172]19   
20    // Count how many queries run during the whole instance.
21    var $_query_count = 0;
[1]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
[136]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,
[1]43    );
[42]44
[1]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    );
[42]50
[1]51    // Caches.
52    var $existing_tables;
53    var $table_columns;
[42]54
[1]55    /**
56     * This method enforces the singleton pattern for this class.
57     *
[136]58     * @return  object  Reference to the global DB object.
[1]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    }
[42]72
[1]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    {
[136]82        $app =& App::getInstance();
83   
[1]84        if (isset($params) && is_array($params)) {
85            // Merge new parameters with old overriding only those passed.
[136]86            $this->_params = array_merge($this->_params, $params);
[1]87        } else {
[136]88            $app->logMsg(sprintf('Parameters are not an array: %s', $params), LOG_ERR, __FILE__, __LINE__);
[1]89        }
90    }
91
92    /**
[136]93     * Return the value of a parameter, if it exists.
[1]94     *
[136]95     * @access public
96     * @param string $param        Which parameter to return.
97     * @return mixed               Configured parameter value.
[1]98     */
99    function getParam($param)
100    {
[136]101        $app =& App::getInstance();
102   
103        if (isset($this->_params[$param])) {
104            return $this->_params[$param];
[1]105        } else {
[146]106            $app->logMsg(sprintf('Parameter is not set: %s', $param), LOG_DEBUG, __FILE__, __LINE__);
[1]107            return null;
108        }
109    }
[42]110
[1]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    {
[136]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__);
[1]124            return false;
125        }
[42]126
[1]127        // Connect to database. Always create a new link to the server.
[136]128        if ($this->dbh = mysql_connect($this->getParam('db_server'), $this->getParam('db_user'), $this->getParam('db_pass'), true)) {
[1]129            // Select database
[136]130            mysql_select_db($this->getParam('db_name'), $this->dbh);
[1]131        }
[42]132
[15]133        // Test for connection errors.
[136]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__);
[15]137
138            // Print helpful or pretty error?
[136]139            if ($this->getParam('db_debug')) {
[1]140                echo $mysql_error_msg . "\n";
141            }
[15]142
143            // Die or continue without connection?
[136]144            if ($this->getParam('db_die_on_failure')) {
[15]145                echo "\n\n<!-- Script execution stopped out of embarrassment. -->";
146                die;
147            } else {
148                return false;
149            }
[1]150        }
[42]151
[1]152        // DB connection success!
[136]153        $this->_connected = true;
[1]154
[10]155        // Tell MySQL what character set we're useing. Available only on MySQL verions > 4.01.01.
[136]156        $this->query("/*!40101 SET NAMES '" . $this->mysql_character_sets[strtolower($app->getParam('character_set'))] . "' */");
[10]157
[1]158        return true;
159    }
[42]160
[1]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    {
[136]170        if (!$this->_connected) {
[1]171            return false;
172        }
173
[136]174        return mysql_close($this->dbh);
[1]175    }
[42]176
[1]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    {
[136]187        if (!$this->_connected) {
[1]188            return false;
189        }
190
[136]191        return $this->dbh;
[1]192    }
[42]193
[1]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    {
[136]203        return (true === $this->_connected);
[1]204    }
[71]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    {
[136]217        if (!$this->_connected) {
218            return false;
[71]219        }
[136]220
221        return mysql_real_escape_string($string, $this->dbh);
[71]222    }
[42]223
[1]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)
[136]233    {   
234        $app =& App::getInstance();
[42]235
[136]236        if (!$this->_connected) {
[1]237           return false;
238        }
239
[172]240        $this->_query_count++;
241
[1]242        $debugqry = preg_replace("/\n[\t ]+/", "\n", $query);
[136]243        if ($this->getParam('db_always_debug') || $debug) {
[172]244            echo "<!-- ----------------- Query $this->_query_count ---------------------\n$debugqry\n-->\n";
[1]245        }
[42]246
[1]247        // Execute!
[136]248        $qid = mysql_query($query, $this->dbh);
[42]249
[1]250        // Error checking.
[136]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>';
[1]254            } else {
255                echo _("This page is temporarily unavailable. It should be back up in a few minutes.");
256            }
[136]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')) {
[1]259                echo "\n\n<!-- Script execution stopped out of embarrassment. -->";
260                die;
261            }
262        }
[42]263
[1]264        return $qid;
265    }
266
267    /**
[42]268     * Loads a list of tables in the current database into an array, and returns
[1]269     * true if the requested table is found. Use this function to enable/disable
[42]270     * funtionality based upon the current available db tables or to dynamically
[1]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)
[42]278    {
[136]279        $app =& App::getInstance();
280   
281        if (!$this->_connected) {
[1]282            return false;
283        }
284
[136]285        if (!isset($this->existing_tables) || !$use_cached_results) {
286            $this->existing_tables = array();
287            $qid = $this->query("SHOW TABLES");
[1]288            while (list($row) = mysql_fetch_row($qid)) {
[136]289                $this->existing_tables[] = $row;
[1]290            }
291        }
[136]292        if (in_array($table, $this->existing_tables)) {
[1]293            return true;
294        } else {
[156]295            $app->logMsg(sprintf('Nonexistent DB table: %s.%s', $this->getParam('db_name'), $table), LOG_ALERT, __FILE__, __LINE__);
[1]296            return false;
297        }
298    }
[42]299
[1]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)
[42]310    {
[136]311        if (!$this->_connected) {
[1]312            return false;
313        }
314
315        // Ensure the table exists.
[136]316        if (!$this->tableExists($table, $use_cached_results)) {
[1]317            return false;
318        }
[42]319
[1]320        // For single-value columns.
321        if (!is_array($columns)) {
322            $columns = array($columns);
323        }
[42]324
[136]325        if (!isset($this->table_columns[$table]) || !$use_cached_results) {
[1]326            // Populate and cache array of current columns for this table.
[136]327            $this->table_columns[$table] = array();
328            $qid = $this->query("DESCRIBE $table");
[1]329            while ($row = mysql_fetch_row($qid)) {
[136]330                $this->table_columns[$table][] = $row[0];
[1]331            }
332        }
[42]333
[1]334        if ($strict) {
335            // Do an exact comparison of table schemas.
336            sort($columns);
[136]337            sort($this->table_columns[$table]);
338            return $this->table_columns[$table] == $columns;
[1]339        } else {
340            // Only check that the specified columns are available in the table.
[136]341            $match_columns = array_intersect($this->table_columns[$table], $columns);
[1]342            sort($columns);
343            sort($match_columns);
344            return $match_columns == $columns;
345        }
346    }
[172]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    }
[42]361
[1]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    }
[42]374
[1]375} // End.
376
377?>
Note: See TracBrowser for help on using the repository browser.