3 # This file deals with MySQL interface functions
4 # and query specifics/optimisations
6 require_once( "CacheManager.php" );
8 define( "DB_READ", -1 );
9 define( "DB_WRITE", -2 );
10 define( "DB_LAST", -3 );
12 define( "LIST_COMMA", 0 );
13 define( "LIST_AND", 1 );
14 define( "LIST_SET", 2 );
18 #------------------------------------------------------------------------------
20 #------------------------------------------------------------------------------
21 /* private */ var $mLastQuery = "";
22 /* private */ var $mBufferResults = true;
23 /* private */ var $mIgnoreErrors = false;
25 /* private */ var $mServer, $mUser, $mPassword, $mConn, $mDBname;
26 /* private */ var $mOut, $mDebug, $mOpened = false;
28 /* private */ var $mFailFunction;
30 #------------------------------------------------------------------------------
32 #------------------------------------------------------------------------------
34 # These set a variable and return the previous state
36 # Fail function, takes a Database as a parameter
37 # Set to false for default, 1 for ignore errors
38 function setFailFunction( $function ) { return wfSetVar( $this->mFailFunction
, $function ); }
40 # Output page, used for reporting errors
41 # FALSE means discard output
42 function &setOutputPage( &$out ) { $this->mOut
=& $out; }
44 # Boolean, controls output of large amounts of debug information
45 function setDebug( $debug ) { return wfSetVar( $this->mDebug
, $debug ); }
47 # Turns buffering of SQL result sets on (true) or off (false). Default is
48 # "on" and it should not be changed without good reasons.
49 function setBufferResults( $buffer ) { return wfSetVar( $this->mBufferResults
, $buffer ); }
51 # Turns on (false) or off (true) the automatic generation and sending
52 # of a "we're sorry, but there has been a database error" page on
53 # database errors. Default is on (false). When turned off, the
54 # code should use wfLastErrno() and wfLastError() to handle the
55 # situation as appropriate.
56 function setIgnoreErrors( $ignoreErrors ) { return wfSetVar( $this->mIgnoreErrors
, $ignoreErrors ); }
60 function lastQuery() { return $this->mLastQuery
; }
61 function isOpen() { return $this->mOpened
; }
63 #------------------------------------------------------------------------------
65 #------------------------------------------------------------------------------
70 # Can't get a reference if it hasn't been set yet
71 if ( !isset( $wgOut ) ) {
74 $this->mOut
=& $wgOut;
78 /* static */ function newFromParams( $server, $user, $password, $dbName,
79 $failFunction = false, $debug = false, $bufferResults = true, $ignoreErrors = false )
82 $db->mFailFunction
= $failFunction;
83 $db->mIgnoreErrors
= $ignoreErrors;
85 $db->mBufferResults
= $bufferResults;
86 $db->open( $server, $user, $password, $dbName );
90 # Usually aborts on failure
91 # If the failFunction is set to a non-zero integer, returns success
92 function open( $server, $user, $password, $dbName )
94 global $wgEmergencyContact;
97 $this->mServer
= $server;
99 $this->mPassword
= $password;
100 $this->mDBname
= $dbName;
104 @$this->mConn
= mysql_connect( $server, $user, $password );
105 if ( $dbName != "" ) {
106 if ( $this->mConn
!== false ) {
107 $success = @mysql_select_db
( $dbName, $this->mConn
);
109 wfDebug( "Error selecting database \"$dbName\": " . $this->lastError() . "\n" );
112 wfDebug( "DB connection error\n" );
113 wfDebug( "Server: $server, User: $user, Password: " .
114 substr( $password, 0, 3 ) . "...\n" );
119 $success = !!$this->mConn
;
123 $this->reportConnectionError();
126 $this->mOpened
= $success;
130 # Closes a database connection, if it is open
131 # Returns success, true if already closed
134 $this->mOpened
= false;
135 if ( $this->mConn
) {
136 return mysql_close( $this->mConn
);
142 /* private */ function reportConnectionError( $msg = "")
144 if ( $this->mFailFunction
) {
145 if ( !is_int( $this->mFailFunction
) ) {
146 $this->$mFailFunction( $this );
149 wfEmergencyAbort( $this );
153 # Usually aborts on failure
154 # If errors are explicitly ignored, returns success
155 function query( $sql, $fname = "" )
159 if ( $wgProfiling ) {
160 # generalizeSQL will probably cut down the query to reasonable
161 # logging size most of the time. The substr is really just a sanity check.
162 $profName = "query: " . substr( Database
::generalizeSQL( $sql ), 0, 255 );
163 wfProfileIn( $profName );
166 $this->mLastQuery
= $sql;
168 if ( $this->mDebug
) {
169 $sqlx = substr( $sql, 0, 500 );
170 $sqlx = wordwrap(strtr($sqlx,"\t\n"," "));
171 wfDebug( "SQL: $sqlx\n" );
173 if( $this->mBufferResults
) {
174 $ret = mysql_query( $sql, $this->mConn
);
176 $ret = mysql_unbuffered_query( $sql, $this->mConn
);
179 if ( false === $ret ) {
180 $error = mysql_error( $this->mConn
);
181 $errno = mysql_errno( $this->mConn
);
182 if( $this->mIgnoreErrors
) {
183 wfDebug("SQL ERROR (ignored): " . $error . "\n");
185 wfDebug("SQL ERROR: " . $error . "\n");
187 // this calls wfAbruptExit()
188 $this->mOut
->databaseError( $fname, $sql, $error, $errno );
193 if ( $wgProfiling ) {
194 wfProfileOut( $profName );
199 function freeResult( $res ) {
200 if ( !@mysql_free_result
( $res ) ) {
201 wfDebugDieBacktrace( "Unable to free MySQL result\n" );
204 function fetchObject( $res ) {
205 @$row = mysql_fetch_object( $res );
206 # FIXME: HACK HACK HACK HACK debug
207 if( mysql_errno() ) {
208 wfDebugDieBacktrace( "SQL error: " . htmlspecialchars( mysql_error() ) );
213 function fetchRow( $res ) {
214 @$row = mysql_fetch_array( $res );
215 if (mysql_errno() ) {
216 wfDebugDieBacktrace( "SQL error: " . htmlspecialchars( mysql_error() ) );
221 function numRows( $res ) {
222 @$n = mysql_num_rows( $res );
223 if( mysql_errno() ) {
224 wfDebugDieBacktrace( "SQL error: " . htmlspecialchars( mysql_error() ) );
228 function numFields( $res ) { return mysql_num_fields( $res ); }
229 function fieldName( $res, $n ) { return mysql_field_name( $res, $n ); }
230 function insertId() { return mysql_insert_id( $this->mConn
); }
231 function dataSeek( $res, $row ) { return mysql_data_seek( $res, $row ); }
232 function lastErrno() { return mysql_errno(); }
233 function lastError() { return mysql_error(); }
234 function affectedRows() { return mysql_affected_rows( $this->mConn
); }
236 # Simple UPDATE wrapper
237 # Usually aborts on failure
238 # If errors are explicitly ignored, returns success
239 function set( $table, $var, $value, $cond, $fname = "Database::set" )
241 $sql = "UPDATE $table SET $var = '" .
242 wfStrencode( $value ) . "' WHERE ($cond)";
243 return !!$this->query( $sql, DB_WRITE
, $fname );
246 # Simple SELECT wrapper, returns a single field, input must be encoded
247 # Usually aborts on failure
248 # If errors are explicitly ignored, returns FALSE on failure
249 function get( $table, $var, $cond, $fname = "Database::get" )
251 $sql = "SELECT $var FROM $table WHERE ($cond)";
252 $result = $this->query( $sql, DB_READ
, $fname );
255 if ( mysql_num_rows( $result ) > 0 ) {
256 $s = mysql_fetch_object( $result );
258 mysql_free_result( $result );
263 # More complex SELECT wrapper, single row only
264 # Aborts or returns FALSE on error
265 # Takes an array of selected variables, and a condition map, which is ANDed
266 # e.g. getArray( "cur", array( "cur_id" ), array( "cur_namespace" => 0, "cur_title" => "Astronomy" ) )
267 # would return an object where $obj->cur_id is the ID of the Astronomy article
268 function getArray( $table, $vars, $conds, $fname = "Database::getArray" )
270 $vars = implode( ",", $vars );
271 $where = Database
::makeList( $conds, LIST_AND
);
272 $sql = "SELECT $vars FROM $table WHERE $where LIMIT 1";
273 $res = $this->query( $sql, $fname );
274 if ( $res === false ||
!$this->numRows( $res ) ) {
277 $obj = $this->fetchObject( $res );
278 $this->freeResult( $res );
282 # Removes most variables from an SQL query and replaces them with X or N for numbers.
283 # It's only slightly flawed. Don't use for anything important.
284 /* static */ function generalizeSQL( $sql )
286 # This does the same as the regexp below would do, but in such a way
287 # as to avoid crashing php on some large strings.
288 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
290 $sql = str_replace ( "\\\\", "", $sql);
291 $sql = str_replace ( "\\'", "", $sql);
292 $sql = str_replace ( "\\\"", "", $sql);
293 $sql = preg_replace ("/'.*'/s", "'X'", $sql);
294 $sql = preg_replace ('/".*"/s', "'X'", $sql);
296 # All newlines, tabs, etc replaced by single space
297 $sql = preg_replace ( "/\s+/", " ", $sql);
300 $sql = preg_replace ('/-?[0-9]+/s', "N", $sql);
305 # Determines whether a field exists in a table
306 # Usually aborts on failure
307 # If errors are explicitly ignored, returns NULL on failure
308 function fieldExists( $table, $field, $fname = "Database::fieldExists" )
310 $res = $this->query( "DESCRIBE $table", DB_READ
, $fname );
317 while ( $row = $this->fetchObject( $res ) ) {
318 if ( $row->Field
== $field ) {
326 # Determines whether an index exists
327 # Usually aborts on failure
328 # If errors are explicitly ignored, returns NULL on failure
329 function indexExists( $table, $index, $fname = "Database::indexExists" )
331 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
332 # SHOW INDEX should work for 3.x and up:
333 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
334 $sql = "SHOW INDEX FROM $table";
335 $res = $this->query( $sql, DB_READ
, $fname );
342 while ( $row = $this->fetchObject( $res ) ) {
343 if ( $row->Key_name
== $index ) {
351 function tableExists( $table )
353 $old = $this->mIgnoreErrors
;
354 $this->mIgnoreErrors
= true;
355 $res = $this->query( "SELECT 1 FROM $table LIMIT 1" );
356 $this->mIgnoreErrors
= $old;
358 $this->freeResult( $res );
365 function fieldInfo( $table, $field )
367 $res = $this->query( "SELECT * FROM $table LIMIT 1" );
368 $n = mysql_num_fields( $res );
369 for( $i = 0; $i < $n; $i++
) {
370 $meta = mysql_fetch_field( $res, $i );
371 if( $field == $meta->name
) {
378 # INSERT wrapper, inserts an array into a table
379 # Keys are field names, values are values
380 # Usually aborts on failure
381 # If errors are explicitly ignored, returns success
382 function insertArray( $table, $a, $fname = "Database::insertArray" )
384 $sql1 = "INSERT INTO $table (";
385 $sql2 = "VALUES (" . Database
::makeList( $a );
387 foreach ( $a as $field => $value ) {
394 $sql = "$sql1) $sql2)";
395 return !!$this->query( $sql, $fname );
398 # A cross between insertArray and getArray, takes a condition array and a SET array
399 function updateArray( $table, $values, $conds, $fname = "Database::updateArray" )
401 $sql = "UPDATE $table SET " . $this->makeList( $values, LIST_SET
);
402 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
403 $this->query( $sql, $fname );
406 # Makes a wfStrencoded list from an array
407 # $mode: LIST_COMMA - comma separated, no field names
408 # LIST_AND - ANDed WHERE clause (without the WHERE)
409 # LIST_SET - comma separated with field names, like a SET clause
410 /* static */ function makeList( $a, $mode = LIST_COMMA
)
414 foreach ( $a as $field => $value ) {
416 if ( $mode == LIST_AND
) {
424 if ( $mode == LIST_AND ||
$mode == LIST_SET
) {
427 if ( !is_numeric( $value ) ) {
428 $list .= "'" . wfStrencode( $value ) . "'";
436 function selectDB( $db )
438 $this->mDBname
= $db;
439 mysql_select_db( $db, $this->mConn
);
442 function startTimer( $timeout )
446 $tid = mysql_thread_id( $this->mConn
);
447 exec( "php $IP/killthread.php $timeout $tid &>/dev/null &" );
456 #------------------------------------------------------------------------------
458 #------------------------------------------------------------------------------
460 /* Standard fail function, called by default when a connection cannot be established
461 Displays the file cache if possible */
462 function wfEmergencyAbort( &$conn ) {
463 global $wgTitle, $wgUseFileCache, $title, $wgInputEncoding, $wgSiteNotice, $wgOutputEncoding;
465 if( !headers_sent() ) {
466 header( "HTTP/1.0 500 Internal Server Error" );
467 header( "Content-type: text/html; charset=$wgOutputEncoding" );
468 /* Don't cache error pages! They cause no end of trouble... */
469 header( "Cache-control: none" );
470 header( "Pragma: nocache" );
472 $msg = $wgSiteNotice;
473 if($msg == "") $msg = wfMsgNoDB( "noconnect" );
476 if($wgUseFileCache) {
481 $t = Title
::newFromURL( $title );
482 } elseif (@$_REQUEST['search']) {
483 $search = $_REQUEST['search'];
484 echo wfMsgNoDB( "searchdisabled" );
485 echo wfMsgNoDB( "googlesearch", htmlspecialchars( $search ), $wgInputEncoding );
488 $t = Title
::newFromText( wfMsgNoDB( "mainpage" ) );
492 $cache = new CacheManager( $t );
493 if( $cache->isFileCached() ) {
494 $msg = "<p style='color: red'><b>$msg<br />\n" .
495 wfMsgNoDB( "cachederror" ) . "</b></p>\n";
497 $tag = "<div id='article'>";
501 $cache->fetchPageText() );
509 function wfStrencode( $s )
511 return addslashes( $s );
514 # Ideally we'd be using actual time fields in the db
515 function wfTimestamp2Unix( $ts ) {
516 return gmmktime( ( (int)substr( $ts, 8, 2) ),
517 (int)substr( $ts, 10, 2 ), (int)substr( $ts, 12, 2 ),
518 (int)substr( $ts, 4, 2 ), (int)substr( $ts, 6, 2 ),
519 (int)substr( $ts, 0, 4 ) );
522 function wfUnix2Timestamp( $unixtime ) {
523 return gmdate( "YmdHis", $unixtime );
526 function wfTimestampNow() {
528 return gmdate( "YmdHis" );
531 # Sorting hack for MySQL 3, which doesn't use index sorts for DESC
532 function wfInvertTimestamp( $ts ) {
540 function wfLimitResult( $limit, $offset ) {
541 return " LIMIT ".(is_numeric($offset)?
"{$offset},":"")."{$limit} ";