db.php 43.7 KB
Newer Older
root's avatar
root committed
1
<?php
lucha's avatar
lucha committed
2 3 4 5 6 7 8 9 10 11
/*
Plugin Name: HyperDB
Plugin URI: https://wordpress.org/plugins/hyperdb/
Description: An advanced database class that supports replication, failover, load balancing, and partitioning.
Author: Automattic
License: GPLv2 or later
Version: 1.5
*/

/** This file should be installed at ABSPATH/wp-content/db.php **/
root's avatar
root committed
12 13 14

/** Load the wpdb class while preventing instantiation **/
$wpdb = true;
shammash's avatar
shammash committed
15 16 17 18
if ( defined('WPDB_PATH') )
	require_once(WPDB_PATH);
else
	require_once( ABSPATH . WPINC . '/wp-db.php' );
root's avatar
root committed
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41

if ( defined('DB_CONFIG_FILE') && file_exists( DB_CONFIG_FILE ) ) {

	/** The config file was defined earlier. **/

} elseif ( file_exists( ABSPATH . 'db-config.php') ) {

	/** The config file resides in ABSPATH. **/
	define( 'DB_CONFIG_FILE', ABSPATH . 'db-config.php' );

} elseif ( file_exists( dirname(ABSPATH) . '/db-config.php' ) && ! file_exists( dirname(ABSPATH) . '/wp-settings.php' ) ) {

	/** The config file resides one level above ABSPATH but is not part of another install. **/
	define( 'DB_CONFIG_FILE', dirname(ABSPATH) . '/db-config.php' );

} else {

	/** Lacking a config file, revert to the standard database class. **/
	$wpdb = new wpdb( DB_USER, DB_PASSWORD, DB_NAME, DB_HOST );
	return;

}

shammash's avatar
shammash committed
42
/**
lucha's avatar
lucha committed
43
 * Common definitions
shammash's avatar
shammash committed
44 45 46 47 48
 */
define( 'HYPERDB_LAG_OK', 1 );
define( 'HYPERDB_LAG_BEHIND', 2 );
define( 'HYPERDB_LAG_UNKNOWN', 3 );

lucha's avatar
lucha committed
49 50 51
define( 'HYPERDB_CONN_HOST_ERROR', 2003 );   // Can't connect to MySQL server on '%s' (%d)
define( 'HYPERDB_SERVER_GONE_ERROR', 2006 ); // MySQL server has gone away

root's avatar
root committed
52
class hyperdb extends wpdb {
53 54

        /**
joe's avatar
joe committed
55
	 * A/I patch!
56 57 58 59
	 * store a FlexiHash() instance here.
	 */
	var $hash_map;

root's avatar
root committed
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
	/**
	 * The last table that was queried
	 * @var string
	 */
	var $last_table;

	/**
	 * After any SQL_CALC_FOUND_ROWS query, the query "SELECT FOUND_ROWS()"
	 * is sent and the mysql result resource stored here. The next query
	 * for FOUND_ROWS() will retrieve this. We do this to prevent any
	 * intervening queries from making FOUND_ROWS() inaccessible. You may
	 * prevent this by adding "NO_SELECT_FOUND_ROWS" in a comment.
	 * @var resource
	 */
	var $last_found_rows_result;

	/**
	 * Whether to store queries in an array. Useful for debugging and profiling.
	 * @var bool
	 */
	var $save_queries = false;

	/**
	 * The current mysql link resource
	 * @var resource
	 */
	var $dbh;

	/**
	 * Associative array (dbhname => dbh) for established mysql connections
	 * @var array
	 */
	var $dbhs;

	/**
	 * The multi-dimensional array of datasets and servers
	 * @var array
	 */
	var $hyper_servers = array();

	/**
	 * Optional directory of tables and their datasets
	 * @var array
	 */
	var $hyper_tables = array();

	/**
	 * Optional directory of callbacks to determine datasets from queries
	 * @var array
	 */
	var $hyper_callbacks = array();

	/**
	 * Custom callback to save debug info in $this->queries
	 * @var callable
	 */
	var $save_query_callback = null;

	/**
lucha's avatar
lucha committed
119
	 * Whether to use persistent connections
root's avatar
root committed
120 121 122 123 124 125 126 127 128 129 130 131
	 * @var bool
	 */
	var $persistent = false;

	/**
	 * The maximum number of db links to keep open. The least-recently used
	 * link will be closed when the number of links exceeds this.
	 * @var int
	 */
	var $max_connections = 10;

	/**
lucha's avatar
lucha committed
132
	 * Whether to check with fsockopen prior to connecting to mysql.
root's avatar
root committed
133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173
	 * @var bool
	 */
	var $check_tcp_responsiveness = true;

	/**
	 * Minimum number of connections to try before bailing
	 * @var int
	 */
	var $min_tries = 3;

	/**
	 * Send Reads To Masters. This disables slave connections while true.
	 * Otherwise it is an array of written tables.
	 * @var array
	 */
	var $srtm = array();

	/**
	 * The log of db connections made and the time each one took
	 * @var array
	 */
	var $db_connections;

	/**
	 * The list of unclosed connections sorted by LRU
	 */
	var $open_connections = array();

	/**
	 * The last server used and the database name selected
	 * @var array
	 */
	var $last_used_server;

	/**
	 * Lookup array (dbhname => (server, db name) ) for re-selecting the db
	 * when a link is re-used.
	 * @var array
	 */
	var $used_servers = array();

shammash's avatar
shammash committed
174 175 176 177 178 179 180 181 182 183 184 185
	/**
	 * Whether to save debug_backtrace in save_query_callback. You may wish
	 * to disable this, e.g. when tracing out-of-memory problems.
	 */
	var $save_backtrace = true;

	/**
	 * Maximum lag in seconds. Set null to disable. Requires callbacks.
	 * @var integer
	 */
	var $default_lag_threshold = null;

root's avatar
root committed
186
	/**
lucha's avatar
lucha committed
187 188
	 * Lookup array (dbhname => host:port)
	 * @var array
root's avatar
root committed
189
	 */
lucha's avatar
lucha committed
190 191 192 193 194 195 196 197 198 199 200
	var $dbh2host = array();

	/**
	 * Keeps track of the dbhname usage and errors.
	 */
	var $dbhname_heartbeats = array();

	/**
	 * Counter for how many queries have failed during the life of the $wpdb object
	 */
	var $num_failed_queries = 0;
root's avatar
root committed
201 202 203 204 205 206 207 208 209 210

	/**
	 * Gets ready to make database connections
	 * @param array db class vars
	 */
	function __construct( $args = null ) {
		if ( is_array($args) )
			foreach ( get_class_vars(__CLASS__) as $var => $value )
				if ( isset($args[$var]) )
					$this->$var = $args[$var];
shammash's avatar
shammash committed
211

lucha's avatar
lucha committed
212 213
		$this->use_mysqli = $this->should_use_mysqli();

shammash's avatar
shammash committed
214 215 216
		$this->init_charset();
	}

lucha's avatar
lucha committed
217 218 219 220 221 222 223
	/**
	 * Triggers __construct() for backwards compatibility with PHP4
	 */
	function hyperdb( $args = null ) {
		return $this->__construct($args);
	}

shammash's avatar
shammash committed
224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239
	/**
	 * Sets $this->charset and $this->collate
	 */
	function init_charset() {
		if ( function_exists('is_multisite') && is_multisite() ) {
			$this->charset = 'utf8';
			if ( defined( 'DB_COLLATE' ) && DB_COLLATE )
				$this->collate = DB_COLLATE;
			else
				$this->collate = 'utf8_general_ci';
		} elseif ( defined( 'DB_COLLATE' ) ) {
			$this->collate = DB_COLLATE;
		}

		if ( defined( 'DB_CHARSET' ) )
			$this->charset = DB_CHARSET;
root's avatar
root committed
240 241 242 243 244 245 246 247 248 249 250
	}

