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