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

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

Add $app->isCLI() to replace $app->cli

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