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

Last change on this file since 484 was 484, checked in by anonymous, 10 years ago

Changed private methods and properties to protected. A few minor bug fixes.

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