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 );
108 * Returns an array where the values in the first array are replaced by the
109 * values in the second array with the corresponding keys
115 function wfArrayLookup( $a, $b ) {
116 return array_flip( array_intersect( array_flip( $a ), array_keys( $b ) ) );
120 * Appends to second array if $value differs from that in $default
122 * @param $key String|Int
123 * @param $value Mixed
124 * @param $default Mixed
125 * @param $changed Array to alter
127 function wfAppendToArrayIfNotDefault( $key, $value, $default, &$changed ) {
128 if ( is_null( $changed ) ) {
129 throw new MWException( 'GlobalFunctions::wfAppendToArrayIfNotDefault got null' );
131 if ( $default[$key] !== $value ) {
132 $changed[$key] = $value;
137 * Backwards array plus for people who haven't bothered to read the PHP manual
138 * XXX: will not darn your socks for you.
140 * @param $array1 Array
141 * @param [$array2, [...]] Arrays
144 function wfArrayMerge( $array1/* ... */ ) {
145 $args = func_get_args();
146 $args = array_reverse( $args, true );
148 foreach ( $args as $arg ) {
155 * Merge arrays in the style of getUserPermissionsErrors, with duplicate removal
157 * wfMergeErrorArrays(
158 * array( array( 'x' ) ),
159 * array( array( 'x', '2' ) ),
160 * array( array( 'x' ) ),
161 * array( array( 'y') )
172 function wfMergeErrorArrays( /*...*/ ) {
173 $args = func_get_args();
175 foreach ( $args as $errors ) {
176 foreach ( $errors as $params ) {
177 # @todo FIXME: Sometimes get nested arrays for $params,
178 # which leads to E_NOTICEs
179 $spec = implode( "\t", $params );
180 $out[$spec] = $params;
183 return array_values( $out );
187 * Insert array into another array after the specified *KEY*
189 * @param $array Array: The array.
190 * @param $insert Array: The array to insert.
191 * @param $after Mixed: The key to insert after
194 function wfArrayInsertAfter( $array, $insert, $after ) {
195 // Find the offset of the element to insert after.
196 $keys = array_keys( $array );
197 $offsetByKey = array_flip( $keys );
199 $offset = $offsetByKey[$after];
201 // Insert at the specified offset
202 $before = array_slice( $array, 0, $offset +
1, true );
203 $after = array_slice( $array, $offset +
1, count( $array ) - $offset, true );
205 $output = $before +
$insert +
$after;
211 * Recursively converts the parameter (an object) to an array with the same data
213 * @param $objOrArray Object|Array
214 * @param $recursive Bool
217 function wfObjectToArray( $objOrArray, $recursive = true ) {
219 if( is_object( $objOrArray ) ) {
220 $objOrArray = get_object_vars( $objOrArray );
222 foreach ( $objOrArray as $key => $value ) {
223 if ( $recursive && ( is_object( $value ) ||
is_array( $value ) ) ) {
224 $value = wfObjectToArray( $value );
227 $array[$key] = $value;
234 * Wrapper around array_map() which also taints variables
236 * @param $function Callback
237 * @param $input Array
240 function wfArrayMap( $function, $input ) {
241 $ret = array_map( $function, $input );
242 foreach ( $ret as $key => $value ) {
243 $taint = istainted( $input[$key] );
245 taint( $ret[$key], $taint );
252 * Get a random decimal value between 0 and 1, in a way
253 * not likely to give duplicate values for any realistic
254 * number of articles.
258 function wfRandom() {
259 # The maximum random value is "only" 2^31-1, so get two random
260 # values to reduce the chance of dupes
261 $max = mt_getrandmax() +
1;
262 $rand = number_format( ( mt_rand() * $max +
mt_rand() )
263 / $max / $max, 12, '.', '' );
268 * We want some things to be included as literal characters in our title URLs
269 * for prettiness, which urlencode encodes by default. According to RFC 1738,
270 * all of the following should be safe:
274 * But + is not safe because it's used to indicate a space; &= are only safe in
275 * paths and not in queries (and we don't distinguish here); ' seems kind of
276 * scary; and urlencode() doesn't touch -_. to begin with. Plus, although /
277 * is reserved, we don't care. So the list we unescape is:
281 * However, IIS7 redirects fail when the url contains a colon (Bug 22709),
282 * so no fancy : for IIS7.
284 * %2F in the page titles seems to fatally break for some reason.
289 function wfUrlencode( $s ) {
291 if ( is_null( $needle ) ) {
292 $needle = array( '%3B', '%40', '%24', '%21', '%2A', '%28', '%29', '%2C', '%2F' );
293 if ( !isset( $_SERVER['SERVER_SOFTWARE'] ) ||
( strpos( $_SERVER['SERVER_SOFTWARE'], 'Microsoft-IIS/7' ) === false ) ) {
298 $s = urlencode( $s );
301 array( ';', '@', '$', '!', '*', '(', ')', ',', '/', ':' ),
309 * Sends a line to the debug log if enabled or, optionally, to a comment in output.
310 * In normal operation this is a NOP.
312 * Controlling globals:
313 * $wgDebugLogFile - points to the log file
314 * $wgProfileOnly - if set, normal debug messages will not be recorded.
315 * $wgDebugRawPage - if false, 'action=raw' hits will not result in debug output.
316 * $wgDebugComments - if on, some debug items may appear in comments in the HTML output.
318 * @param $text String
319 * @param $logonly Bool: set true to avoid appearing in HTML when $wgDebugComments is set
321 function wfDebug( $text, $logonly = false ) {
322 global $wgOut, $wgDebugLogFile, $wgDebugComments, $wgProfileOnly, $wgDebugRawPage;
323 global $wgDebugLogPrefix, $wgShowDebug;
325 static $cache = array(); // Cache of unoutputted messages
326 $text = wfDebugTimer() . $text;
328 # Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
329 if ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' && !$wgDebugRawPage ) {
333 if ( ( $wgDebugComments ||
$wgShowDebug ) && !$logonly ) {
336 if ( isset( $wgOut ) && is_object( $wgOut ) ) {
337 // add the message and any cached messages to the output
338 array_map( array( $wgOut, 'debug' ), $cache );
342 if ( $wgDebugLogFile != '' && !$wgProfileOnly ) {
343 # Strip unprintables; they can switch terminal modes when binary data
344 # gets dumped, which is pretty annoying.
345 $text = preg_replace( '![\x00-\x08\x0b\x0c\x0e-\x1f]!', ' ', $text );
346 $text = $wgDebugLogPrefix . $text;
347 wfErrorLog( $text, $wgDebugLogFile );
352 * Get microsecond timestamps for debug logs
356 function wfDebugTimer() {
357 global $wgDebugTimestamps;
358 if ( !$wgDebugTimestamps ) {
361 static $start = null;
363 if ( $start === null ) {
364 $start = microtime( true );
365 $prefix = "\n$start";
367 $prefix = sprintf( "%6.4f", microtime( true ) - $start );
370 return $prefix . ' ';
374 * Send a line giving PHP memory usage.
376 * @param $exact Bool: print exact values instead of kilobytes (default: false)
378 function wfDebugMem( $exact = false ) {
379 $mem = memory_get_usage();
381 $mem = floor( $mem / 1024 ) . ' kilobytes';
385 wfDebug( "Memory usage: $mem\n" );
389 * Send a line to a supplementary debug log file, if configured, or main debug log if not.
390 * $wgDebugLogGroups[$logGroup] should be set to a filename to send to a separate log.
392 * @param $logGroup String
393 * @param $text String
394 * @param $public Bool: whether to log the event in the public log if no private
395 * log file is specified, (default true)
397 function wfDebugLog( $logGroup, $text, $public = true ) {
398 global $wgDebugLogGroups, $wgShowHostnames;
399 $text = trim( $text ) . "\n";
400 if( isset( $wgDebugLogGroups[$logGroup] ) ) {
401 $time = wfTimestamp( TS_DB
);
403 if ( $wgShowHostnames ) {
404 $host = wfHostname();
408 wfErrorLog( "$time $host $wiki: $text", $wgDebugLogGroups[$logGroup] );
409 } elseif ( $public === true ) {
410 wfDebug( $text, true );
415 * Log for database errors
417 * @param $text String: database error message.
419 function wfLogDBError( $text ) {
420 global $wgDBerrorLog, $wgDBname;
421 if ( $wgDBerrorLog ) {
422 $host = trim(`hostname`
);
423 $text = date( 'D M j G:i:s T Y' ) . "\t$host\t$wgDBname\t$text";
424 wfErrorLog( $text, $wgDBerrorLog );
429 * Log to a file without getting "file size exceeded" signals.
431 * Can also log to TCP or UDP with the syntax udp://host:port/prefix. This will
432 * send lines to the specified port, prefixed by the specified prefix and a space.
434 * @param $text String
435 * @param $file String filename
437 function wfErrorLog( $text, $file ) {
438 if ( substr( $file, 0, 4 ) == 'udp:' ) {
439 # Needs the sockets extension
440 if ( preg_match( '!^(tcp|udp):(?://)?\[([0-9a-fA-F:]+)\]:(\d+)(?:/(.*))?$!', $file, $m ) ) {
441 // IPv6 bracketed host
443 $port = intval( $m[3] );
444 $prefix = isset( $m[4] ) ?
$m[4] : false;
446 } elseif ( preg_match( '!^(tcp|udp):(?://)?([a-zA-Z0-9.-]+):(\d+)(?:/(.*))?$!', $file, $m ) ) {
448 if ( !IP
::isIPv4( $host ) ) {
449 $host = gethostbyname( $host );
451 $port = intval( $m[3] );
452 $prefix = isset( $m[4] ) ?
$m[4] : false;
455 throw new MWException( __METHOD__
. ': Invalid UDP specification' );
458 // Clean it up for the multiplexer
459 if ( strval( $prefix ) !== '' ) {
460 $text = preg_replace( '/^/m', $prefix . ' ', $text );
463 if ( strlen( $text ) > 65534 ) {
464 $text = substr( $text, 0, 65534 );
467 if ( substr( $text, -1 ) != "\n" ) {
470 } elseif ( strlen( $text ) > 65535 ) {
471 $text = substr( $text, 0, 65535 );
474 $sock = socket_create( $domain, SOCK_DGRAM
, SOL_UDP
);
478 socket_sendto( $sock, $text, strlen( $text ), 0, $host, $port );
479 socket_close( $sock );
481 wfSuppressWarnings();
482 $exists = file_exists( $file );
483 $size = $exists ?
filesize( $file ) : false;
484 if ( !$exists ||
( $size !== false && $size +
strlen( $text ) < 0x7fffffff ) ) {
485 file_put_contents( $file, $text, FILE_APPEND
);
494 function wfLogProfilingData() {
495 global $wgRequestTime, $wgDebugLogFile, $wgDebugRawPage, $wgRequest;
496 global $wgProfileLimit, $wgUser;
498 $profiler = Profiler
::instance();
500 # Profiling must actually be enabled...
501 if ( $profiler->isStub() ) {
505 // Get total page request time and only show pages that longer than
506 // $wgProfileLimit time (default is 0)
508 $elapsed = $now - $wgRequestTime;
509 if ( $elapsed <= $wgProfileLimit ) {
513 $profiler->logData();
515 // Check whether this should be logged in the debug file.
516 if ( $wgDebugLogFile == '' ||
( $wgRequest->getVal( 'action' ) == 'raw' && !$wgDebugRawPage ) ) {
521 if ( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) {
522 $forward = ' forwarded for ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
524 if ( !empty( $_SERVER['HTTP_CLIENT_IP'] ) ) {
525 $forward .= ' client IP ' . $_SERVER['HTTP_CLIENT_IP'];
527 if ( !empty( $_SERVER['HTTP_FROM'] ) ) {
528 $forward .= ' from ' . $_SERVER['HTTP_FROM'];
531 $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
533 // Don't load $wgUser at this late stage just for statistics purposes
534 // @todo FIXME: We can detect some anons even if it is not loaded. See User::getId()
535 if ( $wgUser->isItemLoaded( 'id' ) && $wgUser->isAnon() ) {
538 $log = sprintf( "%s\t%04.3f\t%s\n",
539 gmdate( 'YmdHis' ), $elapsed,
540 urldecode( $wgRequest->getRequestURL() . $forward ) );
542 wfErrorLog( $log . $profiler->getOutput(), $wgDebugLogFile );
546 * Check if the wiki read-only lock file is present. This can be used to lock
547 * off editing functions, but doesn't guarantee that the database will not be
552 function wfReadOnly() {
553 global $wgReadOnlyFile, $wgReadOnly;
555 if ( !is_null( $wgReadOnly ) ) {
556 return (bool)$wgReadOnly;
558 if ( $wgReadOnlyFile == '' ) {
561 // Set $wgReadOnly for faster access next time
562 if ( is_file( $wgReadOnlyFile ) ) {
563 $wgReadOnly = file_get_contents( $wgReadOnlyFile );
567 return (bool)$wgReadOnly;
570 function wfReadOnlyReason() {
577 * Return a Language object from $langcode
579 * @param $langcode Mixed: either:
580 * - a Language object
581 * - code of the language to get the message for, if it is
582 * a valid code create a language for that language, if
583 * it is a string but not a valid code then make a basic
585 * - a boolean: if it's false then use the current users
586 * language (as a fallback for the old parameter
587 * functionality), or if it is true then use the wikis
588 * @return Language object
590 function wfGetLangObj( $langcode = false ) {
591 # Identify which language to get or create a language object for.
592 # Using is_object here due to Stub objects.
593 if( is_object( $langcode ) ) {
594 # Great, we already have the object (hopefully)!
598 global $wgContLang, $wgLanguageCode;
599 if( $langcode === true ||
$langcode === $wgLanguageCode ) {
600 # $langcode is the language code of the wikis content language object.
601 # or it is a boolean and value is true
606 if( $langcode === false ||
$langcode === $wgLang->getCode() ) {
607 # $langcode is the language code of user language object.
608 # or it was a boolean and value is false
612 $validCodes = array_keys( Language
::getLanguageNames() );
613 if( in_array( $langcode, $validCodes ) ) {
614 # $langcode corresponds to a valid language.
615 return Language
::factory( $langcode );
618 # $langcode is a string, but not a valid language code; use content language.
619 wfDebug( "Invalid language code passed to wfGetLangObj, falling back to content language.\n" );
624 * Use this instead of $wgContLang, when working with user interface.
625 * User interface is currently hard coded according to wiki content language
626 * in many ways, especially regarding to text direction. There is lots stuff
627 * to fix, hence this function to keep the old behaviour unless the global
628 * $wgBetterDirectionality is enabled (or removed when everything works).
632 function wfUILang() {
633 global $wgBetterDirectionality;
634 return wfGetLangObj( !$wgBetterDirectionality );
638 * This is the new function for getting translated interface messages.
639 * See the Message class for documentation how to use them.
640 * The intention is that this function replaces all old wfMsg* functions.
641 * @param $key \string Message key.
642 * Varargs: normal message parameters.
646 function wfMessage( $key /*...*/) {
647 $params = func_get_args();
648 array_shift( $params );
649 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
650 $params = $params[0];
652 return new Message( $key, $params );
656 * This function accepts multiple message keys and returns a message instance
657 * for the first message which is non-empty. If all messages are empty then an
658 * instance of the first message key is returned.
659 * @param varargs: message keys
663 function wfMessageFallback( /*...*/ ) {
664 $args = func_get_args();
665 return MWFunction
::callArray( 'Message::newFallbackSequence', $args );
669 * Get a message from anywhere, for the current user language.
671 * Use wfMsgForContent() instead if the message should NOT
672 * change depending on the user preferences.
674 * @param $key String: lookup key for the message, usually
675 * defined in languages/Language.php
677 * This function also takes extra optional parameters (not
678 * shown in the function definition), which can be used to
679 * insert variable text into the predefined message.
682 function wfMsg( $key ) {
683 $args = func_get_args();
684 array_shift( $args );
685 return wfMsgReal( $key, $args, true );
689 * Same as above except doesn't transform the message
694 function wfMsgNoTrans( $key ) {
695 $args = func_get_args();
696 array_shift( $args );
697 return wfMsgReal( $key, $args, true, false, false );
701 * Get a message from anywhere, for the current global language
702 * set with $wgLanguageCode.
704 * Use this if the message should NOT change dependent on the
705 * language set in the user's preferences. This is the case for
706 * most text written into logs, as well as link targets (such as
707 * the name of the copyright policy page). Link titles, on the
708 * other hand, should be shown in the UI language.
710 * Note that MediaWiki allows users to change the user interface
711 * language in their preferences, but a single installation
712 * typically only contains content in one language.
714 * Be wary of this distinction: If you use wfMsg() where you should
715 * use wfMsgForContent(), a user of the software may have to
716 * customize potentially hundreds of messages in
717 * order to, e.g., fix a link in every possible language.
719 * @param $key String: lookup key for the message, usually
720 * defined in languages/Language.php
723 function wfMsgForContent( $key ) {
724 global $wgForceUIMsgAsContentMsg;
725 $args = func_get_args();
726 array_shift( $args );
728 if( is_array( $wgForceUIMsgAsContentMsg ) &&
729 in_array( $key, $wgForceUIMsgAsContentMsg ) )
733 return wfMsgReal( $key, $args, true, $forcontent );
737 * Same as above except doesn't transform the message
742 function wfMsgForContentNoTrans( $key ) {
743 global $wgForceUIMsgAsContentMsg;
744 $args = func_get_args();
745 array_shift( $args );
747 if( is_array( $wgForceUIMsgAsContentMsg ) &&
748 in_array( $key, $wgForceUIMsgAsContentMsg ) )
752 return wfMsgReal( $key, $args, true, $forcontent, false );
756 * Get a message from the language file, for the UI elements
758 * @deprecated since 1.18; use wfMessage()
760 function wfMsgNoDB( $key ) {
761 wfDeprecated( __FUNCTION__
);
762 $args = func_get_args();
763 array_shift( $args );
764 return wfMsgReal( $key, $args, false );
768 * Get a message from the language file, for the content
770 * @deprecated since 1.18; use wfMessage()
772 function wfMsgNoDBForContent( $key ) {
773 wfDeprecated( __FUNCTION__
);
774 global $wgForceUIMsgAsContentMsg;
775 $args = func_get_args();
776 array_shift( $args );
778 if( is_array( $wgForceUIMsgAsContentMsg ) &&
779 in_array( $key, $wgForceUIMsgAsContentMsg ) )
783 return wfMsgReal( $key, $args, false, $forcontent );
788 * Really get a message
790 * @param $key String: key to get.
792 * @param $useDB Boolean
793 * @param $forContent Mixed: Language code, or false for user lang, true for content lang.
794 * @param $transform Boolean: Whether or not to transform the message.
795 * @return String: the requested message.
797 function wfMsgReal( $key, $args, $useDB = true, $forContent = false, $transform = true ) {
798 wfProfileIn( __METHOD__
);
799 $message = wfMsgGetKey( $key, $useDB, $forContent, $transform );
800 $message = wfMsgReplaceArgs( $message, $args );
801 wfProfileOut( __METHOD__
);
806 * This function provides the message source for messages to be edited which are *not* stored in the database.
808 * @deprecated since 1.18; use wfMessage()
811 function wfMsgWeirdKey( $key ) {
812 wfDeprecated( __FUNCTION__
);
813 $source = wfMsgGetKey( $key, false, true, false );
814 if ( wfEmptyMsg( $key ) ) {
822 * Fetch a message string value, but don't replace any keys yet.
826 * @param $langCode String: Code of the language to get the message for, or
827 * behaves as a content language switch if it is a boolean.
828 * @param $transform Boolean: whether to parse magic words, etc.
831 function wfMsgGetKey( $key, $useDB, $langCode = false, $transform = true ) {
832 wfRunHooks( 'NormalizeMessageKey', array( &$key, &$useDB, &$langCode, &$transform ) );
834 $cache = MessageCache
::singleton();
835 $message = $cache->get( $key, $useDB, $langCode );
836 if( $message === false ) {
837 $message = '<' . htmlspecialchars( $key ) . '>';
838 } elseif ( $transform ) {
839 $message = $cache->transform( $message );
845 * Replace message parameter keys on the given formatted output.
847 * @param $message String
852 function wfMsgReplaceArgs( $message, $args ) {
853 # Fix windows line-endings
854 # Some messages are split with explode("\n", $msg)
855 $message = str_replace( "\r", '', $message );
858 if ( count( $args ) ) {
859 if ( is_array( $args[0] ) ) {
860 $args = array_values( $args[0] );
862 $replacementKeys = array();
863 foreach( $args as $n => $param ) {
864 $replacementKeys['$' . ( $n +
1 )] = $param;
866 $message = strtr( $message, $replacementKeys );
873 * Return an HTML-escaped version of a message.
874 * Parameter replacements, if any, are done *after* the HTML-escaping,
875 * so parameters may contain HTML (eg links or form controls). Be sure
876 * to pre-escape them if you really do want plaintext, or just wrap
877 * the whole thing in htmlspecialchars().
880 * @param string ... parameters
883 function wfMsgHtml( $key ) {
884 $args = func_get_args();
885 array_shift( $args );
886 return wfMsgReplaceArgs( htmlspecialchars( wfMsgGetKey( $key, true ) ), $args );
890 * Return an HTML version of message
891 * Parameter replacements, if any, are done *after* parsing the wiki-text message,
892 * so parameters may contain HTML (eg links or form controls). Be sure
893 * to pre-escape them if you really do want plaintext, or just wrap
894 * the whole thing in htmlspecialchars().
897 * @param string ... parameters
900 function wfMsgWikiHtml( $key ) {
901 $args = func_get_args();
902 array_shift( $args );
903 return wfMsgReplaceArgs(
904 MessageCache
::singleton()->parse( wfMsgGetKey( $key, true ), null, /* can't be set to false */ true )->getText(),
909 * Returns message in the requested format
910 * @param $key String: key of the message
911 * @param $options Array: processing rules. Can take the following options:
912 * <i>parse</i>: parses wikitext to HTML
913 * <i>parseinline</i>: parses wikitext to HTML and removes the surrounding
914 * p's added by parser or tidy
915 * <i>escape</i>: filters message through htmlspecialchars
916 * <i>escapenoentities</i>: same, but allows entity references like   through
917 * <i>replaceafter</i>: parameters are substituted after parsing or escaping
918 * <i>parsemag</i>: transform the message using magic phrases
919 * <i>content</i>: fetch message for content language instead of interface
920 * Also can accept a single associative argument, of the form 'language' => 'xx':
921 * <i>language</i>: Language object or language code to fetch message for
922 * (overriden by <i>content</i>).
923 * Behavior for conflicting options (e.g., parse+parseinline) is undefined.
927 function wfMsgExt( $key, $options ) {
928 $args = func_get_args();
929 array_shift( $args );
930 array_shift( $args );
931 $options = (array)$options;
933 foreach( $options as $arrayKey => $option ) {
934 if( !preg_match( '/^[0-9]+|language$/', $arrayKey ) ) {
935 # An unknown index, neither numeric nor "language"
936 wfWarn( "wfMsgExt called with incorrect parameter key $arrayKey", 1, E_USER_WARNING
);
937 } elseif( preg_match( '/^[0-9]+$/', $arrayKey ) && !in_array( $option,
938 array( 'parse', 'parseinline', 'escape', 'escapenoentities',
939 'replaceafter', 'parsemag', 'content' ) ) ) {
940 # A numeric index with unknown value
941 wfWarn( "wfMsgExt called with incorrect parameter $option", 1, E_USER_WARNING
);
945 if( in_array( 'content', $options, true ) ) {
949 } elseif( array_key_exists( 'language', $options ) ) {
951 $langCode = wfGetLangObj( $options['language'] );
952 $langCodeObj = $langCode;
959 $string = wfMsgGetKey( $key, /*DB*/true, $langCode, /*Transform*/false );
961 if( !in_array( 'replaceafter', $options, true ) ) {
962 $string = wfMsgReplaceArgs( $string, $args );
965 $messageCache = MessageCache
::singleton();
966 if( in_array( 'parse', $options, true ) ) {
967 $string = $messageCache->parse( $string, null, true, !$forContent, $langCodeObj )->getText();
968 } elseif ( in_array( 'parseinline', $options, true ) ) {
969 $string = $messageCache->parse( $string, null, true, !$forContent, $langCodeObj )->getText();
971 if( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $string, $m ) ) {
974 } elseif ( in_array( 'parsemag', $options, true ) ) {
975 $string = $messageCache->transform( $string,
976 !$forContent, $langCodeObj );
979 if ( in_array( 'escape', $options, true ) ) {
980 $string = htmlspecialchars ( $string );
981 } elseif ( in_array( 'escapenoentities', $options, true ) ) {
982 $string = Sanitizer
::escapeHtmlAllowEntities( $string );
985 if( in_array( 'replaceafter', $options, true ) ) {
986 $string = wfMsgReplaceArgs( $string, $args );
993 * Since wfMsg() and co suck, they don't return false if the message key they
994 * looked up didn't exist but a XHTML string, this function checks for the
995 * nonexistance of messages by checking the MessageCache::get() result directly.
997 * @param $key String: the message key looked up
998 * @return Boolean True if the message *doesn't* exist.
1000 function wfEmptyMsg( $key ) {
1001 return MessageCache
::singleton()->get( $key, /*useDB*/true, /*content*/false ) === false;
1005 * Print an error message and die, returning nonzero to the shell if any. Plain die()
1006 * fails to return nonzero to the shell if you pass a string. Entry points may customise
1007 * this function to return a prettier error message, but implementations must not assume
1008 * access to any of the usual MediaWiki infrastructure (AutoLoader, localisation, database,
1009 * etc). This should not be called directly once $wgFullyInitialised is set; instead,
1010 * throw an exception and let Exception.php handle whether or not it's possible to show
1013 * @param $msg String
1015 if( !function_exists( 'wfDie' ) ){
1016 function wfDie( $msg = '' ) {
1023 * Throw a debugging exception. This function previously once exited the process,
1024 * but now throws an exception instead, with similar results.
1026 * @param $msg String: message shown when dieing.
1028 function wfDebugDieBacktrace( $msg = '' ) {
1029 throw new MWException( $msg );
1033 * Fetch server name for use in error reporting etc.
1034 * Use real server name if available, so we know which machine
1035 * in a server farm generated the current page.
1039 function wfHostname() {
1041 if ( is_null( $host ) ) {
1042 if ( function_exists( 'posix_uname' ) ) {
1043 // This function not present on Windows
1044 $uname = @posix_uname
();
1048 if( is_array( $uname ) && isset( $uname['nodename'] ) ) {
1049 $host = $uname['nodename'];
1050 } elseif ( getenv( 'COMPUTERNAME' ) ) {
1051 # Windows computer name
1052 $host = getenv( 'COMPUTERNAME' );
1054 # This may be a virtual server.
1055 $host = $_SERVER['SERVER_NAME'];
1062 * Returns a HTML comment with the elapsed time since request.
1063 * This method has no side effects.
1067 function wfReportTime() {
1068 global $wgRequestTime, $wgShowHostnames;
1071 $elapsed = $now - $wgRequestTime;
1073 return $wgShowHostnames
1074 ?
sprintf( '<!-- Served by %s in %01.3f secs. -->', wfHostname(), $elapsed )
1075 : sprintf( '<!-- Served in %01.3f secs. -->', $elapsed );
1079 * Safety wrapper for debug_backtrace().
1081 * With Zend Optimizer 3.2.0 loaded, this causes segfaults under somewhat
1082 * murky circumstances, which may be triggered in part by stub objects
1083 * or other fancy talkin'.
1085 * Will return an empty array if Zend Optimizer is detected or if
1086 * debug_backtrace is disabled, otherwise the output from
1087 * debug_backtrace() (trimmed).
1089 * @return array of backtrace information
1091 function wfDebugBacktrace() {
1092 static $disabled = null;
1094 if( extension_loaded( 'Zend Optimizer' ) ) {
1095 wfDebug( "Zend Optimizer detected; skipping debug_backtrace for safety.\n" );
1099 if ( is_null( $disabled ) ) {
1101 $functions = explode( ',', ini_get( 'disable_functions' ) );
1102 $functions = array_map( 'trim', $functions );
1103 $functions = array_map( 'strtolower', $functions );
1104 if ( in_array( 'debug_backtrace', $functions ) ) {
1105 wfDebug( "debug_backtrace is in disabled_functions\n" );
1113 return array_slice( debug_backtrace(), 1 );
1117 * Get a debug backtrace as a string
1121 function wfBacktrace() {
1122 global $wgCommandLineMode;
1124 if ( $wgCommandLineMode ) {
1129 $backtrace = wfDebugBacktrace();
1130 foreach( $backtrace as $call ) {
1131 if( isset( $call['file'] ) ) {
1132 $f = explode( DIRECTORY_SEPARATOR
, $call['file'] );
1133 $file = $f[count( $f ) - 1];
1137 if( isset( $call['line'] ) ) {
1138 $line = $call['line'];
1142 if ( $wgCommandLineMode ) {
1143 $msg .= "$file line $line calls ";
1145 $msg .= '<li>' . $file . ' line ' . $line . ' calls ';
1147 if( !empty( $call['class'] ) ) {
1148 $msg .= $call['class'] . '::';
1150 $msg .= $call['function'] . '()';
1152 if ( $wgCommandLineMode ) {
1158 if ( $wgCommandLineMode ) {
1168 /* Some generic result counters, pulled out of SearchEngine */
1174 * @param $offset Int
1178 function wfShowingResults( $offset, $limit ) {
1182 array( 'parseinline' ),
1183 $wgLang->formatNum( $limit ),
1184 $wgLang->formatNum( $offset +
1 )
1191 * @param $offset Int
1196 function wfShowingResultsNum( $offset, $limit, $num ) {
1199 'showingresultsnum',
1200 array( 'parseinline' ),
1201 $wgLang->formatNum( $limit ),
1202 $wgLang->formatNum( $offset +
1 ),
1203 $wgLang->formatNum( $num )
1208 * Generate (prev x| next x) (20|50|100...) type links for paging
1210 * @param $offset String
1211 * @param $limit Integer
1212 * @param $link String
1213 * @param $query String: optional URL query parameter string
1214 * @param $atend Bool: optional param for specified if this is the last page
1217 function wfViewPrevNext( $offset, $limit, $link, $query = '', $atend = false ) {
1219 $fmtLimit = $wgLang->formatNum( $limit );
1220 // @todo FIXME: Why on earth this needs one message for the text and another one for tooltip?
1221 # Get prev/next link display text
1222 $prev = wfMsgExt( 'prevn', array( 'parsemag', 'escape' ), $fmtLimit );
1223 $next = wfMsgExt( 'nextn', array( 'parsemag', 'escape' ), $fmtLimit );
1224 # Get prev/next link title text
1225 $pTitle = wfMsgExt( 'prevn-title', array( 'parsemag', 'escape' ), $fmtLimit );
1226 $nTitle = wfMsgExt( 'nextn-title', array( 'parsemag', 'escape' ), $fmtLimit );
1227 # Fetch the title object
1228 if( is_object( $link ) ) {
1231 $title = Title
::newFromText( $link );
1232 if( is_null( $title ) ) {
1236 # Make 'previous' link
1237 if( 0 != $offset ) {
1238 $po = $offset - $limit;
1239 $po = max( $po, 0 );
1240 $q = "limit={$limit}&offset={$po}";
1241 if( $query != '' ) {
1244 $plink = '<a href="' . $title->escapeLocalURL( $q ) . "\" title=\"{$pTitle}\" class=\"mw-prevlink\">{$prev}</a>";
1249 $no = $offset +
$limit;
1250 $q = "limit={$limit}&offset={$no}";
1251 if( $query != '' ) {
1257 $nlink = '<a href="' . $title->escapeLocalURL( $q ) . "\" title=\"{$nTitle}\" class=\"mw-nextlink\">{$next}</a>";
1259 # Make links to set number of items per page
1260 $nums = $wgLang->pipeList( array(
1261 wfNumLink( $offset, 20, $title, $query ),
1262 wfNumLink( $offset, 50, $title, $query ),
1263 wfNumLink( $offset, 100, $title, $query ),
1264 wfNumLink( $offset, 250, $title, $query ),
1265 wfNumLink( $offset, 500, $title, $query )
1267 return wfMsgHtml( 'viewprevnext', $plink, $nlink, $nums );
1271 * Generate links for (20|50|100...) items-per-page links
1273 * @param $offset String
1274 * @param $limit Integer
1275 * @param $title Title
1276 * @param $query String: optional URL query parameter string
1278 function wfNumLink( $offset, $limit, $title, $query = '' ) {
1280 if( $query == '' ) {
1285 $q .= "limit={$limit}&offset={$offset}";
1286 $fmtLimit = $wgLang->formatNum( $limit );
1287 $lTitle = wfMsgExt( 'shown-title', array( 'parsemag', 'escape' ), $limit );
1288 $s = '<a href="' . $title->escapeLocalURL( $q ) . "\" title=\"{$lTitle}\" class=\"mw-numlink\">{$fmtLimit}</a>";
1294 * @todo FIXME: We may want to blacklist some broken browsers
1296 * @param $force Bool
1297 * @return bool Whereas client accept gzip compression
1299 function wfClientAcceptsGzip( $force = false ) {
1300 static $result = null;
1301 if ( $result === null ||
$force ) {
1303 if( isset( $_SERVER['HTTP_ACCEPT_ENCODING'] ) ) {
1304 # @todo FIXME: We may want to blacklist some broken browsers
1307 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
1308 $_SERVER['HTTP_ACCEPT_ENCODING'],
1312 if( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) {
1316 wfDebug( " accepts gzip\n" );
1325 * Obtain the offset and limit values from the request string;
1326 * used in special pages
1328 * @param $deflimit Int default limit if none supplied
1329 * @param $optionname String Name of a user preference to check against
1333 function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) {
1335 return $wgRequest->getLimitOffset( $deflimit, $optionname );
1339 * Escapes the given text so that it may be output using addWikiText()
1340 * without any linking, formatting, etc. making its way through. This
1341 * is achieved by substituting certain characters with HTML entities.
1342 * As required by the callers, <nowiki> is not used.
1344 * @param $text String: text to be escaped
1347 function wfEscapeWikiText( $text ) {
1348 $text = strtr( "\n$text", array(
1349 '"' => '"', '&' => '&', "'" => ''', '<' => '<',
1350 '=' => '=', '>' => '>', '[' => '[', ']' => ']',
1351 '{' => '{', '|' => '|', '}' => '}',
1352 "\n#" => "\n#", "\n*" => "\n*",
1353 "\n:" => "\n:", "\n;" => "\n;",
1354 '://' => '://', 'ISBN ' => 'ISBN ', 'RFC ' => 'RFC ',
1356 return substr( $text, 1 );
1360 * Get the current unix timetstamp with microseconds. Useful for profiling
1364 return microtime( true );
1368 * Sets dest to source and returns the original value of dest
1369 * If source is NULL, it just returns the value, it doesn't set the variable
1370 * If force is true, it will set the value even if source is NULL
1372 * @param $dest Mixed
1373 * @param $source Mixed
1374 * @param $force Bool
1377 function wfSetVar( &$dest, $source, $force = false ) {
1379 if ( !is_null( $source ) ||
$force ) {
1386 * As for wfSetVar except setting a bit
1390 * @param $state Bool
1392 function wfSetBit( &$dest, $bit, $state = true ) {
1393 $temp = (bool)( $dest & $bit );
1394 if ( !is_null( $state ) ) {
1405 * This function takes two arrays as input, and returns a CGI-style string, e.g.
1406 * "days=7&limit=100". Options in the first array override options in the second.
1407 * Options set to "" will not be output.
1409 * @param $array1 Array( String|Array )
1410 * @param $array2 Array( String|Array )
1413 function wfArrayToCGI( $array1, $array2 = null ) {
1414 if ( !is_null( $array2 ) ) {
1415 $array1 = $array1 +
$array2;
1419 foreach ( $array1 as $key => $value ) {
1420 if ( $value !== '' ) {
1424 if ( is_array( $value ) ) {
1426 foreach ( $value as $v ) {
1427 $cgi .= ( $firstTime ?
'' : '&') .
1428 urlencode( $key . '[]' ) . '=' .
1433 if ( is_object( $value ) ) {
1434 $value = $value->__toString();
1436 $cgi .= urlencode( $key ) . '=' .
1437 urlencode( $value );
1445 * This is the logical opposite of wfArrayToCGI(): it accepts a query string as
1446 * its argument and returns the same string in array form. This allows compa-
1447 * tibility with legacy functions that accept raw query strings instead of nice
1448 * arrays. Of course, keys and values are urldecode()d. Don't try passing in-
1449 * valid query strings, or it will explode.
1451 * @param $query String: query string
1452 * @return array Array version of input
1454 function wfCgiToArray( $query ) {
1455 if( isset( $query[0] ) && $query[0] == '?' ) {
1456 $query = substr( $query, 1 );
1458 $bits = explode( '&', $query );
1460 foreach( $bits as $bit ) {
1464 list( $key, $value ) = explode( '=', $bit );
1465 $key = urldecode( $key );
1466 $value = urldecode( $value );
1467 $ret[$key] = $value;
1473 * Append a query string to an existing URL, which may or may not already
1474 * have query string parameters already. If so, they will be combined.
1476 * @param $url String
1477 * @param $query Mixed: string or associative array
1480 function wfAppendQuery( $url, $query ) {
1481 if ( is_array( $query ) ) {
1482 $query = wfArrayToCGI( $query );
1484 if( $query != '' ) {
1485 if( false === strpos( $url, '?' ) ) {
1496 * Expand a potentially local URL to a fully-qualified URL. Assumes $wgServer
1497 * and $wgProto are correct.
1499 * @todo this won't work with current-path-relative URLs
1500 * like "subdir/foo.html", etc.
1502 * @param $url String: either fully-qualified or a local path + query
1503 * @return string Fully-qualified URL
1505 function wfExpandUrl( $url ) {
1506 if( substr( $url, 0, 2 ) == '//' ) {
1508 return $wgProto . ':' . $url;
1509 } elseif( substr( $url, 0, 1 ) == '/' ) {
1511 return $wgServer . $url;
1518 * Windows-compatible version of escapeshellarg()
1519 * Windows doesn't recognise single-quotes in the shell, but the escapeshellarg()
1520 * function puts single quotes in regardless of OS.
1522 * Also fixes the locale problems on Linux in PHP 5.2.6+ (bug backported to
1523 * earlier distro releases of PHP)
1528 function wfEscapeShellArg( ) {
1529 wfInitShellLocale();
1531 $args = func_get_args();
1534 foreach ( $args as $arg ) {
1541 if ( wfIsWindows() ) {
1542 // Escaping for an MSVC-style command line parser and CMD.EXE
1544 // * http://web.archive.org/web/20020708081031/http://mailman.lyra.org/pipermail/scite-interest/2002-March/000436.html
1545 // * http://technet.microsoft.com/en-us/library/cc723564.aspx
1548 // Double the backslashes before any double quotes. Escape the double quotes.
1549 $tokens = preg_split( '/(\\\\*")/', $arg, -1, PREG_SPLIT_DELIM_CAPTURE
);
1552 foreach ( $tokens as $token ) {
1553 if ( $iteration %
2 == 1 ) {
1554 // Delimiter, a double quote preceded by zero or more slashes
1555 $arg .= str_replace( '\\', '\\\\', substr( $token, 0, -1 ) ) . '\\"';
1556 } elseif ( $iteration %
4 == 2 ) {
1557 // ^ in $token will be outside quotes, need to be escaped
1558 $arg .= str_replace( '^', '^^', $token );
1559 } else { // $iteration % 4 == 0
1560 // ^ in $token will appear inside double quotes, so leave as is
1565 // Double the backslashes before the end of the string, because
1566 // we will soon add a quote
1568 if ( preg_match( '/^(.*?)(\\\\+)$/', $arg, $m ) ) {
1569 $arg = $m[1] . str_replace( '\\', '\\\\', $m[2] );
1572 // Add surrounding quotes
1573 $retVal .= '"' . $arg . '"';
1575 $retVal .= escapeshellarg( $arg );
1582 * wfMerge attempts to merge differences between three texts.
1583 * Returns true for a clean merge and false for failure or a conflict.
1585 * @param $old String
1586 * @param $mine String
1587 * @param $yours String
1588 * @param $result String
1591 function wfMerge( $old, $mine, $yours, &$result ) {
1594 # This check may also protect against code injection in
1595 # case of broken installations.
1596 wfSuppressWarnings();
1597 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
1598 wfRestoreWarnings();
1601 wfDebug( "diff3 not found\n" );
1605 # Make temporary files
1607 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
1608 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
1609 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
1611 fwrite( $oldtextFile, $old );
1612 fclose( $oldtextFile );
1613 fwrite( $mytextFile, $mine );
1614 fclose( $mytextFile );
1615 fwrite( $yourtextFile, $yours );
1616 fclose( $yourtextFile );
1618 # Check for a conflict
1619 $cmd = $wgDiff3 . ' -a --overlap-only ' .
1620 wfEscapeShellArg( $mytextName ) . ' ' .
1621 wfEscapeShellArg( $oldtextName ) . ' ' .
1622 wfEscapeShellArg( $yourtextName );
1623 $handle = popen( $cmd, 'r' );
1625 if( fgets( $handle, 1024 ) ) {
1633 $cmd = $wgDiff3 . ' -a -e --merge ' .
1634 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
1635 $handle = popen( $cmd, 'r' );
1638 $data = fread( $handle, 8192 );
1639 if ( strlen( $data ) == 0 ) {
1645 unlink( $mytextName );
1646 unlink( $oldtextName );
1647 unlink( $yourtextName );
1649 if ( $result === '' && $old !== '' && !$conflict ) {
1650 wfDebug( "Unexpected null result from diff3. Command: $cmd\n" );
1657 * Returns unified plain-text diff of two texts.
1658 * Useful for machine processing of diffs.
1660 * @param $before String: the text before the changes.
1661 * @param $after String: the text after the changes.
1662 * @param $params String: command-line options for the diff command.
1663 * @return String: unified diff of $before and $after
1665 function wfDiff( $before, $after, $params = '-u' ) {
1666 if ( $before == $after ) {
1671 wfSuppressWarnings();
1672 $haveDiff = $wgDiff && file_exists( $wgDiff );
1673 wfRestoreWarnings();
1675 # This check may also protect against code injection in
1676 # case of broken installations.
1678 wfDebug( "diff executable not found\n" );
1679 $diffs = new Diff( explode( "\n", $before ), explode( "\n", $after ) );
1680 $format = new UnifiedDiffFormatter();
1681 return $format->format( $diffs );
1684 # Make temporary files
1686 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
1687 $newtextFile = fopen( $newtextName = tempnam( $td, 'merge-your-' ), 'w' );
1689 fwrite( $oldtextFile, $before );
1690 fclose( $oldtextFile );
1691 fwrite( $newtextFile, $after );
1692 fclose( $newtextFile );
1694 // Get the diff of the two files
1695 $cmd = "$wgDiff " . $params . ' ' . wfEscapeShellArg( $oldtextName, $newtextName );
1697 $h = popen( $cmd, 'r' );
1702 $data = fread( $h, 8192 );
1703 if ( strlen( $data ) == 0 ) {
1711 unlink( $oldtextName );
1712 unlink( $newtextName );
1714 // Kill the --- and +++ lines. They're not useful.
1715 $diff_lines = explode( "\n", $diff );
1716 if ( strpos( $diff_lines[0], '---' ) === 0 ) {
1717 unset( $diff_lines[0] );
1719 if ( strpos( $diff_lines[1], '+++' ) === 0 ) {
1720 unset( $diff_lines[1] );
1723 $diff = implode( "\n", $diff_lines );
1729 * A wrapper around the PHP function var_export().
1730 * Either print it or add it to the regular output ($wgOut).
1732 * @param $var A PHP variable to dump.
1734 function wfVarDump( $var ) {
1736 $s = str_replace( "\n", "<br />\n", var_export( $var, true ) . "\n" );
1737 if ( headers_sent() ||
!@is_object
( $wgOut ) ) {
1740 $wgOut->addHTML( $s );
1745 * Provide a simple HTTP error.
1747 * @param $code Int|String
1748 * @param $label String
1749 * @param $desc String
1751 function wfHttpError( $code, $label, $desc ) {
1754 header( "HTTP/1.0 $code $label" );
1755 header( "Status: $code $label" );
1756 $wgOut->sendCacheControl();
1758 header( 'Content-type: text/html; charset=utf-8' );
1759 print "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">".
1760 '<html><head><title>' .
1761 htmlspecialchars( $label ) .
1762 '</title></head><body><h1>' .
1763 htmlspecialchars( $label ) .
1765 nl2br( htmlspecialchars( $desc ) ) .
1766 "</p></body></html>\n";
1770 * Clear away any user-level output buffers, discarding contents.
1772 * Suitable for 'starting afresh', for instance when streaming
1773 * relatively large amounts of data without buffering, or wanting to
1774 * output image files without ob_gzhandler's compression.
1776 * The optional $resetGzipEncoding parameter controls suppression of
1777 * the Content-Encoding header sent by ob_gzhandler; by default it
1778 * is left. See comments for wfClearOutputBuffers() for why it would
1781 * Note that some PHP configuration options may add output buffer
1782 * layers which cannot be removed; these are left in place.
1784 * @param $resetGzipEncoding Bool
1786 function wfResetOutputBuffers( $resetGzipEncoding = true ) {
1787 if( $resetGzipEncoding ) {
1788 // Suppress Content-Encoding and Content-Length
1789 // headers from 1.10+s wfOutputHandler
1790 global $wgDisableOutputCompression;
1791 $wgDisableOutputCompression = true;
1793 while( $status = ob_get_status() ) {
1794 if( $status['type'] == 0 /* PHP_OUTPUT_HANDLER_INTERNAL */ ) {
1795 // Probably from zlib.output_compression or other
1796 // PHP-internal setting which can't be removed.
1798 // Give up, and hope the result doesn't break
1802 if( !ob_end_clean() ) {
1803 // Could not remove output buffer handler; abort now
1804 // to avoid getting in some kind of infinite loop.
1807 if( $resetGzipEncoding ) {
1808 if( $status['name'] == 'ob_gzhandler' ) {
1809 // Reset the 'Content-Encoding' field set by this handler
1810 // so we can start fresh.
1811 if ( function_exists( 'header_remove' ) ) {
1812 // Available since PHP 5.3.0
1813 header_remove( 'Content-Encoding' );
1815 // We need to provide a valid content-coding. See bug 28069
1816 header( 'Content-Encoding: identity' );
1825 * More legible than passing a 'false' parameter to wfResetOutputBuffers():
1827 * Clear away output buffers, but keep the Content-Encoding header
1828 * produced by ob_gzhandler, if any.
1830 * This should be used for HTTP 304 responses, where you need to
1831 * preserve the Content-Encoding header of the real result, but
1832 * also need to suppress the output of ob_gzhandler to keep to spec
1833 * and avoid breaking Firefox in rare cases where the headers and
1834 * body are broken over two packets.
1836 function wfClearOutputBuffers() {
1837 wfResetOutputBuffers( false );
1841 * Converts an Accept-* header into an array mapping string values to quality
1844 * @param $accept String
1845 * @param $def String default
1848 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
1849 # No arg means accept anything (per HTTP spec)
1851 return array( $def => 1.0 );
1856 $parts = explode( ',', $accept );
1858 foreach( $parts as $part ) {
1859 # @todo FIXME: Doesn't deal with params like 'text/html; level=1'
1860 @list
( $value, $qpart ) = explode( ';', trim( $part ) );
1862 if( !isset( $qpart ) ) {
1863 $prefs[$value] = 1.0;
1864 } elseif( preg_match( '/q\s*=\s*(\d*\.\d+)/', $qpart, $match ) ) {
1865 $prefs[$value] = floatval( $match[1] );
1873 * Checks if a given MIME type matches any of the keys in the given
1874 * array. Basic wildcards are accepted in the array keys.
1876 * Returns the matching MIME type (or wildcard) if a match, otherwise
1879 * @param $type String
1880 * @param $avail Array
1884 function mimeTypeMatch( $type, $avail ) {
1885 if( array_key_exists( $type, $avail ) ) {
1888 $parts = explode( '/', $type );
1889 if( array_key_exists( $parts[0] . '/*', $avail ) ) {
1890 return $parts[0] . '/*';
1891 } elseif( array_key_exists( '*/*', $avail ) ) {
1900 * Returns the 'best' match between a client's requested internet media types
1901 * and the server's list of available types. Each list should be an associative
1902 * array of type to preference (preference is a float between 0.0 and 1.0).
1903 * Wildcards in the types are acceptable.
1905 * @param $cprefs Array: client's acceptable type list
1906 * @param $sprefs Array: server's offered types
1909 * @todo FIXME: Doesn't handle params like 'text/plain; charset=UTF-8'
1910 * XXX: generalize to negotiate other stuff
1912 function wfNegotiateType( $cprefs, $sprefs ) {
1915 foreach( array_keys($sprefs) as $type ) {
1916 $parts = explode( '/', $type );
1917 if( $parts[1] != '*' ) {
1918 $ckey = mimeTypeMatch( $type, $cprefs );
1920 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1925 foreach( array_keys( $cprefs ) as $type ) {
1926 $parts = explode( '/', $type );
1927 if( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
1928 $skey = mimeTypeMatch( $type, $sprefs );
1930 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1938 foreach( array_keys( $combine ) as $type ) {
1939 if( $combine[$type] > $bestq ) {
1941 $bestq = $combine[$type];
1949 * Reference-counted warning suppression
1953 function wfSuppressWarnings( $end = false ) {
1954 static $suppressCount = 0;
1955 static $originalLevel = false;
1958 if ( $suppressCount ) {
1960 if ( !$suppressCount ) {
1961 error_reporting( $originalLevel );
1965 if ( !$suppressCount ) {
1966 // E_DEPRECATED is undefined in PHP 5.2
1967 if( !defined( 'E_DEPRECATED' ) ){
1968 define( 'E_DEPRECATED', 8192 );
1970 $originalLevel = error_reporting( E_ALL
& ~
( E_WARNING | E_NOTICE | E_USER_WARNING | E_USER_NOTICE | E_DEPRECATED
) );
1977 * Restore error level to previous value
1979 function wfRestoreWarnings() {
1980 wfSuppressWarnings( true );
1983 # Autodetect, convert and provide timestamps of various types
1986 * Unix time - the number of seconds since 1970-01-01 00:00:00 UTC
1988 define( 'TS_UNIX', 0 );
1991 * MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
1993 define( 'TS_MW', 1 );
1996 * MySQL DATETIME (YYYY-MM-DD HH:MM:SS)
1998 define( 'TS_DB', 2 );
2001 * RFC 2822 format, for E-mail and HTTP headers
2003 define( 'TS_RFC2822', 3 );
2006 * ISO 8601 format with no timezone: 1986-02-09T20:00:00Z
2008 * This is used by Special:Export
2010 define( 'TS_ISO_8601', 4 );
2013 * An Exif timestamp (YYYY:MM:DD HH:MM:SS)
2015 * @see http://exif.org/Exif2-2.PDF The Exif 2.2 spec, see page 28 for the
2016 * DateTime tag and page 36 for the DateTimeOriginal and
2017 * DateTimeDigitized tags.
2019 define( 'TS_EXIF', 5 );
2022 * Oracle format time.
2024 define( 'TS_ORACLE', 6 );
2027 * Postgres format time.
2029 define( 'TS_POSTGRES', 7 );
2034 define( 'TS_DB2', 8 );
2037 * ISO 8601 basic format with no timezone: 19860209T200000Z. This is used by ResourceLoader
2039 define( 'TS_ISO_8601_BASIC', 9 );
2042 * Get a timestamp string in one of various formats
2044 * @param $outputtype Mixed: A timestamp in one of the supported formats, the
2045 * function will autodetect which format is supplied and act
2047 * @param $ts Mixed: the timestamp to convert or 0 for the current timestamp
2048 * @return Mixed: String / false The same date in the format specified in $outputtype or false
2050 function wfTimestamp( $outputtype = TS_UNIX
, $ts = 0 ) {
2055 if ( !$ts ) { // We want to catch 0, '', null... but not date strings starting with a letter.
2058 } elseif ( preg_match( '/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)$/D', $ts, $da ) ) {
2060 } elseif ( preg_match( '/^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/D', $ts, $da ) ) {
2062 } elseif ( preg_match( '/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/D', $ts, $da ) ) {
2064 } elseif ( preg_match( '/^-?\d{1,13}$/D', $ts ) ) {
2067 $strtime = "@$ts"; // Undocumented?
2068 } elseif ( preg_match( '/^\d{2}-\d{2}-\d{4} \d{2}:\d{2}:\d{2}.\d{6}$/', $ts ) ) {
2069 # TS_ORACLE // session altered to DD-MM-YYYY HH24:MI:SS.FF6
2070 $strtime = preg_replace( '/(\d\d)\.(\d\d)\.(\d\d)(\.(\d+))?/', "$1:$2:$3",
2071 str_replace( '+00:00', 'UTC', $ts ) );
2072 } elseif ( preg_match( '/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.*\d*)?Z$/', $ts, $da ) ) {
2074 } elseif ( preg_match( '/^(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})(?:\.*\d*)?Z$/', $ts, $da ) ) {
2076 } elseif ( preg_match( '/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.*\d*[\+\- ](\d\d)$/', $ts, $da ) ) {
2078 } elseif ( preg_match( '/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.*\d* GMT$/', $ts, $da ) ) {
2080 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.\d\d\d$/',$ts,$da)) {
2082 } elseif ( preg_match( '/^[ \t\r\n]*([A-Z][a-z]{2},[ \t\r\n]*)?' . # Day of week
2083 '\d\d?[ \t\r\n]*[A-Z][a-z]{2}[ \t\r\n]*\d{2}(?:\d{2})?' . # dd Mon yyyy
2084 '[ \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
2085 # TS_RFC2822, accepting a trailing comment. See http://www.squid-cache.org/mail-archive/squid-users/200307/0122.html / r77171
2086 # The regex is a superset of rfc2822 for readability
2087 $strtime = strtok( $ts, ';' );
2088 } 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 ) ) {
2091 } 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 ) ) {
2096 wfDebug("wfTimestamp() fed bogus time value: TYPE=$outputtype; VALUE=$ts\n");
2103 static $formats = array(
2106 TS_DB
=> 'Y-m-d H:i:s',
2107 TS_ISO_8601
=> 'Y-m-d\TH:i:s\Z',
2108 TS_ISO_8601_BASIC
=> 'Ymd\THis\Z',
2109 TS_EXIF
=> 'Y:m:d H:i:s', // This shouldn't ever be used, but is included for completeness
2110 TS_RFC2822
=> 'D, d M Y H:i:s',
2111 TS_ORACLE
=> 'd-m-Y H:i:s.000000', // Was 'd-M-y h.i.s A' . ' +00:00' before r51500
2112 TS_POSTGRES
=> 'Y-m-d H:i:s',
2113 TS_DB2
=> 'Y-m-d H:i:s',
2116 if ( !isset( $formats[$outputtype] ) ) {
2117 throw new MWException( 'wfTimestamp() called with illegal output type.' );
2120 if ( function_exists( "date_create" ) ) {
2121 if ( count( $da ) ) {
2122 $ds = sprintf("%04d-%02d-%02dT%02d:%02d:%02d.00+00:00",
2123 (int)$da[1], (int)$da[2], (int)$da[3],
2124 (int)$da[4], (int)$da[5], (int)$da[6]);
2126 $d = date_create( $ds, new DateTimeZone( 'GMT' ) );
2127 } elseif ( $strtime ) {
2128 $d = date_create( $strtime, new DateTimeZone( 'GMT' ) );
2134 wfDebug("wfTimestamp() fed bogus time value: $outputtype; $ts\n");
2138 $output = $d->format( $formats[$outputtype] );
2140 if ( count( $da ) ) {
2141 // Warning! gmmktime() acts oddly if the month or day is set to 0
2142 // We may want to handle that explicitly at some point
2143 $uts = gmmktime( (int)$da[4], (int)$da[5], (int)$da[6],
2144 (int)$da[2], (int)$da[3], (int)$da[1] );
2145 } elseif ( $strtime ) {
2146 $uts = strtotime( $strtime );
2149 if ( $uts === false ) {
2150 wfDebug("wfTimestamp() can't parse the timestamp (non 32-bit time? Update php): $outputtype; $ts\n");
2154 if ( TS_UNIX
== $outputtype ) {
2157 $output = gmdate( $formats[$outputtype], $uts );
2160 if ( ( $outputtype == TS_RFC2822
) ||
( $outputtype == TS_POSTGRES
) ) {
2168 * Return a formatted timestamp, or null if input is null.
2169 * For dealing with nullable timestamp columns in the database.
2171 * @param $outputtype Integer
2175 function wfTimestampOrNull( $outputtype = TS_UNIX
, $ts = null ) {
2176 if( is_null( $ts ) ) {
2179 return wfTimestamp( $outputtype, $ts );
2184 * Convenience function; returns MediaWiki timestamp for the present time.
2188 function wfTimestampNow() {
2190 return wfTimestamp( TS_MW
, time() );
2194 * Check if the operating system is Windows
2196 * @return Bool: true if it's Windows, False otherwise.
2198 function wfIsWindows() {
2199 static $isWindows = null;
2200 if ( $isWindows === null ) {
2201 $isWindows = substr( php_uname(), 0, 7 ) == 'Windows';
2207 * Check if we are running under HipHop
2211 function wfIsHipHop() {
2212 return function_exists( 'hphp_thread_set_warmup_enabled' );
2216 * Swap two variables
2221 function swap( &$x, &$y ) {
2228 * Tries to get the system directory for temporary files. The TMPDIR, TMP, and
2229 * TEMP environment variables are then checked in sequence, and if none are set
2230 * try sys_get_temp_dir() for PHP >= 5.2.1. All else fails, return /tmp for Unix
2231 * or C:\Windows\Temp for Windows and hope for the best.
2232 * It is common to call it with tempnam().
2234 * NOTE: When possible, use instead the tmpfile() function to create
2235 * temporary files to avoid race conditions on file creation, etc.
2239 function wfTempDir() {
2240 foreach( array( 'TMPDIR', 'TMP', 'TEMP' ) as $var ) {
2241 $tmp = getenv( $var );
2242 if( $tmp && file_exists( $tmp ) && is_dir( $tmp ) && is_writable( $tmp ) ) {
2246 if( function_exists( 'sys_get_temp_dir' ) ) {
2247 return sys_get_temp_dir();
2250 return wfIsWindows() ?
'C:\Windows\Temp' : '/tmp';
2254 * Make directory, and make all parent directories if they don't exist
2256 * @param $dir String: full path to directory to create
2257 * @param $mode Integer: chmod value to use, default is $wgDirectoryMode
2258 * @param $caller String: optional caller param for debugging.
2261 function wfMkdirParents( $dir, $mode = null, $caller = null ) {
2262 global $wgDirectoryMode;
2264 if ( !is_null( $caller ) ) {
2265 wfDebug( "$caller: called wfMkdirParents($dir)" );
2268 if( strval( $dir ) === '' ||
file_exists( $dir ) ) {
2272 $dir = str_replace( array( '\\', '/' ), DIRECTORY_SEPARATOR
, $dir );
2274 if ( is_null( $mode ) ) {
2275 $mode = $wgDirectoryMode;
2278 // Turn off the normal warning, we're doing our own below
2279 wfSuppressWarnings();
2280 $ok = mkdir( $dir, $mode, true ); // PHP5 <3
2281 wfRestoreWarnings();
2284 // PHP doesn't report the path in its warning message, so add our own to aid in diagnosis.
2285 trigger_error( __FUNCTION__
. ": failed to mkdir \"$dir\" mode $mode", E_USER_WARNING
);
2291 * Increment a statistics counter
2293 * @param $key String
2296 function wfIncrStats( $key, $count = 1 ) {
2297 global $wgStatsMethod;
2299 $count = intval( $count );
2301 if( $wgStatsMethod == 'udp' ) {
2302 global $wgUDPProfilerHost, $wgUDPProfilerPort, $wgDBname, $wgAggregateStatsID;
2305 $id = $wgAggregateStatsID !== false ?
$wgAggregateStatsID : $wgDBname;
2308 $socket = socket_create( AF_INET
, SOCK_DGRAM
, SOL_UDP
);
2309 $statline = "stats/{$id} - {$count} 1 1 1 1 -total\n";
2313 strlen( $statline ),
2319 $statline = "stats/{$id} - {$count} 1 1 1 1 {$key}\n";
2320 wfSuppressWarnings();
2324 strlen( $statline ),
2329 wfRestoreWarnings();
2330 } elseif( $wgStatsMethod == 'cache' ) {
2332 $key = wfMemcKey( 'stats', $key );
2333 if ( is_null( $wgMemc->incr( $key, $count ) ) ) {
2334 $wgMemc->add( $key, $count );
2342 * @param $nr Mixed: the number to format
2343 * @param $acc Integer: the number of digits after the decimal point, default 2
2344 * @param $round Boolean: whether or not to round the value, default true
2347 function wfPercent( $nr, $acc = 2, $round = true ) {
2348 $ret = sprintf( "%.${acc}f", $nr );
2349 return $round ?
round( $ret, $acc ) . '%' : "$ret%";
2353 * Find out whether or not a mixed variable exists in a string
2355 * @param $needle String
2356 * @param $str String
2357 * @param $insensitive Boolean
2360 function in_string( $needle, $str, $insensitive = false ) {
2362 if( $insensitive ) $func = 'stripos';
2364 return $func( $str, $needle ) !== false;
2367 function wfSpecialList( $page, $details ) {
2369 $details = $details ?
' ' . $wgContLang->getDirMark() . "($details)" : '';
2370 return $page . $details;
2374 * Returns a regular expression of url protocols
2378 function wfUrlProtocols() {
2379 global $wgUrlProtocols;
2381 static $retval = null;
2382 if ( !is_null( $retval ) ) {
2386 // Support old-style $wgUrlProtocols strings, for backwards compatibility
2387 // with LocalSettings files from 1.5
2388 if ( is_array( $wgUrlProtocols ) ) {
2389 $protocols = array();
2390 foreach ( $wgUrlProtocols as $protocol ) {
2391 $protocols[] = preg_quote( $protocol, '/' );
2394 $retval = implode( '|', $protocols );
2396 $retval = $wgUrlProtocols;
2402 * Safety wrapper around ini_get() for boolean settings.
2403 * The values returned from ini_get() are pre-normalized for settings
2404 * set via php.ini or php_flag/php_admin_flag... but *not*
2405 * for those set via php_value/php_admin_value.
2407 * It's fairly common for people to use php_value instead of php_flag,
2408 * which can leave you with an 'off' setting giving a false positive
2409 * for code that just takes the ini_get() return value as a boolean.
2411 * To make things extra interesting, setting via php_value accepts
2412 * "true" and "yes" as true, but php.ini and php_flag consider them false. :)
2413 * Unrecognized values go false... again opposite PHP's own coercion
2414 * from string to bool.
2416 * Luckily, 'properly' set settings will always come back as '0' or '1',
2417 * so we only have to worry about them and the 'improper' settings.
2419 * I frickin' hate PHP... :P
2421 * @param $setting String
2424 function wfIniGetBool( $setting ) {
2425 $val = ini_get( $setting );
2426 // 'on' and 'true' can't have whitespace around them, but '1' can.
2427 return strtolower( $val ) == 'on'
2428 ||
strtolower( $val ) == 'true'
2429 ||
strtolower( $val ) == 'yes'
2430 ||
preg_match( "/^\s*[+-]?0*[1-9]/", $val ); // approx C atoi() function
2434 * Wrapper function for PHP's dl(). This doesn't work in most situations from
2435 * PHP 5.3 onward, and is usually disabled in shared environments anyway.
2437 * @param $extension String A PHP extension. The file suffix (.so or .dll)
2439 * @param $fileName String Name of the library, if not $extension.suffix
2440 * @return Bool - Whether or not the extension is loaded
2442 function wfDl( $extension, $fileName = null ) {
2443 if( extension_loaded( $extension ) ) {
2448 $sapi = php_sapi_name();
2449 if( version_compare( PHP_VERSION
, '5.3.0', '<' ) ||
2450 $sapi == 'cli' ||
$sapi == 'cgi' ||
$sapi == 'embed' )
2452 $canDl = ( function_exists( 'dl' ) && is_callable( 'dl' )
2453 && wfIniGetBool( 'enable_dl' ) && !wfIniGetBool( 'safe_mode' ) );
2457 $fileName = $fileName ?
$fileName : $extension;
2458 if( wfIsWindows() ) {
2459 $fileName = 'php_' . $fileName;
2461 wfSuppressWarnings();
2462 dl( $fileName . '.' . PHP_SHLIB_SUFFIX
);
2463 wfRestoreWarnings();
2465 return extension_loaded( $extension );
2469 * Execute a shell command, with time and memory limits mirrored from the PHP
2470 * configuration if supported.
2471 * @param $cmd String Command line, properly escaped for shell.
2472 * @param &$retval optional, will receive the program's exit code.
2473 * (non-zero is usually failure)
2474 * @param $environ Array optional environment variables which should be
2475 * added to the executed command environment.
2476 * @return collected stdout as a string (trailing newlines stripped)
2478 function wfShellExec( $cmd, &$retval = null, $environ = array() ) {
2479 global $IP, $wgMaxShellMemory, $wgMaxShellFileSize, $wgMaxShellTime;
2482 if ( is_null( $disabled ) ) {
2484 if( wfIniGetBool( 'safe_mode' ) ) {
2485 wfDebug( "wfShellExec can't run in safe_mode, PHP's exec functions are too broken.\n" );
2486 $disabled = 'safemode';
2488 $functions = explode( ',', ini_get( 'disable_functions' ) );
2489 $functions = array_map( 'trim', $functions );
2490 $functions = array_map( 'strtolower', $functions );
2491 if ( in_array( 'passthru', $functions ) ) {
2492 wfDebug( "passthru is in disabled_functions\n" );
2493 $disabled = 'passthru';
2499 return $disabled == 'safemode' ?
2500 'Unable to run external programs in safe mode.' :
2501 'Unable to run external programs, passthru() is disabled.';
2504 wfInitShellLocale();
2507 foreach( $environ as $k => $v ) {
2508 if ( wfIsWindows() ) {
2509 /* Surrounding a set in quotes (method used by wfEscapeShellArg) makes the quotes themselves
2510 * appear in the environment variable, so we must use carat escaping as documented in
2511 * http://technet.microsoft.com/en-us/library/cc723564.aspx
2512 * Note however that the quote isn't listed there, but is needed, and the parentheses
2513 * are listed there but doesn't appear to need it.
2515 $envcmd .= "set $k=" . preg_replace( '/([&|()<>^"])/', '^\\1', $v ) . '&& ';
2517 /* Assume this is a POSIX shell, thus required to accept variable assignments before the command
2518 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_09_01
2520 $envcmd .= "$k=" . escapeshellarg( $v ) . ' ';
2523 $cmd = $envcmd . $cmd;
2525 if ( wfIsWindows() ) {
2526 if ( version_compare( PHP_VERSION
, '5.3.0', '<' ) && /* Fixed in 5.3.0 :) */
2527 ( version_compare( PHP_VERSION
, '5.2.1', '>=' ) ||
php_uname( 's' ) == 'Windows NT' ) )
2529 # Hack to work around PHP's flawed invocation of cmd.exe
2530 # http://news.php.net/php.internals/21796
2531 # Windows 9x doesn't accept any kind of quotes
2532 $cmd = '"' . $cmd . '"';
2534 } elseif ( php_uname( 's' ) == 'Linux' ) {
2535 $time = intval( $wgMaxShellTime );
2536 $mem = intval( $wgMaxShellMemory );
2537 $filesize = intval( $wgMaxShellFileSize );
2539 if ( $time > 0 && $mem > 0 ) {
2540 $script = "$IP/bin/ulimit4.sh";
2541 if ( is_executable( $script ) ) {
2542 $cmd = '/bin/bash ' . escapeshellarg( $script ) . " $time $mem $filesize " . escapeshellarg( $cmd );
2546 wfDebug( "wfShellExec: $cmd\n" );
2548 $retval = 1; // error by default?
2550 passthru( $cmd, $retval );
2551 $output = ob_get_contents();
2554 if ( $retval == 127 ) {
2555 wfDebugLog( 'exec', "Possibly missing executable file: $cmd\n" );
2561 * Workaround for http://bugs.php.net/bug.php?id=45132
2562 * escapeshellarg() destroys non-ASCII characters if LANG is not a UTF-8 locale
2564 function wfInitShellLocale() {
2565 static $done = false;
2570 global $wgShellLocale;
2571 if ( !wfIniGetBool( 'safe_mode' ) ) {
2572 putenv( "LC_CTYPE=$wgShellLocale" );
2573 setlocale( LC_CTYPE
, $wgShellLocale );
2578 * This function works like "use VERSION" in Perl, the program will die with a
2579 * backtrace if the current version of PHP is less than the version provided
2581 * This is useful for extensions which due to their nature are not kept in sync
2582 * with releases, and might depend on other versions of PHP than the main code
2584 * Note: PHP might die due to parsing errors in some cases before it ever
2585 * manages to call this function, such is life
2587 * @see perldoc -f use
2589 * @param $req_ver Mixed: the version to check, can be a string, an integer, or
2592 function wfUsePHP( $req_ver ) {
2593 $php_ver = PHP_VERSION
;
2595 if ( version_compare( $php_ver, (string)$req_ver, '<' ) ) {
2596 throw new MWException( "PHP $req_ver required--this is only $php_ver" );
2601 * This function works like "use VERSION" in Perl except it checks the version
2602 * of MediaWiki, the program will die with a backtrace if the current version
2603 * of MediaWiki is less than the version provided.
2605 * This is useful for extensions which due to their nature are not kept in sync
2608 * @see perldoc -f use
2610 * @param $req_ver Mixed: the version to check, can be a string, an integer, or
2613 function wfUseMW( $req_ver ) {
2616 if ( version_compare( $wgVersion, (string)$req_ver, '<' ) ) {
2617 throw new MWException( "MediaWiki $req_ver required--this is only $wgVersion" );
2622 * Return the final portion of a pathname.
2623 * Reimplemented because PHP5's basename() is buggy with multibyte text.
2624 * http://bugs.php.net/bug.php?id=33898
2626 * PHP's basename() only considers '\' a pathchar on Windows and Netware.
2627 * We'll consider it so always, as we don't want \s in our Unix paths either.
2629 * @param $path String
2630 * @param $suffix String: to remove if present
2633 function wfBaseName( $path, $suffix = '' ) {
2634 $encSuffix = ( $suffix == '' )
2636 : ( '(?:' . preg_quote( $suffix, '#' ) . ')?' );
2638 if( preg_match( "#([^/\\\\]*?){$encSuffix}[/\\\\]*$#", $path, $matches ) ) {
2646 * Generate a relative path name to the given file.
2647 * May explode on non-matching case-insensitive paths,
2648 * funky symlinks, etc.
2650 * @param $path String: absolute destination path including target filename
2651 * @param $from String: Absolute source path, directory only
2654 function wfRelativePath( $path, $from ) {
2655 // Normalize mixed input on Windows...
2656 $path = str_replace( '/', DIRECTORY_SEPARATOR
, $path );
2657 $from = str_replace( '/', DIRECTORY_SEPARATOR
, $from );
2659 // Trim trailing slashes -- fix for drive root
2660 $path = rtrim( $path, DIRECTORY_SEPARATOR
);
2661 $from = rtrim( $from, DIRECTORY_SEPARATOR
);
2663 $pieces = explode( DIRECTORY_SEPARATOR
, dirname( $path ) );
2664 $against = explode( DIRECTORY_SEPARATOR
, $from );
2666 if( $pieces[0] !== $against[0] ) {
2667 // Non-matching Windows drive letters?
2668 // Return a full path.
2672 // Trim off common prefix
2673 while( count( $pieces ) && count( $against )
2674 && $pieces[0] == $against[0] ) {
2675 array_shift( $pieces );
2676 array_shift( $against );
2679 // relative dots to bump us to the parent
2680 while( count( $against ) ) {
2681 array_unshift( $pieces, '..' );
2682 array_shift( $against );
2685 array_push( $pieces, wfBaseName( $path ) );
2687 return implode( DIRECTORY_SEPARATOR
, $pieces );
2691 * parse_url() work-alike, but non-broken. Differences:
2693 * 1) Does not raise warnings on bad URLs (just returns false)
2694 * 2) Handles protocols that don't use :// (e.g., mailto: and news:) correctly
2695 * 3) Adds a "delimiter" element to the array, either '://' or ':' (see (2))
2697 * @param $url String: a URL to parse
2698 * @return Array: bits of the URL in an associative array, per PHP docs
2700 function wfParseUrl( $url ) {
2701 global $wgUrlProtocols; // Allow all protocols defined in DefaultSettings/LocalSettings.php
2702 wfSuppressWarnings();
2703 $bits = parse_url( $url );
2704 wfRestoreWarnings();
2709 // most of the protocols are followed by ://, but mailto: and sometimes news: not, check for it
2710 if ( in_array( $bits['scheme'] . '://', $wgUrlProtocols ) ) {
2711 $bits['delimiter'] = '://';
2712 } elseif ( in_array( $bits['scheme'] . ':', $wgUrlProtocols ) ) {
2713 $bits['delimiter'] = ':';
2714 // parse_url detects for news: and mailto: the host part of an url as path
2715 // We have to correct this wrong detection
2716 if ( isset( $bits['path'] ) ) {
2717 $bits['host'] = $bits['path'];
2728 * Make a URL index, appropriate for the el_index field of externallinks.
2730 * @param $url String
2733 function wfMakeUrlIndex( $url ) {
2734 $bits = wfParseUrl( $url );
2736 // Reverse the labels in the hostname, convert to lower case
2737 // For emails reverse domainpart only
2738 if ( $bits['scheme'] == 'mailto' ) {
2739 $mailparts = explode( '@', $bits['host'], 2 );
2740 if ( count( $mailparts ) === 2 ) {
2741 $domainpart = strtolower( implode( '.', array_reverse( explode( '.', $mailparts[1] ) ) ) );
2743 // No domain specified, don't mangle it
2746 $reversedHost = $domainpart . '@' . $mailparts[0];
2747 } else if ( isset( $bits['host'] ) ) {
2748 $reversedHost = strtolower( implode( '.', array_reverse( explode( '.', $bits['host'] ) ) ) );
2750 // In file: URIs for instance it's common to have an empty host,
2751 // which turns up as not getting a 'host' member from parse_url.
2752 $reversedHost = '.';
2754 // Add an extra dot to the end
2755 // Why? Is it in wrong place in mailto links?
2756 if ( substr( $reversedHost, -1, 1 ) !== '.' ) {
2757 $reversedHost .= '.';
2759 // Reconstruct the pseudo-URL
2760 $prot = $bits['scheme'];
2761 $index = $prot . $bits['delimiter'] . $reversedHost;
2762 // Leave out user and password. Add the port, path, query and fragment
2763 if ( isset( $bits['port'] ) ) {
2764 $index .= ':' . $bits['port'];
2766 if ( isset( $bits['path'] ) ) {
2767 // parse_url() removes the initial '/' from the path
2768 // for file: URLs with Windows-style paths, such as
2769 // file:///c:/windows/stuff. We need to add it back
2770 // to keep our division between host and path properly.
2771 if ( strlen( $bits['path'] ) > 0 && substr( $bits['path'], 0, 1 ) !== '/' ) {
2774 $index .= $bits['path'];
2778 if ( isset( $bits['query'] ) ) {
2779 $index .= '?' . $bits['query'];
2781 if ( isset( $bits['fragment'] ) ) {
2782 $index .= '#' . $bits['fragment'];
2788 * Do any deferred updates and clear the list
2790 * @param $commit String: set to 'commit' to commit after every update to
2791 * prevent lock contention
2793 function wfDoUpdates( $commit = '' ) {
2794 global $wgDeferredUpdateList;
2796 wfProfileIn( __METHOD__
);
2798 // No need to get master connections in case of empty updates array
2799 if ( !count( $wgDeferredUpdateList ) ) {
2800 wfProfileOut( __METHOD__
);
2804 $doCommit = $commit == 'commit';
2806 $dbw = wfGetDB( DB_MASTER
);
2809 foreach ( $wgDeferredUpdateList as $update ) {
2810 $update->doUpdate();
2812 if ( $doCommit && $dbw->trxLevel() ) {
2817 $wgDeferredUpdateList = array();
2818 wfProfileOut( __METHOD__
);
2822 * Convert an arbitrarily-long digit string from one numeric base
2823 * to another, optionally zero-padding to a minimum column width.
2825 * Supports base 2 through 36; digit values 10-36 are represented
2826 * as lowercase letters a-z. Input is case-insensitive.
2828 * @param $input String: of digits
2829 * @param $sourceBase Integer: 2-36
2830 * @param $destBase Integer: 2-36
2831 * @param $pad Integer: 1 or greater
2832 * @param $lowercase Boolean
2833 * @return String or false on invalid input
2835 function wfBaseConvert( $input, $sourceBase, $destBase, $pad = 1, $lowercase = true ) {
2836 $input = strval( $input );
2837 if( $sourceBase < 2 ||
2842 $sourceBase != intval( $sourceBase ) ||
2843 $destBase != intval( $destBase ) ||
2844 $pad != intval( $pad ) ||
2845 !is_string( $input ) ||
2849 $digitChars = ( $lowercase ) ?
'0123456789abcdefghijklmnopqrstuvwxyz' : '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
2850 $inDigits = array();
2853 // Decode and validate input string
2854 $input = strtolower( $input );
2855 for( $i = 0; $i < strlen( $input ); $i++
) {
2856 $n = strpos( $digitChars, $input[$i] );
2857 if( $n === false ||
$n > $sourceBase ) {
2863 // Iterate over the input, modulo-ing out an output digit
2864 // at a time until input is gone.
2865 while( count( $inDigits ) ) {
2867 $workDigits = array();
2870 foreach( $inDigits as $digit ) {
2871 $work *= $sourceBase;
2874 if( $work < $destBase ) {
2875 // Gonna need to pull another digit.
2876 if( count( $workDigits ) ) {
2877 // Avoid zero-padding; this lets us find
2878 // the end of the input very easily when
2879 // length drops to zero.
2883 // Finally! Actual division!
2884 $workDigits[] = intval( $work / $destBase );
2886 // Isn't it annoying that most programming languages
2887 // don't have a single divide-and-remainder operator,
2888 // even though the CPU implements it that way?
2889 $work = $work %
$destBase;
2893 // All that division leaves us with a remainder,
2894 // which is conveniently our next output digit.
2895 $outChars .= $digitChars[$work];
2898 $inDigits = $workDigits;
2901 while( strlen( $outChars ) < $pad ) {
2905 return strrev( $outChars );
2909 * Create an object with a given name and an array of construct parameters
2911 * @param $name String
2912 * @param $p Array: parameters
2913 * @deprecated since 1.18, warnings in 1.19, removal in 1.20
2915 function wfCreateObject( $name, $p ) {
2916 wfDeprecated( __FUNCTION__
);
2917 return MWFunction
::newObj( $name, $p );
2920 function wfHttpOnlySafe() {
2921 global $wgHttpOnlyBlacklist;
2923 if( isset( $_SERVER['HTTP_USER_AGENT'] ) ) {
2924 foreach( $wgHttpOnlyBlacklist as $regex ) {
2925 if( preg_match( $regex, $_SERVER['HTTP_USER_AGENT'] ) ) {
2935 * Initialise php session
2937 * @param $sessionId Bool
2939 function wfSetupSession( $sessionId = false ) {
2940 global $wgSessionsInMemcached, $wgCookiePath, $wgCookieDomain,
2941 $wgCookieSecure, $wgCookieHttpOnly, $wgSessionHandler;
2942 if( $wgSessionsInMemcached ) {
2943 if ( !defined( 'MW_COMPILED' ) ) {
2945 require_once( "$IP/includes/cache/MemcachedSessions.php" );
2947 session_set_save_handler( 'memsess_open', 'memsess_close', 'memsess_read',
2948 'memsess_write', 'memsess_destroy', 'memsess_gc' );
2950 // It's necessary to register a shutdown function to call session_write_close(),
2951 // because by the time the request shutdown function for the session module is
2952 // called, $wgMemc has already been destroyed. Shutdown functions registered
2953 // this way are called before object destruction.
2954 register_shutdown_function( 'memsess_write_close' );
2955 } elseif( $wgSessionHandler && $wgSessionHandler != ini_get( 'session.save_handler' ) ) {
2956 # Only set this if $wgSessionHandler isn't null and session.save_handler
2957 # hasn't already been set to the desired value (that causes errors)
2958 ini_set( 'session.save_handler', $wgSessionHandler );
2960 $httpOnlySafe = wfHttpOnlySafe() && $wgCookieHttpOnly;
2961 wfDebugLog( 'cookie',
2962 'session_set_cookie_params: "' . implode( '", "',
2968 $httpOnlySafe ) ) . '"' );
2969 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $httpOnlySafe );
2970 session_cache_limiter( 'private, must-revalidate' );
2972 session_id( $sessionId );
2974 wfSuppressWarnings();
2976 wfRestoreWarnings();
2980 * Get an object from the precompiled serialized directory
2982 * @param $name String
2983 * @return Mixed: the variable on success, false on failure
2985 function wfGetPrecompiledData( $name ) {
2988 $file = "$IP/serialized/$name";
2989 if ( file_exists( $file ) ) {
2990 $blob = file_get_contents( $file );
2992 return unserialize( $blob );
2999 * Get the name of the function which called this function
3002 * @return Bool|string
3004 function wfGetCaller( $level = 2 ) {
3005 $backtrace = wfDebugBacktrace();
3006 if ( isset( $backtrace[$level] ) ) {
3007 return wfFormatStackFrame( $backtrace[$level] );
3009 $caller = 'unknown';
3015 * Return a string consisting of callers in the stack. Useful sometimes
3016 * for profiling specific points.
3018 * @param $limit The maximum depth of the stack frame to return, or false for
3022 function wfGetAllCallers( $limit = 3 ) {
3023 $trace = array_reverse( wfDebugBacktrace() );
3024 if ( !$limit ||
$limit > count( $trace ) - 1 ) {
3025 $limit = count( $trace ) - 1;
3027 $trace = array_slice( $trace, -$limit - 1, $limit );
3028 return implode( '/', array_map( 'wfFormatStackFrame', $trace ) );
3032 * Return a string representation of frame
3034 * @param $frame Array
3037 function wfFormatStackFrame( $frame ) {
3038 return isset( $frame['class'] ) ?
3039 $frame['class'] . '::' . $frame['function'] :
3049 function wfMemcKey( /*... */ ) {
3050 $args = func_get_args();
3051 $key = wfWikiID() . ':' . implode( ':', $args );
3052 $key = str_replace( ' ', '_', $key );
3057 * Get a cache key for a foreign DB
3060 * @param $prefix String
3061 * @param varargs String
3064 function wfForeignMemcKey( $db, $prefix /*, ... */ ) {
3065 $args = array_slice( func_get_args(), 2 );
3067 $key = "$db-$prefix:" . implode( ':', $args );
3069 $key = $db . ':' . implode( ':', $args );
3075 * Get an ASCII string identifying this wiki
3076 * This is used as a prefix in memcached keys
3080 function wfWikiID() {
3081 global $wgDBprefix, $wgDBname;
3082 if ( $wgDBprefix ) {
3083 return "$wgDBname-$wgDBprefix";
3090 * Split a wiki ID into DB name and table prefix
3092 * @param $wiki String
3093 * @param $bits String
3095 function wfSplitWikiID( $wiki ) {
3096 $bits = explode( '-', $wiki, 2 );
3097 if ( count( $bits ) < 2 ) {
3104 * Get a Database object.
3106 * @param $db Integer: index of the connection to get. May be DB_MASTER for the
3107 * master (for write queries), DB_SLAVE for potentially lagged read
3108 * queries, or an integer >= 0 for a particular server.
3110 * @param $groups Mixed: query groups. An array of group names that this query
3111 * belongs to. May contain a single string if the query is only
3114 * @param $wiki String: the wiki ID, or false for the current wiki
3116 * Note: multiple calls to wfGetDB(DB_SLAVE) during the course of one request
3117 * will always return the same object, unless the underlying connection or load
3118 * balancer is manually destroyed.
3120 * Note 2: use $this->getDB() in maintenance scripts that may be invoked by
3121 * updater to ensure that a proper database is being updated.
3123 * @return DatabaseBase
3125 function &wfGetDB( $db, $groups = array(), $wiki = false ) {
3126 return wfGetLB( $wiki )->getConnection( $db, $groups, $wiki );
3130 * Get a load balancer object.
3132 * @param $wiki String: wiki ID, or false for the current wiki
3133 * @return LoadBalancer
3135 function wfGetLB( $wiki = false ) {
3136 return wfGetLBFactory()->getMainLB( $wiki );
3140 * Get the load balancer factory object
3144 function &wfGetLBFactory() {
3145 return LBFactory
::singleton();
3150 * Shortcut for RepoGroup::singleton()->findFile()
3152 * @param $title String or Title object
3153 * @param $options Associative array of options:
3154 * time: requested time for an archived image, or false for the
3155 * current version. An image object will be returned which was
3156 * created at the specified time.
3158 * ignoreRedirect: If true, do not follow file redirects
3160 * private: If true, return restricted (deleted) files if the current
3161 * user is allowed to view them. Otherwise, such files will not
3164 * bypassCache: If true, do not use the process-local cache of File objects
3166 * @return File, or false if the file does not exist
3168 function wfFindFile( $title, $options = array() ) {
3169 return RepoGroup
::singleton()->findFile( $title, $options );
3173 * Get an object referring to a locally registered file.
3174 * Returns a valid placeholder object if the file does not exist.
3176 * @param $title Title or String
3177 * @return File, or null if passed an invalid Title
3179 function wfLocalFile( $title ) {
3180 return RepoGroup
::singleton()->getLocalRepo()->newFile( $title );
3184 * Should low-performance queries be disabled?
3187 * @codeCoverageIgnore
3189 function wfQueriesMustScale() {
3190 global $wgMiserMode;
3192 ||
( SiteStats
::pages() > 100000
3193 && SiteStats
::edits() > 1000000
3194 && SiteStats
::users() > 10000 );
3198 * Get the path to a specified script file, respecting file
3199 * extensions; this is a wrapper around $wgScriptExtension etc.
3201 * @param $script String: script filename, sans extension
3204 function wfScript( $script = 'index' ) {
3205 global $wgScriptPath, $wgScriptExtension;
3206 return "{$wgScriptPath}/{$script}{$wgScriptExtension}";
3210 * Get the script URL.
3212 * @return script URL
3214 function wfGetScriptUrl() {
3215 if( isset( $_SERVER['SCRIPT_NAME'] ) ) {
3217 # as it was called, minus the query string.
3219 # Some sites use Apache rewrite rules to handle subdomains,
3220 # and have PHP set up in a weird way that causes PHP_SELF
3221 # to contain the rewritten URL instead of the one that the
3222 # outside world sees.
3224 # If in this mode, use SCRIPT_URL instead, which mod_rewrite
3225 # provides containing the "before" URL.
3226 return $_SERVER['SCRIPT_NAME'];
3228 return $_SERVER['URL'];
3233 * Convenience function converts boolean values into "true"
3234 * or "false" (string) values
3236 * @param $value Boolean
3239 function wfBoolToStr( $value ) {
3240 return $value ?
'true' : 'false';
3244 * Load an extension messages file
3246 * @deprecated since 1.16, warnings in 1.18, remove in 1.20
3247 * @codeCoverageIgnore
3249 function wfLoadExtensionMessages() {
3250 wfDeprecated( __FUNCTION__
);
3254 * Get a platform-independent path to the null file, e.g. /dev/null
3258 function wfGetNull() {
3259 return wfIsWindows()
3265 * Throws a warning that $function is deprecated
3267 * @param $function String
3270 function wfDeprecated( $function ) {
3271 static $functionsWarned = array();
3272 if ( !isset( $functionsWarned[$function] ) ) {
3273 $functionsWarned[$function] = true;
3274 wfWarn( "Use of $function is deprecated.", 2 );
3279 * Send a warning either to the debug log or in a PHP error depending on
3280 * $wgDevelopmentWarnings
3282 * @param $msg String: message to send
3283 * @param $callerOffset Integer: number of items to go back in the backtrace to
3284 * find the correct caller (1 = function calling wfWarn, ...)
3285 * @param $level Integer: PHP error level; only used when $wgDevelopmentWarnings
3288 function wfWarn( $msg, $callerOffset = 1, $level = E_USER_NOTICE
) {
3289 global $wgDevelopmentWarnings;
3291 $callers = wfDebugBacktrace();
3292 if ( isset( $callers[$callerOffset +
1] ) ) {
3293 $callerfunc = $callers[$callerOffset +
1];
3294 $callerfile = $callers[$callerOffset];
3295 if ( isset( $callerfile['file'] ) && isset( $callerfile['line'] ) ) {
3296 $file = $callerfile['file'] . ' at line ' . $callerfile['line'];
3298 $file = '(internal function)';
3301 if ( isset( $callerfunc['class'] ) ) {
3302 $func .= $callerfunc['class'] . '::';
3304 if ( isset( $callerfunc['function'] ) ) {
3305 $func .= $callerfunc['function'];
3307 $msg .= " [Called from $func in $file]";
3310 if ( $wgDevelopmentWarnings ) {
3311 trigger_error( $msg, $level );
3313 wfDebug( "$msg\n" );
3318 * Modern version of wfWaitForSlaves(). Instead of looking at replication lag
3319 * and waiting for it to go down, this waits for the slaves to catch up to the
3320 * master position. Use this when updating very large numbers of rows, as
3321 * in maintenance scripts, to avoid causing too much lag. Of course, this is
3322 * a no-op if there are no slaves.
3324 * @param $maxLag Integer (deprecated)
3325 * @param $wiki mixed Wiki identifier accepted by wfGetLB
3328 function wfWaitForSlaves( $maxLag = false, $wiki = false ) {
3329 $lb = wfGetLB( $wiki );
3330 // bug 27975 - Don't try to wait for slaves if there are none
3331 // Prevents permission error when getting master position
3332 if ( $lb->getServerCount() > 1 ) {
3333 $dbw = $lb->getConnection( DB_MASTER
);
3334 $pos = $dbw->getMasterPos();
3335 $lb->waitForAll( $pos );
3340 * Used to be used for outputting text in the installer/updater
3341 * @deprecated since 1.18, warnings in 1.19, remove in 1.20
3343 function wfOut( $s ) {
3344 wfDeprecated( __METHOD__
);
3345 global $wgCommandLineMode;
3346 if ( $wgCommandLineMode && !defined( 'MEDIAWIKI_INSTALL' ) ) {
3349 echo htmlspecialchars( $s );
3355 * Count down from $n to zero on the terminal, with a one-second pause
3356 * between showing each number. For use in command-line scripts.
3357 * @codeCoverageIgnore
3359 function wfCountDown( $n ) {
3360 for ( $i = $n; $i >= 0; $i-- ) {
3362 echo str_repeat( "\x08", strlen( $i +
1 ) );
3374 * Generate a random 32-character hexadecimal token.
3375 * @param $salt Mixed: some sort of salt, if necessary, to add to random
3376 * characters before hashing.
3378 * @codeCoverageIgnore
3380 function wfGenerateToken( $salt = '' ) {
3381 $salt = serialize( $salt );
3382 return md5( mt_rand( 0, 0x7fffffff ) . $salt );
3386 * Replace all invalid characters with -
3388 * @param $name Mixed: filename to process
3391 function wfStripIllegalFilenameChars( $name ) {
3392 global $wgIllegalFileChars;
3393 $name = wfBaseName( $name );
3394 $name = preg_replace(
3395 "/[^" . Title
::legalChars() . "]" .
3396 ( $wgIllegalFileChars ?
"|[" . $wgIllegalFileChars . "]" : '' ) .
3405 * Set PHP's memory limit to the larger of php.ini or $wgMemoryLimit;
3407 * @return Integer value memory was set to.
3409 function wfMemoryLimit() {
3410 global $wgMemoryLimit;
3411 $memlimit = wfShorthandToInteger( ini_get( 'memory_limit' ) );
3412 if( $memlimit != -1 ) {
3413 $conflimit = wfShorthandToInteger( $wgMemoryLimit );
3414 if( $conflimit == -1 ) {
3415 wfDebug( "Removing PHP's memory limit\n" );
3416 wfSuppressWarnings();
3417 ini_set( 'memory_limit', $conflimit );
3418 wfRestoreWarnings();
3420 } elseif ( $conflimit > $memlimit ) {
3421 wfDebug( "Raising PHP's memory limit to $conflimit bytes\n" );
3422 wfSuppressWarnings();
3423 ini_set( 'memory_limit', $conflimit );
3424 wfRestoreWarnings();
3432 * Converts shorthand byte notation to integer form
3434 * @param $string String
3437 function wfShorthandToInteger( $string = '' ) {
3438 $string = trim( $string );
3439 if( $string === '' ) {
3442 $last = $string[strlen( $string ) - 1];
3443 $val = intval( $string );
3448 // break intentionally missing
3452 // break intentionally missing
3462 * Get the normalised IETF language tag
3463 * See unit test for examples.
3465 * @param $code String: The language code.
3466 * @return $langCode String: The language code which complying with BCP 47 standards.
3468 function wfBCP47( $code ) {
3469 $codeSegment = explode( '-', $code );
3471 foreach ( $codeSegment as $segNo => $seg ) {
3472 if ( count( $codeSegment ) > 0 ) {
3473 // when previous segment is x, it is a private segment and should be lc
3474 if( $segNo > 0 && strtolower( $codeSegment[($segNo - 1)] ) == 'x') {
3475 $codeBCP[$segNo] = strtolower( $seg );
3476 // ISO 3166 country code
3477 } elseif ( ( strlen( $seg ) == 2 ) && ( $segNo > 0 ) ) {
3478 $codeBCP[$segNo] = strtoupper( $seg );
3479 // ISO 15924 script code
3480 } elseif ( ( strlen( $seg ) == 4 ) && ( $segNo > 0 ) ) {
3481 $codeBCP[$segNo] = ucfirst( strtolower( $seg ) );
3482 // Use lowercase for other cases
3484 $codeBCP[$segNo] = strtolower( $seg );
3487 // Use lowercase for single segment
3488 $codeBCP[$segNo] = strtolower( $seg );
3491 $langCode = implode( '-', $codeBCP );
3496 * Get a cache object.
3498 * @param integer $inputType Cache type, one the the CACHE_* constants.
3501 function wfGetCache( $inputType ) {
3502 return ObjectCache
::getInstance( $inputType );
3506 * Get the main cache object
3510 function wfGetMainCache() {
3511 global $wgMainCacheType;
3512 return ObjectCache
::getInstance( $wgMainCacheType );
3516 * Get the cache object used by the message cache
3520 function wfGetMessageCacheStorage() {
3521 global $wgMessageCacheType;
3522 return ObjectCache
::getInstance( $wgMessageCacheType );
3526 * Get the cache object used by the parser cache
3530 function wfGetParserCacheStorage() {
3531 global $wgParserCacheType;
3532 return ObjectCache
::getInstance( $wgParserCacheType );