c243b5dd17476945b0599801fb04ad9eed38525b
[lhc/web/wiklou.git] / includes / Database.php
1 <?
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 class Database {
10
11 #------------------------------------------------------------------------------
12 # Variables
13 #------------------------------------------------------------------------------
14 /* private */ var $mLastQuery = "";
15 /* private */ var $mBufferResults = true;
16 /* private */ var $mIgnoreErrors = false;
17
18 /* private */ var $mServer, $mUser, $mPassword, $mConn, $mDBname;
19 /* private */ var $mOut, $mDebug;
20
21 /* private */ var $mFailFunction;
22
23 #------------------------------------------------------------------------------
24 # Accessors
25 #------------------------------------------------------------------------------
26 # Set functions
27 # These set a variable and return the previous state
28
29 # Fail function, takes a Database as a parameter
30 # Set to false for default, 1 for ignore errors
31 function setFailFunction( $function ) { return wfSetVar( $this->mFailFunction, $function ); }
32
33 # Output page, used for reporting errors
34 # FALSE means discard output
35 function &setOutputPage( &$out ) { return wfSetRef( $this->mOut, $out ); }
36
37 # Boolean, controls output of large amounts of debug information
38 function setDebug( $debug ) { return wfSetVar( $this->mDebug, $debug ); }
39
40 # Turns buffering of SQL result sets on (true) or off (false). Default is
41 # "on" and it should not be changed without good reasons.
42 function setBufferResults( $buffer ) { return wfSetVar( $this->mBufferResults, $buffer ); }
43
44 # Turns on (false) or off (true) the automatic generation and sending
45 # of a "we're sorry, but there has been a database error" page on
46 # database errors. Default is on (false). When turned off, the
47 # code should use wfLastErrno() and wfLastError() to handle the
48 # situation as appropriate.
49 function setIgnoreErrors( $ignoreErrors ) { return wfSetVar( $this->mIgnoreErrors, $ignoreErrors ); }
50
51 # Get functions
52
53 function lastQuery() { return $this->mLastQuery; }
54
55 #------------------------------------------------------------------------------
56 # Other functions
57 #------------------------------------------------------------------------------
58
59 function Database()
60 {
61 global $wgOut;
62 $this->mOut = $wgOut;
63
64 }
65
66 /* static */ function newFromParams( $server, $user, $password, $dbName,
67 $failFunction = false, $debug = false, $bufferResults = true, $ignoreErrors = false )
68 {
69 $db = new Database;
70 $db->mFailFunction = $failFunction;
71 $db->mIgnoreErrors = $ignoreErrors;
72 $db->mDebug = $debug;
73 $db->open( $server, $user, $password, $dbName );
74 return $db;
75 }
76
77 # Usually aborts on failure
78 # If the failFunction is set to a non-zero integer, returns success
79 function open( $server, $user, $password, $dbName )
80 {
81 global $wgEmergencyContact;
82
83 $this->close();
84 $this->mServer = $server;
85 $this->mUser = $user;
86 $this->mPassword = $password;
87 $this->mDbName = $dbName;
88
89 $success = false;
90
91 @$this->mConn = mysql_connect( $server, $user, $password );
92 if ( $this->mConn !== false ) {
93 $success = @mysql_select_db( $dbName, $this->mConn );
94 if ( !$success ) {
95 wfDebug( "Error selecting database \"$dbName\": " . $this->lastError() . "\n" );
96 }
97 } else {
98 wfDebug( "DB connect error: " . $this->lastError() . "\n" );
99 wfDebug( "Server: $server, User: $user, Password: " .
100 substr( $password, 0, 3 ) . "...\n" );
101 $success = false;
102 }
103
104 if ( !$success ) {
105 $this->reportConnectionError();
106 $this->close();
107 }
108 return $success;
109 }
110
111 # Closes a database connection, if it is open
112 # Returns success, true if already closed
113 function close()
114 {
115 if ( $this->mConn ) {
116 return mysql_close( $this->mConn );
117 } else {
118 return true;
119 }
120 }
121
122 /* private */ function reportConnectionError( $msg = "")
123 {
124 if ( $this->mFailFunction ) {
125 if ( !is_int( $this->mFailFunction ) ) {
126 $this->$mFailFunction( $this );
127 }
128 } else {
129 wfEmergencyAbort( $this );
130 }
131 }
132
133 # Usually aborts on failure
134 # If errors are explicitly ignored, returns success
135 function query( $sql, $db, $fname = "" )
136 {
137 global $wgProfiling;
138
139 if ( $wgProfiling ) {
140 # generalizeSQL will probably cut down the query to reasonable
141 # logging size most of the time. The substr is really just a sanity check.
142 $profName = "query: " . substr( Database::generalizeSQL( $sql ), 0, 255 );
143 wfProfileIn( $profName );
144 }
145
146 $this->mLastQuery = $sql;
147
148 if ( $this->mDebug ) {
149 $sqlx = substr( $sql, 0, 500 );
150 $sqlx = wordwrap(strtr($sqlx,"\t\n"," "));
151 wfDebug( "SQL: $sqlx\n" );
152 }
153 if( $this->mBufferResults ) {
154 $ret = mysql_query( $sql, $this->mConn );
155 } else {
156 $ret = mysql_unbuffered_query( $sql, $this->mConn );
157 }
158
159 if ( false === $ret ) {
160 if( $this->mIgnoreErrors ) {
161 wfDebug("SQL ERROR (ignored): " . mysql_error( $this->mConn ) . "\n");
162 } else {
163 wfDebug("SQL ERROR: " . mysql_error( $this->mConn ) . "\n");
164 if ( $this->mOut ) {
165 $this->mOut->databaseError( $fname ); // calls wfAbruptExit()
166 }
167 }
168 }
169
170 if ( $wgProfiling ) {
171 wfProfileOut( $profName );
172 }
173 return $ret;
174 }
175
176 function freeResult( $res ) { mysql_free_result( $res ); }
177 function fetchObject( $res ) { return mysql_fetch_object( $res ); }
178 function numRows( $res ) { return mysql_num_rows( $res ); }
179 function numFields( $res ) { return mysql_num_fields( $res ); }
180 function fieldName( $res, $n ) { return mysql_field_name( $res, $n ); }
181 function insertId() { return mysql_insert_id( $this->mConn ); }
182 function dataSeek( $res, $row ) { return mysql_data_seek( $res, $row ); }
183 function lastErrno() { return mysql_errno( $this->mConn ); }
184 function lastError() { return mysql_error( $this->mConn ); }
185 function affectedRows() { return mysql_affected_rows( $this->mConn ); }
186
187 # Simple UPDATE wrapper
188 # Usually aborts on failure
189 # If errors are explicitly ignored, returns success
190 function set( $table, $var, $value, $cond, $fname = "Database::set" )
191 {
192 $sql = "UPDATE $table SET $var = '" .
193 wfStrencode( $value ) . "' WHERE ($cond)";
194 return !!$this->query( $sql, DB_WRITE, $fname );
195 }
196
197 # Simple SELECT wrapper
198 # Usually aborts on failure
199 # If errors are explicitly ignored, returns FALSE on failure
200 function get( $table, $var, $cond, $fname = "Database::get" )
201 {
202 $sql = "SELECT $var FROM $table WHERE ($cond)";
203 $result = $this->query( $sql, DB_READ, $fname );
204
205 $ret = "";
206 if ( mysql_num_rows( $result ) > 0 ) {
207 $s = mysql_fetch_object( $result );
208 $ret = $s->$var;
209 mysql_free_result( $result );
210 }
211 return $ret;
212 }
213
214 # Removes most variables from an SQL query and replaces them with X or N for numbers.
215 # It's only slightly flawed. Don't use for anything important.
216 /* static */ function generalizeSQL( $sql )
217 {
218 # This does the same as the regexp below would do, but in such a way
219 # as to avoid crashing php on some large strings.
220 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
221
222 $sql = str_replace ( "\\\\", "", $sql);
223 $sql = str_replace ( "\\'", "", $sql);
224 $sql = str_replace ( "\\\"", "", $sql);
225 $sql = preg_replace ("/'.*'/s", "'X'", $sql);
226 $sql = preg_replace ('/".*"/s', "'X'", $sql);
227
228 # All newlines, tabs, etc replaced by single space
229 $sql = preg_replace ( "/\s+/", " ", $sql);
230
231 # All numbers => N
232 $sql = preg_replace ('/-?[0-9]+/s', "N", $sql);
233
234 return $sql;
235 }
236
237 # Determines whether a field exists in a table
238 # Usually aborts on failure
239 # If errors are explicitly ignored, returns NULL on failure
240 function fieldExists( $table, $field, $fname = "Database::fieldExists" )
241 {
242 $res = $this->query( "DESCRIBE $table", DB_READ, $fname );
243 if ( !$res ) {
244 return NULL;
245 }
246
247 $found = false;
248
249 while ( $row = $this->fetchObject( $res ) ) {
250 if ( $row->Field == $field ) {
251 $found = true;
252 break;
253 }
254 }
255 return $found;
256 }
257
258 # Determines whether an index exists
259 # Usually aborts on failure
260 # If errors are explicitly ignored, returns NULL on failure
261 function indexExists( $table, $index, $fname = "Database::indexExists" )
262 {
263 $sql = "SHOW INDEXES FROM $table";
264 $res = $this->query( $sql, DB_READ, $fname );
265 if ( !$res ) {
266 return NULL;
267 }
268
269 $found = false;
270
271 while ( $row = $this->fetchObject( $res ) ) {
272 if ( $row->Key_name == $index ) {
273 $found = true;
274 break;
275 }
276 }
277 return $found;
278 }
279
280 # INSERT wrapper, inserts an array into a table
281 # Keys are field names, values are values
282 # Usually aborts on failure
283 # If errors are explicitly ignored, returns success
284 function insertArray( $table, $a, $fname = "Database::insertArray" )
285 {
286 $sql1 = "INSERT INTO $table (";
287 $sql2 = "VALUES (";
288 $first = true;
289 foreach ( $a as $field => $value ) {
290 if ( $first ) {
291 $sql1 .= ",";
292 $sql2 .= ",";
293 $first = false;
294 }
295 $sql1 .= $field;
296 if ( is_string( $value ) ) {
297 $sql2 .= "'" . wfStrencode( $value ) . "'";
298 } else {
299 $sql2 .= $value;
300 }
301 }
302 $sql = "$sql1) $sql2)";
303 return !!$this->query( $sql, DB_WRITE, $fname );
304 }
305 }
306
307 #------------------------------------------------------------------------------
308 # Global functions
309 #------------------------------------------------------------------------------
310
311 /* Standard fail function, called by default when a connection cannot be established
312 Displays the file cache if possible */
313 function wfEmergencyAbort( &$conn ) {
314 global $wgTitle, $wgUseFileCache, $title, $wgInputEncoding, $wgOutputEncoding;
315
316 header( "Content-type: text/html; charset=$wgOutputEncoding" );
317 if($msg == "") $msg = wfMsgNoDB( "noconnect" );
318 $text = $msg;
319
320 if($wgUseFileCache) {
321 if($wgTitle) {
322 $t =& $wgTitle;
323 } else {
324 if($title) {
325 $t = Title::newFromURL( $title );
326 } elseif ($_REQUEST['search']) {
327 $search = $_REQUEST['search'];
328 echo wfMsgNoDB( "searchdisabled", htmlspecialchars( $search ), $wgInputEncoding );
329 wfAbruptExit();
330 } else {
331 $t = Title::newFromText( wfMsgNoDB( "mainpage" ) );
332 }
333 }
334
335 $cache = new CacheManager( $t );
336 if( $cache->isFileCached() ) {
337 $msg = "<p style='color: red'><b>$msg<br>\n" .
338 wfMsgNoDB( "cachederror" ) . "</b></p>\n";
339
340 $tag = "<div id='article'>";
341 $text = str_replace(
342 $tag,
343 $tag . $msg,
344 $cache->fetchPageText() );
345 }
346 }
347
348 /* Don't cache error pages! They cause no end of trouble... */
349 header( "Cache-control: none" );
350 header( "Pragma: nocache" );
351 echo $text;
352 wfAbruptExit();
353 }
354
355 function wfStrencode( $s )
356 {
357 return addslashes( $s );
358 }
359
360 # Ideally we'd be using actual time fields in the db
361 function wfTimestamp2Unix( $ts ) {
362 return gmmktime( ( (int)substr( $ts, 8, 2) ),
363 (int)substr( $ts, 10, 2 ), (int)substr( $ts, 12, 2 ),
364 (int)substr( $ts, 4, 2 ), (int)substr( $ts, 6, 2 ),
365 (int)substr( $ts, 0, 4 ) );
366 }
367
368 function wfUnix2Timestamp( $unixtime ) {
369 return gmdate( "YmdHis", $unixtime );
370 }
371
372 function wfTimestampNow() {
373 # return NOW
374 return gmdate( "YmdHis" );
375 }
376
377 # Sorting hack for MySQL 3, which doesn't use index sorts for DESC
378 function wfInvertTimestamp( $ts ) {
379 return strtr(
380 $ts,
381 "0123456789",
382 "9876543210"
383 );
384 }
385 ?>