db.php 29.5 KB
Newer Older
root's avatar
root committed
1 2 3 4 5 6
<?php
// HyperDB
// This file should be installed at ABSPATH/wp-content/db.php

/** Load the wpdb class while preventing instantiation **/
$wpdb = true;
shammash's avatar
shammash committed
7 8 9 10
if ( defined('WPDB_PATH') )
	require_once(WPDB_PATH);
else
	require_once( ABSPATH . WPINC . '/wp-db.php' );
root's avatar
root committed
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28

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' );

} 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
29
/**
joe's avatar
joe committed
30
 * Common definitions
shammash's avatar
shammash committed
31 32 33 34 35
 */
define( 'HYPERDB_LAG_OK', 1 );
define( 'HYPERDB_LAG_BEHIND', 2 );
define( 'HYPERDB_LAG_UNKNOWN', 3 );

root's avatar
root committed
36
class hyperdb extends wpdb {
37

root's avatar
root committed
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 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 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138
	/**
	 * 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;

	/**
	 * Whether to use mysql_pconnect instead of mysql_connect
	 * @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;

	/**
	 * Whether to check with fsockopen prior to mysql_connect.
	 * @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();

joe's avatar
joe committed
139 140 141 142 143 144
	/**
	 * Lookup array (dbhname => host:port)
	 * @var array
	 */
	var $dbh2host = array();

root's avatar
root committed
145 146 147 148 149 150 151 152 153 154 155 156 157
	/**
	 * 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
158 159 160 161 162 163 164 165 166 167 168 169
	/**
	 * 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
170 171 172
	/**
	 * Triggers __construct() for backwards compatibility with PHP4
	 */
shammash's avatar
shammash committed
173
	function hyperdb( $args = null ) {
root's avatar
root committed
174 175 176 177 178 179 180 181 182 183 184 185
		return $this->__construct($args);
	}

	/**
	 * 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
186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205

		$this->init_charset();
	}

	/**
	 * 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
206 207 208 209 210 211 212 213 214 215 216
	}

	/**
	 * 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
217

root's avatar
root committed
218 219 220 221 222 223 224 225 226 227 228 229 230 231
		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
232
	 * Add a callback to a group of callbacks.
joe's avatar
joe committed
233
	 * The default group is 'dataset', used to examine
shammash's avatar
shammash committed
234
	 * queries and determine dataset.
root's avatar
root committed
235
	 */
shammash's avatar
shammash committed
236 237
	function add_callback( $callback, $group = 'dataset' ) {
		$this->hyper_callbacks[ $group ][] = $callback;
root's avatar
root committed
238 239 240 241 242 243 244 245 246 247 248
	}

	/**
	 * Find the first table name referenced in a query
	 * @param string query
	 * @return string table
	 */
	function get_table_from_query ( $q ) {
		// 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
249
		$q = ltrim($q, "\t (");
root's avatar
root committed
250 251 252 253 254 255 256 257 258 259 260 261 262 263 264

		// 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)?'
				. ')\s+`?(\w+)`?/is', $q, $maybe) )
			return $maybe[1];

		// Refer to the previous query
		if ( preg_match('/^\s*SELECT.*?\s+FOUND_ROWS\(\)/is', $q) )
			return $this->last_table;

joe's avatar
joe committed
265 266
		// SHOW TABLE STATUS and SHOW TABLES
		if ( preg_match('/^\s*(?:'
root's avatar
root committed
267
				. 'SHOW\s+TABLE\s+STATUS.+(?:LIKE\s+|WHERE\s+Name\s*=\s*)'
joe's avatar
joe committed
268 269
				. '|SHOW\s+(?:FULL\s+)?TABLES.+(?:LIKE\s+|WHERE\s+Name\s*=\s*)'
				. ')\W(\w+)\W/is', $q, $maybe) )
root's avatar
root committed
270 271
			return $maybe[1];

272 273 274 275 276 277
        // 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
278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307
		// 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)'
				. ')\s+`?(\w+)`?/is', $q, $maybe) )
			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
