source: trunk/lib/DB.inc.php

Last change on this file was 810, checked in by anonymous, 2 months ago

Enable setting db_timezone during runtime. Refactor setParam() in App, DB, and PDO.

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