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

Last change on this file since 600 was 575, checked in by anonymous, 7 years ago

Changed LOG_ levels.

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