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