* Copyright 2001-2010 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 { // If $db->connect has successfully opened a db connection. var $_connected = false; // Database handle. var $dbh; // Count how many queries run during the whole instance. var $_query_count = 0; // Hash of DB parameters. var $_params = array(); // Default parameters. var $_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, ); // Translate between HTML and MySQL character set names. var $mysql_character_sets = array( 'utf-8' => 'utf8', 'iso-8859-1' => 'latin1', ); // Caches. var $existing_tables; var $table_columns; /** * This method enforces the singleton pattern for this class. * * @return object Reference to the global DB object. * @access public * @static */ function &getInstance() { static $instance = null; if ($instance === null) { $instance = new DB(); } return $instance; } /** * Set (or overwrite existing) parameters by passing an array of new parameters. * * @access public * * @param array $params Array of parameters (key => val pairs). */ function setParam($params) { $app =& App::getInstance(); if (isset($params) && is_array($params)) { // Merge new parameters with old overriding only those passed. $this->_params = array_merge($this->_params, $params); } else { $app->logMsg(sprintf('Parameters are not an array: %s', $params), LOG_ERR, __FILE__, __LINE__); } } /** * Return the value of a parameter, if it exists. * * @access public * @param string $param Which parameter to return. * @return mixed Configured parameter value. */ function getParam($param) { $app =& App::getInstance(); if (isset($this->_params[$param])) { 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 */ 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; } // Connect to database. Always create a new link to the server. 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 error: (' . mysql_errno($this->dbh) . ') ' . mysql_error($this->dbh) : 'Codebase MySQL error: Could not connect to server.'; $app->logMsg($mysql_error_msg, LOG_EMERG, __FILE__, __LINE__); // Print helpful or pretty error? if ($this->getParam('db_debug')) { echo $mysql_error_msg . "\n"; } // Die if db_die_on_failure = true, or just continue without connection return $this->_fail(); } // DB connection success! $this->_connected = true; // Tell MySQL what character set we're using. Available only on MySQL versions > 4.01.01. if ('' != $app->getParam('character_set') && isset($this->mysql_character_sets[mb_strtolower($app->getParam('character_set'))])) { $this->query("/*!40101 SET NAMES '" . $this->mysql_character_sets[mb_strtolower($app->getParam('character_set'))] . "' */"); } else { $app->logMsg(sprintf('%s is not a known character_set.', $app->getParam('character_set')), LOG_ERR, __FILE__, __LINE__); } return true; } /** * Close db connection. * * @access public * @author Quinn Comendant * @since 28 Aug 2005 14:32:01 */ function close() { if (!$this->_connected) { return false; } return mysql_close($this->dbh); } /* * 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 */ function _fail() { if ($this->getParam('db_die_on_failure')) { 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 */ 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 */ 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 */ 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 */ function query($query, $debug=false) { $app =& App::getInstance(); if (!$this->_connected) { return false; } $this->_query_count++; $debugqry = preg_replace("/\n[\t ]+/", "\n", $query); if ($this->getParam('db_always_debug') || $debug) { echo "\n"; } // 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')) { 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 $strict Get fresh table info (in case DB changed). * @return bool true if given $table exists. */ function tableExists($table, $use_cached_results=true) { $app =& App::getInstance(); if (!$this->_connected) { return false; } if (!isset($this->existing_tables) || !$use_cached_results) { $this->existing_tables = array(); $qid = $this->query("SHOW TABLES"); while (list($row) = mysql_fetch_row($qid)) { $this->existing_tables[] = $row; } } if (in_array($table, $this->existing_tables)) { return true; } else { $app->logMsg(sprintf('Nonexistent DB table: %s.%s', $this->getParam('db_name'), $table), LOG_ALERT, __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, or are additional fields in the table okay? * @param bool $strict Get fresh table info (in case DB changed). * @return bool true if given $table exists. */ function columnExists($table, $columns, $strict=true, $use_cached_results=true) { if (!$this->_connected) { return false; } // Ensure the table exists. if (!$this->tableExists($table, $use_cached_results)) { return false; } // For single-value columns. if (!is_array($columns)) { $columns = array($columns); } if (!isset($this->table_columns[$table]) || !$use_cached_results) { // Populate and cache array of current columns for this table. $this->table_columns[$table] = array(); $qid = $this->query("DESCRIBE $table"); while ($row = mysql_fetch_row($qid)) { $this->table_columns[$table][] = $row[0]; } } if ($strict) { // Do an exact comparison of table schemas. sort($columns); sort($this->table_columns[$table]); return $this->table_columns[$table] == $columns; } else { // Only check that the specified columns are available in the table. $match_columns = array_intersect($this->table_columns[$table], $columns); sort($columns); sort($match_columns); return $match_columns == $columns; } } /* * Return the total number of queries run this for. * * @access public * @return int Number of queries * @author Quinn Comendant * @version 1.0 * @since 15 Jun 2006 11:46:05 */ function numQueries() { return $this->_query_count; } /** * Reset cached items. * * @access public * @author Quinn Comendant * @since 28 Aug 2005 22:10:50 */ function resetCache() { $this->existing_tables = null; $this->table_columns = null; } } // End. ?>