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