I guess we can support OFFSET too, or can we?
[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
19 /** Number of times to re-try an operation in case of deadlock */
20 define( 'DEADLOCK_TRIES', 4 );
21 /** Minimum time to wait before retry, in microseconds */
22 define( 'DEADLOCK_DELAY_MIN', 500000 );
23 /** Maximum time to wait before retry */
24 define( 'DEADLOCK_DELAY_MAX', 1500000 );
25
26 class DBObject {
27 var $mData;
28
29 function DBObject($data) {
30 $this->mData = $data;
31 }
32
33 function isLOB() {
34 return false;
35 }
36
37 function data() {
38 return $this->mData;
39 }
40 };
41
42 /**
43 * Database abstraction object
44 * @package MediaWiki
45 */
46 class Database {
47
48 #------------------------------------------------------------------------------
49 # Variables
50 #------------------------------------------------------------------------------
51 /**#@+
52 * @access private
53 */
54 var $mLastQuery = '';
55
56 var $mServer, $mUser, $mPassword, $mConn, $mDBname;
57 var $mOut, $mOpened = false;
58
59 var $mFailFunction;
60 var $mTablePrefix;
61 var $mFlags;
62 var $mTrxLevel = 0;
63 var $mErrorCount = 0;
64 /**#@-*/
65
66 #------------------------------------------------------------------------------
67 # Accessors
68 #------------------------------------------------------------------------------
69 # These optionally set a variable and return the previous state
70
71 /**
72 * Fail function, takes a Database as a parameter
73 * Set to false for default, 1 for ignore errors
74 */
75 function failFunction( $function = NULL ) {
76 return wfSetVar( $this->mFailFunction, $function );
77 }
78
79 /**
80 * Output page, used for reporting errors
81 * FALSE means discard output
82 */
83 function &setOutputPage( &$out ) {
84 $this->mOut =& $out;
85 }
86
87 /**
88 * Boolean, controls output of large amounts of debug information
89 */
90 function debug( $debug = NULL ) {
91 return wfSetBit( $this->mFlags, DBO_DEBUG, $debug );
92 }
93
94 /**
95 * Turns buffering of SQL result sets on (true) or off (false).
96 * Default is "on" and it should not be changed without good reasons.
97 */
98 function bufferResults( $buffer = NULL ) {
99 if ( is_null( $buffer ) ) {
100 return !(bool)( $this->mFlags & DBO_NOBUFFER );
101 } else {
102 return !wfSetBit( $this->mFlags, DBO_NOBUFFER, !$buffer );
103 }
104 }
105
106 /**
107 * Turns on (false) or off (true) the automatic generation and sending
108 * of a "we're sorry, but there has been a database error" page on
109 * database errors. Default is on (false). When turned off, the
110 * code should use wfLastErrno() and wfLastError() to handle the
111 * situation as appropriate.
112 */
113 function ignoreErrors( $ignoreErrors = NULL ) {
114 return wfSetBit( $this->mFlags, DBO_IGNORE, $ignoreErrors );
115 }
116
117 /**
118 * The current depth of nested transactions
119 * @param integer $level
120 */
121 function trxLevel( $level = NULL ) {
122 return wfSetVar( $this->mTrxLevel, $level );
123 }
124
125 /**
126 * Number of errors logged, only useful when errors are ignored
127 */
128 function errorCount( $count = NULL ) {
129 return wfSetVar( $this->mErrorCount, $count );
130 }
131
132 /**#@+
133 * Get function
134 */
135 function lastQuery() { return $this->mLastQuery; }
136 function isOpen() { return $this->mOpened; }
137 /**#@-*/
138
139 #------------------------------------------------------------------------------
140 # Other functions
141 #------------------------------------------------------------------------------
142
143 /**#@+
144 * @param string $server database server host
145 * @param string $user database user name
146 * @param string $password database user password
147 * @param string $dbname database name
148 */
149
150 /**
151 * @param failFunction
152 * @param $flags
153 * @param string $tablePrefix Database table prefixes. By default use the prefix gave in LocalSettings.php
154 */
155 function Database( $server = false, $user = false, $password = false, $dbName = false,
156 $failFunction = false, $flags = 0, $tablePrefix = 'get from global' ) {
157
158 global $wgOut, $wgDBprefix, $wgCommandLineMode;
159 # Can't get a reference if it hasn't been set yet
160 if ( !isset( $wgOut ) ) {
161 $wgOut = NULL;
162 }
163 $this->mOut =& $wgOut;
164
165 $this->mFailFunction = $failFunction;
166 $this->mFlags = $flags;
167
168 if ( $this->mFlags & DBO_DEFAULT ) {
169 if ( $wgCommandLineMode ) {
170 $this->mFlags &= ~DBO_TRX;
171 } else {
172 $this->mFlags |= DBO_TRX;
173 }
174 }
175
176 /*
177 // Faster read-only access
178 if ( wfReadOnly() ) {
179 $this->mFlags |= DBO_PERSISTENT;
180 $this->mFlags &= ~DBO_TRX;
181 }*/
182
183 /** Get the default table prefix*/
184 if ( $tablePrefix == 'get from global' ) {
185 $this->mTablePrefix = $wgDBprefix;
186 } else {
187 $this->mTablePrefix = $tablePrefix;
188 }
189
190 if ( $server ) {
191 $this->open( $server, $user, $password, $dbName );
192 }
193 }
194
195 /**
196 * @static
197 * @param failFunction
198 * @param $flags
199 */
200 function newFromParams( $server, $user, $password, $dbName,
201 $failFunction = false, $flags = 0 )
202 {
203 return new Database( $server, $user, $password, $dbName, $failFunction, $flags );
204 }
205
206 /**
207 * Usually aborts on failure
208 * If the failFunction is set to a non-zero integer, returns success
209 */
210 function open( $server, $user, $password, $dbName ) {
211 # Test for missing mysql.so
212 # First try to load it
213 if (!@extension_loaded('mysql')) {
214 @dl('mysql.so');
215 }
216
217 # Otherwise we get a suppressed fatal error, which is very hard to track down
218 if ( !function_exists( 'mysql_connect' ) ) {
219 die( "MySQL functions missing, have you compiled PHP with the --with-mysql option?\n" );
220 }
221
222 $this->close();
223 $this->mServer = $server;
224 $this->mUser = $user;
225 $this->mPassword = $password;
226 $this->mDBname = $dbName;
227
228 $success = false;
229
230 if ( $this->mFlags & DBO_PERSISTENT ) {
231 @/**/$this->mConn = mysql_pconnect( $server, $user, $password );
232 } else {
233 # Create a new connection...
234 @/**/$this->mConn = mysql_connect( $server, $user, $password, true );
235 }
236
237 if ( $dbName != '' ) {
238 if ( $this->mConn !== false ) {
239 $success = @/**/mysql_select_db( $dbName, $this->mConn );
240 if ( !$success ) {
241 wfDebug( "Error selecting database \"$dbName\": " . $this->lastError() . "\n" );
242 }
243 } else {
244 wfDebug( "DB connection error\n" );
245 wfDebug( "Server: $server, User: $user, Password: " .
246 substr( $password, 0, 3 ) . "..., error: " . mysql_error() . "\n" );
247 $success = false;
248 }
249 } else {
250 # Delay USE query
251 $success = (bool)$this->mConn;
252 }
253
254 if ( !$success ) {
255 $this->reportConnectionError();
256 $this->close();
257 }
258 $this->mOpened = $success;
259 return $success;
260 }
261 /**#@-*/
262
263 /**
264 * Closes a database connection.
265 * if it is open : commits any open transactions
266 *
267 * @return bool operation success. true if already closed.
268 */
269 function close()
270 {
271 $this->mOpened = false;
272 if ( $this->mConn ) {
273 if ( $this->trxLevel() ) {
274 $this->immediateCommit();
275 }
276 return mysql_close( $this->mConn );
277 } else {
278 return true;
279 }
280 }
281
282 /**
283 * @access private
284 * @param string $msg error message ?
285 * @todo parameter $msg is not used
286 */
287 function reportConnectionError( $msg = '') {
288 if ( $this->mFailFunction ) {
289 if ( !is_int( $this->mFailFunction ) ) {
290 $ff = $this->mFailFunction;
291 $ff( $this, $this->lastError() );
292 }
293 } else {
294 wfEmergencyAbort( $this, mysql_error() );
295 }
296 }
297
298 /**
299 * Usually aborts on failure
300 * If errors are explicitly ignored, returns success
301 */
302 function query( $sql, $fname = '', $tempIgnore = false ) {
303 global $wgProfiling, $wgCommandLineMode;
304
305 if ( wfReadOnly() ) {
306 # This is a quick check for the most common kinds of write query used
307 # in MediaWiki, to provide extra safety in addition to UI-level checks.
308 # It is not intended to prevent every conceivable write query, or even
309 # to handle such queries gracefully.
310 if ( preg_match( '/^(update|insert|replace|delete)/i', $sql ) ) {
311 wfDebug( "Write query from $fname blocked\n" );
312 return false;
313 }
314 }
315
316 if ( $wgProfiling ) {
317 # generalizeSQL will probably cut down the query to reasonable
318 # logging size most of the time. The substr is really just a sanity check.
319 $profName = 'query: ' . $fname . ' ' . substr( Database::generalizeSQL( $sql ), 0, 255 );
320 wfProfileIn( 'Database::query' );
321 wfProfileIn( $profName );
322 }
323
324 $this->mLastQuery = $sql;
325
326 # Add a comment for easy SHOW PROCESSLIST interpretation
327 if ( $fname ) {
328 $commentedSql = "/* $fname */ $sql";
329 } else {
330 $commentedSql = $sql;
331 }
332
333 # If DBO_TRX is set, start a transaction
334 if ( ( $this->mFlags & DBO_TRX ) && !$this->trxLevel() && $sql != 'BEGIN' ) {
335 $this->begin();
336 }
337
338 if ( $this->debug() ) {
339 $sqlx = substr( $commentedSql, 0, 500 );
340 $sqlx = strtr( $sqlx, "\t\n", ' ' );
341 wfDebug( "SQL: $sqlx\n" );
342 }
343
344 # Do the query and handle errors
345 $ret = $this->doQuery( $commentedSql );
346
347 # Try reconnecting if the connection was lost
348 if ( false === $ret && ( $this->lastErrno() == 2013 || $this->lastErrno() == 2006 ) ) {
349 # Transaction is gone, like it or not
350 $this->mTrxLevel = 0;
351 wfDebug( "Connection lost, reconnecting...\n" );
352 if ( $this->ping() ) {
353 wfDebug( "Reconnected\n" );
354 $ret = $this->doQuery( $commentedSql );
355 } else {
356 wfDebug( "Failed\n" );
357 }
358 }
359
360 if ( false === $ret ) {
361 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
362 }
363
364 if ( $wgProfiling ) {
365 wfProfileOut( $profName );
366 wfProfileOut( 'Database::query' );
367 }
368 return $ret;
369 }
370
371 /**
372 * The DBMS-dependent part of query()
373 * @param string $sql SQL query.
374 */
375 function doQuery( $sql ) {
376 if( $this->bufferResults() ) {
377 $ret = mysql_query( $sql, $this->mConn );
378 } else {
379 $ret = mysql_unbuffered_query( $sql, $this->mConn );
380 }
381 return $ret;
382 }
383
384 /**
385 * @param $error
386 * @param $errno
387 * @param $sql
388 * @param string $fname
389 * @param bool $tempIgnore
390 */
391 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
392 global $wgCommandLineMode, $wgFullyInitialised;
393 # Ignore errors during error handling to avoid infinite recursion
394 $ignore = $this->ignoreErrors( true );
395 $this->mErrorCount ++;
396
397 if( $ignore || $tempIgnore ) {
398 wfDebug("SQL ERROR (ignored): " . $error . "\n");
399 } else {
400 $sql1line = str_replace( "\n", "\\n", $sql );
401 wfLogDBError("$fname\t{$this->mServer}\t$errno\t$error\t$sql1line\n");
402 wfDebug("SQL ERROR: " . $error . "\n");
403 if ( $wgCommandLineMode || !$this->mOut || empty( $wgFullyInitialised ) ) {
404 $message = "A database error has occurred\n" .
405 "Query: $sql\n" .
406 "Function: $fname\n" .
407 "Error: $errno $error\n";
408 if ( !$wgCommandLineMode ) {
409 $message = nl2br( $message );
410 }
411 wfDebugDieBacktrace( $message );
412 } else {
413 // this calls wfAbruptExit()
414 $this->mOut->databaseError( $fname, $sql, $error, $errno );
415 }
416 }
417 $this->ignoreErrors( $ignore );
418 }
419
420
421 /**
422 * Intended to be compatible with the PEAR::DB wrapper functions.
423 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
424 *
425 * ? = scalar value, quoted as necessary
426 * ! = raw SQL bit (a function for instance)
427 * & = filename; reads the file and inserts as a blob
428 * (we don't use this though...)
429 */
430 function prepare( $sql, $func = 'Database::prepare' ) {
431 /* MySQL doesn't support prepared statements (yet), so just
432 pack up the query for reference. We'll manually replace
433 the bits later. */
434 return array( 'query' => $sql, 'func' => $func );
435 }
436
437 function freePrepared( $prepared ) {
438 /* No-op for MySQL */
439 }
440
441 /**
442 * Execute a prepared query with the various arguments
443 * @param string $prepared the prepared sql
444 * @param mixed $args Either an array here, or put scalars as varargs
445 */
446 function execute( $prepared, $args = null ) {
447 if( !is_array( $args ) ) {
448 # Pull the var args
449 $args = func_get_args();
450 array_shift( $args );
451 }
452 $sql = $this->fillPrepared( $prepared['query'], $args );
453 return $this->query( $sql, $prepared['func'] );
454 }
455
456 /**
457 * Prepare & execute an SQL statement, quoting and inserting arguments
458 * in the appropriate places.
459 * @param string $query
460 * @param string $args ...
461 */
462 function safeQuery( $query, $args = null ) {
463 $prepared = $this->prepare( $query, 'Database::safeQuery' );
464 if( !is_array( $args ) ) {
465 # Pull the var args
466 $args = func_get_args();
467 array_shift( $args );
468 }
469 $retval = $this->execute( $prepared, $args );
470 $this->freePrepared( $prepared );
471 return $retval;
472 }
473
474 /**
475 * For faking prepared SQL statements on DBs that don't support
476 * it directly.
477 * @param string $preparedSql - a 'preparable' SQL statement
478 * @param array $args - array of arguments to fill it with
479 * @return string executable SQL
480 */
481 function fillPrepared( $preparedQuery, $args ) {
482 $n = 0;
483 reset( $args );
484 $this->preparedArgs =& $args;
485 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
486 array( &$this, 'fillPreparedArg' ), $preparedQuery );
487 }
488
489 /**
490 * preg_callback func for fillPrepared()
491 * The arguments should be in $this->preparedArgs and must not be touched
492 * while we're doing this.
493 *
494 * @param array $matches
495 * @return string
496 * @access private
497 */
498 function fillPreparedArg( $matches ) {
499 switch( $matches[1] ) {
500 case '\\?': return '?';
501 case '\\!': return '!';
502 case '\\&': return '&';
503 }
504 list( $n, $arg ) = each( $this->preparedArgs );
505 switch( $matches[1] ) {
506 case '?': return $this->addQuotes( $arg );
507 case '!': return $arg;
508 case '&':
509 # return $this->addQuotes( file_get_contents( $arg ) );
510 wfDebugDieBacktrace( '& mode is not implemented. If it\'s really needed, uncomment the line above.' );
511 default:
512 wfDebugDieBacktrace( 'Received invalid match. This should never happen!' );
513 }
514 }
515
516 /**#@+
517 * @param mixed $res A SQL result
518 */
519 /**
520 * Free a result object
521 */
522 function freeResult( $res ) {
523 if ( !@/**/mysql_free_result( $res ) ) {
524 wfDebugDieBacktrace( "Unable to free MySQL result\n" );
525 }
526 }
527
528 /**
529 * Fetch the next row from the given result object, in object form
530 */
531 function fetchObject( $res ) {
532 @/**/$row = mysql_fetch_object( $res );
533 if( mysql_errno() ) {
534 wfDebugDieBacktrace( 'Error in fetchObject(): ' . htmlspecialchars( mysql_error() ) );
535 }
536 return $row;
537 }
538
539 /**
540 * Fetch the next row from the given result object
541 * Returns an array
542 */
543 function fetchRow( $res ) {
544 @/**/$row = mysql_fetch_array( $res );
545 if (mysql_errno() ) {
546 wfDebugDieBacktrace( 'Error in fetchRow(): ' . htmlspecialchars( mysql_error() ) );
547 }
548 return $row;
549 }
550
551 /**
552 * Get the number of rows in a result object
553 */
554 function numRows( $res ) {
555 @/**/$n = mysql_num_rows( $res );
556 if( mysql_errno() ) {
557 wfDebugDieBacktrace( 'Error in numRows(): ' . htmlspecialchars( mysql_error() ) );
558 }
559 return $n;
560 }
561
562 /**
563 * Get the number of fields in a result object
564 * See documentation for mysql_num_fields()
565 */
566 function numFields( $res ) { return mysql_num_fields( $res ); }
567
568 /**
569 * Get a field name in a result object
570 * See documentation for mysql_field_name()
571 */
572 function fieldName( $res, $n ) { return mysql_field_name( $res, $n ); }
573
574 /**
575 * Get the inserted value of an auto-increment row
576 *
577 * The value inserted should be fetched from nextSequenceValue()
578 *
579 * Example:
580 * $id = $dbw->nextSequenceValue('page_page_id_seq');
581 * $dbw->insert('page',array('page_id' => $id));
582 * $id = $dbw->insertId();
583 */
584 function insertId() { return mysql_insert_id( $this->mConn ); }
585
586 /**
587 * Change the position of the cursor in a result object
588 * See mysql_data_seek()
589 */
590 function dataSeek( $res, $row ) { return mysql_data_seek( $res, $row ); }
591
592 /**
593 * Get the last error number
594 * See mysql_errno()
595 */
596 function lastErrno() {
597 if ( $this->mConn ) {
598 return mysql_errno( $this->mConn );
599 } else {
600 return mysql_errno();
601 }
602 }
603
604 /**
605 * Get a description of the last error
606 * See mysql_error() for more details
607 */
608 function lastError() {
609 if ( $this->mConn ) {
610 $error = mysql_error( $this->mConn );
611 } else {
612 $error = mysql_error();
613 }
614 if( $error ) {
615 $error .= ' (' . $this->mServer . ')';
616 }
617 return $error;
618 }
619 /**
620 * Get the number of rows affected by the last write query
621 * See mysql_affected_rows() for more details
622 */
623 function affectedRows() { return mysql_affected_rows( $this->mConn ); }
624 /**#@-*/ // end of template : @param $result
625
626 /**
627 * Simple UPDATE wrapper
628 * Usually aborts on failure
629 * If errors are explicitly ignored, returns success
630 *
631 * This function exists for historical reasons, Database::update() has a more standard
632 * calling convention and feature set
633 */
634 function set( $table, $var, $value, $cond, $fname = 'Database::set' )
635 {
636 $table = $this->tableName( $table );
637 $sql = "UPDATE $table SET $var = '" .
638 $this->strencode( $value ) . "' WHERE ($cond)";
639 return (bool)$this->query( $sql, DB_MASTER, $fname );
640 }
641
642 /**
643 * Simple SELECT wrapper, returns a single field, input must be encoded
644 * Usually aborts on failure
645 * If errors are explicitly ignored, returns FALSE on failure
646 */
647 function selectField( $table, $var, $cond='', $fname = 'Database::selectField', $options = array() ) {
648 if ( !is_array( $options ) ) {
649 $options = array( $options );
650 }
651 $options['LIMIT'] = 1;
652
653 $res = $this->select( $table, $var, $cond, $fname, $options );
654 if ( $res === false || !$this->numRows( $res ) ) {
655 return false;
656 }
657 $row = $this->fetchRow( $res );
658 if ( $row !== false ) {
659 $this->freeResult( $res );
660 return $row[0];
661 } else {
662 return false;
663 }
664 }
665
666 /**
667 * Returns an optional USE INDEX clause to go after the table, and a
668 * string to go at the end of the query
669 *
670 * @access private
671 *
672 * @param array $options an associative array of options to be turned into
673 * an SQL query, valid keys are listed in the function.
674 * @return array
675 */
676 function makeSelectOptions( $options ) {
677 $tailOpts = '';
678
679 if ( isset( $options['GROUP BY'] ) ) {
680 $tailOpts .= " GROUP BY {$options['GROUP BY']}";
681 }
682 if ( isset( $options['ORDER BY'] ) ) {
683 $tailOpts .= " ORDER BY {$options['ORDER BY']}";
684 }
685
686 if ( is_numeric( array_search( 'FOR UPDATE', $options ) ) ) {
687 $tailOpts .= ' FOR UPDATE';
688 }
689
690 if ( is_numeric( array_search( 'LOCK IN SHARE MODE', $options ) ) ) {
691 $tailOpts .= ' LOCK IN SHARE MODE';
692 }
693
694 if ( isset( $options['USE INDEX'] ) ) {
695 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
696 } else {
697 $useIndex = '';
698 }
699 return array( $useIndex, $tailOpts );
700 }
701
702 /**
703 * SELECT wrapper
704 */
705 function select( $table, $vars, $conds='', $fname = 'Database::select', $options = array() )
706 {
707 if( is_array( $vars ) ) {
708 $vars = implode( ',', $vars );
709 }
710 if( !is_array( $options ) ) {
711 $options = array( $options );
712 }
713 if( is_array( $table ) ) {
714 $from = ' FROM ' . implode( ',', array_map( array( &$this, 'tableName' ), $table ) );
715 } elseif ($table!='') {
716 $from = ' FROM ' .$this->tableName( $table );
717 } else {
718 $from = '';
719 }
720
721 list( $useIndex, $tailOpts ) = $this->makeSelectOptions( $options );
722
723 if( !empty( $conds ) ) {
724 if ( is_array( $conds ) ) {
725 $conds = $this->makeList( $conds, LIST_AND );
726 }
727 $sql = "SELECT $vars $from $useIndex WHERE $conds $tailOpts";
728 } else {
729 $sql = "SELECT $vars $from $useIndex $tailOpts";
730 }
731 if (isset($options['LIMIT'])) {
732 $sql = $this->limitResult($sql, $options['LIMIT'], isset($options['OFFSET']) ? $options['OFFSET'] : false);
733 }
734 return $this->query( $sql, $fname );
735 }
736
737 /**
738 * Single row SELECT wrapper
739 * Aborts or returns FALSE on error
740 *
741 * $vars: the selected variables
742 * $conds: a condition map, terms are ANDed together.
743 * Items with numeric keys are taken to be literal conditions
744 * Takes an array of selected variables, and a condition map, which is ANDed
745 * e.g: selectRow( "page", array( "page_id" ), array( "page_namespace" =>
746 * NS_MAIN, "page_title" => "Astronomy" ) ) would return an object where
747 * $obj- >page_id is the ID of the Astronomy article
748 *
749 * @todo migrate documentation to phpdocumentor format
750 */
751 function selectRow( $table, $vars, $conds, $fname = 'Database::selectRow', $options = array() ) {
752 $options['LIMIT'] = 1;
753 $res = $this->select( $table, $vars, $conds, $fname, $options );
754 if ( $res === false )
755 return false;
756 if ( !$this->numRows($res) ) {
757 $this->freeResult($res);
758 return false;
759 }
760 $obj = $this->fetchObject( $res );
761 $this->freeResult( $res );
762 return $obj;
763
764 }
765
766 /**
767 * Removes most variables from an SQL query and replaces them with X or N for numbers.
768 * It's only slightly flawed. Don't use for anything important.
769 *
770 * @param string $sql A SQL Query
771 * @static
772 */
773 function generalizeSQL( $sql ) {
774 # This does the same as the regexp below would do, but in such a way
775 # as to avoid crashing php on some large strings.
776 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
777
778 $sql = str_replace ( "\\\\", '', $sql);
779 $sql = str_replace ( "\\'", '', $sql);
780 $sql = str_replace ( "\\\"", '', $sql);
781 $sql = preg_replace ("/'.*'/s", "'X'", $sql);
782 $sql = preg_replace ('/".*"/s', "'X'", $sql);
783
784 # All newlines, tabs, etc replaced by single space
785 $sql = preg_replace ( "/\s+/", ' ', $sql);
786
787 # All numbers => N
788 $sql = preg_replace ('/-?[0-9]+/s', 'N', $sql);
789
790 return $sql;
791 }
792
793 /**
794 * Determines whether a field exists in a table
795 * Usually aborts on failure
796 * If errors are explicitly ignored, returns NULL on failure
797 */
798 function fieldExists( $table, $field, $fname = 'Database::fieldExists' ) {
799 $table = $this->tableName( $table );
800 $res = $this->query( 'DESCRIBE '.$table, DB_SLAVE, $fname );
801 if ( !$res ) {
802 return NULL;
803 }
804
805 $found = false;
806
807 while ( $row = $this->fetchObject( $res ) ) {
808 if ( $row->Field == $field ) {
809 $found = true;
810 break;
811 }
812 }
813 return $found;
814 }
815
816 /**
817 * Determines whether an index exists
818 * Usually aborts on failure
819 * If errors are explicitly ignored, returns NULL on failure
820 */
821 function indexExists( $table, $index, $fname = 'Database::indexExists' ) {
822 $info = $this->indexInfo( $table, $index, $fname );
823 if ( is_null( $info ) ) {
824 return NULL;
825 } else {
826 return $info !== false;
827 }
828 }
829
830
831 /**
832 * Get information about an index into an object
833 * Returns false if the index does not exist
834 */
835 function indexInfo( $table, $index, $fname = 'Database::indexInfo' ) {
836 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
837 # SHOW INDEX should work for 3.x and up:
838 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
839 $table = $this->tableName( $table );
840 $sql = 'SHOW INDEX FROM '.$table;
841 $res = $this->query( $sql, $fname );
842 if ( !$res ) {
843 return NULL;
844 }
845
846 while ( $row = $this->fetchObject( $res ) ) {
847 if ( $row->Key_name == $index ) {
848 return $row;
849 }
850 }
851 return false;
852 }
853
854 /**
855 * Query whether a given table exists
856 */
857 function tableExists( $table ) {
858 $table = $this->tableName( $table );
859 $old = $this->ignoreErrors( true );
860 $res = $this->query( "SELECT 1 FROM $table LIMIT 1" );
861 $this->ignoreErrors( $old );
862 if( $res ) {
863 $this->freeResult( $res );
864 return true;
865 } else {
866 return false;
867 }
868 }
869
870 /**
871 * mysql_fetch_field() wrapper
872 * Returns false if the field doesn't exist
873 *
874 * @param $table
875 * @param $field
876 */
877 function fieldInfo( $table, $field ) {
878 $table = $this->tableName( $table );
879 $res = $this->query( "SELECT * FROM $table LIMIT 1" );
880 $n = mysql_num_fields( $res );
881 for( $i = 0; $i < $n; $i++ ) {
882 $meta = mysql_fetch_field( $res, $i );
883 if( $field == $meta->name ) {
884 return $meta;
885 }
886 }
887 return false;
888 }
889
890 /**
891 * mysql_field_type() wrapper
892 */
893 function fieldType( $res, $index ) {
894 return mysql_field_type( $res, $index );
895 }
896
897 /**
898 * Determines if a given index is unique
899 */
900 function indexUnique( $table, $index ) {
901 $indexInfo = $this->indexInfo( $table, $index );
902 if ( !$indexInfo ) {
903 return NULL;
904 }
905 return !$indexInfo->Non_unique;
906 }
907
908 /**
909 * INSERT wrapper, inserts an array into a table
910 *
911 * $a may be a single associative array, or an array of these with numeric keys, for
912 * multi-row insert.
913 *
914 * Usually aborts on failure
915 * If errors are explicitly ignored, returns success
916 */
917 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
918 # No rows to insert, easy just return now
919 if ( !count( $a ) ) {
920 return true;
921 }
922
923 $table = $this->tableName( $table );
924 if ( !is_array( $options ) ) {
925 $options = array( $options );
926 }
927 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
928 $multi = true;
929 $keys = array_keys( $a[0] );
930 } else {
931 $multi = false;
932 $keys = array_keys( $a );
933 }
934
935 $sql = 'INSERT ' . implode( ' ', $options ) .
936 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
937
938 if ( $multi ) {
939 $first = true;
940 foreach ( $a as $row ) {
941 if ( $first ) {
942 $first = false;
943 } else {
944 $sql .= ',';
945 }
946 $sql .= '(' . $this->makeList( $row ) . ')';
947 }
948 } else {
949 $sql .= '(' . $this->makeList( $a ) . ')';
950 }
951 return (bool)$this->query( $sql, $fname );
952 }
953
954 /**
955 * Make UPDATE options for the Database::update function
956 *
957 * @access private
958 * @param array $options The options passed to Database::update
959 * @return string
960 */
961 function makeUpdateOptions( $options ) {
962 if( !is_array( $options ) ) {
963 wfDebugDieBacktrace( 'makeUpdateOptions given non-array' );
964 }
965 $opts = array();
966 if ( in_array( 'LOW_PRIORITY', $options ) )
967 $opts[] = $this->lowPriorityOption();
968 if ( in_array( 'IGNORE', $options ) )
969 $opts[] = 'IGNORE';
970 return implode(' ', $opts);
971 }
972
973 /**
974 * UPDATE wrapper, takes a condition array and a SET array
975 *
976 * @param string $table The table to UPDATE
977 * @param array $values An array of values to SET
978 * @param array $conds An array of conditions (WHERE)
979 * @param string $fname The Class::Function calling this function
980 * (for the log)
981 * @param array $options An array of UPDATE options, can be one or
982 * more of IGNORE, LOW_PRIORITY
983 */
984 function update( $table, $values, $conds, $fname = 'Database::update', $options = array() ) {
985 $table = $this->tableName( $table );
986 $opts = $this->makeUpdateOptions( $options );
987 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET );
988 if ( $conds != '*' ) {
989 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND );
990 }
991 $this->query( $sql, $fname );
992 }
993
994 /**
995 * Makes a wfStrencoded list from an array
996 * $mode: LIST_COMMA - comma separated, no field names
997 * LIST_AND - ANDed WHERE clause (without the WHERE)
998 * LIST_SET - comma separated with field names, like a SET clause
999 * LIST_NAMES - comma separated field names
1000 */
1001 function makeList( $a, $mode = LIST_COMMA ) {
1002 if ( !is_array( $a ) ) {
1003 wfDebugDieBacktrace( 'Database::makeList called with incorrect parameters' );
1004 }
1005
1006 $first = true;
1007 $list = '';
1008 foreach ( $a as $field => $value ) {
1009 if ( !$first ) {
1010 if ( $mode == LIST_AND ) {
1011 $list .= ' AND ';
1012 } else {
1013 $list .= ',';
1014 }
1015 } else {
1016 $first = false;
1017 }
1018 if ( $mode == LIST_AND && is_numeric( $field ) ) {
1019 $list .= "($value)";
1020 } elseif ( $mode == LIST_AND && is_array ($value) ) {
1021 $list .= $field." IN (".$this->makeList($value).") ";
1022 } else {
1023 if ( $mode == LIST_AND || $mode == LIST_SET ) {
1024 $list .= "$field = ";
1025 }
1026 $list .= $mode == LIST_NAMES ? $value : $this->addQuotes( $value );
1027 }
1028 }
1029 return $list;
1030 }
1031
1032 /**
1033 * Change the current database
1034 */
1035 function selectDB( $db ) {
1036 $this->mDBname = $db;
1037 return mysql_select_db( $db, $this->mConn );
1038 }
1039
1040 /**
1041 * Starts a timer which will kill the DB thread after $timeout seconds
1042 */
1043 function startTimer( $timeout ) {
1044 global $IP;
1045 if( function_exists( 'mysql_thread_id' ) ) {
1046 # This will kill the query if it's still running after $timeout seconds.
1047 $tid = mysql_thread_id( $this->mConn );
1048 exec( "php $IP/includes/killthread.php $timeout $tid &>/dev/null &" );
1049 }
1050 }
1051
1052 /**
1053 * Stop a timer started by startTimer()
1054 * Currently unimplemented.
1055 *
1056 */
1057 function stopTimer() { }
1058
1059 /**
1060 * Format a table name ready for use in constructing an SQL query
1061 *
1062 * This does two important things: it quotes table names which as necessary,
1063 * and it adds a table prefix if there is one.
1064 *
1065 * All functions of this object which require a table name call this function
1066 * themselves. Pass the canonical name to such functions. This is only needed
1067 * when calling query() directly.
1068 *
1069 * @param string $name database table name
1070 */
1071 function tableName( $name ) {
1072 global $wgSharedDB;
1073 # Skip quoted literals
1074 if ( $name{0} != '`' ) {
1075 if ( $this->mTablePrefix !== '' && strpos( '.', $name ) === false ) {
1076 $name = "{$this->mTablePrefix}$name";
1077 }
1078 if ( isset( $wgSharedDB ) && "{$this->mTablePrefix}user" == $name ) {
1079 $name = "`$wgSharedDB`.`$name`";
1080 } else {
1081 # Standard quoting
1082 $name = "`$name`";
1083 }
1084 }
1085 return $name;
1086 }
1087
1088 /**
1089 * Fetch a number of table names into an array
1090 * This is handy when you need to construct SQL for joins
1091 *
1092 * Example:
1093 * extract($dbr->tableNames('user','watchlist'));
1094 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1095 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1096 */
1097 function tableNames() {
1098 $inArray = func_get_args();
1099 $retVal = array();
1100 foreach ( $inArray as $name ) {
1101 $retVal[$name] = $this->tableName( $name );
1102 }
1103 return $retVal;
1104 }
1105
1106 /**
1107 * Wrapper for addslashes()
1108 * @param string $s String to be slashed.
1109 * @return string slashed string.
1110 */
1111 function strencode( $s ) {
1112 return addslashes( $s );
1113 }
1114
1115 /**
1116 * If it's a string, adds quotes and backslashes
1117 * Otherwise returns as-is
1118 */
1119 function addQuotes( $s ) {
1120 if ( is_null( $s ) ) {
1121 return 'NULL';
1122 } else {
1123 # This will also quote numeric values. This should be harmless,
1124 # and protects against weird problems that occur when they really
1125 # _are_ strings such as article titles and string->number->string
1126 # conversion is not 1:1.
1127 return "'" . $this->strencode( $s ) . "'";
1128 }
1129 }
1130
1131 /**
1132 * Returns an appropriately quoted sequence value for inserting a new row.
1133 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
1134 * subclass will return an integer, and save the value for insertId()
1135 */
1136 function nextSequenceValue( $seqName ) {
1137 return NULL;
1138 }
1139
1140 /**
1141 * USE INDEX clause
1142 * PostgreSQL doesn't have them and returns ""
1143 */
1144 function useIndexClause( $index ) {
1145 return "FORCE INDEX ($index)";
1146 }
1147
1148 /**
1149 * REPLACE query wrapper
1150 * PostgreSQL simulates this with a DELETE followed by INSERT
1151 * $row is the row to insert, an associative array
1152 * $uniqueIndexes is an array of indexes. Each element may be either a
1153 * field name or an array of field names
1154 *
1155 * It may be more efficient to leave off unique indexes which are unlikely to collide.
1156 * However if you do this, you run the risk of encountering errors which wouldn't have
1157 * occurred in MySQL
1158 *
1159 * @todo migrate comment to phodocumentor format
1160 */
1161 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
1162 $table = $this->tableName( $table );
1163
1164 # Single row case
1165 if ( !is_array( reset( $rows ) ) ) {
1166 $rows = array( $rows );
1167 }
1168
1169 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) .') VALUES ';
1170 $first = true;
1171 foreach ( $rows as $row ) {
1172 if ( $first ) {
1173 $first = false;
1174 } else {
1175 $sql .= ',';
1176 }
1177 $sql .= '(' . $this->makeList( $row ) . ')';
1178 }
1179 return $this->query( $sql, $fname );
1180 }
1181
1182 /**
1183 * DELETE where the condition is a join
1184 * MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
1185 *
1186 * For safety, an empty $conds will not delete everything. If you want to delete all rows where the
1187 * join condition matches, set $conds='*'
1188 *
1189 * DO NOT put the join condition in $conds
1190 *
1191 * @param string $delTable The table to delete from.
1192 * @param string $joinTable The other table.
1193 * @param string $delVar The variable to join on, in the first table.
1194 * @param string $joinVar The variable to join on, in the second table.
1195 * @param array $conds Condition array of field names mapped to variables, ANDed together in the WHERE clause
1196 */
1197 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'Database::deleteJoin' ) {
1198 if ( !$conds ) {
1199 wfDebugDieBacktrace( 'Database::deleteJoin() called with empty $conds' );
1200 }
1201
1202 $delTable = $this->tableName( $delTable );
1203 $joinTable = $this->tableName( $joinTable );
1204 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1205 if ( $conds != '*' ) {
1206 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND );
1207 }
1208
1209 return $this->query( $sql, $fname );
1210 }
1211
1212 /**
1213 * Returns the size of a text field, or -1 for "unlimited"
1214 */
1215 function textFieldSize( $table, $field ) {
1216 $table = $this->tableName( $table );
1217 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
1218 $res = $this->query( $sql, 'Database::textFieldSize' );
1219 $row = $this->fetchObject( $res );
1220 $this->freeResult( $res );
1221
1222 if ( preg_match( "/\((.*)\)/", $row->Type, $m ) ) {
1223 $size = $m[1];
1224 } else {
1225 $size = -1;
1226 }
1227 return $size;
1228 }
1229
1230 /**
1231 * @return string Returns the text of the low priority option if it is supported, or a blank string otherwise
1232 */
1233 function lowPriorityOption() {
1234 return 'LOW_PRIORITY';
1235 }
1236
1237 /**
1238 * DELETE query wrapper
1239 *
1240 * Use $conds == "*" to delete all rows
1241 */
1242 function delete( $table, $conds, $fname = 'Database::delete' ) {
1243 if ( !$conds ) {
1244 wfDebugDieBacktrace( 'Database::delete() called with no conditions' );
1245 }
1246 $table = $this->tableName( $table );
1247 $sql = "DELETE FROM $table";
1248 if ( $conds != '*' ) {
1249 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
1250 }
1251 return $this->query( $sql, $fname );
1252 }
1253
1254 /**
1255 * INSERT SELECT wrapper
1256 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
1257 * Source items may be literals rather than field names, but strings should be quoted with Database::addQuotes()
1258 * $conds may be "*" to copy the whole table
1259 * srcTable may be an array of tables.
1260 */
1261 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'Database::insertSelect' ) {
1262 $destTable = $this->tableName( $destTable );
1263 if( is_array( $srcTable ) ) {
1264 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
1265 } else {
1266 $srcTable = $this->tableName( $srcTable );
1267 }
1268 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
1269 ' SELECT ' . implode( ',', $varMap ) .
1270 " FROM $srcTable";
1271 if ( $conds != '*' ) {
1272 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
1273 }
1274 return $this->query( $sql, $fname );
1275 }
1276
1277 /**
1278 * Construct a LIMIT query with optional offset
1279 * This is used for query pages
1280 */
1281 function limitResult($sql, $limit, $offset) {
1282 return "$sql LIMIT ".((is_numeric($offset) && $offset != 0)?"{$offset},":"")."{$limit} ";
1283 }
1284 function limitResultForUpdate($sql, $num) {
1285 return $this->limitResult($sql, $num, 0);
1286 }
1287
1288 /**
1289 * Returns an SQL expression for a simple conditional.
1290 * Uses IF on MySQL.
1291 *
1292 * @param string $cond SQL expression which will result in a boolean value
1293 * @param string $trueVal SQL expression to return if true
1294 * @param string $falseVal SQL expression to return if false
1295 * @return string SQL fragment
1296 */
1297 function conditional( $cond, $trueVal, $falseVal ) {
1298 return " IF($cond, $trueVal, $falseVal) ";
1299 }
1300
1301 /**
1302 * Determines if the last failure was due to a deadlock
1303 */
1304 function wasDeadlock() {
1305 return $this->lastErrno() == 1213;
1306 }
1307
1308 /**
1309 * Perform a deadlock-prone transaction.
1310 *
1311 * This function invokes a callback function to perform a set of write
1312 * queries. If a deadlock occurs during the processing, the transaction
1313 * will be rolled back and the callback function will be called again.
1314 *
1315 * Usage:
1316 * $dbw->deadlockLoop( callback, ... );
1317 *
1318 * Extra arguments are passed through to the specified callback function.
1319 *
1320 * Returns whatever the callback function returned on its successful,
1321 * iteration, or false on error, for example if the retry limit was
1322 * reached.
1323 */
1324 function deadlockLoop() {
1325 $myFname = 'Database::deadlockLoop';
1326
1327 $this->begin();
1328 $args = func_get_args();
1329 $function = array_shift( $args );
1330 $oldIgnore = $this->ignoreErrors( true );
1331 $tries = DEADLOCK_TRIES;
1332 if ( is_array( $function ) ) {
1333 $fname = $function[0];
1334 } else {
1335 $fname = $function;
1336 }
1337 do {
1338 $retVal = call_user_func_array( $function, $args );
1339 $error = $this->lastError();
1340 $errno = $this->lastErrno();
1341 $sql = $this->lastQuery();
1342
1343 if ( $errno ) {
1344 if ( $this->wasDeadlock() ) {
1345 # Retry
1346 usleep( mt_rand( DEADLOCK_DELAY_MIN, DEADLOCK_DELAY_MAX ) );
1347 } else {
1348 $this->reportQueryError( $error, $errno, $sql, $fname );
1349 }
1350 }
1351 } while( $this->wasDeadlock() && --$tries > 0 );
1352 $this->ignoreErrors( $oldIgnore );
1353 if ( $tries <= 0 ) {
1354 $this->query( 'ROLLBACK', $myFname );
1355 $this->reportQueryError( $error, $errno, $sql, $fname );
1356 return false;
1357 } else {
1358 $this->query( 'COMMIT', $myFname );
1359 return $retVal;
1360 }
1361 }
1362
1363 /**
1364 * Do a SELECT MASTER_POS_WAIT()
1365 *
1366 * @param string $file the binlog file
1367 * @param string $pos the binlog position
1368 * @param integer $timeout the maximum number of seconds to wait for synchronisation
1369 */
1370 function masterPosWait( $file, $pos, $timeout ) {
1371 $fname = 'Database::masterPosWait';
1372 wfProfileIn( $fname );
1373
1374
1375 # Commit any open transactions
1376 $this->immediateCommit();
1377
1378 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
1379 $encFile = $this->strencode( $file );
1380 $sql = "SELECT MASTER_POS_WAIT('$encFile', $pos, $timeout)";
1381 $res = $this->doQuery( $sql );
1382 if ( $res && $row = $this->fetchRow( $res ) ) {
1383 $this->freeResult( $res );
1384 wfProfileOut( $fname );
1385 return $row[0];
1386 } else {
1387 wfProfileOut( $fname );
1388 return false;
1389 }
1390 }
1391
1392 /**
1393 * Get the position of the master from SHOW SLAVE STATUS
1394 */
1395 function getSlavePos() {
1396 $res = $this->query( 'SHOW SLAVE STATUS', 'Database::getSlavePos' );
1397 $row = $this->fetchObject( $res );
1398 if ( $row ) {
1399 return array( $row->Master_Log_File, $row->Read_Master_Log_Pos );
1400 } else {
1401 return array( false, false );
1402 }
1403 }
1404
1405 /**
1406 * Get the position of the master from SHOW MASTER STATUS
1407 */
1408 function getMasterPos() {
1409 $res = $this->query( 'SHOW MASTER STATUS', 'Database::getMasterPos' );
1410 $row = $this->fetchObject( $res );
1411 if ( $row ) {
1412 return array( $row->File, $row->Position );
1413 } else {
1414 return array( false, false );
1415 }
1416 }
1417
1418 /**
1419 * Begin a transaction, or if a transaction has already started, continue it
1420 */
1421 function begin( $fname = 'Database::begin' ) {
1422 if ( !$this->mTrxLevel ) {
1423 $this->immediateBegin( $fname );
1424 } else {
1425 $this->mTrxLevel++;
1426 }
1427 }
1428
1429 /**
1430 * End a transaction, or decrement the nest level if transactions are nested
1431 */
1432 function commit( $fname = 'Database::commit' ) {
1433 if ( $this->mTrxLevel ) {
1434 $this->mTrxLevel--;
1435 }
1436 if ( !$this->mTrxLevel ) {
1437 $this->immediateCommit( $fname );
1438 }
1439 }
1440
1441 /**
1442 * Rollback a transaction
1443 */
1444 function rollback( $fname = 'Database::rollback' ) {
1445 $this->query( 'ROLLBACK', $fname );
1446 $this->mTrxLevel = 0;
1447 }
1448
1449 /**
1450 * Begin a transaction, committing any previously open transaction
1451 */
1452 function immediateBegin( $fname = 'Database::immediateBegin' ) {
1453 $this->query( 'BEGIN', $fname );
1454 $this->mTrxLevel = 1;
1455 }
1456
1457 /**
1458 * Commit transaction, if one is open
1459 */
1460 function immediateCommit( $fname = 'Database::immediateCommit' ) {
1461 $this->query( 'COMMIT', $fname );
1462 $this->mTrxLevel = 0;
1463 }
1464
1465 /**
1466 * Return MW-style timestamp used for MySQL schema
1467 */
1468 function timestamp( $ts=0 ) {
1469 return wfTimestamp(TS_MW,$ts);
1470 }
1471
1472 /**
1473 * Local database timestamp format or null
1474 */
1475 function timestampOrNull( $ts = null ) {
1476 if( is_null( $ts ) ) {
1477 return null;
1478 } else {
1479 return $this->timestamp( $ts );
1480 }
1481 }
1482
1483 /**
1484 * @todo document
1485 */
1486 function resultObject( &$result ) {
1487 if( empty( $result ) ) {
1488 return NULL;
1489 } else {
1490 return new ResultWrapper( $this, $result );
1491 }
1492 }
1493
1494 /**
1495 * Return aggregated value alias
1496 */
1497 function aggregateValue ($valuedata,$valuename='value') {
1498 return $valuename;
1499 }
1500
1501 /**
1502 * @return string wikitext of a link to the server software's web site
1503 */
1504 function getSoftwareLink() {
1505 return "[http://www.mysql.com/ MySQL]";
1506 }
1507
1508 /**
1509 * @return string Version information from the database
1510 */
1511 function getServerVersion() {
1512 return mysql_get_server_info();
1513 }
1514
1515 /**
1516 * Ping the server and try to reconnect if it there is no connection
1517 */
1518 function ping() {
1519 if( function_exists( 'mysql_ping' ) ) {
1520 return mysql_ping( $this->mConn );
1521 } else {
1522 wfDebug( "Tried to call mysql_ping but this is ancient PHP version. Faking it!\n" );
1523 return true;
1524 }
1525 }
1526
1527 /**
1528 * Get slave lag.
1529 * At the moment, this will only work if the DB user has the PROCESS privilege
1530 */
1531 function getLag() {
1532 $res = $this->query( 'SHOW PROCESSLIST' );
1533 # Find slave SQL thread. Assumed to be the second one running, which is a bit
1534 # dubious, but unfortunately there's no easy rigorous way
1535 $slaveThreads = 0;
1536 while ( $row = $this->fetchObject( $res ) ) {
1537 if ( $row->User == 'system user' ) {
1538 if ( ++$slaveThreads == 2 ) {
1539 # This is it, return the time
1540 return $row->Time;
1541 }
1542 }
1543 }
1544 return false;
1545 }
1546
1547 /**
1548 * Get status information from SHOW STATUS in an associative array
1549 */
1550 function getStatus() {
1551 $res = $this->query( 'SHOW STATUS' );
1552 $status = array();
1553 while ( $row = $this->fetchObject( $res ) ) {
1554 $status[$row->Variable_name] = $row->Value;
1555 }
1556 return $status;
1557 }
1558
1559 /**
1560 * Return the maximum number of items allowed in a list, or 0 for unlimited.
1561 */
1562 function maxListLen() {
1563 return 0;
1564 }
1565
1566 function encodeBlob($b) {
1567 return $b;
1568 }
1569
1570 function notNullTimestamp() {
1571 return "!= 0";
1572 }
1573 function isNullTimestamp() {
1574 return "= '0'";
1575 }
1576 }
1577
1578 /**
1579 * Database abstraction object for mySQL
1580 * Inherit all methods and properties of Database::Database()
1581 *
1582 * @package MediaWiki
1583 * @see Database
1584 */
1585 class DatabaseMysql extends Database {
1586 # Inherit all
1587 }
1588
1589
1590 /**
1591 * Result wrapper for grabbing data queried by someone else
1592 *
1593 * @package MediaWiki
1594 */
1595 class ResultWrapper {
1596 var $db, $result;
1597
1598 /**
1599 * @todo document
1600 */
1601 function ResultWrapper( $database, $result ) {
1602 $this->db =& $database;
1603 $this->result =& $result;
1604 }
1605
1606 /**
1607 * @todo document
1608 */
1609 function numRows() {
1610 return $this->db->numRows( $this->result );
1611 }
1612
1613 /**
1614 * @todo document
1615 */
1616 function fetchObject() {
1617 return $this->db->fetchObject( $this->result );
1618 }
1619
1620 /**
1621 * @todo document
1622 */
1623 function &fetchRow() {
1624 return $this->db->fetchRow( $this->result );
1625 }
1626
1627 /**
1628 * @todo document
1629 */
1630 function free() {
1631 $this->db->freeResult( $this->result );
1632 unset( $this->result );
1633 unset( $this->db );
1634 }
1635
1636 function seek( $row ) {
1637 $this->db->dataSeek( $this->result, $row );
1638 }
1639 }
1640
1641 #------------------------------------------------------------------------------
1642 # Global functions
1643 #------------------------------------------------------------------------------
1644
1645 /**
1646 * Standard fail function, called by default when a connection cannot be
1647 * established.
1648 * Displays the file cache if possible
1649 */
1650 function wfEmergencyAbort( &$conn, $error ) {
1651 global $wgTitle, $wgUseFileCache, $title, $wgInputEncoding, $wgOutputEncoding;
1652 global $wgSitename, $wgServer;
1653
1654 # I give up, Brion is right. Getting the message cache to work when there is no DB is tricky.
1655 # Hard coding strings instead.
1656
1657 $noconnect = 'Sorry! The wiki is experiencing some technical difficulties, and cannot contact the database server: $1. <br />
1658 $1';
1659 $mainpage = 'Main Page';
1660 $searchdisabled = <<<EOT
1661 <p style="margin: 1.5em 2em 1em">$wgSitename search is disabled for performance reasons. You can search via Google in the meantime.
1662 <span style="font-size: 89%; display: block; margin-left: .2em">Note that their indexes of $wgSitename content may be out of date.</span></p>',
1663 EOT;
1664
1665 $googlesearch = "
1666 <!-- SiteSearch Google -->
1667 <FORM method=GET action=\"http://www.google.com/search\">
1668 <TABLE bgcolor=\"#FFFFFF\"><tr><td>
1669 <A HREF=\"http://www.google.com/\">
1670 <IMG SRC=\"http://www.google.com/logos/Logo_40wht.gif\"
1671 border=\"0\" ALT=\"Google\"></A>
1672 </td>
1673 <td>
1674 <INPUT TYPE=text name=q size=31 maxlength=255 value=\"$1\">
1675 <INPUT type=submit name=btnG VALUE=\"Google Search\">
1676 <font size=-1>
1677 <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 />
1678 <input type='hidden' name='ie' value='$2'>
1679 <input type='hidden' name='oe' value='$2'>
1680 </font>
1681 </td></tr></TABLE>
1682 </FORM>
1683 <!-- SiteSearch Google -->";
1684 $cachederror = "The following is a cached copy of the requested page, and may not be up to date. ";
1685
1686
1687 if( !headers_sent() ) {
1688 header( 'HTTP/1.0 500 Internal Server Error' );
1689 header( 'Content-type: text/html; charset='.$wgOutputEncoding );
1690 /* Don't cache error pages! They cause no end of trouble... */
1691 header( 'Cache-control: none' );
1692 header( 'Pragma: nocache' );
1693 }
1694 $msg = wfGetSiteNotice();
1695 if($msg == '') {
1696 $msg = str_replace( '$1', $error, $noconnect );
1697 }
1698 $text = $msg;
1699
1700 if($wgUseFileCache) {
1701 if($wgTitle) {
1702 $t =& $wgTitle;
1703 } else {
1704 if($title) {
1705 $t = Title::newFromURL( $title );
1706 } elseif (@/**/$_REQUEST['search']) {
1707 $search = $_REQUEST['search'];
1708 echo $searchdisabled;
1709 echo str_replace( array( '$1', '$2' ), array( htmlspecialchars( $search ),
1710 $wgInputEncoding ), $googlesearch );
1711 wfErrorExit();
1712 } else {
1713 $t = Title::newFromText( $mainpage );
1714 }
1715 }
1716
1717 $cache = new CacheManager( $t );
1718 if( $cache->isFileCached() ) {
1719 $msg = '<p style="color: red"><b>'.$msg."<br />\n" .
1720 $cachederror . "</b></p>\n";
1721
1722 $tag = '<div id="article">';
1723 $text = str_replace(
1724 $tag,
1725 $tag . $msg,
1726 $cache->fetchPageText() );
1727 }
1728 }
1729
1730 echo $text;
1731 wfErrorExit();
1732 }
1733
1734 ?>