* Made makeUpdateOptions() DBMS independant
[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 * Make UPDATE options for the Database::update function
934 *
935 * @access private
936 * @param array $options The options passed to Database::update
937 * @return string
938 */
939 function makeUpdateOptions( $options ) {
940 $opts = array();
941 if ( in_array( 'LOW_PRIORITY', $options ) )
942 $opts[] = $this->lowPriorityOption();
943 if ( in_array( 'IGNORE', $options ) )
944 $opts[] = 'IGNORE';
945 return implode(' ', $opts);
946 }
947
948 /**
949 * UPDATE wrapper, takes a condition array and a SET array
950 *
951 * @param string $table The table to UPDATE
952 * @param array $values An array of values to SET
953 * @param array $conds An array of conditions (WHERE)
954 * @param string $fname The Class::Function calling this function
955 * (for the log)
956 * @param array $options An array of UPDATE options, can be one or
957 * more of IGNORE, LOW_PRIORITY
958 */
959 function update( $table, $values, $conds, $fname = 'Database::update', $options = array() ) {
960 $table = $this->tableName( $table );
961 $opts = $this->makeUpdateOptions( $options );
962 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET );
963 if ( $conds != '*' ) {
964 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND );
965 }
966 $this->query( $sql, $fname );
967 }
968
969 /**
970 * Makes a wfStrencoded list from an array
971 * $mode: LIST_COMMA - comma separated, no field names
972 * LIST_AND - ANDed WHERE clause (without the WHERE)
973 * LIST_SET - comma separated with field names, like a SET clause
974 * LIST_NAMES - comma separated field names
975 */
976 function makeList( $a, $mode = LIST_COMMA ) {
977 if ( !is_array( $a ) ) {
978 wfDebugDieBacktrace( 'Database::makeList called with incorrect parameters' );
979 }
980
981 $first = true;
982 $list = '';
983 foreach ( $a as $field => $value ) {
984 if ( !$first ) {
985 if ( $mode == LIST_AND ) {
986 $list .= ' AND ';
987 } else {
988 $list .= ',';
989 }
990 } else {
991 $first = false;
992 }
993 if ( $mode == LIST_AND && is_numeric( $field ) ) {
994 $list .= "($value)";
995 } elseif ( $mode == LIST_AND && is_array ($value) ) {
996 $list .= $field." IN (".$this->makeList($value).") ";
997 } else {
998 if ( $mode == LIST_AND || $mode == LIST_SET ) {
999 $list .= $field.'=';
1000 }
1001 $list .= ($mode==LIST_NAMES?$value:$this->addQuotes( $value ));
1002 }
1003 }
1004 return $list;
1005 }
1006
1007 /**
1008 * Change the current database
1009 */
1010 function selectDB( $db ) {
1011 $this->mDBname = $db;
1012 return mysql_select_db( $db, $this->mConn );
1013 }
1014
1015 /**
1016 * Starts a timer which will kill the DB thread after $timeout seconds
1017 */
1018 function startTimer( $timeout ) {
1019 global $IP;
1020 if( function_exists( 'mysql_thread_id' ) ) {
1021 # This will kill the query if it's still running after $timeout seconds.
1022 $tid = mysql_thread_id( $this->mConn );
1023 exec( "php $IP/includes/killthread.php $timeout $tid &>/dev/null &" );
1024 }
1025 }
1026
1027 /**
1028 * Stop a timer started by startTimer()
1029 * Currently unimplemented.
1030 *
1031 */
1032 function stopTimer() { }
1033
1034 /**
1035 * Format a table name ready for use in constructing an SQL query
1036 *
1037 * This does two important things: it quotes table names which as necessary,
1038 * and it adds a table prefix if there is one.
1039 *
1040 * All functions of this object which require a table name call this function
1041 * themselves. Pass the canonical name to such functions. This is only needed
1042 * when calling query() directly.
1043 *
1044 * @param string $name database table name
1045 */
1046 function tableName( $name ) {
1047 global $wgSharedDB;
1048 # Skip quoted literals
1049 if ( $name{0} != '`' ) {
1050 if ( $this->mTablePrefix !== '' && strpos( '.', $name ) === false ) {
1051 $name = "{$this->mTablePrefix}$name";
1052 }
1053 if ( isset( $wgSharedDB ) && "{$this->mTablePrefix}user" == $name ) {
1054 $name = "`$wgSharedDB`.`$name`";
1055 } else {
1056 # Standard quoting
1057 $name = "`$name`";
1058 }
1059 }
1060 return $name;
1061 }
1062
1063 /**
1064 * Fetch a number of table names into an array
1065 * This is handy when you need to construct SQL for joins
1066 *
1067 * Example:
1068 * extract($dbr->tableNames('user','watchlist'));
1069 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1070 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1071 */
1072 function tableNames() {
1073 $inArray = func_get_args();
1074 $retVal = array();
1075 foreach ( $inArray as $name ) {
1076 $retVal[$name] = $this->tableName( $name );
1077 }
1078 return $retVal;
1079 }
1080
1081 /**
1082 * Wrapper for addslashes()
1083 * @param string $s String to be slashed.
1084 * @return string slashed string.
1085 */
1086 function strencode( $s ) {
1087 return addslashes( $s );
1088 }
1089
1090 /**
1091 * If it's a string, adds quotes and backslashes
1092 * Otherwise returns as-is
1093 */
1094 function addQuotes( $s ) {
1095 if ( is_null( $s ) ) {
1096 return 'NULL';
1097 } else {
1098 # This will also quote numeric values. This should be harmless,
1099 # and protects against weird problems that occur when they really
1100 # _are_ strings such as article titles and string->number->string
1101 # conversion is not 1:1.
1102 return "'" . $this->strencode( $s ) . "'";
1103 }
1104 }
1105
1106 /**
1107 * Returns an appropriately quoted sequence value for inserting a new row.
1108 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
1109 * subclass will return an integer, and save the value for insertId()
1110 */
1111 function nextSequenceValue( $seqName ) {
1112 return NULL;
1113 }
1114
1115 /**
1116 * USE INDEX clause
1117 * PostgreSQL doesn't have them and returns ""
1118 */
1119 function useIndexClause( $index ) {
1120 return "USE INDEX ($index)";
1121 }
1122
1123 /**
1124 * REPLACE query wrapper
1125 * PostgreSQL simulates this with a DELETE followed by INSERT
1126 * $row is the row to insert, an associative array
1127 * $uniqueIndexes is an array of indexes. Each element may be either a
1128 * field name or an array of field names
1129 *
1130 * It may be more efficient to leave off unique indexes which are unlikely to collide.
1131 * However if you do this, you run the risk of encountering errors which wouldn't have
1132 * occurred in MySQL
1133 *
1134 * @todo migrate comment to phodocumentor format
1135 */
1136 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
1137 $table = $this->tableName( $table );
1138
1139 # Single row case
1140 if ( !is_array( reset( $rows ) ) ) {
1141 $rows = array( $rows );
1142 }
1143
1144 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) .') VALUES ';
1145 $first = true;
1146 foreach ( $rows as $row ) {
1147 if ( $first ) {
1148 $first = false;
1149 } else {
1150 $sql .= ',';
1151 }
1152 $sql .= '(' . $this->makeList( $row ) . ')';
1153 }
1154 return $this->query( $sql, $fname );
1155 }
1156
1157 /**
1158 * DELETE where the condition is a join
1159 * MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
1160 *
1161 * For safety, an empty $conds will not delete everything. If you want to delete all rows where the
1162 * join condition matches, set $conds='*'
1163 *
1164 * DO NOT put the join condition in $conds
1165 *
1166 * @param string $delTable The table to delete from.
1167 * @param string $joinTable The other table.
1168 * @param string $delVar The variable to join on, in the first table.
1169 * @param string $joinVar The variable to join on, in the second table.
1170 * @param array $conds Condition array of field names mapped to variables, ANDed together in the WHERE clause
1171 */
1172 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'Database::deleteJoin' ) {
1173 if ( !$conds ) {
1174 wfDebugDieBacktrace( 'Database::deleteJoin() called with empty $conds' );
1175 }
1176
1177 $delTable = $this->tableName( $delTable );
1178 $joinTable = $this->tableName( $joinTable );
1179 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1180 if ( $conds != '*' ) {
1181 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND );
1182 }
1183
1184 return $this->query( $sql, $fname );
1185 }
1186
1187 /**
1188 * Returns the size of a text field, or -1 for "unlimited"
1189 */
1190 function textFieldSize( $table, $field ) {
1191 $table = $this->tableName( $table );
1192 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
1193 $res = $this->query( $sql, 'Database::textFieldSize' );
1194 $row = $this->fetchObject( $res );
1195 $this->freeResult( $res );
1196
1197 if ( preg_match( "/\((.*)\)/", $row->Type, $m ) ) {
1198 $size = $m[1];
1199 } else {
1200 $size = -1;
1201 }
1202 return $size;
1203 }
1204
1205 /**
1206 * @return string Returns the text of the low priority option if it is supported, or a blank string otherwise
1207 */
1208 function lowPriorityOption() {
1209 return 'LOW_PRIORITY';
1210 }
1211
1212 /**
1213 * DELETE query wrapper
1214 *
1215 * Use $conds == "*" to delete all rows
1216 */
1217 function delete( $table, $conds, $fname = 'Database::delete' ) {
1218 if ( !$conds ) {
1219 wfDebugDieBacktrace( 'Database::delete() called with no conditions' );
1220 }
1221 $table = $this->tableName( $table );
1222 $sql = "DELETE FROM $table";
1223 if ( $conds != '*' ) {
1224 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
1225 }
1226 return $this->query( $sql, $fname );
1227 }
1228
1229 /**
1230 * INSERT SELECT wrapper
1231 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
1232 * Source items may be literals rather than field names, but strings should be quoted with Database::addQuotes()
1233 * $conds may be "*" to copy the whole table
1234 * srcTable may be an array of tables.
1235 */
1236 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'Database::insertSelect' ) {
1237 $destTable = $this->tableName( $destTable );
1238 if( is_array( $srcTable ) ) {
1239 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
1240 } else {
1241 $srcTable = $this->tableName( $srcTable );
1242 }
1243 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
1244 ' SELECT ' . implode( ',', $varMap ) .
1245 " FROM $srcTable";
1246 if ( $conds != '*' ) {
1247 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
1248 }
1249 return $this->query( $sql, $fname );
1250 }
1251
1252 /**
1253 * Construct a LIMIT query with optional offset
1254 * This is used for query pages
1255 */
1256 function limitResult($limit,$offset) {
1257 return ' LIMIT '.(is_numeric($offset)?"{$offset},":"")."{$limit} ";
1258 }
1259
1260 /**
1261 * Returns an SQL expression for a simple conditional.
1262 * Uses IF on MySQL.
1263 *
1264 * @param string $cond SQL expression which will result in a boolean value
1265 * @param string $trueVal SQL expression to return if true
1266 * @param string $falseVal SQL expression to return if false
1267 * @return string SQL fragment
1268 */
1269 function conditional( $cond, $trueVal, $falseVal ) {
1270 return " IF($cond, $trueVal, $falseVal) ";
1271 }
1272
1273 /**
1274 * Determines if the last failure was due to a deadlock
1275 */
1276 function wasDeadlock() {
1277 return $this->lastErrno() == 1213;
1278 }
1279
1280 /**
1281 * Perform a deadlock-prone transaction.
1282 *
1283 * This function invokes a callback function to perform a set of write
1284 * queries. If a deadlock occurs during the processing, the transaction
1285 * will be rolled back and the callback function will be called again.
1286 *
1287 * Usage:
1288 * $dbw->deadlockLoop( callback, ... );
1289 *
1290 * Extra arguments are passed through to the specified callback function.
1291 *
1292 * Returns whatever the callback function returned on its successful,
1293 * iteration, or false on error, for example if the retry limit was
1294 * reached.
1295 */
1296 function deadlockLoop() {
1297 $myFname = 'Database::deadlockLoop';
1298
1299 $this->query( 'BEGIN', $myFname );
1300 $args = func_get_args();
1301 $function = array_shift( $args );
1302 $oldIgnore = $this->ignoreErrors( true );
1303 $tries = DEADLOCK_TRIES;
1304 if ( is_array( $function ) ) {
1305 $fname = $function[0];
1306 } else {
1307 $fname = $function;
1308 }
1309 do {
1310 $retVal = call_user_func_array( $function, $args );
1311 $error = $this->lastError();
1312 $errno = $this->lastErrno();
1313 $sql = $this->lastQuery();
1314
1315 if ( $errno ) {
1316 if ( $this->wasDeadlock() ) {
1317 # Retry
1318 usleep( mt_rand( DEADLOCK_DELAY_MIN, DEADLOCK_DELAY_MAX ) );
1319 } else {
1320 $this->reportQueryError( $error, $errno, $sql, $fname );
1321 }
1322 }
1323 } while( $this->wasDeadlock() && --$tries > 0 );
1324 $this->ignoreErrors( $oldIgnore );
1325 if ( $tries <= 0 ) {
1326 $this->query( 'ROLLBACK', $myFname );
1327 $this->reportQueryError( $error, $errno, $sql, $fname );
1328 return false;
1329 } else {
1330 $this->query( 'COMMIT', $myFname );
1331 return $retVal;
1332 }
1333 }
1334
1335 /**
1336 * Do a SELECT MASTER_POS_WAIT()
1337 *
1338 * @param string $file the binlog file
1339 * @param string $pos the binlog position
1340 * @param integer $timeout the maximum number of seconds to wait for synchronisation
1341 */
1342 function masterPosWait( $file, $pos, $timeout ) {
1343 $fname = 'Database::masterPosWait';
1344 wfProfileIn( $fname );
1345
1346
1347 # Commit any open transactions
1348 $this->immediateCommit();
1349
1350 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
1351 $encFile = $this->strencode( $file );
1352 $sql = "SELECT MASTER_POS_WAIT('$encFile', $pos, $timeout)";
1353 $res = $this->doQuery( $sql );
1354 if ( $res && $row = $this->fetchRow( $res ) ) {
1355 $this->freeResult( $res );
1356 return $row[0];
1357 } else {
1358 return false;
1359 }
1360 }
1361
1362 /**
1363 * Get the position of the master from SHOW SLAVE STATUS
1364 */
1365 function getSlavePos() {
1366 $res = $this->query( 'SHOW SLAVE STATUS', 'Database::getSlavePos' );
1367 $row = $this->fetchObject( $res );
1368 if ( $row ) {
1369 return array( $row->Master_Log_File, $row->Read_Master_Log_Pos );
1370 } else {
1371 return array( false, false );
1372 }
1373 }
1374
1375 /**
1376 * Get the position of the master from SHOW MASTER STATUS
1377 */
1378 function getMasterPos() {
1379 $res = $this->query( 'SHOW MASTER STATUS', 'Database::getMasterPos' );
1380 $row = $this->fetchObject( $res );
1381 if ( $row ) {
1382 return array( $row->File, $row->Position );
1383 } else {
1384 return array( false, false );
1385 }
1386 }
1387
1388 /**
1389 * Begin a transaction, or if a transaction has already started, continue it
1390 */
1391 function begin( $fname = 'Database::begin' ) {
1392 if ( !$this->mTrxLevel ) {
1393 $this->immediateBegin( $fname );
1394 } else {
1395 $this->mTrxLevel++;
1396 }
1397 }
1398
1399 /**
1400 * End a transaction, or decrement the nest level if transactions are nested
1401 */
1402 function commit( $fname = 'Database::commit' ) {
1403 if ( $this->mTrxLevel ) {
1404 $this->mTrxLevel--;
1405 }
1406 if ( !$this->mTrxLevel ) {
1407 $this->immediateCommit( $fname );
1408 }
1409 }
1410
1411 /**
1412 * Rollback a transaction
1413 */
1414 function rollback( $fname = 'Database::rollback' ) {
1415 $this->query( 'ROLLBACK', $fname );
1416 $this->mTrxLevel = 0;
1417 }
1418
1419 /**
1420 * Begin a transaction, committing any previously open transaction
1421 */
1422 function immediateBegin( $fname = 'Database::immediateBegin' ) {
1423 $this->query( 'BEGIN', $fname );
1424 $this->mTrxLevel = 1;
1425 }
1426
1427 /**
1428 * Commit transaction, if one is open
1429 */
1430 function immediateCommit( $fname = 'Database::immediateCommit' ) {
1431 $this->query( 'COMMIT', $fname );
1432 $this->mTrxLevel = 0;
1433 }
1434
1435 /**
1436 * Return MW-style timestamp used for MySQL schema
1437 */
1438 function timestamp( $ts=0 ) {
1439 return wfTimestamp(TS_MW,$ts);
1440 }
1441
1442 /**
1443 * Local database timestamp format or null
1444 */
1445 function timestampOrNull( $ts = null ) {
1446 if( is_null( $ts ) ) {
1447 return null;
1448 } else {
1449 return $this->timestamp( $ts );
1450 }
1451 }
1452
1453 /**
1454 * @todo document
1455 */
1456 function &resultObject( &$result ) {
1457 if( empty( $result ) ) {
1458 return NULL;
1459 } else {
1460 return new ResultWrapper( $this, $result );
1461 }
1462 }
1463
1464 /**
1465 * Return aggregated value alias
1466 */
1467 function aggregateValue ($valuedata,$valuename='value') {
1468 return $valuename;
1469 }
1470
1471 /**
1472 * @return string wikitext of a link to the server software's web site
1473 */
1474 function getSoftwareLink() {
1475 return "[http://www.mysql.com/ MySQL]";
1476 }
1477
1478 /**
1479 * @return string Version information from the database
1480 */
1481 function getServerVersion() {
1482 return mysql_get_server_info();
1483 }
1484
1485 /**
1486 * Ping the server and try to reconnect if it there is no connection
1487 */
1488 function ping() {
1489 if( function_exists( 'mysql_ping' ) ) {
1490 return mysql_ping( $this->mConn );
1491 } else {
1492 wfDebug( "Tried to call mysql_ping but this is ancient PHP version. Faking it!\n" );
1493 return true;
1494 }
1495 }
1496
1497 /**
1498 * Get slave lag.
1499 * At the moment, this will only work if the DB user has the PROCESS privilege
1500 */
1501 function getLag() {
1502 $res = $this->query( 'SHOW PROCESSLIST' );
1503 # Find slave SQL thread. Assumed to be the second one running, which is a bit
1504 # dubious, but unfortunately there's no easy rigorous way
1505 $slaveThreads = 0;
1506 while ( $row = $this->fetchObject( $res ) ) {
1507 if ( $row->User == 'system user' ) {
1508 if ( ++$slaveThreads == 2 ) {
1509 # This is it, return the time
1510 return $row->Time;
1511 }
1512 }
1513 }
1514 return false;
1515 }
1516
1517 /**
1518 * Get status information from SHOW STATUS in an associative array
1519 */
1520 function getStatus() {
1521 $res = $this->query( 'SHOW STATUS' );
1522 $status = array();
1523 while ( $row = $this->fetchObject( $res ) ) {
1524 $status[$row->Variable_name] = $row->Value;
1525 }
1526 return $status;
1527 }
1528 }
1529
1530 /**
1531 * Database abstraction object for mySQL
1532 * Inherit all methods and properties of Database::Database()
1533 *
1534 * @package MediaWiki
1535 * @see Database
1536 */
1537 class DatabaseMysql extends Database {
1538 # Inherit all
1539 }
1540
1541
1542 /**
1543 * Result wrapper for grabbing data queried by someone else
1544 *
1545 * @package MediaWiki
1546 */
1547 class ResultWrapper {
1548 var $db, $result;
1549
1550 /**
1551 * @todo document
1552 */
1553 function ResultWrapper( $database, $result ) {
1554 $this->db =& $database;
1555 $this->result =& $result;
1556 }
1557
1558 /**
1559 * @todo document
1560 */
1561 function numRows() {
1562 return $this->db->numRows( $this->result );
1563 }
1564
1565 /**
1566 * @todo document
1567 */
1568 function &fetchObject() {
1569 return $this->db->fetchObject( $this->result );
1570 }
1571
1572 /**
1573 * @todo document
1574 */
1575 function &fetchRow() {
1576 return $this->db->fetchRow( $this->result );
1577 }
1578
1579 /**
1580 * @todo document
1581 */
1582 function free() {
1583 $this->db->freeResult( $this->result );
1584 unset( $this->result );
1585 unset( $this->db );
1586 }
1587
1588 function seek( $row ) {
1589 $this->db->dataSeek( $this->result, $row );
1590 }
1591 }
1592
1593 #------------------------------------------------------------------------------
1594 # Global functions
1595 #------------------------------------------------------------------------------
1596
1597 /**
1598 * Standard fail function, called by default when a connection cannot be
1599 * established.
1600 * Displays the file cache if possible
1601 */
1602 function wfEmergencyAbort( &$conn, $error ) {
1603 global $wgTitle, $wgUseFileCache, $title, $wgInputEncoding, $wgOutputEncoding;
1604 global $wgSitename, $wgServer;
1605
1606 # I give up, Brion is right. Getting the message cache to work when there is no DB is tricky.
1607 # Hard coding strings instead.
1608
1609 $noconnect = 'Sorry! The wiki is experiencing some technical difficulties, and cannot contact the database server. <br />
1610 $1';
1611 $mainpage = 'Main Page';
1612 $searchdisabled = <<<EOT
1613 <p style="margin: 1.5em 2em 1em">$wgSitename search is disabled for performance reasons. You can search via Google in the meantime.
1614 <span style="font-size: 89%; display: block; margin-left: .2em">Note that their indexes of $wgSitename content may be out of date.</span></p>',
1615 EOT;
1616
1617 $googlesearch = "
1618 <!-- SiteSearch Google -->
1619 <FORM method=GET action=\"http://www.google.com/search\">
1620 <TABLE bgcolor=\"#FFFFFF\"><tr><td>
1621 <A HREF=\"http://www.google.com/\">
1622 <IMG SRC=\"http://www.google.com/logos/Logo_40wht.gif\"
1623 border=\"0\" ALT=\"Google\"></A>
1624 </td>
1625 <td>
1626 <INPUT TYPE=text name=q size=31 maxlength=255 value=\"$1\">
1627 <INPUT type=submit name=btnG VALUE=\"Google Search\">
1628 <font size=-1>
1629 <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 />
1630 <input type='hidden' name='ie' value='$2'>
1631 <input type='hidden' name='oe' value='$2'>
1632 </font>
1633 </td></tr></TABLE>
1634 </FORM>
1635 <!-- SiteSearch Google -->";
1636 $cachederror = "The following is a cached copy of the requested page, and may not be up to date. ";
1637
1638
1639 if( !headers_sent() ) {
1640 header( 'HTTP/1.0 500 Internal Server Error' );
1641 header( 'Content-type: text/html; charset='.$wgOutputEncoding );
1642 /* Don't cache error pages! They cause no end of trouble... */
1643 header( 'Cache-control: none' );
1644 header( 'Pragma: nocache' );
1645 }
1646 $msg = wfGetSiteNotice();
1647 if($msg == '') {
1648 $msg = str_replace( '$1', $error, $noconnect );
1649 }
1650 $text = $msg;
1651
1652 if($wgUseFileCache) {
1653 if($wgTitle) {
1654 $t =& $wgTitle;
1655 } else {
1656 if($title) {
1657 $t = Title::newFromURL( $title );
1658 } elseif (@/**/$_REQUEST['search']) {
1659 $search = $_REQUEST['search'];
1660 echo $searchdisabled;
1661 echo str_replace( array( '$1', '$2' ), array( htmlspecialchars( $search ),
1662 $wgInputEncoding ), $googlesearch );
1663 wfErrorExit();
1664 } else {
1665 $t = Title::newFromText( $mainpage );
1666 }
1667 }
1668
1669 $cache = new CacheManager( $t );
1670 if( $cache->isFileCached() ) {
1671 $msg = '<p style="color: red"><b>'.$msg."<br />\n" .
1672 $cachederror . "</b></p>\n";
1673
1674 $tag = '<div id="article">';
1675 $text = str_replace(
1676 $tag,
1677 $tag . $msg,
1678 $cache->fetchPageText() );
1679 }
1680 }
1681
1682 echo $text;
1683 wfErrorExit();
1684 }
1685
1686 ?>