Automatic reconnect when the connection is lost. This hopefully won't happen much...
[lhc/web/wiklou.git] / includes / Database.php
1 <?php
2 /**
3 * This file deals with MySQL interface functions
4 * and query specifics/optimisations
5 * @package MediaWiki
6 */
7
8 /**
9 * Depends on the CacheManager
10 */
11 require_once( 'CacheManager.php' );
12
13 /** See Database::makeList() */
14 define( 'LIST_COMMA', 0 );
15 define( 'LIST_AND', 1 );
16 define( 'LIST_SET', 2 );
17 define( 'LIST_NAMES', 3);
18
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 );
25
26 /**
27 * Database abstraction object
28 * @package MediaWiki
29 */
30 class Database {
31
32 #------------------------------------------------------------------------------
33 # Variables
34 #------------------------------------------------------------------------------
35 /**#@+
36 * @access private
37 */
38 var $mLastQuery = '';
39
40 var $mServer, $mUser, $mPassword, $mConn, $mDBname;
41 var $mOut, $mOpened = false;
42
43 var $mFailFunction;
44 var $mTablePrefix;
45 var $mFlags;
46 var $mTrxLevel = 0;
47 /**#@-*/
48
49 #------------------------------------------------------------------------------
50 # Accessors
51 #------------------------------------------------------------------------------
52 # These optionally set a variable and return the previous state
53
54 /**
55 * Fail function, takes a Database as a parameter
56 * Set to false for default, 1 for ignore errors
57 */
58 function failFunction( $function = NULL ) {
59 return wfSetVar( $this->mFailFunction, $function );
60 }
61
62 /**
63 * Output page, used for reporting errors
64 * FALSE means discard output
65 */
66 function &setOutputPage( &$out ) {
67 $this->mOut =& $out;
68 }
69
70 /**
71 * Boolean, controls output of large amounts of debug information
72 */
73 function debug( $debug = NULL ) {
74 return wfSetBit( $this->mFlags, DBO_DEBUG, $debug );
75 }
76
77 /**
78 * Turns buffering of SQL result sets on (true) or off (false).
79 * Default is "on" and it should not be changed without good reasons.
80 */
81 function bufferResults( $buffer = NULL ) {
82 if ( is_null( $buffer ) ) {
83 return !(bool)( $this->mFlags & DBO_NOBUFFER );
84 } else {
85 return !wfSetBit( $this->mFlags, DBO_NOBUFFER, !$buffer );
86 }
87 }
88
89 /**
90 * Turns on (false) or off (true) the automatic generation and sending
91 * of a "we're sorry, but there has been a database error" page on
92 * database errors. Default is on (false). When turned off, the
93 * code should use wfLastErrno() and wfLastError() to handle the
94 * situation as appropriate.
95 */
96 function ignoreErrors( $ignoreErrors = NULL ) {
97 return wfSetBit( $this->mFlags, DBO_IGNORE, $ignoreErrors );
98 }
99
100 /**
101 * The current depth of nested transactions
102 * @param integer $level
103 */
104 function trxLevel( $level = NULL ) {
105 return wfSetVar( $this->mTrxLevel, $level );
106 }
107
108 /**#@+
109 * Get function
110 */
111 function lastQuery() { return $this->mLastQuery; }
112 function isOpen() { return $this->mOpened; }
113 /**#@-*/
114
115 #------------------------------------------------------------------------------
116 # Other functions
117 #------------------------------------------------------------------------------
118
119 /**#@+
120 * @param string $server database server host
121 * @param string $user database user name
122 * @param string $password database user password
123 * @param string $dbname database name
124 */
125
126 /**
127 * @param failFunction
128 * @param $flags
129 * @param string $tablePrefix Database table prefixes. By default use the prefix gave in LocalSettings.php
130 */
131 function Database( $server = false, $user = false, $password = false, $dbName = false,
132 $failFunction = false, $flags = 0, $tablePrefix = 'get from global' ) {
133
134 global $wgOut, $wgDBprefix, $wgCommandLineMode;
135 # Can't get a reference if it hasn't been set yet
136 if ( !isset( $wgOut ) ) {
137 $wgOut = NULL;
138 }
139 $this->mOut =& $wgOut;
140
141 $this->mFailFunction = $failFunction;
142 $this->mFlags = $flags;
143
144 if ( $this->mFlags & DBO_DEFAULT ) {
145 if ( $wgCommandLineMode ) {
146 $this->mFlags &= ~DBO_TRX;
147 } else {
148 $this->mFlags |= DBO_TRX;
149 }
150 }
151
152 /*
153 // Faster read-only access
154 if ( wfReadOnly() ) {
155 $this->mFlags |= DBO_PERSISTENT;
156 $this->mFlags &= ~DBO_TRX;
157 }*/
158
159 /** Get the default table prefix*/
160 if ( $tablePrefix == 'get from global' ) {
161 $this->mTablePrefix = $wgDBprefix;
162 } else {
163 $this->mTablePrefix = $tablePrefix;
164 }
165
166 if ( $server ) {
167 $this->open( $server, $user, $password, $dbName );
168 }
169 }
170
171 /**
172 * @static
173 * @param failFunction
174 * @param $flags
175 */
176 function newFromParams( $server, $user, $password, $dbName,
177 $failFunction = false, $flags = 0 )
178 {
179 return new Database( $server, $user, $password, $dbName, $failFunction, $flags );
180 }
181
182 /**
183 * Usually aborts on failure
184 * If the failFunction is set to a non-zero integer, returns success
185 */
186 function open( $server, $user, $password, $dbName ) {
187 # Test for missing mysql.so
188 # First try to load it
189 if (!@extension_loaded('mysql')) {
190 @dl('mysql.so');
191 }
192
193 # Otherwise we get a suppressed fatal error, which is very hard to track down
194 if ( !function_exists( 'mysql_connect' ) ) {
195 die( "MySQL functions missing, have you compiled PHP with the --with-mysql option?\n" );
196 }
197
198 $this->close();
199 $this->mServer = $server;
200 $this->mUser = $user;
201 $this->mPassword = $password;
202 $this->mDBname = $dbName;
203
204 $success = false;
205
206 if ( $this->mFlags & DBO_PERSISTENT ) {
207 @/**/$this->mConn = mysql_pconnect( $server, $user, $password );
208 } else {
209 @/**/$this->mConn = mysql_connect( $server, $user, $password );
210 }
211
212 if ( $dbName != '' ) {
213 if ( $this->mConn !== false ) {
214 $success = @/**/mysql_select_db( $dbName, $this->mConn );
215 if ( !$success ) {
216 wfDebug( "Error selecting database \"$dbName\": " . $this->lastError() . "\n" );
217 }
218 } else {
219 wfDebug( "DB connection error\n" );
220 wfDebug( "Server: $server, User: $user, Password: " .
221 substr( $password, 0, 3 ) . "...\n" );
222 $success = false;
223 }
224 } else {
225 # Delay USE query
226 $success = !!$this->mConn;
227 }
228
229 if ( !$success ) {
230 $this->reportConnectionError();
231 $this->close();
232 }
233 $this->mOpened = $success;
234 return $success;
235 }
236 /**#@-*/
237
238 /**
239 * Closes a database connection.
240 * if it is open : commits any open transactions
241 *
242 * @return bool operation success. true if already closed.
243 */
244 function close()
245 {
246 $this->mOpened = false;
247 if ( $this->mConn ) {
248 if ( $this->trxLevel() ) {
249 $this->immediateCommit();
250 }
251 return mysql_close( $this->mConn );
252 } else {
253 return true;
254 }
255 }
256
257 /**
258 * @access private
259 * @param string $msg error message ?
260 * @todo parameter $msg is not used
261 */
262 function reportConnectionError( $msg = '') {
263 if ( $this->mFailFunction ) {
264 if ( !is_int( $this->mFailFunction ) ) {
265 $ff = $this->mFailFunction;
266 $ff( $this, mysql_error() );
267 }
268 } else {
269 wfEmergencyAbort( $this, mysql_error() );
270 }
271 }
272
273 /**
274 * Usually aborts on failure
275 * If errors are explicitly ignored, returns success
276 */
277 function query( $sql, $fname = '', $tempIgnore = false ) {
278 global $wgProfiling, $wgCommandLineMode;
279
280 if ( $wgProfiling ) {
281 # generalizeSQL will probably cut down the query to reasonable
282 # logging size most of the time. The substr is really just a sanity check.
283 $profName = 'query: ' . substr( Database::generalizeSQL( $sql ), 0, 255 );
284 wfProfileIn( $profName );
285 }
286
287 $this->mLastQuery = $sql;
288
289 # Add a comment for easy SHOW PROCESSLIST interpretation
290 if ( $fname ) {
291 $commentedSql = "/* $fname */ $sql";
292 } else {
293 $commentedSql = $sql;
294 }
295
296 # If DBO_TRX is set, start a transaction
297 if ( ( $this->mFlags & DBO_TRX ) && !$this->trxLevel() && $sql != 'BEGIN' ) {
298 $this->begin();
299 }
300
301 if ( $this->debug() ) {
302 $sqlx = substr( $sql, 0, 500 );
303 $sqlx = strtr($sqlx,"\t\n",' ');
304 wfDebug( "SQL: $sqlx\n" );
305 }
306
307 # Do the query and handle errors
308 $ret = $this->doQuery( $commentedSql );
309
310 # Try reconnecting if the connection was lost
311 if ( false === $ret && $this->lastErrno() == 2013 ) {
312 # Transaction is gone, like it or not
313 $this->mTrxLevel = 0;
314 wfDebug( "Connection lost, reconnecting...\n" );
315 if ( $this->ping() ) {
316 wfDebug( "Reconnected\n" );
317 $ret = $this->doQuery( $commentedSql );
318 } else {
319 wfDebug( "Failed\n" );
320 }
321 }
322
323 if ( false === $ret ) {
324 # Automatic reconnect
325 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
326 }
327
328 if ( $wgProfiling ) {
329 wfProfileOut( $profName );
330 }
331 return $ret;
332 }
333
334 /**
335 * The DBMS-dependent part of query()
336 * @param string $sql SQL query.
337 */
338 function doQuery( $sql ) {
339 if( $this->bufferResults() ) {
340 $ret = mysql_query( $sql, $this->mConn );
341 } else {
342 $ret = mysql_unbuffered_query( $sql, $this->mConn );
343 }
344 return $ret;
345 }
346
347 /**
348 * @param $error
349 * @param $errno
350 * @param $sql
351 * @param string $fname
352 * @param bool $tempIgnore
353 */
354 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
355 global $wgCommandLineMode, $wgFullyInitialised;
356 # Ignore errors during error handling to avoid infinite recursion
357 $ignore = $this->ignoreErrors( true );
358
359 if( $ignore || $tempIgnore ) {
360 wfDebug("SQL ERROR (ignored): " . $error . "\n");
361 } else {
362 $sql1line = str_replace( "\n", "\\n", $sql );
363 wfLogDBError("$fname\t{$this->mServer}\t$errno\t$error\t$sql1line\n");
364 wfDebug("SQL ERROR: " . $error . "\n");
365 if ( $wgCommandLineMode || !$this->mOut || empty( $wgFullyInitialised ) ) {
366 $message = "A database error has occurred\n" .
367 "Query: $sql\n" .
368 "Function: $fname\n" .
369 "Error: $errno $error\n";
370 if ( !$wgCommandLineMode ) {
371 $message = nl2br( $message );
372 }
373 wfDebugDieBacktrace( $message );
374 } else {
375 // this calls wfAbruptExit()
376 $this->mOut->databaseError( $fname, $sql, $error, $errno );
377 }
378 }
379 $this->ignoreErrors( $ignore );
380 }
381
382
383 /**
384 * Intended to be compatible with the PEAR::DB wrapper functions.
385 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
386 *
387 * ? = scalar value, quoted as necessary
388 * ! = raw SQL bit (a function for instance)
389 * & = filename; reads the file and inserts as a blob
390 * (we don't use this though...)
391 */
392 function prepare( $sql, $func = 'Database::prepare' ) {
393 /* MySQL doesn't support prepared statements (yet), so just
394 pack up the query for reference. We'll manually replace
395 the bits later. */
396 return array( 'query' => $sql, 'func' => $func );
397 }
398
399 function freePrepared( $prepared ) {
400 /* No-op for MySQL */
401 }
402
403 /**
404 * Execute a prepared query with the various arguments
405 * @param string $prepared the prepared sql
406 * @param mixed $args Either an array here, or put scalars as varargs
407 */
408 function execute( $prepared, $args = null ) {
409 if( !is_array( $args ) ) {
410 # Pull the var args
411 $args = func_get_args();
412 array_shift( $args );
413 }
414 $sql = $this->fillPrepared( $prepared['query'], $args );
415 return $this->query( $sql, $prepared['func'] );
416 }
417
418 /**
419 * Prepare & execute an SQL statement, quoting and inserting arguments
420 * in the appropriate places.
421 * @param string $query
422 * @param string $args (default null)
423 */
424 function safeQuery( $query, $args = null ) {
425 $prepared = $this->prepare( $query, 'Database::safeQuery' );
426 if( !is_array( $args ) ) {
427 # Pull the var args
428 $args = func_get_args();
429 array_shift( $args );
430 }
431 $retval = $this->execute( $prepared, $args );
432 $this->freePrepared( $prepared );
433 return $retval;
434 }
435
436 /**
437 * For faking prepared SQL statements on DBs that don't support
438 * it directly.
439 * @param string $preparedSql - a 'preparable' SQL statement
440 * @param array $args - array of arguments to fill it with
441 * @return string executable SQL
442 */
443 function fillPrepared( $preparedQuery, $args ) {
444 $n = 0;
445 reset( $args );
446 $this->preparedArgs =& $args;
447 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
448 array( &$this, 'fillPreparedArg' ), $preparedQuery );
449 }
450
451 /**
452 * preg_callback func for fillPrepared()
453 * The arguments should be in $this->preparedArgs and must not be touched
454 * while we're doing this.
455 *
456 * @param array $matches
457 * @return string
458 * @access private
459 */
460 function fillPreparedArg( $matches ) {
461 switch( $matches[1] ) {
462 case '\\?': return '?';
463 case '\\!': return '!';
464 case '\\&': return '&';
465 }
466 list( $n, $arg ) = each( $this->preparedArgs );
467 switch( $matches[1] ) {
468 case '?': return $this->addQuotes( $arg );
469 case '!': return $arg;
470 case '&':
471 # return $this->addQuotes( file_get_contents( $arg ) );
472 wfDebugDieBacktrace( '& mode is not implemented. If it\'s really needed, uncomment the line above.' );
473 default:
474 wfDebugDieBacktrace( 'Received invalid match. This should never happen!' );
475 }
476 }
477
478 /**#@+
479 * @param mixed $res A SQL result
480 */
481 /**
482 * Free a result object
483 */
484 function freeResult( $res ) {
485 if ( !@/**/mysql_free_result( $res ) ) {
486 wfDebugDieBacktrace( "Unable to free MySQL result\n" );
487 }
488 }
489
490 /**
491 * Fetch the next row from the given result object, in object form
492 */
493 function fetchObject( $res ) {
494 @/**/$row = mysql_fetch_object( $res );
495 if( mysql_errno() ) {
496 wfDebugDieBacktrace( 'Error in fetchObject(): ' . htmlspecialchars( mysql_error() ) );
497 }
498 return $row;
499 }
500
501 /**
502 * Fetch the next row from the given result object
503 * Returns an array
504 */
505 function fetchRow( $res ) {
506 @/**/$row = mysql_fetch_array( $res );
507 if (mysql_errno() ) {
508 wfDebugDieBacktrace( 'Error in fetchRow(): ' . htmlspecialchars( mysql_error() ) );
509 }
510 return $row;
511 }
512
513 /**
514 * Get the number of rows in a result object
515 */
516 function numRows( $res ) {
517 @/**/$n = mysql_num_rows( $res );
518 if( mysql_errno() ) {
519 wfDebugDieBacktrace( 'Error in numRows(): ' . htmlspecialchars( mysql_error() ) );
520 }
521 return $n;
522 }
523
524 /**
525 * Get the number of fields in a result object
526 * See documentation for mysql_num_fields()
527 */
528 function numFields( $res ) { return mysql_num_fields( $res ); }
529
530 /**
531 * Get a field name in a result object
532 * See documentation for mysql_field_name()
533 */
534 function fieldName( $res, $n ) { return mysql_field_name( $res, $n ); }
535
536 /**
537 * Get the inserted value of an auto-increment row
538 *
539 * The value inserted should be fetched from nextSequenceValue()
540 *
541 * Example:
542 * $id = $dbw->nextSequenceValue('page_page_id_seq');
543 * $dbw->insert('page',array('page_id' => $id));
544 * $id = $dbw->insertId();
545 */
546 function insertId() { return mysql_insert_id( $this->mConn ); }
547
548 /**
549 * Change the position of the cursor in a result object
550 * See mysql_data_seek()
551 */
552 function dataSeek( $res, $row ) { return mysql_data_seek( $res, $row ); }
553
554 /**
555 * Get the last error number
556 * See mysql_errno()
557 */
558 function lastErrno() {
559 if ( $this->mConn ) {
560 return mysql_errno( $this->mConn );
561 } else {
562 return mysql_errno();
563 }
564 }
565
566 /**
567 * Get a description of the last error
568 * See mysql_error() for more details
569 */
570 function lastError() {
571 if ( $this->mConn ) {
572 $error = mysql_error( $this->mConn );
573 } else {
574 $error = mysql_error();
575 }
576 if( $error ) {
577 $error .= ' (' . $this->mServer . ')';
578 }
579 return $error;
580 }
581 /**
582 * Get the number of rows affected by the last write query
583 * See mysql_affected_rows() for more details
584 */
585 function affectedRows() { return mysql_affected_rows( $this->mConn ); }
586 /**#@-*/ // end of template : @param $result
587
588 /**
589 * Simple UPDATE wrapper
590 * Usually aborts on failure
591 * If errors are explicitly ignored, returns success
592 *
593 * This function exists for historical reasons, Database::update() has a more standard
594 * calling convention and feature set
595 */
596 function set( $table, $var, $value, $cond, $fname = 'Database::set' )
597 {
598 $table = $this->tableName( $table );
599 $sql = "UPDATE $table SET $var = '" .
600 $this->strencode( $value ) . "' WHERE ($cond)";
601 return !!$this->query( $sql, DB_MASTER, $fname );
602 }
603
604 /**
605 * Simple SELECT wrapper, returns a single field, input must be encoded
606 * Usually aborts on failure
607 * If errors are explicitly ignored, returns FALSE on failure
608 */
609 function selectField( $table, $var, $cond='', $fname = 'Database::selectField', $options = array() ) {
610 if ( !is_array( $options ) ) {
611 $options = array( $options );
612 }
613 $options['LIMIT'] = 1;
614
615 $res = $this->select( $table, $var, $cond, $fname, $options );
616 if ( $res === false || !$this->numRows( $res ) ) {
617 return false;
618 }
619 $row = $this->fetchRow( $res );
620 if ( $row !== false ) {
621 $this->freeResult( $res );
622 return $row[0];
623 } else {
624 return false;
625 }
626 }
627
628 /**
629 * Returns an optional USE INDEX clause to go after the table, and a
630 * string to go at the end of the query
631 */
632 function makeSelectOptions( $options ) {
633 if ( !is_array( $options ) ) {
634 $options = array( $options );
635 }
636
637 $tailOpts = '';
638
639 if ( isset( $options['ORDER BY'] ) ) {
640 $tailOpts .= " ORDER BY {$options['ORDER BY']}";
641 }
642 if ( isset( $options['LIMIT'] ) ) {
643 $tailOpts .= " LIMIT {$options['LIMIT']}";
644 }
645
646 if ( is_numeric( array_search( 'FOR UPDATE', $options ) ) ) {
647 $tailOpts .= ' FOR UPDATE';
648 }
649
650 if ( is_numeric( array_search( 'LOCK IN SHARE MODE', $options ) ) ) {
651 $tailOpts .= ' LOCK IN SHARE MODE';
652 }
653
654 if ( isset( $options['USE INDEX'] ) ) {
655 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
656 } else {
657 $useIndex = '';
658 }
659 return array( $useIndex, $tailOpts );
660 }
661
662 /**
663 * SELECT wrapper
664 */
665 function select( $table, $vars, $conds='', $fname = 'Database::select', $options = array() )
666 {
667 if( is_array( $vars ) ) {
668 $vars = implode( ',', $vars );
669 }
670 if( is_array( $table ) ) {
671 $from = ' FROM ' . implode( ',', array_map( array( &$this, 'tableName' ), $table ) );
672 } elseif ($table!='') {
673 $from = ' FROM ' .$this->tableName( $table );
674 } else {
675 $from = '';
676 }
677
678 list( $useIndex, $tailOpts ) = $this->makeSelectOptions( $options );
679
680 if( !empty( $conds ) ) {
681 if ( is_array( $conds ) ) {
682 $conds = $this->makeList( $conds, LIST_AND );
683 }
684 $sql = "SELECT $vars $from $useIndex WHERE $conds $tailOpts";
685 } else {
686 $sql = "SELECT $vars $from $useIndex $tailOpts";
687 }
688 return $this->query( $sql, $fname );
689 }
690
691 /**
692 * Single row SELECT wrapper
693 * Aborts or returns FALSE on error
694 *
695 * $vars: the selected variables
696 * $conds: a condition map, terms are ANDed together.
697 * Items with numeric keys are taken to be literal conditions
698 * Takes an array of selected variables, and a condition map, which is ANDed
699 * e.g: selectRow( "page", array( "page_id" ), array( "page_namespace" =>
700 * NS_MAIN, "page_title" => "Astronomy" ) ) would return an object where
701 * $obj- >page_id is the ID of the Astronomy article
702 *
703 * @todo migrate documentation to phpdocumentor format
704 */
705 function selectRow( $table, $vars, $conds, $fname = 'Database::selectRow', $options = array() ) {
706 $options['LIMIT'] = 1;
707 $res = $this->select( $table, $vars, $conds, $fname, $options );
708 if ( $res === false || !$this->numRows( $res ) ) {
709 return false;
710 }
711 $obj = $this->fetchObject( $res );
712 $this->freeResult( $res );
713 return $obj;
714
715 }
716
717 /**
718 * Removes most variables from an SQL query and replaces them with X or N for numbers.
719 * It's only slightly flawed. Don't use for anything important.
720 *
721 * @param string $sql A SQL Query
722 * @static
723 */
724 function generalizeSQL( $sql ) {
725 # This does the same as the regexp below would do, but in such a way
726 # as to avoid crashing php on some large strings.
727 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
728
729 $sql = str_replace ( "\\\\", '', $sql);
730 $sql = str_replace ( "\\'", '', $sql);
731 $sql = str_replace ( "\\\"", '', $sql);
732 $sql = preg_replace ("/'.*'/s", "'X'", $sql);
733 $sql = preg_replace ('/".*"/s', "'X'", $sql);
734
735 # All newlines, tabs, etc replaced by single space
736 $sql = preg_replace ( "/\s+/", ' ', $sql);
737
738 # All numbers => N
739 $sql = preg_replace ('/-?[0-9]+/s', 'N', $sql);
740
741 return $sql;
742 }
743
744 /**
745 * Determines whether a field exists in a table
746 * Usually aborts on failure
747 * If errors are explicitly ignored, returns NULL on failure
748 */
749 function fieldExists( $table, $field, $fname = 'Database::fieldExists' ) {
750 $table = $this->tableName( $table );
751 $res = $this->query( 'DESCRIBE '.$table, DB_SLAVE, $fname );
752 if ( !$res ) {
753 return NULL;
754 }
755
756 $found = false;
757
758 while ( $row = $this->fetchObject( $res ) ) {
759 if ( $row->Field == $field ) {
760 $found = true;
761 break;
762 }
763 }
764 return $found;
765 }
766
767 /**
768 * Determines whether an index exists
769 * Usually aborts on failure
770 * If errors are explicitly ignored, returns NULL on failure
771 */
772 function indexExists( $table, $index, $fname = 'Database::indexExists' ) {
773 $info = $this->indexInfo( $table, $index, $fname );
774 if ( is_null( $info ) ) {
775 return NULL;
776 } else {
777 return $info !== false;
778 }
779 }
780
781
782 /**
783 * Get information about an index into an object
784 * Returns false if the index does not exist
785 */
786 function indexInfo( $table, $index, $fname = 'Database::indexInfo' ) {
787 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
788 # SHOW INDEX should work for 3.x and up:
789 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
790 $table = $this->tableName( $table );
791 $sql = 'SHOW INDEX FROM '.$table;
792 $res = $this->query( $sql, $fname );
793 if ( !$res ) {
794 return NULL;
795 }
796
797 while ( $row = $this->fetchObject( $res ) ) {
798 if ( $row->Key_name == $index ) {
799 return $row;
800 }
801 }
802 return false;
803 }
804
805 /**
806 * Query whether a given table exists
807 */
808 function tableExists( $table ) {
809 $table = $this->tableName( $table );
810 $old = $this->ignoreErrors( true );
811 $res = $this->query( "SELECT 1 FROM $table LIMIT 1" );
812 $this->ignoreErrors( $old );
813 if( $res ) {
814 $this->freeResult( $res );
815 return true;
816 } else {
817 return false;
818 }
819 }
820
821 /**
822 * mysql_fetch_field() wrapper
823 * Returns false if the field doesn't exist
824 *
825 * @param $table
826 * @param $field
827 */
828 function fieldInfo( $table, $field ) {
829 $table = $this->tableName( $table );
830 $res = $this->query( "SELECT * FROM $table LIMIT 1" );
831 $n = mysql_num_fields( $res );
832 for( $i = 0; $i < $n; $i++ ) {
833 $meta = mysql_fetch_field( $res, $i );
834 if( $field == $meta->name ) {
835 return $meta;
836 }
837 }
838 return false;
839 }
840
841 /**
842 * mysql_field_type() wrapper
843 */
844 function fieldType( $res, $index ) {
845 return mysql_field_type( $res, $index );
846 }
847
848 /**
849 * Determines if a given index is unique
850 */
851 function indexUnique( $table, $index ) {
852 $indexInfo = $this->indexInfo( $table, $index );
853 if ( !$indexInfo ) {
854 return NULL;
855 }
856 return !$indexInfo->Non_unique;
857 }
858
859 /**
860 * INSERT wrapper, inserts an array into a table
861 *
862 * $a may be a single associative array, or an array of these with numeric keys, for
863 * multi-row insert.
864 *
865 * Usually aborts on failure
866 * If errors are explicitly ignored, returns success
867 */
868 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
869 # No rows to insert, easy just return now
870 if ( !count( $a ) ) {
871 return true;
872 }
873
874 $table = $this->tableName( $table );
875 if ( !is_array( $options ) ) {
876 $options = array( $options );
877 }
878 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
879 $multi = true;
880 $keys = array_keys( $a[0] );
881 } else {
882 $multi = false;
883 $keys = array_keys( $a );
884 }
885
886 $sql = 'INSERT ' . implode( ' ', $options ) .
887 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
888
889 if ( $multi ) {
890 $first = true;
891 foreach ( $a as $row ) {
892 if ( $first ) {
893 $first = false;
894 } else {
895 $sql .= ',';
896 }
897 $sql .= '(' . $this->makeList( $row ) . ')';
898 }
899 } else {
900 $sql .= '(' . $this->makeList( $a ) . ')';
901 }
902 return !!$this->query( $sql, $fname );
903 }
904
905 /**
906 * UPDATE wrapper, takes a condition array and a SET array
907 */
908 function update( $table, $values, $conds, $fname = 'Database::update' ) {
909 $table = $this->tableName( $table );
910 $sql = "UPDATE $table SET " . $this->makeList( $values, LIST_SET );
911 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND );
912 $this->query( $sql, $fname );
913 }
914
915 /**
916 * Makes a wfStrencoded list from an array
917 * $mode: LIST_COMMA - comma separated, no field names
918 * LIST_AND - ANDed WHERE clause (without the WHERE)
919 * LIST_SET - comma separated with field names, like a SET clause
920 * LIST_NAMES - comma separated field names
921 */
922 function makeList( $a, $mode = LIST_COMMA ) {
923 if ( !is_array( $a ) ) {
924 wfDebugDieBacktrace( 'Database::makeList called with incorrect parameters' );
925 }
926
927 $first = true;
928 $list = '';
929 foreach ( $a as $field => $value ) {
930 if ( !$first ) {
931 if ( $mode == LIST_AND ) {
932 $list .= ' AND ';
933 } else {
934 $list .= ',';
935 }
936 } else {
937 $first = false;
938 }
939 if ( $mode == LIST_AND && is_numeric( $field ) ) {
940 $list .= "($value)";
941 } elseif ( $mode == LIST_AND && is_array ($value) ) {
942 $list .= $field." IN (".$this->makeList($value).") ";
943 } else {
944 if ( $mode == LIST_AND || $mode == LIST_SET ) {
945 $list .= $field.'=';
946 }
947 $list .= ($mode==LIST_NAMES?$value:$this->addQuotes( $value ));
948 }
949 }
950 return $list;
951 }
952
953 /**
954 * Change the current database
955 */
956 function selectDB( $db ) {
957 $this->mDBname = $db;
958 return mysql_select_db( $db, $this->mConn );
959 }
960
961 /**
962 * Starts a timer which will kill the DB thread after $timeout seconds
963 */
964 function startTimer( $timeout ) {
965 global $IP;
966 if( function_exists( 'mysql_thread_id' ) ) {
967 # This will kill the query if it's still running after $timeout seconds.
968 $tid = mysql_thread_id( $this->mConn );
969 exec( "php $IP/includes/killthread.php $timeout $tid &>/dev/null &" );
970 }
971 }
972
973 /**
974 * Stop a timer started by startTimer()
975 * Currently unimplemented.
976 *
977 */
978 function stopTimer() { }
979
980 /**
981 * Format a table name ready for use in constructing an SQL query
982 *
983 * This does two important things: it quotes table names which as necessary,
984 * and it adds a table prefix if there is one.
985 *
986 * All functions of this object which require a table name call this function
987 * themselves. Pass the canonical name to such functions. This is only needed
988 * when calling query() directly.
989 *
990 * @param string $name database table name
991 */
992 function tableName( $name ) {
993 global $wgSharedDB;
994 # Skip quoted literals
995 if ( $name{0} != '`' ) {
996 if ( $this->mTablePrefix !== '' && strpos( '.', $name ) === false ) {
997 $name = "{$this->mTablePrefix}$name";
998 }
999 if ( isset( $wgSharedDB ) && 'user' == $name ) {
1000 $name = "`$wgSharedDB`.`$name`";
1001 } else {
1002 # Standard quoting
1003 $name = "`$name`";
1004 }
1005 }
1006 return $name;
1007 }
1008
1009 /**
1010 * Fetch a number of table names into an array
1011 * This is handy when you need to construct SQL for joins
1012 *
1013 * Example:
1014 * extract($dbr->tableNames('user','watchlist'));
1015 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1016 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1017 */
1018 function tableNames() {
1019 $inArray = func_get_args();
1020 $retVal = array();
1021 foreach ( $inArray as $name ) {
1022 $retVal[$name] = $this->tableName( $name );
1023 }
1024 return $retVal;
1025 }
1026
1027 /**
1028 * Wrapper for addslashes()
1029 * @param string $s String to be slashed.
1030 * @return string slashed string.
1031 */
1032 function strencode( $s ) {
1033 return addslashes( $s );
1034 }
1035
1036 /**
1037 * If it's a string, adds quotes and backslashes
1038 * Otherwise returns as-is
1039 */
1040 function addQuotes( $s ) {
1041 if ( is_null( $s ) ) {
1042 $s = 'NULL';
1043 } else {
1044 # This will also quote numeric values. This should be harmless,
1045 # and protects against weird problems that occur when they really
1046 # _are_ strings such as article titles and string->number->string
1047 # conversion is not 1:1.
1048 $s = "'" . $this->strencode( $s ) . "'";
1049 }
1050 return $s;
1051 }
1052
1053 /**
1054 * Returns an appropriately quoted sequence value for inserting a new row.
1055 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
1056 * subclass will return an integer, and save the value for insertId()
1057 */
1058 function nextSequenceValue( $seqName ) {
1059 return NULL;
1060 }
1061
1062 /**
1063 * USE INDEX clause
1064 * PostgreSQL doesn't have them and returns ""
1065 */
1066 function useIndexClause( $index ) {
1067 return 'USE INDEX ('.$index.')';
1068 }
1069
1070 /**
1071 * REPLACE query wrapper
1072 * PostgreSQL simulates this with a DELETE followed by INSERT
1073 * $row is the row to insert, an associative array
1074 * $uniqueIndexes is an array of indexes. Each element may be either a
1075 * field name or an array of field names
1076 *
1077 * It may be more efficient to leave off unique indexes which are unlikely to collide.
1078 * However if you do this, you run the risk of encountering errors which wouldn't have
1079 * occurred in MySQL
1080 *
1081 * @todo migrate comment to phodocumentor format
1082 */
1083 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
1084 $table = $this->tableName( $table );
1085
1086 # Single row case
1087 if ( !is_array( reset( $rows ) ) ) {
1088 $rows = array( $rows );
1089 }
1090
1091 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) .') VALUES ';
1092 $first = true;
1093 foreach ( $rows as $row ) {
1094 if ( $first ) {
1095 $first = false;
1096 } else {
1097 $sql .= ',';
1098 }
1099 $sql .= '(' . $this->makeList( $row ) . ')';
1100 }
1101 return $this->query( $sql, $fname );
1102 }
1103
1104 /**
1105 * DELETE where the condition is a join
1106 * MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
1107 *
1108 * For safety, an empty $conds will not delete everything. If you want to delete all rows where the
1109 * join condition matches, set $conds='*'
1110 *
1111 * DO NOT put the join condition in $conds
1112 *
1113 * @param string $delTable The table to delete from.
1114 * @param string $joinTable The other table.
1115 * @param string $delVar The variable to join on, in the first table.
1116 * @param string $joinVar The variable to join on, in the second table.
1117 * @param array $conds Condition array of field names mapped to variables, ANDed together in the WHERE clause
1118 */
1119 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'Database::deleteJoin' ) {
1120 if ( !$conds ) {
1121 wfDebugDieBacktrace( 'Database::deleteJoin() called with empty $conds' );
1122 }
1123
1124 $delTable = $this->tableName( $delTable );
1125 $joinTable = $this->tableName( $joinTable );
1126 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1127 if ( $conds != '*' ) {
1128 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND );
1129 }
1130
1131 return $this->query( $sql, $fname );
1132 }
1133
1134 /**
1135 * Returns the size of a text field, or -1 for "unlimited"
1136 */
1137 function textFieldSize( $table, $field ) {
1138 $table = $this->tableName( $table );
1139 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
1140 $res = $this->query( $sql, 'Database::textFieldSize' );
1141 $row = $this->fetchObject( $res );
1142 $this->freeResult( $res );
1143
1144 if ( preg_match( "/\((.*)\)/", $row->Type, $m ) ) {
1145 $size = $m[1];
1146 } else {
1147 $size = -1;
1148 }
1149 return $size;
1150 }
1151
1152 /**
1153 * @return string Returns the text of the low priority option if it is supported, or a blank string otherwise
1154 */
1155 function lowPriorityOption() {
1156 return 'LOW_PRIORITY';
1157 }
1158
1159 /**
1160 * DELETE query wrapper
1161 *
1162 * Use $conds == "*" to delete all rows
1163 */
1164 function delete( $table, $conds, $fname = 'Database::delete' ) {
1165 if ( !$conds ) {
1166 wfDebugDieBacktrace( 'Database::delete() called with no conditions' );
1167 }
1168 $table = $this->tableName( $table );
1169 $sql = "DELETE FROM $table ";
1170 if ( $conds != '*' ) {
1171 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND );
1172 }
1173 return $this->query( $sql, $fname );
1174 }
1175
1176 /**
1177 * INSERT SELECT wrapper
1178 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
1179 * Source items may be literals rather than field names, but strings should be quoted with Database::addQuotes()
1180 * $conds may be "*" to copy the whole table
1181 * srcTable may be an array of tables.
1182 */
1183 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'Database::insertSelect' ) {
1184 $destTable = $this->tableName( $destTable );
1185 if( is_array( $srcTable ) ) {
1186 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
1187 } else {
1188 $srcTable = $this->tableName( $srcTable );
1189 }
1190 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
1191 ' SELECT ' . implode( ',', $varMap ) .
1192 " FROM $srcTable";
1193 if ( $conds != '*' ) {
1194 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
1195 }
1196 return $this->query( $sql, $fname );
1197 }
1198
1199 /**
1200 * Construct a LIMIT query with optional offset
1201 * This is used for query pages
1202 */
1203 function limitResult($limit,$offset) {
1204 return ' LIMIT '.(is_numeric($offset)?"{$offset},":"")."{$limit} ";
1205 }
1206
1207 /**
1208 * Returns an SQL expression for a simple conditional.
1209 * Uses IF on MySQL.
1210 *
1211 * @param string $cond SQL expression which will result in a boolean value
1212 * @param string $trueVal SQL expression to return if true
1213 * @param string $falseVal SQL expression to return if false
1214 * @return string SQL fragment
1215 */
1216 function conditional( $cond, $trueVal, $falseVal ) {
1217 return " IF($cond, $trueVal, $falseVal) ";
1218 }
1219
1220 /**
1221 * Determines if the last failure was due to a deadlock
1222 */
1223 function wasDeadlock() {
1224 return $this->lastErrno() == 1213;
1225 }
1226
1227 /**
1228 * Perform a deadlock-prone transaction.
1229 *
1230 * This function invokes a callback function to perform a set of write
1231 * queries. If a deadlock occurs during the processing, the transaction
1232 * will be rolled back and the callback function will be called again.
1233 *
1234 * Usage:
1235 * $dbw->deadlockLoop( callback, ... );
1236 *
1237 * Extra arguments are passed through to the specified callback function.
1238 *
1239 * Returns whatever the callback function returned on its successful,
1240 * iteration, or false on error, for example if the retry limit was
1241 * reached.
1242 */
1243 function deadlockLoop() {
1244 $myFname = 'Database::deadlockLoop';
1245
1246 $this->query( 'BEGIN', $myFname );
1247 $args = func_get_args();
1248 $function = array_shift( $args );
1249 $oldIgnore = $this->ignoreErrors( true );
1250 $tries = DEADLOCK_TRIES;
1251 if ( is_array( $function ) ) {
1252 $fname = $function[0];
1253 } else {
1254 $fname = $function;
1255 }
1256 do {
1257 $retVal = call_user_func_array( $function, $args );
1258 $error = $this->lastError();
1259 $errno = $this->lastErrno();
1260 $sql = $this->lastQuery();
1261
1262 if ( $errno ) {
1263 if ( $this->wasDeadlock() ) {
1264 # Retry
1265 usleep( mt_rand( DEADLOCK_DELAY_MIN, DEADLOCK_DELAY_MAX ) );
1266 } else {
1267 $this->reportQueryError( $error, $errno, $sql, $fname );
1268 }
1269 }
1270 } while( $this->wasDeadlock() && --$tries > 0 );
1271 $this->ignoreErrors( $oldIgnore );
1272 if ( $tries <= 0 ) {
1273 $this->query( 'ROLLBACK', $myFname );
1274 $this->reportQueryError( $error, $errno, $sql, $fname );
1275 return false;
1276 } else {
1277 $this->query( 'COMMIT', $myFname );
1278 return $retVal;
1279 }
1280 }
1281
1282 /**
1283 * Do a SELECT MASTER_POS_WAIT()
1284 *
1285 * @param string $file the binlog file
1286 * @param string $pos the binlog position
1287 * @param integer $timeout the maximum number of seconds to wait for synchronisation
1288 */
1289 function masterPosWait( $file, $pos, $timeout ) {
1290 $fname = 'Database::masterPosWait';
1291 wfProfileIn( $fname );
1292
1293
1294 # Commit any open transactions
1295 $this->immediateCommit();
1296
1297 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
1298 $encFile = $this->strencode( $file );
1299 $sql = "SELECT MASTER_POS_WAIT('$encFile', $pos, $timeout)";
1300 $res = $this->doQuery( $sql );
1301 if ( $res && $row = $this->fetchRow( $res ) ) {
1302 $this->freeResult( $res );
1303 return $row[0];
1304 } else {
1305 return false;
1306 }
1307 }
1308
1309 /**
1310 * Get the position of the master from SHOW SLAVE STATUS
1311 */
1312 function getSlavePos() {
1313 $res = $this->query( 'SHOW SLAVE STATUS', 'Database::getSlavePos' );
1314 $row = $this->fetchObject( $res );
1315 if ( $row ) {
1316 return array( $row->Master_Log_File, $row->Read_Master_Log_Pos );
1317 } else {
1318 return array( false, false );
1319 }
1320 }
1321
1322 /**
1323 * Get the position of the master from SHOW MASTER STATUS
1324 */
1325 function getMasterPos() {
1326 $res = $this->query( 'SHOW MASTER STATUS', 'Database::getMasterPos' );
1327 $row = $this->fetchObject( $res );
1328 if ( $row ) {
1329 return array( $row->File, $row->Position );
1330 } else {
1331 return array( false, false );
1332 }
1333 }
1334
1335 /**
1336 * Begin a transaction, or if a transaction has already started, continue it
1337 */
1338 function begin( $fname = 'Database::begin' ) {
1339 if ( !$this->mTrxLevel ) {
1340 $this->immediateBegin( $fname );
1341 } else {
1342 $this->mTrxLevel++;
1343 }
1344 }
1345
1346 /**
1347 * End a transaction, or decrement the nest level if transactions are nested
1348 */
1349 function commit( $fname = 'Database::commit' ) {
1350 if ( $this->mTrxLevel ) {
1351 $this->mTrxLevel--;
1352 }
1353 if ( !$this->mTrxLevel ) {
1354 $this->immediateCommit( $fname );
1355 }
1356 }
1357
1358 /**
1359 * Rollback a transaction
1360 */
1361 function rollback( $fname = 'Database::rollback' ) {
1362 $this->query( 'ROLLBACK', $fname );
1363 $this->mTrxLevel = 0;
1364 }
1365
1366 /**
1367 * Begin a transaction, committing any previously open transaction
1368 */
1369 function immediateBegin( $fname = 'Database::immediateBegin' ) {
1370 $this->query( 'BEGIN', $fname );
1371 $this->mTrxLevel = 1;
1372 }
1373
1374 /**
1375 * Commit transaction, if one is open
1376 */
1377 function immediateCommit( $fname = 'Database::immediateCommit' ) {
1378 $this->query( 'COMMIT', $fname );
1379 $this->mTrxLevel = 0;
1380 }
1381
1382 /**
1383 * Return MW-style timestamp used for MySQL schema
1384 */
1385 function timestamp( $ts=0 ) {
1386 return wfTimestamp(TS_MW,$ts);
1387 }
1388
1389 /**
1390 * @todo document
1391 */
1392 function &resultObject( &$result ) {
1393 if( empty( $result ) ) {
1394 return NULL;
1395 } else {
1396 return new ResultWrapper( $this, $result );
1397 }
1398 }
1399
1400 /**
1401 * Return aggregated value alias
1402 */
1403 function aggregateValue ($valuedata,$valuename='value') {
1404 return $valuename;
1405 }
1406
1407 /**
1408 * @return string wikitext of a link to the server software's web site
1409 */
1410 function getSoftwareLink() {
1411 return "[http://www.mysql.com/ MySQL]";
1412 }
1413
1414 /**
1415 * @return string Version information from the database
1416 */
1417 function getServerVersion() {
1418 return mysql_get_server_info();
1419 }
1420
1421 /**
1422 * Ping the server and try to reconnect if it there is no connection
1423 */
1424 function ping() {
1425 return mysql_ping( $this->mConn );
1426 }
1427 }
1428
1429 /**
1430 * Database abstraction object for mySQL
1431 * Inherit all methods and properties of Database::Database()
1432 *
1433 * @package MediaWiki
1434 * @see Database
1435 */
1436 class DatabaseMysql extends Database {
1437 # Inherit all
1438 }
1439
1440
1441 /**
1442 * Result wrapper for grabbing data queried by someone else
1443 *
1444 * @package MediaWiki
1445 */
1446 class ResultWrapper {
1447 var $db, $result;
1448
1449 /**
1450 * @todo document
1451 */
1452 function ResultWrapper( $database, $result ) {
1453 $this->db =& $database;
1454 $this->result =& $result;
1455 }
1456
1457 /**
1458 * @todo document
1459 */
1460 function numRows() {
1461 return $this->db->numRows( $this->result );
1462 }
1463
1464 /**
1465 * @todo document
1466 */
1467 function &fetchObject() {
1468 return $this->db->fetchObject( $this->result );
1469 }
1470
1471 /**
1472 * @todo document
1473 */
1474 function &fetchRow() {
1475 return $this->db->fetchRow( $this->result );
1476 }
1477
1478 /**
1479 * @todo document
1480 */
1481 function free() {
1482 $this->db->freeResult( $this->result );
1483 unset( $this->result );
1484 unset( $this->db );
1485 }
1486
1487 function seek( $row ) {
1488 $this->db->dataSeek( $this->result, $row );
1489 }
1490 }
1491
1492 #------------------------------------------------------------------------------
1493 # Global functions
1494 #------------------------------------------------------------------------------
1495
1496 /**
1497 * Standard fail function, called by default when a connection cannot be
1498 * established.
1499 * Displays the file cache if possible
1500 */
1501 function wfEmergencyAbort( &$conn, $error ) {
1502 global $wgTitle, $wgUseFileCache, $title, $wgInputEncoding, $wgOutputEncoding;
1503 global $wgSitename, $wgServer;
1504
1505 # I give up, Brion is right. Getting the message cache to work when there is no DB is tricky.
1506 # Hard coding strings instead.
1507
1508 $noconnect = 'Sorry! The wiki is experiencing some technical difficulties, and cannot contact the database server. <br />
1509 $1';
1510 $mainpage = 'Main Page';
1511 $searchdisabled = <<<EOT
1512 <p style="margin: 1.5em 2em 1em">$wgSitename search is disabled for performance reasons. You can search via Google in the meantime.
1513 <span style="font-size: 89%; display: block; margin-left: .2em">Note that their indexes of $wgSitename content may be out of date.</span></p>',
1514 EOT;
1515
1516 $googlesearch = "
1517 <!-- SiteSearch Google -->
1518 <FORM method=GET action=\"http://www.google.com/search\">
1519 <TABLE bgcolor=\"#FFFFFF\"><tr><td>
1520 <A HREF=\"http://www.google.com/\">
1521 <IMG SRC=\"http://www.google.com/logos/Logo_40wht.gif\"
1522 border=\"0\" ALT=\"Google\"></A>
1523 </td>
1524 <td>
1525 <INPUT TYPE=text name=q size=31 maxlength=255 value=\"$1\">
1526 <INPUT type=submit name=btnG VALUE=\"Google Search\">
1527 <font size=-1>
1528 <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 />
1529 <input type='hidden' name='ie' value='$2'>
1530 <input type='hidden' name='oe' value='$2'>
1531 </font>
1532 </td></tr></TABLE>
1533 </FORM>
1534 <!-- SiteSearch Google -->";
1535 $cachederror = "The following is a cached copy of the requested page, and may not be up to date. ";
1536
1537
1538 if( !headers_sent() ) {
1539 header( 'HTTP/1.0 500 Internal Server Error' );
1540 header( 'Content-type: text/html; charset='.$wgOutputEncoding );
1541 /* Don't cache error pages! They cause no end of trouble... */
1542 header( 'Cache-control: none' );
1543 header( 'Pragma: nocache' );
1544 }
1545 $msg = wfGetSiteNotice();
1546 if($msg == '') {
1547 $msg = str_replace( '$1', $error, $noconnect );
1548 }
1549 $text = $msg;
1550
1551 if($wgUseFileCache) {
1552 if($wgTitle) {
1553 $t =& $wgTitle;
1554 } else {
1555 if($title) {
1556 $t = Title::newFromURL( $title );
1557 } elseif (@/**/$_REQUEST['search']) {
1558 $search = $_REQUEST['search'];
1559 echo $searchdisabled;
1560 echo str_replace( array( '$1', '$2' ), array( htmlspecialchars( $search ),
1561 $wgInputEncoding ), $googlesearch );
1562 wfErrorExit();
1563 } else {
1564 $t = Title::newFromText( $mainpage );
1565 }
1566 }
1567
1568 $cache = new CacheManager( $t );
1569 if( $cache->isFileCached() ) {
1570 $msg = '<p style="color: red"><b>'.$msg."<br />\n" .
1571 $cachederror . "</b></p>\n";
1572
1573 $tag = '<div id="article">';
1574 $text = str_replace(
1575 $tag,
1576 $tag . $msg,
1577 $cache->fetchPageText() );
1578 }
1579 }
1580
1581 echo $text;
1582 wfErrorExit();
1583 }
1584
1585 ?>