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

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

Add support for mysql-specific character sets and collations

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