Merged
authorDan Fuhry <dan@enanocms.org>
Wed, 21 Aug 2013 22:13:58 -0400
changeset 137660b580d22c7b
parent 1374 f99b9c5036d4
parent 1375 d66e43ac35b6
child 1377 fa2b0825bbc5
Merged
     1.1 --- a/includes/dbal.php	Sat Dec 15 12:40:59 2012 -0500
     1.2 +++ b/includes/dbal.php	Wed Aug 21 22:13:58 2013 -0400
     1.3 @@ -143,6 +143,32 @@
     1.4  	
     1.5  	function connect($manual_credentials = false, $dbhost = false, $dbuser = false, $dbpasswd = false, $dbname = false, $dbport = false)
     1.6  	{
     1.7 +		if ( !function_exists('mysql_connect') )
     1.8 +		{
     1.9 +			if ( class_exists('PDO') && extension_loaded("pdo_mysql") )
    1.10 +			{
    1.11 +				$pdo_string = '<p><strong>Never fear!</strong> Your server has PDO and the PDO MySQL driver installed. This means you can simply edit your config.php to use
    1.12 +									an alternate database driver, without losing any of your existing site data. Look for the line that says:</p>
    1.13 +								<pre>$dbdriver = \'mysql\';</pre>
    1.14 +								<p>and change it to:</p>
    1.15 +								<pre>$dbdriver = \'mysql_pdo\';</pre>';
    1.16 +			}
    1.17 +			else
    1.18 +			{
    1.19 +				$pdo_string = '<p>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
    1.20 +									use the new database driver. Once the PDO and PDO_MySQL PHP extensions are installed, look in Enano\'s config.php file for
    1.21 +									the line that says:</p>
    1.22 +								<pre>$dbdriver = \'mysql\';</pre>
    1.23 +								<p>and change it to:</p>
    1.24 +								<pre>$dbdriver = \'mysql_pdo\';</pre>';
    1.25 +			}
    1.26 +			grinding_halt('MySQL no longer supported', '<p>Your site configuration specifies that the MySQL database driver is to be used, however PHP has removed this
    1.27 +								driver from newer versions.</p>' . $pdo_string .
    1.28 +								'<p><strong>Your site\'s data is not at risk.</strong> This notice by itself simply means you upgraded to a newer version of PHP. Your site\'s
    1.29 +									data ordinarily will not have been touched and your site will function properly again as soon as you switch over to the PDO MySQL
    1.30 +									driver.</p>');
    1.31 +		}
    1.32 +		
    1.33  		if ( !defined('ENANO_SQL_CONSTANTS') )
    1.34  		{
    1.35  			define('ENANO_SQL_CONSTANTS', '');
    1.36 @@ -543,6 +569,686 @@
    1.37  	}
    1.38  	
    1.39  	/**
    1.40 +	* Get MySQL server version
    1.41 +	* @return string
    1.42 +	*/
    1.43 +	
    1.44 +	function get_server_version()
    1.45 +	{
    1.46 +		return mysql_get_server_info();
    1.47 +	}
    1.48 +	
    1.49 +	/**
    1.50 + 	* Close the database connection
    1.51 + 	*/
    1.52 +	
    1.53 +	function close()
    1.54 +	{
    1.55 +		if ( !$this->_conn )
    1.56 +			return;
    1.57 +		
    1.58 +		// anything we locked should certainly be unlocked now;
    1.59 +		@mysql_query("COMMIT;", $this->_conn);
    1.60 +		@mysql_query("UNLOCK TABLES;", $this->_conn);
    1.61 +		@mysql_close($this->_conn);
    1.62 +		unset($this->_conn);
    1.63 +	}
    1.64 +	
    1.65 +	/**
    1.66 + 	* Get a list of columns in the given table
    1.67 + 	* @param string Table
    1.68 + 	* @return array
    1.69 + 	*/
    1.70 +	
    1.71 +	function columns_in($table)
    1.72 +	{
    1.73 +		if ( !is_string($table) )
    1.74 +			return false;
    1.75 +		$q = $this->sql_query("SHOW COLUMNS IN $table;");
    1.76 +		if ( !$q )
    1.77 +			$this->_die();
    1.78 +		
    1.79 +		$columns = array();
    1.80 +		while ( $row = $this->fetchrow_num() )
    1.81 +		{
    1.82 +			$columns[] = $row[0];
    1.83 +		}
    1.84 +		return $columns;
    1.85 +	}
    1.86 +	
    1.87 +	/**
    1.88 + 	* Get the text of the most recent error.
    1.89 + 	* @return string
    1.90 + 	*/
    1.91 +	
    1.92 +	function sql_error()
    1.93 +	{
    1.94 +		return mysql_error();
    1.95 +	}
    1.96 +	
    1.97 +	/**
    1.98 + 	* Generates and outputs a report of all the SQL queries made during execution. Should only be called after everything's over with.
    1.99 + 	*/
   1.100 +	
   1.101 +	function sql_report()
   1.102 +	{
   1.103 +		global $db, $session, $paths, $template, $plugins; // Common objects
   1.104 +		if ( !$session->get_permissions('mod_misc') )
   1.105 +		{
   1.106 +			die_friendly('Access denied', '<p>You are not authorized to generate a SQL backtrace.</p>');
   1.107 +		}
   1.108 +		// Create copies of variables that may be changed after header is called
   1.109 +		$backtrace = $this->query_backtrace;
   1.110 +		$times = $this->query_times;
   1.111 +		$template->header();
   1.112 +		echo '<h3>SQL query log and timetable</h3>';
   1.113 +		echo '<div class="tblholder">
   1.114 +						<table border="0" cellspacing="1" cellpadding="4">';
   1.115 +		$i = 0;
   1.116 +		foreach ( $backtrace as $query )
   1.117 +		{
   1.118 +			$i++;
   1.119 +			$unbuffered = false;
   1.120 +			if ( substr($query, 0, 13) == '(UNBUFFERED) ' )
   1.121 +			{
   1.122 +				$query = substr($query, 13);
   1.123 +				$unbuffered = true;
   1.124 +			}
   1.125 +			if ( $i == 1 )
   1.126 +			{
   1.127 +				echo '<tr>
   1.128 +								<th colspan="2">SQL backtrace for a normal page load of ' . htmlspecialchars($paths->cpage['urlname']) . '</th>
   1.129 +							</tr>';
   1.130 +			}
   1.131 +			else
   1.132 +			{
   1.133 +				echo '<tr>
   1.134 +								<th class="subhead" colspan="2">&nbsp;</th>
   1.135 +							</tr>';
   1.136 +			}
   1.137 +			echo '<tr>
   1.138 +							<td class="row2">Query:</td>
   1.139 +							<td class="row1"><pre>' . htmlspecialchars($query) . '</pre></td>
   1.140 +						</tr>
   1.141 +						<tr>
   1.142 +							<td class="row2">Time:</td>
   1.143 +							<td class="row1">' . number_format($this->query_times[$query], 6) . ' seconds</td>
   1.144 +						</tr>
   1.145 +						<tr>
   1.146 +							<td class="row2">Unbuffered:</td>
   1.147 +							<td class="row1">' . ( $unbuffered ? 'Yes' : 'No' ) . '</td>
   1.148 +						</tr>';
   1.149 +			if ( isset($this->query_sources[$query]) )
   1.150 +			{
   1.151 +				echo '<tr>
   1.152 +								<td class="row2">Called from:</td>
   1.153 +								<td class="row1">' . $this->query_sources[$query] . '</td>
   1.154 +							</tr>';
   1.155 +			}
   1.156 +		}
   1.157 +		if ( function_exists('array_sum') )
   1.158 +		{
   1.159 +			$query_time_total = array_sum($this->query_times);
   1.160 +			echo '<tr>
   1.161 +							<th class="subhead" colspan="2">
   1.162 +								Total time taken for SQL queries: ' . round( $query_time_total, 6 ) . ' seconds
   1.163 +							</th>
   1.164 +						</tr>';
   1.165 +		}
   1.166 +		echo '  </table>
   1.167 +					</div>';
   1.168 +		$template->footer();
   1.169 +	}
   1.170 +	
   1.171 +	/**
   1.172 +	 * Begin transaction
   1.173 +	 */
   1.174 +	
   1.175 +	function transaction_begin()
   1.176 +	{
   1.177 +		$this->sql_query('BEGIN;');
   1.178 +	}
   1.179 +	
   1.180 +	/**
   1.181 +	 * Commit transaction
   1.182 +	 */
   1.183 +	
   1.184 +	function transaction_commit()
   1.185 +	{
   1.186 +		$this->sql_query('COMMIT;');
   1.187 +	}
   1.188 +	
   1.189 +	/**
   1.190 +	 * Rollback transaction
   1.191 +	 */
   1.192 +	
   1.193 +	function transaction_rollback()
   1.194 +	{
   1.195 +		$this->sql_query('ROLLBACK;');
   1.196 +	}
   1.197 +}
   1.198 +
   1.199 +class mysql_pdo {
   1.200 +	var $num_queries, $query_backtrace, $query_times, $query_sources, $latest_result, $latest_query, $_conn, $sql_stack_fields, $sql_stack_values, $debug;
   1.201 +	var $row = array();
   1.202 +	var $rowset = array();
   1.203 +	var $errhandler;
   1.204 +	var $dbms_name = 'MySQL';
   1.205 +	
   1.206 +	/**
   1.207 + 	* Get a flat textual list of queries that have been made.
   1.208 + 	*/
   1.209 +	
   1.210 +	function sql_backtrace()
   1.211 +	{
   1.212 +		return implode("\n-------------------------------------------------------------------\n", $this->query_backtrace);
   1.213 +	}
   1.214 +	
   1.215 +	/**
   1.216 + 	* Connect to the database, but only if a connection isn't already up.
   1.217 + 	*/
   1.218 +	
   1.219 +	function ensure_connection()
   1.220 +	{
   1.221 +		if(!$this->_conn)
   1.222 +		{
   1.223 +			$this->connect();
   1.224 +		}
   1.225 +	}
   1.226 +	
   1.227 +	/**
   1.228 + 	* Exit Enano, dumping out a friendly error message indicating a database error on the way out.
   1.229 + 	* @param string Description or location of error; defaults to none
   1.230 + 	*/
   1.231 + 
   1.232 +	function _die($t = '')
   1.233 +	{
   1.234 +		if ( defined('ENANO_HEADERS_SENT') )
   1.235 +			ob_clean();
   1.236 +		
   1.237 +		$internal_text = $this->get_error($t);
   1.238 +		
   1.239 +		if ( defined('ENANO_CONFIG_FETCHED') )
   1.240 +			// config is in, we can show a slightly nicer looking error page
   1.241 +			die_semicritical('Database error', $internal_text);
   1.242 +		else
   1.243 +			// no config, display using no-DB template engine
   1.244 +			grinding_halt('Database error', $internal_text);
   1.245 +		
   1.246 +		exit;
   1.247 +	}
   1.248 +	
   1.249 +	/**
   1.250 + 	* Get the internal text used for a database error message.
   1.251 + 	* @param string Description or location of error; defaults to none
   1.252 + 	*/
   1.253 +	
   1.254 +	function get_error($t = '')
   1.255 +	{
   1.256 +		@header('HTTP/1.1 500 Internal Server Error');
   1.257 +		
   1.258 +		$bt = $this->latest_query;
   1.259 +		$e = htmlspecialchars($this->sql_error());
   1.260 +		if ( empty($e) )
   1.261 +			$e = '&lt;none&gt;';
   1.262 +		
   1.263 +		global $email;
   1.264 +		
   1.265 +		// As long as the admin's e-mail is accessible, display it.
   1.266 +		$email_info = ( defined('ENANO_CONFIG_FETCHED') && is_object($email) )
   1.267 +										? ', at &lt;' . $email->jscode() . $email->encryptEmail(getConfig('contact_email')) . '&gt;'
   1.268 +										: '';
   1.269 +		
   1.270 +		$internal_text = "<h3>The site was unable to finish serving your request.</h3>
   1.271 +											<p>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}.</p>
   1.272 +											<p>Description or location of error: $t<br />
   1.273 +											Error returned by $this->dbms_name extension: $e</p>
   1.274 +											<p>Most recent SQL query:</p>
   1.275 +											<pre>$bt</pre>";
   1.276 +		return $internal_text;
   1.277 +	}
   1.278 +	
   1.279 +	/**
   1.280 + 	* Exit Enano and output a JSON format datbase error.
   1.281 + 	* @param string Description or location of error; defaults to none
   1.282 + 	*/
   1.283 +	
   1.284 +	function die_json($loc = false)
   1.285 +	{
   1.286 +		$e = str_replace("\n", "\\n", addslashes(htmlspecialchars($this->sql_error())));
   1.287 +		$q = str_replace("\n", "\\n", addslashes($this->latest_query));
   1.288 +		$loc = ( $loc ) ? addslashes("\n\nDescription or location of error: $loc") : "";
   1.289 +		$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.";
   1.290 +		$loc = str_replace("\n", "\\n", $loc);
   1.291 +		$t = "{\"mode\":\"error\",\"error\":\"An error occurred during database query.\\nQuery was:\\n  $q\\n\\nError returned by {$this->dbms_name}: $e$loc\"}";
   1.292 +		die($t);
   1.293 +	}
   1.294 +	
   1.295 +	/**
   1.296 + 	* Connect to the database.
   1.297 + 	* @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.
   1.298 + 	* @param string Database server hostname
   1.299 + 	* @param string Database server username
   1.300 + 	* @param string Database server password
   1.301 + 	* @param string Name of the database
   1.302 + 	* @param int Optional port number to connect over
   1.303 + 	*/
   1.304 +	
   1.305 +	function connect($manual_credentials = false, $dbhost = false, $dbuser = false, $dbpasswd = false, $dbname = false, $dbport = false)
   1.306 +	{
   1.307 +		if ( !defined('ENANO_SQL_CONSTANTS') )
   1.308 +		{
   1.309 +			define('ENANO_SQL_CONSTANTS', '');
   1.310 +			define('ENANO_DBLAYER', 'MYSQL');
   1.311 +			define('ENANO_SQLFUNC_LOWERCASE', 'lcase');
   1.312 +			define('ENANO_SQL_MULTISTRING_PRFIX', '');
   1.313 +			define('ENANO_SQL_BOOLEAN_TRUE', 'true');
   1.314 +			define('ENANO_SQL_BOOLEAN_FALSE', 'false');
   1.315 +		}
   1.316 +		
   1.317 +		if ( !$manual_credentials )
   1.318 +		{
   1.319 +			if ( defined('IN_ENANO_INSTALL') && !defined('IN_ENANO_UPGRADE') )
   1.320 +			{
   1.321 +				@include(ENANO_ROOT.'/config.new.php');
   1.322 +			}
   1.323 +			else
   1.324 +			{
   1.325 +				@include(ENANO_ROOT.'/config.php');
   1.326 +			}
   1.327 +			
   1.328 +			if ( isset($crypto_key) )
   1.329 +				unset($crypto_key); // Get this sucker out of memory fast
   1.330 +			if ( empty($dbport) )
   1.331 +				$dbport = 3306;
   1.332 +			
   1.333 +			if ( !defined('ENANO_INSTALLED') && !defined('MIDGET_INSTALLED') && !defined('IN_ENANO_INSTALL') )
   1.334 +			{
   1.335 +				// scriptPath isn't set yet - we need to autodetect it to avoid infinite redirects
   1.336 +				if ( !defined('scriptPath') )
   1.337 +				{
   1.338 +					if ( isset($_SERVER['PATH_INFO']) && !preg_match('/index\.php$/', $_SERVER['PATH_INFO']) )
   1.339 +					{
   1.340 +						$_SERVER['REQUEST_URI'] = preg_replace(';' . preg_quote($_SERVER['PATH_INFO']) . '$;', '', $_SERVER['REQUEST_URI']);
   1.341 +					}
   1.342 +					if ( !preg_match('/\.php$/', $_SERVER['REQUEST_URI']) )
   1.343 +					{
   1.344 +						// user requested http://foo/enano as opposed to http://foo/enano/index.php
   1.345 +						$_SERVER['REQUEST_URI'] .= '/index.php';
   1.346 +					}
   1.347 +					$sp = dirname($_SERVER['REQUEST_URI']);
   1.348 +					if($sp == '/' || $sp == '\\') $sp = '';
   1.349 +					define('scriptPath', $sp);
   1.350 +					define('contentPath', "$sp/index.php?title=");
   1.351 +				}
   1.352 +				$loc = scriptPath . '/install/index.php';
   1.353 +				define('IN_ENANO_INSTALL', 1);
   1.354 +				$GLOBALS['lang'] = new Language('eng');
   1.355 +				global $lang;
   1.356 +				$lang->load_file('./language/english/core.json');
   1.357 +				$lang->load_file('./language/english/install.json');
   1.358 +				// header("Location: $loc");
   1.359 +				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);
   1.360 +				exit;
   1.361 +			}
   1.362 +		}
   1.363 +		
   1.364 +		if ( !$dbport )
   1.365 +			$dbport = 3306;
   1.366 +		
   1.367 +		if ( $dbhost && !empty($dbport) && $dbport != 3306 )
   1.368 +			$dbhost = '127.0.0.1';
   1.369 +		
   1.370 +		$host_line = ( preg_match('/^:/', $dbhost) ) ? $dbhost : "{$dbhost}:{$dbport}";
   1.371 +		
   1.372 +		$this->_conn = new PDO("mysql:host=$dbhost;dbname=$dbname;charset=UTF8", $dbuser, $dbpasswd);
   1.373 +		
   1.374 +		unset($dbuser);
   1.375 +		unset($dbpasswd); // Security
   1.376 +		
   1.377 +		if ( !$this->_conn && !$manual_credentials )
   1.378 +		{
   1.379 +			grinding_halt('Enano is having a problem', '<p>Error: couldn\'t connect to MySQL.<br />'.mysql_error().'</p>');
   1.380 +		}
   1.381 +		else if ( !$this->_conn && $manual_credentials )
   1.382 +		{
   1.383 +			return false;
   1.384 +		}
   1.385 +		
   1.386 +		// Reset some variables
   1.387 +		$this->query_backtrace = array();
   1.388 +		$this->query_times = array();
   1.389 +		$this->query_sources = array();
   1.390 +		$this->num_queries = 0;
   1.391 +		
   1.392 +		$this->debug = ( defined('ENANO_DEBUG') );
   1.393 +		
   1.394 +		// We're in!
   1.395 +		return true;
   1.396 +	}
   1.397 +	
   1.398 +	/**
   1.399 + 	* Make a SQL query.
   1.400 + 	* @param string Query
   1.401 + 	* @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.
   1.402 + 	* @return resource or false on failure
   1.403 + 	*/
   1.404 +	
   1.405 +	function sql_query($q, $log_query = true)
   1.406 +	{
   1.407 +		if ( $this->debug && function_exists('debug_backtrace') )
   1.408 +		{
   1.409 +			$backtrace = @debug_backtrace();
   1.410 +			if ( is_array($backtrace) )
   1.411 +			{
   1.412 +				$bt = $backtrace[0];
   1.413 +				if ( isset($backtrace[1]['class']) )
   1.414 +				{
   1.415 +					if ( $backtrace[1]['class'] == 'sessionManager' )
   1.416 +					{
   1.417 +						$bt = $backtrace[1];
   1.418 +					}
   1.419 +				}
   1.420 +				$this->query_sources[$q] = substr($bt['file'], strlen(ENANO_ROOT) + 1) . ', line ' . $bt['line'];
   1.421 +			}
   1.422 +			unset($backtrace);
   1.423 +		}
   1.424 +		
   1.425 +		$this->num_queries++;
   1.426 +		if ( $log_query || defined('ENANO_DEBUG') )
   1.427 +		{
   1.428 +			$this->query_backtrace[] = $q;
   1.429 +			$this->latest_query = $q;
   1.430 +		}
   1.431 +		// First make sure we have a connection
   1.432 +		if ( !$this->_conn )
   1.433 +		{
   1.434 +			$this->_die('A database connection has not yet been established.');
   1.435 +		}
   1.436 +		// Start the timer
   1.437 +		if ( $log_query || defined('ENANO_DEBUG') )
   1.438 +			$time_start = microtime_float();
   1.439 +		// Does this query look malicious?
   1.440 +		if ( $log_query || defined('ENANO_DEBUG') )
   1.441 +		{
   1.442 +			if ( !$this->check_query($q) )
   1.443 +			{
   1.444 +				$this->report_query($q);
   1.445 +				$debug = ( defined('ENANO_DEBUG') ) ? '<p>Query was:</p><pre>'.htmlspecialchars($q).'</pre>' : '';
   1.446 +				grinding_halt('SQL Injection attempt', '<p>Enano has caught and prevented an SQL injection attempt. Your IP address has been recorded and the administrator has been notified.</p>' . $debug);
   1.447 +			}
   1.448 +		}
   1.449 +		
   1.450 +		try
   1.451 +		{
   1.452 +			$r = $this->_conn->query($q);
   1.453 +		}
   1.454 +		catch ( PDOException $e )
   1.455 +		{
   1.456 +			return false;
   1.457 +		}
   1.458 +		
   1.459 +		if ( $log_query )
   1.460 +			$this->query_times[$q] = microtime_float() - $time_start;
   1.461 +		
   1.462 +		$this->latest_result = $r;
   1.463 +		
   1.464 +		return $r;
   1.465 +	}
   1.466 +	
   1.467 +	/**
   1.468 + 	* 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.
   1.469 + 	* @param string Query
   1.470 + 	* @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.
   1.471 + 	* @return resource or false on failure
   1.472 + 	*/
   1.473 +	
   1.474 +	function sql_unbuffered_query($q, $log_query = true)
   1.475 +	{
   1.476 +		$this->num_queries++;
   1.477 +		if ( $log_query || defined('ENANO_DEBUG') )
   1.478 +			$this->query_backtrace[] = '(UNBUFFERED) ' . $q;
   1.479 +		$this->latest_query = $q;
   1.480 +		// First make sure we have a connection
   1.481 +		if ( !$this->_conn )
   1.482 +		{
   1.483 +			$this->_die('A database connection has not yet been established.');
   1.484 +		}
   1.485 +		// Does this query look malicious?
   1.486 +		if ( !$this->check_query($q) )
   1.487 +		{
   1.488 +			$this->report_query($q);
   1.489 +			$debug = ( defined('ENANO_DEBUG') ) ? '<p>Query was:</p><pre>'.htmlspecialchars($q).'</pre>' : '';
   1.490 +			grinding_halt('SQL Injection attempt', '<p>Enano has caught and prevented an SQL injection attempt. Your IP address has been recorded and the administrator has been notified.</p>' . $debug);
   1.491 +		}
   1.492 +		
   1.493 +		$time_start = microtime_float();
   1.494 +		try
   1.495 +		{
   1.496 +			$r = $this->_conn->query($q);
   1.497 +		}
   1.498 +		catch ( PDOException $e )
   1.499 +		{
   1.500 +			return false;
   1.501 +		}
   1.502 +		$this->query_times[$q] = microtime_float() - $time_start;
   1.503 +		$this->latest_result = $r;
   1.504 +		return $r;
   1.505 +	}
   1.506 +	
   1.507 +	/**
   1.508 + 	* Performs heuristic analysis on a SQL query to check for known attack patterns.
   1.509 + 	* @param string $q the query to check
   1.510 + 	* @return bool true if query passed check, otherwise false
   1.511 + 	*/
   1.512 +	
   1.513 +	function check_query($q, $debug = false)
   1.514 +	{
   1.515 +		global $db_sql_parse_time;
   1.516 +		$ts = microtime_float();
   1.517 +		
   1.518 +		// remove properly escaped quotes
   1.519 +		$q = str_replace('\\\\', '', $q);
   1.520 +		$q = str_replace(array("\\\"", "\\'"), '', $q);
   1.521 +		
   1.522 +		// make sure quotes match
   1.523 +		foreach ( array("'", '"') as $quote )
   1.524 +		{
   1.525 +			$n_quotes = get_char_count($q, $quote);
   1.526 +			if ( $n_quotes % 2 == 1 )
   1.527 +			{
   1.528 +				// mismatched quotes
   1.529 +				if ( $debug ) echo "Found mismatched quotes in query; parsed:\n$q\n";
   1.530 +				return false;
   1.531 +			}
   1.532 +			// this quote is now confirmed to be matching; we can safely move all quoted strings out and replace with a token
   1.533 +			$q = preg_replace("/$quote(.*?)$quote/s", 'SAFE_QUOTE', $q);
   1.534 +		}
   1.535 +		$q = preg_replace("/(SAFE_QUOTE)+/", 'SAFE_QUOTE', $q);
   1.536 +		
   1.537 +		// quotes are now matched out. does this string have a comment marker in it?
   1.538 +		if ( strstr($q, '--') )
   1.539 +		{
   1.540 +			return false;
   1.541 +		}
   1.542 +		
   1.543 +		if ( preg_match('/[\s]+(SAFE_QUOTE|[\S]+)=\\1($|[\s]+)/', $q, $match) )
   1.544 +		{
   1.545 +			if ( $debug ) echo 'Found always-true test in query, injection attempt caught, match:<br />' . '<pre>' . print_r($match, true) . '</pre>';
   1.546 +			return false;
   1.547 +		}
   1.548 +		
   1.549 +		$ts = microtime_float() - $ts;
   1.550 +		$db_sql_parse_time += $ts;
   1.551 +		return true;
   1.552 +	}
   1.553 +	
   1.554 +	/**
   1.555 + 	* Set the internal result pointer to X
   1.556 + 	* @param int $pos The number of the row
   1.557 + 	* @param resource $result The MySQL result resource - if not given, the latest cached query is assumed
   1.558 + 	* @return true on success, false on failure
   1.559 + 	*/
   1.560 + 	
   1.561 +	function sql_data_seek($pos, $result = false)
   1.562 +	{
   1.563 +		if ( !$result )
   1.564 +			$result = $this->latest_result;
   1.565 +		if ( !$result )
   1.566 +			return false;
   1.567 +		
   1.568 +		return mysql_data_seek($result, $pos) ? true : false;
   1.569 +	}
   1.570 +	
   1.571 +	/**
   1.572 + 	* Reports a bad query to the admin
   1.573 + 	* @param string $query the naughty query
   1.574 + 	* @access private
   1.575 + 	*/
   1.576 + 	
   1.577 +	function report_query($query)
   1.578 +	{
   1.579 +		global $session;
   1.580 +		if ( is_object($session) && defined('ENANO_MAINSTREAM') )
   1.581 +		{
   1.582 +			$username = $session->username;
   1.583 +			$user_id = $session->user_id;
   1.584 +		}
   1.585 +		else
   1.586 +		{
   1.587 +			$username = 'Unavailable';
   1.588 +			$user_id = 1;
   1.589 +		} 
   1.590 +		
   1.591 +		$query = $this->escape($query);
   1.592 +		$q = $this->sql_query('INSERT INTO '.table_prefix.'logs(log_type,     action,         time_id,    date_string, page_text,      author,            author_uid,       edit_summary)
   1.593 + 																										VALUES(\'security\', \'sql_inject\', '.time().', \'\',        \''.$query.'\', \''.$username.'\', ' . $user_id . ', \''.$_SERVER['REMOTE_ADDR'].'\');');
   1.594 +	}
   1.595 +	
   1.596 +	/**
   1.597 + 	* Returns the ID of the row last inserted.
   1.598 + 	* @return int
   1.599 + 	*/
   1.600 +	
   1.601 +	function insert_id()
   1.602 +	{
   1.603 +		$q = $this->sql_query("SELECT LAST_INSERT_ID();");
   1.604 +		if ( !$q )
   1.605 +			return false;
   1.606 +		
   1.607 +		list($iid) = $this->fetchrow_num();
   1.608 +		return $iid;
   1.609 +	}
   1.610 +	
   1.611 +	/**
   1.612 + 	* Fetch one row from the given query as an associative array.
   1.613 + 	* @param resource The resource returned from sql_query; if this isn't provided, the last result resource is used.
   1.614 + 	* @return array
   1.615 + 	*/
   1.616 +	
   1.617 +	function fetchrow($r = false)
   1.618 +	{
   1.619 +		if ( !$this->_conn )
   1.620 +			return false;
   1.621 +		
   1.622 +		if ( !$r )
   1.623 +			$r = $this->latest_result;
   1.624 +		
   1.625 +		if ( !$r )
   1.626 +			$this->_die('$db->fetchrow(): an invalid MySQL resource was passed.');
   1.627 +		
   1.628 +		$row = $r->fetch(PDO::FETCH_ASSOC);
   1.629 +		
   1.630 +		return integerize_array($row);
   1.631 +	}
   1.632 +	
   1.633 +	/**
   1.634 + 	* Fetch one row from the given query as a numeric array.
   1.635 + 	* @param resource The resource returned from sql_query; if this isn't provided, the last result resource is used.
   1.636 + 	* @return array
   1.637 + 	*/
   1.638 +	
   1.639 +	function fetchrow_num($r = false)
   1.640 +	{
   1.641 +		if ( !$r )
   1.642 +			$r = $this->latest_result;
   1.643 +		if ( !$r )
   1.644 +			$this->_die('$db->fetchrow(): an invalid MySQL resource was passed.');
   1.645 +		
   1.646 +		$row = $r->fetch(PDO::FETCH_NUM);
   1.647 +		return integerize_array($row);
   1.648 +	}
   1.649 +	
   1.650 +	/**
   1.651 + 	* Get the number of results for a given query.
   1.652 + 	* @param resource The resource returned from sql_query; if this isn't provided, the last result resource is used.
   1.653 + 	* @return array
   1.654 + 	*/
   1.655 +	
   1.656 +	function numrows($r = false)
   1.657 +	{
   1.658 +		if ( !$r )
   1.659 +			$r = $this->latest_result;
   1.660 +		if ( !$r )
   1.661 +			$this->_die('$db->fetchrow(): an invalid MySQL resource was passed.');
   1.662 +		
   1.663 +		return $r->rowCount();
   1.664 +	}
   1.665 +	
   1.666 +	/**
   1.667 + 	* Escape a string so that it may safely be included in a SQL query.
   1.668 + 	* @param string String to escape
   1.669 + 	* @return string Escaped string
   1.670 + 	*/
   1.671 +	
   1.672 +	function escape($str)
   1.673 +	{
   1.674 +		$str = substr($this->_conn->quote($str), 1, -1);
   1.675 +		return $str;
   1.676 +	}
   1.677 +	
   1.678 +	/**
   1.679 + 	* Free the given result from memory. Use this when completely finished with a result resource.
   1.680 + 	* @param resource The resource returned from sql_query; if this isn't provided, the last result resource is used.
   1.681 + 	* @return null
   1.682 + 	*/
   1.683 +	
   1.684 +	function free_result($result = false)
   1.685 +	{
   1.686 +		if ( !$result )
   1.687 +			$result = $this->latest_result;
   1.688 +		if ( !$result )
   1.689 +			return null;
   1.690 +		
   1.691 +		//@mysql_free_result($result);
   1.692 +		return null;
   1.693 +	}
   1.694 +	
   1.695 +	/**
   1.696 + 	* Returns the number of rows affected.
   1.697 + 	* @return int
   1.698 + 	*/
   1.699 +	
   1.700 +	function sql_affectedrows()
   1.701 +	{
   1.702 +		return mysql_affected_rows($this->_conn);
   1.703 +	}
   1.704 +	
   1.705 +	/**
   1.706 +	* Get MySQL server version
   1.707 +	* @return string
   1.708 +	*/
   1.709 +	
   1.710 +	function get_server_version()
   1.711 +	{
   1.712 +		$q = $this->sql_query("SHOW VARIABLES WHERE Variable_name = 'version';");
   1.713 +		if ( !$q )
   1.714 +			$this->_die("while fetching MySQL server version");
   1.715 +		$row = $this->fetchrow($q);
   1.716 +		return $row['Value'];
   1.717 +	}
   1.718 +	
   1.719 +	/**
   1.720   	* Close the database connection
   1.721   	*/
   1.722  	
   1.723 @@ -584,7 +1290,8 @@
   1.724  	
   1.725  	function sql_error()
   1.726  	{
   1.727 -		return mysql_error();
   1.728 +		list(,,$errtext) = $this->_conn->errorInfo();
   1.729 +		return $errtext;
   1.730  	}
   1.731  	
   1.732  	/**