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

Last change on this file since 523 was 502, checked in by anonymous, 9 years ago

Many minor fixes during pulso development

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