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);
434 # Suppress warning messages here; if the file itself can't
435 # be written we'll worry about it then.
436 $archive = "{$wgUploadDirectory}/{$subdir}";
437 if ( ! is_dir( $archive ) ) { @mkdir
( $archive, 0777 ); }
438 $archive .= "/" . $hash{0};
439 if ( ! is_dir( $archive ) ) { @mkdir
( $archive, 0777 ); }
440 $archive .= "/" . substr( $hash, 0, 2 );
441 if ( ! is_dir( $archive ) ) { @mkdir
( $archive, 0777 ); }
447 function wfRecordUpload( $name, $oldver, $size, $desc, $copyStatus = "", $source = "" )
449 global $wgUser, $wgLang, $wgTitle, $wgOut, $wgDeferredUpdateList;
450 global $wgUseCopyrightUpload;
452 $fname = "wfRecordUpload";
454 $sql = "SELECT img_name,img_size,img_timestamp,img_description,img_user," .
455 "img_user_text FROM image WHERE img_name='" . wfStrencode( $name ) . "'";
456 $res = wfQuery( $sql, DB_READ
, $fname );
458 $now = wfTimestampNow();
459 $won = wfInvertTimestamp( $now );
460 $size = IntVal( $size );
462 if ( $wgUseCopyrightUpload )
464 $textdesc = "== " . wfMsg ( "filedesc" ) . " ==\n" . $desc . "\n" .
465 "== " . wfMsg ( "filestatus" ) . " ==\n" . $copyStatus . "\n" .
466 "== " . wfMsg ( "filesource" ) . " ==\n" . $source ;
468 else $textdesc = $desc ;
470 $now = wfTimestampNow();
471 $won = wfInvertTimestamp( $now );
473 if ( 0 == wfNumRows( $res ) ) {
474 $sql = "INSERT INTO image (img_name,img_size,img_timestamp," .
475 "img_description,img_user,img_user_text) VALUES ('" .
476 wfStrencode( $name ) . "',$size,'{$now}','" .
477 wfStrencode( $desc ) . "', '" . $wgUser->getID() .
478 "', '" . wfStrencode( $wgUser->getName() ) . "')";
479 wfQuery( $sql, DB_WRITE
, $fname );
481 $sql = "SELECT cur_id,cur_text FROM cur WHERE cur_namespace=" .
482 Namespace::getImage() . " AND cur_title='" .
483 wfStrencode( $name ) . "'";
484 $res = wfQuery( $sql, DB_READ
, $fname );
485 if ( 0 == wfNumRows( $res ) ) {
487 Namespace::getImage() . ",'" .
488 wfStrencode( $name ) . "','" .
489 wfStrencode( $desc ) . "','" . $wgUser->getID() . "','" .
490 wfStrencode( $wgUser->getName() ) . "','" . $now .
492 $sql = "INSERT INTO cur (cur_namespace,cur_title," .
493 "cur_comment,cur_user,cur_user_text,cur_timestamp,cur_is_new," .
494 "cur_text,inverse_timestamp,cur_touched) VALUES (" .
496 ",'" . wfStrencode( $textdesc ) . "','{$won}','{$now}')";
497 wfQuery( $sql, DB_WRITE
, $fname );
498 $id = wfInsertId() or 0; # We should throw an error instead
500 $titleObj = Title
::makeTitle( NS_IMAGE
, $name );
501 RecentChange
::notifyNew( $now, $titleObj, 0, $wgUser, $desc );
503 $u = new SearchUpdate( $id, $name, $desc );
507 $s = wfFetchObject( $res );
509 $sql = "INSERT INTO oldimage (oi_name,oi_archive_name,oi_size," .
510 "oi_timestamp,oi_description,oi_user,oi_user_text) VALUES ('" .
511 wfStrencode( $s->img_name
) . "','" .
512 wfStrencode( $oldver ) .
513 "',{$s->img_size},'{$s->img_timestamp}','" .
514 wfStrencode( $s->img_description
) . "','" .
515 wfStrencode( $s->img_user
) . "','" .
516 wfStrencode( $s->img_user_text
) . "')";
517 wfQuery( $sql, DB_WRITE
, $fname );
519 $sql = "UPDATE image SET img_size={$size}," .
520 "img_timestamp='" . wfTimestampNow() . "',img_user='" .
521 $wgUser->getID() . "',img_user_text='" .
522 wfStrencode( $wgUser->getName() ) . "', img_description='" .
523 wfStrencode( $desc ) . "' WHERE img_name='" .
524 wfStrencode( $name ) . "'";
525 wfQuery( $sql, DB_WRITE
, $fname );
527 $sql = "UPDATE cur SET cur_touched='{$now}' WHERE cur_namespace=" .
528 Namespace::getImage() . " AND cur_title='" .
529 wfStrencode( $name ) . "'";
530 wfQuery( $sql, DB_WRITE
, $fname );
533 $log = new LogPage( wfMsg( "uploadlogpage" ), wfMsg( "uploadlogpagetext" ) );
534 $da = wfMsg( "uploadedimage", "[[:" . $wgLang->getNsText(
535 Namespace::getImage() ) . ":{$name}|{$name}]]" );
536 $ta = wfMsg( "uploadedimage", $name );
537 $log->addEntry( $da, $desc, $ta );
541 /* Some generic result counters, pulled out of SearchEngine */
543 function wfShowingResults( $offset, $limit )
546 return wfMsg( "showingresults", $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+
1 ) );
549 function wfShowingResultsNum( $offset, $limit, $num )
552 return wfMsg( "showingresultsnum", $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+
1 ), $wgLang->formatNum( $num ) );
555 function wfViewPrevNext( $offset, $limit, $link, $query = "", $atend = false )
557 global $wgUser, $wgLang;
558 $fmtLimit = $wgLang->formatNum( $limit );
559 $prev = wfMsg( "prevn", $fmtLimit );
560 $next = wfMsg( "nextn", $fmtLimit );
561 $link = wfUrlencode( $link );
563 $sk = $wgUser->getSkin();
564 if ( 0 != $offset ) {
565 $po = $offset - $limit;
566 if ( $po < 0 ) { $po = 0; }
567 $q = "limit={$limit}&offset={$po}";
568 if ( "" != $query ) { $q .= "&{$query}"; }
569 $plink = "<a href=\"" . wfLocalUrlE( $link, $q ) . "\">{$prev}</a>";
570 } else { $plink = $prev; }
572 $no = $offset +
$limit;
573 $q = "limit={$limit}&offset={$no}";
574 if ( "" != $query ) { $q .= "&{$query}"; }
579 $nlink = "<a href=\"" . wfLocalUrlE( $link, $q ) . "\">{$next}</a>";
581 $nums = wfNumLink( $offset, 20, $link , $query ) . " | " .
582 wfNumLink( $offset, 50, $link, $query ) . " | " .
583 wfNumLink( $offset, 100, $link, $query ) . " | " .
584 wfNumLink( $offset, 250, $link, $query ) . " | " .
585 wfNumLink( $offset, 500, $link, $query );
587 return wfMsg( "viewprevnext", $plink, $nlink, $nums );
590 function wfNumLink( $offset, $limit, $link, $query = "" )
592 global $wgUser, $wgLang;
593 if ( "" == $query ) { $q = ""; }
594 else { $q = "{$query}&"; }
595 $q .= "limit={$limit}&offset={$offset}";
597 $fmtLimit = $wgLang->formatNum( $limit );
598 $s = "<a href=\"" . wfLocalUrlE( $link, $q ) . "\">{$fmtLimit}</a>";
602 function wfClientAcceptsGzip() {
605 # FIXME: we may want to blacklist some broken browsers
607 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
608 $_SERVER["HTTP_ACCEPT_ENCODING"],
610 if( ( $m[1] == "q" ) && ( $m[2] == 0 ) ) return false;
611 wfDebug( " accepts gzip\n" );
618 # Yay, more global functions!
619 function wfCheckLimits( $deflimit = 50, $optionname = "rclimit" ) {
620 global $wgUser, $wgRequest;
622 $limit = $wgRequest->getInt( 'limit', 0 );
623 if( $limit < 0 ) $limit = 0;
624 if( ( $limit == 0 ) && ( $optionname != "" ) ) {
625 $limit = (int)$wgUser->getOption( $optionname );
627 if( $limit <= 0 ) $limit = $deflimit;
628 if( $limit > 5000 ) $limit = 5000; # We have *some* limits...
630 $offset = $wgRequest->getInt( 'offset', 0 );
631 if( $offset < 0 ) $offset = 0;
632 if( $offset > 65000 ) $offset = 65000; # do we need a max? what?
634 return array( $limit, $offset );
637 # Escapes the given text so that it may be output using addWikiText()
638 # without any linking, formatting, etc. making its way through. This
639 # is achieved by substituting certain characters with HTML entities.
640 # As required by the callers, <nowiki> is not used. It currently does
641 # not filter out characters which have special meaning only at the
642 # start of a line, such as "*".
643 function wfEscapeWikiText( $text )
646 array( '[', '|', "'", 'ISBN ' , '://' , "\n=" ),
647 array( '[', '|', ''', 'ISBN ', '://' , "\n=" ),
648 htmlspecialchars($text) );
652 function wfQuotedPrintable( $string, $charset = "" )
654 # Probably incomplete; see RFC 2045
655 if( empty( $charset ) ) {
656 global $wgInputEncoding;
657 $charset = $wgInputEncoding;
659 $charset = strtoupper( $charset );
660 $charset = str_replace( "ISO-8859", "ISO8859", $charset ); // ?
662 $illegal = '\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\xff=';
663 $replace = $illegal . '\t ?_';
664 if( !preg_match( "/[$illegal]/", $string ) ) return $string;
665 $out = "=?$charset?Q?";
666 $out .= preg_replace( "/([$replace])/e", 'sprintf("=%02X",ord("$1"))', $string );
672 $st = explode( " ", microtime() );
673 return (float)$st[0] +
(float)$st[1];
676 # Changes the first character to an HTML entity
677 function wfHtmlEscapeFirst( $text ) {
679 $newText = substr($text, 1);
680 return "&#$ord;$newText";
683 # Sets dest to source and returns the original value of dest
684 function wfSetVar( &$dest, $source )
691 # Sets dest to a reference to source and returns the original dest
692 function &wfSetRef( &$dest, &$source )
699 # This function takes two arrays as input, and returns a CGI-style string, e.g.
700 # "days=7&limit=100". Options in the first array override options in the second.
701 # Options set to "" will not be output.
702 function wfArrayToCGI( $array1, $array2 = NULL )
704 if ( !is_null( $array2 ) ) {
705 $array1 = $array1 +
$array2;
709 foreach ( $array1 as $key => $value ) {
710 if ( "" !== $value ) {
714 $cgi .= "{$key}={$value}";
720 # This is obsolete, use SquidUpdate::purge()
721 function wfPurgeSquidServers ($urlArr) {
722 SquidUpdate
::purge( $urlArr );
725 # Windows-compatible version of escapeshellarg()
726 function wfEscapeShellArg( )
728 $args = func_get_args();
731 foreach ( $args as $arg ) {
738 if (substr(php_uname(), 0, 7) == "Windows") {
739 $retVal .= "\"$arg\"";
741 $retVal .= escapeshellarg( $arg );
747 # wfMerge attempts to merge differences between three texts.
748 # Returns true for a clean merge and false for failure or a conflict.
750 function wfMerge( $old, $mine, $yours, &$result ){
753 # This check may also protect against code injection in
754 # case of broken installations.
755 if(! file_exists( $wgDiff3 ) ){
759 # Make temporary files
761 $oldtextFile = fopen( $oldtextName = tempnam( $td, "merge-old-" ), "w" );
762 $mytextFile = fopen( $mytextName = tempnam( $td, "merge-mine-" ), "w" );
763 $yourtextFile = fopen( $yourtextName = tempnam( $td, "merge-your-" ), "w" );
765 fwrite( $oldtextFile, $old ); fclose( $oldtextFile );
766 fwrite( $mytextFile, $mine ); fclose( $mytextFile );
767 fwrite( $yourtextFile, $yours ); fclose( $yourtextFile );
769 # Check for a conflict
770 $cmd = wfEscapeShellArg( $wgDiff3 ) . " -a --overlap-only " .
771 wfEscapeShellArg( $mytextName ) . " " .
772 wfEscapeShellArg( $oldtextName ) . " " .
773 wfEscapeShellArg( $yourtextName );
774 $handle = popen( $cmd, "r" );
776 if( fgets( $handle ) ){
784 $cmd = wfEscapeShellArg( $wgDiff3 ) . " -a -e --merge " .
785 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
786 $handle = popen( $cmd, "r" );
789 $data = fread( $handle, 8192 );
790 if ( strlen( $data ) == 0 ) {
796 unlink( $mytextName ); unlink( $oldtextName ); unlink( $yourtextName );
800 function wfVarDump( $var )
803 $s = str_replace("\n","<br>\n", var_export( $var, true ) . "\n");
804 if ( headers_sent() ||
!@is_object
( $wgOut ) ) {
807 $wgOut->addHTML( $s );
811 # Provide a simple HTTP error.
812 function wfHttpError( $code, $label, $desc ) {
815 header( "HTTP/1.0 $code $label" );
816 header( "Status: $code $label" );
817 $wgOut->sendCacheControl();
819 # Don't send content if it's a HEAD request.
820 if( $_SERVER['REQUEST_METHOD'] == 'HEAD' ) {
821 header( "Content-type: text/plain" );
826 # Converts an Accept-* header into an array mapping string values to quality factors
827 function wfAcceptToPrefs( $accept, $def = "*/*" ) {
828 # No arg means accept anything (per HTTP spec)
830 return array( $def => 1 );
835 $parts = explode( ",", $accept );
837 foreach( $parts as $part ) {
838 # FIXME: doesn't deal with params like 'text/html; level=1'
839 @list
( $value, $qpart ) = explode( ";", $part );
840 if( !isset( $qpart ) ) {
842 } elseif( preg_match( '/q\s*=\s*(\d*\.\d+)/', $qpart, $match ) ) {
843 $prefs[$value] = $match[1];
850 /* private */ function mimeTypeMatch( $type, $avail ) {
851 if( array_key_exists($type, $avail) ) {
854 $parts = explode( '/', $type );
855 if( array_key_exists( $parts[0] . '/*', $avail ) ) {
856 return $parts[0] . '/*';
857 } elseif( array_key_exists( '*/*', $avail ) ) {
865 # FIXME: doesn't handle params like 'text/plain; charset=UTF-8'
866 # XXX: generalize to negotiate other stuff
867 function wfNegotiateType( $cprefs, $sprefs ) {
870 foreach( array_keys($sprefs) as $type ) {
871 $parts = explode( '/', $type );
872 if( $parts[1] != '*' ) {
873 $ckey = mimeTypeMatch( $type, $cprefs );
875 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
880 foreach( array_keys( $cprefs ) as $type ) {
881 $parts = explode( '/', $type );
882 if( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
883 $skey = mimeTypeMatch( $type, $sprefs );
885 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
893 foreach( array_keys( $combine ) as $type ) {
894 if( $combine[$type] > $bestq ) {
896 $bestq = $combine[$type];