4 * Global functions used everywhere
9 * Some globals and requires needed
13 * Total number of articles
14 * @global integer $wgNumberOfArticles
16 $wgNumberOfArticles = -1; # Unset
18 * Total number of views
19 * @global integer $wgTotalViews
23 * Total number of edits
24 * @global integer $wgTotalEdits
29 require_once( 'DatabaseFunctions.php' );
30 require_once( 'UpdateClasses.php' );
31 require_once( 'LogPage.php' );
32 require_once( 'normal/UtfNormalUtil.php' );
35 * Compatibility functions
36 * PHP <4.3.x is not actively supported; 4.1.x and 4.2.x might or might not work.
37 * <4.1.x will not work, as we use a number of features introduced in 4.1.0
38 * such as the new autoglobals.
40 if( !function_exists('iconv') ) {
41 # iconv support is not in the default configuration and so may not be present.
42 # Assume will only ever use utf-8 and iso-8859-1.
43 # This will *not* work in all circumstances.
44 function iconv( $from, $to, $string ) {
45 if(strcasecmp( $from, $to ) == 0) return $string;
46 if(strcasecmp( $from, 'utf-8' ) == 0) return utf8_decode( $string );
47 if(strcasecmp( $to, 'utf-8' ) == 0) return utf8_encode( $string );
52 if( !function_exists('file_get_contents') ) {
53 # Exists in PHP 4.3.0+
54 function file_get_contents( $filename ) {
55 return implode( '', file( $filename ) );
59 if( !function_exists('is_a') ) {
60 # Exists in PHP 4.2.0+
61 function is_a( $object, $class_name ) {
63 (strcasecmp( get_class( $object ), $class_name ) == 0) ||
64 is_subclass_of( $object, $class_name );
68 # UTF-8 substr function based on a PHP manual comment
69 if ( !function_exists( 'mb_substr' ) ) {
70 function mb_substr( $str, $start ) {
71 preg_match_all( '/./us', $str, $ar );
73 if( func_num_args() >= 3 ) {
74 $end = func_get_arg( 2 );
75 return join( '', array_slice( $ar[0], $start, $end ) );
77 return join( '', array_slice( $ar[0], $start ) );
82 if( !function_exists( 'floatval' ) ) {
84 * First defined in PHP 4.2.0
88 function floatval( $var ) {
94 * Where as we got a random seed
95 * @var bool $wgTotalViews
97 $wgRandomSeeded = false;
100 * Seed Mersenne Twister
101 * Only necessary in PHP < 4.2.0
105 function wfSeedRandom() {
106 global $wgRandomSeeded;
108 if ( ! $wgRandomSeeded && version_compare( phpversion(), '4.2.0' ) < 0 ) {
109 $seed = hexdec(substr(md5(microtime()),-8)) & 0x7fffffff;
111 $wgRandomSeeded = true;
116 * Get a random decimal value between 0 and 1, in a way
117 * not likely to give duplicate values for any realistic
118 * number of articles.
122 function wfRandom() {
123 # The maximum random value is "only" 2^31-1, so get two random
124 # values to reduce the chance of dupes
125 $max = mt_getrandmax();
126 $rand = number_format( (mt_rand() * $max +
mt_rand())
127 / $max / $max, 12, '.', '' );
132 * We want / and : to be included as literal characters in our title URLs.
133 * %2F in the page titles seems to fatally break for some reason.
138 function wfUrlencode ( $s ) {
139 $s = urlencode( $s );
140 $s = preg_replace( '/%3[Aa]/', ':', $s );
141 $s = preg_replace( '/%2[Ff]/', '/', $s );
147 * Sends a line to the debug log if enabled or, optionally, to a comment in output.
148 * In normal operation this is a NOP.
150 * Controlling globals:
151 * $wgDebugLogFile - points to the log file
152 * $wgProfileOnly - if set, normal debug messages will not be recorded.
153 * $wgDebugRawPage - if false, 'action=raw' hits will not result in debug output.
154 * $wgDebugComments - if on, some debug items may appear in comments in the HTML output.
156 * @param string $text
157 * @param bool $logonly Set true to avoid appearing in HTML when $wgDebugComments is set
159 function wfDebug( $text, $logonly = false ) {
160 global $wgOut, $wgDebugLogFile, $wgDebugComments, $wgProfileOnly, $wgDebugRawPage;
162 # Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
163 if ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' && !$wgDebugRawPage ) {
167 if ( isset( $wgOut ) && $wgDebugComments && !$logonly ) {
168 $wgOut->debug( $text );
170 if ( '' != $wgDebugLogFile && !$wgProfileOnly ) {
171 # Strip unprintables; they can switch terminal modes when binary data
172 # gets dumped, which is pretty annoying.
173 $text = preg_replace( '![\x00-\x08\x0b\x0c\x0e-\x1f]!', ' ', $text );
174 @error_log
( $text, 3, $wgDebugLogFile );
179 * Send a line to a supplementary debug log file, if configured, or main debug log if not.
180 * $wgDebugLogGroups[$logGroup] should be set to a filename to send to a separate log.
182 * @param string $logGroup
183 * @param string $text
184 * @param bool $public Whether to log the event in the public log if no private
185 * log file is specified, (default true)
187 function wfDebugLog( $logGroup, $text, $public = true ) {
188 global $wgDebugLogGroups, $wgDBname;
189 if( $text{strlen( $text ) - 1} != "\n" ) $text .= "\n";
190 if( isset( $wgDebugLogGroups[$logGroup] ) ) {
191 @error_log
( "$wgDBname: $text", 3, $wgDebugLogGroups[$logGroup] );
192 } else if ( $public === true ) {
193 wfDebug( $text, true );
198 * Log for database errors
199 * @param string $text Database error message.
201 function wfLogDBError( $text ) {
202 global $wgDBerrorLog;
203 if ( $wgDBerrorLog ) {
204 $host = trim(`hostname`
);
205 $text = date('D M j G:i:s T Y') . "\t$host\t".$text;
206 error_log( $text, 3, $wgDBerrorLog );
213 function logProfilingData() {
214 global $wgRequestTime, $wgDebugLogFile, $wgDebugRawPage, $wgRequest;
215 global $wgProfiling, $wgUser;
218 list( $usec, $sec ) = explode( ' ', $wgRequestTime );
219 $start = (float)$sec +
(float)$usec;
220 $elapsed = $now - $start;
221 if ( $wgProfiling ) {
222 $prof = wfGetProfilingOutput( $start, $elapsed );
224 if( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) )
225 $forward = ' forwarded for ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
226 if( !empty( $_SERVER['HTTP_CLIENT_IP'] ) )
227 $forward .= ' client IP ' . $_SERVER['HTTP_CLIENT_IP'];
228 if( !empty( $_SERVER['HTTP_FROM'] ) )
229 $forward .= ' from ' . $_SERVER['HTTP_FROM'];
231 $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
232 if( $wgUser->isAnon() )
234 $log = sprintf( "%s\t%04.3f\t%s\n",
235 gmdate( 'YmdHis' ), $elapsed,
236 urldecode( $_SERVER['REQUEST_URI'] . $forward ) );
237 if ( '' != $wgDebugLogFile && ( $wgRequest->getVal('action') != 'raw' ||
$wgDebugRawPage ) ) {
238 error_log( $log . $prof, 3, $wgDebugLogFile );
244 * Check if the wiki read-only lock file is present. This can be used to lock
245 * off editing functions, but doesn't guarantee that the database will not be
249 function wfReadOnly() {
250 global $wgReadOnlyFile, $wgReadOnly;
255 if ( '' == $wgReadOnlyFile ) {
259 // Set $wgReadOnly and unset $wgReadOnlyFile, for faster access next time
260 if ( is_file( $wgReadOnlyFile ) ) {
261 $wgReadOnly = file_get_contents( $wgReadOnlyFile );
265 $wgReadOnlyFile = '';
271 * Get a message from anywhere, for the current user language.
273 * Use wfMsgForContent() instead if the message should NOT
274 * change depending on the user preferences.
276 * Note that the message may contain HTML, and is therefore
277 * not safe for insertion anywhere. Some functions such as
278 * addWikiText will do the escaping for you. Use wfMsgHtml()
279 * if you need an escaped message.
281 * @param string lookup key for the message, usually
282 * defined in languages/Language.php
284 function wfMsg( $key ) {
285 $args = func_get_args();
286 array_shift( $args );
287 return wfMsgReal( $key, $args, true );
291 * Same as above except doesn't transform the message
293 function wfMsgNoTrans( $key ) {
294 $args = func_get_args();
295 array_shift( $args );
296 return wfMsgReal( $key, $args, true, false );
300 * Get a message from anywhere, for the current global language
301 * set with $wgLanguageCode.
303 * Use this if the message should NOT change dependent on the
304 * language set in the user's preferences. This is the case for
305 * most text written into logs, as well as link targets (such as
306 * the name of the copyright policy page). Link titles, on the
307 * other hand, should be shown in the UI language.
309 * Note that MediaWiki allows users to change the user interface
310 * language in their preferences, but a single installation
311 * typically only contains content in one language.
313 * Be wary of this distinction: If you use wfMsg() where you should
314 * use wfMsgForContent(), a user of the software may have to
315 * customize over 70 messages in order to, e.g., fix a link in every
318 * @param string lookup key for the message, usually
319 * defined in languages/Language.php
321 function wfMsgForContent( $key ) {
322 global $wgForceUIMsgAsContentMsg;
323 $args = func_get_args();
324 array_shift( $args );
326 if( is_array( $wgForceUIMsgAsContentMsg ) &&
327 in_array( $key, $wgForceUIMsgAsContentMsg ) )
329 return wfMsgReal( $key, $args, true, $forcontent );
333 * Same as above except doesn't transform the message
335 function wfMsgForContentNoTrans( $key ) {
336 global $wgForceUIMsgAsContentMsg;
337 $args = func_get_args();
338 array_shift( $args );
340 if( is_array( $wgForceUIMsgAsContentMsg ) &&
341 in_array( $key, $wgForceUIMsgAsContentMsg ) )
343 return wfMsgReal( $key, $args, true, $forcontent, false );
347 * Get a message from the language file, for the UI elements
349 function wfMsgNoDB( $key ) {
350 $args = func_get_args();
351 array_shift( $args );
352 return wfMsgReal( $key, $args, false );
356 * Get a message from the language file, for the content
358 function wfMsgNoDBForContent( $key ) {
359 global $wgForceUIMsgAsContentMsg;
360 $args = func_get_args();
361 array_shift( $args );
363 if( is_array( $wgForceUIMsgAsContentMsg ) &&
364 in_array( $key, $wgForceUIMsgAsContentMsg ) )
366 return wfMsgReal( $key, $args, false, $forcontent );
371 * Really get a message
373 function wfMsgReal( $key, $args, $useDB, $forContent=false, $transform = true ) {
374 $fname = 'wfMsgReal';
375 wfProfileIn( $fname );
377 $message = wfMsgGetKey( $key, $useDB, $forContent, $transform );
378 $message = wfMsgReplaceArgs( $message, $args );
379 wfProfileOut( $fname );
384 * Fetch a message string value, but don't replace any keys yet.
387 * @param bool $forContent
391 function wfMsgGetKey( $key, $useDB, $forContent = false, $transform = true ) {
392 global $wgParser, $wgMsgParserOptions, $wgContLang, $wgMessageCache, $wgLang;
394 if ( is_object( $wgMessageCache ) )
395 $transstat = $wgMessageCache->getTransform();
397 if( is_object( $wgMessageCache ) ) {
399 $wgMessageCache->disableTransform();
400 $message = $wgMessageCache->get( $key, $useDB, $forContent );
403 $lang = &$wgContLang;
408 wfSuppressWarnings();
410 if( is_object( $lang ) ) {
411 $message = $lang->getMessage( $key );
416 if($message === false)
417 $message = Language
::getMessage($key);
418 if ( $transform && strstr( $message, '{{' ) !== false ) {
419 $message = $wgParser->transformMsg($message, $wgMsgParserOptions);
423 if ( is_object( $wgMessageCache ) && ! $transform )
424 $wgMessageCache->setTransform( $transstat );
430 * Replace message parameter keys on the given formatted output.
432 * @param string $message
437 function wfMsgReplaceArgs( $message, $args ) {
438 # Fix windows line-endings
439 # Some messages are split with explode("\n", $msg)
440 $message = str_replace( "\r", '', $message );
443 if ( count( $args ) )
444 if ( is_array( $args[0] ) )
445 foreach ( $args[0] as $key => $val )
446 $message = str_replace( '$' . $key, $val, $message );
448 foreach( $args as $n => $param )
449 $replacementKeys['$' . ($n +
1)] = $param;
450 $message = strtr( $message, $replacementKeys );
457 * Return an HTML-escaped version of a message.
458 * Parameter replacements, if any, are done *after* the HTML-escaping,
459 * so parameters may contain HTML (eg links or form controls). Be sure
460 * to pre-escape them if you really do want plaintext, or just wrap
461 * the whole thing in htmlspecialchars().
464 * @param string ... parameters
467 function wfMsgHtml( $key ) {
468 $args = func_get_args();
469 array_shift( $args );
470 return wfMsgReplaceArgs( htmlspecialchars( wfMsgGetKey( $key, true ) ), $args );
474 * Return an HTML version of message
475 * Parameter replacements, if any, are done *after* parsing the wiki-text message,
476 * so parameters may contain HTML (eg links or form controls). Be sure
477 * to pre-escape them if you really do want plaintext, or just wrap
478 * the whole thing in htmlspecialchars().
481 * @param string ... parameters
484 function wfMsgWikiHtml( $key ) {
486 $args = func_get_args();
487 array_shift( $args );
488 return wfMsgReplaceArgs( $wgOut->parse( wfMsgGetKey( $key, true ), /* can't be set to false */ true ), $args );
492 * Just like exit() but makes a note of it.
493 * Commits open transactions except if the error parameter is set
495 function wfAbruptExit( $error = false ){
496 global $wgLoadBalancer;
497 static $called = false;
503 if( function_exists( 'debug_backtrace' ) ){ // PHP >= 4.3
504 $bt = debug_backtrace();
505 for($i = 0; $i < count($bt) ; $i++
){
506 $file = isset($bt[$i]['file']) ?
$bt[$i]['file'] : "unknown";
507 $line = isset($bt[$i]['line']) ?
$bt[$i]['line'] : "unknown";
508 wfDebug("WARNING: Abrupt exit in $file at line $line\n");
511 wfDebug('WARNING: Abrupt exit\n');
514 $wgLoadBalancer->closeAll();
522 function wfErrorExit() {
523 wfAbruptExit( true );
527 * Die with a backtrace
528 * This is meant as a debugging aid to track down where bad data comes from.
529 * Shouldn't be used in production code except maybe in "shouldn't happen" areas.
531 * @param string $msg Message shown when dieing.
533 function wfDebugDieBacktrace( $msg = '' ) {
534 global $wgCommandLineMode;
536 $backtrace = wfBacktrace();
537 if ( $backtrace !== false ) {
538 if ( $wgCommandLineMode ) {
539 $msg .= "\nBacktrace:\n$backtrace";
541 $msg .= "\n<p>Backtrace:</p>\n$backtrace";
545 echo wfReportTime()."\n";
550 * Returns a HTML comment with the elapsed time since request.
551 * This method has no side effects.
554 function wfReportTime() {
555 global $wgRequestTime;
558 list( $usec, $sec ) = explode( ' ', $wgRequestTime );
559 $start = (float)$sec +
(float)$usec;
560 $elapsed = $now - $start;
562 # Use real server name if available, so we know which machine
563 # in a server farm generated the current page.
564 if ( function_exists( 'posix_uname' ) ) {
565 $uname = @posix_uname
();
569 if( is_array( $uname ) && isset( $uname['nodename'] ) ) {
570 $hostname = $uname['nodename'];
572 # This may be a virtual server.
573 $hostname = $_SERVER['SERVER_NAME'];
575 $com = sprintf( "<!-- Served by %s in %01.2f secs. -->",
576 $hostname, $elapsed );
580 function wfBacktrace() {
581 global $wgCommandLineMode;
582 if ( !function_exists( 'debug_backtrace' ) ) {
586 if ( $wgCommandLineMode ) {
591 $backtrace = debug_backtrace();
592 foreach( $backtrace as $call ) {
593 if( isset( $call['file'] ) ) {
594 $f = explode( DIRECTORY_SEPARATOR
, $call['file'] );
595 $file = $f[count($f)-1];
599 if( isset( $call['line'] ) ) {
600 $line = $call['line'];
604 if ( $wgCommandLineMode ) {
605 $msg .= "$file line $line calls ";
607 $msg .= '<li>' . $file . ' line ' . $line . ' calls ';
609 if( !empty( $call['class'] ) ) $msg .= $call['class'] . '::';
610 $msg .= $call['function'] . '()';
612 if ( $wgCommandLineMode ) {
618 if ( $wgCommandLineMode ) {
628 /* Some generic result counters, pulled out of SearchEngine */
634 function wfShowingResults( $offset, $limit ) {
636 return wfMsg( 'showingresults', $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+
1 ) );
642 function wfShowingResultsNum( $offset, $limit, $num ) {
644 return wfMsg( 'showingresultsnum', $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+
1 ), $wgLang->formatNum( $num ) );
650 function wfViewPrevNext( $offset, $limit, $link, $query = '', $atend = false ) {
651 global $wgUser, $wgLang;
652 $fmtLimit = $wgLang->formatNum( $limit );
653 $prev = wfMsg( 'prevn', $fmtLimit );
654 $next = wfMsg( 'nextn', $fmtLimit );
656 if( is_object( $link ) ) {
659 $title = Title
::newFromText( $link );
660 if( is_null( $title ) ) {
665 $sk = $wgUser->getSkin();
666 if ( 0 != $offset ) {
667 $po = $offset - $limit;
668 if ( $po < 0 ) { $po = 0; }
669 $q = "limit={$limit}&offset={$po}";
670 if ( '' != $query ) { $q .= '&'.$query; }
671 $plink = '<a href="' . $title->escapeLocalUrl( $q ) . "\">{$prev}</a>";
672 } else { $plink = $prev; }
674 $no = $offset +
$limit;
675 $q = 'limit='.$limit.'&offset='.$no;
676 if ( '' != $query ) { $q .= '&'.$query; }
681 $nlink = '<a href="' . $title->escapeLocalUrl( $q ) . "\">{$next}</a>";
683 $nums = wfNumLink( $offset, 20, $title, $query ) . ' | ' .
684 wfNumLink( $offset, 50, $title, $query ) . ' | ' .
685 wfNumLink( $offset, 100, $title, $query ) . ' | ' .
686 wfNumLink( $offset, 250, $title, $query ) . ' | ' .
687 wfNumLink( $offset, 500, $title, $query );
689 return wfMsg( 'viewprevnext', $plink, $nlink, $nums );
695 function wfNumLink( $offset, $limit, &$title, $query = '' ) {
696 global $wgUser, $wgLang;
697 if ( '' == $query ) { $q = ''; }
698 else { $q = $query.'&'; }
699 $q .= 'limit='.$limit.'&offset='.$offset;
701 $fmtLimit = $wgLang->formatNum( $limit );
702 $s = '<a href="' . $title->escapeLocalUrl( $q ) . "\">{$fmtLimit}</a>";
708 * @todo FIXME: we may want to blacklist some broken browsers
710 * @return bool Whereas client accept gzip compression
712 function wfClientAcceptsGzip() {
715 # FIXME: we may want to blacklist some broken browsers
717 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
718 $_SERVER['HTTP_ACCEPT_ENCODING'],
720 if( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) return false;
721 wfDebug( " accepts gzip\n" );
729 * Yay, more global functions!
731 function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) {
733 return $wgRequest->getLimitOffset( $deflimit, $optionname );
737 * Escapes the given text so that it may be output using addWikiText()
738 * without any linking, formatting, etc. making its way through. This
739 * is achieved by substituting certain characters with HTML entities.
740 * As required by the callers, <nowiki> is not used. It currently does
741 * not filter out characters which have special meaning only at the
742 * start of a line, such as "*".
744 * @param string $text Text to be escaped
746 function wfEscapeWikiText( $text ) {
748 array( '[', '|', '\'', 'ISBN ' , '://' , "\n=", '{{' ),
749 array( '[', '|', ''', 'ISBN ', '://' , "\n=", '{{' ),
750 htmlspecialchars($text) );
757 function wfQuotedPrintable( $string, $charset = '' ) {
758 # Probably incomplete; see RFC 2045
759 if( empty( $charset ) ) {
760 global $wgInputEncoding;
761 $charset = $wgInputEncoding;
763 $charset = strtoupper( $charset );
764 $charset = str_replace( 'ISO-8859', 'ISO8859', $charset ); // ?
766 $illegal = '\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\xff=';
767 $replace = $illegal . '\t ?_';
768 if( !preg_match( "/[$illegal]/", $string ) ) return $string;
769 $out = "=?$charset?Q?";
770 $out .= preg_replace( "/([$replace])/e", 'sprintf("=%02X",ord("$1"))', $string );
776 * Returns an escaped string suitable for inclusion in a string literal
777 * for JavaScript source code.
778 * Illegal control characters are assumed not to be present.
780 * @param string $string
783 function wfEscapeJsString( $string ) {
784 // See ECMA 262 section 7.8.4 for string literal format
792 # To avoid closing the element or CDATA section
796 return strtr( $string, $pairs );
804 $st = explode( ' ', microtime() );
805 return (float)$st[0] +
(float)$st[1];
809 * Changes the first character to an HTML entity
811 function wfHtmlEscapeFirst( $text ) {
813 $newText = substr($text, 1);
814 return "&#$ord;$newText";
818 * Sets dest to source and returns the original value of dest
819 * If source is NULL, it just returns the value, it doesn't set the variable
821 function wfSetVar( &$dest, $source ) {
823 if ( !is_null( $source ) ) {
830 * As for wfSetVar except setting a bit
832 function wfSetBit( &$dest, $bit, $state = true ) {
833 $temp = (bool)($dest & $bit );
834 if ( !is_null( $state ) ) {
845 * This function takes two arrays as input, and returns a CGI-style string, e.g.
846 * "days=7&limit=100". Options in the first array override options in the second.
847 * Options set to "" will not be output.
849 function wfArrayToCGI( $array1, $array2 = NULL )
851 if ( !is_null( $array2 ) ) {
852 $array1 = $array1 +
$array2;
856 foreach ( $array1 as $key => $value ) {
857 if ( '' !== $value ) {
861 $cgi .= urlencode( $key ) . '=' . urlencode( $value );
868 * This is obsolete, use SquidUpdate::purge()
871 function wfPurgeSquidServers ($urlArr) {
872 SquidUpdate
::purge( $urlArr );
876 * Windows-compatible version of escapeshellarg()
877 * Windows doesn't recognise single-quotes in the shell, but the escapeshellarg()
878 * function puts single quotes in regardless of OS
880 function wfEscapeShellArg( ) {
881 $args = func_get_args();
884 foreach ( $args as $arg ) {
891 if ( wfIsWindows() ) {
892 $retVal .= '"' . str_replace( '"','\"', $arg ) . '"';
894 $retVal .= escapeshellarg( $arg );
901 * wfMerge attempts to merge differences between three texts.
902 * Returns true for a clean merge and false for failure or a conflict.
904 function wfMerge( $old, $mine, $yours, &$result ){
907 # This check may also protect against code injection in
908 # case of broken installations.
909 if(! file_exists( $wgDiff3 ) ){
910 wfDebug( "diff3 not found\n" );
914 # Make temporary files
916 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
917 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
918 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
920 fwrite( $oldtextFile, $old ); fclose( $oldtextFile );
921 fwrite( $mytextFile, $mine ); fclose( $mytextFile );
922 fwrite( $yourtextFile, $yours ); fclose( $yourtextFile );
924 # Check for a conflict
925 $cmd = $wgDiff3 . ' -a --overlap-only ' .
926 wfEscapeShellArg( $mytextName ) . ' ' .
927 wfEscapeShellArg( $oldtextName ) . ' ' .
928 wfEscapeShellArg( $yourtextName );
929 $handle = popen( $cmd, 'r' );
931 if( fgets( $handle, 1024 ) ){
939 $cmd = $wgDiff3 . ' -a -e --merge ' .
940 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
941 $handle = popen( $cmd, 'r' );
944 $data = fread( $handle, 8192 );
945 if ( strlen( $data ) == 0 ) {
951 unlink( $mytextName ); unlink( $oldtextName ); unlink( $yourtextName );
953 if ( $result === '' && $old !== '' && $conflict == false ) {
954 wfDebug( "Unexpected null result from diff3. Command: $cmd\n" );
963 function wfVarDump( $var ) {
965 $s = str_replace("\n","<br />\n", var_export( $var, true ) . "\n");
966 if ( headers_sent() ||
!@is_object
( $wgOut ) ) {
969 $wgOut->addHTML( $s );
974 * Provide a simple HTTP error.
976 function wfHttpError( $code, $label, $desc ) {
979 header( "HTTP/1.0 $code $label" );
980 header( "Status: $code $label" );
981 $wgOut->sendCacheControl();
983 header( 'Content-type: text/html' );
984 print "<html><head><title>" .
985 htmlspecialchars( $label ) .
986 "</title></head><body><h1>" .
987 htmlspecialchars( $label ) .
989 htmlspecialchars( $desc ) .
990 "</p></body></html>\n";
994 * Converts an Accept-* header into an array mapping string values to quality
997 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
998 # No arg means accept anything (per HTTP spec)
1000 return array( $def => 1 );
1005 $parts = explode( ',', $accept );
1007 foreach( $parts as $part ) {
1008 # FIXME: doesn't deal with params like 'text/html; level=1'
1009 @list
( $value, $qpart ) = explode( ';', $part );
1010 if( !isset( $qpart ) ) {
1012 } elseif( preg_match( '/q\s*=\s*(\d*\.\d+)/', $qpart, $match ) ) {
1013 $prefs[$value] = $match[1];
1021 * Checks if a given MIME type matches any of the keys in the given
1022 * array. Basic wildcards are accepted in the array keys.
1024 * Returns the matching MIME type (or wildcard) if a match, otherwise
1027 * @param string $type
1028 * @param array $avail
1032 function mimeTypeMatch( $type, $avail ) {
1033 if( array_key_exists($type, $avail) ) {
1036 $parts = explode( '/', $type );
1037 if( array_key_exists( $parts[0] . '/*', $avail ) ) {
1038 return $parts[0] . '/*';
1039 } elseif( array_key_exists( '*/*', $avail ) ) {
1048 * Returns the 'best' match between a client's requested internet media types
1049 * and the server's list of available types. Each list should be an associative
1050 * array of type to preference (preference is a float between 0.0 and 1.0).
1051 * Wildcards in the types are acceptable.
1053 * @param array $cprefs Client's acceptable type list
1054 * @param array $sprefs Server's offered types
1057 * @todo FIXME: doesn't handle params like 'text/plain; charset=UTF-8'
1058 * XXX: generalize to negotiate other stuff
1060 function wfNegotiateType( $cprefs, $sprefs ) {
1063 foreach( array_keys($sprefs) as $type ) {
1064 $parts = explode( '/', $type );
1065 if( $parts[1] != '*' ) {
1066 $ckey = mimeTypeMatch( $type, $cprefs );
1068 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1073 foreach( array_keys( $cprefs ) as $type ) {
1074 $parts = explode( '/', $type );
1075 if( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
1076 $skey = mimeTypeMatch( $type, $sprefs );
1078 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1086 foreach( array_keys( $combine ) as $type ) {
1087 if( $combine[$type] > $bestq ) {
1089 $bestq = $combine[$type];
1098 * Returns an array where the values in the first array are replaced by the
1099 * values in the second array with the corresponding keys
1103 function wfArrayLookup( $a, $b ) {
1104 return array_flip( array_intersect( array_flip( $a ), array_keys( $b ) ) );
1108 * Convenience function; returns MediaWiki timestamp for the present time.
1111 function wfTimestampNow() {
1113 return wfTimestamp( TS_MW
, time() );
1117 * Reference-counted warning suppression
1119 function wfSuppressWarnings( $end = false ) {
1120 static $suppressCount = 0;
1121 static $originalLevel = false;
1124 if ( $suppressCount ) {
1126 if ( !$suppressCount ) {
1127 error_reporting( $originalLevel );
1131 if ( !$suppressCount ) {
1132 $originalLevel = error_reporting( E_ALL
& ~
( E_WARNING | E_NOTICE
) );
1139 * Restore error level to previous value
1141 function wfRestoreWarnings() {
1142 wfSuppressWarnings( true );
1145 # Autodetect, convert and provide timestamps of various types
1148 * Unix time - the number of seconds since 1970-01-01 00:00:00 UTC
1150 define('TS_UNIX', 0);
1153 * MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
1158 * MySQL DATETIME (YYYY-MM-DD HH:MM:SS)
1163 * RFC 2822 format, for E-mail and HTTP headers
1165 define('TS_RFC2822', 3);
1168 * ISO 8601 format with no timezone: 1986-02-09T20:00:00Z
1170 * This is used by Special:Export
1172 define('TS_ISO_8601', 4);
1175 * An Exif timestamp (YYYY:MM:DD HH:MM:SS)
1177 * @link http://exif.org/Exif2-2.PDF The Exif 2.2 spec, see page 28 for the
1178 * DateTime tag and page 36 for the DateTimeOriginal and
1179 * DateTimeDigitized tags.
1181 define('TS_EXIF', 5);
1184 * Oracle format time.
1186 define('TS_ORACLE', 6);
1189 * @param mixed $outputtype A timestamp in one of the supported formats, the
1190 * function will autodetect which format is supplied
1191 and act accordingly.
1192 * @return string Time in the format specified in $outputtype
1194 function wfTimestamp($outputtype=TS_UNIX
,$ts=0) {
1198 } elseif (preg_match("/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)$/",$ts,$da)) {
1200 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1201 (int)$da[2],(int)$da[3],(int)$da[1]);
1202 } elseif (preg_match("/^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/",$ts,$da)) {
1204 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1205 (int)$da[2],(int)$da[3],(int)$da[1]);
1206 } elseif (preg_match("/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/",$ts,$da)) {
1208 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1209 (int)$da[2],(int)$da[3],(int)$da[1]);
1210 } elseif (preg_match("/^(\d{1,13})$/",$ts,$datearray)) {
1213 } elseif (preg_match('/^(\d{1,2})-(...)-(\d\d(\d\d)?) (\d\d)\.(\d\d)\.(\d\d)/', $ts, $da)) {
1215 $uts = strtotime(preg_replace('/(\d\d)\.(\d\d)\.(\d\d)(\.(\d+))?/', "$1:$2:$3",
1216 str_replace("+00:00", "UTC", $ts)));
1217 } elseif (preg_match('/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})Z$/', $ts, $da)) {
1219 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1220 (int)$da[2],(int)$da[3],(int)$da[1]);
1222 # Bogus value; fall back to the epoch...
1223 wfDebug("wfTimestamp() fed bogus time value: $outputtype; $ts\n");
1228 switch($outputtype) {
1232 return gmdate( 'YmdHis', $uts );
1234 return gmdate( 'Y-m-d H:i:s', $uts );
1236 return gmdate( 'Y-m-d\TH:i:s\Z', $uts );
1237 // This shouldn't ever be used, but is included for completeness
1239 return gmdate( 'Y:m:d H:i:s', $uts );
1241 return gmdate( 'D, d M Y H:i:s', $uts ) . ' GMT';
1243 return gmdate( 'd-M-y h.i.s A', $uts) . ' +00:00';
1245 wfDebugDieBacktrace( 'wfTimestamp() called with illegal output type.');
1250 * Return a formatted timestamp, or null if input is null.
1251 * For dealing with nullable timestamp columns in the database.
1252 * @param int $outputtype
1256 function wfTimestampOrNull( $outputtype = TS_UNIX
, $ts = null ) {
1257 if( is_null( $ts ) ) {
1260 return wfTimestamp( $outputtype, $ts );
1265 * Check if the operating system is Windows
1267 * @return bool True if it's Windows, False otherwise.
1269 function wfIsWindows() {
1270 if (substr(php_uname(), 0, 7) == 'Windows') {
1278 * Swap two variables
1280 function swap( &$x, &$y ) {
1286 function wfGetSiteNotice() {
1287 global $wgSiteNotice, $wgTitle, $wgOut;
1288 $fname = 'wfGetSiteNotice';
1289 wfProfileIn( $fname );
1291 $notice = wfMsgForContent( 'sitenotice' );
1292 if( $notice == '<sitenotice>' ||
$notice == '-' ) {
1295 if( $notice == '' ) {
1296 # We may also need to override a message with eg downtime info
1297 # FIXME: make this work!
1298 $notice = $wgSiteNotice;
1300 if($notice != '-' && $notice != '') {
1301 $specialparser = new Parser();
1302 $parserOutput = $specialparser->parse( $notice, $wgTitle, $wgOut->mParserOptions
, false );
1303 $notice = $parserOutput->getText();
1305 wfProfileOut( $fname );
1310 * Format an XML element with given attributes and, optionally, text content.
1311 * Element and attribute names are assumed to be ready for literal inclusion.
1312 * Strings are assumed to not contain XML-illegal characters; special
1313 * characters (<, >, &) are escaped but illegals are not touched.
1315 * @param string $element
1316 * @param array $attribs Name=>value pairs. Values will be escaped.
1317 * @param string $contents NULL to make an open tag only; '' for a contentless closed tag (default)
1320 function wfElement( $element, $attribs = null, $contents = '') {
1321 $out = '<' . $element;
1322 if( !is_null( $attribs ) ) {
1323 foreach( $attribs as $name => $val ) {
1324 $out .= ' ' . $name . '="' . htmlspecialchars( $val ) . '"';
1327 if( is_null( $contents ) ) {
1330 if( $contents == '' ) {
1333 $out .= '>' . htmlspecialchars( $contents ) . "</$element>";
1340 * Format an XML element as with wfElement(), but run text through the
1341 * UtfNormal::cleanUp() validator first to ensure that no invalid UTF-8
1344 * @param string $element
1345 * @param array $attribs Name=>value pairs. Values will be escaped.
1346 * @param string $contents NULL to make an open tag only; '' for a contentless closed tag (default)
1349 function wfElementClean( $element, $attribs = array(), $contents = '') {
1351 $attribs = array_map( array( 'UtfNormal', 'cleanUp' ), $attribs );
1354 $contents = UtfNormal
::cleanUp( $contents );
1356 return wfElement( $element, $attribs, $contents );
1360 function wfOpenElement( $element, $attribs = null ) { return wfElement( $element, $attribs, null ); }
1361 function wfCloseElement( $element ) { return "</$element>"; }
1364 * Create a namespace selector
1366 * @param mixed $selected The namespace which should be selected, default ''
1367 * @param string $allnamespaces Value of a special item denoting all namespaces. Null to not include (default)
1368 * @return Html string containing the namespace selector
1370 function &HTMLnamespaceselector($selected = '', $allnamespaces = null) {
1372 if( $selected !== '' ) {
1373 if( is_null( $selected ) ) {
1374 // No namespace selected; let exact match work without hitting Main
1377 // Let input be numeric strings without breaking the empty match.
1378 $selected = intval( $selected );
1381 $s = "<select name='namespace' class='namespaceselector'>\n\t";
1382 $arr = $wgContLang->getFormattedNamespaces();
1383 if( !is_null($allnamespaces) ) {
1384 $arr = array($allnamespaces => wfMsgHtml('namespacesall')) +
$arr;
1386 foreach ($arr as $index => $name) {
1387 if ($index < NS_MAIN
) continue;
1389 $name = $index !== 0 ?
$name : wfMsgHtml('blanknamespace');
1391 if ($index === $selected) {
1392 $s .= wfElement("option",
1393 array("value" => $index, "selected" => "selected"),
1396 $s .= wfElement("option", array("value" => $index), $name);
1399 $s .= "\n</select>\n";
1403 /** Global singleton instance of MimeMagic. This is initialized on demand,
1404 * please always use the wfGetMimeMagic() function to get the instance.
1410 /** Factory functions for the global MimeMagic object.
1411 * This function always returns the same singleton instance of MimeMagic.
1412 * That objects will be instantiated on the first call to this function.
1413 * If needed, the MimeMagic.php file is automatically included by this function.
1414 * @return MimeMagic the global MimeMagic objects.
1416 function &wfGetMimeMagic() {
1417 global $wgMimeMagic;
1419 if (!is_null($wgMimeMagic)) {
1420 return $wgMimeMagic;
1423 if (!class_exists("MimeMagic")) {
1425 require_once("MimeMagic.php");
1428 $wgMimeMagic= new MimeMagic();
1430 return $wgMimeMagic;
1435 * Tries to get the system directory for temporary files.
1436 * The TMPDIR, TMP, and TEMP environment variables are checked in sequence,
1437 * and if none are set /tmp is returned as the generic Unix default.
1439 * NOTE: When possible, use the tempfile() function to create temporary
1440 * files to avoid race conditions on file creation, etc.
1444 function wfTempDir() {
1445 foreach( array( 'TMPDIR', 'TMP', 'TEMP' ) as $var ) {
1446 $tmp = getenv( $var );
1447 if( $tmp && file_exists( $tmp ) && is_dir( $tmp ) && is_writable( $tmp ) ) {
1451 # Hope this is Unix of some kind!
1456 * Make directory, and make all parent directories if they don't exist
1458 function wfMkdirParents( $fullDir, $mode ) {
1459 $parts = explode( '/', $fullDir );
1462 foreach ( $parts as $dir ) {
1463 $path .= $dir . '/';
1464 if ( !is_dir( $path ) ) {
1465 if ( !mkdir( $path, $mode ) ) {
1474 * Increment a statistics counter
1476 function wfIncrStats( $key ) {
1477 global $wgDBname, $wgMemc;
1478 $key = "$wgDBname:stats:$key";
1479 if ( is_null( $wgMemc->incr( $key ) ) ) {
1480 $wgMemc->add( $key, 1 );
1485 * @param mixed $nr The number to format
1486 * @param int $acc The number of digits after the decimal point, default 2
1487 * @param bool $round Whether or not to round the value, default true
1490 function wfPercent( $nr, $acc = 2, $round = true ) {
1491 $ret = sprintf( "%.${acc}f", $nr );
1492 return $round ?
round( $ret, $acc ) . '%' : "$ret%";
1496 * Encrypt a username/password.
1498 * @param string $userid ID of the user
1499 * @param string $password Password of the user
1500 * @return string Hashed password
1502 function wfEncryptPassword( $userid, $password ) {
1503 global $wgPasswordSalt;
1504 $p = md5( $password);
1507 return md5( "{$userid}-{$p}" );
1513 * Appends to second array if $value differs from that in $default
1515 function wfAppendToArrayIfNotDefault( $key, $value, $default, &$changed ) {
1516 if ( is_null( $changed ) ) {
1517 wfDebugDieBacktrace('GlobalFunctions::wfAppendToArrayIfNotDefault got null');
1519 if ( $default[$key] !== $value ) {
1520 $changed[$key] = $value;
1525 * Since wfMsg() and co suck, they don't return false if the message key they
1526 * looked up didn't exist but a XHTML string, this function checks for the
1527 * nonexistance of messages by looking at wfMsg() output
1529 * @param $msg The message key looked up
1530 * @param $wfMsgOut The output of wfMsg*()
1533 function wfEmptyMsg( $msg, $wfMsgOut ) {
1534 return $wfMsgOut === "<$msg>";
1538 * Find out whether or not a mixed variable exists in a string
1540 * @param mixed needle
1541 * @param string haystack
1544 function in_string( $needle, $str ) {
1545 return strpos( $str, $needle ) !== false;
1549 * Returns a regular expression of url protocols
1553 function wfUrlProtocols() {
1554 global $wgUrlProtocols;
1556 $protocols = array();
1557 foreach ($wgUrlProtocols as $protocol)
1558 $protocols[] = preg_quote( $protocol, '/' );
1560 return implode( '|', $protocols );
1564 * Check if a string is well-formed XML.
1565 * Must include the surrounding tag.
1567 * @param string $text
1570 * @todo Error position reporting return
1572 function wfIsWellFormedXml( $text ) {
1573 $parser = xml_parser_create( "UTF-8" );
1575 # case folding violates XML standard, turn it off
1576 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING
, false );
1578 if( !xml_parse( $parser, $text, true ) ) {
1579 $err = xml_error_string( xml_get_error_code( $parser ) );
1580 $position = xml_get_current_byte_index( $parser );
1581 //$fragment = $this->extractFragment( $html, $position );
1582 //$this->mXmlError = "$err at byte $position:\n$fragment";
1583 xml_parser_free( $parser );
1586 xml_parser_free( $parser );
1591 * Check if a string is a well-formed XML fragment.
1592 * Wraps fragment in an <html> bit and doctype, so it can be a fragment
1593 * and can use HTML named entities.
1595 * @param string $text
1598 function wfIsWellFormedXmlFragment( $text ) {
1600 '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" ' .
1601 '"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">' .
1605 return wfIsWellFormedXml( $html );
1609 * shell_exec() with time and memory limits mirrored from the PHP configuration,
1612 function wfShellExec( $cmd )
1616 if ( php_uname( 's' ) == 'Linux' ) {
1617 $time = ini_get( 'max_execution_time' );
1618 $mem = ini_get( 'memory_limit' );
1619 if( preg_match( '/^([0-9]+)[Mm]$/', trim( $mem ), $m ) ) {
1620 $mem = intval( $m[1] * (1024*1024) );
1622 if ( $time > 0 && $mem > 0 ) {
1623 $script = "$IP/bin/ulimit.sh";
1624 if ( is_executable( $script ) ) {
1625 $memKB = intval( $mem / 1024 );
1626 $cmd = escapeshellarg( $script ) . " $time $memKB $cmd";
1630 return shell_exec( $cmd );