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

Last change on this file since 334 was 334, checked in by quinn, 16 years ago

Fixed lots of misplings. I'm so embarrassed! ;P

File size: 12.1 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. FALSE recommended for production sites.
36        'db_always_debug' => false,
37
38        // Display db errors. FALSE recommended for production sites.
39        'db_debug' => false,
40       
41        // Script stops on db error. TRUE recommended for production sites.
42        'db_die_on_failure' => true,
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 if db_die_on_failure = true, or just continue without connection
144            return $this->_fail();
145        }
146
147        // DB connection success!
148        $this->_connected = true;
149
150        // Tell MySQL what character set we're using. Available only on MySQL versions > 4.01.01.
151        if ('' != $app->getParam('character_set') && isset($this->mysql_character_sets[mb_strtolower($app->getParam('character_set'))])) {
152            $this->query("/*!40101 SET NAMES '" . $this->mysql_character_sets[mb_strtolower($app->getParam('character_set'))] . "' */");
153        } else {
154            $app->logMsg(sprintf('%s is not a known character_set.', $app->getParam('character_set')), LOG_ERR, __FILE__, __LINE__);
155        }
156
157        return true;
158    }
159
160    /**
161     * Close db connection.
162     *
163     * @access  public
164     * @author  Quinn Comendant <quinn@strangecode.com>
165     * @since   28 Aug 2005 14:32:01
166     */
167    function close()
168    {
169        if (!$this->_connected) {
170            return false;
171        }
172
173        return mysql_close($this->dbh);
174    }
175   
176    /*
177    * Die only if db_die_on_failure is true. This will be set to false for some cases
178    * when a database is not required for web app functionality.
179    *
180    * @access   public
181    * @param    string  $msg Print $msg when dying.
182    * @return   bool    false If we don't die.
183    * @author   Quinn Comendant <quinn@strangecode.com>
184    * @version  1.0
185    * @since    15 Jan 2007 15:59:00
186    */
187    function _fail()
188    {
189        if ($this->getParam('db_die_on_failure')) {
190            echo _("This page is temporarily unavailable. Please try again in a few minutes.");
191            die;
192        } else {
193            return false;
194        }
195    }
196
197    /**
198     * Return the current database handler.
199     *
200     * @access  public
201     * @return  resource Current value of $this->dbh.
202     * @author  Quinn Comendant <quinn@strangecode.com>
203     * @since   20 Aug 2005 13:50:36
204     */
205    function getDBH()
206    {
207        if (!$this->_connected) {
208            return false;
209        }
210
211        return $this->dbh;
212    }
213
214    /**
215     * Returns connection status
216     *
217     * @access  public
218     * @author  Quinn Comendant <quinn@strangecode.com>
219     * @since   28 Aug 2005 14:58:09
220     */
221    function isConnected()
222    {
223        return (true === $this->_connected);
224    }
225   
226    /**
227     * Returns a properly escaped string using mysql_real_escape_string() with the current connection's charset.
228     *
229     * @access  public
230     * @param   string  $string     Input string to be sent as SQL query.
231     * @return  string              Escaped string from mysql_real_escape_string()
232     * @author  Quinn Comendant <quinn@strangecode.com>
233     * @since   06 Mar 2006 16:41:32
234     */
235    function escapeString($string)
236    {
237        if (!$this->_connected) {
238            return false;
239        }
240
241        return mysql_real_escape_string($string, $this->dbh);
242    }
243
244    /**
245     * A wrapper for mysql_query. Allows us to set the database link_identifier,
246     * to trap errors and ease debugging.
247     *
248     * @param  string  $query   The SQL query to execute
249     * @param  bool    $debug   If true, prints debugging info
250     * @return resource         Query identifier
251     */
252    function query($query, $debug=false)
253    {   
254        $app =& App::getInstance();
255
256        if (!$this->_connected) {
257           return false;
258        }
259
260        $this->_query_count++;
261
262        $debugqry = preg_replace("/\n[\t ]+/", "\n", $query);
263        if ($this->getParam('db_always_debug') || $debug) {
264            echo "<!-- ----------------- Query $this->_query_count ---------------------\n$debugqry\n-->\n";
265        }
266
267        // Execute!
268        $qid = mysql_query($query, $this->dbh);
269
270        // Error checking.
271        if (!$qid || mysql_error($this->dbh)) {
272            $app->logMsg(sprintf('MySQL error %s: %s in query: %s', mysql_errno($this->dbh), mysql_error($this->dbh), $debugqry), LOG_EMERG, __FILE__, __LINE__);
273            if ($this->getParam('db_debug')) {
274                echo '<pre style="padding:2em; background:#ddd; font:9px monaco;">' . wordwrap(mysql_error($this->dbh)) . '<hr>' . htmlspecialchars($debugqry) . '</pre>';
275            }           
276            // Die if db_die_on_failure = true, or just continue without connection
277            return $this->_fail();
278        }
279
280        return $qid;
281    }
282
283    /**
284     * Loads a list of tables in the current database into an array, and returns
285     * true if the requested table is found. Use this function to enable/disable
286     * functionality based upon the current available db tables or to dynamically
287     * create tables if missing.
288     *
289     * @param  string $table    The name of the table to search.
290     * @param  bool   $strict   Get fresh table info (in case DB changed).
291     * @return bool    true if given $table exists.
292     */
293    function tableExists($table, $use_cached_results=true)
294    {
295        $app =& App::getInstance();
296   
297        if (!$this->_connected) {
298            return false;
299        }
300
301        if (!isset($this->existing_tables) || !$use_cached_results) {
302            $this->existing_tables = array();
303            $qid = $this->query("SHOW TABLES");
304            while (list($row) = mysql_fetch_row($qid)) {
305                $this->existing_tables[] = $row;
306            }
307        }
308        if (in_array($table, $this->existing_tables)) {
309            return true;
310        } else {
311            $app->logMsg(sprintf('Nonexistent DB table: %s.%s', $this->getParam('db_name'), $table), LOG_ALERT, __FILE__, __LINE__);
312            return false;
313        }
314    }
315
316    /**
317     * Tests if the given array of columns exists in the specified table.
318     *
319     * @param  string $table    The name of the table to search.
320     * @param  array  $columns  An array of column names.
321     * @param  bool   $strict   Exact schema match, or are additional fields in the table okay?
322     * @param  bool   $strict   Get fresh table info (in case DB changed).
323     * @return bool    true if given $table exists.
324     */
325    function columnExists($table, $columns, $strict=true, $use_cached_results=true)
326    {
327        if (!$this->_connected) {
328            return false;
329        }
330
331        // Ensure the table exists.
332        if (!$this->tableExists($table, $use_cached_results)) {
333            return false;
334        }
335
336        // For single-value columns.
337        if (!is_array($columns)) {
338            $columns = array($columns);
339        }
340
341        if (!isset($this->table_columns[$table]) || !$use_cached_results) {
342            // Populate and cache array of current columns for this table.
343            $this->table_columns[$table] = array();
344            $qid = $this->query("DESCRIBE $table");
345            while ($row = mysql_fetch_row($qid)) {
346                $this->table_columns[$table][] = $row[0];
347            }
348        }
349
350        if ($strict) {
351            // Do an exact comparison of table schemas.
352            sort($columns);
353            sort($this->table_columns[$table]);
354            return $this->table_columns[$table] == $columns;
355        } else {
356            // Only check that the specified columns are available in the table.
357            $match_columns = array_intersect($this->table_columns[$table], $columns);
358            sort($columns);
359            sort($match_columns);
360            return $match_columns == $columns;
361        }
362    }
363   
364    /*
365    * Return the total number of queries run this for.
366    *
367    * @access   public
368    * @return   int Number of queries
369    * @author   Quinn Comendant <quinn@strangecode.com>
370    * @version  1.0
371    * @since    15 Jun 2006 11:46:05
372    */
373    function numQueries()
374    {
375        return $this->_query_count;
376    }
377
378    /**
379     * Reset cached items.
380     *
381     * @access  public
382     * @author  Quinn Comendant <quinn@strangecode.com>
383     * @since   28 Aug 2005 22:10:50
384     */
385    function resetCache()
386    {
387        $this->existing_tables = null;
388        $this->table_columns = null;
389    }
390
391} // End.
392
393?>
Note: See TracBrowser for help on using the repository browser.