3 * Global functions used everywhere
7 if ( !defined( 'MEDIAWIKI' ) ) {
8 die( "This file is part of MediaWiki, it is not a valid entry point" );
11 require_once dirname( __FILE__
) . '/normal/UtfNormalUtil.php';
13 // Hide compatibility functions from Doxygen
17 * Compatibility functions
19 * We more or less support PHP 5.0.x and up.
20 * Re-implementations of newer functions or functions in non-standard
21 * PHP extensions may be included here.
23 if( !function_exists( 'iconv' ) ) {
24 # iconv support is not in the default configuration and so may not be present.
25 # Assume will only ever use utf-8 and iso-8859-1.
26 # This will *not* work in all circumstances.
27 function iconv( $from, $to, $string ) {
28 if ( substr( $to, -8 ) == '//IGNORE' ) {
29 $to = substr( $to, 0, strlen( $to ) - 8 );
31 if( strcasecmp( $from, $to ) == 0 ) {
34 if( strcasecmp( $from, 'utf-8' ) == 0 ) {
35 return utf8_decode( $string );
37 if( strcasecmp( $to, 'utf-8' ) == 0 ) {
38 return utf8_encode( $string );
44 if ( !function_exists( 'mb_substr' ) ) {
46 * Fallback implementation for mb_substr, hardcoded to UTF-8.
47 * Attempts to be at least _moderately_ efficient; best optimized
48 * for relatively small offset and count values -- about 5x slower
49 * than native mb_string in my testing.
51 * Larger offsets are still fairly efficient for Latin text, but
52 * can be up to 100x slower than native if the text is heavily
53 * multibyte and we have to slog through a few hundred kb.
55 function mb_substr( $str, $start, $count='end' ) {
57 $split = mb_substr_split_unicode( $str, intval( $start ) );
58 $str = substr( $str, $split );
61 if( $count !== 'end' ) {
62 $split = mb_substr_split_unicode( $str, intval( $count ) );
63 $str = substr( $str, 0, $split );
69 function mb_substr_split_unicode( $str, $splitPos ) {
70 if( $splitPos == 0 ) {
74 $byteLen = strlen( $str );
77 if( $splitPos > 256 ) {
78 // Optimize large string offsets by skipping ahead N bytes.
79 // This will cut out most of our slow time on Latin-based text,
80 // and 1/2 to 1/3 on East European and Asian scripts.
82 while ( $bytePos < $byteLen && $str{$bytePos} >= "\x80" && $str{$bytePos} < "\xc0" ) {
85 $charPos = mb_strlen( substr( $str, 0, $bytePos ) );
91 while( $charPos++
< $splitPos ) {
93 // Move past any tail bytes
94 while ( $bytePos < $byteLen && $str{$bytePos} >= "\x80" && $str{$bytePos} < "\xc0" ) {
99 $splitPosX = $splitPos +
1;
100 $charPos = 0; // relative to end of string; we don't care about the actual char position here
102 while( $bytePos > 0 && $charPos-- >= $splitPosX ) {
104 // Move past any tail bytes
105 while ( $bytePos > 0 && $str{$bytePos} >= "\x80" && $str{$bytePos} < "\xc0" ) {
115 if ( !function_exists( 'mb_strlen' ) ) {
117 * Fallback implementation of mb_strlen, hardcoded to UTF-8.
119 * @param string $enc optional encoding; ignored
122 function mb_strlen( $str, $enc = '' ) {
123 $counts = count_chars( $str );
127 for( $i = 0; $i < 0x80; $i++
) {
128 $total +
= $counts[$i];
131 // Count multibyte sequence heads
132 for( $i = 0xc0; $i < 0xff; $i++
) {
133 $total +
= $counts[$i];
140 if( !function_exists( 'mb_strpos' ) ) {
142 * Fallback implementation of mb_strpos, hardcoded to UTF-8.
143 * @param $haystack String
144 * @param $needle String
145 * @param $offset String: optional start position
146 * @param $encoding String: optional encoding; ignored
149 function mb_strpos( $haystack, $needle, $offset = 0, $encoding = '' ) {
150 $needle = preg_quote( $needle, '/' );
153 preg_match( '/' . $needle . '/u', $haystack, $ar, PREG_OFFSET_CAPTURE
, $offset );
155 if( isset( $ar[0][1] ) ) {
163 if( !function_exists( 'mb_strrpos' ) ) {
165 * Fallback implementation of mb_strrpos, hardcoded to UTF-8.
166 * @param $haystack String
167 * @param $needle String
168 * @param $offset String: optional start position
169 * @param $encoding String: optional encoding; ignored
172 function mb_strrpos( $haystack, $needle, $offset = 0, $encoding = '' ) {
173 $needle = preg_quote( $needle, '/' );
176 preg_match_all( '/' . $needle . '/u', $haystack, $ar, PREG_OFFSET_CAPTURE
, $offset );
178 if( isset( $ar[0] ) && count( $ar[0] ) > 0 &&
179 isset( $ar[0][count( $ar[0] ) - 1][1] ) ) {
180 return $ar[0][count( $ar[0] ) - 1][1];
187 // Support for Wietse Venema's taint feature
188 if ( !function_exists( 'istainted' ) ) {
189 function istainted( $var ) {
192 function taint( $var, $level = 0 ) {}
193 function untaint( $var, $level = 0 ) {}
194 define( 'TC_HTML', 1 );
195 define( 'TC_SHELL', 1 );
196 define( 'TC_MYSQL', 1 );
197 define( 'TC_PCRE', 1 );
198 define( 'TC_SELF', 1 );
204 * Like array_diff( $a, $b ) except that it works with two-dimensional arrays.
206 function wfArrayDiff2( $a, $b ) {
207 return array_udiff( $a, $b, 'wfArrayDiff2_cmp' );
209 function wfArrayDiff2_cmp( $a, $b ) {
210 if ( !is_array( $a ) ) {
211 return strcmp( $a, $b );
212 } elseif ( count( $a ) !== count( $b ) ) {
213 return count( $a ) < count( $b ) ?
-1 : 1;
217 while( ( list( $keyA, $valueA ) = each( $a ) ) && ( list( $keyB, $valueB ) = each( $b ) ) ) {
218 $cmp = strcmp( $valueA, $valueB );
228 * Seed Mersenne Twister
229 * No-op for compatibility; only necessary in PHP < 4.2.0
230 * @deprecated. Remove in 1.18
232 function wfSeedRandom() {
233 wfDeprecated(__FUNCTION__
);
237 * Get a random decimal value between 0 and 1, in a way
238 * not likely to give duplicate values for any realistic
239 * number of articles.
243 function wfRandom() {
244 # The maximum random value is "only" 2^31-1, so get two random
245 # values to reduce the chance of dupes
246 $max = mt_getrandmax() +
1;
247 $rand = number_format( ( mt_rand() * $max +
mt_rand() )
248 / $max / $max, 12, '.', '' );
253 * We want some things to be included as literal characters in our title URLs
254 * for prettiness, which urlencode encodes by default. According to RFC 1738,
255 * all of the following should be safe:
259 * But + is not safe because it's used to indicate a space; &= are only safe in
260 * paths and not in queries (and we don't distinguish here); ' seems kind of
261 * scary; and urlencode() doesn't touch -_. to begin with. Plus, although /
262 * is reserved, we don't care. So the list we unescape is:
266 * However, IIS7 redirects fail when the url contains a colon (Bug 22709),
267 * so no fancy : for IIS7.
269 * %2F in the page titles seems to fatally break for some reason.
274 function wfUrlencode( $s ) {
276 if ( is_null( $needle ) ) {
277 $needle = array( '%3B', '%40', '%24', '%21', '%2A', '%28', '%29', '%2C', '%2F' );
278 if ( !isset( $_SERVER['SERVER_SOFTWARE'] ) ||
( strpos( $_SERVER['SERVER_SOFTWARE'], 'Microsoft-IIS/7' ) === false ) ) {
283 $s = urlencode( $s );
286 array( ';', '@', '$', '!', '*', '(', ')', ',', '/', ':' ),
294 * Sends a line to the debug log if enabled or, optionally, to a comment in output.
295 * In normal operation this is a NOP.
297 * Controlling globals:
298 * $wgDebugLogFile - points to the log file
299 * $wgProfileOnly - if set, normal debug messages will not be recorded.
300 * $wgDebugRawPage - if false, 'action=raw' hits will not result in debug output.
301 * $wgDebugComments - if on, some debug items may appear in comments in the HTML output.
303 * @param $text String
304 * @param $logonly Bool: set true to avoid appearing in HTML when $wgDebugComments is set
306 function wfDebug( $text, $logonly = false ) {
307 global $wgOut, $wgDebugLogFile, $wgDebugComments, $wgProfileOnly, $wgDebugRawPage;
308 global $wgDebugLogPrefix, $wgShowDebug;
309 static $recursion = 0;
311 static $cache = array(); // Cache of unoutputted messages
312 $text = wfDebugTimer() . $text;
314 # Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
315 if ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' && !$wgDebugRawPage ) {
319 if ( ( $wgDebugComments ||
$wgShowDebug ) && !$logonly ) {
322 if ( !isset( $wgOut ) ) {
325 if ( !StubObject
::isRealObject( $wgOut ) ) {
334 // add the message and possible cached ones to the output
335 array_map( array( $wgOut, 'debug' ), $cache );
338 if ( $wgDebugLogFile != '' && !$wgProfileOnly ) {
339 # Strip unprintables; they can switch terminal modes when binary data
340 # gets dumped, which is pretty annoying.
341 $text = preg_replace( '![\x00-\x08\x0b\x0c\x0e-\x1f]!', ' ', $text );
342 $text = $wgDebugLogPrefix . $text;
343 wfErrorLog( $text, $wgDebugLogFile );
347 function wfDebugTimer() {
348 global $wgDebugTimestamps;
349 if ( !$wgDebugTimestamps ) {
352 static $start = null;
354 if ( $start === null ) {
355 $start = microtime( true );
356 $prefix = "\n$start";
358 $prefix = sprintf( "%6.4f", microtime( true ) - $start );
361 return $prefix . ' ';
365 * Send a line giving PHP memory usage.
366 * @param $exact Bool: print exact values instead of kilobytes (default: false)
368 function wfDebugMem( $exact = false ) {
369 $mem = memory_get_usage();
371 $mem = floor( $mem / 1024 ) . ' kilobytes';
375 wfDebug( "Memory usage: $mem\n" );
379 * Send a line to a supplementary debug log file, if configured, or main debug log if not.
380 * $wgDebugLogGroups[$logGroup] should be set to a filename to send to a separate log.
382 * @param $logGroup String
383 * @param $text String
384 * @param $public Bool: whether to log the event in the public log if no private
385 * log file is specified, (default true)
387 function wfDebugLog( $logGroup, $text, $public = true ) {
388 global $wgDebugLogGroups, $wgShowHostnames;
389 $text = trim( $text ) . "\n";
390 if( isset( $wgDebugLogGroups[$logGroup] ) ) {
391 $time = wfTimestamp( TS_DB
);
393 if ( $wgShowHostnames ) {
394 $host = wfHostname();
398 wfErrorLog( "$time $host $wiki: $text", $wgDebugLogGroups[$logGroup] );
399 } elseif ( $public === true ) {
400 wfDebug( $text, true );
405 * Log for database errors
406 * @param $text String: database error message.
408 function wfLogDBError( $text ) {
409 global $wgDBerrorLog, $wgDBname;
410 if ( $wgDBerrorLog ) {
411 $host = trim(`hostname`
);
412 $text = date( 'D M j G:i:s T Y' ) . "\t$host\t$wgDBname\t$text";
413 wfErrorLog( $text, $wgDBerrorLog );
418 * Log to a file without getting "file size exceeded" signals.
420 * Can also log to TCP or UDP with the syntax udp://host:port/prefix. This will
421 * send lines to the specified port, prefixed by the specified prefix and a space.
423 function wfErrorLog( $text, $file ) {
424 if ( substr( $file, 0, 4 ) == 'udp:' ) {
425 # Needs the sockets extension
426 if ( preg_match( '!^(tcp|udp):(?://)?\[([0-9a-fA-F:]+)\]:(\d+)(?:/(.*))?$!', $file, $m ) ) {
427 // IPv6 bracketed host
430 $port = intval( $m[3] );
431 $prefix = isset( $m[4] ) ?
$m[4] : false;
433 } elseif ( preg_match( '!^(tcp|udp):(?://)?([a-zA-Z0-9.-]+):(\d+)(?:/(.*))?$!', $file, $m ) ) {
436 if ( !IP
::isIPv4( $host ) ) {
437 $host = gethostbyname( $host );
439 $port = intval( $m[3] );
440 $prefix = isset( $m[4] ) ?
$m[4] : false;
443 throw new MWException( __METHOD__
. ': Invalid UDP specification' );
445 // Clean it up for the multiplexer
446 if ( strval( $prefix ) !== '' ) {
447 $text = preg_replace( '/^/m', $prefix . ' ', $text );
448 if ( substr( $text, -1 ) != "\n" ) {
453 $sock = socket_create( $domain, SOCK_DGRAM
, SOL_UDP
);
457 socket_sendto( $sock, $text, strlen( $text ), 0, $host, $port );
458 socket_close( $sock );
460 wfSuppressWarnings();
461 $exists = file_exists( $file );
462 $size = $exists ?
filesize( $file ) : false;
463 if ( !$exists ||
( $size !== false && $size +
strlen( $text ) < 0x7fffffff ) ) {
464 error_log( $text, 3, $file );
473 function wfLogProfilingData() {
474 global $wgRequestTime, $wgDebugLogFile, $wgDebugRawPage, $wgRequest;
475 global $wgProfiler, $wgProfileLimit, $wgUser;
476 # Profiling must actually be enabled...
477 if( is_null( $wgProfiler ) ) {
480 # Get total page request time
482 $elapsed = $now - $wgRequestTime;
483 # Only show pages that longer than $wgProfileLimit time (default is 0)
484 if( $elapsed <= $wgProfileLimit ) {
487 $prof = wfGetProfilingOutput( $wgRequestTime, $elapsed );
489 if( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) {
490 $forward = ' forwarded for ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
492 if( !empty( $_SERVER['HTTP_CLIENT_IP'] ) ) {
493 $forward .= ' client IP ' . $_SERVER['HTTP_CLIENT_IP'];
495 if( !empty( $_SERVER['HTTP_FROM'] ) ) {
496 $forward .= ' from ' . $_SERVER['HTTP_FROM'];
499 $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
501 // Don't unstub $wgUser at this late stage just for statistics purposes
502 if( StubObject
::isRealObject( $wgUser ) && $wgUser->isAnon() ) {
505 $log = sprintf( "%s\t%04.3f\t%s\n",
506 gmdate( 'YmdHis' ), $elapsed,
507 urldecode( $wgRequest->getRequestURL() . $forward ) );
508 if ( $wgDebugLogFile != '' && ( $wgRequest->getVal( 'action' ) != 'raw' ||
$wgDebugRawPage ) ) {
509 wfErrorLog( $log . $prof, $wgDebugLogFile );
514 * Check if the wiki read-only lock file is present. This can be used to lock
515 * off editing functions, but doesn't guarantee that the database will not be
519 function wfReadOnly() {
520 global $wgReadOnlyFile, $wgReadOnly;
522 if ( !is_null( $wgReadOnly ) ) {
523 return (bool)$wgReadOnly;
525 if ( $wgReadOnlyFile == '' ) {
528 // Set $wgReadOnly for faster access next time
529 if ( is_file( $wgReadOnlyFile ) ) {
530 $wgReadOnly = file_get_contents( $wgReadOnlyFile );
534 return (bool)$wgReadOnly;
537 function wfReadOnlyReason() {
544 * Return a Language object from $langcode
545 * @param $langcode Mixed: either:
546 * - a Language object
547 * - code of the language to get the message for, if it is
548 * a valid code create a language for that language, if
549 * it is a string but not a valid code then make a basic
551 * - a boolean: if it's false then use the current users
552 * language (as a fallback for the old parameter
553 * functionality), or if it is true then use the wikis
554 * @return Language object
556 function wfGetLangObj( $langcode = false ) {
557 # Identify which language to get or create a language object for.
558 # Using is_object here due to Stub objects.
559 if( is_object( $langcode ) ) {
560 # Great, we already have the object (hopefully)!
564 global $wgContLang, $wgLanguageCode;
565 if( $langcode === true ||
$langcode === $wgLanguageCode ) {
566 # $langcode is the language code of the wikis content language object.
567 # or it is a boolean and value is true
572 if( $langcode === false ||
$langcode === $wgLang->getCode() ) {
573 # $langcode is the language code of user language object.
574 # or it was a boolean and value is false
578 $validCodes = array_keys( Language
::getLanguageNames() );
579 if( in_array( $langcode, $validCodes ) ) {
580 # $langcode corresponds to a valid language.
581 return Language
::factory( $langcode );
584 # $langcode is a string, but not a valid language code; use content language.
585 wfDebug( "Invalid language code passed to wfGetLangObj, falling back to content language.\n" );
590 * Use this instead of $wgContLang, when working with user interface.
591 * User interface is currently hard coded according to wiki content language
592 * in many ways, especially regarding to text direction. There is lots stuff
593 * to fix, hence this function to keep the old behaviour unless the global
594 * $wgBetterDirectionality is enabled (or removed when everything works).
596 function wfUILang() {
597 global $wgBetterDirectionality;
598 return wfGetLangObj( !$wgBetterDirectionality );
602 * Get a message from anywhere, for the current user language.
604 * Use wfMsgForContent() instead if the message should NOT
605 * change depending on the user preferences.
607 * @param $key String: lookup key for the message, usually
608 * defined in languages/Language.php
610 * This function also takes extra optional parameters (not
611 * shown in the function definition), which can be used to
612 * insert variable text into the predefined message.
614 function wfMsg( $key ) {
615 $args = func_get_args();
616 array_shift( $args );
617 return wfMsgReal( $key, $args, true );
621 * Same as above except doesn't transform the message
623 function wfMsgNoTrans( $key ) {
624 $args = func_get_args();
625 array_shift( $args );
626 return wfMsgReal( $key, $args, true, false, false );
630 * Get a message from anywhere, for the current global language
631 * set with $wgLanguageCode.
633 * Use this if the message should NOT change dependent on the
634 * language set in the user's preferences. This is the case for
635 * most text written into logs, as well as link targets (such as
636 * the name of the copyright policy page). Link titles, on the
637 * other hand, should be shown in the UI language.
639 * Note that MediaWiki allows users to change the user interface
640 * language in their preferences, but a single installation
641 * typically only contains content in one language.
643 * Be wary of this distinction: If you use wfMsg() where you should
644 * use wfMsgForContent(), a user of the software may have to
645 * customize potentially hundreds of messages in
646 * order to, e.g., fix a link in every possible language.
648 * @param $key String: lookup key for the message, usually
649 * defined in languages/Language.php
651 function wfMsgForContent( $key ) {
652 global $wgForceUIMsgAsContentMsg;
653 $args = func_get_args();
654 array_shift( $args );
656 if( is_array( $wgForceUIMsgAsContentMsg ) &&
657 in_array( $key, $wgForceUIMsgAsContentMsg ) )
661 return wfMsgReal( $key, $args, true, $forcontent );
665 * Same as above except doesn't transform the message
667 function wfMsgForContentNoTrans( $key ) {
668 global $wgForceUIMsgAsContentMsg;
669 $args = func_get_args();
670 array_shift( $args );
672 if( is_array( $wgForceUIMsgAsContentMsg ) &&
673 in_array( $key, $wgForceUIMsgAsContentMsg ) )
677 return wfMsgReal( $key, $args, true, $forcontent, false );
681 * Get a message from the language file, for the UI elements
683 function wfMsgNoDB( $key ) {
684 $args = func_get_args();
685 array_shift( $args );
686 return wfMsgReal( $key, $args, false );
690 * Get a message from the language file, for the content
692 function wfMsgNoDBForContent( $key ) {
693 global $wgForceUIMsgAsContentMsg;
694 $args = func_get_args();
695 array_shift( $args );
697 if( is_array( $wgForceUIMsgAsContentMsg ) &&
698 in_array( $key, $wgForceUIMsgAsContentMsg ) )
702 return wfMsgReal( $key, $args, false, $forcontent );
707 * Really get a message
708 * @param $key String: key to get.
710 * @param $useDB Boolean
711 * @param $forContent Mixed: Language code, or false for user lang, true for content lang.
712 * @param $transform Boolean: Whether or not to transform the message.
713 * @return String: the requested message.
715 function wfMsgReal( $key, $args, $useDB = true, $forContent = false, $transform = true ) {
716 wfProfileIn( __METHOD__
);
717 $message = wfMsgGetKey( $key, $useDB, $forContent, $transform );
718 $message = wfMsgReplaceArgs( $message, $args );
719 wfProfileOut( __METHOD__
);
724 * This function provides the message source for messages to be edited which are *not* stored in the database.
725 * @param $key String:
727 function wfMsgWeirdKey( $key ) {
728 $source = wfMsgGetKey( $key, false, true, false );
729 if ( wfEmptyMsg( $key, $source ) ) {
737 * Fetch a message string value, but don't replace any keys yet.
740 * @param $langCode String: Code of the language to get the message for, or
741 * behaves as a content language switch if it is a boolean.
742 * @param $transform Boolean: whether to parse magic words, etc.
745 function wfMsgGetKey( $key, $useDB, $langCode = false, $transform = true ) {
746 global $wgMessageCache;
748 wfRunHooks( 'NormalizeMessageKey', array( &$key, &$useDB, &$langCode, &$transform ) );
750 if ( !is_object( $wgMessageCache ) ) {
751 throw new MWException( 'Trying to get message before message cache is initialised' );
754 $message = $wgMessageCache->get( $key, $useDB, $langCode );
755 if( $message === false ) {
756 $message = '<' . htmlspecialchars( $key ) . '>';
757 } elseif ( $transform ) {
758 $message = $wgMessageCache->transform( $message );
764 * Replace message parameter keys on the given formatted output.
766 * @param $message String
771 function wfMsgReplaceArgs( $message, $args ) {
772 # Fix windows line-endings
773 # Some messages are split with explode("\n", $msg)
774 $message = str_replace( "\r", '', $message );
777 if ( count( $args ) ) {
778 if ( is_array( $args[0] ) ) {
779 $args = array_values( $args[0] );
781 $replacementKeys = array();
782 foreach( $args as $n => $param ) {
783 $replacementKeys['$' . ( $n +
1 )] = $param;
785 $message = strtr( $message, $replacementKeys );
792 * Return an HTML-escaped version of a message.
793 * Parameter replacements, if any, are done *after* the HTML-escaping,
794 * so parameters may contain HTML (eg links or form controls). Be sure
795 * to pre-escape them if you really do want plaintext, or just wrap
796 * the whole thing in htmlspecialchars().
799 * @param string ... parameters
802 function wfMsgHtml( $key ) {
803 $args = func_get_args();
804 array_shift( $args );
805 return wfMsgReplaceArgs( htmlspecialchars( wfMsgGetKey( $key, true ) ), $args );
809 * Return an HTML version of message
810 * Parameter replacements, if any, are done *after* parsing the wiki-text message,
811 * so parameters may contain HTML (eg links or form controls). Be sure
812 * to pre-escape them if you really do want plaintext, or just wrap
813 * the whole thing in htmlspecialchars().
816 * @param string ... parameters
819 function wfMsgWikiHtml( $key ) {
821 $args = func_get_args();
822 array_shift( $args );
823 return wfMsgReplaceArgs( $wgOut->parse( wfMsgGetKey( $key, true ), /* can't be set to false */ true ), $args );
827 * Returns message in the requested format
828 * @param $key String: key of the message
829 * @param $options Array: processing rules. Can take the following options:
830 * <i>parse</i>: parses wikitext to HTML
831 * <i>parseinline</i>: parses wikitext to HTML and removes the surrounding
832 * p's added by parser or tidy
833 * <i>escape</i>: filters message through htmlspecialchars
834 * <i>escapenoentities</i>: same, but allows entity references like   through
835 * <i>replaceafter</i>: parameters are substituted after parsing or escaping
836 * <i>parsemag</i>: transform the message using magic phrases
837 * <i>content</i>: fetch message for content language instead of interface
838 * Also can accept a single associative argument, of the form 'language' => 'xx':
839 * <i>language</i>: Language object or language code to fetch message for
840 * (overriden by <i>content</i>), its behaviour with parser, parseinline
841 * and parsemag is undefined.
842 * Behavior for conflicting options (e.g., parse+parseinline) is undefined.
844 function wfMsgExt( $key, $options ) {
847 $args = func_get_args();
848 array_shift( $args );
849 array_shift( $args );
850 $options = (array)$options;
852 foreach( $options as $arrayKey => $option ) {
853 if( !preg_match( '/^[0-9]+|language$/', $arrayKey ) ) {
854 # An unknown index, neither numeric nor "language"
855 wfWarn( "wfMsgExt called with incorrect parameter key $arrayKey", 1, E_USER_WARNING
);
856 } elseif( preg_match( '/^[0-9]+$/', $arrayKey ) && !in_array( $option,
857 array( 'parse', 'parseinline', 'escape', 'escapenoentities',
858 'replaceafter', 'parsemag', 'content' ) ) ) {
859 # A numeric index with unknown value
860 wfWarn( "wfMsgExt called with incorrect parameter $option", 1, E_USER_WARNING
);
864 if( in_array( 'content', $options, true ) ) {
867 } elseif( array_key_exists( 'language', $options ) ) {
869 $langCode = wfGetLangObj( $options['language'] );
875 $string = wfMsgGetKey( $key, /*DB*/true, $langCode, /*Transform*/false );
877 if( !in_array( 'replaceafter', $options, true ) ) {
878 $string = wfMsgReplaceArgs( $string, $args );
881 if( in_array( 'parse', $options, true ) ) {
882 $string = $wgOut->parse( $string, true, !$forContent );
883 } elseif ( in_array( 'parseinline', $options, true ) ) {
884 $string = $wgOut->parse( $string, true, !$forContent );
886 if( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $string, $m ) ) {
889 } elseif ( in_array( 'parsemag', $options, true ) ) {
890 global $wgMessageCache;
891 if ( isset( $wgMessageCache ) ) {
892 $string = $wgMessageCache->transform( $string,
894 is_object( $langCode ) ?
$langCode : null );
898 if ( in_array( 'escape', $options, true ) ) {
899 $string = htmlspecialchars ( $string );
900 } elseif ( in_array( 'escapenoentities', $options, true ) ) {
901 $string = Sanitizer
::escapeHtmlAllowEntities( $string );
904 if( in_array( 'replaceafter', $options, true ) ) {
905 $string = wfMsgReplaceArgs( $string, $args );
913 * Just like exit() but makes a note of it.
914 * Commits open transactions except if the error parameter is set
916 * @deprecated Please return control to the caller or throw an exception
918 function wfAbruptExit( $error = false ) {
919 static $called = false;
925 $bt = wfDebugBacktrace();
927 for( $i = 0; $i < count( $bt ); $i++
) {
928 $file = isset( $bt[$i]['file'] ) ?
$bt[$i]['file'] : 'unknown';
929 $line = isset( $bt[$i]['line'] ) ?
$bt[$i]['line'] : 'unknown';
930 wfDebug( "WARNING: Abrupt exit in $file at line $line\n");
933 wfDebug( "WARNING: Abrupt exit\n" );
936 wfLogProfilingData();
939 wfGetLB()->closeAll();
945 * @deprecated Please return control the caller or throw an exception
947 function wfErrorExit() {
948 wfAbruptExit( true );
952 * Print a simple message and die, returning nonzero to the shell if any.
953 * Plain die() fails to return nonzero to the shell if you pass a string.
956 function wfDie( $msg = '' ) {
962 * Throw a debugging exception. This function previously once exited the process,
963 * but now throws an exception instead, with similar results.
965 * @param $msg String: message shown when dieing.
967 function wfDebugDieBacktrace( $msg = '' ) {
968 throw new MWException( $msg );
972 * Fetch server name for use in error reporting etc.
973 * Use real server name if available, so we know which machine
974 * in a server farm generated the current page.
977 function wfHostname() {
979 if ( is_null( $host ) ) {
980 if ( function_exists( 'posix_uname' ) ) {
981 // This function not present on Windows
982 $uname = @posix_uname
();
986 if( is_array( $uname ) && isset( $uname['nodename'] ) ) {
987 $host = $uname['nodename'];
988 } elseif ( getenv( 'COMPUTERNAME' ) ) {
989 # Windows computer name
990 $host = getenv( 'COMPUTERNAME' );
992 # This may be a virtual server.
993 $host = $_SERVER['SERVER_NAME'];
1000 * Returns a HTML comment with the elapsed time since request.
1001 * This method has no side effects.
1004 function wfReportTime() {
1005 global $wgRequestTime, $wgShowHostnames;
1008 $elapsed = $now - $wgRequestTime;
1010 return $wgShowHostnames
1011 ?
sprintf( '<!-- Served by %s in %01.3f secs. -->', wfHostname(), $elapsed )
1012 : sprintf( '<!-- Served in %01.3f secs. -->', $elapsed );
1016 * Safety wrapper for debug_backtrace().
1018 * With Zend Optimizer 3.2.0 loaded, this causes segfaults under somewhat
1019 * murky circumstances, which may be triggered in part by stub objects
1020 * or other fancy talkin'.
1022 * Will return an empty array if Zend Optimizer is detected or if
1023 * debug_backtrace is disabled, otherwise the output from
1024 * debug_backtrace() (trimmed).
1026 * @return array of backtrace information
1028 function wfDebugBacktrace() {
1029 static $disabled = null;
1031 if( extension_loaded( 'Zend Optimizer' ) ) {
1032 wfDebug( "Zend Optimizer detected; skipping debug_backtrace for safety.\n" );
1036 if ( is_null( $disabled ) ) {
1038 $functions = explode( ',', ini_get( 'disable_functions' ) );
1039 $functions = array_map( 'trim', $functions );
1040 $functions = array_map( 'strtolower', $functions );
1041 if ( in_array( 'debug_backtrace', $functions ) ) {
1042 wfDebug( "debug_backtrace is in disabled_functions\n" );
1050 return array_slice( debug_backtrace(), 1 );
1053 function wfBacktrace() {
1054 global $wgCommandLineMode;
1056 if ( $wgCommandLineMode ) {
1061 $backtrace = wfDebugBacktrace();
1062 foreach( $backtrace as $call ) {
1063 if( isset( $call['file'] ) ) {
1064 $f = explode( DIRECTORY_SEPARATOR
, $call['file'] );
1065 $file = $f[count( $f ) - 1];
1069 if( isset( $call['line'] ) ) {
1070 $line = $call['line'];
1074 if ( $wgCommandLineMode ) {
1075 $msg .= "$file line $line calls ";
1077 $msg .= '<li>' . $file . ' line ' . $line . ' calls ';
1079 if( !empty( $call['class'] ) ) {
1080 $msg .= $call['class'] . '::';
1082 $msg .= $call['function'] . '()';
1084 if ( $wgCommandLineMode ) {
1090 if ( $wgCommandLineMode ) {
1100 /* Some generic result counters, pulled out of SearchEngine */
1106 function wfShowingResults( $offset, $limit ) {
1110 array( 'parseinline' ),
1111 $wgLang->formatNum( $limit ),
1112 $wgLang->formatNum( $offset +
1 )
1119 function wfShowingResultsNum( $offset, $limit, $num ) {
1122 'showingresultsnum',
1123 array( 'parseinline' ),
1124 $wgLang->formatNum( $limit ),
1125 $wgLang->formatNum( $offset +
1 ),
1126 $wgLang->formatNum( $num )
1131 * Generate (prev x| next x) (20|50|100...) type links for paging
1132 * @param $offset String
1133 * @param $limit Integer
1134 * @param $link String
1135 * @param $query String: optional URL query parameter string
1136 * @param $atend Bool: optional param for specified if this is the last page
1138 function wfViewPrevNext( $offset, $limit, $link, $query = '', $atend = false ) {
1140 $fmtLimit = $wgLang->formatNum( $limit );
1141 // FIXME: Why on earth this needs one message for the text and another one for tooltip??
1142 # Get prev/next link display text
1143 $prev = wfMsgExt( 'prevn', array( 'parsemag', 'escape' ), $fmtLimit );
1144 $next = wfMsgExt( 'nextn', array( 'parsemag', 'escape' ), $fmtLimit );
1145 # Get prev/next link title text
1146 $pTitle = wfMsgExt( 'prevn-title', array( 'parsemag', 'escape' ), $fmtLimit );
1147 $nTitle = wfMsgExt( 'nextn-title', array( 'parsemag', 'escape' ), $fmtLimit );
1148 # Fetch the title object
1149 if( is_object( $link ) ) {
1152 $title = Title
::newFromText( $link );
1153 if( is_null( $title ) ) {
1157 # Make 'previous' link
1158 if( 0 != $offset ) {
1159 $po = $offset - $limit;
1160 $po = max( $po, 0 );
1161 $q = "limit={$limit}&offset={$po}";
1162 if( $query != '' ) {
1165 $plink = '<a href="' . $title->escapeLocalURL( $q ) . "\" title=\"{$pTitle}\" class=\"mw-prevlink\">{$prev}</a>";
1170 $no = $offset +
$limit;
1171 $q = "limit={$limit}&offset={$no}";
1172 if( $query != '' ) {
1178 $nlink = '<a href="' . $title->escapeLocalURL( $q ) . "\" title=\"{$nTitle}\" class=\"mw-nextlink\">{$next}</a>";
1180 # Make links to set number of items per page
1181 $nums = $wgLang->pipeList( array(
1182 wfNumLink( $offset, 20, $title, $query ),
1183 wfNumLink( $offset, 50, $title, $query ),
1184 wfNumLink( $offset, 100, $title, $query ),
1185 wfNumLink( $offset, 250, $title, $query ),
1186 wfNumLink( $offset, 500, $title, $query )
1188 return wfMsgHtml( 'viewprevnext', $plink, $nlink, $nums );
1192 * Generate links for (20|50|100...) items-per-page links
1193 * @param $offset String
1194 * @param $limit Integer
1195 * @param $title Title
1196 * @param $query String: optional URL query parameter string
1198 function wfNumLink( $offset, $limit, $title, $query = '' ) {
1200 if( $query == '' ) {
1205 $q .= "limit={$limit}&offset={$offset}";
1206 $fmtLimit = $wgLang->formatNum( $limit );
1207 $lTitle = wfMsgExt( 'shown-title', array( 'parsemag', 'escape' ), $limit );
1208 $s = '<a href="' . $title->escapeLocalURL( $q ) . "\" title=\"{$lTitle}\" class=\"mw-numlink\">{$fmtLimit}</a>";
1214 * @todo FIXME: we may want to blacklist some broken browsers
1216 * @return bool Whereas client accept gzip compression
1218 function wfClientAcceptsGzip() {
1219 if( isset( $_SERVER['HTTP_ACCEPT_ENCODING'] ) ) {
1220 # FIXME: we may want to blacklist some broken browsers
1223 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
1224 $_SERVER['HTTP_ACCEPT_ENCODING'],
1228 if( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) {
1231 wfDebug( " accepts gzip\n" );
1239 * Obtain the offset and limit values from the request string;
1240 * used in special pages
1242 * @param $deflimit Default limit if none supplied
1243 * @param $optionname Name of a user preference to check against
1247 function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) {
1249 return $wgRequest->getLimitOffset( $deflimit, $optionname );
1253 * Escapes the given text so that it may be output using addWikiText()
1254 * without any linking, formatting, etc. making its way through. This
1255 * is achieved by substituting certain characters with HTML entities.
1256 * As required by the callers, <nowiki> is not used. It currently does
1257 * not filter out characters which have special meaning only at the
1258 * start of a line, such as "*".
1260 * @param $text String: text to be escaped
1262 function wfEscapeWikiText( $text ) {
1263 $text = str_replace(
1264 array( '[', '|', ']', '\'', 'ISBN ', 'RFC ', '://', "\n=", '{{' ), # }}
1265 array( '[', '|', ']', ''', 'ISBN ', 'RFC ', '://', "\n=", '{{' ),
1266 htmlspecialchars( $text )
1274 function wfQuotedPrintable( $string, $charset = '' ) {
1275 # Probably incomplete; see RFC 2045
1276 if( empty( $charset ) ) {
1277 global $wgInputEncoding;
1278 $charset = $wgInputEncoding;
1280 $charset = strtoupper( $charset );
1281 $charset = str_replace( 'ISO-8859', 'ISO8859', $charset ); // ?
1283 $illegal = '\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\xff=';
1284 $replace = $illegal . '\t ?_';
1285 if( !preg_match( "/[$illegal]/", $string ) ) {
1288 $out = "=?$charset?Q?";
1289 $out .= preg_replace( "/([$replace])/e", 'sprintf("=%02X",ord("$1"))', $string );
1300 return microtime( true );
1304 * Sets dest to source and returns the original value of dest
1305 * If source is NULL, it just returns the value, it doesn't set the variable
1307 function wfSetVar( &$dest, $source ) {
1309 if ( !is_null( $source ) ) {
1316 * As for wfSetVar except setting a bit
1318 function wfSetBit( &$dest, $bit, $state = true ) {
1319 $temp = (bool)( $dest & $bit );
1320 if ( !is_null( $state ) ) {
1331 * This function takes two arrays as input, and returns a CGI-style string, e.g.
1332 * "days=7&limit=100". Options in the first array override options in the second.
1333 * Options set to "" will not be output.
1335 function wfArrayToCGI( $array1, $array2 = null ) {
1336 if ( !is_null( $array2 ) ) {
1337 $array1 = $array1 +
$array2;
1341 foreach ( $array1 as $key => $value ) {
1342 if ( $value !== '' ) {
1346 if ( is_array( $value ) ) {
1348 foreach ( $value as $v ) {
1349 $cgi .= ( $firstTime ?
'' : '&') .
1350 urlencode( $key . '[]' ) . '=' .
1355 if ( is_object( $value ) ) {
1356 $value = $value->__toString();
1358 $cgi .= urlencode( $key ) . '=' .
1359 urlencode( $value );
1367 * This is the logical opposite of wfArrayToCGI(): it accepts a query string as
1368 * its argument and returns the same string in array form. This allows compa-
1369 * tibility with legacy functions that accept raw query strings instead of nice
1370 * arrays. Of course, keys and values are urldecode()d. Don't try passing in-
1371 * valid query strings, or it will explode.
1373 * @param $query String: query string
1374 * @return array Array version of input
1376 function wfCgiToArray( $query ) {
1377 if( isset( $query[0] ) && $query[0] == '?' ) {
1378 $query = substr( $query, 1 );
1380 $bits = explode( '&', $query );
1382 foreach( $bits as $bit ) {
1386 list( $key, $value ) = explode( '=', $bit );
1387 $key = urldecode( $key );
1388 $value = urldecode( $value );
1389 $ret[$key] = $value;
1395 * Append a query string to an existing URL, which may or may not already
1396 * have query string parameters already. If so, they will be combined.
1398 * @param $url String
1399 * @param $query Mixed: string or associative array
1402 function wfAppendQuery( $url, $query ) {
1403 if ( is_array( $query ) ) {
1404 $query = wfArrayToCGI( $query );
1406 if( $query != '' ) {
1407 if( false === strpos( $url, '?' ) ) {
1418 * Expand a potentially local URL to a fully-qualified URL. Assumes $wgServer
1419 * and $wgProto are correct.
1421 * @todo this won't work with current-path-relative URLs
1422 * like "subdir/foo.html", etc.
1424 * @param $url String: either fully-qualified or a local path + query
1425 * @return string Fully-qualified URL
1427 function wfExpandUrl( $url ) {
1428 if( substr( $url, 0, 2 ) == '//' ) {
1430 return $wgProto . ':' . $url;
1431 } elseif( substr( $url, 0, 1 ) == '/' ) {
1433 return $wgServer . $url;
1440 * This is obsolete, use SquidUpdate::purge()
1443 function wfPurgeSquidServers( $urlArr ) {
1444 SquidUpdate
::purge( $urlArr );
1448 * Windows-compatible version of escapeshellarg()
1449 * Windows doesn't recognise single-quotes in the shell, but the escapeshellarg()
1450 * function puts single quotes in regardless of OS.
1452 * Also fixes the locale problems on Linux in PHP 5.2.6+ (bug backported to
1453 * earlier distro releases of PHP)
1455 function wfEscapeShellArg( ) {
1456 wfInitShellLocale();
1458 $args = func_get_args();
1461 foreach ( $args as $arg ) {
1468 if ( wfIsWindows() ) {
1469 // Escaping for an MSVC-style command line parser
1470 // Ref: http://mailman.lyra.org/pipermail/scite-interest/2002-March/000436.html
1471 // Double the backslashes before any double quotes. Escape the double quotes.
1472 $tokens = preg_split( '/(\\\\*")/', $arg, -1, PREG_SPLIT_DELIM_CAPTURE
);
1475 foreach ( $tokens as $token ) {
1476 if ( $iteration %
2 == 1 ) {
1477 // Delimiter, a double quote preceded by zero or more slashes
1478 $arg .= str_replace( '\\', '\\\\', substr( $token, 0, -1 ) ) . '\\"';
1479 } elseif ( $iteration %
4 == 2 ) {
1480 // ^ in $token will be outside quotes, need to be escaped
1481 $arg .= str_replace( '^', '^^', $token );
1482 } else { // $iteration % 4 == 0
1483 // ^ in $token will appear inside double quotes, so leave as is
1488 // Double the backslashes before the end of the string, because
1489 // we will soon add a quote
1491 if ( preg_match( '/^(.*?)(\\\\+)$/', $arg, $m ) ) {
1492 $arg = $m[1] . str_replace( '\\', '\\\\', $m[2] );
1495 // Add surrounding quotes
1496 $retVal .= '"' . $arg . '"';
1498 $retVal .= escapeshellarg( $arg );
1505 * wfMerge attempts to merge differences between three texts.
1506 * Returns true for a clean merge and false for failure or a conflict.
1508 function wfMerge( $old, $mine, $yours, &$result ) {
1511 # This check may also protect against code injection in
1512 # case of broken installations.
1513 wfSuppressWarnings();
1514 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
1515 wfRestoreWarnings();
1518 wfDebug( "diff3 not found\n" );
1522 # Make temporary files
1524 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
1525 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
1526 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
1528 fwrite( $oldtextFile, $old );
1529 fclose( $oldtextFile );
1530 fwrite( $mytextFile, $mine );
1531 fclose( $mytextFile );
1532 fwrite( $yourtextFile, $yours );
1533 fclose( $yourtextFile );
1535 # Check for a conflict
1536 $cmd = $wgDiff3 . ' -a --overlap-only ' .
1537 wfEscapeShellArg( $mytextName ) . ' ' .
1538 wfEscapeShellArg( $oldtextName ) . ' ' .
1539 wfEscapeShellArg( $yourtextName );
1540 $handle = popen( $cmd, 'r' );
1542 if( fgets( $handle, 1024 ) ) {
1550 $cmd = $wgDiff3 . ' -a -e --merge ' .
1551 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
1552 $handle = popen( $cmd, 'r' );
1555 $data = fread( $handle, 8192 );
1556 if ( strlen( $data ) == 0 ) {
1562 unlink( $mytextName );
1563 unlink( $oldtextName );
1564 unlink( $yourtextName );
1566 if ( $result === '' && $old !== '' && !$conflict ) {
1567 wfDebug( "Unexpected null result from diff3. Command: $cmd\n" );
1574 * Returns unified plain-text diff of two texts.
1575 * Useful for machine processing of diffs.
1576 * @param $before String: the text before the changes.
1577 * @param $after String: the text after the changes.
1578 * @param $params String: command-line options for the diff command.
1579 * @return String: unified diff of $before and $after
1581 function wfDiff( $before, $after, $params = '-u' ) {
1582 if ( $before == $after ) {
1587 wfSuppressWarnings();
1588 $haveDiff = $wgDiff && file_exists( $wgDiff );
1589 wfRestoreWarnings();
1591 # This check may also protect against code injection in
1592 # case of broken installations.
1594 wfDebug( "diff executable not found\n" );
1595 $diffs = new Diff( explode( "\n", $before ), explode( "\n", $after ) );
1596 $format = new UnifiedDiffFormatter();
1597 return $format->format( $diffs );
1600 # Make temporary files
1602 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
1603 $newtextFile = fopen( $newtextName = tempnam( $td, 'merge-your-' ), 'w' );
1605 fwrite( $oldtextFile, $before );
1606 fclose( $oldtextFile );
1607 fwrite( $newtextFile, $after );
1608 fclose( $newtextFile );
1610 // Get the diff of the two files
1611 $cmd = "$wgDiff " . $params . ' ' . wfEscapeShellArg( $oldtextName, $newtextName );
1613 $h = popen( $cmd, 'r' );
1618 $data = fread( $h, 8192 );
1619 if ( strlen( $data ) == 0 ) {
1627 unlink( $oldtextName );
1628 unlink( $newtextName );
1630 // Kill the --- and +++ lines. They're not useful.
1631 $diff_lines = explode( "\n", $diff );
1632 if ( strpos( $diff_lines[0], '---' ) === 0 ) {
1633 unset( $diff_lines[0] );
1635 if ( strpos( $diff_lines[1], '+++' ) === 0 ) {
1636 unset( $diff_lines[1] );
1639 $diff = implode( "\n", $diff_lines );
1645 * A wrapper around the PHP function var_export().
1646 * Either print it or add it to the regular output ($wgOut).
1648 * @param $var A PHP variable to dump.
1650 function wfVarDump( $var ) {
1652 $s = str_replace( "\n", "<br />\n", var_export( $var, true ) . "\n" );
1653 if ( headers_sent() ||
!@is_object
( $wgOut ) ) {
1656 $wgOut->addHTML( $s );
1661 * Provide a simple HTTP error.
1663 function wfHttpError( $code, $label, $desc ) {
1666 header( "HTTP/1.0 $code $label" );
1667 header( "Status: $code $label" );
1668 $wgOut->sendCacheControl();
1670 header( 'Content-type: text/html; charset=utf-8' );
1671 print "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">".
1672 '<html><head><title>' .
1673 htmlspecialchars( $label ) .
1674 '</title></head><body><h1>' .
1675 htmlspecialchars( $label ) .
1677 nl2br( htmlspecialchars( $desc ) ) .
1678 "</p></body></html>\n";
1682 * Clear away any user-level output buffers, discarding contents.
1684 * Suitable for 'starting afresh', for instance when streaming
1685 * relatively large amounts of data without buffering, or wanting to
1686 * output image files without ob_gzhandler's compression.
1688 * The optional $resetGzipEncoding parameter controls suppression of
1689 * the Content-Encoding header sent by ob_gzhandler; by default it
1690 * is left. See comments for wfClearOutputBuffers() for why it would
1693 * Note that some PHP configuration options may add output buffer
1694 * layers which cannot be removed; these are left in place.
1696 * @param $resetGzipEncoding Bool
1698 function wfResetOutputBuffers( $resetGzipEncoding = true ) {
1699 if( $resetGzipEncoding ) {
1700 // Suppress Content-Encoding and Content-Length
1701 // headers from 1.10+s wfOutputHandler
1702 global $wgDisableOutputCompression;
1703 $wgDisableOutputCompression = true;
1705 while( $status = ob_get_status() ) {
1706 if( $status['type'] == 0 /* PHP_OUTPUT_HANDLER_INTERNAL */ ) {
1707 // Probably from zlib.output_compression or other
1708 // PHP-internal setting which can't be removed.
1710 // Give up, and hope the result doesn't break
1714 if( !ob_end_clean() ) {
1715 // Could not remove output buffer handler; abort now
1716 // to avoid getting in some kind of infinite loop.
1719 if( $resetGzipEncoding ) {
1720 if( $status['name'] == 'ob_gzhandler' ) {
1721 // Reset the 'Content-Encoding' field set by this handler
1722 // so we can start fresh.
1723 header( 'Content-Encoding:' );
1731 * More legible than passing a 'false' parameter to wfResetOutputBuffers():
1733 * Clear away output buffers, but keep the Content-Encoding header
1734 * produced by ob_gzhandler, if any.
1736 * This should be used for HTTP 304 responses, where you need to
1737 * preserve the Content-Encoding header of the real result, but
1738 * also need to suppress the output of ob_gzhandler to keep to spec
1739 * and avoid breaking Firefox in rare cases where the headers and
1740 * body are broken over two packets.
1742 function wfClearOutputBuffers() {
1743 wfResetOutputBuffers( false );
1747 * Converts an Accept-* header into an array mapping string values to quality
1750 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
1751 # No arg means accept anything (per HTTP spec)
1753 return array( $def => 1.0 );
1758 $parts = explode( ',', $accept );
1760 foreach( $parts as $part ) {
1761 # FIXME: doesn't deal with params like 'text/html; level=1'
1762 @list
( $value, $qpart ) = explode( ';', trim( $part ) );
1764 if( !isset( $qpart ) ) {
1765 $prefs[$value] = 1.0;
1766 } elseif( preg_match( '/q\s*=\s*(\d*\.\d+)/', $qpart, $match ) ) {
1767 $prefs[$value] = floatval( $match[1] );
1775 * Checks if a given MIME type matches any of the keys in the given
1776 * array. Basic wildcards are accepted in the array keys.
1778 * Returns the matching MIME type (or wildcard) if a match, otherwise
1781 * @param $type String
1782 * @param $avail Array
1786 function mimeTypeMatch( $type, $avail ) {
1787 if( array_key_exists( $type, $avail ) ) {
1790 $parts = explode( '/', $type );
1791 if( array_key_exists( $parts[0] . '/*', $avail ) ) {
1792 return $parts[0] . '/*';
1793 } elseif( array_key_exists( '*/*', $avail ) ) {
1802 * Returns the 'best' match between a client's requested internet media types
1803 * and the server's list of available types. Each list should be an associative
1804 * array of type to preference (preference is a float between 0.0 and 1.0).
1805 * Wildcards in the types are acceptable.
1807 * @param $cprefs Array: client's acceptable type list
1808 * @param $sprefs Array: server's offered types
1811 * @todo FIXME: doesn't handle params like 'text/plain; charset=UTF-8'
1812 * XXX: generalize to negotiate other stuff
1814 function wfNegotiateType( $cprefs, $sprefs ) {
1817 foreach( array_keys($sprefs) as $type ) {
1818 $parts = explode( '/', $type );
1819 if( $parts[1] != '*' ) {
1820 $ckey = mimeTypeMatch( $type, $cprefs );
1822 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1827 foreach( array_keys( $cprefs ) as $type ) {
1828 $parts = explode( '/', $type );
1829 if( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
1830 $skey = mimeTypeMatch( $type, $sprefs );
1832 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1840 foreach( array_keys( $combine ) as $type ) {
1841 if( $combine[$type] > $bestq ) {
1843 $bestq = $combine[$type];
1852 * Returns an array where the values in the first array are replaced by the
1853 * values in the second array with the corresponding keys
1857 function wfArrayLookup( $a, $b ) {
1858 return array_flip( array_intersect( array_flip( $a ), array_keys( $b ) ) );
1862 * Convenience function; returns MediaWiki timestamp for the present time.
1865 function wfTimestampNow() {
1867 return wfTimestamp( TS_MW
, time() );
1871 * Reference-counted warning suppression
1873 function wfSuppressWarnings( $end = false ) {
1874 static $suppressCount = 0;
1875 static $originalLevel = false;
1878 if ( $suppressCount ) {
1880 if ( !$suppressCount ) {
1881 error_reporting( $originalLevel );
1885 if ( !$suppressCount ) {
1886 $originalLevel = error_reporting( E_ALL
& ~
( E_WARNING | E_NOTICE | E_USER_WARNING | E_USER_NOTICE
) );
1893 * Restore error level to previous value
1895 function wfRestoreWarnings() {
1896 wfSuppressWarnings( true );
1899 # Autodetect, convert and provide timestamps of various types
1902 * Unix time - the number of seconds since 1970-01-01 00:00:00 UTC
1904 define( 'TS_UNIX', 0 );
1907 * MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
1909 define( 'TS_MW', 1 );
1912 * MySQL DATETIME (YYYY-MM-DD HH:MM:SS)
1914 define( 'TS_DB', 2 );
1917 * RFC 2822 format, for E-mail and HTTP headers
1919 define( 'TS_RFC2822', 3 );
1922 * ISO 8601 format with no timezone: 1986-02-09T20:00:00Z
1924 * This is used by Special:Export
1926 define( 'TS_ISO_8601', 4 );
1929 * An Exif timestamp (YYYY:MM:DD HH:MM:SS)
1931 * @see http://exif.org/Exif2-2.PDF The Exif 2.2 spec, see page 28 for the
1932 * DateTime tag and page 36 for the DateTimeOriginal and
1933 * DateTimeDigitized tags.
1935 define( 'TS_EXIF', 5 );
1938 * Oracle format time.
1940 define( 'TS_ORACLE', 6 );
1943 * Postgres format time.
1945 define( 'TS_POSTGRES', 7 );
1950 define( 'TS_DB2', 8 );
1953 * @param $outputtype Mixed: A timestamp in one of the supported formats, the
1954 * function will autodetect which format is supplied and act
1956 * @param $ts Mixed: the timestamp to convert or 0 for the current timestamp
1957 * @return String: in the format specified in $outputtype
1959 function wfTimestamp( $outputtype = TS_UNIX
, $ts = 0 ) {
1964 } elseif ( preg_match( '/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)$/D', $ts, $da ) ) {
1966 } elseif ( preg_match( '/^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/D', $ts, $da ) ) {
1968 } elseif ( preg_match( '/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/D', $ts, $da ) ) {
1970 } elseif ( preg_match( '/^-?\d{1,13}$/D', $ts ) ) {
1973 } elseif ( preg_match( '/^\d{2}-\d{2}-\d{4} \d{2}:\d{2}:\d{2}.\d{6}$/', $ts ) ) {
1974 # TS_ORACLE // session altered to DD-MM-YYYY HH24:MI:SS.FF6
1975 $uts = strtotime( preg_replace( '/(\d\d)\.(\d\d)\.(\d\d)(\.(\d+))?/', "$1:$2:$3",
1976 str_replace( '+00:00', 'UTC', $ts ) ) );
1977 } elseif ( preg_match( '/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.*\d*)?Z$/', $ts, $da ) ) {
1979 } elseif ( preg_match( '/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.*\d*[\+\- ](\d\d)$/', $ts, $da ) ) {
1981 } elseif ( preg_match( '/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.*\d* GMT$/', $ts, $da ) ) {
1983 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.\d\d\d$/',$ts,$da)) {
1985 } elseif ( preg_match( '/^[A-Z][a-z]{2}, \d\d [A-Z][a-z]{2} \d{4} \d\d:\d\d:\d\d/', $ts ) ) {
1987 $uts = strtotime( $ts );
1989 # Bogus value; fall back to the epoch...
1990 wfDebug("wfTimestamp() fed bogus time value: $outputtype; $ts\n");
1994 if (count( $da ) ) {
1995 // Warning! gmmktime() acts oddly if the month or day is set to 0
1996 // We may want to handle that explicitly at some point
1997 $uts = gmmktime( (int)$da[4], (int)$da[5], (int)$da[6],
1998 (int)$da[2], (int)$da[3], (int)$da[1] );
2001 switch( $outputtype ) {
2005 return gmdate( 'YmdHis', $uts );
2007 return gmdate( 'Y-m-d H:i:s', $uts );
2009 return gmdate( 'Y-m-d\TH:i:s\Z', $uts );
2010 // This shouldn't ever be used, but is included for completeness
2012 return gmdate( 'Y:m:d H:i:s', $uts );
2014 return gmdate( 'D, d M Y H:i:s', $uts ) . ' GMT';
2016 return gmdate( 'd-m-Y H:i:s.000000', $uts );
2017 //return gmdate( 'd-M-y h.i.s A', $uts ) . ' +00:00';
2019 return gmdate( 'Y-m-d H:i:s', $uts ) . ' GMT';
2021 return gmdate( 'Y-m-d H:i:s', $uts );
2023 throw new MWException( 'wfTimestamp() called with illegal output type.' );
2028 * Return a formatted timestamp, or null if input is null.
2029 * For dealing with nullable timestamp columns in the database.
2030 * @param $outputtype Integer
2034 function wfTimestampOrNull( $outputtype = TS_UNIX
, $ts = null ) {
2035 if( is_null( $ts ) ) {
2038 return wfTimestamp( $outputtype, $ts );
2043 * Check if the operating system is Windows
2045 * @return Bool: true if it's Windows, False otherwise.
2047 function wfIsWindows() {
2048 if ( substr( php_uname(), 0, 7 ) == 'Windows' ) {
2056 * Swap two variables
2058 function swap( &$x, &$y ) {
2064 function wfGetCachedNotice( $name ) {
2065 global $wgOut, $wgRenderHashAppend, $parserMemc;
2066 $fname = 'wfGetCachedNotice';
2067 wfProfileIn( $fname );
2071 if( $name === 'default' ) {
2073 global $wgSiteNotice;
2074 $notice = $wgSiteNotice;
2075 if( empty( $notice ) ) {
2076 wfProfileOut( $fname );
2080 $notice = wfMsgForContentNoTrans( $name );
2081 if( wfEmptyMsg( $name, $notice ) ||
$notice == '-' ) {
2082 wfProfileOut( $fname );
2087 // Use the extra hash appender to let eg SSL variants separately cache.
2088 $key = wfMemcKey( $name . $wgRenderHashAppend );
2089 $cachedNotice = $parserMemc->get( $key );
2090 if( is_array( $cachedNotice ) ) {
2091 if( md5( $notice ) == $cachedNotice['hash'] ) {
2092 $notice = $cachedNotice['html'];
2101 if( is_object( $wgOut ) ) {
2102 $parsed = $wgOut->parse( $notice );
2103 $parserMemc->set( $key, array( 'html' => $parsed, 'hash' => md5( $notice ) ), 600 );
2106 wfDebug( 'wfGetCachedNotice called for ' . $name . ' with no $wgOut available' . "\n" );
2110 $notice = '<div id="localNotice">' .$notice . '</div>';
2111 wfProfileOut( $fname );
2115 function wfGetNamespaceNotice() {
2119 if ( !isset( $wgTitle ) ||
!is_object( $wgTitle ) ) {
2123 $fname = 'wfGetNamespaceNotice';
2124 wfProfileIn( $fname );
2126 $key = 'namespacenotice-' . $wgTitle->getNsText();
2127 $namespaceNotice = wfGetCachedNotice( $key );
2128 if ( $namespaceNotice && substr( $namespaceNotice, 0, 7 ) != '<p><' ) {
2129 $namespaceNotice = '<div id="namespacebanner">' . $namespaceNotice . '</div>';
2131 $namespaceNotice = '';
2134 wfProfileOut( $fname );
2135 return $namespaceNotice;
2138 function wfGetSiteNotice() {
2140 $fname = 'wfGetSiteNotice';
2141 wfProfileIn( $fname );
2144 if( wfRunHooks( 'SiteNoticeBefore', array( &$siteNotice ) ) ) {
2145 if( is_object( $wgUser ) && $wgUser->isLoggedIn() ) {
2146 $siteNotice = wfGetCachedNotice( 'sitenotice' );
2148 $anonNotice = wfGetCachedNotice( 'anonnotice' );
2149 if( !$anonNotice ) {
2150 $siteNotice = wfGetCachedNotice( 'sitenotice' );
2152 $siteNotice = $anonNotice;
2155 if( !$siteNotice ) {
2156 $siteNotice = wfGetCachedNotice( 'default' );
2160 wfRunHooks( 'SiteNoticeAfter', array( &$siteNotice ) );
2161 wfProfileOut( $fname );
2166 * BC wrapper for MimeMagic::singleton()
2169 function &wfGetMimeMagic() {
2170 wfDeprecated( __FUNCTION__
);
2171 return MimeMagic
::singleton();
2175 * Tries to get the system directory for temporary files. The TMPDIR, TMP, and
2176 * TEMP environment variables are then checked in sequence, and if none are set
2177 * try sys_get_temp_dir() for PHP >= 5.2.1. All else fails, return /tmp for Unix
2178 * or C:\Windows\Temp for Windows and hope for the best.
2179 * It is common to call it with tempnam().
2181 * NOTE: When possible, use instead the tmpfile() function to create
2182 * temporary files to avoid race conditions on file creation, etc.
2186 function wfTempDir() {
2187 foreach( array( 'TMPDIR', 'TMP', 'TEMP' ) as $var ) {
2188 $tmp = getenv( $var );
2189 if( $tmp && file_exists( $tmp ) && is_dir( $tmp ) && is_writable( $tmp ) ) {
2193 if( function_exists( 'sys_get_temp_dir' ) ) {
2194 return sys_get_temp_dir();
2197 return wfIsWindows() ?
'C:\Windows\Temp' : '/tmp';
2201 * Make directory, and make all parent directories if they don't exist
2203 * @param $dir String: full path to directory to create
2204 * @param $mode Integer: chmod value to use, default is $wgDirectoryMode
2205 * @param $caller String: optional caller param for debugging.
2208 function wfMkdirParents( $dir, $mode = null, $caller = null ) {
2209 global $wgDirectoryMode;
2211 if ( !is_null( $caller ) ) {
2212 wfDebug( "$caller: called wfMkdirParents($dir)" );
2215 if( strval( $dir ) === '' ||
file_exists( $dir ) ) {
2219 $dir = str_replace( array( '\\', '/' ), DIRECTORY_SEPARATOR
, $dir );
2221 if ( is_null( $mode ) ) {
2222 $mode = $wgDirectoryMode;
2225 // Turn off the normal warning, we're doing our own below
2226 wfSuppressWarnings();
2227 $ok = mkdir( $dir, $mode, true ); // PHP5 <3
2228 wfRestoreWarnings();
2231 // PHP doesn't report the path in its warning message, so add our own to aid in diagnosis.
2232 trigger_error( __FUNCTION__
. ": failed to mkdir \"$dir\" mode $mode", E_USER_WARNING
);
2238 * Increment a statistics counter
2240 function wfIncrStats( $key ) {
2241 global $wgStatsMethod;
2243 if( $wgStatsMethod == 'udp' ) {
2244 global $wgUDPProfilerHost, $wgUDPProfilerPort, $wgDBname;
2247 $socket = socket_create( AF_INET
, SOCK_DGRAM
, SOL_UDP
);
2248 $statline = "stats/{$wgDBname} - 1 1 1 1 1 -total\n";
2252 strlen( $statline ),
2258 $statline = "stats/{$wgDBname} - 1 1 1 1 1 {$key}\n";
2262 strlen( $statline ),
2267 } elseif( $wgStatsMethod == 'cache' ) {
2269 $key = wfMemcKey( 'stats', $key );
2270 if ( is_null( $wgMemc->incr( $key ) ) ) {
2271 $wgMemc->add( $key, 1 );
2279 * @param $nr Mixed: the number to format
2280 * @param $acc Integer: the number of digits after the decimal point, default 2
2281 * @param $round Boolean: whether or not to round the value, default true
2284 function wfPercent( $nr, $acc = 2, $round = true ) {
2285 $ret = sprintf( "%.${acc}f", $nr );
2286 return $round ?
round( $ret, $acc ) . '%' : "$ret%";
2290 * Encrypt a username/password.
2292 * @param $userid Integer: ID of the user
2293 * @param $password String: password of the user
2294 * @return String: hashed password
2295 * @deprecated Use User::crypt() or User::oldCrypt() instead
2297 function wfEncryptPassword( $userid, $password ) {
2298 wfDeprecated(__FUNCTION__
);
2299 # Just wrap around User::oldCrypt()
2300 return User
::oldCrypt( $password, $userid );
2304 * Appends to second array if $value differs from that in $default
2306 function wfAppendToArrayIfNotDefault( $key, $value, $default, &$changed ) {
2307 if ( is_null( $changed ) ) {
2308 throw new MWException( 'GlobalFunctions::wfAppendToArrayIfNotDefault got null' );
2310 if ( $default[$key] !== $value ) {
2311 $changed[$key] = $value;
2316 * Since wfMsg() and co suck, they don't return false if the message key they
2317 * looked up didn't exist but a XHTML string, this function checks for the
2318 * nonexistance of messages by looking at wfMsg() output
2320 * @param $key String: the message key looked up
2321 * @return Boolean True if the message *doesn't* exist.
2323 function wfEmptyMsg( $key ) {
2324 global $wgMessageCache;
2325 return $wgMessageCache->get( $key, /*useDB*/true, /*content*/false ) === false;
2329 * Find out whether or not a mixed variable exists in a string
2331 * @param $needle String
2332 * @param $str String
2335 function in_string( $needle, $str ) {
2336 return strpos( $str, $needle ) !== false;
2339 function wfSpecialList( $page, $details ) {
2341 $details = $details ?
' ' . $wgContLang->getDirMark() . "($details)" : '';
2342 return $page . $details;
2346 * Returns a regular expression of url protocols
2350 function wfUrlProtocols() {
2351 global $wgUrlProtocols;
2353 static $retval = null;
2354 if ( !is_null( $retval ) ) {
2358 // Support old-style $wgUrlProtocols strings, for backwards compatibility
2359 // with LocalSettings files from 1.5
2360 if ( is_array( $wgUrlProtocols ) ) {
2361 $protocols = array();
2362 foreach ( $wgUrlProtocols as $protocol ) {
2363 $protocols[] = preg_quote( $protocol, '/' );
2366 $retval = implode( '|', $protocols );
2368 $retval = $wgUrlProtocols;
2374 * Safety wrapper around ini_get() for boolean settings.
2375 * The values returned from ini_get() are pre-normalized for settings
2376 * set via php.ini or php_flag/php_admin_flag... but *not*
2377 * for those set via php_value/php_admin_value.
2379 * It's fairly common for people to use php_value instead of php_flag,
2380 * which can leave you with an 'off' setting giving a false positive
2381 * for code that just takes the ini_get() return value as a boolean.
2383 * To make things extra interesting, setting via php_value accepts
2384 * "true" and "yes" as true, but php.ini and php_flag consider them false. :)
2385 * Unrecognized values go false... again opposite PHP's own coercion
2386 * from string to bool.
2388 * Luckily, 'properly' set settings will always come back as '0' or '1',
2389 * so we only have to worry about them and the 'improper' settings.
2391 * I frickin' hate PHP... :P
2393 * @param $setting String
2396 function wfIniGetBool( $setting ) {
2397 $val = ini_get( $setting );
2398 // 'on' and 'true' can't have whitespace around them, but '1' can.
2399 return strtolower( $val ) == 'on'
2400 ||
strtolower( $val ) == 'true'
2401 ||
strtolower( $val ) == 'yes'
2402 ||
preg_match( "/^\s*[+-]?0*[1-9]/", $val ); // approx C atoi() function
2406 * Wrapper function for PHP's dl(). This doesn't work in most situations from
2407 * PHP 5.3 onward, and is usually disabled in shared environments anyway.
2409 * @param $extension String A PHP extension. The file suffix (.so or .dll)
2411 * @return Bool - Whether or not the extension is loaded
2413 function wfDl( $extension ) {
2414 if( extension_loaded( $extension ) ) {
2418 $canDl = ( function_exists( 'dl' ) && is_callable( 'dl' )
2419 && wfIniGetBool( 'enable_dl' ) && !wfIniGetBool( 'safe_mode' ) );
2422 wfSuppressWarnings();
2423 dl( $extension . '.' . PHP_SHLIB_SUFFIX
);
2424 wfRestoreWarnings();
2426 return extension_loaded( $extension );
2430 * Execute a shell command, with time and memory limits mirrored from the PHP
2431 * configuration if supported.
2432 * @param $cmd Command line, properly escaped for shell.
2433 * @param &$retval optional, will receive the program's exit code.
2434 * (non-zero is usually failure)
2435 * @return collected stdout as a string (trailing newlines stripped)
2437 function wfShellExec( $cmd, &$retval = null ) {
2438 global $IP, $wgMaxShellMemory, $wgMaxShellFileSize, $wgMaxShellTime;
2441 if ( is_null( $disabled ) ) {
2443 if( wfIniGetBool( 'safe_mode' ) ) {
2444 wfDebug( "wfShellExec can't run in safe_mode, PHP's exec functions are too broken.\n" );
2447 $functions = explode( ',', ini_get( 'disable_functions' ) );
2448 $functions = array_map( 'trim', $functions );
2449 $functions = array_map( 'strtolower', $functions );
2450 if ( in_array( 'passthru', $functions ) ) {
2451 wfDebug( "passthru is in disabled_functions\n" );
2457 return 'Unable to run external programs in safe mode.';
2460 wfInitShellLocale();
2462 if ( php_uname( 's' ) == 'Linux' ) {
2463 $time = intval( $wgMaxShellTime );
2464 $mem = intval( $wgMaxShellMemory );
2465 $filesize = intval( $wgMaxShellFileSize );
2467 if ( $time > 0 && $mem > 0 ) {
2468 $script = "$IP/bin/ulimit4.sh";
2469 if ( is_executable( $script ) ) {
2470 $cmd = '/bin/bash ' . escapeshellarg( $script ) . " $time $mem $filesize " . escapeshellarg( $cmd );
2473 } elseif ( php_uname( 's' ) == 'Windows NT' &&
2474 version_compare( PHP_VERSION
, '5.3.0', '<' ) )
2476 # This is a hack to work around PHP's flawed invocation of cmd.exe
2477 # http://news.php.net/php.internals/21796
2478 # Which is fixed in 5.3.0 :)
2479 $cmd = '"' . $cmd . '"';
2481 wfDebug( "wfShellExec: $cmd\n" );
2483 $retval = 1; // error by default?
2485 passthru( $cmd, $retval );
2486 $output = ob_get_contents();
2489 if ( $retval == 127 ) {
2490 wfDebugLog( 'exec', "Possibly missing executable file: $cmd\n" );
2496 * Workaround for http://bugs.php.net/bug.php?id=45132
2497 * escapeshellarg() destroys non-ASCII characters if LANG is not a UTF-8 locale
2499 function wfInitShellLocale() {
2500 static $done = false;
2505 global $wgShellLocale;
2506 if ( !wfIniGetBool( 'safe_mode' ) ) {
2507 putenv( "LC_CTYPE=$wgShellLocale" );
2508 setlocale( LC_CTYPE
, $wgShellLocale );
2513 * This function works like "use VERSION" in Perl, the program will die with a
2514 * backtrace if the current version of PHP is less than the version provided
2516 * This is useful for extensions which due to their nature are not kept in sync
2517 * with releases, and might depend on other versions of PHP than the main code
2519 * Note: PHP might die due to parsing errors in some cases before it ever
2520 * manages to call this function, such is life
2522 * @see perldoc -f use
2524 * @param $req_ver Mixed: the version to check, can be a string, an integer, or
2527 function wfUsePHP( $req_ver ) {
2528 $php_ver = PHP_VERSION
;
2530 if ( version_compare( $php_ver, (string)$req_ver, '<' ) ) {
2531 throw new MWException( "PHP $req_ver required--this is only $php_ver" );
2536 * This function works like "use VERSION" in Perl except it checks the version
2537 * of MediaWiki, the program will die with a backtrace if the current version
2538 * of MediaWiki is less than the version provided.
2540 * This is useful for extensions which due to their nature are not kept in sync
2543 * @see perldoc -f use
2545 * @param $req_ver Mixed: the version to check, can be a string, an integer, or
2548 function wfUseMW( $req_ver ) {
2551 if ( version_compare( $wgVersion, (string)$req_ver, '<' ) ) {
2552 throw new MWException( "MediaWiki $req_ver required--this is only $wgVersion" );
2557 * Return the final portion of a pathname.
2558 * Reimplemented because PHP5's basename() is buggy with multibyte text.
2559 * http://bugs.php.net/bug.php?id=33898
2561 * PHP's basename() only considers '\' a pathchar on Windows and Netware.
2562 * We'll consider it so always, as we don't want \s in our Unix paths either.
2564 * @param $path String
2565 * @param $suffix String: to remove if present
2568 function wfBaseName( $path, $suffix = '' ) {
2569 $encSuffix = ( $suffix == '' )
2571 : ( '(?:' . preg_quote( $suffix, '#' ) . ')?' );
2573 if( preg_match( "#([^/\\\\]*?){$encSuffix}[/\\\\]*$#", $path, $matches ) ) {
2581 * Generate a relative path name to the given file.
2582 * May explode on non-matching case-insensitive paths,
2583 * funky symlinks, etc.
2585 * @param $path String: absolute destination path including target filename
2586 * @param $from String: Absolute source path, directory only
2589 function wfRelativePath( $path, $from ) {
2590 // Normalize mixed input on Windows...
2591 $path = str_replace( '/', DIRECTORY_SEPARATOR
, $path );
2592 $from = str_replace( '/', DIRECTORY_SEPARATOR
, $from );
2594 // Trim trailing slashes -- fix for drive root
2595 $path = rtrim( $path, DIRECTORY_SEPARATOR
);
2596 $from = rtrim( $from, DIRECTORY_SEPARATOR
);
2598 $pieces = explode( DIRECTORY_SEPARATOR
, dirname( $path ) );
2599 $against = explode( DIRECTORY_SEPARATOR
, $from );
2601 if( $pieces[0] !== $against[0] ) {
2602 // Non-matching Windows drive letters?
2603 // Return a full path.
2607 // Trim off common prefix
2608 while( count( $pieces ) && count( $against )
2609 && $pieces[0] == $against[0] ) {
2610 array_shift( $pieces );
2611 array_shift( $against );
2614 // relative dots to bump us to the parent
2615 while( count( $against ) ) {
2616 array_unshift( $pieces, '..' );
2617 array_shift( $against );
2620 array_push( $pieces, wfBaseName( $path ) );
2622 return implode( DIRECTORY_SEPARATOR
, $pieces );
2626 * Backwards array plus for people who haven't bothered to read the PHP manual
2627 * XXX: will not darn your socks for you.
2629 * @param $array1 Array
2630 * @param [$array2, [...]] Arrays
2633 function wfArrayMerge( $array1/* ... */ ) {
2634 $args = func_get_args();
2635 $args = array_reverse( $args, true );
2637 foreach ( $args as $arg ) {
2644 * Merge arrays in the style of getUserPermissionsErrors, with duplicate removal
2646 * wfMergeErrorArrays(
2647 * array( array( 'x' ) ),
2648 * array( array( 'x', '2' ) ),
2649 * array( array( 'x' ) ),
2650 * array( array( 'y') )
2654 * array( 'x', '2' ),
2659 function wfMergeErrorArrays( /*...*/ ) {
2660 $args = func_get_args();
2662 foreach ( $args as $errors ) {
2663 foreach ( $errors as $params ) {
2664 # FIXME: sometimes get nested arrays for $params,
2665 # which leads to E_NOTICEs
2666 $spec = implode( "\t", $params );
2667 $out[$spec] = $params;
2670 return array_values( $out );
2674 * parse_url() work-alike, but non-broken. Differences:
2676 * 1) Does not raise warnings on bad URLs (just returns false)
2677 * 2) Handles protocols that don't use :// (e.g., mailto: and news:) correctly
2678 * 3) Adds a "delimiter" element to the array, either '://' or ':' (see (2))
2680 * @param $url String: a URL to parse
2681 * @return Array: bits of the URL in an associative array, per PHP docs
2683 function wfParseUrl( $url ) {
2684 global $wgUrlProtocols; // Allow all protocols defined in DefaultSettings/LocalSettings.php
2685 wfSuppressWarnings();
2686 $bits = parse_url( $url );
2687 wfRestoreWarnings();
2692 // most of the protocols are followed by ://, but mailto: and sometimes news: not, check for it
2693 if ( in_array( $bits['scheme'] . '://', $wgUrlProtocols ) ) {
2694 $bits['delimiter'] = '://';
2695 } elseif ( in_array( $bits['scheme'] . ':', $wgUrlProtocols ) ) {
2696 $bits['delimiter'] = ':';
2697 // parse_url detects for news: and mailto: the host part of an url as path
2698 // We have to correct this wrong detection
2699 if ( isset( $bits['path'] ) ) {
2700 $bits['host'] = $bits['path'];
2711 * Make a URL index, appropriate for the el_index field of externallinks.
2713 function wfMakeUrlIndex( $url ) {
2714 $bits = wfParseUrl( $url );
2716 // Reverse the labels in the hostname, convert to lower case
2717 // For emails reverse domainpart only
2718 if ( $bits['scheme'] == 'mailto' ) {
2719 $mailparts = explode( '@', $bits['host'], 2 );
2720 if ( count( $mailparts ) === 2 ) {
2721 $domainpart = strtolower( implode( '.', array_reverse( explode( '.', $mailparts[1] ) ) ) );
2723 // No domain specified, don't mangle it
2726 $reversedHost = $domainpart . '@' . $mailparts[0];
2728 $reversedHost = strtolower( implode( '.', array_reverse( explode( '.', $bits['host'] ) ) ) );
2730 // Add an extra dot to the end
2731 // Why? Is it in wrong place in mailto links?
2732 if ( substr( $reversedHost, -1, 1 ) !== '.' ) {
2733 $reversedHost .= '.';
2735 // Reconstruct the pseudo-URL
2736 $prot = $bits['scheme'];
2737 $index = $prot . $bits['delimiter'] . $reversedHost;
2738 // Leave out user and password. Add the port, path, query and fragment
2739 if ( isset( $bits['port'] ) ) {
2740 $index .= ':' . $bits['port'];
2742 if ( isset( $bits['path'] ) ) {
2743 $index .= $bits['path'];
2747 if ( isset( $bits['query'] ) ) {
2748 $index .= '?' . $bits['query'];
2750 if ( isset( $bits['fragment'] ) ) {
2751 $index .= '#' . $bits['fragment'];
2757 * Do any deferred updates and clear the list
2758 * TODO: This could be in Wiki.php if that class made any sense at all
2760 function wfDoUpdates() {
2761 global $wgPostCommitUpdateList, $wgDeferredUpdateList;
2762 foreach ( $wgDeferredUpdateList as $update ) {
2763 $update->doUpdate();
2765 foreach ( $wgPostCommitUpdateList as $update ) {
2766 $update->doUpdate();
2768 $wgDeferredUpdateList = array();
2769 $wgPostCommitUpdateList = array();
2773 * Convert an arbitrarily-long digit string from one numeric base
2774 * to another, optionally zero-padding to a minimum column width.
2776 * Supports base 2 through 36; digit values 10-36 are represented
2777 * as lowercase letters a-z. Input is case-insensitive.
2779 * @param $input String: of digits
2780 * @param $sourceBase Integer: 2-36
2781 * @param $destBase Integer: 2-36
2782 * @param $pad Integer: 1 or greater
2783 * @param $lowercase Boolean
2784 * @return String or false on invalid input
2786 function wfBaseConvert( $input, $sourceBase, $destBase, $pad = 1, $lowercase = true ) {
2787 $input = strval( $input );
2788 if( $sourceBase < 2 ||
2793 $sourceBase != intval( $sourceBase ) ||
2794 $destBase != intval( $destBase ) ||
2795 $pad != intval( $pad ) ||
2796 !is_string( $input ) ||
2800 $digitChars = ( $lowercase ) ?
'0123456789abcdefghijklmnopqrstuvwxyz' : '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
2801 $inDigits = array();
2804 // Decode and validate input string
2805 $input = strtolower( $input );
2806 for( $i = 0; $i < strlen( $input ); $i++
) {
2807 $n = strpos( $digitChars, $input{$i} );
2808 if( $n === false ||
$n > $sourceBase ) {
2814 // Iterate over the input, modulo-ing out an output digit
2815 // at a time until input is gone.
2816 while( count( $inDigits ) ) {
2818 $workDigits = array();
2821 foreach( $inDigits as $digit ) {
2822 $work *= $sourceBase;
2825 if( $work < $destBase ) {
2826 // Gonna need to pull another digit.
2827 if( count( $workDigits ) ) {
2828 // Avoid zero-padding; this lets us find
2829 // the end of the input very easily when
2830 // length drops to zero.
2834 // Finally! Actual division!
2835 $workDigits[] = intval( $work / $destBase );
2837 // Isn't it annoying that most programming languages
2838 // don't have a single divide-and-remainder operator,
2839 // even though the CPU implements it that way?
2840 $work = $work %
$destBase;
2844 // All that division leaves us with a remainder,
2845 // which is conveniently our next output digit.
2846 $outChars .= $digitChars[$work];
2849 $inDigits = $workDigits;
2852 while( strlen( $outChars ) < $pad ) {
2856 return strrev( $outChars );
2860 * Create an object with a given name and an array of construct parameters
2861 * @param $name String
2862 * @param $p Array: parameters
2864 function wfCreateObject( $name, $p ) {
2865 $p = array_values( $p );
2866 switch ( count( $p ) ) {
2870 return new $name( $p[0] );
2872 return new $name( $p[0], $p[1] );
2874 return new $name( $p[0], $p[1], $p[2] );
2876 return new $name( $p[0], $p[1], $p[2], $p[3] );
2878 return new $name( $p[0], $p[1], $p[2], $p[3], $p[4] );
2880 return new $name( $p[0], $p[1], $p[2], $p[3], $p[4], $p[5] );
2882 throw new MWException( 'Too many arguments to construtor in wfCreateObject' );
2886 function wfHttpOnlySafe() {
2887 global $wgHttpOnlyBlacklist;
2888 if( !version_compare( '5.2', PHP_VERSION
, '<' ) ) {
2892 if( isset( $_SERVER['HTTP_USER_AGENT'] ) ) {
2893 foreach( $wgHttpOnlyBlacklist as $regex ) {
2894 if( preg_match( $regex, $_SERVER['HTTP_USER_AGENT'] ) ) {
2904 * Initialise php session
2906 function wfSetupSession() {
2907 global $wgSessionsInMemcached, $wgCookiePath, $wgCookieDomain,
2908 $wgCookieSecure, $wgCookieHttpOnly, $wgSessionHandler;
2909 if( $wgSessionsInMemcached ) {
2910 require_once( 'MemcachedSessions.php' );
2911 } elseif( $wgSessionHandler && $wgSessionHandler != ini_get( 'session.save_handler' ) ) {
2912 # Only set this if $wgSessionHandler isn't null and session.save_handler
2913 # hasn't already been set to the desired value (that causes errors)
2914 ini_set( 'session.save_handler', $wgSessionHandler );
2916 $httpOnlySafe = wfHttpOnlySafe();
2917 wfDebugLog( 'cookie',
2918 'session_set_cookie_params: "' . implode( '", "',
2924 $httpOnlySafe && $wgCookieHttpOnly ) ) . '"' );
2925 if( $httpOnlySafe && $wgCookieHttpOnly ) {
2926 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookieHttpOnly );
2928 // PHP 5.1 throws warnings if you pass the HttpOnly parameter for 5.2.
2929 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
2931 session_cache_limiter( 'private, must-revalidate' );
2932 wfSuppressWarnings();
2934 wfRestoreWarnings();
2938 * Get an object from the precompiled serialized directory
2940 * @return Mixed: the variable on success, false on failure
2942 function wfGetPrecompiledData( $name ) {
2945 $file = "$IP/serialized/$name";
2946 if ( file_exists( $file ) ) {
2947 $blob = file_get_contents( $file );
2949 return unserialize( $blob );
2955 function wfGetCaller( $level = 2 ) {
2956 $backtrace = wfDebugBacktrace();
2957 if ( isset( $backtrace[$level] ) ) {
2958 return wfFormatStackFrame( $backtrace[$level] );
2960 $caller = 'unknown';
2966 * Return a string consisting of callers in the stack. Useful sometimes
2967 * for profiling specific points.
2969 * @param $limit The maximum depth of the stack frame to return, or false for
2972 function wfGetAllCallers( $limit = 3 ) {
2973 $trace = array_reverse( wfDebugBacktrace() );
2974 if ( !$limit ||
$limit > count( $trace ) - 1 ) {
2975 $limit = count( $trace ) - 1;
2977 $trace = array_slice( $trace, -$limit - 1, $limit );
2978 return implode( '/', array_map( 'wfFormatStackFrame', $trace ) );
2982 * Return a string representation of frame
2984 function wfFormatStackFrame( $frame ) {
2985 return isset( $frame['class'] ) ?
2986 $frame['class'] . '::' . $frame['function'] :
2993 function wfMemcKey( /*... */ ) {
2994 $args = func_get_args();
2995 $key = wfWikiID() . ':' . implode( ':', $args );
2996 $key = str_replace( ' ', '_', $key );
3001 * Get a cache key for a foreign DB
3003 function wfForeignMemcKey( $db, $prefix /*, ... */ ) {
3004 $args = array_slice( func_get_args(), 2 );
3006 $key = "$db-$prefix:" . implode( ':', $args );
3008 $key = $db . ':' . implode( ':', $args );
3014 * Get an ASCII string identifying this wiki
3015 * This is used as a prefix in memcached keys
3017 function wfWikiID() {
3018 global $wgDBprefix, $wgDBname;
3019 if ( $wgDBprefix ) {
3020 return "$wgDBname-$wgDBprefix";
3027 * Split a wiki ID into DB name and table prefix
3029 function wfSplitWikiID( $wiki ) {
3030 $bits = explode( '-', $wiki, 2 );
3031 if ( count( $bits ) < 2 ) {
3038 * Get a Database object.
3039 * @param $db Integer: index of the connection to get. May be DB_MASTER for the
3040 * master (for write queries), DB_SLAVE for potentially lagged read
3041 * queries, or an integer >= 0 for a particular server.
3043 * @param $groups Mixed: query groups. An array of group names that this query
3044 * belongs to. May contain a single string if the query is only
3047 * @param $wiki String: the wiki ID, or false for the current wiki
3049 * Note: multiple calls to wfGetDB(DB_SLAVE) during the course of one request
3050 * will always return the same object, unless the underlying connection or load
3051 * balancer is manually destroyed.
3053 * @return DatabaseBase
3055 function &wfGetDB( $db, $groups = array(), $wiki = false ) {
3056 return wfGetLB( $wiki )->getConnection( $db, $groups, $wiki );
3060 * Get a load balancer object.
3062 * @param $wiki String: wiki ID, or false for the current wiki
3063 * @return LoadBalancer
3065 function wfGetLB( $wiki = false ) {
3066 return wfGetLBFactory()->getMainLB( $wiki );
3070 * Get the load balancer factory object
3072 function &wfGetLBFactory() {
3073 return LBFactory
::singleton();
3078 * Shortcut for RepoGroup::singleton()->findFile()
3079 * @param $title Either a string or Title object
3080 * @param $options Associative array of options:
3081 * time: requested time for an archived image, or false for the
3082 * current version. An image object will be returned which was
3083 * created at the specified time.
3085 * ignoreRedirect: If true, do not follow file redirects
3087 * private: If true, return restricted (deleted) files if the current
3088 * user is allowed to view them. Otherwise, such files will not
3091 * bypassCache: If true, do not use the process-local cache of File objects
3093 * @return File, or false if the file does not exist
3095 function wfFindFile( $title, $options = array() ) {
3096 return RepoGroup
::singleton()->findFile( $title, $options );
3100 * Get an object referring to a locally registered file.
3101 * Returns a valid placeholder object if the file does not exist.
3102 * @param $title Either a string or Title object
3103 * @return File, or null if passed an invalid Title
3105 function wfLocalFile( $title ) {
3106 return RepoGroup
::singleton()->getLocalRepo()->newFile( $title );
3110 * Should low-performance queries be disabled?
3114 function wfQueriesMustScale() {
3115 global $wgMiserMode;
3117 ||
( SiteStats
::pages() > 100000
3118 && SiteStats
::edits() > 1000000
3119 && SiteStats
::users() > 10000 );
3123 * Get the path to a specified script file, respecting file
3124 * extensions; this is a wrapper around $wgScriptExtension etc.
3126 * @param $script String: script filename, sans extension
3129 function wfScript( $script = 'index' ) {
3130 global $wgScriptPath, $wgScriptExtension;
3131 return "{$wgScriptPath}/{$script}{$wgScriptExtension}";
3135 * Get the script URL.
3137 * @return script URL
3139 function wfGetScriptUrl() {
3140 if( isset( $_SERVER['SCRIPT_NAME'] ) ) {
3142 # as it was called, minus the query string.
3144 # Some sites use Apache rewrite rules to handle subdomains,
3145 # and have PHP set up in a weird way that causes PHP_SELF
3146 # to contain the rewritten URL instead of the one that the
3147 # outside world sees.
3149 # If in this mode, use SCRIPT_URL instead, which mod_rewrite
3150 # provides containing the "before" URL.
3151 return $_SERVER['SCRIPT_NAME'];
3153 return $_SERVER['URL'];
3158 * Convenience function converts boolean values into "true"
3159 * or "false" (string) values
3161 * @param $value Boolean
3164 function wfBoolToStr( $value ) {
3165 return $value ?
'true' : 'false';
3169 * Load an extension messages file
3170 * @deprecated in 1.16 (warnings in 1.18, removed in ?)
3172 function wfLoadExtensionMessages( $extensionName, $langcode = false ) {
3176 * Get a platform-independent path to the null file, e.g.
3181 function wfGetNull() {
3182 return wfIsWindows()
3188 * Displays a maxlag error
3190 * @param $host String: server that lags the most
3191 * @param $lag Integer: maxlag (actual)
3192 * @param $maxLag Integer: maxlag (requested)
3194 function wfMaxlagError( $host, $lag, $maxLag ) {
3195 global $wgShowHostnames;
3196 header( 'HTTP/1.1 503 Service Unavailable' );
3197 header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
3198 header( 'X-Database-Lag: ' . intval( $lag ) );
3199 header( 'Content-Type: text/plain' );
3200 if( $wgShowHostnames ) {
3201 echo "Waiting for $host: $lag seconds lagged\n";
3203 echo "Waiting for a database server: $lag seconds lagged\n";
3208 * Throws a warning that $function is deprecated
3209 * @param $function String
3212 function wfDeprecated( $function ) {
3213 static $functionsWarned = array();
3214 if ( !isset( $functionsWarned[$function] ) ) {
3215 $functionsWarned[$function] = true;
3216 wfWarn( "Use of $function is deprecated.", 2 );
3221 * Send a warning either to the debug log or in a PHP error depending on
3222 * $wgDevelopmentWarnings
3224 * @param $msg String: message to send
3225 * @param $callerOffset Integer: number of itmes to go back in the backtrace to
3226 * find the correct caller (1 = function calling wfWarn, ...)
3227 * @param $level Integer: PHP error level; only used when $wgDevelopmentWarnings
3230 function wfWarn( $msg, $callerOffset = 1, $level = E_USER_NOTICE
) {
3231 $callers = wfDebugBacktrace();
3232 if( isset( $callers[$callerOffset +
1] ) ){
3233 $callerfunc = $callers[$callerOffset +
1];
3234 $callerfile = $callers[$callerOffset];
3235 if( isset( $callerfile['file'] ) && isset( $callerfile['line'] ) ) {
3236 $file = $callerfile['file'] . ' at line ' . $callerfile['line'];
3238 $file = '(internal function)';
3241 if( isset( $callerfunc['class'] ) ) {
3242 $func .= $callerfunc['class'] . '::';
3244 $func .= @$callerfunc['function'];
3245 $msg .= " [Called from $func in $file]";
3248 global $wgDevelopmentWarnings;
3249 if ( $wgDevelopmentWarnings ) {
3250 trigger_error( $msg, $level );
3252 wfDebug( "$msg\n" );
3257 * Sleep until the worst slave's replication lag is less than or equal to
3258 * $maxLag, in seconds. Use this when updating very large numbers of rows, as
3259 * in maintenance scripts, to avoid causing too much lag. Of course, this is
3260 * a no-op if there are no slaves.
3262 * Every time the function has to wait for a slave, it will print a message to
3263 * that effect (and then sleep for a little while), so it's probably not best
3264 * to use this outside maintenance scripts in its present form.
3266 * @param $maxLag Integer
3267 * @param $wiki mixed Wiki identifier accepted by wfGetLB
3270 function wfWaitForSlaves( $maxLag, $wiki = false ) {
3272 $lb = wfGetLB( $wiki );
3273 list( $host, $lag ) = $lb->getMaxLag( $wiki );
3274 while( $lag > $maxLag ) {
3275 $name = @gethostbyaddr
( $host );
3276 if( $name !== false ) {
3279 print "Waiting for $host (lagged $lag seconds)...\n";
3281 list( $host, $lag ) = $lb->getMaxLag();
3287 * Output some plain text in command-line mode or in the installer (updaters.inc).
3288 * Do not use it in any other context, its behaviour is subject to change.
3290 function wfOut( $s ) {
3291 global $wgCommandLineMode;
3292 if ( $wgCommandLineMode && !defined( 'MEDIAWIKI_INSTALL' ) ) {
3295 echo htmlspecialchars( $s );
3301 * Count down from $n to zero on the terminal, with a one-second pause
3302 * between showing each number. For use in command-line scripts.
3304 function wfCountDown( $n ) {
3305 for ( $i = $n; $i >= 0; $i-- ) {
3307 echo str_repeat( "\x08", strlen( $i +
1 ) );
3319 * Generate a random 32-character hexadecimal token.
3320 * @param $salt Mixed: some sort of salt, if necessary, to add to random
3321 * characters before hashing.
3323 function wfGenerateToken( $salt = '' ) {
3324 $salt = serialize( $salt );
3326 return md5( mt_rand( 0, 0x7fffffff ) . $salt );
3330 * Replace all invalid characters with -
3331 * @param $name Mixed: filename to process
3333 function wfStripIllegalFilenameChars( $name ) {
3334 global $wgIllegalFileChars;
3335 $name = wfBaseName( $name );
3336 $name = preg_replace(
3337 "/[^" . Title
::legalChars() . "]" .
3338 ( $wgIllegalFileChars ?
"|[" . $wgIllegalFileChars . "]" : '' ) .
3347 * Insert array into another array after the specified *KEY*
3348 * @param $array Array: The array.
3349 * @param $insert Array: The array to insert.
3350 * @param $after Mixed: The key to insert after
3352 function wfArrayInsertAfter( $array, $insert, $after ) {
3353 // Find the offset of the element to insert after.
3354 $keys = array_keys( $array );
3355 $offsetByKey = array_flip( $keys );
3357 $offset = $offsetByKey[$after];
3359 // Insert at the specified offset
3360 $before = array_slice( $array, 0, $offset +
1, true );
3361 $after = array_slice( $array, $offset +
1, count( $array ) - $offset, true );
3363 $output = $before +
$insert +
$after;
3368 /* Recursively converts the parameter (an object) to an array with the same data */
3369 function wfObjectToArray( $object, $recursive = true ) {
3371 foreach ( get_object_vars( $object ) as $key => $value ) {
3372 if ( is_object( $value ) && $recursive ) {
3373 $value = wfObjectToArray( $value );
3376 $array[$key] = $value;
3383 * Set PHP's memory limit to the larger of php.ini or $wgMemoryLimit;
3384 * @return Integer value memory was set to.
3386 function wfMemoryLimit() {
3387 global $wgMemoryLimit;
3388 $memlimit = wfShorthandToInteger( ini_get( 'memory_limit' ) );
3389 $conflimit = wfShorthandToInteger( $wgMemoryLimit );
3390 if( $memlimit != -1 ) {
3391 if( $conflimit == -1 ) {
3392 wfDebug( "Removing PHP's memory limit\n" );
3393 wfSuppressWarnings();
3394 ini_set( 'memory_limit', $conflimit );
3395 wfRestoreWarnings();
3397 } elseif ( $conflimit > $memlimit ) {
3398 wfDebug( "Raising PHP's memory limit to $conflimit bytes\n" );
3399 wfSuppressWarnings();
3400 ini_set( 'memory_limit', $conflimit );
3401 wfRestoreWarnings();
3409 * Converts shorthand byte notation to integer form
3410 * @param $string String
3413 function wfShorthandToInteger( $string = '' ) {
3414 $string = trim( $string );
3415 if( empty( $string ) ) {
3418 $last = strtolower( $string[strlen( $string ) - 1] );
3419 $val = intval( $string );
3433 * Get the normalised IETF language tag
3434 * @param $code String: The language code.
3435 * @return $langCode String: The language code which complying with BCP 47 standards.
3437 function wfBCP47( $code ) {
3438 $codeSegment = explode( '-', $code );
3439 foreach ( $codeSegment as $segNo => $seg ) {
3440 if ( count( $codeSegment ) > 0 ) {
3441 // ISO 3166 country code
3442 if ( ( strlen( $seg ) == 2 ) && ( $segNo > 0 ) ) {
3443 $codeBCP[$segNo] = strtoupper( $seg );
3444 // ISO 15924 script code
3445 } elseif ( ( strlen( $seg ) == 4 ) && ( $segNo > 0 ) ) {
3446 $codeBCP[$segNo] = ucfirst( $seg );
3447 // Use lowercase for other cases
3449 $codeBCP[$segNo] = strtolower( $seg );
3452 // Use lowercase for single segment
3453 $codeBCP[$segNo] = strtolower( $seg );
3456 $langCode = implode( '-', $codeBCP );
3460 function wfArrayMap( $function, $input ) {
3461 $ret = array_map( $function, $input );
3462 foreach ( $ret as $key => $value ) {
3463 $taint = istainted( $input[$key] );
3465 taint( $ret[$key], $taint );
3472 * Returns the PackageRepository object for interaction with the package repository.
3474 * TODO: Make the repository type also configurable.
3478 * @return PackageRepository
3480 function wfGetRepository() {
3481 global $wgRepositoryApiLocation;
3482 static $repository = false;
3484 if ( $repository === false ) {
3485 $repository = new DistributionRepository( $wgRepositoryApiLocation );