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' );
89 function wfArrayDiff2_cmp( $a, $b ) {
90 if ( !is_array( $a ) ) {
91 return strcmp( $a, $b );
92 } elseif ( count( $a ) !== count( $b ) ) {
93 return count( $a ) < count( $b ) ?
-1 : 1;
97 while( ( list( , $valueA ) = each( $a ) ) && ( list( , $valueB ) = each( $b ) ) ) {
98 $cmp = strcmp( $valueA, $valueB );
109 * Returns an array where the values in the first array are replaced by the
110 * values in the second array with the corresponding keys
116 function wfArrayLookup( $a, $b ) {
117 return array_flip( array_intersect( array_flip( $a ), array_keys( $b ) ) );
121 * Appends to second array if $value differs from that in $default
123 * @param $key String|Int
124 * @param $value Mixed
125 * @param $default Mixed
126 * @param $changed Array to alter
128 function wfAppendToArrayIfNotDefault( $key, $value, $default, &$changed ) {
129 if ( is_null( $changed ) ) {
130 throw new MWException( 'GlobalFunctions::wfAppendToArrayIfNotDefault got null' );
132 if ( $default[$key] !== $value ) {
133 $changed[$key] = $value;
138 * Backwards array plus for people who haven't bothered to read the PHP manual
139 * XXX: will not darn your socks for you.
141 * @param $array1 Array
142 * @param [$array2, [...]] Arrays
145 function wfArrayMerge( $array1/* ... */ ) {
146 $args = func_get_args();
147 $args = array_reverse( $args, true );
149 foreach ( $args as $arg ) {
156 * Merge arrays in the style of getUserPermissionsErrors, with duplicate removal
158 * wfMergeErrorArrays(
159 * array( array( 'x' ) ),
160 * array( array( 'x', '2' ) ),
161 * array( array( 'x' ) ),
162 * array( array( 'y') )
173 function wfMergeErrorArrays( /*...*/ ) {
174 $args = func_get_args();
176 foreach ( $args as $errors ) {
177 foreach ( $errors as $params ) {
178 # @todo FIXME: Sometimes get nested arrays for $params,
179 # which leads to E_NOTICEs
180 $spec = implode( "\t", $params );
181 $out[$spec] = $params;
184 return array_values( $out );
188 * Insert array into another array after the specified *KEY*
190 * @param $array Array: The array.
191 * @param $insert Array: The array to insert.
192 * @param $after Mixed: The key to insert after
195 function wfArrayInsertAfter( $array, $insert, $after ) {
196 // Find the offset of the element to insert after.
197 $keys = array_keys( $array );
198 $offsetByKey = array_flip( $keys );
200 $offset = $offsetByKey[$after];
202 // Insert at the specified offset
203 $before = array_slice( $array, 0, $offset +
1, true );
204 $after = array_slice( $array, $offset +
1, count( $array ) - $offset, true );
206 $output = $before +
$insert +
$after;
212 * Recursively converts the parameter (an object) to an array with the same data
214 * @param $objOrArray Object|Array
215 * @param $recursive Bool
218 function wfObjectToArray( $objOrArray, $recursive = true ) {
220 if( is_object( $objOrArray ) ) {
221 $objOrArray = get_object_vars( $objOrArray );
223 foreach ( $objOrArray as $key => $value ) {
224 if ( $recursive && ( is_object( $value ) ||
is_array( $value ) ) ) {
225 $value = wfObjectToArray( $value );
228 $array[$key] = $value;
235 * Wrapper around array_map() which also taints variables
237 * @param $function Callback
238 * @param $input Array
241 function wfArrayMap( $function, $input ) {
242 $ret = array_map( $function, $input );
243 foreach ( $ret as $key => $value ) {
244 $taint = istainted( $input[$key] );
246 taint( $ret[$key], $taint );
253 * Get a random decimal value between 0 and 1, in a way
254 * not likely to give duplicate values for any realistic
255 * number of articles.
259 function wfRandom() {
260 # The maximum random value is "only" 2^31-1, so get two random
261 # values to reduce the chance of dupes
262 $max = mt_getrandmax() +
1;
263 $rand = number_format( ( mt_rand() * $max +
mt_rand() )
264 / $max / $max, 12, '.', '' );
269 * We want some things to be included as literal characters in our title URLs
270 * for prettiness, which urlencode encodes by default. According to RFC 1738,
271 * all of the following should be safe:
275 * But + is not safe because it's used to indicate a space; &= are only safe in
276 * paths and not in queries (and we don't distinguish here); ' seems kind of
277 * scary; and urlencode() doesn't touch -_. to begin with. Plus, although /
278 * is reserved, we don't care. So the list we unescape is:
282 * However, IIS7 redirects fail when the url contains a colon (Bug 22709),
283 * so no fancy : for IIS7.
285 * %2F in the page titles seems to fatally break for some reason.
290 function wfUrlencode( $s ) {
292 if ( is_null( $needle ) ) {
293 $needle = array( '%3B', '%40', '%24', '%21', '%2A', '%28', '%29', '%2C', '%2F' );
294 if ( !isset( $_SERVER['SERVER_SOFTWARE'] ) ||
( strpos( $_SERVER['SERVER_SOFTWARE'], 'Microsoft-IIS/7' ) === false ) ) {
299 $s = urlencode( $s );
302 array( ';', '@', '$', '!', '*', '(', ')', ',', '/', ':' ),
310 * Sends a line to the debug log if enabled or, optionally, to a comment in output.
311 * In normal operation this is a NOP.
313 * Controlling globals:
314 * $wgDebugLogFile - points to the log file
315 * $wgProfileOnly - if set, normal debug messages will not be recorded.
316 * $wgDebugRawPage - if false, 'action=raw' hits will not result in debug output.
317 * $wgDebugComments - if on, some debug items may appear in comments in the HTML output.
319 * @param $text String
320 * @param $logonly Bool: set true to avoid appearing in HTML when $wgDebugComments is set
322 function wfDebug( $text, $logonly = false ) {
323 global $wgOut, $wgDebugLogFile, $wgDebugComments, $wgProfileOnly, $wgDebugRawPage;
324 global $wgDebugLogPrefix, $wgShowDebug;
326 static $cache = array(); // Cache of unoutputted messages
327 $text = wfDebugTimer() . $text;
329 # Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
330 if ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' && !$wgDebugRawPage ) {
334 if ( ( $wgDebugComments ||
$wgShowDebug ) && !$logonly ) {
337 if ( isset( $wgOut ) && is_object( $wgOut ) ) {
338 // add the message and any cached messages to the output
339 array_map( array( $wgOut, 'debug' ), $cache );
343 if ( wfRunHooks( 'Debug', array( $text, null /* no log group */ ) ) ) {
344 if ( $wgDebugLogFile != '' && !$wgProfileOnly ) {
345 # Strip unprintables; they can switch terminal modes when binary data
346 # gets dumped, which is pretty annoying.
347 $text = preg_replace( '![\x00-\x08\x0b\x0c\x0e-\x1f]!', ' ', $text );
348 $text = $wgDebugLogPrefix . $text;
349 wfErrorLog( $text, $wgDebugLogFile );
355 * Get microsecond timestamps for debug logs
359 function wfDebugTimer() {
360 global $wgDebugTimestamps;
361 if ( !$wgDebugTimestamps ) {
364 static $start = null;
366 if ( $start === null ) {
367 $start = microtime( true );
368 $prefix = "\n$start";
370 $prefix = sprintf( "%6.4f", microtime( true ) - $start );
373 return $prefix . ' ';
377 * Send a line giving PHP memory usage.
379 * @param $exact Bool: print exact values instead of kilobytes (default: false)
381 function wfDebugMem( $exact = false ) {
382 $mem = memory_get_usage();
384 $mem = floor( $mem / 1024 ) . ' kilobytes';
388 wfDebug( "Memory usage: $mem\n" );
392 * Send a line to a supplementary debug log file, if configured, or main debug log if not.
393 * $wgDebugLogGroups[$logGroup] should be set to a filename to send to a separate log.
395 * @param $logGroup String
396 * @param $text String
397 * @param $public Bool: whether to log the event in the public log if no private
398 * log file is specified, (default true)
400 function wfDebugLog( $logGroup, $text, $public = true ) {
401 global $wgDebugLogGroups, $wgShowHostnames;
402 $text = trim( $text ) . "\n";
403 if( isset( $wgDebugLogGroups[$logGroup] ) ) {
404 $time = wfTimestamp( TS_DB
);
406 if ( $wgShowHostnames ) {
407 $host = wfHostname();
411 if ( wfRunHooks( 'Debug', array( $text, $logGroup ) ) ) {
412 wfErrorLog( "$time $host $wiki: $text", $wgDebugLogGroups[$logGroup] );
414 } elseif ( $public === true ) {
415 wfDebug( $text, true );
420 * Log for database errors
422 * @param $text String: database error message.
424 function wfLogDBError( $text ) {
425 global $wgDBerrorLog, $wgDBname;
426 if ( $wgDBerrorLog ) {
427 $host = trim(`hostname`
);
428 $text = date( 'D M j G:i:s T Y' ) . "\t$host\t$wgDBname\t$text";
429 wfErrorLog( $text, $wgDBerrorLog );
434 * Log to a file without getting "file size exceeded" signals.
436 * Can also log to TCP or UDP with the syntax udp://host:port/prefix. This will
437 * send lines to the specified port, prefixed by the specified prefix and a space.
439 * @param $text String
440 * @param $file String filename
442 function wfErrorLog( $text, $file ) {
443 if ( substr( $file, 0, 4 ) == 'udp:' ) {
444 # Needs the sockets extension
445 if ( preg_match( '!^(tcp|udp):(?://)?\[([0-9a-fA-F:]+)\]:(\d+)(?:/(.*))?$!', $file, $m ) ) {
446 // IPv6 bracketed host
448 $port = intval( $m[3] );
449 $prefix = isset( $m[4] ) ?
$m[4] : false;
451 } elseif ( preg_match( '!^(tcp|udp):(?://)?([a-zA-Z0-9.-]+):(\d+)(?:/(.*))?$!', $file, $m ) ) {
453 if ( !IP
::isIPv4( $host ) ) {
454 $host = gethostbyname( $host );
456 $port = intval( $m[3] );
457 $prefix = isset( $m[4] ) ?
$m[4] : false;
460 throw new MWException( __METHOD__
. ': Invalid UDP specification' );
463 // Clean it up for the multiplexer
464 if ( strval( $prefix ) !== '' ) {
465 $text = preg_replace( '/^/m', $prefix . ' ', $text );
468 if ( strlen( $text ) > 65534 ) {
469 $text = substr( $text, 0, 65534 );
472 if ( substr( $text, -1 ) != "\n" ) {
475 } elseif ( strlen( $text ) > 65535 ) {
476 $text = substr( $text, 0, 65535 );
479 $sock = socket_create( $domain, SOCK_DGRAM
, SOL_UDP
);
483 socket_sendto( $sock, $text, strlen( $text ), 0, $host, $port );
484 socket_close( $sock );
486 wfSuppressWarnings();
487 $exists = file_exists( $file );
488 $size = $exists ?
filesize( $file ) : false;
489 if ( !$exists ||
( $size !== false && $size +
strlen( $text ) < 0x7fffffff ) ) {
490 file_put_contents( $file, $text, FILE_APPEND
);
499 function wfLogProfilingData() {
500 global $wgRequestTime, $wgDebugLogFile, $wgDebugRawPage, $wgRequest;
501 global $wgProfileLimit, $wgUser;
503 $profiler = Profiler
::instance();
505 # Profiling must actually be enabled...
506 if ( $profiler->isStub() ) {
510 // Get total page request time and only show pages that longer than
511 // $wgProfileLimit time (default is 0)
513 $elapsed = $now - $wgRequestTime;
514 if ( $elapsed <= $wgProfileLimit ) {
518 $profiler->logData();
520 // Check whether this should be logged in the debug file.
521 if ( $wgDebugLogFile == '' ||
( $wgRequest->getVal( 'action' ) == 'raw' && !$wgDebugRawPage ) ) {
526 if ( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) {
527 $forward = ' forwarded for ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
529 if ( !empty( $_SERVER['HTTP_CLIENT_IP'] ) ) {
530 $forward .= ' client IP ' . $_SERVER['HTTP_CLIENT_IP'];
532 if ( !empty( $_SERVER['HTTP_FROM'] ) ) {
533 $forward .= ' from ' . $_SERVER['HTTP_FROM'];
536 $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
538 // Don't load $wgUser at this late stage just for statistics purposes
539 // @todo FIXME: We can detect some anons even if it is not loaded. See User::getId()
540 if ( $wgUser->isItemLoaded( 'id' ) && $wgUser->isAnon() ) {
543 $log = sprintf( "%s\t%04.3f\t%s\n",
544 gmdate( 'YmdHis' ), $elapsed,
545 urldecode( $wgRequest->getRequestURL() . $forward ) );
547 wfErrorLog( $log . $profiler->getOutput(), $wgDebugLogFile );
551 * Check if the wiki read-only lock file is present. This can be used to lock
552 * off editing functions, but doesn't guarantee that the database will not be
557 function wfReadOnly() {
558 global $wgReadOnlyFile, $wgReadOnly;
560 if ( !is_null( $wgReadOnly ) ) {
561 return (bool)$wgReadOnly;
563 if ( $wgReadOnlyFile == '' ) {
566 // Set $wgReadOnly for faster access next time
567 if ( is_file( $wgReadOnlyFile ) ) {
568 $wgReadOnly = file_get_contents( $wgReadOnlyFile );
572 return (bool)$wgReadOnly;
575 function wfReadOnlyReason() {
582 * Return a Language object from $langcode
584 * @param $langcode Mixed: either:
585 * - a Language object
586 * - code of the language to get the message for, if it is
587 * a valid code create a language for that language, if
588 * it is a string but not a valid code then make a basic
590 * - a boolean: if it's false then use the current users
591 * language (as a fallback for the old parameter
592 * functionality), or if it is true then use the wikis
593 * @return Language object
595 function wfGetLangObj( $langcode = false ) {
596 # Identify which language to get or create a language object for.
597 # Using is_object here due to Stub objects.
598 if( is_object( $langcode ) ) {
599 # Great, we already have the object (hopefully)!
603 global $wgContLang, $wgLanguageCode;
604 if( $langcode === true ||
$langcode === $wgLanguageCode ) {
605 # $langcode is the language code of the wikis content language object.
606 # or it is a boolean and value is true
611 if( $langcode === false ||
$langcode === $wgLang->getCode() ) {
612 # $langcode is the language code of user language object.
613 # or it was a boolean and value is false
617 $validCodes = array_keys( Language
::getLanguageNames() );
618 if( in_array( $langcode, $validCodes ) ) {
619 # $langcode corresponds to a valid language.
620 return Language
::factory( $langcode );
623 # $langcode is a string, but not a valid language code; use content language.
624 wfDebug( "Invalid language code passed to wfGetLangObj, falling back to content language.\n" );
629 * Use this instead of $wgContLang, when working with user interface.
630 * User interface is currently hard coded according to wiki content language
631 * in many ways, especially regarding to text direction. There is lots stuff
632 * to fix, hence this function to keep the old behaviour unless the global
633 * $wgBetterDirectionality is enabled (or removed when everything works).
637 function wfUILang() {
638 global $wgBetterDirectionality;
639 return wfGetLangObj( !$wgBetterDirectionality );
643 * This is the new function for getting translated interface messages.
644 * See the Message class for documentation how to use them.
645 * The intention is that this function replaces all old wfMsg* functions.
646 * @param $key \string Message key.
647 * Varargs: normal message parameters.
651 function wfMessage( $key /*...*/) {
652 $params = func_get_args();
653 array_shift( $params );
654 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
655 $params = $params[0];
657 return new Message( $key, $params );
661 * This function accepts multiple message keys and returns a message instance
662 * for the first message which is non-empty. If all messages are empty then an
663 * instance of the first message key is returned.
664 * @param varargs: message keys
668 function wfMessageFallback( /*...*/ ) {
669 $args = func_get_args();
670 return MWFunction
::callArray( 'Message::newFallbackSequence', $args );
674 * Get a message from anywhere, for the current user language.
676 * Use wfMsgForContent() instead if the message should NOT
677 * change depending on the user preferences.
679 * @param $key String: lookup key for the message, usually
680 * defined in languages/Language.php
682 * This function also takes extra optional parameters (not
683 * shown in the function definition), which can be used to
684 * insert variable text into the predefined message.
687 function wfMsg( $key ) {
688 $args = func_get_args();
689 array_shift( $args );
690 return wfMsgReal( $key, $args, true );
694 * Same as above except doesn't transform the message
699 function wfMsgNoTrans( $key ) {
700 $args = func_get_args();
701 array_shift( $args );
702 return wfMsgReal( $key, $args, true, false, false );
706 * Get a message from anywhere, for the current global language
707 * set with $wgLanguageCode.
709 * Use this if the message should NOT change dependent on the
710 * language set in the user's preferences. This is the case for
711 * most text written into logs, as well as link targets (such as
712 * the name of the copyright policy page). Link titles, on the
713 * other hand, should be shown in the UI language.
715 * Note that MediaWiki allows users to change the user interface
716 * language in their preferences, but a single installation
717 * typically only contains content in one language.
719 * Be wary of this distinction: If you use wfMsg() where you should
720 * use wfMsgForContent(), a user of the software may have to
721 * customize potentially hundreds of messages in
722 * order to, e.g., fix a link in every possible language.
724 * @param $key String: lookup key for the message, usually
725 * defined in languages/Language.php
728 function wfMsgForContent( $key ) {
729 global $wgForceUIMsgAsContentMsg;
730 $args = func_get_args();
731 array_shift( $args );
733 if( is_array( $wgForceUIMsgAsContentMsg ) &&
734 in_array( $key, $wgForceUIMsgAsContentMsg ) )
738 return wfMsgReal( $key, $args, true, $forcontent );
742 * Same as above except doesn't transform the message
747 function wfMsgForContentNoTrans( $key ) {
748 global $wgForceUIMsgAsContentMsg;
749 $args = func_get_args();
750 array_shift( $args );
752 if( is_array( $wgForceUIMsgAsContentMsg ) &&
753 in_array( $key, $wgForceUIMsgAsContentMsg ) )
757 return wfMsgReal( $key, $args, true, $forcontent, false );
761 * Get a message from the language file, for the UI elements
763 * @deprecated since 1.18; use wfMessage()
765 function wfMsgNoDB( $key ) {
766 wfDeprecated( __FUNCTION__
);
767 $args = func_get_args();
768 array_shift( $args );
769 return wfMsgReal( $key, $args, false );
773 * Get a message from the language file, for the content
775 * @deprecated since 1.18; use wfMessage()
777 function wfMsgNoDBForContent( $key ) {
778 wfDeprecated( __FUNCTION__
);
779 global $wgForceUIMsgAsContentMsg;
780 $args = func_get_args();
781 array_shift( $args );
783 if( is_array( $wgForceUIMsgAsContentMsg ) &&
784 in_array( $key, $wgForceUIMsgAsContentMsg ) )
788 return wfMsgReal( $key, $args, false, $forcontent );
793 * Really get a message
795 * @param $key String: key to get.
797 * @param $useDB Boolean
798 * @param $forContent Mixed: Language code, or false for user lang, true for content lang.
799 * @param $transform Boolean: Whether or not to transform the message.
800 * @return String: the requested message.
802 function wfMsgReal( $key, $args, $useDB = true, $forContent = false, $transform = true ) {
803 wfProfileIn( __METHOD__
);
804 $message = wfMsgGetKey( $key, $useDB, $forContent, $transform );
805 $message = wfMsgReplaceArgs( $message, $args );
806 wfProfileOut( __METHOD__
);
811 * This function provides the message source for messages to be edited which are *not* stored in the database.
813 * @deprecated since 1.18; use wfMessage()
816 function wfMsgWeirdKey( $key ) {
817 wfDeprecated( __FUNCTION__
);
818 $source = wfMsgGetKey( $key, false, true, false );
819 if ( wfEmptyMsg( $key ) ) {
827 * Fetch a message string value, but don't replace any keys yet.
831 * @param $langCode String: Code of the language to get the message for, or
832 * behaves as a content language switch if it is a boolean.
833 * @param $transform Boolean: whether to parse magic words, etc.
836 function wfMsgGetKey( $key, $useDB, $langCode = false, $transform = true ) {
837 wfRunHooks( 'NormalizeMessageKey', array( &$key, &$useDB, &$langCode, &$transform ) );
839 $cache = MessageCache
::singleton();
840 $message = $cache->get( $key, $useDB, $langCode );
841 if( $message === false ) {
842 $message = '<' . htmlspecialchars( $key ) . '>';
843 } elseif ( $transform ) {
844 $message = $cache->transform( $message );
850 * Replace message parameter keys on the given formatted output.
852 * @param $message String
857 function wfMsgReplaceArgs( $message, $args ) {
858 # Fix windows line-endings
859 # Some messages are split with explode("\n", $msg)
860 $message = str_replace( "\r", '', $message );
863 if ( count( $args ) ) {
864 if ( is_array( $args[0] ) ) {
865 $args = array_values( $args[0] );
867 $replacementKeys = array();
868 foreach( $args as $n => $param ) {
869 $replacementKeys['$' . ( $n +
1 )] = $param;
871 $message = strtr( $message, $replacementKeys );
878 * Return an HTML-escaped version of a message.
879 * Parameter replacements, if any, are done *after* the HTML-escaping,
880 * so parameters may contain HTML (eg links or form controls). Be sure
881 * to pre-escape them if you really do want plaintext, or just wrap
882 * the whole thing in htmlspecialchars().
885 * @param string ... parameters
888 function wfMsgHtml( $key ) {
889 $args = func_get_args();
890 array_shift( $args );
891 return wfMsgReplaceArgs( htmlspecialchars( wfMsgGetKey( $key, true ) ), $args );
895 * Return an HTML version of message
896 * Parameter replacements, if any, are done *after* parsing the wiki-text message,
897 * so parameters may contain HTML (eg links or form controls). Be sure
898 * to pre-escape them if you really do want plaintext, or just wrap
899 * the whole thing in htmlspecialchars().
902 * @param string ... parameters
905 function wfMsgWikiHtml( $key ) {
906 $args = func_get_args();
907 array_shift( $args );
908 return wfMsgReplaceArgs(
909 MessageCache
::singleton()->parse( wfMsgGetKey( $key, true ), null, /* can't be set to false */ true )->getText(),
914 * Returns message in the requested format
915 * @param $key String: key of the message
916 * @param $options Array: processing rules. Can take the following options:
917 * <i>parse</i>: parses wikitext to HTML
918 * <i>parseinline</i>: parses wikitext to HTML and removes the surrounding
919 * p's added by parser or tidy
920 * <i>escape</i>: filters message through htmlspecialchars
921 * <i>escapenoentities</i>: same, but allows entity references like   through
922 * <i>replaceafter</i>: parameters are substituted after parsing or escaping
923 * <i>parsemag</i>: transform the message using magic phrases
924 * <i>content</i>: fetch message for content language instead of interface
925 * Also can accept a single associative argument, of the form 'language' => 'xx':
926 * <i>language</i>: Language object or language code to fetch message for
927 * (overriden by <i>content</i>).
928 * Behavior for conflicting options (e.g., parse+parseinline) is undefined.
932 function wfMsgExt( $key, $options ) {
933 $args = func_get_args();
934 array_shift( $args );
935 array_shift( $args );
936 $options = (array)$options;
938 foreach( $options as $arrayKey => $option ) {
939 if( !preg_match( '/^[0-9]+|language$/', $arrayKey ) ) {
940 # An unknown index, neither numeric nor "language"
941 wfWarn( "wfMsgExt called with incorrect parameter key $arrayKey", 1, E_USER_WARNING
);
942 } elseif( preg_match( '/^[0-9]+$/', $arrayKey ) && !in_array( $option,
943 array( 'parse', 'parseinline', 'escape', 'escapenoentities',
944 'replaceafter', 'parsemag', 'content' ) ) ) {
945 # A numeric index with unknown value
946 wfWarn( "wfMsgExt called with incorrect parameter $option", 1, E_USER_WARNING
);
950 if( in_array( 'content', $options, true ) ) {
954 } elseif( array_key_exists( 'language', $options ) ) {
956 $langCode = wfGetLangObj( $options['language'] );
957 $langCodeObj = $langCode;
964 $string = wfMsgGetKey( $key, /*DB*/true, $langCode, /*Transform*/false );
966 if( !in_array( 'replaceafter', $options, true ) ) {
967 $string = wfMsgReplaceArgs( $string, $args );
970 $messageCache = MessageCache
::singleton();
971 if( in_array( 'parse', $options, true ) ) {
972 $string = $messageCache->parse( $string, null, true, !$forContent, $langCodeObj )->getText();
973 } elseif ( in_array( 'parseinline', $options, true ) ) {
974 $string = $messageCache->parse( $string, null, true, !$forContent, $langCodeObj )->getText();
976 if( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $string, $m ) ) {
979 } elseif ( in_array( 'parsemag', $options, true ) ) {
980 $string = $messageCache->transform( $string,
981 !$forContent, $langCodeObj );
984 if ( in_array( 'escape', $options, true ) ) {
985 $string = htmlspecialchars ( $string );
986 } elseif ( in_array( 'escapenoentities', $options, true ) ) {
987 $string = Sanitizer
::escapeHtmlAllowEntities( $string );
990 if( in_array( 'replaceafter', $options, true ) ) {
991 $string = wfMsgReplaceArgs( $string, $args );
998 * Since wfMsg() and co suck, they don't return false if the message key they
999 * looked up didn't exist but a XHTML string, this function checks for the
1000 * nonexistance of messages by checking the MessageCache::get() result directly.
1002 * @param $key String: the message key looked up
1003 * @return Boolean True if the message *doesn't* exist.
1005 function wfEmptyMsg( $key ) {
1006 return MessageCache
::singleton()->get( $key, /*useDB*/true, /*content*/false ) === false;
1010 * Print an error message and die, returning nonzero to the shell if any. Plain die()
1011 * fails to return nonzero to the shell if you pass a string. Entry points may customise
1012 * this function to return a prettier error message, but implementations must not assume
1013 * access to any of the usual MediaWiki infrastructure (AutoLoader, localisation, database,
1014 * etc). This should not be called directly once $wgFullyInitialised is set; instead,
1015 * throw an exception and let Exception.php handle whether or not it's possible to show
1018 * @param $msg String
1020 if( !function_exists( 'wfDie' ) ){
1021 function wfDie( $msg = '' ) {
1028 * Throw a debugging exception. This function previously once exited the process,
1029 * but now throws an exception instead, with similar results.
1031 * @param $msg String: message shown when dieing.
1033 function wfDebugDieBacktrace( $msg = '' ) {
1034 throw new MWException( $msg );
1038 * Fetch server name for use in error reporting etc.
1039 * Use real server name if available, so we know which machine
1040 * in a server farm generated the current page.
1044 function wfHostname() {
1046 if ( is_null( $host ) ) {
1047 if ( function_exists( 'posix_uname' ) ) {
1048 // This function not present on Windows
1049 $uname = @posix_uname
();
1053 if( is_array( $uname ) && isset( $uname['nodename'] ) ) {
1054 $host = $uname['nodename'];
1055 } elseif ( getenv( 'COMPUTERNAME' ) ) {
1056 # Windows computer name
1057 $host = getenv( 'COMPUTERNAME' );
1059 # This may be a virtual server.
1060 $host = $_SERVER['SERVER_NAME'];
1067 * Returns a HTML comment with the elapsed time since request.
1068 * This method has no side effects.
1072 function wfReportTime() {
1073 global $wgRequestTime, $wgShowHostnames;
1076 $elapsed = $now - $wgRequestTime;
1078 return $wgShowHostnames
1079 ?
sprintf( '<!-- Served by %s in %01.3f secs. -->', wfHostname(), $elapsed )
1080 : sprintf( '<!-- Served in %01.3f secs. -->', $elapsed );
1084 * Safety wrapper for debug_backtrace().
1086 * With Zend Optimizer 3.2.0 loaded, this causes segfaults under somewhat
1087 * murky circumstances, which may be triggered in part by stub objects
1088 * or other fancy talkin'.
1090 * Will return an empty array if Zend Optimizer is detected or if
1091 * debug_backtrace is disabled, otherwise the output from
1092 * debug_backtrace() (trimmed).
1094 * @return array of backtrace information
1096 function wfDebugBacktrace() {
1097 static $disabled = null;
1099 if( extension_loaded( 'Zend Optimizer' ) ) {
1100 wfDebug( "Zend Optimizer detected; skipping debug_backtrace for safety.\n" );
1104 if ( is_null( $disabled ) ) {
1106 $functions = explode( ',', ini_get( 'disable_functions' ) );
1107 $functions = array_map( 'trim', $functions );
1108 $functions = array_map( 'strtolower', $functions );
1109 if ( in_array( 'debug_backtrace', $functions ) ) {
1110 wfDebug( "debug_backtrace is in disabled_functions\n" );
1118 return array_slice( debug_backtrace(), 1 );
1122 * Get a debug backtrace as a string
1126 function wfBacktrace() {
1127 global $wgCommandLineMode;
1129 if ( $wgCommandLineMode ) {
1134 $backtrace = wfDebugBacktrace();
1135 foreach( $backtrace as $call ) {
1136 if( isset( $call['file'] ) ) {
1137 $f = explode( DIRECTORY_SEPARATOR
, $call['file'] );
1138 $file = $f[count( $f ) - 1];
1142 if( isset( $call['line'] ) ) {
1143 $line = $call['line'];
1147 if ( $wgCommandLineMode ) {
1148 $msg .= "$file line $line calls ";
1150 $msg .= '<li>' . $file . ' line ' . $line . ' calls ';
1152 if( !empty( $call['class'] ) ) {
1153 $msg .= $call['class'] . '::';
1155 $msg .= $call['function'] . '()';
1157 if ( $wgCommandLineMode ) {
1163 if ( $wgCommandLineMode ) {
1173 * Get the name of the function which called this function
1176 * @return Bool|string
1178 function wfGetCaller( $level = 2 ) {
1179 $backtrace = wfDebugBacktrace();
1180 if ( isset( $backtrace[$level] ) ) {
1181 return wfFormatStackFrame( $backtrace[$level] );
1183 $caller = 'unknown';
1189 * Return a string consisting of callers in the stack. Useful sometimes
1190 * for profiling specific points.
1192 * @param $limit The maximum depth of the stack frame to return, or false for
1196 function wfGetAllCallers( $limit = 3 ) {
1197 $trace = array_reverse( wfDebugBacktrace() );
1198 if ( !$limit ||
$limit > count( $trace ) - 1 ) {
1199 $limit = count( $trace ) - 1;
1201 $trace = array_slice( $trace, -$limit - 1, $limit );
1202 return implode( '/', array_map( 'wfFormatStackFrame', $trace ) );
1206 * Return a string representation of frame
1208 * @param $frame Array
1211 function wfFormatStackFrame( $frame ) {
1212 return isset( $frame['class'] ) ?
1213 $frame['class'] . '::' . $frame['function'] :
1218 /* Some generic result counters, pulled out of SearchEngine */
1224 * @param $offset Int
1228 function wfShowingResults( $offset, $limit ) {
1232 array( 'parseinline' ),
1233 $wgLang->formatNum( $limit ),
1234 $wgLang->formatNum( $offset +
1 )
1241 * @param $offset Int
1246 function wfShowingResultsNum( $offset, $limit, $num ) {
1249 'showingresultsnum',
1250 array( 'parseinline' ),
1251 $wgLang->formatNum( $limit ),
1252 $wgLang->formatNum( $offset +
1 ),
1253 $wgLang->formatNum( $num )
1258 * Generate (prev x| next x) (20|50|100...) type links for paging
1260 * @param $offset String
1261 * @param $limit Integer
1262 * @param $link String
1263 * @param $query String: optional URL query parameter string
1264 * @param $atend Bool: optional param for specified if this is the last page
1267 function wfViewPrevNext( $offset, $limit, $link, $query = '', $atend = false ) {
1269 $fmtLimit = $wgLang->formatNum( $limit );
1270 // @todo FIXME: Why on earth this needs one message for the text and another one for tooltip?
1271 # Get prev/next link display text
1272 $prev = wfMsgExt( 'prevn', array( 'parsemag', 'escape' ), $fmtLimit );
1273 $next = wfMsgExt( 'nextn', array( 'parsemag', 'escape' ), $fmtLimit );
1274 # Get prev/next link title text
1275 $pTitle = wfMsgExt( 'prevn-title', array( 'parsemag', 'escape' ), $fmtLimit );
1276 $nTitle = wfMsgExt( 'nextn-title', array( 'parsemag', 'escape' ), $fmtLimit );
1277 # Fetch the title object
1278 if( is_object( $link ) ) {
1281 $title = Title
::newFromText( $link );
1282 if( is_null( $title ) ) {
1286 # Make 'previous' link
1287 if( 0 != $offset ) {
1288 $po = $offset - $limit;
1289 $po = max( $po, 0 );
1290 $q = "limit={$limit}&offset={$po}";
1291 if( $query != '' ) {
1294 $plink = '<a href="' . $title->escapeLocalURL( $q ) . "\" title=\"{$pTitle}\" class=\"mw-prevlink\">{$prev}</a>";
1299 $no = $offset +
$limit;
1300 $q = "limit={$limit}&offset={$no}";
1301 if( $query != '' ) {
1307 $nlink = '<a href="' . $title->escapeLocalURL( $q ) . "\" title=\"{$nTitle}\" class=\"mw-nextlink\">{$next}</a>";
1309 # Make links to set number of items per page
1310 $nums = $wgLang->pipeList( array(
1311 wfNumLink( $offset, 20, $title, $query ),
1312 wfNumLink( $offset, 50, $title, $query ),
1313 wfNumLink( $offset, 100, $title, $query ),
1314 wfNumLink( $offset, 250, $title, $query ),
1315 wfNumLink( $offset, 500, $title, $query )
1317 return wfMsgHtml( 'viewprevnext', $plink, $nlink, $nums );
1321 * Generate links for (20|50|100...) items-per-page links
1323 * @param $offset String
1324 * @param $limit Integer
1325 * @param $title Title
1326 * @param $query String: optional URL query parameter string
1328 function wfNumLink( $offset, $limit, $title, $query = '' ) {
1330 if( $query == '' ) {
1335 $q .= "limit={$limit}&offset={$offset}";
1336 $fmtLimit = $wgLang->formatNum( $limit );
1337 $lTitle = wfMsgExt( 'shown-title', array( 'parsemag', 'escape' ), $limit );
1338 $s = '<a href="' . $title->escapeLocalURL( $q ) . "\" title=\"{$lTitle}\" class=\"mw-numlink\">{$fmtLimit}</a>";
1344 * @todo FIXME: We may want to blacklist some broken browsers
1346 * @param $force Bool
1347 * @return bool Whereas client accept gzip compression
1349 function wfClientAcceptsGzip( $force = false ) {
1350 static $result = null;
1351 if ( $result === null ||
$force ) {
1353 if( isset( $_SERVER['HTTP_ACCEPT_ENCODING'] ) ) {
1354 # @todo FIXME: We may want to blacklist some broken browsers
1357 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
1358 $_SERVER['HTTP_ACCEPT_ENCODING'],
1362 if( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) {
1366 wfDebug( " accepts gzip\n" );
1375 * Obtain the offset and limit values from the request string;
1376 * used in special pages
1378 * @param $deflimit Int default limit if none supplied
1379 * @param $optionname String Name of a user preference to check against
1383 function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) {
1385 return $wgRequest->getLimitOffset( $deflimit, $optionname );
1389 * Escapes the given text so that it may be output using addWikiText()
1390 * without any linking, formatting, etc. making its way through. This
1391 * is achieved by substituting certain characters with HTML entities.
1392 * As required by the callers, <nowiki> is not used.
1394 * @param $text String: text to be escaped
1397 function wfEscapeWikiText( $text ) {
1398 $text = strtr( "\n$text", array(
1399 '"' => '"', '&' => '&', "'" => ''', '<' => '<',
1400 '=' => '=', '>' => '>', '[' => '[', ']' => ']',
1401 '{' => '{', '|' => '|', '}' => '}',
1402 "\n#" => "\n#", "\n*" => "\n*",
1403 "\n:" => "\n:", "\n;" => "\n;",
1404 '://' => '://', 'ISBN ' => 'ISBN ', 'RFC ' => 'RFC ',
1406 return substr( $text, 1 );
1410 * Get the current unix timetstamp with microseconds. Useful for profiling
1414 return microtime( true );
1418 * Sets dest to source and returns the original value of dest
1419 * If source is NULL, it just returns the value, it doesn't set the variable
1420 * If force is true, it will set the value even if source is NULL
1422 * @param $dest Mixed
1423 * @param $source Mixed
1424 * @param $force Bool
1427 function wfSetVar( &$dest, $source, $force = false ) {
1429 if ( !is_null( $source ) ||
$force ) {
1436 * As for wfSetVar except setting a bit
1440 * @param $state Bool
1442 function wfSetBit( &$dest, $bit, $state = true ) {
1443 $temp = (bool)( $dest & $bit );
1444 if ( !is_null( $state ) ) {
1455 * This function takes two arrays as input, and returns a CGI-style string, e.g.
1456 * "days=7&limit=100". Options in the first array override options in the second.
1457 * Options set to "" will not be output.
1459 * @param $array1 Array( String|Array )
1460 * @param $array2 Array( String|Array )
1463 function wfArrayToCGI( $array1, $array2 = null ) {
1464 if ( !is_null( $array2 ) ) {
1465 $array1 = $array1 +
$array2;
1469 foreach ( $array1 as $key => $value ) {
1470 if ( $value !== '' ) {
1474 if ( is_array( $value ) ) {
1476 foreach ( $value as $v ) {
1477 $cgi .= ( $firstTime ?
'' : '&') .
1478 urlencode( $key . '[]' ) . '=' .
1483 if ( is_object( $value ) ) {
1484 $value = $value->__toString();
1486 $cgi .= urlencode( $key ) . '=' .
1487 urlencode( $value );
1495 * This is the logical opposite of wfArrayToCGI(): it accepts a query string as
1496 * its argument and returns the same string in array form. This allows compa-
1497 * tibility with legacy functions that accept raw query strings instead of nice
1498 * arrays. Of course, keys and values are urldecode()d. Don't try passing in-
1499 * valid query strings, or it will explode.
1501 * @param $query String: query string
1502 * @return array Array version of input
1504 function wfCgiToArray( $query ) {
1505 if( isset( $query[0] ) && $query[0] == '?' ) {
1506 $query = substr( $query, 1 );
1508 $bits = explode( '&', $query );
1510 foreach( $bits as $bit ) {
1514 list( $key, $value ) = explode( '=', $bit );
1515 $key = urldecode( $key );
1516 $value = urldecode( $value );
1517 $ret[$key] = $value;
1523 * Append a query string to an existing URL, which may or may not already
1524 * have query string parameters already. If so, they will be combined.
1526 * @param $url String
1527 * @param $query Mixed: string or associative array
1530 function wfAppendQuery( $url, $query ) {
1531 if ( is_array( $query ) ) {
1532 $query = wfArrayToCGI( $query );
1534 if( $query != '' ) {
1535 if( false === strpos( $url, '?' ) ) {
1546 * Expand a potentially local URL to a fully-qualified URL. Assumes $wgServer
1547 * and $wgProto are correct.
1549 * @todo this won't work with current-path-relative URLs
1550 * like "subdir/foo.html", etc.
1552 * @param $url String: either fully-qualified or a local path + query
1553 * @return string Fully-qualified URL
1555 function wfExpandUrl( $url ) {
1556 if( substr( $url, 0, 2 ) == '//' ) {
1558 return $wgProto . ':' . $url;
1559 } elseif( substr( $url, 0, 1 ) == '/' ) {
1561 return $wgServer . $url;
1568 * Windows-compatible version of escapeshellarg()
1569 * Windows doesn't recognise single-quotes in the shell, but the escapeshellarg()
1570 * function puts single quotes in regardless of OS.
1572 * Also fixes the locale problems on Linux in PHP 5.2.6+ (bug backported to
1573 * earlier distro releases of PHP)
1578 function wfEscapeShellArg( ) {
1579 wfInitShellLocale();
1581 $args = func_get_args();
1584 foreach ( $args as $arg ) {
1591 if ( wfIsWindows() ) {
1592 // Escaping for an MSVC-style command line parser and CMD.EXE
1594 // * http://web.archive.org/web/20020708081031/http://mailman.lyra.org/pipermail/scite-interest/2002-March/000436.html
1595 // * http://technet.microsoft.com/en-us/library/cc723564.aspx
1598 // Double the backslashes before any double quotes. Escape the double quotes.
1599 $tokens = preg_split( '/(\\\\*")/', $arg, -1, PREG_SPLIT_DELIM_CAPTURE
);
1602 foreach ( $tokens as $token ) {
1603 if ( $iteration %
2 == 1 ) {
1604 // Delimiter, a double quote preceded by zero or more slashes
1605 $arg .= str_replace( '\\', '\\\\', substr( $token, 0, -1 ) ) . '\\"';
1606 } elseif ( $iteration %
4 == 2 ) {
1607 // ^ in $token will be outside quotes, need to be escaped
1608 $arg .= str_replace( '^', '^^', $token );
1609 } else { // $iteration % 4 == 0
1610 // ^ in $token will appear inside double quotes, so leave as is
1615 // Double the backslashes before the end of the string, because
1616 // we will soon add a quote
1618 if ( preg_match( '/^(.*?)(\\\\+)$/', $arg, $m ) ) {
1619 $arg = $m[1] . str_replace( '\\', '\\\\', $m[2] );
1622 // Add surrounding quotes
1623 $retVal .= '"' . $arg . '"';
1625 $retVal .= escapeshellarg( $arg );
1632 * wfMerge attempts to merge differences between three texts.
1633 * Returns true for a clean merge and false for failure or a conflict.
1635 * @param $old String
1636 * @param $mine String
1637 * @param $yours String
1638 * @param $result String
1641 function wfMerge( $old, $mine, $yours, &$result ) {
1644 # This check may also protect against code injection in
1645 # case of broken installations.
1646 wfSuppressWarnings();
1647 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
1648 wfRestoreWarnings();
1651 wfDebug( "diff3 not found\n" );
1655 # Make temporary files
1657 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
1658 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
1659 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
1661 fwrite( $oldtextFile, $old );
1662 fclose( $oldtextFile );
1663 fwrite( $mytextFile, $mine );
1664 fclose( $mytextFile );
1665 fwrite( $yourtextFile, $yours );
1666 fclose( $yourtextFile );
1668 # Check for a conflict
1669 $cmd = $wgDiff3 . ' -a --overlap-only ' .
1670 wfEscapeShellArg( $mytextName ) . ' ' .
1671 wfEscapeShellArg( $oldtextName ) . ' ' .
1672 wfEscapeShellArg( $yourtextName );
1673 $handle = popen( $cmd, 'r' );
1675 if( fgets( $handle, 1024 ) ) {
1683 $cmd = $wgDiff3 . ' -a -e --merge ' .
1684 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
1685 $handle = popen( $cmd, 'r' );
1688 $data = fread( $handle, 8192 );
1689 if ( strlen( $data ) == 0 ) {
1695 unlink( $mytextName );
1696 unlink( $oldtextName );
1697 unlink( $yourtextName );
1699 if ( $result === '' && $old !== '' && !$conflict ) {
1700 wfDebug( "Unexpected null result from diff3. Command: $cmd\n" );
1707 * Returns unified plain-text diff of two texts.
1708 * Useful for machine processing of diffs.
1710 * @param $before String: the text before the changes.
1711 * @param $after String: the text after the changes.
1712 * @param $params String: command-line options for the diff command.
1713 * @return String: unified diff of $before and $after
1715 function wfDiff( $before, $after, $params = '-u' ) {
1716 if ( $before == $after ) {
1721 wfSuppressWarnings();
1722 $haveDiff = $wgDiff && file_exists( $wgDiff );
1723 wfRestoreWarnings();
1725 # This check may also protect against code injection in
1726 # case of broken installations.
1728 wfDebug( "diff executable not found\n" );
1729 $diffs = new Diff( explode( "\n", $before ), explode( "\n", $after ) );
1730 $format = new UnifiedDiffFormatter();
1731 return $format->format( $diffs );
1734 # Make temporary files
1736 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
1737 $newtextFile = fopen( $newtextName = tempnam( $td, 'merge-your-' ), 'w' );
1739 fwrite( $oldtextFile, $before );
1740 fclose( $oldtextFile );
1741 fwrite( $newtextFile, $after );
1742 fclose( $newtextFile );
1744 // Get the diff of the two files
1745 $cmd = "$wgDiff " . $params . ' ' . wfEscapeShellArg( $oldtextName, $newtextName );
1747 $h = popen( $cmd, 'r' );
1752 $data = fread( $h, 8192 );
1753 if ( strlen( $data ) == 0 ) {
1761 unlink( $oldtextName );
1762 unlink( $newtextName );
1764 // Kill the --- and +++ lines. They're not useful.
1765 $diff_lines = explode( "\n", $diff );
1766 if ( strpos( $diff_lines[0], '---' ) === 0 ) {
1767 unset( $diff_lines[0] );
1769 if ( strpos( $diff_lines[1], '+++' ) === 0 ) {
1770 unset( $diff_lines[1] );
1773 $diff = implode( "\n", $diff_lines );
1779 * A wrapper around the PHP function var_export().
1780 * Either print it or add it to the regular output ($wgOut).
1782 * @param $var A PHP variable to dump.
1784 function wfVarDump( $var ) {
1786 $s = str_replace( "\n", "<br />\n", var_export( $var, true ) . "\n" );
1787 if ( headers_sent() ||
!@is_object
( $wgOut ) ) {
1790 $wgOut->addHTML( $s );
1795 * Provide a simple HTTP error.
1797 * @param $code Int|String
1798 * @param $label String
1799 * @param $desc String
1801 function wfHttpError( $code, $label, $desc ) {
1804 header( "HTTP/1.0 $code $label" );
1805 header( "Status: $code $label" );
1806 $wgOut->sendCacheControl();
1808 header( 'Content-type: text/html; charset=utf-8' );
1809 print "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">".
1810 '<html><head><title>' .
1811 htmlspecialchars( $label ) .
1812 '</title></head><body><h1>' .
1813 htmlspecialchars( $label ) .
1815 nl2br( htmlspecialchars( $desc ) ) .
1816 "</p></body></html>\n";
1820 * Clear away any user-level output buffers, discarding contents.
1822 * Suitable for 'starting afresh', for instance when streaming
1823 * relatively large amounts of data without buffering, or wanting to
1824 * output image files without ob_gzhandler's compression.
1826 * The optional $resetGzipEncoding parameter controls suppression of
1827 * the Content-Encoding header sent by ob_gzhandler; by default it
1828 * is left. See comments for wfClearOutputBuffers() for why it would
1831 * Note that some PHP configuration options may add output buffer
1832 * layers which cannot be removed; these are left in place.
1834 * @param $resetGzipEncoding Bool
1836 function wfResetOutputBuffers( $resetGzipEncoding = true ) {
1837 if( $resetGzipEncoding ) {
1838 // Suppress Content-Encoding and Content-Length
1839 // headers from 1.10+s wfOutputHandler
1840 global $wgDisableOutputCompression;
1841 $wgDisableOutputCompression = true;
1843 while( $status = ob_get_status() ) {
1844 if( $status['type'] == 0 /* PHP_OUTPUT_HANDLER_INTERNAL */ ) {
1845 // Probably from zlib.output_compression or other
1846 // PHP-internal setting which can't be removed.
1848 // Give up, and hope the result doesn't break
1852 if( !ob_end_clean() ) {
1853 // Could not remove output buffer handler; abort now
1854 // to avoid getting in some kind of infinite loop.
1857 if( $resetGzipEncoding ) {
1858 if( $status['name'] == 'ob_gzhandler' ) {
1859 // Reset the 'Content-Encoding' field set by this handler
1860 // so we can start fresh.
1861 if ( function_exists( 'header_remove' ) ) {
1862 // Available since PHP 5.3.0
1863 header_remove( 'Content-Encoding' );
1865 // We need to provide a valid content-coding. See bug 28069
1866 header( 'Content-Encoding: identity' );
1875 * More legible than passing a 'false' parameter to wfResetOutputBuffers():
1877 * Clear away output buffers, but keep the Content-Encoding header
1878 * produced by ob_gzhandler, if any.
1880 * This should be used for HTTP 304 responses, where you need to
1881 * preserve the Content-Encoding header of the real result, but
1882 * also need to suppress the output of ob_gzhandler to keep to spec
1883 * and avoid breaking Firefox in rare cases where the headers and
1884 * body are broken over two packets.
1886 function wfClearOutputBuffers() {
1887 wfResetOutputBuffers( false );
1891 * Converts an Accept-* header into an array mapping string values to quality
1894 * @param $accept String
1895 * @param $def String default
1898 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
1899 # No arg means accept anything (per HTTP spec)
1901 return array( $def => 1.0 );
1906 $parts = explode( ',', $accept );
1908 foreach( $parts as $part ) {
1909 # @todo FIXME: Doesn't deal with params like 'text/html; level=1'
1910 @list
( $value, $qpart ) = explode( ';', trim( $part ) );
1912 if( !isset( $qpart ) ) {
1913 $prefs[$value] = 1.0;
1914 } elseif( preg_match( '/q\s*=\s*(\d*\.\d+)/', $qpart, $match ) ) {
1915 $prefs[$value] = floatval( $match[1] );
1923 * Checks if a given MIME type matches any of the keys in the given
1924 * array. Basic wildcards are accepted in the array keys.
1926 * Returns the matching MIME type (or wildcard) if a match, otherwise
1929 * @param $type String
1930 * @param $avail Array
1934 function mimeTypeMatch( $type, $avail ) {
1935 if( array_key_exists( $type, $avail ) ) {
1938 $parts = explode( '/', $type );
1939 if( array_key_exists( $parts[0] . '/*', $avail ) ) {
1940 return $parts[0] . '/*';
1941 } elseif( array_key_exists( '*/*', $avail ) ) {
1950 * Returns the 'best' match between a client's requested internet media types
1951 * and the server's list of available types. Each list should be an associative
1952 * array of type to preference (preference is a float between 0.0 and 1.0).
1953 * Wildcards in the types are acceptable.
1955 * @param $cprefs Array: client's acceptable type list
1956 * @param $sprefs Array: server's offered types
1959 * @todo FIXME: Doesn't handle params like 'text/plain; charset=UTF-8'
1960 * XXX: generalize to negotiate other stuff
1962 function wfNegotiateType( $cprefs, $sprefs ) {
1965 foreach( array_keys($sprefs) as $type ) {
1966 $parts = explode( '/', $type );
1967 if( $parts[1] != '*' ) {
1968 $ckey = mimeTypeMatch( $type, $cprefs );
1970 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1975 foreach( array_keys( $cprefs ) as $type ) {
1976 $parts = explode( '/', $type );
1977 if( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
1978 $skey = mimeTypeMatch( $type, $sprefs );
1980 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1988 foreach( array_keys( $combine ) as $type ) {
1989 if( $combine[$type] > $bestq ) {
1991 $bestq = $combine[$type];
1999 * Reference-counted warning suppression
2003 function wfSuppressWarnings( $end = false ) {
2004 static $suppressCount = 0;
2005 static $originalLevel = false;
2008 if ( $suppressCount ) {
2010 if ( !$suppressCount ) {
2011 error_reporting( $originalLevel );
2015 if ( !$suppressCount ) {
2016 // E_DEPRECATED is undefined in PHP 5.2
2017 if( !defined( 'E_DEPRECATED' ) ){
2018 define( 'E_DEPRECATED', 8192 );
2020 $originalLevel = error_reporting( E_ALL
& ~
( E_WARNING | E_NOTICE | E_USER_WARNING | E_USER_NOTICE | E_DEPRECATED
) );
2027 * Restore error level to previous value
2029 function wfRestoreWarnings() {
2030 wfSuppressWarnings( true );
2033 # Autodetect, convert and provide timestamps of various types
2036 * Unix time - the number of seconds since 1970-01-01 00:00:00 UTC
2038 define( 'TS_UNIX', 0 );
2041 * MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
2043 define( 'TS_MW', 1 );
2046 * MySQL DATETIME (YYYY-MM-DD HH:MM:SS)
2048 define( 'TS_DB', 2 );
2051 * RFC 2822 format, for E-mail and HTTP headers
2053 define( 'TS_RFC2822', 3 );
2056 * ISO 8601 format with no timezone: 1986-02-09T20:00:00Z
2058 * This is used by Special:Export
2060 define( 'TS_ISO_8601', 4 );
2063 * An Exif timestamp (YYYY:MM:DD HH:MM:SS)
2065 * @see http://exif.org/Exif2-2.PDF The Exif 2.2 spec, see page 28 for the
2066 * DateTime tag and page 36 for the DateTimeOriginal and
2067 * DateTimeDigitized tags.
2069 define( 'TS_EXIF', 5 );
2072 * Oracle format time.
2074 define( 'TS_ORACLE', 6 );
2077 * Postgres format time.
2079 define( 'TS_POSTGRES', 7 );
2084 define( 'TS_DB2', 8 );
2087 * ISO 8601 basic format with no timezone: 19860209T200000Z. This is used by ResourceLoader
2089 define( 'TS_ISO_8601_BASIC', 9 );
2092 * Get a timestamp string in one of various formats
2094 * @param $outputtype Mixed: A timestamp in one of the supported formats, the
2095 * function will autodetect which format is supplied and act
2097 * @param $ts Mixed: the timestamp to convert or 0 for the current timestamp
2098 * @return Mixed: String / false The same date in the format specified in $outputtype or false
2100 function wfTimestamp( $outputtype = TS_UNIX
, $ts = 0 ) {
2105 if ( !$ts ) { // We want to catch 0, '', null... but not date strings starting with a letter.
2108 } elseif ( preg_match( '/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)$/D', $ts, $da ) ) {
2110 } elseif ( preg_match( '/^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/D', $ts, $da ) ) {
2112 } elseif ( preg_match( '/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/D', $ts, $da ) ) {
2114 } elseif ( preg_match( '/^-?\d{1,13}$/D', $ts ) ) {
2117 $strtime = "@$ts"; // Undocumented?
2118 } elseif ( preg_match( '/^\d{2}-\d{2}-\d{4} \d{2}:\d{2}:\d{2}.\d{6}$/', $ts ) ) {
2119 # TS_ORACLE // session altered to DD-MM-YYYY HH24:MI:SS.FF6
2120 $strtime = preg_replace( '/(\d\d)\.(\d\d)\.(\d\d)(\.(\d+))?/', "$1:$2:$3",
2121 str_replace( '+00:00', 'UTC', $ts ) );
2122 } elseif ( preg_match( '/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.*\d*)?Z$/', $ts, $da ) ) {
2124 } elseif ( preg_match( '/^(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})(?:\.*\d*)?Z$/', $ts, $da ) ) {
2126 } elseif ( preg_match( '/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.*\d*[\+\- ](\d\d)$/', $ts, $da ) ) {
2128 } elseif ( preg_match( '/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.*\d* GMT$/', $ts, $da ) ) {
2130 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.\d\d\d$/',$ts,$da)) {
2132 } elseif ( preg_match( '/^[ \t\r\n]*([A-Z][a-z]{2},[ \t\r\n]*)?' . # Day of week
2133 '\d\d?[ \t\r\n]*[A-Z][a-z]{2}[ \t\r\n]*\d{2}(?:\d{2})?' . # dd Mon yyyy
2134 '[ \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
2135 # TS_RFC2822, accepting a trailing comment. See http://www.squid-cache.org/mail-archive/squid-users/200307/0122.html / r77171
2136 # The regex is a superset of rfc2822 for readability
2137 $strtime = strtok( $ts, ';' );
2138 } 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 ) ) {
2141 } 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 ) ) {
2146 wfDebug("wfTimestamp() fed bogus time value: TYPE=$outputtype; VALUE=$ts\n");
2153 static $formats = array(
2156 TS_DB
=> 'Y-m-d H:i:s',
2157 TS_ISO_8601
=> 'Y-m-d\TH:i:s\Z',
2158 TS_ISO_8601_BASIC
=> 'Ymd\THis\Z',
2159 TS_EXIF
=> 'Y:m:d H:i:s', // This shouldn't ever be used, but is included for completeness
2160 TS_RFC2822
=> 'D, d M Y H:i:s',
2161 TS_ORACLE
=> 'd-m-Y H:i:s.000000', // Was 'd-M-y h.i.s A' . ' +00:00' before r51500
2162 TS_POSTGRES
=> 'Y-m-d H:i:s',
2163 TS_DB2
=> 'Y-m-d H:i:s',
2166 if ( !isset( $formats[$outputtype] ) ) {
2167 throw new MWException( 'wfTimestamp() called with illegal output type.' );
2170 if ( function_exists( "date_create" ) ) {
2171 if ( count( $da ) ) {
2172 $ds = sprintf("%04d-%02d-%02dT%02d:%02d:%02d.00+00:00",
2173 (int)$da[1], (int)$da[2], (int)$da[3],
2174 (int)$da[4], (int)$da[5], (int)$da[6]);
2176 $d = date_create( $ds, new DateTimeZone( 'GMT' ) );
2177 } elseif ( $strtime ) {
2178 $d = date_create( $strtime, new DateTimeZone( 'GMT' ) );
2184 wfDebug("wfTimestamp() fed bogus time value: $outputtype; $ts\n");
2188 $output = $d->format( $formats[$outputtype] );
2190 if ( count( $da ) ) {
2191 // Warning! gmmktime() acts oddly if the month or day is set to 0
2192 // We may want to handle that explicitly at some point
2193 $uts = gmmktime( (int)$da[4], (int)$da[5], (int)$da[6],
2194 (int)$da[2], (int)$da[3], (int)$da[1] );
2195 } elseif ( $strtime ) {
2196 $uts = strtotime( $strtime );
2199 if ( $uts === false ) {
2200 wfDebug("wfTimestamp() can't parse the timestamp (non 32-bit time? Update php): $outputtype; $ts\n");
2204 if ( TS_UNIX
== $outputtype ) {
2207 $output = gmdate( $formats[$outputtype], $uts );
2210 if ( ( $outputtype == TS_RFC2822
) ||
( $outputtype == TS_POSTGRES
) ) {
2218 * Return a formatted timestamp, or null if input is null.
2219 * For dealing with nullable timestamp columns in the database.
2221 * @param $outputtype Integer
2225 function wfTimestampOrNull( $outputtype = TS_UNIX
, $ts = null ) {
2226 if( is_null( $ts ) ) {
2229 return wfTimestamp( $outputtype, $ts );
2234 * Convenience function; returns MediaWiki timestamp for the present time.
2238 function wfTimestampNow() {
2240 return wfTimestamp( TS_MW
, time() );
2244 * Check if the operating system is Windows
2246 * @return Bool: true if it's Windows, False otherwise.
2248 function wfIsWindows() {
2249 static $isWindows = null;
2250 if ( $isWindows === null ) {
2251 $isWindows = substr( php_uname(), 0, 7 ) == 'Windows';
2257 * Check if we are running under HipHop
2261 function wfIsHipHop() {
2262 return function_exists( 'hphp_thread_set_warmup_enabled' );
2266 * Swap two variables
2271 function swap( &$x, &$y ) {
2278 * Tries to get the system directory for temporary files. The TMPDIR, TMP, and
2279 * TEMP environment variables are then checked in sequence, and if none are set
2280 * try sys_get_temp_dir() for PHP >= 5.2.1. All else fails, return /tmp for Unix
2281 * or C:\Windows\Temp for Windows and hope for the best.
2282 * It is common to call it with tempnam().
2284 * NOTE: When possible, use instead the tmpfile() function to create
2285 * temporary files to avoid race conditions on file creation, etc.
2289 function wfTempDir() {
2290 foreach( array( 'TMPDIR', 'TMP', 'TEMP' ) as $var ) {
2291 $tmp = getenv( $var );
2292 if( $tmp && file_exists( $tmp ) && is_dir( $tmp ) && is_writable( $tmp ) ) {
2296 if( function_exists( 'sys_get_temp_dir' ) ) {
2297 return sys_get_temp_dir();
2300 return wfIsWindows() ?
'C:\Windows\Temp' : '/tmp';
2304 * Make directory, and make all parent directories if they don't exist
2306 * @param $dir String: full path to directory to create
2307 * @param $mode Integer: chmod value to use, default is $wgDirectoryMode
2308 * @param $caller String: optional caller param for debugging.
2311 function wfMkdirParents( $dir, $mode = null, $caller = null ) {
2312 global $wgDirectoryMode;
2314 if ( !is_null( $caller ) ) {
2315 wfDebug( "$caller: called wfMkdirParents($dir)" );
2318 if( strval( $dir ) === '' ||
file_exists( $dir ) ) {
2322 $dir = str_replace( array( '\\', '/' ), DIRECTORY_SEPARATOR
, $dir );
2324 if ( is_null( $mode ) ) {
2325 $mode = $wgDirectoryMode;
2328 // Turn off the normal warning, we're doing our own below
2329 wfSuppressWarnings();
2330 $ok = mkdir( $dir, $mode, true ); // PHP5 <3
2331 wfRestoreWarnings();
2334 // PHP doesn't report the path in its warning message, so add our own to aid in diagnosis.
2335 trigger_error( __FUNCTION__
. ": failed to mkdir \"$dir\" mode $mode", E_USER_WARNING
);
2341 * Increment a statistics counter
2343 * @param $key String
2346 function wfIncrStats( $key, $count = 1 ) {
2347 global $wgStatsMethod;
2349 $count = intval( $count );
2351 if( $wgStatsMethod == 'udp' ) {
2352 global $wgUDPProfilerHost, $wgUDPProfilerPort, $wgDBname, $wgAggregateStatsID;
2355 $id = $wgAggregateStatsID !== false ?
$wgAggregateStatsID : $wgDBname;
2358 $socket = socket_create( AF_INET
, SOCK_DGRAM
, SOL_UDP
);
2359 $statline = "stats/{$id} - {$count} 1 1 1 1 -total\n";
2363 strlen( $statline ),
2369 $statline = "stats/{$id} - {$count} 1 1 1 1 {$key}\n";
2370 wfSuppressWarnings();
2374 strlen( $statline ),
2379 wfRestoreWarnings();
2380 } elseif( $wgStatsMethod == 'cache' ) {
2382 $key = wfMemcKey( 'stats', $key );
2383 if ( is_null( $wgMemc->incr( $key, $count ) ) ) {
2384 $wgMemc->add( $key, $count );
2392 * @param $nr Mixed: the number to format
2393 * @param $acc Integer: the number of digits after the decimal point, default 2
2394 * @param $round Boolean: whether or not to round the value, default true
2397 function wfPercent( $nr, $acc = 2, $round = true ) {
2398 $ret = sprintf( "%.${acc}f", $nr );
2399 return $round ?
round( $ret, $acc ) . '%' : "$ret%";
2403 * Find out whether or not a mixed variable exists in a string
2405 * @param $needle String
2406 * @param $str String
2407 * @param $insensitive Boolean
2410 function in_string( $needle, $str, $insensitive = false ) {
2412 if( $insensitive ) $func = 'stripos';
2414 return $func( $str, $needle ) !== false;
2417 function wfSpecialList( $page, $details ) {
2419 $details = $details ?
' ' . $wgContLang->getDirMark() . "($details)" : '';
2420 return $page . $details;
2424 * Returns a regular expression of url protocols
2428 function wfUrlProtocols() {
2429 global $wgUrlProtocols;
2431 static $retval = null;
2432 if ( !is_null( $retval ) ) {
2436 // Support old-style $wgUrlProtocols strings, for backwards compatibility
2437 // with LocalSettings files from 1.5
2438 if ( is_array( $wgUrlProtocols ) ) {
2439 $protocols = array();
2440 foreach ( $wgUrlProtocols as $protocol ) {
2441 $protocols[] = preg_quote( $protocol, '/' );
2444 $retval = implode( '|', $protocols );
2446 $retval = $wgUrlProtocols;
2452 * Safety wrapper around ini_get() for boolean settings.
2453 * The values returned from ini_get() are pre-normalized for settings
2454 * set via php.ini or php_flag/php_admin_flag... but *not*
2455 * for those set via php_value/php_admin_value.
2457 * It's fairly common for people to use php_value instead of php_flag,
2458 * which can leave you with an 'off' setting giving a false positive
2459 * for code that just takes the ini_get() return value as a boolean.
2461 * To make things extra interesting, setting via php_value accepts
2462 * "true" and "yes" as true, but php.ini and php_flag consider them false. :)
2463 * Unrecognized values go false... again opposite PHP's own coercion
2464 * from string to bool.
2466 * Luckily, 'properly' set settings will always come back as '0' or '1',
2467 * so we only have to worry about them and the 'improper' settings.
2469 * I frickin' hate PHP... :P
2471 * @param $setting String
2474 function wfIniGetBool( $setting ) {
2475 $val = ini_get( $setting );
2476 // 'on' and 'true' can't have whitespace around them, but '1' can.
2477 return strtolower( $val ) == 'on'
2478 ||
strtolower( $val ) == 'true'
2479 ||
strtolower( $val ) == 'yes'
2480 ||
preg_match( "/^\s*[+-]?0*[1-9]/", $val ); // approx C atoi() function
2484 * Wrapper function for PHP's dl(). This doesn't work in most situations from
2485 * PHP 5.3 onward, and is usually disabled in shared environments anyway.
2487 * @param $extension String A PHP extension. The file suffix (.so or .dll)
2489 * @param $fileName String Name of the library, if not $extension.suffix
2490 * @return Bool - Whether or not the extension is loaded
2492 function wfDl( $extension, $fileName = null ) {
2493 if( extension_loaded( $extension ) ) {
2498 $sapi = php_sapi_name();
2499 if( version_compare( PHP_VERSION
, '5.3.0', '<' ) ||
2500 $sapi == 'cli' ||
$sapi == 'cgi' ||
$sapi == 'embed' )
2502 $canDl = ( function_exists( 'dl' ) && is_callable( 'dl' )
2503 && wfIniGetBool( 'enable_dl' ) && !wfIniGetBool( 'safe_mode' ) );
2507 $fileName = $fileName ?
$fileName : $extension;
2508 if( wfIsWindows() ) {
2509 $fileName = 'php_' . $fileName;
2511 wfSuppressWarnings();
2512 dl( $fileName . '.' . PHP_SHLIB_SUFFIX
);
2513 wfRestoreWarnings();
2515 return extension_loaded( $extension );
2519 * Execute a shell command, with time and memory limits mirrored from the PHP
2520 * configuration if supported.
2521 * @param $cmd String Command line, properly escaped for shell.
2522 * @param &$retval optional, will receive the program's exit code.
2523 * (non-zero is usually failure)
2524 * @param $environ Array optional environment variables which should be
2525 * added to the executed command environment.
2526 * @return collected stdout as a string (trailing newlines stripped)
2528 function wfShellExec( $cmd, &$retval = null, $environ = array() ) {
2529 global $IP, $wgMaxShellMemory, $wgMaxShellFileSize, $wgMaxShellTime;
2532 if ( is_null( $disabled ) ) {
2534 if( wfIniGetBool( 'safe_mode' ) ) {
2535 wfDebug( "wfShellExec can't run in safe_mode, PHP's exec functions are too broken.\n" );
2536 $disabled = 'safemode';
2538 $functions = explode( ',', ini_get( 'disable_functions' ) );
2539 $functions = array_map( 'trim', $functions );
2540 $functions = array_map( 'strtolower', $functions );
2541 if ( in_array( 'passthru', $functions ) ) {
2542 wfDebug( "passthru is in disabled_functions\n" );
2543 $disabled = 'passthru';
2549 return $disabled == 'safemode' ?
2550 'Unable to run external programs in safe mode.' :
2551 'Unable to run external programs, passthru() is disabled.';
2554 wfInitShellLocale();
2557 foreach( $environ as $k => $v ) {
2558 if ( wfIsWindows() ) {
2559 /* Surrounding a set in quotes (method used by wfEscapeShellArg) makes the quotes themselves
2560 * appear in the environment variable, so we must use carat escaping as documented in
2561 * http://technet.microsoft.com/en-us/library/cc723564.aspx
2562 * Note however that the quote isn't listed there, but is needed, and the parentheses
2563 * are listed there but doesn't appear to need it.
2565 $envcmd .= "set $k=" . preg_replace( '/([&|()<>^"])/', '^\\1', $v ) . '&& ';
2567 /* Assume this is a POSIX shell, thus required to accept variable assignments before the command
2568 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_09_01
2570 $envcmd .= "$k=" . escapeshellarg( $v ) . ' ';
2573 $cmd = $envcmd . $cmd;
2575 if ( wfIsWindows() ) {
2576 if ( version_compare( PHP_VERSION
, '5.3.0', '<' ) && /* Fixed in 5.3.0 :) */
2577 ( version_compare( PHP_VERSION
, '5.2.1', '>=' ) ||
php_uname( 's' ) == 'Windows NT' ) )
2579 # Hack to work around PHP's flawed invocation of cmd.exe
2580 # http://news.php.net/php.internals/21796
2581 # Windows 9x doesn't accept any kind of quotes
2582 $cmd = '"' . $cmd . '"';
2584 } elseif ( php_uname( 's' ) == 'Linux' ) {
2585 $time = intval( $wgMaxShellTime );
2586 $mem = intval( $wgMaxShellMemory );
2587 $filesize = intval( $wgMaxShellFileSize );
2589 if ( $time > 0 && $mem > 0 ) {
2590 $script = "$IP/bin/ulimit4.sh";
2591 if ( is_executable( $script ) ) {
2592 $cmd = '/bin/bash ' . escapeshellarg( $script ) . " $time $mem $filesize " . escapeshellarg( $cmd );
2596 wfDebug( "wfShellExec: $cmd\n" );
2598 $retval = 1; // error by default?
2600 passthru( $cmd, $retval );
2601 $output = ob_get_contents();
2604 if ( $retval == 127 ) {
2605 wfDebugLog( 'exec', "Possibly missing executable file: $cmd\n" );
2611 * Workaround for http://bugs.php.net/bug.php?id=45132
2612 * escapeshellarg() destroys non-ASCII characters if LANG is not a UTF-8 locale
2614 function wfInitShellLocale() {
2615 static $done = false;
2620 global $wgShellLocale;
2621 if ( !wfIniGetBool( 'safe_mode' ) ) {
2622 putenv( "LC_CTYPE=$wgShellLocale" );
2623 setlocale( LC_CTYPE
, $wgShellLocale );
2628 * This function works like "use VERSION" in Perl, the program will die with a
2629 * backtrace if the current version of PHP is less than the version provided
2631 * This is useful for extensions which due to their nature are not kept in sync
2632 * with releases, and might depend on other versions of PHP than the main code
2634 * Note: PHP might die due to parsing errors in some cases before it ever
2635 * manages to call this function, such is life
2637 * @see perldoc -f use
2639 * @param $req_ver Mixed: the version to check, can be a string, an integer, or
2642 function wfUsePHP( $req_ver ) {
2643 $php_ver = PHP_VERSION
;
2645 if ( version_compare( $php_ver, (string)$req_ver, '<' ) ) {
2646 throw new MWException( "PHP $req_ver required--this is only $php_ver" );
2651 * This function works like "use VERSION" in Perl except it checks the version
2652 * of MediaWiki, the program will die with a backtrace if the current version
2653 * of MediaWiki is less than the version provided.
2655 * This is useful for extensions which due to their nature are not kept in sync
2658 * @see perldoc -f use
2660 * @param $req_ver Mixed: the version to check, can be a string, an integer, or
2663 function wfUseMW( $req_ver ) {
2666 if ( version_compare( $wgVersion, (string)$req_ver, '<' ) ) {
2667 throw new MWException( "MediaWiki $req_ver required--this is only $wgVersion" );
2672 * Return the final portion of a pathname.
2673 * Reimplemented because PHP5's basename() is buggy with multibyte text.
2674 * http://bugs.php.net/bug.php?id=33898
2676 * PHP's basename() only considers '\' a pathchar on Windows and Netware.
2677 * We'll consider it so always, as we don't want \s in our Unix paths either.
2679 * @param $path String
2680 * @param $suffix String: to remove if present
2683 function wfBaseName( $path, $suffix = '' ) {
2684 $encSuffix = ( $suffix == '' )
2686 : ( '(?:' . preg_quote( $suffix, '#' ) . ')?' );
2688 if( preg_match( "#([^/\\\\]*?){$encSuffix}[/\\\\]*$#", $path, $matches ) ) {
2696 * Generate a relative path name to the given file.
2697 * May explode on non-matching case-insensitive paths,
2698 * funky symlinks, etc.
2700 * @param $path String: absolute destination path including target filename
2701 * @param $from String: Absolute source path, directory only
2704 function wfRelativePath( $path, $from ) {
2705 // Normalize mixed input on Windows...
2706 $path = str_replace( '/', DIRECTORY_SEPARATOR
, $path );
2707 $from = str_replace( '/', DIRECTORY_SEPARATOR
, $from );
2709 // Trim trailing slashes -- fix for drive root
2710 $path = rtrim( $path, DIRECTORY_SEPARATOR
);
2711 $from = rtrim( $from, DIRECTORY_SEPARATOR
);
2713 $pieces = explode( DIRECTORY_SEPARATOR
, dirname( $path ) );
2714 $against = explode( DIRECTORY_SEPARATOR
, $from );
2716 if( $pieces[0] !== $against[0] ) {
2717 // Non-matching Windows drive letters?
2718 // Return a full path.
2722 // Trim off common prefix
2723 while( count( $pieces ) && count( $against )
2724 && $pieces[0] == $against[0] ) {
2725 array_shift( $pieces );
2726 array_shift( $against );
2729 // relative dots to bump us to the parent
2730 while( count( $against ) ) {
2731 array_unshift( $pieces, '..' );
2732 array_shift( $against );
2735 array_push( $pieces, wfBaseName( $path ) );
2737 return implode( DIRECTORY_SEPARATOR
, $pieces );
2741 * parse_url() work-alike, but non-broken. Differences:
2743 * 1) Does not raise warnings on bad URLs (just returns false)
2744 * 2) Handles protocols that don't use :// (e.g., mailto: and news:) correctly
2745 * 3) Adds a "delimiter" element to the array, either '://' or ':' (see (2))
2747 * @param $url String: a URL to parse
2748 * @return Array: bits of the URL in an associative array, per PHP docs
2750 function wfParseUrl( $url ) {
2751 global $wgUrlProtocols; // Allow all protocols defined in DefaultSettings/LocalSettings.php
2752 wfSuppressWarnings();
2753 $bits = parse_url( $url );
2754 wfRestoreWarnings();
2759 // most of the protocols are followed by ://, but mailto: and sometimes news: not, check for it
2760 if ( in_array( $bits['scheme'] . '://', $wgUrlProtocols ) ) {
2761 $bits['delimiter'] = '://';
2762 } elseif ( in_array( $bits['scheme'] . ':', $wgUrlProtocols ) ) {
2763 $bits['delimiter'] = ':';
2764 // parse_url detects for news: and mailto: the host part of an url as path
2765 // We have to correct this wrong detection
2766 if ( isset( $bits['path'] ) ) {
2767 $bits['host'] = $bits['path'];
2778 * Make a URL index, appropriate for the el_index field of externallinks.
2780 * @param $url String
2783 function wfMakeUrlIndex( $url ) {
2784 $bits = wfParseUrl( $url );
2786 // Reverse the labels in the hostname, convert to lower case
2787 // For emails reverse domainpart only
2788 if ( $bits['scheme'] == 'mailto' ) {
2789 $mailparts = explode( '@', $bits['host'], 2 );
2790 if ( count( $mailparts ) === 2 ) {
2791 $domainpart = strtolower( implode( '.', array_reverse( explode( '.', $mailparts[1] ) ) ) );
2793 // No domain specified, don't mangle it
2796 $reversedHost = $domainpart . '@' . $mailparts[0];
2797 } else if ( isset( $bits['host'] ) ) {
2798 $reversedHost = strtolower( implode( '.', array_reverse( explode( '.', $bits['host'] ) ) ) );
2800 // In file: URIs for instance it's common to have an empty host,
2801 // which turns up as not getting a 'host' member from parse_url.
2802 $reversedHost = '.';
2804 // Add an extra dot to the end
2805 // Why? Is it in wrong place in mailto links?
2806 if ( substr( $reversedHost, -1, 1 ) !== '.' ) {
2807 $reversedHost .= '.';
2809 // Reconstruct the pseudo-URL
2810 $prot = $bits['scheme'];
2811 $index = $prot . $bits['delimiter'] . $reversedHost;
2812 // Leave out user and password. Add the port, path, query and fragment
2813 if ( isset( $bits['port'] ) ) {
2814 $index .= ':' . $bits['port'];
2816 if ( isset( $bits['path'] ) ) {
2817 // parse_url() removes the initial '/' from the path
2818 // for file: URLs with Windows-style paths, such as
2819 // file:///c:/windows/stuff. We need to add it back
2820 // to keep our division between host and path properly.
2821 if ( strlen( $bits['path'] ) > 0 && substr( $bits['path'], 0, 1 ) !== '/' ) {
2824 $index .= $bits['path'];
2828 if ( isset( $bits['query'] ) ) {
2829 $index .= '?' . $bits['query'];
2831 if ( isset( $bits['fragment'] ) ) {
2832 $index .= '#' . $bits['fragment'];
2838 * Do any deferred updates and clear the list
2840 * @param $commit String: set to 'commit' to commit after every update to
2841 * prevent lock contention
2843 function wfDoUpdates( $commit = '' ) {
2844 global $wgDeferredUpdateList;
2846 wfProfileIn( __METHOD__
);
2848 // No need to get master connections in case of empty updates array
2849 if ( !count( $wgDeferredUpdateList ) ) {
2850 wfProfileOut( __METHOD__
);
2854 $doCommit = $commit == 'commit';
2856 $dbw = wfGetDB( DB_MASTER
);
2859 foreach ( $wgDeferredUpdateList as $update ) {
2860 $update->doUpdate();
2862 if ( $doCommit && $dbw->trxLevel() ) {
2867 $wgDeferredUpdateList = array();
2868 wfProfileOut( __METHOD__
);
2872 * Convert an arbitrarily-long digit string from one numeric base
2873 * to another, optionally zero-padding to a minimum column width.
2875 * Supports base 2 through 36; digit values 10-36 are represented
2876 * as lowercase letters a-z. Input is case-insensitive.
2878 * @param $input String: of digits
2879 * @param $sourceBase Integer: 2-36
2880 * @param $destBase Integer: 2-36
2881 * @param $pad Integer: 1 or greater
2882 * @param $lowercase Boolean
2883 * @return String or false on invalid input
2885 function wfBaseConvert( $input, $sourceBase, $destBase, $pad = 1, $lowercase = true ) {
2886 $input = strval( $input );
2887 if( $sourceBase < 2 ||
2892 $sourceBase != intval( $sourceBase ) ||
2893 $destBase != intval( $destBase ) ||
2894 $pad != intval( $pad ) ||
2895 !is_string( $input ) ||
2899 $digitChars = ( $lowercase ) ?
'0123456789abcdefghijklmnopqrstuvwxyz' : '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
2900 $inDigits = array();
2903 // Decode and validate input string
2904 $input = strtolower( $input );
2905 for( $i = 0; $i < strlen( $input ); $i++
) {
2906 $n = strpos( $digitChars, $input[$i] );
2907 if( $n === false ||
$n > $sourceBase ) {
2913 // Iterate over the input, modulo-ing out an output digit
2914 // at a time until input is gone.
2915 while( count( $inDigits ) ) {
2917 $workDigits = array();
2920 foreach( $inDigits as $digit ) {
2921 $work *= $sourceBase;
2924 if( $work < $destBase ) {
2925 // Gonna need to pull another digit.
2926 if( count( $workDigits ) ) {
2927 // Avoid zero-padding; this lets us find
2928 // the end of the input very easily when
2929 // length drops to zero.
2933 // Finally! Actual division!
2934 $workDigits[] = intval( $work / $destBase );
2936 // Isn't it annoying that most programming languages
2937 // don't have a single divide-and-remainder operator,
2938 // even though the CPU implements it that way?
2939 $work = $work %
$destBase;
2943 // All that division leaves us with a remainder,
2944 // which is conveniently our next output digit.
2945 $outChars .= $digitChars[$work];
2948 $inDigits = $workDigits;
2951 while( strlen( $outChars ) < $pad ) {
2955 return strrev( $outChars );
2959 * Create an object with a given name and an array of construct parameters
2961 * @param $name String
2962 * @param $p Array: parameters
2963 * @deprecated since 1.18, warnings in 1.19, removal in 1.20
2965 function wfCreateObject( $name, $p ) {
2966 wfDeprecated( __FUNCTION__
);
2967 return MWFunction
::newObj( $name, $p );
2970 function wfHttpOnlySafe() {
2971 global $wgHttpOnlyBlacklist;
2973 if( isset( $_SERVER['HTTP_USER_AGENT'] ) ) {
2974 foreach( $wgHttpOnlyBlacklist as $regex ) {
2975 if( preg_match( $regex, $_SERVER['HTTP_USER_AGENT'] ) ) {
2985 * Initialise php session
2987 * @param $sessionId Bool
2989 function wfSetupSession( $sessionId = false ) {
2990 global $wgSessionsInMemcached, $wgCookiePath, $wgCookieDomain,
2991 $wgCookieSecure, $wgCookieHttpOnly, $wgSessionHandler;
2992 if( $wgSessionsInMemcached ) {
2993 if ( !defined( 'MW_COMPILED' ) ) {
2995 require_once( "$IP/includes/cache/MemcachedSessions.php" );
2997 session_set_save_handler( 'memsess_open', 'memsess_close', 'memsess_read',
2998 'memsess_write', 'memsess_destroy', 'memsess_gc' );
3000 // It's necessary to register a shutdown function to call session_write_close(),
3001 // because by the time the request shutdown function for the session module is
3002 // called, $wgMemc has already been destroyed. Shutdown functions registered
3003 // this way are called before object destruction.
3004 register_shutdown_function( 'memsess_write_close' );
3005 } elseif( $wgSessionHandler && $wgSessionHandler != ini_get( 'session.save_handler' ) ) {
3006 # Only set this if $wgSessionHandler isn't null and session.save_handler
3007 # hasn't already been set to the desired value (that causes errors)
3008 ini_set( 'session.save_handler', $wgSessionHandler );
3010 $httpOnlySafe = wfHttpOnlySafe() && $wgCookieHttpOnly;
3011 wfDebugLog( 'cookie',
3012 'session_set_cookie_params: "' . implode( '", "',
3018 $httpOnlySafe ) ) . '"' );
3019 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $httpOnlySafe );
3020 session_cache_limiter( 'private, must-revalidate' );
3022 session_id( $sessionId );
3024 wfSuppressWarnings();
3026 wfRestoreWarnings();
3030 * Get an object from the precompiled serialized directory
3032 * @param $name String
3033 * @return Mixed: the variable on success, false on failure
3035 function wfGetPrecompiledData( $name ) {
3038 $file = "$IP/serialized/$name";
3039 if ( file_exists( $file ) ) {
3040 $blob = file_get_contents( $file );
3042 return unserialize( $blob );
3054 function wfMemcKey( /*... */ ) {
3055 $args = func_get_args();
3056 $key = wfWikiID() . ':' . implode( ':', $args );
3057 $key = str_replace( ' ', '_', $key );
3062 * Get a cache key for a foreign DB
3065 * @param $prefix String
3066 * @param varargs String
3069 function wfForeignMemcKey( $db, $prefix /*, ... */ ) {
3070 $args = array_slice( func_get_args(), 2 );
3072 $key = "$db-$prefix:" . implode( ':', $args );
3074 $key = $db . ':' . implode( ':', $args );
3080 * Get an ASCII string identifying this wiki
3081 * This is used as a prefix in memcached keys
3085 function wfWikiID() {
3086 global $wgDBprefix, $wgDBname;
3087 if ( $wgDBprefix ) {
3088 return "$wgDBname-$wgDBprefix";
3095 * Split a wiki ID into DB name and table prefix
3097 * @param $wiki String
3098 * @param $bits String
3100 function wfSplitWikiID( $wiki ) {
3101 $bits = explode( '-', $wiki, 2 );
3102 if ( count( $bits ) < 2 ) {
3109 * Get a Database object.
3111 * @param $db Integer: index of the connection to get. May be DB_MASTER for the
3112 * master (for write queries), DB_SLAVE for potentially lagged read
3113 * queries, or an integer >= 0 for a particular server.
3115 * @param $groups Mixed: query groups. An array of group names that this query
3116 * belongs to. May contain a single string if the query is only
3119 * @param $wiki String: the wiki ID, or false for the current wiki
3121 * Note: multiple calls to wfGetDB(DB_SLAVE) during the course of one request
3122 * will always return the same object, unless the underlying connection or load
3123 * balancer is manually destroyed.
3125 * Note 2: use $this->getDB() in maintenance scripts that may be invoked by
3126 * updater to ensure that a proper database is being updated.
3128 * @return DatabaseBase
3130 function &wfGetDB( $db, $groups = array(), $wiki = false ) {
3131 return wfGetLB( $wiki )->getConnection( $db, $groups, $wiki );
3135 * Get a load balancer object.
3137 * @param $wiki String: wiki ID, or false for the current wiki
3138 * @return LoadBalancer
3140 function wfGetLB( $wiki = false ) {
3141 return wfGetLBFactory()->getMainLB( $wiki );
3145 * Get the load balancer factory object
3149 function &wfGetLBFactory() {
3150 return LBFactory
::singleton();
3155 * Shortcut for RepoGroup::singleton()->findFile()
3157 * @param $title String or Title object
3158 * @param $options Associative array of options:
3159 * time: requested time for an archived image, or false for the
3160 * current version. An image object will be returned which was
3161 * created at the specified time.
3163 * ignoreRedirect: If true, do not follow file redirects
3165 * private: If true, return restricted (deleted) files if the current
3166 * user is allowed to view them. Otherwise, such files will not
3169 * bypassCache: If true, do not use the process-local cache of File objects
3171 * @return File, or false if the file does not exist
3173 function wfFindFile( $title, $options = array() ) {
3174 return RepoGroup
::singleton()->findFile( $title, $options );
3178 * Get an object referring to a locally registered file.
3179 * Returns a valid placeholder object if the file does not exist.
3181 * @param $title Title or String
3182 * @return File, or null if passed an invalid Title
3184 function wfLocalFile( $title ) {
3185 return RepoGroup
::singleton()->getLocalRepo()->newFile( $title );
3189 * Should low-performance queries be disabled?
3192 * @codeCoverageIgnore
3194 function wfQueriesMustScale() {
3195 global $wgMiserMode;
3197 ||
( SiteStats
::pages() > 100000
3198 && SiteStats
::edits() > 1000000
3199 && SiteStats
::users() > 10000 );
3203 * Get the path to a specified script file, respecting file
3204 * extensions; this is a wrapper around $wgScriptExtension etc.
3206 * @param $script String: script filename, sans extension
3209 function wfScript( $script = 'index' ) {
3210 global $wgScriptPath, $wgScriptExtension;
3211 return "{$wgScriptPath}/{$script}{$wgScriptExtension}";
3215 * Get the script URL.
3217 * @return script URL
3219 function wfGetScriptUrl() {
3220 if( isset( $_SERVER['SCRIPT_NAME'] ) ) {
3222 # as it was called, minus the query string.
3224 # Some sites use Apache rewrite rules to handle subdomains,
3225 # and have PHP set up in a weird way that causes PHP_SELF
3226 # to contain the rewritten URL instead of the one that the
3227 # outside world sees.
3229 # If in this mode, use SCRIPT_URL instead, which mod_rewrite
3230 # provides containing the "before" URL.
3231 return $_SERVER['SCRIPT_NAME'];
3233 return $_SERVER['URL'];
3238 * Convenience function converts boolean values into "true"
3239 * or "false" (string) values
3241 * @param $value Boolean
3244 function wfBoolToStr( $value ) {
3245 return $value ?
'true' : 'false';
3249 * Load an extension messages file
3251 * @deprecated since 1.16, warnings in 1.18, remove in 1.20
3252 * @codeCoverageIgnore
3254 function wfLoadExtensionMessages() {
3255 wfDeprecated( __FUNCTION__
);
3259 * Get a platform-independent path to the null file, e.g. /dev/null
3263 function wfGetNull() {
3264 return wfIsWindows()
3270 * Throws a warning that $function is deprecated
3272 * @param $function String
3275 function wfDeprecated( $function ) {
3276 static $functionsWarned = array();
3277 if ( !isset( $functionsWarned[$function] ) ) {
3278 $functionsWarned[$function] = true;
3279 wfWarn( "Use of $function is deprecated.", 2 );
3284 * Send a warning either to the debug log or in a PHP error depending on
3285 * $wgDevelopmentWarnings
3287 * @param $msg String: message to send
3288 * @param $callerOffset Integer: number of items to go back in the backtrace to
3289 * find the correct caller (1 = function calling wfWarn, ...)
3290 * @param $level Integer: PHP error level; only used when $wgDevelopmentWarnings
3293 function wfWarn( $msg, $callerOffset = 1, $level = E_USER_NOTICE
) {
3294 global $wgDevelopmentWarnings;
3296 $callers = wfDebugBacktrace();
3297 if ( isset( $callers[$callerOffset +
1] ) ) {
3298 $callerfunc = $callers[$callerOffset +
1];
3299 $callerfile = $callers[$callerOffset];
3300 if ( isset( $callerfile['file'] ) && isset( $callerfile['line'] ) ) {
3301 $file = $callerfile['file'] . ' at line ' . $callerfile['line'];
3303 $file = '(internal function)';
3306 if ( isset( $callerfunc['class'] ) ) {
3307 $func .= $callerfunc['class'] . '::';
3309 if ( isset( $callerfunc['function'] ) ) {
3310 $func .= $callerfunc['function'];
3312 $msg .= " [Called from $func in $file]";
3315 if ( $wgDevelopmentWarnings ) {
3316 trigger_error( $msg, $level );
3318 wfDebug( "$msg\n" );
3323 * Modern version of wfWaitForSlaves(). Instead of looking at replication lag
3324 * and waiting for it to go down, this waits for the slaves to catch up to the
3325 * master position. Use this when updating very large numbers of rows, as
3326 * in maintenance scripts, to avoid causing too much lag. Of course, this is
3327 * a no-op if there are no slaves.
3329 * @param $maxLag Integer (deprecated)
3330 * @param $wiki mixed Wiki identifier accepted by wfGetLB
3333 function wfWaitForSlaves( $maxLag = false, $wiki = false ) {
3334 $lb = wfGetLB( $wiki );
3335 // bug 27975 - Don't try to wait for slaves if there are none
3336 // Prevents permission error when getting master position
3337 if ( $lb->getServerCount() > 1 ) {
3338 $dbw = $lb->getConnection( DB_MASTER
);
3339 $pos = $dbw->getMasterPos();
3340 $lb->waitForAll( $pos );
3345 * Used to be used for outputting text in the installer/updater
3346 * @deprecated since 1.18, warnings in 1.19, remove in 1.20
3348 function wfOut( $s ) {
3349 wfDeprecated( __METHOD__
);
3350 global $wgCommandLineMode;
3351 if ( $wgCommandLineMode && !defined( 'MEDIAWIKI_INSTALL' ) ) {
3354 echo htmlspecialchars( $s );
3360 * Count down from $n to zero on the terminal, with a one-second pause
3361 * between showing each number. For use in command-line scripts.
3362 * @codeCoverageIgnore
3364 function wfCountDown( $n ) {
3365 for ( $i = $n; $i >= 0; $i-- ) {
3367 echo str_repeat( "\x08", strlen( $i +
1 ) );
3379 * Generate a random 32-character hexadecimal token.
3380 * @param $salt Mixed: some sort of salt, if necessary, to add to random
3381 * characters before hashing.
3383 * @codeCoverageIgnore
3385 function wfGenerateToken( $salt = '' ) {
3386 $salt = serialize( $salt );
3387 return md5( mt_rand( 0, 0x7fffffff ) . $salt );
3391 * Replace all invalid characters with -
3393 * @param $name Mixed: filename to process
3396 function wfStripIllegalFilenameChars( $name ) {
3397 global $wgIllegalFileChars;
3398 $name = wfBaseName( $name );
3399 $name = preg_replace(
3400 "/[^" . Title
::legalChars() . "]" .
3401 ( $wgIllegalFileChars ?
"|[" . $wgIllegalFileChars . "]" : '' ) .
3410 * Set PHP's memory limit to the larger of php.ini or $wgMemoryLimit;
3412 * @return Integer value memory was set to.
3414 function wfMemoryLimit() {
3415 global $wgMemoryLimit;
3416 $memlimit = wfShorthandToInteger( ini_get( 'memory_limit' ) );
3417 if( $memlimit != -1 ) {
3418 $conflimit = wfShorthandToInteger( $wgMemoryLimit );
3419 if( $conflimit == -1 ) {
3420 wfDebug( "Removing PHP's memory limit\n" );
3421 wfSuppressWarnings();
3422 ini_set( 'memory_limit', $conflimit );
3423 wfRestoreWarnings();
3425 } elseif ( $conflimit > $memlimit ) {
3426 wfDebug( "Raising PHP's memory limit to $conflimit bytes\n" );
3427 wfSuppressWarnings();
3428 ini_set( 'memory_limit', $conflimit );
3429 wfRestoreWarnings();
3437 * Converts shorthand byte notation to integer form
3439 * @param $string String
3442 function wfShorthandToInteger( $string = '' ) {
3443 $string = trim( $string );
3444 if( $string === '' ) {
3447 $last = $string[strlen( $string ) - 1];
3448 $val = intval( $string );
3453 // break intentionally missing
3457 // break intentionally missing
3467 * Get the normalised IETF language tag
3468 * See unit test for examples.
3470 * @param $code String: The language code.
3471 * @return $langCode String: The language code which complying with BCP 47 standards.
3473 function wfBCP47( $code ) {
3474 $codeSegment = explode( '-', $code );
3476 foreach ( $codeSegment as $segNo => $seg ) {
3477 if ( count( $codeSegment ) > 0 ) {
3478 // when previous segment is x, it is a private segment and should be lc
3479 if( $segNo > 0 && strtolower( $codeSegment[($segNo - 1)] ) == 'x') {
3480 $codeBCP[$segNo] = strtolower( $seg );
3481 // ISO 3166 country code
3482 } elseif ( ( strlen( $seg ) == 2 ) && ( $segNo > 0 ) ) {
3483 $codeBCP[$segNo] = strtoupper( $seg );
3484 // ISO 15924 script code
3485 } elseif ( ( strlen( $seg ) == 4 ) && ( $segNo > 0 ) ) {
3486 $codeBCP[$segNo] = ucfirst( strtolower( $seg ) );
3487 // Use lowercase for other cases
3489 $codeBCP[$segNo] = strtolower( $seg );
3492 // Use lowercase for single segment
3493 $codeBCP[$segNo] = strtolower( $seg );
3496 $langCode = implode( '-', $codeBCP );
3501 * Get a cache object.
3503 * @param integer $inputType Cache type, one the the CACHE_* constants.
3506 function wfGetCache( $inputType ) {
3507 return ObjectCache
::getInstance( $inputType );
3511 * Get the main cache object
3515 function wfGetMainCache() {
3516 global $wgMainCacheType;
3517 return ObjectCache
::getInstance( $wgMainCacheType );
3521 * Get the cache object used by the message cache
3525 function wfGetMessageCacheStorage() {
3526 global $wgMessageCacheType;
3527 return ObjectCache
::getInstance( $wgMessageCacheType );
3531 * Get the cache object used by the parser cache
3535 function wfGetParserCacheStorage() {
3536 global $wgParserCacheType;
3537 return ObjectCache
::getInstance( $wgParserCacheType );
3541 * Call hook functions defined in $wgHooks
3543 * @param $event String: event name
3544 * @param $args Array: parameters passed to hook functions
3547 function wfRunHooks( $event, $args = array() ) {
3548 return Hooks
::run( $event, $args );