308 309
		$q = ltrim($q, "\r\n\t (");
		return !preg_match('/^(?:SELECT|SHOW|DESCRIBE|EXPLAIN)\s/i', $q);
root's avatar
root committed
310 311 312 313 314 315 316 317 318 319
	}

	/**
	 * 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
320 321
	 * 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
322
	 */
shammash's avatar
shammash committed
323
	function run_callbacks( $group, $args = null) {
joe's avatar
joe committed
324
		if ( !isset( $this->hyper_callbacks[ $group ] ) || !is_array( $this->hyper_callbacks[ $group ] ) )
shammash's avatar
shammash committed
325 326 327 328 329 330 331 332 333 334 335
			return null;

		if ( !isset($args) ) {
			$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
336 337 338 339 340 341 342 343 344 345 346
			$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
347
	function db_connect( $query = '' ) {
root's avatar
root committed
348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379
		$connect_function = $this->persistent ? 'mysql_pconnect' : 'mysql_connect';
		if ( empty( $this->hyper_servers ) ) {
			if ( is_resource( $this->dbh ) )
				return $this->dbh;
			if (
				!defined('DB_HOST')
				|| !defined('DB_USER')
				|| !defined('DB_PASSWORD')
				|| !defined('DB_NAME') )
				return $this->bail("We were unable to query because there was no database defined.");
			$this->dbh = @ $connect_function(DB_HOST, DB_USER, DB_PASSWORD, true);
			if ( ! is_resource( $this->dbh ) )
				return $this->bail("We were unable to connect to the database. (DB_HOST)");
			if ( ! mysql_select_db(DB_NAME, $this->dbh) )
				return $this->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'";
				mysql_query($collation_query, $this->dbh);
			}
			return $this->dbh;
		}

		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
380
		} elseif ( null !== $this->callback_result = $this->run_callbacks( 'dataset', $query ) ) {
root's avatar
root committed
381 382 383 384 385 386 387 388 389 390 391 392 393 394
			if ( is_array($this->callback_result) )
				extract( $this->callback_result, EXTR_OVERWRITE );
			else
				$dataset = $this->callback_result;
		}

		if ( !isset($dataset) )
			$dataset = 'global';

		if ( !$dataset )
			return $this->bail("Unable to determine which dataset to query. ($this->table)");
		else
			$this->dataset = $dataset;

395 396 397 398
        if (WP_DEBUG === true) {
            $_ai_msg = sprintf("We choose dataset %s for query '%s'", $this->dataset, $query);
            $this->print_error($_ai_msg);
        }
root's avatar
root committed
399
		// Determine whether the query must be sent to the master (a writable server)
joe's avatar
joe committed
400
		if ( !empty( $use_master ) || $this->srtm === true || isset($this->srtm[$this->table]) ) {
root's avatar
root committed
401 402 403 404 405 406 407
			$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
408 409 410 411 412 413 414 415
			$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
416 417 418 419 420 421 422 423 424 425 426 427 428
		} 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
joe's avatar
joe committed
429
		while ( isset( $this->dbhs[$dbhname] ) && is_resource( $this->dbhs[$dbhname] ) ) {
root's avatar
root committed
430 431 432 433 434 435 436 437 438 439 440
			// 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'] ) {
					if ( !mysql_select_db($name, $this->dbhs[$dbhname]) ) {
						// this can happen when the user varies and lacks permission on the $name database
joe's avatar
joe committed
441 442 443 444 445
						if ( isset( $conn['disconnect (select failed)'] ) )
							++$conn['disconnect (select failed)'];
						else
							$conn['disconnect (select failed)'] = 1;

root's avatar
root committed
446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466
						$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');

			if ( !mysql_ping($this->dbhs[$dbhname]) ) {
joe's avatar
joe committed
467 468 469 470 471
				if ( isset( $conn['disconnect (ping failed)'] ) )
					++$conn['disconnect (ping failed)'];
				else
					$conn['disconnect (ping failed)'] = 1;

root's avatar
root committed
472 473 474 475
				$this->disconnect($dbhname);
				break;
			}

joe's avatar
joe committed
476
			if ( isset( $conn['queries'] ) )
joe's avatar
joe committed
477 478 479
				++$conn['queries'];
			else
				$conn['queries'] = 1;
root's avatar
root committed
480 481 482 483

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

joe's avatar
joe committed
484
		if ( $use_master && defined( "MASTER_DB_DEAD" ) ) {
root's avatar
root committed
485 486 487 488 489 490 491 492 493 494 495 496 497 498 499
			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]) )
			return $this->bail("No databases available with $this->table ($dataset)");

		// 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);
joe's avatar
joe committed
500
				foreach ( $keys as $key )
root's avatar
root committed
501 502
					$servers[] = compact('group', 'key');
			}
