# HG changeset patch # User Dan Fuhry # Date 1377137638 14400 # Node ID 60b580d22c7bdfd0bf41ad5a65d7ab1af814e55f # Parent f99b9c5036d4fdaa01ac3c9e794888b6ab6aa7f2# Parent d66e43ac35b60661194177025c0d52e094d636e1 Merged diff -r f99b9c5036d4 -r 60b580d22c7b includes/dbal.php --- a/includes/dbal.php Sat Dec 15 12:40:59 2012 -0500 +++ b/includes/dbal.php Wed Aug 21 22:13:58 2013 -0400 @@ -143,6 +143,32 @@ function connect($manual_credentials = false, $dbhost = false, $dbuser = false, $dbpasswd = false, $dbname = false, $dbport = false) { + if ( !function_exists('mysql_connect') ) + { + if ( class_exists('PDO') && extension_loaded("pdo_mysql") ) + { + $pdo_string = '

Never fear! Your server has PDO and the PDO MySQL driver installed. This means you can simply edit your config.php to use + an alternate database driver, without losing any of your existing site data. Look for the line that says:

+
$dbdriver = \'mysql\';
+

and change it to:

+
$dbdriver = \'mysql_pdo\';
'; + } + else + { + $pdo_string = '

Enano can\'t load right now, but it will resume working once you install the PDO MySQL extension and then edit Enano\'s config.php file to + use the new database driver. Once the PDO and PDO_MySQL PHP extensions are installed, look in Enano\'s config.php file for + the line that says:

+
$dbdriver = \'mysql\';
+

and change it to:

+
$dbdriver = \'mysql_pdo\';
'; + } + grinding_halt('MySQL no longer supported', '

Your site configuration specifies that the MySQL database driver is to be used, however PHP has removed this + driver from newer versions.

' . $pdo_string . + '

Your site\'s data is not at risk. This notice by itself simply means you upgraded to a newer version of PHP. Your site\'s + data ordinarily will not have been touched and your site will function properly again as soon as you switch over to the PDO MySQL + driver.

