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

Last change on this file since 724 was 724, checked in by anonymous, 4 years ago

Use the /u regex modifier only when using UTF-8. Disable indexed array key removal from URL query args.

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