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

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

Reduce timezone support to simply setting defaults for user, php, and mysql (all UTC), just to ensure consistency

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