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