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, $wgProfileStack, $wgProfileLimit, $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;
393 global $wgContLang, $wgLanguageCode;
394 global $wgMessageCache, $wgLang;
396 if ( is_object( $wgMessageCache ) )
397 $transstat = $wgMessageCache->getTransform();
399 if( is_object( $wgMessageCache ) ) {
401 $wgMessageCache->disableTransform();
402 $message = $wgMessageCache->get( $key, $useDB, $forContent );
405 $lang = &$wgContLang;
410 wfSuppressWarnings();
412 if( is_object( $lang ) ) {
413 $message = $lang->getMessage( $key );
418 if($message === false)
419 $message = Language
::getMessage($key);
420 if ( $transform && strstr( $message, '{{' ) !== false ) {
421 $message = $wgParser->transformMsg($message, $wgMsgParserOptions);
425 if ( is_object( $wgMessageCache ) && ! $transform )
426 $wgMessageCache->setTransform( $transstat );
432 * Replace message parameter keys on the given formatted output.
434 * @param string $message
439 function wfMsgReplaceArgs( $message, $args ) {
440 # Fix windows line-endings
441 # Some messages are split with explode("\n", $msg)
442 $message = str_replace( "\r", '', $message );
445 if ( count( $args ) )
446 if ( is_array( $args[0] ) )
447 foreach ( $args[0] as $key => $val )
448 $message = str_replace( '$' . $key, $val, $message );
450 foreach( $args as $n => $param )
451 $replacementKeys['$' . ($n +
1)] = $param;
452 $message = strtr( $message, $replacementKeys );
459 * Return an HTML-escaped version of a message.
460 * Parameter replacements, if any, are done *after* the HTML-escaping,
461 * so parameters may contain HTML (eg links or form controls). Be sure
462 * to pre-escape them if you really do want plaintext, or just wrap
463 * the whole thing in htmlspecialchars().
466 * @param string ... parameters
469 function wfMsgHtml( $key ) {
470 $args = func_get_args();
471 array_shift( $args );
472 return wfMsgReplaceArgs( htmlspecialchars( wfMsgGetKey( $key, true ) ), $args );
476 * Return an HTML version of message
477 * Parameter replacements, if any, are done *after* parsing the wiki-text message,
478 * so parameters may contain HTML (eg links or form controls). Be sure
479 * to pre-escape them if you really do want plaintext, or just wrap
480 * the whole thing in htmlspecialchars().
483 * @param string ... parameters
486 function wfMsgWikiHtml( $key ) {
488 $args = func_get_args();
489 array_shift( $args );
490 return wfMsgReplaceArgs( $wgOut->parse( wfMsgGetKey( $key, true ), /* can't be set to false */ true ), $args );
494 * Just like exit() but makes a note of it.
495 * Commits open transactions except if the error parameter is set
497 function wfAbruptExit( $error = false ){
498 global $wgLoadBalancer;
499 static $called = false;
505 if( function_exists( 'debug_backtrace' ) ){ // PHP >= 4.3
506 $bt = debug_backtrace();
507 for($i = 0; $i < count($bt) ; $i++
){
508 $file = isset($bt[$i]['file']) ?
$bt[$i]['file'] : "unknown";
509 $line = isset($bt[$i]['line']) ?
$bt[$i]['line'] : "unknown";
510 wfDebug("WARNING: Abrupt exit in $file at line $line\n");
513 wfDebug('WARNING: Abrupt exit\n');
516 $wgLoadBalancer->closeAll();
524 function wfErrorExit() {
525 wfAbruptExit( true );
529 * Die with a backtrace
530 * This is meant as a debugging aid to track down where bad data comes from.
531 * Shouldn't be used in production code except maybe in "shouldn't happen" areas.
533 * @param string $msg Message shown when dieing.
535 function wfDebugDieBacktrace( $msg = '' ) {
536 global $wgCommandLineMode;
538 $backtrace = wfBacktrace();
539 if ( $backtrace !== false ) {
540 if ( $wgCommandLineMode ) {
541 $msg .= "\nBacktrace:\n$backtrace";
543 $msg .= "\n<p>Backtrace:</p>\n$backtrace";
547 echo wfReportTime()."\n";
552 * Returns a HTML comment with the elapsed time since request.
553 * This method has no side effects.
556 function wfReportTime() {
557 global $wgRequestTime;
560 list( $usec, $sec ) = explode( ' ', $wgRequestTime );
561 $start = (float)$sec +
(float)$usec;
562 $elapsed = $now - $start;
564 # Use real server name if available, so we know which machine
565 # in a server farm generated the current page.
566 if ( function_exists( 'posix_uname' ) ) {
567 $uname = @posix_uname
();
571 if( is_array( $uname ) && isset( $uname['nodename'] ) ) {
572 $hostname = $uname['nodename'];
574 # This may be a virtual server.
575 $hostname = $_SERVER['SERVER_NAME'];
577 $com = sprintf( "<!-- Served by %s in %01.2f secs. -->",
578 $hostname, $elapsed );
582 function wfBacktrace() {
583 global $wgCommandLineMode;
584 if ( !function_exists( 'debug_backtrace' ) ) {
588 if ( $wgCommandLineMode ) {
593 $backtrace = debug_backtrace();
594 foreach( $backtrace as $call ) {
595 if( isset( $call['file'] ) ) {
596 $f = explode( DIRECTORY_SEPARATOR
, $call['file'] );
597 $file = $f[count($f)-1];
601 if( isset( $call['line'] ) ) {
602 $line = $call['line'];
606 if ( $wgCommandLineMode ) {
607 $msg .= "$file line $line calls ";
609 $msg .= '<li>' . $file . ' line ' . $line . ' calls ';
611 if( !empty( $call['class'] ) ) $msg .= $call['class'] . '::';
612 $msg .= $call['function'] . '()';
614 if ( $wgCommandLineMode ) {
620 if ( $wgCommandLineMode ) {
630 /* Some generic result counters, pulled out of SearchEngine */
636 function wfShowingResults( $offset, $limit ) {
638 return wfMsg( 'showingresults', $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+
1 ) );
644 function wfShowingResultsNum( $offset, $limit, $num ) {
646 return wfMsg( 'showingresultsnum', $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+
1 ), $wgLang->formatNum( $num ) );
652 function wfViewPrevNext( $offset, $limit, $link, $query = '', $atend = false ) {
653 global $wgUser, $wgLang;
654 $fmtLimit = $wgLang->formatNum( $limit );
655 $prev = wfMsg( 'prevn', $fmtLimit );
656 $next = wfMsg( 'nextn', $fmtLimit );
658 if( is_object( $link ) ) {
661 $title = Title
::newFromText( $link );
662 if( is_null( $title ) ) {
667 $sk = $wgUser->getSkin();
668 if ( 0 != $offset ) {
669 $po = $offset - $limit;
670 if ( $po < 0 ) { $po = 0; }
671 $q = "limit={$limit}&offset={$po}";
672 if ( '' != $query ) { $q .= '&'.$query; }
673 $plink = '<a href="' . $title->escapeLocalUrl( $q ) . "\">{$prev}</a>";
674 } else { $plink = $prev; }
676 $no = $offset +
$limit;
677 $q = 'limit='.$limit.'&offset='.$no;
678 if ( '' != $query ) { $q .= '&'.$query; }
683 $nlink = '<a href="' . $title->escapeLocalUrl( $q ) . "\">{$next}</a>";
685 $nums = wfNumLink( $offset, 20, $title, $query ) . ' | ' .
686 wfNumLink( $offset, 50, $title, $query ) . ' | ' .
687 wfNumLink( $offset, 100, $title, $query ) . ' | ' .
688 wfNumLink( $offset, 250, $title, $query ) . ' | ' .
689 wfNumLink( $offset, 500, $title, $query );
691 return wfMsg( 'viewprevnext', $plink, $nlink, $nums );
697 function wfNumLink( $offset, $limit, &$title, $query = '' ) {
698 global $wgUser, $wgLang;
699 if ( '' == $query ) { $q = ''; }
700 else { $q = $query.'&'; }
701 $q .= 'limit='.$limit.'&offset='.$offset;
703 $fmtLimit = $wgLang->formatNum( $limit );
704 $s = '<a href="' . $title->escapeLocalUrl( $q ) . "\">{$fmtLimit}</a>";
710 * @todo FIXME: we may want to blacklist some broken browsers
712 * @return bool Whereas client accept gzip compression
714 function wfClientAcceptsGzip() {
717 # FIXME: we may want to blacklist some broken browsers
719 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
720 $_SERVER['HTTP_ACCEPT_ENCODING'],
722 if( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) return false;
723 wfDebug( " accepts gzip\n" );
731 * Yay, more global functions!
733 function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) {
735 return $wgRequest->getLimitOffset( $deflimit, $optionname );
739 * Escapes the given text so that it may be output using addWikiText()
740 * without any linking, formatting, etc. making its way through. This
741 * is achieved by substituting certain characters with HTML entities.
742 * As required by the callers, <nowiki> is not used. It currently does
743 * not filter out characters which have special meaning only at the
744 * start of a line, such as "*".
746 * @param string $text Text to be escaped
748 function wfEscapeWikiText( $text ) {
750 array( '[', '|', '\'', 'ISBN ' , '://' , "\n=", '{{' ),
751 array( '[', '|', ''', 'ISBN ', '://' , "\n=", '{{' ),
752 htmlspecialchars($text) );
759 function wfQuotedPrintable( $string, $charset = '' ) {
760 # Probably incomplete; see RFC 2045
761 if( empty( $charset ) ) {
762 global $wgInputEncoding;
763 $charset = $wgInputEncoding;
765 $charset = strtoupper( $charset );
766 $charset = str_replace( 'ISO-8859', 'ISO8859', $charset ); // ?
768 $illegal = '\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\xff=';
769 $replace = $illegal . '\t ?_';
770 if( !preg_match( "/[$illegal]/", $string ) ) return $string;
771 $out = "=?$charset?Q?";
772 $out .= preg_replace( "/([$replace])/e", 'sprintf("=%02X",ord("$1"))', $string );
778 * Returns an escaped string suitable for inclusion in a string literal
779 * for JavaScript source code.
780 * Illegal control characters are assumed not to be present.
782 * @param string $string
785 function wfEscapeJsString( $string ) {
786 // See ECMA 262 section 7.8.4 for string literal format
794 # To avoid closing the element or CDATA section
798 return strtr( $string, $pairs );
806 $st = explode( ' ', microtime() );
807 return (float)$st[0] +
(float)$st[1];
811 * Changes the first character to an HTML entity
813 function wfHtmlEscapeFirst( $text ) {
815 $newText = substr($text, 1);
816 return "&#$ord;$newText";
820 * Sets dest to source and returns the original value of dest
821 * If source is NULL, it just returns the value, it doesn't set the variable
823 function wfSetVar( &$dest, $source ) {
825 if ( !is_null( $source ) ) {
832 * As for wfSetVar except setting a bit
834 function wfSetBit( &$dest, $bit, $state = true ) {
835 $temp = (bool)($dest & $bit );
836 if ( !is_null( $state ) ) {
847 * This function takes two arrays as input, and returns a CGI-style string, e.g.
848 * "days=7&limit=100". Options in the first array override options in the second.
849 * Options set to "" will not be output.
851 function wfArrayToCGI( $array1, $array2 = NULL )
853 if ( !is_null( $array2 ) ) {
854 $array1 = $array1 +
$array2;
858 foreach ( $array1 as $key => $value ) {
859 if ( '' !== $value ) {
863 $cgi .= urlencode( $key ) . '=' . urlencode( $value );
870 * This is obsolete, use SquidUpdate::purge()
873 function wfPurgeSquidServers ($urlArr) {
874 SquidUpdate
::purge( $urlArr );
878 * Windows-compatible version of escapeshellarg()
879 * Windows doesn't recognise single-quotes in the shell, but the escapeshellarg()
880 * function puts single quotes in regardless of OS
882 function wfEscapeShellArg( ) {
883 $args = func_get_args();
886 foreach ( $args as $arg ) {
893 if ( wfIsWindows() ) {
894 $retVal .= '"' . str_replace( '"','\"', $arg ) . '"';
896 $retVal .= escapeshellarg( $arg );
903 * wfMerge attempts to merge differences between three texts.
904 * Returns true for a clean merge and false for failure or a conflict.
906 function wfMerge( $old, $mine, $yours, &$result ){
909 # This check may also protect against code injection in
910 # case of broken installations.
911 if(! file_exists( $wgDiff3 ) ){
912 wfDebug( "diff3 not found\n" );
916 # Make temporary files
918 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
919 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
920 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
922 fwrite( $oldtextFile, $old ); fclose( $oldtextFile );
923 fwrite( $mytextFile, $mine ); fclose( $mytextFile );
924 fwrite( $yourtextFile, $yours ); fclose( $yourtextFile );
926 # Check for a conflict
927 $cmd = $wgDiff3 . ' -a --overlap-only ' .
928 wfEscapeShellArg( $mytextName ) . ' ' .
929 wfEscapeShellArg( $oldtextName ) . ' ' .
930 wfEscapeShellArg( $yourtextName );
931 $handle = popen( $cmd, 'r' );
933 if( fgets( $handle, 1024 ) ){
941 $cmd = $wgDiff3 . ' -a -e --merge ' .
942 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
943 $handle = popen( $cmd, 'r' );
946 $data = fread( $handle, 8192 );
947 if ( strlen( $data ) == 0 ) {
953 unlink( $mytextName ); unlink( $oldtextName ); unlink( $yourtextName );
955 if ( $result === '' && $old !== '' && $conflict == false ) {
956 wfDebug( "Unexpected null result from diff3. Command: $cmd\n" );
965 function wfVarDump( $var ) {
967 $s = str_replace("\n","<br />\n", var_export( $var, true ) . "\n");
968 if ( headers_sent() ||
!@is_object
( $wgOut ) ) {
971 $wgOut->addHTML( $s );
976 * Provide a simple HTTP error.
978 function wfHttpError( $code, $label, $desc ) {
981 header( "HTTP/1.0 $code $label" );
982 header( "Status: $code $label" );
983 $wgOut->sendCacheControl();
985 header( 'Content-type: text/html' );
986 print "<html><head><title>" .
987 htmlspecialchars( $label ) .
988 "</title></head><body><h1>" .
989 htmlspecialchars( $label ) .
991 htmlspecialchars( $desc ) .
992 "</p></body></html>\n";
996 * Converts an Accept-* header into an array mapping string values to quality
999 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
1000 # No arg means accept anything (per HTTP spec)
1002 return array( $def => 1 );
1007 $parts = explode( ',', $accept );
1009 foreach( $parts as $part ) {
1010 # FIXME: doesn't deal with params like 'text/html; level=1'
1011 @list
( $value, $qpart ) = explode( ';', $part );
1012 if( !isset( $qpart ) ) {
1014 } elseif( preg_match( '/q\s*=\s*(\d*\.\d+)/', $qpart, $match ) ) {
1015 $prefs[$value] = $match[1];
1023 * Checks if a given MIME type matches any of the keys in the given
1024 * array. Basic wildcards are accepted in the array keys.
1026 * Returns the matching MIME type (or wildcard) if a match, otherwise
1029 * @param string $type
1030 * @param array $avail
1034 function mimeTypeMatch( $type, $avail ) {
1035 if( array_key_exists($type, $avail) ) {
1038 $parts = explode( '/', $type );
1039 if( array_key_exists( $parts[0] . '/*', $avail ) ) {
1040 return $parts[0] . '/*';
1041 } elseif( array_key_exists( '*/*', $avail ) ) {
1050 * Returns the 'best' match between a client's requested internet media types
1051 * and the server's list of available types. Each list should be an associative
1052 * array of type to preference (preference is a float between 0.0 and 1.0).
1053 * Wildcards in the types are acceptable.
1055 * @param array $cprefs Client's acceptable type list
1056 * @param array $sprefs Server's offered types
1059 * @todo FIXME: doesn't handle params like 'text/plain; charset=UTF-8'
1060 * XXX: generalize to negotiate other stuff
1062 function wfNegotiateType( $cprefs, $sprefs ) {
1065 foreach( array_keys($sprefs) as $type ) {
1066 $parts = explode( '/', $type );
1067 if( $parts[1] != '*' ) {
1068 $ckey = mimeTypeMatch( $type, $cprefs );
1070 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1075 foreach( array_keys( $cprefs ) as $type ) {
1076 $parts = explode( '/', $type );
1077 if( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
1078 $skey = mimeTypeMatch( $type, $sprefs );
1080 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1088 foreach( array_keys( $combine ) as $type ) {
1089 if( $combine[$type] > $bestq ) {
1091 $bestq = $combine[$type];
1100 * Returns an array where the values in the first array are replaced by the
1101 * values in the second array with the corresponding keys
1105 function wfArrayLookup( $a, $b ) {
1106 return array_flip( array_intersect( array_flip( $a ), array_keys( $b ) ) );
1110 * Convenience function; returns MediaWiki timestamp for the present time.
1113 function wfTimestampNow() {
1115 return wfTimestamp( TS_MW
, time() );
1119 * Reference-counted warning suppression
1121 function wfSuppressWarnings( $end = false ) {
1122 static $suppressCount = 0;
1123 static $originalLevel = false;
1126 if ( $suppressCount ) {
1128 if ( !$suppressCount ) {
1129 error_reporting( $originalLevel );
1133 if ( !$suppressCount ) {
1134 $originalLevel = error_reporting( E_ALL
& ~
( E_WARNING | E_NOTICE
) );
1141 * Restore error level to previous value
1143 function wfRestoreWarnings() {
1144 wfSuppressWarnings( true );
1147 # Autodetect, convert and provide timestamps of various types
1150 * Unix time - the number of seconds since 1970-01-01 00:00:00 UTC
1152 define('TS_UNIX', 0);
1155 * MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
1160 * MySQL DATETIME (YYYY-MM-DD HH:MM:SS)
1165 * RFC 2822 format, for E-mail and HTTP headers
1167 define('TS_RFC2822', 3);
1170 * ISO 8601 format with no timezone: 1986-02-09T20:00:00Z
1172 * This is used by Special:Export
1174 define('TS_ISO_8601', 4);
1177 * An Exif timestamp (YYYY:MM:DD HH:MM:SS)
1179 * @link http://exif.org/Exif2-2.PDF The Exif 2.2 spec, see page 28 for the
1180 * DateTime tag and page 36 for the DateTimeOriginal and
1181 * DateTimeDigitized tags.
1183 define('TS_EXIF', 5);
1186 * Oracle format time.
1188 define('TS_ORACLE', 6);
1191 * @param mixed $outputtype A timestamp in one of the supported formats, the
1192 * function will autodetect which format is supplied
1193 and act accordingly.
1194 * @return string Time in the format specified in $outputtype
1196 function wfTimestamp($outputtype=TS_UNIX
,$ts=0) {
1200 } elseif (preg_match("/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)$/",$ts,$da)) {
1202 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1203 (int)$da[2],(int)$da[3],(int)$da[1]);
1204 } elseif (preg_match("/^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/",$ts,$da)) {
1206 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1207 (int)$da[2],(int)$da[3],(int)$da[1]);
1208 } elseif (preg_match("/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/",$ts,$da)) {
1210 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1211 (int)$da[2],(int)$da[3],(int)$da[1]);
1212 } elseif (preg_match("/^(\d{1,13})$/",$ts,$datearray)) {
1215 } elseif (preg_match('/^(\d{1,2})-(...)-(\d\d(\d\d)?) (\d\d)\.(\d\d)\.(\d\d)/', $ts, $da)) {
1217 $uts = strtotime(preg_replace('/(\d\d)\.(\d\d)\.(\d\d)(\.(\d+))?/', "$1:$2:$3",
1218 str_replace("+00:00", "UTC", $ts)));
1219 } elseif (preg_match('/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})Z$/', $ts, $da)) {
1221 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1222 (int)$da[2],(int)$da[3],(int)$da[1]);
1224 # Bogus value; fall back to the epoch...
1225 wfDebug("wfTimestamp() fed bogus time value: $outputtype; $ts\n");
1230 switch($outputtype) {
1234 return gmdate( 'YmdHis', $uts );
1236 return gmdate( 'Y-m-d H:i:s', $uts );
1238 return gmdate( 'Y-m-d\TH:i:s\Z', $uts );
1239 // This shouldn't ever be used, but is included for completeness
1241 return gmdate( 'Y:m:d H:i:s', $uts );
1243 return gmdate( 'D, d M Y H:i:s', $uts ) . ' GMT';
1245 return gmdate( 'd-M-y h.i.s A', $uts) . ' +00:00';
1247 wfDebugDieBacktrace( 'wfTimestamp() called with illegal output type.');
1252 * Return a formatted timestamp, or null if input is null.
1253 * For dealing with nullable timestamp columns in the database.
1254 * @param int $outputtype
1258 function wfTimestampOrNull( $outputtype = TS_UNIX
, $ts = null ) {
1259 if( is_null( $ts ) ) {
1262 return wfTimestamp( $outputtype, $ts );
1267 * Check where as the operating system is Windows
1269 * @return bool True if it's windows, False otherwise.
1271 function wfIsWindows() {
1272 if (substr(php_uname(), 0, 7) == 'Windows') {
1280 * Swap two variables
1282 function swap( &$x, &$y ) {
1288 function wfGetSiteNotice() {
1289 global $wgSiteNotice, $wgTitle, $wgOut;
1290 $fname = 'wfGetSiteNotice';
1291 wfProfileIn( $fname );
1293 $notice = wfMsg( 'sitenotice' );
1294 if( $notice == '<sitenotice>' ||
$notice == '-' ) {
1297 if( $notice == '' ) {
1298 # We may also need to override a message with eg downtime info
1299 # FIXME: make this work!
1300 $notice = $wgSiteNotice;
1302 if($notice != '-' && $notice != '') {
1303 $specialparser = new Parser();
1304 $parserOutput = $specialparser->parse( $notice, $wgTitle, $wgOut->mParserOptions
, false );
1305 $notice = $parserOutput->getText();
1307 wfProfileOut( $fname );
1312 * Format an XML element with given attributes and, optionally, text content.
1313 * Element and attribute names are assumed to be ready for literal inclusion.
1314 * Strings are assumed to not contain XML-illegal characters; special
1315 * characters (<, >, &) are escaped but illegals are not touched.
1317 * @param string $element
1318 * @param array $attribs Name=>value pairs. Values will be escaped.
1319 * @param string $contents NULL to make an open tag only; '' for a contentless closed tag (default)
1322 function wfElement( $element, $attribs = null, $contents = '') {
1323 $out = '<' . $element;
1324 if( !is_null( $attribs ) ) {
1325 foreach( $attribs as $name => $val ) {
1326 $out .= ' ' . $name . '="' . htmlspecialchars( $val ) . '"';
1329 if( is_null( $contents ) ) {
1332 if( $contents == '' ) {
1336 $out .= htmlspecialchars( $contents );
1337 $out .= "</$element>";
1344 * Format an XML element as with wfElement(), but run text through the
1345 * UtfNormal::cleanUp() validator first to ensure that no invalid UTF-8
1348 * @param string $element
1349 * @param array $attribs Name=>value pairs. Values will be escaped.
1350 * @param string $contents NULL to make an open tag only; '' for a contentless closed tag (default)
1353 function wfElementClean( $element, $attribs = array(), $contents = '') {
1355 $attribs = array_map( array( 'UtfNormal', 'cleanUp' ), $attribs );
1358 $contents = UtfNormal
::cleanUp( $contents );
1360 return wfElement( $element, $attribs, $contents );
1364 function wfOpenElement( $element ) { return "<$element>"; }
1365 function wfCloseElement( $element ) { return "</$element>"; }
1368 * Create a namespace selector
1370 * @param mixed $selected The namespace which should be selected, default ''
1371 * @param string $allnamespaces Value of a special item denoting all namespaces. Null to not include (default)
1372 * @return Html string containing the namespace selector
1374 function &HTMLnamespaceselector($selected = '', $allnamespaces = null) {
1376 if( $selected !== '' ) {
1377 if( is_null( $selected ) ) {
1378 // No namespace selected; let exact match work without hitting Main
1381 // Let input be numeric strings without breaking the empty match.
1382 $selected = intval( $selected );
1385 $s = "<select name='namespace' class='namespaceselector'>\n\t";
1386 $arr = $wgContLang->getFormattedNamespaces();
1387 if( !is_null($allnamespaces) ) {
1388 $arr = array($allnamespaces => wfMsgHtml('namespacesall')) +
$arr;
1390 foreach ($arr as $index => $name) {
1391 if ($index < NS_MAIN
) continue;
1393 $name = $index !== 0 ?
$name : wfMsgHtml('blanknamespace');
1395 if ($index === $selected) {
1396 $s .= wfElement("option",
1397 array("value" => $index, "selected" => "selected"),
1400 $s .= wfElement("option", array("value" => $index), $name);
1403 $s .= "\n</select>\n";
1407 /** Global singleton instance of MimeMagic. This is initialized on demand,
1408 * please always use the wfGetMimeMagic() function to get the instance.
1414 /** Factory functions for the global MimeMagic object.
1415 * This function always returns the same singleton instance of MimeMagic.
1416 * That objects will be instantiated on the first call to this function.
1417 * If needed, the MimeMagic.php file is automatically included by this function.
1418 * @return MimeMagic the global MimeMagic objects.
1420 function &wfGetMimeMagic() {
1421 global $wgMimeMagic;
1423 if (!is_null($wgMimeMagic)) {
1424 return $wgMimeMagic;
1427 if (!class_exists("MimeMagic")) {
1429 require_once("MimeMagic.php");
1432 $wgMimeMagic= new MimeMagic();
1434 return $wgMimeMagic;
1439 * Tries to get the system directory for temporary files.
1440 * The TMPDIR, TMP, and TEMP environment variables are checked in sequence,
1441 * and if none are set /tmp is returned as the generic Unix default.
1443 * NOTE: When possible, use the tempfile() function to create temporary
1444 * files to avoid race conditions on file creation, etc.
1448 function wfTempDir() {
1449 foreach( array( 'TMPDIR', 'TMP', 'TEMP' ) as $var ) {
1450 $tmp = getenv( $var );
1451 if( $tmp && file_exists( $tmp ) && is_dir( $tmp ) && is_writable( $tmp ) ) {
1455 # Hope this is Unix of some kind!
1460 * Make directory, and make all parent directories if they don't exist
1462 function wfMkdirParents( $fullDir, $mode ) {
1463 $parts = explode( '/', $fullDir );
1466 foreach ( $parts as $dir ) {
1467 $path .= $dir . '/';
1468 if ( !is_dir( $path ) ) {
1469 if ( !mkdir( $path, $mode ) ) {
1478 * Increment a statistics counter
1480 function wfIncrStats( $key ) {
1481 global $wgDBname, $wgMemc;
1482 $key = "$wgDBname:stats:$key";
1483 if ( is_null( $wgMemc->incr( $key ) ) ) {
1484 $wgMemc->add( $key, 1 );
1489 * @param mixed $nr The number to format
1490 * @param int $acc The number of digits after the decimal point, default 2
1491 * @param bool $round Whether or not to round the value, default true
1494 function wfPercent( $nr, $acc = 2, $round = true ) {
1495 $ret = sprintf( "%.${acc}f", $nr );
1496 return $round ?
round( $ret, $acc ) . '%' : "$ret%";
1500 * Encrypt a username/password.
1502 * @param string $userid ID of the user
1503 * @param string $password Password of the user
1504 * @return string Hashed password
1506 function wfEncryptPassword( $userid, $password ) {
1507 global $wgPasswordSalt;
1508 $p = md5( $password);
1511 return md5( "{$userid}-{$p}" );
1517 * Appends to second array if $value differs from that in $default
1519 function wfAppendToArrayIfNotDefault( $key, $value, $default, &$changed ) {
1520 if ( is_null( $changed ) ) {
1521 wfDebugDieBacktrace('GlobalFunctions::wfAppendToArrayIfNotDefault got null');
1523 if ( $default[$key] !== $value ) {
1524 $changed[$key] = $value;
1529 * Since wfMsg() and co suck, they don't return false if the message key they
1530 * looked up didn't exist but a XHTML string, this function checks for the
1531 * nonexistance of messages by looking at wfMsg() output
1533 * @param $msg The message key looked up
1534 * @param $wfMsgOut The output of wfMsg*()
1537 function wfEmptyMsg( $msg, $wfMsgOut ) {
1538 return $wfMsgOut === "<$msg>";
1542 * Find out whether or not a mixed variable exists in a string
1544 * @param mixed needle
1545 * @param string haystack
1548 function in_string( $needle, $str ) {
1549 return strpos( $str, $needle ) !== false;
1553 * Returns a regular expression of url protocols
1557 function wfUrlProtocols() {
1558 global $wgUrlProtocols;
1561 foreach ($wgUrlProtocols as $protocol)
1562 $x[] = preg_quote( $protocol, '/' );
1564 return implode( '|', $x );
1568 * Check if a string is well-formed XML.
1569 * Must include the surrounding tag.
1571 * @param string $text
1574 * @todo Error position reporting return
1576 function wfIsWellFormedXml( $text ) {
1577 $parser = xml_parser_create( "UTF-8" );
1579 # case folding violates XML standard, turn it off
1580 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING
, false );
1582 if( !xml_parse( $parser, $text, true ) ) {
1583 $err = xml_error_string( xml_get_error_code( $parser ) );
1584 $position = xml_get_current_byte_index( $parser );
1585 //$fragment = $this->extractFragment( $html, $position );
1586 //$this->mXmlError = "$err at byte $position:\n$fragment";
1587 xml_parser_free( $parser );
1590 xml_parser_free( $parser );
1595 * Check if a string is a well-formed XML fragment.
1596 * Wraps fragment in an <html> bit and doctype, so it can be a fragment
1597 * and can use HTML named entities.
1599 * @param string $text
1602 function wfIsWellFormedXmlFragment( $text ) {
1604 '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" ' .
1605 '"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">' .
1609 return wfIsWellFormedXml( $html );
1613 * shell_exec() with time and memory limits mirrored from the PHP configuration,
1616 function wfShellExec( $cmd )
1620 if ( php_uname( 's' ) == 'Linux' ) {
1621 $time = ini_get( 'max_execution_time' );
1622 $mem = ini_get( 'memory_limit' );
1623 if( preg_match( '/^([0-9]+)[Mm]$/', trim( $mem ), $m ) ) {
1624 $mem = intval( $m[1] * (1024*1024) );
1626 if ( $time > 0 && $mem > 0 ) {
1627 $script = "$IP/bin/ulimit.sh";
1628 if ( is_executable( $script ) ) {
1629 $memKB = intval( $mem / 1024 );
1630 $cmd = escapeshellarg( $script ) . " $time $memKB $cmd";
1634 return shell_exec( $cmd );