	/**
	 * Add the connection parameters for a database
	 */
	function add_database( $db ) {
		extract($db, EXTR_SKIP);
		isset($dataset) or $dataset = 'global';
		isset($read)    or $read = 1;
		isset($write)   or $write = 1;
		unset($db['dataset']);
shammash's avatar
shammash committed
251

root's avatar
root committed
252 253 254 255 256 257 258 259 260 261 262 263 264 265
		if ( $read )
			$this->hyper_servers[ $dataset ][ 'read' ][ $read ][] = $db;
		if ( $write )
			$this->hyper_servers[ $dataset ][ 'write' ][ $write ][] = $db;
	}

	/**
	 * Specify the dateset where a table is found
	 */
	function add_table( $dataset, $table ) {
		$this->hyper_tables[ $table ] = $dataset;
	}

	/**
shammash's avatar
shammash committed
266
	 * Add a callback to a group of callbacks.
lucha's avatar
lucha committed
267
	 * The default group is 'dataset', used to examine
shammash's avatar
shammash committed
268
	 * queries and determine dataset.
root's avatar
root committed
269
	 */
shammash's avatar
shammash committed
270 271
	function add_callback( $callback, $group = 'dataset' ) {
		$this->hyper_callbacks[ $group ][] = $callback;
root's avatar
root committed
272 273 274 275 276 277 278
	}

	/**
	 * Find the first table name referenced in a query
	 * @param string query
	 * @return string table
	 */
lucha's avatar
lucha committed
279
	function get_table_from_query( $q ) {
root's avatar
root committed
280 281 282
		// Remove characters that can legally trail the table name
		$q = rtrim($q, ';/-#');
		// allow (select...) union [...] style queries. Use the first queries table name.
joe's avatar
joe committed
283
		$q = ltrim($q, "\t (");
lucha's avatar
lucha committed
284 285 286 287 288 289 290 291 292 293 294 295 296
		// Strip everything between parentheses except nested
		// selects and use only 1500 chars of the query
		$q = preg_replace( '/\((?!\s*select)[^(]*?\)/is', '()', substr( $q, 0, 1500 ) );

		// Refer to the previous query
		// wpdb doesn't implement last_table, so we run it first.
		if ( preg_match('/^\s*SELECT.*?\s+FOUND_ROWS\(\)/is', $q) )
			return $this->last_table;

		if( method_exists( get_parent_class( $this ), 'get_table_from_query' ) ) {
			// WPDB has added support for get_table_from_query, which should take precedence
			return parent::get_table_from_query( $q );
		}
root's avatar
root committed
297 298 299 300 301 302 303 304

		// Quickly match most common queries
		if ( preg_match('/^\s*(?:'
				. 'SELECT.*?\s+FROM'
				. '|INSERT(?:\s+IGNORE)?(?:\s+INTO)?'
				. '|REPLACE(?:\s+INTO)?'
				. '|UPDATE(?:\s+IGNORE)?'
				. '|DELETE(?:\s+IGNORE)?(?:\s+FROM)?'
lucha's avatar
lucha committed
305
				. ')\s+`?([\w-]+)`?/is', $q, $maybe) )
root's avatar
root committed
306 307
			return $maybe[1];

joe's avatar
joe committed
308 309
		// SHOW TABLE STATUS and SHOW TABLES
		if ( preg_match('/^\s*(?:'
root's avatar
root committed
310
				. 'SHOW\s+TABLE\s+STATUS.+(?:LIKE\s+|WHERE\s+Name\s*=\s*)'
joe's avatar
joe committed
311
				. '|SHOW\s+(?:FULL\s+)?TABLES.+(?:LIKE\s+|WHERE\s+Name\s*=\s*)'
lucha's avatar
lucha committed
312
				. ')\W([\w-]+)\W/is', $q, $maybe) )
root's avatar
root committed
313 314
			return $maybe[1];

315 316 317 318 319 320
        // SHOW TABLES LIKE (used in some plugins)
        if ( preg_match('/^\s*'
                . 'SHOW\s+TABLES\s+LIKE\s+'
                . '\W(\w+)\W/is', $q, $maybe) )
            return $maybe[1];

root's avatar
root committed
321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339
		// Big pattern for the rest of the table-related queries in MySQL 5.0
		if ( preg_match('/^\s*(?:'
				. '(?:EXPLAIN\s+(?:EXTENDED\s+)?)?SELECT.*?\s+FROM'
				. '|INSERT(?:\s+LOW_PRIORITY|\s+DELAYED|\s+HIGH_PRIORITY)?(?:\s+IGNORE)?(?:\s+INTO)?'
				. '|REPLACE(?:\s+LOW_PRIORITY|\s+DELAYED)?(?:\s+INTO)?'
				. '|UPDATE(?:\s+LOW_PRIORITY)?(?:\s+IGNORE)?'
				. '|DELETE(?:\s+LOW_PRIORITY|\s+QUICK|\s+IGNORE)*(?:\s+FROM)?'
				. '|DESCRIBE|DESC|EXPLAIN|HANDLER'
				. '|(?:LOCK|UNLOCK)\s+TABLE(?:S)?'
				. '|(?:RENAME|OPTIMIZE|BACKUP|RESTORE|CHECK|CHECKSUM|ANALYZE|OPTIMIZE|REPAIR).*\s+TABLE'
				. '|TRUNCATE(?:\s+TABLE)?'
				. '|CREATE(?:\s+TEMPORARY)?\s+TABLE(?:\s+IF\s+NOT\s+EXISTS)?'
				. '|ALTER(?:\s+IGNORE)?\s+TABLE'
				. '|DROP\s+TABLE(?:\s+IF\s+EXISTS)?'
				. '|CREATE(?:\s+\w+)?\s+INDEX.*\s+ON'
				. '|DROP\s+INDEX.*\s+ON'
				. '|LOAD\s+DATA.*INFILE.*INTO\s+TABLE'
				. '|(?:GRANT|REVOKE).*ON\s+TABLE'
				. '|SHOW\s+(?:.*FROM|.*TABLE)'
lucha's avatar
lucha committed
340
				. ')\s+`?([\w-]+)`?/is', $q, $maybe) )
root's avatar
root committed
341 342 343 344 345 346 347 348 349 350
			return $maybe[1];
	}

	/**
	 * Determine the likelihood that this query could alter anything
	 * @param string query
	 * @return bool
	 */
	function is_write_query( $q ) {
		// Quick and dirty: only SELECT statements are considered read-only.
shammash's avatar
shammash committed
351
		$q = ltrim($q, "\r\n\t (");
lucha's avatar
lucha committed
352
		return !preg_match('/^(?:SELECT|SHOW|DESCRIBE|DESC|EXPLAIN)\s/i', $q);
root's avatar
root committed
353 354 355 356 357 358 359 360 361 362
	}

	/**
	 * Set a flag to prevent reading from slaves which might be lagging after a write
	 */
	function send_reads_to_masters() {
		$this->srtm = true;
	}

	/**
shammash's avatar
shammash committed
363 364
	 * Callbacks are executed in the order in which they are registered until one
	 * of them returns something other than null.
root's avatar
root committed
365
	 */
shammash's avatar
shammash committed
366
	function run_callbacks( $group, $args = null) {
lucha's avatar
lucha committed
367
		if ( ! isset( $this->hyper_callbacks[ $group ] ) || ! is_array( $this->hyper_callbacks[ $group ] ) )
shammash's avatar
shammash committed
368 369
			return null;

lucha's avatar
lucha committed
370
		if ( ! isset( $args ) ) {
shammash's avatar
shammash committed
371 372 373 374 375 376 377 378
			$args = array( &$this );
		} elseif ( is_array( $args ) ) {
			$args[] = &$this;
		} else {
			$args = array( $args, &$this );
		}

		foreach ( $this->hyper_callbacks[ $group ] as $func ) {
root's avatar
root committed
379 380 381 382 383 384 385 386 387 388 389
			$result = call_user_func_array($func, $args);
			if ( isset($result) )
				return $result;
		}
	}

