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