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