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