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