source: tags/2.1.5/lib/DB.inc.php

Last change on this file was 377, checked in by quinn, 14 years ago

Releasing trunk as stable version 2.1.5

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