	/**
	 * Figure out which database server should handle the query, and connect to it.
	 * @param string query
	 * @return resource mysql database connection
	 */
joe's avatar
joe committed
390
	function db_connect( $query = '' ) {
root's avatar
root committed
391 392 393 394 395 396 397 398
		if ( empty( $query ) )
			return false;

		$this->last_table = $this->table = $this->get_table_from_query($query);

		if ( isset($this->hyper_tables[$this->table]) ) {
			$dataset = $this->hyper_tables[$this->table];
			$this->callback_result = null;
shammash's avatar
shammash committed
399
		} elseif ( null !== $this->callback_result = $this->run_callbacks( 'dataset', $query ) ) {
root's avatar
root committed
400 401 402 403 404 405
			if ( is_array($this->callback_result) )
				extract( $this->callback_result, EXTR_OVERWRITE );
			else
				$dataset = $this->callback_result;
		}

lucha's avatar
lucha committed
406
		if ( ! isset($dataset) )
root's avatar
root committed
407 408
			$dataset = 'global';

lucha's avatar
lucha committed
409 410
		if ( ! $dataset )
			return $this->log_and_bail("Unable to determine dataset (for table: $this->table)");
root's avatar
root committed
411 412 413
		else
			$this->dataset = $dataset;

lucha's avatar
lucha committed
414 415
		$this->run_callbacks( 'dataset_found', $dataset );

416 417 418 419 420
        if (WP_DEBUG === true) {
            $_ai_msg = sprintf("We choose dataset %s for query '%s'", $this->dataset, $query);
            $this->print_error($_ai_msg);
        }

lucha's avatar
lucha committed
421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443
		if ( empty( $this->hyper_servers ) ) {
			if ( $this->is_mysql_connection( $this->dbh ) )
				return $this->dbh;
			if (
				!defined('DB_HOST')
				|| !defined('DB_USER')
				|| !defined('DB_PASSWORD')
				|| !defined('DB_NAME') )
				return $this->log_and_bail("We were unable to query because there was no database defined");
			$this->dbh = $this->ex_mysql_connect( DB_HOST, DB_USER, DB_PASSWORD, $this->persistent );
			if ( ! $this->is_mysql_connection( $this->dbh ) )
				return $this->log_and_bail("We were unable to connect to the database. (DB_HOST)");
			if ( ! $this->ex_mysql_select_db( DB_NAME, $this->dbh ) )
				return $this->log_and_bail("We were unable to select the database");
			if ( ! empty( $this->charset ) ) {
				$collation_query = "SET NAMES '$this->charset'";
				if ( !empty( $this->collate ) )
					$collation_query .= " COLLATE '$this->collate'";
				$this->ex_mysql_query( $collation_query, $this->dbh );
			}
			return $this->dbh;
		}

root's avatar
root committed
444
		// Determine whether the query must be sent to the master (a writable server)
joe's avatar
joe committed
445
		if ( !empty( $use_master ) || $this->srtm === true || isset($this->srtm[$this->table]) ) {
root's avatar
root committed
446 447 448 449 450 451 452
			$use_master = true;
		} elseif ( $is_write = $this->is_write_query($query) ) {
			$use_master = true;
			if ( is_array($this->srtm) )
				$this->srtm[$this->table] = true;
		} elseif ( !isset($use_master) && is_array($this->srtm) && !empty($this->srtm) ) {
			// Detect queries that have a join in the srtm array.
joe's avatar
joe committed
453 454 455 456 457 458 459 460
			$use_master = false;
			$query_match = substr( $query, 0, 1000 );
			foreach ( $this->srtm as $key => $value ) {
				if ( false !== stripos( $query_match, $key ) ) {
					$use_master = true;
					break;
				}
			}
root's avatar
root committed
461 462 463 464 465 466 467 468 469 470 471 472 473
		} else {
			$use_master = false;
		}

		if ( $use_master ) {
			$this->dbhname = $dbhname = $dataset . '__w';
			$operation = 'write';
		} else {
			$this->dbhname = $dbhname = $dataset . '__r';
			$operation = 'read';
		}

		// Try to reuse an existing connection
lucha's avatar
lucha committed
474
		while ( isset( $this->dbhs[$dbhname] ) && $this->is_mysql_connection( $this->dbhs[$dbhname] ) ) {
root's avatar
root committed
475 476 477 478 479 480 481 482 483
			// Find the connection for incrementing counters
			foreach ( array_keys($this->db_connections) as $i )
				if ( $this->db_connections[$i]['dbhname'] == $dbhname )
					$conn =& $this->db_connections[$i];

			if ( isset($server['name']) ) {
				$name = $server['name'];
				// A callback has specified a database name so it's possible the existing connection selected a different one.
				if ( $name != $this->used_servers[$dbhname]['name'] ) {
lucha's avatar
lucha committed
484
					if ( ! $this->ex_mysql_select_db( $name, $this->dbhs[$dbhname] ) ) {
root's avatar
root committed
485
						// this can happen when the user varies and lacks permission on the $name database
joe's avatar
joe committed
486 487 488 489 490
						if ( isset( $conn['disconnect (select failed)'] ) )
							++$conn['disconnect (select failed)'];
						else
							$conn['disconnect (select failed)'] = 1;

root's avatar
root committed
491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510
						$this->disconnect($dbhname);
						break;
					}
					$this->used_servers[$dbhname]['name'] = $name;
				}
			} else {
				$name = $this->used_servers[$dbhname]['name'];
			}

			$this->current_host = $this->dbh2host[$dbhname];

			// Keep this connection at the top of the stack to prevent disconnecting frequently-used connections
			if ( $k = array_search($dbhname, $this->open_connections) ) {
				unset($this->open_connections[$k]);
				$this->open_connections[] = $dbhname;
			}

			$this->last_used_server = $this->used_servers[$dbhname];
			$this->last_connection = compact('dbhname', 'name');

lucha's avatar
lucha committed
511
			if ( $this->should_mysql_ping() && ! $this->ex_mysql_ping( $this->dbhs[$dbhname] ) ) {
joe's avatar
joe committed
512 513 514 515 516
				if ( isset( $conn['disconnect (ping failed)'] ) )
					++$conn['disconnect (ping failed)'];
				else
					$conn['disconnect (ping failed)'] = 1;

root's avatar
root committed
517 518 519 520
				$this->disconnect($dbhname);
				break;
			}

lucha's avatar
lucha committed
521
			if ( isset( $conn['queries'] ) )
joe's avatar
joe committed
522 523 524
				++$conn['queries'];
			else
				$conn['queries'] = 1;
root's avatar
root committed
525 526 527 528

			return $this->dbhs[$dbhname];
		}

joe's avatar
joe committed
529
		if ( $use_master && defined( "MASTER_DB_DEAD" ) ) {
root's avatar
root committed
530 531 532 533
			return $this->bail("We're updating the database, please try back in 5 minutes. If you are posting to your blog please hit the refresh button on your browser in a few minutes to post the data again. It will be posted as soon as the database is back online again.");
		}

		if ( empty($this->hyper_servers[$dataset][$operation]) )
lucha's avatar
lucha committed
534
			return $this->log_and_bail("No databases available with $this->table ($dataset)");
root's avatar
root committed
535 536 537 538 539 540 541 542 543 544

		// Put the groups in order by priority
		ksort($this->hyper_servers[$dataset][$operation]);

		// Make a list of at least $this->min_tries connections to try, repeating as necessary.
		$servers = array();
		do {
			foreach ( $this->hyper_servers[$dataset][$operation] as $group => $items ) {
				$keys = array_keys($items);
				shuffle($keys);
lucha's avatar
lucha committed
545
				foreach ( $keys as $key )
root's avatar
root committed
546 547
					$servers[] = compact('group', 'key');
			}
shammash's avatar
shammash committed
548

lucha's avatar
lucha committed
549 550 551
			if ( !$tries_remaining = count( $servers ) )
				return $this->log_and_bail("No database servers were found to match the query ($this->table, $dataset)");

shammash's avatar
shammash committed
552 553 554
			if ( !isset( $unique_servers ) )
				$unique_servers = $tries_remaining;

root's avatar
root committed
555 556 557
		} while ( $tries_remaining < $this->min_tries );

		// Connect to a database server
shammash's avatar
shammash committed
558 559 560
		do {
			$unique_lagged_slaves = array();
			$success = false;
root's avatar
root committed
561

shammash's avatar
shammash committed
562
			foreach ( $servers as $group_key ) {
lucha's avatar
lucha committed
563 564
				--$tries_remaining;

shammash's avatar
shammash committed
565 566 567
				// If all servers are lagged, we need to start ignoring the lag and retry
				if ( count( $unique_lagged_slaves ) == $unique_servers )
					break;
root's avatar
root committed
568

shammash's avatar
shammash committed
569 570
				// $group, $key
				extract($group_key, EXTR_OVERWRITE);
root's avatar
root committed
571

lucha's avatar
lucha committed
572
				// $host, $user, $password, $name, $read, $write [, $lag_threshold, $timeout ]
shammash's avatar
shammash committed
573
				extract($this->hyper_servers[$dataset][$operation][$group][$key], EXTR_OVERWRITE);
joe's avatar
joe committed
574
				$port = null;
root's avatar
root committed
575

shammash's avatar
shammash committed
576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609
				// Split host:port into $host and $port
				if ( strpos($host, ':') )
					list($host, $port) = explode(':', $host);

				// Overlay $server if it was extracted from a callback
				if ( isset($server) && is_array($server) )
					extract($server, EXTR_OVERWRITE);

				// Split again in case $server had host:port
				if ( strpos($host, ':') )
					list($host, $port) = explode(':', $host);

				// Make sure there's always a port number
				if ( empty($port) )
					$port = 3306;

				// Use a default timeout of 200ms
				if ( !isset($timeout) )
					$timeout = 0.2;

				// Get the minimum group here, in case $server rewrites it
				if ( !isset( $min_group ) || $min_group > $group )
					$min_group = $group;

				// Can be used by the lag callbacks
				$this->lag_cache_key = "$host:$port";
				$this->lag_threshold = isset($lag_threshold) ? $lag_threshold : $this->default_lag_threshold;

				// Check for a lagged slave, if applicable
				if ( !$use_master && !$write && !isset( $ignore_slave_lag )
					&& isset($this->lag_threshold) && !isset( $server['host'] )
					&& ( $lagged_status = $this->get_lag_cache() ) === HYPERDB_LAG_BEHIND
				) {
					// If it is the last lagged slave and it is with the best preference we will ignore its lag
joe's avatar
joe committed
610
					if ( !isset( $unique_lagged_slaves["$host:$port"] )
shammash's avatar
shammash committed
611 612 613 614 615
						&& $unique_servers == count( $unique_lagged_slaves ) + 1
						&& $group == $min_group )
					{
						$this->lag_threshold = null;
					} else {
joe's avatar
joe committed
616
						$unique_lagged_slaves["$host:$port"] = $this->lag;
shammash's avatar
shammash committed
617 618 619
						continue;
					}
				}
root's avatar
root committed
620

shammash's avatar
shammash committed
621
				$this->timer_start();
root's avatar
root committed
622

shammash's avatar
shammash committed
623
				// Connect if necessary or possible
lucha's avatar
lucha committed
624 625 626
				$server_state = null;
				if ( $use_master || ! $tries_remaining ||
					'up' == $server_state = $this->get_server_state( $host, $port, $timeout ) )
shammash's avatar
shammash committed
627
				{
lucha's avatar
lucha committed
628 629 630
					$this->set_connect_timeout( 'pre_connect', $use_master, $tries_remaining );
					$this->dbhs[$dbhname] = $this->ex_mysql_connect( "$host:$port", $user, $password, $this->persistent );
					$this->set_connect_timeout( 'post_connect', $use_master, $tries_remaining );
shammash's avatar
shammash committed
631 632 633
				} else {
					$this->dbhs[$dbhname] = false;
				}
root's avatar
root committed
634

shammash's avatar
shammash committed
635 636
				$elapsed = $this->timer_stop();

lucha's avatar
lucha committed
637
				if ( $this->is_mysql_connection( $this->dbhs[$dbhname] ) ) {
shammash's avatar
shammash committed
638 639 640 641 642 643 644 645 646
					/**
					 * If we care about lag, disconnect lagged slaves and try to find others.
					 * We don't disconnect if it is the last lagged slave and it is with the best preference.
					 */
					if ( !$use_master && !$write && !isset( $ignore_slave_lag )
						&& isset($this->lag_threshold) && !isset( $server['host'] )
						&& $lagged_status !== HYPERDB_LAG_OK
						&& ( $lagged_status = $this->get_lag() ) === HYPERDB_LAG_BEHIND
						&& !(
joe's avatar
joe committed
647
							!isset( $unique_lagged_slaves["$host:$port"] )
shammash's avatar
shammash committed
648 649 650 651 652 653 654 655 656 657 658
							&& $unique_servers == count( $unique_lagged_slaves ) + 1
							&& $group == $min_group
						)
					) {
						$success = false;
						$unique_lagged_slaves["$host:$port"] = $this->lag;
						$this->disconnect( $dbhname );
						$this->dbhs[$dbhname] = false;
						$msg = "Replication lag of {$this->lag}s on $host:$port ($dbhname)";
						$this->print_error( $msg );
						continue;
lucha's avatar
lucha committed
659
					} elseif ( $this->ex_mysql_select_db( $name, $this->dbhs[$dbhname] ) ) {
shammash's avatar
shammash committed
660 661 662 663 664
						$success = true;
						$this->current_host = "$host:$port";
						$this->dbh2host[$dbhname] = "$host:$port";
						$queries = 1;
						$lag = isset( $this->lag ) ? $this->lag : 0;
joe's avatar
joe committed
665
						$this->last_connection = compact('dbhname', 'host', 'port', 'user', 'name', 'tcp', 'elapsed', 'success', 'queries', 'lag');
shammash's avatar
shammash committed
666 667 668 669 670
						$this->db_connections[] = $this->last_connection;
						$this->open_connections[] = $dbhname;
						break;
					}
				}
root's avatar
root committed
671

lucha's avatar
lucha committed
672 673 674 675 676 677 678 679 680 681
				if ( 'down' == $server_state )
					continue; // don't flood the logs if already down

				if ( HYPERDB_CONN_HOST_ERROR == $this->ex_mysql_errno() &&
					( 'up' == $server_state || ! $tries_remaining ) )
				{
					$this->mark_server_as_down( $host, $port );
					$server_state = 'down';
				}

root's avatar
root committed
682 683 684
				$success = false;
				$this->last_connection = compact('dbhname', 'host', 'port', 'user', 'name', 'tcp', 'elapsed', 'success');
				$this->db_connections[] = $this->last_connection;
joe's avatar
joe committed
685 686 687 688 689 690 691 692 693 694 695 696 697
                /* Workaround to stop logging a/i */
                if ( AI_LOG_HYPERDB == true ) {
                    $msg = date( "Y-m-d H:i:s" ) . " Can't select $dbhname - \n";
                    $msg .= "'referrer' => '{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}',\n";
                    $msg .= "'server' => {$server},\n";
                    $msg .= "'host' => {$host},\n";
                    $msg .= "'error' => " . $this->ex_mysql_error() . ",\n";
                    $msg .= "'errno' => " . $this->ex_mysql_errno() . ",\n";
                    $msg .= "'server_state' => $server_state\n";
                    $msg .= "'lagged_status' => " . ( isset( $lagged_status ) ? $lagged_status : HYPERDB_LAG_UNKNOWN );

                    $this->print_error( $msg );
                }
shammash's avatar
shammash committed
698 699
			}

lucha's avatar
lucha committed
700 701
			if ( ! $success || ! isset( $this->dbhs[$dbhname] ) || ! $this->is_mysql_connection( $this->dbhs[$dbhname] ) ) {
				if ( !isset( $ignore_slave_lag ) && count( $unique_lagged_slaves ) ) {
shammash's avatar
shammash committed
702 703 704 705 706
					// Lagged slaves were not used. Ignore the lag for this connection attempt and retry.
					$ignore_slave_lag = true;
					$tries_remaining = count( $servers );
					continue;
				}
joe's avatar
joe committed
707

shammash's avatar
shammash committed
708
				$error_details = array(
root's avatar
root committed
709
					'host' => $host,
shammash's avatar
shammash committed
710 711 712 713 714
					'port' => $port,
					'operation' => $operation,
					'table' => $this->table,
					'dataset' => $dataset,
					'dbhname' => $dbhname
root's avatar
root committed
715
				);
shammash's avatar
shammash committed
716
				$this->run_callbacks( 'db_connection_error', $error_details );
root's avatar
root committed
717

shammash's avatar
shammash committed
718
				return $this->bail( "Unable to connect to $host:$port to $operation table '$this->table' ($dataset)" );
root's avatar
root committed
719 720
			}

shammash's avatar
shammash committed
721 722 723
			break;
		} while ( true );

lucha's avatar
lucha committed
724
		if ( !isset( $charset ) )
joe's avatar
joe committed
725 726 727 728 729
			$charset = null;

		if ( !isset( $collate ) )
			$collate = null;

shammash's avatar
shammash committed
730
		$this->set_charset($this->dbhs[$dbhname], $charset, $collate);
joe's avatar
joe committed
731 732

		if ( !isset( $charset ) )
Joe Oblivian's avatar
Joe Oblivian committed
733 734 735 736 737 738 739
			$charset = null;

		if ( !isset( $collate ) )
			$collate = null;

        // AI workaround: set all queries to latin1
		$this->set_charset($this->dbhs[$dbhname], 'latin1');
root's avatar
root committed
740

shammash's avatar
shammash committed
741
		$this->dbh = $this->dbhs[$dbhname]; // needed by $wpdb->_real_escape()
root's avatar
root committed
742 743 744 745 746 747 748 749 750 751 752 753 754 755

		$this->last_used_server = compact('host', 'user', 'name', 'read', 'write');

		$this->used_servers[$dbhname] = $this->last_used_server;

		while ( !$this->persistent && count($this->open_connections) > $this->max_connections ) {
			$oldest_connection = array_shift($this->open_connections);
			if ( $this->dbhs[$oldest_connection] != $this->dbhs[$dbhname] )
				$this->disconnect($oldest_connection);
		}

		return $this->dbhs[$dbhname];
	}

shammash's avatar
shammash committed
756 757
	/**
	 * Sets the connection's character set.
lucha's avatar
lucha committed
758
	 * @param resource $dbh     The resource given by ex_mysql_connect
shammash's avatar
shammash committed
759 760 761 762 763 764 765 766
	 * @param string   $charset The character set (optional)
	 * @param string   $collate The collation (optional)
	 */
	function set_charset($dbh, $charset = null, $collate = null) {
		if ( !isset($charset) )
			$charset = $this->charset;
		if ( !isset($collate) )
			$collate = $this->collate;
lucha's avatar
lucha committed
767 768 769 770 771 772 773 774 775 776 777 778 779 780 781

		if ( ! $this->has_cap( 'collation', $dbh ) || empty( $charset ) )
			return;

		if ( ! in_array( strtolower( $charset ), array( 'utf8', 'utf8mb4', 'latin1' ) ) )
			wp_die( "$charset charset isn't supported in HyperDB for security reasons" );

		if ( $this->is_mysql_set_charset_callable() && $this->has_cap( 'set_charset', $dbh ) ) {
			$this->ex_mysql_set_charset( $charset, $dbh );
			$this->real_escape = true;
		} else {
			$query = $this->prepare( 'SET NAMES %s', $charset );
			if ( ! empty( $collate ) )
				$query .= $this->prepare( ' COLLATE %s', $collate );
			$this->ex_mysql_query( $query, $dbh );
shammash's avatar
shammash committed
782 783 784
		}
	}

lucha's avatar
lucha committed
785 786 787 788 789 790 791 792 793 794 795 796 797 798
	/*
 	 * Force addslashes() for the escapes.
 	 *
 	 * HyperDB makes connections when a query is made
 	 * which is why we can't use mysql_real_escape_string() for escapes.
 	 * This is also the reason why we don't allow certain charsets. See set_charset().
 	 */
	function _real_escape( $string ) {
		$escaped = addslashes( $string );
		if ( method_exists( get_parent_class( $this ), 'add_placeholder_escape' ) ) {
			$escaped = $this->add_placeholder_escape( $escaped );
		}
		return $escaped;
	}
root's avatar
root committed
799 800 801 802 803
	/**
	 * Disconnect and remove connection from open connections list
	 * @param string $tdbhname
	 */
	function disconnect($dbhname) {
lucha's avatar
lucha committed
804
		if ( false !== $k = array_search($dbhname, $this->open_connections) )
root's avatar
root committed
805 806
			unset($this->open_connections[$k]);

lucha's avatar
lucha committed
807 808 809 810 811 812
		foreach ( array_keys( $this->db_connections ) as $i )
			if ( $this->db_connections[$i]['dbhname'] == $dbhname )
				unset( $this->db_connections[$i] );

		if ( $this->is_mysql_connection( $this->dbhs[$dbhname] ) )
			$this->ex_mysql_close( $this->dbhs[$dbhname] );
root's avatar
root committed
813 814 815 816 817 818 819 820 821

		unset($this->dbhs[$dbhname]);
	}

