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