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