source: trunk/lib/DB.inc.php @ 53

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

${1}

File size: 11.7 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        if (!isset($this) || !is_a($this, 'DB') && !is_subclass_of($this, 'DB')) {
88            $this =& DB::getInstance();
89        }
90
91        if (isset($params) && is_array($params)) {
92            // Merge new parameters with old overriding only those passed.
93            $this->_params = array_merge($this->_params, $params);
94        } else {
95            App::logMsg(sprintf('Parameters are not an array: %s', $params), LOG_ERR, __FILE__, __LINE__);
96        }
97    }
98
99    /**
100     * Return the value of a parameter.
101     *
102     * @access  public
103     *
104     * @param   string  $param      The key of the parameter to return.
105     *
106     * @return  mixed               Parameter value.
107     */
108    function getParam($param)
109    {
110        if (!isset($this) || !is_a($this, 'DB') && !is_subclass_of($this, 'DB')) {
111            $this =& DB::getInstance();
112        }
113
114        if (isset($this->_params[$param])) {
115            return $this->_params[$param];
116        } else {
117            App::logMsg(sprintf('Parameter is not set: %s', $param), LOG_DEBUG, __FILE__, __LINE__);
118            return null;
119        }
120    }
121
122    /**
123     * Connect to database with credentials in params.
124     *
125     * @access  public
126     * @author  Quinn Comendant <quinn@strangecode.com>
127     * @since   28 Aug 2005 14:02:49
128     */
129    function connect()
130    {
131        if (!isset($this) || !is_a($this, 'DB') && !is_subclass_of($this, 'DB')) {
132            $this =& DB::getInstance();
133        }
134
135        if (!$this->getParam('db_name') || !$this->getParam('db_user') || !$this->getParam('db_pass')) {
136            App::logMsg('Database credentials missing.', LOG_EMERG, __FILE__, __LINE__);
137            return false;
138        }
139
140        // Connect to database. Always create a new link to the server.
141        if ($this->dbh = mysql_connect($this->getParam('db_server'), $this->getParam('db_user'), $this->getParam('db_pass'), true)) {
142            // Select database
143            mysql_select_db($this->getParam('db_name'), $this->dbh);
144        } else {
145            App::logMsg(sprintf('mysql_connect failed.', null), LOG_ERR, __FILE__, __LINE__);
146        }
147
148        // Test for connection errors.
149        if (!$this->dbh || mysql_error($this->dbh)) {
150            $mysql_error_msg = $this->dbh ? 'Codebase MySQL error: (' . mysql_errno($this->dbh) . ') ' . mysql_error($this->dbh) : 'Codebase MySQL error: Could not connect to server.';
151            App::logMsg($mysql_error_msg, LOG_EMERG, __FILE__, __LINE__);
152
153            // Print helpful or pretty error?
154            if ($this->getParam('db_debug')) {
155                echo $mysql_error_msg . "\n";
156            } else {
157                echo _("This page is temporarily unavailable. It should be back up in a few minutes.");
158            }
159
160            // Die or continue without connection?
161            if ($this->getParam('db_die_on_failure')) {
162                echo "\n\n<!-- Script execution stopped out of embarrassment. -->";
163                die;
164            } else {
165                return false;
166            }
167        }
168
169        // DB connection success!
170        $this->_connected = true;
171
172        // Tell MySQL what character set we're useing. Available only on MySQL verions > 4.01.01.
173        $this->query("/*!40101 SET NAMES '" . $this->mysql_character_sets[strtolower(App::getParam('character_set'))] . "' */");
174
175        return true;
176    }
177
178    /**
179     * Close db connection.
180     *
181     * @access  public
182     * @author  Quinn Comendant <quinn@strangecode.com>
183     * @since   28 Aug 2005 14:32:01
184     */
185    function close()
186    {
187        if (!isset($this) || !is_a($this, 'DB') && !is_subclass_of($this, 'DB')) {
188            $this =& DB::getInstance();
189        }
190
191        if (!$this->_connected) {
192            return false;
193        }
194
195        mysql_close($this->dbh);
196    }
197
198    /**
199     * Return the current database handler.
200     *
201     * @access  public
202     * @return  resource Current value of $this->dbh.
203     * @author  Quinn Comendant <quinn@strangecode.com>
204     * @since   20 Aug 2005 13:50:36
205     */
206    function getDBH()
207    {
208        if (!isset($this) || !is_a($this, 'DB') && !is_subclass_of($this, 'DB')) {
209            $this =& DB::getInstance();
210        }
211
212        if (!$this->_connected) {
213            return false;
214        }
215
216        return $this->dbh;
217    }
218
219    /**
220     * Returns connection status
221     *
222     * @access  public
223     * @author  Quinn Comendant <quinn@strangecode.com>
224     * @since   28 Aug 2005 14:58:09
225     */
226    function isConnected()
227    {
228        return $this->_connected;
229    }
230
231    /**
232     * A wrapper for mysql_query. Allows us to set the database link_identifier,
233     * to trap errors and ease debugging.
234     *
235     * @param  string  $query   The SQL query to execute
236     * @param  bool    $debug   If true, prints debugging info
237     * @return resource         Query identifier
238     */
239    function query($query, $debug=false)
240    {
241        static $_query_count = 0;
242
243        if (!isset($this) || !is_a($this, 'DB') && !is_subclass_of($this, 'DB')) {
244            $this =& DB::getInstance();
245        }
246
247        if (!$this->_connected) {
248           return false;
249        }
250
251        $_query_count++;
252        $debugqry = preg_replace("/\n[\t ]+/", "\n", $query);
253        if ($this->getParam('db_always_debug') || $debug) {
254            echo "<!-- ----------------- Query $_query_count ---------------------\n$debugqry\n-->\n";
255        }
256
257        // Execute!
258        $qid = mysql_query($query, $this->dbh);
259
260        // Error checking.
261        if (!$qid || mysql_error($this->dbh)) {
262            if ($this->getParam('db_debug')) {
263                echo '<pre style="padding:2em; background:#ddd; font:9px monaco;">' . wordwrap(mysql_error($this->dbh)) . '<hr>' . htmlspecialchars($debugqry) . '</pre>';
264            } else {
265                echo _("This page is temporarily unavailable. It should be back up in a few minutes.");
266            }
267            App::logMsg(sprintf('MySQL error %s: %s in query: %s', mysql_errno($this->dbh), mysql_error($this->dbh), $debugqry), LOG_EMERG, __FILE__, __LINE__);
268            if ($this->getParam('db_die_on_failure')) {
269                echo "\n\n<!-- Script execution stopped out of embarrassment. -->";
270                die;
271            }
272        }
273
274        return $qid;
275    }
276
277    /**
278     * Loads a list of tables in the current database into an array, and returns
279     * true if the requested table is found. Use this function to enable/disable
280     * funtionality based upon the current available db tables or to dynamically
281     * create tables if missing.
282     *
283     * @param  string $table    The name of the table to search.
284     * @param  bool   $strict   Get fresh table info (in case DB changed).
285     * @return bool    true if given $table exists.
286     */
287    function tableExists($table, $use_cached_results=true)
288    {
289        if (!isset($this) || !is_a($this, 'DB') && !is_subclass_of($this, 'DB')) {
290            $this =& DB::getInstance();
291        }
292
293        if (!$this->_connected) {
294            return false;
295        }
296
297        if (!isset($this->existing_tables) || !$use_cached_results) {
298            $this->existing_tables = array();
299            $qid = $this->query("SHOW TABLES");
300            while (list($row) = mysql_fetch_row($qid)) {
301                $this->existing_tables[] = $row;
302            }
303        }
304        if (in_array($table, $this->existing_tables)) {
305            return true;
306        } else {
307            App::logMsg(sprintf('nonexistent DB table: %s.%s', $this->getParam('db_name'), $table), LOG_ALERT, __FILE__, __LINE__);
308            return false;
309        }
310    }
311
312    /**
313     * Tests if the given array of columns exists in the specified table.
314     *
315     * @param  string $table    The name of the table to search.
316     * @param  array  $columns  An array of column names.
317     * @param  bool   $strict   Exact schema match, or are additional fields in the table okay?
318     * @param  bool   $strict   Get fresh table info (in case DB changed).
319     * @return bool    true if given $table exists.
320     */
321    function columnExists($table, $columns, $strict=true, $use_cached_results=true)
322    {
323        if (!isset($this) || !is_a($this, 'DB') && !is_subclass_of($this, 'DB')) {
324            $this =& DB::getInstance();
325        }
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.