3 * Global functions used everywhere
7 if ( !defined( 'MEDIAWIKI' ) ) {
8 die( "This file is part of MediaWiki, it is not a valid entry point" );
11 require_once dirname( __FILE__
) . '/normal/UtfNormalUtil.php';
13 // Hide compatibility functions from Doxygen
17 * Compatibility functions
19 * We support PHP 5.1.x and up.
20 * Re-implementations of newer functions or functions in non-standard
21 * PHP extensions may be included here.
24 if( !function_exists( 'iconv' ) ) {
25 function iconv( $from, $to, $string ) {
26 return Fallback
::iconv( $from, $to, $string );
30 if ( !function_exists( 'mb_substr' ) ) {
31 function mb_substr( $str, $start, $count='end' ) {
32 return Fallback
::mb_substr( $str, $start, $count );
35 function mb_substr_split_unicode( $str, $splitPos ) {
36 return Fallback
::mb_substr_split_unicode( $str, $splitPos );
40 if ( !function_exists( 'mb_strlen' ) ) {
41 function mb_strlen( $str, $enc = '' ) {
42 return Fallback
::mb_strlen( $str, $enc );
46 if( !function_exists( 'mb_strpos' ) ) {
48 function mb_strpos( $haystack, $needle, $offset = 0, $encoding = '' ) {
49 return Fallback
::mb_strpos( $haystack, $needle, $offset, $encoding );
54 if( !function_exists( 'mb_strrpos' ) ) {
55 function mb_strrpos( $haystack, $needle, $offset = 0, $encoding = '' ) {
56 return Fallback
::mb_strrpos( $haystack, $needle, $offset, $encoding );
61 // Support for Wietse Venema's taint feature
62 if ( !function_exists( 'istainted' ) ) {
63 function istainted( $var ) {
66 function taint( $var, $level = 0 ) {}
67 function untaint( $var, $level = 0 ) {}
68 define( 'TC_HTML', 1 );
69 define( 'TC_SHELL', 1 );
70 define( 'TC_MYSQL', 1 );
71 define( 'TC_PCRE', 1 );
72 define( 'TC_SELF', 1 );
79 * Like array_diff( $a, $b ) except that it works with two-dimensional arrays.
81 function wfArrayDiff2( $a, $b ) {
82 return array_udiff( $a, $b, 'wfArrayDiff2_cmp' );
84 function wfArrayDiff2_cmp( $a, $b ) {
85 if ( !is_array( $a ) ) {
86 return strcmp( $a, $b );
87 } elseif ( count( $a ) !== count( $b ) ) {
88 return count( $a ) < count( $b ) ?
-1 : 1;
92 while( ( list( , $valueA ) = each( $a ) ) && ( list( , $valueB ) = each( $b ) ) ) {
93 $cmp = strcmp( $valueA, $valueB );
103 * Get a random decimal value between 0 and 1, in a way
104 * not likely to give duplicate values for any realistic
105 * number of articles.
109 function wfRandom() {
110 # The maximum random value is "only" 2^31-1, so get two random
111 # values to reduce the chance of dupes
112 $max = mt_getrandmax() +
1;
113 $rand = number_format( ( mt_rand() * $max +
mt_rand() )
114 / $max / $max, 12, '.', '' );
119 * We want some things to be included as literal characters in our title URLs
120 * for prettiness, which urlencode encodes by default. According to RFC 1738,
121 * all of the following should be safe:
125 * But + is not safe because it's used to indicate a space; &= are only safe in
126 * paths and not in queries (and we don't distinguish here); ' seems kind of
127 * scary; and urlencode() doesn't touch -_. to begin with. Plus, although /
128 * is reserved, we don't care. So the list we unescape is:
132 * However, IIS7 redirects fail when the url contains a colon (Bug 22709),
133 * so no fancy : for IIS7.
135 * %2F in the page titles seems to fatally break for some reason.
140 function wfUrlencode( $s ) {
142 if ( is_null( $needle ) ) {
143 $needle = array( '%3B', '%40', '%24', '%21', '%2A', '%28', '%29', '%2C', '%2F' );
144 if ( !isset( $_SERVER['SERVER_SOFTWARE'] ) ||
( strpos( $_SERVER['SERVER_SOFTWARE'], 'Microsoft-IIS/7' ) === false ) ) {
149 $s = urlencode( $s );
152 array( ';', '@', '$', '!', '*', '(', ')', ',', '/', ':' ),
160 * Sends a line to the debug log if enabled or, optionally, to a comment in output.
161 * In normal operation this is a NOP.
163 * Controlling globals:
164 * $wgDebugLogFile - points to the log file
165 * $wgProfileOnly - if set, normal debug messages will not be recorded.
166 * $wgDebugRawPage - if false, 'action=raw' hits will not result in debug output.
167 * $wgDebugComments - if on, some debug items may appear in comments in the HTML output.
169 * @param $text String
170 * @param $logonly Bool: set true to avoid appearing in HTML when $wgDebugComments is set
172 function wfDebug( $text, $logonly = false ) {
173 global $wgOut, $wgDebugLogFile, $wgDebugComments, $wgProfileOnly, $wgDebugRawPage;
174 global $wgDebugLogPrefix, $wgShowDebug;
176 static $cache = array(); // Cache of unoutputted messages
177 $text = wfDebugTimer() . $text;
179 # Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
180 if ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' && !$wgDebugRawPage ) {
184 if ( ( $wgDebugComments ||
$wgShowDebug ) && !$logonly ) {
187 if ( isset( $wgOut ) && StubObject
::isRealObject( $wgOut ) ) {
188 // add the message and any cached messages to the output
189 array_map( array( $wgOut, 'debug' ), $cache );
193 if ( $wgDebugLogFile != '' && !$wgProfileOnly ) {
194 # Strip unprintables; they can switch terminal modes when binary data
195 # gets dumped, which is pretty annoying.
196 $text = preg_replace( '![\x00-\x08\x0b\x0c\x0e-\x1f]!', ' ', $text );
197 $text = $wgDebugLogPrefix . $text;
198 wfErrorLog( $text, $wgDebugLogFile );
202 function wfDebugTimer() {
203 global $wgDebugTimestamps;
204 if ( !$wgDebugTimestamps ) {
207 static $start = null;
209 if ( $start === null ) {
210 $start = microtime( true );
211 $prefix = "\n$start";
213 $prefix = sprintf( "%6.4f", microtime( true ) - $start );
216 return $prefix . ' ';
220 * Send a line giving PHP memory usage.
221 * @param $exact Bool: print exact values instead of kilobytes (default: false)
223 function wfDebugMem( $exact = false ) {
224 $mem = memory_get_usage();
226 $mem = floor( $mem / 1024 ) . ' kilobytes';
230 wfDebug( "Memory usage: $mem\n" );
234 * Send a line to a supplementary debug log file, if configured, or main debug log if not.
235 * $wgDebugLogGroups[$logGroup] should be set to a filename to send to a separate log.
237 * @param $logGroup String
238 * @param $text String
239 * @param $public Bool: whether to log the event in the public log if no private
240 * log file is specified, (default true)
242 function wfDebugLog( $logGroup, $text, $public = true ) {
243 global $wgDebugLogGroups, $wgShowHostnames;
244 $text = trim( $text ) . "\n";
245 if( isset( $wgDebugLogGroups[$logGroup] ) ) {
246 $time = wfTimestamp( TS_DB
);
248 if ( $wgShowHostnames ) {
249 $host = wfHostname();
253 wfErrorLog( "$time $host $wiki: $text", $wgDebugLogGroups[$logGroup] );
254 } elseif ( $public === true ) {
255 wfDebug( $text, true );
260 * Log for database errors
261 * @param $text String: database error message.
263 function wfLogDBError( $text ) {
264 global $wgDBerrorLog, $wgDBname;
265 if ( $wgDBerrorLog ) {
266 $host = trim(`hostname`
);
267 $text = date( 'D M j G:i:s T Y' ) . "\t$host\t$wgDBname\t$text";
268 wfErrorLog( $text, $wgDBerrorLog );
273 * Log to a file without getting "file size exceeded" signals.
275 * Can also log to TCP or UDP with the syntax udp://host:port/prefix. This will
276 * send lines to the specified port, prefixed by the specified prefix and a space.
278 function wfErrorLog( $text, $file ) {
279 if ( substr( $file, 0, 4 ) == 'udp:' ) {
280 # Needs the sockets extension
281 if ( preg_match( '!^(tcp|udp):(?://)?\[([0-9a-fA-F:]+)\]:(\d+)(?:/(.*))?$!', $file, $m ) ) {
282 // IPv6 bracketed host
284 $port = intval( $m[3] );
285 $prefix = isset( $m[4] ) ?
$m[4] : false;
287 } elseif ( preg_match( '!^(tcp|udp):(?://)?([a-zA-Z0-9.-]+):(\d+)(?:/(.*))?$!', $file, $m ) ) {
289 if ( !IP
::isIPv4( $host ) ) {
290 $host = gethostbyname( $host );
292 $port = intval( $m[3] );
293 $prefix = isset( $m[4] ) ?
$m[4] : false;
296 throw new MWException( __METHOD__
. ': Invalid UDP specification' );
298 // Clean it up for the multiplexer
299 if ( strval( $prefix ) !== '' ) {
300 $text = preg_replace( '/^/m', $prefix . ' ', $text );
301 if ( substr( $text, -1 ) != "\n" ) {
306 $sock = socket_create( $domain, SOCK_DGRAM
, SOL_UDP
);
310 socket_sendto( $sock, $text, strlen( $text ), 0, $host, $port );
311 socket_close( $sock );
313 wfSuppressWarnings();
314 $exists = file_exists( $file );
315 $size = $exists ?
filesize( $file ) : false;
316 if ( !$exists ||
( $size !== false && $size +
strlen( $text ) < 0x7fffffff ) ) {
317 error_log( $text, 3, $file );
326 function wfLogProfilingData() {
327 global $wgRequestTime, $wgDebugLogFile, $wgDebugRawPage, $wgRequest;
328 global $wgProfiler, $wgProfileLimit, $wgUser;
329 # Profiling must actually be enabled...
330 if( is_null( $wgProfiler ) ) {
333 # Get total page request time
335 $elapsed = $now - $wgRequestTime;
336 # Only show pages that longer than $wgProfileLimit time (default is 0)
337 if( $elapsed <= $wgProfileLimit ) {
340 $prof = wfGetProfilingOutput( $wgRequestTime, $elapsed );
342 if( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) {
343 $forward = ' forwarded for ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
345 if( !empty( $_SERVER['HTTP_CLIENT_IP'] ) ) {
346 $forward .= ' client IP ' . $_SERVER['HTTP_CLIENT_IP'];
348 if( !empty( $_SERVER['HTTP_FROM'] ) ) {
349 $forward .= ' from ' . $_SERVER['HTTP_FROM'];
352 $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
354 // Don't unstub $wgUser at this late stage just for statistics purposes
355 // FIXME: We can detect some anons even if it is not loaded. See User::getId()
356 if( $wgUser->mDataLoaded
&& $wgUser->isAnon() ) {
359 $log = sprintf( "%s\t%04.3f\t%s\n",
360 gmdate( 'YmdHis' ), $elapsed,
361 urldecode( $wgRequest->getRequestURL() . $forward ) );
362 if ( $wgDebugLogFile != '' && ( $wgRequest->getVal( 'action' ) != 'raw' ||
$wgDebugRawPage ) ) {
363 wfErrorLog( $log . $prof, $wgDebugLogFile );
368 * Check if the wiki read-only lock file is present. This can be used to lock
369 * off editing functions, but doesn't guarantee that the database will not be
373 function wfReadOnly() {
374 global $wgReadOnlyFile, $wgReadOnly;
376 if ( !is_null( $wgReadOnly ) ) {
377 return (bool)$wgReadOnly;
379 if ( $wgReadOnlyFile == '' ) {
382 // Set $wgReadOnly for faster access next time
383 if ( is_file( $wgReadOnlyFile ) ) {
384 $wgReadOnly = file_get_contents( $wgReadOnlyFile );
388 return (bool)$wgReadOnly;
391 function wfReadOnlyReason() {
398 * Return a Language object from $langcode
399 * @param $langcode Mixed: either:
400 * - a Language object
401 * - code of the language to get the message for, if it is
402 * a valid code create a language for that language, if
403 * it is a string but not a valid code then make a basic
405 * - a boolean: if it's false then use the current users
406 * language (as a fallback for the old parameter
407 * functionality), or if it is true then use the wikis
408 * @return Language object
410 function wfGetLangObj( $langcode = false ) {
411 # Identify which language to get or create a language object for.
412 # Using is_object here due to Stub objects.
413 if( is_object( $langcode ) ) {
414 # Great, we already have the object (hopefully)!
418 global $wgContLang, $wgLanguageCode;
419 if( $langcode === true ||
$langcode === $wgLanguageCode ) {
420 # $langcode is the language code of the wikis content language object.
421 # or it is a boolean and value is true
426 if( $langcode === false ||
$langcode === $wgLang->getCode() ) {
427 # $langcode is the language code of user language object.
428 # or it was a boolean and value is false
432 $validCodes = array_keys( Language
::getLanguageNames() );
433 if( in_array( $langcode, $validCodes ) ) {
434 # $langcode corresponds to a valid language.
435 return Language
::factory( $langcode );
438 # $langcode is a string, but not a valid language code; use content language.
439 wfDebug( "Invalid language code passed to wfGetLangObj, falling back to content language.\n" );
444 * Use this instead of $wgContLang, when working with user interface.
445 * User interface is currently hard coded according to wiki content language
446 * in many ways, especially regarding to text direction. There is lots stuff
447 * to fix, hence this function to keep the old behaviour unless the global
448 * $wgBetterDirectionality is enabled (or removed when everything works).
450 function wfUILang() {
451 global $wgBetterDirectionality;
452 return wfGetLangObj( !$wgBetterDirectionality );
456 * This is the new function for getting translated interface messages.
457 * See the Message class for documentation how to use them.
458 * The intention is that this function replaces all old wfMsg* functions.
459 * @param $key \string Message key.
460 * Varargs: normal message parameters.
461 * @return \type{Message}
464 function wfMessage( $key /*...*/) {
465 $params = func_get_args();
466 array_shift( $params );
467 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
468 $params = $params[0];
470 return new Message( $key, $params );
474 * This function accepts multiple message keys and returns a message instance
475 * for the first message which is non-empty. If all messages are empty then an
476 * instance of the first message key is returned.
477 * Varargs: message keys
478 * @return \type{Message}
481 function wfMessageFallback( /*...*/ ) {
482 $args = func_get_args();
483 return call_user_func_array( array( 'Message', 'newFallbackSequence' ), $args );
487 * Get a message from anywhere, for the current user language.
489 * Use wfMsgForContent() instead if the message should NOT
490 * change depending on the user preferences.
492 * @param $key String: lookup key for the message, usually
493 * defined in languages/Language.php
495 * This function also takes extra optional parameters (not
496 * shown in the function definition), which can be used to
497 * insert variable text into the predefined message.
499 function wfMsg( $key ) {
500 $args = func_get_args();
501 array_shift( $args );
502 return wfMsgReal( $key, $args, true );
506 * Same as above except doesn't transform the message
508 function wfMsgNoTrans( $key ) {
509 $args = func_get_args();
510 array_shift( $args );
511 return wfMsgReal( $key, $args, true, false, false );
515 * Get a message from anywhere, for the current global language
516 * set with $wgLanguageCode.
518 * Use this if the message should NOT change dependent on the
519 * language set in the user's preferences. This is the case for
520 * most text written into logs, as well as link targets (such as
521 * the name of the copyright policy page). Link titles, on the
522 * other hand, should be shown in the UI language.
524 * Note that MediaWiki allows users to change the user interface
525 * language in their preferences, but a single installation
526 * typically only contains content in one language.
528 * Be wary of this distinction: If you use wfMsg() where you should
529 * use wfMsgForContent(), a user of the software may have to
530 * customize potentially hundreds of messages in
531 * order to, e.g., fix a link in every possible language.
533 * @param $key String: lookup key for the message, usually
534 * defined in languages/Language.php
536 function wfMsgForContent( $key ) {
537 global $wgForceUIMsgAsContentMsg;
538 $args = func_get_args();
539 array_shift( $args );
541 if( is_array( $wgForceUIMsgAsContentMsg ) &&
542 in_array( $key, $wgForceUIMsgAsContentMsg ) )
546 return wfMsgReal( $key, $args, true, $forcontent );
550 * Same as above except doesn't transform the message
552 function wfMsgForContentNoTrans( $key ) {
553 global $wgForceUIMsgAsContentMsg;
554 $args = func_get_args();
555 array_shift( $args );
557 if( is_array( $wgForceUIMsgAsContentMsg ) &&
558 in_array( $key, $wgForceUIMsgAsContentMsg ) )
562 return wfMsgReal( $key, $args, true, $forcontent, false );
566 * Get a message from the language file, for the UI elements
568 function wfMsgNoDB( $key ) {
569 $args = func_get_args();
570 array_shift( $args );
571 return wfMsgReal( $key, $args, false );
575 * Get a message from the language file, for the content
577 function wfMsgNoDBForContent( $key ) {
578 global $wgForceUIMsgAsContentMsg;
579 $args = func_get_args();
580 array_shift( $args );
582 if( is_array( $wgForceUIMsgAsContentMsg ) &&
583 in_array( $key, $wgForceUIMsgAsContentMsg ) )
587 return wfMsgReal( $key, $args, false, $forcontent );
592 * Really get a message
593 * @param $key String: key to get.
595 * @param $useDB Boolean
596 * @param $forContent Mixed: Language code, or false for user lang, true for content lang.
597 * @param $transform Boolean: Whether or not to transform the message.
598 * @return String: the requested message.
600 function wfMsgReal( $key, $args, $useDB = true, $forContent = false, $transform = true ) {
601 wfProfileIn( __METHOD__
);
602 $message = wfMsgGetKey( $key, $useDB, $forContent, $transform );
603 $message = wfMsgReplaceArgs( $message, $args );
604 wfProfileOut( __METHOD__
);
609 * This function provides the message source for messages to be edited which are *not* stored in the database.
611 * @deprecated in 1.18; use wfMessage()
614 function wfMsgWeirdKey( $key ) {
615 $source = wfMsgGetKey( $key, false, true, false );
616 if ( wfEmptyMsg( $key, $source ) ) {
624 * Fetch a message string value, but don't replace any keys yet.
627 * @param $langCode String: Code of the language to get the message for, or
628 * behaves as a content language switch if it is a boolean.
629 * @param $transform Boolean: whether to parse magic words, etc.
632 function wfMsgGetKey( $key, $useDB, $langCode = false, $transform = true ) {
633 wfRunHooks( 'NormalizeMessageKey', array( &$key, &$useDB, &$langCode, &$transform ) );
635 $cache = MessageCache
::singleton();
636 $message = $cache->get( $key, $useDB, $langCode );
637 if( $message === false ) {
638 $message = '<' . htmlspecialchars( $key ) . '>';
639 } elseif ( $transform ) {
640 $message = $cache->transform( $message );
646 * Replace message parameter keys on the given formatted output.
648 * @param $message String
653 function wfMsgReplaceArgs( $message, $args ) {
654 # Fix windows line-endings
655 # Some messages are split with explode("\n", $msg)
656 $message = str_replace( "\r", '', $message );
659 if ( count( $args ) ) {
660 if ( is_array( $args[0] ) ) {
661 $args = array_values( $args[0] );
663 $replacementKeys = array();
664 foreach( $args as $n => $param ) {
665 $replacementKeys['$' . ( $n +
1 )] = $param;
667 $message = strtr( $message, $replacementKeys );
674 * Return an HTML-escaped version of a message.
675 * Parameter replacements, if any, are done *after* the HTML-escaping,
676 * so parameters may contain HTML (eg links or form controls). Be sure
677 * to pre-escape them if you really do want plaintext, or just wrap
678 * the whole thing in htmlspecialchars().
681 * @param string ... parameters
684 function wfMsgHtml( $key ) {
685 $args = func_get_args();
686 array_shift( $args );
687 return wfMsgReplaceArgs( htmlspecialchars( wfMsgGetKey( $key, true ) ), $args );
691 * Return an HTML version of message
692 * Parameter replacements, if any, are done *after* parsing the wiki-text message,
693 * so parameters may contain HTML (eg links or form controls). Be sure
694 * to pre-escape them if you really do want plaintext, or just wrap
695 * the whole thing in htmlspecialchars().
698 * @param string ... parameters
701 function wfMsgWikiHtml( $key ) {
703 $args = func_get_args();
704 array_shift( $args );
705 return wfMsgReplaceArgs( $wgOut->parse( wfMsgGetKey( $key, true ), /* can't be set to false */ true ), $args );
709 * Returns message in the requested format
710 * @param $key String: key of the message
711 * @param $options Array: processing rules. Can take the following options:
712 * <i>parse</i>: parses wikitext to HTML
713 * <i>parseinline</i>: parses wikitext to HTML and removes the surrounding
714 * p's added by parser or tidy
715 * <i>escape</i>: filters message through htmlspecialchars
716 * <i>escapenoentities</i>: same, but allows entity references like   through
717 * <i>replaceafter</i>: parameters are substituted after parsing or escaping
718 * <i>parsemag</i>: transform the message using magic phrases
719 * <i>content</i>: fetch message for content language instead of interface
720 * Also can accept a single associative argument, of the form 'language' => 'xx':
721 * <i>language</i>: Language object or language code to fetch message for
722 * (overriden by <i>content</i>), its behaviour with parse, parseinline
723 * and parsemag is undefined.
724 * Behavior for conflicting options (e.g., parse+parseinline) is undefined.
726 function wfMsgExt( $key, $options ) {
729 $args = func_get_args();
730 array_shift( $args );
731 array_shift( $args );
732 $options = (array)$options;
734 foreach( $options as $arrayKey => $option ) {
735 if( !preg_match( '/^[0-9]+|language$/', $arrayKey ) ) {
736 # An unknown index, neither numeric nor "language"
737 wfWarn( "wfMsgExt called with incorrect parameter key $arrayKey", 1, E_USER_WARNING
);
738 } elseif( preg_match( '/^[0-9]+$/', $arrayKey ) && !in_array( $option,
739 array( 'parse', 'parseinline', 'escape', 'escapenoentities',
740 'replaceafter', 'parsemag', 'content' ) ) ) {
741 # A numeric index with unknown value
742 wfWarn( "wfMsgExt called with incorrect parameter $option", 1, E_USER_WARNING
);
746 if( in_array( 'content', $options, true ) ) {
750 } elseif( array_key_exists( 'language', $options ) ) {
752 $langCode = wfGetLangObj( $options['language'] );
753 $langCodeObj = $langCode;
760 $string = wfMsgGetKey( $key, /*DB*/true, $langCode, /*Transform*/false );
762 if( !in_array( 'replaceafter', $options, true ) ) {
763 $string = wfMsgReplaceArgs( $string, $args );
766 if( in_array( 'parse', $options, true ) ) {
767 $string = $wgOut->parse( $string, true, !$forContent, $langCodeObj );
768 } elseif ( in_array( 'parseinline', $options, true ) ) {
769 $string = $wgOut->parse( $string, true, !$forContent, $langCodeObj );
771 if( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $string, $m ) ) {
774 } elseif ( in_array( 'parsemag', $options, true ) ) {
775 $string = MessageCache
::singleton()->transform( $string,
776 !$forContent, $langCodeObj );
779 if ( in_array( 'escape', $options, true ) ) {
780 $string = htmlspecialchars ( $string );
781 } elseif ( in_array( 'escapenoentities', $options, true ) ) {
782 $string = Sanitizer
::escapeHtmlAllowEntities( $string );
785 if( in_array( 'replaceafter', $options, true ) ) {
786 $string = wfMsgReplaceArgs( $string, $args );
794 * Just like exit() but makes a note of it.
795 * Commits open transactions except if the error parameter is set
797 * @deprecated Please return control to the caller or throw an exception. Will
798 * be removed in 1.19.
800 function wfAbruptExit( $error = false ) {
801 static $called = false;
807 wfDeprecated( __FUNCTION__
);
808 $bt = wfDebugBacktrace();
810 for( $i = 0; $i < count( $bt ); $i++
) {
811 $file = isset( $bt[$i]['file'] ) ?
$bt[$i]['file'] : 'unknown';
812 $line = isset( $bt[$i]['line'] ) ?
$bt[$i]['line'] : 'unknown';
813 wfDebug( "WARNING: Abrupt exit in $file at line $line\n");
816 wfDebug( "WARNING: Abrupt exit\n" );
819 wfLogProfilingData();
822 wfGetLB()->closeAll();
828 * @deprecated Please return control the caller or throw an exception. Will
829 * be removed in 1.19.
831 function wfErrorExit() {
832 wfDeprecated( __FUNCTION__
);
833 wfAbruptExit( true );
837 * Print a simple message and die, returning nonzero to the shell if any.
838 * Plain die() fails to return nonzero to the shell if you pass a string.
841 function wfDie( $msg = '' ) {
847 * Throw a debugging exception. This function previously once exited the process,
848 * but now throws an exception instead, with similar results.
850 * @param $msg String: message shown when dieing.
852 function wfDebugDieBacktrace( $msg = '' ) {
853 throw new MWException( $msg );
857 * Fetch server name for use in error reporting etc.
858 * Use real server name if available, so we know which machine
859 * in a server farm generated the current page.
862 function wfHostname() {
864 if ( is_null( $host ) ) {
865 if ( function_exists( 'posix_uname' ) ) {
866 // This function not present on Windows
867 $uname = @posix_uname
();
871 if( is_array( $uname ) && isset( $uname['nodename'] ) ) {
872 $host = $uname['nodename'];
873 } elseif ( getenv( 'COMPUTERNAME' ) ) {
874 # Windows computer name
875 $host = getenv( 'COMPUTERNAME' );
877 # This may be a virtual server.
878 $host = $_SERVER['SERVER_NAME'];
885 * Returns a HTML comment with the elapsed time since request.
886 * This method has no side effects.
889 function wfReportTime() {
890 global $wgRequestTime, $wgShowHostnames;
893 $elapsed = $now - $wgRequestTime;
895 return $wgShowHostnames
896 ?
sprintf( '<!-- Served by %s in %01.3f secs. -->', wfHostname(), $elapsed )
897 : sprintf( '<!-- Served in %01.3f secs. -->', $elapsed );
901 * Safety wrapper for debug_backtrace().
903 * With Zend Optimizer 3.2.0 loaded, this causes segfaults under somewhat
904 * murky circumstances, which may be triggered in part by stub objects
905 * or other fancy talkin'.
907 * Will return an empty array if Zend Optimizer is detected or if
908 * debug_backtrace is disabled, otherwise the output from
909 * debug_backtrace() (trimmed).
911 * @return array of backtrace information
913 function wfDebugBacktrace() {
914 static $disabled = null;
916 if( extension_loaded( 'Zend Optimizer' ) ) {
917 wfDebug( "Zend Optimizer detected; skipping debug_backtrace for safety.\n" );
921 if ( is_null( $disabled ) ) {
923 $functions = explode( ',', ini_get( 'disable_functions' ) );
924 $functions = array_map( 'trim', $functions );
925 $functions = array_map( 'strtolower', $functions );
926 if ( in_array( 'debug_backtrace', $functions ) ) {
927 wfDebug( "debug_backtrace is in disabled_functions\n" );
935 return array_slice( debug_backtrace(), 1 );
938 function wfBacktrace() {
939 global $wgCommandLineMode;
941 if ( $wgCommandLineMode ) {
946 $backtrace = wfDebugBacktrace();
947 foreach( $backtrace as $call ) {
948 if( isset( $call['file'] ) ) {
949 $f = explode( DIRECTORY_SEPARATOR
, $call['file'] );
950 $file = $f[count( $f ) - 1];
954 if( isset( $call['line'] ) ) {
955 $line = $call['line'];
959 if ( $wgCommandLineMode ) {
960 $msg .= "$file line $line calls ";
962 $msg .= '<li>' . $file . ' line ' . $line . ' calls ';
964 if( !empty( $call['class'] ) ) {
965 $msg .= $call['class'] . '::';
967 $msg .= $call['function'] . '()';
969 if ( $wgCommandLineMode ) {
975 if ( $wgCommandLineMode ) {
985 /* Some generic result counters, pulled out of SearchEngine */
991 function wfShowingResults( $offset, $limit ) {
995 array( 'parseinline' ),
996 $wgLang->formatNum( $limit ),
997 $wgLang->formatNum( $offset +
1 )
1004 function wfShowingResultsNum( $offset, $limit, $num ) {
1007 'showingresultsnum',
1008 array( 'parseinline' ),
1009 $wgLang->formatNum( $limit ),
1010 $wgLang->formatNum( $offset +
1 ),
1011 $wgLang->formatNum( $num )
1016 * Generate (prev x| next x) (20|50|100...) type links for paging
1017 * @param $offset String
1018 * @param $limit Integer
1019 * @param $link String
1020 * @param $query String: optional URL query parameter string
1021 * @param $atend Bool: optional param for specified if this is the last page
1023 function wfViewPrevNext( $offset, $limit, $link, $query = '', $atend = false ) {
1025 $fmtLimit = $wgLang->formatNum( $limit );
1026 // FIXME: Why on earth this needs one message for the text and another one for tooltip??
1027 # Get prev/next link display text
1028 $prev = wfMsgExt( 'prevn', array( 'parsemag', 'escape' ), $fmtLimit );
1029 $next = wfMsgExt( 'nextn', array( 'parsemag', 'escape' ), $fmtLimit );
1030 # Get prev/next link title text
1031 $pTitle = wfMsgExt( 'prevn-title', array( 'parsemag', 'escape' ), $fmtLimit );
1032 $nTitle = wfMsgExt( 'nextn-title', array( 'parsemag', 'escape' ), $fmtLimit );
1033 # Fetch the title object
1034 if( is_object( $link ) ) {
1037 $title = Title
::newFromText( $link );
1038 if( is_null( $title ) ) {
1042 # Make 'previous' link
1043 if( 0 != $offset ) {
1044 $po = $offset - $limit;
1045 $po = max( $po, 0 );
1046 $q = "limit={$limit}&offset={$po}";
1047 if( $query != '' ) {
1050 $plink = '<a href="' . $title->escapeLocalURL( $q ) . "\" title=\"{$pTitle}\" class=\"mw-prevlink\">{$prev}</a>";
1055 $no = $offset +
$limit;
1056 $q = "limit={$limit}&offset={$no}";
1057 if( $query != '' ) {
1063 $nlink = '<a href="' . $title->escapeLocalURL( $q ) . "\" title=\"{$nTitle}\" class=\"mw-nextlink\">{$next}</a>";
1065 # Make links to set number of items per page
1066 $nums = $wgLang->pipeList( array(
1067 wfNumLink( $offset, 20, $title, $query ),
1068 wfNumLink( $offset, 50, $title, $query ),
1069 wfNumLink( $offset, 100, $title, $query ),
1070 wfNumLink( $offset, 250, $title, $query ),
1071 wfNumLink( $offset, 500, $title, $query )
1073 return wfMsgHtml( 'viewprevnext', $plink, $nlink, $nums );
1077 * Generate links for (20|50|100...) items-per-page links
1078 * @param $offset String
1079 * @param $limit Integer
1080 * @param $title Title
1081 * @param $query String: optional URL query parameter string
1083 function wfNumLink( $offset, $limit, $title, $query = '' ) {
1085 if( $query == '' ) {
1090 $q .= "limit={$limit}&offset={$offset}";
1091 $fmtLimit = $wgLang->formatNum( $limit );
1092 $lTitle = wfMsgExt( 'shown-title', array( 'parsemag', 'escape' ), $limit );
1093 $s = '<a href="' . $title->escapeLocalURL( $q ) . "\" title=\"{$lTitle}\" class=\"mw-numlink\">{$fmtLimit}</a>";
1099 * @todo FIXME: we may want to blacklist some broken browsers
1101 * @return bool Whereas client accept gzip compression
1103 function wfClientAcceptsGzip( $force = false ) {
1104 static $result = null;
1105 if ( $result === null ||
$force ) {
1107 if( isset( $_SERVER['HTTP_ACCEPT_ENCODING'] ) ) {
1108 # FIXME: we may want to blacklist some broken browsers
1111 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
1112 $_SERVER['HTTP_ACCEPT_ENCODING'],
1116 if( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) {
1120 wfDebug( " accepts gzip\n" );
1129 * Obtain the offset and limit values from the request string;
1130 * used in special pages
1132 * @param $deflimit Default limit if none supplied
1133 * @param $optionname Name of a user preference to check against
1137 function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) {
1139 return $wgRequest->getLimitOffset( $deflimit, $optionname );
1143 * Escapes the given text so that it may be output using addWikiText()
1144 * without any linking, formatting, etc. making its way through. This
1145 * is achieved by substituting certain characters with HTML entities.
1146 * As required by the callers, <nowiki> is not used.
1148 * @param $text String: text to be escaped
1150 function wfEscapeWikiText( $text ) {
1151 $text = strtr( "\n$text", array(
1152 '"' => '"', '&' => '&', "'" => ''', '<' => '<',
1153 '=' => '=', '>' => '>', '[' => '[', ']' => ']',
1154 '{' => '{', '|' => '|', '}' => '}',
1155 "\n#" => "\n#", "\n*" => "\n*",
1156 "\n:" => "\n:", "\n;" => "\n;",
1157 '://' => '://', 'ISBN ' => 'ISBN ', 'RFC ' => 'RFC ',
1159 return substr( $text, 1 );
1167 return microtime( true );
1171 * Sets dest to source and returns the original value of dest
1172 * If source is NULL, it just returns the value, it doesn't set the variable
1173 * If force is true, it will set the value even if source is NULL
1175 function wfSetVar( &$dest, $source, $force = false ) {
1177 if ( !is_null( $source ) ||
$force ) {
1184 * As for wfSetVar except setting a bit
1186 function wfSetBit( &$dest, $bit, $state = true ) {
1187 $temp = (bool)( $dest & $bit );
1188 if ( !is_null( $state ) ) {
1199 * This function takes two arrays as input, and returns a CGI-style string, e.g.
1200 * "days=7&limit=100". Options in the first array override options in the second.
1201 * Options set to "" will not be output.
1203 function wfArrayToCGI( $array1, $array2 = null ) {
1204 if ( !is_null( $array2 ) ) {
1205 $array1 = $array1 +
$array2;
1209 foreach ( $array1 as $key => $value ) {
1210 if ( $value !== '' ) {
1214 if ( is_array( $value ) ) {
1216 foreach ( $value as $v ) {
1217 $cgi .= ( $firstTime ?
'' : '&') .
1218 urlencode( $key . '[]' ) . '=' .
1223 if ( is_object( $value ) ) {
1224 $value = $value->__toString();
1226 $cgi .= urlencode( $key ) . '=' .
1227 urlencode( $value );
1235 * This is the logical opposite of wfArrayToCGI(): it accepts a query string as
1236 * its argument and returns the same string in array form. This allows compa-
1237 * tibility with legacy functions that accept raw query strings instead of nice
1238 * arrays. Of course, keys and values are urldecode()d. Don't try passing in-
1239 * valid query strings, or it will explode.
1241 * @param $query String: query string
1242 * @return array Array version of input
1244 function wfCgiToArray( $query ) {
1245 if( isset( $query[0] ) && $query[0] == '?' ) {
1246 $query = substr( $query, 1 );
1248 $bits = explode( '&', $query );
1250 foreach( $bits as $bit ) {
1254 list( $key, $value ) = explode( '=', $bit );
1255 $key = urldecode( $key );
1256 $value = urldecode( $value );
1257 $ret[$key] = $value;
1263 * Append a query string to an existing URL, which may or may not already
1264 * have query string parameters already. If so, they will be combined.
1266 * @param $url String
1267 * @param $query Mixed: string or associative array
1270 function wfAppendQuery( $url, $query ) {
1271 if ( is_array( $query ) ) {
1272 $query = wfArrayToCGI( $query );
1274 if( $query != '' ) {
1275 if( false === strpos( $url, '?' ) ) {
1286 * Expand a potentially local URL to a fully-qualified URL. Assumes $wgServer
1287 * and $wgProto are correct.
1289 * @todo this won't work with current-path-relative URLs
1290 * like "subdir/foo.html", etc.
1292 * @param $url String: either fully-qualified or a local path + query
1293 * @return string Fully-qualified URL
1295 function wfExpandUrl( $url ) {
1296 if( substr( $url, 0, 2 ) == '//' ) {
1298 return $wgProto . ':' . $url;
1299 } elseif( substr( $url, 0, 1 ) == '/' ) {
1301 return $wgServer . $url;
1308 * Windows-compatible version of escapeshellarg()
1309 * Windows doesn't recognise single-quotes in the shell, but the escapeshellarg()
1310 * function puts single quotes in regardless of OS.
1312 * Also fixes the locale problems on Linux in PHP 5.2.6+ (bug backported to
1313 * earlier distro releases of PHP)
1315 function wfEscapeShellArg( ) {
1316 wfInitShellLocale();
1318 $args = func_get_args();
1321 foreach ( $args as $arg ) {
1328 if ( wfIsWindows() ) {
1329 // Escaping for an MSVC-style command line parser and CMD.EXE
1331 // * http://web.archive.org/web/20020708081031/http://mailman.lyra.org/pipermail/scite-interest/2002-March/000436.html
1332 // * http://technet.microsoft.com/en-us/library/cc723564.aspx
1335 // Double the backslashes before any double quotes. Escape the double quotes.
1336 $tokens = preg_split( '/(\\\\*")/', $arg, -1, PREG_SPLIT_DELIM_CAPTURE
);
1339 foreach ( $tokens as $token ) {
1340 if ( $iteration %
2 == 1 ) {
1341 // Delimiter, a double quote preceded by zero or more slashes
1342 $arg .= str_replace( '\\', '\\\\', substr( $token, 0, -1 ) ) . '\\"';
1343 } elseif ( $iteration %
4 == 2 ) {
1344 // ^ in $token will be outside quotes, need to be escaped
1345 $arg .= str_replace( '^', '^^', $token );
1346 } else { // $iteration % 4 == 0
1347 // ^ in $token will appear inside double quotes, so leave as is
1352 // Double the backslashes before the end of the string, because
1353 // we will soon add a quote
1355 if ( preg_match( '/^(.*?)(\\\\+)$/', $arg, $m ) ) {
1356 $arg = $m[1] . str_replace( '\\', '\\\\', $m[2] );
1359 // Add surrounding quotes
1360 $retVal .= '"' . $arg . '"';
1362 $retVal .= escapeshellarg( $arg );
1369 * wfMerge attempts to merge differences between three texts.
1370 * Returns true for a clean merge and false for failure or a conflict.
1372 function wfMerge( $old, $mine, $yours, &$result ) {
1375 # This check may also protect against code injection in
1376 # case of broken installations.
1377 wfSuppressWarnings();
1378 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
1379 wfRestoreWarnings();
1382 wfDebug( "diff3 not found\n" );
1386 # Make temporary files
1388 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
1389 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
1390 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
1392 fwrite( $oldtextFile, $old );
1393 fclose( $oldtextFile );
1394 fwrite( $mytextFile, $mine );
1395 fclose( $mytextFile );
1396 fwrite( $yourtextFile, $yours );
1397 fclose( $yourtextFile );
1399 # Check for a conflict
1400 $cmd = $wgDiff3 . ' -a --overlap-only ' .
1401 wfEscapeShellArg( $mytextName ) . ' ' .
1402 wfEscapeShellArg( $oldtextName ) . ' ' .
1403 wfEscapeShellArg( $yourtextName );
1404 $handle = popen( $cmd, 'r' );
1406 if( fgets( $handle, 1024 ) ) {
1414 $cmd = $wgDiff3 . ' -a -e --merge ' .
1415 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
1416 $handle = popen( $cmd, 'r' );
1419 $data = fread( $handle, 8192 );
1420 if ( strlen( $data ) == 0 ) {
1426 unlink( $mytextName );
1427 unlink( $oldtextName );
1428 unlink( $yourtextName );
1430 if ( $result === '' && $old !== '' && !$conflict ) {
1431 wfDebug( "Unexpected null result from diff3. Command: $cmd\n" );
1438 * Returns unified plain-text diff of two texts.
1439 * Useful for machine processing of diffs.
1440 * @param $before String: the text before the changes.
1441 * @param $after String: the text after the changes.
1442 * @param $params String: command-line options for the diff command.
1443 * @return String: unified diff of $before and $after
1445 function wfDiff( $before, $after, $params = '-u' ) {
1446 if ( $before == $after ) {
1451 wfSuppressWarnings();
1452 $haveDiff = $wgDiff && file_exists( $wgDiff );
1453 wfRestoreWarnings();
1455 # This check may also protect against code injection in
1456 # case of broken installations.
1458 wfDebug( "diff executable not found\n" );
1459 $diffs = new Diff( explode( "\n", $before ), explode( "\n", $after ) );
1460 $format = new UnifiedDiffFormatter();
1461 return $format->format( $diffs );
1464 # Make temporary files
1466 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
1467 $newtextFile = fopen( $newtextName = tempnam( $td, 'merge-your-' ), 'w' );
1469 fwrite( $oldtextFile, $before );
1470 fclose( $oldtextFile );
1471 fwrite( $newtextFile, $after );
1472 fclose( $newtextFile );
1474 // Get the diff of the two files
1475 $cmd = "$wgDiff " . $params . ' ' . wfEscapeShellArg( $oldtextName, $newtextName );
1477 $h = popen( $cmd, 'r' );
1482 $data = fread( $h, 8192 );
1483 if ( strlen( $data ) == 0 ) {
1491 unlink( $oldtextName );
1492 unlink( $newtextName );
1494 // Kill the --- and +++ lines. They're not useful.
1495 $diff_lines = explode( "\n", $diff );
1496 if ( strpos( $diff_lines[0], '---' ) === 0 ) {
1497 unset( $diff_lines[0] );
1499 if ( strpos( $diff_lines[1], '+++' ) === 0 ) {
1500 unset( $diff_lines[1] );
1503 $diff = implode( "\n", $diff_lines );
1509 * A wrapper around the PHP function var_export().
1510 * Either print it or add it to the regular output ($wgOut).
1512 * @param $var A PHP variable to dump.
1514 function wfVarDump( $var ) {
1516 $s = str_replace( "\n", "<br />\n", var_export( $var, true ) . "\n" );
1517 if ( headers_sent() ||
!@is_object
( $wgOut ) ) {
1520 $wgOut->addHTML( $s );
1525 * Provide a simple HTTP error.
1527 function wfHttpError( $code, $label, $desc ) {
1530 header( "HTTP/1.0 $code $label" );
1531 header( "Status: $code $label" );
1532 $wgOut->sendCacheControl();
1534 header( 'Content-type: text/html; charset=utf-8' );
1535 print "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">".
1536 '<html><head><title>' .
1537 htmlspecialchars( $label ) .
1538 '</title></head><body><h1>' .
1539 htmlspecialchars( $label ) .
1541 nl2br( htmlspecialchars( $desc ) ) .
1542 "</p></body></html>\n";
1546 * Clear away any user-level output buffers, discarding contents.
1548 * Suitable for 'starting afresh', for instance when streaming
1549 * relatively large amounts of data without buffering, or wanting to
1550 * output image files without ob_gzhandler's compression.
1552 * The optional $resetGzipEncoding parameter controls suppression of
1553 * the Content-Encoding header sent by ob_gzhandler; by default it
1554 * is left. See comments for wfClearOutputBuffers() for why it would
1557 * Note that some PHP configuration options may add output buffer
1558 * layers which cannot be removed; these are left in place.
1560 * @param $resetGzipEncoding Bool
1562 function wfResetOutputBuffers( $resetGzipEncoding = true ) {
1563 if( $resetGzipEncoding ) {
1564 // Suppress Content-Encoding and Content-Length
1565 // headers from 1.10+s wfOutputHandler
1566 global $wgDisableOutputCompression;
1567 $wgDisableOutputCompression = true;
1569 while( $status = ob_get_status() ) {
1570 if( $status['type'] == 0 /* PHP_OUTPUT_HANDLER_INTERNAL */ ) {
1571 // Probably from zlib.output_compression or other
1572 // PHP-internal setting which can't be removed.
1574 // Give up, and hope the result doesn't break
1578 if( !ob_end_clean() ) {
1579 // Could not remove output buffer handler; abort now
1580 // to avoid getting in some kind of infinite loop.
1583 if( $resetGzipEncoding ) {
1584 if( $status['name'] == 'ob_gzhandler' ) {
1585 // Reset the 'Content-Encoding' field set by this handler
1586 // so we can start fresh.
1587 header( 'Content-Encoding:' );
1595 * More legible than passing a 'false' parameter to wfResetOutputBuffers():
1597 * Clear away output buffers, but keep the Content-Encoding header
1598 * produced by ob_gzhandler, if any.
1600 * This should be used for HTTP 304 responses, where you need to
1601 * preserve the Content-Encoding header of the real result, but
1602 * also need to suppress the output of ob_gzhandler to keep to spec
1603 * and avoid breaking Firefox in rare cases where the headers and
1604 * body are broken over two packets.
1606 function wfClearOutputBuffers() {
1607 wfResetOutputBuffers( false );
1611 * Converts an Accept-* header into an array mapping string values to quality
1614 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
1615 # No arg means accept anything (per HTTP spec)
1617 return array( $def => 1.0 );
1622 $parts = explode( ',', $accept );
1624 foreach( $parts as $part ) {
1625 # FIXME: doesn't deal with params like 'text/html; level=1'
1626 @list
( $value, $qpart ) = explode( ';', trim( $part ) );
1628 if( !isset( $qpart ) ) {
1629 $prefs[$value] = 1.0;
1630 } elseif( preg_match( '/q\s*=\s*(\d*\.\d+)/', $qpart, $match ) ) {
1631 $prefs[$value] = floatval( $match[1] );
1639 * Checks if a given MIME type matches any of the keys in the given
1640 * array. Basic wildcards are accepted in the array keys.
1642 * Returns the matching MIME type (or wildcard) if a match, otherwise
1645 * @param $type String
1646 * @param $avail Array
1650 function mimeTypeMatch( $type, $avail ) {
1651 if( array_key_exists( $type, $avail ) ) {
1654 $parts = explode( '/', $type );
1655 if( array_key_exists( $parts[0] . '/*', $avail ) ) {
1656 return $parts[0] . '/*';
1657 } elseif( array_key_exists( '*/*', $avail ) ) {
1666 * Returns the 'best' match between a client's requested internet media types
1667 * and the server's list of available types. Each list should be an associative
1668 * array of type to preference (preference is a float between 0.0 and 1.0).
1669 * Wildcards in the types are acceptable.
1671 * @param $cprefs Array: client's acceptable type list
1672 * @param $sprefs Array: server's offered types
1675 * @todo FIXME: doesn't handle params like 'text/plain; charset=UTF-8'
1676 * XXX: generalize to negotiate other stuff
1678 function wfNegotiateType( $cprefs, $sprefs ) {
1681 foreach( array_keys($sprefs) as $type ) {
1682 $parts = explode( '/', $type );
1683 if( $parts[1] != '*' ) {
1684 $ckey = mimeTypeMatch( $type, $cprefs );
1686 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1691 foreach( array_keys( $cprefs ) as $type ) {
1692 $parts = explode( '/', $type );
1693 if( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
1694 $skey = mimeTypeMatch( $type, $sprefs );
1696 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1704 foreach( array_keys( $combine ) as $type ) {
1705 if( $combine[$type] > $bestq ) {
1707 $bestq = $combine[$type];
1716 * Returns an array where the values in the first array are replaced by the
1717 * values in the second array with the corresponding keys
1721 function wfArrayLookup( $a, $b ) {
1722 return array_flip( array_intersect( array_flip( $a ), array_keys( $b ) ) );
1726 * Convenience function; returns MediaWiki timestamp for the present time.
1729 function wfTimestampNow() {
1731 return wfTimestamp( TS_MW
, time() );
1735 * Reference-counted warning suppression
1737 function wfSuppressWarnings( $end = false ) {
1738 static $suppressCount = 0;
1739 static $originalLevel = false;
1742 if ( $suppressCount ) {
1744 if ( !$suppressCount ) {
1745 error_reporting( $originalLevel );
1749 if ( !$suppressCount ) {
1750 $originalLevel = error_reporting( E_ALL
& ~
( E_WARNING | E_NOTICE | E_USER_WARNING | E_USER_NOTICE
) );
1757 * Restore error level to previous value
1759 function wfRestoreWarnings() {
1760 wfSuppressWarnings( true );
1763 # Autodetect, convert and provide timestamps of various types
1766 * Unix time - the number of seconds since 1970-01-01 00:00:00 UTC
1768 define( 'TS_UNIX', 0 );
1771 * MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
1773 define( 'TS_MW', 1 );
1776 * MySQL DATETIME (YYYY-MM-DD HH:MM:SS)
1778 define( 'TS_DB', 2 );
1781 * RFC 2822 format, for E-mail and HTTP headers
1783 define( 'TS_RFC2822', 3 );
1786 * ISO 8601 format with no timezone: 1986-02-09T20:00:00Z
1788 * This is used by Special:Export
1790 define( 'TS_ISO_8601', 4 );
1793 * An Exif timestamp (YYYY:MM:DD HH:MM:SS)
1795 * @see http://exif.org/Exif2-2.PDF The Exif 2.2 spec, see page 28 for the
1796 * DateTime tag and page 36 for the DateTimeOriginal and
1797 * DateTimeDigitized tags.
1799 define( 'TS_EXIF', 5 );
1802 * Oracle format time.
1804 define( 'TS_ORACLE', 6 );
1807 * Postgres format time.
1809 define( 'TS_POSTGRES', 7 );
1814 define( 'TS_DB2', 8 );
1817 * ISO 8601 basic format with no timezone: 19860209T200000Z
1819 * This is used by ResourceLoader
1821 define( 'TS_ISO_8601_BASIC', 9 );
1824 * @param $outputtype Mixed: A timestamp in one of the supported formats, the
1825 * function will autodetect which format is supplied and act
1827 * @param $ts Mixed: the timestamp to convert or 0 for the current timestamp
1828 * @return Mixed: String / false The same date in the format specified in $outputtype or false
1830 function wfTimestamp( $outputtype = TS_UNIX
, $ts = 0 ) {
1835 if ( !$ts ) { // We want to catch 0, '', null... but not date strings starting with a letter.
1838 } elseif ( preg_match( '/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)$/D', $ts, $da ) ) {
1840 } elseif ( preg_match( '/^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/D', $ts, $da ) ) {
1842 } elseif ( preg_match( '/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/D', $ts, $da ) ) {
1844 } elseif ( preg_match( '/^-?\d{1,13}$/D', $ts ) ) {
1847 $strtime = "@$ts"; // Undocumented?
1848 } elseif ( preg_match( '/^\d{2}-\d{2}-\d{4} \d{2}:\d{2}:\d{2}.\d{6}$/', $ts ) ) {
1849 # TS_ORACLE // session altered to DD-MM-YYYY HH24:MI:SS.FF6
1850 $strtime = preg_replace( '/(\d\d)\.(\d\d)\.(\d\d)(\.(\d+))?/', "$1:$2:$3",
1851 str_replace( '+00:00', 'UTC', $ts ) );
1852 } elseif ( preg_match( '/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.*\d*)?Z$/', $ts, $da ) ) {
1854 } elseif ( preg_match( '/^(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})(?:\.*\d*)?Z$/', $ts, $da ) ) {
1856 } elseif ( preg_match( '/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.*\d*[\+\- ](\d\d)$/', $ts, $da ) ) {
1858 } elseif ( preg_match( '/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.*\d* GMT$/', $ts, $da ) ) {
1860 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.\d\d\d$/',$ts,$da)) {
1862 } elseif ( preg_match( '/^[ \t\r\n]*([A-Z][a-z]{2},[ \t\r\n]*)?' . # Day of week
1863 '\d\d?[ \t\r\n]*[A-Z][a-z]{2}[ \t\r\n]*\d{2}(?:\d{2})?' . # dd Mon yyyy
1864 '[ \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
1865 # TS_RFC2822, accepting a trailing comment. See http://www.squid-cache.org/mail-archive/squid-users/200307/0122.html / r77171
1866 # The regex is a superset of rfc2822 for readability
1867 $strtime = strtok( $ts, ';' );
1868 } 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 ) ) {
1871 } 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 ) ) {
1876 wfDebug("wfTimestamp() fed bogus time value: TYPE=$outputtype; VALUE=$ts\n");
1883 static $formats = array(
1886 TS_DB
=> 'Y-m-d H:i:s',
1887 TS_ISO_8601
=> 'Y-m-d\TH:i:s\Z',
1888 TS_ISO_8601_BASIC
=> 'Ymd\THis\Z',
1889 TS_EXIF
=> 'Y:m:d H:i:s', // This shouldn't ever be used, but is included for completeness
1890 TS_RFC2822
=> 'D, d M Y H:i:s',
1891 TS_ORACLE
=> 'd-m-Y H:i:s.000000', // Was 'd-M-y h.i.s A' . ' +00:00' before r51500
1892 TS_POSTGRES
=> 'Y-m-d H:i:s',
1893 TS_DB2
=> 'Y-m-d H:i:s',
1896 if ( !isset( $formats[$outputtype] ) ) {
1897 throw new MWException( 'wfTimestamp() called with illegal output type.' );
1900 if ( function_exists( "date_create" ) ) {
1901 if ( count( $da ) ) {
1902 $ds = sprintf("%04d-%02d-%02dT%02d:%02d:%02d.00+00:00",
1903 (int)$da[1], (int)$da[2], (int)$da[3],
1904 (int)$da[4], (int)$da[5], (int)$da[6]);
1906 $d = date_create( $ds, new DateTimeZone( 'GMT' ) );
1907 } elseif ( $strtime ) {
1908 $d = date_create( $strtime, new DateTimeZone( 'GMT' ) );
1914 wfDebug("wfTimestamp() fed bogus time value: $outputtype; $ts\n");
1918 $output = $d->format( $formats[$outputtype] );
1920 if ( count( $da ) ) {
1921 // Warning! gmmktime() acts oddly if the month or day is set to 0
1922 // We may want to handle that explicitly at some point
1923 $uts = gmmktime( (int)$da[4], (int)$da[5], (int)$da[6],
1924 (int)$da[2], (int)$da[3], (int)$da[1] );
1925 } elseif ( $strtime ) {
1926 $uts = strtotime( $strtime );
1929 if ( $uts === false ) {
1930 wfDebug("wfTimestamp() can't parse the timestamp (non 32-bit time? Update php): $outputtype; $ts\n");
1934 if ( TS_UNIX
== $outputtype ) {
1937 $output = gmdate( $formats[$outputtype], $uts );
1940 if ( ( $outputtype == TS_RFC2822
) ||
( $outputtype == TS_POSTGRES
) ) {
1948 * Return a formatted timestamp, or null if input is null.
1949 * For dealing with nullable timestamp columns in the database.
1950 * @param $outputtype Integer
1954 function wfTimestampOrNull( $outputtype = TS_UNIX
, $ts = null ) {
1955 if( is_null( $ts ) ) {
1958 return wfTimestamp( $outputtype, $ts );
1963 * Check if the operating system is Windows
1965 * @return Bool: true if it's Windows, False otherwise.
1967 function wfIsWindows() {
1968 static $isWindows = null;
1969 if ( $isWindows === null ) {
1970 $isWindows = substr( php_uname(), 0, 7 ) == 'Windows';
1976 * Swap two variables
1978 function swap( &$x, &$y ) {
1984 function wfGetCachedNotice( $name ) {
1985 global $wgOut, $wgRenderHashAppend, $parserMemc;
1986 $fname = 'wfGetCachedNotice';
1987 wfProfileIn( $fname );
1991 if( $name === 'default' ) {
1993 global $wgSiteNotice;
1994 $notice = $wgSiteNotice;
1995 if( empty( $notice ) ) {
1996 wfProfileOut( $fname );
2000 $msg = wfMessage( $name )->inContentLanguage();
2001 if( $msg->isDisabled() ) {
2002 wfProfileOut( $fname );
2005 $notice = $msg->plain();
2008 // Use the extra hash appender to let eg SSL variants separately cache.
2009 $key = wfMemcKey( $name . $wgRenderHashAppend );
2010 $cachedNotice = $parserMemc->get( $key );
2011 if( is_array( $cachedNotice ) ) {
2012 if( md5( $notice ) == $cachedNotice['hash'] ) {
2013 $notice = $cachedNotice['html'];
2022 if( is_object( $wgOut ) ) {
2023 $parsed = $wgOut->parse( $notice );
2024 $parserMemc->set( $key, array( 'html' => $parsed, 'hash' => md5( $notice ) ), 600 );
2027 wfDebug( 'wfGetCachedNotice called for ' . $name . ' with no $wgOut available' . "\n" );
2031 $notice = '<div id="localNotice">' .$notice . '</div>';
2032 wfProfileOut( $fname );
2036 function wfGetNamespaceNotice() {
2040 if ( !isset( $wgTitle ) ||
!is_object( $wgTitle ) ) {
2044 $fname = 'wfGetNamespaceNotice';
2045 wfProfileIn( $fname );
2047 $key = 'namespacenotice-' . $wgTitle->getNsText();
2048 $namespaceNotice = wfGetCachedNotice( $key );
2049 if ( $namespaceNotice && substr( $namespaceNotice, 0, 7 ) != '<p><' ) {
2050 $namespaceNotice = '<div id="namespacebanner">' . $namespaceNotice . '</div>';
2052 $namespaceNotice = '';
2055 wfProfileOut( $fname );
2056 return $namespaceNotice;
2059 function wfGetSiteNotice() {
2061 $fname = 'wfGetSiteNotice';
2062 wfProfileIn( $fname );
2065 if( wfRunHooks( 'SiteNoticeBefore', array( &$siteNotice ) ) ) {
2066 if( is_object( $wgUser ) && $wgUser->isLoggedIn() ) {
2067 $siteNotice = wfGetCachedNotice( 'sitenotice' );
2069 $anonNotice = wfGetCachedNotice( 'anonnotice' );
2070 if( !$anonNotice ) {
2071 $siteNotice = wfGetCachedNotice( 'sitenotice' );
2073 $siteNotice = $anonNotice;
2076 if( !$siteNotice ) {
2077 $siteNotice = wfGetCachedNotice( 'default' );
2081 wfRunHooks( 'SiteNoticeAfter', array( &$siteNotice ) );
2082 wfProfileOut( $fname );
2087 * BC wrapper for MimeMagic::singleton()
2088 * @deprecated No longer needed as of 1.17 (r68836). Remove in 1.19.
2090 function &wfGetMimeMagic() {
2091 wfDeprecated( __FUNCTION__
);
2092 return MimeMagic
::singleton();
2096 * Tries to get the system directory for temporary files. The TMPDIR, TMP, and
2097 * TEMP environment variables are then checked in sequence, and if none are set
2098 * try sys_get_temp_dir() for PHP >= 5.2.1. All else fails, return /tmp for Unix
2099 * or C:\Windows\Temp for Windows and hope for the best.
2100 * It is common to call it with tempnam().
2102 * NOTE: When possible, use instead the tmpfile() function to create
2103 * temporary files to avoid race conditions on file creation, etc.
2107 function wfTempDir() {
2108 foreach( array( 'TMPDIR', 'TMP', 'TEMP' ) as $var ) {
2109 $tmp = getenv( $var );
2110 if( $tmp && file_exists( $tmp ) && is_dir( $tmp ) && is_writable( $tmp ) ) {
2114 if( function_exists( 'sys_get_temp_dir' ) ) {
2115 return sys_get_temp_dir();
2118 return wfIsWindows() ?
'C:\Windows\Temp' : '/tmp';
2122 * Make directory, and make all parent directories if they don't exist
2124 * @param $dir String: full path to directory to create
2125 * @param $mode Integer: chmod value to use, default is $wgDirectoryMode
2126 * @param $caller String: optional caller param for debugging.
2129 function wfMkdirParents( $dir, $mode = null, $caller = null ) {
2130 global $wgDirectoryMode;
2132 if ( !is_null( $caller ) ) {
2133 wfDebug( "$caller: called wfMkdirParents($dir)" );
2136 if( strval( $dir ) === '' ||
file_exists( $dir ) ) {
2140 $dir = str_replace( array( '\\', '/' ), DIRECTORY_SEPARATOR
, $dir );
2142 if ( is_null( $mode ) ) {
2143 $mode = $wgDirectoryMode;
2146 // Turn off the normal warning, we're doing our own below
2147 wfSuppressWarnings();
2148 $ok = mkdir( $dir, $mode, true ); // PHP5 <3
2149 wfRestoreWarnings();
2152 // PHP doesn't report the path in its warning message, so add our own to aid in diagnosis.
2153 trigger_error( __FUNCTION__
. ": failed to mkdir \"$dir\" mode $mode", E_USER_WARNING
);
2159 * Increment a statistics counter
2161 function wfIncrStats( $key ) {
2162 global $wgStatsMethod;
2164 if( $wgStatsMethod == 'udp' ) {
2165 global $wgUDPProfilerHost, $wgUDPProfilerPort, $wgDBname;
2168 $socket = socket_create( AF_INET
, SOCK_DGRAM
, SOL_UDP
);
2169 $statline = "stats/{$wgDBname} - 1 1 1 1 1 -total\n";
2173 strlen( $statline ),
2179 $statline = "stats/{$wgDBname} - 1 1 1 1 1 {$key}\n";
2180 wfSuppressWarnings();
2184 strlen( $statline ),
2189 wfRestoreWarnings();
2190 } elseif( $wgStatsMethod == 'cache' ) {
2192 $key = wfMemcKey( 'stats', $key );
2193 if ( is_null( $wgMemc->incr( $key ) ) ) {
2194 $wgMemc->add( $key, 1 );
2202 * @param $nr Mixed: the number to format
2203 * @param $acc Integer: the number of digits after the decimal point, default 2
2204 * @param $round Boolean: whether or not to round the value, default true
2207 function wfPercent( $nr, $acc = 2, $round = true ) {
2208 $ret = sprintf( "%.${acc}f", $nr );
2209 return $round ?
round( $ret, $acc ) . '%' : "$ret%";
2213 * Encrypt a username/password.
2215 * @param $userid Integer: ID of the user
2216 * @param $password String: password of the user
2217 * @return String: hashed password
2218 * @deprecated Use User::crypt() or User::oldCrypt() instead
2220 function wfEncryptPassword( $userid, $password ) {
2221 wfDeprecated(__FUNCTION__
);
2222 # Just wrap around User::oldCrypt()
2223 return User
::oldCrypt( $password, $userid );
2227 * Appends to second array if $value differs from that in $default
2229 function wfAppendToArrayIfNotDefault( $key, $value, $default, &$changed ) {
2230 if ( is_null( $changed ) ) {
2231 throw new MWException( 'GlobalFunctions::wfAppendToArrayIfNotDefault got null' );
2233 if ( $default[$key] !== $value ) {
2234 $changed[$key] = $value;
2239 * Since wfMsg() and co suck, they don't return false if the message key they
2240 * looked up didn't exist but a XHTML string, this function checks for the
2241 * nonexistance of messages by looking at wfMsg() output
2243 * @param $key String: the message key looked up
2244 * @return Boolean True if the message *doesn't* exist.
2246 function wfEmptyMsg( $key ) {
2247 return MessageCache
::singleton()->get( $key, /*useDB*/true, /*content*/false ) === false;
2251 * Find out whether or not a mixed variable exists in a string
2253 * @param $needle String
2254 * @param $str String
2255 * @param $insensitive Boolean
2258 function in_string( $needle, $str, $insensitive = false ) {
2260 if( $insensitive ) $func = 'stripos';
2262 return $func( $str, $needle ) !== false;
2265 function wfSpecialList( $page, $details ) {
2267 $details = $details ?
' ' . $wgContLang->getDirMark() . "($details)" : '';
2268 return $page . $details;
2272 * Returns a regular expression of url protocols
2276 function wfUrlProtocols() {
2277 global $wgUrlProtocols;
2279 static $retval = null;
2280 if ( !is_null( $retval ) ) {
2284 // Support old-style $wgUrlProtocols strings, for backwards compatibility
2285 // with LocalSettings files from 1.5
2286 if ( is_array( $wgUrlProtocols ) ) {
2287 $protocols = array();
2288 foreach ( $wgUrlProtocols as $protocol ) {
2289 $protocols[] = preg_quote( $protocol, '/' );
2292 $retval = implode( '|', $protocols );
2294 $retval = $wgUrlProtocols;
2300 * Safety wrapper around ini_get() for boolean settings.
2301 * The values returned from ini_get() are pre-normalized for settings
2302 * set via php.ini or php_flag/php_admin_flag... but *not*
2303 * for those set via php_value/php_admin_value.
2305 * It's fairly common for people to use php_value instead of php_flag,
2306 * which can leave you with an 'off' setting giving a false positive
2307 * for code that just takes the ini_get() return value as a boolean.
2309 * To make things extra interesting, setting via php_value accepts
2310 * "true" and "yes" as true, but php.ini and php_flag consider them false. :)
2311 * Unrecognized values go false... again opposite PHP's own coercion
2312 * from string to bool.
2314 * Luckily, 'properly' set settings will always come back as '0' or '1',
2315 * so we only have to worry about them and the 'improper' settings.
2317 * I frickin' hate PHP... :P
2319 * @param $setting String
2322 function wfIniGetBool( $setting ) {
2323 $val = ini_get( $setting );
2324 // 'on' and 'true' can't have whitespace around them, but '1' can.
2325 return strtolower( $val ) == 'on'
2326 ||
strtolower( $val ) == 'true'
2327 ||
strtolower( $val ) == 'yes'
2328 ||
preg_match( "/^\s*[+-]?0*[1-9]/", $val ); // approx C atoi() function
2332 * Wrapper function for PHP's dl(). This doesn't work in most situations from
2333 * PHP 5.3 onward, and is usually disabled in shared environments anyway.
2335 * @param $extension String A PHP extension. The file suffix (.so or .dll)
2337 * @return Bool - Whether or not the extension is loaded
2339 function wfDl( $extension ) {
2340 if( extension_loaded( $extension ) ) {
2344 $canDl = ( function_exists( 'dl' ) && is_callable( 'dl' )
2345 && wfIniGetBool( 'enable_dl' ) && !wfIniGetBool( 'safe_mode' ) );
2348 wfSuppressWarnings();
2349 dl( $extension . '.' . PHP_SHLIB_SUFFIX
);
2350 wfRestoreWarnings();
2352 return extension_loaded( $extension );
2356 * Execute a shell command, with time and memory limits mirrored from the PHP
2357 * configuration if supported.
2358 * @param $cmd String Command line, properly escaped for shell.
2359 * @param &$retval optional, will receive the program's exit code.
2360 * (non-zero is usually failure)
2361 * @param $environ Array optional environment variables which should be
2362 * added to the executed command environment.
2363 * @return collected stdout as a string (trailing newlines stripped)
2365 function wfShellExec( $cmd, &$retval = null, $environ = array() ) {
2366 global $IP, $wgMaxShellMemory, $wgMaxShellFileSize, $wgMaxShellTime;
2369 if ( is_null( $disabled ) ) {
2371 if( wfIniGetBool( 'safe_mode' ) ) {
2372 wfDebug( "wfShellExec can't run in safe_mode, PHP's exec functions are too broken.\n" );
2373 $disabled = 'safemode';
2375 $functions = explode( ',', ini_get( 'disable_functions' ) );
2376 $functions = array_map( 'trim', $functions );
2377 $functions = array_map( 'strtolower', $functions );
2378 if ( in_array( 'passthru', $functions ) ) {
2379 wfDebug( "passthru is in disabled_functions\n" );
2380 $disabled = 'passthru';
2386 return $disabled == 'safemode' ?
2387 'Unable to run external programs in safe mode.' :
2388 'Unable to run external programs, passthru() is disabled.';
2391 wfInitShellLocale();
2394 foreach( $environ as $k => $v ) {
2395 if ( wfIsWindows() ) {
2396 /* Surrounding a set in quotes (method used by wfEscapeShellArg) makes the quotes themselves
2397 * appear in the environment variable, so we must use carat escaping as documented in
2398 * http://technet.microsoft.com/en-us/library/cc723564.aspx
2399 * Note however that the quote isn't listed there, but is needed, and the parentheses
2400 * are listed there but doesn't appear to need it.
2402 $envcmd .= "set $k=" . preg_replace( '/([&|()<>^"])/', '^\\1', $v ) . '&& ';
2404 /* Assume this is a POSIX shell, thus required to accept variable assignments before the command
2405 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_09_01
2407 $envcmd .= "$k=" . escapeshellarg( $v ) . ' ';
2410 $cmd = $envcmd . $cmd;
2412 if ( wfIsWindows() ) {
2413 if ( version_compare( PHP_VERSION
, '5.3.0', '<' ) && /* Fixed in 5.3.0 :) */
2414 ( version_compare( PHP_VERSION
, '5.2.1', '>=' ) ||
php_uname( 's' ) == 'Windows NT' ) )
2416 # Hack to work around PHP's flawed invocation of cmd.exe
2417 # http://news.php.net/php.internals/21796
2418 # Windows 9x doesn't accept any kind of quotes
2419 $cmd = '"' . $cmd . '"';
2421 } elseif ( php_uname( 's' ) == 'Linux' ) {
2422 $time = intval( $wgMaxShellTime );
2423 $mem = intval( $wgMaxShellMemory );
2424 $filesize = intval( $wgMaxShellFileSize );
2426 if ( $time > 0 && $mem > 0 ) {
2427 $script = "$IP/bin/ulimit4.sh";
2428 if ( is_executable( $script ) ) {
2429 $cmd = '/bin/bash ' . escapeshellarg( $script ) . " $time $mem $filesize " . escapeshellarg( $cmd );
2433 wfDebug( "wfShellExec: $cmd\n" );
2435 $retval = 1; // error by default?
2437 passthru( $cmd, $retval );
2438 $output = ob_get_contents();
2441 if ( $retval == 127 ) {
2442 wfDebugLog( 'exec', "Possibly missing executable file: $cmd\n" );
2448 * Workaround for http://bugs.php.net/bug.php?id=45132
2449 * escapeshellarg() destroys non-ASCII characters if LANG is not a UTF-8 locale
2451 function wfInitShellLocale() {
2452 static $done = false;
2457 global $wgShellLocale;
2458 if ( !wfIniGetBool( 'safe_mode' ) ) {
2459 putenv( "LC_CTYPE=$wgShellLocale" );
2460 setlocale( LC_CTYPE
, $wgShellLocale );
2465 * This function works like "use VERSION" in Perl, the program will die with a
2466 * backtrace if the current version of PHP is less than the version provided
2468 * This is useful for extensions which due to their nature are not kept in sync
2469 * with releases, and might depend on other versions of PHP than the main code
2471 * Note: PHP might die due to parsing errors in some cases before it ever
2472 * manages to call this function, such is life
2474 * @see perldoc -f use
2476 * @param $req_ver Mixed: the version to check, can be a string, an integer, or
2479 function wfUsePHP( $req_ver ) {
2480 $php_ver = PHP_VERSION
;
2482 if ( version_compare( $php_ver, (string)$req_ver, '<' ) ) {
2483 throw new MWException( "PHP $req_ver required--this is only $php_ver" );
2488 * This function works like "use VERSION" in Perl except it checks the version
2489 * of MediaWiki, the program will die with a backtrace if the current version
2490 * of MediaWiki is less than the version provided.
2492 * This is useful for extensions which due to their nature are not kept in sync
2495 * @see perldoc -f use
2497 * @param $req_ver Mixed: the version to check, can be a string, an integer, or
2500 function wfUseMW( $req_ver ) {
2503 if ( version_compare( $wgVersion, (string)$req_ver, '<' ) ) {
2504 throw new MWException( "MediaWiki $req_ver required--this is only $wgVersion" );
2509 * Return the final portion of a pathname.
2510 * Reimplemented because PHP5's basename() is buggy with multibyte text.
2511 * http://bugs.php.net/bug.php?id=33898
2513 * PHP's basename() only considers '\' a pathchar on Windows and Netware.
2514 * We'll consider it so always, as we don't want \s in our Unix paths either.
2516 * @param $path String
2517 * @param $suffix String: to remove if present
2520 function wfBaseName( $path, $suffix = '' ) {
2521 $encSuffix = ( $suffix == '' )
2523 : ( '(?:' . preg_quote( $suffix, '#' ) . ')?' );
2525 if( preg_match( "#([^/\\\\]*?){$encSuffix}[/\\\\]*$#", $path, $matches ) ) {
2533 * Generate a relative path name to the given file.
2534 * May explode on non-matching case-insensitive paths,
2535 * funky symlinks, etc.
2537 * @param $path String: absolute destination path including target filename
2538 * @param $from String: Absolute source path, directory only
2541 function wfRelativePath( $path, $from ) {
2542 // Normalize mixed input on Windows...
2543 $path = str_replace( '/', DIRECTORY_SEPARATOR
, $path );
2544 $from = str_replace( '/', DIRECTORY_SEPARATOR
, $from );
2546 // Trim trailing slashes -- fix for drive root
2547 $path = rtrim( $path, DIRECTORY_SEPARATOR
);
2548 $from = rtrim( $from, DIRECTORY_SEPARATOR
);
2550 $pieces = explode( DIRECTORY_SEPARATOR
, dirname( $path ) );
2551 $against = explode( DIRECTORY_SEPARATOR
, $from );
2553 if( $pieces[0] !== $against[0] ) {
2554 // Non-matching Windows drive letters?
2555 // Return a full path.
2559 // Trim off common prefix
2560 while( count( $pieces ) && count( $against )
2561 && $pieces[0] == $against[0] ) {
2562 array_shift( $pieces );
2563 array_shift( $against );
2566 // relative dots to bump us to the parent
2567 while( count( $against ) ) {
2568 array_unshift( $pieces, '..' );
2569 array_shift( $against );
2572 array_push( $pieces, wfBaseName( $path ) );
2574 return implode( DIRECTORY_SEPARATOR
, $pieces );
2578 * Backwards array plus for people who haven't bothered to read the PHP manual
2579 * XXX: will not darn your socks for you.
2581 * @param $array1 Array
2582 * @param [$array2, [...]] Arrays
2585 function wfArrayMerge( $array1/* ... */ ) {
2586 $args = func_get_args();
2587 $args = array_reverse( $args, true );
2589 foreach ( $args as $arg ) {
2596 * Merge arrays in the style of getUserPermissionsErrors, with duplicate removal
2598 * wfMergeErrorArrays(
2599 * array( array( 'x' ) ),
2600 * array( array( 'x', '2' ) ),
2601 * array( array( 'x' ) ),
2602 * array( array( 'y') )
2606 * array( 'x', '2' ),
2611 function wfMergeErrorArrays( /*...*/ ) {
2612 $args = func_get_args();
2614 foreach ( $args as $errors ) {
2615 foreach ( $errors as $params ) {
2616 # FIXME: sometimes get nested arrays for $params,
2617 # which leads to E_NOTICEs
2618 $spec = implode( "\t", $params );
2619 $out[$spec] = $params;
2622 return array_values( $out );
2626 * parse_url() work-alike, but non-broken. Differences:
2628 * 1) Does not raise warnings on bad URLs (just returns false)
2629 * 2) Handles protocols that don't use :// (e.g., mailto: and news:) correctly
2630 * 3) Adds a "delimiter" element to the array, either '://' or ':' (see (2))
2632 * @param $url String: a URL to parse
2633 * @return Array: bits of the URL in an associative array, per PHP docs
2635 function wfParseUrl( $url ) {
2636 global $wgUrlProtocols; // Allow all protocols defined in DefaultSettings/LocalSettings.php
2637 wfSuppressWarnings();
2638 $bits = parse_url( $url );
2639 wfRestoreWarnings();
2644 // most of the protocols are followed by ://, but mailto: and sometimes news: not, check for it
2645 if ( in_array( $bits['scheme'] . '://', $wgUrlProtocols ) ) {
2646 $bits['delimiter'] = '://';
2647 } elseif ( in_array( $bits['scheme'] . ':', $wgUrlProtocols ) ) {
2648 $bits['delimiter'] = ':';
2649 // parse_url detects for news: and mailto: the host part of an url as path
2650 // We have to correct this wrong detection
2651 if ( isset( $bits['path'] ) ) {
2652 $bits['host'] = $bits['path'];
2663 * Make a URL index, appropriate for the el_index field of externallinks.
2665 function wfMakeUrlIndex( $url ) {
2666 $bits = wfParseUrl( $url );
2668 // Reverse the labels in the hostname, convert to lower case
2669 // For emails reverse domainpart only
2670 if ( $bits['scheme'] == 'mailto' ) {
2671 $mailparts = explode( '@', $bits['host'], 2 );
2672 if ( count( $mailparts ) === 2 ) {
2673 $domainpart = strtolower( implode( '.', array_reverse( explode( '.', $mailparts[1] ) ) ) );
2675 // No domain specified, don't mangle it
2678 $reversedHost = $domainpart . '@' . $mailparts[0];
2680 $reversedHost = strtolower( implode( '.', array_reverse( explode( '.', $bits['host'] ) ) ) );
2682 // Add an extra dot to the end
2683 // Why? Is it in wrong place in mailto links?
2684 if ( substr( $reversedHost, -1, 1 ) !== '.' ) {
2685 $reversedHost .= '.';
2687 // Reconstruct the pseudo-URL
2688 $prot = $bits['scheme'];
2689 $index = $prot . $bits['delimiter'] . $reversedHost;
2690 // Leave out user and password. Add the port, path, query and fragment
2691 if ( isset( $bits['port'] ) ) {
2692 $index .= ':' . $bits['port'];
2694 if ( isset( $bits['path'] ) ) {
2695 $index .= $bits['path'];
2699 if ( isset( $bits['query'] ) ) {
2700 $index .= '?' . $bits['query'];
2702 if ( isset( $bits['fragment'] ) ) {
2703 $index .= '#' . $bits['fragment'];
2709 * Do any deferred updates and clear the list
2711 * @param $commit String: set to 'commit' to commit after every update to
2712 * prevent lock contention
2714 function wfDoUpdates( $commit = '' ) {
2715 global $wgDeferredUpdateList;
2717 wfProfileIn( __METHOD__
);
2719 // No need to get master connections in case of empty updates array
2720 if ( !count( $wgDeferredUpdateList ) ) {
2721 wfProfileOut( __METHOD__
);
2725 $doCommit = $commit == 'commit';
2727 $dbw = wfGetDB( DB_MASTER
);
2730 foreach ( $wgDeferredUpdateList as $update ) {
2731 $update->doUpdate();
2733 if ( $doCommit && $dbw->trxLevel() ) {
2738 $wgDeferredUpdateList = array();
2739 wfProfileOut( __METHOD__
);
2743 * Convert an arbitrarily-long digit string from one numeric base
2744 * to another, optionally zero-padding to a minimum column width.
2746 * Supports base 2 through 36; digit values 10-36 are represented
2747 * as lowercase letters a-z. Input is case-insensitive.
2749 * @param $input String: of digits
2750 * @param $sourceBase Integer: 2-36
2751 * @param $destBase Integer: 2-36
2752 * @param $pad Integer: 1 or greater
2753 * @param $lowercase Boolean
2754 * @return String or false on invalid input
2756 function wfBaseConvert( $input, $sourceBase, $destBase, $pad = 1, $lowercase = true ) {
2757 $input = strval( $input );
2758 if( $sourceBase < 2 ||
2763 $sourceBase != intval( $sourceBase ) ||
2764 $destBase != intval( $destBase ) ||
2765 $pad != intval( $pad ) ||
2766 !is_string( $input ) ||
2770 $digitChars = ( $lowercase ) ?
'0123456789abcdefghijklmnopqrstuvwxyz' : '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
2771 $inDigits = array();
2774 // Decode and validate input string
2775 $input = strtolower( $input );
2776 for( $i = 0; $i < strlen( $input ); $i++
) {
2777 $n = strpos( $digitChars, $input{$i} );
2778 if( $n === false ||
$n > $sourceBase ) {
2784 // Iterate over the input, modulo-ing out an output digit
2785 // at a time until input is gone.
2786 while( count( $inDigits ) ) {
2788 $workDigits = array();
2791 foreach( $inDigits as $digit ) {
2792 $work *= $sourceBase;
2795 if( $work < $destBase ) {
2796 // Gonna need to pull another digit.
2797 if( count( $workDigits ) ) {
2798 // Avoid zero-padding; this lets us find
2799 // the end of the input very easily when
2800 // length drops to zero.
2804 // Finally! Actual division!
2805 $workDigits[] = intval( $work / $destBase );
2807 // Isn't it annoying that most programming languages
2808 // don't have a single divide-and-remainder operator,
2809 // even though the CPU implements it that way?
2810 $work = $work %
$destBase;
2814 // All that division leaves us with a remainder,
2815 // which is conveniently our next output digit.
2816 $outChars .= $digitChars[$work];
2819 $inDigits = $workDigits;
2822 while( strlen( $outChars ) < $pad ) {
2826 return strrev( $outChars );
2830 * Create an object with a given name and an array of construct parameters
2831 * @param $name String
2832 * @param $p Array: parameters
2835 function wfCreateObject( $name, $p ) {
2836 return MWFunction
::newObj( $name, $p );
2839 function wfHttpOnlySafe() {
2840 global $wgHttpOnlyBlacklist;
2841 if( !version_compare( '5.2', PHP_VERSION
, '<' ) ) {
2845 if( isset( $_SERVER['HTTP_USER_AGENT'] ) ) {
2846 foreach( $wgHttpOnlyBlacklist as $regex ) {
2847 if( preg_match( $regex, $_SERVER['HTTP_USER_AGENT'] ) ) {
2857 * Initialise php session
2859 function wfSetupSession( $sessionId = false ) {
2860 global $wgSessionsInMemcached, $wgCookiePath, $wgCookieDomain,
2861 $wgCookieSecure, $wgCookieHttpOnly, $wgSessionHandler;
2862 if( $wgSessionsInMemcached ) {
2863 require_once( 'MemcachedSessions.php' );
2864 } elseif( $wgSessionHandler && $wgSessionHandler != ini_get( 'session.save_handler' ) ) {
2865 # Only set this if $wgSessionHandler isn't null and session.save_handler
2866 # hasn't already been set to the desired value (that causes errors)
2867 ini_set( 'session.save_handler', $wgSessionHandler );
2869 $httpOnlySafe = wfHttpOnlySafe();
2870 wfDebugLog( 'cookie',
2871 'session_set_cookie_params: "' . implode( '", "',
2877 $httpOnlySafe && $wgCookieHttpOnly ) ) . '"' );
2878 if( $httpOnlySafe && $wgCookieHttpOnly ) {
2879 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookieHttpOnly );
2881 // PHP 5.1 throws warnings if you pass the HttpOnly parameter for 5.2.
2882 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
2884 session_cache_limiter( 'private, must-revalidate' );
2886 session_id( $sessionId );
2888 wfSuppressWarnings();
2890 wfRestoreWarnings();
2894 * Get an object from the precompiled serialized directory
2896 * @return Mixed: the variable on success, false on failure
2898 function wfGetPrecompiledData( $name ) {
2901 $file = "$IP/serialized/$name";
2902 if ( file_exists( $file ) ) {
2903 $blob = file_get_contents( $file );
2905 return unserialize( $blob );
2911 function wfGetCaller( $level = 2 ) {
2912 $backtrace = wfDebugBacktrace();
2913 if ( isset( $backtrace[$level] ) ) {
2914 return wfFormatStackFrame( $backtrace[$level] );
2916 $caller = 'unknown';
2922 * Return a string consisting of callers in the stack. Useful sometimes
2923 * for profiling specific points.
2925 * @param $limit The maximum depth of the stack frame to return, or false for
2928 function wfGetAllCallers( $limit = 3 ) {
2929 $trace = array_reverse( wfDebugBacktrace() );
2930 if ( !$limit ||
$limit > count( $trace ) - 1 ) {
2931 $limit = count( $trace ) - 1;
2933 $trace = array_slice( $trace, -$limit - 1, $limit );
2934 return implode( '/', array_map( 'wfFormatStackFrame', $trace ) );
2938 * Return a string representation of frame
2940 function wfFormatStackFrame( $frame ) {
2941 return isset( $frame['class'] ) ?
2942 $frame['class'] . '::' . $frame['function'] :
2949 function wfMemcKey( /*... */ ) {
2950 $args = func_get_args();
2951 $key = wfWikiID() . ':' . implode( ':', $args );
2952 $key = str_replace( ' ', '_', $key );
2957 * Get a cache key for a foreign DB
2959 function wfForeignMemcKey( $db, $prefix /*, ... */ ) {
2960 $args = array_slice( func_get_args(), 2 );
2962 $key = "$db-$prefix:" . implode( ':', $args );
2964 $key = $db . ':' . implode( ':', $args );
2970 * Get an ASCII string identifying this wiki
2971 * This is used as a prefix in memcached keys
2973 function wfWikiID() {
2974 global $wgDBprefix, $wgDBname;
2975 if ( $wgDBprefix ) {
2976 return "$wgDBname-$wgDBprefix";
2983 * Split a wiki ID into DB name and table prefix
2985 function wfSplitWikiID( $wiki ) {
2986 $bits = explode( '-', $wiki, 2 );
2987 if ( count( $bits ) < 2 ) {
2994 * Get a Database object.
2995 * @param $db Integer: index of the connection to get. May be DB_MASTER for the
2996 * master (for write queries), DB_SLAVE for potentially lagged read
2997 * queries, or an integer >= 0 for a particular server.
2999 * @param $groups Mixed: query groups. An array of group names that this query
3000 * belongs to. May contain a single string if the query is only
3003 * @param $wiki String: the wiki ID, or false for the current wiki
3005 * Note: multiple calls to wfGetDB(DB_SLAVE) during the course of one request
3006 * will always return the same object, unless the underlying connection or load
3007 * balancer is manually destroyed.
3009 * @return DatabaseBase
3011 function &wfGetDB( $db, $groups = array(), $wiki = false ) {
3012 return wfGetLB( $wiki )->getConnection( $db, $groups, $wiki );
3016 * Get a load balancer object.
3018 * @param $wiki String: wiki ID, or false for the current wiki
3019 * @return LoadBalancer
3021 function wfGetLB( $wiki = false ) {
3022 return wfGetLBFactory()->getMainLB( $wiki );
3026 * Get the load balancer factory object
3029 function &wfGetLBFactory() {
3030 return LBFactory
::singleton();
3035 * Shortcut for RepoGroup::singleton()->findFile()
3036 * @param $title String or Title object
3037 * @param $options Associative array of options:
3038 * time: requested time for an archived image, or false for the
3039 * current version. An image object will be returned which was
3040 * created at the specified time.
3042 * ignoreRedirect: If true, do not follow file redirects
3044 * private: If true, return restricted (deleted) files if the current
3045 * user is allowed to view them. Otherwise, such files will not
3048 * bypassCache: If true, do not use the process-local cache of File objects
3050 * @return File, or false if the file does not exist
3052 function wfFindFile( $title, $options = array() ) {
3053 return RepoGroup
::singleton()->findFile( $title, $options );
3057 * Get an object referring to a locally registered file.
3058 * Returns a valid placeholder object if the file does not exist.
3059 * @param $title Title or String
3060 * @return File, or null if passed an invalid Title
3062 function wfLocalFile( $title ) {
3063 return RepoGroup
::singleton()->getLocalRepo()->newFile( $title );
3067 * Should low-performance queries be disabled?
3071 function wfQueriesMustScale() {
3072 global $wgMiserMode;
3074 ||
( SiteStats
::pages() > 100000
3075 && SiteStats
::edits() > 1000000
3076 && SiteStats
::users() > 10000 );
3080 * Get the path to a specified script file, respecting file
3081 * extensions; this is a wrapper around $wgScriptExtension etc.
3083 * @param $script String: script filename, sans extension
3086 function wfScript( $script = 'index' ) {
3087 global $wgScriptPath, $wgScriptExtension;
3088 return "{$wgScriptPath}/{$script}{$wgScriptExtension}";
3092 * Get the script URL.
3094 * @return script URL
3096 function wfGetScriptUrl() {
3097 if( isset( $_SERVER['SCRIPT_NAME'] ) ) {
3099 # as it was called, minus the query string.
3101 # Some sites use Apache rewrite rules to handle subdomains,
3102 # and have PHP set up in a weird way that causes PHP_SELF
3103 # to contain the rewritten URL instead of the one that the
3104 # outside world sees.
3106 # If in this mode, use SCRIPT_URL instead, which mod_rewrite
3107 # provides containing the "before" URL.
3108 return $_SERVER['SCRIPT_NAME'];
3110 return $_SERVER['URL'];
3115 * Convenience function converts boolean values into "true"
3116 * or "false" (string) values
3118 * @param $value Boolean
3121 function wfBoolToStr( $value ) {
3122 return $value ?
'true' : 'false';
3126 * Load an extension messages file
3127 * @deprecated in 1.16, warnings in 1.18, remove in 1.20
3129 function wfLoadExtensionMessages( $extensionName, $langcode = false ) {
3130 wfDeprecated( __FUNCTION__
);
3134 * Get a platform-independent path to the null file, e.g.
3139 function wfGetNull() {
3140 return wfIsWindows()
3146 * Displays a maxlag error
3148 * @param $host String: server that lags the most
3149 * @param $lag Integer: maxlag (actual)
3150 * @param $maxLag Integer: maxlag (requested)
3152 function wfMaxlagError( $host, $lag, $maxLag ) {
3153 global $wgShowHostnames;
3154 header( 'HTTP/1.1 503 Service Unavailable' );
3155 header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
3156 header( 'X-Database-Lag: ' . intval( $lag ) );
3157 header( 'Content-Type: text/plain' );
3158 if( $wgShowHostnames ) {
3159 echo "Waiting for $host: $lag seconds lagged\n";
3161 echo "Waiting for a database server: $lag seconds lagged\n";
3166 * Throws a warning that $function is deprecated
3167 * @param $function String
3170 function wfDeprecated( $function ) {
3171 static $functionsWarned = array();
3172 if ( !isset( $functionsWarned[$function] ) ) {
3173 $functionsWarned[$function] = true;
3174 wfWarn( "Use of $function is deprecated.", 2 );
3179 * Send a warning either to the debug log or in a PHP error depending on
3180 * $wgDevelopmentWarnings
3182 * @param $msg String: message to send
3183 * @param $callerOffset Integer: number of itmes to go back in the backtrace to
3184 * find the correct caller (1 = function calling wfWarn, ...)
3185 * @param $level Integer: PHP error level; only used when $wgDevelopmentWarnings
3188 function wfWarn( $msg, $callerOffset = 1, $level = E_USER_NOTICE
) {
3189 $callers = wfDebugBacktrace();
3190 if( isset( $callers[$callerOffset +
1] ) ){
3191 $callerfunc = $callers[$callerOffset +
1];
3192 $callerfile = $callers[$callerOffset];
3193 if( isset( $callerfile['file'] ) && isset( $callerfile['line'] ) ) {
3194 $file = $callerfile['file'] . ' at line ' . $callerfile['line'];
3196 $file = '(internal function)';
3199 if( isset( $callerfunc['class'] ) ) {
3200 $func .= $callerfunc['class'] . '::';
3202 if( isset( $callerfunc['function'] ) ) {
3203 $func .= $callerfunc['function'];
3205 $msg .= " [Called from $func in $file]";
3208 global $wgDevelopmentWarnings;
3209 if ( $wgDevelopmentWarnings ) {
3210 trigger_error( $msg, $level );
3212 wfDebug( "$msg\n" );
3217 * Sleep until the worst slave's replication lag is less than or equal to
3218 * $maxLag, in seconds. Use this when updating very large numbers of rows, as
3219 * in maintenance scripts, to avoid causing too much lag. Of course, this is
3220 * a no-op if there are no slaves.
3222 * Every time the function has to wait for a slave, it will print a message to
3223 * that effect (and then sleep for a little while), so it's probably not best
3224 * to use this outside maintenance scripts in its present form.
3226 * @param $maxLag Integer
3227 * @param $wiki mixed Wiki identifier accepted by wfGetLB
3230 function wfWaitForSlaves( $maxLag, $wiki = false ) {
3232 $lb = wfGetLB( $wiki );
3233 list( $host, $lag ) = $lb->getMaxLag( $wiki );
3234 while( $lag > $maxLag ) {
3235 wfSuppressWarnings();
3236 $name = gethostbyaddr( $host );
3237 wfRestoreWarnings();
3238 if( $name !== false ) {
3241 print "Waiting for $host (lagged $lag seconds)...\n";
3243 list( $host, $lag ) = $lb->getMaxLag();
3249 * Used to be used for outputting text in the installer/updater
3250 * @deprecated Warnings in 1.19, removal in 1.20
3252 function wfOut( $s ) {
3253 global $wgCommandLineMode;
3254 if ( $wgCommandLineMode && !defined( 'MEDIAWIKI_INSTALL' ) ) {
3257 echo htmlspecialchars( $s );
3263 * Count down from $n to zero on the terminal, with a one-second pause
3264 * between showing each number. For use in command-line scripts.
3266 function wfCountDown( $n ) {
3267 for ( $i = $n; $i >= 0; $i-- ) {
3269 echo str_repeat( "\x08", strlen( $i +
1 ) );
3281 * Generate a random 32-character hexadecimal token.
3282 * @param $salt Mixed: some sort of salt, if necessary, to add to random
3283 * characters before hashing.
3285 function wfGenerateToken( $salt = '' ) {
3286 $salt = serialize( $salt );
3287 return md5( mt_rand( 0, 0x7fffffff ) . $salt );
3291 * Replace all invalid characters with -
3292 * @param $name Mixed: filename to process
3294 function wfStripIllegalFilenameChars( $name ) {
3295 global $wgIllegalFileChars;
3296 $name = wfBaseName( $name );
3297 $name = preg_replace(
3298 "/[^" . Title
::legalChars() . "]" .
3299 ( $wgIllegalFileChars ?
"|[" . $wgIllegalFileChars . "]" : '' ) .
3308 * Insert array into another array after the specified *KEY*
3309 * @param $array Array: The array.
3310 * @param $insert Array: The array to insert.
3311 * @param $after Mixed: The key to insert after
3313 function wfArrayInsertAfter( $array, $insert, $after ) {
3314 // Find the offset of the element to insert after.
3315 $keys = array_keys( $array );
3316 $offsetByKey = array_flip( $keys );
3318 $offset = $offsetByKey[$after];
3320 // Insert at the specified offset
3321 $before = array_slice( $array, 0, $offset +
1, true );
3322 $after = array_slice( $array, $offset +
1, count( $array ) - $offset, true );
3324 $output = $before +
$insert +
$after;
3329 /* Recursively converts the parameter (an object) to an array with the same data */
3330 function wfObjectToArray( $object, $recursive = true ) {
3332 foreach ( get_object_vars( $object ) as $key => $value ) {
3333 if ( is_object( $value ) && $recursive ) {
3334 $value = wfObjectToArray( $value );
3337 $array[$key] = $value;
3344 * Set PHP's memory limit to the larger of php.ini or $wgMemoryLimit;
3345 * @return Integer value memory was set to.
3347 function wfMemoryLimit() {
3348 global $wgMemoryLimit;
3349 $memlimit = wfShorthandToInteger( ini_get( 'memory_limit' ) );
3350 if( $memlimit != -1 ) {
3351 $conflimit = wfShorthandToInteger( $wgMemoryLimit );
3352 if( $conflimit == -1 ) {
3353 wfDebug( "Removing PHP's memory limit\n" );
3354 wfSuppressWarnings();
3355 ini_set( 'memory_limit', $conflimit );
3356 wfRestoreWarnings();
3358 } elseif ( $conflimit > $memlimit ) {
3359 wfDebug( "Raising PHP's memory limit to $conflimit bytes\n" );
3360 wfSuppressWarnings();
3361 ini_set( 'memory_limit', $conflimit );
3362 wfRestoreWarnings();
3370 * Converts shorthand byte notation to integer form
3371 * @param $string String
3374 function wfShorthandToInteger( $string = '' ) {
3375 $string = trim( $string );
3376 if( $string === '' ) {
3379 $last = $string[strlen( $string ) - 1];
3380 $val = intval( $string );
3385 // break intentionally missing
3389 // break intentionally missing
3399 * Get the normalised IETF language tag
3400 * See unit test for examples.
3401 * @param $code String: The language code.
3402 * @return $langCode String: The language code which complying with BCP 47 standards.
3404 function wfBCP47( $code ) {
3405 $codeSegment = explode( '-', $code );
3406 foreach ( $codeSegment as $segNo => $seg ) {
3407 if ( count( $codeSegment ) > 0 ) {
3408 // when previous segment is x, it is a private segment and should be lc
3409 if( $segNo > 0 && strtolower( $codeSegment[($segNo - 1)] ) == 'x') {
3410 $codeBCP[$segNo] = strtolower( $seg );
3411 // ISO 3166 country code
3412 } elseif ( ( strlen( $seg ) == 2 ) && ( $segNo > 0 ) ) {
3413 $codeBCP[$segNo] = strtoupper( $seg );
3414 // ISO 15924 script code
3415 } elseif ( ( strlen( $seg ) == 4 ) && ( $segNo > 0 ) ) {
3416 $codeBCP[$segNo] = ucfirst( strtolower( $seg ) );
3417 // Use lowercase for other cases
3419 $codeBCP[$segNo] = strtolower( $seg );
3422 // Use lowercase for single segment
3423 $codeBCP[$segNo] = strtolower( $seg );
3426 $langCode = implode( '-', $codeBCP );
3430 function wfArrayMap( $function, $input ) {
3431 $ret = array_map( $function, $input );
3432 foreach ( $ret as $key => $value ) {
3433 $taint = istainted( $input[$key] );
3435 taint( $ret[$key], $taint );