	/**
	 * Kill cached query results
	 */
	function flush() {
		$this->last_error = '';
lucha's avatar
lucha committed
822
		$this->last_errno = 0;
root's avatar
root committed
823 824 825 826 827 828 829 830 831
		$this->num_rows = 0;
		parent::flush();
	}

	/**
	 * Basic query. See docs for more details.
	 * @param string $query
	 * @return int number of rows
	 */
lucha's avatar
lucha committed
832
	function query( $query ) {
root's avatar
root committed
833 834 835 836 837 838 839 840 841 842 843 844 845 846
		// some queries are made before the plugins have been loaded, and thus cannot be filtered with this method
		if ( function_exists('apply_filters') )
			$query = apply_filters('query', $query);

		// initialise return
		$return_val = 0;
		$this->flush();

		// Log how the function was called
		$this->func_call = "\$db->query(\"$query\")";

		// Keep track of the last query for debug..
		$this->last_query = $query;

lucha's avatar
lucha committed
847 848 849 850 851 852 853 854
		if ( preg_match( '/^\s*SELECT\s+FOUND_ROWS(\s*)/i', $query ) ) {
			if ( $this->is_mysql_result( $this->last_found_rows_result ) ) {
				$this->result = $this->last_found_rows_result;
				$elapsed = 0;
			} else {
				$this->print_error( "Attempted SELECT FOUND_ROWS() without prior SQL_CALC_FOUND_ROWS." );
				return false;
			}
root's avatar
root committed
855 856 857
		} else {
			$this->dbh = $this->db_connect( $query );

lucha's avatar
lucha committed
858 859 860 861 862
			if ( ! $this->is_mysql_connection( $this->dbh ) ) {
				$this->check_current_query = true;
				$this->last_error = 'Database connection failed';
				$this->num_failed_queries++;
				do_action( 'sql_query_log', $query, false, $this->last_error );
root's avatar
root committed
863
				return false;
lucha's avatar
lucha committed
864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887
			}

			$query_comment = $this->run_callbacks( 'get_query_comment', $query );
			if ( ! empty( $query_comment ) )
				$query = rtrim( $query, ";\t \n\r" ) . ' /* ' . $query_comment . ' */';

			// If we're writing to the database, make sure the query will write safely.
			if ( $this->check_current_query && method_exists( $this, 'check_ascii' ) && ! $this->check_ascii( $query ) ) {
				$stripped_query = $this->strip_invalid_text_from_query( $query );
				if ( $stripped_query !== $query ) {
					$this->insert_id = 0;
					$this->last_error = 'Invalid query';
					$this->num_failed_queries++;
					do_action( 'sql_query_log', $query, false, $this->last_error );
					return false;
				}
			}

			$this->check_current_query = true;

			// Inject setup and teardown statements
			$statement_before_query = $this->run_callbacks( 'statement_before_query' );
			$statement_after_query = $this->run_callbacks( 'statement_after_query' );
			$query_for_log = $query;
root's avatar
root committed
888

889 890 891 892
            // A/I: prevent mysql-proxy to cache the admin section
            if (strpos($_SERVER['REQUEST_URI'], '/wp-admin/') !== false) {
                $query .= ' /* NO CACHE */';
            }
joe's avatar
joe committed
893

root's avatar
root committed
894
			$this->timer_start();
lucha's avatar
lucha committed
895 896 897 898 899 900 901 902 903 904 905
			if ( $statement_before_query ) {
				$query_for_log = "$statement_before_query; $query_for_log";
				$this->ex_mysql_query( $statement_before_query, $this->dbh );
			}

			$this->result = $this->ex_mysql_query( $query, $this->dbh );

			if ( $statement_after_query ) {
				$query_for_log = "$query_for_log; $statement_after_query";
				$this->ex_mysql_query( $statement_after_query, $this->dbh );
			}
root's avatar
root committed
906 907 908 909 910 911
			$elapsed = $this->timer_stop();
			++$this->num_queries;

			if ( preg_match('/^\s*SELECT\s+SQL_CALC_FOUND_ROWS\s/i', $query) ) {
				if ( false === strpos($query, "NO_SELECT_FOUND_ROWS") ) {
					$this->timer_start();
lucha's avatar
lucha committed
912
					$this->last_found_rows_result = $this->ex_mysql_query( "SELECT FOUND_ROWS()", $this->dbh );
root's avatar
root committed
913 914 915 916 917 918 919 920
					$elapsed += $this->timer_stop();
					++$this->num_queries;
					$query .= "; SELECT FOUND_ROWS()";
				}
			} else {
				$this->last_found_rows_result = null;
			}

lucha's avatar
lucha committed
921 922
			$this->dbhname_heartbeats[$this->dbhname]['last_used'] = microtime( true );

root's avatar
root committed
923
			if ( $this->save_queries ) {
lucha's avatar
lucha committed
924 925 926 927 928 929 930 931
				if ( is_callable($this->save_query_callback) ) {
					$saved_query = call_user_func_array( $this->save_query_callback, array( $query_for_log, $elapsed, $this->save_backtrace ? debug_backtrace( DEBUG_BACKTRACE_IGNORE_ARGS ) : null, &$this ) );
					if ( $saved_query !== null ) {
						$this->queries[] = $saved_query;
					}
				} else {
					$this->queries[] = array( $query_for_log, $elapsed, $this->get_caller() );
				}
root's avatar
root committed
932 933 934 935
			}
		}

		// If there is an error then take note of it
lucha's avatar
lucha committed
936 937 938
		if ( $this->last_error = $this->ex_mysql_error( $this->dbh ) ) {
			$this->last_errno = $this->ex_mysql_errno( $this->dbh );
			$this->dbhname_heartbeats[$this->dbhname]['last_errno'] = $this->last_errno;
root's avatar
root committed
939
			$this->print_error($this->last_error);
lucha's avatar
lucha committed
940 941
			$this->num_failed_queries++;
			do_action( 'sql_query_log', $query, false, $this->last_error );
root's avatar
root committed
942 943 944
			return false;
		}

lucha's avatar
lucha committed
945 946
		if ( preg_match('/^\s*(insert|delete|update|replace|alter)\s/i',$query) ) {
			$this->rows_affected = $this->ex_mysql_affected_rows( $this->dbh );
root's avatar
root committed
947 948

			// Take note of the insert_id
lucha's avatar
lucha committed
949 950
			if ( preg_match('/^\s*(insert|replace)\s/i',$query) ) {
				$this->insert_id = $this->ex_mysql_insert_id( $this->dbh );
root's avatar
root committed
951 952 953
			}
			// Return number of rows affected
			$return_val = $this->rows_affected;
lucha's avatar
lucha committed
954 955 956
		} else if ( is_bool( $this->result ) ) {
			$return_val = $this->result;
			$this->result = null;
root's avatar
root committed
957 958 959
		} else {
			$i = 0;
			$this->col_info = array();
lucha's avatar
lucha committed
960 961
			while ( $i < $this->ex_mysql_num_fields( $this->result ) ) {
				$this->col_info[$i] = $this->ex_mysql_fetch_field( $this->result );
root's avatar
root committed
962 963 964 965
				$i++;
			}
			$num_rows = 0;
			$this->last_result = array();
lucha's avatar
lucha committed
966
			while ( $row = $this->ex_mysql_fetch_object( $this->result ) ) {
root's avatar
root committed
967 968 969 970
				$this->last_result[$num_rows] = $row;
				$num_rows++;
			}

lucha's avatar
lucha committed
971 972
			$this->ex_mysql_free_result( $this->result );
			$this->result = null;
root's avatar
root committed
973 974 975 976 977 978 979 980

			// Log number of rows the query returned
			$this->num_rows = $num_rows;

			// Return number of rows selected
			$return_val = $this->num_rows;
		}

lucha's avatar
lucha committed
981
		do_action( 'sql_query_log', $query, $return_val, $this->last_error );
root's avatar
root committed
982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026
		return $return_val;
	}

