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