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