typo
[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 global $wgDBmysql4;
1182 return $wgDBmysql4
1183 ? "FORCE INDEX ($index)"
1184 : "USE INDEX ($index)";
1185 }
1186
1187 /**
1188 * REPLACE query wrapper
1189 * PostgreSQL simulates this with a DELETE followed by INSERT
1190 * $row is the row to insert, an associative array
1191 * $uniqueIndexes is an array of indexes. Each element may be either a
1192 * field name or an array of field names
1193 *
1194 * It may be more efficient to leave off unique indexes which are unlikely to collide.
1195 * However if you do this, you run the risk of encountering errors which wouldn't have
1196 * occurred in MySQL
1197 *
1198 * @todo migrate comment to phodocumentor format
1199 */
1200 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
1201 $table = $this->tableName( $table );
1202
1203 # Single row case
1204 if ( !is_array( reset( $rows ) ) ) {
1205 $rows = array( $rows );
1206 }
1207
1208 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) .') VALUES ';
1209 $first = true;
1210 foreach ( $rows as $row ) {
1211 if ( $first ) {
1212 $first = false;
1213 } else {
1214 $sql .= ',';
1215 }
1216 $sql .= '(' . $this->makeList( $row ) . ')';
1217 }
1218 return $this->query( $sql, $fname );
1219 }
1220
1221 /**
1222 * DELETE where the condition is a join
1223 * MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
1224 *
1225 * For safety, an empty $conds will not delete everything. If you want to delete all rows where the
1226 * join condition matches, set $conds='*'
1227 *
1228 * DO NOT put the join condition in $conds
1229 *
1230 * @param string $delTable The table to delete from.
1231 * @param string $joinTable The other table.
1232 * @param string $delVar The variable to join on, in the first table.
1233 * @param string $joinVar The variable to join on, in the second table.
1234 * @param array $conds Condition array of field names mapped to variables, ANDed together in the WHERE clause
1235 */
1236 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'Database::deleteJoin' ) {
1237 if ( !$conds ) {
1238 wfDebugDieBacktrace( 'Database::deleteJoin() called with empty $conds' );
1239 }
1240
1241 $delTable = $this->tableName( $delTable );
1242 $joinTable = $this->tableName( $joinTable );
1243 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1244 if ( $conds != '*' ) {
1245 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND );
1246 }
1247
1248 return $this->query( $sql, $fname );
1249 }
1250
1251 /**
1252 * Returns the size of a text field, or -1 for "unlimited"
1253 */
1254 function textFieldSize( $table, $field ) {
1255 $table = $this->tableName( $table );
1256 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
1257 $res = $this->query( $sql, 'Database::textFieldSize' );
1258 $row = $this->fetchObject( $res );
1259 $this->freeResult( $res );
1260
1261 if ( preg_match( "/\((.*)\)/", $row->Type, $m ) ) {
1262 $size = $m[1];
1263 } else {
1264 $size = -1;
1265 }
1266 return $size;
1267 }
1268
1269 /**
1270 * @return string Returns the text of the low priority option if it is supported, or a blank string otherwise
1271 */
1272 function lowPriorityOption() {
1273 return 'LOW_PRIORITY';
1274 }
1275
1276 /**
1277 * DELETE query wrapper
1278 *
1279 * Use $conds == "*" to delete all rows
1280 */
1281 function delete( $table, $conds, $fname = 'Database::delete' ) {
1282 if ( !$conds ) {
1283 wfDebugDieBacktrace( 'Database::delete() called with no conditions' );
1284 }
1285 $table = $this->tableName( $table );
1286 $sql = "DELETE FROM $table";
1287 if ( $conds != '*' ) {
1288 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
1289 }
1290 return $this->query( $sql, $fname );
1291 }
1292
1293 /**
1294 * INSERT SELECT wrapper
1295 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
1296 * Source items may be literals rather than field names, but strings should be quoted with Database::addQuotes()
1297 * $conds may be "*" to copy the whole table
1298 * srcTable may be an array of tables.
1299 */
1300 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'Database::insertSelect' ) {
1301 $destTable = $this->tableName( $destTable );
1302 if( is_array( $srcTable ) ) {
1303 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
1304 } else {
1305 $srcTable = $this->tableName( $srcTable );
1306 }
1307 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
1308 ' SELECT ' . implode( ',', $varMap ) .
1309 " FROM $srcTable";
1310 if ( $conds != '*' ) {
1311 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
1312 }
1313 return $this->query( $sql, $fname );
1314 }
1315
1316 /**
1317 * Construct a LIMIT query with optional offset
1318 * This is used for query pages
1319 * $sql string SQL query we will append the limit too
1320 * $limit integer the SQL limit
1321 * $offset integer the SQL offset (default false)
1322 */
1323 function limitResult($sql, $limit, $offset=false) {
1324 return " $sql LIMIT ".((is_numeric($offset) && $offset != 0)?"{$offset},":"")."{$limit} ";
1325 }
1326 function limitResultForUpdate($sql, $num) {
1327 return $this->limitResult($sql, $num, 0);
1328 }
1329
1330 /**
1331 * Returns an SQL expression for a simple conditional.
1332 * Uses IF on MySQL.
1333 *
1334 * @param string $cond SQL expression which will result in a boolean value
1335 * @param string $trueVal SQL expression to return if true
1336 * @param string $falseVal SQL expression to return if false
1337 * @return string SQL fragment
1338 */
1339 function conditional( $cond, $trueVal, $falseVal ) {
1340 return " IF($cond, $trueVal, $falseVal) ";
1341 }
1342
1343 /**
1344 * Determines if the last failure was due to a deadlock
1345 */
1346 function wasDeadlock() {
1347 return $this->lastErrno() == 1213;
1348 }
1349
1350 /**
1351 * Perform a deadlock-prone transaction.
1352 *
1353 * This function invokes a callback function to perform a set of write
1354 * queries. If a deadlock occurs during the processing, the transaction
1355 * will be rolled back and the callback function will be called again.
1356 *
1357 * Usage:
1358 * $dbw->deadlockLoop( callback, ... );
1359 *
1360 * Extra arguments are passed through to the specified callback function.
1361 *
1362 * Returns whatever the callback function returned on its successful,
1363 * iteration, or false on error, for example if the retry limit was
1364 * reached.
1365 */
1366 function deadlockLoop() {
1367 $myFname = 'Database::deadlockLoop';
1368
1369 $this->begin();
1370 $args = func_get_args();
1371 $function = array_shift( $args );
1372 $oldIgnore = $this->ignoreErrors( true );
1373 $tries = DEADLOCK_TRIES;
1374 if ( is_array( $function ) ) {
1375 $fname = $function[0];
1376 } else {
1377 $fname = $function;
1378 }
1379 do {
1380 $retVal = call_user_func_array( $function, $args );
1381 $error = $this->lastError();
1382 $errno = $this->lastErrno();
1383 $sql = $this->lastQuery();
1384
1385 if ( $errno ) {
1386 if ( $this->wasDeadlock() ) {
1387 # Retry
1388 usleep( mt_rand( DEADLOCK_DELAY_MIN, DEADLOCK_DELAY_MAX ) );
1389 } else {
1390 $this->reportQueryError( $error, $errno, $sql, $fname );
1391 }
1392 }
1393 } while( $this->wasDeadlock() && --$tries > 0 );
1394 $this->ignoreErrors( $oldIgnore );
1395 if ( $tries <= 0 ) {
1396 $this->query( 'ROLLBACK', $myFname );
1397 $this->reportQueryError( $error, $errno, $sql, $fname );
1398 return false;
1399 } else {
1400 $this->query( 'COMMIT', $myFname );
1401 return $retVal;
1402 }
1403 }
1404
1405 /**
1406 * Do a SELECT MASTER_POS_WAIT()
1407 *
1408 * @param string $file the binlog file
1409 * @param string $pos the binlog position
1410 * @param integer $timeout the maximum number of seconds to wait for synchronisation
1411 */
1412 function masterPosWait( $file, $pos, $timeout ) {
1413 $fname = 'Database::masterPosWait';
1414 wfProfileIn( $fname );
1415
1416
1417 # Commit any open transactions
1418 $this->immediateCommit();
1419
1420 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
1421 $encFile = $this->strencode( $file );
1422 $sql = "SELECT MASTER_POS_WAIT('$encFile', $pos, $timeout)";
1423 $res = $this->doQuery( $sql );
1424 if ( $res && $row = $this->fetchRow( $res ) ) {
1425 $this->freeResult( $res );
1426 wfProfileOut( $fname );
1427 return $row[0];
1428 } else {
1429 wfProfileOut( $fname );
1430 return false;
1431 }
1432 }
1433
1434 /**
1435 * Get the position of the master from SHOW SLAVE STATUS
1436 */
1437 function getSlavePos() {
1438 $res = $this->query( 'SHOW SLAVE STATUS', 'Database::getSlavePos' );
1439 $row = $this->fetchObject( $res );
1440 if ( $row ) {
1441 return array( $row->Master_Log_File, $row->Read_Master_Log_Pos );
1442 } else {
1443 return array( false, false );
1444 }
1445 }
1446
1447 /**
1448 * Get the position of the master from SHOW MASTER STATUS
1449 */
1450 function getMasterPos() {
1451 $res = $this->query( 'SHOW MASTER STATUS', 'Database::getMasterPos' );
1452 $row = $this->fetchObject( $res );
1453 if ( $row ) {
1454 return array( $row->File, $row->Position );
1455 } else {
1456 return array( false, false );
1457 }
1458 }
1459
1460 /**
1461 * Begin a transaction, or if a transaction has already started, continue it
1462 */
1463 function begin( $fname = 'Database::begin' ) {
1464 if ( !$this->mTrxLevel ) {
1465 $this->immediateBegin( $fname );
1466 } else {
1467 $this->mTrxLevel++;
1468 }
1469 }
1470
1471 /**
1472 * End a transaction, or decrement the nest level if transactions are nested
1473 */
1474 function commit( $fname = 'Database::commit' ) {
1475 if ( $this->mTrxLevel ) {
1476 $this->mTrxLevel--;
1477 }
1478 if ( !$this->mTrxLevel ) {
1479 $this->immediateCommit( $fname );
1480 }
1481 }
1482
1483 /**
1484 * Rollback a transaction
1485 */
1486 function rollback( $fname = 'Database::rollback' ) {
1487 $this->query( 'ROLLBACK', $fname );
1488 $this->mTrxLevel = 0;
1489 }
1490
1491 /**
1492 * Begin a transaction, committing any previously open transaction
1493 */
1494 function immediateBegin( $fname = 'Database::immediateBegin' ) {
1495 $this->query( 'BEGIN', $fname );
1496 $this->mTrxLevel = 1;
1497 }
1498
1499 /**
1500 * Commit transaction, if one is open
1501 */
1502 function immediateCommit( $fname = 'Database::immediateCommit' ) {
1503 $this->query( 'COMMIT', $fname );
1504 $this->mTrxLevel = 0;
1505 }
1506
1507 /**
1508 * Return MW-style timestamp used for MySQL schema
1509 */
1510 function timestamp( $ts=0 ) {
1511 return wfTimestamp(TS_MW,$ts);
1512 }
1513
1514 /**
1515 * Local database timestamp format or null
1516 */
1517 function timestampOrNull( $ts = null ) {
1518 if( is_null( $ts ) ) {
1519 return null;
1520 } else {
1521 return $this->timestamp( $ts );
1522 }
1523 }
1524
1525 /**
1526 * @todo document
1527 */
1528 function resultObject( &$result ) {
1529 if( empty( $result ) ) {
1530 return NULL;
1531 } else {
1532 return new ResultWrapper( $this, $result );
1533 }
1534 }
1535
1536 /**
1537 * Return aggregated value alias
1538 */
1539 function aggregateValue ($valuedata,$valuename='value') {
1540 return $valuename;
1541 }
1542
1543 /**
1544 * @return string wikitext of a link to the server software's web site
1545 */
1546 function getSoftwareLink() {
1547 return "[http://www.mysql.com/ MySQL]";
1548 }
1549
1550 /**
1551 * @return string Version information from the database
1552 */
1553 function getServerVersion() {
1554 return mysql_get_server_info();
1555 }
1556
1557 /**
1558 * Ping the server and try to reconnect if it there is no connection
1559 */
1560 function ping() {
1561 if( function_exists( 'mysql_ping' ) ) {
1562 return mysql_ping( $this->mConn );
1563 } else {
1564 wfDebug( "Tried to call mysql_ping but this is ancient PHP version. Faking it!\n" );
1565 return true;
1566 }
1567 }
1568
1569 /**
1570 * Get slave lag.
1571 * At the moment, this will only work if the DB user has the PROCESS privilege
1572 */
1573 function getLag() {
1574 $res = $this->query( 'SHOW PROCESSLIST' );
1575 # Find slave SQL thread. Assumed to be the second one running, which is a bit
1576 # dubious, but unfortunately there's no easy rigorous way
1577 $slaveThreads = 0;
1578 while ( $row = $this->fetchObject( $res ) ) {
1579 if ( $row->User == 'system user' ) {
1580 if ( ++$slaveThreads == 2 ) {
1581 # This is it, return the time
1582 return $row->Time;
1583 }
1584 }
1585 }
1586 return false;
1587 }
1588
1589 /**
1590 * Get status information from SHOW STATUS in an associative array
1591 */
1592 function getStatus() {
1593 $res = $this->query( 'SHOW STATUS' );
1594 $status = array();
1595 while ( $row = $this->fetchObject( $res ) ) {
1596 $status[$row->Variable_name] = $row->Value;
1597 }
1598 return $status;
1599 }
1600
1601 /**
1602 * Return the maximum number of items allowed in a list, or 0 for unlimited.
1603 */
1604 function maxListLen() {
1605 return 0;
1606 }
1607
1608 function encodeBlob($b) {
1609 return $b;
1610 }
1611
1612 function notNullTimestamp() {
1613 return "!= 0";
1614 }
1615 function isNullTimestamp() {
1616 return "= '0'";
1617 }
1618 }
1619
1620 /**
1621 * Database abstraction object for mySQL
1622 * Inherit all methods and properties of Database::Database()
1623 *
1624 * @package MediaWiki
1625 * @see Database
1626 */
1627 class DatabaseMysql extends Database {
1628 # Inherit all
1629 }
1630
1631
1632 /**
1633 * Result wrapper for grabbing data queried by someone else
1634 *
1635 * @package MediaWiki
1636 */
1637 class ResultWrapper {
1638 var $db, $result;
1639
1640 /**
1641 * @todo document
1642 */
1643 function ResultWrapper( $database, $result ) {
1644 $this->db =& $database;
1645 $this->result =& $result;
1646 }
1647
1648 /**
1649 * @todo document
1650 */
1651 function numRows() {
1652 return $this->db->numRows( $this->result );
1653 }
1654
1655 /**
1656 * @todo document
1657 */
1658 function fetchObject() {
1659 return $this->db->fetchObject( $this->result );
1660 }
1661
1662 /**
1663 * @todo document
1664 */
1665 function &fetchRow() {
1666 return $this->db->fetchRow( $this->result );
1667 }
1668
1669 /**
1670 * @todo document
1671 */
1672 function free() {
1673 $this->db->freeResult( $this->result );
1674 unset( $this->result );
1675 unset( $this->db );
1676 }
1677
1678 function seek( $row ) {
1679 $this->db->dataSeek( $this->result, $row );
1680 }
1681 }
1682
1683 #------------------------------------------------------------------------------
1684 # Global functions
1685 #------------------------------------------------------------------------------
1686
1687 /**
1688 * Standard fail function, called by default when a connection cannot be
1689 * established.
1690 * Displays the file cache if possible
1691 */
1692 function wfEmergencyAbort( &$conn, $error ) {
1693 global $wgTitle, $wgUseFileCache, $title, $wgInputEncoding, $wgOutputEncoding;
1694 global $wgSitename, $wgServer, $wgMessageCache;
1695
1696 # I give up, Brion is right. Getting the message cache to work when there is no DB is tricky.
1697 # Hard coding strings instead.
1698
1699 $noconnect = 'Sorry! The wiki is experiencing some technical difficulties, and cannot contact the database server: $1. <br />
1700 $1';
1701 $mainpage = 'Main Page';
1702 $searchdisabled = <<<EOT
1703 <p style="margin: 1.5em 2em 1em">$wgSitename search is disabled for performance reasons. You can search via Google in the meantime.
1704 <span style="font-size: 89%; display: block; margin-left: .2em">Note that their indexes of $wgSitename content may be out of date.</span></p>',
1705 EOT;
1706
1707 $googlesearch = "
1708 <!-- SiteSearch Google -->
1709 <FORM method=GET action=\"http://www.google.com/search\">
1710 <TABLE bgcolor=\"#FFFFFF\"><tr><td>
1711 <A HREF=\"http://www.google.com/\">
1712 <IMG SRC=\"http://www.google.com/logos/Logo_40wht.gif\"
1713 border=\"0\" ALT=\"Google\"></A>
1714 </td>
1715 <td>
1716 <INPUT TYPE=text name=q size=31 maxlength=255 value=\"$1\">
1717 <INPUT type=submit name=btnG VALUE=\"Google Search\">
1718 <font size=-1>
1719 <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 />
1720 <input type='hidden' name='ie' value='$2'>
1721 <input type='hidden' name='oe' value='$2'>
1722 </font>
1723 </td></tr></TABLE>
1724 </FORM>
1725 <!-- SiteSearch Google -->";
1726 $cachederror = "The following is a cached copy of the requested page, and may not be up to date. ";
1727
1728
1729 if( !headers_sent() ) {
1730 header( 'HTTP/1.0 500 Internal Server Error' );
1731 header( 'Content-type: text/html; charset='.$wgOutputEncoding );
1732 /* Don't cache error pages! They cause no end of trouble... */
1733 header( 'Cache-control: none' );
1734 header( 'Pragma: nocache' );
1735 }
1736
1737 # No database access
1738 if ( is_object( $wgMessageCache ) ) {
1739 $wgMessageCache->disable();
1740 }
1741
1742 $msg = wfGetSiteNotice();
1743 if($msg == '') {
1744 $msg = str_replace( '$1', $error, $noconnect );
1745 }
1746 $text = $msg;
1747
1748 if($wgUseFileCache) {
1749 if($wgTitle) {
1750 $t =& $wgTitle;
1751 } else {
1752 if($title) {
1753 $t = Title::newFromURL( $title );
1754 } elseif (@/**/$_REQUEST['search']) {
1755 $search = $_REQUEST['search'];
1756 echo $searchdisabled;
1757 echo str_replace( array( '$1', '$2' ), array( htmlspecialchars( $search ),
1758 $wgInputEncoding ), $googlesearch );
1759 wfErrorExit();
1760 } else {
1761 $t = Title::newFromText( $mainpage );
1762 }
1763 }
1764
1765 $cache = new CacheManager( $t );
1766 if( $cache->isFileCached() ) {
1767 $msg = '<p style="color: red"><b>'.$msg."<br />\n" .
1768 $cachederror . "</b></p>\n";
1769
1770 $tag = '<div id="article">';
1771 $text = str_replace(
1772 $tag,
1773 $tag . $msg,
1774 $cache->fetchPageText() );
1775 }
1776 }
1777
1778 echo $text;
1779 wfErrorExit();
1780 }
1781
1782 ?>