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