source: tags/2.0.2/lib/DB.inc.php @ 480

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

Q - added tags/2.0.2 as the first php5 compatible version of the 2.0 branch.

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