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