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

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

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

File size: 17.6 KB
RevLine 
[1]1<?php
2/**
[362]3 * The Strangecode Codebase - a general application development framework for PHP
4 * For details visit the project site: <http://trac.strangecode.com/codebase/>
[396]5 * Copyright 2001-2012 Strangecode, LLC
[465]6 *
[362]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.
[465]13 *
[362]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.
[465]18 *
[362]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/**
[1]24 * DB.inc.php
25 *
[136]26 * Very lightweight DB semi-abstraction layer. Mainly to catch errors with mysql_query, with some goodies.
[1]27 *
28 * @author  Quinn Comendant <quinn@strangecode.com>
[136]29 * @version 2.1
[1]30 */
[42]31
[502]32class DB
33{
[468]34    // A place to keep an object instance for the singleton pattern.
[484]35    protected static $instance = null;
[468]36
[136]37    // If $db->connect has successfully opened a db connection.
[484]38    protected $_connected = false;
[1]39
[136]40    // Database handle.
[468]41    public $dbh;
[465]42
[172]43    // Count how many queries run during the whole instance.
[484]44    protected $_query_count = 0;
[1]45
46    // Hash of DB parameters.
[484]47    protected $_params = array();
[1]48
49    // Default parameters.
[484]50    protected $_param_defaults = array(
[1]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
[231]58        // Display all SQL queries. FALSE recommended for production sites.
[136]59        'db_always_debug' => false,
60
[231]61        // Display db errors. FALSE recommended for production sites.
[136]62        'db_debug' => false,
[465]63
[231]64        // Script stops on db error. TRUE recommended for production sites.
65        'db_die_on_failure' => true,
[601]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',
[660]70
71        // Timezone for MySQL.
72        'timezone' => 'UTC',
[683]73
74        // MySQL character set and collation.
75        'character_set' => '',
76        'collation' => '',
[1]77    );
[42]78
[1]79    // Translate between HTML and MySQL character set names.
[468]80    public $mysql_character_sets = array(
[1]81        'utf-8' => 'utf8',
82        'iso-8859-1' => 'latin1',
83    );
[42]84
[1]85    // Caches.
[630]86    protected static $existing_tables = null;
87    protected static $table_columns = null;
[42]88
[1]89    /**
[601]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    /**
[1]99     * This method enforces the singleton pattern for this class.
100     *
[136]101     * @return  object  Reference to the global DB object.
[1]102     * @access  public
103     * @static
104     */
[468]105    public static function &getInstance()
[1]106    {
[468]107        if (self::$instance === null) {
108            self::$instance = new self();
[1]109        }
110
[468]111        return self::$instance;
[1]112    }
[42]113
[1]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     */
[468]121    public function setParam($params)
[1]122    {
[479]123        $app =& App::getInstance();
[465]124
[1]125        if (isset($params) && is_array($params)) {
126            // Merge new parameters with old overriding only those passed.
[136]127            $this->_params = array_merge($this->_params, $params);
[1]128        } else {
[136]129            $app->logMsg(sprintf('Parameters are not an array: %s', $params), LOG_ERR, __FILE__, __LINE__);
[1]130        }
131    }
132
133    /**
[136]134     * Return the value of a parameter, if it exists.
[1]135     *
[136]136     * @access public
137     * @param string $param        Which parameter to return.
138     * @return mixed               Configured parameter value.
[1]139     */
[468]140    public function getParam($param)
[1]141    {
[479]142        $app =& App::getInstance();
[465]143
[478]144        if (array_key_exists($param, $this->_params)) {
[136]145            return $this->_params[$param];
[1]146        } else {
[146]147            $app->logMsg(sprintf('Parameter is not set: %s', $param), LOG_DEBUG, __FILE__, __LINE__);
[1]148            return null;
149        }
150    }
[42]151
[1]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     */
[468]159    public function connect()
[1]160    {
[479]161        $app =& App::getInstance();
[465]162
[136]163        if (!$this->getParam('db_name') || !$this->getParam('db_user') || !$this->getParam('db_pass')) {
164            $app->logMsg('Database credentials missing.', LOG_EMERG, __FILE__, __LINE__);
[1]165            return false;
166        }
[42]167
[563]168        if (!$this->getParam('db_server')) {
169            // If db_server not specified, assume localhost.
[564]170            $this->setParam(array('db_server' => 'localhost'));
[563]171        }
172
[1]173        // Connect to database. Always create a new link to the server.
[563]174        // Connection errors are suppressed so we can do our own error management below.
[468]175        if ($this->dbh = @mysql_connect($this->getParam('db_server'), $this->getParam('db_user'), $this->getParam('db_pass'), true)) {
[1]176            // Select database
[136]177            mysql_select_db($this->getParam('db_name'), $this->dbh);
[1]178        }
[42]179
[15]180        // Test for connection errors.
[136]181        if (!$this->dbh || mysql_error($this->dbh)) {
[627]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'));
[136]183            $app->logMsg($mysql_error_msg, LOG_EMERG, __FILE__, __LINE__);
[15]184
185            // Print helpful or pretty error?
[136]186            if ($this->getParam('db_debug')) {
[697]187                if (!$app->isCLI()) {
188                    printf('<pre style="padding:1em;background:#ddd;font:0.9rem monospace;">%s</pre>', $mysql_error_msg);
189                }
[1]190            }
[15]191
[416]192            // Die if db_die_on_failure = true, or just continue without connection.
[230]193            return $this->_fail();
[1]194        }
[42]195
[1]196        // DB connection success!
[136]197        $this->_connected = true;
[1]198
[683]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'))]));
[209]202        }
[683]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        }
[10]210
[601]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
[660]216        // Set MySQL session timezone.
217        if ($this->getParam('timezone')) {
[658]218            // https://dev.mysql.com/doc/refman/5.5/en/time-zone-support.html
[661]219            $this->query(sprintf("SET time_zone = '%s';", $this->getParam('timezone')));
[654]220        }
221
[1]222        return true;
223    }
[42]224
[1]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     */
[468]232    public function close()
[1]233    {
[136]234        if (!$this->_connected) {
[1]235            return false;
236        }
[416]237        $this->_connected = false;
[136]238        return mysql_close($this->dbh);
[1]239    }
[465]240
[230]241    /*
[416]242    *
[465]243    *
[416]244    * @access   public
[465]245    * @param
246    * @return
[416]247    * @author   Quinn Comendant <quinn@strangecode.com>
248    * @version  1.0
249    * @since    03 Jul 2013 14:50:23
250    */
[468]251    public function reconnect()
[416]252    {
253        $this->close();
254        $this->connect();
255    }
[465]256
[416]257    /*
[230]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    */
[484]268    protected function _fail()
[230]269    {
[547]270        $app =& App::getInstance();
271
[230]272        if ($this->getParam('db_die_on_failure')) {
[665]273            if (!$app->isCLI()) {
[484]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            }
[230]278            die;
279        } else {
280            return false;
281        }
282    }
[42]283
[1]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     */
[468]292    public function getDBH()
[1]293    {
[136]294        if (!$this->_connected) {
[1]295            return false;
296        }
297
[136]298        return $this->dbh;
[1]299    }
[42]300
[1]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     */
[468]308    public function isConnected()
[1]309    {
[136]310        return (true === $this->_connected);
[1]311    }
[465]312
[71]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     */
[468]322    public function escapeString($string)
[71]323    {
[136]324        if (!$this->_connected) {
325            return false;
[71]326        }
[136]327
328        return mysql_real_escape_string($string, $this->dbh);
[71]329    }
[42]330
[1]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     */
[468]339    public function query($query, $debug=false)
[465]340    {
[136]341        $app =& App::getInstance();
[42]342
[136]343        if (!$this->_connected) {
[1]344           return false;
345        }
346
[172]347        $this->_query_count++;
348
[697]349        $debugqry = preg_replace("/\n[\t ]+/u", "\n", $query);
[136]350        if ($this->getParam('db_always_debug') || $debug) {
[679]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            }
[1]356        }
[465]357
358        // Ensure we have an active connection.
[419]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
[416]361        if (!mysql_ping($this->dbh)) {
[546]362            $app->logMsg(sprintf('MySQL ping failed; reconnecting
 ("%s")', truncate(trim($debugqry), 150)), LOG_DEBUG, __FILE__, __LINE__);
[416]363            $this->reconnect();
364        }
[42]365
[1]366        // Execute!
[136]367        $qid = mysql_query($query, $this->dbh);
[42]368
[1]369        // Error checking.
[136]370        if (!$qid || mysql_error($this->dbh)) {
[230]371            $app->logMsg(sprintf('MySQL error %s: %s in query: %s', mysql_errno($this->dbh), mysql_error($this->dbh), $debugqry), LOG_EMERG, __FILE__, __LINE__);
[136]372            if ($this->getParam('db_debug')) {
[665]373                if (!$app->isCLI()) {
[697]374                    echo '<pre style="padding:1em;background:#ddd;font:0.9rem monospace;">' . wordwrap(mysql_error($this->dbh)) . '<hr>' . htmlspecialchars($debugqry) . '</pre>';
[484]375                }
[465]376            }
[230]377            // Die if db_die_on_failure = true, or just continue without connection
378            return $this->_fail();
[1]379        }
[42]380
[1]381        return $qid;
382    }
383
384    /**
[42]385     * Loads a list of tables in the current database into an array, and returns
[1]386     * true if the requested table is found. Use this function to enable/disable
[334]387     * functionality based upon the current available db tables or to dynamically
[1]388     * create tables if missing.
389     *
[396]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.
[1]393     */
[468]394    public function tableExists($table, $use_cached_results=true)
[42]395    {
[479]396        $app =& App::getInstance();
[465]397
[136]398        if (!$this->_connected) {
[1]399            return false;
400        }
401
[630]402        if (is_null(self::$existing_tables) || !$use_cached_results) {
403            self::$existing_tables = array();
[136]404            $qid = $this->query("SHOW TABLES");
[1]405            while (list($row) = mysql_fetch_row($qid)) {
[630]406                self::$existing_tables[] = $row;
[1]407            }
408        }
[630]409
410        if (in_array($table, self::$existing_tables)) {
[1]411            return true;
412        } else {
[484]413            $app->logMsg(sprintf('Nonexistent DB table: %s.%s', $this->getParam('db_name'), $table), LOG_INFO, __FILE__, __LINE__);
[1]414            return false;
415        }
416    }
[42]417
[1]418    /**
419     * Tests if the given array of columns exists in the specified table.
420     *
[396]421     * @param  string $table                The name of the table to search.
422     * @param  array  $columns              An array of column names.
[550]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).
[396]424     * @param  bool   $use_cached_results   Get fresh table info (in case DB changed).
425     * @return bool                         true if column(s) exist.
[1]426     */
[468]427    public function columnExists($table, $columns, $strict=true, $use_cached_results=true)
[42]428    {
[532]429        $app =& App::getInstance();
430
[136]431        if (!$this->_connected) {
[532]432            $app->logMsg(sprintf('No DB connection to run %s', __METHOD__), LOG_NOTICE, __FILE__, __LINE__);
[1]433            return false;
434        }
435
436        // Ensure the table exists.
[136]437        if (!$this->tableExists($table, $use_cached_results)) {
[575]438            $app->logMsg(sprintf('Table does not exist: %s', $table), LOG_NOTICE, __FILE__, __LINE__);
[1]439            return false;
440        }
[42]441
[1]442        // For single-value columns.
443        if (!is_array($columns)) {
444            $columns = array($columns);
445        }
[42]446
[630]447        if (!isset(self::$table_columns[$table]) || !$use_cached_results) {
[1]448            // Populate and cache array of current columns for this table.
[630]449            self::$table_columns[$table] = array();
[136]450            $qid = $this->query("DESCRIBE $table");
[1]451            while ($row = mysql_fetch_row($qid)) {
[630]452                self::$table_columns[$table][] = $row[0];
[1]453            }
454        }
[42]455
[1]456        if ($strict) {
457            // Do an exact comparison of table schemas.
458            sort($columns);
[630]459            sort(self::$table_columns[$table]);
460            return self::$table_columns[$table] == $columns;
[1]461        } else {
462            // Only check that the specified columns are available in the table.
[630]463            $match_columns = array_intersect(self::$table_columns[$table], $columns);
[1]464            sort($columns);
465            sort($match_columns);
466            return $match_columns == $columns;
467        }
468    }
[465]469
[172]470    /*
[396]471    * Return the total number of queries executed thus far.
[172]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    */
[468]479    public function numQueries()
[172]480    {
481        return $this->_query_count;
482    }
[42]483
[1]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     */
[468]491    public function resetCache()
[1]492    {
[630]493        self::$existing_tables = null;
494        self::$table_columns = null;
[1]495    }
[42]496
[497]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
[1]523} // End.
524
Note: See TracBrowser for help on using the repository browser.