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

Last change on this file since 468 was 468, checked in by anonymous, 10 years ago

Completed integrating /branches/eli_branch into /trunk. Changes include:

  • Removed closing ?> from end of files
  • Upgrade old-style contructor methods to use construct() instead.
  • Class properties and methods defined as public, private, static or protected
  • Ensure code runs under E_ALL with only mysql_* deprecated warnings
  • Search for the '@' symbol anywhere it might be used to supress runtime errors, then replace with proper error recovery.
  • Run the php cli -l option to check files for syntax errors.
  • Bring tests up-to-date with latest version and methods of PHPUnit
File size: 14.0 KB
Line 
1<?php
2/**
3 * The Strangecode Codebase - a general application development framework for PHP
4 * For details visit the project site: <http://trac.strangecode.com/codebase/>
5 * Copyright 2001-2012 Strangecode, LLC
6 *
7 * This file is part of The Strangecode Codebase.
8 *
9 * The Strangecode Codebase is free software: you can redistribute it and/or
10 * modify it under the terms of the GNU General Public License as published by the
11 * Free Software Foundation, either version 3 of the License, or (at your option)
12 * any later version.
13 *
14 * The Strangecode Codebase is distributed in the hope that it will be useful, but
15 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
16 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
17 * details.
18 *
19 * You should have received a copy of the GNU General Public License along with
20 * The Strangecode Codebase. If not, see <http://www.gnu.org/licenses/>.
21 */
22
23/**
24 * DB.inc.php
25 *
26 * Very lightweight DB semi-abstraction layer. Mainly to catch errors with mysql_query, with some goodies.
27 *
28 * @author  Quinn Comendant <quinn@strangecode.com>
29 * @version 2.1
30 */
31
32class DB {
33
34    // A place to keep an object instance for the singleton pattern.
35    private static $instance = null;
36
37    // If $db->connect has successfully opened a db connection.
38    private $_connected = false;
39
40    // Database handle.
41    public $dbh;
42
43    // Count how many queries run during the whole instance.
44    private $_query_count = 0;
45
46    // Hash of DB parameters.
47    private $_params = array();
48
49    // Default parameters.
50    private $_param_defaults = array(
51
52        // DB passwords should be set as apache environment variables in httpd.conf, readable only by root.
53        'db_server' => 'localhost',
54        'db_name' => null,
55        'db_user' => null,
56        'db_pass' => null,
57
58        // Display all SQL queries. FALSE recommended for production sites.
59        'db_always_debug' => false,
60
61        // Display db errors. FALSE recommended for production sites.
62        'db_debug' => false,
63
64        // Script stops on db error. TRUE recommended for production sites.
65        'db_die_on_failure' => true,
66    );
67
68    // Translate between HTML and MySQL character set names.
69    public $mysql_character_sets = array(
70        'utf-8' => 'utf8',
71        'iso-8859-1' => 'latin1',
72    );
73
74    // Caches.
75    private $existing_tables;
76    private $table_columns;
77
78    /**
79     * This method enforces the singleton pattern for this class.
80     *
81     * @return  object  Reference to the global DB object.
82     * @access  public
83     * @static
84     */
85    public static function &getInstance()
86    {
87        if (self::$instance === null) {
88            self::$instance = new self();
89        }
90
91        return self::$instance;
92    }
93
94    /**
95     * Set (or overwrite existing) parameters by passing an array of new parameters.
96     *
97     * @access public
98     *
99     * @param  array    $params     Array of parameters (key => val pairs).
100     */
101    public function setParam($params)
102    {
103        $app =& App::getInstance();
104
105        if (isset($params) && is_array($params)) {
106            // Merge new parameters with old overriding only those passed.
107            $this->_params = array_merge($this->_params, $params);
108        } else {
109            $app->logMsg(sprintf('Parameters are not an array: %s', $params), LOG_ERR, __FILE__, __LINE__);
110        }
111    }
112
113    /**
114     * Return the value of a parameter, if it exists.
115     *
116     * @access public
117     * @param string $param        Which parameter to return.
118     * @return mixed               Configured parameter value.
119     */
120    public function getParam($param)
121    {
122        $app =& App::getInstance();
123
124        if (isset($this->_params[$param])) {
125            return $this->_params[$param];
126        } else {
127            $app->logMsg(sprintf('Parameter is not set: %s', $param), LOG_DEBUG, __FILE__, __LINE__);
128            return null;
129        }
130    }
131
132    /**
133     * Connect to database with credentials in params.
134     *
135     * @access  public
136     * @author  Quinn Comendant <quinn@strangecode.com>
137     * @since   28 Aug 2005 14:02:49
138     */
139    public function connect()
140    {
141        $app =& App::getInstance();
142
143        if (!$this->getParam('db_name') || !$this->getParam('db_user') || !$this->getParam('db_pass')) {
144            $app->logMsg('Database credentials missing.', LOG_EMERG, __FILE__, __LINE__);
145            return false;
146        }
147
148        // Connect to database. Always create a new link to the server.
149        if ($this->dbh = @mysql_connect($this->getParam('db_server'), $this->getParam('db_user'), $this->getParam('db_pass'), true)) {
150            // Select database
151            mysql_select_db($this->getParam('db_name'), $this->dbh);
152        }
153
154        // Test for connection errors.
155        if (!$this->dbh || mysql_error($this->dbh)) {
156            $mysql_error_msg = $this->dbh ? 'Codebase MySQL error: (' . mysql_errno($this->dbh) . ') ' . mysql_error($this->dbh) : 'Codebase MySQL error: Could not connect to server.';
157            $app->logMsg($mysql_error_msg, LOG_EMERG, __FILE__, __LINE__);
158
159            // Print helpful or pretty error?
160            if ($this->getParam('db_debug')) {
161                echo $mysql_error_msg . "\n";
162            }
163
164            // Die if db_die_on_failure = true, or just continue without connection.
165            return $this->_fail();
166        }
167
168        // DB connection success!
169        $this->_connected = true;
170
171        // Tell MySQL what character set we're using. Available only on MySQL versions > 4.01.01.
172        if ('' != $app->getParam('character_set') && isset($this->mysql_character_sets[mb_strtolower($app->getParam('character_set'))])) {
173            $this->query("/*!40101 SET NAMES '" . $this->mysql_character_sets[mb_strtolower($app->getParam('character_set'))] . "' */");
174        } else {
175            $app->logMsg(sprintf('%s is not a known character_set.', $app->getParam('character_set')), LOG_ERR, __FILE__, __LINE__);
176        }
177
178        return true;
179    }
180
181    /**
182     * Close db connection.
183     *
184     * @access  public
185     * @author  Quinn Comendant <quinn@strangecode.com>
186     * @since   28 Aug 2005 14:32:01
187     */
188    public function close()
189    {
190        if (!$this->_connected) {
191            return false;
192        }
193        $this->_connected = false;
194        return mysql_close($this->dbh);
195    }
196
197    /*
198    *
199    *
200    * @access   public
201    * @param
202    * @return
203    * @author   Quinn Comendant <quinn@strangecode.com>
204    * @version  1.0
205    * @since    03 Jul 2013 14:50:23
206    */
207    public function reconnect()
208    {
209        $this->close();
210        $this->connect();
211    }
212
213    /*
214    * Die only if db_die_on_failure is true. This will be set to false for some cases
215    * when a database is not required for web app functionality.
216    *
217    * @access   public
218    * @param    string  $msg Print $msg when dying.
219    * @return   bool    false If we don't die.
220    * @author   Quinn Comendant <quinn@strangecode.com>
221    * @version  1.0
222    * @since    15 Jan 2007 15:59:00
223    */
224    private function _fail()
225    {
226        if ($this->getParam('db_die_on_failure')) {
227            header(' ', true, 503);
228            echo _("This page is temporarily unavailable. Please try again in a few minutes.");
229            die;
230        } else {
231            return false;
232        }
233    }
234
235    /**
236     * Return the current database handler.
237     *
238     * @access  public
239     * @return  resource Current value of $this->dbh.
240     * @author  Quinn Comendant <quinn@strangecode.com>
241     * @since   20 Aug 2005 13:50:36
242     */
243    public function getDBH()
244    {
245        if (!$this->_connected) {
246            return false;
247        }
248
249        return $this->dbh;
250    }
251
252    /**
253     * Returns connection status
254     *
255     * @access  public
256     * @author  Quinn Comendant <quinn@strangecode.com>
257     * @since   28 Aug 2005 14:58:09
258     */
259    public function isConnected()
260    {
261        return (true === $this->_connected);
262    }
263
264    /**
265     * Returns a properly escaped string using mysql_real_escape_string() with the current connection's charset.
266     *
267     * @access  public
268     * @param   string  $string     Input string to be sent as SQL query.
269     * @return  string              Escaped string from mysql_real_escape_string()
270     * @author  Quinn Comendant <quinn@strangecode.com>
271     * @since   06 Mar 2006 16:41:32
272     */
273    public function escapeString($string)
274    {
275        if (!$this->_connected) {
276            return false;
277        }
278
279        return mysql_real_escape_string($string, $this->dbh);
280    }
281
282    /**
283     * A wrapper for mysql_query. Allows us to set the database link_identifier,
284     * to trap errors and ease debugging.
285     *
286     * @param  string  $query   The SQL query to execute
287     * @param  bool    $debug   If true, prints debugging info
288     * @return resource         Query identifier
289     */
290    public function query($query, $debug=false)
291    {
292        $app =& App::getInstance();
293
294        if (!$this->_connected) {
295           return false;
296        }
297
298        $this->_query_count++;
299
300        $debugqry = preg_replace("/\n[\t ]+/", "\n", $query);
301        if ($this->getParam('db_always_debug') || $debug) {
302            echo "<!-- ----------------- Query $this->_query_count ---------------------\n$debugqry\n-->\n";
303        }
304
305        // Ensure we have an active connection.
306        // If we continue on a dead connection we might experience a "MySQL server has gone away" error.
307        // http://dev.mysql.com/doc/refman/5.0/en/gone-away.html
308        if (!mysql_ping($this->dbh)) {
309            $app->logMsg(sprintf('MySQL ping failed; reconnecting
 ("%s")', truncate(trim($debugqry), 150)), LOG_NOTICE, __FILE__, __LINE__);
310            $this->reconnect();
311        }
312
313        // Execute!
314        $qid = mysql_query($query, $this->dbh);
315
316        // Error checking.
317        if (!$qid || mysql_error($this->dbh)) {
318            $app->logMsg(sprintf('MySQL error %s: %s in query: %s', mysql_errno($this->dbh), mysql_error($this->dbh), $debugqry), LOG_EMERG, __FILE__, __LINE__);
319            if ($this->getParam('db_debug')) {
320                echo '<pre style="padding:2em; background:#ddd; font:9px monaco;">' . wordwrap(mysql_error($this->dbh)) . '<hr>' . htmlspecialchars($debugqry) . '</pre>';
321            }
322            // Die if db_die_on_failure = true, or just continue without connection
323            return $this->_fail();
324        }
325
326        return $qid;
327    }
328
329    /**
330     * Loads a list of tables in the current database into an array, and returns
331     * true if the requested table is found. Use this function to enable/disable
332     * functionality based upon the current available db tables or to dynamically
333     * create tables if missing.
334     *
335     * @param  string $table                The name of the table to search.
336     * @param  bool   $use_cached_results   Get fresh table info (in case DB changed).
337     * @return bool                         true if given $table exists.
338     */
339    public function tableExists($table, $use_cached_results=true)
340    {
341        $app =& App::getInstance();
342
343        if (!$this->_connected) {
344            return false;
345        }
346
347        if (!isset($this->existing_tables) || !$use_cached_results) {
348            $this->existing_tables = array();
349            $qid = $this->query("SHOW TABLES");
350            while (list($row) = mysql_fetch_row($qid)) {
351                $this->existing_tables[] = $row;
352            }
353        }
354        if (in_array($table, $this->existing_tables)) {
355            return true;
356        } else {
357            $app->logMsg(sprintf('Nonexistent DB table: %s.%s', $this->getParam('db_name'), $table), LOG_ALERT, __FILE__, __LINE__);
358            return false;
359        }
360    }
361
362    /**
363     * Tests if the given array of columns exists in the specified table.
364     *
365     * @param  string $table                The name of the table to search.
366     * @param  array  $columns              An array of column names.
367     * @param  bool   $strict               Exact schema match, or are additional fields in the table okay?
368     * @param  bool   $use_cached_results   Get fresh table info (in case DB changed).
369     * @return bool                         true if column(s) exist.
370     */
371    public function columnExists($table, $columns, $strict=true, $use_cached_results=true)
372    {
373        if (!$this->_connected) {
374            return false;
375        }
376
377        // Ensure the table exists.
378        if (!$this->tableExists($table, $use_cached_results)) {
379            return false;
380        }
381
382        // For single-value columns.
383        if (!is_array($columns)) {
384            $columns = array($columns);
385        }
386
387        if (!isset($this->table_columns[$table]) || !$use_cached_results) {
388            // Populate and cache array of current columns for this table.
389            $this->table_columns[$table] = array();
390            $qid = $this->query("DESCRIBE $table");
391            while ($row = mysql_fetch_row($qid)) {
392                $this->table_columns[$table][] = $row[0];
393            }
394        }
395
396        if ($strict) {
397            // Do an exact comparison of table schemas.
398            sort($columns);
399            sort($this->table_columns[$table]);
400            return $this->table_columns[$table] == $columns;
401        } else {
402            // Only check that the specified columns are available in the table.
403            $match_columns = array_intersect($this->table_columns[$table], $columns);
404            sort($columns);
405            sort($match_columns);
406            return $match_columns == $columns;
407        }
408    }
409
410    /*
411    * Return the total number of queries executed thus far.
412    *
413    * @access   public
414    * @return   int Number of queries
415    * @author   Quinn Comendant <quinn@strangecode.com>
416    * @version  1.0
417    * @since    15 Jun 2006 11:46:05
418    */
419    public function numQueries()
420    {
421        return $this->_query_count;
422    }
423
424    /**
425     * Reset cached items.
426     *
427     * @access  public
428     * @author  Quinn Comendant <quinn@strangecode.com>
429     * @since   28 Aug 2005 22:10:50
430     */
431    public function resetCache()
432    {
433        $this->existing_tables = null;
434        $this->table_columns = null;
435    }
436
437} // End.
438
Note: See TracBrowser for help on using the repository browser.