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 function wfLocalUrl( $a, $q = "" )
54 global $wgServer, $wgScript, $wgArticlePath;
56 $a = str_replace( " ", "_", $a );
57 #$a = wfUrlencode( $a ); # This stuff is _already_ URL-encoded.
63 $a = "{$wgScript}?{$q}";
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
75 function wfLocalUrlE( $a, $q = "" )
77 return wfEscapeHTML( wfLocalUrl( $a, $q ) );
80 function wfFullUrl( $a, $q = "" ) {
82 return $wgServer . wfLocalUrl( $a, $q );
85 function wfFullUrlE( $a, $q = "" ) {
86 return wfEscapeHTML( wfFullUrl( $a, $q ) );
89 function wfImageUrl( $img )
93 $nt = Title
::newFromText( $img );
96 $name = $nt->getDBkey();
99 $url = "{$wgUploadPath}/" . $hash{0} . "/" .
100 substr( $hash, 0, 2 ) . "/{$name}";
101 return wfUrlencode( $url );
104 function wfImagePath( $img )
106 global $wgUploadDirectory;
108 $nt = Title
::newFromText( $img );
109 if( !$nt ) return "";
111 $name = $nt->getDBkey();
112 $hash = md5( $name );
114 $path = "{$wgUploadDirectory}/" . $hash{0} . "/" .
115 substr( $hash, 0, 2 ) . "/{$name}";
119 function wfThumbUrl( $img )
121 global $wgUploadPath;
123 $nt = Title
::newFromText( $img );
124 if( !$nt ) return "";
126 $name = $nt->getDBkey();
127 $hash = md5( $name );
129 $url = "{$wgUploadPath}/thumb/" . $hash{0} . "/" .
130 substr( $hash, 0, 2 ) . "/{$name}";
131 return wfUrlencode( $url );
135 function wfImageThumbUrl( $name, $subdir="thumb" )
137 global $wgUploadPath;
139 $hash = md5( $name );
140 $url = "{$wgUploadPath}/{$subdir}/" . $hash{0} . "/" .
141 substr( $hash, 0, 2 ) . "/{$name}";
142 return wfUrlencode($url);
145 function wfImageArchiveUrl( $name )
147 global $wgUploadPath;
149 $hash = md5( substr( $name, 15) );
150 $url = "{$wgUploadPath}/archive/" . $hash{0} . "/" .
151 substr( $hash, 0, 2 ) . "/{$name}";
152 return wfUrlencode($url);
155 function wfUrlencode ( $s )
157 $ulink = urlencode( $s );
158 $ulink = preg_replace( "/%3[Aa]/", ":", $ulink );
159 $ulink = preg_replace( "/%2[Ff]/", "/", $ulink );
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;";
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
187 function wfDebug( $text, $logonly = false )
189 global $wgOut, $wgDebugLogFile, $wgDebugComments, $wgProfileOnly;
191 if ( $wgDebugComments && !$logonly ) {
192 $wgOut->debug( $text );
194 if ( "" != $wgDebugLogFile && !$wgProfileOnly ) {
195 error_log( $text, 3, $wgDebugLogFile );
199 function logProfilingData()
201 global $wgRequestTime, $wgDebugLogFile;
202 global $wgProfiling, $wgProfileStack, $wgProfileLimit, $wgUser;
203 list( $usec, $sec ) = explode( " ", microtime() );
204 $now = (float)$sec +
(float)$usec;
206 list( $usec, $sec ) = explode( " ", $wgRequestTime );
207 $start = (float)$sec +
(float)$usec;
208 $elapsed = $now - $start;
209 if ( "" != $wgDebugLogFile ) {
210 $prof = wfGetProfilingOutput( $start, $elapsed );
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'];
219 $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
220 if($wgUser->getId() == 0)
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 );
230 function wfReadOnly()
232 global $wgReadOnlyFile;
234 if ( "" == $wgReadOnlyFile ) { return false; }
235 return is_file( $wgReadOnlyFile );
238 $wgReplacementKeys = array( "$1", "$2", "$3", "$4", "$5", "$6", "$7", "$8", "$9" );
240 # Get a message from anywhere
241 function wfMsg( $key ) {
242 $args = func_get_args();
243 if ( count( $args ) ) {
244 array_shift( $args );
246 return wfMsgReal( $key, $args, true );
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 );
255 return wfMsgReal( $key, $args, false );
258 # Really get a message
259 function wfMsgReal( $key, $args, $useDB ) {
260 global $wgReplacementKeys, $wgMessageCache, $wgLang;
263 wfProfileIn( $fname );
264 if ( $wgMessageCache ) {
265 $message = $wgMessageCache->get( $key, $useDB );
266 } elseif ( $wgLang ) {
267 $message = $wgLang->getMessage( $key );
269 wfDebug( "No language object when getting $key\n" );
270 $message = "<$key>";
274 if( count( $args ) ) {
275 $message = str_replace( $wgReplacementKeys, $args, $message );
277 wfProfileOut( $fname );
281 function wfCleanFormFields( $fields )
283 global $HTTP_POST_VARS;
284 global $wgInputEncoding, $wgOutputEncoding, $wgEditEncoding, $wgLang;
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] );
293 if ( isset( $
{$fname} ) ) {
294 $
{$fname} = stripslashes( $
{$fname} );
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] );
308 if ( isset( $
{$fname} ) ) {
309 $
{$fname} = $wgLang->iconv(
310 $enc, $wgInputEncoding, $
{$fname} );
316 function wfMungeQuotes( $in )
318 $out = str_replace( "%", "%25", $in );
319 $out = str_replace( "'", "%27", $out );
320 $out = str_replace( "\"", "%22", $out );
324 function wfDemungeQuotes( $in )
326 $out = str_replace( "%22", "\"", $in );
327 $out = str_replace( "%27", "'", $out );
328 $out = str_replace( "%25", "%", $out );
332 function wfCleanQueryVar( $var )
335 if ( get_magic_quotes_gpc() ) {
336 $var = stripslashes( $var );
338 return $wgLang->recodeInput( $var );
341 function wfSpecialPage()
343 global $wgUser, $wgOut, $wgTitle, $wgLang;
345 /* FIXME: this list probably shouldn't be language-specific, per se */
346 $validSP = $wgLang->getValidSpecialPages();
347 $sysopSP = $wgLang->getSysopSpecialPages();
348 $devSP = $wgLang->getDeveloperSpecialPages();
350 $wgOut->setArticleRelated( false );
351 $wgOut->setRobotpolicy( "noindex,follow" );
354 list($t, $par) = split( "/", $wgTitle->getDBkey(), 2 );
356 if ( array_key_exists( $t, $validSP ) ||
357 ( $wgUser->isSysop() && array_key_exists( $t, $sysopSP ) ) ||
358 ( $wgUser->isDeveloper() && array_key_exists( $t, $devSP ) ) ) {
360 $wgTitle = Title
::makeTitle( Namespace::getSpecial(), $t );
362 $wgOut->setPageTitle( wfMsg( strtolower( $wgTitle->getText() ) ) );
364 $inc = "Special" . $t . ".php";
365 include_once( $inc );
366 $call = "wfSpecial" . $t;
368 } else if ( array_key_exists( $t, $sysopSP ) ) {
369 $wgOut->sysopRequired();
370 } else if ( array_key_exists( $t, $devSP ) ) {
371 $wgOut->developerRequired();
373 $wgOut->errorpage( "nosuchspecialpage", "nospecialpagetext" );
377 function wfSearch( $s )
379 $se = new SearchEngine( wfCleanQueryVar( $s ) );
384 { # pick the nearest match
385 $se = new SearchEngine( wfCleanQueryVar( $s ) );
389 # Just like exit() but makes a note of it.
390 function wfAbruptExit(){
391 static $called = false;
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");
405 wfDebug("WARNING: Abrupt exit\n");
410 function wfNumberOfArticles()
412 global $wgNumberOfArticles;
415 return $wgNumberOfArticles;
418 /* private */ function wfLoadSiteStats()
420 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
421 if ( -1 != $wgNumberOfArticles ) return;
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" );
427 if ( 0 == wfNumRows( $res ) ) { return; }
429 $s = wfFetchObject( $res );
430 $wgTotalViews = $s->ss_total_views
;
431 $wgTotalEdits = $s->ss_total_edits
;
432 $wgNumberOfArticles = $s->ss_good_articles
;
436 function wfEscapeHTML( $in )
439 array( "&", "\"", ">", "<" ),
440 array( "&", """, ">", "<" ),
444 function wfEscapeHTMLTagsOnly( $in ) {
446 array( "\"", ">", "<" ),
447 array( """, ">", "<" ),
451 function wfUnescapeHTML( $in )
453 $in = str_replace( "<", "<", $in );
454 $in = str_replace( ">", ">", $in );
455 $in = str_replace( """, "\"", $in );
456 $in = str_replace( "&", "&", $in );
460 function wfImageDir( $fname )
462 global $wgUploadDirectory;
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 ); }
475 function wfImageThumbDir( $fname , $subdir="thumb")
477 return wfImageArchiveDir( $fname, $subdir );
480 function wfImageArchiveDir( $fname , $subdir="archive")
482 global $wgUploadDirectory;
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 ); }
497 function wfRecordUpload( $name, $oldver, $size, $desc )
499 global $wgUser, $wgLang, $wgTitle, $wgOut, $wgDeferredUpdateList;
500 global $wgUseCopyrightUpload , $wpUploadCopyStatus , $wpUploadSource ;
502 $fname = "wfRecordUpload";
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 );
508 $now = wfTimestampNow();
509 $won = wfInvertTimestamp( $now );
510 $size = IntVal( $size );
512 if ( $wgUseCopyrightUpload )
514 $textdesc = "== " . wfMsg ( "filedesc" ) . " ==\n" . $desc . "\n" .
515 "== " . wfMsg ( "filestatus" ) . " ==\n" . $wpUploadCopyStatus . "\n" .
516 "== " . wfMsg ( "filesource" ) . " ==\n" . $wpUploadSource ;
518 else $textdesc = $desc ;
520 $now = wfTimestampNow();
521 $won = wfInvertTimestamp( $now );
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 );
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 ) ) {
537 Namespace::getImage() . ",'" .
538 wfStrencode( $name ) . "','" .
539 wfStrencode( $desc ) . "','" . $wgUser->getID() . "','" .
540 wfStrencode( $wgUser->getName() ) . "','" . $now .
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 (" .
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 );
557 $s = wfFetchObject( $res );
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 );
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 );
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 );
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 );
591 /* Some generic result counters, pulled out of SearchEngine */
593 function wfShowingResults( $offset, $limit )
595 return wfMsg( "showingresults", $limit, $offset+
1 );
598 function wfShowingResultsNum( $offset, $limit, $num )
600 return wfMsg( "showingresultsnum", $limit, $offset+
1, $num );
603 function wfViewPrevNext( $offset, $limit, $link, $query = "", $atend = false )
606 $prev = wfMsg( "prevn", $limit );
607 $next = wfMsg( "nextn", $limit );
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; }
618 $no = $offset +
$limit;
619 $q = "limit={$limit}&offset={$no}";
620 if ( "" != $query ) { $q .= "&{$query}"; }
625 $nlink = "<a href=\"" . wfLocalUrlE( $link, $q ) . "\">{$next}</a>";
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 );
633 return wfMsg( "viewprevnext", $plink, $nlink, $nums );
636 function wfNumLink( $offset, $limit, $link, $query = "" )
639 if ( "" == $query ) { $q = ""; }
640 else { $q = "{$query}&"; }
641 $q .= "limit={$limit}&offset={$offset}";
643 $s = "<a href=\"" . wfLocalUrlE( $link, $q ) . "\">{$limit}</a>";
647 function wfClientAcceptsGzip() {
650 # FIXME: we may want to blacklist some broken browsers
652 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
653 $_SERVER["HTTP_ACCEPT_ENCODING"],
655 if( ( $m[1] == "q" ) && ( $m[2] == 0 ) ) return false;
656 wfDebug( " accepts gzip\n" );
663 # Yay, more global functions!
664 function wfCheckLimits( $deflimit = 50, $optionname = "rclimit" ) {
667 $limit = (int)$_REQUEST['limit'];
668 if( $limit < 0 ) $limit = 0;
669 if( ( $limit == 0 ) && ( $optionname != "" ) ) {
670 $limit = (int)$wgUser->getOption( $optionname );
672 if( $limit <= 0 ) $limit = $deflimit;
673 if( $limit > 5000 ) $limit = 5000; # We have *some* limits...
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?
680 return array( $limit, $offset );
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 )
692 array( '[', '|', "'", 'ISBN ' , '://' , "\n=" ),
693 array( '[', '|', ''', 'ISBN ', '://' , "\n=" ),
694 htmlspecialchars($text) );
698 function wfQuotedPrintable( $string, $charset = "" )
700 # Probably incomplete; see RFC 2045
701 if( empty( $charset ) ) {
702 global $wgInputEncoding;
703 $charset = $wgInputEncoding;
705 $charset = strtoupper( $charset );
706 $charset = str_replace( "ISO-8859", "ISO8859", $charset ); // ?
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 );
717 # Changes the first character to an HTML entity
718 function wfHtmlEscapeFirst( $text ) {
720 $newText = substr($text, 1);
721 return "&#$ord;$newText";
724 function wfSetVar( &$dest, $source )
731 function &wfSetRef( &$dest, $source )
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 )
743 if ( !is_null( $array2 ) ) {
744 $array1 = $array1 +
$array2;
748 foreach ( $array1 as $key => $value ) {
749 if ( "" !== $value ) {
753 $cgi .= "{$key}={$value}";
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 */
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;
776 $totalsockets = count($wgSquidServers) * $sockspersq;
779 /* this sets up the sockets and tests the first socket for each server. */
780 for ($ss=0;$ss < count($wgSquidServers);$ss++
) {
783 while ($so < $sockspersq && !$failed) {
785 /* first socket for this server, do the tests */
786 $socket = @fsockopen
($wgSquidServers[$ss], 80, $error, $errstr, 3);
789 $totalsockets -= $sockspersq;
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) {
799 $totalsockets -= $sockspersq;
801 @stream_set_blocking
($socket,false);
802 $sockets[] = $socket;
806 /* open the remaining sockets for this server */
807 $sockets[] = @fsockopen
($wgSquidServers[$ss], 80, $error, $errstr, 2);
808 @stream_set_blocking
($sockets[$s],false);
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++
) {
821 while (strlen($res) < 100 && $esc < 20 ) {
822 $res .= @fread
($sockets[$s],512);
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");
833 foreach ($sockets as $socket) {