don't produce warnings in get() if the item is missing
[mediawiki.git] / includes / Database.php
blob55932b5c18142e05221959f26b1ba32a4ef8ddf2
1 <?php
2 /**
3 * This file deals with MySQL interface functions
4 * and query specifics/optimisations
5 * @package MediaWiki
6 */
8 /**
9 * Depends on the CacheManager
11 require_once( 'CacheManager.php' );
13 /** See Database::makeList() */
14 define( 'LIST_COMMA', 0 );
15 define( 'LIST_AND', 1 );
16 define( 'LIST_SET', 2 );
17 define( 'LIST_NAMES', 3);
19 /** Number of times to re-try an operation in case of deadlock */
20 define( 'DEADLOCK_TRIES', 4 );
21 /** Minimum time to wait before retry, in microseconds */
22 define( 'DEADLOCK_DELAY_MIN', 500000 );
23 /** Maximum time to wait before retry */
24 define( 'DEADLOCK_DELAY_MAX', 1500000 );
26 class DBObject {
27 var $mData;
29 function DBObject($data) {
30 $this->mData = $data;
33 function isLOB() {
34 return false;
37 function data() {
38 return $this->mData;
42 /**
43 * Database abstraction object
44 * @package MediaWiki
46 class Database {
48 #------------------------------------------------------------------------------
49 # Variables
50 #------------------------------------------------------------------------------
51 /**#@+
52 * @access private
54 var $mLastQuery = '';
56 var $mServer, $mUser, $mPassword, $mConn = null, $mDBname;
57 var $mOut, $mOpened = false;
59 var $mFailFunction;
60 var $mTablePrefix;
61 var $mFlags;
62 var $mTrxLevel = 0;
63 var $mErrorCount = 0;
64 /**#@-*/
66 #------------------------------------------------------------------------------
67 # Accessors
68 #------------------------------------------------------------------------------
69 # These optionally set a variable and return the previous state
71 /**
72 * Fail function, takes a Database as a parameter
73 * Set to false for default, 1 for ignore errors
75 function failFunction( $function = NULL ) {
76 return wfSetVar( $this->mFailFunction, $function );
79 /**
80 * Output page, used for reporting errors
81 * FALSE means discard output
83 function &setOutputPage( &$out ) {
84 $this->mOut =& $out;
87 /**
88 * Boolean, controls output of large amounts of debug information
90 function debug( $debug = NULL ) {
91 return wfSetBit( $this->mFlags, DBO_DEBUG, $debug );
94 /**
95 * Turns buffering of SQL result sets on (true) or off (false).
96 * Default is "on" and it should not be changed without good reasons.
98 function bufferResults( $buffer = NULL ) {
99 if ( is_null( $buffer ) ) {
100 return !(bool)( $this->mFlags & DBO_NOBUFFER );
101 } else {
102 return !wfSetBit( $this->mFlags, DBO_NOBUFFER, !$buffer );
107 * Turns on (false) or off (true) the automatic generation and sending
108 * of a "we're sorry, but there has been a database error" page on
109 * database errors. Default is on (false). When turned off, the
110 * code should use wfLastErrno() and wfLastError() to handle the
111 * situation as appropriate.
113 function ignoreErrors( $ignoreErrors = NULL ) {
114 return wfSetBit( $this->mFlags, DBO_IGNORE, $ignoreErrors );
118 * The current depth of nested transactions
119 * @param integer $level
121 function trxLevel( $level = NULL ) {
122 return wfSetVar( $this->mTrxLevel, $level );
126 * Number of errors logged, only useful when errors are ignored
128 function errorCount( $count = NULL ) {
129 return wfSetVar( $this->mErrorCount, $count );
132 /**#@+
133 * Get function
135 function lastQuery() { return $this->mLastQuery; }
136 function isOpen() { return $this->mOpened; }
137 /**#@-*/
139 #------------------------------------------------------------------------------
140 # Other functions
141 #------------------------------------------------------------------------------
143 /**#@+
144 * @param string $server database server host
145 * @param string $user database user name
146 * @param string $password database user password
147 * @param string $dbname database name
151 * @param failFunction
152 * @param $flags
153 * @param string $tablePrefix Database table prefixes. By default use the prefix gave in LocalSettings.php
155 function Database( $server = false, $user = false, $password = false, $dbName = false,
156 $failFunction = false, $flags = 0, $tablePrefix = 'get from global' ) {
158 global $wgOut, $wgDBprefix, $wgCommandLineMode;
159 # Can't get a reference if it hasn't been set yet
160 if ( !isset( $wgOut ) ) {
161 $wgOut = NULL;
163 $this->mOut =& $wgOut;
165 $this->mFailFunction = $failFunction;
166 $this->mFlags = $flags;
168 if ( $this->mFlags & DBO_DEFAULT ) {
169 if ( $wgCommandLineMode ) {
170 $this->mFlags &= ~DBO_TRX;
171 } else {
172 $this->mFlags |= DBO_TRX;
177 // Faster read-only access
178 if ( wfReadOnly() ) {
179 $this->mFlags |= DBO_PERSISTENT;
180 $this->mFlags &= ~DBO_TRX;
183 /** Get the default table prefix*/
184 if ( $tablePrefix == 'get from global' ) {
185 $this->mTablePrefix = $wgDBprefix;
186 } else {
187 $this->mTablePrefix = $tablePrefix;
190 if ( $server ) {
191 $this->open( $server, $user, $password, $dbName );
196 * @static
197 * @param failFunction
198 * @param $flags
200 function newFromParams( $server, $user, $password, $dbName,
201 $failFunction = false, $flags = 0 )
203 return new Database( $server, $user, $password, $dbName, $failFunction, $flags );
207 * Usually aborts on failure
208 * If the failFunction is set to a non-zero integer, returns success
210 function open( $server, $user, $password, $dbName ) {
211 # Test for missing mysql.so
212 # First try to load it
213 if (!@extension_loaded('mysql')) {
214 @dl('mysql.so');
217 # Otherwise we get a suppressed fatal error, which is very hard to track down
218 if ( !function_exists( 'mysql_connect' ) ) {
219 die( "MySQL functions missing, have you compiled PHP with the --with-mysql option?\n" );
222 $this->close();
223 $this->mServer = $server;
224 $this->mUser = $user;
225 $this->mPassword = $password;
226 $this->mDBname = $dbName;
228 $success = false;
230 if ( $this->mFlags & DBO_PERSISTENT ) {
231 @/**/$this->mConn = mysql_pconnect( $server, $user, $password );
232 } else {
233 # Create a new connection...
234 if( version_compare( PHP_VERSION, '4.2.0', 'ge' ) ) {
235 @/**/$this->mConn = mysql_connect( $server, $user, $password, true );
236 } else {
237 # On PHP 4.1 the new_link parameter is not available. We cannot
238 # guarantee that we'll actually get a new connection, and this
239 # may cause some operations to fail possibly.
240 @/**/$this->mConn = mysql_connect( $server, $user, $password );
244 if ( $dbName != '' ) {
245 if ( $this->mConn !== false ) {
246 $success = @/**/mysql_select_db( $dbName, $this->mConn );
247 if ( !$success ) {
248 wfDebug( "Error selecting database \"$dbName\": " . $this->lastError() . "\n" );
250 } else {
251 wfDebug( "DB connection error\n" );
252 wfDebug( "Server: $server, User: $user, Password: " .
253 substr( $password, 0, 3 ) . "..., error: " . mysql_error() . "\n" );
254 $success = false;
256 } else {
257 # Delay USE query
258 $success = (bool)$this->mConn;
261 if ( !$success ) {
262 $this->reportConnectionError();
264 $this->mOpened = $success;
265 return $success;
267 /**#@-*/
270 * Closes a database connection.
271 * if it is open : commits any open transactions
273 * @return bool operation success. true if already closed.
275 function close()
277 $this->mOpened = false;
278 if ( $this->mConn ) {
279 if ( $this->trxLevel() ) {
280 $this->immediateCommit();
282 return mysql_close( $this->mConn );
283 } else {
284 return true;
289 * @access private
290 * @param string $msg error message ?
292 function reportConnectionError() {
293 if ( $this->mFailFunction ) {
294 if ( !is_int( $this->mFailFunction ) ) {
295 $ff = $this->mFailFunction;
296 $ff( $this, $this->lastError() );
298 } else {
299 wfEmergencyAbort( $this, $this->lastError() );
304 * Usually aborts on failure
305 * If errors are explicitly ignored, returns success
307 function query( $sql, $fname = '', $tempIgnore = false ) {
308 global $wgProfiling, $wgCommandLineMode;
310 if ( wfReadOnly() ) {
311 # This is a quick check for the most common kinds of write query used
312 # in MediaWiki, to provide extra safety in addition to UI-level checks.
313 # It is not intended to prevent every conceivable write query, or even
314 # to handle such queries gracefully.
315 if ( preg_match( '/^(update|insert|replace|delete)/i', $sql ) ) {
316 wfDebug( "Write query from $fname blocked\n" );
317 return false;
321 if ( $wgProfiling ) {
322 # generalizeSQL will probably cut down the query to reasonable
323 # logging size most of the time. The substr is really just a sanity check.
324 $profName = 'query: ' . $fname . ' ' . substr( Database::generalizeSQL( $sql ), 0, 255 );
325 wfProfileIn( 'Database::query' );
326 wfProfileIn( $profName );
329 $this->mLastQuery = $sql;
331 # Add a comment for easy SHOW PROCESSLIST interpretation
332 if ( $fname ) {
333 $commentedSql = "/* $fname */ $sql";
334 } else {
335 $commentedSql = $sql;
338 # If DBO_TRX is set, start a transaction
339 if ( ( $this->mFlags & DBO_TRX ) && !$this->trxLevel() && $sql != 'BEGIN' ) {
340 $this->begin();
343 if ( $this->debug() ) {
344 $sqlx = substr( $commentedSql, 0, 500 );
345 $sqlx = strtr( $sqlx, "\t\n", ' ' );
346 wfDebug( "SQL: $sqlx\n" );
349 # Do the query and handle errors
350 $ret = $this->doQuery( $commentedSql );
352 # Try reconnecting if the connection was lost
353 if ( false === $ret && ( $this->lastErrno() == 2013 || $this->lastErrno() == 2006 ) ) {
354 # Transaction is gone, like it or not
355 $this->mTrxLevel = 0;
356 wfDebug( "Connection lost, reconnecting...\n" );
357 if ( $this->ping() ) {
358 wfDebug( "Reconnected\n" );
359 $ret = $this->doQuery( $commentedSql );
360 } else {
361 wfDebug( "Failed\n" );
365 if ( false === $ret ) {
366 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
369 if ( $wgProfiling ) {
370 wfProfileOut( $profName );
371 wfProfileOut( 'Database::query' );
373 return $ret;
377 * The DBMS-dependent part of query()
378 * @param string $sql SQL query.
380 function doQuery( $sql ) {
381 if( $this->bufferResults() ) {
382 $ret = mysql_query( $sql, $this->mConn );
383 } else {
384 $ret = mysql_unbuffered_query( $sql, $this->mConn );
386 return $ret;
390 * @param $error
391 * @param $errno
392 * @param $sql
393 * @param string $fname
394 * @param bool $tempIgnore
396 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
397 global $wgCommandLineMode, $wgFullyInitialised;
398 # Ignore errors during error handling to avoid infinite recursion
399 $ignore = $this->ignoreErrors( true );
400 $this->mErrorCount ++;
402 if( $ignore || $tempIgnore ) {
403 wfDebug("SQL ERROR (ignored): " . $error . "\n");
404 } else {
405 $sql1line = str_replace( "\n", "\\n", $sql );
406 wfLogDBError("$fname\t{$this->mServer}\t$errno\t$error\t$sql1line\n");
407 wfDebug("SQL ERROR: " . $error . "\n");
408 if ( $wgCommandLineMode || !$this->mOut || empty( $wgFullyInitialised ) ) {
409 $message = "A database error has occurred\n" .
410 "Query: $sql\n" .
411 "Function: $fname\n" .
412 "Error: $errno $error\n";
413 if ( !$wgCommandLineMode ) {
414 $message = nl2br( $message );
416 wfDebugDieBacktrace( $message );
417 } else {
418 // this calls wfAbruptExit()
419 $this->mOut->databaseError( $fname, $sql, $error, $errno );
422 $this->ignoreErrors( $ignore );
427 * Intended to be compatible with the PEAR::DB wrapper functions.
428 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
430 * ? = scalar value, quoted as necessary
431 * ! = raw SQL bit (a function for instance)
432 * & = filename; reads the file and inserts as a blob
433 * (we don't use this though...)
435 function prepare( $sql, $func = 'Database::prepare' ) {
436 /* MySQL doesn't support prepared statements (yet), so just
437 pack up the query for reference. We'll manually replace
438 the bits later. */
439 return array( 'query' => $sql, 'func' => $func );
442 function freePrepared( $prepared ) {
443 /* No-op for MySQL */
447 * Execute a prepared query with the various arguments
448 * @param string $prepared the prepared sql
449 * @param mixed $args Either an array here, or put scalars as varargs
451 function execute( $prepared, $args = null ) {
452 if( !is_array( $args ) ) {
453 # Pull the var args
454 $args = func_get_args();
455 array_shift( $args );
457 $sql = $this->fillPrepared( $prepared['query'], $args );
458 return $this->query( $sql, $prepared['func'] );
462 * Prepare & execute an SQL statement, quoting and inserting arguments
463 * in the appropriate places.
464 * @param string $query
465 * @param string $args ...
467 function safeQuery( $query, $args = null ) {
468 $prepared = $this->prepare( $query, 'Database::safeQuery' );
469 if( !is_array( $args ) ) {
470 # Pull the var args
471 $args = func_get_args();
472 array_shift( $args );
474 $retval = $this->execute( $prepared, $args );
475 $this->freePrepared( $prepared );
476 return $retval;
480 * For faking prepared SQL statements on DBs that don't support
481 * it directly.
482 * @param string $preparedSql - a 'preparable' SQL statement
483 * @param array $args - array of arguments to fill it with
484 * @return string executable SQL
486 function fillPrepared( $preparedQuery, $args ) {
487 $n = 0;
488 reset( $args );
489 $this->preparedArgs =& $args;
490 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
491 array( &$this, 'fillPreparedArg' ), $preparedQuery );
495 * preg_callback func for fillPrepared()
496 * The arguments should be in $this->preparedArgs and must not be touched
497 * while we're doing this.
499 * @param array $matches
500 * @return string
501 * @access private
503 function fillPreparedArg( $matches ) {
504 switch( $matches[1] ) {
505 case '\\?': return '?';
506 case '\\!': return '!';
507 case '\\&': return '&';
509 list( $n, $arg ) = each( $this->preparedArgs );
510 switch( $matches[1] ) {
511 case '?': return $this->addQuotes( $arg );
512 case '!': return $arg;
513 case '&':
514 # return $this->addQuotes( file_get_contents( $arg ) );
515 wfDebugDieBacktrace( '& mode is not implemented. If it\'s really needed, uncomment the line above.' );
516 default:
517 wfDebugDieBacktrace( 'Received invalid match. This should never happen!' );
521 /**#@+
522 * @param mixed $res A SQL result
525 * Free a result object
527 function freeResult( $res ) {
528 if ( !@/**/mysql_free_result( $res ) ) {
529 wfDebugDieBacktrace( "Unable to free MySQL result\n" );
534 * Fetch the next row from the given result object, in object form
536 function fetchObject( $res ) {
537 @/**/$row = mysql_fetch_object( $res );
538 if( mysql_errno() ) {
539 wfDebugDieBacktrace( 'Error in fetchObject(): ' . htmlspecialchars( mysql_error() ) );
541 return $row;
545 * Fetch the next row from the given result object
546 * Returns an array
548 function fetchRow( $res ) {
549 @/**/$row = mysql_fetch_array( $res );
550 if (mysql_errno() ) {
551 wfDebugDieBacktrace( 'Error in fetchRow(): ' . htmlspecialchars( mysql_error() ) );
553 return $row;
557 * Get the number of rows in a result object
559 function numRows( $res ) {
560 @/**/$n = mysql_num_rows( $res );
561 if( mysql_errno() ) {
562 wfDebugDieBacktrace( 'Error in numRows(): ' . htmlspecialchars( mysql_error() ) );
564 return $n;
568 * Get the number of fields in a result object
569 * See documentation for mysql_num_fields()
571 function numFields( $res ) { return mysql_num_fields( $res ); }
574 * Get a field name in a result object
575 * See documentation for mysql_field_name()
577 function fieldName( $res, $n ) { return mysql_field_name( $res, $n ); }
580 * Get the inserted value of an auto-increment row
582 * The value inserted should be fetched from nextSequenceValue()
584 * Example:
585 * $id = $dbw->nextSequenceValue('page_page_id_seq');
586 * $dbw->insert('page',array('page_id' => $id));
587 * $id = $dbw->insertId();
589 function insertId() { return mysql_insert_id( $this->mConn ); }
592 * Change the position of the cursor in a result object
593 * See mysql_data_seek()
595 function dataSeek( $res, $row ) { return mysql_data_seek( $res, $row ); }
598 * Get the last error number
599 * See mysql_errno()
601 function lastErrno() {
602 if ( $this->mConn ) {
603 return mysql_errno( $this->mConn );
604 } else {
605 return mysql_errno();
610 * Get a description of the last error
611 * See mysql_error() for more details
613 function lastError() {
614 if ( $this->mConn ) {
615 # Even if it's non-zero, it can still be invalid
616 wfSuppressWarnings();
617 $error = mysql_error( $this->mConn );
618 if ( !$error ) {
619 $error = mysql_error();
621 wfRestoreWarnings();
622 } else {
623 $error = mysql_error();
625 if( $error ) {
626 $error .= ' (' . $this->mServer . ')';
628 return $error;
631 * Get the number of rows affected by the last write query
632 * See mysql_affected_rows() for more details
634 function affectedRows() { return mysql_affected_rows( $this->mConn ); }
635 /**#@-*/ // end of template : @param $result
638 * Simple UPDATE wrapper
639 * Usually aborts on failure
640 * If errors are explicitly ignored, returns success
642 * This function exists for historical reasons, Database::update() has a more standard
643 * calling convention and feature set
645 function set( $table, $var, $value, $cond, $fname = 'Database::set' )
647 $table = $this->tableName( $table );
648 $sql = "UPDATE $table SET $var = '" .
649 $this->strencode( $value ) . "' WHERE ($cond)";
650 return (bool)$this->query( $sql, DB_MASTER, $fname );
654 * Simple SELECT wrapper, returns a single field, input must be encoded
655 * Usually aborts on failure
656 * If errors are explicitly ignored, returns FALSE on failure
658 function selectField( $table, $var, $cond='', $fname = 'Database::selectField', $options = array() ) {
659 if ( !is_array( $options ) ) {
660 $options = array( $options );
662 $options['LIMIT'] = 1;
664 $res = $this->select( $table, $var, $cond, $fname, $options );
665 if ( $res === false || !$this->numRows( $res ) ) {
666 return false;
668 $row = $this->fetchRow( $res );
669 if ( $row !== false ) {
670 $this->freeResult( $res );
671 return $row[0];
672 } else {
673 return false;
678 * Returns an optional USE INDEX clause to go after the table, and a
679 * string to go at the end of the query
681 * @access private
683 * @param array $options an associative array of options to be turned into
684 * an SQL query, valid keys are listed in the function.
685 * @return array
687 function makeSelectOptions( $options ) {
688 $tailOpts = '';
690 if ( isset( $options['GROUP BY'] ) ) {
691 $tailOpts .= " GROUP BY {$options['GROUP BY']}";
693 if ( isset( $options['ORDER BY'] ) ) {
694 $tailOpts .= " ORDER BY {$options['ORDER BY']}";
697 if ( is_numeric( array_search( 'FOR UPDATE', $options ) ) ) {
698 $tailOpts .= ' FOR UPDATE';
701 if ( is_numeric( array_search( 'LOCK IN SHARE MODE', $options ) ) ) {
702 $tailOpts .= ' LOCK IN SHARE MODE';
705 if ( isset( $options['USE INDEX'] ) ) {
706 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
707 } else {
708 $useIndex = '';
710 return array( $useIndex, $tailOpts );
714 * SELECT wrapper
716 function select( $table, $vars, $conds='', $fname = 'Database::select', $options = array() )
718 if( is_array( $vars ) ) {
719 $vars = implode( ',', $vars );
721 if( !is_array( $options ) ) {
722 $options = array( $options );
724 if( is_array( $table ) ) {
725 $from = ' FROM ' . implode( ',', array_map( array( &$this, 'tableName' ), $table ) );
726 } elseif ($table!='') {
727 $from = ' FROM ' .$this->tableName( $table );
728 } else {
729 $from = '';
732 list( $useIndex, $tailOpts ) = $this->makeSelectOptions( $options );
734 if( !empty( $conds ) ) {
735 if ( is_array( $conds ) ) {
736 $conds = $this->makeList( $conds, LIST_AND );
738 $sql = "SELECT $vars $from $useIndex WHERE $conds $tailOpts";
739 } else {
740 $sql = "SELECT $vars $from $useIndex $tailOpts";
742 if (isset($options['LIMIT'])) {
743 $sql = $this->limitResult($sql, $options['LIMIT'], isset($options['OFFSET']) ? $options['OFFSET'] : false);
745 return $this->query( $sql, $fname );
749 * Single row SELECT wrapper
750 * Aborts or returns FALSE on error
752 * $vars: the selected variables
753 * $conds: a condition map, terms are ANDed together.
754 * Items with numeric keys are taken to be literal conditions
755 * Takes an array of selected variables, and a condition map, which is ANDed
756 * e.g: selectRow( "page", array( "page_id" ), array( "page_namespace" =>
757 * NS_MAIN, "page_title" => "Astronomy" ) ) would return an object where
758 * $obj- >page_id is the ID of the Astronomy article
760 * @todo migrate documentation to phpdocumentor format
762 function selectRow( $table, $vars, $conds, $fname = 'Database::selectRow', $options = array() ) {
763 $options['LIMIT'] = 1;
764 $res = $this->select( $table, $vars, $conds, $fname, $options );
765 if ( $res === false )
766 return false;
767 if ( !$this->numRows($res) ) {
768 $this->freeResult($res);
769 return false;
771 $obj = $this->fetchObject( $res );
772 $this->freeResult( $res );
773 return $obj;
778 * Removes most variables from an SQL query and replaces them with X or N for numbers.
779 * It's only slightly flawed. Don't use for anything important.
781 * @param string $sql A SQL Query
782 * @static
784 function generalizeSQL( $sql ) {
785 # This does the same as the regexp below would do, but in such a way
786 # as to avoid crashing php on some large strings.
787 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
789 $sql = str_replace ( "\\\\", '', $sql);
790 $sql = str_replace ( "\\'", '', $sql);
791 $sql = str_replace ( "\\\"", '', $sql);
792 $sql = preg_replace ("/'.*'/s", "'X'", $sql);
793 $sql = preg_replace ('/".*"/s', "'X'", $sql);
795 # All newlines, tabs, etc replaced by single space
796 $sql = preg_replace ( "/\s+/", ' ', $sql);
798 # All numbers => N
799 $sql = preg_replace ('/-?[0-9]+/s', 'N', $sql);
801 return $sql;
805 * Determines whether a field exists in a table
806 * Usually aborts on failure
807 * If errors are explicitly ignored, returns NULL on failure
809 function fieldExists( $table, $field, $fname = 'Database::fieldExists' ) {
810 $table = $this->tableName( $table );
811 $res = $this->query( 'DESCRIBE '.$table, DB_SLAVE, $fname );
812 if ( !$res ) {
813 return NULL;
816 $found = false;
818 while ( $row = $this->fetchObject( $res ) ) {
819 if ( $row->Field == $field ) {
820 $found = true;
821 break;
824 return $found;
828 * Determines whether an index exists
829 * Usually aborts on failure
830 * If errors are explicitly ignored, returns NULL on failure
832 function indexExists( $table, $index, $fname = 'Database::indexExists' ) {
833 $info = $this->indexInfo( $table, $index, $fname );
834 if ( is_null( $info ) ) {
835 return NULL;
836 } else {
837 return $info !== false;
843 * Get information about an index into an object
844 * Returns false if the index does not exist
846 function indexInfo( $table, $index, $fname = 'Database::indexInfo' ) {
847 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
848 # SHOW INDEX should work for 3.x and up:
849 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
850 $table = $this->tableName( $table );
851 $sql = 'SHOW INDEX FROM '.$table;
852 $res = $this->query( $sql, $fname );
853 if ( !$res ) {
854 return NULL;
857 while ( $row = $this->fetchObject( $res ) ) {
858 if ( $row->Key_name == $index ) {
859 return $row;
862 return false;
866 * Query whether a given table exists
868 function tableExists( $table ) {
869 $table = $this->tableName( $table );
870 $old = $this->ignoreErrors( true );
871 $res = $this->query( "SELECT 1 FROM $table LIMIT 1" );
872 $this->ignoreErrors( $old );
873 if( $res ) {
874 $this->freeResult( $res );
875 return true;
876 } else {
877 return false;
882 * mysql_fetch_field() wrapper
883 * Returns false if the field doesn't exist
885 * @param $table
886 * @param $field
888 function fieldInfo( $table, $field ) {
889 $table = $this->tableName( $table );
890 $res = $this->query( "SELECT * FROM $table LIMIT 1" );
891 $n = mysql_num_fields( $res );
892 for( $i = 0; $i < $n; $i++ ) {
893 $meta = mysql_fetch_field( $res, $i );
894 if( $field == $meta->name ) {
895 return $meta;
898 return false;
902 * mysql_field_type() wrapper
904 function fieldType( $res, $index ) {
905 return mysql_field_type( $res, $index );
909 * Determines if a given index is unique
911 function indexUnique( $table, $index ) {
912 $indexInfo = $this->indexInfo( $table, $index );
913 if ( !$indexInfo ) {
914 return NULL;
916 return !$indexInfo->Non_unique;
920 * INSERT wrapper, inserts an array into a table
922 * $a may be a single associative array, or an array of these with numeric keys, for
923 * multi-row insert.
925 * Usually aborts on failure
926 * If errors are explicitly ignored, returns success
928 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
929 # No rows to insert, easy just return now
930 if ( !count( $a ) ) {
931 return true;
934 $table = $this->tableName( $table );
935 if ( !is_array( $options ) ) {
936 $options = array( $options );
938 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
939 $multi = true;
940 $keys = array_keys( $a[0] );
941 } else {
942 $multi = false;
943 $keys = array_keys( $a );
946 $sql = 'INSERT ' . implode( ' ', $options ) .
947 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
949 if ( $multi ) {
950 $first = true;
951 foreach ( $a as $row ) {
952 if ( $first ) {
953 $first = false;
954 } else {
955 $sql .= ',';
957 $sql .= '(' . $this->makeList( $row ) . ')';
959 } else {
960 $sql .= '(' . $this->makeList( $a ) . ')';
962 return (bool)$this->query( $sql, $fname );
966 * Make UPDATE options for the Database::update function
968 * @access private
969 * @param array $options The options passed to Database::update
970 * @return string
972 function makeUpdateOptions( $options ) {
973 if( !is_array( $options ) ) {
974 wfDebugDieBacktrace( 'makeUpdateOptions given non-array' );
976 $opts = array();
977 if ( in_array( 'LOW_PRIORITY', $options ) )
978 $opts[] = $this->lowPriorityOption();
979 if ( in_array( 'IGNORE', $options ) )
980 $opts[] = 'IGNORE';
981 return implode(' ', $opts);
985 * UPDATE wrapper, takes a condition array and a SET array
987 * @param string $table The table to UPDATE
988 * @param array $values An array of values to SET
989 * @param array $conds An array of conditions (WHERE)
990 * @param string $fname The Class::Function calling this function
991 * (for the log)
992 * @param array $options An array of UPDATE options, can be one or
993 * more of IGNORE, LOW_PRIORITY
995 function update( $table, $values, $conds, $fname = 'Database::update', $options = array() ) {
996 $table = $this->tableName( $table );
997 $opts = $this->makeUpdateOptions( $options );
998 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET );
999 if ( $conds != '*' ) {
1000 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND );
1002 $this->query( $sql, $fname );
1006 * Makes a wfStrencoded list from an array
1007 * $mode: LIST_COMMA - comma separated, no field names
1008 * LIST_AND - ANDed WHERE clause (without the WHERE)
1009 * LIST_SET - comma separated with field names, like a SET clause
1010 * LIST_NAMES - comma separated field names
1012 function makeList( $a, $mode = LIST_COMMA ) {
1013 if ( !is_array( $a ) ) {
1014 wfDebugDieBacktrace( 'Database::makeList called with incorrect parameters' );
1017 $first = true;
1018 $list = '';
1019 foreach ( $a as $field => $value ) {
1020 if ( !$first ) {
1021 if ( $mode == LIST_AND ) {
1022 $list .= ' AND ';
1023 } else {
1024 $list .= ',';
1026 } else {
1027 $first = false;
1029 if ( $mode == LIST_AND && is_numeric( $field ) ) {
1030 $list .= "($value)";
1031 } elseif ( $mode == LIST_AND && is_array ($value) ) {
1032 $list .= $field." IN (".$this->makeList($value).") ";
1033 } else {
1034 if ( $mode == LIST_AND || $mode == LIST_SET ) {
1035 $list .= "$field = ";
1037 $list .= $mode == LIST_NAMES ? $value : $this->addQuotes( $value );
1040 return $list;
1044 * Change the current database
1046 function selectDB( $db ) {
1047 $this->mDBname = $db;
1048 return mysql_select_db( $db, $this->mConn );
1052 * Starts a timer which will kill the DB thread after $timeout seconds
1054 function startTimer( $timeout ) {
1055 global $IP;
1056 if( function_exists( 'mysql_thread_id' ) ) {
1057 # This will kill the query if it's still running after $timeout seconds.
1058 $tid = mysql_thread_id( $this->mConn );
1059 exec( "php $IP/includes/killthread.php $timeout $tid &>/dev/null &" );
1064 * Stop a timer started by startTimer()
1065 * Currently unimplemented.
1068 function stopTimer() { }
1071 * Format a table name ready for use in constructing an SQL query
1073 * This does two important things: it quotes table names which as necessary,
1074 * and it adds a table prefix if there is one.
1076 * All functions of this object which require a table name call this function
1077 * themselves. Pass the canonical name to such functions. This is only needed
1078 * when calling query() directly.
1080 * @param string $name database table name
1082 function tableName( $name ) {
1083 global $wgSharedDB;
1084 # Skip quoted literals
1085 if ( $name{0} != '`' ) {
1086 if ( $this->mTablePrefix !== '' && strpos( '.', $name ) === false ) {
1087 $name = "{$this->mTablePrefix}$name";
1089 if ( isset( $wgSharedDB ) && "{$this->mTablePrefix}user" == $name ) {
1090 $name = "`$wgSharedDB`.`$name`";
1091 } else {
1092 # Standard quoting
1093 $name = "`$name`";
1096 return $name;
1100 * Fetch a number of table names into an array
1101 * This is handy when you need to construct SQL for joins
1103 * Example:
1104 * extract($dbr->tableNames('user','watchlist'));
1105 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1106 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1108 function tableNames() {
1109 $inArray = func_get_args();
1110 $retVal = array();
1111 foreach ( $inArray as $name ) {
1112 $retVal[$name] = $this->tableName( $name );
1114 return $retVal;
1118 * Wrapper for addslashes()
1119 * @param string $s String to be slashed.
1120 * @return string slashed string.
1122 function strencode( $s ) {
1123 return addslashes( $s );
1127 * If it's a string, adds quotes and backslashes
1128 * Otherwise returns as-is
1130 function addQuotes( $s ) {
1131 if ( is_null( $s ) ) {
1132 return 'NULL';
1133 } else {
1134 # This will also quote numeric values. This should be harmless,
1135 # and protects against weird problems that occur when they really
1136 # _are_ strings such as article titles and string->number->string
1137 # conversion is not 1:1.
1138 return "'" . $this->strencode( $s ) . "'";
1143 * Escape string for safe LIKE usage
1145 function escapeLike( $s ) {
1146 $s=$this->strencode( $s );
1147 $s=str_replace(array('%','_'),array('\%','\_'),$s);
1148 return $s;
1152 * Returns an appropriately quoted sequence value for inserting a new row.
1153 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
1154 * subclass will return an integer, and save the value for insertId()
1156 function nextSequenceValue( $seqName ) {
1157 return NULL;
1161 * USE INDEX clause
1162 * PostgreSQL doesn't have them and returns ""
1164 function useIndexClause( $index ) {
1165 global $wgDBmysql4;
1166 return $wgDBmysql4
1167 ? "FORCE INDEX ($index)"
1168 : "USE INDEX ($index)";
1172 * REPLACE query wrapper
1173 * PostgreSQL simulates this with a DELETE followed by INSERT
1174 * $row is the row to insert, an associative array
1175 * $uniqueIndexes is an array of indexes. Each element may be either a
1176 * field name or an array of field names
1178 * It may be more efficient to leave off unique indexes which are unlikely to collide.
1179 * However if you do this, you run the risk of encountering errors which wouldn't have
1180 * occurred in MySQL
1182 * @todo migrate comment to phodocumentor format
1184 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
1185 $table = $this->tableName( $table );
1187 # Single row case
1188 if ( !is_array( reset( $rows ) ) ) {
1189 $rows = array( $rows );
1192 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) .') VALUES ';
1193 $first = true;
1194 foreach ( $rows as $row ) {
1195 if ( $first ) {
1196 $first = false;
1197 } else {
1198 $sql .= ',';
1200 $sql .= '(' . $this->makeList( $row ) . ')';
1202 return $this->query( $sql, $fname );
1206 * DELETE where the condition is a join
1207 * MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
1209 * For safety, an empty $conds will not delete everything. If you want to delete all rows where the
1210 * join condition matches, set $conds='*'
1212 * DO NOT put the join condition in $conds
1214 * @param string $delTable The table to delete from.
1215 * @param string $joinTable The other table.
1216 * @param string $delVar The variable to join on, in the first table.
1217 * @param string $joinVar The variable to join on, in the second table.
1218 * @param array $conds Condition array of field names mapped to variables, ANDed together in the WHERE clause
1220 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'Database::deleteJoin' ) {
1221 if ( !$conds ) {
1222 wfDebugDieBacktrace( 'Database::deleteJoin() called with empty $conds' );
1225 $delTable = $this->tableName( $delTable );
1226 $joinTable = $this->tableName( $joinTable );
1227 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1228 if ( $conds != '*' ) {
1229 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND );
1232 return $this->query( $sql, $fname );
1236 * Returns the size of a text field, or -1 for "unlimited"
1238 function textFieldSize( $table, $field ) {
1239 $table = $this->tableName( $table );
1240 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
1241 $res = $this->query( $sql, 'Database::textFieldSize' );
1242 $row = $this->fetchObject( $res );
1243 $this->freeResult( $res );
1245 if ( preg_match( "/\((.*)\)/", $row->Type, $m ) ) {
1246 $size = $m[1];
1247 } else {
1248 $size = -1;
1250 return $size;
1254 * @return string Returns the text of the low priority option if it is supported, or a blank string otherwise
1256 function lowPriorityOption() {
1257 return 'LOW_PRIORITY';
1261 * DELETE query wrapper
1263 * Use $conds == "*" to delete all rows
1265 function delete( $table, $conds, $fname = 'Database::delete' ) {
1266 if ( !$conds ) {
1267 wfDebugDieBacktrace( 'Database::delete() called with no conditions' );
1269 $table = $this->tableName( $table );
1270 $sql = "DELETE FROM $table";
1271 if ( $conds != '*' ) {
1272 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
1274 return $this->query( $sql, $fname );
1278 * INSERT SELECT wrapper
1279 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
1280 * Source items may be literals rather than field names, but strings should be quoted with Database::addQuotes()
1281 * $conds may be "*" to copy the whole table
1282 * srcTable may be an array of tables.
1284 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'Database::insertSelect' ) {
1285 $destTable = $this->tableName( $destTable );
1286 if( is_array( $srcTable ) ) {
1287 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
1288 } else {
1289 $srcTable = $this->tableName( $srcTable );
1291 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
1292 ' SELECT ' . implode( ',', $varMap ) .
1293 " FROM $srcTable";
1294 if ( $conds != '*' ) {
1295 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
1297 return $this->query( $sql, $fname );
1301 * Construct a LIMIT query with optional offset
1302 * This is used for query pages
1303 * $sql string SQL query we will append the limit too
1304 * $limit integer the SQL limit
1305 * $offset integer the SQL offset (default false)
1307 function limitResult($sql, $limit, $offset=false) {
1308 return " $sql LIMIT ".((is_numeric($offset) && $offset != 0)?"{$offset},":"")."{$limit} ";
1310 function limitResultForUpdate($sql, $num) {
1311 return $this->limitResult($sql, $num, 0);
1315 * Returns an SQL expression for a simple conditional.
1316 * Uses IF on MySQL.
1318 * @param string $cond SQL expression which will result in a boolean value
1319 * @param string $trueVal SQL expression to return if true
1320 * @param string $falseVal SQL expression to return if false
1321 * @return string SQL fragment
1323 function conditional( $cond, $trueVal, $falseVal ) {
1324 return " IF($cond, $trueVal, $falseVal) ";
1328 * Determines if the last failure was due to a deadlock
1330 function wasDeadlock() {
1331 return $this->lastErrno() == 1213;
1335 * Perform a deadlock-prone transaction.
1337 * This function invokes a callback function to perform a set of write
1338 * queries. If a deadlock occurs during the processing, the transaction
1339 * will be rolled back and the callback function will be called again.
1341 * Usage:
1342 * $dbw->deadlockLoop( callback, ... );
1344 * Extra arguments are passed through to the specified callback function.
1346 * Returns whatever the callback function returned on its successful,
1347 * iteration, or false on error, for example if the retry limit was
1348 * reached.
1350 function deadlockLoop() {
1351 $myFname = 'Database::deadlockLoop';
1353 $this->begin();
1354 $args = func_get_args();
1355 $function = array_shift( $args );
1356 $oldIgnore = $this->ignoreErrors( true );
1357 $tries = DEADLOCK_TRIES;
1358 if ( is_array( $function ) ) {
1359 $fname = $function[0];
1360 } else {
1361 $fname = $function;
1363 do {
1364 $retVal = call_user_func_array( $function, $args );
1365 $error = $this->lastError();
1366 $errno = $this->lastErrno();
1367 $sql = $this->lastQuery();
1369 if ( $errno ) {
1370 if ( $this->wasDeadlock() ) {
1371 # Retry
1372 usleep( mt_rand( DEADLOCK_DELAY_MIN, DEADLOCK_DELAY_MAX ) );
1373 } else {
1374 $this->reportQueryError( $error, $errno, $sql, $fname );
1377 } while( $this->wasDeadlock() && --$tries > 0 );
1378 $this->ignoreErrors( $oldIgnore );
1379 if ( $tries <= 0 ) {
1380 $this->query( 'ROLLBACK', $myFname );
1381 $this->reportQueryError( $error, $errno, $sql, $fname );
1382 return false;
1383 } else {
1384 $this->query( 'COMMIT', $myFname );
1385 return $retVal;
1390 * Do a SELECT MASTER_POS_WAIT()
1392 * @param string $file the binlog file
1393 * @param string $pos the binlog position
1394 * @param integer $timeout the maximum number of seconds to wait for synchronisation
1396 function masterPosWait( $file, $pos, $timeout ) {
1397 $fname = 'Database::masterPosWait';
1398 wfProfileIn( $fname );
1401 # Commit any open transactions
1402 $this->immediateCommit();
1404 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
1405 $encFile = $this->strencode( $file );
1406 $sql = "SELECT MASTER_POS_WAIT('$encFile', $pos, $timeout)";
1407 $res = $this->doQuery( $sql );
1408 if ( $res && $row = $this->fetchRow( $res ) ) {
1409 $this->freeResult( $res );
1410 wfProfileOut( $fname );
1411 return $row[0];
1412 } else {
1413 wfProfileOut( $fname );
1414 return false;
1419 * Get the position of the master from SHOW SLAVE STATUS
1421 function getSlavePos() {
1422 $res = $this->query( 'SHOW SLAVE STATUS', 'Database::getSlavePos' );
1423 $row = $this->fetchObject( $res );
1424 if ( $row ) {
1425 return array( $row->Master_Log_File, $row->Read_Master_Log_Pos );
1426 } else {
1427 return array( false, false );
1432 * Get the position of the master from SHOW MASTER STATUS
1434 function getMasterPos() {
1435 $res = $this->query( 'SHOW MASTER STATUS', 'Database::getMasterPos' );
1436 $row = $this->fetchObject( $res );
1437 if ( $row ) {
1438 return array( $row->File, $row->Position );
1439 } else {
1440 return array( false, false );
1445 * Begin a transaction, or if a transaction has already started, continue it
1447 function begin( $fname = 'Database::begin' ) {
1448 if ( !$this->mTrxLevel ) {
1449 $this->immediateBegin( $fname );
1450 } else {
1451 $this->mTrxLevel++;
1456 * End a transaction, or decrement the nest level if transactions are nested
1458 function commit( $fname = 'Database::commit' ) {
1459 if ( $this->mTrxLevel ) {
1460 $this->mTrxLevel--;
1462 if ( !$this->mTrxLevel ) {
1463 $this->immediateCommit( $fname );
1468 * Rollback a transaction
1470 function rollback( $fname = 'Database::rollback' ) {
1471 $this->query( 'ROLLBACK', $fname );
1472 $this->mTrxLevel = 0;
1476 * Begin a transaction, committing any previously open transaction
1478 function immediateBegin( $fname = 'Database::immediateBegin' ) {
1479 $this->query( 'BEGIN', $fname );
1480 $this->mTrxLevel = 1;
1484 * Commit transaction, if one is open
1486 function immediateCommit( $fname = 'Database::immediateCommit' ) {
1487 $this->query( 'COMMIT', $fname );
1488 $this->mTrxLevel = 0;
1492 * Return MW-style timestamp used for MySQL schema
1494 function timestamp( $ts=0 ) {
1495 return wfTimestamp(TS_MW,$ts);
1499 * Local database timestamp format or null
1501 function timestampOrNull( $ts = null ) {
1502 if( is_null( $ts ) ) {
1503 return null;
1504 } else {
1505 return $this->timestamp( $ts );
1510 * @todo document
1512 function resultObject( &$result ) {
1513 if( empty( $result ) ) {
1514 return NULL;
1515 } else {
1516 return new ResultWrapper( $this, $result );
1521 * Return aggregated value alias
1523 function aggregateValue ($valuedata,$valuename='value') {
1524 return $valuename;
1528 * @return string wikitext of a link to the server software's web site
1530 function getSoftwareLink() {
1531 return "[http://www.mysql.com/ MySQL]";
1535 * @return string Version information from the database
1537 function getServerVersion() {
1538 return mysql_get_server_info();
1542 * Ping the server and try to reconnect if it there is no connection
1544 function ping() {
1545 if( function_exists( 'mysql_ping' ) ) {
1546 return mysql_ping( $this->mConn );
1547 } else {
1548 wfDebug( "Tried to call mysql_ping but this is ancient PHP version. Faking it!\n" );
1549 return true;
1554 * Get slave lag.
1555 * At the moment, this will only work if the DB user has the PROCESS privilege
1557 function getLag() {
1558 $res = $this->query( 'SHOW PROCESSLIST' );
1559 # Find slave SQL thread. Assumed to be the second one running, which is a bit
1560 # dubious, but unfortunately there's no easy rigorous way
1561 $slaveThreads = 0;
1562 while ( $row = $this->fetchObject( $res ) ) {
1563 if ( $row->User == 'system user' ) {
1564 if ( ++$slaveThreads == 2 ) {
1565 # This is it, return the time
1566 return $row->Time;
1570 return false;
1574 * Get status information from SHOW STATUS in an associative array
1576 function getStatus() {
1577 $res = $this->query( 'SHOW STATUS' );
1578 $status = array();
1579 while ( $row = $this->fetchObject( $res ) ) {
1580 $status[$row->Variable_name] = $row->Value;
1582 return $status;
1586 * Return the maximum number of items allowed in a list, or 0 for unlimited.
1588 function maxListLen() {
1589 return 0;
1592 function encodeBlob($b) {
1593 return $b;
1596 function notNullTimestamp() {
1597 return "!= 0";
1599 function isNullTimestamp() {
1600 return "= '0'";
1605 * Database abstraction object for mySQL
1606 * Inherit all methods and properties of Database::Database()
1608 * @package MediaWiki
1609 * @see Database
1611 class DatabaseMysql extends Database {
1612 # Inherit all
1617 * Result wrapper for grabbing data queried by someone else
1619 * @package MediaWiki
1621 class ResultWrapper {
1622 var $db, $result;
1625 * @todo document
1627 function ResultWrapper( $database, $result ) {
1628 $this->db =& $database;
1629 $this->result =& $result;
1633 * @todo document
1635 function numRows() {
1636 return $this->db->numRows( $this->result );
1640 * @todo document
1642 function fetchObject() {
1643 return $this->db->fetchObject( $this->result );
1647 * @todo document
1649 function &fetchRow() {
1650 return $this->db->fetchRow( $this->result );
1654 * @todo document
1656 function free() {
1657 $this->db->freeResult( $this->result );
1658 unset( $this->result );
1659 unset( $this->db );
1662 function seek( $row ) {
1663 $this->db->dataSeek( $this->result, $row );
1667 #------------------------------------------------------------------------------
1668 # Global functions
1669 #------------------------------------------------------------------------------
1672 * Standard fail function, called by default when a connection cannot be
1673 * established.
1674 * Displays the file cache if possible
1676 function wfEmergencyAbort( &$conn, $error ) {
1677 global $wgTitle, $wgUseFileCache, $title, $wgInputEncoding, $wgOutputEncoding;
1678 global $wgSitename, $wgServer, $wgMessageCache;
1680 # I give up, Brion is right. Getting the message cache to work when there is no DB is tricky.
1681 # Hard coding strings instead.
1683 $noconnect = 'Sorry! The wiki is experiencing some technical difficulties, and cannot contact the database server: $1. <br />
1684 $1';
1685 $mainpage = 'Main Page';
1686 $searchdisabled = <<<EOT
1687 <p style="margin: 1.5em 2em 1em">$wgSitename search is disabled for performance reasons. You can search via Google in the meantime.
1688 <span style="font-size: 89%; display: block; margin-left: .2em">Note that their indexes of $wgSitename content may be out of date.</span></p>',
1689 EOT;
1691 $googlesearch = "
1692 <!-- SiteSearch Google -->
1693 <FORM method=GET action=\"http://www.google.com/search\">
1694 <TABLE bgcolor=\"#FFFFFF\"><tr><td>
1695 <A HREF=\"http://www.google.com/\">
1696 <IMG SRC=\"http://www.google.com/logos/Logo_40wht.gif\"
1697 border=\"0\" ALT=\"Google\"></A>
1698 </td>
1699 <td>
1700 <INPUT TYPE=text name=q size=31 maxlength=255 value=\"$1\">
1701 <INPUT type=submit name=btnG VALUE=\"Google Search\">
1702 <font size=-1>
1703 <input type=hidden name=domains value=\"$wgServer\"><br /><input type=radio name=sitesearch value=\"\"> WWW <input type=radio name=sitesearch value=\"$wgServer\" checked> $wgServer <br />
1704 <input type='hidden' name='ie' value='$2'>
1705 <input type='hidden' name='oe' value='$2'>
1706 </font>
1707 </td></tr></TABLE>
1708 </FORM>
1709 <!-- SiteSearch Google -->";
1710 $cachederror = "The following is a cached copy of the requested page, and may not be up to date. ";
1713 if( !headers_sent() ) {
1714 header( 'HTTP/1.0 500 Internal Server Error' );
1715 header( 'Content-type: text/html; charset='.$wgOutputEncoding );
1716 /* Don't cache error pages! They cause no end of trouble... */
1717 header( 'Cache-control: none' );
1718 header( 'Pragma: nocache' );
1721 # No database access
1722 $wgMessageCache->disable();
1724 $msg = wfGetSiteNotice();
1725 if($msg == '') {
1726 $msg = str_replace( '$1', $error, $noconnect );
1728 $text = $msg;
1730 if($wgUseFileCache) {
1731 if($wgTitle) {
1732 $t =& $wgTitle;
1733 } else {
1734 if($title) {
1735 $t = Title::newFromURL( $title );
1736 } elseif (@/**/$_REQUEST['search']) {
1737 $search = $_REQUEST['search'];
1738 echo $searchdisabled;
1739 echo str_replace( array( '$1', '$2' ), array( htmlspecialchars( $search ),
1740 $wgInputEncoding ), $googlesearch );
1741 wfErrorExit();
1742 } else {
1743 $t = Title::newFromText( $mainpage );
1747 $cache = new CacheManager( $t );
1748 if( $cache->isFileCached() ) {
1749 $msg = '<p style="color: red"><b>'.$msg."<br />\n" .
1750 $cachederror . "</b></p>\n";
1752 $tag = '<div id="article">';
1753 $text = str_replace(
1754 $tag,
1755 $tag . $msg,
1756 $cache->fetchPageText() );
1760 echo $text;
1761 wfErrorExit();