2 # Global functions used everywhere
4 $wgNumberOfArticles = -1; # Unset
8 include_once( "DatabaseFunctions.php" );
9 include_once( "UpdateClasses.php" );
10 include_once( "LogPage.php" );
13 * Compatibility functions
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.
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 );
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 ) );
39 $wgRandomSeeded = false;
41 function wfSeedRandom()
43 global $wgRandomSeeded;
45 if ( ! $wgRandomSeeded ) {
46 $seed = hexdec(substr(md5(microtime()),-8)) & 0x7fffffff;
48 $wgRandomSeeded = true;
52 # Generates a URL from a URL-encoded title and a query string
53 # Title::getURL() is preferred in most cases
55 function wfLocalUrl( $a, $q = "" )
57 global $wgServer, $wgScript, $wgArticlePath;
59 $a = str_replace( " ", "_", $a );
65 $a = "{$wgScript}?{$q}";
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
77 function wfLocalUrlE( $a, $q = "" )
79 return wfEscapeHTML( wfLocalUrl( $a, $q ) );
82 function wfFullUrl( $a, $q = "" ) {
83 $titleObj = Title
::newFromURL( $a );
84 return $titleObj->getURL( $q, false, true );
87 function wfFullUrlE( $a, $q = "" ) {
88 $titleObj = Title
::newFromURL( $a );
89 return $titleObj->getURL( $q, true, true );
93 function wfImageUrl( $img )
97 $nt = Title
::newFromText( $img );
100 $name = $nt->getDBkey();
101 $hash = md5( $name );
103 $url = "{$wgUploadPath}/" . $hash{0} . "/" .
104 substr( $hash, 0, 2 ) . "/{$name}";
105 return wfUrlencode( $url );
108 function wfImagePath( $img )
110 global $wgUploadDirectory;
112 $nt = Title
::newFromText( $img );
113 if( !$nt ) return "";
115 $name = $nt->getDBkey();
116 $hash = md5( $name );
118 $path = "{$wgUploadDirectory}/" . $hash{0} . "/" .
119 substr( $hash, 0, 2 ) . "/{$name}";
123 function wfThumbUrl( $img )
125 global $wgUploadPath;
127 $nt = Title
::newFromText( $img );
128 if( !$nt ) return "";
130 $name = $nt->getDBkey();
131 $hash = md5( $name );
133 $url = "{$wgUploadPath}/thumb/" . $hash{0} . "/" .
134 substr( $hash, 0, 2 ) . "/{$name}";
135 return wfUrlencode( $url );
139 function wfImageThumbUrl( $name, $subdir="thumb" )
141 global $wgUploadPath;
143 $hash = md5( $name );
144 $url = "{$wgUploadPath}/{$subdir}/" . $hash{0} . "/" .
145 substr( $hash, 0, 2 ) . "/{$name}";
146 return wfUrlencode($url);
149 function wfImageArchiveUrl( $name )
151 global $wgUploadPath;
153 $hash = md5( substr( $name, 15) );
154 $url = "{$wgUploadPath}/archive/" . $hash{0} . "/" .
155 substr( $hash, 0, 2 ) . "/{$name}";
156 return wfUrlencode($url);
159 function wfUrlencode ( $s )
161 $s = urlencode( $s );
162 $s = preg_replace( "/%3[Aa]/", ":", $s );
163 $s = preg_replace( "/%2[Ff]/", "/", $s );
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;";
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
192 function wfDebug( $text, $logonly = false )
194 global $wgOut, $wgDebugLogFile, $wgDebugComments, $wgProfileOnly;
196 if ( isset( $wgOut ) && $wgDebugComments && !$logonly ) {
197 $wgOut->debug( $text );
199 if ( "" != $wgDebugLogFile && !$wgProfileOnly ) {
200 error_log( $text, 3, $wgDebugLogFile );
204 function logProfilingData()
206 global $wgRequestTime, $wgDebugLogFile;
207 global $wgProfiling, $wgProfileStack, $wgProfileLimit, $wgUser;
210 list( $usec, $sec ) = explode( " ", $wgRequestTime );
211 $start = (float)$sec +
(float)$usec;
212 $elapsed = $now - $start;
213 if ( "" != $wgDebugLogFile ) {
214 $prof = wfGetProfilingOutput( $start, $elapsed );
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'];
223 $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
224 if($wgUser->getId() == 0)
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 );
234 function wfReadOnly()
236 global $wgReadOnlyFile;
238 if ( "" == $wgReadOnlyFile ) { return false; }
239 return is_file( $wgReadOnlyFile );
242 $wgReplacementKeys = array( "$1", "$2", "$3", "$4", "$5", "$6", "$7", "$8", "$9" );
244 # Get a message from anywhere
245 function wfMsg( $key ) {
246 $args = func_get_args();
247 if ( count( $args ) ) {
248 array_shift( $args );
250 return wfMsgReal( $key, $args, true );
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 );
259 return wfMsgReal( $key, $args, false );
262 # Really get a message
263 function wfMsgReal( $key, $args, $useDB ) {
264 global $wgReplacementKeys, $wgMessageCache, $wgLang;
267 wfProfileIn( $fname );
268 if ( $wgMessageCache ) {
269 $message = $wgMessageCache->get( $key, $useDB );
270 } elseif ( $wgLang ) {
271 $message = $wgLang->getMessage( $key );
273 wfDebug( "No language object when getting $key\n" );
274 $message = "<$key>";
278 if( count( $args ) ) {
279 $message = str_replace( $wgReplacementKeys, $args, $message );
281 wfProfileOut( $fname );
285 function wfCleanFormFields( $fields )
287 global $HTTP_POST_VARS;
288 global $wgInputEncoding, $wgOutputEncoding, $wgEditEncoding, $wgLang;
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] );
297 if ( isset( $
{$fname} ) ) {
298 $
{$fname} = stripslashes( $
{$fname} );
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] );
312 if ( isset( $
{$fname} ) ) {
313 $
{$fname} = $wgLang->iconv(
314 $enc, $wgInputEncoding, $
{$fname} );
320 function wfMungeQuotes( $in )
322 $out = str_replace( "%", "%25", $in );
323 $out = str_replace( "'", "%27", $out );
324 $out = str_replace( "\"", "%22", $out );
328 function wfDemungeQuotes( $in )
330 $out = str_replace( "%22", "\"", $in );
331 $out = str_replace( "%27", "'", $out );
332 $out = str_replace( "%25", "%", $out );
336 function wfCleanQueryVar( $var )
339 if ( get_magic_quotes_gpc() ) {
340 $var = stripslashes( $var );
342 return $wgLang->recodeInput( $var );
345 function wfSpecialPage()
347 global $wgUser, $wgOut, $wgTitle, $wgLang;
349 /* FIXME: this list probably shouldn't be language-specific, per se */
350 $validSP = $wgLang->getValidSpecialPages();
351 $sysopSP = $wgLang->getSysopSpecialPages();
352 $devSP = $wgLang->getDeveloperSpecialPages();
354 $wgOut->setArticleRelated( false );
355 $wgOut->setRobotpolicy( "noindex,follow" );
358 list($t, $par) = split( "/", $wgTitle->getDBkey(), 2 );
360 if ( array_key_exists( $t, $validSP ) ||
361 ( $wgUser->isSysop() && array_key_exists( $t, $sysopSP ) ) ||
362 ( $wgUser->isDeveloper() && array_key_exists( $t, $devSP ) ) ) {
364 $wgTitle = Title
::makeTitle( Namespace::getSpecial(), $t );
366 $wgOut->setPageTitle( wfMsg( strtolower( $wgTitle->getText() ) ) );
368 $inc = "Special" . $t . ".php";
369 include_once( $inc );
370 $call = "wfSpecial" . $t;
372 } else if ( array_key_exists( $t, $sysopSP ) ) {
373 $wgOut->sysopRequired();
374 } else if ( array_key_exists( $t, $devSP ) ) {
375 $wgOut->developerRequired();
377 $wgOut->errorpage( "nosuchspecialpage", "nospecialpagetext" );
381 function wfSearch( $s )
383 $se = new SearchEngine( wfCleanQueryVar( $s ) );
388 { # pick the nearest match
389 $se = new SearchEngine( wfCleanQueryVar( $s ) );
393 # Just like exit() but makes a note of it.
394 function wfAbruptExit(){
395 static $called = false;
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");
409 wfDebug("WARNING: Abrupt exit\n");
414 function wfNumberOfArticles()
416 global $wgNumberOfArticles;
419 return $wgNumberOfArticles;
422 /* private */ function wfLoadSiteStats()
424 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
425 if ( -1 != $wgNumberOfArticles ) return;
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" );
431 if ( 0 == wfNumRows( $res ) ) { return; }
433 $s = wfFetchObject( $res );
434 $wgTotalViews = $s->ss_total_views
;
435 $wgTotalEdits = $s->ss_total_edits
;
436 $wgNumberOfArticles = $s->ss_good_articles
;
440 function wfEscapeHTML( $in )
443 array( "&", "\"", ">", "<" ),
444 array( "&", """, ">", "<" ),
448 function wfEscapeHTMLTagsOnly( $in ) {
450 array( "\"", ">", "<" ),
451 array( """, ">", "<" ),
455 function wfUnescapeHTML( $in )
457 $in = str_replace( "<", "<", $in );
458 $in = str_replace( ">", ">", $in );
459 $in = str_replace( """, "\"", $in );
460 $in = str_replace( "&", "&", $in );
464 function wfImageDir( $fname )
466 global $wgUploadDirectory;
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 ); }
479 function wfImageThumbDir( $fname , $subdir="thumb")
481 return wfImageArchiveDir( $fname, $subdir );
484 function wfImageArchiveDir( $fname , $subdir="archive")
486 global $wgUploadDirectory;
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 ); }
501 function wfRecordUpload( $name, $oldver, $size, $desc )
503 global $wgUser, $wgLang, $wgTitle, $wgOut, $wgDeferredUpdateList;
504 global $wgUseCopyrightUpload , $wpUploadCopyStatus , $wpUploadSource ;
506 $fname = "wfRecordUpload";
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 );
512 $now = wfTimestampNow();
513 $won = wfInvertTimestamp( $now );
514 $size = IntVal( $size );
516 if ( $wgUseCopyrightUpload )
518 $textdesc = "== " . wfMsg ( "filedesc" ) . " ==\n" . $desc . "\n" .
519 "== " . wfMsg ( "filestatus" ) . " ==\n" . $wpUploadCopyStatus . "\n" .
520 "== " . wfMsg ( "filesource" ) . " ==\n" . $wpUploadSource ;
522 else $textdesc = $desc ;
524 $now = wfTimestampNow();
525 $won = wfInvertTimestamp( $now );
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 );
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 ) ) {
541 Namespace::getImage() . ",'" .
542 wfStrencode( $name ) . "','" .
543 wfStrencode( $desc ) . "','" . $wgUser->getID() . "','" .
544 wfStrencode( $wgUser->getName() ) . "','" . $now .
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 (" .
550 ",'" . wfStrencode( $textdesc ) . "','{$won}','{$now}')";
551 wfQuery( $sql, DB_WRITE
, $fname );
552 $id = wfInsertId() or 0; # We should throw an error instead
554 $titleObj = Title
::makeTitle( NS_IMAGE
, $name );
555 RecentChange
::notifyNew( $now, $titleObj, 0, $wgUser, $desc );
557 $u = new SearchUpdate( $id, $name, $desc );
561 $s = wfFetchObject( $res );
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 );
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 );
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 );
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 );
595 /* Some generic result counters, pulled out of SearchEngine */
597 function wfShowingResults( $offset, $limit )
600 return wfMsg( "showingresults", $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+
1 ) );
603 function wfShowingResultsNum( $offset, $limit, $num )
606 return wfMsg( "showingresultsnum", $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+
1 ), $wgLang->formatNum( $num ) );
609 function wfViewPrevNext( $offset, $limit, $link, $query = "", $atend = false )
611 global $wgUser, $wgLang;
612 $fmtLimit = $wgLang->formatNum( $limit );
613 $prev = wfMsg( "prevn", $fmtLimit );
614 $next = wfMsg( "nextn", $fmtLimit );
615 $link = wfUrlencode( $link );
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; }
626 $no = $offset +
$limit;
627 $q = "limit={$limit}&offset={$no}";
628 if ( "" != $query ) { $q .= "&{$query}"; }
633 $nlink = "<a href=\"" . wfLocalUrlE( $link, $q ) . "\">{$next}</a>";
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 );
641 return wfMsg( "viewprevnext", $plink, $nlink, $nums );
644 function wfNumLink( $offset, $limit, $link, $query = "" )
646 global $wgUser, $wgLang;
647 if ( "" == $query ) { $q = ""; }
648 else { $q = "{$query}&"; }
649 $q .= "limit={$limit}&offset={$offset}";
651 $fmtLimit = $wgLang->formatNum( $limit );
652 $s = "<a href=\"" . wfLocalUrlE( $link, $q ) . "\">{$fmtLimit}</a>";
656 function wfClientAcceptsGzip() {
659 # FIXME: we may want to blacklist some broken browsers
661 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
662 $_SERVER["HTTP_ACCEPT_ENCODING"],
664 if( ( $m[1] == "q" ) && ( $m[2] == 0 ) ) return false;
665 wfDebug( " accepts gzip\n" );
672 # Yay, more global functions!
673 function wfCheckLimits( $deflimit = 50, $optionname = "rclimit" ) {
676 $limit = (int)$_REQUEST['limit'];
677 if( $limit < 0 ) $limit = 0;
678 if( ( $limit == 0 ) && ( $optionname != "" ) ) {
679 $limit = (int)$wgUser->getOption( $optionname );
681 if( $limit <= 0 ) $limit = $deflimit;
682 if( $limit > 5000 ) $limit = 5000; # We have *some* limits...
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?
689 return array( $limit, $offset );
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 )
701 array( '[', '|', "'", 'ISBN ' , '://' , "\n=" ),
702 array( '[', '|', ''', 'ISBN ', '://' , "\n=" ),
703 htmlspecialchars($text) );
707 function wfQuotedPrintable( $string, $charset = "" )
709 # Probably incomplete; see RFC 2045
710 if( empty( $charset ) ) {
711 global $wgInputEncoding;
712 $charset = $wgInputEncoding;
714 $charset = strtoupper( $charset );
715 $charset = str_replace( "ISO-8859", "ISO8859", $charset ); // ?
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 );
727 $st = explode( " ", microtime() );
728 return (float)$st[0] +
(float)$st[1];
731 # Changes the first character to an HTML entity
732 function wfHtmlEscapeFirst( $text ) {
734 $newText = substr($text, 1);
735 return "&#$ord;$newText";
738 # Sets dest to source and returns the original value of dest
739 function wfSetVar( &$dest, $source )
746 # Sets dest to a reference to source and returns the original dest
747 function &wfSetRef( &$dest, &$source )
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 )
759 if ( !is_null( $array2 ) ) {
760 $array1 = $array1 +
$array2;
764 foreach ( $array1 as $key => $value ) {
765 if ( "" !== $value ) {
769 $cgi .= "{$key}={$value}";
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 */
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;
792 $totalsockets = count($wgSquidServers) * $sockspersq;
795 /* this sets up the sockets and tests the first socket for each server. */
796 for ($ss=0;$ss < count($wgSquidServers);$ss++
) {
799 while ($so < $sockspersq && !$failed) {
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);
807 $totalsockets -= $sockspersq;
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) {
817 $totalsockets -= $sockspersq;
819 @stream_set_blocking
($socket,false);
820 $sockets[] = $socket;
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);
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++
) {
841 while (strlen($res) < 100 && $esc < 20 ) {
842 $res .= @fread
($sockets[$s],512);
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");
853 foreach ($sockets as $socket) {