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