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

Last change on this file since 564 was 564, checked in by anonymous, 8 years ago

Fixed db_server=>localhost regression. Removed Auth->initDB from Auth->clear. Enabled logging by default for cb cli scripts.

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