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 $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::getLocalURL() 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 ) );
80 # die( "Call to obsolete function wfLocalUrlE()" );
83 function wfFullUrl( $a, $q = "" ) {
84 wfDebugDieBacktrace( "Call to obsolete function wfFullUrl(); use Title::getFullURL" );
87 function wfFullUrlE( $a, $q = "" ) {
88 wfDebugDieBacktrace( "Call to obsolete function wfFullUrlE(); use Title::getFullUrlE" );
92 // orphan function wfThumbUrl( $img )
94 // global $wgUploadPath;
96 // $nt = Title::newFromText( $img );
97 // if( !$nt ) return "";
99 // $name = $nt->getDBkey();
100 // $hash = md5( $name );
102 // $url = "{$wgUploadPath}/thumb/" . $hash{0} . "/" .
103 // substr( $hash, 0, 2 ) . "/{$name}";
104 // return wfUrlencode( $url );
108 function wfImageArchiveUrl( $name )
110 global $wgUploadPath;
112 $hash = md5( substr( $name, 15) );
113 $url = "{$wgUploadPath}/archive/" . $hash{0} . "/" .
114 substr( $hash, 0, 2 ) . "/{$name}";
115 return wfUrlencode($url);
118 function wfUrlencode ( $s )
120 $s = urlencode( $s );
121 $s = preg_replace( "/%3[Aa]/", ":", $s );
122 $s = preg_replace( "/%2[Ff]/", "/", $s );
127 function wfUtf8Sequence($codepoint) {
128 if($codepoint < 0x80) return chr($codepoint);
129 if($codepoint < 0x800) return chr($codepoint >> 6 & 0x3f |
0xc0) .
130 chr($codepoint & 0x3f |
0x80);
131 if($codepoint < 0x10000) return chr($codepoint >> 12 & 0x0f |
0xe0) .
132 chr($codepoint >> 6 & 0x3f |
0x80) .
133 chr($codepoint & 0x3f |
0x80);
134 if($codepoint < 0x100000) return chr($codepoint >> 18 & 0x07 |
0xf0) . # Double-check this
135 chr($codepoint >> 12 & 0x3f |
0x80) .
136 chr($codepoint >> 6 & 0x3f |
0x80) .
137 chr($codepoint & 0x3f |
0x80);
138 # Doesn't yet handle outside the BMP
139 return "&#$codepoint;";
142 function wfMungeToUtf8($string) {
143 global $wgInputEncoding; # This is debatable
144 #$string = iconv($wgInputEncoding, "UTF-8", $string);
145 $string = preg_replace ( '/&#([0-9]+);/e', 'wfUtf8Sequence($1)', $string );
146 $string = preg_replace ( '/&#x([0-9a-f]+);/ie', 'wfUtf8Sequence(0x$1)', $string );
147 # Should also do named entities here
151 function wfDebug( $text, $logonly = false )
153 global $wgOut, $wgDebugLogFile, $wgDebugComments, $wgProfileOnly;
155 if ( isset( $wgOut ) && $wgDebugComments && !$logonly ) {
156 $wgOut->debug( $text );
158 if ( "" != $wgDebugLogFile && !$wgProfileOnly ) {
159 error_log( $text, 3, $wgDebugLogFile );
163 function logProfilingData()
165 global $wgRequestTime, $wgDebugLogFile;
166 global $wgProfiling, $wgProfileStack, $wgProfileLimit, $wgUser;
169 list( $usec, $sec ) = explode( " ", $wgRequestTime );
170 $start = (float)$sec +
(float)$usec;
171 $elapsed = $now - $start;
172 if ( "" != $wgDebugLogFile ) {
173 $prof = wfGetProfilingOutput( $start, $elapsed );
175 if( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) )
176 $forward = " forwarded for " . $_SERVER['HTTP_X_FORWARDED_FOR'];
177 if( !empty( $_SERVER['HTTP_CLIENT_IP'] ) )
178 $forward .= " client IP " . $_SERVER['HTTP_CLIENT_IP'];
179 if( !empty( $_SERVER['HTTP_FROM'] ) )
180 $forward .= " from " . $_SERVER['HTTP_FROM'];
182 $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
183 if($wgUser->getId() == 0)
185 $log = sprintf( "%s\t%04.3f\t%s\n",
186 gmdate( "YmdHis" ), $elapsed,
187 urldecode( $_SERVER['REQUEST_URI'] . $forward ) );
188 error_log( $log . $prof, 3, $wgDebugLogFile );
193 function wfReadOnly()
195 global $wgReadOnlyFile;
197 if ( "" == $wgReadOnlyFile ) { return false; }
198 return is_file( $wgReadOnlyFile );
201 $wgReplacementKeys = array( "$1", "$2", "$3", "$4", "$5", "$6", "$7", "$8", "$9" );
203 # Get a message from anywhere
204 function wfMsg( $key ) {
205 $args = func_get_args();
206 if ( count( $args ) ) {
207 array_shift( $args );
209 return wfMsgReal( $key, $args, true );
212 # Get a message from the language file
213 function wfMsgNoDB( $key ) {
214 $args = func_get_args();
215 if ( count( $args ) ) {
216 array_shift( $args );
218 return wfMsgReal( $key, $args, false );
221 # Really get a message
222 function wfMsgReal( $key, $args, $useDB ) {
223 global $wgReplacementKeys, $wgMessageCache, $wgLang;
226 wfProfileIn( $fname );
227 if ( $wgMessageCache ) {
228 $message = $wgMessageCache->get( $key, $useDB );
229 } elseif ( $wgLang ) {
230 $message = $wgLang->getMessage( $key );
232 wfDebug( "No language object when getting $key\n" );
233 $message = "<$key>";
237 if( count( $args ) ) {
238 $message = str_replace( $wgReplacementKeys, $args, $message );
240 wfProfileOut( $fname );
244 function wfCleanFormFields( $fields )
246 wfDebugDieBacktrace( "Call to obsolete wfCleanFormFields(). Use wgRequest instead..." );
249 function wfMungeQuotes( $in )
251 $out = str_replace( "%", "%25", $in );
252 $out = str_replace( "'", "%27", $out );
253 $out = str_replace( "\"", "%22", $out );
257 function wfDemungeQuotes( $in )
259 $out = str_replace( "%22", "\"", $in );
260 $out = str_replace( "%27", "'", $out );
261 $out = str_replace( "%25", "%", $out );
265 function wfCleanQueryVar( $var )
267 wfDebugDieBacktrace( "Call to obsolete function wfCleanQueryVar(); use wgRequest instead" );
270 function wfSpecialPage()
272 global $wgUser, $wgOut, $wgTitle, $wgLang;
274 /* FIXME: this list probably shouldn't be language-specific, per se */
275 $validSP = $wgLang->getValidSpecialPages();
276 $sysopSP = $wgLang->getSysopSpecialPages();
277 $devSP = $wgLang->getDeveloperSpecialPages();
279 $wgOut->setArticleRelated( false );
280 $wgOut->setRobotpolicy( "noindex,follow" );
282 $bits = split( "/", $wgTitle->getDBkey(), 2 );
284 if( empty( $bits[1] ) ) {
290 if ( array_key_exists( $t, $validSP ) ||
291 ( $wgUser->isSysop() && array_key_exists( $t, $sysopSP ) ) ||
292 ( $wgUser->isDeveloper() && array_key_exists( $t, $devSP ) ) ) {
294 $wgTitle = Title
::makeTitle( Namespace::getSpecial(), $t );
296 $wgOut->setPageTitle( wfMsg( strtolower( $wgTitle->getText() ) ) );
298 $inc = "Special" . $t . ".php";
299 require_once( $inc );
300 $call = "wfSpecial" . $t;
302 } else if ( array_key_exists( $t, $sysopSP ) ) {
303 $wgOut->sysopRequired();
304 } else if ( array_key_exists( $t, $devSP ) ) {
305 $wgOut->developerRequired();
307 $wgOut->errorpage( "nosuchspecialpage", "nospecialpagetext" );
311 function wfSearch( $s )
313 $se = new SearchEngine( $s );
318 { # pick the nearest match
319 $se = new SearchEngine( $s );
323 # Just like exit() but makes a note of it.
324 function wfAbruptExit(){
325 static $called = false;
331 if( function_exists( "debug_backtrace" ) ){ // PHP >= 4.3
332 $bt = debug_backtrace();
333 for($i = 0; $i < count($bt) ; $i++
){
334 $file = $bt[$i]["file"];
335 $line = $bt[$i]["line"];
336 wfDebug("WARNING: Abrupt exit in $file at line $line\n");
339 wfDebug("WARNING: Abrupt exit\n");
344 function wfDebugDieBacktrace( $msg = "" ) {
345 $msg .= "\n<p>Backtrace:</p>\n<ul>\n";
346 $backtrace = debug_backtrace();
347 foreach( $backtrace as $call ) {
348 $f = explode( DIRECTORY_SEPARATOR
, $call['file'] );
349 $file = $f[count($f)-1];
350 $msg .= "<li>" . $file . " line " . $call['line'] . ", in ";
351 if( !empty( $call['class'] ) ) $msg .= $call['class'] . "::";
352 $msg .= $call['function'] . "()</li>\n";
357 function wfNumberOfArticles()
359 global $wgNumberOfArticles;
362 return $wgNumberOfArticles;
365 /* private */ function wfLoadSiteStats()
367 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
368 if ( -1 != $wgNumberOfArticles ) return;
370 $sql = "SELECT ss_total_views, ss_total_edits, ss_good_articles " .
371 "FROM site_stats WHERE ss_row_id=1";
372 $res = wfQuery( $sql, DB_READ
, "wfLoadSiteStats" );
374 if ( 0 == wfNumRows( $res ) ) { return; }
376 $s = wfFetchObject( $res );
377 $wgTotalViews = $s->ss_total_views
;
378 $wgTotalEdits = $s->ss_total_edits
;
379 $wgNumberOfArticles = $s->ss_good_articles
;
383 function wfEscapeHTML( $in )
386 array( "&", "\"", ">", "<" ),
387 array( "&", """, ">", "<" ),
391 function wfEscapeHTMLTagsOnly( $in ) {
393 array( "\"", ">", "<" ),
394 array( """, ">", "<" ),
398 function wfUnescapeHTML( $in )
400 $in = str_replace( "<", "<", $in );
401 $in = str_replace( ">", ">", $in );
402 $in = str_replace( """, "\"", $in );
403 $in = str_replace( "&", "&", $in );
407 function wfImageDir( $fname )
409 global $wgUploadDirectory;
411 $hash = md5( $fname );
412 $oldumask = umask(0);
413 $dest = $wgUploadDirectory . "/" . $hash{0};
414 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
415 $dest .= "/" . substr( $hash, 0, 2 );
416 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
422 function wfImageThumbDir( $fname , $subdir="thumb")
424 return wfImageArchiveDir( $fname, $subdir );
427 function wfImageArchiveDir( $fname , $subdir="archive")
429 global $wgUploadDirectory;
431 $hash = md5( $fname );
432 $oldumask = umask(0);
433 $archive = "{$wgUploadDirectory}/{$subdir}";
434 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
435 $archive .= "/" . $hash{0};
436 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
437 $archive .= "/" . substr( $hash, 0, 2 );
438 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
444 function wfRecordUpload( $name, $oldver, $size, $desc, $copyStatus = "", $source = "" )
446 global $wgUser, $wgLang, $wgTitle, $wgOut, $wgDeferredUpdateList;
447 global $wgUseCopyrightUpload;
449 $fname = "wfRecordUpload";
451 $sql = "SELECT img_name,img_size,img_timestamp,img_description,img_user," .
452 "img_user_text FROM image WHERE img_name='" . wfStrencode( $name ) . "'";
453 $res = wfQuery( $sql, DB_READ
, $fname );
455 $now = wfTimestampNow();
456 $won = wfInvertTimestamp( $now );
457 $size = IntVal( $size );
459 if ( $wgUseCopyrightUpload )
461 $textdesc = "== " . wfMsg ( "filedesc" ) . " ==\n" . $desc . "\n" .
462 "== " . wfMsg ( "filestatus" ) . " ==\n" . $copyStatus . "\n" .
463 "== " . wfMsg ( "filesource" ) . " ==\n" . $source ;
465 else $textdesc = $desc ;
467 $now = wfTimestampNow();
468 $won = wfInvertTimestamp( $now );
470 if ( 0 == wfNumRows( $res ) ) {
471 $sql = "INSERT INTO image (img_name,img_size,img_timestamp," .
472 "img_description,img_user,img_user_text) VALUES ('" .
473 wfStrencode( $name ) . "',$size,'{$now}','" .
474 wfStrencode( $desc ) . "', '" . $wgUser->getID() .
475 "', '" . wfStrencode( $wgUser->getName() ) . "')";
476 wfQuery( $sql, DB_WRITE
, $fname );
478 $sql = "SELECT cur_id,cur_text FROM cur WHERE cur_namespace=" .
479 Namespace::getImage() . " AND cur_title='" .
480 wfStrencode( $name ) . "'";
481 $res = wfQuery( $sql, DB_READ
, $fname );
482 if ( 0 == wfNumRows( $res ) ) {
484 Namespace::getImage() . ",'" .
485 wfStrencode( $name ) . "','" .
486 wfStrencode( $desc ) . "','" . $wgUser->getID() . "','" .
487 wfStrencode( $wgUser->getName() ) . "','" . $now .
489 $sql = "INSERT INTO cur (cur_namespace,cur_title," .
490 "cur_comment,cur_user,cur_user_text,cur_timestamp,cur_is_new," .
491 "cur_text,inverse_timestamp,cur_touched) VALUES (" .
493 ",'" . wfStrencode( $textdesc ) . "','{$won}','{$now}')";
494 wfQuery( $sql, DB_WRITE
, $fname );
495 $id = wfInsertId() or 0; # We should throw an error instead
497 $titleObj = Title
::makeTitle( NS_IMAGE
, $name );
498 RecentChange
::notifyNew( $now, $titleObj, 0, $wgUser, $desc );
500 $u = new SearchUpdate( $id, $name, $desc );
504 $s = wfFetchObject( $res );
506 $sql = "INSERT INTO oldimage (oi_name,oi_archive_name,oi_size," .
507 "oi_timestamp,oi_description,oi_user,oi_user_text) VALUES ('" .
508 wfStrencode( $s->img_name
) . "','" .
509 wfStrencode( $oldver ) .
510 "',{$s->img_size},'{$s->img_timestamp}','" .
511 wfStrencode( $s->img_description
) . "','" .
512 wfStrencode( $s->img_user
) . "','" .
513 wfStrencode( $s->img_user_text
) . "')";
514 wfQuery( $sql, DB_WRITE
, $fname );
516 $sql = "UPDATE image SET img_size={$size}," .
517 "img_timestamp='" . wfTimestampNow() . "',img_user='" .
518 $wgUser->getID() . "',img_user_text='" .
519 wfStrencode( $wgUser->getName() ) . "', img_description='" .
520 wfStrencode( $desc ) . "' WHERE img_name='" .
521 wfStrencode( $name ) . "'";
522 wfQuery( $sql, DB_WRITE
, $fname );
524 $sql = "UPDATE cur SET cur_touched='{$now}' WHERE cur_namespace=" .
525 Namespace::getImage() . " AND cur_title='" .
526 wfStrencode( $name ) . "'";
527 wfQuery( $sql, DB_WRITE
, $fname );
530 $log = new LogPage( wfMsg( "uploadlogpage" ), wfMsg( "uploadlogpagetext" ) );
531 $da = wfMsg( "uploadedimage", "[[:" . $wgLang->getNsText(
532 Namespace::getImage() ) . ":{$name}|{$name}]]" );
533 $ta = wfMsg( "uploadedimage", $name );
534 $log->addEntry( $da, $desc, $ta );
538 /* Some generic result counters, pulled out of SearchEngine */
540 function wfShowingResults( $offset, $limit )
543 return wfMsg( "showingresults", $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+
1 ) );
546 function wfShowingResultsNum( $offset, $limit, $num )
549 return wfMsg( "showingresultsnum", $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+
1 ), $wgLang->formatNum( $num ) );
552 function wfViewPrevNext( $offset, $limit, $link, $query = "", $atend = false )
554 global $wgUser, $wgLang;
555 $fmtLimit = $wgLang->formatNum( $limit );
556 $prev = wfMsg( "prevn", $fmtLimit );
557 $next = wfMsg( "nextn", $fmtLimit );
558 $link = wfUrlencode( $link );
560 $sk = $wgUser->getSkin();
561 if ( 0 != $offset ) {
562 $po = $offset - $limit;
563 if ( $po < 0 ) { $po = 0; }
564 $q = "limit={$limit}&offset={$po}";
565 if ( "" != $query ) { $q .= "&{$query}"; }
566 $plink = "<a href=\"" . wfLocalUrlE( $link, $q ) . "\">{$prev}</a>";
567 } else { $plink = $prev; }
569 $no = $offset +
$limit;
570 $q = "limit={$limit}&offset={$no}";
571 if ( "" != $query ) { $q .= "&{$query}"; }
576 $nlink = "<a href=\"" . wfLocalUrlE( $link, $q ) . "\">{$next}</a>";
578 $nums = wfNumLink( $offset, 20, $link , $query ) . " | " .
579 wfNumLink( $offset, 50, $link, $query ) . " | " .
580 wfNumLink( $offset, 100, $link, $query ) . " | " .
581 wfNumLink( $offset, 250, $link, $query ) . " | " .
582 wfNumLink( $offset, 500, $link, $query );
584 return wfMsg( "viewprevnext", $plink, $nlink, $nums );
587 function wfNumLink( $offset, $limit, $link, $query = "" )
589 global $wgUser, $wgLang;
590 if ( "" == $query ) { $q = ""; }
591 else { $q = "{$query}&"; }
592 $q .= "limit={$limit}&offset={$offset}";
594 $fmtLimit = $wgLang->formatNum( $limit );
595 $s = "<a href=\"" . wfLocalUrlE( $link, $q ) . "\">{$fmtLimit}</a>";
599 function wfClientAcceptsGzip() {
602 # FIXME: we may want to blacklist some broken browsers
604 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
605 $_SERVER["HTTP_ACCEPT_ENCODING"],
607 if( ( $m[1] == "q" ) && ( $m[2] == 0 ) ) return false;
608 wfDebug( " accepts gzip\n" );
615 # Yay, more global functions!
616 function wfCheckLimits( $deflimit = 50, $optionname = "rclimit" ) {
617 global $wgUser, $wgRequest;
619 $limit = $wgRequest->getInt( 'limit', 0 );
620 if( $limit < 0 ) $limit = 0;
621 if( ( $limit == 0 ) && ( $optionname != "" ) ) {
622 $limit = (int)$wgUser->getOption( $optionname );
624 if( $limit <= 0 ) $limit = $deflimit;
625 if( $limit > 5000 ) $limit = 5000; # We have *some* limits...
627 $offset = $wgRequest->getInt( 'offset', 0 );
628 if( $offset < 0 ) $offset = 0;
629 if( $offset > 65000 ) $offset = 65000; # do we need a max? what?
631 return array( $limit, $offset );
634 # Escapes the given text so that it may be output using addWikiText()
635 # without any linking, formatting, etc. making its way through. This
636 # is achieved by substituting certain characters with HTML entities.
637 # As required by the callers, <nowiki> is not used. It currently does
638 # not filter out characters which have special meaning only at the
639 # start of a line, such as "*".
640 function wfEscapeWikiText( $text )
643 array( '[', '|', "'", 'ISBN ' , '://' , "\n=" ),
644 array( '[', '|', ''', 'ISBN ', '://' , "\n=" ),
645 htmlspecialchars($text) );
649 function wfQuotedPrintable( $string, $charset = "" )
651 # Probably incomplete; see RFC 2045
652 if( empty( $charset ) ) {
653 global $wgInputEncoding;
654 $charset = $wgInputEncoding;
656 $charset = strtoupper( $charset );
657 $charset = str_replace( "ISO-8859", "ISO8859", $charset ); // ?
659 $illegal = '\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\xff=';
660 $replace = $illegal . '\t ?_';
661 if( !preg_match( "/[$illegal]/", $string ) ) return $string;
662 $out = "=?$charset?Q?";
663 $out .= preg_replace( "/([$replace])/e", 'sprintf("=%02X",ord("$1"))', $string );
669 $st = explode( " ", microtime() );
670 return (float)$st[0] +
(float)$st[1];
673 # Changes the first character to an HTML entity
674 function wfHtmlEscapeFirst( $text ) {
676 $newText = substr($text, 1);
677 return "&#$ord;$newText";
680 # Sets dest to source and returns the original value of dest
681 function wfSetVar( &$dest, $source )
688 # Sets dest to a reference to source and returns the original dest
689 function &wfSetRef( &$dest, &$source )
696 # This function takes two arrays as input, and returns a CGI-style string, e.g.
697 # "days=7&limit=100". Options in the first array override options in the second.
698 # Options set to "" will not be output.
699 function wfArrayToCGI( $array1, $array2 = NULL )
701 if ( !is_null( $array2 ) ) {
702 $array1 = $array1 +
$array2;
706 foreach ( $array1 as $key => $value ) {
707 if ( "" !== $value ) {
711 $cgi .= "{$key}={$value}";
717 # This is obsolete, use SquidUpdate::purge()
718 function wfPurgeSquidServers ($urlArr) {
719 SquidUpdate
::purge( $urlArr );
722 # Windows-compatible version of escapeshellarg()
723 function wfEscapeShellArg( )
725 $args = func_get_args();
728 foreach ( $args as $arg ) {
735 if (substr(php_uname(), 0, 7) == "Windows") {
736 $retVal .= "\"$arg\"";
738 $retVal .= escapeshellarg( $arg );
744 # wfMerge attempts to merge differences between three texts.
745 # Returns true for a clean merge and false for failure or a conflict.
747 function wfMerge( $old, $mine, $yours, &$result ){
750 # This check may also protect against code injection in
751 # case of broken installations.
752 if(! file_exists( $wgDiff3 ) ){
756 # Make temporary files
758 $oldtextFile = fopen( $oldtextName = tempnam( $td, "merge-old-" ), "w" );
759 $mytextFile = fopen( $mytextName = tempnam( $td, "merge-mine-" ), "w" );
760 $yourtextFile = fopen( $yourtextName = tempnam( $td, "merge-your-" ), "w" );
762 fwrite( $oldtextFile, $old ); fclose( $oldtextFile );
763 fwrite( $mytextFile, $mine ); fclose( $mytextFile );
764 fwrite( $yourtextFile, $yours ); fclose( $yourtextFile );
766 # Check for a conflict
767 $cmd = wfEscapeShellArg( $wgDiff3 ) . " -a --overlap-only " .
768 wfEscapeShellArg( $mytextName ) . " " .
769 wfEscapeShellArg( $oldtextName ) . " " .
770 wfEscapeShellArg( $yourtextName );
771 $handle = popen( $cmd, "r" );
773 if( fgets( $handle ) ){
781 $cmd = wfEscapeShellArg( $wgDiff3 ) . " -a -e --merge " .
782 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
783 $handle = popen( $cmd, "r" );
786 $data = fread( $handle, 8192 );
787 if ( strlen( $data ) == 0 ) {
793 unlink( $mytextName ); unlink( $oldtextName ); unlink( $yourtextName );
797 function wfVarDump( $var )
800 $s = str_replace("\n","<br>\n", var_export( $var, true ) . "\n");
801 if ( headers_sent() ||
!@is_object
( $wgOut ) ) {
804 $wgOut->addHTML( $s );
808 # Provide a simple HTTP error.
809 function wfHttpError( $code, $label, $desc ) {
812 header( "HTTP/1.0 $code $label" );
813 header( "Status: $code $label" );
814 $wgOut->sendCacheControl();
816 # Don't send content if it's a HEAD request.
817 if( $_SERVER['REQUEST_METHOD'] == 'HEAD' ) {
818 header( "Content-type: text/plain" );
823 # Converts an Accept-* header into an array mapping string values to quality factors
824 function wfAcceptToPrefs( $accept, $def = "*/*" ) {
825 # No arg means accept anything (per HTTP spec)
827 return array( $def => 1 );
832 $parts = explode( ",", $accept );
834 foreach( $parts as $part ) {
835 # FIXME: doesn't deal with params like 'text/html; level=1'
836 @list
( $value, $qpart ) = explode( ";", $part );
837 if( !isset( $qpart ) ) {
839 } elseif( preg_match( '/q\s*=\s*(\d*\.\d+)/', $qpart, $match ) ) {
840 $prefs[$value] = $match[1];
847 /* private */ function mimeTypeMatch( $type, $avail ) {
848 if( array_key_exists($type, $avail) ) {
851 $parts = explode( '/', $type );
852 if( array_key_exists( $parts[0] . '/*', $avail ) ) {
853 return $parts[0] . '/*';
854 } elseif( array_key_exists( '*/*', $avail ) ) {
862 # FIXME: doesn't handle params like 'text/plain; charset=UTF-8'
863 # XXX: generalize to negotiate other stuff
864 function wfNegotiateType( $cprefs, $sprefs ) {
867 foreach( array_keys($sprefs) as $type ) {
868 $parts = explode( '/', $type );
869 if( $parts[1] != '*' ) {
870 $ckey = mimeTypeMatch( $type, $cprefs );
872 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
877 foreach( array_keys( $cprefs ) as $type ) {
878 $parts = explode( '/', $type );
879 if( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
880 $skey = mimeTypeMatch( $type, $sprefs );
882 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
890 foreach( array_keys( $combine ) as $type ) {
891 if( $combine[$type] > $bestq ) {
893 $bestq = $combine[$type];