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