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 // Hide compatibility functions from Doxygen
15 * Compatibility functions
17 * We support PHP 5.2.3 and up.
18 * Re-implementations of newer functions or functions in non-standard
19 * PHP extensions may be included here.
22 if( !function_exists( 'iconv' ) ) {
23 /** @codeCoverageIgnore */
24 function iconv( $from, $to, $string ) {
25 return Fallback
::iconv( $from, $to, $string );
29 if ( !function_exists( 'mb_substr' ) ) {
30 /** @codeCoverageIgnore */
31 function mb_substr( $str, $start, $count='end' ) {
32 return Fallback
::mb_substr( $str, $start, $count );
35 /** @codeCoverageIgnore */
36 function mb_substr_split_unicode( $str, $splitPos ) {
37 return Fallback
::mb_substr_split_unicode( $str, $splitPos );
41 if ( !function_exists( 'mb_strlen' ) ) {
42 /** @codeCoverageIgnore */
43 function mb_strlen( $str, $enc = '' ) {
44 return Fallback
::mb_strlen( $str, $enc );
48 if( !function_exists( 'mb_strpos' ) ) {
49 /** @codeCoverageIgnore */
50 function mb_strpos( $haystack, $needle, $offset = 0, $encoding = '' ) {
51 return Fallback
::mb_strpos( $haystack, $needle, $offset, $encoding );
56 if( !function_exists( 'mb_strrpos' ) ) {
57 /** @codeCoverageIgnore */
58 function mb_strrpos( $haystack, $needle, $offset = 0, $encoding = '' ) {
59 return Fallback
::mb_strrpos( $haystack, $needle, $offset, $encoding );
64 // Support for Wietse Venema's taint feature
65 if ( !function_exists( 'istainted' ) ) {
66 /** @codeCoverageIgnore */
67 function istainted( $var ) {
70 /** @codeCoverageIgnore */
71 function taint( $var, $level = 0 ) {}
72 /** @codeCoverageIgnore */
73 function untaint( $var, $level = 0 ) {}
74 define( 'TC_HTML', 1 );
75 define( 'TC_SHELL', 1 );
76 define( 'TC_MYSQL', 1 );
77 define( 'TC_PCRE', 1 );
78 define( 'TC_SELF', 1 );
83 * Like array_diff( $a, $b ) except that it works with two-dimensional arrays.
85 function wfArrayDiff2( $a, $b ) {
86 return array_udiff( $a, $b, 'wfArrayDiff2_cmp' );
88 function wfArrayDiff2_cmp( $a, $b ) {
89 if ( !is_array( $a ) ) {
90 return strcmp( $a, $b );
91 } elseif ( count( $a ) !== count( $b ) ) {
92 return count( $a ) < count( $b ) ?
-1 : 1;
96 while( ( list( , $valueA ) = each( $a ) ) && ( list( , $valueB ) = each( $b ) ) ) {
97 $cmp = strcmp( $valueA, $valueB );
107 * Get a random decimal value between 0 and 1, in a way
108 * not likely to give duplicate values for any realistic
109 * number of articles.
113 function wfRandom() {
114 # The maximum random value is "only" 2^31-1, so get two random
115 # values to reduce the chance of dupes
116 $max = mt_getrandmax() +
1;
117 $rand = number_format( ( mt_rand() * $max +
mt_rand() )
118 / $max / $max, 12, '.', '' );
123 * We want some things to be included as literal characters in our title URLs
124 * for prettiness, which urlencode encodes by default. According to RFC 1738,
125 * all of the following should be safe:
129 * But + is not safe because it's used to indicate a space; &= are only safe in
130 * paths and not in queries (and we don't distinguish here); ' seems kind of
131 * scary; and urlencode() doesn't touch -_. to begin with. Plus, although /
132 * is reserved, we don't care. So the list we unescape is:
136 * However, IIS7 redirects fail when the url contains a colon (Bug 22709),
137 * so no fancy : for IIS7.
139 * %2F in the page titles seems to fatally break for some reason.
144 function wfUrlencode( $s ) {
146 if ( is_null( $needle ) ) {
147 $needle = array( '%3B', '%40', '%24', '%21', '%2A', '%28', '%29', '%2C', '%2F' );
148 if ( !isset( $_SERVER['SERVER_SOFTWARE'] ) ||
( strpos( $_SERVER['SERVER_SOFTWARE'], 'Microsoft-IIS/7' ) === false ) ) {
153 $s = urlencode( $s );
156 array( ';', '@', '$', '!', '*', '(', ')', ',', '/', ':' ),
164 * Sends a line to the debug log if enabled or, optionally, to a comment in output.
165 * In normal operation this is a NOP.
167 * Controlling globals:
168 * $wgDebugLogFile - points to the log file
169 * $wgProfileOnly - if set, normal debug messages will not be recorded.
170 * $wgDebugRawPage - if false, 'action=raw' hits will not result in debug output.
171 * $wgDebugComments - if on, some debug items may appear in comments in the HTML output.
173 * @param $text String
174 * @param $logonly Bool: set true to avoid appearing in HTML when $wgDebugComments is set
176 function wfDebug( $text, $logonly = false ) {
177 global $wgOut, $wgDebugLogFile, $wgDebugComments, $wgProfileOnly, $wgDebugRawPage;
178 global $wgDebugLogPrefix, $wgShowDebug;
180 static $cache = array(); // Cache of unoutputted messages
181 $text = wfDebugTimer() . $text;
183 # Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
184 if ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' && !$wgDebugRawPage ) {
188 if ( ( $wgDebugComments ||
$wgShowDebug ) && !$logonly ) {
191 if ( isset( $wgOut ) && is_object( $wgOut ) ) {
192 // add the message and any cached messages to the output
193 array_map( array( $wgOut, 'debug' ), $cache );
197 if ( $wgDebugLogFile != '' && !$wgProfileOnly ) {
198 # Strip unprintables; they can switch terminal modes when binary data
199 # gets dumped, which is pretty annoying.
200 $text = preg_replace( '![\x00-\x08\x0b\x0c\x0e-\x1f]!', ' ', $text );
201 $text = $wgDebugLogPrefix . $text;
202 wfErrorLog( $text, $wgDebugLogFile );
207 * Get microsecond timestamps for debug logs
211 function wfDebugTimer() {
212 global $wgDebugTimestamps;
213 if ( !$wgDebugTimestamps ) {
216 static $start = null;
218 if ( $start === null ) {
219 $start = microtime( true );
220 $prefix = "\n$start";
222 $prefix = sprintf( "%6.4f", microtime( true ) - $start );
225 return $prefix . ' ';
229 * Send a line giving PHP memory usage.
231 * @param $exact Bool: print exact values instead of kilobytes (default: false)
233 function wfDebugMem( $exact = false ) {
234 $mem = memory_get_usage();
236 $mem = floor( $mem / 1024 ) . ' kilobytes';
240 wfDebug( "Memory usage: $mem\n" );
244 * Send a line to a supplementary debug log file, if configured, or main debug log if not.
245 * $wgDebugLogGroups[$logGroup] should be set to a filename to send to a separate log.
247 * @param $logGroup String
248 * @param $text String
249 * @param $public Bool: whether to log the event in the public log if no private
250 * log file is specified, (default true)
252 function wfDebugLog( $logGroup, $text, $public = true ) {
253 global $wgDebugLogGroups, $wgShowHostnames;
254 $text = trim( $text ) . "\n";
255 if( isset( $wgDebugLogGroups[$logGroup] ) ) {
256 $time = wfTimestamp( TS_DB
);
258 if ( $wgShowHostnames ) {
259 $host = wfHostname();
263 wfErrorLog( "$time $host $wiki: $text", $wgDebugLogGroups[$logGroup] );
264 } elseif ( $public === true ) {
265 wfDebug( $text, true );
270 * Log for database errors
272 * @param $text String: database error message.
274 function wfLogDBError( $text ) {
275 global $wgDBerrorLog, $wgDBname;
276 if ( $wgDBerrorLog ) {
277 $host = trim(`hostname`
);
278 $text = date( 'D M j G:i:s T Y' ) . "\t$host\t$wgDBname\t$text";
279 wfErrorLog( $text, $wgDBerrorLog );
284 * Log to a file without getting "file size exceeded" signals.
286 * Can also log to TCP or UDP with the syntax udp://host:port/prefix. This will
287 * send lines to the specified port, prefixed by the specified prefix and a space.
289 * @param $text String
290 * @param $file String filename
292 function wfErrorLog( $text, $file ) {
293 if ( substr( $file, 0, 4 ) == 'udp:' ) {
294 # Needs the sockets extension
295 if ( preg_match( '!^(tcp|udp):(?://)?\[([0-9a-fA-F:]+)\]:(\d+)(?:/(.*))?$!', $file, $m ) ) {
296 // IPv6 bracketed host
298 $port = intval( $m[3] );
299 $prefix = isset( $m[4] ) ?
$m[4] : false;
301 } elseif ( preg_match( '!^(tcp|udp):(?://)?([a-zA-Z0-9.-]+):(\d+)(?:/(.*))?$!', $file, $m ) ) {
303 if ( !IP
::isIPv4( $host ) ) {
304 $host = gethostbyname( $host );
306 $port = intval( $m[3] );
307 $prefix = isset( $m[4] ) ?
$m[4] : false;
310 throw new MWException( __METHOD__
. ': Invalid UDP specification' );
313 // Clean it up for the multiplexer
314 if ( strval( $prefix ) !== '' ) {
315 $text = preg_replace( '/^/m', $prefix . ' ', $text );
318 if ( strlen( $text ) > 65534 ) {
319 $text = substr( $text, 0, 65534 );
322 if ( substr( $text, -1 ) != "\n" ) {
325 } elseif ( strlen( $text ) > 65535 ) {
326 $text = substr( $text, 0, 65535 );
329 $sock = socket_create( $domain, SOCK_DGRAM
, SOL_UDP
);
333 socket_sendto( $sock, $text, strlen( $text ), 0, $host, $port );
334 socket_close( $sock );
336 wfSuppressWarnings();
337 $exists = file_exists( $file );
338 $size = $exists ?
filesize( $file ) : false;
339 if ( !$exists ||
( $size !== false && $size +
strlen( $text ) < 0x7fffffff ) ) {
340 file_put_contents( $file, $text, FILE_APPEND
);
349 function wfLogProfilingData() {
350 global $wgRequestTime, $wgDebugLogFile, $wgDebugRawPage, $wgRequest;
351 global $wgProfileLimit, $wgUser;
353 $profiler = Profiler
::instance();
355 # Profiling must actually be enabled...
356 if ( $profiler->isStub() ) {
360 // Get total page request time and only show pages that longer than
361 // $wgProfileLimit time (default is 0)
363 $elapsed = $now - $wgRequestTime;
364 if ( $elapsed <= $wgProfileLimit ) {
368 $profiler->logData();
370 // Check whether this should be logged in the debug file.
371 if ( $wgDebugLogFile == '' ||
( $wgRequest->getVal( 'action' ) == 'raw' && !$wgDebugRawPage ) ) {
376 if ( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) {
377 $forward = ' forwarded for ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
379 if ( !empty( $_SERVER['HTTP_CLIENT_IP'] ) ) {
380 $forward .= ' client IP ' . $_SERVER['HTTP_CLIENT_IP'];
382 if ( !empty( $_SERVER['HTTP_FROM'] ) ) {
383 $forward .= ' from ' . $_SERVER['HTTP_FROM'];
386 $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
388 // Don't load $wgUser at this late stage just for statistics purposes
389 // @todo FIXME: We can detect some anons even if it is not loaded. See User::getId()
390 if ( $wgUser->isItemLoaded( 'id' ) && $wgUser->isAnon() ) {
393 $log = sprintf( "%s\t%04.3f\t%s\n",
394 gmdate( 'YmdHis' ), $elapsed,
395 urldecode( $wgRequest->getRequestURL() . $forward ) );
397 wfErrorLog( $log . $profiler->getOutput(), $wgDebugLogFile );
401 * Check if the wiki read-only lock file is present. This can be used to lock
402 * off editing functions, but doesn't guarantee that the database will not be
407 function wfReadOnly() {
408 global $wgReadOnlyFile, $wgReadOnly;
410 if ( !is_null( $wgReadOnly ) ) {
411 return (bool)$wgReadOnly;
413 if ( $wgReadOnlyFile == '' ) {
416 // Set $wgReadOnly for faster access next time
417 if ( is_file( $wgReadOnlyFile ) ) {
418 $wgReadOnly = file_get_contents( $wgReadOnlyFile );
422 return (bool)$wgReadOnly;
425 function wfReadOnlyReason() {
432 * Return a Language object from $langcode
434 * @param $langcode Mixed: either:
435 * - a Language object
436 * - code of the language to get the message for, if it is
437 * a valid code create a language for that language, if
438 * it is a string but not a valid code then make a basic
440 * - a boolean: if it's false then use the current users
441 * language (as a fallback for the old parameter
442 * functionality), or if it is true then use the wikis
443 * @return Language object
445 function wfGetLangObj( $langcode = false ) {
446 # Identify which language to get or create a language object for.
447 # Using is_object here due to Stub objects.
448 if( is_object( $langcode ) ) {
449 # Great, we already have the object (hopefully)!
453 global $wgContLang, $wgLanguageCode;
454 if( $langcode === true ||
$langcode === $wgLanguageCode ) {
455 # $langcode is the language code of the wikis content language object.
456 # or it is a boolean and value is true
461 if( $langcode === false ||
$langcode === $wgLang->getCode() ) {
462 # $langcode is the language code of user language object.
463 # or it was a boolean and value is false
467 $validCodes = array_keys( Language
::getLanguageNames() );
468 if( in_array( $langcode, $validCodes ) ) {
469 # $langcode corresponds to a valid language.
470 return Language
::factory( $langcode );
473 # $langcode is a string, but not a valid language code; use content language.
474 wfDebug( "Invalid language code passed to wfGetLangObj, falling back to content language.\n" );
479 * Use this instead of $wgContLang, when working with user interface.
480 * User interface is currently hard coded according to wiki content language
481 * in many ways, especially regarding to text direction. There is lots stuff
482 * to fix, hence this function to keep the old behaviour unless the global
483 * $wgBetterDirectionality is enabled (or removed when everything works).
487 function wfUILang() {
488 global $wgBetterDirectionality;
489 return wfGetLangObj( !$wgBetterDirectionality );
493 * This is the new function for getting translated interface messages.
494 * See the Message class for documentation how to use them.
495 * The intention is that this function replaces all old wfMsg* functions.
496 * @param $key \string Message key.
497 * Varargs: normal message parameters.
501 function wfMessage( $key /*...*/) {
502 $params = func_get_args();
503 array_shift( $params );
504 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
505 $params = $params[0];
507 return new Message( $key, $params );
511 * This function accepts multiple message keys and returns a message instance
512 * for the first message which is non-empty. If all messages are empty then an
513 * instance of the first message key is returned.
514 * @param varargs: message keys
518 function wfMessageFallback( /*...*/ ) {
519 $args = func_get_args();
520 return MWFunction
::callArray( 'Message::newFallbackSequence', $args );
524 * Get a message from anywhere, for the current user language.
526 * Use wfMsgForContent() instead if the message should NOT
527 * change depending on the user preferences.
529 * @param $key String: lookup key for the message, usually
530 * defined in languages/Language.php
532 * This function also takes extra optional parameters (not
533 * shown in the function definition), which can be used to
534 * insert variable text into the predefined message.
537 function wfMsg( $key ) {
538 $args = func_get_args();
539 array_shift( $args );
540 return wfMsgReal( $key, $args, true );
544 * Same as above except doesn't transform the message
549 function wfMsgNoTrans( $key ) {
550 $args = func_get_args();
551 array_shift( $args );
552 return wfMsgReal( $key, $args, true, false, false );
556 * Get a message from anywhere, for the current global language
557 * set with $wgLanguageCode.
559 * Use this if the message should NOT change dependent on the
560 * language set in the user's preferences. This is the case for
561 * most text written into logs, as well as link targets (such as
562 * the name of the copyright policy page). Link titles, on the
563 * other hand, should be shown in the UI language.
565 * Note that MediaWiki allows users to change the user interface
566 * language in their preferences, but a single installation
567 * typically only contains content in one language.
569 * Be wary of this distinction: If you use wfMsg() where you should
570 * use wfMsgForContent(), a user of the software may have to
571 * customize potentially hundreds of messages in
572 * order to, e.g., fix a link in every possible language.
574 * @param $key String: lookup key for the message, usually
575 * defined in languages/Language.php
578 function wfMsgForContent( $key ) {
579 global $wgForceUIMsgAsContentMsg;
580 $args = func_get_args();
581 array_shift( $args );
583 if( is_array( $wgForceUIMsgAsContentMsg ) &&
584 in_array( $key, $wgForceUIMsgAsContentMsg ) )
588 return wfMsgReal( $key, $args, true, $forcontent );
592 * Same as above except doesn't transform the message
597 function wfMsgForContentNoTrans( $key ) {
598 global $wgForceUIMsgAsContentMsg;
599 $args = func_get_args();
600 array_shift( $args );
602 if( is_array( $wgForceUIMsgAsContentMsg ) &&
603 in_array( $key, $wgForceUIMsgAsContentMsg ) )
607 return wfMsgReal( $key, $args, true, $forcontent, false );
611 * Get a message from the language file, for the UI elements
613 * @deprecated since 1.18; use wfMessage()
615 function wfMsgNoDB( $key ) {
616 wfDeprecated( __FUNCTION__
);
617 $args = func_get_args();
618 array_shift( $args );
619 return wfMsgReal( $key, $args, false );
623 * Get a message from the language file, for the content
625 * @deprecated since 1.18; use wfMessage()
627 function wfMsgNoDBForContent( $key ) {
628 wfDeprecated( __FUNCTION__
);
629 global $wgForceUIMsgAsContentMsg;
630 $args = func_get_args();
631 array_shift( $args );
633 if( is_array( $wgForceUIMsgAsContentMsg ) &&
634 in_array( $key, $wgForceUIMsgAsContentMsg ) )
638 return wfMsgReal( $key, $args, false, $forcontent );
643 * Really get a message
645 * @param $key String: key to get.
647 * @param $useDB Boolean
648 * @param $forContent Mixed: Language code, or false for user lang, true for content lang.
649 * @param $transform Boolean: Whether or not to transform the message.
650 * @return String: the requested message.
652 function wfMsgReal( $key, $args, $useDB = true, $forContent = false, $transform = true ) {
653 wfProfileIn( __METHOD__
);
654 $message = wfMsgGetKey( $key, $useDB, $forContent, $transform );
655 $message = wfMsgReplaceArgs( $message, $args );
656 wfProfileOut( __METHOD__
);
661 * This function provides the message source for messages to be edited which are *not* stored in the database.
663 * @deprecated since 1.18; use wfMessage()
666 function wfMsgWeirdKey( $key ) {
667 wfDeprecated( __FUNCTION__
);
668 $source = wfMsgGetKey( $key, false, true, false );
669 if ( wfEmptyMsg( $key ) ) {
677 * Fetch a message string value, but don't replace any keys yet.
681 * @param $langCode String: Code of the language to get the message for, or
682 * behaves as a content language switch if it is a boolean.
683 * @param $transform Boolean: whether to parse magic words, etc.
686 function wfMsgGetKey( $key, $useDB, $langCode = false, $transform = true ) {
687 wfRunHooks( 'NormalizeMessageKey', array( &$key, &$useDB, &$langCode, &$transform ) );
689 $cache = MessageCache
::singleton();
690 $message = $cache->get( $key, $useDB, $langCode );
691 if( $message === false ) {
692 $message = '<' . htmlspecialchars( $key ) . '>';
693 } elseif ( $transform ) {
694 $message = $cache->transform( $message );
700 * Replace message parameter keys on the given formatted output.
702 * @param $message String
707 function wfMsgReplaceArgs( $message, $args ) {
708 # Fix windows line-endings
709 # Some messages are split with explode("\n", $msg)
710 $message = str_replace( "\r", '', $message );
713 if ( count( $args ) ) {
714 if ( is_array( $args[0] ) ) {
715 $args = array_values( $args[0] );
717 $replacementKeys = array();
718 foreach( $args as $n => $param ) {
719 $replacementKeys['$' . ( $n +
1 )] = $param;
721 $message = strtr( $message, $replacementKeys );
728 * Return an HTML-escaped version of a message.
729 * Parameter replacements, if any, are done *after* the HTML-escaping,
730 * so parameters may contain HTML (eg links or form controls). Be sure
731 * to pre-escape them if you really do want plaintext, or just wrap
732 * the whole thing in htmlspecialchars().
735 * @param string ... parameters
738 function wfMsgHtml( $key ) {
739 $args = func_get_args();
740 array_shift( $args );
741 return wfMsgReplaceArgs( htmlspecialchars( wfMsgGetKey( $key, true ) ), $args );
745 * Return an HTML version of message
746 * Parameter replacements, if any, are done *after* parsing the wiki-text message,
747 * so parameters may contain HTML (eg links or form controls). Be sure
748 * to pre-escape them if you really do want plaintext, or just wrap
749 * the whole thing in htmlspecialchars().
752 * @param string ... parameters
755 function wfMsgWikiHtml( $key ) {
756 $args = func_get_args();
757 array_shift( $args );
758 return wfMsgReplaceArgs(
759 MessageCache
::singleton()->parse( wfMsgGetKey( $key, true ), null, /* can't be set to false */ true )->getText(),
764 * Returns message in the requested format
765 * @param $key String: key of the message
766 * @param $options Array: processing rules. Can take the following options:
767 * <i>parse</i>: parses wikitext to HTML
768 * <i>parseinline</i>: parses wikitext to HTML and removes the surrounding
769 * p's added by parser or tidy
770 * <i>escape</i>: filters message through htmlspecialchars
771 * <i>escapenoentities</i>: same, but allows entity references like   through
772 * <i>replaceafter</i>: parameters are substituted after parsing or escaping
773 * <i>parsemag</i>: transform the message using magic phrases
774 * <i>content</i>: fetch message for content language instead of interface
775 * Also can accept a single associative argument, of the form 'language' => 'xx':
776 * <i>language</i>: Language object or language code to fetch message for
777 * (overriden by <i>content</i>).
778 * Behavior for conflicting options (e.g., parse+parseinline) is undefined.
782 function wfMsgExt( $key, $options ) {
783 $args = func_get_args();
784 array_shift( $args );
785 array_shift( $args );
786 $options = (array)$options;
788 foreach( $options as $arrayKey => $option ) {
789 if( !preg_match( '/^[0-9]+|language$/', $arrayKey ) ) {
790 # An unknown index, neither numeric nor "language"
791 wfWarn( "wfMsgExt called with incorrect parameter key $arrayKey", 1, E_USER_WARNING
);
792 } elseif( preg_match( '/^[0-9]+$/', $arrayKey ) && !in_array( $option,
793 array( 'parse', 'parseinline', 'escape', 'escapenoentities',
794 'replaceafter', 'parsemag', 'content' ) ) ) {
795 # A numeric index with unknown value
796 wfWarn( "wfMsgExt called with incorrect parameter $option", 1, E_USER_WARNING
);
800 if( in_array( 'content', $options, true ) ) {
804 } elseif( array_key_exists( 'language', $options ) ) {
806 $langCode = wfGetLangObj( $options['language'] );
807 $langCodeObj = $langCode;
814 $string = wfMsgGetKey( $key, /*DB*/true, $langCode, /*Transform*/false );
816 if( !in_array( 'replaceafter', $options, true ) ) {
817 $string = wfMsgReplaceArgs( $string, $args );
820 $messageCache = MessageCache
::singleton();
821 if( in_array( 'parse', $options, true ) ) {
822 $string = $messageCache->parse( $string, null, true, !$forContent, $langCodeObj )->getText();
823 } elseif ( in_array( 'parseinline', $options, true ) ) {
824 $string = $messageCache->parse( $string, null, true, !$forContent, $langCodeObj )->getText();
826 if( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $string, $m ) ) {
829 } elseif ( in_array( 'parsemag', $options, true ) ) {
830 $string = $messageCache->transform( $string,
831 !$forContent, $langCodeObj );
834 if ( in_array( 'escape', $options, true ) ) {
835 $string = htmlspecialchars ( $string );
836 } elseif ( in_array( 'escapenoentities', $options, true ) ) {
837 $string = Sanitizer
::escapeHtmlAllowEntities( $string );
840 if( in_array( 'replaceafter', $options, true ) ) {
841 $string = wfMsgReplaceArgs( $string, $args );
848 * Print an error message and die, returning nonzero to the shell if any. Plain die()
849 * fails to return nonzero to the shell if you pass a string. Entry points may customise
850 * this function to return a prettier error message, but implementations must not assume
851 * access to any of the usual MediaWiki infrastructure (AutoLoader, localisation, database,
852 * etc). This should not be called directly once $wgFullyInitialised is set; instead,
853 * throw an exception and let Exception.php handle whether or not it's possible to show
858 if( !function_exists( 'wfDie' ) ){
859 function wfDie( $msg = '' ) {
866 * Throw a debugging exception. This function previously once exited the process,
867 * but now throws an exception instead, with similar results.
869 * @param $msg String: message shown when dieing.
871 function wfDebugDieBacktrace( $msg = '' ) {
872 throw new MWException( $msg );
876 * Fetch server name for use in error reporting etc.
877 * Use real server name if available, so we know which machine
878 * in a server farm generated the current page.
882 function wfHostname() {
884 if ( is_null( $host ) ) {
885 if ( function_exists( 'posix_uname' ) ) {
886 // This function not present on Windows
887 $uname = @posix_uname
();
891 if( is_array( $uname ) && isset( $uname['nodename'] ) ) {
892 $host = $uname['nodename'];
893 } elseif ( getenv( 'COMPUTERNAME' ) ) {
894 # Windows computer name
895 $host = getenv( 'COMPUTERNAME' );
897 # This may be a virtual server.
898 $host = $_SERVER['SERVER_NAME'];
905 * Returns a HTML comment with the elapsed time since request.
906 * This method has no side effects.
910 function wfReportTime() {
911 global $wgRequestTime, $wgShowHostnames;
914 $elapsed = $now - $wgRequestTime;
916 return $wgShowHostnames
917 ?
sprintf( '<!-- Served by %s in %01.3f secs. -->', wfHostname(), $elapsed )
918 : sprintf( '<!-- Served in %01.3f secs. -->', $elapsed );
922 * Safety wrapper for debug_backtrace().
924 * With Zend Optimizer 3.2.0 loaded, this causes segfaults under somewhat
925 * murky circumstances, which may be triggered in part by stub objects
926 * or other fancy talkin'.
928 * Will return an empty array if Zend Optimizer is detected or if
929 * debug_backtrace is disabled, otherwise the output from
930 * debug_backtrace() (trimmed).
932 * @return array of backtrace information
934 function wfDebugBacktrace() {
935 static $disabled = null;
937 if( extension_loaded( 'Zend Optimizer' ) ) {
938 wfDebug( "Zend Optimizer detected; skipping debug_backtrace for safety.\n" );
942 if ( is_null( $disabled ) ) {
944 $functions = explode( ',', ini_get( 'disable_functions' ) );
945 $functions = array_map( 'trim', $functions );
946 $functions = array_map( 'strtolower', $functions );
947 if ( in_array( 'debug_backtrace', $functions ) ) {
948 wfDebug( "debug_backtrace is in disabled_functions\n" );
956 return array_slice( debug_backtrace(), 1 );
960 * Get a debug backtrace as a string
964 function wfBacktrace() {
965 global $wgCommandLineMode;
967 if ( $wgCommandLineMode ) {
972 $backtrace = wfDebugBacktrace();
973 foreach( $backtrace as $call ) {
974 if( isset( $call['file'] ) ) {
975 $f = explode( DIRECTORY_SEPARATOR
, $call['file'] );
976 $file = $f[count( $f ) - 1];
980 if( isset( $call['line'] ) ) {
981 $line = $call['line'];
985 if ( $wgCommandLineMode ) {
986 $msg .= "$file line $line calls ";
988 $msg .= '<li>' . $file . ' line ' . $line . ' calls ';
990 if( !empty( $call['class'] ) ) {
991 $msg .= $call['class'] . '::';
993 $msg .= $call['function'] . '()';
995 if ( $wgCommandLineMode ) {
1001 if ( $wgCommandLineMode ) {
1011 /* Some generic result counters, pulled out of SearchEngine */
1017 * @param $offset Int
1021 function wfShowingResults( $offset, $limit ) {
1025 array( 'parseinline' ),
1026 $wgLang->formatNum( $limit ),
1027 $wgLang->formatNum( $offset +
1 )
1034 * @param $offset Int
1039 function wfShowingResultsNum( $offset, $limit, $num ) {
1042 'showingresultsnum',
1043 array( 'parseinline' ),
1044 $wgLang->formatNum( $limit ),
1045 $wgLang->formatNum( $offset +
1 ),
1046 $wgLang->formatNum( $num )
1051 * Generate (prev x| next x) (20|50|100...) type links for paging
1053 * @param $offset String
1054 * @param $limit Integer
1055 * @param $link String
1056 * @param $query String: optional URL query parameter string
1057 * @param $atend Bool: optional param for specified if this is the last page
1060 function wfViewPrevNext( $offset, $limit, $link, $query = '', $atend = false ) {
1062 $fmtLimit = $wgLang->formatNum( $limit );
1063 // @todo FIXME: Why on earth this needs one message for the text and another one for tooltip?
1064 # Get prev/next link display text
1065 $prev = wfMsgExt( 'prevn', array( 'parsemag', 'escape' ), $fmtLimit );
1066 $next = wfMsgExt( 'nextn', array( 'parsemag', 'escape' ), $fmtLimit );
1067 # Get prev/next link title text
1068 $pTitle = wfMsgExt( 'prevn-title', array( 'parsemag', 'escape' ), $fmtLimit );
1069 $nTitle = wfMsgExt( 'nextn-title', array( 'parsemag', 'escape' ), $fmtLimit );
1070 # Fetch the title object
1071 if( is_object( $link ) ) {
1074 $title = Title
::newFromText( $link );
1075 if( is_null( $title ) ) {
1079 # Make 'previous' link
1080 if( 0 != $offset ) {
1081 $po = $offset - $limit;
1082 $po = max( $po, 0 );
1083 $q = "limit={$limit}&offset={$po}";
1084 if( $query != '' ) {
1087 $plink = '<a href="' . $title->escapeLocalURL( $q ) . "\" title=\"{$pTitle}\" class=\"mw-prevlink\">{$prev}</a>";
1092 $no = $offset +
$limit;
1093 $q = "limit={$limit}&offset={$no}";
1094 if( $query != '' ) {
1100 $nlink = '<a href="' . $title->escapeLocalURL( $q ) . "\" title=\"{$nTitle}\" class=\"mw-nextlink\">{$next}</a>";
1102 # Make links to set number of items per page
1103 $nums = $wgLang->pipeList( array(
1104 wfNumLink( $offset, 20, $title, $query ),
1105 wfNumLink( $offset, 50, $title, $query ),
1106 wfNumLink( $offset, 100, $title, $query ),
1107 wfNumLink( $offset, 250, $title, $query ),
1108 wfNumLink( $offset, 500, $title, $query )
1110 return wfMsgHtml( 'viewprevnext', $plink, $nlink, $nums );
1114 * Generate links for (20|50|100...) items-per-page links
1116 * @param $offset String
1117 * @param $limit Integer
1118 * @param $title Title
1119 * @param $query String: optional URL query parameter string
1121 function wfNumLink( $offset, $limit, $title, $query = '' ) {
1123 if( $query == '' ) {
1128 $q .= "limit={$limit}&offset={$offset}";
1129 $fmtLimit = $wgLang->formatNum( $limit );
1130 $lTitle = wfMsgExt( 'shown-title', array( 'parsemag', 'escape' ), $limit );
1131 $s = '<a href="' . $title->escapeLocalURL( $q ) . "\" title=\"{$lTitle}\" class=\"mw-numlink\">{$fmtLimit}</a>";
1137 * @todo FIXME: We may want to blacklist some broken browsers
1139 * @param $force Bool
1140 * @return bool Whereas client accept gzip compression
1142 function wfClientAcceptsGzip( $force = false ) {
1143 static $result = null;
1144 if ( $result === null ||
$force ) {
1146 if( isset( $_SERVER['HTTP_ACCEPT_ENCODING'] ) ) {
1147 # @todo FIXME: We may want to blacklist some broken browsers
1150 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
1151 $_SERVER['HTTP_ACCEPT_ENCODING'],
1155 if( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) {
1159 wfDebug( " accepts gzip\n" );
1168 * Obtain the offset and limit values from the request string;
1169 * used in special pages
1171 * @param $deflimit Int default limit if none supplied
1172 * @param $optionname String Name of a user preference to check against
1176 function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) {
1178 return $wgRequest->getLimitOffset( $deflimit, $optionname );
1182 * Escapes the given text so that it may be output using addWikiText()
1183 * without any linking, formatting, etc. making its way through. This
1184 * is achieved by substituting certain characters with HTML entities.
1185 * As required by the callers, <nowiki> is not used.
1187 * @param $text String: text to be escaped
1190 function wfEscapeWikiText( $text ) {
1191 $text = strtr( "\n$text", array(
1192 '"' => '"', '&' => '&', "'" => ''', '<' => '<',
1193 '=' => '=', '>' => '>', '[' => '[', ']' => ']',
1194 '{' => '{', '|' => '|', '}' => '}',
1195 "\n#" => "\n#", "\n*" => "\n*",
1196 "\n:" => "\n:", "\n;" => "\n;",
1197 '://' => '://', 'ISBN ' => 'ISBN ', 'RFC ' => 'RFC ',
1199 return substr( $text, 1 );
1203 * Get the current unix timetstamp with microseconds. Useful for profiling
1207 return microtime( true );
1211 * Sets dest to source and returns the original value of dest
1212 * If source is NULL, it just returns the value, it doesn't set the variable
1213 * If force is true, it will set the value even if source is NULL
1215 * @param $dest Mixed
1216 * @param $source Mixed
1217 * @param $force Bool
1220 function wfSetVar( &$dest, $source, $force = false ) {
1222 if ( !is_null( $source ) ||
$force ) {
1229 * As for wfSetVar except setting a bit
1233 * @param $state Bool
1235 function wfSetBit( &$dest, $bit, $state = true ) {
1236 $temp = (bool)( $dest & $bit );
1237 if ( !is_null( $state ) ) {
1248 * This function takes two arrays as input, and returns a CGI-style string, e.g.
1249 * "days=7&limit=100". Options in the first array override options in the second.
1250 * Options set to "" will not be output.
1252 * @param $array1 Array( String|Array )
1253 * @param $array2 Array( String|Array )
1256 function wfArrayToCGI( $array1, $array2 = null ) {
1257 if ( !is_null( $array2 ) ) {
1258 $array1 = $array1 +
$array2;
1262 foreach ( $array1 as $key => $value ) {
1263 if ( $value !== '' ) {
1267 if ( is_array( $value ) ) {
1269 foreach ( $value as $v ) {
1270 $cgi .= ( $firstTime ?
'' : '&') .
1271 urlencode( $key . '[]' ) . '=' .
1276 if ( is_object( $value ) ) {
1277 $value = $value->__toString();
1279 $cgi .= urlencode( $key ) . '=' .
1280 urlencode( $value );
1288 * This is the logical opposite of wfArrayToCGI(): it accepts a query string as
1289 * its argument and returns the same string in array form. This allows compa-
1290 * tibility with legacy functions that accept raw query strings instead of nice
1291 * arrays. Of course, keys and values are urldecode()d. Don't try passing in-
1292 * valid query strings, or it will explode.
1294 * @param $query String: query string
1295 * @return array Array version of input
1297 function wfCgiToArray( $query ) {
1298 if( isset( $query[0] ) && $query[0] == '?' ) {
1299 $query = substr( $query, 1 );
1301 $bits = explode( '&', $query );
1303 foreach( $bits as $bit ) {
1307 list( $key, $value ) = explode( '=', $bit );
1308 $key = urldecode( $key );
1309 $value = urldecode( $value );
1310 $ret[$key] = $value;
1316 * Append a query string to an existing URL, which may or may not already
1317 * have query string parameters already. If so, they will be combined.
1319 * @param $url String
1320 * @param $query Mixed: string or associative array
1323 function wfAppendQuery( $url, $query ) {
1324 if ( is_array( $query ) ) {
1325 $query = wfArrayToCGI( $query );
1327 if( $query != '' ) {
1328 if( false === strpos( $url, '?' ) ) {
1339 * Expand a potentially local URL to a fully-qualified URL. Assumes $wgServer
1340 * and $wgProto are correct.
1342 * @todo this won't work with current-path-relative URLs
1343 * like "subdir/foo.html", etc.
1345 * @param $url String: either fully-qualified or a local path + query
1346 * @return string Fully-qualified URL
1348 function wfExpandUrl( $url ) {
1349 if( substr( $url, 0, 2 ) == '//' ) {
1351 return $wgProto . ':' . $url;
1352 } elseif( substr( $url, 0, 1 ) == '/' ) {
1354 return $wgServer . $url;
1361 * Windows-compatible version of escapeshellarg()
1362 * Windows doesn't recognise single-quotes in the shell, but the escapeshellarg()
1363 * function puts single quotes in regardless of OS.
1365 * Also fixes the locale problems on Linux in PHP 5.2.6+ (bug backported to
1366 * earlier distro releases of PHP)
1371 function wfEscapeShellArg( ) {
1372 wfInitShellLocale();
1374 $args = func_get_args();
1377 foreach ( $args as $arg ) {
1384 if ( wfIsWindows() ) {
1385 // Escaping for an MSVC-style command line parser and CMD.EXE
1387 // * http://web.archive.org/web/20020708081031/http://mailman.lyra.org/pipermail/scite-interest/2002-March/000436.html
1388 // * http://technet.microsoft.com/en-us/library/cc723564.aspx
1391 // Double the backslashes before any double quotes. Escape the double quotes.
1392 $tokens = preg_split( '/(\\\\*")/', $arg, -1, PREG_SPLIT_DELIM_CAPTURE
);
1395 foreach ( $tokens as $token ) {
1396 if ( $iteration %
2 == 1 ) {
1397 // Delimiter, a double quote preceded by zero or more slashes
1398 $arg .= str_replace( '\\', '\\\\', substr( $token, 0, -1 ) ) . '\\"';
1399 } elseif ( $iteration %
4 == 2 ) {
1400 // ^ in $token will be outside quotes, need to be escaped
1401 $arg .= str_replace( '^', '^^', $token );
1402 } else { // $iteration % 4 == 0
1403 // ^ in $token will appear inside double quotes, so leave as is
1408 // Double the backslashes before the end of the string, because
1409 // we will soon add a quote
1411 if ( preg_match( '/^(.*?)(\\\\+)$/', $arg, $m ) ) {
1412 $arg = $m[1] . str_replace( '\\', '\\\\', $m[2] );
1415 // Add surrounding quotes
1416 $retVal .= '"' . $arg . '"';
1418 $retVal .= escapeshellarg( $arg );
1425 * wfMerge attempts to merge differences between three texts.
1426 * Returns true for a clean merge and false for failure or a conflict.
1428 * @param $old String
1429 * @param $mine String
1430 * @param $yours String
1431 * @param $result String
1434 function wfMerge( $old, $mine, $yours, &$result ) {
1437 # This check may also protect against code injection in
1438 # case of broken installations.
1439 wfSuppressWarnings();
1440 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
1441 wfRestoreWarnings();
1444 wfDebug( "diff3 not found\n" );
1448 # Make temporary files
1450 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
1451 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
1452 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
1454 fwrite( $oldtextFile, $old );
1455 fclose( $oldtextFile );
1456 fwrite( $mytextFile, $mine );
1457 fclose( $mytextFile );
1458 fwrite( $yourtextFile, $yours );
1459 fclose( $yourtextFile );
1461 # Check for a conflict
1462 $cmd = $wgDiff3 . ' -a --overlap-only ' .
1463 wfEscapeShellArg( $mytextName ) . ' ' .
1464 wfEscapeShellArg( $oldtextName ) . ' ' .
1465 wfEscapeShellArg( $yourtextName );
1466 $handle = popen( $cmd, 'r' );
1468 if( fgets( $handle, 1024 ) ) {
1476 $cmd = $wgDiff3 . ' -a -e --merge ' .
1477 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
1478 $handle = popen( $cmd, 'r' );
1481 $data = fread( $handle, 8192 );
1482 if ( strlen( $data ) == 0 ) {
1488 unlink( $mytextName );
1489 unlink( $oldtextName );
1490 unlink( $yourtextName );
1492 if ( $result === '' && $old !== '' && !$conflict ) {
1493 wfDebug( "Unexpected null result from diff3. Command: $cmd\n" );
1500 * Returns unified plain-text diff of two texts.
1501 * Useful for machine processing of diffs.
1503 * @param $before String: the text before the changes.
1504 * @param $after String: the text after the changes.
1505 * @param $params String: command-line options for the diff command.
1506 * @return String: unified diff of $before and $after
1508 function wfDiff( $before, $after, $params = '-u' ) {
1509 if ( $before == $after ) {
1514 wfSuppressWarnings();
1515 $haveDiff = $wgDiff && file_exists( $wgDiff );
1516 wfRestoreWarnings();
1518 # This check may also protect against code injection in
1519 # case of broken installations.
1521 wfDebug( "diff executable not found\n" );
1522 $diffs = new Diff( explode( "\n", $before ), explode( "\n", $after ) );
1523 $format = new UnifiedDiffFormatter();
1524 return $format->format( $diffs );
1527 # Make temporary files
1529 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
1530 $newtextFile = fopen( $newtextName = tempnam( $td, 'merge-your-' ), 'w' );
1532 fwrite( $oldtextFile, $before );
1533 fclose( $oldtextFile );
1534 fwrite( $newtextFile, $after );
1535 fclose( $newtextFile );
1537 // Get the diff of the two files
1538 $cmd = "$wgDiff " . $params . ' ' . wfEscapeShellArg( $oldtextName, $newtextName );
1540 $h = popen( $cmd, 'r' );
1545 $data = fread( $h, 8192 );
1546 if ( strlen( $data ) == 0 ) {
1554 unlink( $oldtextName );
1555 unlink( $newtextName );
1557 // Kill the --- and +++ lines. They're not useful.
1558 $diff_lines = explode( "\n", $diff );
1559 if ( strpos( $diff_lines[0], '---' ) === 0 ) {
1560 unset( $diff_lines[0] );
1562 if ( strpos( $diff_lines[1], '+++' ) === 0 ) {
1563 unset( $diff_lines[1] );
1566 $diff = implode( "\n", $diff_lines );
1572 * A wrapper around the PHP function var_export().
1573 * Either print it or add it to the regular output ($wgOut).
1575 * @param $var A PHP variable to dump.
1577 function wfVarDump( $var ) {
1579 $s = str_replace( "\n", "<br />\n", var_export( $var, true ) . "\n" );
1580 if ( headers_sent() ||
!@is_object
( $wgOut ) ) {
1583 $wgOut->addHTML( $s );
1588 * Provide a simple HTTP error.
1590 * @param $code Int|String
1591 * @param $label String
1592 * @param $desc String
1594 function wfHttpError( $code, $label, $desc ) {
1597 header( "HTTP/1.0 $code $label" );
1598 header( "Status: $code $label" );
1599 $wgOut->sendCacheControl();
1601 header( 'Content-type: text/html; charset=utf-8' );
1602 print "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">".
1603 '<html><head><title>' .
1604 htmlspecialchars( $label ) .
1605 '</title></head><body><h1>' .
1606 htmlspecialchars( $label ) .
1608 nl2br( htmlspecialchars( $desc ) ) .
1609 "</p></body></html>\n";
1613 * Clear away any user-level output buffers, discarding contents.
1615 * Suitable for 'starting afresh', for instance when streaming
1616 * relatively large amounts of data without buffering, or wanting to
1617 * output image files without ob_gzhandler's compression.
1619 * The optional $resetGzipEncoding parameter controls suppression of
1620 * the Content-Encoding header sent by ob_gzhandler; by default it
1621 * is left. See comments for wfClearOutputBuffers() for why it would
1624 * Note that some PHP configuration options may add output buffer
1625 * layers which cannot be removed; these are left in place.
1627 * @param $resetGzipEncoding Bool
1629 function wfResetOutputBuffers( $resetGzipEncoding = true ) {
1630 if( $resetGzipEncoding ) {
1631 // Suppress Content-Encoding and Content-Length
1632 // headers from 1.10+s wfOutputHandler
1633 global $wgDisableOutputCompression;
1634 $wgDisableOutputCompression = true;
1636 while( $status = ob_get_status() ) {
1637 if( $status['type'] == 0 /* PHP_OUTPUT_HANDLER_INTERNAL */ ) {
1638 // Probably from zlib.output_compression or other
1639 // PHP-internal setting which can't be removed.
1641 // Give up, and hope the result doesn't break
1645 if( !ob_end_clean() ) {
1646 // Could not remove output buffer handler; abort now
1647 // to avoid getting in some kind of infinite loop.
1650 if( $resetGzipEncoding ) {
1651 if( $status['name'] == 'ob_gzhandler' ) {
1652 // Reset the 'Content-Encoding' field set by this handler
1653 // so we can start fresh.
1654 if ( function_exists( 'header_remove' ) ) {
1655 // Available since PHP 5.3.0
1656 header_remove( 'Content-Encoding' );
1658 // We need to provide a valid content-coding. See bug 28069
1659 header( 'Content-Encoding: identity' );
1668 * More legible than passing a 'false' parameter to wfResetOutputBuffers():
1670 * Clear away output buffers, but keep the Content-Encoding header
1671 * produced by ob_gzhandler, if any.
1673 * This should be used for HTTP 304 responses, where you need to
1674 * preserve the Content-Encoding header of the real result, but
1675 * also need to suppress the output of ob_gzhandler to keep to spec
1676 * and avoid breaking Firefox in rare cases where the headers and
1677 * body are broken over two packets.
1679 function wfClearOutputBuffers() {
1680 wfResetOutputBuffers( false );
1684 * Converts an Accept-* header into an array mapping string values to quality
1687 * @param $accept String
1688 * @param $def String default
1691 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
1692 # No arg means accept anything (per HTTP spec)
1694 return array( $def => 1.0 );
1699 $parts = explode( ',', $accept );
1701 foreach( $parts as $part ) {
1702 # @todo FIXME: Doesn't deal with params like 'text/html; level=1'
1703 @list
( $value, $qpart ) = explode( ';', trim( $part ) );
1705 if( !isset( $qpart ) ) {
1706 $prefs[$value] = 1.0;
1707 } elseif( preg_match( '/q\s*=\s*(\d*\.\d+)/', $qpart, $match ) ) {
1708 $prefs[$value] = floatval( $match[1] );
1716 * Checks if a given MIME type matches any of the keys in the given
1717 * array. Basic wildcards are accepted in the array keys.
1719 * Returns the matching MIME type (or wildcard) if a match, otherwise
1722 * @param $type String
1723 * @param $avail Array
1727 function mimeTypeMatch( $type, $avail ) {
1728 if( array_key_exists( $type, $avail ) ) {
1731 $parts = explode( '/', $type );
1732 if( array_key_exists( $parts[0] . '/*', $avail ) ) {
1733 return $parts[0] . '/*';
1734 } elseif( array_key_exists( '*/*', $avail ) ) {
1743 * Returns the 'best' match between a client's requested internet media types
1744 * and the server's list of available types. Each list should be an associative
1745 * array of type to preference (preference is a float between 0.0 and 1.0).
1746 * Wildcards in the types are acceptable.
1748 * @param $cprefs Array: client's acceptable type list
1749 * @param $sprefs Array: server's offered types
1752 * @todo FIXME: Doesn't handle params like 'text/plain; charset=UTF-8'
1753 * XXX: generalize to negotiate other stuff
1755 function wfNegotiateType( $cprefs, $sprefs ) {
1758 foreach( array_keys($sprefs) as $type ) {
1759 $parts = explode( '/', $type );
1760 if( $parts[1] != '*' ) {
1761 $ckey = mimeTypeMatch( $type, $cprefs );
1763 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1768 foreach( array_keys( $cprefs ) as $type ) {
1769 $parts = explode( '/', $type );
1770 if( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
1771 $skey = mimeTypeMatch( $type, $sprefs );
1773 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1781 foreach( array_keys( $combine ) as $type ) {
1782 if( $combine[$type] > $bestq ) {
1784 $bestq = $combine[$type];
1793 * Returns an array where the values in the first array are replaced by the
1794 * values in the second array with the corresponding keys
1800 function wfArrayLookup( $a, $b ) {
1801 return array_flip( array_intersect( array_flip( $a ), array_keys( $b ) ) );
1805 * Reference-counted warning suppression
1809 function wfSuppressWarnings( $end = false ) {
1810 static $suppressCount = 0;
1811 static $originalLevel = false;
1814 if ( $suppressCount ) {
1816 if ( !$suppressCount ) {
1817 error_reporting( $originalLevel );
1821 if ( !$suppressCount ) {
1822 // E_DEPRECATED is undefined in PHP 5.2
1823 if( !defined( 'E_DEPRECATED' ) ){
1824 define( 'E_DEPRECATED', 8192 );
1826 $originalLevel = error_reporting( E_ALL
& ~
( E_WARNING | E_NOTICE | E_USER_WARNING | E_USER_NOTICE | E_DEPRECATED
) );
1833 * Restore error level to previous value
1835 function wfRestoreWarnings() {
1836 wfSuppressWarnings( true );
1839 # Autodetect, convert and provide timestamps of various types
1842 * Unix time - the number of seconds since 1970-01-01 00:00:00 UTC
1844 define( 'TS_UNIX', 0 );
1847 * MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
1849 define( 'TS_MW', 1 );
1852 * MySQL DATETIME (YYYY-MM-DD HH:MM:SS)
1854 define( 'TS_DB', 2 );
1857 * RFC 2822 format, for E-mail and HTTP headers
1859 define( 'TS_RFC2822', 3 );
1862 * ISO 8601 format with no timezone: 1986-02-09T20:00:00Z
1864 * This is used by Special:Export
1866 define( 'TS_ISO_8601', 4 );
1869 * An Exif timestamp (YYYY:MM:DD HH:MM:SS)
1871 * @see http://exif.org/Exif2-2.PDF The Exif 2.2 spec, see page 28 for the
1872 * DateTime tag and page 36 for the DateTimeOriginal and
1873 * DateTimeDigitized tags.
1875 define( 'TS_EXIF', 5 );
1878 * Oracle format time.
1880 define( 'TS_ORACLE', 6 );
1883 * Postgres format time.
1885 define( 'TS_POSTGRES', 7 );
1890 define( 'TS_DB2', 8 );
1893 * ISO 8601 basic format with no timezone: 19860209T200000Z. This is used by ResourceLoader
1895 define( 'TS_ISO_8601_BASIC', 9 );
1898 * Get a timestamp string in one of various formats
1900 * @param $outputtype Mixed: A timestamp in one of the supported formats, the
1901 * function will autodetect which format is supplied and act
1903 * @param $ts Mixed: the timestamp to convert or 0 for the current timestamp
1904 * @return Mixed: String / false The same date in the format specified in $outputtype or false
1906 function wfTimestamp( $outputtype = TS_UNIX
, $ts = 0 ) {
1911 if ( !$ts ) { // We want to catch 0, '', null... but not date strings starting with a letter.
1914 } elseif ( preg_match( '/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)$/D', $ts, $da ) ) {
1916 } elseif ( preg_match( '/^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/D', $ts, $da ) ) {
1918 } elseif ( preg_match( '/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/D', $ts, $da ) ) {
1920 } elseif ( preg_match( '/^-?\d{1,13}$/D', $ts ) ) {
1923 $strtime = "@$ts"; // Undocumented?
1924 } elseif ( preg_match( '/^\d{2}-\d{2}-\d{4} \d{2}:\d{2}:\d{2}.\d{6}$/', $ts ) ) {
1925 # TS_ORACLE // session altered to DD-MM-YYYY HH24:MI:SS.FF6
1926 $strtime = preg_replace( '/(\d\d)\.(\d\d)\.(\d\d)(\.(\d+))?/', "$1:$2:$3",
1927 str_replace( '+00:00', 'UTC', $ts ) );
1928 } elseif ( preg_match( '/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.*\d*)?Z$/', $ts, $da ) ) {
1930 } elseif ( preg_match( '/^(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})(?:\.*\d*)?Z$/', $ts, $da ) ) {
1932 } elseif ( preg_match( '/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.*\d*[\+\- ](\d\d)$/', $ts, $da ) ) {
1934 } elseif ( preg_match( '/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.*\d* GMT$/', $ts, $da ) ) {
1936 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.\d\d\d$/',$ts,$da)) {
1938 } elseif ( preg_match( '/^[ \t\r\n]*([A-Z][a-z]{2},[ \t\r\n]*)?' . # Day of week
1939 '\d\d?[ \t\r\n]*[A-Z][a-z]{2}[ \t\r\n]*\d{2}(?:\d{2})?' . # dd Mon yyyy
1940 '[ \t\r\n]*\d\d[ \t\r\n]*:[ \t\r\n]*\d\d[ \t\r\n]*:[ \t\r\n]*\d\d/S', $ts ) ) { # hh:mm:ss
1941 # TS_RFC2822, accepting a trailing comment. See http://www.squid-cache.org/mail-archive/squid-users/200307/0122.html / r77171
1942 # The regex is a superset of rfc2822 for readability
1943 $strtime = strtok( $ts, ';' );
1944 } elseif ( preg_match( '/^[A-Z][a-z]{5,8}, \d\d-[A-Z][a-z]{2}-\d{2} \d\d:\d\d:\d\d/', $ts ) ) {
1947 } elseif ( preg_match( '/^[A-Z][a-z]{2} [A-Z][a-z]{2} +\d{1,2} \d\d:\d\d:\d\d \d{4}/', $ts ) ) {
1952 wfDebug("wfTimestamp() fed bogus time value: TYPE=$outputtype; VALUE=$ts\n");
1959 static $formats = array(
1962 TS_DB
=> 'Y-m-d H:i:s',
1963 TS_ISO_8601
=> 'Y-m-d\TH:i:s\Z',
1964 TS_ISO_8601_BASIC
=> 'Ymd\THis\Z',
1965 TS_EXIF
=> 'Y:m:d H:i:s', // This shouldn't ever be used, but is included for completeness
1966 TS_RFC2822
=> 'D, d M Y H:i:s',
1967 TS_ORACLE
=> 'd-m-Y H:i:s.000000', // Was 'd-M-y h.i.s A' . ' +00:00' before r51500
1968 TS_POSTGRES
=> 'Y-m-d H:i:s',
1969 TS_DB2
=> 'Y-m-d H:i:s',
1972 if ( !isset( $formats[$outputtype] ) ) {
1973 throw new MWException( 'wfTimestamp() called with illegal output type.' );
1976 if ( function_exists( "date_create" ) ) {
1977 if ( count( $da ) ) {
1978 $ds = sprintf("%04d-%02d-%02dT%02d:%02d:%02d.00+00:00",
1979 (int)$da[1], (int)$da[2], (int)$da[3],
1980 (int)$da[4], (int)$da[5], (int)$da[6]);
1982 $d = date_create( $ds, new DateTimeZone( 'GMT' ) );
1983 } elseif ( $strtime ) {
1984 $d = date_create( $strtime, new DateTimeZone( 'GMT' ) );
1990 wfDebug("wfTimestamp() fed bogus time value: $outputtype; $ts\n");
1994 $output = $d->format( $formats[$outputtype] );
1996 if ( count( $da ) ) {
1997 // Warning! gmmktime() acts oddly if the month or day is set to 0
1998 // We may want to handle that explicitly at some point
1999 $uts = gmmktime( (int)$da[4], (int)$da[5], (int)$da[6],
2000 (int)$da[2], (int)$da[3], (int)$da[1] );
2001 } elseif ( $strtime ) {
2002 $uts = strtotime( $strtime );
2005 if ( $uts === false ) {
2006 wfDebug("wfTimestamp() can't parse the timestamp (non 32-bit time? Update php): $outputtype; $ts\n");
2010 if ( TS_UNIX
== $outputtype ) {
2013 $output = gmdate( $formats[$outputtype], $uts );
2016 if ( ( $outputtype == TS_RFC2822
) ||
( $outputtype == TS_POSTGRES
) ) {
2024 * Return a formatted timestamp, or null if input is null.
2025 * For dealing with nullable timestamp columns in the database.
2027 * @param $outputtype Integer
2031 function wfTimestampOrNull( $outputtype = TS_UNIX
, $ts = null ) {
2032 if( is_null( $ts ) ) {
2035 return wfTimestamp( $outputtype, $ts );
2040 * Convenience function; returns MediaWiki timestamp for the present time.
2044 function wfTimestampNow() {
2046 return wfTimestamp( TS_MW
, time() );
2050 * Check if the operating system is Windows
2052 * @return Bool: true if it's Windows, False otherwise.
2054 function wfIsWindows() {
2055 static $isWindows = null;
2056 if ( $isWindows === null ) {
2057 $isWindows = substr( php_uname(), 0, 7 ) == 'Windows';
2063 * Check if we are running under HipHop
2067 function wfIsHipHop() {
2068 return function_exists( 'hphp_thread_set_warmup_enabled' );
2072 * Swap two variables
2077 function swap( &$x, &$y ) {
2084 * Tries to get the system directory for temporary files. The TMPDIR, TMP, and
2085 * TEMP environment variables are then checked in sequence, and if none are set
2086 * try sys_get_temp_dir() for PHP >= 5.2.1. All else fails, return /tmp for Unix
2087 * or C:\Windows\Temp for Windows and hope for the best.
2088 * It is common to call it with tempnam().
2090 * NOTE: When possible, use instead the tmpfile() function to create
2091 * temporary files to avoid race conditions on file creation, etc.
2095 function wfTempDir() {
2096 foreach( array( 'TMPDIR', 'TMP', 'TEMP' ) as $var ) {
2097 $tmp = getenv( $var );
2098 if( $tmp && file_exists( $tmp ) && is_dir( $tmp ) && is_writable( $tmp ) ) {
2102 if( function_exists( 'sys_get_temp_dir' ) ) {
2103 return sys_get_temp_dir();
2106 return wfIsWindows() ?
'C:\Windows\Temp' : '/tmp';
2110 * Make directory, and make all parent directories if they don't exist
2112 * @param $dir String: full path to directory to create
2113 * @param $mode Integer: chmod value to use, default is $wgDirectoryMode
2114 * @param $caller String: optional caller param for debugging.
2117 function wfMkdirParents( $dir, $mode = null, $caller = null ) {
2118 global $wgDirectoryMode;
2120 if ( !is_null( $caller ) ) {
2121 wfDebug( "$caller: called wfMkdirParents($dir)" );
2124 if( strval( $dir ) === '' ||
file_exists( $dir ) ) {
2128 $dir = str_replace( array( '\\', '/' ), DIRECTORY_SEPARATOR
, $dir );
2130 if ( is_null( $mode ) ) {
2131 $mode = $wgDirectoryMode;
2134 // Turn off the normal warning, we're doing our own below
2135 wfSuppressWarnings();
2136 $ok = mkdir( $dir, $mode, true ); // PHP5 <3
2137 wfRestoreWarnings();
2140 // PHP doesn't report the path in its warning message, so add our own to aid in diagnosis.
2141 trigger_error( __FUNCTION__
. ": failed to mkdir \"$dir\" mode $mode", E_USER_WARNING
);
2147 * Increment a statistics counter
2149 * @param $key String
2152 function wfIncrStats( $key, $count = 1 ) {
2153 global $wgStatsMethod;
2155 $count = intval( $count );
2157 if( $wgStatsMethod == 'udp' ) {
2158 global $wgUDPProfilerHost, $wgUDPProfilerPort, $wgDBname, $wgAggregateStatsID;
2161 $id = $wgAggregateStatsID !== false ?
$wgAggregateStatsID : $wgDBname;
2164 $socket = socket_create( AF_INET
, SOCK_DGRAM
, SOL_UDP
);
2165 $statline = "stats/{$id} - {$count} 1 1 1 1 -total\n";
2169 strlen( $statline ),
2175 $statline = "stats/{$id} - {$count} 1 1 1 1 {$key}\n";
2176 wfSuppressWarnings();
2180 strlen( $statline ),
2185 wfRestoreWarnings();
2186 } elseif( $wgStatsMethod == 'cache' ) {
2188 $key = wfMemcKey( 'stats', $key );
2189 if ( is_null( $wgMemc->incr( $key, $count ) ) ) {
2190 $wgMemc->add( $key, $count );
2198 * @param $nr Mixed: the number to format
2199 * @param $acc Integer: the number of digits after the decimal point, default 2
2200 * @param $round Boolean: whether or not to round the value, default true
2203 function wfPercent( $nr, $acc = 2, $round = true ) {
2204 $ret = sprintf( "%.${acc}f", $nr );
2205 return $round ?
round( $ret, $acc ) . '%' : "$ret%";
2209 * Appends to second array if $value differs from that in $default
2211 * @param $key String|Int
2212 * @param $value Mixed
2213 * @param $default Mixed
2214 * @param $changed Array to alter
2216 function wfAppendToArrayIfNotDefault( $key, $value, $default, &$changed ) {
2217 if ( is_null( $changed ) ) {
2218 throw new MWException( 'GlobalFunctions::wfAppendToArrayIfNotDefault got null' );
2220 if ( $default[$key] !== $value ) {
2221 $changed[$key] = $value;
2226 * Since wfMsg() and co suck, they don't return false if the message key they
2227 * looked up didn't exist but a XHTML string, this function checks for the
2228 * nonexistance of messages by checking the MessageCache::get() result directly.
2230 * @param $key String: the message key looked up
2231 * @return Boolean True if the message *doesn't* exist.
2233 function wfEmptyMsg( $key ) {
2234 return MessageCache
::singleton()->get( $key, /*useDB*/true, /*content*/false ) === false;
2238 * Find out whether or not a mixed variable exists in a string
2240 * @param $needle String
2241 * @param $str String
2242 * @param $insensitive Boolean
2245 function in_string( $needle, $str, $insensitive = false ) {
2247 if( $insensitive ) $func = 'stripos';
2249 return $func( $str, $needle ) !== false;
2252 function wfSpecialList( $page, $details ) {
2254 $details = $details ?
' ' . $wgContLang->getDirMark() . "($details)" : '';
2255 return $page . $details;
2259 * Returns a regular expression of url protocols
2263 function wfUrlProtocols() {
2264 global $wgUrlProtocols;
2266 static $retval = null;
2267 if ( !is_null( $retval ) ) {
2271 // Support old-style $wgUrlProtocols strings, for backwards compatibility
2272 // with LocalSettings files from 1.5
2273 if ( is_array( $wgUrlProtocols ) ) {
2274 $protocols = array();
2275 foreach ( $wgUrlProtocols as $protocol ) {
2276 $protocols[] = preg_quote( $protocol, '/' );
2279 $retval = implode( '|', $protocols );
2281 $retval = $wgUrlProtocols;
2287 * Safety wrapper around ini_get() for boolean settings.
2288 * The values returned from ini_get() are pre-normalized for settings
2289 * set via php.ini or php_flag/php_admin_flag... but *not*
2290 * for those set via php_value/php_admin_value.
2292 * It's fairly common for people to use php_value instead of php_flag,
2293 * which can leave you with an 'off' setting giving a false positive
2294 * for code that just takes the ini_get() return value as a boolean.
2296 * To make things extra interesting, setting via php_value accepts
2297 * "true" and "yes" as true, but php.ini and php_flag consider them false. :)
2298 * Unrecognized values go false... again opposite PHP's own coercion
2299 * from string to bool.
2301 * Luckily, 'properly' set settings will always come back as '0' or '1',
2302 * so we only have to worry about them and the 'improper' settings.
2304 * I frickin' hate PHP... :P
2306 * @param $setting String
2309 function wfIniGetBool( $setting ) {
2310 $val = ini_get( $setting );
2311 // 'on' and 'true' can't have whitespace around them, but '1' can.
2312 return strtolower( $val ) == 'on'
2313 ||
strtolower( $val ) == 'true'
2314 ||
strtolower( $val ) == 'yes'
2315 ||
preg_match( "/^\s*[+-]?0*[1-9]/", $val ); // approx C atoi() function
2319 * Wrapper function for PHP's dl(). This doesn't work in most situations from
2320 * PHP 5.3 onward, and is usually disabled in shared environments anyway.
2322 * @param $extension String A PHP extension. The file suffix (.so or .dll)
2324 * @param $fileName String Name of the library, if not $extension.suffix
2325 * @return Bool - Whether or not the extension is loaded
2327 function wfDl( $extension, $fileName = null ) {
2328 if( extension_loaded( $extension ) ) {
2333 $sapi = php_sapi_name();
2334 if( version_compare( PHP_VERSION
, '5.3.0', '<' ) ||
2335 $sapi == 'cli' ||
$sapi == 'cgi' ||
$sapi == 'embed' )
2337 $canDl = ( function_exists( 'dl' ) && is_callable( 'dl' )
2338 && wfIniGetBool( 'enable_dl' ) && !wfIniGetBool( 'safe_mode' ) );
2342 $fileName = $fileName ?
$fileName : $extension;
2343 if( wfIsWindows() ) {
2344 $fileName = 'php_' . $fileName;
2346 wfSuppressWarnings();
2347 dl( $fileName . '.' . PHP_SHLIB_SUFFIX
);
2348 wfRestoreWarnings();
2350 return extension_loaded( $extension );
2354 * Execute a shell command, with time and memory limits mirrored from the PHP
2355 * configuration if supported.
2356 * @param $cmd String Command line, properly escaped for shell.
2357 * @param &$retval optional, will receive the program's exit code.
2358 * (non-zero is usually failure)
2359 * @param $environ Array optional environment variables which should be
2360 * added to the executed command environment.
2361 * @return collected stdout as a string (trailing newlines stripped)
2363 function wfShellExec( $cmd, &$retval = null, $environ = array() ) {
2364 global $IP, $wgMaxShellMemory, $wgMaxShellFileSize, $wgMaxShellTime;
2367 if ( is_null( $disabled ) ) {
2369 if( wfIniGetBool( 'safe_mode' ) ) {
2370 wfDebug( "wfShellExec can't run in safe_mode, PHP's exec functions are too broken.\n" );
2371 $disabled = 'safemode';
2373 $functions = explode( ',', ini_get( 'disable_functions' ) );
2374 $functions = array_map( 'trim', $functions );
2375 $functions = array_map( 'strtolower', $functions );
2376 if ( in_array( 'passthru', $functions ) ) {
2377 wfDebug( "passthru is in disabled_functions\n" );
2378 $disabled = 'passthru';
2384 return $disabled == 'safemode' ?
2385 'Unable to run external programs in safe mode.' :
2386 'Unable to run external programs, passthru() is disabled.';
2389 wfInitShellLocale();
2392 foreach( $environ as $k => $v ) {
2393 if ( wfIsWindows() ) {
2394 /* Surrounding a set in quotes (method used by wfEscapeShellArg) makes the quotes themselves
2395 * appear in the environment variable, so we must use carat escaping as documented in
2396 * http://technet.microsoft.com/en-us/library/cc723564.aspx
2397 * Note however that the quote isn't listed there, but is needed, and the parentheses
2398 * are listed there but doesn't appear to need it.
2400 $envcmd .= "set $k=" . preg_replace( '/([&|()<>^"])/', '^\\1', $v ) . '&& ';
2402 /* Assume this is a POSIX shell, thus required to accept variable assignments before the command
2403 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_09_01
2405 $envcmd .= "$k=" . escapeshellarg( $v ) . ' ';
2408 $cmd = $envcmd . $cmd;
2410 if ( wfIsWindows() ) {
2411 if ( version_compare( PHP_VERSION
, '5.3.0', '<' ) && /* Fixed in 5.3.0 :) */
2412 ( version_compare( PHP_VERSION
, '5.2.1', '>=' ) ||
php_uname( 's' ) == 'Windows NT' ) )
2414 # Hack to work around PHP's flawed invocation of cmd.exe
2415 # http://news.php.net/php.internals/21796
2416 # Windows 9x doesn't accept any kind of quotes
2417 $cmd = '"' . $cmd . '"';
2419 } elseif ( php_uname( 's' ) == 'Linux' ) {
2420 $time = intval( $wgMaxShellTime );
2421 $mem = intval( $wgMaxShellMemory );
2422 $filesize = intval( $wgMaxShellFileSize );
2424 if ( $time > 0 && $mem > 0 ) {
2425 $script = "$IP/bin/ulimit4.sh";
2426 if ( is_executable( $script ) ) {
2427 $cmd = '/bin/bash ' . escapeshellarg( $script ) . " $time $mem $filesize " . escapeshellarg( $cmd );
2431 wfDebug( "wfShellExec: $cmd\n" );
2433 $retval = 1; // error by default?
2435 passthru( $cmd, $retval );
2436 $output = ob_get_contents();
2439 if ( $retval == 127 ) {
2440 wfDebugLog( 'exec', "Possibly missing executable file: $cmd\n" );
2446 * Workaround for http://bugs.php.net/bug.php?id=45132
2447 * escapeshellarg() destroys non-ASCII characters if LANG is not a UTF-8 locale
2449 function wfInitShellLocale() {
2450 static $done = false;
2455 global $wgShellLocale;
2456 if ( !wfIniGetBool( 'safe_mode' ) ) {
2457 putenv( "LC_CTYPE=$wgShellLocale" );
2458 setlocale( LC_CTYPE
, $wgShellLocale );
2463 * This function works like "use VERSION" in Perl, the program will die with a
2464 * backtrace if the current version of PHP is less than the version provided
2466 * This is useful for extensions which due to their nature are not kept in sync
2467 * with releases, and might depend on other versions of PHP than the main code
2469 * Note: PHP might die due to parsing errors in some cases before it ever
2470 * manages to call this function, such is life
2472 * @see perldoc -f use
2474 * @param $req_ver Mixed: the version to check, can be a string, an integer, or
2477 function wfUsePHP( $req_ver ) {
2478 $php_ver = PHP_VERSION
;
2480 if ( version_compare( $php_ver, (string)$req_ver, '<' ) ) {
2481 throw new MWException( "PHP $req_ver required--this is only $php_ver" );
2486 * This function works like "use VERSION" in Perl except it checks the version
2487 * of MediaWiki, the program will die with a backtrace if the current version
2488 * of MediaWiki is less than the version provided.
2490 * This is useful for extensions which due to their nature are not kept in sync
2493 * @see perldoc -f use
2495 * @param $req_ver Mixed: the version to check, can be a string, an integer, or
2498 function wfUseMW( $req_ver ) {
2501 if ( version_compare( $wgVersion, (string)$req_ver, '<' ) ) {
2502 throw new MWException( "MediaWiki $req_ver required--this is only $wgVersion" );
2507 * Return the final portion of a pathname.
2508 * Reimplemented because PHP5's basename() is buggy with multibyte text.
2509 * http://bugs.php.net/bug.php?id=33898
2511 * PHP's basename() only considers '\' a pathchar on Windows and Netware.
2512 * We'll consider it so always, as we don't want \s in our Unix paths either.
2514 * @param $path String
2515 * @param $suffix String: to remove if present
2518 function wfBaseName( $path, $suffix = '' ) {
2519 $encSuffix = ( $suffix == '' )
2521 : ( '(?:' . preg_quote( $suffix, '#' ) . ')?' );
2523 if( preg_match( "#([^/\\\\]*?){$encSuffix}[/\\\\]*$#", $path, $matches ) ) {
2531 * Generate a relative path name to the given file.
2532 * May explode on non-matching case-insensitive paths,
2533 * funky symlinks, etc.
2535 * @param $path String: absolute destination path including target filename
2536 * @param $from String: Absolute source path, directory only
2539 function wfRelativePath( $path, $from ) {
2540 // Normalize mixed input on Windows...
2541 $path = str_replace( '/', DIRECTORY_SEPARATOR
, $path );
2542 $from = str_replace( '/', DIRECTORY_SEPARATOR
, $from );
2544 // Trim trailing slashes -- fix for drive root
2545 $path = rtrim( $path, DIRECTORY_SEPARATOR
);
2546 $from = rtrim( $from, DIRECTORY_SEPARATOR
);
2548 $pieces = explode( DIRECTORY_SEPARATOR
, dirname( $path ) );
2549 $against = explode( DIRECTORY_SEPARATOR
, $from );
2551 if( $pieces[0] !== $against[0] ) {
2552 // Non-matching Windows drive letters?
2553 // Return a full path.
2557 // Trim off common prefix
2558 while( count( $pieces ) && count( $against )
2559 && $pieces[0] == $against[0] ) {
2560 array_shift( $pieces );
2561 array_shift( $against );
2564 // relative dots to bump us to the parent
2565 while( count( $against ) ) {
2566 array_unshift( $pieces, '..' );
2567 array_shift( $against );
2570 array_push( $pieces, wfBaseName( $path ) );
2572 return implode( DIRECTORY_SEPARATOR
, $pieces );
2576 * Backwards array plus for people who haven't bothered to read the PHP manual
2577 * XXX: will not darn your socks for you.
2579 * @param $array1 Array
2580 * @param [$array2, [...]] Arrays
2583 function wfArrayMerge( $array1/* ... */ ) {
2584 $args = func_get_args();
2585 $args = array_reverse( $args, true );
2587 foreach ( $args as $arg ) {
2594 * Merge arrays in the style of getUserPermissionsErrors, with duplicate removal
2596 * wfMergeErrorArrays(
2597 * array( array( 'x' ) ),
2598 * array( array( 'x', '2' ) ),
2599 * array( array( 'x' ) ),
2600 * array( array( 'y') )
2604 * array( 'x', '2' ),
2611 function wfMergeErrorArrays( /*...*/ ) {
2612 $args = func_get_args();
2614 foreach ( $args as $errors ) {
2615 foreach ( $errors as $params ) {
2616 # @todo FIXME: Sometimes get nested arrays for $params,
2617 # which leads to E_NOTICEs
2618 $spec = implode( "\t", $params );
2619 $out[$spec] = $params;
2622 return array_values( $out );
2626 * parse_url() work-alike, but non-broken. Differences:
2628 * 1) Does not raise warnings on bad URLs (just returns false)
2629 * 2) Handles protocols that don't use :// (e.g., mailto: and news:) correctly
2630 * 3) Adds a "delimiter" element to the array, either '://' or ':' (see (2))
2632 * @param $url String: a URL to parse
2633 * @return Array: bits of the URL in an associative array, per PHP docs
2635 function wfParseUrl( $url ) {
2636 global $wgUrlProtocols; // Allow all protocols defined in DefaultSettings/LocalSettings.php
2637 wfSuppressWarnings();
2638 $bits = parse_url( $url );
2639 wfRestoreWarnings();
2644 // most of the protocols are followed by ://, but mailto: and sometimes news: not, check for it
2645 if ( in_array( $bits['scheme'] . '://', $wgUrlProtocols ) ) {
2646 $bits['delimiter'] = '://';
2647 } elseif ( in_array( $bits['scheme'] . ':', $wgUrlProtocols ) ) {
2648 $bits['delimiter'] = ':';
2649 // parse_url detects for news: and mailto: the host part of an url as path
2650 // We have to correct this wrong detection
2651 if ( isset( $bits['path'] ) ) {
2652 $bits['host'] = $bits['path'];
2663 * Make a URL index, appropriate for the el_index field of externallinks.
2665 * @param $url String
2668 function wfMakeUrlIndex( $url ) {
2669 $bits = wfParseUrl( $url );
2671 // Reverse the labels in the hostname, convert to lower case
2672 // For emails reverse domainpart only
2673 if ( $bits['scheme'] == 'mailto' ) {
2674 $mailparts = explode( '@', $bits['host'], 2 );
2675 if ( count( $mailparts ) === 2 ) {
2676 $domainpart = strtolower( implode( '.', array_reverse( explode( '.', $mailparts[1] ) ) ) );
2678 // No domain specified, don't mangle it
2681 $reversedHost = $domainpart . '@' . $mailparts[0];
2682 } else if ( isset( $bits['host'] ) ) {
2683 $reversedHost = strtolower( implode( '.', array_reverse( explode( '.', $bits['host'] ) ) ) );
2685 // In file: URIs for instance it's common to have an empty host,
2686 // which turns up as not getting a 'host' member from parse_url.
2687 $reversedHost = '.';
2689 // Add an extra dot to the end
2690 // Why? Is it in wrong place in mailto links?
2691 if ( substr( $reversedHost, -1, 1 ) !== '.' ) {
2692 $reversedHost .= '.';
2694 // Reconstruct the pseudo-URL
2695 $prot = $bits['scheme'];
2696 $index = $prot . $bits['delimiter'] . $reversedHost;
2697 // Leave out user and password. Add the port, path, query and fragment
2698 if ( isset( $bits['port'] ) ) {
2699 $index .= ':' . $bits['port'];
2701 if ( isset( $bits['path'] ) ) {
2702 // parse_url() removes the initial '/' from the path
2703 // for file: URLs with Windows-style paths, such as
2704 // file:///c:/windows/stuff. We need to add it back
2705 // to keep our division between host and path properly.
2706 if ( strlen( $bits['path'] ) > 0 && substr( $bits['path'], 0, 1 ) !== '/' ) {
2709 $index .= $bits['path'];
2713 if ( isset( $bits['query'] ) ) {
2714 $index .= '?' . $bits['query'];
2716 if ( isset( $bits['fragment'] ) ) {
2717 $index .= '#' . $bits['fragment'];
2723 * Do any deferred updates and clear the list
2725 * @param $commit String: set to 'commit' to commit after every update to
2726 * prevent lock contention
2728 function wfDoUpdates( $commit = '' ) {
2729 global $wgDeferredUpdateList;
2731 wfProfileIn( __METHOD__
);
2733 // No need to get master connections in case of empty updates array
2734 if ( !count( $wgDeferredUpdateList ) ) {
2735 wfProfileOut( __METHOD__
);
2739 $doCommit = $commit == 'commit';
2741 $dbw = wfGetDB( DB_MASTER
);
2744 foreach ( $wgDeferredUpdateList as $update ) {
2745 $update->doUpdate();
2747 if ( $doCommit && $dbw->trxLevel() ) {
2752 $wgDeferredUpdateList = array();
2753 wfProfileOut( __METHOD__
);
2757 * Convert an arbitrarily-long digit string from one numeric base
2758 * to another, optionally zero-padding to a minimum column width.
2760 * Supports base 2 through 36; digit values 10-36 are represented
2761 * as lowercase letters a-z. Input is case-insensitive.
2763 * @param $input String: of digits
2764 * @param $sourceBase Integer: 2-36
2765 * @param $destBase Integer: 2-36
2766 * @param $pad Integer: 1 or greater
2767 * @param $lowercase Boolean
2768 * @return String or false on invalid input
2770 function wfBaseConvert( $input, $sourceBase, $destBase, $pad = 1, $lowercase = true ) {
2771 $input = strval( $input );
2772 if( $sourceBase < 2 ||
2777 $sourceBase != intval( $sourceBase ) ||
2778 $destBase != intval( $destBase ) ||
2779 $pad != intval( $pad ) ||
2780 !is_string( $input ) ||
2784 $digitChars = ( $lowercase ) ?
'0123456789abcdefghijklmnopqrstuvwxyz' : '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
2785 $inDigits = array();
2788 // Decode and validate input string
2789 $input = strtolower( $input );
2790 for( $i = 0; $i < strlen( $input ); $i++
) {
2791 $n = strpos( $digitChars, $input[$i] );
2792 if( $n === false ||
$n > $sourceBase ) {
2798 // Iterate over the input, modulo-ing out an output digit
2799 // at a time until input is gone.
2800 while( count( $inDigits ) ) {
2802 $workDigits = array();
2805 foreach( $inDigits as $digit ) {
2806 $work *= $sourceBase;
2809 if( $work < $destBase ) {
2810 // Gonna need to pull another digit.
2811 if( count( $workDigits ) ) {
2812 // Avoid zero-padding; this lets us find
2813 // the end of the input very easily when
2814 // length drops to zero.
2818 // Finally! Actual division!
2819 $workDigits[] = intval( $work / $destBase );
2821 // Isn't it annoying that most programming languages
2822 // don't have a single divide-and-remainder operator,
2823 // even though the CPU implements it that way?
2824 $work = $work %
$destBase;
2828 // All that division leaves us with a remainder,
2829 // which is conveniently our next output digit.
2830 $outChars .= $digitChars[$work];
2833 $inDigits = $workDigits;
2836 while( strlen( $outChars ) < $pad ) {
2840 return strrev( $outChars );
2844 * Create an object with a given name and an array of construct parameters
2846 * @param $name String
2847 * @param $p Array: parameters
2848 * @deprecated since 1.18
2850 function wfCreateObject( $name, $p ) {
2851 return MWFunction
::newObj( $name, $p );
2854 function wfHttpOnlySafe() {
2855 global $wgHttpOnlyBlacklist;
2857 if( isset( $_SERVER['HTTP_USER_AGENT'] ) ) {
2858 foreach( $wgHttpOnlyBlacklist as $regex ) {
2859 if( preg_match( $regex, $_SERVER['HTTP_USER_AGENT'] ) ) {
2869 * Initialise php session
2871 * @param $sessionId Bool
2873 function wfSetupSession( $sessionId = false ) {
2874 global $wgSessionsInMemcached, $wgCookiePath, $wgCookieDomain,
2875 $wgCookieSecure, $wgCookieHttpOnly, $wgSessionHandler;
2876 if( $wgSessionsInMemcached ) {
2877 if ( !defined( 'MW_COMPILED' ) ) {
2879 require_once( "$IP/includes/cache/MemcachedSessions.php" );
2881 session_set_save_handler( 'memsess_open', 'memsess_close', 'memsess_read',
2882 'memsess_write', 'memsess_destroy', 'memsess_gc' );
2884 // It's necessary to register a shutdown function to call session_write_close(),
2885 // because by the time the request shutdown function for the session module is
2886 // called, $wgMemc has already been destroyed. Shutdown functions registered
2887 // this way are called before object destruction.
2888 register_shutdown_function( 'memsess_write_close' );
2889 } elseif( $wgSessionHandler && $wgSessionHandler != ini_get( 'session.save_handler' ) ) {
2890 # Only set this if $wgSessionHandler isn't null and session.save_handler
2891 # hasn't already been set to the desired value (that causes errors)
2892 ini_set( 'session.save_handler', $wgSessionHandler );
2894 $httpOnlySafe = wfHttpOnlySafe() && $wgCookieHttpOnly;
2895 wfDebugLog( 'cookie',
2896 'session_set_cookie_params: "' . implode( '", "',
2902 $httpOnlySafe ) ) . '"' );
2903 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $httpOnlySafe );
2904 session_cache_limiter( 'private, must-revalidate' );
2906 session_id( $sessionId );
2908 wfSuppressWarnings();
2910 wfRestoreWarnings();
2914 * Get an object from the precompiled serialized directory
2916 * @param $name String
2917 * @return Mixed: the variable on success, false on failure
2919 function wfGetPrecompiledData( $name ) {
2922 $file = "$IP/serialized/$name";
2923 if ( file_exists( $file ) ) {
2924 $blob = file_get_contents( $file );
2926 return unserialize( $blob );
2933 * Get the name of the function which called this function
2936 * @return Bool|string
2938 function wfGetCaller( $level = 2 ) {
2939 $backtrace = wfDebugBacktrace();
2940 if ( isset( $backtrace[$level] ) ) {
2941 return wfFormatStackFrame( $backtrace[$level] );
2943 $caller = 'unknown';
2949 * Return a string consisting of callers in the stack. Useful sometimes
2950 * for profiling specific points.
2952 * @param $limit The maximum depth of the stack frame to return, or false for
2956 function wfGetAllCallers( $limit = 3 ) {
2957 $trace = array_reverse( wfDebugBacktrace() );
2958 if ( !$limit ||
$limit > count( $trace ) - 1 ) {
2959 $limit = count( $trace ) - 1;
2961 $trace = array_slice( $trace, -$limit - 1, $limit );
2962 return implode( '/', array_map( 'wfFormatStackFrame', $trace ) );
2966 * Return a string representation of frame
2968 * @param $frame Array
2971 function wfFormatStackFrame( $frame ) {
2972 return isset( $frame['class'] ) ?
2973 $frame['class'] . '::' . $frame['function'] :
2983 function wfMemcKey( /*... */ ) {
2984 $args = func_get_args();
2985 $key = wfWikiID() . ':' . implode( ':', $args );
2986 $key = str_replace( ' ', '_', $key );
2991 * Get a cache key for a foreign DB
2994 * @param $prefix String
2995 * @param varargs String
2998 function wfForeignMemcKey( $db, $prefix /*, ... */ ) {
2999 $args = array_slice( func_get_args(), 2 );
3001 $key = "$db-$prefix:" . implode( ':', $args );
3003 $key = $db . ':' . implode( ':', $args );
3009 * Get an ASCII string identifying this wiki
3010 * This is used as a prefix in memcached keys
3014 function wfWikiID() {
3015 global $wgDBprefix, $wgDBname;
3016 if ( $wgDBprefix ) {
3017 return "$wgDBname-$wgDBprefix";
3024 * Split a wiki ID into DB name and table prefix
3026 * @param $wiki String
3027 * @param $bits String
3029 function wfSplitWikiID( $wiki ) {
3030 $bits = explode( '-', $wiki, 2 );
3031 if ( count( $bits ) < 2 ) {
3038 * Get a Database object.
3040 * @param $db Integer: index of the connection to get. May be DB_MASTER for the
3041 * master (for write queries), DB_SLAVE for potentially lagged read
3042 * queries, or an integer >= 0 for a particular server.
3044 * @param $groups Mixed: query groups. An array of group names that this query
3045 * belongs to. May contain a single string if the query is only
3048 * @param $wiki String: the wiki ID, or false for the current wiki
3050 * Note: multiple calls to wfGetDB(DB_SLAVE) during the course of one request
3051 * will always return the same object, unless the underlying connection or load
3052 * balancer is manually destroyed.
3054 * @return DatabaseBase
3056 function &wfGetDB( $db, $groups = array(), $wiki = false ) {
3057 return wfGetLB( $wiki )->getConnection( $db, $groups, $wiki );
3061 * Get a load balancer object.
3063 * @param $wiki String: wiki ID, or false for the current wiki
3064 * @return LoadBalancer
3066 function wfGetLB( $wiki = false ) {
3067 return wfGetLBFactory()->getMainLB( $wiki );
3071 * Get the load balancer factory object
3075 function &wfGetLBFactory() {
3076 return LBFactory
::singleton();
3081 * Shortcut for RepoGroup::singleton()->findFile()
3083 * @param $title String or Title object
3084 * @param $options Associative array of options:
3085 * time: requested time for an archived image, or false for the
3086 * current version. An image object will be returned which was
3087 * created at the specified time.
3089 * ignoreRedirect: If true, do not follow file redirects
3091 * private: If true, return restricted (deleted) files if the current
3092 * user is allowed to view them. Otherwise, such files will not
3095 * bypassCache: If true, do not use the process-local cache of File objects
3097 * @return File, or false if the file does not exist
3099 function wfFindFile( $title, $options = array() ) {
3100 return RepoGroup
::singleton()->findFile( $title, $options );
3104 * Get an object referring to a locally registered file.
3105 * Returns a valid placeholder object if the file does not exist.
3107 * @param $title Title or String
3108 * @return File, or null if passed an invalid Title
3110 function wfLocalFile( $title ) {
3111 return RepoGroup
::singleton()->getLocalRepo()->newFile( $title );
3115 * Should low-performance queries be disabled?
3118 * @codeCoverageIgnore
3120 function wfQueriesMustScale() {
3121 global $wgMiserMode;
3123 ||
( SiteStats
::pages() > 100000
3124 && SiteStats
::edits() > 1000000
3125 && SiteStats
::users() > 10000 );
3129 * Get the path to a specified script file, respecting file
3130 * extensions; this is a wrapper around $wgScriptExtension etc.
3132 * @param $script String: script filename, sans extension
3135 function wfScript( $script = 'index' ) {
3136 global $wgScriptPath, $wgScriptExtension;
3137 return "{$wgScriptPath}/{$script}{$wgScriptExtension}";
3141 * Get the script URL.
3143 * @return script URL
3145 function wfGetScriptUrl() {
3146 if( isset( $_SERVER['SCRIPT_NAME'] ) ) {
3148 # as it was called, minus the query string.
3150 # Some sites use Apache rewrite rules to handle subdomains,
3151 # and have PHP set up in a weird way that causes PHP_SELF
3152 # to contain the rewritten URL instead of the one that the
3153 # outside world sees.
3155 # If in this mode, use SCRIPT_URL instead, which mod_rewrite
3156 # provides containing the "before" URL.
3157 return $_SERVER['SCRIPT_NAME'];
3159 return $_SERVER['URL'];
3164 * Convenience function converts boolean values into "true"
3165 * or "false" (string) values
3167 * @param $value Boolean
3170 function wfBoolToStr( $value ) {
3171 return $value ?
'true' : 'false';
3175 * Load an extension messages file
3177 * @deprecated since 1.16, warnings in 1.18, remove in 1.20
3178 * @codeCoverageIgnore
3180 function wfLoadExtensionMessages() {
3181 wfDeprecated( __FUNCTION__
);
3185 * Get a platform-independent path to the null file, e.g. /dev/null
3189 function wfGetNull() {
3190 return wfIsWindows()
3196 * Throws a warning that $function is deprecated
3198 * @param $function String
3201 function wfDeprecated( $function ) {
3202 static $functionsWarned = array();
3203 if ( !isset( $functionsWarned[$function] ) ) {
3204 $functionsWarned[$function] = true;
3205 wfWarn( "Use of $function is deprecated.", 2 );
3210 * Send a warning either to the debug log or in a PHP error depending on
3211 * $wgDevelopmentWarnings
3213 * @param $msg String: message to send
3214 * @param $callerOffset Integer: number of items to go back in the backtrace to
3215 * find the correct caller (1 = function calling wfWarn, ...)
3216 * @param $level Integer: PHP error level; only used when $wgDevelopmentWarnings
3219 function wfWarn( $msg, $callerOffset = 1, $level = E_USER_NOTICE
) {
3220 global $wgDevelopmentWarnings;
3222 $callers = wfDebugBacktrace();
3223 if ( isset( $callers[$callerOffset +
1] ) ) {
3224 $callerfunc = $callers[$callerOffset +
1];
3225 $callerfile = $callers[$callerOffset];
3226 if ( isset( $callerfile['file'] ) && isset( $callerfile['line'] ) ) {
3227 $file = $callerfile['file'] . ' at line ' . $callerfile['line'];
3229 $file = '(internal function)';
3232 if ( isset( $callerfunc['class'] ) ) {
3233 $func .= $callerfunc['class'] . '::';
3235 if ( isset( $callerfunc['function'] ) ) {
3236 $func .= $callerfunc['function'];
3238 $msg .= " [Called from $func in $file]";
3241 if ( $wgDevelopmentWarnings ) {
3242 trigger_error( $msg, $level );
3244 wfDebug( "$msg\n" );
3249 * Modern version of wfWaitForSlaves(). Instead of looking at replication lag
3250 * and waiting for it to go down, this waits for the slaves to catch up to the
3251 * master position. Use this when updating very large numbers of rows, as
3252 * in maintenance scripts, to avoid causing too much lag. Of course, this is
3253 * a no-op if there are no slaves.
3255 * @param $maxLag Integer (deprecated)
3256 * @param $wiki mixed Wiki identifier accepted by wfGetLB
3259 function wfWaitForSlaves( $maxLag = false, $wiki = false ) {
3260 $lb = wfGetLB( $wiki );
3261 // bug 27975 - Don't try to wait for slaves if there are none
3262 // Prevents permission error when getting master position
3263 if ( $lb->getServerCount() > 1 ) {
3264 $dbw = $lb->getConnection( DB_MASTER
);
3265 $pos = $dbw->getMasterPos();
3266 $lb->waitForAll( $pos );
3271 * Used to be used for outputting text in the installer/updater
3272 * @deprecated since 1.18, warnings in 1.19, remove in 1.20
3274 function wfOut( $s ) {
3275 wfDeprecated( __METHOD__
);
3276 global $wgCommandLineMode;
3277 if ( $wgCommandLineMode && !defined( 'MEDIAWIKI_INSTALL' ) ) {
3280 echo htmlspecialchars( $s );
3286 * Count down from $n to zero on the terminal, with a one-second pause
3287 * between showing each number. For use in command-line scripts.
3288 * @codeCoverageIgnore
3290 function wfCountDown( $n ) {
3291 for ( $i = $n; $i >= 0; $i-- ) {
3293 echo str_repeat( "\x08", strlen( $i +
1 ) );
3305 * Generate a random 32-character hexadecimal token.
3306 * @param $salt Mixed: some sort of salt, if necessary, to add to random
3307 * characters before hashing.
3309 * @codeCoverageIgnore
3311 function wfGenerateToken( $salt = '' ) {
3312 $salt = serialize( $salt );
3313 return md5( mt_rand( 0, 0x7fffffff ) . $salt );
3317 * Replace all invalid characters with -
3319 * @param $name Mixed: filename to process
3322 function wfStripIllegalFilenameChars( $name ) {
3323 global $wgIllegalFileChars;
3324 $name = wfBaseName( $name );
3325 $name = preg_replace(
3326 "/[^" . Title
::legalChars() . "]" .
3327 ( $wgIllegalFileChars ?
"|[" . $wgIllegalFileChars . "]" : '' ) .
3336 * Insert array into another array after the specified *KEY*
3338 * @param $array Array: The array.
3339 * @param $insert Array: The array to insert.
3340 * @param $after Mixed: The key to insert after
3343 function wfArrayInsertAfter( $array, $insert, $after ) {
3344 // Find the offset of the element to insert after.
3345 $keys = array_keys( $array );
3346 $offsetByKey = array_flip( $keys );
3348 $offset = $offsetByKey[$after];
3350 // Insert at the specified offset
3351 $before = array_slice( $array, 0, $offset +
1, true );
3352 $after = array_slice( $array, $offset +
1, count( $array ) - $offset, true );
3354 $output = $before +
$insert +
$after;
3360 * Recursively converts the parameter (an object) to an array with the same data
3362 * @param $objOrArray Object|Array
3363 * @param $recursive Bool
3366 function wfObjectToArray( $objOrArray, $recursive = true ) {
3368 if( is_object( $objOrArray ) ) {
3369 $objOrArray = get_object_vars( $objOrArray );
3371 foreach ( $objOrArray as $key => $value ) {
3372 if ( $recursive && ( is_object( $value ) ||
is_array( $value ) ) ) {
3373 $value = wfObjectToArray( $value );
3376 $array[$key] = $value;
3383 * Set PHP's memory limit to the larger of php.ini or $wgMemoryLimit;
3385 * @return Integer value memory was set to.
3387 function wfMemoryLimit() {
3388 global $wgMemoryLimit;
3389 $memlimit = wfShorthandToInteger( ini_get( 'memory_limit' ) );
3390 if( $memlimit != -1 ) {
3391 $conflimit = wfShorthandToInteger( $wgMemoryLimit );
3392 if( $conflimit == -1 ) {
3393 wfDebug( "Removing PHP's memory limit\n" );
3394 wfSuppressWarnings();
3395 ini_set( 'memory_limit', $conflimit );
3396 wfRestoreWarnings();
3398 } elseif ( $conflimit > $memlimit ) {
3399 wfDebug( "Raising PHP's memory limit to $conflimit bytes\n" );
3400 wfSuppressWarnings();
3401 ini_set( 'memory_limit', $conflimit );
3402 wfRestoreWarnings();
3410 * Converts shorthand byte notation to integer form
3412 * @param $string String
3415 function wfShorthandToInteger( $string = '' ) {
3416 $string = trim( $string );
3417 if( $string === '' ) {
3420 $last = $string[strlen( $string ) - 1];
3421 $val = intval( $string );
3426 // break intentionally missing
3430 // break intentionally missing
3440 * Get the normalised IETF language tag
3441 * See unit test for examples.
3443 * @param $code String: The language code.
3444 * @return $langCode String: The language code which complying with BCP 47 standards.
3446 function wfBCP47( $code ) {
3447 $codeSegment = explode( '-', $code );
3449 foreach ( $codeSegment as $segNo => $seg ) {
3450 if ( count( $codeSegment ) > 0 ) {
3451 // when previous segment is x, it is a private segment and should be lc
3452 if( $segNo > 0 && strtolower( $codeSegment[($segNo - 1)] ) == 'x') {
3453 $codeBCP[$segNo] = strtolower( $seg );
3454 // ISO 3166 country code
3455 } elseif ( ( strlen( $seg ) == 2 ) && ( $segNo > 0 ) ) {
3456 $codeBCP[$segNo] = strtoupper( $seg );
3457 // ISO 15924 script code
3458 } elseif ( ( strlen( $seg ) == 4 ) && ( $segNo > 0 ) ) {
3459 $codeBCP[$segNo] = ucfirst( strtolower( $seg ) );
3460 // Use lowercase for other cases
3462 $codeBCP[$segNo] = strtolower( $seg );
3465 // Use lowercase for single segment
3466 $codeBCP[$segNo] = strtolower( $seg );
3469 $langCode = implode( '-', $codeBCP );
3474 * Wrapper around array_map() which also taints variables
3476 * @param $function Callback
3477 * @param $input Array
3480 function wfArrayMap( $function, $input ) {
3481 $ret = array_map( $function, $input );
3482 foreach ( $ret as $key => $value ) {
3483 $taint = istainted( $input[$key] );
3485 taint( $ret[$key], $taint );
3493 * Get a cache object.
3495 * @param integer $inputType Cache type, one the the CACHE_* constants.
3498 function wfGetCache( $inputType ) {
3499 return ObjectCache
::getInstance( $inputType );
3503 * Get the main cache object
3507 function wfGetMainCache() {
3508 global $wgMainCacheType;
3509 return ObjectCache
::getInstance( $wgMainCacheType );
3513 * Get the cache object used by the message cache
3517 function wfGetMessageCacheStorage() {
3518 global $wgMessageCacheType;
3519 return ObjectCache
::getInstance( $wgMessageCacheType );
3523 * Get the cache object used by the parser cache
3527 function wfGetParserCacheStorage() {
3528 global $wgParserCacheType;
3529 return ObjectCache
::getInstance( $wgParserCacheType );