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