To language.php 1.645
[mediawiki.git] / includes / Database.php
blobc974d138c5552b70e57f93ee0b144d821da00a9a
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 function setFlag( $flag ) {
140 $this->mFlags |= $flag;
143 function clearFlag( $flag ) {
144 $this->mFlags &= ~$flag;
147 function getFlag( $flag ) {
148 return !!($this->mFlags & $flag);
151 #------------------------------------------------------------------------------
152 # Other functions
153 #------------------------------------------------------------------------------
155 /**#@+
156 * @param string $server database server host
157 * @param string $user database user name
158 * @param string $password database user password
159 * @param string $dbname database name
163 * @param failFunction
164 * @param $flags
165 * @param string $tablePrefix Database table prefixes. By default use the prefix gave in LocalSettings.php
167 function Database( $server = false, $user = false, $password = false, $dbName = false,
168 $failFunction = false, $flags = 0, $tablePrefix = 'get from global' ) {
170 global $wgOut, $wgDBprefix, $wgCommandLineMode;
171 # Can't get a reference if it hasn't been set yet
172 if ( !isset( $wgOut ) ) {
173 $wgOut = NULL;
175 $this->mOut =& $wgOut;
177 $this->mFailFunction = $failFunction;
178 $this->mFlags = $flags;
180 if ( $this->mFlags & DBO_DEFAULT ) {
181 if ( $wgCommandLineMode ) {
182 $this->mFlags &= ~DBO_TRX;
183 } else {
184 $this->mFlags |= DBO_TRX;
189 // Faster read-only access
190 if ( wfReadOnly() ) {
191 $this->mFlags |= DBO_PERSISTENT;
192 $this->mFlags &= ~DBO_TRX;
195 /** Get the default table prefix*/
196 if ( $tablePrefix == 'get from global' ) {
197 $this->mTablePrefix = $wgDBprefix;
198 } else {
199 $this->mTablePrefix = $tablePrefix;
202 if ( $server ) {
203 $this->open( $server, $user, $password, $dbName );
208 * @static
209 * @param failFunction
210 * @param $flags
212 function newFromParams( $server, $user, $password, $dbName,
213 $failFunction = false, $flags = 0 )
215 return new Database( $server, $user, $password, $dbName, $failFunction, $flags );
219 * Usually aborts on failure
220 * If the failFunction is set to a non-zero integer, returns success
222 function open( $server, $user, $password, $dbName ) {
223 # Test for missing mysql.so
224 # First try to load it
225 if (!@extension_loaded('mysql')) {
226 @dl('mysql.so');
229 # Otherwise we get a suppressed fatal error, which is very hard to track down
230 if ( !function_exists( 'mysql_connect' ) ) {
231 die( "MySQL functions missing, have you compiled PHP with the --with-mysql option?\n" );
234 $this->close();
235 $this->mServer = $server;
236 $this->mUser = $user;
237 $this->mPassword = $password;
238 $this->mDBname = $dbName;
240 $success = false;
242 if ( $this->mFlags & DBO_PERSISTENT ) {
243 @/**/$this->mConn = mysql_pconnect( $server, $user, $password );
244 } else {
245 # Create a new connection...
246 if( version_compare( PHP_VERSION, '4.2.0', 'ge' ) ) {
247 @/**/$this->mConn = mysql_connect( $server, $user, $password, true );
248 } else {
249 # On PHP 4.1 the new_link parameter is not available. We cannot
250 # guarantee that we'll actually get a new connection, and this
251 # may cause some operations to fail possibly.
252 @/**/$this->mConn = mysql_connect( $server, $user, $password );
256 if ( $dbName != '' ) {
257 if ( $this->mConn !== false ) {
258 $success = @/**/mysql_select_db( $dbName, $this->mConn );
259 if ( !$success ) {
260 wfDebug( "Error selecting database \"$dbName\": " . $this->lastError() . "\n" );
262 } else {
263 wfDebug( "DB connection error\n" );
264 wfDebug( "Server: $server, User: $user, Password: " .
265 substr( $password, 0, 3 ) . "..., error: " . mysql_error() . "\n" );
266 $success = false;
268 } else {
269 # Delay USE query
270 $success = (bool)$this->mConn;
273 if ( !$success ) {
274 $this->reportConnectionError();
276 $this->mOpened = $success;
277 return $success;
279 /**#@-*/
282 * Closes a database connection.
283 * if it is open : commits any open transactions
285 * @return bool operation success. true if already closed.
287 function close()
289 $this->mOpened = false;
290 if ( $this->mConn ) {
291 if ( $this->trxLevel() ) {
292 $this->immediateCommit();
294 return mysql_close( $this->mConn );
295 } else {
296 return true;
301 * @access private
302 * @param string $msg error message ?
304 function reportConnectionError() {
305 if ( $this->mFailFunction ) {
306 if ( !is_int( $this->mFailFunction ) ) {
307 $ff = $this->mFailFunction;
308 $ff( $this, $this->lastError() );
310 } else {
311 wfEmergencyAbort( $this, $this->lastError() );
316 * Usually aborts on failure
317 * If errors are explicitly ignored, returns success
319 function query( $sql, $fname = '', $tempIgnore = false ) {
320 global $wgProfiling, $wgCommandLineMode;
322 if ( wfReadOnly() ) {
323 # This is a quick check for the most common kinds of write query used
324 # in MediaWiki, to provide extra safety in addition to UI-level checks.
325 # It is not intended to prevent every conceivable write query, or even
326 # to handle such queries gracefully.
327 if ( preg_match( '/^(update|insert|replace|delete)/i', $sql ) ) {
328 wfDebug( "Write query from $fname blocked\n" );
329 return false;
333 if ( $wgProfiling ) {
334 # generalizeSQL will probably cut down the query to reasonable
335 # logging size most of the time. The substr is really just a sanity check.
336 $profName = 'query: ' . $fname . ' ' . substr( Database::generalizeSQL( $sql ), 0, 255 );
337 wfProfileIn( 'Database::query' );
338 wfProfileIn( $profName );
341 $this->mLastQuery = $sql;
343 # Add a comment for easy SHOW PROCESSLIST interpretation
344 if ( $fname ) {
345 $commentedSql = "/* $fname */ $sql";
346 } else {
347 $commentedSql = $sql;
350 # If DBO_TRX is set, start a transaction
351 if ( ( $this->mFlags & DBO_TRX ) && !$this->trxLevel() && $sql != 'BEGIN' ) {
352 $this->begin();
355 if ( $this->debug() ) {
356 $sqlx = substr( $commentedSql, 0, 500 );
357 $sqlx = strtr( $sqlx, "\t\n", ' ' );
358 wfDebug( "SQL: $sqlx\n" );
361 # Do the query and handle errors
362 $ret = $this->doQuery( $commentedSql );
364 # Try reconnecting if the connection was lost
365 if ( false === $ret && ( $this->lastErrno() == 2013 || $this->lastErrno() == 2006 ) ) {
366 # Transaction is gone, like it or not
367 $this->mTrxLevel = 0;
368 wfDebug( "Connection lost, reconnecting...\n" );
369 if ( $this->ping() ) {
370 wfDebug( "Reconnected\n" );
371 $ret = $this->doQuery( $commentedSql );
372 } else {
373 wfDebug( "Failed\n" );
377 if ( false === $ret ) {
378 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
381 if ( $wgProfiling ) {
382 wfProfileOut( $profName );
383 wfProfileOut( 'Database::query' );
385 return $ret;
389 * The DBMS-dependent part of query()
390 * @param string $sql SQL query.
392 function doQuery( $sql ) {
393 if( $this->bufferResults() ) {
394 $ret = mysql_query( $sql, $this->mConn );
395 } else {
396 $ret = mysql_unbuffered_query( $sql, $this->mConn );
398 return $ret;
402 * @param $error
403 * @param $errno
404 * @param $sql
405 * @param string $fname
406 * @param bool $tempIgnore
408 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
409 global $wgCommandLineMode, $wgFullyInitialised;
410 # Ignore errors during error handling to avoid infinite recursion
411 $ignore = $this->ignoreErrors( true );
412 $this->mErrorCount ++;
414 if( $ignore || $tempIgnore ) {
415 wfDebug("SQL ERROR (ignored): " . $error . "\n");
416 } else {
417 $sql1line = str_replace( "\n", "\\n", $sql );
418 wfLogDBError("$fname\t{$this->mServer}\t$errno\t$error\t$sql1line\n");
419 wfDebug("SQL ERROR: " . $error . "\n");
420 if ( $wgCommandLineMode || !$this->mOut || empty( $wgFullyInitialised ) ) {
421 $message = "A database error has occurred\n" .
422 "Query: $sql\n" .
423 "Function: $fname\n" .
424 "Error: $errno $error\n";
425 if ( !$wgCommandLineMode ) {
426 $message = nl2br( $message );
428 wfDebugDieBacktrace( $message );
429 } else {
430 // this calls wfAbruptExit()
431 $this->mOut->databaseError( $fname, $sql, $error, $errno );
434 $this->ignoreErrors( $ignore );
439 * Intended to be compatible with the PEAR::DB wrapper functions.
440 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
442 * ? = scalar value, quoted as necessary
443 * ! = raw SQL bit (a function for instance)
444 * & = filename; reads the file and inserts as a blob
445 * (we don't use this though...)
447 function prepare( $sql, $func = 'Database::prepare' ) {
448 /* MySQL doesn't support prepared statements (yet), so just
449 pack up the query for reference. We'll manually replace
450 the bits later. */
451 return array( 'query' => $sql, 'func' => $func );
454 function freePrepared( $prepared ) {
455 /* No-op for MySQL */
459 * Execute a prepared query with the various arguments
460 * @param string $prepared the prepared sql
461 * @param mixed $args Either an array here, or put scalars as varargs
463 function execute( $prepared, $args = null ) {
464 if( !is_array( $args ) ) {
465 # Pull the var args
466 $args = func_get_args();
467 array_shift( $args );
469 $sql = $this->fillPrepared( $prepared['query'], $args );
470 return $this->query( $sql, $prepared['func'] );
474 * Prepare & execute an SQL statement, quoting and inserting arguments
475 * in the appropriate places.
476 * @param string $query
477 * @param string $args ...
479 function safeQuery( $query, $args = null ) {
480 $prepared = $this->prepare( $query, 'Database::safeQuery' );
481 if( !is_array( $args ) ) {
482 # Pull the var args
483 $args = func_get_args();
484 array_shift( $args );
486 $retval = $this->execute( $prepared, $args );
487 $this->freePrepared( $prepared );
488 return $retval;
492 * For faking prepared SQL statements on DBs that don't support
493 * it directly.
494 * @param string $preparedSql - a 'preparable' SQL statement
495 * @param array $args - array of arguments to fill it with
496 * @return string executable SQL
498 function fillPrepared( $preparedQuery, $args ) {
499 $n = 0;
500 reset( $args );
501 $this->preparedArgs =& $args;
502 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
503 array( &$this, 'fillPreparedArg' ), $preparedQuery );
507 * preg_callback func for fillPrepared()
508 * The arguments should be in $this->preparedArgs and must not be touched
509 * while we're doing this.
511 * @param array $matches
512 * @return string
513 * @access private
515 function fillPreparedArg( $matches ) {
516 switch( $matches[1] ) {
517 case '\\?': return '?';
518 case '\\!': return '!';
519 case '\\&': return '&';
521 list( $n, $arg ) = each( $this->preparedArgs );
522 switch( $matches[1] ) {
523 case '?': return $this->addQuotes( $arg );
524 case '!': return $arg;
525 case '&':
526 # return $this->addQuotes( file_get_contents( $arg ) );
527 wfDebugDieBacktrace( '& mode is not implemented. If it\'s really needed, uncomment the line above.' );
528 default:
529 wfDebugDieBacktrace( 'Received invalid match. This should never happen!' );
533 /**#@+
534 * @param mixed $res A SQL result
537 * Free a result object
539 function freeResult( $res ) {
540 if ( !@/**/mysql_free_result( $res ) ) {
541 wfDebugDieBacktrace( "Unable to free MySQL result\n" );
546 * Fetch the next row from the given result object, in object form
548 function fetchObject( $res ) {
549 @/**/$row = mysql_fetch_object( $res );
550 if( mysql_errno() ) {
551 wfDebugDieBacktrace( 'Error in fetchObject(): ' . htmlspecialchars( mysql_error() ) );
553 return $row;
557 * Fetch the next row from the given result object
558 * Returns an array
560 function fetchRow( $res ) {
561 @/**/$row = mysql_fetch_array( $res );
562 if (mysql_errno() ) {
563 wfDebugDieBacktrace( 'Error in fetchRow(): ' . htmlspecialchars( mysql_error() ) );
565 return $row;
569 * Get the number of rows in a result object
571 function numRows( $res ) {
572 @/**/$n = mysql_num_rows( $res );
573 if( mysql_errno() ) {
574 wfDebugDieBacktrace( 'Error in numRows(): ' . htmlspecialchars( mysql_error() ) );
576 return $n;
580 * Get the number of fields in a result object
581 * See documentation for mysql_num_fields()
583 function numFields( $res ) { return mysql_num_fields( $res ); }
586 * Get a field name in a result object
587 * See documentation for mysql_field_name()
589 function fieldName( $res, $n ) { return mysql_field_name( $res, $n ); }
592 * Get the inserted value of an auto-increment row
594 * The value inserted should be fetched from nextSequenceValue()
596 * Example:
597 * $id = $dbw->nextSequenceValue('page_page_id_seq');
598 * $dbw->insert('page',array('page_id' => $id));
599 * $id = $dbw->insertId();
601 function insertId() { return mysql_insert_id( $this->mConn ); }
604 * Change the position of the cursor in a result object
605 * See mysql_data_seek()
607 function dataSeek( $res, $row ) { return mysql_data_seek( $res, $row ); }
610 * Get the last error number
611 * See mysql_errno()
613 function lastErrno() {
614 if ( $this->mConn ) {
615 return mysql_errno( $this->mConn );
616 } else {
617 return mysql_errno();
622 * Get a description of the last error
623 * See mysql_error() for more details
625 function lastError() {
626 if ( $this->mConn ) {
627 # Even if it's non-zero, it can still be invalid
628 wfSuppressWarnings();
629 $error = mysql_error( $this->mConn );
630 if ( !$error ) {
631 $error = mysql_error();
633 wfRestoreWarnings();
634 } else {
635 $error = mysql_error();
637 if( $error ) {
638 $error .= ' (' . $this->mServer . ')';
640 return $error;
643 * Get the number of rows affected by the last write query
644 * See mysql_affected_rows() for more details
646 function affectedRows() { return mysql_affected_rows( $this->mConn ); }
647 /**#@-*/ // end of template : @param $result
650 * Simple UPDATE wrapper
651 * Usually aborts on failure
652 * If errors are explicitly ignored, returns success
654 * This function exists for historical reasons, Database::update() has a more standard
655 * calling convention and feature set
657 function set( $table, $var, $value, $cond, $fname = 'Database::set' )
659 $table = $this->tableName( $table );
660 $sql = "UPDATE $table SET $var = '" .
661 $this->strencode( $value ) . "' WHERE ($cond)";
662 return (bool)$this->query( $sql, DB_MASTER, $fname );
666 * Simple SELECT wrapper, returns a single field, input must be encoded
667 * Usually aborts on failure
668 * If errors are explicitly ignored, returns FALSE on failure
670 function selectField( $table, $var, $cond='', $fname = 'Database::selectField', $options = array() ) {
671 if ( !is_array( $options ) ) {
672 $options = array( $options );
674 $options['LIMIT'] = 1;
676 $res = $this->select( $table, $var, $cond, $fname, $options );
677 if ( $res === false || !$this->numRows( $res ) ) {
678 return false;
680 $row = $this->fetchRow( $res );
681 if ( $row !== false ) {
682 $this->freeResult( $res );
683 return $row[0];
684 } else {
685 return false;
690 * Returns an optional USE INDEX clause to go after the table, and a
691 * string to go at the end of the query
693 * @access private
695 * @param array $options an associative array of options to be turned into
696 * an SQL query, valid keys are listed in the function.
697 * @return array
699 function makeSelectOptions( $options ) {
700 $tailOpts = '';
702 if ( isset( $options['GROUP BY'] ) ) {
703 $tailOpts .= " GROUP BY {$options['GROUP BY']}";
705 if ( isset( $options['ORDER BY'] ) ) {
706 $tailOpts .= " ORDER BY {$options['ORDER BY']}";
708 if (isset($options['LIMIT'])) {
709 $tailOpts .= $this->limitResult('', $options['LIMIT'],
710 isset($options['OFFSET']) ? $options['OFFSET'] : false);
712 if ( is_numeric( array_search( 'FOR UPDATE', $options ) ) ) {
713 $tailOpts .= ' FOR UPDATE';
716 if ( is_numeric( array_search( 'LOCK IN SHARE MODE', $options ) ) ) {
717 $tailOpts .= ' LOCK IN SHARE MODE';
720 if ( isset( $options['USE INDEX'] ) ) {
721 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
722 } else {
723 $useIndex = '';
725 return array( $useIndex, $tailOpts );
729 * SELECT wrapper
731 function select( $table, $vars, $conds='', $fname = 'Database::select', $options = array() )
733 if( is_array( $vars ) ) {
734 $vars = implode( ',', $vars );
736 if( !is_array( $options ) ) {
737 $options = array( $options );
739 if( is_array( $table ) ) {
740 $from = ' FROM ' . implode( ',', array_map( array( &$this, 'tableName' ), $table ) );
741 } elseif ($table!='') {
742 $from = ' FROM ' .$this->tableName( $table );
743 } else {
744 $from = '';
747 list( $useIndex, $tailOpts ) = $this->makeSelectOptions( $options );
749 if( !empty( $conds ) ) {
750 if ( is_array( $conds ) ) {
751 $conds = $this->makeList( $conds, LIST_AND );
753 $sql = "SELECT $vars $from $useIndex WHERE $conds $tailOpts";
754 } else {
755 $sql = "SELECT $vars $from $useIndex $tailOpts";
758 return $this->query( $sql, $fname );
762 * Single row SELECT wrapper
763 * Aborts or returns FALSE on error
765 * $vars: the selected variables
766 * $conds: a condition map, terms are ANDed together.
767 * Items with numeric keys are taken to be literal conditions
768 * Takes an array of selected variables, and a condition map, which is ANDed
769 * e.g: selectRow( "page", array( "page_id" ), array( "page_namespace" =>
770 * NS_MAIN, "page_title" => "Astronomy" ) ) would return an object where
771 * $obj- >page_id is the ID of the Astronomy article
773 * @todo migrate documentation to phpdocumentor format
775 function selectRow( $table, $vars, $conds, $fname = 'Database::selectRow', $options = array() ) {
776 $options['LIMIT'] = 1;
777 $res = $this->select( $table, $vars, $conds, $fname, $options );
778 if ( $res === false )
779 return false;
780 if ( !$this->numRows($res) ) {
781 $this->freeResult($res);
782 return false;
784 $obj = $this->fetchObject( $res );
785 $this->freeResult( $res );
786 return $obj;
791 * Removes most variables from an SQL query and replaces them with X or N for numbers.
792 * It's only slightly flawed. Don't use for anything important.
794 * @param string $sql A SQL Query
795 * @static
797 function generalizeSQL( $sql ) {
798 # This does the same as the regexp below would do, but in such a way
799 # as to avoid crashing php on some large strings.
800 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
802 $sql = str_replace ( "\\\\", '', $sql);
803 $sql = str_replace ( "\\'", '', $sql);
804 $sql = str_replace ( "\\\"", '', $sql);
805 $sql = preg_replace ("/'.*'/s", "'X'", $sql);
806 $sql = preg_replace ('/".*"/s', "'X'", $sql);
808 # All newlines, tabs, etc replaced by single space
809 $sql = preg_replace ( "/\s+/", ' ', $sql);
811 # All numbers => N
812 $sql = preg_replace ('/-?[0-9]+/s', 'N', $sql);
814 return $sql;
818 * Determines whether a field exists in a table
819 * Usually aborts on failure
820 * If errors are explicitly ignored, returns NULL on failure
822 function fieldExists( $table, $field, $fname = 'Database::fieldExists' ) {
823 $table = $this->tableName( $table );
824 $res = $this->query( 'DESCRIBE '.$table, DB_SLAVE, $fname );
825 if ( !$res ) {
826 return NULL;
829 $found = false;
831 while ( $row = $this->fetchObject( $res ) ) {
832 if ( $row->Field == $field ) {
833 $found = true;
834 break;
837 return $found;
841 * Determines whether an index exists
842 * Usually aborts on failure
843 * If errors are explicitly ignored, returns NULL on failure
845 function indexExists( $table, $index, $fname = 'Database::indexExists' ) {
846 $info = $this->indexInfo( $table, $index, $fname );
847 if ( is_null( $info ) ) {
848 return NULL;
849 } else {
850 return $info !== false;
856 * Get information about an index into an object
857 * Returns false if the index does not exist
859 function indexInfo( $table, $index, $fname = 'Database::indexInfo' ) {
860 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
861 # SHOW INDEX should work for 3.x and up:
862 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
863 $table = $this->tableName( $table );
864 $sql = 'SHOW INDEX FROM '.$table;
865 $res = $this->query( $sql, $fname );
866 if ( !$res ) {
867 return NULL;
870 while ( $row = $this->fetchObject( $res ) ) {
871 if ( $row->Key_name == $index ) {
872 return $row;
875 return false;
879 * Query whether a given table exists
881 function tableExists( $table ) {
882 $table = $this->tableName( $table );
883 $old = $this->ignoreErrors( true );
884 $res = $this->query( "SELECT 1 FROM $table LIMIT 1" );
885 $this->ignoreErrors( $old );
886 if( $res ) {
887 $this->freeResult( $res );
888 return true;
889 } else {
890 return false;
895 * mysql_fetch_field() wrapper
896 * Returns false if the field doesn't exist
898 * @param $table
899 * @param $field
901 function fieldInfo( $table, $field ) {
902 $table = $this->tableName( $table );
903 $res = $this->query( "SELECT * FROM $table LIMIT 1" );
904 $n = mysql_num_fields( $res );
905 for( $i = 0; $i < $n; $i++ ) {
906 $meta = mysql_fetch_field( $res, $i );
907 if( $field == $meta->name ) {
908 return $meta;
911 return false;
915 * mysql_field_type() wrapper
917 function fieldType( $res, $index ) {
918 return mysql_field_type( $res, $index );
922 * Determines if a given index is unique
924 function indexUnique( $table, $index ) {
925 $indexInfo = $this->indexInfo( $table, $index );
926 if ( !$indexInfo ) {
927 return NULL;
929 return !$indexInfo->Non_unique;
933 * INSERT wrapper, inserts an array into a table
935 * $a may be a single associative array, or an array of these with numeric keys, for
936 * multi-row insert.
938 * Usually aborts on failure
939 * If errors are explicitly ignored, returns success
941 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
942 # No rows to insert, easy just return now
943 if ( !count( $a ) ) {
944 return true;
947 $table = $this->tableName( $table );
948 if ( !is_array( $options ) ) {
949 $options = array( $options );
951 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
952 $multi = true;
953 $keys = array_keys( $a[0] );
954 } else {
955 $multi = false;
956 $keys = array_keys( $a );
959 $sql = 'INSERT ' . implode( ' ', $options ) .
960 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
962 if ( $multi ) {
963 $first = true;
964 foreach ( $a as $row ) {
965 if ( $first ) {
966 $first = false;
967 } else {
968 $sql .= ',';
970 $sql .= '(' . $this->makeList( $row ) . ')';
972 } else {
973 $sql .= '(' . $this->makeList( $a ) . ')';
975 return (bool)$this->query( $sql, $fname );
979 * Make UPDATE options for the Database::update function
981 * @access private
982 * @param array $options The options passed to Database::update
983 * @return string
985 function makeUpdateOptions( $options ) {
986 if( !is_array( $options ) ) {
987 $options = array( $options );
989 $opts = array();
990 if ( in_array( 'LOW_PRIORITY', $options ) )
991 $opts[] = $this->lowPriorityOption();
992 if ( in_array( 'IGNORE', $options ) )
993 $opts[] = 'IGNORE';
994 return implode(' ', $opts);
998 * UPDATE wrapper, takes a condition array and a SET array
1000 * @param string $table The table to UPDATE
1001 * @param array $values An array of values to SET
1002 * @param array $conds An array of conditions (WHERE)
1003 * @param string $fname The Class::Function calling this function
1004 * (for the log)
1005 * @param array $options An array of UPDATE options, can be one or
1006 * more of IGNORE, LOW_PRIORITY
1008 function update( $table, $values, $conds, $fname = 'Database::update', $options = array() ) {
1009 $table = $this->tableName( $table );
1010 $opts = $this->makeUpdateOptions( $options );
1011 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET );
1012 if ( $conds != '*' ) {
1013 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND );
1015 $this->query( $sql, $fname );
1019 * Makes a wfStrencoded list from an array
1020 * $mode: LIST_COMMA - comma separated, no field names
1021 * LIST_AND - ANDed WHERE clause (without the WHERE)
1022 * LIST_SET - comma separated with field names, like a SET clause
1023 * LIST_NAMES - comma separated field names
1025 function makeList( $a, $mode = LIST_COMMA ) {
1026 if ( !is_array( $a ) ) {
1027 wfDebugDieBacktrace( 'Database::makeList called with incorrect parameters' );
1030 $first = true;
1031 $list = '';
1032 foreach ( $a as $field => $value ) {
1033 if ( !$first ) {
1034 if ( $mode == LIST_AND ) {
1035 $list .= ' AND ';
1036 } else {
1037 $list .= ',';
1039 } else {
1040 $first = false;
1042 if ( $mode == LIST_AND && is_numeric( $field ) ) {
1043 $list .= "($value)";
1044 } elseif ( $mode == LIST_AND && is_array ($value) ) {
1045 $list .= $field." IN (".$this->makeList($value).") ";
1046 } else {
1047 if ( $mode == LIST_AND || $mode == LIST_SET ) {
1048 $list .= "$field = ";
1050 $list .= $mode == LIST_NAMES ? $value : $this->addQuotes( $value );
1053 return $list;
1057 * Change the current database
1059 function selectDB( $db ) {
1060 $this->mDBname = $db;
1061 return mysql_select_db( $db, $this->mConn );
1065 * Starts a timer which will kill the DB thread after $timeout seconds
1067 function startTimer( $timeout ) {
1068 global $IP;
1069 if( function_exists( 'mysql_thread_id' ) ) {
1070 # This will kill the query if it's still running after $timeout seconds.
1071 $tid = mysql_thread_id( $this->mConn );
1072 exec( "php $IP/includes/killthread.php $timeout $tid &>/dev/null &" );
1077 * Stop a timer started by startTimer()
1078 * Currently unimplemented.
1081 function stopTimer() { }
1084 * Format a table name ready for use in constructing an SQL query
1086 * This does two important things: it quotes table names which as necessary,
1087 * and it adds a table prefix if there is one.
1089 * All functions of this object which require a table name call this function
1090 * themselves. Pass the canonical name to such functions. This is only needed
1091 * when calling query() directly.
1093 * @param string $name database table name
1095 function tableName( $name ) {
1096 global $wgSharedDB;
1097 # Skip quoted literals
1098 if ( $name{0} != '`' ) {
1099 if ( $this->mTablePrefix !== '' && strpos( '.', $name ) === false ) {
1100 $name = "{$this->mTablePrefix}$name";
1102 if ( isset( $wgSharedDB ) && "{$this->mTablePrefix}user" == $name ) {
1103 $name = "`$wgSharedDB`.`$name`";
1104 } else {
1105 # Standard quoting
1106 $name = "`$name`";
1109 return $name;
1113 * Fetch a number of table names into an array
1114 * This is handy when you need to construct SQL for joins
1116 * Example:
1117 * extract($dbr->tableNames('user','watchlist'));
1118 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1119 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1121 function tableNames() {
1122 $inArray = func_get_args();
1123 $retVal = array();
1124 foreach ( $inArray as $name ) {
1125 $retVal[$name] = $this->tableName( $name );
1127 return $retVal;
1131 * Wrapper for addslashes()
1132 * @param string $s String to be slashed.
1133 * @return string slashed string.
1135 function strencode( $s ) {
1136 return addslashes( $s );
1140 * If it's a string, adds quotes and backslashes
1141 * Otherwise returns as-is
1143 function addQuotes( $s ) {
1144 if ( is_null( $s ) ) {
1145 return 'NULL';
1146 } else {
1147 # This will also quote numeric values. This should be harmless,
1148 # and protects against weird problems that occur when they really
1149 # _are_ strings such as article titles and string->number->string
1150 # conversion is not 1:1.
1151 return "'" . $this->strencode( $s ) . "'";
1156 * Escape string for safe LIKE usage
1158 function escapeLike( $s ) {
1159 $s=$this->strencode( $s );
1160 $s=str_replace(array('%','_'),array('\%','\_'),$s);
1161 return $s;
1165 * Returns an appropriately quoted sequence value for inserting a new row.
1166 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
1167 * subclass will return an integer, and save the value for insertId()
1169 function nextSequenceValue( $seqName ) {
1170 return NULL;
1174 * USE INDEX clause
1175 * PostgreSQL doesn't have them and returns ""
1177 function useIndexClause( $index ) {
1178 global $wgDBmysql4;
1179 return $wgDBmysql4
1180 ? "FORCE INDEX ($index)"
1181 : "USE INDEX ($index)";
1185 * REPLACE query wrapper
1186 * PostgreSQL simulates this with a DELETE followed by INSERT
1187 * $row is the row to insert, an associative array
1188 * $uniqueIndexes is an array of indexes. Each element may be either a
1189 * field name or an array of field names
1191 * It may be more efficient to leave off unique indexes which are unlikely to collide.
1192 * However if you do this, you run the risk of encountering errors which wouldn't have
1193 * occurred in MySQL
1195 * @todo migrate comment to phodocumentor format
1197 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
1198 $table = $this->tableName( $table );
1200 # Single row case
1201 if ( !is_array( reset( $rows ) ) ) {
1202 $rows = array( $rows );
1205 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) .') VALUES ';
1206 $first = true;
1207 foreach ( $rows as $row ) {
1208 if ( $first ) {
1209 $first = false;
1210 } else {
1211 $sql .= ',';
1213 $sql .= '(' . $this->makeList( $row ) . ')';
1215 return $this->query( $sql, $fname );
1219 * DELETE where the condition is a join
1220 * MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
1222 * For safety, an empty $conds will not delete everything. If you want to delete all rows where the
1223 * join condition matches, set $conds='*'
1225 * DO NOT put the join condition in $conds
1227 * @param string $delTable The table to delete from.
1228 * @param string $joinTable The other table.
1229 * @param string $delVar The variable to join on, in the first table.
1230 * @param string $joinVar The variable to join on, in the second table.
1231 * @param array $conds Condition array of field names mapped to variables, ANDed together in the WHERE clause
1233 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'Database::deleteJoin' ) {
1234 if ( !$conds ) {
1235 wfDebugDieBacktrace( 'Database::deleteJoin() called with empty $conds' );
1238 $delTable = $this->tableName( $delTable );
1239 $joinTable = $this->tableName( $joinTable );
1240 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1241 if ( $conds != '*' ) {
1242 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND );
1245 return $this->query( $sql, $fname );
1249 * Returns the size of a text field, or -1 for "unlimited"
1251 function textFieldSize( $table, $field ) {
1252 $table = $this->tableName( $table );
1253 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
1254 $res = $this->query( $sql, 'Database::textFieldSize' );
1255 $row = $this->fetchObject( $res );
1256 $this->freeResult( $res );
1258 if ( preg_match( "/\((.*)\)/", $row->Type, $m ) ) {
1259 $size = $m[1];
1260 } else {
1261 $size = -1;
1263 return $size;
1267 * @return string Returns the text of the low priority option if it is supported, or a blank string otherwise
1269 function lowPriorityOption() {
1270 return 'LOW_PRIORITY';
1274 * DELETE query wrapper
1276 * Use $conds == "*" to delete all rows
1278 function delete( $table, $conds, $fname = 'Database::delete' ) {
1279 if ( !$conds ) {
1280 wfDebugDieBacktrace( 'Database::delete() called with no conditions' );
1282 $table = $this->tableName( $table );
1283 $sql = "DELETE FROM $table";
1284 if ( $conds != '*' ) {
1285 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
1287 return $this->query( $sql, $fname );
1291 * INSERT SELECT wrapper
1292 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
1293 * Source items may be literals rather than field names, but strings should be quoted with Database::addQuotes()
1294 * $conds may be "*" to copy the whole table
1295 * srcTable may be an array of tables.
1297 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'Database::insertSelect' ) {
1298 $destTable = $this->tableName( $destTable );
1299 if( is_array( $srcTable ) ) {
1300 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
1301 } else {
1302 $srcTable = $this->tableName( $srcTable );
1304 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
1305 ' SELECT ' . implode( ',', $varMap ) .
1306 " FROM $srcTable";
1307 if ( $conds != '*' ) {
1308 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
1310 return $this->query( $sql, $fname );
1314 * Construct a LIMIT query with optional offset
1315 * This is used for query pages
1316 * $sql string SQL query we will append the limit too
1317 * $limit integer the SQL limit
1318 * $offset integer the SQL offset (default false)
1320 function limitResult($sql, $limit, $offset=false) {
1321 return " $sql LIMIT ".((is_numeric($offset) && $offset != 0)?"{$offset},":"")."{$limit} ";
1323 function limitResultForUpdate($sql, $num) {
1324 return $this->limitResult($sql, $num, 0);
1328 * Returns an SQL expression for a simple conditional.
1329 * Uses IF on MySQL.
1331 * @param string $cond SQL expression which will result in a boolean value
1332 * @param string $trueVal SQL expression to return if true
1333 * @param string $falseVal SQL expression to return if false
1334 * @return string SQL fragment
1336 function conditional( $cond, $trueVal, $falseVal ) {
1337 return " IF($cond, $trueVal, $falseVal) ";
1341 * Determines if the last failure was due to a deadlock
1343 function wasDeadlock() {
1344 return $this->lastErrno() == 1213;
1348 * Perform a deadlock-prone transaction.
1350 * This function invokes a callback function to perform a set of write
1351 * queries. If a deadlock occurs during the processing, the transaction
1352 * will be rolled back and the callback function will be called again.
1354 * Usage:
1355 * $dbw->deadlockLoop( callback, ... );
1357 * Extra arguments are passed through to the specified callback function.
1359 * Returns whatever the callback function returned on its successful,
1360 * iteration, or false on error, for example if the retry limit was
1361 * reached.
1363 function deadlockLoop() {
1364 $myFname = 'Database::deadlockLoop';
1366 $this->begin();
1367 $args = func_get_args();
1368 $function = array_shift( $args );
1369 $oldIgnore = $this->ignoreErrors( true );
1370 $tries = DEADLOCK_TRIES;
1371 if ( is_array( $function ) ) {
1372 $fname = $function[0];
1373 } else {
1374 $fname = $function;
1376 do {
1377 $retVal = call_user_func_array( $function, $args );
1378 $error = $this->lastError();
1379 $errno = $this->lastErrno();
1380 $sql = $this->lastQuery();
1382 if ( $errno ) {
1383 if ( $this->wasDeadlock() ) {
1384 # Retry
1385 usleep( mt_rand( DEADLOCK_DELAY_MIN, DEADLOCK_DELAY_MAX ) );
1386 } else {
1387 $this->reportQueryError( $error, $errno, $sql, $fname );
1390 } while( $this->wasDeadlock() && --$tries > 0 );
1391 $this->ignoreErrors( $oldIgnore );
1392 if ( $tries <= 0 ) {
1393 $this->query( 'ROLLBACK', $myFname );
1394 $this->reportQueryError( $error, $errno, $sql, $fname );
1395 return false;
1396 } else {
1397 $this->query( 'COMMIT', $myFname );
1398 return $retVal;
1403 * Do a SELECT MASTER_POS_WAIT()
1405 * @param string $file the binlog file
1406 * @param string $pos the binlog position
1407 * @param integer $timeout the maximum number of seconds to wait for synchronisation
1409 function masterPosWait( $file, $pos, $timeout ) {
1410 $fname = 'Database::masterPosWait';
1411 wfProfileIn( $fname );
1414 # Commit any open transactions
1415 $this->immediateCommit();
1417 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
1418 $encFile = $this->strencode( $file );
1419 $sql = "SELECT MASTER_POS_WAIT('$encFile', $pos, $timeout)";
1420 $res = $this->doQuery( $sql );
1421 if ( $res && $row = $this->fetchRow( $res ) ) {
1422 $this->freeResult( $res );
1423 wfProfileOut( $fname );
1424 return $row[0];
1425 } else {
1426 wfProfileOut( $fname );
1427 return false;
1432 * Get the position of the master from SHOW SLAVE STATUS
1434 function getSlavePos() {
1435 $res = $this->query( 'SHOW SLAVE STATUS', 'Database::getSlavePos' );
1436 $row = $this->fetchObject( $res );
1437 if ( $row ) {
1438 return array( $row->Master_Log_File, $row->Read_Master_Log_Pos );
1439 } else {
1440 return array( false, false );
1445 * Get the position of the master from SHOW MASTER STATUS
1447 function getMasterPos() {
1448 $res = $this->query( 'SHOW MASTER STATUS', 'Database::getMasterPos' );
1449 $row = $this->fetchObject( $res );
1450 if ( $row ) {
1451 return array( $row->File, $row->Position );
1452 } else {
1453 return array( false, false );
1458 * Begin a transaction, or if a transaction has already started, continue it
1460 function begin( $fname = 'Database::begin' ) {
1461 if ( !$this->mTrxLevel ) {
1462 $this->immediateBegin( $fname );
1463 } else {
1464 $this->mTrxLevel++;
1469 * End a transaction, or decrement the nest level if transactions are nested
1471 function commit( $fname = 'Database::commit' ) {
1472 if ( $this->mTrxLevel ) {
1473 $this->mTrxLevel--;
1475 if ( !$this->mTrxLevel ) {
1476 $this->immediateCommit( $fname );
1481 * Rollback a transaction
1483 function rollback( $fname = 'Database::rollback' ) {
1484 $this->query( 'ROLLBACK', $fname );
1485 $this->mTrxLevel = 0;
1489 * Begin a transaction, committing any previously open transaction
1491 function immediateBegin( $fname = 'Database::immediateBegin' ) {
1492 $this->query( 'BEGIN', $fname );
1493 $this->mTrxLevel = 1;
1497 * Commit transaction, if one is open
1499 function immediateCommit( $fname = 'Database::immediateCommit' ) {
1500 $this->query( 'COMMIT', $fname );
1501 $this->mTrxLevel = 0;
1505 * Return MW-style timestamp used for MySQL schema
1507 function timestamp( $ts=0 ) {
1508 return wfTimestamp(TS_MW,$ts);
1512 * Local database timestamp format or null
1514 function timestampOrNull( $ts = null ) {
1515 if( is_null( $ts ) ) {
1516 return null;
1517 } else {
1518 return $this->timestamp( $ts );
1523 * @todo document
1525 function resultObject( &$result ) {
1526 if( empty( $result ) ) {
1527 return NULL;
1528 } else {
1529 return new ResultWrapper( $this, $result );
1534 * Return aggregated value alias
1536 function aggregateValue ($valuedata,$valuename='value') {
1537 return $valuename;
1541 * @return string wikitext of a link to the server software's web site
1543 function getSoftwareLink() {
1544 return "[http://www.mysql.com/ MySQL]";
1548 * @return string Version information from the database
1550 function getServerVersion() {
1551 return mysql_get_server_info();
1555 * Ping the server and try to reconnect if it there is no connection
1557 function ping() {
1558 if( function_exists( 'mysql_ping' ) ) {
1559 return mysql_ping( $this->mConn );
1560 } else {
1561 wfDebug( "Tried to call mysql_ping but this is ancient PHP version. Faking it!\n" );
1562 return true;
1567 * Get slave lag.
1568 * At the moment, this will only work if the DB user has the PROCESS privilege
1570 function getLag() {
1571 $res = $this->query( 'SHOW PROCESSLIST' );
1572 # Find slave SQL thread. Assumed to be the second one running, which is a bit
1573 # dubious, but unfortunately there's no easy rigorous way
1574 $slaveThreads = 0;
1575 while ( $row = $this->fetchObject( $res ) ) {
1576 if ( $row->User == 'system user' ) {
1577 if ( ++$slaveThreads == 2 ) {
1578 # This is it, return the time
1579 return $row->Time;
1583 return false;
1587 * Get status information from SHOW STATUS in an associative array
1589 function getStatus() {
1590 $res = $this->query( 'SHOW STATUS' );
1591 $status = array();
1592 while ( $row = $this->fetchObject( $res ) ) {
1593 $status[$row->Variable_name] = $row->Value;
1595 return $status;
1599 * Return the maximum number of items allowed in a list, or 0 for unlimited.
1601 function maxListLen() {
1602 return 0;
1605 function encodeBlob($b) {
1606 return $b;
1609 function notNullTimestamp() {
1610 return "!= 0";
1612 function isNullTimestamp() {
1613 return "= '0'";
1618 * Database abstraction object for mySQL
1619 * Inherit all methods and properties of Database::Database()
1621 * @package MediaWiki
1622 * @see Database
1624 class DatabaseMysql extends Database {
1625 # Inherit all
1630 * Result wrapper for grabbing data queried by someone else
1632 * @package MediaWiki
1634 class ResultWrapper {
1635 var $db, $result;
1638 * @todo document
1640 function ResultWrapper( $database, $result ) {
1641 $this->db =& $database;
1642 $this->result =& $result;
1646 * @todo document
1648 function numRows() {
1649 return $this->db->numRows( $this->result );
1653 * @todo document
1655 function fetchObject() {
1656 return $this->db->fetchObject( $this->result );
1660 * @todo document
1662 function &fetchRow() {
1663 return $this->db->fetchRow( $this->result );
1667 * @todo document
1669 function free() {
1670 $this->db->freeResult( $this->result );
1671 unset( $this->result );
1672 unset( $this->db );
1675 function seek( $row ) {
1676 $this->db->dataSeek( $this->result, $row );
1680 #------------------------------------------------------------------------------
1681 # Global functions
1682 #------------------------------------------------------------------------------
1685 * Standard fail function, called by default when a connection cannot be
1686 * established.
1687 * Displays the file cache if possible
1689 function wfEmergencyAbort( &$conn, $error ) {
1690 global $wgTitle, $wgUseFileCache, $title, $wgInputEncoding, $wgOutputEncoding;
1691 global $wgSitename, $wgServer, $wgMessageCache;
1693 # I give up, Brion is right. Getting the message cache to work when there is no DB is tricky.
1694 # Hard coding strings instead.
1696 $noconnect = 'Sorry! The wiki is experiencing some technical difficulties, and cannot contact the database server: $1. <br />
1697 $1';
1698 $mainpage = 'Main Page';
1699 $searchdisabled = <<<EOT
1700 <p style="margin: 1.5em 2em 1em">$wgSitename search is disabled for performance reasons. You can search via Google in the meantime.
1701 <span style="font-size: 89%; display: block; margin-left: .2em">Note that their indexes of $wgSitename content may be out of date.</span></p>',
1702 EOT;
1704 $googlesearch = "
1705 <!-- SiteSearch Google -->
1706 <FORM method=GET action=\"http://www.google.com/search\">
1707 <TABLE bgcolor=\"#FFFFFF\"><tr><td>
1708 <A HREF=\"http://www.google.com/\">
1709 <IMG SRC=\"http://www.google.com/logos/Logo_40wht.gif\"
1710 border=\"0\" ALT=\"Google\"></A>
1711 </td>
1712 <td>
1713 <INPUT TYPE=text name=q size=31 maxlength=255 value=\"$1\">
1714 <INPUT type=submit name=btnG VALUE=\"Google Search\">
1715 <font size=-1>
1716 <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 />
1717 <input type='hidden' name='ie' value='$2'>
1718 <input type='hidden' name='oe' value='$2'>
1719 </font>
1720 </td></tr></TABLE>
1721 </FORM>
1722 <!-- SiteSearch Google -->";
1723 $cachederror = "The following is a cached copy of the requested page, and may not be up to date. ";
1726 if( !headers_sent() ) {
1727 header( 'HTTP/1.0 500 Internal Server Error' );
1728 header( 'Content-type: text/html; charset='.$wgOutputEncoding );
1729 /* Don't cache error pages! They cause no end of trouble... */
1730 header( 'Cache-control: none' );
1731 header( 'Pragma: nocache' );
1734 # No database access
1735 $wgMessageCache->disable();
1737 $msg = wfGetSiteNotice();
1738 if($msg == '') {
1739 $msg = str_replace( '$1', $error, $noconnect );
1741 $text = $msg;
1743 if($wgUseFileCache) {
1744 if($wgTitle) {
1745 $t =& $wgTitle;
1746 } else {
1747 if($title) {
1748 $t = Title::newFromURL( $title );
1749 } elseif (@/**/$_REQUEST['search']) {
1750 $search = $_REQUEST['search'];
1751 echo $searchdisabled;
1752 echo str_replace( array( '$1', '$2' ), array( htmlspecialchars( $search ),
1753 $wgInputEncoding ), $googlesearch );
1754 wfErrorExit();
1755 } else {
1756 $t = Title::newFromText( $mainpage );
1760 $cache = new CacheManager( $t );
1761 if( $cache->isFileCached() ) {
1762 $msg = '<p style="color: red"><b>'.$msg."<br />\n" .
1763 $cachederror . "</b></p>\n";
1765 $tag = '<div id="article">';
1766 $text = str_replace(
1767 $tag,
1768 $tag . $msg,
1769 $cache->fetchPageText() );
1773 echo $text;
1774 wfErrorExit();