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