'); + } + if ( !defined('ENANO_SQL_CONSTANTS') ) { define('ENANO_SQL_CONSTANTS', ''); @@ -543,6 +569,686 @@ } /** + * Get MySQL server version + * @return string + */ + + function get_server_version() + { + return mysql_get_server_info(); + } + + /** + * Close the database connection + */ + + function close() + { + if ( !$this->_conn ) + return; + + // anything we locked should certainly be unlocked now; + @mysql_query("COMMIT;", $this->_conn); + @mysql_query("UNLOCK TABLES;", $this->_conn); + @mysql_close($this->_conn); + unset($this->_conn); + } + + /** + * Get a list of columns in the given table + * @param string Table + * @return array + */ + + function columns_in($table) + { + if ( !is_string($table) ) + return false; + $q = $this->sql_query("SHOW COLUMNS IN $table;"); + if ( !$q ) + $this->_die(); + + $columns = array(); + while ( $row = $this->fetchrow_num() ) + { + $columns[] = $row[0]; + } + return $columns; + } + + /** + * Get the text of the most recent error. + * @return string + */ + + function sql_error() + { + return mysql_error(); + } + + /** + * Generates and outputs a report of all the SQL queries made during execution. Should only be called after everything's over with. + */ + + function sql_report() + { + global $db, $session, $paths, $template, $plugins; // Common objects + if ( !$session->get_permissions('mod_misc') ) + { + die_friendly('Access denied', '

You are not authorized to generate a SQL backtrace.

'); + } + // Create copies of variables that may be changed after header is called + $backtrace = $this->query_backtrace; + $times = $this->query_times; + $template->header(); + echo '

SQL query log and timetable

'; + echo '
+ '; + $i = 0; + foreach ( $backtrace as $query ) + { + $i++; + $unbuffered = false; + if ( substr($query, 0, 13) == '(UNBUFFERED) ' ) + { + $query = substr($query, 13); + $unbuffered = true; + } + if ( $i == 1 ) + { + echo ' + + '; + } + else + { + echo ' + + '; + } + echo ' + + + + + + + + + + + '; + if ( isset($this->query_sources[$query]) ) + { + echo ' + + + '; + } + } + if ( function_exists('array_sum') ) + { + $query_time_total = array_sum($this->query_times); + echo ' + + '; + } + echo '
SQL backtrace for a normal page load of ' . htmlspecialchars($paths->cpage['urlname']) . '
 
Query:
' . htmlspecialchars($query) . '
Time:' . number_format($this->query_times[$query], 6) . ' seconds
Unbuffered:' . ( $unbuffered ? 'Yes' : 'No' ) . '
Called from:' . $this->query_sources[$query] . '
+ Total time taken for SQL queries: ' . round( $query_time_total, 6 ) . ' seconds +
+
'; + $template->footer(); + } + + /** + * Begin transaction + */ + + function transaction_begin() + { + $this->sql_query('BEGIN;'); + } + + /** + * Commit transaction + */ + + function transaction_commit() + { + $this->sql_query('COMMIT;'); + } + + /** + * Rollback transaction + */ + + function transaction_rollback() + { + $this->sql_query('ROLLBACK;'); + } +} + +class mysql_pdo { + var $num_queries, $query_backtrace, $query_times, $query_sources, $latest_result, $latest_query, $_conn, $sql_stack_fields, $sql_stack_values, $debug; + var $row = array(); + var $rowset = array(); + var $errhandler; + var $dbms_name = 'MySQL'; + + /** + * Get a flat textual list of queries that have been made. + */ + + function sql_backtrace() + { + return implode("\n-------------------------------------------------------------------\n", $this->query_backtrace); + } + + /** + * Connect to the database, but only if a connection isn't already up. + */ + + function ensure_connection() + { + if(!$this->_conn) + { + $this->connect(); + } + } + + /** + * Exit Enano, dumping out a friendly error message indicating a database error on the way out. + * @param string Description or location of error; defaults to none + */ + + function _die($t = '') + { + if ( defined('ENANO_HEADERS_SENT') ) + ob_clean(); + + $internal_text = $this->get_error($t); + + if ( defined('ENANO_CONFIG_FETCHED') ) + // config is in, we can show a slightly nicer looking error page + die_semicritical('Database error', $internal_text); + else + // no config, display using no-DB template engine + grinding_halt('Database error', $internal_text); + + exit; + } + + /** + * Get the internal text used for a database error message. + * @param string Description or location of error; defaults to none + */ + + function get_error($t = '') + { + @header('HTTP/1.1 500 Internal Server Error'); + + $bt = $this->latest_query; + $e = htmlspecialchars($this->sql_error()); + if ( empty($e) ) + $e = '<none>'; + + global $email; + + // As long as the admin's e-mail is accessible, display it. + $email_info = ( defined('ENANO_CONFIG_FETCHED') && is_object($email) ) + ? ', at <' . $email->jscode() . $email->encryptEmail(getConfig('contact_email')) . '>' + : ''; + + $internal_text = "

The site was unable to finish serving your request.

+

We apologize for the inconveience, but an error occurred in the Enano database layer. Please report the full text of this page to the administrator of this site{$email_info}.

+

Description or location of error: $t
+ Error returned by $this->dbms_name extension: $e

+

Most recent SQL query:

+
$bt
"; + return $internal_text; + } + + /** + * Exit Enano and output a JSON format datbase error. + * @param string Description or location of error; defaults to none + */ + + function die_json($loc = false) + { + $e = str_replace("\n", "\\n", addslashes(htmlspecialchars($this->sql_error()))); + $q = str_replace("\n", "\\n", addslashes($this->latest_query)); + $loc = ( $loc ) ? addslashes("\n\nDescription or location of error: $loc") : ""; + $loc .= "\n\nPlease report the full text of this error to the administrator of the site. If you believe that this is a bug with the software, please contact support@enanocms.org."; + $loc = str_replace("\n", "\\n", $loc); + $t = "{\"mode\":\"error\",\"error\":\"An error occurred during database query.\\nQuery was:\\n $q\\n\\nError returned by {$this->dbms_name}: $e$loc\"}"; + die($t); + } + + /** + * Connect to the database. + * @param bool If true, enables all other parameters. Defaults to false, which emans that you can call this function with no arguments and it will fetch information from the config file. + * @param string Database server hostname + * @param string Database server username + * @param string Database server password + * @param string Name of the database + * @param int Optional port number to connect over + */ + + function connect($manual_credentials = false, $dbhost = false, $dbuser = false, $dbpasswd = false, $dbname = false, $dbport = false) + { + if ( !defined('ENANO_SQL_CONSTANTS') ) + { + define('ENANO_SQL_CONSTANTS', ''); + define('ENANO_DBLAYER', 'MYSQL'); + define('ENANO_SQLFUNC_LOWERCASE', 'lcase'); + define('ENANO_SQL_MULTISTRING_PRFIX', ''); + define('ENANO_SQL_BOOLEAN_TRUE', 'true'); + define('ENANO_SQL_BOOLEAN_FALSE', 'false'); + } + + if ( !$manual_credentials ) + { + if ( defined('IN_ENANO_INSTALL') && !defined('IN_ENANO_UPGRADE') ) + { + @include(ENANO_ROOT.'/config.new.php'); + } + else + { + @include(ENANO_ROOT.'/config.php'); + } + + if ( isset($crypto_key) ) + unset($crypto_key); // Get this sucker out of memory fast + if ( empty($dbport) ) + $dbport = 3306; + + if ( !defined('ENANO_INSTALLED') && !defined('MIDGET_INSTALLED') && !defined('IN_ENANO_INSTALL') ) + { + // scriptPath isn't set yet - we need to autodetect it to avoid infinite redirects + if ( !defined('scriptPath') ) + { + if ( isset($_SERVER['PATH_INFO']) && !preg_match('/index\.php$/', $_SERVER['PATH_INFO']) ) + { + $_SERVER['REQUEST_URI'] = preg_replace(';' . preg_quote($_SERVER['PATH_INFO']) . '$;', '', $_SERVER['REQUEST_URI']); + } + if ( !preg_match('/\.php$/', $_SERVER['REQUEST_URI']) ) + { + // user requested http://foo/enano as opposed to http://foo/enano/index.php + $_SERVER['REQUEST_URI'] .= '/index.php'; + } + $sp = dirname($_SERVER['REQUEST_URI']); + if($sp == '/' || $sp == '\\') $sp = ''; + define('scriptPath', $sp); + define('contentPath', "$sp/index.php?title="); + } + $loc = scriptPath . '/install/index.php'; + define('IN_ENANO_INSTALL', 1); + $GLOBALS['lang'] = new Language('eng'); + global $lang; + $lang->load_file('./language/english/core.json'); + $lang->load_file('./language/english/install.json'); + // header("Location: $loc"); + redirect($loc, 'Enano not installed', 'We can\'t seem to find an Enano installation (valid config file). You will be transferred to the installation wizard momentarily...', 0); + exit; + } + } + + if ( !$dbport ) + $dbport = 3306; + + if ( $dbhost && !empty($dbport) && $dbport != 3306 ) + $dbhost = '127.0.0.1'; + + $host_line = ( preg_match('/^:/', $dbhost) ) ? $dbhost : "{$dbhost}:{$dbport}"; + + $this->_conn = new PDO("mysql:host=$dbhost;dbname=$dbname;charset=UTF8", $dbuser, $dbpasswd); + + unset($dbuser); + unset($dbpasswd); // Security + + if ( !$this->_conn && !$manual_credentials ) + { + grinding_halt('Enano is having a problem', '

Error: couldn\'t connect to MySQL.
'.mysql_error().'

'); + } + else if ( !$this->_conn && $manual_credentials ) + { + return false; + } + + // Reset some variables + $this->query_backtrace = array(); + $this->query_times = array(); + $this->query_sources = array(); + $this->num_queries = 0; + + $this->debug = ( defined('ENANO_DEBUG') ); + + // We're in! + return true; + } + + /** + * Make a SQL query. + * @param string Query + * @param bool If false, skips all checks and logging stages. If you're doing a ton of queries, set this to true; in all other cases, leave at the default of false. + * @return resource or false on failure + */ + + function sql_query($q, $log_query = true) + { + if ( $this->debug && function_exists('debug_backtrace') ) + { + $backtrace = @debug_backtrace(); + if ( is_array($backtrace) ) + { + $bt = $backtrace[0]; + if ( isset($backtrace[1]['class']) ) + { + if ( $backtrace[1]['class'] == 'sessionManager' ) + { + $bt = $backtrace[1]; + } + } + $this->query_sources[$q] = substr($bt['file'], strlen(ENANO_ROOT) + 1) . ', line ' . $bt['line']; + } + unset($backtrace); + } + + $this->num_queries++; + if ( $log_query || defined('ENANO_DEBUG') ) + { + $this->query_backtrace[] = $q; + $this->latest_query = $q; + } + // First make sure we have a connection + if ( !$this->_conn ) + { + $this->_die('A database connection has not yet been established.'); + } + // Start the timer + if ( $log_query || defined('ENANO_DEBUG') ) + $time_start = microtime_float(); + // Does this query look malicious? + if ( $log_query || defined('ENANO_DEBUG') ) + { + if ( !$this->check_query($q) ) + { + $this->report_query($q); + $debug = ( defined('ENANO_DEBUG') ) ? '

Query was:

'.htmlspecialchars($q).'
' : ''; + grinding_halt('SQL Injection attempt', '

Enano has caught and prevented an SQL injection attempt. Your IP address has been recorded and the administrator has been notified.

' . $debug); + } + } + + try + { + $r = $this->_conn->query($q); + } + catch ( PDOException $e ) + { + return false; + } + + if ( $log_query ) + $this->query_times[$q] = microtime_float() - $time_start; + + $this->latest_result = $r; + + return $r; + } + + /** + * Make a SQL query, but do not have PHP buffer all the results. Useful for queries that are expected to return a huge number of results. + * @param string Query + * @param bool If false, skips all checks and logging stages. If you're doing a ton of queries, set this to true; in all other cases, leave at the default of false. + * @return resource or false on failure + */ + + function sql_unbuffered_query($q, $log_query = true) + { + $this->num_queries++; + if ( $log_query || defined('ENANO_DEBUG') ) + $this->query_backtrace[] = '(UNBUFFERED) ' . $q; + $this->latest_query = $q; + // First make sure we have a connection + if ( !$this->_conn ) + { + $this->_die('A database connection has not yet been established.'); + } + // Does this query look malicious? + if ( !$this->check_query($q) ) + { + $this->report_query($q); + $debug = ( defined('ENANO_DEBUG') ) ? '

Query was:

'.htmlspecialchars($q).'
' : ''; + grinding_halt('SQL Injection attempt', '

Enano has caught and prevented an SQL injection attempt. Your IP address has been recorded and the administrator has been notified.

' . $debug); + } + + $time_start = microtime_float(); + try + { + $r = $this->_conn->query($q); + } + catch ( PDOException $e ) + { + return false; + } + $this->query_times[$q] = microtime_float() - $time_start; + $this->latest_result = $r; + return $r; + } + + /** + * Performs heuristic analysis on a SQL query to check for known attack patterns. + * @param string $q the query to check + * @return bool true if query passed check, otherwise false + */ + + function check_query($q, $debug = false) + { + global $db_sql_parse_time; + $ts = microtime_float(); + + // remove properly escaped quotes + $q = str_replace('\\\\', '', $q); + $q = str_replace(array("\\\"", "\\'"), '', $q); + + // make sure quotes match + foreach ( array("'", '"') as $quote ) + { + $n_quotes = get_char_count($q, $quote); + if ( $n_quotes % 2 == 1 ) + { + // mismatched quotes + if ( $debug ) echo "Found mismatched quotes in query; parsed:\n$q\n"; + return false; + } + // this quote is now confirmed to be matching; we can safely move all quoted strings out and replace with a token + $q = preg_replace("/$quote(.*?)$quote/s", 'SAFE_QUOTE', $q); + } + $q = preg_replace("/(SAFE_QUOTE)+/", 'SAFE_QUOTE', $q); + + // quotes are now matched out. does this string have a comment marker in it? + if ( strstr($q, '--') ) + { + return false; + } + + if ( preg_match('/[\s]+(SAFE_QUOTE|[\S]+)=\\1($|[\s]+)/', $q, $match) ) + { + if ( $debug ) echo 'Found always-true test in query, injection attempt caught, match:
' . '
' . print_r($match, true) . '
'; + return false; + } + + $ts = microtime_float() - $ts; + $db_sql_parse_time += $ts; + return true; + } + + /** + * Set the internal result pointer to X + * @param int $pos The number of the row + * @param resource $result The MySQL result resource - if not given, the latest cached query is assumed + * @return true on success, false on failure + */ + + function sql_data_seek($pos, $result = false) + { + if ( !$result ) + $result = $this->latest_result; + if ( !$result ) + return false; + + return mysql_data_seek($result, $pos) ? true : false; + } + + /** + * Reports a bad query to the admin + * @param string $query the naughty query + * @access private + */ + + function report_query($query) + { + global $session; + if ( is_object($session) && defined('ENANO_MAINSTREAM') ) + { + $username = $session->username; + $user_id = $session->user_id; + } + else + { + $username = 'Unavailable'; + $user_id = 1; + } + + $query = $this->escape($query); + $q = $this->sql_query('INSERT INTO '.table_prefix.'logs(log_type, action, time_id, date_string, page_text, author, author_uid, edit_summary) + VALUES(\'security\', \'sql_inject\', '.time().', \'\', \''.$query.'\', \''.$username.'\', ' . $user_id . ', \''.$_SERVER['REMOTE_ADDR'].'\');'); + } + + /** + * Returns the ID of the row last inserted. + * @return int + */ + + function insert_id() + { + $q = $this->sql_query("SELECT LAST_INSERT_ID();"); + if ( !$q ) + return false; + + list($iid) = $this->fetchrow_num(); + return $iid; + } + + /** + * Fetch one row from the given query as an associative array. + * @param resource The resource returned from sql_query; if this isn't provided, the last result resource is used. + * @return array + */ + + function fetchrow($r = false) + { + if ( !$this->_conn ) + return false; + + if ( !$r ) + $r = $this->latest_result; + + if ( !$r ) + $this->_die('$db->fetchrow(): an invalid MySQL resource was passed.'); + + $row = $r->fetch(PDO::FETCH_ASSOC); + + return integerize_array($row); + } + + /** + * Fetch one row from the given query as a numeric array. + * @param resource The resource returned from sql_query; if this isn't provided, the last result resource is used. + * @return array + */ + + function fetchrow_num($r = false) + { + if ( !$r ) + $r = $this->latest_result; + if ( !$r ) + $this->_die('$db->fetchrow(): an invalid MySQL resource was passed.'); + + $row = $r->fetch(PDO::FETCH_NUM); + return integerize_array($row); + } + + /** + * Get the number of results for a given query. + * @param resource The resource returned from sql_query; if this isn't provided, the last result resource is used. + * @return array + */ + + function numrows($r = false) + { + if ( !$r ) + $r = $this->latest_result; + if ( !$r ) + $this->_die('$db->fetchrow(): an invalid MySQL resource was passed.'); + + return $r->rowCount(); + } + + /** + * Escape a string so that it may safely be included in a SQL query. + * @param string String to escape + * @return string Escaped string + */ + + function escape($str) + { + $str = substr($this->_conn->quote($str), 1, -1); + return $str; + } + + /** + * Free the given result from memory. Use this when completely finished with a result resource. + * @param resource The resource returned from sql_query; if this isn't provided, the last result resource is used. + * @return null + */ + + function free_result($result = false) + { + if ( !$result ) + $result = $this->latest_result; + if ( !$result ) + return null; + + //@mysql_free_result($result); + return null; + } + + /** + * Returns the number of rows affected. + * @return int + */ + + function sql_affectedrows() + { + return mysql_affected_rows($this->_conn); + } + + /** + * Get MySQL server version + * @return string + */ + + function get_server_version() + { + $q = $this->sql_query("SHOW VARIABLES WHERE Variable_name = 'version';"); + if ( !$q ) + $this->_die("while fetching MySQL server version"); + $row = $this->fetchrow($q); + return $row['Value']; + } + + /** * Close the database connection */ @@ -584,7 +1290,8 @@ function sql_error() { - return mysql_error(); + list(,,$errtext) = $this->_conn->errorInfo(); + return $errtext; } /**