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