fixed a couple of minor bugs
[mediawiki.git] / includes / Database.php
blob8acd3d75111130fc6d073f2118e1688835d51a2d
1 <?php
2 include_once( "FulltextStoplist.php" );
3 include_once( "CacheManager.php" );
5 define( "DB_READ", -1 );
6 define( "DB_WRITE", -2 );
7 define( "DB_LAST", -3 );
9 define( "LIST_COMMA", 0 );
10 define( "LIST_AND", 1 );
12 class Database {
14 #------------------------------------------------------------------------------
15 # Variables
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 #------------------------------------------------------------------------------
27 # Accessors
28 #------------------------------------------------------------------------------
29 # Set functions
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 ); }
54 # Get functions
56 function lastQuery() { return $this->mLastQuery; }
57 function isOpen() { return $this->mOpened; }
59 #------------------------------------------------------------------------------
60 # Other functions
61 #------------------------------------------------------------------------------
63 function Database()
65 global $wgOut;
66 $this->mOut = $wgOut;
70 /* static */ function newFromParams( $server, $user, $password, $dbName,
71 $failFunction = false, $debug = false, $bufferResults = true, $ignoreErrors = false )
73 $db = new Database;
74 $db->mFailFunction = $failFunction;
75 $db->mIgnoreErrors = $ignoreErrors;
76 $db->mDebug = $debug;
77 $db->open( $server, $user, $password, $dbName );
78 return $db;
81 # Usually aborts on failure
82 # If the failFunction is set to a non-zero integer, returns success
83 function open( $server, $user, $password, $dbName )
85 global $wgEmergencyContact;
87 $this->close();
88 $this->mServer = $server;
89 $this->mUser = $user;
90 $this->mPassword = $password;
91 $this->mDBname = $dbName;
93 $success = false;
95 @$this->mConn = mysql_connect( $server, $user, $password );
96 if ( $dbName != "" ) {
97 if ( $this->mConn !== false ) {
98 $success = @mysql_select_db( $dbName, $this->mConn );
99 if ( !$success ) {
100 wfDebug( "Error selecting database \"$dbName\": " . $this->lastError() . "\n" );
102 } else {
103 wfDebug( "DB connect error: " . $this->lastError() . "\n" );
104 wfDebug( "Server: $server, User: $user, Password: " .
105 substr( $password, 0, 3 ) . "...\n" );
106 $success = false;
108 } else {
109 # Delay USE query
110 $success = !!$this->mConn;
113 if ( !$success ) {
114 $this->reportConnectionError();
115 $this->close();
117 $this->mOpened = $success;
118 return $success;
121 # Closes a database connection, if it is open
122 # Returns success, true if already closed
123 function close()
125 $this->mOpened = false;
126 if ( $this->mConn ) {
127 return mysql_close( $this->mConn );
128 } else {
129 return true;
133 /* private */ function reportConnectionError( $msg = "")
135 if ( $this->mFailFunction ) {
136 if ( !is_int( $this->mFailFunction ) ) {
137 $this->$mFailFunction( $this );
139 } else {
140 wfEmergencyAbort( $this );
144 # Usually aborts on failure
145 # If errors are explicitly ignored, returns success
146 function query( $sql, $fname = "" )
148 global $wgProfiling;
150 if ( $wgProfiling ) {
151 # generalizeSQL will probably cut down the query to reasonable
152 # logging size most of the time. The substr is really just a sanity check.
153 $profName = "query: " . substr( Database::generalizeSQL( $sql ), 0, 255 );
154 wfProfileIn( $profName );
157 $this->mLastQuery = $sql;
159 if ( $this->mDebug ) {
160 $sqlx = substr( $sql, 0, 500 );
161 $sqlx = wordwrap(strtr($sqlx,"\t\n"," "));
162 wfDebug( "SQL: $sqlx\n" );
164 if( $this->mBufferResults ) {
165 $ret = mysql_query( $sql, $this->mConn );
166 } else {
167 $ret = mysql_unbuffered_query( $sql, $this->mConn );
170 if ( false === $ret ) {
171 if( $this->mIgnoreErrors ) {
172 wfDebug("SQL ERROR (ignored): " . mysql_error( $this->mConn ) . "\n");
173 } else {
174 wfDebug("SQL ERROR: " . mysql_error( $this->mConn ) . "\n");
175 if ( $this->mOut ) {
176 // this calls wfAbruptExit()
177 $this->mOut->databaseError( $fname, $this );
182 if ( $wgProfiling ) {
183 wfProfileOut( $profName );
185 return $ret;
188 function freeResult( $res ) { mysql_free_result( $res ); }
189 function fetchObject( $res ) { return mysql_fetch_object( $res ); }
190 function numRows( $res ) { return mysql_num_rows( $res ); }
191 function numFields( $res ) { return mysql_num_fields( $res ); }
192 function fieldName( $res, $n ) { return mysql_field_name( $res, $n ); }
193 function insertId() { return mysql_insert_id( $this->mConn ); }
194 function dataSeek( $res, $row ) { return mysql_data_seek( $res, $row ); }
195 function lastErrno() { return mysql_errno( $this->mConn ); }
196 function lastError() { return mysql_error( $this->mConn ); }
197 function affectedRows() { return mysql_affected_rows( $this->mConn ); }
199 # Simple UPDATE wrapper
200 # Usually aborts on failure
201 # If errors are explicitly ignored, returns success
202 function set( $table, $var, $value, $cond, $fname = "Database::set" )
204 $sql = "UPDATE $table SET $var = '" .
205 wfStrencode( $value ) . "' WHERE ($cond)";
206 return !!$this->query( $sql, DB_WRITE, $fname );
209 # Simple SELECT wrapper
210 # Usually aborts on failure
211 # If errors are explicitly ignored, returns FALSE on failure
212 function get( $table, $var, $cond, $fname = "Database::get" )
214 $sql = "SELECT $var FROM $table WHERE ($cond)";
215 $result = $this->query( $sql, DB_READ, $fname );
217 $ret = "";
218 if ( mysql_num_rows( $result ) > 0 ) {
219 $s = mysql_fetch_object( $result );
220 $ret = $s->$var;
221 mysql_free_result( $result );
223 return $ret;
226 # More complex SELECT wrapper, single row only
227 # Aborts or returns FALSE on error
228 # Takes an array of selected variables, and a condition map, which is ANDed
229 # e.g. getArray( "cur", array( "cur_id" ), array( "cur_namespace" => 0, "cur_title" => "Astronomy" ) )
230 # would return an object where $obj->cur_id is the ID of the Astronomy article
231 function getArray( $table, $vars, $conds, $fname = "Database::getArray" )
233 $vars = implode( ",", $vars );
234 $where = Database::makeList( $conds, LIST_AND );
235 $sql = "SELECT $vars FROM $table WHERE $where";
236 $res = $this->query( $sql, $fname );
237 if ( $res === false || !$this->numRows( $res ) ) {
238 return false;
240 $obj = $this->fetchObject( $res );
241 $this->freeResult( $res );
242 return $obj;
245 # Removes most variables from an SQL query and replaces them with X or N for numbers.
246 # It's only slightly flawed. Don't use for anything important.
247 /* static */ function generalizeSQL( $sql )
249 # This does the same as the regexp below would do, but in such a way
250 # as to avoid crashing php on some large strings.
251 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
253 $sql = str_replace ( "\\\\", "", $sql);
254 $sql = str_replace ( "\\'", "", $sql);
255 $sql = str_replace ( "\\\"", "", $sql);
256 $sql = preg_replace ("/'.*'/s", "'X'", $sql);
257 $sql = preg_replace ('/".*"/s', "'X'", $sql);
259 # All newlines, tabs, etc replaced by single space
260 $sql = preg_replace ( "/\s+/", " ", $sql);
262 # All numbers => N
263 $sql = preg_replace ('/-?[0-9]+/s', "N", $sql);
265 return $sql;
268 # Determines whether a field exists in a table
269 # Usually aborts on failure
270 # If errors are explicitly ignored, returns NULL on failure
271 function fieldExists( $table, $field, $fname = "Database::fieldExists" )
273 $res = $this->query( "DESCRIBE $table", DB_READ, $fname );
274 if ( !$res ) {
275 return NULL;
278 $found = false;
280 while ( $row = $this->fetchObject( $res ) ) {
281 if ( $row->Field == $field ) {
282 $found = true;
283 break;
286 return $found;
289 # Determines whether an index exists
290 # Usually aborts on failure
291 # If errors are explicitly ignored, returns NULL on failure
292 function indexExists( $table, $index, $fname = "Database::indexExists" )
294 $sql = "SHOW INDEXES FROM $table";
295 $res = $this->query( $sql, DB_READ, $fname );
296 if ( !$res ) {
297 return NULL;
300 $found = false;
302 while ( $row = $this->fetchObject( $res ) ) {
303 if ( $row->Key_name == $index ) {
304 $found = true;
305 break;
308 return $found;
311 function tableExists( $table )
313 $res = mysql_list_tables( $this->mDBname );
314 if( !$res ) {
315 echo "** " . $this->lastError() . "\n";
316 return false;
318 $nTables = $this->numRows( $res );
319 for( $i = 0; $i < $nTables; $i++ ) {
320 if( mysql_tablename( $res, $i ) == $table ) return true;
322 return false;
325 function fieldInfo( $table, $field )
327 $res = $this->query( "SELECT * FROM $table LIMIT 1" );
328 $n = mysql_num_fields( $res );
329 for( $i = 0; $i < $n; $i++ ) {
330 $meta = mysql_fetch_field( $res, $i );
331 if( $field == $meta->name ) {
332 return $meta;
335 return false;
338 # INSERT wrapper, inserts an array into a table
339 # Keys are field names, values are values
340 # Usually aborts on failure
341 # If errors are explicitly ignored, returns success
342 function insertArray( $table, $a, $fname = "Database::insertArray" )
344 $sql1 = "INSERT INTO $table (";
345 $sql2 = "VALUES (" . Database::makeList( $a );
346 $first = true;
347 foreach ( $a as $field => $value ) {
348 if ( !$first ) {
349 $sql1 .= ",";
351 $first = false;
352 $sql1 .= $field;
354 $sql = "$sql1) $sql2)";
355 return !!$this->query( $sql, $fname );
358 # Makes a wfStrencoded list from an array
359 # $mode: LIST_COMMA - comma separated
360 # LIST_AND - ANDed WHERE clause (without the WHERE)
361 /* static */ function makeList( $a, $mode = LIST_COMMA)
363 $first = true;
364 $list = "";
365 foreach ( $a as $field => $value ) {
366 if ( !$first ) {
367 if ( $mode == LIST_AND ) {
368 $list .= " AND ";
369 } else {
370 $list .= ",";
372 } else {
373 $first = false;
375 if ( $mode == LIST_AND ) {
376 $list .= "$field=";
378 if ( is_string( $value ) ) {
379 $list .= "'" . wfStrencode( $value ) . "'";
380 } else {
381 $list .= $value;
384 return $list;
387 function selectDB( $db )
389 $this->mDBname = $db;
390 mysql_select_db( $db, $this->mConn );
393 function startTimer( $timeout )
395 global $IP;
397 $tid = mysql_thread_id( $this->mConn );
398 exec( "php $IP/killthread.php $timeout $tid &>/dev/null &" );
401 function stopTimer()
407 #------------------------------------------------------------------------------
408 # Global functions
409 #------------------------------------------------------------------------------
411 /* Standard fail function, called by default when a connection cannot be established
412 Displays the file cache if possible */
413 function wfEmergencyAbort( &$conn ) {
414 global $wgTitle, $wgUseFileCache, $title, $wgInputEncoding, $wgSiteNotice, $wgOutputEncoding;
416 header( "Content-type: text/html; charset=$wgOutputEncoding" );
417 $msg = $wgSiteNotice;
418 if($msg == "") $msg = wfMsgNoDB( "noconnect" );
419 $text = $msg;
421 if($wgUseFileCache) {
422 if($wgTitle) {
423 $t =& $wgTitle;
424 } else {
425 if($title) {
426 $t = Title::newFromURL( $title );
427 } elseif ($_REQUEST['search']) {
428 $search = $_REQUEST['search'];
429 echo wfMsgNoDB( "searchdisabled" );
430 echo wfMsgNoDB( "googlesearch", htmlspecialchars( $search ), $wgInputEncoding );
431 wfAbruptExit();
432 } else {
433 $t = Title::newFromText( wfMsgNoDB( "mainpage" ) );
437 $cache = new CacheManager( $t );
438 if( $cache->isFileCached() ) {
439 $msg = "<p style='color: red'><b>$msg<br>\n" .
440 wfMsgNoDB( "cachederror" ) . "</b></p>\n";
442 $tag = "<div id='article'>";
443 $text = str_replace(
444 $tag,
445 $tag . $msg,
446 $cache->fetchPageText() );
450 /* Don't cache error pages! They cause no end of trouble... */
451 header( "Cache-control: none" );
452 header( "Pragma: nocache" );
453 echo $text;
454 wfAbruptExit();
457 function wfStrencode( $s )
459 return addslashes( $s );
462 # Ideally we'd be using actual time fields in the db
463 function wfTimestamp2Unix( $ts ) {
464 return gmmktime( ( (int)substr( $ts, 8, 2) ),
465 (int)substr( $ts, 10, 2 ), (int)substr( $ts, 12, 2 ),
466 (int)substr( $ts, 4, 2 ), (int)substr( $ts, 6, 2 ),
467 (int)substr( $ts, 0, 4 ) );
470 function wfUnix2Timestamp( $unixtime ) {
471 return gmdate( "YmdHis", $unixtime );
474 function wfTimestampNow() {
475 # return NOW
476 return gmdate( "YmdHis" );
479 # Sorting hack for MySQL 3, which doesn't use index sorts for DESC
480 function wfInvertTimestamp( $ts ) {
481 return strtr(
482 $ts,
483 "0123456789",
484 "9876543210"