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 );
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 #------------------------------------------------------------------------------
70 /* static */ function newFromParams( $server, $user, $password, $dbName,
71 $failFunction = false, $debug = false, $bufferResults = true, $ignoreErrors = false )
74 $db->mFailFunction
= $failFunction;
75 $db->mIgnoreErrors
= $ignoreErrors;
77 $db->open( $server, $user, $password, $dbName );
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;
88 $this->mServer
= $server;
90 $this->mPassword
= $password;
91 $this->mDBname
= $dbName;
95 @$this->mConn
= mysql_connect( $server, $user, $password );
96 if ( $dbName != "" ) {
97 if ( $this->mConn
!== false ) {
98 $success = @mysql_select_db
( $dbName, $this->mConn
);
100 wfDebug( "Error selecting database \"$dbName\": " . $this->lastError() . "\n" );
103 wfDebug( "DB connect error: " . $this->lastError() . "\n" );
104 wfDebug( "Server: $server, User: $user, Password: " .
105 substr( $password, 0, 3 ) . "...\n" );
114 $this->reportConnectionError();
117 $this->mOpened
= $success;
121 # Closes a database connection, if it is open
122 # Returns success, true if already closed
125 $this->mOpened
= false;
126 if ( $this->mConn
) {
127 return mysql_close( $this->mConn
);
133 /* private */ function reportConnectionError( $msg = "")
135 if ( $this->mFailFunction
) {
136 if ( !is_int( $this->mFailFunction
) ) {
137 $this->$mFailFunction( $this );
140 wfEmergencyAbort( $this );
144 # Usually aborts on failure
145 # If errors are explicitly ignored, returns success
146 function query( $sql, $fname = "" )
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
);
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");
174 wfDebug("SQL ERROR: " . mysql_error( $this->mConn
) . "\n");
176 $this->mOut
->databaseError( $fname ); // calls wfAbruptExit()
181 if ( $wgProfiling ) {
182 wfProfileOut( $profName );
187 function freeResult( $res ) { mysql_free_result( $res ); }
188 function fetchObject( $res ) { return mysql_fetch_object( $res ); }
189 function numRows( $res ) { return mysql_num_rows( $res ); }
190 function numFields( $res ) { return mysql_num_fields( $res ); }
191 function fieldName( $res, $n ) { return mysql_field_name( $res, $n ); }
192 function insertId() { return mysql_insert_id( $this->mConn
); }
193 function dataSeek( $res, $row ) { return mysql_data_seek( $res, $row ); }
194 function lastErrno() { return mysql_errno( $this->mConn
); }
195 function lastError() { return mysql_error( $this->mConn
); }
196 function affectedRows() { return mysql_affected_rows( $this->mConn
); }
198 # Simple UPDATE wrapper
199 # Usually aborts on failure
200 # If errors are explicitly ignored, returns success
201 function set( $table, $var, $value, $cond, $fname = "Database::set" )
203 $sql = "UPDATE $table SET $var = '" .
204 wfStrencode( $value ) . "' WHERE ($cond)";
205 return !!$this->query( $sql, DB_WRITE
, $fname );
208 # Simple SELECT wrapper
209 # Usually aborts on failure
210 # If errors are explicitly ignored, returns FALSE on failure
211 function get( $table, $var, $cond, $fname = "Database::get" )
213 $sql = "SELECT $var FROM $table WHERE ($cond)";
214 $result = $this->query( $sql, DB_READ
, $fname );
217 if ( mysql_num_rows( $result ) > 0 ) {
218 $s = mysql_fetch_object( $result );
220 mysql_free_result( $result );
225 # More complex SELECT wrapper, single row only
226 # Aborts or returns FALSE on error
227 # Takes an array of selected variables, and a condition map, which is ANDed
228 # e.g. getArray( "cur", array( "cur_id" ), array( "cur_namespace" => 0, "cur_title" => "Astronomy" ) )
229 # would return an object where $obj->cur_id is the ID of the Astronomy article
230 function getArray( $table, $vars, $conds, $fname = "Database::getArray" )
232 $vars = implode( ",", $vars );
233 $where = Database
::makeList( $conds, LIST_AND
);
234 $sql = "SELECT $vars FROM $table WHERE $where";
235 $res = $this->query( $sql, $fname );
236 if ( $res === false ||
!$this->numRows( $res ) ) {
239 return $this->fetchObject( $res );
242 # Removes most variables from an SQL query and replaces them with X or N for numbers.
243 # It's only slightly flawed. Don't use for anything important.
244 /* static */ function generalizeSQL( $sql )
246 # This does the same as the regexp below would do, but in such a way
247 # as to avoid crashing php on some large strings.
248 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
250 $sql = str_replace ( "\\\\", "", $sql);
251 $sql = str_replace ( "\\'", "", $sql);
252 $sql = str_replace ( "\\\"", "", $sql);
253 $sql = preg_replace ("/'.*'/s", "'X'", $sql);
254 $sql = preg_replace ('/".*"/s', "'X'", $sql);
256 # All newlines, tabs, etc replaced by single space
257 $sql = preg_replace ( "/\s+/", " ", $sql);
260 $sql = preg_replace ('/-?[0-9]+/s', "N", $sql);
265 # Determines whether a field exists in a table
266 # Usually aborts on failure
267 # If errors are explicitly ignored, returns NULL on failure
268 function fieldExists( $table, $field, $fname = "Database::fieldExists" )
270 $res = $this->query( "DESCRIBE $table", DB_READ
, $fname );
277 while ( $row = $this->fetchObject( $res ) ) {
278 if ( $row->Field
== $field ) {
286 # Determines whether an index exists
287 # Usually aborts on failure
288 # If errors are explicitly ignored, returns NULL on failure
289 function indexExists( $table, $index, $fname = "Database::indexExists" )
291 $sql = "SHOW INDEXES FROM $table";
292 $res = $this->query( $sql, DB_READ
, $fname );
299 while ( $row = $this->fetchObject( $res ) ) {
300 if ( $row->Key_name
== $index ) {
308 function tableExists( $table )
310 $res = mysql_list_tables( $this->mDBname
);
312 echo "** " . $this->lastError() . "\n";
315 for( $i = $this->numRows( $res ) - 1; $i--; $i > 0 ) {
316 if( mysql_tablename( $res, $i ) == $table ) return true;
321 function fieldInfo( $table, $field )
323 $res = $this->query( "SELECT * FROM $table LIMIT 1" );
324 $n = mysql_num_fields( $res );
325 for( $i = 0; $i < $n; $i++
) {
326 $meta = mysql_fetch_field( $res, $i );
327 if( $field == $meta->name
) {
334 # INSERT wrapper, inserts an array into a table
335 # Keys are field names, values are values
336 # Usually aborts on failure
337 # If errors are explicitly ignored, returns success
338 function insertArray( $table, $a, $fname = "Database::insertArray" )
340 $sql1 = "INSERT INTO $table (";
341 $sql2 = "VALUES (" . Database
::makeList( $a );
343 foreach ( $a as $field => $value ) {
350 $sql = "$sql1) $sql2)";
351 return !!$this->query( $sql, $fname );
354 # Makes a wfStrencoded list from an array
355 # $mode: LIST_COMMA - comma separated
356 # LIST_AND - ANDed WHERE clause (without the WHERE)
357 /* static */ function makeList( $a, $mode = LIST_COMMA
)
361 foreach ( $a as $field => $value ) {
363 if ( $mode == LIST_AND
) {
371 if ( $mode == LIST_AND
) {
374 if ( is_string( $value ) ) {
375 $list .= "'" . wfStrencode( $value ) . "'";
383 function selectDB( $db )
385 $this->mDatabase
= $db;
386 mysql_select_db( $db, $this->mConn
);
390 #------------------------------------------------------------------------------
392 #------------------------------------------------------------------------------
394 /* Standard fail function, called by default when a connection cannot be established
395 Displays the file cache if possible */
396 function wfEmergencyAbort( &$conn ) {
397 global $wgTitle, $wgUseFileCache, $title, $wgInputEncoding, $wgSiteNotice, $wgOutputEncoding;
399 header( "Content-type: text/html; charset=$wgOutputEncoding" );
400 $msg = $wgSiteNotice;
401 if($msg == "") $msg = wfMsgNoDB( "noconnect" );
404 if($wgUseFileCache) {
409 $t = Title
::newFromURL( $title );
410 } elseif ($_REQUEST['search']) {
411 $search = $_REQUEST['search'];
412 echo wfMsgNoDB( "searchdisabled", htmlspecialchars( $search ), $wgInputEncoding );
415 $t = Title
::newFromText( wfMsgNoDB( "mainpage" ) );
419 $cache = new CacheManager( $t );
420 if( $cache->isFileCached() ) {
421 $msg = "<p style='color: red'><b>$msg<br>\n" .
422 wfMsgNoDB( "cachederror" ) . "</b></p>\n";
424 $tag = "<div id='article'>";
428 $cache->fetchPageText() );
432 /* Don't cache error pages! They cause no end of trouble... */
433 header( "Cache-control: none" );
434 header( "Pragma: nocache" );
439 function wfStrencode( $s )
441 return addslashes( $s );
444 # Ideally we'd be using actual time fields in the db
445 function wfTimestamp2Unix( $ts ) {
446 return gmmktime( ( (int)substr( $ts, 8, 2) ),
447 (int)substr( $ts, 10, 2 ), (int)substr( $ts, 12, 2 ),
448 (int)substr( $ts, 4, 2 ), (int)substr( $ts, 6, 2 ),
449 (int)substr( $ts, 0, 4 ) );
452 function wfUnix2Timestamp( $unixtime ) {
453 return gmdate( "YmdHis", $unixtime );
456 function wfTimestampNow() {
458 return gmdate( "YmdHis" );
461 # Sorting hack for MySQL 3, which doesn't use index sorts for DESC
462 function wfInvertTimestamp( $ts ) {