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