source: branches/2.0singleton/lib/DB.inc.php @ 127

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

Updated App.inc.php thru Hierarchy.inc.php

File size: 12.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    {
[127]87        $app =& App::getInstance();
88   
[119]89        if (!isset($_this) || !is_a($_this, 'DB') && !is_subclass_of($_this, 'DB')) {
90            $_this =& DB::getInstance();
[1]91        }
92
93        if (isset($params) && is_array($params)) {
94            // Merge new parameters with old overriding only those passed.
[119]95            $_this->_params = array_merge($_this->_params, $params);
[1]96        } else {
[127]97            $app->logMsg(sprintf('Parameters are not an array: %s', $params), LOG_ERR, __FILE__, __LINE__);
[1]98        }
99    }
100
101    /**
102     * Return the value of a parameter.
103     *
104     * @access  public
105     *
106     * @param   string  $param      The key of the parameter to return.
107     *
108     * @return  mixed               Parameter value.
109     */
110    function getParam($param)
111    {
[127]112        $app =& App::getInstance();
113   
[119]114        if (!isset($_this) || !is_a($_this, 'DB') && !is_subclass_of($_this, 'DB')) {
115            $_this =& DB::getInstance();
[1]116        }
117
[119]118        if (isset($_this->_params[$param])) {
119            return $_this->_params[$param];
[1]120        } else {
[127]121            $app->logMsg(sprintf('Parameter is not set: %s', $param), LOG_DEBUG, __FILE__, __LINE__);
[1]122            return null;
123        }
124    }
[42]125
[1]126    /**
127     * Connect to database with credentials in params.
128     *
129     * @access  public
130     * @author  Quinn Comendant <quinn@strangecode.com>
131     * @since   28 Aug 2005 14:02:49
132     */
133    function connect()
134    {
[127]135        $app =& App::getInstance();
136   
[119]137        if (!isset($_this) || !is_a($_this, 'DB') && !is_subclass_of($_this, 'DB')) {
138            $_this =& DB::getInstance();
[1]139        }
[42]140
[119]141        if (!$_this->getParam('db_name') || !$_this->getParam('db_user') || !$_this->getParam('db_pass')) {
[127]142            $app->logMsg('Database credentials missing.', LOG_EMERG, __FILE__, __LINE__);
[1]143            return false;
144        }
[42]145
[1]146        // Connect to database. Always create a new link to the server.
[119]147        if ($_this->dbh = mysql_connect($_this->getParam('db_server'), $_this->getParam('db_user'), $_this->getParam('db_pass'), true)) {
[1]148            // Select database
[119]149            mysql_select_db($_this->getParam('db_name'), $_this->dbh);
[1]150        }
[42]151
[15]152        // Test for connection errors.
[119]153        if (!$_this->dbh || mysql_error($_this->dbh)) {
154            $mysql_error_msg = $_this->dbh ? 'Codebase MySQL error: (' . mysql_errno($_this->dbh) . ') ' . mysql_error($_this->dbh) : 'Codebase MySQL error: Could not connect to server.';
[127]155            $app->logMsg($mysql_error_msg, LOG_EMERG, __FILE__, __LINE__);
[15]156
157            // Print helpful or pretty error?
[119]158            if ($_this->getParam('db_debug')) {
[1]159                echo $mysql_error_msg . "\n";
160            } else {
161                echo _("This page is temporarily unavailable. It should be back up in a few minutes.");
162            }
[15]163
164            // Die or continue without connection?
[119]165            if ($_this->getParam('db_die_on_failure')) {
[15]166                echo "\n\n<!-- Script execution stopped out of embarrassment. -->";
167                die;
168            } else {
169                return false;
170            }
[1]171        }
[42]172
[1]173        // DB connection success!
[119]174        $_this->_connected = true;
[1]175
[10]176        // Tell MySQL what character set we're useing. Available only on MySQL verions > 4.01.01.
[127]177        $_this->query("/*!40101 SET NAMES '" . $_this->mysql_character_sets[strtolower($app->getParam('character_set'))] . "' */");
[10]178
[1]179        return true;
180    }
[42]181
[1]182    /**
183     * Close db connection.
184     *
185     * @access  public
186     * @author  Quinn Comendant <quinn@strangecode.com>
187     * @since   28 Aug 2005 14:32:01
188     */
189    function close()
190    {
[119]191        if (!isset($_this) || !is_a($_this, 'DB') && !is_subclass_of($_this, 'DB')) {
192            $_this =& DB::getInstance();
[1]193        }
[42]194
[119]195        if (!$_this->_connected) {
[1]196            return false;
197        }
198
[119]199        mysql_close($_this->dbh);
[1]200    }
[42]201
[1]202    /**
203     * Return the current database handler.
204     *
205     * @access  public
206     * @return  resource Current value of $this->dbh.
207     * @author  Quinn Comendant <quinn@strangecode.com>
208     * @since   20 Aug 2005 13:50:36
209     */
210    function getDBH()
211    {
[119]212        if (!isset($_this) || !is_a($_this, 'DB') && !is_subclass_of($_this, 'DB')) {
213            $_this =& DB::getInstance();
[1]214        }
[42]215
[119]216        if (!$_this->_connected) {
[1]217            return false;
218        }
219
[119]220        return $_this->dbh;
[1]221    }
[42]222
[1]223    /**
224     * Returns connection status
225     *
226     * @access  public
227     * @author  Quinn Comendant <quinn@strangecode.com>
228     * @since   28 Aug 2005 14:58:09
229     */
230    function isConnected()
231    {
232        return $this->_connected;
233    }
[71]234   
235    /**
236     * Returns a properly escaped string using mysql_real_escape_string() with the current connection's charset.
237     *
238     * @access  public
239     * @param   string  $string     Input string to be sent as SQL query.
240     * @return  string              Escaped string from mysql_real_escape_string()
241     * @author  Quinn Comendant <quinn@strangecode.com>
242     * @since   06 Mar 2006 16:41:32
243     */
244    function escapeString($string)
245    {
[119]246        if (!isset($_this) || !is_a($_this, 'DB') && !is_subclass_of($_this, 'DB')) {
247            $_this =& DB::getInstance();
[71]248        }
[119]249        return mysql_real_escape_string($string, $_this->dbh);
[71]250    }
[42]251
[1]252    /**
253     * A wrapper for mysql_query. Allows us to set the database link_identifier,
254     * to trap errors and ease debugging.
255     *
256     * @param  string  $query   The SQL query to execute
257     * @param  bool    $debug   If true, prints debugging info
258     * @return resource         Query identifier
259     */
260    function query($query, $debug=false)
261    {
[127]262        $app =& App::getInstance();
263   
[1]264        static $_query_count = 0;
[42]265
[119]266        if (!isset($_this) || !is_a($_this, 'DB') && !is_subclass_of($_this, 'DB')) {
267            $_this =& DB::getInstance();
[1]268        }
[42]269
[119]270        if (!$_this->_connected) {
[1]271           return false;
272        }
273
274        $_query_count++;
275        $debugqry = preg_replace("/\n[\t ]+/", "\n", $query);
[119]276        if ($_this->getParam('db_always_debug') || $debug) {
[1]277            echo "<!-- ----------------- Query $_query_count ---------------------\n$debugqry\n-->\n";
278        }
[42]279
[1]280        // Execute!
[119]281        $qid = mysql_query($query, $_this->dbh);
[42]282
[1]283        // Error checking.
[119]284        if (!$qid || mysql_error($_this->dbh)) {
285            if ($_this->getParam('db_debug')) {
286                echo '<pre style="padding:2em; background:#ddd; font:9px monaco;">' . wordwrap(mysql_error($_this->dbh)) . '<hr>' . htmlspecialchars($debugqry) . '</pre>';
[1]287            } else {
288                echo _("This page is temporarily unavailable. It should be back up in a few minutes.");
289            }
[127]290            $app->logMsg(sprintf('MySQL error %s: %s in query: %s', mysql_errno($_this->dbh), mysql_error($_this->dbh), $debugqry), LOG_EMERG, __FILE__, __LINE__);
[119]291            if ($_this->getParam('db_die_on_failure')) {
[1]292                echo "\n\n<!-- Script execution stopped out of embarrassment. -->";
293                die;
294            }
295        }
[42]296
[1]297        return $qid;
298    }
299
300    /**
[42]301     * Loads a list of tables in the current database into an array, and returns
[1]302     * true if the requested table is found. Use this function to enable/disable
[42]303     * funtionality based upon the current available db tables or to dynamically
[1]304     * create tables if missing.
305     *
306     * @param  string $table    The name of the table to search.
307     * @param  bool   $strict   Get fresh table info (in case DB changed).
308     * @return bool    true if given $table exists.
309     */
310    function tableExists($table, $use_cached_results=true)
[42]311    {
[127]312        $app =& App::getInstance();
313   
[119]314        if (!isset($_this) || !is_a($_this, 'DB') && !is_subclass_of($_this, 'DB')) {
315            $_this =& DB::getInstance();
[1]316        }
[42]317
[119]318        if (!$_this->_connected) {
[1]319            return false;
320        }
321
[119]322        if (!isset($_this->existing_tables) || !$use_cached_results) {
323            $_this->existing_tables = array();
324            $qid = $_this->query("SHOW TABLES");
[1]325            while (list($row) = mysql_fetch_row($qid)) {
[119]326                $_this->existing_tables[] = $row;
[1]327            }
328        }
[119]329        if (in_array($table, $_this->existing_tables)) {
[1]330            return true;
331        } else {
[127]332            $app->logMsg(sprintf('nonexistent DB table: %s.%s', $_this->getParam('db_name'), $table), LOG_ALERT, __FILE__, __LINE__);
[1]333            return false;
334        }
335    }
[42]336
[1]337    /**
338     * Tests if the given array of columns exists in the specified table.
339     *
340     * @param  string $table    The name of the table to search.
341     * @param  array  $columns  An array of column names.
342     * @param  bool   $strict   Exact schema match, or are additional fields in the table okay?
343     * @param  bool   $strict   Get fresh table info (in case DB changed).
344     * @return bool    true if given $table exists.
345     */
346    function columnExists($table, $columns, $strict=true, $use_cached_results=true)
[42]347    {
[119]348        if (!isset($_this) || !is_a($_this, 'DB') && !is_subclass_of($_this, 'DB')) {
349            $_this =& DB::getInstance();
[1]350        }
[42]351
[119]352        if (!$_this->_connected) {
[1]353            return false;
354        }
355
356        // Ensure the table exists.
[119]357        if (!$_this->tableExists($table, $use_cached_results)) {
[1]358            return false;
359        }
[42]360
[1]361        // For single-value columns.
362        if (!is_array($columns)) {
363            $columns = array($columns);
364        }
[42]365
[119]366        if (!isset($_this->table_columns[$table]) || !$use_cached_results) {
[1]367            // Populate and cache array of current columns for this table.
[119]368            $_this->table_columns[$table] = array();
369            $qid = $_this->query("DESCRIBE $table");
[1]370            while ($row = mysql_fetch_row($qid)) {
[119]371                $_this->table_columns[$table][] = $row[0];
[1]372            }
373        }
[42]374
[1]375        if ($strict) {
376            // Do an exact comparison of table schemas.
377            sort($columns);
[119]378            sort($_this->table_columns[$table]);
379            return $_this->table_columns[$table] == $columns;
[1]380        } else {
381            // Only check that the specified columns are available in the table.
[119]382            $match_columns = array_intersect($_this->table_columns[$table], $columns);
[1]383            sort($columns);
384            sort($match_columns);
385            return $match_columns == $columns;
386        }
387    }
[42]388
[1]389    /**
390     * Reset cached items.
391     *
392     * @access  public
393     * @author  Quinn Comendant <quinn@strangecode.com>
394     * @since   28 Aug 2005 22:10:50
395     */
396    function resetCache()
397    {
398        $this->existing_tables = null;
399        $this->table_columns = null;
400    }
[42]401
[1]402} // End.
403
404?>
Note: See TracBrowser for help on using the repository browser.