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' );
33 require_once( 'XmlFunctions.php' );
36 * Compatibility functions
37 * PHP <4.3.x is not actively supported; 4.1.x and 4.2.x might or might not work.
38 * <4.1.x will not work, as we use a number of features introduced in 4.1.0
39 * such as the new autoglobals.
41 if( !function_exists('iconv') ) {
42 # iconv support is not in the default configuration and so may not be present.
43 # Assume will only ever use utf-8 and iso-8859-1.
44 # This will *not* work in all circumstances.
45 function iconv( $from, $to, $string ) {
46 if(strcasecmp( $from, $to ) == 0) return $string;
47 if(strcasecmp( $from, 'utf-8' ) == 0) return utf8_decode( $string );
48 if(strcasecmp( $to, 'utf-8' ) == 0) return utf8_encode( $string );
53 if( !function_exists('file_get_contents') ) {
54 # Exists in PHP 4.3.0+
55 function file_get_contents( $filename ) {
56 return implode( '', file( $filename ) );
60 if( !function_exists('is_a') ) {
61 # Exists in PHP 4.2.0+
62 function is_a( $object, $class_name ) {
64 (strcasecmp( get_class( $object ), $class_name ) == 0) ||
65 is_subclass_of( $object, $class_name );
69 # UTF-8 substr function based on a PHP manual comment
70 if ( !function_exists( 'mb_substr' ) ) {
71 function mb_substr( $str, $start ) {
72 preg_match_all( '/./us', $str, $ar );
74 if( func_num_args() >= 3 ) {
75 $end = func_get_arg( 2 );
76 return join( '', array_slice( $ar[0], $start, $end ) );
78 return join( '', array_slice( $ar[0], $start ) );
83 if( !function_exists( 'floatval' ) ) {
85 * First defined in PHP 4.2.0
89 function floatval( $var ) {
94 if ( !function_exists( 'array_diff_key' ) ) {
96 * Exists in PHP 5.1.0+
97 * Not quite compatible, two-argument version only
98 * Null values will cause problems due to this use of isset()
100 function array_diff_key( $left, $right ) {
102 foreach ( $left as $key => $value ) {
103 if ( isset( $right[$key] ) ) {
104 unset( $result[$key] );
111 // If it doesn't exist no ctype_* stuff will
112 if ( ! function_exists( 'ctype_alnum' ) )
113 require_once 'compatability/ctype.php';
116 * Wrapper for clone() for PHP 4, for the moment.
117 * PHP 5 won't let you declare a 'clone' function, even conditionally,
118 * so it has to be a wrapper with a different name.
120 function wfClone( $object ) {
121 // WARNING: clone() is not a function in PHP 5, so function_exists fails.
122 if( version_compare( PHP_VERSION
, '5.0' ) < 0 ) {
125 return clone( $object );
130 * Where as we got a random seed
131 * @var bool $wgTotalViews
133 $wgRandomSeeded = false;
136 * Seed Mersenne Twister
137 * Only necessary in PHP < 4.2.0
141 function wfSeedRandom() {
142 global $wgRandomSeeded;
144 if ( ! $wgRandomSeeded && version_compare( phpversion(), '4.2.0' ) < 0 ) {
145 $seed = hexdec(substr(md5(microtime()),-8)) & 0x7fffffff;
147 $wgRandomSeeded = true;
152 * Get a random decimal value between 0 and 1, in a way
153 * not likely to give duplicate values for any realistic
154 * number of articles.
158 function wfRandom() {
159 # The maximum random value is "only" 2^31-1, so get two random
160 # values to reduce the chance of dupes
161 $max = mt_getrandmax();
162 $rand = number_format( (mt_rand() * $max +
mt_rand())
163 / $max / $max, 12, '.', '' );
168 * We want / and : to be included as literal characters in our title URLs.
169 * %2F in the page titles seems to fatally break for some reason.
174 function wfUrlencode ( $s ) {
175 $s = urlencode( $s );
176 $s = preg_replace( '/%3[Aa]/', ':', $s );
177 $s = preg_replace( '/%2[Ff]/', '/', $s );
183 * Sends a line to the debug log if enabled or, optionally, to a comment in output.
184 * In normal operation this is a NOP.
186 * Controlling globals:
187 * $wgDebugLogFile - points to the log file
188 * $wgProfileOnly - if set, normal debug messages will not be recorded.
189 * $wgDebugRawPage - if false, 'action=raw' hits will not result in debug output.
190 * $wgDebugComments - if on, some debug items may appear in comments in the HTML output.
192 * @param string $text
193 * @param bool $logonly Set true to avoid appearing in HTML when $wgDebugComments is set
195 function wfDebug( $text, $logonly = false ) {
196 global $wgOut, $wgDebugLogFile, $wgDebugComments, $wgProfileOnly, $wgDebugRawPage;
198 # Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
199 if ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' && !$wgDebugRawPage ) {
203 if ( isset( $wgOut ) && $wgDebugComments && !$logonly ) {
204 $wgOut->debug( $text );
206 if ( '' != $wgDebugLogFile && !$wgProfileOnly ) {
207 # Strip unprintables; they can switch terminal modes when binary data
208 # gets dumped, which is pretty annoying.
209 $text = preg_replace( '![\x00-\x08\x0b\x0c\x0e-\x1f]!', ' ', $text );
210 @error_log
( $text, 3, $wgDebugLogFile );
215 * Send a line to a supplementary debug log file, if configured, or main debug log if not.
216 * $wgDebugLogGroups[$logGroup] should be set to a filename to send to a separate log.
218 * @param string $logGroup
219 * @param string $text
220 * @param bool $public Whether to log the event in the public log if no private
221 * log file is specified, (default true)
223 function wfDebugLog( $logGroup, $text, $public = true ) {
224 global $wgDebugLogGroups, $wgDBname;
225 if( $text{strlen( $text ) - 1} != "\n" ) $text .= "\n";
226 if( isset( $wgDebugLogGroups[$logGroup] ) ) {
227 $time = wfTimestamp( TS_DB
);
228 @error_log
( "$time $wgDBname: $text", 3, $wgDebugLogGroups[$logGroup] );
229 } else if ( $public === true ) {
230 wfDebug( $text, true );
235 * Log for database errors
236 * @param string $text Database error message.
238 function wfLogDBError( $text ) {
239 global $wgDBerrorLog;
240 if ( $wgDBerrorLog ) {
241 $host = trim(`hostname`
);
242 $text = date('D M j G:i:s T Y') . "\t$host\t".$text;
243 error_log( $text, 3, $wgDBerrorLog );
250 function logProfilingData() {
251 global $wgRequestTime, $wgDebugLogFile, $wgDebugRawPage, $wgRequest;
252 global $wgProfiling, $wgUser;
255 list( $usec, $sec ) = explode( ' ', $wgRequestTime );
256 $start = (float)$sec +
(float)$usec;
257 $elapsed = $now - $start;
258 if ( $wgProfiling ) {
259 $prof = wfGetProfilingOutput( $start, $elapsed );
261 if( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) )
262 $forward = ' forwarded for ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
263 if( !empty( $_SERVER['HTTP_CLIENT_IP'] ) )
264 $forward .= ' client IP ' . $_SERVER['HTTP_CLIENT_IP'];
265 if( !empty( $_SERVER['HTTP_FROM'] ) )
266 $forward .= ' from ' . $_SERVER['HTTP_FROM'];
268 $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
269 if( is_object($wgUser) && $wgUser->isAnon() )
271 $log = sprintf( "%s\t%04.3f\t%s\n",
272 gmdate( 'YmdHis' ), $elapsed,
273 urldecode( $_SERVER['REQUEST_URI'] . $forward ) );
274 if ( '' != $wgDebugLogFile && ( $wgRequest->getVal('action') != 'raw' ||
$wgDebugRawPage ) ) {
275 error_log( $log . $prof, 3, $wgDebugLogFile );
281 * Check if the wiki read-only lock file is present. This can be used to lock
282 * off editing functions, but doesn't guarantee that the database will not be
286 function wfReadOnly() {
287 global $wgReadOnlyFile, $wgReadOnly;
289 if ( !is_null( $wgReadOnly ) ) {
290 return (bool)$wgReadOnly;
292 if ( '' == $wgReadOnlyFile ) {
295 // Set $wgReadOnly for faster access next time
296 if ( is_file( $wgReadOnlyFile ) ) {
297 $wgReadOnly = file_get_contents( $wgReadOnlyFile );
301 return (bool)$wgReadOnly;
306 * Get a message from anywhere, for the current user language.
308 * Use wfMsgForContent() instead if the message should NOT
309 * change depending on the user preferences.
311 * Note that the message may contain HTML, and is therefore
312 * not safe for insertion anywhere. Some functions such as
313 * addWikiText will do the escaping for you. Use wfMsgHtml()
314 * if you need an escaped message.
316 * @param string lookup key for the message, usually
317 * defined in languages/Language.php
319 function wfMsg( $key ) {
320 $args = func_get_args();
321 array_shift( $args );
322 return wfMsgReal( $key, $args, true );
326 * Same as above except doesn't transform the message
328 function wfMsgNoTrans( $key ) {
329 $args = func_get_args();
330 array_shift( $args );
331 return wfMsgReal( $key, $args, true, false );
335 * Get a message from anywhere, for the current global language
336 * set with $wgLanguageCode.
338 * Use this if the message should NOT change dependent on the
339 * language set in the user's preferences. This is the case for
340 * most text written into logs, as well as link targets (such as
341 * the name of the copyright policy page). Link titles, on the
342 * other hand, should be shown in the UI language.
344 * Note that MediaWiki allows users to change the user interface
345 * language in their preferences, but a single installation
346 * typically only contains content in one language.
348 * Be wary of this distinction: If you use wfMsg() where you should
349 * use wfMsgForContent(), a user of the software may have to
350 * customize over 70 messages in order to, e.g., fix a link in every
353 * @param string lookup key for the message, usually
354 * defined in languages/Language.php
356 function wfMsgForContent( $key ) {
357 global $wgForceUIMsgAsContentMsg;
358 $args = func_get_args();
359 array_shift( $args );
361 if( is_array( $wgForceUIMsgAsContentMsg ) &&
362 in_array( $key, $wgForceUIMsgAsContentMsg ) )
364 return wfMsgReal( $key, $args, true, $forcontent );
368 * Same as above except doesn't transform the message
370 function wfMsgForContentNoTrans( $key ) {
371 global $wgForceUIMsgAsContentMsg;
372 $args = func_get_args();
373 array_shift( $args );
375 if( is_array( $wgForceUIMsgAsContentMsg ) &&
376 in_array( $key, $wgForceUIMsgAsContentMsg ) )
378 return wfMsgReal( $key, $args, true, $forcontent, false );
382 * Get a message from the language file, for the UI elements
384 function wfMsgNoDB( $key ) {
385 $args = func_get_args();
386 array_shift( $args );
387 return wfMsgReal( $key, $args, false );
391 * Get a message from the language file, for the content
393 function wfMsgNoDBForContent( $key ) {
394 global $wgForceUIMsgAsContentMsg;
395 $args = func_get_args();
396 array_shift( $args );
398 if( is_array( $wgForceUIMsgAsContentMsg ) &&
399 in_array( $key, $wgForceUIMsgAsContentMsg ) )
401 return wfMsgReal( $key, $args, false, $forcontent );
406 * Really get a message
408 function wfMsgReal( $key, $args, $useDB, $forContent=false, $transform = true ) {
409 $fname = 'wfMsgReal';
411 $message = wfMsgGetKey( $key, $useDB, $forContent, $transform );
412 $message = wfMsgReplaceArgs( $message, $args );
417 * This function provides the message source for messages to be edited which are *not* stored in the database
420 function wfMsgWeirdKey ( $key ) {
421 $subsource = str_replace ( ' ' , '_' , $key ) ;
422 $source = wfMsg ( $subsource ) ;
423 if ( $source == "<{$subsource}>" ) {
424 # Try again with first char lower case
425 $subsource = strtolower ( substr ( $subsource , 0 , 1 ) ) . substr ( $subsource , 1 ) ;
426 $source = wfMsg ( $subsource ) ;
428 if ( $source == "<{$subsource}>" ) {
429 # Didn't work either, return blank text
436 * Fetch a message string value, but don't replace any keys yet.
439 * @param bool $forContent
443 function wfMsgGetKey( $key, $useDB, $forContent = false, $transform = true ) {
444 global $wgParser, $wgMsgParserOptions, $wgContLang, $wgMessageCache, $wgLang;
446 if ( is_object( $wgMessageCache ) )
447 $transstat = $wgMessageCache->getTransform();
449 if( is_object( $wgMessageCache ) ) {
451 $wgMessageCache->disableTransform();
452 $message = $wgMessageCache->get( $key, $useDB, $forContent );
455 $lang = &$wgContLang;
460 wfSuppressWarnings();
462 if( is_object( $lang ) ) {
463 $message = $lang->getMessage( $key );
468 if($message === false)
469 $message = Language
::getMessage($key);
470 if ( $transform && strstr( $message, '{{' ) !== false ) {
471 $message = $wgParser->transformMsg($message, $wgMsgParserOptions);
475 if ( is_object( $wgMessageCache ) && ! $transform )
476 $wgMessageCache->setTransform( $transstat );
482 * Replace message parameter keys on the given formatted output.
484 * @param string $message
489 function wfMsgReplaceArgs( $message, $args ) {
490 # Fix windows line-endings
491 # Some messages are split with explode("\n", $msg)
492 $message = str_replace( "\r", '', $message );
495 if ( count( $args ) ) {
496 if ( is_array( $args[0] ) ) {
497 foreach ( $args[0] as $key => $val ) {
498 $message = str_replace( '$' . $key, $val, $message );
501 foreach( $args as $n => $param ) {
502 $replacementKeys['$' . ($n +
1)] = $param;
504 $message = strtr( $message, $replacementKeys );
512 * Return an HTML-escaped version of a message.
513 * Parameter replacements, if any, are done *after* the HTML-escaping,
514 * so parameters may contain HTML (eg links or form controls). Be sure
515 * to pre-escape them if you really do want plaintext, or just wrap
516 * the whole thing in htmlspecialchars().
519 * @param string ... parameters
522 function wfMsgHtml( $key ) {
523 $args = func_get_args();
524 array_shift( $args );
525 return wfMsgReplaceArgs( htmlspecialchars( wfMsgGetKey( $key, true ) ), $args );
529 * Return an HTML version of message
530 * Parameter replacements, if any, are done *after* parsing the wiki-text message,
531 * so parameters may contain HTML (eg links or form controls). Be sure
532 * to pre-escape them if you really do want plaintext, or just wrap
533 * the whole thing in htmlspecialchars().
536 * @param string ... parameters
539 function wfMsgWikiHtml( $key ) {
541 $args = func_get_args();
542 array_shift( $args );
543 return wfMsgReplaceArgs( $wgOut->parse( wfMsgGetKey( $key, true ), /* can't be set to false */ true ), $args );
547 * Just like exit() but makes a note of it.
548 * Commits open transactions except if the error parameter is set
550 function wfAbruptExit( $error = false ){
551 global $wgLoadBalancer;
552 static $called = false;
558 if( function_exists( 'debug_backtrace' ) ){ // PHP >= 4.3
559 $bt = debug_backtrace();
560 for($i = 0; $i < count($bt) ; $i++
){
561 $file = isset($bt[$i]['file']) ?
$bt[$i]['file'] : "unknown";
562 $line = isset($bt[$i]['line']) ?
$bt[$i]['line'] : "unknown";
563 wfDebug("WARNING: Abrupt exit in $file at line $line\n");
566 wfDebug('WARNING: Abrupt exit\n');
573 $wgLoadBalancer->closeAll();
581 function wfErrorExit() {
582 wfAbruptExit( true );
586 * Print a simple message and die, returning nonzero to the shell if any.
587 * Plain die() fails to return nonzero to the shell if you pass a string.
590 function wfDie( $msg='' ) {
596 * Die with a backtrace
597 * This is meant as a debugging aid to track down where bad data comes from.
598 * Shouldn't be used in production code except maybe in "shouldn't happen" areas.
600 * @param string $msg Message shown when dieing.
602 function wfDebugDieBacktrace( $msg = '' ) {
603 global $wgCommandLineMode;
605 $backtrace = wfBacktrace();
606 if ( $backtrace !== false ) {
607 if ( $wgCommandLineMode ) {
608 $msg .= "\nBacktrace:\n$backtrace";
610 $msg .= "\n<p>Backtrace:</p>\n$backtrace";
614 echo wfReportTime()."\n";
619 * Returns a HTML comment with the elapsed time since request.
620 * This method has no side effects.
623 function wfReportTime() {
624 global $wgRequestTime;
627 list( $usec, $sec ) = explode( ' ', $wgRequestTime );
628 $start = (float)$sec +
(float)$usec;
629 $elapsed = $now - $start;
631 # Use real server name if available, so we know which machine
632 # in a server farm generated the current page.
633 if ( function_exists( 'posix_uname' ) ) {
634 $uname = @posix_uname
();
638 if( is_array( $uname ) && isset( $uname['nodename'] ) ) {
639 $hostname = $uname['nodename'];
641 # This may be a virtual server.
642 $hostname = $_SERVER['SERVER_NAME'];
644 $com = sprintf( "<!-- Served by %s in %01.2f secs. -->",
645 $hostname, $elapsed );
649 function wfBacktrace() {
650 global $wgCommandLineMode;
651 if ( !function_exists( 'debug_backtrace' ) ) {
655 if ( $wgCommandLineMode ) {
660 $backtrace = debug_backtrace();
661 foreach( $backtrace as $call ) {
662 if( isset( $call['file'] ) ) {
663 $f = explode( DIRECTORY_SEPARATOR
, $call['file'] );
664 $file = $f[count($f)-1];
668 if( isset( $call['line'] ) ) {
669 $line = $call['line'];
673 if ( $wgCommandLineMode ) {
674 $msg .= "$file line $line calls ";
676 $msg .= '<li>' . $file . ' line ' . $line . ' calls ';
678 if( !empty( $call['class'] ) ) $msg .= $call['class'] . '::';
679 $msg .= $call['function'] . '()';
681 if ( $wgCommandLineMode ) {
687 if ( $wgCommandLineMode ) {
697 /* Some generic result counters, pulled out of SearchEngine */
703 function wfShowingResults( $offset, $limit ) {
705 return wfMsg( 'showingresults', $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+
1 ) );
711 function wfShowingResultsNum( $offset, $limit, $num ) {
713 return wfMsg( 'showingresultsnum', $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+
1 ), $wgLang->formatNum( $num ) );
719 function wfViewPrevNext( $offset, $limit, $link, $query = '', $atend = false ) {
721 $fmtLimit = $wgLang->formatNum( $limit );
722 $prev = wfMsg( 'prevn', $fmtLimit );
723 $next = wfMsg( 'nextn', $fmtLimit );
725 if( is_object( $link ) ) {
728 $title = Title
::newFromText( $link );
729 if( is_null( $title ) ) {
734 if ( 0 != $offset ) {
735 $po = $offset - $limit;
736 if ( $po < 0 ) { $po = 0; }
737 $q = "limit={$limit}&offset={$po}";
738 if ( '' != $query ) { $q .= '&'.$query; }
739 $plink = '<a href="' . $title->escapeLocalUrl( $q ) . "\">{$prev}</a>";
740 } else { $plink = $prev; }
742 $no = $offset +
$limit;
743 $q = 'limit='.$limit.'&offset='.$no;
744 if ( '' != $query ) { $q .= '&'.$query; }
749 $nlink = '<a href="' . $title->escapeLocalUrl( $q ) . "\">{$next}</a>";
751 $nums = wfNumLink( $offset, 20, $title, $query ) . ' | ' .
752 wfNumLink( $offset, 50, $title, $query ) . ' | ' .
753 wfNumLink( $offset, 100, $title, $query ) . ' | ' .
754 wfNumLink( $offset, 250, $title, $query ) . ' | ' .
755 wfNumLink( $offset, 500, $title, $query );
757 return wfMsg( 'viewprevnext', $plink, $nlink, $nums );
763 function wfNumLink( $offset, $limit, &$title, $query = '' ) {
765 if ( '' == $query ) { $q = ''; }
766 else { $q = $query.'&'; }
767 $q .= 'limit='.$limit.'&offset='.$offset;
769 $fmtLimit = $wgLang->formatNum( $limit );
770 $s = '<a href="' . $title->escapeLocalUrl( $q ) . "\">{$fmtLimit}</a>";
776 * @todo FIXME: we may want to blacklist some broken browsers
778 * @return bool Whereas client accept gzip compression
780 function wfClientAcceptsGzip() {
783 # FIXME: we may want to blacklist some broken browsers
785 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
786 $_SERVER['HTTP_ACCEPT_ENCODING'],
788 if( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) return false;
789 wfDebug( " accepts gzip\n" );
797 * Yay, more global functions!
799 function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) {
801 return $wgRequest->getLimitOffset( $deflimit, $optionname );
805 * Escapes the given text so that it may be output using addWikiText()
806 * without any linking, formatting, etc. making its way through. This
807 * is achieved by substituting certain characters with HTML entities.
808 * As required by the callers, <nowiki> is not used. It currently does
809 * not filter out characters which have special meaning only at the
810 * start of a line, such as "*".
812 * @param string $text Text to be escaped
814 function wfEscapeWikiText( $text ) {
816 array( '[', '|', '\'', 'ISBN ' , '://' , "\n=", '{{' ),
817 array( '[', '|', ''', 'ISBN ', '://' , "\n=", '{{' ),
818 htmlspecialchars($text) );
825 function wfQuotedPrintable( $string, $charset = '' ) {
826 # Probably incomplete; see RFC 2045
827 if( empty( $charset ) ) {
828 global $wgInputEncoding;
829 $charset = $wgInputEncoding;
831 $charset = strtoupper( $charset );
832 $charset = str_replace( 'ISO-8859', 'ISO8859', $charset ); // ?
834 $illegal = '\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\xff=';
835 $replace = $illegal . '\t ?_';
836 if( !preg_match( "/[$illegal]/", $string ) ) return $string;
837 $out = "=?$charset?Q?";
838 $out .= preg_replace( "/([$replace])/e", 'sprintf("=%02X",ord("$1"))', $string );
849 $st = explode( ' ', microtime() );
850 return (float)$st[0] +
(float)$st[1];
854 * Sets dest to source and returns the original value of dest
855 * If source is NULL, it just returns the value, it doesn't set the variable
857 function wfSetVar( &$dest, $source ) {
859 if ( !is_null( $source ) ) {
866 * As for wfSetVar except setting a bit
868 function wfSetBit( &$dest, $bit, $state = true ) {
869 $temp = (bool)($dest & $bit );
870 if ( !is_null( $state ) ) {
881 * This function takes two arrays as input, and returns a CGI-style string, e.g.
882 * "days=7&limit=100". Options in the first array override options in the second.
883 * Options set to "" will not be output.
885 function wfArrayToCGI( $array1, $array2 = NULL )
887 if ( !is_null( $array2 ) ) {
888 $array1 = $array1 +
$array2;
892 foreach ( $array1 as $key => $value ) {
893 if ( '' !== $value ) {
897 $cgi .= urlencode( $key ) . '=' . urlencode( $value );
904 * This is obsolete, use SquidUpdate::purge()
907 function wfPurgeSquidServers ($urlArr) {
908 SquidUpdate
::purge( $urlArr );
912 * Windows-compatible version of escapeshellarg()
913 * Windows doesn't recognise single-quotes in the shell, but the escapeshellarg()
914 * function puts single quotes in regardless of OS
916 function wfEscapeShellArg( ) {
917 $args = func_get_args();
920 foreach ( $args as $arg ) {
927 if ( wfIsWindows() ) {
928 // Escaping for an MSVC-style command line parser
929 // Ref: http://mailman.lyra.org/pipermail/scite-interest/2002-March/000436.html
930 // Double the backslashes before any double quotes. Escape the double quotes.
931 $tokens = preg_split( '/(\\\\*")/', $arg, -1, PREG_SPLIT_DELIM_CAPTURE
);
934 foreach ( $tokens as $token ) {
936 $arg .= str_replace( '\\', '\\\\', substr( $token, 0, -1 ) ) . '\\"';
942 // Double the backslashes before the end of the string, because
943 // we will soon add a quote
944 if ( preg_match( '/^(.*?)(\\\\+)$/', $arg, $m ) ) {
945 $arg = $m[1] . str_replace( '\\', '\\\\', $m[2] );
948 // Add surrounding quotes
949 $retVal .= '"' . $arg . '"';
951 $retVal .= escapeshellarg( $arg );
958 * wfMerge attempts to merge differences between three texts.
959 * Returns true for a clean merge and false for failure or a conflict.
961 function wfMerge( $old, $mine, $yours, &$result ){
964 # This check may also protect against code injection in
965 # case of broken installations.
966 if(! file_exists( $wgDiff3 ) ){
967 wfDebug( "diff3 not found\n" );
971 # Make temporary files
973 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
974 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
975 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
977 fwrite( $oldtextFile, $old ); fclose( $oldtextFile );
978 fwrite( $mytextFile, $mine ); fclose( $mytextFile );
979 fwrite( $yourtextFile, $yours ); fclose( $yourtextFile );
981 # Check for a conflict
982 $cmd = $wgDiff3 . ' -a --overlap-only ' .
983 wfEscapeShellArg( $mytextName ) . ' ' .
984 wfEscapeShellArg( $oldtextName ) . ' ' .
985 wfEscapeShellArg( $yourtextName );
986 $handle = popen( $cmd, 'r' );
988 if( fgets( $handle, 1024 ) ){
996 $cmd = $wgDiff3 . ' -a -e --merge ' .
997 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
998 $handle = popen( $cmd, 'r' );
1001 $data = fread( $handle, 8192 );
1002 if ( strlen( $data ) == 0 ) {
1008 unlink( $mytextName ); unlink( $oldtextName ); unlink( $yourtextName );
1010 if ( $result === '' && $old !== '' && $conflict == false ) {
1011 wfDebug( "Unexpected null result from diff3. Command: $cmd\n" );
1020 function wfVarDump( $var ) {
1022 $s = str_replace("\n","<br />\n", var_export( $var, true ) . "\n");
1023 if ( headers_sent() ||
!@is_object
( $wgOut ) ) {
1026 $wgOut->addHTML( $s );
1031 * Provide a simple HTTP error.
1033 function wfHttpError( $code, $label, $desc ) {
1036 header( "HTTP/1.0 $code $label" );
1037 header( "Status: $code $label" );
1038 $wgOut->sendCacheControl();
1040 header( 'Content-type: text/html' );
1041 print "<html><head><title>" .
1042 htmlspecialchars( $label ) .
1043 "</title></head><body><h1>" .
1044 htmlspecialchars( $label ) .
1046 htmlspecialchars( $desc ) .
1047 "</p></body></html>\n";
1051 * Converts an Accept-* header into an array mapping string values to quality
1054 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
1055 # No arg means accept anything (per HTTP spec)
1057 return array( $def => 1 );
1062 $parts = explode( ',', $accept );
1064 foreach( $parts as $part ) {
1065 # FIXME: doesn't deal with params like 'text/html; level=1'
1066 @list
( $value, $qpart ) = explode( ';', $part );
1067 if( !isset( $qpart ) ) {
1069 } elseif( preg_match( '/q\s*=\s*(\d*\.\d+)/', $qpart, $match ) ) {
1070 $prefs[$value] = $match[1];
1078 * Checks if a given MIME type matches any of the keys in the given
1079 * array. Basic wildcards are accepted in the array keys.
1081 * Returns the matching MIME type (or wildcard) if a match, otherwise
1084 * @param string $type
1085 * @param array $avail
1089 function mimeTypeMatch( $type, $avail ) {
1090 if( array_key_exists($type, $avail) ) {
1093 $parts = explode( '/', $type );
1094 if( array_key_exists( $parts[0] . '/*', $avail ) ) {
1095 return $parts[0] . '/*';
1096 } elseif( array_key_exists( '*/*', $avail ) ) {
1105 * Returns the 'best' match between a client's requested internet media types
1106 * and the server's list of available types. Each list should be an associative
1107 * array of type to preference (preference is a float between 0.0 and 1.0).
1108 * Wildcards in the types are acceptable.
1110 * @param array $cprefs Client's acceptable type list
1111 * @param array $sprefs Server's offered types
1114 * @todo FIXME: doesn't handle params like 'text/plain; charset=UTF-8'
1115 * XXX: generalize to negotiate other stuff
1117 function wfNegotiateType( $cprefs, $sprefs ) {
1120 foreach( array_keys($sprefs) as $type ) {
1121 $parts = explode( '/', $type );
1122 if( $parts[1] != '*' ) {
1123 $ckey = mimeTypeMatch( $type, $cprefs );
1125 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1130 foreach( array_keys( $cprefs ) as $type ) {
1131 $parts = explode( '/', $type );
1132 if( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
1133 $skey = mimeTypeMatch( $type, $sprefs );
1135 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1143 foreach( array_keys( $combine ) as $type ) {
1144 if( $combine[$type] > $bestq ) {
1146 $bestq = $combine[$type];
1155 * Returns an array where the values in the first array are replaced by the
1156 * values in the second array with the corresponding keys
1160 function wfArrayLookup( $a, $b ) {
1161 return array_flip( array_intersect( array_flip( $a ), array_keys( $b ) ) );
1165 * Convenience function; returns MediaWiki timestamp for the present time.
1168 function wfTimestampNow() {
1170 return wfTimestamp( TS_MW
, time() );
1174 * Reference-counted warning suppression
1176 function wfSuppressWarnings( $end = false ) {
1177 static $suppressCount = 0;
1178 static $originalLevel = false;
1181 if ( $suppressCount ) {
1183 if ( !$suppressCount ) {
1184 error_reporting( $originalLevel );
1188 if ( !$suppressCount ) {
1189 $originalLevel = error_reporting( E_ALL
& ~
( E_WARNING | E_NOTICE
) );
1196 * Restore error level to previous value
1198 function wfRestoreWarnings() {
1199 wfSuppressWarnings( true );
1202 # Autodetect, convert and provide timestamps of various types
1205 * Unix time - the number of seconds since 1970-01-01 00:00:00 UTC
1207 define('TS_UNIX', 0);
1210 * MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
1215 * MySQL DATETIME (YYYY-MM-DD HH:MM:SS)
1220 * RFC 2822 format, for E-mail and HTTP headers
1222 define('TS_RFC2822', 3);
1225 * ISO 8601 format with no timezone: 1986-02-09T20:00:00Z
1227 * This is used by Special:Export
1229 define('TS_ISO_8601', 4);
1232 * An Exif timestamp (YYYY:MM:DD HH:MM:SS)
1234 * @link http://exif.org/Exif2-2.PDF The Exif 2.2 spec, see page 28 for the
1235 * DateTime tag and page 36 for the DateTimeOriginal and
1236 * DateTimeDigitized tags.
1238 define('TS_EXIF', 5);
1241 * Oracle format time.
1243 define('TS_ORACLE', 6);
1246 * @param mixed $outputtype A timestamp in one of the supported formats, the
1247 * function will autodetect which format is supplied
1248 * and act accordingly.
1249 * @return string Time in the format specified in $outputtype
1251 function wfTimestamp($outputtype=TS_UNIX
,$ts=0) {
1255 } elseif (preg_match("/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)$/",$ts,$da)) {
1257 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1258 (int)$da[2],(int)$da[3],(int)$da[1]);
1259 } elseif (preg_match("/^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/",$ts,$da)) {
1261 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1262 (int)$da[2],(int)$da[3],(int)$da[1]);
1263 } elseif (preg_match("/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/",$ts,$da)) {
1265 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1266 (int)$da[2],(int)$da[3],(int)$da[1]);
1267 } elseif (preg_match("/^(\d{1,13})$/",$ts,$datearray)) {
1270 } elseif (preg_match('/^(\d{1,2})-(...)-(\d\d(\d\d)?) (\d\d)\.(\d\d)\.(\d\d)/', $ts, $da)) {
1272 $uts = strtotime(preg_replace('/(\d\d)\.(\d\d)\.(\d\d)(\.(\d+))?/', "$1:$2:$3",
1273 str_replace("+00:00", "UTC", $ts)));
1274 } elseif (preg_match('/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})Z$/', $ts, $da)) {
1276 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1277 (int)$da[2],(int)$da[3],(int)$da[1]);
1279 # Bogus value; fall back to the epoch...
1280 wfDebug("wfTimestamp() fed bogus time value: $outputtype; $ts\n");
1285 switch($outputtype) {
1289 return gmdate( 'YmdHis', $uts );
1291 return gmdate( 'Y-m-d H:i:s', $uts );
1293 return gmdate( 'Y-m-d\TH:i:s\Z', $uts );
1294 // This shouldn't ever be used, but is included for completeness
1296 return gmdate( 'Y:m:d H:i:s', $uts );
1298 return gmdate( 'D, d M Y H:i:s', $uts ) . ' GMT';
1300 return gmdate( 'd-M-y h.i.s A', $uts) . ' +00:00';
1302 wfDebugDieBacktrace( 'wfTimestamp() called with illegal output type.');
1307 * Return a formatted timestamp, or null if input is null.
1308 * For dealing with nullable timestamp columns in the database.
1309 * @param int $outputtype
1313 function wfTimestampOrNull( $outputtype = TS_UNIX
, $ts = null ) {
1314 if( is_null( $ts ) ) {
1317 return wfTimestamp( $outputtype, $ts );
1322 * Check if the operating system is Windows
1324 * @return bool True if it's Windows, False otherwise.
1326 function wfIsWindows() {
1327 if (substr(php_uname(), 0, 7) == 'Windows') {
1335 * Swap two variables
1337 function swap( &$x, &$y ) {
1343 function wfGetCachedNotice( $name ) {
1344 global $wgOut, $parserMemc, $wgDBname;
1345 $fname = 'wfGetCachedNotice';
1346 wfProfileIn( $fname );
1349 $notice = wfMsgForContent( $name );
1350 if( $notice == '<'. $name . ';>' ||
$notice == '-' ) {
1351 wfProfileOut( $fname );
1355 $cachedNotice = $parserMemc->get( $wgDBname . ':' . $name );
1356 if( is_array( $cachedNotice ) ) {
1357 if( md5( $notice ) == $cachedNotice['hash'] ) {
1358 $notice = $cachedNotice['html'];
1367 if( is_object( $wgOut ) ) {
1368 $parsed = $wgOut->parse( $notice );
1369 $parserMemc->set( $wgDBname . ':' . $name, array( 'html' => $parsed, 'hash' => md5( $notice ) ), 600 );
1372 wfDebug( 'wfGetCachedNotice called for ' . $name . ' with no $wgOut available' );
1377 wfProfileOut( $fname );
1381 function wfGetNamespaceNotice() {
1385 if ( !isset( $wgTitle ) ||
!is_object( $wgTitle ) )
1388 $fname = 'wfGetNamespaceNotice';
1389 wfProfileIn( $fname );
1391 $key = "namespacenotice-" . $wgTitle->getNsText();
1392 $namespaceNotice = wfGetCachedNotice( $key );
1393 if ( $namespaceNotice && substr ( $namespaceNotice , 0 ,7 ) != "<p><" ) {
1394 $namespaceNotice = '<div id="namespacebanner">' . $namespaceNotice . "</div>";
1396 $namespaceNotice = "";
1399 wfProfileOut( $fname );
1400 return $namespaceNotice;
1403 function wfGetSiteNotice() {
1404 global $wgUser, $wgSiteNotice;
1405 $fname = 'wfGetSiteNotice';
1406 wfProfileIn( $fname );
1408 if( is_object( $wgUser ) && $wgUser->isLoggedIn() ) {
1409 $siteNotice = wfGetCachedNotice( 'sitenotice' );
1410 $siteNotice = !$siteNotice ?
$wgSiteNotice : $siteNotice;
1412 $anonNotice = wfGetCachedNotice( 'anonnotice' );
1413 if( !$anonNotice ) {
1414 $siteNotice = wfGetCachedNotice( 'sitenotice' );
1415 $siteNotice = !$siteNotice ?
$wgSiteNotice : $siteNotice;
1417 $siteNotice = $anonNotice;
1421 wfProfileOut( $fname );
1422 return( $siteNotice );
1425 /** Global singleton instance of MimeMagic. This is initialized on demand,
1426 * please always use the wfGetMimeMagic() function to get the instance.
1432 /** Factory functions for the global MimeMagic object.
1433 * This function always returns the same singleton instance of MimeMagic.
1434 * That objects will be instantiated on the first call to this function.
1435 * If needed, the MimeMagic.php file is automatically included by this function.
1436 * @return MimeMagic the global MimeMagic objects.
1438 function &wfGetMimeMagic() {
1439 global $wgMimeMagic;
1441 if (!is_null($wgMimeMagic)) {
1442 return $wgMimeMagic;
1445 if (!class_exists("MimeMagic")) {
1447 require_once("MimeMagic.php");
1450 $wgMimeMagic= new MimeMagic();
1452 return $wgMimeMagic;
1457 * Tries to get the system directory for temporary files.
1458 * The TMPDIR, TMP, and TEMP environment variables are checked in sequence,
1459 * and if none are set /tmp is returned as the generic Unix default.
1461 * NOTE: When possible, use the tempfile() function to create temporary
1462 * files to avoid race conditions on file creation, etc.
1466 function wfTempDir() {
1467 foreach( array( 'TMPDIR', 'TMP', 'TEMP' ) as $var ) {
1468 $tmp = getenv( $var );
1469 if( $tmp && file_exists( $tmp ) && is_dir( $tmp ) && is_writable( $tmp ) ) {
1473 # Hope this is Unix of some kind!
1478 * Make directory, and make all parent directories if they don't exist
1480 function wfMkdirParents( $fullDir, $mode ) {
1481 $parts = explode( '/', $fullDir );
1484 foreach ( $parts as $dir ) {
1485 $path .= $dir . '/';
1486 if ( !is_dir( $path ) ) {
1487 if ( !mkdir( $path, $mode ) ) {
1496 * Increment a statistics counter
1498 function wfIncrStats( $key ) {
1499 global $wgDBname, $wgMemc;
1500 /* LIVE HACK AVOID MEMCACHED ACCESSES DURING HIGH LOAD */
1501 if ($wgDBname != 'enwiki' and $wgDBname != 'dewiki' and $wgDBname != 'commonswiki' and $wgDBname != 'testwiki')
1505 $socket=socket_create(AF_INET
, SOCK_DGRAM
, SOL_UDP
);
1506 $statline="{$wgDBname} - 1 1 1 1 1 -total\n";
1507 socket_sendto($socket,$statline,strlen($statline),0,"webster","3811");
1509 $statline="{$wgDBname} - 1 1 1 1 1 {$key}\n";
1510 socket_sendto($socket,$statline,strlen($statline),0,"webster","3811");
1513 $key = "$wgDBname:stats:$key";
1514 if ( is_null( $wgMemc->incr( $key ) ) ) {
1515 $wgMemc->add( $key, 1 );
1520 * @param mixed $nr The number to format
1521 * @param int $acc The number of digits after the decimal point, default 2
1522 * @param bool $round Whether or not to round the value, default true
1525 function wfPercent( $nr, $acc = 2, $round = true ) {
1526 $ret = sprintf( "%.${acc}f", $nr );
1527 return $round ?
round( $ret, $acc ) . '%' : "$ret%";
1531 * Encrypt a username/password.
1533 * @param string $userid ID of the user
1534 * @param string $password Password of the user
1535 * @return string Hashed password
1537 function wfEncryptPassword( $userid, $password ) {
1538 global $wgPasswordSalt;
1539 $p = md5( $password);
1542 return md5( "{$userid}-{$p}" );
1548 * Appends to second array if $value differs from that in $default
1550 function wfAppendToArrayIfNotDefault( $key, $value, $default, &$changed ) {
1551 if ( is_null( $changed ) ) {
1552 wfDebugDieBacktrace('GlobalFunctions::wfAppendToArrayIfNotDefault got null');
1554 if ( $default[$key] !== $value ) {
1555 $changed[$key] = $value;
1560 * Since wfMsg() and co suck, they don't return false if the message key they
1561 * looked up didn't exist but a XHTML string, this function checks for the
1562 * nonexistance of messages by looking at wfMsg() output
1564 * @param $msg The message key looked up
1565 * @param $wfMsgOut The output of wfMsg*()
1568 function wfEmptyMsg( $msg, $wfMsgOut ) {
1569 return $wfMsgOut === "<$msg>";
1573 * Find out whether or not a mixed variable exists in a string
1575 * @param mixed needle
1576 * @param string haystack
1579 function in_string( $needle, $str ) {
1580 return strpos( $str, $needle ) !== false;
1584 * Returns a regular expression of url protocols
1588 function wfUrlProtocols() {
1589 global $wgUrlProtocols;
1591 // Support old-style $wgUrlProtocols strings, for backwards compatibility
1592 // with LocalSettings files from 1.5
1593 if ( is_array( $wgUrlProtocols ) ) {
1594 $protocols = array();
1595 foreach ($wgUrlProtocols as $protocol)
1596 $protocols[] = preg_quote( $protocol, '/' );
1598 return implode( '|', $protocols );
1600 return $wgUrlProtocols;
1605 * shell_exec() with time and memory limits mirrored from the PHP configuration,
1608 function wfShellExec( $cmd )
1612 if ( php_uname( 's' ) == 'Linux' ) {
1613 $time = ini_get( 'max_execution_time' );
1614 $mem = ini_get( 'memory_limit' );
1615 if( preg_match( '/^([0-9]+)[Mm]$/', trim( $mem ), $m ) ) {
1616 $mem = intval( $m[1] * (1024*1024) );
1618 if ( $time > 0 && $mem > 0 ) {
1619 $script = "$IP/bin/ulimit.sh";
1620 if ( is_executable( $script ) ) {
1621 $memKB = intval( $mem / 1024 );
1622 $cmd = escapeshellarg( $script ) . " $time $memKB $cmd";
1625 } elseif ( php_uname( 's' ) == 'Windows NT' ) {
1626 # This is a hack to work around PHP's flawed invocation of cmd.exe
1627 # http://news.php.net/php.internals/21796
1628 $cmd = '"' . $cmd . '"';
1630 return shell_exec( $cmd );
1634 * This function works like "use VERSION" in Perl, the program will die with a
1635 * backtrace if the current version of PHP is less than the version provided
1637 * This is useful for extensions which due to their nature are not kept in sync
1638 * with releases, and might depend on other versions of PHP than the main code
1640 * Note: PHP might die due to parsing errors in some cases before it ever
1641 * manages to call this function, such is life
1643 * @see perldoc -f use
1645 * @param mixed $version The version to check, can be a string, an integer, or
1648 function wfUsePHP( $req_ver ) {
1649 $php_ver = PHP_VERSION
;
1651 if ( version_compare( $php_ver, (string)$req_ver, '<' ) )
1652 wfDebugDieBacktrace( "PHP $req_ver required--this is only $php_ver" );
1656 * This function works like "use VERSION" in Perl except it checks the version
1657 * of MediaWiki, the program will die with a backtrace if the current version
1658 * of MediaWiki is less than the version provided.
1660 * This is useful for extensions which due to their nature are not kept in sync
1663 * @see perldoc -f use
1665 * @param mixed $version The version to check, can be a string, an integer, or
1668 function wfUseMW( $req_ver ) {
1671 if ( version_compare( $wgVersion, (string)$req_ver, '<' ) )
1672 wfDebugDieBacktrace( "MediaWiki $req_ver required--this is only $wgVersion" );
1676 * Escape a string to make it suitable for inclusion in a preg_replace()
1677 * replacement parameter.
1679 * @param string $string
1682 function wfRegexReplacement( $string ) {
1683 $string = str_replace( '\\', '\\\\', $string );
1684 $string = str_replace( '$', '\\$', $string );
1689 * Return the final portion of a pathname.
1690 * Reimplemented because PHP5's basename() is buggy with multibyte text.
1691 * http://bugs.php.net/bug.php?id=33898
1693 * PHP's basename() only considers '\' a pathchar on Windows and Netware.
1694 * We'll consider it so always, as we don't want \s in our Unix paths either.
1696 * @param string $path
1699 function wfBaseName( $path ) {
1700 if( preg_match( '#([^/\\\\]*)[/\\\\]*$#', $path, $matches ) ) {
1708 * Make a URL index, appropriate for the el_index field of externallinks.
1710 function wfMakeUrlIndex( $url ) {
1711 wfSuppressWarnings();
1712 $bits = parse_url( $url );
1713 wfRestoreWarnings();
1714 if ( !$bits ||
$bits['scheme'] !== 'http' ) {
1717 // Reverse the labels in the hostname, convert to lower case
1718 $reversedHost = strtolower( implode( '.', array_reverse( explode( '.', $bits['host'] ) ) ) );
1719 // Add an extra dot to the end
1720 if ( substr( $reversedHost, -1, 1 ) !== '.' ) {
1721 $reversedHost .= '.';
1723 // Reconstruct the pseudo-URL
1724 $index = "http://$reversedHost";
1725 // Leave out user and password. Add the port, path, query and fragment
1726 if ( isset( $bits['port'] ) ) $index .= ':' . $bits['port'];
1727 if ( isset( $bits['path'] ) ) {
1728 $index .= $bits['path'];
1732 if ( isset( $bits['query'] ) ) $index .= '?' . $bits['query'];
1733 if ( isset( $bits['fragment'] ) ) $index .= '#' . $bits['fragment'];
1738 * Do any deferred updates and clear the list
1739 * TODO: This could be in Wiki.php if that class made any sense at all
1741 function wfDoUpdates()
1743 global $wgPostCommitUpdateList, $wgDeferredUpdateList;
1744 foreach ( $wgDeferredUpdateList as $update ) {
1745 $update->doUpdate();
1747 foreach ( $wgPostCommitUpdateList as $update ) {
1748 $update->doUpdate();
1750 $wgDeferredUpdateList = array();
1751 $wgPostCommitUpdateList = array();