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
Line 
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>
9 * @version 1.0.1
10 */
11
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    );
37
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    );
43
44    // Caches.
45    var $existing_tables;
46    var $table_columns;
47
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    }
65
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    {
87        $app =& App::getInstance();
88   
89        if (!isset($_this) || !is_a($_this, 'DB') && !is_subclass_of($_this, 'DB')) {
90            $_this =& DB::getInstance();
91        }
92
93        if (isset($params) && is_array($params)) {
94            // Merge new parameters with old overriding only those passed.
95            $_this->_params = array_merge($_this->_params, $params);
96        } else {
97            $app->logMsg(sprintf('Parameters are not an array: %s', $params), LOG_ERR, __FILE__, __LINE__);
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    {
112        $app =& App::getInstance();
113   
114        if (!isset($_this) || !is_a($_this, 'DB') && !is_subclass_of($_this, 'DB')) {
115            $_this =& DB::getInstance();
116        }
117
118        if (isset($_this->_params[$param])) {
119            return $_this->_params[$param];
120        } else {
121            $app->logMsg(sprintf('Parameter is not set: %s', $param), LOG_DEBUG, __FILE__, __LINE__);
122            return null;
123        }
124    }
125
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    {
135        $app =& App::getInstance();
136   
137        if (!isset($_this) || !is_a($_this, 'DB') && !is_subclass_of($_this, 'DB')) {
138            $_this =& DB::getInstance();
139        }
140
141        if (!$_this->getParam('db_name') || !$_this->getParam('db_user') || !$_this->getParam('db_pass')) {
142            $app->logMsg('Database credentials missing.', LOG_EMERG, __FILE__, __LINE__);
143            return false;
144        }
145
146        // Connect to database. Always create a new link to the server.
147        if ($_this->dbh = mysql_connect($_this->getParam('db_server'), $_this->getParam('db_user'), $_this->getParam('db_pass'), true)) {
148            // Select database
149            mysql_select_db($_this->getParam('db_name'), $_this->dbh);
150        }
151
152        // Test for connection errors.
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.';
155            $app->logMsg($mysql_error_msg, LOG_EMERG, __FILE__, __LINE__);
156
157            // Print helpful or pretty error?
158            if ($_this->getParam('db_debug')) {
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            }
163
164            // Die or continue without connection?
165            if ($_this->getParam('db_die_on_failure')) {
166                echo "\n\n<!-- Script execution stopped out of embarrassment. -->";
167                die;
168            } else {
169                return false;
170            }
171        }
172
173        // DB connection success!
174        $_this->_connected = true;
175
176        // Tell MySQL what character set we're useing. Available only on MySQL verions > 4.01.01.
177        $_this->query("/*!40101 SET NAMES '" . $_this->mysql_character_sets[strtolower($app->getParam('character_set'))] . "' */");
178
179        return true;
180    }
181
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    {
191        if (!isset($_this) || !is_a($_this, 'DB') && !is_subclass_of($_this, 'DB')) {
192            $_this =& DB::getInstance();
193        }
194
195        if (!$_this->_connected) {
196            return false;
197        }
198
199        mysql_close($_this->dbh);
200    }
201
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    {
212        if (!isset($_this) || !is_a($_this, 'DB') && !is_subclass_of($_this, 'DB')) {
213            $_this =& DB::getInstance();
214        }
215
216        if (!$_this->_connected) {
217            return false;
218        }
219
220        return $_this->dbh;
221    }
222
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    }
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    {
246        if (!isset($_this) || !is_a($_this, 'DB') && !is_subclass_of($_this, 'DB')) {
247            $_this =& DB::getInstance();
248        }
249        return mysql_real_escape_string($string, $_this->dbh);
250    }
251
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    {
262        $app =& App::getInstance();
263   
264        static $_query_count = 0;
265
266        if (!isset($_this) || !is_a($_this, 'DB') && !is_subclass_of($_this, 'DB')) {
267            $_this =& DB::getInstance();
268        }
269
270        if (!$_this->_connected) {
271           return false;
272        }
273
274        $_query_count++;
275        $debugqry = preg_replace("/\n[\t ]+/", "\n", $query);
276        if ($_this->getParam('db_always_debug') || $debug) {
277            echo "<!-- ----------------- Query $_query_count ---------------------\n$debugqry\n-->\n";
278        }
279
280        // Execute!
281        $qid = mysql_query($query, $_this->dbh);
282
283        // Error checking.
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>';
287            } else {
288                echo _("This page is temporarily unavailable. It should be back up in a few minutes.");
289            }
290            $app->logMsg(sprintf('MySQL error %s: %s in query: %s', mysql_errno($_this->dbh), mysql_error($_this->dbh), $debugqry), LOG_EMERG, __FILE__, __LINE__);
291            if ($_this->getParam('db_die_on_failure')) {
292                echo "\n\n<!-- Script execution stopped out of embarrassment. -->";
293                die;
294            }
295        }
296
297        return $qid;
298    }
299
300    /**
301     * Loads a list of tables in the current database into an array, and returns
302     * true if the requested table is found. Use this function to enable/disable
303     * funtionality based upon the current available db tables or to dynamically
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)
311    {
312        $app =& App::getInstance();
313   
314        if (!isset($_this) || !is_a($_this, 'DB') && !is_subclass_of($_this, 'DB')) {
315            $_this =& DB::getInstance();
316        }
317
318        if (!$_this->_connected) {
319            return false;
320        }
321
322        if (!isset($_this->existing_tables) || !$use_cached_results) {
323            $_this->existing_tables = array();
324            $qid = $_this->query("SHOW TABLES");
325            while (list($row) = mysql_fetch_row($qid)) {
326                $_this->existing_tables[] = $row;
327            }
328        }
329        if (in_array($table, $_this->existing_tables)) {
330            return true;
331        } else {
332            $app->logMsg(sprintf('nonexistent DB table: %s.%s', $_this->getParam('db_name'), $table), LOG_ALERT, __FILE__, __LINE__);
333            return false;
334        }
335    }
336
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)
347    {
348        if (!isset($_this) || !is_a($_this, 'DB') && !is_subclass_of($_this, 'DB')) {
349            $_this =& DB::getInstance();
350        }
351
352        if (!$_this->_connected) {
353            return false;
354        }
355
356        // Ensure the table exists.
357        if (!$_this->tableExists($table, $use_cached_results)) {
358            return false;
359        }
360
361        // For single-value columns.
362        if (!is_array($columns)) {
363            $columns = array($columns);
364        }
365
366        if (!isset($_this->table_columns[$table]) || !$use_cached_results) {
367            // Populate and cache array of current columns for this table.
368            $_this->table_columns[$table] = array();
369            $qid = $_this->query("DESCRIBE $table");
370            while ($row = mysql_fetch_row($qid)) {
371                $_this->table_columns[$table][] = $row[0];
372            }
373        }
374
375        if ($strict) {
376            // Do an exact comparison of table schemas.
377            sort($columns);
378            sort($_this->table_columns[$table]);
379            return $_this->table_columns[$table] == $columns;
380        } else {
381            // Only check that the specified columns are available in the table.
382            $match_columns = array_intersect($_this->table_columns[$table], $columns);
383            sort($columns);
384            sort($match_columns);
385            return $match_columns == $columns;
386        }
387    }
388
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    }
401
402} // End.
403
404?>
Note: See TracBrowser for help on using the repository browser.