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