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

Last change on this file since 729 was 724, checked in by anonymous, 4 years ago

Use the /u regex modifier only when using UTF-8. Disable indexed array key removal from URL query args.

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        }
[1]172        // Connect to database. Always create a new link to the server.
[563]173        // Connection errors are suppressed so we can do our own error management below.
[721]174        if ($this->dbh = @mysql_connect($this->getParam('db_server'), $this->getParam('db_user'), $this->getParam('db_pass'), true)) {
[1]175            // Select database
[136]176            mysql_select_db($this->getParam('db_name'), $this->dbh);
[1]177        }
[42]178
[15]179        // Test for connection errors.
[136]180        if (!$this->dbh || mysql_error($this->dbh)) {
[712]181            $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]182            $app->logMsg($mysql_error_msg, LOG_ERR, __FILE__, __LINE__);
[15]183
184            // Print helpful or pretty error?
[136]185            if ($this->getParam('db_debug')) {
[697]186                if (!$app->isCLI()) {
187                    printf('<pre style="padding:1em;background:#ddd;font:0.9rem monospace;">%s</pre>', $mysql_error_msg);
188                }
[1]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
[724]348        $debugqry = preg_replace('/\n[\t ]+/' . $app->getParam('preg_u'), "\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()) {
[697]373                    echo '<pre style="padding:1em;background:#ddd;font:0.9rem monospace;">' . wordwrap(mysql_error($this->dbh)) . '<hr>' . htmlspecialchars($debugqry) . '</pre>';
[484]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.