shammash's avatar
shammash committed
503

joe's avatar
joe committed
504
			if ( !$tries_remaining = count( $servers ) )
root's avatar
root committed
505
				return $this->bail("No database servers were found to match the query. ($this->table, $dataset)");
joe's avatar
joe committed
506

shammash's avatar
shammash committed
507 508 509
			if ( !isset( $unique_servers ) )
				$unique_servers = $tries_remaining;

root's avatar
root committed
510 511 512
		} while ( $tries_remaining < $this->min_tries );

		// Connect to a database server
shammash's avatar
shammash committed
513 514 515
		do {
			$unique_lagged_slaves = array();
			$success = false;
root's avatar
root committed
516

shammash's avatar
shammash committed
517
			foreach ( $servers as $group_key ) {
joe's avatar
joe committed
518 519
				--$tries_remaining;

shammash's avatar
shammash committed
520 521 522
				// 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
523

shammash's avatar
shammash committed
524 525
				// $group, $key
				extract($group_key, EXTR_OVERWRITE);
root's avatar
root committed
526

shammash's avatar
shammash committed
527 528
				// $host, $user, $password, $name, $read, $write [, $lag_threshold, $connect_function, $timeout ]
				extract($this->hyper_servers[$dataset][$operation][$group][$key], EXTR_OVERWRITE);
joe's avatar
joe committed
529
				$port = null;
root's avatar
root committed
530

shammash's avatar
shammash committed
531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564
				// 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
565
					if ( !isset( $unique_lagged_slaves["$host:$port"] )
shammash's avatar
shammash committed
566 567 568 569 570
						&& $unique_servers == count( $unique_lagged_slaves ) + 1
						&& $group == $min_group )
					{
						$this->lag_threshold = null;
					} else {
joe's avatar
joe committed
571
						$unique_lagged_slaves["$host:$port"] = $this->lag;
shammash's avatar
shammash committed
572 573 574
						continue;
					}
				}
root's avatar
root committed
575

shammash's avatar
shammash committed
576
				$this->timer_start();
root's avatar
root committed
577

shammash's avatar
shammash committed
578 579 580 581 582
				// Connect if necessary or possible
				$tcp = null;
				if ( $use_master || !$tries_remaining || !$this->check_tcp_responsiveness
					|| true === $tcp = $this->check_tcp_responsiveness($host, $port, $timeout) )
				{
joe's avatar
joe committed
583
					$this->dbhs[$dbhname] = @ $connect_function( "$host:$port", $user, $password, true );
shammash's avatar
shammash committed
584 585 586
				} else {
					$this->dbhs[$dbhname] = false;
				}
root's avatar
root committed
587

shammash's avatar
shammash committed
588 589 590 591 592 593 594 595 596 597 598 599
				$elapsed = $this->timer_stop();

				if ( is_resource( $this->dbhs[$dbhname] ) ) {
					/**
					 * 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
600
							!isset( $unique_lagged_slaves["$host:$port"] )
shammash's avatar
shammash committed
601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617
							&& $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;
					} elseif ( mysql_select_db( $name, $this->dbhs[ $dbhname ] ) ) {
						$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
618
						$this->last_connection = compact('dbhname', 'host', 'port', 'user', 'name', 'tcp', 'elapsed', 'success', 'queries', 'lag');
shammash's avatar
shammash committed
619 620 621 622 623
						$this->db_connections[] = $this->last_connection;
						$this->open_connections[] = $dbhname;
						break;
					}
				}
root's avatar
root committed
624 625 626 627

				$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
628 629 630 631 632 633 634 635 636 637 638 639 640
				/* 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' => " . mysql_error() . ",\n";
					$msg .= "'errno' => " . mysql_errno() . ",\n";
					$msg .= "'tcp_responsive' => " . ( $tcp === true ? 'true' : $tcp ) . ",\n";
					$msg .= "'lagged_status' => " . ( isset( $lagged_status ) ? $lagged_status : HYPERDB_LAG_UNKNOWN );

					$this->print_error( $msg );
				}
shammash's avatar
shammash committed
641 642 643
			}

			if ( !$success || !isset($this->dbhs[$dbhname]) || !is_resource( $this->dbhs[$dbhname] ) ) {
joe's avatar
joe committed
644
				if ( !isset( $ignore_slave_lag ) && count( $unique_lagged_slaves ) ) {
shammash's avatar
shammash committed
645 646 647 648 649
					// 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
650

shammash's avatar
shammash committed
651
				$error_details = array(
root's avatar
root committed
652
					'host' => $host,
shammash's avatar
shammash committed
653 654 655 656 657
					'port' => $port,
					'operation' => $operation,
					'table' => $this->table,
					'dataset' => $dataset,
					'dbhname' => $dbhname
root's avatar
root committed
658
				);
shammash's avatar
shammash committed
659
				$this->run_callbacks( 'db_connection_error', $error_details );
root's avatar
root committed
660

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

shammash's avatar
shammash committed
664 665 666
			break;
		} while ( true );

joe's avatar
joe committed
667
		if ( !isset( $charset ) )
joe's avatar
joe committed
668 669 670 671 672
			$charset = null;

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

shammash's avatar
shammash committed
673
		$this->set_charset($this->dbhs[$dbhname], $charset, $collate);
joe's avatar
joe committed
674 675

		if ( !isset( $charset ) )
Joe Oblivian's avatar
Joe Oblivian committed
676 677 678 679 680 681 682
			$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
683

shammash's avatar
shammash committed
684
		$this->dbh = $this->dbhs[$dbhname]; // needed by $wpdb->_real_escape()
root's avatar
root committed
685 686 687 688 689 690 691 692 693 694 695 696 697 698

		$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
699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722
	/**
	 * Sets the connection's character set.
	 * @param resource $dbh     The resource given by mysql_connect
	 * @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;
		if ( $this->has_cap( 'collation', $dbh ) && !empty( $charset ) ) {
			if ( function_exists( 'mysql_set_charset' ) && $this->has_cap( 'set_charset', $dbh ) ) {
				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 );
				mysql_query( $query, $dbh );
			}
		}
	}

root's avatar
root committed
723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793
	/**
	 * Disconnect and remove connection from open connections list
	 * @param string $tdbhname
	 */
	function disconnect($dbhname) {
		if ( $k = array_search($dbhname, $this->open_connections) )
			unset($this->open_connections[$k]);

		if ( is_resource($this->dbhs[$dbhname]) )
			mysql_close($this->dbhs[$dbhname]);

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

	/**
	 * Kill cached query results
	 */
	function flush() {
		$this->last_error = '';
		$this->num_rows = 0;
		parent::flush();
	}

	/**
	 * Basic query. See docs for more details.
	 * @param string $query
	 * @return int number of rows
	 */
	function query($query) {
		// 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;

		if ( preg_match('/^\s*SELECT\s+FOUND_ROWS(\s*)/i', $query) && is_resource($this->last_found_rows_result) ) {
			$this->result = $this->last_found_rows_result;
			$elapsed = 0;
		} else {
			$this->dbh = $this->db_connect( $query );

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

			$this->timer_start();
			$this->result = mysql_query($query, $this->dbh);
			$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();
					$this->last_found_rows_result = mysql_query("SELECT FOUND_ROWS()", $this->dbh);
					$elapsed += $this->timer_stop();
					++$this->num_queries;
					$query .= "; SELECT FOUND_ROWS()";
				}
			} else {
				$this->last_found_rows_result = null;
			}

			if ( $this->save_queries ) {
				if ( is_callable($this->save_query_callback) )
shammash's avatar
shammash committed
794
					$this->queries[] = call_user_func_array( $this->save_query_callback, array( $query, $elapsed, $this->save_backtrace ? debug_backtrace( false ) : null, &$this ) );
root's avatar
root committed
795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882
				else
					$this->queries[] = array( $query, $elapsed, $this->get_caller() );
			}
		}

		// If there is an error then take note of it
		if ( $this->last_error = mysql_error($this->dbh) ) {
			$this->print_error($this->last_error);
			return false;
		}

		if ( preg_match("/^\\s*(insert|delete|update|replace|alter) /i",$query) ) {
			$this->rows_affected = mysql_affected_rows($this->dbh);

			// Take note of the insert_id
			if ( preg_match("/^\\s*(insert|replace) /i",$query) ) {
				$this->insert_id = mysql_insert_id($this->dbh);
			}
			// Return number of rows affected
			$return_val = $this->rows_affected;
		} else {
			$i = 0;
			$this->col_info = array();
			while ($i < @mysql_num_fields($this->result)) {
				$this->col_info[$i] = @mysql_fetch_field($this->result);
				$i++;
			}
			$num_rows = 0;
			$this->last_result = array();
			while ( $row = @mysql_fetch_object($this->result) ) {
				$this->last_result[$num_rows] = $row;
				$num_rows++;
			}

			@mysql_free_result($this->result);

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

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

		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
883 884
		case 'set_charset' :
			return version_compare($version, '5.0.7', '>=');
root's avatar
root committed
885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916
		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;
		elseif ( is_resource( $dbh_or_table ) )
			$dbh =& $dbh_or_table;
		else
			$dbh = $this->db_connect( "SELECT FROM $dbh_or_table $this->users" );

		if ( $dbh )
			return preg_replace('/[^0-9.].*/', '', mysql_get_server_info( $dbh ));
		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 '';

shammash's avatar
shammash committed
917
		$bt = debug_backtrace( false );
root's avatar
root committed
918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944
		$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;

			if ( isset($trace['class']) )
				$caller = $trace['class'] . '::' . $trace['function'];
			else
				$caller = $trace['function'];
			break;
		}
		return $caller;
	}

	/**
	 * Check the responsiveness of a tcp/ip daemon
	 * @return (bool) true when $host:$post responds within $float_timeout seconds, else (bool) false
	 */
joe's avatar
joe committed
945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969
	function check_tcp_responsiveness( $host, $port, $float_timeout ) {
		if ( function_exists( 'apc_store' ) ) {
			$use_apc = true;
			$apc_key = "{$host}{$port}";
			$apc_ttl = 10;
		} else {
			$use_apc = false;
		}

		if ( $use_apc ) {
			$cached_value = apc_fetch( $apc_key );
			switch ( $cached_value ) {
				case 'up':
					$this->tcp_responsive = 'true';
					return true;
				case 'down':
					$this->tcp_responsive = 'false';
					return false;
			}
		}

		$socket = @ fsockopen( $host, $port, $errno, $errstr, $float_timeout );
		if ( $socket === false ) {
			if ( $use_apc )
				apc_store( $apc_key, 'down', $apc_ttl );
root's avatar
root committed
970
			return "[ > $float_timeout ] ($errno) '$errstr'";
joe's avatar
joe committed
971 972 973 974 975 976 977
		}

		fclose( $socket );

		if ( $use_apc )
			apc_store( $apc_key, 'up', $apc_ttl );

shammash's avatar
shammash committed
978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000
		return true;
	}

	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
1001 1002 1003
	}

	// Helper functions for configuration
joe's avatar
joe committed
1004

root's avatar
root committed
1005 1006
} // class hyperdb

Joe Oblivian's avatar
Joe Oblivian committed
1007
$wpdb = new hyperdb();
Joe's avatar
Joe committed
1008

root's avatar
root committed
1009 1010 1011
require( DB_CONFIG_FILE );

?>