add Last-Modified header
[lhc/web/wiklou.git] / includes / Database.php
1 <?php
2 # $Id$
3 # This file deals with MySQL interface functions
4 # and query specifics/optimisations
5 #
6 require_once( "CacheManager.php" );
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 ) { $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 # Test for missing mysql.so
93 # Otherwise we get a suppressed fatal error, which is very hard to track down
94 if ( !function_exists( 'mysql_connect' ) ) {
95 die( "MySQL functions missing, have you compiled PHP with the --with-mysql option?\n" );
96 }
97
98 $this->close();
99 $this->mServer = $server;
100 $this->mUser = $user;
101 $this->mPassword = $password;
102 $this->mDBname = $dbName;
103
104 $success = false;
105
106 @$this->mConn = mysql_connect( $server, $user, $password );
107 if ( $dbName != "" ) {
108 if ( $this->mConn !== false ) {
109 $success = @mysql_select_db( $dbName, $this->mConn );
110 if ( !$success ) {
111 wfDebug( "Error selecting database \"$dbName\": " . $this->lastError() . "\n" );
112 }
113 } else {
114 wfDebug( "DB connection error\n" );
115 wfDebug( "Server: $server, User: $user, Password: " .
116 substr( $password, 0, 3 ) . "...\n" );
117 $success = false;
118 }
119 } else {
120 # Delay USE query
121 $success = !!$this->mConn;
122 }
123
124 if ( !$success ) {
125 $this->reportConnectionError();
126 $this->close();
127 }
128 $this->mOpened = $success;
129 return $success;
130 }
131
132 # Closes a database connection, if it is open
133 # Returns success, true if already closed
134 function close()
135 {
136 $this->mOpened = false;
137 if ( $this->mConn ) {
138 return mysql_close( $this->mConn );
139 } else {
140 return true;
141 }
142 }
143
144 /* private */ function reportConnectionError( $msg = "")
145 {
146 if ( $this->mFailFunction ) {
147 if ( !is_int( $this->mFailFunction ) ) {
148 $ff = $this->mFailFunction;
149 $ff( $this, mysql_error() );
150 }
151 } else {
152 wfEmergencyAbort( $this, mysql_error() );
153 }
154 }
155
156 # Usually aborts on failure
157 # If errors are explicitly ignored, returns success
158 function query( $sql, $fname = "" )
159 {
160 global $wgProfiling, $wgCommandLineMode;
161
162 if ( $wgProfiling ) {
163 # generalizeSQL will probably cut down the query to reasonable
164 # logging size most of the time. The substr is really just a sanity check.
165 $profName = "query: " . substr( Database::generalizeSQL( $sql ), 0, 255 );
166 wfProfileIn( $profName );
167 }
168
169 $this->mLastQuery = $sql;
170
171 if ( $this->mDebug ) {
172 $sqlx = substr( $sql, 0, 500 );
173 $sqlx = wordwrap(strtr($sqlx,"\t\n"," "));
174 wfDebug( "SQL: $sqlx\n" );
175 }
176 if( $this->mBufferResults ) {
177 $ret = mysql_query( $sql, $this->mConn );
178 } else {
179 $ret = mysql_unbuffered_query( $sql, $this->mConn );
180 }
181
182 if ( false === $ret ) {
183 $error = mysql_error( $this->mConn );
184 $errno = mysql_errno( $this->mConn );
185 if( $this->mIgnoreErrors ) {
186 wfDebug("SQL ERROR (ignored): " . $error . "\n");
187 } else {
188 $sql1line = str_replace( "\n", "\\n", $sql );
189 wfLogDBError("$errno\t$error\t$sql1line\n");
190 wfDebug("SQL ERROR: " . $error . "\n");
191 if ( $wgCommandLineMode ) {
192 wfDebugDieBacktrace( "A database error has occurred\n" .
193 "Query: $sql\n" .
194 "Function: $fname\n" .
195 "Error: $errno $error\n"
196 );
197 } elseif ( $this->mOut ) {
198 // this calls wfAbruptExit()
199 $this->mOut->databaseError( $fname, $sql, $error, $errno );
200 }
201 }
202 }
203
204 if ( $wgProfiling ) {
205 wfProfileOut( $profName );
206 }
207 return $ret;
208 }
209
210 function freeResult( $res ) {
211 if ( !@mysql_free_result( $res ) ) {
212 wfDebugDieBacktrace( "Unable to free MySQL result\n" );
213 }
214 }
215 function fetchObject( $res ) {
216 @$row = mysql_fetch_object( $res );
217 # FIXME: HACK HACK HACK HACK debug
218 if( mysql_errno() ) {
219 wfDebugDieBacktrace( "SQL error: " . htmlspecialchars( mysql_error() ) );
220 }
221 return $row;
222 }
223
224 function fetchRow( $res ) {
225 @$row = mysql_fetch_array( $res );
226 if (mysql_errno() ) {
227 wfDebugDieBacktrace( "SQL error: " . htmlspecialchars( mysql_error() ) );
228 }
229 return $row;
230 }
231
232 function numRows( $res ) {
233 @$n = mysql_num_rows( $res );
234 if( mysql_errno() ) {
235 wfDebugDieBacktrace( "SQL error: " . htmlspecialchars( mysql_error() ) );
236 }
237 return $n;
238 }
239 function numFields( $res ) { return mysql_num_fields( $res ); }
240 function fieldName( $res, $n ) { return mysql_field_name( $res, $n ); }
241 function insertId() { return mysql_insert_id( $this->mConn ); }
242 function dataSeek( $res, $row ) { return mysql_data_seek( $res, $row ); }
243 function lastErrno() { return mysql_errno(); }
244 function lastError() { return mysql_error(); }
245 function affectedRows() { return mysql_affected_rows( $this->mConn ); }
246
247 # Simple UPDATE wrapper
248 # Usually aborts on failure
249 # If errors are explicitly ignored, returns success
250 function set( $table, $var, $value, $cond, $fname = "Database::set" )
251 {
252 $sql = "UPDATE $table SET $var = '" .
253 wfStrencode( $value ) . "' WHERE ($cond)";
254 return !!$this->query( $sql, DB_WRITE, $fname );
255 }
256
257 # Simple SELECT wrapper, returns a single field, input must be encoded
258 # Usually aborts on failure
259 # If errors are explicitly ignored, returns FALSE on failure
260 function get( $table, $var, $cond, $fname = "Database::get" )
261 {
262 $sql = "SELECT $var FROM $table WHERE ($cond)";
263 $result = $this->query( $sql, DB_READ, $fname );
264
265 $ret = "";
266 if ( mysql_num_rows( $result ) > 0 ) {
267 $s = mysql_fetch_object( $result );
268 $ret = $s->$var;
269 mysql_free_result( $result );
270 }
271 return $ret;
272 }
273
274 # More complex SELECT wrapper, single row only
275 # Aborts or returns FALSE on error
276 # Takes an array of selected variables, and a condition map, which is ANDed
277 # e.g. getArray( "cur", array( "cur_id" ), array( "cur_namespace" => 0, "cur_title" => "Astronomy" ) )
278 # would return an object where $obj->cur_id is the ID of the Astronomy article
279 function getArray( $table, $vars, $conds, $fname = "Database::getArray" )
280 {
281 $vars = implode( ",", $vars );
282 if ( $conds !== false ) {
283 $where = Database::makeList( $conds, LIST_AND );
284 $sql = "SELECT $vars FROM $table WHERE $where LIMIT 1";
285 } else {
286 $sql = "SELECT $vars FROM $table LIMIT 1";
287 }
288 $res = $this->query( $sql, $fname );
289 if ( $res === false || !$this->numRows( $res ) ) {
290 return false;
291 }
292 $obj = $this->fetchObject( $res );
293 $this->freeResult( $res );
294 return $obj;
295 }
296
297 # Removes most variables from an SQL query and replaces them with X or N for numbers.
298 # It's only slightly flawed. Don't use for anything important.
299 /* static */ function generalizeSQL( $sql )
300 {
301 # This does the same as the regexp below would do, but in such a way
302 # as to avoid crashing php on some large strings.
303 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
304
305 $sql = str_replace ( "\\\\", "", $sql);
306 $sql = str_replace ( "\\'", "", $sql);
307 $sql = str_replace ( "\\\"", "", $sql);
308 $sql = preg_replace ("/'.*'/s", "'X'", $sql);
309 $sql = preg_replace ('/".*"/s', "'X'", $sql);
310
311 # All newlines, tabs, etc replaced by single space
312 $sql = preg_replace ( "/\s+/", " ", $sql);
313
314 # All numbers => N
315 $sql = preg_replace ('/-?[0-9]+/s', "N", $sql);
316
317 return $sql;
318 }
319
320 # Determines whether a field exists in a table
321 # Usually aborts on failure
322 # If errors are explicitly ignored, returns NULL on failure
323 function fieldExists( $table, $field, $fname = "Database::fieldExists" )
324 {
325 $res = $this->query( "DESCRIBE $table", DB_READ, $fname );
326 if ( !$res ) {
327 return NULL;
328 }
329
330 $found = false;
331
332 while ( $row = $this->fetchObject( $res ) ) {
333 if ( $row->Field == $field ) {
334 $found = true;
335 break;
336 }
337 }
338 return $found;
339 }
340
341 # Determines whether an index exists
342 # Usually aborts on failure
343 # If errors are explicitly ignored, returns NULL on failure
344 function indexExists( $table, $index, $fname = "Database::indexExists" )
345 {
346 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
347 # SHOW INDEX should work for 3.x and up:
348 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
349 $sql = "SHOW INDEX FROM $table";
350 $res = $this->query( $sql, DB_READ, $fname );
351 if ( !$res ) {
352 return NULL;
353 }
354
355 $found = false;
356
357 while ( $row = $this->fetchObject( $res ) ) {
358 if ( $row->Key_name == $index ) {
359 $found = true;
360 break;
361 }
362 }
363 return $found;
364 }
365
366 function tableExists( $table )
367 {
368 $old = $this->mIgnoreErrors;
369 $this->mIgnoreErrors = true;
370 $res = $this->query( "SELECT 1 FROM $table LIMIT 1" );
371 $this->mIgnoreErrors = $old;
372 if( $res ) {
373 $this->freeResult( $res );
374 return true;
375 } else {
376 return false;
377 }
378 }
379
380 function fieldInfo( $table, $field )
381 {
382 $res = $this->query( "SELECT * FROM $table LIMIT 1" );
383 $n = mysql_num_fields( $res );
384 for( $i = 0; $i < $n; $i++ ) {
385 $meta = mysql_fetch_field( $res, $i );
386 if( $field == $meta->name ) {
387 return $meta;
388 }
389 }
390 return false;
391 }
392
393 # INSERT wrapper, inserts an array into a table
394 # Keys are field names, values are values
395 # Usually aborts on failure
396 # If errors are explicitly ignored, returns success
397 function insertArray( $table, $a, $fname = "Database::insertArray" )
398 {
399 $sql1 = "INSERT INTO $table (";
400 $sql2 = "VALUES (" . Database::makeList( $a );
401 $first = true;
402 foreach ( $a as $field => $value ) {
403 if ( !$first ) {
404 $sql1 .= ",";
405 }
406 $first = false;
407 $sql1 .= $field;
408 }
409 $sql = "$sql1) $sql2)";
410 return !!$this->query( $sql, $fname );
411 }
412
413 # A cross between insertArray and getArray, takes a condition array and a SET array
414 function updateArray( $table, $values, $conds, $fname = "Database::updateArray" )
415 {
416 $sql = "UPDATE $table SET " . $this->makeList( $values, LIST_SET );
417 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND );
418 $this->query( $sql, $fname );
419 }
420
421 # Makes a wfStrencoded list from an array
422 # $mode: LIST_COMMA - comma separated, no field names
423 # LIST_AND - ANDed WHERE clause (without the WHERE)
424 # LIST_SET - comma separated with field names, like a SET clause
425 /* static */ function makeList( $a, $mode = LIST_COMMA )
426 {
427 $first = true;
428 $list = "";
429 foreach ( $a as $field => $value ) {
430 if ( !$first ) {
431 if ( $mode == LIST_AND ) {
432 $list .= " AND ";
433 } else {
434 $list .= ",";
435 }
436 } else {
437 $first = false;
438 }
439 if ( $mode == LIST_AND || $mode == LIST_SET ) {
440 $list .= "$field=";
441 }
442 if ( !is_numeric( $value ) ) {
443 $list .= "'" . wfStrencode( $value ) . "'";
444 } else {
445 $list .= $value;
446 }
447 }
448 return $list;
449 }
450
451 function selectDB( $db )
452 {
453 $this->mDBname = $db;
454 mysql_select_db( $db, $this->mConn );
455 }
456
457 function startTimer( $timeout )
458 {
459 global $IP;
460
461 $tid = mysql_thread_id( $this->mConn );
462 exec( "php $IP/killthread.php $timeout $tid &>/dev/null &" );
463 }
464
465 function stopTimer()
466 {
467 }
468 }
469
470 #------------------------------------------------------------------------------
471 # Global functions
472 #------------------------------------------------------------------------------
473
474 /* Standard fail function, called by default when a connection cannot be established
475 Displays the file cache if possible */
476 function wfEmergencyAbort( &$conn, $error ) {
477 global $wgTitle, $wgUseFileCache, $title, $wgInputEncoding, $wgSiteNotice, $wgOutputEncoding;
478
479 if( !headers_sent() ) {
480 header( "HTTP/1.0 500 Internal Server Error" );
481 header( "Content-type: text/html; charset=$wgOutputEncoding" );
482 /* Don't cache error pages! They cause no end of trouble... */
483 header( "Cache-control: none" );
484 header( "Pragma: nocache" );
485 }
486 $msg = $wgSiteNotice;
487 if($msg == "") $msg = wfMsgNoDB( "noconnect", $error );
488 $text = $msg;
489
490 if($wgUseFileCache) {
491 if($wgTitle) {
492 $t =& $wgTitle;
493 } else {
494 if($title) {
495 $t = Title::newFromURL( $title );
496 } elseif (@$_REQUEST['search']) {
497 $search = $_REQUEST['search'];
498 echo wfMsgNoDB( "searchdisabled" );
499 echo wfMsgNoDB( "googlesearch", htmlspecialchars( $search ), $wgInputEncoding );
500 wfAbruptExit();
501 } else {
502 $t = Title::newFromText( wfMsgNoDB( "mainpage" ) );
503 }
504 }
505
506 $cache = new CacheManager( $t );
507 if( $cache->isFileCached() ) {
508 $msg = "<p style='color: red'><b>$msg<br />\n" .
509 wfMsgNoDB( "cachederror" ) . "</b></p>\n";
510
511 $tag = "<div id='article'>";
512 $text = str_replace(
513 $tag,
514 $tag . $msg,
515 $cache->fetchPageText() );
516 }
517 }
518
519 echo $text;
520 wfAbruptExit();
521 }
522
523 function wfStrencode( $s )
524 {
525 return addslashes( $s );
526 }
527
528 function wfLimitResult( $limit, $offset ) {
529 return " LIMIT ".(is_numeric($offset)?"{$offset},":"")."{$limit} ";
530 }
531
532
533 ?>