2 require_once( "CacheManager.php" );
4 define( "DB_READ", -1 );
5 define( "DB_WRITE", -2 );
6 define( "DB_LAST", -3 );
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 ) { return wfSetRef( $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;
93 $this->mServer
= $server;
95 $this->mPassword
= $password;
96 $this->mDBname
= $dbName;
100 @$this->mConn
= mysql_connect( $server, $user, $password );
101 if ( $dbName != "" ) {
102 if ( $this->mConn
!== false ) {
103 $success = @mysql_select_db
( $dbName, $this->mConn
);
105 wfDebug( "Error selecting database \"$dbName\": " . $this->lastError() . "\n" );
108 wfDebug( "DB connection error\n" );
109 wfDebug( "Server: $server, User: $user, Password: " .
110 substr( $password, 0, 3 ) . "...\n" );
115 $success = !!$this->mConn
;
119 $this->reportConnectionError();
122 $this->mOpened
= $success;
126 # Closes a database connection, if it is open
127 # Returns success, true if already closed
130 $this->mOpened
= false;
131 if ( $this->mConn
) {
132 return mysql_close( $this->mConn
);
138 /* private */ function reportConnectionError( $msg = "")
140 if ( $this->mFailFunction
) {
141 if ( !is_int( $this->mFailFunction
) ) {
142 $this->$mFailFunction( $this );
145 wfEmergencyAbort( $this );
149 # Usually aborts on failure
150 # If errors are explicitly ignored, returns success
151 function query( $sql, $fname = "" )
155 if ( $wgProfiling ) {
156 # generalizeSQL will probably cut down the query to reasonable
157 # logging size most of the time. The substr is really just a sanity check.
158 $profName = "query: " . substr( Database
::generalizeSQL( $sql ), 0, 255 );
159 wfProfileIn( $profName );
162 $this->mLastQuery
= $sql;
164 if ( $this->mDebug
) {
165 $sqlx = substr( $sql, 0, 500 );
166 $sqlx = wordwrap(strtr($sqlx,"\t\n"," "));
167 wfDebug( "SQL: $sqlx\n" );
169 if( $this->mBufferResults
) {
170 $ret = mysql_query( $sql, $this->mConn
);
172 $ret = mysql_unbuffered_query( $sql, $this->mConn
);
175 if ( false === $ret ) {
176 $error = mysql_error( $this->mConn
);
177 $errno = mysql_errno( $this->mConn
);
178 if( $this->mIgnoreErrors
) {
179 wfDebug("SQL ERROR (ignored): " . $error . "\n");
181 wfDebug("SQL ERROR: " . $error . "\n");
183 // this calls wfAbruptExit()
184 $this->mOut
->databaseError( $fname, $sql, $error, $errno );
189 if ( $wgProfiling ) {
190 wfProfileOut( $profName );
195 function freeResult( $res ) {
196 if ( !@mysql_free_result
( $res ) ) {
197 wfDebugDieBacktrace( "Unable to free MySQL result\n" );
200 function fetchObject( $res ) {
201 @$row = mysql_fetch_object( $res );
202 # FIXME: HACK HACK HACK HACK debug
203 if( mysql_errno() ) {
204 wfDebugDieBacktrace( "SQL error: " . htmlspecialchars( mysql_error() ) );
208 function numRows( $res ) {
209 @$n = mysql_num_rows( $res );
210 if( mysql_errno() ) {
211 wfDebugDieBacktrace( "SQL error: " . htmlspecialchars( mysql_error() ) );
215 function numFields( $res ) { return mysql_num_fields( $res ); }
216 function fieldName( $res, $n ) { return mysql_field_name( $res, $n ); }
217 function insertId() { return mysql_insert_id( $this->mConn
); }
218 function dataSeek( $res, $row ) { return mysql_data_seek( $res, $row ); }
219 function lastErrno() { return mysql_errno(); }
220 function lastError() { return mysql_error(); }
221 function affectedRows() { return mysql_affected_rows( $this->mConn
); }
223 # Simple UPDATE wrapper
224 # Usually aborts on failure
225 # If errors are explicitly ignored, returns success
226 function set( $table, $var, $value, $cond, $fname = "Database::set" )
228 $sql = "UPDATE $table SET $var = '" .
229 wfStrencode( $value ) . "' WHERE ($cond)";
230 return !!$this->query( $sql, DB_WRITE
, $fname );
233 # Simple SELECT wrapper, returns a single field, input must be encoded
234 # Usually aborts on failure
235 # If errors are explicitly ignored, returns FALSE on failure
236 function get( $table, $var, $cond, $fname = "Database::get" )
238 $sql = "SELECT $var FROM $table WHERE ($cond)";
239 $result = $this->query( $sql, DB_READ
, $fname );
242 if ( mysql_num_rows( $result ) > 0 ) {
243 $s = mysql_fetch_object( $result );
245 mysql_free_result( $result );
250 # More complex SELECT wrapper, single row only
251 # Aborts or returns FALSE on error
252 # Takes an array of selected variables, and a condition map, which is ANDed
253 # e.g. getArray( "cur", array( "cur_id" ), array( "cur_namespace" => 0, "cur_title" => "Astronomy" ) )
254 # would return an object where $obj->cur_id is the ID of the Astronomy article
255 function getArray( $table, $vars, $conds, $fname = "Database::getArray" )
257 $vars = implode( ",", $vars );
258 $where = Database
::makeList( $conds, LIST_AND
);
259 $sql = "SELECT $vars FROM $table WHERE $where LIMIT 1";
260 $res = $this->query( $sql, $fname );
261 if ( $res === false ||
!$this->numRows( $res ) ) {
264 $obj = $this->fetchObject( $res );
265 $this->freeResult( $res );
269 # Removes most variables from an SQL query and replaces them with X or N for numbers.
270 # It's only slightly flawed. Don't use for anything important.
271 /* static */ function generalizeSQL( $sql )
273 # This does the same as the regexp below would do, but in such a way
274 # as to avoid crashing php on some large strings.
275 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
277 $sql = str_replace ( "\\\\", "", $sql);
278 $sql = str_replace ( "\\'", "", $sql);
279 $sql = str_replace ( "\\\"", "", $sql);
280 $sql = preg_replace ("/'.*'/s", "'X'", $sql);
281 $sql = preg_replace ('/".*"/s', "'X'", $sql);
283 # All newlines, tabs, etc replaced by single space
284 $sql = preg_replace ( "/\s+/", " ", $sql);
287 $sql = preg_replace ('/-?[0-9]+/s', "N", $sql);
292 # Determines whether a field exists in a table
293 # Usually aborts on failure
294 # If errors are explicitly ignored, returns NULL on failure
295 function fieldExists( $table, $field, $fname = "Database::fieldExists" )
297 $res = $this->query( "DESCRIBE $table", DB_READ
, $fname );
304 while ( $row = $this->fetchObject( $res ) ) {
305 if ( $row->Field
== $field ) {
313 # Determines whether an index exists
314 # Usually aborts on failure
315 # If errors are explicitly ignored, returns NULL on failure
316 function indexExists( $table, $index, $fname = "Database::indexExists" )
318 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
319 # SHOW INDEX should work for 3.x and up:
320 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
321 $sql = "SHOW INDEX FROM $table";
322 $res = $this->query( $sql, DB_READ
, $fname );
329 while ( $row = $this->fetchObject( $res ) ) {
330 if ( $row->Key_name
== $index ) {
338 function tableExists( $table )
340 $old = $this->mIgnoreErrors
;
341 $this->mIgnoreErrors
= true;
342 $res = $this->query( "SELECT 1 FROM $table LIMIT 1" );
343 $this->mIgnoreErrors
= $old;
345 $this->freeResult( $res );
352 function fieldInfo( $table, $field )
354 $res = $this->query( "SELECT * FROM $table LIMIT 1" );
355 $n = mysql_num_fields( $res );
356 for( $i = 0; $i < $n; $i++
) {
357 $meta = mysql_fetch_field( $res, $i );
358 if( $field == $meta->name
) {
365 # INSERT wrapper, inserts an array into a table
366 # Keys are field names, values are values
367 # Usually aborts on failure
368 # If errors are explicitly ignored, returns success
369 function insertArray( $table, $a, $fname = "Database::insertArray" )
371 $sql1 = "INSERT INTO $table (";
372 $sql2 = "VALUES (" . Database
::makeList( $a );
374 foreach ( $a as $field => $value ) {
381 $sql = "$sql1) $sql2)";
382 return !!$this->query( $sql, $fname );
385 # A cross between insertArray and getArray, takes a condition array and a SET array
386 function updateArray( $table, $values, $conds, $fname = "Database::updateArray" )
388 $sql = "UPDATE $table SET " . $this->makeList( $values, LIST_SET
);
389 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
390 $this->query( $sql, $fname );
393 # Makes a wfStrencoded list from an array
394 # $mode: LIST_COMMA - comma separated, no field names
395 # LIST_AND - ANDed WHERE clause (without the WHERE)
396 # LIST_SET - comma separated with field names, like a SET clause
397 /* static */ function makeList( $a, $mode = LIST_COMMA
)
401 foreach ( $a as $field => $value ) {
403 if ( $mode == LIST_AND
) {
411 if ( $mode == LIST_AND ||
$mode == LIST_SET
) {
414 if ( !is_numeric( $value ) ) {
415 $list .= "'" . wfStrencode( $value ) . "'";
423 function selectDB( $db )
425 $this->mDBname
= $db;
426 mysql_select_db( $db, $this->mConn
);
429 function startTimer( $timeout )
433 $tid = mysql_thread_id( $this->mConn
);
434 exec( "php $IP/killthread.php $timeout $tid &>/dev/null &" );
443 #------------------------------------------------------------------------------
445 #------------------------------------------------------------------------------
447 /* Standard fail function, called by default when a connection cannot be established
448 Displays the file cache if possible */
449 function wfEmergencyAbort( &$conn ) {
450 global $wgTitle, $wgUseFileCache, $title, $wgInputEncoding, $wgSiteNotice, $wgOutputEncoding;
452 header( "Content-type: text/html; charset=$wgOutputEncoding" );
453 $msg = $wgSiteNotice;
454 if($msg == "") $msg = wfMsgNoDB( "noconnect" );
457 if($wgUseFileCache) {
462 $t = Title
::newFromURL( $title );
463 } elseif (@$_REQUEST['search']) {
464 $search = $_REQUEST['search'];
465 echo wfMsgNoDB( "searchdisabled" );
466 echo wfMsgNoDB( "googlesearch", htmlspecialchars( $search ), $wgInputEncoding );
469 $t = Title
::newFromText( wfMsgNoDB( "mainpage" ) );
473 $cache = new CacheManager( $t );
474 if( $cache->isFileCached() ) {
475 $msg = "<p style='color: red'><b>$msg<br />\n" .
476 wfMsgNoDB( "cachederror" ) . "</b></p>\n";
478 $tag = "<div id='article'>";
482 $cache->fetchPageText() );
486 /* Don't cache error pages! They cause no end of trouble... */
487 header( "Cache-control: none" );
488 header( "Pragma: nocache" );
493 function wfStrencode( $s )
495 return addslashes( $s );
498 # Ideally we'd be using actual time fields in the db
499 function wfTimestamp2Unix( $ts ) {
500 return gmmktime( ( (int)substr( $ts, 8, 2) ),
501 (int)substr( $ts, 10, 2 ), (int)substr( $ts, 12, 2 ),
502 (int)substr( $ts, 4, 2 ), (int)substr( $ts, 6, 2 ),
503 (int)substr( $ts, 0, 4 ) );
506 function wfUnix2Timestamp( $unixtime ) {
507 return gmdate( "YmdHis", $unixtime );
510 function wfTimestampNow() {
512 return gmdate( "YmdHis" );
515 # Sorting hack for MySQL 3, which doesn't use index sorts for DESC
516 function wfInvertTimestamp( $ts ) {