[1] | 1 | <?php |
---|
| 2 | /** |
---|
[362] | 3 | * The Strangecode Codebase - a general application development framework for PHP |
---|
| 4 | * For details visit the project site: <http://trac.strangecode.com/codebase/> |
---|
[396] | 5 | * Copyright 2001-2012 Strangecode, LLC |
---|
[465] | 6 | * |
---|
[362] | 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. |
---|
[465] | 13 | * |
---|
[362] | 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. |
---|
[465] | 18 | * |
---|
[362] | 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 | /** |
---|
[1] | 24 | * DB.inc.php |
---|
| 25 | * |
---|
[136] | 26 | * Very lightweight DB semi-abstraction layer. Mainly to catch errors with mysql_query, with some goodies. |
---|
[1] | 27 | * |
---|
| 28 | * @author Quinn Comendant <quinn@strangecode.com> |
---|
[136] | 29 | * @version 2.1 |
---|
[1] | 30 | */ |
---|
[42] | 31 | |
---|
[1] | 32 | class DB { |
---|
| 33 | |
---|
[468] | 34 | // A place to keep an object instance for the singleton pattern. |
---|
[484] | 35 | protected static $instance = null; |
---|
[468] | 36 | |
---|
[136] | 37 | // If $db->connect has successfully opened a db connection. |
---|
[484] | 38 | protected $_connected = false; |
---|
[1] | 39 | |
---|
[136] | 40 | // Database handle. |
---|
[468] | 41 | public $dbh; |
---|
[465] | 42 | |
---|
[172] | 43 | // Count how many queries run during the whole instance. |
---|
[484] | 44 | protected $_query_count = 0; |
---|
[1] | 45 | |
---|
| 46 | // Hash of DB parameters. |
---|
[484] | 47 | protected $_params = array(); |
---|
[1] | 48 | |
---|
| 49 | // Default parameters. |
---|
[484] | 50 | protected $_param_defaults = array( |
---|
[1] | 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 | |
---|
[231] | 58 | // Display all SQL queries. FALSE recommended for production sites. |
---|
[136] | 59 | 'db_always_debug' => false, |
---|
| 60 | |
---|
[231] | 61 | // Display db errors. FALSE recommended for production sites. |
---|
[136] | 62 | 'db_debug' => false, |
---|
[465] | 63 | |
---|
[231] | 64 | // Script stops on db error. TRUE recommended for production sites. |
---|
| 65 | 'db_die_on_failure' => true, |
---|
[1] | 66 | ); |
---|
[42] | 67 | |
---|
[1] | 68 | // Translate between HTML and MySQL character set names. |
---|
[468] | 69 | public $mysql_character_sets = array( |
---|
[1] | 70 | 'utf-8' => 'utf8', |
---|
| 71 | 'iso-8859-1' => 'latin1', |
---|
| 72 | ); |
---|
[42] | 73 | |
---|
[1] | 74 | // Caches. |
---|
[484] | 75 | protected $existing_tables; |
---|
| 76 | protected $table_columns; |
---|
[42] | 77 | |
---|
[1] | 78 | /** |
---|
| 79 | * This method enforces the singleton pattern for this class. |
---|
| 80 | * |
---|
[136] | 81 | * @return object Reference to the global DB object. |
---|
[1] | 82 | * @access public |
---|
| 83 | * @static |
---|
| 84 | */ |
---|
[468] | 85 | public static function &getInstance() |
---|
[1] | 86 | { |
---|
[468] | 87 | if (self::$instance === null) { |
---|
| 88 | self::$instance = new self(); |
---|
[1] | 89 | } |
---|
| 90 | |
---|
[468] | 91 | return self::$instance; |
---|
[1] | 92 | } |
---|
[42] | 93 | |
---|
[1] | 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 | */ |
---|
[468] | 101 | public function setParam($params) |
---|
[1] | 102 | { |
---|
[479] | 103 | $app =& App::getInstance(); |
---|
[465] | 104 | |
---|
[1] | 105 | if (isset($params) && is_array($params)) { |
---|
| 106 | // Merge new parameters with old overriding only those passed. |
---|
[136] | 107 | $this->_params = array_merge($this->_params, $params); |
---|
[1] | 108 | } else { |
---|
[136] | 109 | $app->logMsg(sprintf('Parameters are not an array: %s', $params), LOG_ERR, __FILE__, __LINE__); |
---|
[1] | 110 | } |
---|
| 111 | } |
---|
| 112 | |
---|
| 113 | /** |
---|
[136] | 114 | * Return the value of a parameter, if it exists. |
---|
[1] | 115 | * |
---|
[136] | 116 | * @access public |
---|
| 117 | * @param string $param Which parameter to return. |
---|
| 118 | * @return mixed Configured parameter value. |
---|
[1] | 119 | */ |
---|
[468] | 120 | public function getParam($param) |
---|
[1] | 121 | { |
---|
[479] | 122 | $app =& App::getInstance(); |
---|
[465] | 123 | |
---|
[478] | 124 | if (array_key_exists($param, $this->_params)) { |
---|
[136] | 125 | return $this->_params[$param]; |
---|
[1] | 126 | } else { |
---|
[146] | 127 | $app->logMsg(sprintf('Parameter is not set: %s', $param), LOG_DEBUG, __FILE__, __LINE__); |
---|
[1] | 128 | return null; |
---|
| 129 | } |
---|
| 130 | } |
---|
[42] | 131 | |
---|
[1] | 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 | */ |
---|
[468] | 139 | public function connect() |
---|
[1] | 140 | { |
---|
[479] | 141 | $app =& App::getInstance(); |
---|
[465] | 142 | |
---|
[136] | 143 | if (!$this->getParam('db_name') || !$this->getParam('db_user') || !$this->getParam('db_pass')) { |
---|
| 144 | $app->logMsg('Database credentials missing.', LOG_EMERG, __FILE__, __LINE__); |
---|
[1] | 145 | return false; |
---|
| 146 | } |
---|
[42] | 147 | |
---|
[1] | 148 | // Connect to database. Always create a new link to the server. |
---|
[484] | 149 | // Connection errors are surpressed so we can do our own error management below. |
---|
[468] | 150 | if ($this->dbh = @mysql_connect($this->getParam('db_server'), $this->getParam('db_user'), $this->getParam('db_pass'), true)) { |
---|
[1] | 151 | // Select database |
---|
[136] | 152 | mysql_select_db($this->getParam('db_name'), $this->dbh); |
---|
[1] | 153 | } |
---|
[42] | 154 | |
---|
[15] | 155 | // Test for connection errors. |
---|
[136] | 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__); |
---|
[15] | 159 | |
---|
| 160 | // Print helpful or pretty error? |
---|
[136] | 161 | if ($this->getParam('db_debug')) { |
---|
[1] | 162 | echo $mysql_error_msg . "\n"; |
---|
| 163 | } |
---|
[15] | 164 | |
---|
[416] | 165 | // Die if db_die_on_failure = true, or just continue without connection. |
---|
[230] | 166 | return $this->_fail(); |
---|
[1] | 167 | } |
---|
[42] | 168 | |
---|
[1] | 169 | // DB connection success! |
---|
[136] | 170 | $this->_connected = true; |
---|
[1] | 171 | |
---|
[334] | 172 | // Tell MySQL what character set we're using. Available only on MySQL versions > 4.01.01. |
---|
[247] | 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'))] . "' */"); |
---|
[209] | 175 | } else { |
---|
| 176 | $app->logMsg(sprintf('%s is not a known character_set.', $app->getParam('character_set')), LOG_ERR, __FILE__, __LINE__); |
---|
| 177 | } |
---|
[10] | 178 | |
---|
[1] | 179 | return true; |
---|
| 180 | } |
---|
[42] | 181 | |
---|
[1] | 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 | */ |
---|
[468] | 189 | public function close() |
---|
[1] | 190 | { |
---|
[136] | 191 | if (!$this->_connected) { |
---|
[1] | 192 | return false; |
---|
| 193 | } |
---|
[416] | 194 | $this->_connected = false; |
---|
[136] | 195 | return mysql_close($this->dbh); |
---|
[1] | 196 | } |
---|
[465] | 197 | |
---|
[230] | 198 | /* |
---|
[416] | 199 | * |
---|
[465] | 200 | * |
---|
[416] | 201 | * @access public |
---|
[465] | 202 | * @param |
---|
| 203 | * @return |
---|
[416] | 204 | * @author Quinn Comendant <quinn@strangecode.com> |
---|
| 205 | * @version 1.0 |
---|
| 206 | * @since 03 Jul 2013 14:50:23 |
---|
| 207 | */ |
---|
[468] | 208 | public function reconnect() |
---|
[416] | 209 | { |
---|
| 210 | $this->close(); |
---|
| 211 | $this->connect(); |
---|
| 212 | } |
---|
[465] | 213 | |
---|
[416] | 214 | /* |
---|
[230] | 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 | */ |
---|
[484] | 225 | protected function _fail() |
---|
[230] | 226 | { |
---|
| 227 | if ($this->getParam('db_die_on_failure')) { |
---|
[484] | 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 | } |
---|
[230] | 233 | die; |
---|
| 234 | } else { |
---|
| 235 | return false; |
---|
| 236 | } |
---|
| 237 | } |
---|
[42] | 238 | |
---|
[1] | 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 | */ |
---|
[468] | 247 | public function getDBH() |
---|
[1] | 248 | { |
---|
[136] | 249 | if (!$this->_connected) { |
---|
[1] | 250 | return false; |
---|
| 251 | } |
---|
| 252 | |
---|
[136] | 253 | return $this->dbh; |
---|
[1] | 254 | } |
---|
[42] | 255 | |
---|
[1] | 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 | */ |
---|
[468] | 263 | public function isConnected() |
---|
[1] | 264 | { |
---|
[136] | 265 | return (true === $this->_connected); |
---|
[1] | 266 | } |
---|
[465] | 267 | |
---|
[71] | 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 | */ |
---|
[468] | 277 | public function escapeString($string) |
---|
[71] | 278 | { |
---|
[136] | 279 | if (!$this->_connected) { |
---|
| 280 | return false; |
---|
[71] | 281 | } |
---|
[136] | 282 | |
---|
| 283 | return mysql_real_escape_string($string, $this->dbh); |
---|
[71] | 284 | } |
---|
[42] | 285 | |
---|
[1] | 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 | */ |
---|
[468] | 294 | public function query($query, $debug=false) |
---|
[465] | 295 | { |
---|
[136] | 296 | $app =& App::getInstance(); |
---|
[42] | 297 | |
---|
[136] | 298 | if (!$this->_connected) { |
---|
[1] | 299 | return false; |
---|
| 300 | } |
---|
| 301 | |
---|
[172] | 302 | $this->_query_count++; |
---|
| 303 | |
---|
[1] | 304 | $debugqry = preg_replace("/\n[\t ]+/", "\n", $query); |
---|
[136] | 305 | if ($this->getParam('db_always_debug') || $debug) { |
---|
[172] | 306 | echo "<!-- ----------------- Query $this->_query_count ---------------------\n$debugqry\n-->\n"; |
---|
[1] | 307 | } |
---|
[465] | 308 | |
---|
| 309 | // Ensure we have an active connection. |
---|
[419] | 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 |
---|
[416] | 312 | if (!mysql_ping($this->dbh)) { |
---|
[419] | 313 | $app->logMsg(sprintf('MySQL ping failed; reconnecting⊠("%s")', truncate(trim($debugqry), 150)), LOG_NOTICE, __FILE__, __LINE__); |
---|
[416] | 314 | $this->reconnect(); |
---|
| 315 | } |
---|
[42] | 316 | |
---|
[1] | 317 | // Execute! |
---|
[136] | 318 | $qid = mysql_query($query, $this->dbh); |
---|
[42] | 319 | |
---|
[1] | 320 | // Error checking. |
---|
[136] | 321 | if (!$qid || mysql_error($this->dbh)) { |
---|
[230] | 322 | $app->logMsg(sprintf('MySQL error %s: %s in query: %s', mysql_errno($this->dbh), mysql_error($this->dbh), $debugqry), LOG_EMERG, __FILE__, __LINE__); |
---|
[136] | 323 | if ($this->getParam('db_debug')) { |
---|
[484] | 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 | } |
---|
[465] | 327 | } |
---|
[230] | 328 | // Die if db_die_on_failure = true, or just continue without connection |
---|
| 329 | return $this->_fail(); |
---|
[1] | 330 | } |
---|
[42] | 331 | |
---|
[1] | 332 | return $qid; |
---|
| 333 | } |
---|
| 334 | |
---|
| 335 | /** |
---|
[42] | 336 | * Loads a list of tables in the current database into an array, and returns |
---|
[1] | 337 | * true if the requested table is found. Use this function to enable/disable |
---|
[334] | 338 | * functionality based upon the current available db tables or to dynamically |
---|
[1] | 339 | * create tables if missing. |
---|
| 340 | * |
---|
[396] | 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. |
---|
[1] | 344 | */ |
---|
[468] | 345 | public function tableExists($table, $use_cached_results=true) |
---|
[42] | 346 | { |
---|
[479] | 347 | $app =& App::getInstance(); |
---|
[465] | 348 | |
---|
[136] | 349 | if (!$this->_connected) { |
---|
[1] | 350 | return false; |
---|
| 351 | } |
---|
| 352 | |
---|
[136] | 353 | if (!isset($this->existing_tables) || !$use_cached_results) { |
---|
| 354 | $this->existing_tables = array(); |
---|
| 355 | $qid = $this->query("SHOW TABLES"); |
---|
[1] | 356 | while (list($row) = mysql_fetch_row($qid)) { |
---|
[136] | 357 | $this->existing_tables[] = $row; |
---|
[1] | 358 | } |
---|
| 359 | } |
---|
[136] | 360 | if (in_array($table, $this->existing_tables)) { |
---|
[1] | 361 | return true; |
---|
| 362 | } else { |
---|
[484] | 363 | $app->logMsg(sprintf('Nonexistent DB table: %s.%s', $this->getParam('db_name'), $table), LOG_INFO, __FILE__, __LINE__); |
---|
[1] | 364 | return false; |
---|
| 365 | } |
---|
| 366 | } |
---|
[42] | 367 | |
---|
[1] | 368 | /** |
---|
| 369 | * Tests if the given array of columns exists in the specified table. |
---|
| 370 | * |
---|
[396] | 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. |
---|
[1] | 376 | */ |
---|
[468] | 377 | public function columnExists($table, $columns, $strict=true, $use_cached_results=true) |
---|
[42] | 378 | { |
---|
[136] | 379 | if (!$this->_connected) { |
---|
[1] | 380 | return false; |
---|
| 381 | } |
---|
| 382 | |
---|
| 383 | // Ensure the table exists. |
---|
[136] | 384 | if (!$this->tableExists($table, $use_cached_results)) { |
---|
[1] | 385 | return false; |
---|
| 386 | } |
---|
[42] | 387 | |
---|
[1] | 388 | // For single-value columns. |
---|
| 389 | if (!is_array($columns)) { |
---|
| 390 | $columns = array($columns); |
---|
| 391 | } |
---|
[42] | 392 | |
---|
[136] | 393 | if (!isset($this->table_columns[$table]) || !$use_cached_results) { |
---|
[1] | 394 | // Populate and cache array of current columns for this table. |
---|
[136] | 395 | $this->table_columns[$table] = array(); |
---|
| 396 | $qid = $this->query("DESCRIBE $table"); |
---|
[1] | 397 | while ($row = mysql_fetch_row($qid)) { |
---|
[136] | 398 | $this->table_columns[$table][] = $row[0]; |
---|
[1] | 399 | } |
---|
| 400 | } |
---|
[42] | 401 | |
---|
[1] | 402 | if ($strict) { |
---|
| 403 | // Do an exact comparison of table schemas. |
---|
| 404 | sort($columns); |
---|
[136] | 405 | sort($this->table_columns[$table]); |
---|
| 406 | return $this->table_columns[$table] == $columns; |
---|
[1] | 407 | } else { |
---|
| 408 | // Only check that the specified columns are available in the table. |
---|
[136] | 409 | $match_columns = array_intersect($this->table_columns[$table], $columns); |
---|
[1] | 410 | sort($columns); |
---|
| 411 | sort($match_columns); |
---|
| 412 | return $match_columns == $columns; |
---|
| 413 | } |
---|
| 414 | } |
---|
[465] | 415 | |
---|
[172] | 416 | /* |
---|
[396] | 417 | * Return the total number of queries executed thus far. |
---|
[172] | 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 | */ |
---|
[468] | 425 | public function numQueries() |
---|
[172] | 426 | { |
---|
| 427 | return $this->_query_count; |
---|
| 428 | } |
---|
[42] | 429 | |
---|
[1] | 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 | */ |
---|
[468] | 437 | public function resetCache() |
---|
[1] | 438 | { |
---|
| 439 | $this->existing_tables = null; |
---|
| 440 | $this->table_columns = null; |
---|
| 441 | } |
---|
[42] | 442 | |
---|
[1] | 443 | } // End. |
---|
| 444 | |
---|