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

Last change on this file since 711 was 697, checked in by anonymous, 5 years ago

Improve error display. Use \u flag on preg patterns.

File size: 17.6 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    protected static $instance = null;
36
37    // If $db->connect has successfully opened a db connection.
38    protected $_connected = false;
39
40    // Database handle.
41    public $dbh;
42
43    // Count how many queries run during the whole instance.
44    protected $_query_count = 0;
45
46    // Hash of DB parameters.
47    protected $_params = array();
48
49    // Default parameters.
50    protected $_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        // Special date settings. These will dynamically changes depending on MySQL version or settings.
68        'zero_date' => '0000-00-00',
69        'infinity_date' => '9999-12-31',
70
71        // Timezone for MySQL.
72        'timezone' => 'UTC',
73
74        // MySQL character set and collation.
75        'character_set' => '',
76        'collation' => '',
77    );
78
79    // Translate between HTML and MySQL character set names.
80    public $mysql_character_sets = array(
81        'utf-8' => 'utf8',
82        'iso-8859-1' => 'latin1',
83    );
84
85    // Caches.
86    protected static $existing_tables = null;
87    protected static $table_columns = null;
88
89    /**
90     * Constructor.
91     */
92    public function __construct()
93    {
94        // Initialize default parameters.
95        $this->_params = array_merge($this->_params, $this->_param_defaults);
96    }
97
98    /**
99     * This method enforces the singleton pattern for this class.
100     *
101     * @return  object  Reference to the global DB object.
102     * @access  public
103     * @static
104     */
105    public static function &getInstance()
106    {
107        if (self::$instance === null) {
108            self::$instance = new self();
109        }
110
111        return self::$instance;
112    }
113
114    /**
115     * Set (or overwrite existing) parameters by passing an array of new parameters.
116     *
117     * @access public
118     *
119     * @param  array    $params     Array of parameters (key => val pairs).
120     */
121    public function setParam($params)
122    {
123        $app =& App::getInstance();
124
125        if (isset($params) && is_array($params)) {
126            // Merge new parameters with old overriding only those passed.
127            $this->_params = array_merge($this->_params, $params);
128        } else {
129            $app->logMsg(sprintf('Parameters are not an array: %s', $params), LOG_ERR, __FILE__, __LINE__);
130        }
131    }
132
133    /**
134     * Return the value of a parameter, if it exists.
135     *
136     * @access public
137     * @param string $param        Which parameter to return.
138     * @return mixed               Configured parameter value.
139     */
140    public function getParam($param)
141    {
142        $app =& App::getInstance();
143
144        if (array_key_exists($param, $this->_params)) {
145            return $this->_params[$param];
146        } else {
147            $app->logMsg(sprintf('Parameter is not set: %s', $param), LOG_DEBUG, __FILE__, __LINE__);
148            return null;
149        }
150    }
151
152    /**
153     * Connect to database with credentials in params.
154     *
155     * @access  public
156     * @author  Quinn Comendant <quinn@strangecode.com>
157     * @since   28 Aug 2005 14:02:49
158     */
159    public function connect()
160    {
161        $app =& App::getInstance();
162
163        if (!$this->getParam('db_name') || !$this->getParam('db_user') || !$this->getParam('db_pass')) {
164            $app->logMsg('Database credentials missing.', LOG_EMERG, __FILE__, __LINE__);
165            return false;
166        }
167
168        if (!$this->getParam('db_server')) {
169            // If db_server not specified, assume localhost.
170            $this->setParam(array('db_server' => 'localhost'));
171        }
172
173        // Connect to database. Always create a new link to the server.
174        // Connection errors are suppressed so we can do our own error management below.
175        if ($this->dbh = @mysql_connect($this->getParam('db_server'), $this->getParam('db_user'), $this->getParam('db_pass'), true)) {
176            // Select database
177            mysql_select_db($this->getParam('db_name'), $this->dbh);
178        }
179
180        // Test for connection errors.
181        if (!$this->dbh || mysql_error($this->dbh)) {
182            $mysql_error_msg = $this->dbh ? 'Codebase MySQL error: (' . mysql_errno($this->dbh) . ') ' . mysql_error($this->dbh) : sprintf('Codebase MySQL error: Could not connect to server (db_server=%s, db_name=%s, db_user=%s, db_pass=%s)', $this->getParam('db_server'), $this->getParam('db_name'), $this->getParam('db_user'), ('' == $this->getParam('db_pass') ? 'NO' : 'YES'));
183            $app->logMsg($mysql_error_msg, LOG_EMERG, __FILE__, __LINE__);
184
185            // Print helpful or pretty error?
186            if ($this->getParam('db_debug')) {
187                if (!$app->isCLI()) {
188                    printf('<pre style="padding:1em;background:#ddd;font:0.9rem monospace;">%s</pre>', $mysql_error_msg);
189                }
190            }
191
192            // Die if db_die_on_failure = true, or just continue without connection.
193            return $this->_fail();
194        }
195
196        // DB connection success!
197        $this->_connected = true;
198
199        // If the mysql charset is not defined, try to determine a mysql charset from the app charset.
200        if ('' == $this->getParam('character_set') && '' != $app->getParam('character_set') && isset($this->mysql_character_sets[mb_strtolower($app->getParam('character_set'))])) {
201            $this->setParam(array('character_set' => $this->mysql_character_sets[mb_strtolower($app->getParam('character_set'))]));
202        }
203        if ('' != $this->getParam('character_set')) {
204            if ('' != $this->getParam('collation')) {
205                $this->query(sprintf("SET NAMES '%s' COLLATE '%s';", $this->getParam('character_set'), $this->getParam('collation')));
206            } else {
207                $this->query(sprintf("SET NAMES '%s';", $this->getParam('character_set')));
208            }
209        }
210
211        // Update config for this version of MySQL.
212        if (version_compare(mysql_get_server_info(), '5.7.4', '>=')) {
213            $this->setParam(array('zero_date' => '1000-01-01'));
214        }
215
216        // Set MySQL session timezone.
217        if ($this->getParam('timezone')) {
218            // https://dev.mysql.com/doc/refman/5.5/en/time-zone-support.html
219            $this->query(sprintf("SET time_zone = '%s';", $this->getParam('timezone')));
220        }
221
222        return true;
223    }
224
225    /**
226     * Close db connection.
227     *
228     * @access  public
229     * @author  Quinn Comendant <quinn@strangecode.com>
230     * @since   28 Aug 2005 14:32:01
231     */
232    public function close()
233    {
234        if (!$this->_connected) {
235            return false;
236        }
237        $this->_connected = false;
238        return mysql_close($this->dbh);
239    }
240
241    /*
242    *
243    *
244    * @access   public
245    * @param
246    * @return
247    * @author   Quinn Comendant <quinn@strangecode.com>
248    * @version  1.0
249    * @since    03 Jul 2013 14:50:23
250    */
251    public function reconnect()
252    {
253        $this->close();
254        $this->connect();
255    }
256
257    /*
258    * Die only if db_die_on_failure is true. This will be set to false for some cases
259    * when a database is not required for web app functionality.
260    *
261    * @access   public
262    * @param    string  $msg Print $msg when dying.
263    * @return   bool    false If we don't die.
264    * @author   Quinn Comendant <quinn@strangecode.com>
265    * @version  1.0
266    * @since    15 Jan 2007 15:59:00
267    */
268    protected function _fail()
269    {
270        $app =& App::getInstance();
271
272        if ($this->getParam('db_die_on_failure')) {
273            if (!$app->isCLI()) {
274                // For http requests, send a Service Unavailable header.
275                header(' ', true, 503);
276                echo _("This page is temporarily unavailable. Please try again in a few minutes.");
277            }
278            die;
279        } else {
280            return false;
281        }
282    }
283
284    /**
285     * Return the current database handler.
286     *
287     * @access  public
288     * @return  resource Current value of $this->dbh.
289     * @author  Quinn Comendant <quinn@strangecode.com>
290     * @since   20 Aug 2005 13:50:36
291     */
292    public function getDBH()
293    {
294        if (!$this->_connected) {
295            return false;
296        }
297
298        return $this->dbh;
299    }
300
301    /**
302     * Returns connection status
303     *
304     * @access  public
305     * @author  Quinn Comendant <quinn@strangecode.com>
306     * @since   28 Aug 2005 14:58:09
307     */
308    public function isConnected()
309    {
310        return (true === $this->_connected);
311    }
312
313    /**
314     * Returns a properly escaped string using mysql_real_escape_string() with the current connection's charset.
315     *
316     * @access  public
317     * @param   string  $string     Input string to be sent as SQL query.
318     * @return  string              Escaped string from mysql_real_escape_string()
319     * @author  Quinn Comendant <quinn@strangecode.com>
320     * @since   06 Mar 2006 16:41:32
321     */
322    public function escapeString($string)
323    {
324        if (!$this->_connected) {
325            return false;
326        }
327
328        return mysql_real_escape_string($string, $this->dbh);
329    }
330
331    /**
332     * A wrapper for mysql_query. Allows us to set the database link_identifier,
333     * to trap errors and ease debugging.
334     *
335     * @param  string  $query   The SQL query to execute
336     * @param  bool    $debug   If true, prints debugging info
337     * @return resource         Query identifier
338     */
339    public function query($query, $debug=false)
340    {
341        $app =& App::getInstance();
342
343        if (!$this->_connected) {
344           return false;
345        }
346
347        $this->_query_count++;
348
349        $debugqry = preg_replace("/\n[\t ]+/u", "\n", $query);
350        if ($this->getParam('db_always_debug') || $debug) {
351            if ($debug > 1) {
352                dump($debugqry, true, SC_DUMP_PRINT_R, __FILE__, __LINE__);
353            } else {
354                echo "<!-- ----------------- Query $this->_query_count ---------------------\n$debugqry\n-->\n";
355            }
356        }
357
358        // Ensure we have an active connection.
359        // If we continue on a dead connection we might experience a "MySQL server has gone away" error.
360        // http://dev.mysql.com/doc/refman/5.0/en/gone-away.html
361        if (!mysql_ping($this->dbh)) {
362            $app->logMsg(sprintf('MySQL ping failed; reconnecting
 ("%s")', truncate(trim($debugqry), 150)), LOG_DEBUG, __FILE__, __LINE__);
363            $this->reconnect();
364        }
365
366        // Execute!
367        $qid = mysql_query($query, $this->dbh);
368
369        // Error checking.
370        if (!$qid || mysql_error($this->dbh)) {
371            $app->logMsg(sprintf('MySQL error %s: %s in query: %s', mysql_errno($this->dbh), mysql_error($this->dbh), $debugqry), LOG_EMERG, __FILE__, __LINE__);
372            if ($this->getParam('db_debug')) {
373                if (!$app->isCLI()) {
374                    echo '<pre style="padding:1em;background:#ddd;font:0.9rem monospace;">' . wordwrap(mysql_error($this->dbh)) . '<hr>' . htmlspecialchars($debugqry) . '</pre>';
375                }
376            }
377            // Die if db_die_on_failure = true, or just continue without connection
378            return $this->_fail();
379        }
380
381        return $qid;
382    }
383
384    /**
385     * Loads a list of tables in the current database into an array, and returns
386     * true if the requested table is found. Use this function to enable/disable
387     * functionality based upon the current available db tables or to dynamically
388     * create tables if missing.
389     *
390     * @param  string $table                The name of the table to search.
391     * @param  bool   $use_cached_results   Get fresh table info (in case DB changed).
392     * @return bool                         true if given $table exists.
393     */
394    public function tableExists($table, $use_cached_results=true)
395    {
396        $app =& App::getInstance();
397
398        if (!$this->_connected) {
399            return false;
400        }
401
402        if (is_null(self::$existing_tables) || !$use_cached_results) {
403            self::$existing_tables = array();
404            $qid = $this->query("SHOW TABLES");
405            while (list($row) = mysql_fetch_row($qid)) {
406                self::$existing_tables[] = $row;
407            }
408        }
409
410        if (in_array($table, self::$existing_tables)) {
411            return true;
412        } else {
413            $app->logMsg(sprintf('Nonexistent DB table: %s.%s', $this->getParam('db_name'), $table), LOG_INFO, __FILE__, __LINE__);
414            return false;
415        }
416    }
417
418    /**
419     * Tests if the given array of columns exists in the specified table.
420     *
421     * @param  string $table                The name of the table to search.
422     * @param  array  $columns              An array of column names.
423     * @param  bool   $strict               Exact schema match. If TRUE, test if *only* the given columns exist. If FALSE, test if given columns exist (possibly amongst others).
424     * @param  bool   $use_cached_results   Get fresh table info (in case DB changed).
425     * @return bool                         true if column(s) exist.
426     */
427    public function columnExists($table, $columns, $strict=true, $use_cached_results=true)
428    {
429        $app =& App::getInstance();
430
431        if (!$this->_connected) {
432            $app->logMsg(sprintf('No DB connection to run %s', __METHOD__), LOG_NOTICE, __FILE__, __LINE__);
433            return false;
434        }
435
436        // Ensure the table exists.
437        if (!$this->tableExists($table, $use_cached_results)) {
438            $app->logMsg(sprintf('Table does not exist: %s', $table), LOG_NOTICE, __FILE__, __LINE__);
439            return false;
440        }
441
442        // For single-value columns.
443        if (!is_array($columns)) {
444            $columns = array($columns);
445        }
446
447        if (!isset(self::$table_columns[$table]) || !$use_cached_results) {
448            // Populate and cache array of current columns for this table.
449            self::$table_columns[$table] = array();
450            $qid = $this->query("DESCRIBE $table");
451            while ($row = mysql_fetch_row($qid)) {
452                self::$table_columns[$table][] = $row[0];
453            }
454        }
455
456        if ($strict) {
457            // Do an exact comparison of table schemas.
458            sort($columns);
459            sort(self::$table_columns[$table]);
460            return self::$table_columns[$table] == $columns;
461        } else {
462            // Only check that the specified columns are available in the table.
463            $match_columns = array_intersect(self::$table_columns[$table], $columns);
464            sort($columns);
465            sort($match_columns);
466            return $match_columns == $columns;
467        }
468    }
469
470    /*
471    * Return the total number of queries executed thus far.
472    *
473    * @access   public
474    * @return   int Number of queries
475    * @author   Quinn Comendant <quinn@strangecode.com>
476    * @version  1.0
477    * @since    15 Jun 2006 11:46:05
478    */
479    public function numQueries()
480    {
481        return $this->_query_count;
482    }
483
484    /**
485     * Reset cached items.
486     *
487     * @access  public
488     * @author  Quinn Comendant <quinn@strangecode.com>
489     * @since   28 Aug 2005 22:10:50
490     */
491    public function resetCache()
492    {
493        self::$existing_tables = null;
494        self::$table_columns = null;
495    }
496
497    /**
498     * Returns the values of an ENUM or SET column, returning them as an array.
499     *
500     * @param  string $db_table   database table to lookup
501     * @param  string $db_col     database column to lookup
502     * @param  bool   $sort          Sort the output.
503     * @return array    Array of the set/enum values on success, false on failure.
504     */
505    public function getEnumValues($db_table, $db_col, $sort=false)
506    {
507        $app =& App::getInstance();
508
509        $qid = $this->query("SHOW COLUMNS FROM " . $this->escapeString($db_table) . " LIKE '" . $this->escapeString($db_col) . "'", false);
510
511        $row = mysql_fetch_row($qid);
512        if (preg_match('/^enum|^set/i', $row[1]) && preg_match_all("/'([^']*)'/", $row[1], $matches)) {
513            if ($sort) {
514                natsort($matches[1]);
515            }
516            return $matches[1];
517        } else {
518            $app->logMsg(sprintf('No set or enum fields found in %s.%s', $db_table, $db_col), LOG_ERR, __FILE__, __LINE__);
519            return false;
520        }
521    }
522
523} // End.
524
Note: See TracBrowser for help on using the repository browser.