source: trunk/lib/DB.inc.php

Last change on this file was 810, checked in by anonymous, 3 months ago

Enable setting db_timezone during runtime. Refactor setParam() in App, DB, and PDO.

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