now for the real thing- previous submit was a small hack to make it work without...
[lhc/web/wiklou.git] / includes / GlobalFunctions.php
1 <?
2 # Global functions used everywhere
3
4 $wgNumberOfArticles = -1; # Unset
5 $wgTotalViews = -1;
6 $wgTotalEdits = -1;
7
8 include_once( "DatabaseFunctions.php" );
9 include_once( "UpdateClasses.php" );
10 include_once( "LogPage.php" );
11
12 /*
13 * Compatibility functions
14 */
15
16 # PHP <4.3.x is not actively supported; 4.1.x and 4.2.x might or might not work.
17 # <4.1.x will not work, as we use a number of features introduced in 4.1.0
18 # such as the new autoglobals.
19
20 if( !function_exists('iconv') ) {
21 # iconv support is not in the default configuration and so may not be present.
22 # Assume will only ever use utf-8 and iso-8859-1.
23 # This will *not* work in all circumstances.
24 function iconv( $from, $to, $string ) {
25 if(strcasecmp( $from, $to ) == 0) return $string;
26 if(strcasecmp( $from, "utf-8" ) == 0) return utf8_decode( $string );
27 if(strcasecmp( $to, "utf-8" ) == 0) return utf8_encode( $string );
28 return $string;
29 }
30 }
31
32 if( !function_exists('file_get_contents') ) {
33 # Exists in PHP 4.3.0+
34 function file_get_contents( $filename ) {
35 return implode( "", file( $filename ) );
36 }
37 }
38
39 $wgRandomSeeded = false;
40
41 function wfSeedRandom()
42 {
43 global $wgRandomSeeded;
44
45 if ( ! $wgRandomSeeded ) {
46 $seed = hexdec(substr(md5(microtime()),-8)) & 0x7fffffff;
47 mt_srand( $seed );
48 $wgRandomSeeded = true;
49 }
50 }
51
52 function wfLocalUrl( $a, $q = "" )
53 {
54 global $wgServer, $wgScript, $wgArticlePath;
55
56 $a = str_replace( " ", "_", $a );
57 #$a = wfUrlencode( $a ); # This stuff is _already_ URL-encoded.
58
59 if ( "" == $a ) {
60 if( "" == $q ) {
61 $a = $wgScript;
62 } else {
63 $a = "{$wgScript}?{$q}";
64 }
65 } else if ( "" == $q ) {
66 $a = str_replace( "$1", $a, $wgArticlePath );
67 } else {
68 $a = "{$wgScript}?title={$a}&{$q}";
69 }
70 return $a;
71 }
72
73 function wfLocalUrlE( $a, $q = "" )
74 {
75 return wfEscapeHTML( wfLocalUrl( $a, $q ) );
76 }
77
78 function wfFullUrl( $a, $q = "" ) {
79 global $wgServer;
80 return $wgServer . wfLocalUrl( $a, $q );
81 }
82
83 function wfFullUrlE( $a, $q = "" ) {
84 return wfEscapeHTML( wfFullUrl( $a, $q ) );
85 }
86
87 function wfImageUrl( $img )
88 {
89 global $wgUploadPath;
90
91 $nt = Title::newFromText( $img );
92 if( !$nt ) return "";
93
94 $name = $nt->getDBkey();
95 $hash = md5( $name );
96
97 $url = "{$wgUploadPath}/" . $hash{0} . "/" .
98 substr( $hash, 0, 2 ) . "/{$name}";
99 return wfUrlencode( $url );
100 }
101
102 function wfImagePath( $img )
103 {
104 global $wgUploadDirectory;
105
106 $nt = Title::newFromText( $img );
107 if( !$nt ) return "";
108
109 $name = $nt->getDBkey();
110 $hash = md5( $name );
111
112 $url = "{$wgUploadDirectory}/" . $hash{0} . "/" .
113 substr( $hash, 0, 2 ) . "/{$name}";
114 return wfUrlencode( $url );
115 }
116
117 function wfThumbUrl( $img )
118 {
119 global $wgUploadPath;
120
121 $nt = Title::newFromText( $img );
122 if( !$nt ) return "";
123
124 $name = $nt->getDBkey();
125 $hash = md5( $name );
126
127 $url = "{$wgUploadPath}/thumb/" . $hash{0} . "/" .
128 substr( $hash, 0, 2 ) . "/{$name}";
129 return wfUrlencode( $url );
130 }
131
132
133 function wfImageArchiveUrl( $name, $subdir="archive" )
134 {
135 global $wgUploadPath;
136
137 $hash = md5( $name );
138 $url = "{$wgUploadPath}/{$subdir}/" . $hash{0} . "/" .
139 substr( $hash, 0, 2 ) . "/{$name}";
140 return $url;
141 }
142
143 function wfUrlencode ( $s )
144 {
145 $ulink = urlencode( $s );
146 $ulink = preg_replace( "/%3[Aa]/", ":", $ulink );
147 $ulink = preg_replace( "/%2[Ff]/", "/", $ulink );
148 return $ulink;
149 }
150
151 function wfUtf8Sequence($codepoint) {
152 if($codepoint < 0x80) return chr($codepoint);
153 if($codepoint < 0x800) return chr($codepoint >> 6 & 0x3f | 0xc0) .
154 chr($codepoint & 0x3f | 0x80);
155 if($codepoint < 0x10000) return chr($codepoint >> 12 & 0x0f | 0xe0) .
156 chr($codepoint >> 6 & 0x3f | 0x80) .
157 chr($codepoint & 0x3f | 0x80);
158 if($codepoint < 0x100000) return chr($codepoint >> 18 & 0x07 | 0xf0) . # Double-check this
159 chr($codepoint >> 12 & 0x3f | 0x80) .
160 chr($codepoint >> 6 & 0x3f | 0x80) .
161 chr($codepoint & 0x3f | 0x80);
162 # Doesn't yet handle outside the BMP
163 return "&#$codepoint;";
164 }
165
166 function wfMungeToUtf8($string) {
167 global $wgInputEncoding; # This is debatable
168 #$string = iconv($wgInputEncoding, "UTF-8", $string);
169 $string = preg_replace ( '/&#([0-9]+);/e', 'wfUtf8Sequence($1)', $string );
170 $string = preg_replace ( '/&#x([0-9a-f]+);/ie', 'wfUtf8Sequence(0x$1)', $string );
171 # Should also do named entities here
172 return $string;
173 }
174
175 function wfDebug( $text, $logonly = false )
176 {
177 global $wgOut, $wgDebugLogFile, $wgDebugComments, $wgProfileOnly;
178
179 if ( $wgDebugComments && !$logonly ) {
180 $wgOut->debug( $text );
181 }
182 if ( "" != $wgDebugLogFile && !$wgProfileOnly ) {
183 error_log( $text, 3, $wgDebugLogFile );
184 }
185 }
186
187 function logProfilingData()
188 {
189 global $wgRequestTime, $wgDebugLogFile;
190 global $wgProfiling, $wgProfileStack, $wgProfileLimit, $wgUser;
191 list( $usec, $sec ) = explode( " ", microtime() );
192 $now = (float)$sec + (float)$usec;
193
194 list( $usec, $sec ) = explode( " ", $wgRequestTime );
195 $start = (float)$sec + (float)$usec;
196 $elapsed = $now - $start;
197 if ( "" != $wgDebugLogFile ) {
198 $prof = wfGetProfilingOutput( $start, $elapsed );
199 $forward = "";
200 if( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) )
201 $forward = " forwarded for " . $_SERVER['HTTP_X_FORWARDED_FOR'];
202 if( !empty( $_SERVER['HTTP_CLIENT_IP'] ) )
203 $forward .= " client IP " . $_SERVER['HTTP_CLIENT_IP'];
204 if( !empty( $_SERVER['HTTP_FROM'] ) )
205 $forward .= " from " . $_SERVER['HTTP_FROM'];
206 if( $forward )
207 $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
208 if($wgUser->getId() == 0)
209 $forward .= " anon";
210 $log = sprintf( "%s\t%04.3f\t%s\n",
211 gmdate( "YmdHis" ), $elapsed,
212 urldecode( $_SERVER['REQUEST_URI'] . $forward ) );
213 error_log( $log . $prof, 3, $wgDebugLogFile );
214 }
215 }
216
217
218 function wfReadOnly()
219 {
220 global $wgReadOnlyFile;
221
222 if ( "" == $wgReadOnlyFile ) { return false; }
223 return is_file( $wgReadOnlyFile );
224 }
225
226 $wgReplacementKeys = array( "$1", "$2", "$3", "$4", "$5", "$6", "$7", "$8", "$9" );
227
228 # Get a message from anywhere
229 function wfMsg( $key ) {
230 $args = func_get_args();
231 if ( count( $args ) ) {
232 array_shift( $args );
233 }
234 return wfMsgReal( $key, $args, true );
235 }
236
237 # Get a message from the language file
238 function wfMsgNoDB( $key ) {
239 $args = func_get_args();
240 if ( count( $args ) ) {
241 array_shift( $args );
242 }
243 return wfMsgReal( $key, $args, false );
244 }
245
246 # Really get a message
247 function wfMsgReal( $key, $args, $useDB ) {
248 global $wgReplacementKeys, $wgMessageCache, $wgLang;
249
250 $fname = "wfMsg";
251 wfProfileIn( $fname );
252 if ( $wgMessageCache ) {
253 $message = $wgMessageCache->get( $key, $useDB );
254 } elseif ( $wgLang ) {
255 $message = $wgLang->getMessage( $key );
256 } else {
257 wfDebug( "No language object when getting $key\n" );
258 $message = "&lt;$key&gt;";
259 }
260
261 # Replace arguments
262 if( count( $args ) ) {
263 $message = str_replace( $wgReplacementKeys, $args, $message );
264 }
265 wfProfileOut( $fname );
266 return $message;
267 }
268
269 function wfCleanFormFields( $fields )
270 {
271 global $HTTP_POST_VARS;
272 global $wgInputEncoding, $wgOutputEncoding, $wgEditEncoding, $wgLang;
273
274 if ( get_magic_quotes_gpc() ) {
275 foreach ( $fields as $fname ) {
276 if ( isset( $HTTP_POST_VARS[$fname] ) ) {
277 $HTTP_POST_VARS[$fname] = stripslashes(
278 $HTTP_POST_VARS[$fname] );
279 }
280 global ${$fname};
281 if ( isset( ${$fname} ) ) {
282 ${$fname} = stripslashes( ${$fname} );
283 }
284 }
285 }
286 $enc = $wgOutputEncoding;
287 if( $wgEditEncoding != "") $enc = $wgEditEncoding;
288 if ( $enc != $wgInputEncoding ) {
289 foreach ( $fields as $fname ) {
290 if ( isset( $HTTP_POST_VARS[$fname] ) ) {
291 $HTTP_POST_VARS[$fname] = $wgLang->iconv(
292 $wgOutputEncoding, $wgInputEncoding,
293 $HTTP_POST_VARS[$fname] );
294 }
295 global ${$fname};
296 if ( isset( ${$fname} ) ) {
297 ${$fname} = $wgLang->iconv(
298 $enc, $wgInputEncoding, ${$fname} );
299 }
300 }
301 }
302 }
303
304 function wfMungeQuotes( $in )
305 {
306 $out = str_replace( "%", "%25", $in );
307 $out = str_replace( "'", "%27", $out );
308 $out = str_replace( "\"", "%22", $out );
309 return $out;
310 }
311
312 function wfDemungeQuotes( $in )
313 {
314 $out = str_replace( "%22", "\"", $in );
315 $out = str_replace( "%27", "'", $out );
316 $out = str_replace( "%25", "%", $out );
317 return $out;
318 }
319
320 function wfCleanQueryVar( $var )
321 {
322 global $wgLang;
323 if ( get_magic_quotes_gpc() ) {
324 $var = stripslashes( $var );
325 }
326 return $wgLang->recodeInput( $var );
327 }
328
329 function wfSpecialPage()
330 {
331 global $wgUser, $wgOut, $wgTitle, $wgLang;
332
333 /* FIXME: this list probably shouldn't be language-specific, per se */
334 $validSP = $wgLang->getValidSpecialPages();
335 $sysopSP = $wgLang->getSysopSpecialPages();
336 $devSP = $wgLang->getDeveloperSpecialPages();
337
338 $wgOut->setArticleRelated( false );
339 $wgOut->setRobotpolicy( "noindex,follow" );
340
341 $par = NULL;
342 list($t, $par) = split( "/", $wgTitle->getDBkey(), 2 );
343
344 if ( array_key_exists( $t, $validSP ) ||
345 ( $wgUser->isSysop() && array_key_exists( $t, $sysopSP ) ) ||
346 ( $wgUser->isDeveloper() && array_key_exists( $t, $devSP ) ) ) {
347 if($par !== NULL)
348 $wgTitle = Title::makeTitle( Namespace::getSpecial(), $t );
349
350 $wgOut->setPageTitle( wfMsg( strtolower( $wgTitle->getText() ) ) );
351
352 $inc = "Special" . $t . ".php";
353 include_once( $inc );
354 $call = "wfSpecial" . $t;
355 $call( $par );
356 } else if ( array_key_exists( $t, $sysopSP ) ) {
357 $wgOut->sysopRequired();
358 } else if ( array_key_exists( $t, $devSP ) ) {
359 $wgOut->developerRequired();
360 } else {
361 $wgOut->errorpage( "nosuchspecialpage", "nospecialpagetext" );
362 }
363 }
364
365 function wfSearch( $s )
366 {
367 $se = new SearchEngine( wfCleanQueryVar( $s ) );
368 $se->showResults();
369 }
370
371 function wfGo( $s )
372 { # pick the nearest match
373 $se = new SearchEngine( wfCleanQueryVar( $s ) );
374 $se->goResult();
375 }
376
377 # Just like exit() but makes a note of it.
378 function wfAbruptExit(){
379 static $called = false;
380 if ( $called ){
381 exit();
382 }
383 $called = true;
384
385 if( function_exists( "debug_backtrace" ) ){ // PHP >= 4.3
386 $bt = debug_backtrace();
387 for($i = 0; $i < count($bt) ; $i++){
388 $file = $bt[$i]["file"];
389 $line = $bt[$i]["line"];
390 wfDebug("WARNING: Abrupt exit in $file at line $line\n");
391 }
392 } else {
393 wfDebug("WARNING: Abrupt exit\n");
394 }
395 exit();
396 }
397
398 function wfNumberOfArticles()
399 {
400 global $wgNumberOfArticles;
401
402 wfLoadSiteStats();
403 return $wgNumberOfArticles;
404 }
405
406 /* private */ function wfLoadSiteStats()
407 {
408 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
409 if ( -1 != $wgNumberOfArticles ) return;
410
411 $sql = "SELECT ss_total_views, ss_total_edits, ss_good_articles " .
412 "FROM site_stats WHERE ss_row_id=1";
413 $res = wfQuery( $sql, DB_READ, "wfLoadSiteStats" );
414
415 if ( 0 == wfNumRows( $res ) ) { return; }
416 else {
417 $s = wfFetchObject( $res );
418 $wgTotalViews = $s->ss_total_views;
419 $wgTotalEdits = $s->ss_total_edits;
420 $wgNumberOfArticles = $s->ss_good_articles;
421 }
422 }
423
424 function wfEscapeHTML( $in )
425 {
426 return str_replace(
427 array( "&", "\"", ">", "<" ),
428 array( "&amp;", "&quot;", "&gt;", "&lt;" ),
429 $in );
430 }
431
432 function wfEscapeHTMLTagsOnly( $in ) {
433 return str_replace(
434 array( "\"", ">", "<" ),
435 array( "&quot;", "&gt;", "&lt;" ),
436 $in );
437 }
438
439 function wfUnescapeHTML( $in )
440 {
441 $in = str_replace( "&lt;", "<", $in );
442 $in = str_replace( "&gt;", ">", $in );
443 $in = str_replace( "&quot;", "\"", $in );
444 $in = str_replace( "&amp;", "&", $in );
445 return $in;
446 }
447
448 function wfImageDir( $fname )
449 {
450 global $wgUploadDirectory;
451
452 $hash = md5( $fname );
453 $oldumask = umask(0);
454 $dest = $wgUploadDirectory . "/" . $hash{0};
455 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
456 $dest .= "/" . substr( $hash, 0, 2 );
457 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
458
459 umask( $oldumask );
460 return $dest;
461 }
462
463 function wfImageArchiveDir( $fname , $subdir="archive")
464 {
465 global $wgUploadDirectory;
466
467 $hash = md5( $fname );
468 $oldumask = umask(0);
469 $archive = "{$wgUploadDirectory}/{$subdir}";
470 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
471 $archive .= "/" . $hash{0};
472 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
473 $archive .= "/" . substr( $hash, 0, 2 );
474 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
475
476 umask( $oldumask );
477 return $archive;
478 }
479
480 function wfRecordUpload( $name, $oldver, $size, $desc )
481 {
482 global $wgUser, $wgLang, $wgTitle, $wgOut, $wgDeferredUpdateList;
483 global $wgUseCopyrightUpload , $wpUploadCopyStatus , $wpUploadSource ;
484
485 $fname = "wfRecordUpload";
486
487 $sql = "SELECT img_name,img_size,img_timestamp,img_description,img_user," .
488 "img_user_text FROM image WHERE img_name='" . wfStrencode( $name ) . "'";
489 $res = wfQuery( $sql, DB_READ, $fname );
490
491 $now = wfTimestampNow();
492 $won = wfInvertTimestamp( $now );
493 $size = IntVal( $size );
494
495 if ( $wgUseCopyrightUpload )
496 {
497 $textdesc = "== " . wfMsg ( "filedesc" ) . " ==\n" . $desc . "\n" .
498 "== " . wfMsg ( "filestatus" ) . " ==\n" . $wpUploadCopyStatus . "\n" .
499 "== " . wfMsg ( "filesource" ) . " ==\n" . $wpUploadSource ;
500 }
501 else $textdesc = $desc ;
502
503 $now = wfTimestampNow();
504 $won = wfInvertTimestamp( $now );
505
506 if ( 0 == wfNumRows( $res ) ) {
507 $sql = "INSERT INTO image (img_name,img_size,img_timestamp," .
508 "img_description,img_user,img_user_text) VALUES ('" .
509 wfStrencode( $name ) . "',$size,'{$now}','" .
510 wfStrencode( $desc ) . "', '" . $wgUser->getID() .
511 "', '" . wfStrencode( $wgUser->getName() ) . "')";
512 wfQuery( $sql, DB_WRITE, $fname );
513
514 $sql = "SELECT cur_id,cur_text FROM cur WHERE cur_namespace=" .
515 Namespace::getImage() . " AND cur_title='" .
516 wfStrencode( $name ) . "'";
517 $res = wfQuery( $sql, DB_READ, $fname );
518 if ( 0 == wfNumRows( $res ) ) {
519 $common =
520 Namespace::getImage() . ",'" .
521 wfStrencode( $name ) . "','" .
522 wfStrencode( $desc ) . "','" . $wgUser->getID() . "','" .
523 wfStrencode( $wgUser->getName() ) . "','" . $now .
524 "',1";
525 $sql = "INSERT INTO cur (cur_namespace,cur_title," .
526 "cur_comment,cur_user,cur_user_text,cur_timestamp,cur_is_new," .
527 "cur_text,inverse_timestamp,cur_touched) VALUES (" .
528 $common .
529 ",'" . wfStrencode( $textdesc ) . "','{$won}','{$now}')";
530 wfQuery( $sql, DB_WRITE, $fname );
531 $id = wfInsertId() or 0; # We should throw an error instead
532 $sql = "INSERT INTO recentchanges (rc_namespace,rc_title,
533 rc_comment,rc_user,rc_user_text,rc_timestamp,rc_new,
534 rc_cur_id,rc_cur_time) VALUES ({$common},{$id},'{$now}')";
535 wfQuery( $sql, DB_WRITE, $fname );
536 $u = new SearchUpdate( $id, $name, $desc );
537 $u->doUpdate();
538 }
539 } else {
540 $s = wfFetchObject( $res );
541
542 $sql = "INSERT INTO oldimage (oi_name,oi_archive_name,oi_size," .
543 "oi_timestamp,oi_description,oi_user,oi_user_text) VALUES ('" .
544 wfStrencode( $s->img_name ) . "','" .
545 wfStrencode( $oldver ) .
546 "',{$s->img_size},'{$s->img_timestamp}','" .
547 wfStrencode( $s->img_description ) . "','" .
548 wfStrencode( $s->img_user ) . "','" .
549 wfStrencode( $s->img_user_text) . "')";
550 wfQuery( $sql, DB_WRITE, $fname );
551
552 $sql = "UPDATE image SET img_size={$size}," .
553 "img_timestamp='" . wfTimestampNow() . "',img_user='" .
554 $wgUser->getID() . "',img_user_text='" .
555 wfStrencode( $wgUser->getName() ) . "', img_description='" .
556 wfStrencode( $desc ) . "' WHERE img_name='" .
557 wfStrencode( $name ) . "'";
558 wfQuery( $sql, DB_WRITE, $fname );
559
560 $sql = "UPDATE cur SET cur_touched='{$now}' WHERE cur_namespace=" .
561 Namespace::getImage() . " AND cur_title='" .
562 wfStrencode( $name ) . "'";
563 wfQuery( $sql, DB_WRITE, $fname );
564 }
565
566 $log = new LogPage( wfMsg( "uploadlogpage" ), wfMsg( "uploadlogpagetext" ) );
567 $da = wfMsg( "uploadedimage", "[[:" . $wgLang->getNsText(
568 Namespace::getImage() ) . ":{$name}|{$name}]]" );
569 $ta = wfMsg( "uploadedimage", $name );
570 $log->addEntry( $da, $desc, $ta );
571 }
572
573
574 /* Some generic result counters, pulled out of SearchEngine */
575
576 function wfShowingResults( $offset, $limit )
577 {
578 return wfMsg( "showingresults", $limit, $offset+1 );
579 }
580
581 function wfShowingResultsNum( $offset, $limit, $num )
582 {
583 return wfMsg( "showingresultsnum", $limit, $offset+1, $num );
584 }
585
586 function wfViewPrevNext( $offset, $limit, $link, $query = "", $atend = false )
587 {
588 global $wgUser;
589 $prev = wfMsg( "prevn", $limit );
590 $next = wfMsg( "nextn", $limit );
591
592 $sk = $wgUser->getSkin();
593 if ( 0 != $offset ) {
594 $po = $offset - $limit;
595 if ( $po < 0 ) { $po = 0; }
596 $q = "limit={$limit}&offset={$po}";
597 if ( "" != $query ) { $q .= "&{$query}"; }
598 $plink = "<a href=\"" . wfLocalUrlE( $link, $q ) . "\">{$prev}</a>";
599 } else { $plink = $prev; }
600
601 $no = $offset + $limit;
602 $q = "limit={$limit}&offset={$no}";
603 if ( "" != $query ) { $q .= "&{$query}"; }
604
605 if ( $atend ) {
606 $nlink = $next;
607 } else {
608 $nlink = "<a href=\"" . wfLocalUrlE( $link, $q ) . "\">{$next}</a>";
609 }
610 $nums = wfNumLink( $offset, 20, $link , $query ) . " | " .
611 wfNumLink( $offset, 50, $link, $query ) . " | " .
612 wfNumLink( $offset, 100, $link, $query ) . " | " .
613 wfNumLink( $offset, 250, $link, $query ) . " | " .
614 wfNumLink( $offset, 500, $link, $query );
615
616 return wfMsg( "viewprevnext", $plink, $nlink, $nums );
617 }
618
619 function wfNumLink( $offset, $limit, $link, $query = "" )
620 {
621 global $wgUser;
622 if ( "" == $query ) { $q = ""; }
623 else { $q = "{$query}&"; }
624 $q .= "limit={$limit}&offset={$offset}";
625
626 $s = "<a href=\"" . wfLocalUrlE( $link, $q ) . "\">{$limit}</a>";
627 return $s;
628 }
629
630 function wfClientAcceptsGzip() {
631 global $wgUseGzip;
632 if( $wgUseGzip ) {
633 # FIXME: we may want to blacklist some broken browsers
634 if( preg_match(
635 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
636 $_SERVER["HTTP_ACCEPT_ENCODING"],
637 $m ) ) {
638 if( ( $m[1] == "q" ) && ( $m[2] == 0 ) ) return false;
639 wfDebug( " accepts gzip\n" );
640 return true;
641 }
642 }
643 return false;
644 }
645
646 # Yay, more global functions!
647 function wfCheckLimits( $deflimit = 50, $optionname = "rclimit" ) {
648 global $wgUser;
649
650 $limit = (int)$_REQUEST['limit'];
651 if( $limit < 0 ) $limit = 0;
652 if( ( $limit == 0 ) && ( $optionname != "" ) ) {
653 $limit = (int)$wgUser->getOption( $optionname );
654 }
655 if( $limit <= 0 ) $limit = $deflimit;
656 if( $limit > 5000 ) $limit = 5000; # We have *some* limits...
657
658 $offset = (int)$_REQUEST['offset'];
659 $offset = (int)$offset;
660 if( $offset < 0 ) $offset = 0;
661 if( $offset > 65000 ) $offset = 65000; # do we need a max? what?
662
663 return array( $limit, $offset );
664 }
665
666 # Escapes the given text so that it may be output using addWikiText()
667 # without any linking, formatting, etc. making its way through. This
668 # is achieved by substituting certain characters with HTML entities.
669 # As required by the callers, <nowiki> is not used. It currently does
670 # not filter out characters which have special meaning only at the
671 # start of a line, such as "*".
672 function wfEscapeWikiText( $text )
673 {
674 $text = str_replace(
675 array( '[', '|', "'", 'ISBN ' , '://' , "\n=" ),
676 array( '&#91;', '&#124;', '&#39;', 'ISBN&#32;', '&#58;//' , "\n&#61;" ),
677 htmlspecialchars($text) );
678 return $text;
679 }
680
681 function wfQuotedPrintable( $string, $charset = "" )
682 {
683 # Probably incomplete; see RFC 2045
684 if( empty( $charset ) ) {
685 global $wgInputEncoding;
686 $charset = $wgInputEncoding;
687 }
688 $charset = strtoupper( $charset );
689 $charset = str_replace( "ISO-8859", "ISO8859", $charset ); // ?
690
691 $illegal = '\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\xff=';
692 $replace = $illegal . '\t ?_';
693 if( !preg_match( "/[$illegal]/", $string ) ) return $string;
694 $out = "=?$charset?Q?";
695 $out .= preg_replace( "/([$replace])/e", 'sprintf("=%02X",ord("$1"))', $string );
696 $out .= "?=";
697 return $out;
698 }
699
700 # Changes the first character to an HTML entity
701 function wfHtmlEscapeFirst( $text ) {
702 $ord = ord($text);
703 $newText = substr($text, 1);
704 return "&#$ord;$newText";
705 }
706
707 function wfSetVar( &$dest, $source )
708 {
709 $temp = $dest;
710 $dest = $source;
711 return $temp;
712 }
713
714 function &wfSetRef( &$dest, $source )
715 {
716 $temp =& $dest;
717 $dest =& $source;
718 return $temp;
719 }
720
721 # This function takes two arrays as input, and returns a CGI-style string, e.g.
722 # "days=7&limit=100". Options in the first array override options in the second.
723 # Options set to "" will not be output.
724 function wfArrayToCGI( $array1, $array2 = NULL )
725 {
726 if ( !is_null( $array2 ) ) {
727 $array1 = $array1 + $array2;
728 }
729
730 $cgi = "";
731 foreach ( $array1 as $key => $value ) {
732 if ( "" !== $value ) {
733 if ( "" != $cgi ) {
734 $cgi .= "&";
735 }
736 $cgi .= "{$key}={$value}";
737 }
738 }
739 return $cgi;
740 }
741
742 /* Purges a list of Squids defined in $wgSquidServers.
743 $urlArr should contain the full URLs to purge as values
744 (example: $urlArr[] = 'http://my.host/something')
745 XXX report broken Squids per mail or log */
746
747 function wfPurgeSquidServers ($urlArr) {
748 global $wgSquidServers;
749 $maxsocketspersquid = 8; // socket cap per Squid
750 $urlspersocket = 400; // 400 seems to be a good tradeoff, opening a socket takes a while
751 $sockspersq = ceil(count($urlArr) / $urlspersocket );
752 if ($sockspersq == 1) {
753 /* the most common case */
754 $urlspersocket = count($urlArr);
755 } else if ($sockspersq > $maxsocketspersquid ) {
756 $urlspersocket = ceil(count($urlArr) / $maxsocketspersquid);
757 $sockspersq = $maxsocketspersquid;
758 }
759 $totalsockets = count($wgSquidServers) * $sockspersq;
760 $sockets = Array();
761
762 /* this sets up the sockets and tests the first socket for each server. */
763 for ($ss=0;$ss < count($wgSquidServers);$ss++) {
764 $failed = false;
765 $so = 0;
766 while ($so < $sockspersq && !$failed) {
767 if ($so == 0) {
768 /* first socket for this server, do the tests */
769 $socket = @fsockopen($wgSquidServers[$ss], 80, $error, $errstr, 3);
770 if (!$socket) {
771 $failed = true;
772 $totalsockets -= $sockspersq;
773 } else {
774 @fputs($socket,"PURGE " . $urlArr[0] . " HTTP/1.0\r\n".
775 "Connection: Keep-Alive\r\n\r\n");
776 $res = '';
777 while (strlen($res) < 230 ) {
778 $res .= @fread($socket,512);
779 }
780 /* Squid only returns http headers with 200 or 404 status,
781 if there's more returned something's wrong */
782 if (strlen($res) > 250) {
783 fclose($socket);
784 $failed = true;
785 $totalsockets -= $sockspersq;
786 } else {
787 @stream_set_blocking($socket,false);
788 $sockets[] = $socket;
789 }
790 }
791 } else {
792 /* open the remaining sockets for this server */
793 $sockets[] = @fsockopen($wgSquidServers[$ss], 80, $error, $errstr, 2);
794 @stream_set_blocking($sockets[$s],false);
795 }
796 $so++;
797 }
798 }
799
800 if ($urlspersocket > 1) {
801 /* now do the heavy lifting. The fread() relies on Squid returning only the headers */
802 for ($r=0;$r < $urlspersocket;$r++) {
803 for ($s=0;$s < $totalsockets;$s++) {
804 if($r != 0) {
805 $res = '';
806 while (strlen($res) < 230 ) {
807 $res .= @fread($sockets[$s],512);
808 }
809 }
810 $urindex = $r + $urlspersocket * ($s - $sockspersq * floor($s / $sockspersq));
811 @fputs($sockets[$s],"PURGE " . $urlArr[$urindex] . " HTTP/1.0\r\n".
812 "Connection: Keep-Alive\r\n\r\n");
813 }
814 }
815 }
816
817 foreach ($sockets as $socket) {
818 @fclose($sockets);
819 }
820 return;
821 }
822 ?>