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

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

Fix regression

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
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/Mexico_City" or "-6:00".
206        if ($app->getParam('timezone') && $app->getParam('timezone') == $tz && preg_match('!^([A-Z_/-]{3,}|[-+\d:]+)$!/i', $tz)) {
207            // https://dev.mysql.com/doc/refman/5.5/en/time-zone-support.html
208            $this->query(sprintf("SET SESSION time_zone = '%s'", $tz));
209        }
210
211        return true;
212    }
213
214    /**
215     * Close db connection.
216     *
217     * @access  public
218     * @author  Quinn Comendant <quinn@strangecode.com>
219     * @since   28 Aug 2005 14:32:01
220     */
221    public function close()
222    {
223        if (!$this->_connected) {
224            return false;
225        }
226        $this->_connected = false;
227        return mysql_close($this->dbh);
228    }
229
230    /*
231    *
232    *
233    * @access   public
234    * @param
235    * @return
236    * @author   Quinn Comendant <quinn@strangecode.com>
237    * @version  1.0
238    * @since    03 Jul 2013 14:50:23
239    */
240    public function reconnect()
241    {
242        $this->close();
243        $this->connect();
244    }
245
246    /*
247    * Die only if db_die_on_failure is true. This will be set to false for some cases
248    * when a database is not required for web app functionality.
249    *
250    * @access   public
251    * @param    string  $msg Print $msg when dying.
252    * @return   bool    false If we don't die.
253    * @author   Quinn Comendant <quinn@strangecode.com>
254    * @version  1.0
255    * @since    15 Jan 2007 15:59:00
256    */
257    protected function _fail()
258    {
259        $app =& App::getInstance();
260
261        if ($this->getParam('db_die_on_failure')) {
262            if (!$app->cli) {
263                // For http requests, send a Service Unavailable header.
264                header(' ', true, 503);
265                echo _("This page is temporarily unavailable. Please try again in a few minutes.");
266            }
267            die;
268        } else {
269            return false;
270        }
271    }
272
273    /**
274     * Return the current database handler.
275     *
276     * @access  public
277     * @return  resource Current value of $this->dbh.
278     * @author  Quinn Comendant <quinn@strangecode.com>
279     * @since   20 Aug 2005 13:50:36
280     */
281    public function getDBH()
282    {
283        if (!$this->_connected) {
284            return false;
285        }
286
287        return $this->dbh;
288    }
289
290    /**
291     * Returns connection status
292     *
293     * @access  public
294     * @author  Quinn Comendant <quinn@strangecode.com>
295     * @since   28 Aug 2005 14:58:09
296     */
297    public function isConnected()
298    {
299        return (true === $this->_connected);
300    }
301
302    /**
303     * Returns a properly escaped string using mysql_real_escape_string() with the current connection's charset.
304     *
305     * @access  public
306     * @param   string  $string     Input string to be sent as SQL query.
307     * @return  string              Escaped string from mysql_real_escape_string()
308     * @author  Quinn Comendant <quinn@strangecode.com>
309     * @since   06 Mar 2006 16:41:32
310     */
311    public function escapeString($string)
312    {
313        if (!$this->_connected) {
314            return false;
315        }
316
317        return mysql_real_escape_string($string, $this->dbh);
318    }
319
320    /**
321     * A wrapper for mysql_query. Allows us to set the database link_identifier,
322     * to trap errors and ease debugging.
323     *
324     * @param  string  $query   The SQL query to execute
325     * @param  bool    $debug   If true, prints debugging info
326     * @return resource         Query identifier
327     */
328    public function query($query, $debug=false)
329    {
330        $app =& App::getInstance();
331
332        if (!$this->_connected) {
333           return false;
334        }
335
336        $this->_query_count++;
337
338        $debugqry = preg_replace("/\n[\t ]+/", "\n", $query);
339        if ($this->getParam('db_always_debug') || $debug) {
340            echo "<!-- ----------------- Query $this->_query_count ---------------------\n$debugqry\n-->\n";
341        }
342
343        // Ensure we have an active connection.
344        // If we continue on a dead connection we might experience a "MySQL server has gone away" error.
345        // http://dev.mysql.com/doc/refman/5.0/en/gone-away.html
346        if (!mysql_ping($this->dbh)) {
347            $app->logMsg(sprintf('MySQL ping failed; reconnecting
 ("%s")', truncate(trim($debugqry), 150)), LOG_DEBUG, __FILE__, __LINE__);
348            $this->reconnect();
349        }
350
351        // Execute!
352        $qid = mysql_query($query, $this->dbh);
353
354        // Error checking.
355        if (!$qid || mysql_error($this->dbh)) {
356            $app->logMsg(sprintf('MySQL error %s: %s in query: %s', mysql_errno($this->dbh), mysql_error($this->dbh), $debugqry), LOG_EMERG, __FILE__, __LINE__);
357            if ($this->getParam('db_debug')) {
358                if (!$app->cli) {
359                    echo '<pre style="padding:2em; background:#ddd; font:9px monaco;">' . wordwrap(mysql_error($this->dbh)) . '<hr>' . htmlspecialchars($debugqry) . '</pre>';
360                }
361            }
362            // Die if db_die_on_failure = true, or just continue without connection
363            return $this->_fail();
364        }
365
366        return $qid;
367    }
368
369    /**
370     * Loads a list of tables in the current database into an array, and returns
371     * true if the requested table is found. Use this function to enable/disable
372     * functionality based upon the current available db tables or to dynamically
373     * create tables if missing.
374     *
375     * @param  string $table                The name of the table to search.
376     * @param  bool   $use_cached_results   Get fresh table info (in case DB changed).
377     * @return bool                         true if given $table exists.
378     */
379    public function tableExists($table, $use_cached_results=true)
380    {
381        $app =& App::getInstance();
382
383        if (!$this->_connected) {
384            return false;
385        }
386
387        if (is_null(self::$existing_tables) || !$use_cached_results) {
388            self::$existing_tables = array();
389            $qid = $this->query("SHOW TABLES");
390            while (list($row) = mysql_fetch_row($qid)) {
391                self::$existing_tables[] = $row;
392            }
393        }
394
395        if (in_array($table, self::$existing_tables)) {
396            return true;
397        } else {
398            $app->logMsg(sprintf('Nonexistent DB table: %s.%s', $this->getParam('db_name'), $table), LOG_INFO, __FILE__, __LINE__);
399            return false;
400        }
401    }
402
403    /**
404     * Tests if the given array of columns exists in the specified table.
405     *
406     * @param  string $table                The name of the table to search.
407     * @param  array  $columns              An array of column names.
408     * @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).
409     * @param  bool   $use_cached_results   Get fresh table info (in case DB changed).
410     * @return bool                         true if column(s) exist.
411     */
412    public function columnExists($table, $columns, $strict=true, $use_cached_results=true)
413    {
414        $app =& App::getInstance();
415
416        if (!$this->_connected) {
417            $app->logMsg(sprintf('No DB connection to run %s', __METHOD__), LOG_NOTICE, __FILE__, __LINE__);
418            return false;
419        }
420
421        // Ensure the table exists.
422        if (!$this->tableExists($table, $use_cached_results)) {
423            $app->logMsg(sprintf('Table does not exist: %s', $table), LOG_NOTICE, __FILE__, __LINE__);
424            return false;
425        }
426
427        // For single-value columns.
428        if (!is_array($columns)) {
429            $columns = array($columns);
430        }
431
432        if (!isset(self::$table_columns[$table]) || !$use_cached_results) {
433            // Populate and cache array of current columns for this table.
434            self::$table_columns[$table] = array();
435            $qid = $this->query("DESCRIBE $table");
436            while ($row = mysql_fetch_row($qid)) {
437                self::$table_columns[$table][] = $row[0];
438            }
439        }
440
441        if ($strict) {
442            // Do an exact comparison of table schemas.
443            sort($columns);
444            sort(self::$table_columns[$table]);
445            return self::$table_columns[$table] == $columns;
446        } else {
447            // Only check that the specified columns are available in the table.
448            $match_columns = array_intersect(self::$table_columns[$table], $columns);
449            sort($columns);
450            sort($match_columns);
451            return $match_columns == $columns;
452        }
453    }
454
455    /*
456    * Return the total number of queries executed thus far.
457    *
458    * @access   public
459    * @return   int Number of queries
460    * @author   Quinn Comendant <quinn@strangecode.com>
461    * @version  1.0
462    * @since    15 Jun 2006 11:46:05
463    */
464    public function numQueries()
465    {
466        return $this->_query_count;
467    }
468
469    /**
470     * Reset cached items.
471     *
472     * @access  public
473     * @author  Quinn Comendant <quinn@strangecode.com>
474     * @since   28 Aug 2005 22:10:50
475     */
476    public function resetCache()
477    {
478        self::$existing_tables = null;
479        self::$table_columns = null;
480    }
481
482    /**
483     * Returns the values of an ENUM or SET column, returning them as an array.
484     *
485     * @param  string $db_table   database table to lookup
486     * @param  string $db_col     database column to lookup
487     * @param  bool   $sort          Sort the output.
488     * @return array    Array of the set/enum values on success, false on failure.
489     */
490    public function getEnumValues($db_table, $db_col, $sort=false)
491    {
492        $app =& App::getInstance();
493
494        $qid = $this->query("SHOW COLUMNS FROM " . $this->escapeString($db_table) . " LIKE '" . $this->escapeString($db_col) . "'", false);
495
496        $row = mysql_fetch_row($qid);
497        if (preg_match('/^enum|^set/i', $row[1]) && preg_match_all("/'([^']*)'/", $row[1], $matches)) {
498            if ($sort) {
499                natsort($matches[1]);
500            }
501            return $matches[1];
502        } else {
503            $app->logMsg(sprintf('No set or enum fields found in %s.%s', $db_table, $db_col), LOG_ERR, __FILE__, __LINE__);
504            return false;
505        }
506    }
507
508
509} // End.
510
Note: See TracBrowser for help on using the repository browser.