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

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

Reduce timezone support to simply setting defaults for user, php, and mysql (all UTC), just to ensure consistency

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