Fallback to google search box when database is offline
[lhc/web/wiklou.git] / includes / DatabaseFunctions.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 $wgLastDatabaseQuery = "";
10
11 /* private */ $wgBufferSQLResults = true;
12 /* private */ $wgIgnoreSQLErrors = false;
13
14 function wfGetDB( $altuser = "", $altpassword = "", $altserver = "", $altdb = "" )
15 {
16 global $wgDBserver, $wgDBuser, $wgDBpassword;
17 global $wgDBname, $wgDBconnection, $wgEmergencyContact;
18
19 $noconn = wfMsgNoDB( "noconnect", $wgDBserver );
20 $nodb = wfMsgNoDB( "nodb", $wgDBname );
21
22 $helpme = "\n<p>If this error persists after reloading and clearing " .
23 "your browser cache, please notify the <a href=\"mailto:" .
24 $wgEmergencyContact . "\">Wikipedia developers</a>.</p>";
25
26 if ( $altuser != "" ) {
27 $serve = ($altserver ? $altserver : $wgDBserver );
28 $db = ($altdb ? $altdb : $wgDBname );
29 $wgDBconnection = mysql_connect( $serve, $altuser, $altpassword )
30 or die( "bad sql user" );
31 mysql_select_db( $db, $wgDBconnection ) or die(
32 htmlspecialchars(mysql_error()) );
33 }
34
35 if ( ! $wgDBconnection ) {
36 @$wgDBconnection = mysql_connect( $wgDBserver, $wgDBuser, $wgDBpassword )
37 or wfEmergencyAbort();
38
39 @mysql_select_db( $wgDBname, $wgDBconnection )
40 or wfEmergencyAbort();
41 }
42 # mysql_ping( $wgDBconnection );
43 return $wgDBconnection;
44 }
45
46 /* Call this function if we couldn't contact the database...
47 We'll try to use the cache to display something in the meantime */
48 function wfEmergencyAbort( $msg = "" ) {
49 global $wgTitle, $wgUseFileCache, $title, $wgInputEncoding, $wgOutputEncoding;
50
51 header( "Content-type: text/html; charset=$wgOutputEncoding" );
52 if($msg == "") $msg = wfMsgNoDB( "noconnect" );
53 $text = $msg;
54
55 if($wgUseFileCache) {
56 if($wgTitle) {
57 $t =& $wgTitle;
58 } else {
59 if($title) {
60 $t = Title::newFromURL( $title );
61 } elseif ($_REQUEST['search']) {
62 $search = $_REQUEST['search'];
63 echo wfMsgNoDB( "searchdisabled", htmlspecialchars( $search ), $wgInputEncoding );
64 wfAbruptExit();
65 } else {
66 $t = Title::newFromText( wfMsgNoDB( "mainpage" ) );
67 }
68 }
69
70 $cache = new CacheManager( $t );
71 if( $cache->isFileCached() ) {
72 $msg = "<p style='color: red'><b>$msg<br>\n" .
73 wfMsgNoDB( "cachederror" ) . "</b></p>\n";
74
75 $tag = "<div id='article'>";
76 $text = str_replace(
77 $tag,
78 $tag . $msg,
79 $cache->fetchPageText() );
80 }
81 }
82
83 /* Don't cache error pages! They cause no end of trouble... */
84 header( "Cache-control: none" );
85 header( "Pragma: nocache" );
86 echo $text;
87 wfAbruptExit();
88 }
89
90 # $db: DB_READ = -1 read from slave (or only server)
91 # DB_WRITE = -2 write to master (or only server)
92 # 0,1,2,... query a database with a specific index
93 # Replication is not actually implemented just yet
94 function wfQuery( $sql, $db, $fname = "" )
95 {
96 global $wgLastDatabaseQuery, $wgOut, $wgDebugDumpSql, $wgBufferSQLResults,
97 $wgIgnoreSQLErrors, $wgProfiling;
98
99 if ( $wgProfiling ) {
100 # wfGeneralizeSQL will probably cut down the query to reasonable
101 # logging size most of the time. The substr is really just a sanity check.
102 $profName = "wfQuery: " . substr( wfGeneralizeSQL( $sql ), 0, 255 );
103 wfProfileIn( $profName );
104 }
105
106 if ( !is_numeric( $db ) ) {
107 # Someone has tried to call this the old way
108 $wgOut->fatalError( wfMsgNoDB( "wrong_wfQuery_params", $db, $sql ) );
109 }
110
111 $wgLastDatabaseQuery = $sql;
112
113 if( $wgDebugDumpSql ) {
114 $sqlx = substr( $sql, 0, 500 );
115 $sqlx = wordwrap(strtr($sqlx,"\t\n"," "));
116 wfDebug( "SQL: $sqlx\n" );
117 }
118
119 $conn = wfGetDB();
120 if( $wgBufferSQLResults ) {
121 $ret = mysql_query( $sql, $conn );
122 } else {
123 $ret = mysql_unbuffered_query( $sql, $conn );
124 }
125
126 if ( false === $ret ) {
127 if( $wgIgnoreSQLErrors ) {
128 wfDebug("SQL ERROR (ignored): " . mysql_error( $conn ) . "\n");
129 } else {
130 wfDebug("SQL ERROR: " . mysql_error( $conn ) . "\n");
131 $wgOut->databaseError( $fname ); // calls wfAbruptExit()
132 }
133 }
134
135 if ( $wgProfiling ) {
136 wfProfileOut( $profName );
137 }
138 return $ret;
139 }
140
141 # Turns buffering of SQL result sets on (true) or off (false). Default is
142 # "on" and it should not be changed without good reasons.
143 # Returns the previous state.
144
145 function wfBufferSQLResults( $newstate ){
146 global $wgBufferSQLResults;
147 $oldstate = $wgBufferSQLResults;
148 $wgBufferSQLResults = $newstate;
149 return $oldstate;
150 }
151
152 # Turns on (false) or off (true) the automatic generation and sending
153 # of a "we're sorry, but there has been a database error" page on
154 # database errors. Default is on (false). When turned off, the
155 # code should use wfLastErrno() and wfLastError() to handle the
156 # situation as appropriate.
157 # Returns the previous state.
158
159 function wfIgnoreSQLErrors( $newstate ){
160 global $wgIgnoreSQLErrors;
161 $oldstate = $wgIgnoreSQLErrors;
162 $wgIgnoreSQLErrors = $newstate;
163 return $oldstate;
164 }
165
166 function wfFreeResult( $res ) { mysql_free_result( $res ); }
167 function wfFetchObject( $res ) { return mysql_fetch_object( $res ); }
168 function wfNumRows( $res ) { return mysql_num_rows( $res ); }
169 function wfNumFields( $res ) { return mysql_num_fields( $res ); }
170 function wfFieldName( $res, $n ) { return mysql_field_name( $res, $n ); }
171 function wfInsertId() { return mysql_insert_id( wfGetDB() ); }
172 function wfDataSeek( $res, $row ) { return mysql_data_seek( $res, $row ); }
173 function wfLastErrno() { return mysql_errno(); }
174 function wfLastError() { return mysql_error(); }
175 function wfAffectedRows() { return mysql_affected_rows( wfGetDB() ); }
176
177 function wfLastDBquery()
178 {
179 global $wgLastDatabaseQuery;
180 return $wgLastDatabaseQuery;
181 }
182
183 function wfSetSQL( $table, $var, $value, $cond )
184 {
185 $sql = "UPDATE $table SET $var = '" .
186 wfStrencode( $value ) . "' WHERE ($cond)";
187 wfQuery( $sql, DB_WRITE, "wfSetSQL" );
188 }
189
190 function wfGetSQL( $table, $var, $cond )
191 {
192 $sql = "SELECT $var FROM $table WHERE ($cond)";
193 $result = wfQuery( $sql, DB_READ, "wfGetSQL" );
194
195 $ret = "";
196 if ( mysql_num_rows( $result ) > 0 ) {
197 $s = mysql_fetch_object( $result );
198 $ret = $s->$var;
199 mysql_free_result( $result );
200 }
201 return $ret;
202 }
203
204 function wfStrencode( $s )
205 {
206 return addslashes( $s );
207 }
208
209 # Ideally we'd be using actual time fields in the db
210 function wfTimestamp2Unix( $ts ) {
211 return gmmktime( ( (int)substr( $ts, 8, 2) ),
212 (int)substr( $ts, 10, 2 ), (int)substr( $ts, 12, 2 ),
213 (int)substr( $ts, 4, 2 ), (int)substr( $ts, 6, 2 ),
214 (int)substr( $ts, 0, 4 ) );
215 }
216
217 function wfUnix2Timestamp( $unixtime ) {
218 return gmdate( "YmdHis", $unixtime );
219 }
220
221 function wfTimestampNow() {
222 # return NOW
223 return gmdate( "YmdHis" );
224 }
225
226 # Sorting hack for MySQL 3, which doesn't use index sorts for DESC
227 function wfInvertTimestamp( $ts ) {
228 return strtr(
229 $ts,
230 "0123456789",
231 "9876543210"
232 );
233 }
234
235 # Removes most variables from an SQL query and replaces them with X or N for numbers.
236 # It's only slightly flawed. Don't use for anything important.
237 function wfGeneralizeSQL( $sql )
238 {
239 # This does the same as the regexp below would do, but in such a way
240 # as to avoid crashing php on some large strings.
241 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
242
243 $sql = str_replace ( "\\\\", "", $sql);
244 $sql = str_replace ( "\\'", "", $sql);
245 $sql = str_replace ( "\\\"", "", $sql);
246 $sql = preg_replace ("/'.*'/s", "'X'", $sql);
247 $sql = preg_replace ('/".*"/s', "'X'", $sql);
248
249 # All newlines, tabs, etc replaced by single space
250 $sql = preg_replace ( "/\s+/", " ", $sql);
251
252 # All numbers => N
253 $sql = preg_replace ('/-?[0-9]+/s', "N", $sql);
254
255 return $sql;
256 }
257
258 function wfFieldExists( $table, $field )
259 {
260 $fname = "wfFieldExists";
261 $res = wfQuery( "DESCRIBE $table", DB_READ, $fname );
262 $found = false;
263
264 while ( $row = wfFetchObject( $res ) ) {
265 if ( $row->Field == $field ) {
266 $found = true;
267 break;
268 }
269 }
270 return $found;
271 }
272
273 function wfIndexExists( $table, $index )
274 {
275 global $wgDBname;
276 $fname = "wfIndexExists";
277 $sql = "SHOW INDEXES FROM $table";
278 $res = wfQuery( $sql, DB_READ, $fname );
279 $found = false;
280 while ( $row = wfFetchObject( $res ) ) {
281 if ( $row->Key_name == $index ) {
282 $found = true;
283 break;
284 }
285 }
286 return $found;
287 }
288 ?>