6e295e3261a4fac1e17768703ddb02d6ed2b8650
[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 $nTables = $this->numRows( $res );
317 for( $i = 0; $i < $nTables; $i++ ) {
318 if( mysql_tablename( $res, $i ) == $table ) return true;
319 }
320 return false;
321 }
322
323 function fieldInfo( $table, $field )
324 {
325 $res = $this->query( "SELECT * FROM $table LIMIT 1" );
326 $n = mysql_num_fields( $res );
327 for( $i = 0; $i < $n; $i++ ) {
328 $meta = mysql_fetch_field( $res, $i );
329 if( $field == $meta->name ) {
330 return $meta;
331 }
332 }
333 return false;
334 }
335
336 # INSERT wrapper, inserts an array into a table
337 # Keys are field names, values are values
338 # Usually aborts on failure
339 # If errors are explicitly ignored, returns success
340 function insertArray( $table, $a, $fname = "Database::insertArray" )
341 {
342 $sql1 = "INSERT INTO $table (";
343 $sql2 = "VALUES (" . Database::makeList( $a );
344 $first = true;
345 foreach ( $a as $field => $value ) {
346 if ( !$first ) {
347 $sql1 .= ",";
348 }
349 $first = false;
350 $sql1 .= $field;
351 }
352 $sql = "$sql1) $sql2)";
353 return !!$this->query( $sql, $fname );
354 }
355
356 # Makes a wfStrencoded list from an array
357 # $mode: LIST_COMMA - comma separated
358 # LIST_AND - ANDed WHERE clause (without the WHERE)
359 /* static */ function makeList( $a, $mode = LIST_COMMA)
360 {
361 $first = true;
362 $list = "";
363 foreach ( $a as $field => $value ) {
364 if ( !$first ) {
365 if ( $mode == LIST_AND ) {
366 $list .= " AND ";
367 } else {
368 $list .= ",";
369 }
370 } else {
371 $first = false;
372 }
373 if ( $mode == LIST_AND ) {
374 $list .= "$field=";
375 }
376 if ( is_string( $value ) ) {
377 $list .= "'" . wfStrencode( $value ) . "'";
378 } else {
379 $list .= $value;
380 }
381 }
382 return $list;
383 }
384
385 function selectDB( $db )
386 {
387 $this->mDBname = $db;
388 mysql_select_db( $db, $this->mConn );
389 }
390
391 function startTimer( $timeout )
392 {
393 global $IP;
394
395 $tid = mysql_thread_id( $this->mConn );
396 exec( "php $IP/killthread.php $timeout $tid &>/dev/null &" );
397 }
398
399 function stopTimer()
400 {
401 }
402
403 }
404
405 #------------------------------------------------------------------------------
406 # Global functions
407 #------------------------------------------------------------------------------
408
409 /* Standard fail function, called by default when a connection cannot be established
410 Displays the file cache if possible */
411 function wfEmergencyAbort( &$conn ) {
412 global $wgTitle, $wgUseFileCache, $title, $wgInputEncoding, $wgSiteNotice, $wgOutputEncoding;
413
414 header( "Content-type: text/html; charset=$wgOutputEncoding" );
415 $msg = $wgSiteNotice;
416 if($msg == "") $msg = wfMsgNoDB( "noconnect" );
417 $text = $msg;
418
419 if($wgUseFileCache) {
420 if($wgTitle) {
421 $t =& $wgTitle;
422 } else {
423 if($title) {
424 $t = Title::newFromURL( $title );
425 } elseif ($_REQUEST['search']) {
426 $search = $_REQUEST['search'];
427 echo wfMsgNoDB( "searchdisabled" );
428 echo wfMsgNoDB( "googlesearch", htmlspecialchars( $search ), $wgInputEncoding );
429 wfAbruptExit();
430 } else {
431 $t = Title::newFromText( wfMsgNoDB( "mainpage" ) );
432 }
433 }
434
435 $cache = new CacheManager( $t );
436 if( $cache->isFileCached() ) {
437 $msg = "<p style='color: red'><b>$msg<br>\n" .
438 wfMsgNoDB( "cachederror" ) . "</b></p>\n";
439
440 $tag = "<div id='article'>";
441 $text = str_replace(
442 $tag,
443 $tag . $msg,
444 $cache->fetchPageText() );
445 }
446 }
447
448 /* Don't cache error pages! They cause no end of trouble... */
449 header( "Cache-control: none" );
450 header( "Pragma: nocache" );
451 echo $text;
452 wfAbruptExit();
453 }
454
455 function wfStrencode( $s )
456 {
457 return addslashes( $s );
458 }
459
460 # Ideally we'd be using actual time fields in the db
461 function wfTimestamp2Unix( $ts ) {
462 return gmmktime( ( (int)substr( $ts, 8, 2) ),
463 (int)substr( $ts, 10, 2 ), (int)substr( $ts, 12, 2 ),
464 (int)substr( $ts, 4, 2 ), (int)substr( $ts, 6, 2 ),
465 (int)substr( $ts, 0, 4 ) );
466 }
467
468 function wfUnix2Timestamp( $unixtime ) {
469 return gmdate( "YmdHis", $unixtime );
470 }
471
472 function wfTimestampNow() {
473 # return NOW
474 return gmdate( "YmdHis" );
475 }
476
477 # Sorting hack for MySQL 3, which doesn't use index sorts for DESC
478 function wfInvertTimestamp( $ts ) {
479 return strtr(
480 $ts,
481 "0123456789",
482 "9876543210"
483 );
484 }
485 ?>