	/**
	 * Whether or not MySQL database is at least the required minimum version.
	 * The additional argument allows the caller to check a specific database.
	 *
	 * @since 2.5.0
	 * @uses $wp_version
	 *
	 * @return WP_Error
	 */
	function check_database_version( $dbh_or_table = false ) {
		global $wp_version;
		// Make sure the server has MySQL 4.1.2
		$mysql_version = preg_replace( '|[^0-9\.]|', '', $this->db_version( $dbh_or_table ) );
		if ( version_compare($mysql_version, '4.1.2', '<') )
			return new WP_Error( 'database_version', sprintf(__('<strong>ERROR</strong>: WordPress %s requires MySQL 4.1.2 or higher'), $wp_version) );
	}

	/**
	 * This function is called when WordPress is generating the table schema to determine wether or not the current database
	 * supports or needs the collation statements.
	 * The additional argument allows the caller to check a specific database.
	 * @return bool
	 */
	function supports_collation( $dbh_or_table = false ) {
		return $this->has_cap( 'collation', $dbh_or_table );
	}

	/**
	 * Generic function to determine if a database supports a particular feature
	 * The additional argument allows the caller to check a specific database.
	 * @param string $db_cap the feature
	 * @param false|string|resource $dbh_or_table the databaese (the current database, the database housing the specified table, or the database of the mysql resource)
	 * @return bool
	 */
	function has_cap( $db_cap, $dbh_or_table = false ) {
		$version = $this->db_version( $dbh_or_table );

		switch ( strtolower( $db_cap ) ) :
		case 'collation' :
		case 'group_concat' :
		case 'subqueries' :
			return version_compare($version, '4.1', '>=');
shammash's avatar
shammash committed
1027 1028
		case 'set_charset' :
			return version_compare($version, '5.0.7', '>=');
root's avatar
root committed
1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041
		endswitch;

		return false;
	}

