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

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

Add timezone support

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