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