	/**
	 * The database version number
	 * @param false|string|resource $dbh_or_table the databaese (the current database, the database housing the specified table, or the database of the mysql resource)
	 * @return false|string false on failure, version number on success
	 */
	function db_version( $dbh_or_table = false ) {
		if ( !$dbh_or_table && $this->dbh )
			$dbh =& $this->dbh;
lucha's avatar
lucha committed
1042
		elseif ( $this->is_mysql_connection( $dbh_or_table ) )
root's avatar
root committed
1043 1044 1045 1046 1047
			$dbh =& $dbh_or_table;
		else
			$dbh = $this->db_connect( "SELECT FROM $dbh_or_table $this->users" );

		if ( $dbh )
lucha's avatar
lucha committed
1048
			return preg_replace( '/[^0-9.].*/', '', $this->ex_mysql_get_server_info( $dbh ) );
root's avatar
root committed
1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060
		return false;
	}

	/**
	 * Get the name of the function that called wpdb.
	 * @return string the name of the calling function
	 */
	function get_caller() {
		// requires PHP 4.3+
		if ( !is_callable('debug_backtrace') )
			return '';

lucha's avatar
lucha committed
1061 1062 1063 1064
		$hyper_callbacks = array();
		foreach ( $this->hyper_callbacks as $group_name => $group_callbacks )
			$hyper_callbacks = array_merge( $hyper_callbacks, $group_callbacks );

shammash's avatar
shammash committed
1065
		$bt = debug_backtrace( false );
root's avatar
root committed
1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079
		$caller = '';

		foreach ( (array) $bt as $trace ) {
			if ( isset($trace['class']) && is_a( $this, $trace['class'] ) )
				continue;
			elseif ( !isset($trace['function']) )
				continue;
			elseif ( strtolower($trace['function']) == 'call_user_func_array' )
				continue;
			elseif ( strtolower($trace['function']) == 'apply_filters' )
				continue;
			elseif ( strtolower($trace['function']) == 'do_action' )
				continue;

lucha's avatar
lucha committed
1080 1081 1082
			if ( in_array( strtolower($trace['function']), $hyper_callbacks ) )
				continue;

root's avatar
root committed
1083 1084 1085 1086 1087 1088 1089 1090 1091
			if ( isset($trace['class']) )
				$caller = $trace['class'] . '::' . $trace['function'];
			else
				$caller = $trace['function'];
			break;
		}
		return $caller;
	}

lucha's avatar
lucha committed
1092 1093 1094 1095 1096 1097 1098 1099 1100
	function log_and_bail( $msg ) {
		$logged = $this->run_callbacks( 'log_and_bail', $msg );

		if ( ! $logged )
			error_log( "WordPress database error $msg for query {$this->last_query} made by " .  $this->get_caller() );

		return $this->bail( $msg );
	}

root's avatar
root committed
1101 1102
	/**
	 * Check the responsiveness of a tcp/ip daemon
lucha's avatar
lucha committed
1103 1104
	 * @return (string) 'up' when $host:$post responds within $float_timeout seconds,
	 * otherwise a string with details about the failure.
root's avatar
root committed
1105
	 */
joe's avatar
joe committed
1106
	function check_tcp_responsiveness( $host, $port, $float_timeout ) {
lucha's avatar
lucha committed
1107
		if ( function_exists( 'apcu_store' ) ) {
joe's avatar
joe committed
1108
			$use_apc = true;
lucha's avatar
lucha committed
1109 1110
			$apcu_key = "tcp_responsive_{$host}{$port}";
			$apcu_ttl = 10;
joe's avatar
joe committed
1111 1112 1113 1114 1115
		} else {
			$use_apc = false;
		}

		if ( $use_apc ) {
lucha's avatar
lucha committed
1116 1117 1118
			$server_state = apcu_fetch( $apcu_key );
			if ( $server_state )
				return $server_state;
joe's avatar
joe committed
1119 1120 1121 1122
		}

		$socket = @ fsockopen( $host, $port, $errno, $errstr, $float_timeout );
		if ( $socket === false ) {
lucha's avatar
lucha committed
1123
			$server_state = "down [ > $float_timeout ] ($errno) '$errstr'";
joe's avatar
joe committed
1124
			if ( $use_apc )
lucha's avatar
lucha committed
1125 1126 1127
				apcu_store( $apcu_key, $server_state, $apcu_ttl );

			return $server_state;
joe's avatar
joe committed
1128 1129 1130 1131 1132
		}

		fclose( $socket );

		if ( $use_apc )
lucha's avatar
lucha committed
1133
			apcu_store( $apcu_key, 'up', $apcu_ttl );
joe's avatar
joe committed
1134

lucha's avatar
lucha committed
1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180
		return 'up';
	}

