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

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

Add timezone support

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