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