On emergency abort check if headers have already been sent to avoid useless warnings...
[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( "DB_READ", -1 );
9 define( "DB_WRITE", -2 );
10 define( "DB_LAST", -3 );
11
12 define( "LIST_COMMA", 0 );
13 define( "LIST_AND", 1 );
14 define( "LIST_SET", 2 );
15
16 class Database {
17
18 #------------------------------------------------------------------------------
19 # Variables
20 #------------------------------------------------------------------------------
21 /* private */ var $mLastQuery = "";
22 /* private */ var $mBufferResults = true;
23 /* private */ var $mIgnoreErrors = false;
24
25 /* private */ var $mServer, $mUser, $mPassword, $mConn, $mDBname;
26 /* private */ var $mOut, $mDebug, $mOpened = false;
27
28 /* private */ var $mFailFunction;
29
30 #------------------------------------------------------------------------------
31 # Accessors
32 #------------------------------------------------------------------------------
33 # Set functions
34 # These set a variable and return the previous state
35
36 # Fail function, takes a Database as a parameter
37 # Set to false for default, 1 for ignore errors
38 function setFailFunction( $function ) { return wfSetVar( $this->mFailFunction, $function ); }
39
40 # Output page, used for reporting errors
41 # FALSE means discard output
42 function &setOutputPage( &$out ) { return wfSetRef( $this->mOut, $out ); }
43
44 # Boolean, controls output of large amounts of debug information
45 function setDebug( $debug ) { return wfSetVar( $this->mDebug, $debug ); }
46
47 # Turns buffering of SQL result sets on (true) or off (false). Default is
48 # "on" and it should not be changed without good reasons.
49 function setBufferResults( $buffer ) { return wfSetVar( $this->mBufferResults, $buffer ); }
50
51 # Turns on (false) or off (true) the automatic generation and sending
52 # of a "we're sorry, but there has been a database error" page on
53 # database errors. Default is on (false). When turned off, the
54 # code should use wfLastErrno() and wfLastError() to handle the
55 # situation as appropriate.
56 function setIgnoreErrors( $ignoreErrors ) { return wfSetVar( $this->mIgnoreErrors, $ignoreErrors ); }
57
58 # Get functions
59
60 function lastQuery() { return $this->mLastQuery; }
61 function isOpen() { return $this->mOpened; }
62
63 #------------------------------------------------------------------------------
64 # Other functions
65 #------------------------------------------------------------------------------
66
67 function Database()
68 {
69 global $wgOut;
70 # Can't get a reference if it hasn't been set yet
71 if ( !isset( $wgOut ) ) {
72 $wgOut = NULL;
73 }
74 $this->mOut =& $wgOut;
75
76 }
77
78 /* static */ function newFromParams( $server, $user, $password, $dbName,
79 $failFunction = false, $debug = false, $bufferResults = true, $ignoreErrors = false )
80 {
81 $db = new Database;
82 $db->mFailFunction = $failFunction;
83 $db->mIgnoreErrors = $ignoreErrors;
84 $db->mDebug = $debug;
85 $db->mBufferResults = $bufferResults;
86 $db->open( $server, $user, $password, $dbName );
87 return $db;
88 }
89
90 # Usually aborts on failure
91 # If the failFunction is set to a non-zero integer, returns success
92 function open( $server, $user, $password, $dbName )
93 {
94 global $wgEmergencyContact;
95
96 $this->close();
97 $this->mServer = $server;
98 $this->mUser = $user;
99 $this->mPassword = $password;
100 $this->mDBname = $dbName;
101
102 $success = false;
103
104 @$this->mConn = mysql_connect( $server, $user, $password );
105 if ( $dbName != "" ) {
106 if ( $this->mConn !== false ) {
107 $success = @mysql_select_db( $dbName, $this->mConn );
108 if ( !$success ) {
109 wfDebug( "Error selecting database \"$dbName\": " . $this->lastError() . "\n" );
110 }
111 } else {
112 wfDebug( "DB connection error\n" );
113 wfDebug( "Server: $server, User: $user, Password: " .
114 substr( $password, 0, 3 ) . "...\n" );
115 $success = false;
116 }
117 } else {
118 # Delay USE query
119 $success = !!$this->mConn;
120 }
121
122 if ( !$success ) {
123 $this->reportConnectionError();
124 $this->close();
125 }
126 $this->mOpened = $success;
127 return $success;
128 }
129
130 # Closes a database connection, if it is open
131 # Returns success, true if already closed
132 function close()
133 {
134 $this->mOpened = false;
135 if ( $this->mConn ) {
136 return mysql_close( $this->mConn );
137 } else {
138 return true;
139 }
140 }
141
142 /* private */ function reportConnectionError( $msg = "")
143 {
144 if ( $this->mFailFunction ) {
145 if ( !is_int( $this->mFailFunction ) ) {
146 $this->$mFailFunction( $this );
147 }
148 } else {
149 wfEmergencyAbort( $this );
150 }
151 }
152
153 # Usually aborts on failure
154 # If errors are explicitly ignored, returns success
155 function query( $sql, $fname = "" )
156 {
157 global $wgProfiling;
158
159 if ( $wgProfiling ) {
160 # generalizeSQL will probably cut down the query to reasonable
161 # logging size most of the time. The substr is really just a sanity check.
162 $profName = "query: " . substr( Database::generalizeSQL( $sql ), 0, 255 );
163 wfProfileIn( $profName );
164 }
165
166 $this->mLastQuery = $sql;
167
168 if ( $this->mDebug ) {
169 $sqlx = substr( $sql, 0, 500 );
170 $sqlx = wordwrap(strtr($sqlx,"\t\n"," "));
171 wfDebug( "SQL: $sqlx\n" );
172 }
173 if( $this->mBufferResults ) {
174 $ret = mysql_query( $sql, $this->mConn );
175 } else {
176 $ret = mysql_unbuffered_query( $sql, $this->mConn );
177 }
178
179 if ( false === $ret ) {
180 $error = mysql_error( $this->mConn );
181 $errno = mysql_errno( $this->mConn );
182 if( $this->mIgnoreErrors ) {
183 wfDebug("SQL ERROR (ignored): " . $error . "\n");
184 } else {
185 wfDebug("SQL ERROR: " . $error . "\n");
186 if ( $this->mOut ) {
187 // this calls wfAbruptExit()
188 $this->mOut->databaseError( $fname, $sql, $error, $errno );
189 }
190 }
191 }
192
193 if ( $wgProfiling ) {
194 wfProfileOut( $profName );
195 }
196 return $ret;
197 }
198
199 function freeResult( $res ) {
200 if ( !@mysql_free_result( $res ) ) {
201 wfDebugDieBacktrace( "Unable to free MySQL result\n" );
202 }
203 }
204 function fetchObject( $res ) {
205 @$row = mysql_fetch_object( $res );
206 # FIXME: HACK HACK HACK HACK debug
207 if( mysql_errno() ) {
208 wfDebugDieBacktrace( "SQL error: " . htmlspecialchars( mysql_error() ) );
209 }
210 return $row;
211 }
212
213 function fetchRow( $res ) {
214 @$row = mysql_fetch_array( $res );
215 if (mysql_errno() ) {
216 wfDebugDieBacktrace( "SQL error: " . htmlspecialchars( mysql_error() ) );
217 }
218 return $row;
219 }
220
221 function numRows( $res ) {
222 @$n = mysql_num_rows( $res );
223 if( mysql_errno() ) {
224 wfDebugDieBacktrace( "SQL error: " . htmlspecialchars( mysql_error() ) );
225 }
226 return $n;
227 }
228 function numFields( $res ) { return mysql_num_fields( $res ); }
229 function fieldName( $res, $n ) { return mysql_field_name( $res, $n ); }
230 function insertId() { return mysql_insert_id( $this->mConn ); }
231 function dataSeek( $res, $row ) { return mysql_data_seek( $res, $row ); }
232 function lastErrno() { return mysql_errno(); }
233 function lastError() { return mysql_error(); }
234 function affectedRows() { return mysql_affected_rows( $this->mConn ); }
235
236 # Simple UPDATE wrapper
237 # Usually aborts on failure
238 # If errors are explicitly ignored, returns success
239 function set( $table, $var, $value, $cond, $fname = "Database::set" )
240 {
241 $sql = "UPDATE $table SET $var = '" .
242 wfStrencode( $value ) . "' WHERE ($cond)";
243 return !!$this->query( $sql, DB_WRITE, $fname );
244 }
245
246 # Simple SELECT wrapper, returns a single field, input must be encoded
247 # Usually aborts on failure
248 # If errors are explicitly ignored, returns FALSE on failure
249 function get( $table, $var, $cond, $fname = "Database::get" )
250 {
251 $sql = "SELECT $var FROM $table WHERE ($cond)";
252 $result = $this->query( $sql, DB_READ, $fname );
253
254 $ret = "";
255 if ( mysql_num_rows( $result ) > 0 ) {
256 $s = mysql_fetch_object( $result );
257 $ret = $s->$var;
258 mysql_free_result( $result );
259 }
260 return $ret;
261 }
262
263 # More complex SELECT wrapper, single row only
264 # Aborts or returns FALSE on error
265 # Takes an array of selected variables, and a condition map, which is ANDed
266 # e.g. getArray( "cur", array( "cur_id" ), array( "cur_namespace" => 0, "cur_title" => "Astronomy" ) )
267 # would return an object where $obj->cur_id is the ID of the Astronomy article
268 function getArray( $table, $vars, $conds, $fname = "Database::getArray" )
269 {
270 $vars = implode( ",", $vars );
271 $where = Database::makeList( $conds, LIST_AND );
272 $sql = "SELECT $vars FROM $table WHERE $where LIMIT 1";
273 $res = $this->query( $sql, $fname );
274 if ( $res === false || !$this->numRows( $res ) ) {
275 return false;
276 }
277 $obj = $this->fetchObject( $res );
278 $this->freeResult( $res );
279 return $obj;
280 }
281
282 # Removes most variables from an SQL query and replaces them with X or N for numbers.
283 # It's only slightly flawed. Don't use for anything important.
284 /* static */ function generalizeSQL( $sql )
285 {
286 # This does the same as the regexp below would do, but in such a way
287 # as to avoid crashing php on some large strings.
288 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
289
290 $sql = str_replace ( "\\\\", "", $sql);
291 $sql = str_replace ( "\\'", "", $sql);
292 $sql = str_replace ( "\\\"", "", $sql);
293 $sql = preg_replace ("/'.*'/s", "'X'", $sql);
294 $sql = preg_replace ('/".*"/s', "'X'", $sql);
295
296 # All newlines, tabs, etc replaced by single space
297 $sql = preg_replace ( "/\s+/", " ", $sql);
298
299 # All numbers => N
300 $sql = preg_replace ('/-?[0-9]+/s', "N", $sql);
301
302 return $sql;
303 }
304
305 # Determines whether a field exists in a table
306 # Usually aborts on failure
307 # If errors are explicitly ignored, returns NULL on failure
308 function fieldExists( $table, $field, $fname = "Database::fieldExists" )
309 {
310 $res = $this->query( "DESCRIBE $table", DB_READ, $fname );
311 if ( !$res ) {
312 return NULL;
313 }
314
315 $found = false;
316
317 while ( $row = $this->fetchObject( $res ) ) {
318 if ( $row->Field == $field ) {
319 $found = true;
320 break;
321 }
322 }
323 return $found;
324 }
325
326 # Determines whether an index exists
327 # Usually aborts on failure
328 # If errors are explicitly ignored, returns NULL on failure
329 function indexExists( $table, $index, $fname = "Database::indexExists" )
330 {
331 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
332 # SHOW INDEX should work for 3.x and up:
333 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
334 $sql = "SHOW INDEX FROM $table";
335 $res = $this->query( $sql, DB_READ, $fname );
336 if ( !$res ) {
337 return NULL;
338 }
339
340 $found = false;
341
342 while ( $row = $this->fetchObject( $res ) ) {
343 if ( $row->Key_name == $index ) {
344 $found = true;
345 break;
346 }
347 }
348 return $found;
349 }
350
351 function tableExists( $table )
352 {
353 $old = $this->mIgnoreErrors;
354 $this->mIgnoreErrors = true;
355 $res = $this->query( "SELECT 1 FROM $table LIMIT 1" );
356 $this->mIgnoreErrors = $old;
357 if( $res ) {
358 $this->freeResult( $res );
359 return true;
360 } else {
361 return false;
362 }
363 }
364
365 function fieldInfo( $table, $field )
366 {
367 $res = $this->query( "SELECT * FROM $table LIMIT 1" );
368 $n = mysql_num_fields( $res );
369 for( $i = 0; $i < $n; $i++ ) {
370 $meta = mysql_fetch_field( $res, $i );
371 if( $field == $meta->name ) {
372 return $meta;
373 }
374 }
375 return false;
376 }
377
378 # INSERT wrapper, inserts an array into a table
379 # Keys are field names, values are values
380 # Usually aborts on failure
381 # If errors are explicitly ignored, returns success
382 function insertArray( $table, $a, $fname = "Database::insertArray" )
383 {
384 $sql1 = "INSERT INTO $table (";
385 $sql2 = "VALUES (" . Database::makeList( $a );
386 $first = true;
387 foreach ( $a as $field => $value ) {
388 if ( !$first ) {
389 $sql1 .= ",";
390 }
391 $first = false;
392 $sql1 .= $field;
393 }
394 $sql = "$sql1) $sql2)";
395 return !!$this->query( $sql, $fname );
396 }
397
398 # A cross between insertArray and getArray, takes a condition array and a SET array
399 function updateArray( $table, $values, $conds, $fname = "Database::updateArray" )
400 {
401 $sql = "UPDATE $table SET " . $this->makeList( $values, LIST_SET );
402 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND );
403 $this->query( $sql, $fname );
404 }
405
406 # Makes a wfStrencoded list from an array
407 # $mode: LIST_COMMA - comma separated, no field names
408 # LIST_AND - ANDed WHERE clause (without the WHERE)
409 # LIST_SET - comma separated with field names, like a SET clause
410 /* static */ function makeList( $a, $mode = LIST_COMMA )
411 {
412 $first = true;
413 $list = "";
414 foreach ( $a as $field => $value ) {
415 if ( !$first ) {
416 if ( $mode == LIST_AND ) {
417 $list .= " AND ";
418 } else {
419 $list .= ",";
420 }
421 } else {
422 $first = false;
423 }
424 if ( $mode == LIST_AND || $mode == LIST_SET ) {
425 $list .= "$field=";
426 }
427 if ( !is_numeric( $value ) ) {
428 $list .= "'" . wfStrencode( $value ) . "'";
429 } else {
430 $list .= $value;
431 }
432 }
433 return $list;
434 }
435
436 function selectDB( $db )
437 {
438 $this->mDBname = $db;
439 mysql_select_db( $db, $this->mConn );
440 }
441
442 function startTimer( $timeout )
443 {
444 global $IP;
445
446 $tid = mysql_thread_id( $this->mConn );
447 exec( "php $IP/killthread.php $timeout $tid &>/dev/null &" );
448 }
449
450 function stopTimer()
451 {
452 }
453
454 }
455
456 #------------------------------------------------------------------------------
457 # Global functions
458 #------------------------------------------------------------------------------
459
460 /* Standard fail function, called by default when a connection cannot be established
461 Displays the file cache if possible */
462 function wfEmergencyAbort( &$conn ) {
463 global $wgTitle, $wgUseFileCache, $title, $wgInputEncoding, $wgSiteNotice, $wgOutputEncoding;
464
465 if( !headers_sent() ) {
466 header( "HTTP/1.0 500 Internal Server Error" );
467 header( "Content-type: text/html; charset=$wgOutputEncoding" );
468 /* Don't cache error pages! They cause no end of trouble... */
469 header( "Cache-control: none" );
470 header( "Pragma: nocache" );
471 }
472 $msg = $wgSiteNotice;
473 if($msg == "") $msg = wfMsgNoDB( "noconnect" );
474 $text = $msg;
475
476 if($wgUseFileCache) {
477 if($wgTitle) {
478 $t =& $wgTitle;
479 } else {
480 if($title) {
481 $t = Title::newFromURL( $title );
482 } elseif (@$_REQUEST['search']) {
483 $search = $_REQUEST['search'];
484 echo wfMsgNoDB( "searchdisabled" );
485 echo wfMsgNoDB( "googlesearch", htmlspecialchars( $search ), $wgInputEncoding );
486 wfAbruptExit();
487 } else {
488 $t = Title::newFromText( wfMsgNoDB( "mainpage" ) );
489 }
490 }
491
492 $cache = new CacheManager( $t );
493 if( $cache->isFileCached() ) {
494 $msg = "<p style='color: red'><b>$msg<br />\n" .
495 wfMsgNoDB( "cachederror" ) . "</b></p>\n";
496
497 $tag = "<div id='article'>";
498 $text = str_replace(
499 $tag,
500 $tag . $msg,
501 $cache->fetchPageText() );
502 }
503 }
504
505 echo $text;
506 wfAbruptExit();
507 }
508
509 function wfStrencode( $s )
510 {
511 return addslashes( $s );
512 }
513
514 # Ideally we'd be using actual time fields in the db
515 function wfTimestamp2Unix( $ts ) {
516 return gmmktime( ( (int)substr( $ts, 8, 2) ),
517 (int)substr( $ts, 10, 2 ), (int)substr( $ts, 12, 2 ),
518 (int)substr( $ts, 4, 2 ), (int)substr( $ts, 6, 2 ),
519 (int)substr( $ts, 0, 4 ) );
520 }
521
522 function wfUnix2Timestamp( $unixtime ) {
523 return gmdate( "YmdHis", $unixtime );
524 }
525
526 function wfTimestampNow() {
527 # return NOW
528 return gmdate( "YmdHis" );
529 }
530
531 # Sorting hack for MySQL 3, which doesn't use index sorts for DESC
532 function wfInvertTimestamp( $ts ) {
533 return strtr(
534 $ts,
535 "0123456789",
536 "9876543210"
537 );
538 }
539
540 function wfLimitResult( $limit, $offset ) {
541 return " LIMIT ".(is_numeric($offset)?"{$offset},":"")."{$limit} ";
542 }
543
544 ?>