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