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