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 );
11 #------------------------------------------------------------------------------
13 #------------------------------------------------------------------------------
14 /* private */ var $mLastQuery = "";
15 /* private */ var $mBufferResults = true;
16 /* private */ var $mIgnoreErrors = false;
18 /* private */ var $mServer, $mUser, $mPassword, $mConn, $mDBname;
19 /* private */ var $mOut, $mDebug;
21 /* private */ var $mFailFunction;
23 #------------------------------------------------------------------------------
25 #------------------------------------------------------------------------------
27 # These set a variable and return the previous state
29 # Fail function, takes a Database as a parameter
30 # Set to false for default, 1 for ignore errors
31 function setFailFunction( $function ) { return wfSetVar( $this->mFailFunction
, $function ); }
33 # Output page, used for reporting errors
34 # FALSE means discard output
35 function &setOutputPage( &$out ) { return wfSetRef( $this->mOut
, $out ); }
37 # Boolean, controls output of large amounts of debug information
38 function setDebug( $debug ) { return wfSetVar( $this->mDebug
, $debug ); }
40 # Turns buffering of SQL result sets on (true) or off (false). Default is
41 # "on" and it should not be changed without good reasons.
42 function setBufferResults( $buffer ) { return wfSetVar( $this->mBufferResults
, $buffer ); }
44 # Turns on (false) or off (true) the automatic generation and sending
45 # of a "we're sorry, but there has been a database error" page on
46 # database errors. Default is on (false). When turned off, the
47 # code should use wfLastErrno() and wfLastError() to handle the
48 # situation as appropriate.
49 function setIgnoreErrors( $ignoreErrors ) { return wfSetVar( $this->mIgnoreErrors
, $ignoreErrors ); }
53 function lastQuery() { return $this->mLastQuery
; }
55 #------------------------------------------------------------------------------
57 #------------------------------------------------------------------------------
66 /* static */ function newFromParams( $server, $user, $password, $dbName,
67 $failFunction = false, $debug = false, $bufferResults = true, $ignoreErrors = false )
70 $db->mFailFunction
= $failFunction;
71 $db->mIgnoreErrors
= $ignoreErrors;
73 $db->open( $server, $user, $password, $dbName );
77 # Usually aborts on failure
78 # If the failFunction is set to a non-zero integer, returns success
79 function open( $server, $user, $password, $dbName )
81 global $wgEmergencyContact;
84 $this->mServer
= $server;
86 $this->mPassword
= $password;
87 $this->mDbName
= $dbName;
91 @$this->mConn
= mysql_connect( $server, $user, $password );
92 if ( $this->mConn
!== false ) {
93 $success = @mysql_select_db
( $dbName, $this->mConn
);
95 wfDebug( "Error selecting database \"$dbName\": " . $this->lastError() . "\n" );
98 wfDebug( "DB connect error: " . $this->lastError() . "\n" );
99 wfDebug( "Server: $server, User: $user, Password: " .
100 substr( $password, 0, 3 ) . "...\n" );
105 $this->reportConnectionError();
111 # Closes a database connection, if it is open
112 # Returns success, true if already closed
115 if ( $this->mConn
) {
116 return mysql_close( $this->mConn
);
122 /* private */ function reportConnectionError( $msg = "")
124 if ( $this->mFailFunction
) {
125 if ( !is_int( $this->mFailFunction
) ) {
126 $this->$mFailFunction( $this );
129 wfEmergencyAbort( $this );
133 # Usually aborts on failure
134 # If errors are explicitly ignored, returns success
135 function query( $sql, $db, $fname = "" )
139 if ( $wgProfiling ) {
140 # generalizeSQL will probably cut down the query to reasonable
141 # logging size most of the time. The substr is really just a sanity check.
142 $profName = "query: " . substr( Database
::generalizeSQL( $sql ), 0, 255 );
143 wfProfileIn( $profName );
146 $this->mLastQuery
= $sql;
148 if ( $this->mDebug
) {
149 $sqlx = substr( $sql, 0, 500 );
150 $sqlx = wordwrap(strtr($sqlx,"\t\n"," "));
151 wfDebug( "SQL: $sqlx\n" );
153 if( $this->mBufferResults
) {
154 $ret = mysql_query( $sql, $this->mConn
);
156 $ret = mysql_unbuffered_query( $sql, $this->mConn
);
159 if ( false === $ret ) {
160 if( $this->mIgnoreErrors
) {
161 wfDebug("SQL ERROR (ignored): " . mysql_error( $this->mConn
) . "\n");
163 wfDebug("SQL ERROR: " . mysql_error( $this->mConn
) . "\n");
165 $this->mOut
->databaseError( $fname ); // calls wfAbruptExit()
170 if ( $wgProfiling ) {
171 wfProfileOut( $profName );
176 function freeResult( $res ) { mysql_free_result( $res ); }
177 function fetchObject( $res ) { return mysql_fetch_object( $res ); }
178 function numRows( $res ) { return mysql_num_rows( $res ); }
179 function numFields( $res ) { return mysql_num_fields( $res ); }
180 function fieldName( $res, $n ) { return mysql_field_name( $res, $n ); }
181 function insertId() { return mysql_insert_id( $this->mConn
); }
182 function dataSeek( $res, $row ) { return mysql_data_seek( $res, $row ); }
183 function lastErrno() { return mysql_errno( $this->mConn
); }
184 function lastError() { return mysql_error( $this->mConn
); }
185 function affectedRows() { return mysql_affected_rows( $this->mConn
); }
187 # Simple UPDATE wrapper
188 # Usually aborts on failure
189 # If errors are explicitly ignored, returns success
190 function set( $table, $var, $value, $cond, $fname = "Database::set" )
192 $sql = "UPDATE $table SET $var = '" .
193 wfStrencode( $value ) . "' WHERE ($cond)";
194 return !!$this->query( $sql, DB_WRITE
, $fname );
197 # Simple SELECT wrapper
198 # Usually aborts on failure
199 # If errors are explicitly ignored, returns FALSE on failure
200 function get( $table, $var, $cond, $fname = "Database::get" )
202 $sql = "SELECT $var FROM $table WHERE ($cond)";
203 $result = $this->query( $sql, DB_READ
, $fname );
206 if ( mysql_num_rows( $result ) > 0 ) {
207 $s = mysql_fetch_object( $result );
209 mysql_free_result( $result );
214 # Removes most variables from an SQL query and replaces them with X or N for numbers.
215 # It's only slightly flawed. Don't use for anything important.
216 /* static */ function generalizeSQL( $sql )
218 # This does the same as the regexp below would do, but in such a way
219 # as to avoid crashing php on some large strings.
220 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
222 $sql = str_replace ( "\\\\", "", $sql);
223 $sql = str_replace ( "\\'", "", $sql);
224 $sql = str_replace ( "\\\"", "", $sql);
225 $sql = preg_replace ("/'.*'/s", "'X'", $sql);
226 $sql = preg_replace ('/".*"/s', "'X'", $sql);
228 # All newlines, tabs, etc replaced by single space
229 $sql = preg_replace ( "/\s+/", " ", $sql);
232 $sql = preg_replace ('/-?[0-9]+/s', "N", $sql);
237 # Determines whether a field exists in a table
238 # Usually aborts on failure
239 # If errors are explicitly ignored, returns NULL on failure
240 function fieldExists( $table, $field, $fname = "Database::fieldExists" )
242 $res = $this->query( "DESCRIBE $table", DB_READ
, $fname );
249 while ( $row = $this->fetchObject( $res ) ) {
250 if ( $row->Field
== $field ) {
258 # Determines whether an index exists
259 # Usually aborts on failure
260 # If errors are explicitly ignored, returns NULL on failure
261 function indexExists( $table, $index, $fname = "Database::indexExists" )
263 $sql = "SHOW INDEXES FROM $table";
264 $res = $this->query( $sql, DB_READ
, $fname );
271 while ( $row = $this->fetchObject( $res ) ) {
272 if ( $row->Key_name
== $index ) {
280 # INSERT wrapper, inserts an array into a table
281 # Keys are field names, values are values
282 # Usually aborts on failure
283 # If errors are explicitly ignored, returns success
284 function insertArray( $table, $a, $fname = "Database::insertArray" )
286 $sql1 = "INSERT INTO $table (";
289 foreach ( $a as $field => $value ) {
296 if ( is_string( $value ) ) {
297 $sql2 .= "'" . wfStrencode( $value ) . "'";
302 $sql = "$sql1) $sql2)";
303 return !!$this->query( $sql, DB_WRITE
, $fname );
307 #------------------------------------------------------------------------------
309 #------------------------------------------------------------------------------
311 /* Standard fail function, called by default when a connection cannot be established
312 Displays the file cache if possible */
313 function wfEmergencyAbort( &$conn ) {
314 global $wgTitle, $wgUseFileCache, $title, $wgInputEncoding, $wgOutputEncoding;
316 header( "Content-type: text/html; charset=$wgOutputEncoding" );
317 if($msg == "") $msg = wfMsgNoDB( "noconnect" );
320 if($wgUseFileCache) {
325 $t = Title
::newFromURL( $title );
326 } elseif ($_REQUEST['search']) {
327 $search = $_REQUEST['search'];
328 echo wfMsgNoDB( "searchdisabled", htmlspecialchars( $search ), $wgInputEncoding );
331 $t = Title
::newFromText( wfMsgNoDB( "mainpage" ) );
335 $cache = new CacheManager( $t );
336 if( $cache->isFileCached() ) {
337 $msg = "<p style='color: red'><b>$msg<br>\n" .
338 wfMsgNoDB( "cachederror" ) . "</b></p>\n";
340 $tag = "<div id='article'>";
344 $cache->fetchPageText() );
348 /* Don't cache error pages! They cause no end of trouble... */
349 header( "Cache-control: none" );
350 header( "Pragma: nocache" );
355 function wfStrencode( $s )
357 return addslashes( $s );
360 # Ideally we'd be using actual time fields in the db
361 function wfTimestamp2Unix( $ts ) {
362 return gmmktime( ( (int)substr( $ts, 8, 2) ),
363 (int)substr( $ts, 10, 2 ), (int)substr( $ts, 12, 2 ),
364 (int)substr( $ts, 4, 2 ), (int)substr( $ts, 6, 2 ),
365 (int)substr( $ts, 0, 4 ) );
368 function wfUnix2Timestamp( $unixtime ) {
369 return gmdate( "YmdHis", $unixtime );
372 function wfTimestampNow() {
374 return gmdate( "YmdHis" );
377 # Sorting hack for MySQL 3, which doesn't use index sorts for DESC
378 function wfInvertTimestamp( $ts ) {