	function get_server_state( $host, $port, $timeout ) {
		// We still do the check_tcp_responsiveness() until we have
		// mysql connect function with less than 1 second timeout
		if ( $this->check_tcp_responsiveness ) {
			$server_state = $this->check_tcp_responsiveness( $host, $port, $timeout );
			if ( 'up' !== $server_state )
				return $server_state;
		}

		if ( ! function_exists( 'apcu_store' ) )
			return 'up';

		$server_state = apcu_fetch( "server_state_$host$port" );
		if ( ! $server_state )
			return 'up';

		return $server_state;
	}

	function mark_server_as_down( $host, $port, $apcu_ttl = 10 ) {
		if ( ! function_exists( 'apcu_store' ) )
			return;

		apcu_add( "server_state_$host$port", 'down', $apcu_ttl );
	}

	function set_connect_timeout( $tag, $use_master, $tries_remaining ) {
		static $default_connect_timeout;

		if ( ! isset ( $default_connect_timeout ) )
			$default_connect_timeout = $this->ex_mysql_connect_timeout();

		switch ( $tag ) {
			case 'pre_connect':
				if ( ! $use_master && $tries_remaining )
					$this->ex_mysql_connect_timeout( 1 );
				break;
			case 'post_connect':
			default:
				if ( ! $use_master && $tries_remaining )
					$this->ex_mysql_connect_timeout( $default_connect_timeout );
				break;
		}
shammash's avatar
shammash committed
1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202
	}

	function get_lag_cache() {
		$this->lag = $this->run_callbacks( 'get_lag_cache' );

		return $this->check_lag();
	}

	function get_lag() {
		$this->lag = $this->run_callbacks( 'get_lag' );

		return $this->check_lag();
	}

	function check_lag() {
		if ( $this->lag === false )
			return HYPERDB_LAG_UNKNOWN;

		if ( $this->lag > $this->lag_threshold )
			return HYPERDB_LAG_BEHIND;

		return HYPERDB_LAG_OK;
root's avatar
root committed
1203 1204
	}

lucha's avatar
lucha committed
1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460
	function should_use_mysqli() {
		if ( ! function_exists( 'mysqli_connect' ) )
			return false;

		if ( defined( 'WP_USE_EXT_MYSQL' ) && WP_USE_EXT_MYSQL )
			return false;

		return true;
	}

	function should_mysql_ping() {
		// Shouldn't happen
		if ( ! isset( $this->dbhname_heartbeats[$this->dbhname] ) )
			return true;

		// MySQL server has gone away
		if ( isset( $this->dbhname_heartbeats[$this->dbhname]['last_errno'] ) &&
			HYPERDB_SERVER_GONE_ERROR == $this->dbhname_heartbeats[$this->dbhname]['last_errno'] )
		{
			unset( $this->dbhname_heartbeats[$this->dbhname]['last_errno'] );
			return true;
		}

		// More than 0.1 seconds of inactivity on that dbhname
		if ( microtime( true ) - $this->dbhname_heartbeats[$this->dbhname]['last_used'] > 0.1 )
			return true;

		return false;
	}

