2 # Global functions used everywhere
4 $wgNumberOfArticles = -1; # Unset
8 require_once( 'DatabaseFunctions.php' );
9 require_once( 'UpdateClasses.php' );
10 require_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 if( !function_exists('is_a') ) {
40 # Exists in PHP 4.2.0+
41 function is_a( $object, $class_name ) {
43 (strcasecmp( get_class( $object ), $class_name ) == 0) ||
44 is_subclass_of( $object, $class_name );
48 # html_entity_decode exists in PHP 4.3.0+ but is FATALLY BROKEN even then,
49 # with no UTF-8 support.
50 function do_html_entity_decode( $string, $quote_style=ENT_COMPAT
, $charset='ISO-8859-1' ) {
52 if( !isset( $trans ) ) {
53 $trans = array_flip( get_html_translation_table( HTML_ENTITIES
, $quote_style ) );
54 # Assumes $charset will always be the same through a run, and only understands
55 # utf-8 or default. Note - mixing latin1 named entities and unicode numbered
56 # ones will result in a bad link.
57 if( strcasecmp( 'utf-8', $charset ) == 0 ) {
58 $trans = array_map( 'utf8_encode', $trans );
61 return strtr( $string, $trans );
64 $wgRandomSeeded = false;
66 function wfSeedRandom()
68 global $wgRandomSeeded;
70 if ( ! $wgRandomSeeded ) {
71 $seed = hexdec(substr(md5(microtime()),-8)) & 0x7fffffff;
73 $wgRandomSeeded = true;
77 # Generates a URL from a URL-encoded title and a query string
78 # Title::getLocalURL() is preferred in most cases
80 function wfLocalUrl( $a, $q = '' )
82 global $wgServer, $wgScript, $wgArticlePath;
84 $a = str_replace( ' ', '_', $a );
90 $a = "{$wgScript}?{$q}";
92 } else if ( '' == $q ) {
93 $a = str_replace( "$1", $a, $wgArticlePath );
94 } else if ($wgScript != '' ) {
95 $a = "{$wgScript}?title={$a}&{$q}";
96 } else { //XXX hackish solution for toplevel wikis
102 function wfLocalUrlE( $a, $q = '' )
104 return wfEscapeHTML( wfLocalUrl( $a, $q ) );
105 # die( "Call to obsolete function wfLocalUrlE()" );
108 function wfFullUrl( $a, $q = '' ) {
109 wfDebugDieBacktrace( 'Call to obsolete function wfFullUrl(); use Title::getFullURL' );
112 function wfFullUrlE( $a, $q = '' ) {
113 wfDebugDieBacktrace( 'Call to obsolete function wfFullUrlE(); use Title::getFullUrlE' );
117 // orphan function wfThumbUrl( $img )
119 // global $wgUploadPath;
121 // $nt = Title::newFromText( $img );
122 // if( !$nt ) return "";
124 // $name = $nt->getDBkey();
125 // $hash = md5( $name );
127 // $url = "{$wgUploadPath}/thumb/" . $hash{0} . "/" .
128 // substr( $hash, 0, 2 ) . "/{$name}";
129 // return wfUrlencode( $url );
133 function wfImageArchiveUrl( $name )
135 global $wgUploadPath;
137 $hash = md5( substr( $name, 15) );
138 $url = "{$wgUploadPath}/archive/" . $hash{0} . "/" .
139 substr( $hash, 0, 2 ) . "/{$name}";
140 return wfUrlencode($url);
143 function wfUrlencode ( $s )
145 $s = urlencode( $s );
146 $s = preg_replace( '/%3[Aa]/', ':', $s );
147 $s = preg_replace( '/%2[Ff]/', '/', $s );
152 function wfUtf8Sequence($codepoint) {
153 if($codepoint < 0x80) return chr($codepoint);
154 if($codepoint < 0x800) return chr($codepoint >> 6 & 0x3f |
0xc0) .
155 chr($codepoint & 0x3f |
0x80);
156 if($codepoint < 0x10000) return chr($codepoint >> 12 & 0x0f |
0xe0) .
157 chr($codepoint >> 6 & 0x3f |
0x80) .
158 chr($codepoint & 0x3f |
0x80);
159 if($codepoint < 0x100000) return chr($codepoint >> 18 & 0x07 |
0xf0) . # Double-check this
160 chr($codepoint >> 12 & 0x3f |
0x80) .
161 chr($codepoint >> 6 & 0x3f |
0x80) .
162 chr($codepoint & 0x3f |
0x80);
163 # Doesn't yet handle outside the BMP
164 return "&#$codepoint;";
167 # Converts numeric character entities to UTF-8
168 function wfMungeToUtf8($string) {
169 global $wgInputEncoding; # This is debatable
170 #$string = iconv($wgInputEncoding, "UTF-8", $string);
171 $string = preg_replace ( '/&#([0-9]+);/e', 'wfUtf8Sequence($1)', $string );
172 $string = preg_replace ( '/&#x([0-9a-f]+);/ie', 'wfUtf8Sequence(0x$1)', $string );
173 # Should also do named entities here
177 # Converts a single UTF-8 character into the corresponding HTML character entity
178 function wfUtf8Entity( $matches ) {
181 $z = ord( $char{0} );
184 while ( $z & 0x80 ) {
192 if ( $length != strlen( $char ) ) {
195 if ( $length == 1 ) {
199 # Mask off the length-determining bits and shift back to the original location
203 # Add in the free bits from subsequent bytes
204 for ( $i=1; $i<$length; $i++
) {
206 $z |
= ord( $char{$i} ) & 0x3f;
213 # Converts all multi-byte characters in a UTF-8 string into the appropriate character entity
214 function wfUtf8ToHTML($string) {
215 return preg_replace_callback( '/[\\xc0-\\xfd][\\x80-\\xbf]*/', 'wfUtf8Entity', $string );
218 function wfDebug( $text, $logonly = false )
220 global $wgOut, $wgDebugLogFile, $wgDebugComments, $wgProfileOnly;
222 if ( isset( $wgOut ) && $wgDebugComments && !$logonly ) {
223 $wgOut->debug( $text );
225 if ( "" != $wgDebugLogFile && !$wgProfileOnly ) {
226 error_log( $text, 3, $wgDebugLogFile );
230 function logProfilingData()
232 global $wgRequestTime, $wgDebugLogFile;
233 global $wgProfiling, $wgProfileStack, $wgProfileLimit, $wgUser;
236 list( $usec, $sec ) = explode( " ", $wgRequestTime );
237 $start = (float)$sec +
(float)$usec;
238 $elapsed = $now - $start;
239 if ( $wgProfiling ) {
240 $prof = wfGetProfilingOutput( $start, $elapsed );
242 if( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) )
243 $forward = ' forwarded for ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
244 if( !empty( $_SERVER['HTTP_CLIENT_IP'] ) )
245 $forward .= ' client IP ' . $_SERVER['HTTP_CLIENT_IP'];
246 if( !empty( $_SERVER['HTTP_FROM'] ) )
247 $forward .= ' from ' . $_SERVER['HTTP_FROM'];
249 $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
250 if($wgUser->getId() == 0)
252 $log = sprintf( "%s\t%04.3f\t%s\n",
253 gmdate( 'YmdHis' ), $elapsed,
254 urldecode( $_SERVER['REQUEST_URI'] . $forward ) );
255 if ( '' != $wgDebugLogFile ) {
256 error_log( $log . $prof, 3, $wgDebugLogFile );
262 function wfReadOnly()
264 global $wgReadOnlyFile;
266 if ( "" == $wgReadOnlyFile ) { return false; }
267 return is_file( $wgReadOnlyFile );
270 $wgReplacementKeys = array( "$1", "$2", "$3", "$4", "$5", "$6", "$7", "$8", "$9" );
272 # Get a message from anywhere
273 function wfMsg( $key ) {
274 $args = func_get_args();
275 if ( count( $args ) ) {
276 array_shift( $args );
278 return wfMsgReal( $key, $args, true );
281 # Get a message from the language file
282 function wfMsgNoDB( $key ) {
283 $args = func_get_args();
284 if ( count( $args ) ) {
285 array_shift( $args );
287 return wfMsgReal( $key, $args, false );
290 # Really get a message
291 function wfMsgReal( $key, $args, $useDB ) {
292 global $wgReplacementKeys, $wgMessageCache, $wgLang;
295 wfProfileIn( $fname );
296 if ( $wgMessageCache ) {
297 $message = $wgMessageCache->get( $key, $useDB );
298 } elseif ( $wgLang ) {
299 $message = $wgLang->getMessage( $key );
301 wfDebug( "No language object when getting $key\n" );
302 $message = "<$key>";
306 if( count( $args ) ) {
307 $message = str_replace( $wgReplacementKeys, $args, $message );
309 wfProfileOut( $fname );
313 function wfCleanFormFields( $fields )
315 wfDebugDieBacktrace( 'Call to obsolete wfCleanFormFields(). Use wgRequest instead...' );
318 function wfMungeQuotes( $in )
320 $out = str_replace( '%', '%25', $in );
321 $out = str_replace( "'", '%27', $out );
322 $out = str_replace( '"', '%22', $out );
326 function wfDemungeQuotes( $in )
328 $out = str_replace( '%22', '"', $in );
329 $out = str_replace( '%27', "'", $out );
330 $out = str_replace( '%25', '%', $out );
334 function wfCleanQueryVar( $var )
336 wfDebugDieBacktrace( 'Call to obsolete function wfCleanQueryVar(); use wgRequest instead' );
339 function wfSearch( $s )
341 $se = new SearchEngine( $s );
346 { # pick the nearest match
347 $se = new SearchEngine( $s );
351 # Just like exit() but makes a note of it.
352 function wfAbruptExit(){
353 static $called = false;
359 if( function_exists( 'debug_backtrace' ) ){ // PHP >= 4.3
360 $bt = debug_backtrace();
361 for($i = 0; $i < count($bt) ; $i++
){
362 $file = $bt[$i]['file'];
363 $line = $bt[$i]['line'];
364 wfDebug("WARNING: Abrupt exit in $file at line $line\n");
367 wfDebug('WARNING: Abrupt exit\n');
372 function wfDebugDieBacktrace( $msg = '' ) {
373 global $wgCommandLineMode;
375 if ( function_exists( 'debug_backtrace' ) ) {
376 if ( $wgCommandLineMode ) {
377 $msg .= "\nBacktrace:\n";
379 $msg .= "\n<p>Backtrace:</p>\n<ul>\n";
381 $backtrace = debug_backtrace();
382 foreach( $backtrace as $call ) {
383 $f = explode( DIRECTORY_SEPARATOR
, $call['file'] );
384 $file = $f[count($f)-1];
385 if ( $wgCommandLineMode ) {
386 $msg .= "$file line {$call['line']}, in ";
388 $msg .= '<li>' . $file . " line " . $call['line'] . ', in ';
390 if( !empty( $call['class'] ) ) $msg .= $call['class'] . '::';
391 $msg .= $call['function'] . "()";
393 if ( $wgCommandLineMode ) {
403 function wfNumberOfArticles()
405 global $wgNumberOfArticles;
408 return $wgNumberOfArticles;
411 /* private */ function wfLoadSiteStats()
413 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
414 if ( -1 != $wgNumberOfArticles ) return;
416 $sql = 'SELECT ss_total_views, ss_total_edits, ss_good_articles ' .
417 'FROM site_stats WHERE ss_row_id=1';
418 $res = wfQuery( $sql, DB_READ
, 'wfLoadSiteStats' );
420 if ( 0 == wfNumRows( $res ) ) { return; }
422 $s = wfFetchObject( $res );
423 $wgTotalViews = $s->ss_total_views
;
424 $wgTotalEdits = $s->ss_total_edits
;
425 $wgNumberOfArticles = $s->ss_good_articles
;
429 function wfEscapeHTML( $in )
432 array( '&', '"', '>', '<' ),
433 array( '&', '"', '>', '<' ),
437 function wfEscapeHTMLTagsOnly( $in ) {
439 array( '"', '>', '<' ),
440 array( '"', '>', '<' ),
444 function wfUnescapeHTML( $in )
446 $in = str_replace( '<', '<', $in );
447 $in = str_replace( '>', '>', $in );
448 $in = str_replace( '"', '"', $in );
449 $in = str_replace( '&', '&', $in );
453 function wfImageDir( $fname )
455 global $wgUploadDirectory;
457 $hash = md5( $fname );
458 $oldumask = umask(0);
459 $dest = $wgUploadDirectory . '/' . $hash{0};
460 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
461 $dest .= '/' . substr( $hash, 0, 2 );
462 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
468 function wfImageThumbDir( $fname , $subdir='thumb')
470 return wfImageArchiveDir( $fname, $subdir );
473 function wfImageArchiveDir( $fname , $subdir='archive')
475 global $wgUploadDirectory;
477 $hash = md5( $fname );
478 $oldumask = umask(0);
480 # Suppress warning messages here; if the file itself can't
481 # be written we'll worry about it then.
482 $archive = "{$wgUploadDirectory}/{$subdir}";
483 if ( ! is_dir( $archive ) ) { @mkdir
( $archive, 0777 ); }
484 $archive .= '/' . $hash{0};
485 if ( ! is_dir( $archive ) ) { @mkdir
( $archive, 0777 ); }
486 $archive .= '/' . substr( $hash, 0, 2 );
487 if ( ! is_dir( $archive ) ) { @mkdir
( $archive, 0777 ); }
493 function wfRecordUpload( $name, $oldver, $size, $desc, $copyStatus = "", $source = "" )
495 global $wgUser, $wgLang, $wgTitle, $wgOut, $wgDeferredUpdateList;
496 global $wgUseCopyrightUpload;
498 $fname = 'wfRecordUpload';
500 $sql = 'SELECT img_name,img_size,img_timestamp,img_description,img_user,' .
501 "img_user_text FROM image WHERE img_name='" . wfStrencode( $name ) . "'";
502 $res = wfQuery( $sql, DB_READ
, $fname );
504 $now = wfTimestampNow();
505 $won = wfInvertTimestamp( $now );
506 $size = IntVal( $size );
508 if ( $wgUseCopyrightUpload )
510 $textdesc = '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $desc . "\n" .
511 '== ' . wfMsg ( 'filestatus' ) . " ==\n" . $copyStatus . "\n" .
512 '== ' . wfMsg ( 'filesource' ) . " ==\n" . $source ;
514 else $textdesc = $desc ;
516 $now = wfTimestampNow();
517 $won = wfInvertTimestamp( $now );
519 if ( 0 == wfNumRows( $res ) ) {
520 $sql = 'INSERT INTO image (img_name,img_size,img_timestamp,' .
521 "img_description,img_user,img_user_text) VALUES ('" .
522 wfStrencode( $name ) . "',$size,'{$now}','" .
523 wfStrencode( $desc ) . "', '" . $wgUser->getID() .
524 "', '" . wfStrencode( $wgUser->getName() ) . "')";
525 wfQuery( $sql, DB_WRITE
, $fname );
527 $sql = 'SELECT cur_id,cur_text FROM cur WHERE cur_namespace=' .
528 Namespace::getImage() . " AND cur_title='" .
529 wfStrencode( $name ) . "'";
530 $res = wfQuery( $sql, DB_READ
, $fname );
531 if ( 0 == wfNumRows( $res ) ) {
533 Namespace::getImage() . ",'" .
534 wfStrencode( $name ) . "','" .
535 wfStrencode( $desc ) . "','" . $wgUser->getID() . "','" .
536 wfStrencode( $wgUser->getName() ) . "','" . $now .
538 $sql = 'INSERT INTO cur (cur_namespace,cur_title,' .
539 'cur_comment,cur_user,cur_user_text,cur_timestamp,cur_is_new,' .
540 'cur_text,inverse_timestamp,cur_touched) VALUES (' .
542 ",'" . wfStrencode( $textdesc ) . "','{$won}','{$now}')";
543 wfQuery( $sql, DB_WRITE
, $fname );
544 $id = wfInsertId() or 0; # We should throw an error instead
546 $titleObj = Title
::makeTitle( NS_IMAGE
, $name );
547 RecentChange
::notifyNew( $now, $titleObj, 0, $wgUser, $desc );
549 $u = new SearchUpdate( $id, $name, $desc );
553 $s = wfFetchObject( $res );
555 $sql = 'INSERT INTO oldimage (oi_name,oi_archive_name,oi_size,' .
556 "oi_timestamp,oi_description,oi_user,oi_user_text) VALUES ('" .
557 wfStrencode( $s->img_name
) . "','" .
558 wfStrencode( $oldver ) .
559 "',{$s->img_size},'{$s->img_timestamp}','" .
560 wfStrencode( $s->img_description
) . "','" .
561 wfStrencode( $s->img_user
) . "','" .
562 wfStrencode( $s->img_user_text
) . "')";
563 wfQuery( $sql, DB_WRITE
, $fname );
565 $sql = "UPDATE image SET img_size={$size}," .
566 "img_timestamp='" . wfTimestampNow() . "',img_user='" .
567 $wgUser->getID() . "',img_user_text='" .
568 wfStrencode( $wgUser->getName() ) . "', img_description='" .
569 wfStrencode( $desc ) . "' WHERE img_name='" .
570 wfStrencode( $name ) . "'";
571 wfQuery( $sql, DB_WRITE
, $fname );
573 $sql = "UPDATE cur SET cur_touched='{$now}' WHERE cur_namespace=" .
574 Namespace::getImage() . " AND cur_title='" .
575 wfStrencode( $name ) . "'";
576 wfQuery( $sql, DB_WRITE
, $fname );
579 $log = new LogPage( wfMsg( 'uploadlogpage' ), wfMsg( 'uploadlogpagetext' ) );
580 $da = wfMsg( 'uploadedimage', '[[:' . $wgLang->getNsText(
581 Namespace::getImage() ) . ":{$name}|{$name}]]" );
582 $ta = wfMsg( 'uploadedimage', $name );
583 $log->addEntry( $da, $desc, $ta );
587 /* Some generic result counters, pulled out of SearchEngine */
589 function wfShowingResults( $offset, $limit )
592 return wfMsg( 'showingresults', $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+
1 ) );
595 function wfShowingResultsNum( $offset, $limit, $num )
598 return wfMsg( 'showingresultsnum', $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+
1 ), $wgLang->formatNum( $num ) );
601 function wfViewPrevNext( $offset, $limit, $link, $query = '', $atend = false )
603 global $wgUser, $wgLang;
604 $fmtLimit = $wgLang->formatNum( $limit );
605 $prev = wfMsg( 'prevn', $fmtLimit );
606 $next = wfMsg( 'nextn', $fmtLimit );
607 $link = wfUrlencode( $link );
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 = '' )
638 global $wgUser, $wgLang;
639 if ( '' == $query ) { $q = ''; }
640 else { $q = "{$query}&"; }
641 $q .= "limit={$limit}&offset={$offset}";
643 $fmtLimit = $wgLang->formatNum( $limit );
644 $s = '<a href="' . wfLocalUrlE( $link, $q ) . "\">{$fmtLimit}</a>";
648 function wfClientAcceptsGzip() {
651 # FIXME: we may want to blacklist some broken browsers
653 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
654 $_SERVER['HTTP_ACCEPT_ENCODING'],
656 if( ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) return false;
657 wfDebug( " accepts gzip\n" );
664 # Yay, more global functions!
665 function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) {
666 global $wgUser, $wgRequest;
668 $limit = $wgRequest->getInt( 'limit', 0 );
669 if( $limit < 0 ) $limit = 0;
670 if( ( $limit == 0 ) && ( $optionname != '' ) ) {
671 $limit = (int)$wgUser->getOption( $optionname );
673 if( $limit <= 0 ) $limit = $deflimit;
674 if( $limit > 5000 ) $limit = 5000; # We have *some* limits...
676 $offset = $wgRequest->getInt( 'offset', 0 );
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 );
718 $st = explode( ' ', microtime() );
719 return (float)$st[0] +
(float)$st[1];
722 # Changes the first character to an HTML entity
723 function wfHtmlEscapeFirst( $text ) {
725 $newText = substr($text, 1);
726 return "&#$ord;$newText";
729 # Sets dest to source and returns the original value of dest
730 function wfSetVar( &$dest, $source )
737 # Sets dest to a reference to source and returns the original dest
738 # Pity that doesn't work in PHP
739 function &wfSetRef( &$dest, &$source )
741 die( "You can't rebind a variable in the caller's scope" );
744 # This function takes two arrays as input, and returns a CGI-style string, e.g.
745 # "days=7&limit=100". Options in the first array override options in the second.
746 # Options set to "" will not be output.
747 function wfArrayToCGI( $array1, $array2 = NULL )
749 if ( !is_null( $array2 ) ) {
750 $array1 = $array1 +
$array2;
754 foreach ( $array1 as $key => $value ) {
755 if ( '' !== $value ) {
759 $cgi .= "{$key}={$value}";
765 # This is obsolete, use SquidUpdate::purge()
766 function wfPurgeSquidServers ($urlArr) {
767 SquidUpdate
::purge( $urlArr );
770 # Windows-compatible version of escapeshellarg()
771 function wfEscapeShellArg( )
773 $args = func_get_args();
776 foreach ( $args as $arg ) {
783 if ( wfIsWindows() ) {
784 $retVal .= '"' . str_replace( '"','\"', $arg ) . '"';
786 $retVal .= escapeshellarg( $arg );
792 # wfMerge attempts to merge differences between three texts.
793 # Returns true for a clean merge and false for failure or a conflict.
795 function wfMerge( $old, $mine, $yours, &$result ){
798 # This check may also protect against code injection in
799 # case of broken installations.
800 if(! file_exists( $wgDiff3 ) ){
804 # Make temporary files
806 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
807 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
808 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
810 fwrite( $oldtextFile, $old ); fclose( $oldtextFile );
811 fwrite( $mytextFile, $mine ); fclose( $mytextFile );
812 fwrite( $yourtextFile, $yours ); fclose( $yourtextFile );
814 # Check for a conflict
815 $cmd = wfEscapeShellArg( $wgDiff3 ) . ' -a --overlap-only ' .
816 wfEscapeShellArg( $mytextName ) . ' ' .
817 wfEscapeShellArg( $oldtextName ) . ' ' .
818 wfEscapeShellArg( $yourtextName );
819 $handle = popen( $cmd, 'r' );
821 if( fgets( $handle ) ){
829 $cmd = wfEscapeShellArg( $wgDiff3 ) . ' -a -e --merge ' .
830 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
831 $handle = popen( $cmd, 'r' );
834 $data = fread( $handle, 8192 );
835 if ( strlen( $data ) == 0 ) {
841 unlink( $mytextName ); unlink( $oldtextName ); unlink( $yourtextName );
845 function wfVarDump( $var )
848 $s = str_replace("\n","<br>\n", var_export( $var, true ) . "\n");
849 if ( headers_sent() ||
!@is_object
( $wgOut ) ) {
852 $wgOut->addHTML( $s );
856 # Provide a simple HTTP error.
857 function wfHttpError( $code, $label, $desc ) {
860 header( "HTTP/1.0 $code $label" );
861 header( "Status: $code $label" );
862 $wgOut->sendCacheControl();
864 # Don't send content if it's a HEAD request.
865 if( $_SERVER['REQUEST_METHOD'] == 'HEAD' ) {
866 header( 'Content-type: text/plain' );
871 # Converts an Accept-* header into an array mapping string values to quality factors
872 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
873 # No arg means accept anything (per HTTP spec)
875 return array( $def => 1 );
880 $parts = explode( ',', $accept );
882 foreach( $parts as $part ) {
883 # FIXME: doesn't deal with params like 'text/html; level=1'
884 @list
( $value, $qpart ) = explode( ';', $part );
885 if( !isset( $qpart ) ) {
887 } elseif( preg_match( '/q\s*=\s*(\d*\.\d+)/', $qpart, $match ) ) {
888 $prefs[$value] = $match[1];
895 /* private */ function mimeTypeMatch( $type, $avail ) {
896 if( array_key_exists($type, $avail) ) {
899 $parts = explode( '/', $type );
900 if( array_key_exists( $parts[0] . '/*', $avail ) ) {
901 return $parts[0] . '/*';
902 } elseif( array_key_exists( '*/*', $avail ) ) {
910 # FIXME: doesn't handle params like 'text/plain; charset=UTF-8'
911 # XXX: generalize to negotiate other stuff
912 function wfNegotiateType( $cprefs, $sprefs ) {
915 foreach( array_keys($sprefs) as $type ) {
916 $parts = explode( '/', $type );
917 if( $parts[1] != '*' ) {
918 $ckey = mimeTypeMatch( $type, $cprefs );
920 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
925 foreach( array_keys( $cprefs ) as $type ) {
926 $parts = explode( '/', $type );
927 if( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
928 $skey = mimeTypeMatch( $type, $sprefs );
930 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
938 foreach( array_keys( $combine ) as $type ) {
939 if( $combine[$type] > $bestq ) {
941 $bestq = $combine[$type];
949 # Returns an array where the values in the first array are replaced by the
950 # values in the second array with the corresponding keys
951 function wfArrayLookup( $a, $b )
953 return array_flip( array_intersect( array_flip( $a ), array_keys( $b ) ) );
956 # Since Windows is so different to any of the other popular OSes, it seems appropriate
957 # to have a simple way to test for its presence
958 function wfIsWindows() {
959 if (substr(php_uname(), 0, 7) == 'Windows') {