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