* Copyright 2001-2012 Strangecode, LLC * * This file is part of The Strangecode Codebase. * * The Strangecode Codebase is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published by the * Free Software Foundation, either version 3 of the License, or (at your option) * any later version. * * The Strangecode Codebase is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * The Strangecode Codebase. If not, see . */ /** * DB.inc.php * * Very lightweight DB semi-abstraction layer. Mainly to catch errors with mysql_query, with some goodies. * * @author Quinn Comendant * @version 2.1 */ class DB { // A place to keep an object instance for the singleton pattern. protected static $instance = null; // If $db->connect has successfully opened a db connection. protected $_connected = false; // Database handle. public $dbh; // Count how many queries run during the whole instance. protected $_query_count = 0; // Hash of DB parameters. protected $_params = array(); // Default parameters. protected $_param_defaults = array( // DB passwords should be set as apache environment variables in httpd.conf, readable only by root. 'db_server' => 'localhost', 'db_name' => null, 'db_user' => null, 'db_pass' => null, // Display all SQL queries. FALSE recommended for production sites. 'db_always_debug' => false, // Display db errors. FALSE recommended for production sites. 'db_debug' => false, // Script stops on db error. TRUE recommended for production sites. 'db_die_on_failure' => true, // Special date settings. These will dynamically changes depending on MySQL version or settings. 'zero_date' => '0000-00-00', 'infinity_date' => '9999-12-31', // Timezone for MySQL. 'timezone' => 'UTC', // MySQL character set and collation. 'character_set' => '', 'collation' => '', ); // Translate between HTML and MySQL character set names. public $mysql_character_sets = array( 'utf-8' => 'utf8', 'iso-8859-1' => 'latin1', ); // Caches. protected static $existing_tables = null; protected static $table_columns = null; /** * Constructor. */ public function __construct() { // Initialize default parameters. $this->_params = array_merge($this->_params, $this->_param_defaults); } /** * This method enforces the singleton pattern for this class. * * @return object Reference to the global DB object. * @access public * @static */ public static function &getInstance() { if (self::$instance === null) { self::$instance = new self(); } return self::$instance; } /** * Set (or overwrite existing) parameters by passing an array of new parameters. * * @access public * * @param array $params Array of parameters (key => val pairs). */ public function setParam(Array $params) { if (!isset($params) || !is_array($params)) { trigger_error(sprintf('%s failed; not an array: %s', __METHOD__, getDump($params, false, SC_DUMP_PRINT_R)), E_USER_ERROR); } // Merge new parameters with old overriding only those passed. $this->_params = array_merge($this->_params, $params); if ($this->isConnected()) { // Params that require additional processing if set during runtime. foreach ($params as $key => $val) { switch ($key) { case 'timezone': // Set timezone used by MySQL. $this->query(sprintf("SET time_zone = '%s';", $this->escapeString($val))); break; } } } } /** * Return the value of a parameter, if it exists. * * @access public * @param string $param Which parameter to return. * @return mixed Configured parameter value. */ public function getParam($param) { $app =& App::getInstance(); if (array_key_exists($param, $this->_params)) { return $this->_params[$param]; } else { $app->logMsg(sprintf('Parameter is not set: %s', $param), LOG_DEBUG, __FILE__, __LINE__); return null; } } /** * Connect to database with credentials in params. * * @access public * @author Quinn Comendant * @since 28 Aug 2005 14:02:49 */ public function connect() { $app =& App::getInstance(); if (!$this->getParam('db_name') || !$this->getParam('db_user') || !$this->getParam('db_pass')) { $app->logMsg('Database credentials missing.', LOG_EMERG, __FILE__, __LINE__); return false; } if (!$this->getParam('db_server')) { // If db_server not specified, assume localhost. $this->setParam(array('db_server' => 'localhost')); } // Connect to database. Always create a new link to the server. // Connection errors are suppressed so we can do our own error management below. if ($this->dbh = @mysql_connect($this->getParam('db_server'), $this->getParam('db_user'), $this->getParam('db_pass'), true)) { // Select database mysql_select_db($this->getParam('db_name'), $this->dbh); } // Test for connection errors. if (!$this->dbh || mysql_error($this->dbh)) { $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')); $app->logMsg($mysql_error_msg, LOG_ERR, __FILE__, __LINE__); // Print helpful or pretty error? if ($this->getParam('db_debug')) { if (!$app->isCLI()) { printf('
%s
', $mysql_error_msg); } } // Die if db_die_on_failure = true, or just continue without connection. return $this->_fail(); } // DB connection success! $this->_connected = true; // If the mysql charset is not defined, try to determine a mysql charset from the app charset. if ('' == $this->getParam('character_set') && '' != $app->getParam('character_set') && isset($this->mysql_character_sets[mb_strtolower($app->getParam('character_set'))])) { $this->setParam(array('character_set' => $this->mysql_character_sets[mb_strtolower($app->getParam('character_set'))])); } if ('' != $this->getParam('character_set')) { if ('' != $this->getParam('collation')) { $this->query(sprintf("SET NAMES '%s' COLLATE '%s';", $this->getParam('character_set'), $this->getParam('collation'))); } else { $this->query(sprintf("SET NAMES '%s';", $this->getParam('character_set'))); } } // Update config for this version of MySQL. if (version_compare(mysql_get_server_info(), '5.7.4', '>=')) { $this->setParam(array('zero_date' => '1000-01-01')); } // Set MySQL session timezone. if ($this->getParam('timezone')) { // https://dev.mysql.com/doc/refman/5.5/en/time-zone-support.html $this->query(sprintf("SET time_zone = '%s';", $this->getParam('timezone'))); } return true; } /** * Close db connection. * * @access public * @author Quinn Comendant * @since 28 Aug 2005 14:32:01 */ public function close() { if (!$this->_connected) { return false; } $this->_connected = false; return mysql_close($this->dbh); } /* * * * @access public * @param * @return * @author Quinn Comendant * @version 1.0 * @since 03 Jul 2013 14:50:23 */ public function reconnect() { $this->close(); $this->connect(); } /* * Die only if db_die_on_failure is true. This will be set to false for some cases * when a database is not required for web app functionality. * * @access public * @param string $msg Print $msg when dying. * @return bool false If we don't die. * @author Quinn Comendant * @version 1.0 * @since 15 Jan 2007 15:59:00 */ protected function _fail() { $app =& App::getInstance(); if ($this->getParam('db_die_on_failure')) { if (!$app->isCLI()) { // For http requests, send a Service Unavailable header. header(' ', true, 503); echo _("This page is temporarily unavailable. Please try again in a few minutes."); } die; } else { return false; } } /** * Return the current database handler. * * @access public * @return resource Current value of $this->dbh. * @author Quinn Comendant * @since 20 Aug 2005 13:50:36 */ public function getDBH() { if (!$this->_connected) { return false; } return $this->dbh; } /** * Returns connection status * * @access public * @author Quinn Comendant * @since 28 Aug 2005 14:58:09 */ public function isConnected() { return (true === $this->_connected); } /** * Returns a properly escaped string using mysql_real_escape_string() with the current connection's charset. * * @access public * @param string $string Input string to be sent as SQL query. * @return string Escaped string from mysql_real_escape_string() * @author Quinn Comendant * @since 06 Mar 2006 16:41:32 */ public function escapeString($string) { if (!$this->_connected) { return false; } return mysql_real_escape_string($string, $this->dbh); } /** * A wrapper for mysql_query. Allows us to set the database link_identifier, * to trap errors and ease debugging. * * @param string $query The SQL query to execute * @param bool $debug If true, prints debugging info * @return resource Query identifier */ public function query($query, $debug=false) { $app =& App::getInstance(); if (!$this->_connected) { return false; } $this->_query_count++; $debugqry = preg_replace('/\n[\t ]+/' . $app->getParam('preg_u'), "\n", $query); if ($this->getParam('db_always_debug') || $debug) { if ($debug > 1) { dump($debugqry, true, SC_DUMP_PRINT_R, __FILE__, __LINE__); } else { echo "\n"; } } // Ensure we have an active connection. // If we continue on a dead connection we might experience a "MySQL server has gone away" error. // http://dev.mysql.com/doc/refman/5.0/en/gone-away.html if (!mysql_ping($this->dbh)) { $app->logMsg(sprintf('MySQL ping failed; reconnecting… ("%s")', truncate(trim($debugqry), 150)), LOG_DEBUG, __FILE__, __LINE__); $this->reconnect(); } // Execute! $qid = mysql_query($query, $this->dbh); // Error checking. if (!$qid || mysql_error($this->dbh)) { $app->logMsg(sprintf('MySQL error %s: %s in query: %s', mysql_errno($this->dbh), mysql_error($this->dbh), $debugqry), LOG_EMERG, __FILE__, __LINE__); if ($this->getParam('db_debug')) { if (!$app->isCLI()) { echo '
' . wordwrap(mysql_error($this->dbh)) . '
' . htmlspecialchars($debugqry) . '
'; } } // Die if db_die_on_failure = true, or just continue without connection return $this->_fail(); } return $qid; } /** * Loads a list of tables in the current database into an array, and returns * true if the requested table is found. Use this function to enable/disable * functionality based upon the current available db tables or to dynamically * create tables if missing. * * @param string $table The name of the table to search. * @param bool $use_cached_results Get fresh table info (in case DB changed). * @return bool true if given $table exists. */ public function tableExists($table, $use_cached_results=true) { $app =& App::getInstance(); if (!$this->_connected) { return false; } if (is_null(self::$existing_tables) || !$use_cached_results) { self::$existing_tables = array(); $qid = $this->query("SHOW TABLES"); while (list($row) = mysql_fetch_row($qid)) { self::$existing_tables[] = $row; } } if (in_array($table, self::$existing_tables)) { return true; } else { $app->logMsg(sprintf('Nonexistent DB table: %s.%s', $this->getParam('db_name'), $table), LOG_INFO, __FILE__, __LINE__); return false; } } /** * Tests if the given array of columns exists in the specified table. * * @param string $table The name of the table to search. * @param array $columns An array of column names. * @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). * @param bool $use_cached_results Get fresh table info (in case DB changed). * @return bool true if column(s) exist. */ public function columnExists($table, $columns, $strict=true, $use_cached_results=true) { $app =& App::getInstance(); if (!$this->_connected) { $app->logMsg(sprintf('No DB connection to run %s', __METHOD__), LOG_NOTICE, __FILE__, __LINE__); return false; } // Ensure the table exists. if (!$this->tableExists($table, $use_cached_results)) { $app->logMsg(sprintf('Table does not exist: %s', $table), LOG_NOTICE, __FILE__, __LINE__); return false; } // For single-value columns. if (!is_array($columns)) { $columns = array($columns); } if (!isset(self::$table_columns[$table]) || !$use_cached_results) { // Populate and cache array of current columns for this table. self::$table_columns[$table] = array(); $qid = $this->query("DESCRIBE $table"); while ($row = mysql_fetch_row($qid)) { self::$table_columns[$table][] = $row[0]; } } if ($strict) { // Do an exact comparison of table schemas. sort($columns); sort(self::$table_columns[$table]); return self::$table_columns[$table] == $columns; } else { // Only check that the specified columns are available in the table. $match_columns = array_intersect(self::$table_columns[$table], $columns); sort($columns); sort($match_columns); return $match_columns == $columns; } } /* * Return the total number of queries executed thus far. * * @access public * @return int Number of queries * @author Quinn Comendant * @version 1.0 * @since 15 Jun 2006 11:46:05 */ public function numQueries() { return $this->_query_count; } /** * Reset cached items. * * @access public * @author Quinn Comendant * @since 28 Aug 2005 22:10:50 */ public function resetCache() { self::$existing_tables = null; self::$table_columns = null; } /** * Returns the values of an ENUM or SET column, returning them as an array. * * @param string $db_table database table to lookup * @param string $db_col database column to lookup * @param bool $sort Sort the output. * @return array Array of the set/enum values on success, false on failure. */ public function getEnumValues($db_table, $db_col, $sort=false) { $app =& App::getInstance(); $qid = $this->query("SHOW COLUMNS FROM " . $this->escapeString($db_table) . " LIKE '" . $this->escapeString($db_col) . "'", false); $row = mysql_fetch_row($qid); if (preg_match('/^enum|^set/i', $row[1]) && preg_match_all("/'([^']*)'/", $row[1], $matches)) { if ($sort) { natsort($matches[1]); } return $matches[1]; } else { $app->logMsg(sprintf('No set or enum fields found in %s.%s', $db_table, $db_col), LOG_ERR, __FILE__, __LINE__); return false; } } } // End.