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
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        $_this =& DB::getInstance();
88
89        if (isset($params) && is_array($params)) {
90            // Merge new parameters with old overriding only those passed.
91            $_this->_params = array_merge($_this->_params, $params);
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    {
108        $_this =& DB::getInstance();
109
110        if (isset($_this->_params[$param])) {
111            return $_this->_params[$param];
112        } else {
113            App::logMsg(sprintf('Parameter is not set: %s', $param), LOG_DEBUG, __FILE__, __LINE__);
114            return null;
115        }
116    }
117
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    {
127        $_this =& DB::getInstance();
128
129        if (!$_this->getParam('db_name') || !$_this->getParam('db_user') || !$_this->getParam('db_pass')) {
130            App::logMsg('Database credentials missing.', LOG_EMERG, __FILE__, __LINE__);
131            return false;
132        }
133
134        // Connect to database. Always create a new link to the server.
135        if ($_this->dbh = mysql_connect($_this->getParam('db_server'), $_this->getParam('db_user'), $_this->getParam('db_pass'), true)) {
136            // Select database
137            mysql_select_db($_this->getParam('db_name'), $_this->dbh);
138        }
139
140        // Test for connection errors.
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.';
143            App::logMsg($mysql_error_msg, LOG_EMERG, __FILE__, __LINE__);
144
145            // Print helpful or pretty error?
146            if ($_this->getParam('db_debug')) {
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            }
151
152            // Die or continue without connection?
153            if ($_this->getParam('db_die_on_failure')) {
154                echo "\n\n<!-- Script execution stopped out of embarrassment. -->";
155                die;
156            } else {
157                return false;
158            }
159        }
160
161        // DB connection success!
162        $_this->_connected = true;
163
164        // Tell MySQL what character set we're useing. Available only on MySQL verions > 4.01.01.
165        $_this->query("/*!40101 SET NAMES '" . $_this->mysql_character_sets[strtolower(App::getParam('character_set'))] . "' */");
166
167        return true;
168    }
169
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    {
179        $_this =& DB::getInstance();
180
181        if (!$_this->_connected) {
182            return false;
183        }
184
185        mysql_close($_this->dbh);
186    }
187
188    /**
189     * Return the current database handler.
190     *
191     * @access  public
192     * @return  resource Current value of $_this->dbh.
193     * @author  Quinn Comendant <quinn@strangecode.com>
194     * @since   20 Aug 2005 13:50:36
195     */
196    function getDBH()
197    {
198        $_this =& DB::getInstance();
199
200        if (!$_this->_connected) {
201            return false;
202        }
203
204        return $_this->dbh;
205    }
206
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    {
216        $_this =& DB::getInstance();
217
218        return $_this->_connected;
219    }
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    {
232        $_this =& DB::getInstance();
233
234        return mysql_real_escape_string($string, $_this->dbh);
235    }
236
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;
248
249        $_this =& DB::getInstance();
250
251        if (!$_this->_connected) {
252           return false;
253        }
254
255        $_query_count++;
256        $debugqry = preg_replace("/\n[\t ]+/", "\n", $query);
257        if ($_this->getParam('db_always_debug') || $debug) {
258            echo "<!-- ----------------- Query $_query_count ---------------------\n$debugqry\n-->\n";
259        }
260
261        // Execute!
262        $qid = mysql_query($query, $_this->dbh);
263
264        // Error checking.
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>';
268            } else {
269                echo _("This page is temporarily unavailable. It should be back up in a few minutes.");
270            }
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')) {
273                echo "\n\n<!-- Script execution stopped out of embarrassment. -->";
274                die;
275            }
276        }
277
278        return $qid;
279    }
280
281    /**
282     * Loads a list of tables in the current database into an array, and returns
283     * true if the requested table is found. Use this function to enable/disable
284     * funtionality based upon the current available db tables or to dynamically
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)
292    {
293        $_this =& DB::getInstance();
294
295        if (!$_this->_connected) {
296            return false;
297        }
298
299        if (!isset($_this->existing_tables) || !$use_cached_results) {
300            $_this->existing_tables = array();
301            $qid = $_this->query("SHOW TABLES");
302            while (list($row) = mysql_fetch_row($qid)) {
303                $_this->existing_tables[] = $row;
304            }
305        }
306        if (in_array($table, $_this->existing_tables)) {
307            return true;
308        } else {
309            App::logMsg(sprintf('nonexistent DB table: %s.%s', $_this->getParam('db_name'), $table), LOG_ALERT, __FILE__, __LINE__);
310            return false;
311        }
312    }
313
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)
324    {
325        $_this =& DB::getInstance();
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     * 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    {
373        $_this->existing_tables = null;
374        $_this->table_columns = null;
375    }
376
377} // End.
378
379?>
Note: See TracBrowser for help on using the repository browser.