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