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

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

Fix minor bugs. Detect http port and add to site_port, site_url, and page_url params of App.

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