Nicer looking errors in command line mode
[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 wfDebug("SQL ERROR: " . $error . "\n");
189 if ( $wgCommandLineMode ) {
190 wfDebugDieBacktrace( "A database error has occurred\n" .
191 "Query: $sql\n" .
192 "Function: $fname\n" .
193 "Error: $errno $error\n"
194 );
195 } elseif ( $this->mOut ) {
196 // this calls wfAbruptExit()
197 $this->mOut->databaseError( $fname, $sql, $error, $errno );
198 }
199 }
200 }
201
202 if ( $wgProfiling ) {
203 wfProfileOut( $profName );
204 }
205 return $ret;
206 }
207
208 function freeResult( $res ) {
209 if ( !@mysql_free_result( $res ) ) {
210 wfDebugDieBacktrace( "Unable to free MySQL result\n" );
211 }
212 }
213 function fetchObject( $res ) {
214 @$row = mysql_fetch_object( $res );
215 # FIXME: HACK HACK HACK HACK debug
216 if( mysql_errno() ) {
217 wfDebugDieBacktrace( "SQL error: " . htmlspecialchars( mysql_error() ) );
218 }
219 return $row;
220 }
221
222 function fetchRow( $res ) {
223 @$row = mysql_fetch_array( $res );
224 if (mysql_errno() ) {
225 wfDebugDieBacktrace( "SQL error: " . htmlspecialchars( mysql_error() ) );
226 }
227 return $row;
228 }
229
230 function numRows( $res ) {
231 @$n = mysql_num_rows( $res );
232 if( mysql_errno() ) {
233 wfDebugDieBacktrace( "SQL error: " . htmlspecialchars( mysql_error() ) );
234 }
235 return $n;
236 }
237 function numFields( $res ) { return mysql_num_fields( $res ); }
238 function fieldName( $res, $n ) { return mysql_field_name( $res, $n ); }
239 function insertId() { return mysql_insert_id( $this->mConn ); }
240 function dataSeek( $res, $row ) { return mysql_data_seek( $res, $row ); }
241 function lastErrno() { return mysql_errno(); }
242 function lastError() { return mysql_error(); }
243 function affectedRows() { return mysql_affected_rows( $this->mConn ); }
244
245 # Simple UPDATE wrapper
246 # Usually aborts on failure
247 # If errors are explicitly ignored, returns success
248 function set( $table, $var, $value, $cond, $fname = "Database::set" )
249 {
250 $sql = "UPDATE $table SET $var = '" .
251 wfStrencode( $value ) . "' WHERE ($cond)";
252 return !!$this->query( $sql, DB_WRITE, $fname );
253 }
254
255 # Simple SELECT wrapper, returns a single field, input must be encoded
256 # Usually aborts on failure
257 # If errors are explicitly ignored, returns FALSE on failure
258 function get( $table, $var, $cond, $fname = "Database::get" )
259 {
260 $sql = "SELECT $var FROM $table WHERE ($cond)";
261 $result = $this->query( $sql, DB_READ, $fname );
262
263 $ret = "";
264 if ( mysql_num_rows( $result ) > 0 ) {
265 $s = mysql_fetch_object( $result );
266 $ret = $s->$var;
267 mysql_free_result( $result );
268 }
269 return $ret;
270 }
271
272 # More complex SELECT wrapper, single row only
273 # Aborts or returns FALSE on error
274 # Takes an array of selected variables, and a condition map, which is ANDed
275 # e.g. getArray( "cur", array( "cur_id" ), array( "cur_namespace" => 0, "cur_title" => "Astronomy" ) )
276 # would return an object where $obj->cur_id is the ID of the Astronomy article
277 function getArray( $table, $vars, $conds, $fname = "Database::getArray" )
278 {
279 $vars = implode( ",", $vars );
280 if ( $conds !== false ) {
281 $where = Database::makeList( $conds, LIST_AND );
282 $sql = "SELECT $vars FROM $table WHERE $where LIMIT 1";
283 } else {
284 $sql = "SELECT $vars FROM $table LIMIT 1";
285 }
286 $res = $this->query( $sql, $fname );
287 if ( $res === false || !$this->numRows( $res ) ) {
288 return false;
289 }
290 $obj = $this->fetchObject( $res );
291 $this->freeResult( $res );
292 return $obj;
293 }
294
295 # Removes most variables from an SQL query and replaces them with X or N for numbers.
296 # It's only slightly flawed. Don't use for anything important.
297 /* static */ function generalizeSQL( $sql )
298 {
299 # This does the same as the regexp below would do, but in such a way
300 # as to avoid crashing php on some large strings.
301 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
302
303 $sql = str_replace ( "\\\\", "", $sql);
304 $sql = str_replace ( "\\'", "", $sql);
305 $sql = str_replace ( "\\\"", "", $sql);
306 $sql = preg_replace ("/'.*'/s", "'X'", $sql);
307 $sql = preg_replace ('/".*"/s', "'X'", $sql);
308
309 # All newlines, tabs, etc replaced by single space
310 $sql = preg_replace ( "/\s+/", " ", $sql);
311
312 # All numbers => N
313 $sql = preg_replace ('/-?[0-9]+/s', "N", $sql);
314
315 return $sql;
316 }
317
318 # Determines whether a field exists in a table
319 # Usually aborts on failure
320 # If errors are explicitly ignored, returns NULL on failure
321 function fieldExists( $table, $field, $fname = "Database::fieldExists" )
322 {
323 $res = $this->query( "DESCRIBE $table", DB_READ, $fname );
324 if ( !$res ) {
325 return NULL;
326 }
327
328 $found = false;
329
330 while ( $row = $this->fetchObject( $res ) ) {
331 if ( $row->Field == $field ) {
332 $found = true;
333 break;
334 }
335 }
336 return $found;
337 }
338
339 # Determines whether an index exists
340 # Usually aborts on failure
341 # If errors are explicitly ignored, returns NULL on failure
342 function indexExists( $table, $index, $fname = "Database::indexExists" )
343 {
344 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
345 # SHOW INDEX should work for 3.x and up:
346 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
347 $sql = "SHOW INDEX FROM $table";
348 $res = $this->query( $sql, DB_READ, $fname );
349 if ( !$res ) {
350 return NULL;
351 }
352
353 $found = false;
354
355 while ( $row = $this->fetchObject( $res ) ) {
356 if ( $row->Key_name == $index ) {
357 $found = true;
358 break;
359 }
360 }
361 return $found;
362 }
363
364 function tableExists( $table )
365 {
366 $old = $this->mIgnoreErrors;
367 $this->mIgnoreErrors = true;
368 $res = $this->query( "SELECT 1 FROM $table LIMIT 1" );
369 $this->mIgnoreErrors = $old;
370 if( $res ) {
371 $this->freeResult( $res );
372 return true;
373 } else {
374 return false;
375 }
376 }
377
378 function fieldInfo( $table, $field )
379 {
380 $res = $this->query( "SELECT * FROM $table LIMIT 1" );
381 $n = mysql_num_fields( $res );
382 for( $i = 0; $i < $n; $i++ ) {
383 $meta = mysql_fetch_field( $res, $i );
384 if( $field == $meta->name ) {
385 return $meta;
386 }
387 }
388 return false;
389 }
390
391 # INSERT wrapper, inserts an array into a table
392 # Keys are field names, values are values
393 # Usually aborts on failure
394 # If errors are explicitly ignored, returns success
395 function insertArray( $table, $a, $fname = "Database::insertArray" )
396 {
397 $sql1 = "INSERT INTO $table (";
398 $sql2 = "VALUES (" . Database::makeList( $a );
399 $first = true;
400 foreach ( $a as $field => $value ) {
401 if ( !$first ) {
402 $sql1 .= ",";
403 }
404 $first = false;
405 $sql1 .= $field;
406 }
407 $sql = "$sql1) $sql2)";
408 return !!$this->query( $sql, $fname );
409 }
410
411 # A cross between insertArray and getArray, takes a condition array and a SET array
412 function updateArray( $table, $values, $conds, $fname = "Database::updateArray" )
413 {
414 $sql = "UPDATE $table SET " . $this->makeList( $values, LIST_SET );
415 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND );
416 $this->query( $sql, $fname );
417 }
418
419 # Makes a wfStrencoded list from an array
420 # $mode: LIST_COMMA - comma separated, no field names
421 # LIST_AND - ANDed WHERE clause (without the WHERE)
422 # LIST_SET - comma separated with field names, like a SET clause
423 /* static */ function makeList( $a, $mode = LIST_COMMA )
424 {
425 $first = true;
426 $list = "";
427 foreach ( $a as $field => $value ) {
428 if ( !$first ) {
429 if ( $mode == LIST_AND ) {
430 $list .= " AND ";
431 } else {
432 $list .= ",";
433 }
434 } else {
435 $first = false;
436 }
437 if ( $mode == LIST_AND || $mode == LIST_SET ) {
438 $list .= "$field=";
439 }
440 if ( !is_numeric( $value ) ) {
441 $list .= "'" . wfStrencode( $value ) . "'";
442 } else {
443 $list .= $value;
444 }
445 }
446 return $list;
447 }
448
449 function selectDB( $db )
450 {
451 $this->mDBname = $db;
452 mysql_select_db( $db, $this->mConn );
453 }
454
455 function startTimer( $timeout )
456 {
457 global $IP;
458
459 $tid = mysql_thread_id( $this->mConn );
460 exec( "php $IP/killthread.php $timeout $tid &>/dev/null &" );
461 }
462
463 function stopTimer()
464 {
465 }
466
467 }
468
469 #------------------------------------------------------------------------------
470 # Global functions
471 #------------------------------------------------------------------------------
472
473 /* Standard fail function, called by default when a connection cannot be established
474 Displays the file cache if possible */
475 function wfEmergencyAbort( &$conn, $error ) {
476 global $wgTitle, $wgUseFileCache, $title, $wgInputEncoding, $wgSiteNotice, $wgOutputEncoding;
477
478 if( !headers_sent() ) {
479 header( "HTTP/1.0 500 Internal Server Error" );
480 header( "Content-type: text/html; charset=$wgOutputEncoding" );
481 /* Don't cache error pages! They cause no end of trouble... */
482 header( "Cache-control: none" );
483 header( "Pragma: nocache" );
484 }
485 $msg = $wgSiteNotice;
486 if($msg == "") $msg = wfMsgNoDB( "noconnect", $error );
487 $text = $msg;
488
489 if($wgUseFileCache) {
490 if($wgTitle) {
491 $t =& $wgTitle;
492 } else {
493 if($title) {
494 $t = Title::newFromURL( $title );
495 } elseif (@$_REQUEST['search']) {
496 $search = $_REQUEST['search'];
497 echo wfMsgNoDB( "searchdisabled" );
498 echo wfMsgNoDB( "googlesearch", htmlspecialchars( $search ), $wgInputEncoding );
499 wfAbruptExit();
500 } else {
501 $t = Title::newFromText( wfMsgNoDB( "mainpage" ) );
502 }
503 }
504
505 $cache = new CacheManager( $t );
506 if( $cache->isFileCached() ) {
507 $msg = "<p style='color: red'><b>$msg<br />\n" .
508 wfMsgNoDB( "cachederror" ) . "</b></p>\n";
509
510 $tag = "<div id='article'>";
511 $text = str_replace(
512 $tag,
513 $tag . $msg,
514 $cache->fetchPageText() );
515 }
516 }
517
518 echo $text;
519 wfAbruptExit();
520 }
521
522 function wfStrencode( $s )
523 {
524 return addslashes( $s );
525 }
526
527 # Ideally we'd be using actual time fields in the db
528 function wfTimestamp2Unix( $ts ) {
529 return gmmktime( ( (int)substr( $ts, 8, 2) ),
530 (int)substr( $ts, 10, 2 ), (int)substr( $ts, 12, 2 ),
531 (int)substr( $ts, 4, 2 ), (int)substr( $ts, 6, 2 ),
532 (int)substr( $ts, 0, 4 ) );
533 }
534
535 function wfUnix2Timestamp( $unixtime ) {
536 return gmdate( "YmdHis", $unixtime );
537 }
538
539 function wfTimestampNow() {
540 # return NOW
541 return gmdate( "YmdHis" );
542 }
543
544 # Sorting hack for MySQL 3, which doesn't use index sorts for DESC
545 function wfInvertTimestamp( $ts ) {
546 return strtr(
547 $ts,
548 "0123456789",
549 "9876543210"
550 );
551 }
552
553 function wfLimitResult( $limit, $offset ) {
554 return " LIMIT ".(is_numeric($offset)?"{$offset},":"")."{$limit} ";
555 }
556
557 ?>