	function is_mysql_connection( $dbh ) {
		if ( ! $this->use_mysqli )
			return is_resource( $dbh );

		return $dbh instanceof mysqli;
	}

	function is_mysql_result( $result ) {
		if ( ! $this->use_mysqli )
			return is_resource( $result );

		return $result instanceof mysqli_result;
	}

	function is_mysql_set_charset_callable() {
		if ( ! $this->use_mysqli )
			return function_exists( 'mysql_set_charset' );

		return function_exists( 'mysqli_set_charset' );
	}

	// MySQL execution functions.
	// They perform the appropriate calls based on whether we use MySQLi.

	function ex_mysql_query( $query, $dbh ) {
		if ( ! $this->use_mysqli )
			return mysql_query( $query, $dbh );

		return mysqli_query( $dbh, $query );
	}

	function ex_mysql_unbuffered_query( $query, $dbh ) {
		if ( ! $this->use_mysqli )
			return mysql_unbuffered_query( $query, $dbh );

		return mysqli_query( $dbh, $query, MYSQLI_USE_RESULT );
	}

	function ex_mysql_connect( $db_host, $db_user, $db_password, $persistent ) {
		if ( ! $this->use_mysqli ) {
			$connect_function = $persistent ? 'mysql_pconnect' : 'mysql_connect';
			return @$connect_function( $db_host, $db_user, $db_password, true );
		}

		$dbh = mysqli_init();

		// mysqli_real_connect doesn't support the host param including a port or socket
		// like mysql_connect does. This duplicates how mysql_connect detects a port and/or socket file.
		$port = null;
		$socket = null;
		$port_or_socket = strstr( $db_host, ':' );
		if ( ! empty( $port_or_socket ) ) {
			$db_host = substr( $db_host, 0, strpos( $db_host, ':' ) );
			$port_or_socket = substr( $port_or_socket, 1 );
			if ( 0 !== strpos( $port_or_socket, '/' ) ) {
				$port = intval( $port_or_socket );
				$maybe_socket = strstr( $port_or_socket, ':' );
				if ( ! empty( $maybe_socket ) ) {
					$socket = substr( $maybe_socket, 1 );
				}
			} else {
				$socket = $port_or_socket;
			}
		}

		if ( $persistent )
			$db_host = "p:{$db_host}";

        $retval = mysqli_real_connect( $dbh, $db_host, $db_user, $db_password, null, $port, $socket );

		if ( ! $retval || $dbh->connect_errno )
			return false;

		return $dbh;
	}

	function ex_mysql_select_db( $db_name, $dbh ) {
		if ( ! $this->use_mysqli )
			return @mysql_select_db( $db_name, $dbh );

		return @mysqli_select_db( $dbh, $db_name );
	}

	function ex_mysql_close( $dbh ) {
		if ( ! $this->use_mysqli )
			return mysql_close( $dbh );

		return mysqli_close( $dbh );
	}

	function ex_mysql_set_charset( $charset, $dbh ) {
		if ( ! $this->use_mysqli )
			return mysql_set_charset( $charset, $dbh );

		return mysqli_set_charset( $dbh, $charset );
	}

	function ex_mysql_errno( $dbh = null ) {
		if ( ! $this->use_mysqli )
			return is_resource( $dbh ) ? mysql_errno( $dbh ) : mysql_errno();

		if ( is_null( $dbh ) )
			return mysqli_connect_errno();

		return mysqli_errno( $dbh );
	}

	function ex_mysql_error( $dbh = null ) {
		if ( ! $this->use_mysqli )
			return is_resource( $dbh ) ? mysql_error( $dbh ) : mysql_error();

		if ( is_null( $dbh ) )
			return mysqli_connect_error();

		if ( ! $this->is_mysql_connection( $dbh ) )
			return false;

		return mysqli_error( $dbh );
	}

	function ex_mysql_ping( $dbh ) {
		if ( ! $this->use_mysqli )
			return @mysql_ping( $dbh );

		return @mysqli_ping( $dbh );
	}

	function ex_mysql_affected_rows( $dbh ) {
		if ( ! $this->use_mysqli )
			return mysql_affected_rows( $dbh );

		return mysqli_affected_rows( $dbh );
	}

	function ex_mysql_insert_id( $dbh ) {
		if ( ! $this->use_mysqli )
			return mysql_insert_id( $dbh );

		return mysqli_insert_id( $dbh );
	}

	function ex_mysql_num_fields( $result ) {
		if ( ! $this->use_mysqli )
			return @mysql_num_fields( $result );

		return @mysqli_num_fields( $result );
	}

	function ex_mysql_fetch_field( $result ) {
		if ( ! $this->use_mysqli )
			return @mysql_fetch_field( $result );

		return @mysqli_fetch_field( $result );
	}

	function ex_mysql_fetch_assoc( $result ) {
		if ( ! $this->use_mysqli )
			return mysql_fetch_assoc( $result );

		if ( ! $this->is_mysql_result( $result ) )
			return false;

		$object = mysqli_fetch_assoc( $result );

		return ! is_null( $object ) ? $object : false;
	}

	function ex_mysql_fetch_object( $result ) {
		if ( ! $this->use_mysqli )
			return @mysql_fetch_object( $result );

		if ( ! $this->is_mysql_result( $result ) )
			return false;

		$object = @mysqli_fetch_object( $result );

		return ! is_null( $object ) ? $object : false;
	}

	function ex_mysql_fetch_row( $result ) {
		if ( ! $this->use_mysqli )
			return mysql_fetch_row( $result );

		if ( ! $this->is_mysql_result( $result ) )
			return false;

		$row = mysqli_fetch_row( $result );

		return ! is_null( $row ) ? $row : false;

	}

	function ex_mysql_num_rows( $result ) {
		if ( ! $this->use_mysqli )
			return mysql_num_rows( $result );

		return mysqli_num_rows( $result );
	}

	function ex_mysql_free_result( $result ) {
		if ( ! $this->use_mysqli )
			return @mysql_free_result( $result );

		return @mysqli_free_result( $result );
	}

	function ex_mysql_get_server_info( $dbh ) {
		if ( ! $this->use_mysqli )
			return mysql_get_server_info( $dbh );

		return mysqli_get_server_info( $dbh );
	}

	function ex_mysql_connect_timeout( $timeout = null ) {
		if ( is_null( $timeout ) ) {
			if ( ! $this->use_mysqli )
				return ini_get( 'mysql.connect_timeout' );

			return ini_get( 'default_socket_timeout' );
		}

		if ( ! $this->use_mysqli )
			return ini_set( 'mysql.connect_timeout', $timeout );

		return ini_set( 'default_socket_timeout', $timeout );
	}
root's avatar
root committed
1461
	// Helper functions for configuration
lucha's avatar
lucha committed
1462

root's avatar
root committed
1463 1464
} // class hyperdb

Joe Oblivian's avatar
Joe Oblivian committed
1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476
/**
 * AI custom: Logs all queries for debugging purposes
 */
function ai_log_db_queries($query, $time, $backtrace=null, hyperdb $obj ) {
    $fh = fopen( ABSPATH . '/profiling/noblogs_queries_'. date('Ymd') . '.log', 'a');
    if (!$fh) {
        return array($query, $time, $backtrace);
    }
    fwrite($fh, sprintf("##\n#Date: %s\n#Query time: %s\n%s\n", date('r'), $time, $query));
    fclose($fh);
    return array($query, $time, $backtrace);
}
root's avatar
root committed
1477

Joe Oblivian's avatar
Joe Oblivian committed
1478 1479 1480 1481 1482 1483

$wpdb = new hyperdb();
if ( AI_DB_PROFILER === true ) {
    $wpdb->save_queries = true;
    $wpdb->save_query_callback = 'ai_log_db_queries';
}
root's avatar
root committed
1484
require( DB_CONFIG_FILE );