dont require FulltextStoplist on mysql4 databases (saves some memory)
[lhc/web/wiklou.git] / includes / Database.php
1 <?php
2 require_once( "CacheManager.php" );
3
4 define( "DB_READ", -1 );
5 define( "DB_WRITE", -2 );
6 define( "DB_LAST", -3 );
7
8 define( "LIST_COMMA", 0 );
9 define( "LIST_AND", 1 );
10 define( "LIST_SET", 2 );
11
12 class Database {
13
14 #------------------------------------------------------------------------------
15 # Variables
16 #------------------------------------------------------------------------------
17 /* private */ var $mLastQuery = "";
18 /* private */ var $mBufferResults = true;
19 /* private */ var $mIgnoreErrors = false;
20
21 /* private */ var $mServer, $mUser, $mPassword, $mConn, $mDBname;
22 /* private */ var $mOut, $mDebug, $mOpened = false;
23
24 /* private */ var $mFailFunction;
25
26 #------------------------------------------------------------------------------
27 # Accessors
28 #------------------------------------------------------------------------------
29 # Set functions
30 # These set a variable and return the previous state
31
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 ); }
35
36 # Output page, used for reporting errors
37 # FALSE means discard output
38 function &setOutputPage( &$out ) { return wfSetRef( $this->mOut, $out ); }
39
40 # Boolean, controls output of large amounts of debug information
41 function setDebug( $debug ) { return wfSetVar( $this->mDebug, $debug ); }
42
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 ); }
46
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 ); }
53
54 # Get functions
55
56 function lastQuery() { return $this->mLastQuery; }
57 function isOpen() { return $this->mOpened; }
58
59 #------------------------------------------------------------------------------
60 # Other functions
61 #------------------------------------------------------------------------------
62
63 function Database()
64 {
65 global $wgOut;
66 # Can't get a reference if it hasn't been set yet
67 if ( !isset( $wgOut ) ) {
68 $wgOut = NULL;
69 }
70 $this->mOut =& $wgOut;
71
72 }
73
74 /* static */ function newFromParams( $server, $user, $password, $dbName,
75 $failFunction = false, $debug = false, $bufferResults = true, $ignoreErrors = false )
76 {
77 $db = new Database;
78 $db->mFailFunction = $failFunction;
79 $db->mIgnoreErrors = $ignoreErrors;
80 $db->mDebug = $debug;
81 $db->mBufferResults = $bufferResults;
82 $db->open( $server, $user, $password, $dbName );
83 return $db;
84 }
85
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 )
89 {
90 global $wgEmergencyContact;
91
92 $this->close();
93 $this->mServer = $server;
94 $this->mUser = $user;
95 $this->mPassword = $password;
96 $this->mDBname = $dbName;
97
98 $success = false;
99
100 @$this->mConn = mysql_connect( $server, $user, $password );
101 if ( $dbName != "" ) {
102 if ( $this->mConn !== false ) {
103 $success = @mysql_select_db( $dbName, $this->mConn );
104 if ( !$success ) {
105 wfDebug( "Error selecting database \"$dbName\": " . $this->lastError() . "\n" );
106 }
107 } else {
108 wfDebug( "DB connection error\n" );
109 wfDebug( "Server: $server, User: $user, Password: " .
110 substr( $password, 0, 3 ) . "...\n" );
111 $success = false;
112 }
113 } else {
114 # Delay USE query
115 $success = !!$this->mConn;
116 }
117
118 if ( !$success ) {
119 $this->reportConnectionError();
120 $this->close();
121 }
122 $this->mOpened = $success;
123 return $success;
124 }
125
126 # Closes a database connection, if it is open
127 # Returns success, true if already closed
128 function close()
129 {
130 $this->mOpened = false;
131 if ( $this->mConn ) {
132 return mysql_close( $this->mConn );
133 } else {
134 return true;
135 }
136 }
137
138 /* private */ function reportConnectionError( $msg = "")
139 {
140 if ( $this->mFailFunction ) {
141 if ( !is_int( $this->mFailFunction ) ) {
142 $this->$mFailFunction( $this );
143 }
144 } else {
145 wfEmergencyAbort( $this );
146 }
147 }
148
149 # Usually aborts on failure
150 # If errors are explicitly ignored, returns success
151 function query( $sql, $fname = "" )
152 {
153 global $wgProfiling;
154
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 );
160 }
161
162 $this->mLastQuery = $sql;
163
164 if ( $this->mDebug ) {
165 $sqlx = substr( $sql, 0, 500 );
166 $sqlx = wordwrap(strtr($sqlx,"\t\n"," "));
167 wfDebug( "SQL: $sqlx\n" );
168 }
169 if( $this->mBufferResults ) {
170 $ret = mysql_query( $sql, $this->mConn );
171 } else {
172 $ret = mysql_unbuffered_query( $sql, $this->mConn );
173 }
174
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");
180 } else {
181 wfDebug("SQL ERROR: " . $error . "\n");
182 if ( $this->mOut ) {
183 // this calls wfAbruptExit()
184 $this->mOut->databaseError( $fname, $sql, $error, $errno );
185 }
186 }
187 }
188
189 if ( $wgProfiling ) {
190 wfProfileOut( $profName );
191 }
192 return $ret;
193 }
194
195 function freeResult( $res ) {
196 if ( !@mysql_free_result( $res ) ) {
197 wfDebugDieBacktrace( "Unable to free MySQL result\n" );
198 }
199 }
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() ) );
205 }
206 return $row;
207 }
208 function numRows( $res ) {
209 @$n = mysql_num_rows( $res );
210 if( mysql_errno() ) {
211 wfDebugDieBacktrace( "SQL error: " . htmlspecialchars( mysql_error() ) );
212 }
213 return $n;
214 }
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 ); }
222
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" )
227 {
228 $sql = "UPDATE $table SET $var = '" .
229 wfStrencode( $value ) . "' WHERE ($cond)";
230 return !!$this->query( $sql, DB_WRITE, $fname );
231 }
232
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" )
237 {
238 $sql = "SELECT $var FROM $table WHERE ($cond)";
239 $result = $this->query( $sql, DB_READ, $fname );
240
241 $ret = "";
242 if ( mysql_num_rows( $result ) > 0 ) {
243 $s = mysql_fetch_object( $result );
244 $ret = $s->$var;
245 mysql_free_result( $result );
246 }
247 return $ret;
248 }
249
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" )
256 {
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 ) ) {
262 return false;
263 }
264 $obj = $this->fetchObject( $res );
265 $this->freeResult( $res );
266 return $obj;
267 }
268
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 )
272 {
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);
276
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);
282
283 # All newlines, tabs, etc replaced by single space
284 $sql = preg_replace ( "/\s+/", " ", $sql);
285
286 # All numbers => N
287 $sql = preg_replace ('/-?[0-9]+/s', "N", $sql);
288
289 return $sql;
290 }
291
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" )
296 {
297 $res = $this->query( "DESCRIBE $table", DB_READ, $fname );
298 if ( !$res ) {
299 return NULL;
300 }
301
302 $found = false;
303
304 while ( $row = $this->fetchObject( $res ) ) {
305 if ( $row->Field == $field ) {
306 $found = true;
307 break;
308 }
309 }
310 return $found;
311 }
312
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" )
317 {
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 );
323 if ( !$res ) {
324 return NULL;
325 }
326
327 $found = false;
328
329 while ( $row = $this->fetchObject( $res ) ) {
330 if ( $row->Key_name == $index ) {
331 $found = true;
332 break;
333 }
334 }
335 return $found;
336 }
337
338 function tableExists( $table )
339 {
340 $old = $this->mIgnoreErrors;
341 $this->mIgnoreErrors = true;
342 $res = $this->query( "SELECT 1 FROM $table LIMIT 1" );
343 $this->mIgnoreErrors = $old;
344 if( $res ) {
345 $this->freeResult( $res );
346 return true;
347 } else {
348 return false;
349 }
350 }
351
352 function fieldInfo( $table, $field )
353 {
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 ) {
359 return $meta;
360 }
361 }
362 return false;
363 }
364
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" )
370 {
371 $sql1 = "INSERT INTO $table (";
372 $sql2 = "VALUES (" . Database::makeList( $a );
373 $first = true;
374 foreach ( $a as $field => $value ) {
375 if ( !$first ) {
376 $sql1 .= ",";
377 }
378 $first = false;
379 $sql1 .= $field;
380 }
381 $sql = "$sql1) $sql2)";
382 return !!$this->query( $sql, $fname );
383 }
384
385 # A cross between insertArray and getArray, takes a condition array and a SET array
386 function updateArray( $table, $values, $conds, $fname = "Database::updateArray" )
387 {
388 $sql = "UPDATE $table SET " . $this->makeList( $values, LIST_SET );
389 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND );
390 $this->query( $sql, $fname );
391 }
392
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 )
398 {
399 $first = true;
400 $list = "";
401 foreach ( $a as $field => $value ) {
402 if ( !$first ) {
403 if ( $mode == LIST_AND ) {
404 $list .= " AND ";
405 } else {
406 $list .= ",";
407 }
408 } else {
409 $first = false;
410 }
411 if ( $mode == LIST_AND || $mode == LIST_SET ) {
412 $list .= "$field=";
413 }
414 if ( !is_numeric( $value ) ) {
415 $list .= "'" . wfStrencode( $value ) . "'";
416 } else {
417 $list .= $value;
418 }
419 }
420 return $list;
421 }
422
423 function selectDB( $db )
424 {
425 $this->mDBname = $db;
426 mysql_select_db( $db, $this->mConn );
427 }
428
429 function startTimer( $timeout )
430 {
431 global $IP;
432
433 $tid = mysql_thread_id( $this->mConn );
434 exec( "php $IP/killthread.php $timeout $tid &>/dev/null &" );
435 }
436
437 function stopTimer()
438 {
439 }
440
441 }
442
443 #------------------------------------------------------------------------------
444 # Global functions
445 #------------------------------------------------------------------------------
446
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;
451
452 header( "Content-type: text/html; charset=$wgOutputEncoding" );
453 $msg = $wgSiteNotice;
454 if($msg == "") $msg = wfMsgNoDB( "noconnect" );
455 $text = $msg;
456
457 if($wgUseFileCache) {
458 if($wgTitle) {
459 $t =& $wgTitle;
460 } else {
461 if($title) {
462 $t = Title::newFromURL( $title );
463 } elseif (@$_REQUEST['search']) {
464 $search = $_REQUEST['search'];
465 echo wfMsgNoDB( "searchdisabled" );
466 echo wfMsgNoDB( "googlesearch", htmlspecialchars( $search ), $wgInputEncoding );
467 wfAbruptExit();
468 } else {
469 $t = Title::newFromText( wfMsgNoDB( "mainpage" ) );
470 }
471 }
472
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";
477
478 $tag = "<div id='article'>";
479 $text = str_replace(
480 $tag,
481 $tag . $msg,
482 $cache->fetchPageText() );
483 }
484 }
485
486 /* Don't cache error pages! They cause no end of trouble... */
487 header( "Cache-control: none" );
488 header( "Pragma: nocache" );
489 echo $text;
490 wfAbruptExit();
491 }
492
493 function wfStrencode( $s )
494 {
495 return addslashes( $s );
496 }
497
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 ) );
504 }
505
506 function wfUnix2Timestamp( $unixtime ) {
507 return gmdate( "YmdHis", $unixtime );
508 }
509
510 function wfTimestampNow() {
511 # return NOW
512 return gmdate( "YmdHis" );
513 }
514
515 # Sorting hack for MySQL 3, which doesn't use index sorts for DESC
516 function wfInvertTimestamp( $ts ) {
517 return strtr(
518 $ts,
519 "0123456789",
520 "9876543210"
521 );
522 }
523 ?>