Fixed incorrect query() parameters, left over from the brief period of time when...
[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, $wgCommandLineMode;
363
364 if ( wfReadOnly() ) {
365 # This is a quick check for the most common kinds of write query used
366 # in MediaWiki, to provide extra safety in addition to UI-level checks.
367 # It is not intended to prevent every conceivable write query, or even
368 # to handle such queries gracefully.
369 if ( preg_match( '/^(?:update|insert|replace|delete)/i', $sql ) ) {
370 wfDebug( "Write query from $fname blocked\n" );
371 return false;
372 }
373 }
374
375 if ( $wgProfiling ) {
376 # generalizeSQL will probably cut down the query to reasonable
377 # logging size most of the time. The substr is really just a sanity check.
378
379 # Who's been wasting my precious column space? -- TS
380 #$profName = 'query: ' . $fname . ' ' . substr( Database::generalizeSQL( $sql ), 0, 255 );
381 $profName = 'query: ' . substr( Database::generalizeSQL( $sql ), 0, 255 );
382
383 wfProfileIn( 'Database::query' );
384 wfProfileIn( $profName );
385 }
386
387 $this->mLastQuery = $sql;
388
389 # Add a comment for easy SHOW PROCESSLIST interpretation
390 if ( $fname ) {
391 $commentedSql = preg_replace("/\s/", " /* $fname */ ", $sql, 1);
392 } else {
393 $commentedSql = $sql;
394 }
395
396 # If DBO_TRX is set, start a transaction
397 if ( ( $this->mFlags & DBO_TRX ) && !$this->trxLevel() && $sql != 'BEGIN' ) {
398 $this->begin();
399 }
400
401 if ( $this->debug() ) {
402 $sqlx = substr( $commentedSql, 0, 500 );
403 $sqlx = strtr( $sqlx, "\t\n", ' ' );
404 wfDebug( "SQL: $sqlx\n" );
405 }
406
407 # Do the query and handle errors
408 $ret = $this->doQuery( $commentedSql );
409
410 # Try reconnecting if the connection was lost
411 if ( false === $ret && ( $this->lastErrno() == 2013 || $this->lastErrno() == 2006 ) ) {
412 # Transaction is gone, like it or not
413 $this->mTrxLevel = 0;
414 wfDebug( "Connection lost, reconnecting...\n" );
415 if ( $this->ping() ) {
416 wfDebug( "Reconnected\n" );
417 $ret = $this->doQuery( $commentedSql );
418 } else {
419 wfDebug( "Failed\n" );
420 }
421 }
422
423 if ( false === $ret ) {
424 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
425 }
426
427 if ( $wgProfiling ) {
428 wfProfileOut( $profName );
429 wfProfileOut( 'Database::query' );
430 }
431 return $ret;
432 }
433
434 /**
435 * The DBMS-dependent part of query()
436 * @param string $sql SQL query.
437 */
438 function doQuery( $sql ) {
439 if( $this->bufferResults() ) {
440 $ret = mysql_query( $sql, $this->mConn );
441 } else {
442 $ret = mysql_unbuffered_query( $sql, $this->mConn );
443 }
444 return $ret;
445 }
446
447 /**
448 * @param $error
449 * @param $errno
450 * @param $sql
451 * @param string $fname
452 * @param bool $tempIgnore
453 */
454 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
455 global $wgCommandLineMode, $wgFullyInitialised;
456 # Ignore errors during error handling to avoid infinite recursion
457 $ignore = $this->ignoreErrors( true );
458 ++$this->mErrorCount;
459
460 if( $ignore || $tempIgnore ) {
461 wfDebug("SQL ERROR (ignored): $error\n");
462 } else {
463 $sql1line = str_replace( "\n", "\\n", $sql );
464 wfLogDBError("$fname\t{$this->mServer}\t$errno\t$error\t$sql1line\n");
465 wfDebug("SQL ERROR: " . $error . "\n");
466 if ( $wgCommandLineMode || !$this->mOut || empty( $wgFullyInitialised ) ) {
467 $message = "A database error has occurred\n" .
468 "Query: $sql\n" .
469 "Function: $fname\n" .
470 "Error: $errno $error\n";
471 if ( !$wgCommandLineMode ) {
472 $message = nl2br( $message );
473 }
474 wfDebugDieBacktrace( $message );
475 } else {
476 // this calls wfAbruptExit()
477 $this->mOut->databaseError( $fname, $sql, $error, $errno );
478 }
479 }
480 $this->ignoreErrors( $ignore );
481 }
482
483
484 /**
485 * Intended to be compatible with the PEAR::DB wrapper functions.
486 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
487 *
488 * ? = scalar value, quoted as necessary
489 * ! = raw SQL bit (a function for instance)
490 * & = filename; reads the file and inserts as a blob
491 * (we don't use this though...)
492 */
493 function prepare( $sql, $func = 'Database::prepare' ) {
494 /* MySQL doesn't support prepared statements (yet), so just
495 pack up the query for reference. We'll manually replace
496 the bits later. */
497 return array( 'query' => $sql, 'func' => $func );
498 }
499
500 function freePrepared( $prepared ) {
501 /* No-op for MySQL */
502 }
503
504 /**
505 * Execute a prepared query with the various arguments
506 * @param string $prepared the prepared sql
507 * @param mixed $args Either an array here, or put scalars as varargs
508 */
509 function execute( $prepared, $args = null ) {
510 if( !is_array( $args ) ) {
511 # Pull the var args
512 $args = func_get_args();
513 array_shift( $args );
514 }
515 $sql = $this->fillPrepared( $prepared['query'], $args );
516 return $this->query( $sql, $prepared['func'] );
517 }
518
519 /**
520 * Prepare & execute an SQL statement, quoting and inserting arguments
521 * in the appropriate places.
522 * @param string $query
523 * @param string $args ...
524 */
525 function safeQuery( $query, $args = null ) {
526 $prepared = $this->prepare( $query, 'Database::safeQuery' );
527 if( !is_array( $args ) ) {
528 # Pull the var args
529 $args = func_get_args();
530 array_shift( $args );
531 }
532 $retval = $this->execute( $prepared, $args );
533 $this->freePrepared( $prepared );
534 return $retval;
535 }
536
537 /**
538 * For faking prepared SQL statements on DBs that don't support
539 * it directly.
540 * @param string $preparedSql - a 'preparable' SQL statement
541 * @param array $args - array of arguments to fill it with
542 * @return string executable SQL
543 */
544 function fillPrepared( $preparedQuery, $args ) {
545 $n = 0;
546 reset( $args );
547 $this->preparedArgs =& $args;
548 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
549 array( &$this, 'fillPreparedArg' ), $preparedQuery );
550 }
551
552 /**
553 * preg_callback func for fillPrepared()
554 * The arguments should be in $this->preparedArgs and must not be touched
555 * while we're doing this.
556 *
557 * @param array $matches
558 * @return string
559 * @access private
560 */
561 function fillPreparedArg( $matches ) {
562 switch( $matches[1] ) {
563 case '\\?': return '?';
564 case '\\!': return '!';
565 case '\\&': return '&';
566 }
567 list( $n, $arg ) = each( $this->preparedArgs );
568 switch( $matches[1] ) {
569 case '?': return $this->addQuotes( $arg );
570 case '!': return $arg;
571 case '&':
572 # return $this->addQuotes( file_get_contents( $arg ) );
573 wfDebugDieBacktrace( '& mode is not implemented. If it\'s really needed, uncomment the line above.' );
574 default:
575 wfDebugDieBacktrace( 'Received invalid match. This should never happen!' );
576 }
577 }
578
579 /**#@+
580 * @param mixed $res A SQL result
581 */
582 /**
583 * Free a result object
584 */
585 function freeResult( $res ) {
586 if ( !@/**/mysql_free_result( $res ) ) {
587 wfDebugDieBacktrace( "Unable to free MySQL result\n" );
588 }
589 }
590
591 /**
592 * Fetch the next row from the given result object, in object form
593 */
594 function fetchObject( $res ) {
595 @/**/$row = mysql_fetch_object( $res );
596 if( mysql_errno() ) {
597 wfDebugDieBacktrace( 'Error in fetchObject(): ' . htmlspecialchars( mysql_error() ) );
598 }
599 return $row;
600 }
601
602 /**
603 * Fetch the next row from the given result object
604 * Returns an array
605 */
606 function fetchRow( $res ) {
607 @/**/$row = mysql_fetch_array( $res );
608 if (mysql_errno() ) {
609 wfDebugDieBacktrace( 'Error in fetchRow(): ' . htmlspecialchars( mysql_error() ) );
610 }
611 return $row;
612 }
613
614 /**
615 * Get the number of rows in a result object
616 */
617 function numRows( $res ) {
618 @/**/$n = mysql_num_rows( $res );
619 if( mysql_errno() ) {
620 wfDebugDieBacktrace( 'Error in numRows(): ' . htmlspecialchars( mysql_error() ) );
621 }
622 return $n;
623 }
624
625 /**
626 * Get the number of fields in a result object
627 * See documentation for mysql_num_fields()
628 */
629 function numFields( $res ) { return mysql_num_fields( $res ); }
630
631 /**
632 * Get a field name in a result object
633 * See documentation for mysql_field_name()
634 */
635 function fieldName( $res, $n ) { return mysql_field_name( $res, $n ); }
636
637 /**
638 * Get the inserted value of an auto-increment row
639 *
640 * The value inserted should be fetched from nextSequenceValue()
641 *
642 * Example:
643 * $id = $dbw->nextSequenceValue('page_page_id_seq');
644 * $dbw->insert('page',array('page_id' => $id));
645 * $id = $dbw->insertId();
646 */
647 function insertId() { return mysql_insert_id( $this->mConn ); }
648
649 /**
650 * Change the position of the cursor in a result object
651 * See mysql_data_seek()
652 */
653 function dataSeek( $res, $row ) { return mysql_data_seek( $res, $row ); }
654
655 /**
656 * Get the last error number
657 * See mysql_errno()
658 */
659 function lastErrno() {
660 if ( $this->mConn ) {
661 return mysql_errno( $this->mConn );
662 } else {
663 return mysql_errno();
664 }
665 }
666
667 /**
668 * Get a description of the last error
669 * See mysql_error() for more details
670 */
671 function lastError() {
672 if ( $this->mConn ) {
673 # Even if it's non-zero, it can still be invalid
674 wfSuppressWarnings();
675 $error = mysql_error( $this->mConn );
676 if ( !$error ) {
677 $error = mysql_error();
678 }
679 wfRestoreWarnings();
680 } else {
681 $error = mysql_error();
682 }
683 if( $error ) {
684 $error .= ' (' . $this->mServer . ')';
685 }
686 return $error;
687 }
688 /**
689 * Get the number of rows affected by the last write query
690 * See mysql_affected_rows() for more details
691 */
692 function affectedRows() { return mysql_affected_rows( $this->mConn ); }
693 /**#@-*/ // end of template : @param $result
694
695 /**
696 * Simple UPDATE wrapper
697 * Usually aborts on failure
698 * If errors are explicitly ignored, returns success
699 *
700 * This function exists for historical reasons, Database::update() has a more standard
701 * calling convention and feature set
702 */
703 function set( $table, $var, $value, $cond, $fname = 'Database::set' )
704 {
705 $table = $this->tableName( $table );
706 $sql = "UPDATE $table SET $var = '" .
707 $this->strencode( $value ) . "' WHERE ($cond)";
708 return (bool)$this->query( $sql, $fname );
709 }
710
711 /**
712 * Simple SELECT wrapper, returns a single field, input must be encoded
713 * Usually aborts on failure
714 * If errors are explicitly ignored, returns FALSE on failure
715 */
716 function selectField( $table, $var, $cond='', $fname = 'Database::selectField', $options = array() ) {
717 if ( !is_array( $options ) ) {
718 $options = array( $options );
719 }
720 $options['LIMIT'] = 1;
721
722 $res = $this->select( $table, $var, $cond, $fname, $options );
723 if ( $res === false || !$this->numRows( $res ) ) {
724 return false;
725 }
726 $row = $this->fetchRow( $res );
727 if ( $row !== false ) {
728 $this->freeResult( $res );
729 return $row[0];
730 } else {
731 return false;
732 }
733 }
734
735 /**
736 * Returns an optional USE INDEX clause to go after the table, and a
737 * string to go at the end of the query
738 *
739 * @access private
740 *
741 * @param array $options an associative array of options to be turned into
742 * an SQL query, valid keys are listed in the function.
743 * @return array
744 */
745 function makeSelectOptions( $options ) {
746 $tailOpts = '';
747
748 if ( isset( $options['GROUP BY'] ) ) {
749 $tailOpts .= " GROUP BY {$options['GROUP BY']}";
750 }
751 if ( isset( $options['ORDER BY'] ) ) {
752 $tailOpts .= " ORDER BY {$options['ORDER BY']}";
753 }
754 if (isset($options['LIMIT'])) {
755 $tailOpts .= $this->limitResult('', $options['LIMIT'],
756 isset($options['OFFSET']) ? $options['OFFSET'] : false);
757 }
758 if ( is_numeric( array_search( 'FOR UPDATE', $options ) ) ) {
759 $tailOpts .= ' FOR UPDATE';
760 }
761
762 if ( is_numeric( array_search( 'LOCK IN SHARE MODE', $options ) ) ) {
763 $tailOpts .= ' LOCK IN SHARE MODE';
764 }
765
766 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
767 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
768 } else {
769 $useIndex = '';
770 }
771 return array( $useIndex, $tailOpts );
772 }
773
774 /**
775 * SELECT wrapper
776 */
777 function select( $table, $vars, $conds='', $fname = 'Database::select', $options = array() )
778 {
779 if( is_array( $vars ) ) {
780 $vars = implode( ',', $vars );
781 }
782 if( !is_array( $options ) ) {
783 $options = array( $options );
784 }
785 if( is_array( $table ) ) {
786 if ( @is_array( $options['USE INDEX'] ) )
787 $from = ' FROM ' . $this->tableNamesWithUseIndex( $table, $options['USE INDEX'] );
788 else
789 $from = ' FROM ' . implode( ',', array_map( array( &$this, 'tableName' ), $table ) );
790 } elseif ($table!='') {
791 $from = ' FROM ' . $this->tableName( $table );
792 } else {
793 $from = '';
794 }
795
796 list( $useIndex, $tailOpts ) = $this->makeSelectOptions( $options );
797
798 if( !empty( $conds ) ) {
799 if ( is_array( $conds ) ) {
800 $conds = $this->makeList( $conds, LIST_AND );
801 }
802 $sql = "SELECT $vars $from $useIndex WHERE $conds $tailOpts";
803 } else {
804 $sql = "SELECT $vars $from $useIndex $tailOpts";
805 }
806
807 return $this->query( $sql, $fname );
808 }
809
810 /**
811 * Single row SELECT wrapper
812 * Aborts or returns FALSE on error
813 *
814 * $vars: the selected variables
815 * $conds: a condition map, terms are ANDed together.
816 * Items with numeric keys are taken to be literal conditions
817 * Takes an array of selected variables, and a condition map, which is ANDed
818 * e.g: selectRow( "page", array( "page_id" ), array( "page_namespace" =>
819 * NS_MAIN, "page_title" => "Astronomy" ) ) would return an object where
820 * $obj- >page_id is the ID of the Astronomy article
821 *
822 * @todo migrate documentation to phpdocumentor format
823 */
824 function selectRow( $table, $vars, $conds, $fname = 'Database::selectRow', $options = array() ) {
825 $options['LIMIT'] = 1;
826 $res = $this->select( $table, $vars, $conds, $fname, $options );
827 if ( $res === false )
828 return false;
829 if ( !$this->numRows($res) ) {
830 $this->freeResult($res);
831 return false;
832 }
833 $obj = $this->fetchObject( $res );
834 $this->freeResult( $res );
835 return $obj;
836
837 }
838
839 /**
840 * Removes most variables from an SQL query and replaces them with X or N for numbers.
841 * It's only slightly flawed. Don't use for anything important.
842 *
843 * @param string $sql A SQL Query
844 * @static
845 */
846 function generalizeSQL( $sql ) {
847 # This does the same as the regexp below would do, but in such a way
848 # as to avoid crashing php on some large strings.
849 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
850
851 $sql = str_replace ( "\\\\", '', $sql);
852 $sql = str_replace ( "\\'", '', $sql);
853 $sql = str_replace ( "\\\"", '', $sql);
854 $sql = preg_replace ("/'.*'/s", "'X'", $sql);
855 $sql = preg_replace ('/".*"/s', "'X'", $sql);
856
857 # All newlines, tabs, etc replaced by single space
858 $sql = preg_replace ( "/\s+/", ' ', $sql);
859
860 # All numbers => N
861 $sql = preg_replace ('/-?[0-9]+/s', 'N', $sql);
862
863 return $sql;
864 }
865
866 /**
867 * Determines whether a field exists in a table
868 * Usually aborts on failure
869 * If errors are explicitly ignored, returns NULL on failure
870 */
871 function fieldExists( $table, $field, $fname = 'Database::fieldExists' ) {
872 $table = $this->tableName( $table );
873 $res = $this->query( 'DESCRIBE '.$table, $fname );
874 if ( !$res ) {
875 return NULL;
876 }
877
878 $found = false;
879
880 while ( $row = $this->fetchObject( $res ) ) {
881 if ( $row->Field == $field ) {
882 $found = true;
883 break;
884 }
885 }
886 return $found;
887 }
888
889 /**
890 * Determines whether an index exists
891 * Usually aborts on failure
892 * If errors are explicitly ignored, returns NULL on failure
893 */
894 function indexExists( $table, $index, $fname = 'Database::indexExists' ) {
895 $info = $this->indexInfo( $table, $index, $fname );
896 if ( is_null( $info ) ) {
897 return NULL;
898 } else {
899 return $info !== false;
900 }
901 }
902
903
904 /**
905 * Get information about an index into an object
906 * Returns false if the index does not exist
907 */
908 function indexInfo( $table, $index, $fname = 'Database::indexInfo' ) {
909 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
910 # SHOW INDEX should work for 3.x and up:
911 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
912 $table = $this->tableName( $table );
913 $sql = 'SHOW INDEX FROM '.$table;
914 $res = $this->query( $sql, $fname );
915 if ( !$res ) {
916 return NULL;
917 }
918
919 while ( $row = $this->fetchObject( $res ) ) {
920 if ( $row->Key_name == $index ) {
921 return $row;
922 }
923 }
924 return false;
925 }
926
927 /**
928 * Query whether a given table exists
929 */
930 function tableExists( $table ) {
931 $table = $this->tableName( $table );
932 $old = $this->ignoreErrors( true );
933 $res = $this->query( "SELECT 1 FROM $table LIMIT 1" );
934 $this->ignoreErrors( $old );
935 if( $res ) {
936 $this->freeResult( $res );
937 return true;
938 } else {
939 return false;
940 }
941 }
942
943 /**
944 * mysql_fetch_field() wrapper
945 * Returns false if the field doesn't exist
946 *
947 * @param $table
948 * @param $field
949 */
950 function fieldInfo( $table, $field ) {
951 $table = $this->tableName( $table );
952 $res = $this->query( "SELECT * FROM $table LIMIT 1" );
953 $n = mysql_num_fields( $res );
954 for( $i = 0; $i < $n; $i++ ) {
955 $meta = mysql_fetch_field( $res, $i );
956 if( $field == $meta->name ) {
957 return $meta;
958 }
959 }
960 return false;
961 }
962
963 /**
964 * mysql_field_type() wrapper
965 */
966 function fieldType( $res, $index ) {
967 return mysql_field_type( $res, $index );
968 }
969
970 /**
971 * Determines if a given index is unique
972 */
973 function indexUnique( $table, $index ) {
974 $indexInfo = $this->indexInfo( $table, $index );
975 if ( !$indexInfo ) {
976 return NULL;
977 }
978 return !$indexInfo->Non_unique;
979 }
980
981 /**
982 * INSERT wrapper, inserts an array into a table
983 *
984 * $a may be a single associative array, or an array of these with numeric keys, for
985 * multi-row insert.
986 *
987 * Usually aborts on failure
988 * If errors are explicitly ignored, returns success
989 */
990 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
991 # No rows to insert, easy just return now
992 if ( !count( $a ) ) {
993 return true;
994 }
995
996 $table = $this->tableName( $table );
997 if ( !is_array( $options ) ) {
998 $options = array( $options );
999 }
1000 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1001 $multi = true;
1002 $keys = array_keys( $a[0] );
1003 } else {
1004 $multi = false;
1005 $keys = array_keys( $a );
1006 }
1007
1008 $sql = 'INSERT ' . implode( ' ', $options ) .
1009 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1010
1011 if ( $multi ) {
1012 $first = true;
1013 foreach ( $a as $row ) {
1014 if ( $first ) {
1015 $first = false;
1016 } else {
1017 $sql .= ',';
1018 }
1019 $sql .= '(' . $this->makeList( $row ) . ')';
1020 }
1021 } else {
1022 $sql .= '(' . $this->makeList( $a ) . ')';
1023 }
1024 return (bool)$this->query( $sql, $fname );
1025 }
1026
1027 /**
1028 * Make UPDATE options for the Database::update function
1029 *
1030 * @access private
1031 * @param array $options The options passed to Database::update
1032 * @return string
1033 */
1034 function makeUpdateOptions( $options ) {
1035 if( !is_array( $options ) ) {
1036 $options = array( $options );
1037 }
1038 $opts = array();
1039 if ( in_array( 'LOW_PRIORITY', $options ) )
1040 $opts[] = $this->lowPriorityOption();
1041 if ( in_array( 'IGNORE', $options ) )
1042 $opts[] = 'IGNORE';
1043 return implode(' ', $opts);
1044 }
1045
1046 /**
1047 * UPDATE wrapper, takes a condition array and a SET array
1048 *
1049 * @param string $table The table to UPDATE
1050 * @param array $values An array of values to SET
1051 * @param array $conds An array of conditions (WHERE)
1052 * @param string $fname The Class::Function calling this function
1053 * (for the log)
1054 * @param array $options An array of UPDATE options, can be one or
1055 * more of IGNORE, LOW_PRIORITY
1056 */
1057 function update( $table, $values, $conds, $fname = 'Database::update', $options = array() ) {
1058 $table = $this->tableName( $table );
1059 $opts = $this->makeUpdateOptions( $options );
1060 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET );
1061 if ( $conds != '*' ) {
1062 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND );
1063 }
1064 $this->query( $sql, $fname );
1065 }
1066
1067 /**
1068 * Makes a wfStrencoded list from an array
1069 * $mode: LIST_COMMA - comma separated, no field names
1070 * LIST_AND - ANDed WHERE clause (without the WHERE)
1071 * LIST_SET - comma separated with field names, like a SET clause
1072 * LIST_NAMES - comma separated field names
1073 */
1074 function makeList( $a, $mode = LIST_COMMA ) {
1075 if ( !is_array( $a ) ) {
1076 wfDebugDieBacktrace( 'Database::makeList called with incorrect parameters' );
1077 }
1078
1079 $first = true;
1080 $list = '';
1081 foreach ( $a as $field => $value ) {
1082 if ( !$first ) {
1083 if ( $mode == LIST_AND ) {
1084 $list .= ' AND ';
1085 } elseif($mode == LIST_OR) {
1086 $list .= ' OR ';
1087 } else {
1088 $list .= ',';
1089 }
1090 } else {
1091 $first = false;
1092 }
1093 if ( ($mode == LIST_AND || $mode == LIST_OR) && is_numeric( $field ) ) {
1094 $list .= "($value)";
1095 } elseif ( $mode == LIST_AND && is_array ($value) ) {
1096 $list .= $field." IN (".$this->makeList($value).") ";
1097 } else {
1098 if ( $mode == LIST_AND || $mode == LIST_OR || $mode == LIST_SET ) {
1099 $list .= "$field = ";
1100 }
1101 $list .= $mode == LIST_NAMES ? $value : $this->addQuotes( $value );
1102 }
1103 }
1104 return $list;
1105 }
1106
1107 /**
1108 * Change the current database
1109 */
1110 function selectDB( $db ) {
1111 $this->mDBname = $db;
1112 return mysql_select_db( $db, $this->mConn );
1113 }
1114
1115 /**
1116 * Format a table name ready for use in constructing an SQL query
1117 *
1118 * This does two important things: it quotes table names which as necessary,
1119 * and it adds a table prefix if there is one.
1120 *
1121 * All functions of this object which require a table name call this function
1122 * themselves. Pass the canonical name to such functions. This is only needed
1123 * when calling query() directly.
1124 *
1125 * @param string $name database table name
1126 */
1127 function tableName( $name ) {
1128 global $wgSharedDB;
1129 # Skip quoted literals
1130 if ( $name{0} != '`' ) {
1131 if ( $this->mTablePrefix !== '' && strpos( '.', $name ) === false ) {
1132 $name = "{$this->mTablePrefix}$name";
1133 }
1134 if ( isset( $wgSharedDB ) && "{$this->mTablePrefix}user" == $name ) {
1135 $name = "`$wgSharedDB`.`$name`";
1136 } else {
1137 # Standard quoting
1138 $name = "`$name`";
1139 }
1140 }
1141 return $name;
1142 }
1143
1144 /**
1145 * Fetch a number of table names into an array
1146 * This is handy when you need to construct SQL for joins
1147 *
1148 * Example:
1149 * extract($dbr->tableNames('user','watchlist'));
1150 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1151 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1152 */
1153 function tableNames() {
1154 $inArray = func_get_args();
1155 $retVal = array();
1156 foreach ( $inArray as $name ) {
1157 $retVal[$name] = $this->tableName( $name );
1158 }
1159 return $retVal;
1160 }
1161
1162 /**
1163 * @access private
1164 */
1165 function tableNamesWithUseIndex( $tables, $use_index ) {
1166 $ret = array();
1167
1168 foreach ( $tables as $table )
1169 if ( @$use_index[$table] !== null )
1170 $ret[] = $this->tableName( $table ) . ' ' . $this->useIndexClause( implode( ',', (array)$use_index[$table] ) );
1171 else
1172 $ret[] = $this->tableName( $table );
1173
1174 return implode( ',', $ret );
1175 }
1176
1177 /**
1178 * Wrapper for addslashes()
1179 * @param string $s String to be slashed.
1180 * @return string slashed string.
1181 */
1182 function strencode( $s ) {
1183 return addslashes( $s );
1184 }
1185
1186 /**
1187 * If it's a string, adds quotes and backslashes
1188 * Otherwise returns as-is
1189 */
1190 function addQuotes( $s ) {
1191 if ( is_null( $s ) ) {
1192 return 'NULL';
1193 } else {
1194 # This will also quote numeric values. This should be harmless,
1195 # and protects against weird problems that occur when they really
1196 # _are_ strings such as article titles and string->number->string
1197 # conversion is not 1:1.
1198 return "'" . $this->strencode( $s ) . "'";
1199 }
1200 }
1201
1202 /**
1203 * Escape string for safe LIKE usage
1204 */
1205 function escapeLike( $s ) {
1206 $s=$this->strencode( $s );
1207 $s=str_replace(array('%','_'),array('\%','\_'),$s);
1208 return $s;
1209 }
1210
1211 /**
1212 * Returns an appropriately quoted sequence value for inserting a new row.
1213 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
1214 * subclass will return an integer, and save the value for insertId()
1215 */
1216 function nextSequenceValue( $seqName ) {
1217 return NULL;
1218 }
1219
1220 /**
1221 * USE INDEX clause
1222 * PostgreSQL doesn't have them and returns ""
1223 */
1224 function useIndexClause( $index ) {
1225 return "FORCE INDEX ($index)";
1226 }
1227
1228 /**
1229 * REPLACE query wrapper
1230 * PostgreSQL simulates this with a DELETE followed by INSERT
1231 * $row is the row to insert, an associative array
1232 * $uniqueIndexes is an array of indexes. Each element may be either a
1233 * field name or an array of field names
1234 *
1235 * It may be more efficient to leave off unique indexes which are unlikely to collide.
1236 * However if you do this, you run the risk of encountering errors which wouldn't have
1237 * occurred in MySQL
1238 *
1239 * @todo migrate comment to phodocumentor format
1240 */
1241 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
1242 $table = $this->tableName( $table );
1243
1244 # Single row case
1245 if ( !is_array( reset( $rows ) ) ) {
1246 $rows = array( $rows );
1247 }
1248
1249 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) .') VALUES ';
1250 $first = true;
1251 foreach ( $rows as $row ) {
1252 if ( $first ) {
1253 $first = false;
1254 } else {
1255 $sql .= ',';
1256 }
1257 $sql .= '(' . $this->makeList( $row ) . ')';
1258 }
1259 return $this->query( $sql, $fname );
1260 }
1261
1262 /**
1263 * DELETE where the condition is a join
1264 * MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
1265 *
1266 * For safety, an empty $conds will not delete everything. If you want to delete all rows where the
1267 * join condition matches, set $conds='*'
1268 *
1269 * DO NOT put the join condition in $conds
1270 *
1271 * @param string $delTable The table to delete from.
1272 * @param string $joinTable The other table.
1273 * @param string $delVar The variable to join on, in the first table.
1274 * @param string $joinVar The variable to join on, in the second table.
1275 * @param array $conds Condition array of field names mapped to variables, ANDed together in the WHERE clause
1276 */
1277 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'Database::deleteJoin' ) {
1278 if ( !$conds ) {
1279 wfDebugDieBacktrace( 'Database::deleteJoin() called with empty $conds' );
1280 }
1281
1282 $delTable = $this->tableName( $delTable );
1283 $joinTable = $this->tableName( $joinTable );
1284 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1285 if ( $conds != '*' ) {
1286 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND );
1287 }
1288
1289 return $this->query( $sql, $fname );
1290 }
1291
1292 /**
1293 * Returns the size of a text field, or -1 for "unlimited"
1294 */
1295 function textFieldSize( $table, $field ) {
1296 $table = $this->tableName( $table );
1297 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
1298 $res = $this->query( $sql, 'Database::textFieldSize' );
1299 $row = $this->fetchObject( $res );
1300 $this->freeResult( $res );
1301
1302 if ( preg_match( "/\((.*)\)/", $row->Type, $m ) ) {
1303 $size = $m[1];
1304 } else {
1305 $size = -1;
1306 }
1307 return $size;
1308 }
1309
1310 /**
1311 * @return string Returns the text of the low priority option if it is supported, or a blank string otherwise
1312 */
1313 function lowPriorityOption() {
1314 return 'LOW_PRIORITY';
1315 }
1316
1317 /**
1318 * DELETE query wrapper
1319 *
1320 * Use $conds == "*" to delete all rows
1321 */
1322 function delete( $table, $conds, $fname = 'Database::delete' ) {
1323 if ( !$conds ) {
1324 wfDebugDieBacktrace( 'Database::delete() called with no conditions' );
1325 }
1326 $table = $this->tableName( $table );
1327 $sql = "DELETE FROM $table";
1328 if ( $conds != '*' ) {
1329 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
1330 }
1331 return $this->query( $sql, $fname );
1332 }
1333
1334 /**
1335 * INSERT SELECT wrapper
1336 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
1337 * Source items may be literals rather than field names, but strings should be quoted with Database::addQuotes()
1338 * $conds may be "*" to copy the whole table
1339 * srcTable may be an array of tables.
1340 */
1341 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'Database::insertSelect' ) {
1342 $destTable = $this->tableName( $destTable );
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 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 /**
1659 * Database abstraction object for mySQL
1660 * Inherit all methods and properties of Database::Database()
1661 *
1662 * @package MediaWiki
1663 * @see Database
1664 */
1665 class DatabaseMysql extends Database {
1666 # Inherit all
1667 }
1668
1669
1670 /**
1671 * Result wrapper for grabbing data queried by someone else
1672 *
1673 * @package MediaWiki
1674 */
1675 class ResultWrapper {
1676 var $db, $result;
1677
1678 /**
1679 * @todo document
1680 */
1681 function ResultWrapper( &$database, $result ) {
1682 $this->db =& $database;
1683 $this->result =& $result;
1684 }
1685
1686 /**
1687 * @todo document
1688 */
1689 function numRows() {
1690 return $this->db->numRows( $this->result );
1691 }
1692
1693 /**
1694 * @todo document
1695 */
1696 function fetchObject() {
1697 return $this->db->fetchObject( $this->result );
1698 }
1699
1700 /**
1701 * @todo document
1702 */
1703 function &fetchRow() {
1704 return $this->db->fetchRow( $this->result );
1705 }
1706
1707 /**
1708 * @todo document
1709 */
1710 function free() {
1711 $this->db->freeResult( $this->result );
1712 unset( $this->result );
1713 unset( $this->db );
1714 }
1715
1716 function seek( $row ) {
1717 $this->db->dataSeek( $this->result, $row );
1718 }
1719 }
1720
1721 #------------------------------------------------------------------------------
1722 # Global functions
1723 #------------------------------------------------------------------------------
1724
1725 /**
1726 * Standard fail function, called by default when a connection cannot be
1727 * established.
1728 * Displays the file cache if possible
1729 */
1730 function wfEmergencyAbort( &$conn, $error ) {
1731 global $wgTitle, $wgUseFileCache, $title, $wgInputEncoding, $wgOutputEncoding;
1732 global $wgSitename, $wgServer, $wgMessageCache, $wgLogo;
1733
1734 # I give up, Brion is right. Getting the message cache to work when there is no DB is tricky.
1735 # Hard coding strings instead.
1736
1737 $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>";
1738 $mainpage = 'Main Page';
1739 $searchdisabled = <<<EOT
1740 <p style="margin: 1.5em 2em 1em">$wgSitename search is disabled for performance reasons. You can search via Google in the meantime.
1741 <span style="font-size: 89%; display: block; margin-left: .2em">Note that their indexes of $wgSitename content may be out of date.</span></p>',
1742 EOT;
1743
1744 $googlesearch = "
1745 <!-- SiteSearch Google -->
1746 <FORM method=GET action=\"http://www.google.com/search\">
1747 <TABLE bgcolor=\"#FFFFFF\"><tr><td>
1748 <A HREF=\"http://www.google.com/\">
1749 <IMG SRC=\"http://www.google.com/logos/Logo_40wht.gif\"
1750 border=\"0\" ALT=\"Google\"></A>
1751 </td>
1752 <td>
1753 <INPUT TYPE=text name=q size=31 maxlength=255 value=\"$1\">
1754 <INPUT type=submit name=btnG VALUE=\"Google Search\">
1755 <font size=-1>
1756 <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 />
1757 <input type='hidden' name='ie' value='$2'>
1758 <input type='hidden' name='oe' value='$2'>
1759 </font>
1760 </td></tr></TABLE>
1761 </FORM>
1762 <!-- SiteSearch Google -->";
1763 $cachederror = "The following is a cached copy of the requested page, and may not be up to date. ";
1764
1765
1766 if( !headers_sent() ) {
1767 header( 'HTTP/1.0 500 Internal Server Error' );
1768 header( 'Content-type: text/html; charset='.$wgOutputEncoding );
1769 /* Don't cache error pages! They cause no end of trouble... */
1770 header( 'Cache-control: none' );
1771 header( 'Pragma: nocache' );
1772 }
1773
1774 # No database access
1775 if ( is_object( $wgMessageCache ) ) {
1776 $wgMessageCache->disable();
1777 }
1778
1779 if ( trim( $error ) == '' ) {
1780 $error = $this->mServer;
1781 }
1782
1783 wfLogDBError( "Connection error: $error\n" );
1784
1785 $text = str_replace( '$1', $error, $noconnect );
1786 $text .= wfGetSiteNotice();
1787
1788 if($wgUseFileCache) {
1789 if($wgTitle) {
1790 $t =& $wgTitle;
1791 } else {
1792 if($title) {
1793 $t = Title::newFromURL( $title );
1794 } elseif (@/**/$_REQUEST['search']) {
1795 $search = $_REQUEST['search'];
1796 echo $searchdisabled;
1797 echo str_replace( array( '$1', '$2' ), array( htmlspecialchars( $search ),
1798 $wgInputEncoding ), $googlesearch );
1799 wfErrorExit();
1800 } else {
1801 $t = Title::newFromText( $mainpage );
1802 }
1803 }
1804
1805 $cache = new CacheManager( $t );
1806 if( $cache->isFileCached() ) {
1807 $msg = '<p style="color: red"><b>'.$msg."<br />\n" .
1808 $cachederror . "</b></p>\n";
1809
1810 $tag = '<div id="article">';
1811 $text = str_replace(
1812 $tag,
1813 $tag . $msg,
1814 $cache->fetchPageText() );
1815 }
1816 }
1817
1818 echo $text;
1819 wfErrorExit();
1820 }
1821
1822 ?>