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

Last change on this file since 644 was 630, checked in by anonymous, 6 years ago

Disable App::sslOn(). Better logging on Email::send() unreplaced variables. Fix the elusive 'Database table session_tbl has invalid columns' error.

File size: 16.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{
[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
[1]203        return true;
204    }
[42]205
[1]206    /**
207     * Close db connection.
208     *
209     * @access  public
210     * @author  Quinn Comendant <quinn@strangecode.com>
211     * @since   28 Aug 2005 14:32:01
212     */
[468]213    public function close()
[1]214    {
[136]215        if (!$this->_connected) {
[1]216            return false;
217        }
[416]218        $this->_connected = false;
[136]219        return mysql_close($this->dbh);
[1]220    }
[465]221
[230]222    /*
[416]223    *
[465]224    *
[416]225    * @access   public
[465]226    * @param
227    * @return
[416]228    * @author   Quinn Comendant <quinn@strangecode.com>
229    * @version  1.0
230    * @since    03 Jul 2013 14:50:23
231    */
[468]232    public function reconnect()
[416]233    {
234        $this->close();
235        $this->connect();
236    }
[465]237
[416]238    /*
[230]239    * Die only if db_die_on_failure is true. This will be set to false for some cases
240    * when a database is not required for web app functionality.
241    *
242    * @access   public
243    * @param    string  $msg Print $msg when dying.
244    * @return   bool    false If we don't die.
245    * @author   Quinn Comendant <quinn@strangecode.com>
246    * @version  1.0
247    * @since    15 Jan 2007 15:59:00
248    */
[484]249    protected function _fail()
[230]250    {
[547]251        $app =& App::getInstance();
252
[230]253        if ($this->getParam('db_die_on_failure')) {
[547]254            if (!$app->cli) {
[484]255                // For http requests, send a Service Unavailable header.
256                header(' ', true, 503);
257                echo _("This page is temporarily unavailable. Please try again in a few minutes.");
258            }
[230]259            die;
260        } else {
261            return false;
262        }
263    }
[42]264
[1]265    /**
266     * Return the current database handler.
267     *
268     * @access  public
269     * @return  resource Current value of $this->dbh.
270     * @author  Quinn Comendant <quinn@strangecode.com>
271     * @since   20 Aug 2005 13:50:36
272     */
[468]273    public function getDBH()
[1]274    {
[136]275        if (!$this->_connected) {
[1]276            return false;
277        }
278
[136]279        return $this->dbh;
[1]280    }
[42]281
[1]282    /**
283     * Returns connection status
284     *
285     * @access  public
286     * @author  Quinn Comendant <quinn@strangecode.com>
287     * @since   28 Aug 2005 14:58:09
288     */
[468]289    public function isConnected()
[1]290    {
[136]291        return (true === $this->_connected);
[1]292    }
[465]293
[71]294    /**
295     * Returns a properly escaped string using mysql_real_escape_string() with the current connection's charset.
296     *
297     * @access  public
298     * @param   string  $string     Input string to be sent as SQL query.
299     * @return  string              Escaped string from mysql_real_escape_string()
300     * @author  Quinn Comendant <quinn@strangecode.com>
301     * @since   06 Mar 2006 16:41:32
302     */
[468]303    public function escapeString($string)
[71]304    {
[136]305        if (!$this->_connected) {
306            return false;
[71]307        }
[136]308
309        return mysql_real_escape_string($string, $this->dbh);
[71]310    }
[42]311
[1]312    /**
313     * A wrapper for mysql_query. Allows us to set the database link_identifier,
314     * to trap errors and ease debugging.
315     *
316     * @param  string  $query   The SQL query to execute
317     * @param  bool    $debug   If true, prints debugging info
318     * @return resource         Query identifier
319     */
[468]320    public function query($query, $debug=false)
[465]321    {
[136]322        $app =& App::getInstance();
[42]323
[136]324        if (!$this->_connected) {
[1]325           return false;
326        }
327
[172]328        $this->_query_count++;
329
[1]330        $debugqry = preg_replace("/\n[\t ]+/", "\n", $query);
[136]331        if ($this->getParam('db_always_debug') || $debug) {
[172]332            echo "<!-- ----------------- Query $this->_query_count ---------------------\n$debugqry\n-->\n";
[1]333        }
[465]334
335        // Ensure we have an active connection.
[419]336        // If we continue on a dead connection we might experience a "MySQL server has gone away" error.
337        // http://dev.mysql.com/doc/refman/5.0/en/gone-away.html
[416]338        if (!mysql_ping($this->dbh)) {
[546]339            $app->logMsg(sprintf('MySQL ping failed; reconnecting
 ("%s")', truncate(trim($debugqry), 150)), LOG_DEBUG, __FILE__, __LINE__);
[416]340            $this->reconnect();
341        }
[42]342
[1]343        // Execute!
[136]344        $qid = mysql_query($query, $this->dbh);
[42]345
[1]346        // Error checking.
[136]347        if (!$qid || mysql_error($this->dbh)) {
[230]348            $app->logMsg(sprintf('MySQL error %s: %s in query: %s', mysql_errno($this->dbh), mysql_error($this->dbh), $debugqry), LOG_EMERG, __FILE__, __LINE__);
[136]349            if ($this->getParam('db_debug')) {
[547]350                if (!$app->cli) {
[484]351                    echo '<pre style="padding:2em; background:#ddd; font:9px monaco;">' . wordwrap(mysql_error($this->dbh)) . '<hr>' . htmlspecialchars($debugqry) . '</pre>';
352                }
[465]353            }
[230]354            // Die if db_die_on_failure = true, or just continue without connection
355            return $this->_fail();
[1]356        }
[42]357
[1]358        return $qid;
359    }
360
361    /**
[42]362     * Loads a list of tables in the current database into an array, and returns
[1]363     * true if the requested table is found. Use this function to enable/disable
[334]364     * functionality based upon the current available db tables or to dynamically
[1]365     * create tables if missing.
366     *
[396]367     * @param  string $table                The name of the table to search.
368     * @param  bool   $use_cached_results   Get fresh table info (in case DB changed).
369     * @return bool                         true if given $table exists.
[1]370     */
[468]371    public function tableExists($table, $use_cached_results=true)
[42]372    {
[479]373        $app =& App::getInstance();
[465]374
[136]375        if (!$this->_connected) {
[1]376            return false;
377        }
378
[630]379        if (is_null(self::$existing_tables) || !$use_cached_results) {
380            self::$existing_tables = array();
[136]381            $qid = $this->query("SHOW TABLES");
[1]382            while (list($row) = mysql_fetch_row($qid)) {
[630]383                self::$existing_tables[] = $row;
[1]384            }
385        }
[630]386
387        if (in_array($table, self::$existing_tables)) {
[1]388            return true;
389        } else {
[484]390            $app->logMsg(sprintf('Nonexistent DB table: %s.%s', $this->getParam('db_name'), $table), LOG_INFO, __FILE__, __LINE__);
[1]391            return false;
392        }
393    }
[42]394
[1]395    /**
396     * Tests if the given array of columns exists in the specified table.
397     *
[396]398     * @param  string $table                The name of the table to search.
399     * @param  array  $columns              An array of column names.
[550]400     * @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]401     * @param  bool   $use_cached_results   Get fresh table info (in case DB changed).
402     * @return bool                         true if column(s) exist.
[1]403     */
[468]404    public function columnExists($table, $columns, $strict=true, $use_cached_results=true)
[42]405    {
[532]406        $app =& App::getInstance();
407
[136]408        if (!$this->_connected) {
[532]409            $app->logMsg(sprintf('No DB connection to run %s', __METHOD__), LOG_NOTICE, __FILE__, __LINE__);
[1]410            return false;
411        }
412
413        // Ensure the table exists.
[136]414        if (!$this->tableExists($table, $use_cached_results)) {
[575]415            $app->logMsg(sprintf('Table does not exist: %s', $table), LOG_NOTICE, __FILE__, __LINE__);
[1]416            return false;
417        }
[42]418
[1]419        // For single-value columns.
420        if (!is_array($columns)) {
421            $columns = array($columns);
422        }
[42]423
[630]424        if (!isset(self::$table_columns[$table]) || !$use_cached_results) {
[1]425            // Populate and cache array of current columns for this table.
[630]426            self::$table_columns[$table] = array();
[136]427            $qid = $this->query("DESCRIBE $table");
[1]428            while ($row = mysql_fetch_row($qid)) {
[630]429                self::$table_columns[$table][] = $row[0];
[1]430            }
431        }
[42]432
[1]433        if ($strict) {
434            // Do an exact comparison of table schemas.
435            sort($columns);
[630]436            sort(self::$table_columns[$table]);
437            return self::$table_columns[$table] == $columns;
[1]438        } else {
439            // Only check that the specified columns are available in the table.
[630]440            $match_columns = array_intersect(self::$table_columns[$table], $columns);
[1]441            sort($columns);
442            sort($match_columns);
443            return $match_columns == $columns;
444        }
445    }
[465]446
[172]447    /*
[396]448    * Return the total number of queries executed thus far.
[172]449    *
450    * @access   public
451    * @return   int Number of queries
452    * @author   Quinn Comendant <quinn@strangecode.com>
453    * @version  1.0
454    * @since    15 Jun 2006 11:46:05
455    */
[468]456    public function numQueries()
[172]457    {
458        return $this->_query_count;
459    }
[42]460
[1]461    /**
462     * Reset cached items.
463     *
464     * @access  public
465     * @author  Quinn Comendant <quinn@strangecode.com>
466     * @since   28 Aug 2005 22:10:50
467     */
[468]468    public function resetCache()
[1]469    {
[630]470        self::$existing_tables = null;
471        self::$table_columns = null;
[1]472    }
[42]473
[497]474    /**
475     * Returns the values of an ENUM or SET column, returning them as an array.
476     *
477     * @param  string $db_table   database table to lookup
478     * @param  string $db_col     database column to lookup
479     * @param  bool   $sort          Sort the output.
480     * @return array    Array of the set/enum values on success, false on failure.
481     */
482    public function getEnumValues($db_table, $db_col, $sort=false)
483    {
484        $app =& App::getInstance();
485
486        $qid = $this->query("SHOW COLUMNS FROM " . $this->escapeString($db_table) . " LIKE '" . $this->escapeString($db_col) . "'", false);
487
488        $row = mysql_fetch_row($qid);
489        if (preg_match('/^enum|^set/i', $row[1]) && preg_match_all("/'([^']*)'/", $row[1], $matches)) {
490            if ($sort) {
491                natsort($matches[1]);
492            }
493            return $matches[1];
494        } else {
495            $app->logMsg(sprintf('No set or enum fields found in %s.%s', $db_table, $db_col), LOG_ERR, __FILE__, __LINE__);
496            return false;
497        }
498    }
499
500
[1]501} // End.
502
Note: See TracBrowser for help on using the repository browser.