* Using $wgContLang->ucfirst() instead of $wgLang->ucfirst() in loadFromFile() and...
[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'] ) && ! is_array( $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 if ( @is_array( $options['USE INDEX'] ) )
742 $from = ' FROM ' . $this->tableNamesWithUseIndex( $table, $options['USE INDEX'] );
743 else
744 $from = ' FROM ' . implode( ',', array_map( array( &$this, 'tableName' ), $table ) );
745 } elseif ($table!='') {
746 $from = ' FROM ' . $this->tableName( $table );
747 } else {
748 $from = '';
749 }
750
751 list( $useIndex, $tailOpts ) = $this->makeSelectOptions( $options );
752
753 if( !empty( $conds ) ) {
754 if ( is_array( $conds ) ) {
755 $conds = $this->makeList( $conds, LIST_AND );
756 }
757 $sql = "SELECT $vars $from $useIndex WHERE $conds $tailOpts";
758 } else {
759 $sql = "SELECT $vars $from $useIndex $tailOpts";
760 }
761
762 return $this->query( $sql, $fname );
763 }
764
765 /**
766 * Single row SELECT wrapper
767 * Aborts or returns FALSE on error
768 *
769 * $vars: the selected variables
770 * $conds: a condition map, terms are ANDed together.
771 * Items with numeric keys are taken to be literal conditions
772 * Takes an array of selected variables, and a condition map, which is ANDed
773 * e.g: selectRow( "page", array( "page_id" ), array( "page_namespace" =>
774 * NS_MAIN, "page_title" => "Astronomy" ) ) would return an object where
775 * $obj- >page_id is the ID of the Astronomy article
776 *
777 * @todo migrate documentation to phpdocumentor format
778 */
779 function selectRow( $table, $vars, $conds, $fname = 'Database::selectRow', $options = array() ) {
780 $options['LIMIT'] = 1;
781 $res = $this->select( $table, $vars, $conds, $fname, $options );
782 if ( $res === false )
783 return false;
784 if ( !$this->numRows($res) ) {
785 $this->freeResult($res);
786 return false;
787 }
788 $obj = $this->fetchObject( $res );
789 $this->freeResult( $res );
790 return $obj;
791
792 }
793
794 /**
795 * Removes most variables from an SQL query and replaces them with X or N for numbers.
796 * It's only slightly flawed. Don't use for anything important.
797 *
798 * @param string $sql A SQL Query
799 * @static
800 */
801 function generalizeSQL( $sql ) {
802 # This does the same as the regexp below would do, but in such a way
803 # as to avoid crashing php on some large strings.
804 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
805
806 $sql = str_replace ( "\\\\", '', $sql);
807 $sql = str_replace ( "\\'", '', $sql);
808 $sql = str_replace ( "\\\"", '', $sql);
809 $sql = preg_replace ("/'.*'/s", "'X'", $sql);
810 $sql = preg_replace ('/".*"/s', "'X'", $sql);
811
812 # All newlines, tabs, etc replaced by single space
813 $sql = preg_replace ( "/\s+/", ' ', $sql);
814
815 # All numbers => N
816 $sql = preg_replace ('/-?[0-9]+/s', 'N', $sql);
817
818 return $sql;
819 }
820
821 /**
822 * Determines whether a field exists in a table
823 * Usually aborts on failure
824 * If errors are explicitly ignored, returns NULL on failure
825 */
826 function fieldExists( $table, $field, $fname = 'Database::fieldExists' ) {
827 $table = $this->tableName( $table );
828 $res = $this->query( 'DESCRIBE '.$table, DB_SLAVE, $fname );
829 if ( !$res ) {
830 return NULL;
831 }
832
833 $found = false;
834
835 while ( $row = $this->fetchObject( $res ) ) {
836 if ( $row->Field == $field ) {
837 $found = true;
838 break;
839 }
840 }
841 return $found;
842 }
843
844 /**
845 * Determines whether an index exists
846 * Usually aborts on failure
847 * If errors are explicitly ignored, returns NULL on failure
848 */
849 function indexExists( $table, $index, $fname = 'Database::indexExists' ) {
850 $info = $this->indexInfo( $table, $index, $fname );
851 if ( is_null( $info ) ) {
852 return NULL;
853 } else {
854 return $info !== false;
855 }
856 }
857
858
859 /**
860 * Get information about an index into an object
861 * Returns false if the index does not exist
862 */
863 function indexInfo( $table, $index, $fname = 'Database::indexInfo' ) {
864 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
865 # SHOW INDEX should work for 3.x and up:
866 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
867 $table = $this->tableName( $table );
868 $sql = 'SHOW INDEX FROM '.$table;
869 $res = $this->query( $sql, $fname );
870 if ( !$res ) {
871 return NULL;
872 }
873
874 while ( $row = $this->fetchObject( $res ) ) {
875 if ( $row->Key_name == $index ) {
876 return $row;
877 }
878 }
879 return false;
880 }
881
882 /**
883 * Query whether a given table exists
884 */
885 function tableExists( $table ) {
886 $table = $this->tableName( $table );
887 $old = $this->ignoreErrors( true );
888 $res = $this->query( "SELECT 1 FROM $table LIMIT 1" );
889 $this->ignoreErrors( $old );
890 if( $res ) {
891 $this->freeResult( $res );
892 return true;
893 } else {
894 return false;
895 }
896 }
897
898 /**
899 * mysql_fetch_field() wrapper
900 * Returns false if the field doesn't exist
901 *
902 * @param $table
903 * @param $field
904 */
905 function fieldInfo( $table, $field ) {
906 $table = $this->tableName( $table );
907 $res = $this->query( "SELECT * FROM $table LIMIT 1" );
908 $n = mysql_num_fields( $res );
909 for( $i = 0; $i < $n; $i++ ) {
910 $meta = mysql_fetch_field( $res, $i );
911 if( $field == $meta->name ) {
912 return $meta;
913 }
914 }
915 return false;
916 }
917
918 /**
919 * mysql_field_type() wrapper
920 */
921 function fieldType( $res, $index ) {
922 return mysql_field_type( $res, $index );
923 }
924
925 /**
926 * Determines if a given index is unique
927 */
928 function indexUnique( $table, $index ) {
929 $indexInfo = $this->indexInfo( $table, $index );
930 if ( !$indexInfo ) {
931 return NULL;
932 }
933 return !$indexInfo->Non_unique;
934 }
935
936 /**
937 * INSERT wrapper, inserts an array into a table
938 *
939 * $a may be a single associative array, or an array of these with numeric keys, for
940 * multi-row insert.
941 *
942 * Usually aborts on failure
943 * If errors are explicitly ignored, returns success
944 */
945 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
946 # No rows to insert, easy just return now
947 if ( !count( $a ) ) {
948 return true;
949 }
950
951 $table = $this->tableName( $table );
952 if ( !is_array( $options ) ) {
953 $options = array( $options );
954 }
955 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
956 $multi = true;
957 $keys = array_keys( $a[0] );
958 } else {
959 $multi = false;
960 $keys = array_keys( $a );
961 }
962
963 $sql = 'INSERT ' . implode( ' ', $options ) .
964 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
965
966 if ( $multi ) {
967 $first = true;
968 foreach ( $a as $row ) {
969 if ( $first ) {
970 $first = false;
971 } else {
972 $sql .= ',';
973 }
974 $sql .= '(' . $this->makeList( $row ) . ')';
975 }
976 } else {
977 $sql .= '(' . $this->makeList( $a ) . ')';
978 }
979 return (bool)$this->query( $sql, $fname );
980 }
981
982 /**
983 * Make UPDATE options for the Database::update function
984 *
985 * @access private
986 * @param array $options The options passed to Database::update
987 * @return string
988 */
989 function makeUpdateOptions( $options ) {
990 if( !is_array( $options ) ) {
991 $options = array( $options );
992 }
993 $opts = array();
994 if ( in_array( 'LOW_PRIORITY', $options ) )
995 $opts[] = $this->lowPriorityOption();
996 if ( in_array( 'IGNORE', $options ) )
997 $opts[] = 'IGNORE';
998 return implode(' ', $opts);
999 }
1000
1001 /**
1002 * UPDATE wrapper, takes a condition array and a SET array
1003 *
1004 * @param string $table The table to UPDATE
1005 * @param array $values An array of values to SET
1006 * @param array $conds An array of conditions (WHERE)
1007 * @param string $fname The Class::Function calling this function
1008 * (for the log)
1009 * @param array $options An array of UPDATE options, can be one or
1010 * more of IGNORE, LOW_PRIORITY
1011 */
1012 function update( $table, $values, $conds, $fname = 'Database::update', $options = array() ) {
1013 $table = $this->tableName( $table );
1014 $opts = $this->makeUpdateOptions( $options );
1015 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET );
1016 if ( $conds != '*' ) {
1017 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND );
1018 }
1019 $this->query( $sql, $fname );
1020 }
1021
1022 /**
1023 * Makes a wfStrencoded list from an array
1024 * $mode: LIST_COMMA - comma separated, no field names
1025 * LIST_AND - ANDed WHERE clause (without the WHERE)
1026 * LIST_SET - comma separated with field names, like a SET clause
1027 * LIST_NAMES - comma separated field names
1028 */
1029 function makeList( $a, $mode = LIST_COMMA ) {
1030 if ( !is_array( $a ) ) {
1031 wfDebugDieBacktrace( 'Database::makeList called with incorrect parameters' );
1032 }
1033
1034 $first = true;
1035 $list = '';
1036 foreach ( $a as $field => $value ) {
1037 if ( !$first ) {
1038 if ( $mode == LIST_AND ) {
1039 $list .= ' AND ';
1040 } elseif($mode == LIST_OR) {
1041 $list .= ' OR ';
1042 } else {
1043 $list .= ',';
1044 }
1045 } else {
1046 $first = false;
1047 }
1048 if ( ($mode == LIST_AND || $mode == LIST_OR) && is_numeric( $field ) ) {
1049 $list .= "($value)";
1050 } elseif ( $mode == LIST_AND && is_array ($value) ) {
1051 $list .= $field." IN (".$this->makeList($value).") ";
1052 } else {
1053 if ( $mode == LIST_AND || $mode == LIST_OR || $mode == LIST_SET ) {
1054 $list .= "$field = ";
1055 }
1056 $list .= $mode == LIST_NAMES ? $value : $this->addQuotes( $value );
1057 }
1058 }
1059 return $list;
1060 }
1061
1062 /**
1063 * Change the current database
1064 */
1065 function selectDB( $db ) {
1066 $this->mDBname = $db;
1067 return mysql_select_db( $db, $this->mConn );
1068 }
1069
1070 /**
1071 * Starts a timer which will kill the DB thread after $timeout seconds
1072 */
1073 function startTimer( $timeout ) {
1074 global $IP;
1075 if( function_exists( 'mysql_thread_id' ) ) {
1076 # This will kill the query if it's still running after $timeout seconds.
1077 $tid = mysql_thread_id( $this->mConn );
1078 exec( "php $IP/includes/killthread.php $timeout $tid &>/dev/null &" );
1079 }
1080 }
1081
1082 /**
1083 * Stop a timer started by startTimer()
1084 * Currently unimplemented.
1085 *
1086 */
1087 function stopTimer() { }
1088
1089 /**
1090 * Format a table name ready for use in constructing an SQL query
1091 *
1092 * This does two important things: it quotes table names which as necessary,
1093 * and it adds a table prefix if there is one.
1094 *
1095 * All functions of this object which require a table name call this function
1096 * themselves. Pass the canonical name to such functions. This is only needed
1097 * when calling query() directly.
1098 *
1099 * @param string $name database table name
1100 */
1101 function tableName( $name ) {
1102 global $wgSharedDB;
1103 # Skip quoted literals
1104 if ( $name{0} != '`' ) {
1105 if ( $this->mTablePrefix !== '' && strpos( '.', $name ) === false ) {
1106 $name = "{$this->mTablePrefix}$name";
1107 }
1108 if ( isset( $wgSharedDB ) && "{$this->mTablePrefix}user" == $name ) {
1109 $name = "`$wgSharedDB`.`$name`";
1110 } else {
1111 # Standard quoting
1112 $name = "`$name`";
1113 }
1114 }
1115 return $name;
1116 }
1117
1118 /**
1119 * Fetch a number of table names into an array
1120 * This is handy when you need to construct SQL for joins
1121 *
1122 * Example:
1123 * extract($dbr->tableNames('user','watchlist'));
1124 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1125 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1126 */
1127 function tableNames() {
1128 $inArray = func_get_args();
1129 $retVal = array();
1130 foreach ( $inArray as $name ) {
1131 $retVal[$name] = $this->tableName( $name );
1132 }
1133 return $retVal;
1134 }
1135
1136 /**
1137 * @access private
1138 */
1139 function tableNamesWithUseIndex( $tables, $use_index ) {
1140 $ret = array();
1141
1142 foreach ( $tables as $table )
1143 if ( @$use_index[$table] !== null )
1144 $ret[] = $this->tableName( $table ) . ' ' . $this->useIndexClause( implode( ',', (array)$use_index[$table] ) );
1145 else
1146 $ret[] = $this->tableName( $table );
1147
1148 return implode( ',', $ret );
1149 }
1150
1151 /**
1152 * Wrapper for addslashes()
1153 * @param string $s String to be slashed.
1154 * @return string slashed string.
1155 */
1156 function strencode( $s ) {
1157 return addslashes( $s );
1158 }
1159
1160 /**
1161 * If it's a string, adds quotes and backslashes
1162 * Otherwise returns as-is
1163 */
1164 function addQuotes( $s ) {
1165 if ( is_null( $s ) ) {
1166 return 'NULL';
1167 } else {
1168 # This will also quote numeric values. This should be harmless,
1169 # and protects against weird problems that occur when they really
1170 # _are_ strings such as article titles and string->number->string
1171 # conversion is not 1:1.
1172 return "'" . $this->strencode( $s ) . "'";
1173 }
1174 }
1175
1176 /**
1177 * Escape string for safe LIKE usage
1178 */
1179 function escapeLike( $s ) {
1180 $s=$this->strencode( $s );
1181 $s=str_replace(array('%','_'),array('\%','\_'),$s);
1182 return $s;
1183 }
1184
1185 /**
1186 * Returns an appropriately quoted sequence value for inserting a new row.
1187 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
1188 * subclass will return an integer, and save the value for insertId()
1189 */
1190 function nextSequenceValue( $seqName ) {
1191 return NULL;
1192 }
1193
1194 /**
1195 * USE INDEX clause
1196 * PostgreSQL doesn't have them and returns ""
1197 */
1198 function useIndexClause( $index ) {
1199 return "FORCE INDEX ($index)";
1200 }
1201
1202 /**
1203 * REPLACE query wrapper
1204 * PostgreSQL simulates this with a DELETE followed by INSERT
1205 * $row is the row to insert, an associative array
1206 * $uniqueIndexes is an array of indexes. Each element may be either a
1207 * field name or an array of field names
1208 *
1209 * It may be more efficient to leave off unique indexes which are unlikely to collide.
1210 * However if you do this, you run the risk of encountering errors which wouldn't have
1211 * occurred in MySQL
1212 *
1213 * @todo migrate comment to phodocumentor format
1214 */
1215 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
1216 $table = $this->tableName( $table );
1217
1218 # Single row case
1219 if ( !is_array( reset( $rows ) ) ) {
1220 $rows = array( $rows );
1221 }
1222
1223 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) .') VALUES ';
1224 $first = true;
1225 foreach ( $rows as $row ) {
1226 if ( $first ) {
1227 $first = false;
1228 } else {
1229 $sql .= ',';
1230 }
1231 $sql .= '(' . $this->makeList( $row ) . ')';
1232 }
1233 return $this->query( $sql, $fname );
1234 }
1235
1236 /**
1237 * DELETE where the condition is a join
1238 * MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
1239 *
1240 * For safety, an empty $conds will not delete everything. If you want to delete all rows where the
1241 * join condition matches, set $conds='*'
1242 *
1243 * DO NOT put the join condition in $conds
1244 *
1245 * @param string $delTable The table to delete from.
1246 * @param string $joinTable The other table.
1247 * @param string $delVar The variable to join on, in the first table.
1248 * @param string $joinVar The variable to join on, in the second table.
1249 * @param array $conds Condition array of field names mapped to variables, ANDed together in the WHERE clause
1250 */
1251 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'Database::deleteJoin' ) {
1252 if ( !$conds ) {
1253 wfDebugDieBacktrace( 'Database::deleteJoin() called with empty $conds' );
1254 }
1255
1256 $delTable = $this->tableName( $delTable );
1257 $joinTable = $this->tableName( $joinTable );
1258 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1259 if ( $conds != '*' ) {
1260 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND );
1261 }
1262
1263 return $this->query( $sql, $fname );
1264 }
1265
1266 /**
1267 * Returns the size of a text field, or -1 for "unlimited"
1268 */
1269 function textFieldSize( $table, $field ) {
1270 $table = $this->tableName( $table );
1271 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
1272 $res = $this->query( $sql, 'Database::textFieldSize' );
1273 $row = $this->fetchObject( $res );
1274 $this->freeResult( $res );
1275
1276 if ( preg_match( "/\((.*)\)/", $row->Type, $m ) ) {
1277 $size = $m[1];
1278 } else {
1279 $size = -1;
1280 }
1281 return $size;
1282 }
1283
1284 /**
1285 * @return string Returns the text of the low priority option if it is supported, or a blank string otherwise
1286 */
1287 function lowPriorityOption() {
1288 return 'LOW_PRIORITY';
1289 }
1290
1291 /**
1292 * DELETE query wrapper
1293 *
1294 * Use $conds == "*" to delete all rows
1295 */
1296 function delete( $table, $conds, $fname = 'Database::delete' ) {
1297 if ( !$conds ) {
1298 wfDebugDieBacktrace( 'Database::delete() called with no conditions' );
1299 }
1300 $table = $this->tableName( $table );
1301 $sql = "DELETE FROM $table";
1302 if ( $conds != '*' ) {
1303 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
1304 }
1305 return $this->query( $sql, $fname );
1306 }
1307
1308 /**
1309 * INSERT SELECT wrapper
1310 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
1311 * Source items may be literals rather than field names, but strings should be quoted with Database::addQuotes()
1312 * $conds may be "*" to copy the whole table
1313 * srcTable may be an array of tables.
1314 */
1315 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'Database::insertSelect' ) {
1316 $destTable = $this->tableName( $destTable );
1317 if( is_array( $srcTable ) ) {
1318 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
1319 } else {
1320 $srcTable = $this->tableName( $srcTable );
1321 }
1322 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
1323 ' SELECT ' . implode( ',', $varMap ) .
1324 " FROM $srcTable";
1325 if ( $conds != '*' ) {
1326 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
1327 }
1328 return $this->query( $sql, $fname );
1329 }
1330
1331 /**
1332 * Construct a LIMIT query with optional offset
1333 * This is used for query pages
1334 * $sql string SQL query we will append the limit too
1335 * $limit integer the SQL limit
1336 * $offset integer the SQL offset (default false)
1337 */
1338 function limitResult($sql, $limit, $offset=false) {
1339 return " $sql LIMIT ".((is_numeric($offset) && $offset != 0)?"{$offset},":"")."{$limit} ";
1340 }
1341 function limitResultForUpdate($sql, $num) {
1342 return $this->limitResult($sql, $num, 0);
1343 }
1344
1345 /**
1346 * Returns an SQL expression for a simple conditional.
1347 * Uses IF on MySQL.
1348 *
1349 * @param string $cond SQL expression which will result in a boolean value
1350 * @param string $trueVal SQL expression to return if true
1351 * @param string $falseVal SQL expression to return if false
1352 * @return string SQL fragment
1353 */
1354 function conditional( $cond, $trueVal, $falseVal ) {
1355 return " IF($cond, $trueVal, $falseVal) ";
1356 }
1357
1358 /**
1359 * Determines if the last failure was due to a deadlock
1360 */
1361 function wasDeadlock() {
1362 return $this->lastErrno() == 1213;
1363 }
1364
1365 /**
1366 * Perform a deadlock-prone transaction.
1367 *
1368 * This function invokes a callback function to perform a set of write
1369 * queries. If a deadlock occurs during the processing, the transaction
1370 * will be rolled back and the callback function will be called again.
1371 *
1372 * Usage:
1373 * $dbw->deadlockLoop( callback, ... );
1374 *
1375 * Extra arguments are passed through to the specified callback function.
1376 *
1377 * Returns whatever the callback function returned on its successful,
1378 * iteration, or false on error, for example if the retry limit was
1379 * reached.
1380 */
1381 function deadlockLoop() {
1382 $myFname = 'Database::deadlockLoop';
1383
1384 $this->begin();
1385 $args = func_get_args();
1386 $function = array_shift( $args );
1387 $oldIgnore = $this->ignoreErrors( true );
1388 $tries = DEADLOCK_TRIES;
1389 if ( is_array( $function ) ) {
1390 $fname = $function[0];
1391 } else {
1392 $fname = $function;
1393 }
1394 do {
1395 $retVal = call_user_func_array( $function, $args );
1396 $error = $this->lastError();
1397 $errno = $this->lastErrno();
1398 $sql = $this->lastQuery();
1399
1400 if ( $errno ) {
1401 if ( $this->wasDeadlock() ) {
1402 # Retry
1403 usleep( mt_rand( DEADLOCK_DELAY_MIN, DEADLOCK_DELAY_MAX ) );
1404 } else {
1405 $this->reportQueryError( $error, $errno, $sql, $fname );
1406 }
1407 }
1408 } while( $this->wasDeadlock() && --$tries > 0 );
1409 $this->ignoreErrors( $oldIgnore );
1410 if ( $tries <= 0 ) {
1411 $this->query( 'ROLLBACK', $myFname );
1412 $this->reportQueryError( $error, $errno, $sql, $fname );
1413 return false;
1414 } else {
1415 $this->query( 'COMMIT', $myFname );
1416 return $retVal;
1417 }
1418 }
1419
1420 /**
1421 * Do a SELECT MASTER_POS_WAIT()
1422 *
1423 * @param string $file the binlog file
1424 * @param string $pos the binlog position
1425 * @param integer $timeout the maximum number of seconds to wait for synchronisation
1426 */
1427 function masterPosWait( $file, $pos, $timeout ) {
1428 $fname = 'Database::masterPosWait';
1429 wfProfileIn( $fname );
1430
1431
1432 # Commit any open transactions
1433 $this->immediateCommit();
1434
1435 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
1436 $encFile = $this->strencode( $file );
1437 $sql = "SELECT MASTER_POS_WAIT('$encFile', $pos, $timeout)";
1438 $res = $this->doQuery( $sql );
1439 if ( $res && $row = $this->fetchRow( $res ) ) {
1440 $this->freeResult( $res );
1441 wfProfileOut( $fname );
1442 return $row[0];
1443 } else {
1444 wfProfileOut( $fname );
1445 return false;
1446 }
1447 }
1448
1449 /**
1450 * Get the position of the master from SHOW SLAVE STATUS
1451 */
1452 function getSlavePos() {
1453 $res = $this->query( 'SHOW SLAVE STATUS', 'Database::getSlavePos' );
1454 $row = $this->fetchObject( $res );
1455 if ( $row ) {
1456 return array( $row->Master_Log_File, $row->Read_Master_Log_Pos );
1457 } else {
1458 return array( false, false );
1459 }
1460 }
1461
1462 /**
1463 * Get the position of the master from SHOW MASTER STATUS
1464 */
1465 function getMasterPos() {
1466 $res = $this->query( 'SHOW MASTER STATUS', 'Database::getMasterPos' );
1467 $row = $this->fetchObject( $res );
1468 if ( $row ) {
1469 return array( $row->File, $row->Position );
1470 } else {
1471 return array( false, false );
1472 }
1473 }
1474
1475 /**
1476 * Begin a transaction, or if a transaction has already started, continue it
1477 */
1478 function begin( $fname = 'Database::begin' ) {
1479 if ( !$this->mTrxLevel ) {
1480 $this->immediateBegin( $fname );
1481 } else {
1482 $this->mTrxLevel++;
1483 }
1484 }
1485
1486 /**
1487 * End a transaction, or decrement the nest level if transactions are nested
1488 */
1489 function commit( $fname = 'Database::commit' ) {
1490 if ( $this->mTrxLevel ) {
1491 $this->mTrxLevel--;
1492 }
1493 if ( !$this->mTrxLevel ) {
1494 $this->immediateCommit( $fname );
1495 }
1496 }
1497
1498 /**
1499 * Rollback a transaction
1500 */
1501 function rollback( $fname = 'Database::rollback' ) {
1502 $this->query( 'ROLLBACK', $fname );
1503 $this->mTrxLevel = 0;
1504 }
1505
1506 /**
1507 * Begin a transaction, committing any previously open transaction
1508 */
1509 function immediateBegin( $fname = 'Database::immediateBegin' ) {
1510 $this->query( 'BEGIN', $fname );
1511 $this->mTrxLevel = 1;
1512 }
1513
1514 /**
1515 * Commit transaction, if one is open
1516 */
1517 function immediateCommit( $fname = 'Database::immediateCommit' ) {
1518 $this->query( 'COMMIT', $fname );
1519 $this->mTrxLevel = 0;
1520 }
1521
1522 /**
1523 * Return MW-style timestamp used for MySQL schema
1524 */
1525 function timestamp( $ts=0 ) {
1526 return wfTimestamp(TS_MW,$ts);
1527 }
1528
1529 /**
1530 * Local database timestamp format or null
1531 */
1532 function timestampOrNull( $ts = null ) {
1533 if( is_null( $ts ) ) {
1534 return null;
1535 } else {
1536 return $this->timestamp( $ts );
1537 }
1538 }
1539
1540 /**
1541 * @todo document
1542 */
1543 function resultObject( $result ) {
1544 if( empty( $result ) ) {
1545 return NULL;
1546 } else {
1547 return new ResultWrapper( $this, $result );
1548 }
1549 }
1550
1551 /**
1552 * Return aggregated value alias
1553 */
1554 function aggregateValue ($valuedata,$valuename='value') {
1555 return $valuename;
1556 }
1557
1558 /**
1559 * @return string wikitext of a link to the server software's web site
1560 */
1561 function getSoftwareLink() {
1562 return "[http://www.mysql.com/ MySQL]";
1563 }
1564
1565 /**
1566 * @return string Version information from the database
1567 */
1568 function getServerVersion() {
1569 return mysql_get_server_info();
1570 }
1571
1572 /**
1573 * Ping the server and try to reconnect if it there is no connection
1574 */
1575 function ping() {
1576 if( function_exists( 'mysql_ping' ) ) {
1577 return mysql_ping( $this->mConn );
1578 } else {
1579 wfDebug( "Tried to call mysql_ping but this is ancient PHP version. Faking it!\n" );
1580 return true;
1581 }
1582 }
1583
1584 /**
1585 * Get slave lag.
1586 * At the moment, this will only work if the DB user has the PROCESS privilege
1587 */
1588 function getLag() {
1589 $res = $this->query( 'SHOW PROCESSLIST' );
1590 # Find slave SQL thread. Assumed to be the second one running, which is a bit
1591 # dubious, but unfortunately there's no easy rigorous way
1592 $slaveThreads = 0;
1593 while ( $row = $this->fetchObject( $res ) ) {
1594 if ( $row->User == 'system user' ) {
1595 if ( ++$slaveThreads == 2 ) {
1596 # This is it, return the time
1597 return $row->Time;
1598 }
1599 }
1600 }
1601 return false;
1602 }
1603
1604 /**
1605 * Get status information from SHOW STATUS in an associative array
1606 */
1607 function getStatus() {
1608 $res = $this->query( 'SHOW STATUS' );
1609 $status = array();
1610 while ( $row = $this->fetchObject( $res ) ) {
1611 $status[$row->Variable_name] = $row->Value;
1612 }
1613 return $status;
1614 }
1615
1616 /**
1617 * Return the maximum number of items allowed in a list, or 0 for unlimited.
1618 */
1619 function maxListLen() {
1620 return 0;
1621 }
1622
1623 function encodeBlob($b) {
1624 return $b;
1625 }
1626
1627 function notNullTimestamp() {
1628 return "!= 0";
1629 }
1630 function isNullTimestamp() {
1631 return "= '0'";
1632 }
1633 }
1634
1635 /**
1636 * Database abstraction object for mySQL
1637 * Inherit all methods and properties of Database::Database()
1638 *
1639 * @package MediaWiki
1640 * @see Database
1641 */
1642 class DatabaseMysql extends Database {
1643 # Inherit all
1644 }
1645
1646
1647 /**
1648 * Result wrapper for grabbing data queried by someone else
1649 *
1650 * @package MediaWiki
1651 */
1652 class ResultWrapper {
1653 var $db, $result;
1654
1655 /**
1656 * @todo document
1657 */
1658 function ResultWrapper( $database, $result ) {
1659 $this->db =& $database;
1660 $this->result =& $result;
1661 }
1662
1663 /**
1664 * @todo document
1665 */
1666 function numRows() {
1667 return $this->db->numRows( $this->result );
1668 }
1669
1670 /**
1671 * @todo document
1672 */
1673 function fetchObject() {
1674 return $this->db->fetchObject( $this->result );
1675 }
1676
1677 /**
1678 * @todo document
1679 */
1680 function &fetchRow() {
1681 return $this->db->fetchRow( $this->result );
1682 }
1683
1684 /**
1685 * @todo document
1686 */
1687 function free() {
1688 $this->db->freeResult( $this->result );
1689 unset( $this->result );
1690 unset( $this->db );
1691 }
1692
1693 function seek( $row ) {
1694 $this->db->dataSeek( $this->result, $row );
1695 }
1696 }
1697
1698 #------------------------------------------------------------------------------
1699 # Global functions
1700 #------------------------------------------------------------------------------
1701
1702 /**
1703 * Standard fail function, called by default when a connection cannot be
1704 * established.
1705 * Displays the file cache if possible
1706 */
1707 function wfEmergencyAbort( &$conn, $error ) {
1708 global $wgTitle, $wgUseFileCache, $title, $wgInputEncoding, $wgOutputEncoding;
1709 global $wgSitename, $wgServer, $wgMessageCache, $wgLogo;
1710
1711 # I give up, Brion is right. Getting the message cache to work when there is no DB is tricky.
1712 # Hard coding strings instead.
1713
1714 $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>";
1715 $mainpage = 'Main Page';
1716 $searchdisabled = <<<EOT
1717 <p style="margin: 1.5em 2em 1em">$wgSitename search is disabled for performance reasons. You can search via Google in the meantime.
1718 <span style="font-size: 89%; display: block; margin-left: .2em">Note that their indexes of $wgSitename content may be out of date.</span></p>',
1719 EOT;
1720
1721 $googlesearch = "
1722 <!-- SiteSearch Google -->
1723 <FORM method=GET action=\"http://www.google.com/search\">
1724 <TABLE bgcolor=\"#FFFFFF\"><tr><td>
1725 <A HREF=\"http://www.google.com/\">
1726 <IMG SRC=\"http://www.google.com/logos/Logo_40wht.gif\"
1727 border=\"0\" ALT=\"Google\"></A>
1728 </td>
1729 <td>
1730 <INPUT TYPE=text name=q size=31 maxlength=255 value=\"$1\">
1731 <INPUT type=submit name=btnG VALUE=\"Google Search\">
1732 <font size=-1>
1733 <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 />
1734 <input type='hidden' name='ie' value='$2'>
1735 <input type='hidden' name='oe' value='$2'>
1736 </font>
1737 </td></tr></TABLE>
1738 </FORM>
1739 <!-- SiteSearch Google -->";
1740 $cachederror = "The following is a cached copy of the requested page, and may not be up to date. ";
1741
1742
1743 if( !headers_sent() ) {
1744 header( 'HTTP/1.0 500 Internal Server Error' );
1745 header( 'Content-type: text/html; charset='.$wgOutputEncoding );
1746 /* Don't cache error pages! They cause no end of trouble... */
1747 header( 'Cache-control: none' );
1748 header( 'Pragma: nocache' );
1749 }
1750
1751 # No database access
1752 if ( is_object( $wgMessageCache ) ) {
1753 $wgMessageCache->disable();
1754 }
1755
1756 $msg = wfGetSiteNotice();
1757 if($msg == '') {
1758 $msg = str_replace( '$1', $error, $noconnect );
1759 }
1760 $text = $msg;
1761
1762 if($wgUseFileCache) {
1763 if($wgTitle) {
1764 $t =& $wgTitle;
1765 } else {
1766 if($title) {
1767 $t = Title::newFromURL( $title );
1768 } elseif (@/**/$_REQUEST['search']) {
1769 $search = $_REQUEST['search'];
1770 echo $searchdisabled;
1771 echo str_replace( array( '$1', '$2' ), array( htmlspecialchars( $search ),
1772 $wgInputEncoding ), $googlesearch );
1773 wfErrorExit();
1774 } else {
1775 $t = Title::newFromText( $mainpage );
1776 }
1777 }
1778
1779 $cache = new CacheManager( $t );
1780 if( $cache->isFileCached() ) {
1781 $msg = '<p style="color: red"><b>'.$msg."<br />\n" .
1782 $cachederror . "</b></p>\n";
1783
1784 $tag = '<div id="article">';
1785 $text = str_replace(
1786 $tag,
1787 $tag . $msg,
1788 $cache->fetchPageText() );
1789 }
1790 }
1791
1792 echo $text;
1793 wfErrorExit();
1794 }
1795
1796 ?>