3 # This file deals with MySQL interface functions
4 # and query specifics/optimisations
6 require_once( "CacheManager.php" );
8 define( "LIST_COMMA", 0 );
9 define( "LIST_AND", 1 );
10 define( "LIST_SET", 2 );
14 #------------------------------------------------------------------------------
16 #------------------------------------------------------------------------------
17 /* private */ var $mLastQuery = "";
18 /* private */ var $mBufferResults = true;
19 /* private */ var $mIgnoreErrors = false;
21 /* private */ var $mServer, $mUser, $mPassword, $mConn, $mDBname;
22 /* private */ var $mOut, $mDebug, $mOpened = false;
24 /* private */ var $mFailFunction;
26 #------------------------------------------------------------------------------
28 #------------------------------------------------------------------------------
30 # These set a variable and return the previous state
32 # Fail function, takes a Database as a parameter
33 # Set to false for default, 1 for ignore errors
34 function setFailFunction( $function ) { return wfSetVar( $this->mFailFunction
, $function ); }
36 # Output page, used for reporting errors
37 # FALSE means discard output
38 function &setOutputPage( &$out ) { $this->mOut
=& $out; }
40 # Boolean, controls output of large amounts of debug information
41 function setDebug( $debug ) { return wfSetVar( $this->mDebug
, $debug ); }
43 # Turns buffering of SQL result sets on (true) or off (false). Default is
44 # "on" and it should not be changed without good reasons.
45 function setBufferResults( $buffer ) { return wfSetVar( $this->mBufferResults
, $buffer ); }
47 # Turns on (false) or off (true) the automatic generation and sending
48 # of a "we're sorry, but there has been a database error" page on
49 # database errors. Default is on (false). When turned off, the
50 # code should use wfLastErrno() and wfLastError() to handle the
51 # situation as appropriate.
52 function setIgnoreErrors( $ignoreErrors ) { return wfSetVar( $this->mIgnoreErrors
, $ignoreErrors ); }
56 function lastQuery() { return $this->mLastQuery
; }
57 function isOpen() { return $this->mOpened
; }
59 #------------------------------------------------------------------------------
61 #------------------------------------------------------------------------------
66 # Can't get a reference if it hasn't been set yet
67 if ( !isset( $wgOut ) ) {
70 $this->mOut
=& $wgOut;
74 /* static */ function newFromParams( $server, $user, $password, $dbName,
75 $failFunction = false, $debug = false, $bufferResults = true, $ignoreErrors = false )
78 $db->mFailFunction
= $failFunction;
79 $db->mIgnoreErrors
= $ignoreErrors;
81 $db->mBufferResults
= $bufferResults;
82 $db->open( $server, $user, $password, $dbName );
86 # Usually aborts on failure
87 # If the failFunction is set to a non-zero integer, returns success
88 function open( $server, $user, $password, $dbName )
90 global $wgEmergencyContact;
92 # Test for missing mysql.so
93 # Otherwise we get a suppressed fatal error, which is very hard to track down
94 if ( !function_exists( 'mysql_connect' ) ) {
95 die( "MySQL functions missing, have you compiled PHP with the --with-mysql option?\n" );
99 $this->mServer
= $server;
100 $this->mUser
= $user;
101 $this->mPassword
= $password;
102 $this->mDBname
= $dbName;
106 @$this->mConn
= mysql_connect( $server, $user, $password );
107 if ( $dbName != "" ) {
108 if ( $this->mConn
!== false ) {
109 $success = @mysql_select_db
( $dbName, $this->mConn
);
111 wfDebug( "Error selecting database \"$dbName\": " . $this->lastError() . "\n" );
114 wfDebug( "DB connection error\n" );
115 wfDebug( "Server: $server, User: $user, Password: " .
116 substr( $password, 0, 3 ) . "...\n" );
121 $success = !!$this->mConn
;
125 $this->reportConnectionError();
128 $this->mOpened
= $success;
132 # Closes a database connection, if it is open
133 # Returns success, true if already closed
136 $this->mOpened
= false;
137 if ( $this->mConn
) {
138 return mysql_close( $this->mConn
);
144 /* private */ function reportConnectionError( $msg = "")
146 if ( $this->mFailFunction
) {
147 if ( !is_int( $this->mFailFunction
) ) {
148 $ff = $this->mFailFunction
;
149 $ff( $this, mysql_error() );
152 wfEmergencyAbort( $this, mysql_error() );
156 # Usually aborts on failure
157 # If errors are explicitly ignored, returns success
158 function query( $sql, $fname = "" )
160 global $wgProfiling, $wgCommandLineMode;
162 if ( $wgProfiling ) {
163 # generalizeSQL will probably cut down the query to reasonable
164 # logging size most of the time. The substr is really just a sanity check.
165 $profName = "query: " . substr( Database
::generalizeSQL( $sql ), 0, 255 );
166 wfProfileIn( $profName );
169 $this->mLastQuery
= $sql;
171 if ( $this->mDebug
) {
172 $sqlx = substr( $sql, 0, 500 );
173 $sqlx = wordwrap(strtr($sqlx,"\t\n"," "));
174 wfDebug( "SQL: $sqlx\n" );
176 if( $this->mBufferResults
) {
177 $ret = mysql_query( $sql, $this->mConn
);
179 $ret = mysql_unbuffered_query( $sql, $this->mConn
);
182 if ( false === $ret ) {
183 $error = mysql_error( $this->mConn
);
184 $errno = mysql_errno( $this->mConn
);
185 if( $this->mIgnoreErrors
) {
186 wfDebug("SQL ERROR (ignored): " . $error . "\n");
188 $sql1line = str_replace( "\n", "\\n", $sql );
189 wfLogDBError("$errno\t$error\t$sql1line\n");
190 wfDebug("SQL ERROR: " . $error . "\n");
191 if ( $wgCommandLineMode ) {
192 wfDebugDieBacktrace( "A database error has occurred\n" .
194 "Function: $fname\n" .
195 "Error: $errno $error\n"
197 } elseif ( $this->mOut
) {
198 // this calls wfAbruptExit()
199 $this->mOut
->databaseError( $fname, $sql, $error, $errno );
204 if ( $wgProfiling ) {
205 wfProfileOut( $profName );
210 function freeResult( $res ) {
211 if ( !@mysql_free_result
( $res ) ) {
212 wfDebugDieBacktrace( "Unable to free MySQL result\n" );
215 function fetchObject( $res ) {
216 @$row = mysql_fetch_object( $res );
217 # FIXME: HACK HACK HACK HACK debug
218 if( mysql_errno() ) {
219 wfDebugDieBacktrace( "SQL error: " . htmlspecialchars( mysql_error() ) );
224 function fetchRow( $res ) {
225 @$row = mysql_fetch_array( $res );
226 if (mysql_errno() ) {
227 wfDebugDieBacktrace( "SQL error: " . htmlspecialchars( mysql_error() ) );
232 function numRows( $res ) {
233 @$n = mysql_num_rows( $res );
234 if( mysql_errno() ) {
235 wfDebugDieBacktrace( "SQL error: " . htmlspecialchars( mysql_error() ) );
239 function numFields( $res ) { return mysql_num_fields( $res ); }
240 function fieldName( $res, $n ) { return mysql_field_name( $res, $n ); }
241 function insertId() { return mysql_insert_id( $this->mConn
); }
242 function dataSeek( $res, $row ) { return mysql_data_seek( $res, $row ); }
243 function lastErrno() { return mysql_errno(); }
244 function lastError() { return mysql_error(); }
245 function affectedRows() { return mysql_affected_rows( $this->mConn
); }
247 # Simple UPDATE wrapper
248 # Usually aborts on failure
249 # If errors are explicitly ignored, returns success
250 function set( $table, $var, $value, $cond, $fname = "Database::set" )
252 $sql = "UPDATE $table SET $var = '" .
253 wfStrencode( $value ) . "' WHERE ($cond)";
254 return !!$this->query( $sql, DB_WRITE
, $fname );
257 # Simple SELECT wrapper, returns a single field, input must be encoded
258 # Usually aborts on failure
259 # If errors are explicitly ignored, returns FALSE on failure
260 function get( $table, $var, $cond, $fname = "Database::get" )
262 $sql = "SELECT $var FROM $table WHERE ($cond)";
263 $result = $this->query( $sql, DB_READ
, $fname );
266 if ( mysql_num_rows( $result ) > 0 ) {
267 $s = mysql_fetch_object( $result );
269 mysql_free_result( $result );
274 # More complex SELECT wrapper, single row only
275 # Aborts or returns FALSE on error
276 # Takes an array of selected variables, and a condition map, which is ANDed
277 # e.g. getArray( "cur", array( "cur_id" ), array( "cur_namespace" => 0, "cur_title" => "Astronomy" ) )
278 # would return an object where $obj->cur_id is the ID of the Astronomy article
279 function getArray( $table, $vars, $conds, $fname = "Database::getArray" )
281 $vars = implode( ",", $vars );
282 if ( $conds !== false ) {
283 $where = Database
::makeList( $conds, LIST_AND
);
284 $sql = "SELECT $vars FROM $table WHERE $where LIMIT 1";
286 $sql = "SELECT $vars FROM $table LIMIT 1";
288 $res = $this->query( $sql, $fname );
289 if ( $res === false ||
!$this->numRows( $res ) ) {
292 $obj = $this->fetchObject( $res );
293 $this->freeResult( $res );
297 # Removes most variables from an SQL query and replaces them with X or N for numbers.
298 # It's only slightly flawed. Don't use for anything important.
299 /* static */ function generalizeSQL( $sql )
301 # This does the same as the regexp below would do, but in such a way
302 # as to avoid crashing php on some large strings.
303 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
305 $sql = str_replace ( "\\\\", "", $sql);
306 $sql = str_replace ( "\\'", "", $sql);
307 $sql = str_replace ( "\\\"", "", $sql);
308 $sql = preg_replace ("/'.*'/s", "'X'", $sql);
309 $sql = preg_replace ('/".*"/s', "'X'", $sql);
311 # All newlines, tabs, etc replaced by single space
312 $sql = preg_replace ( "/\s+/", " ", $sql);
315 $sql = preg_replace ('/-?[0-9]+/s', "N", $sql);
320 # Determines whether a field exists in a table
321 # Usually aborts on failure
322 # If errors are explicitly ignored, returns NULL on failure
323 function fieldExists( $table, $field, $fname = "Database::fieldExists" )
325 $res = $this->query( "DESCRIBE $table", DB_READ
, $fname );
332 while ( $row = $this->fetchObject( $res ) ) {
333 if ( $row->Field
== $field ) {
341 # Determines whether an index exists
342 # Usually aborts on failure
343 # If errors are explicitly ignored, returns NULL on failure
344 function indexExists( $table, $index, $fname = "Database::indexExists" )
346 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
347 # SHOW INDEX should work for 3.x and up:
348 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
349 $sql = "SHOW INDEX FROM $table";
350 $res = $this->query( $sql, DB_READ
, $fname );
357 while ( $row = $this->fetchObject( $res ) ) {
358 if ( $row->Key_name
== $index ) {
366 function tableExists( $table )
368 $old = $this->mIgnoreErrors
;
369 $this->mIgnoreErrors
= true;
370 $res = $this->query( "SELECT 1 FROM $table LIMIT 1" );
371 $this->mIgnoreErrors
= $old;
373 $this->freeResult( $res );
380 function fieldInfo( $table, $field )
382 $res = $this->query( "SELECT * FROM $table LIMIT 1" );
383 $n = mysql_num_fields( $res );
384 for( $i = 0; $i < $n; $i++
) {
385 $meta = mysql_fetch_field( $res, $i );
386 if( $field == $meta->name
) {
393 # INSERT wrapper, inserts an array into a table
394 # Keys are field names, values are values
395 # Usually aborts on failure
396 # If errors are explicitly ignored, returns success
397 function insertArray( $table, $a, $fname = "Database::insertArray" )
399 $sql1 = "INSERT INTO $table (";
400 $sql2 = "VALUES (" . Database
::makeList( $a );
402 foreach ( $a as $field => $value ) {
409 $sql = "$sql1) $sql2)";
410 return !!$this->query( $sql, $fname );
413 # A cross between insertArray and getArray, takes a condition array and a SET array
414 function updateArray( $table, $values, $conds, $fname = "Database::updateArray" )
416 $sql = "UPDATE $table SET " . $this->makeList( $values, LIST_SET
);
417 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
418 $this->query( $sql, $fname );
421 # Makes a wfStrencoded list from an array
422 # $mode: LIST_COMMA - comma separated, no field names
423 # LIST_AND - ANDed WHERE clause (without the WHERE)
424 # LIST_SET - comma separated with field names, like a SET clause
425 /* static */ function makeList( $a, $mode = LIST_COMMA
)
429 foreach ( $a as $field => $value ) {
431 if ( $mode == LIST_AND
) {
439 if ( $mode == LIST_AND ||
$mode == LIST_SET
) {
442 if ( !is_numeric( $value ) ) {
443 $list .= "'" . wfStrencode( $value ) . "'";
451 function selectDB( $db )
453 $this->mDBname
= $db;
454 mysql_select_db( $db, $this->mConn
);
457 function startTimer( $timeout )
461 $tid = mysql_thread_id( $this->mConn
);
462 exec( "php $IP/killthread.php $timeout $tid &>/dev/null &" );
470 #------------------------------------------------------------------------------
472 #------------------------------------------------------------------------------
474 /* Standard fail function, called by default when a connection cannot be established
475 Displays the file cache if possible */
476 function wfEmergencyAbort( &$conn, $error ) {
477 global $wgTitle, $wgUseFileCache, $title, $wgInputEncoding, $wgSiteNotice, $wgOutputEncoding;
479 if( !headers_sent() ) {
480 header( "HTTP/1.0 500 Internal Server Error" );
481 header( "Content-type: text/html; charset=$wgOutputEncoding" );
482 /* Don't cache error pages! They cause no end of trouble... */
483 header( "Cache-control: none" );
484 header( "Pragma: nocache" );
486 $msg = $wgSiteNotice;
487 if($msg == "") $msg = wfMsgNoDB( "noconnect", $error );
490 if($wgUseFileCache) {
495 $t = Title
::newFromURL( $title );
496 } elseif (@$_REQUEST['search']) {
497 $search = $_REQUEST['search'];
498 echo wfMsgNoDB( "searchdisabled" );
499 echo wfMsgNoDB( "googlesearch", htmlspecialchars( $search ), $wgInputEncoding );
502 $t = Title
::newFromText( wfMsgNoDB( "mainpage" ) );
506 $cache = new CacheManager( $t );
507 if( $cache->isFileCached() ) {
508 $msg = "<p style='color: red'><b>$msg<br />\n" .
509 wfMsgNoDB( "cachederror" ) . "</b></p>\n";
511 $tag = "<div id='article'>";
515 $cache->fetchPageText() );
523 function wfStrencode( $s )
525 return addslashes( $s );
528 function wfLimitResult( $limit, $offset ) {
529 return " LIMIT ".(is_numeric($offset)?
"{$offset},":"")."{$limit} ";