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