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.
23 if( !function_exists( 'iconv' ) ) {
24 # iconv support is not in the default configuration and so may not be present.
25 # Assume will only ever use utf-8 and iso-8859-1.
26 # This will *not* work in all circumstances.
27 function iconv( $from, $to, $string ) {
28 if ( substr( $to, -8 ) == '//IGNORE' ) {
29 $to = substr( $to, 0, strlen( $to ) - 8 );
31 if( strcasecmp( $from, $to ) == 0 ) {
34 if( strcasecmp( $from, 'utf-8' ) == 0 ) {
35 return utf8_decode( $string );
37 if( strcasecmp( $to, 'utf-8' ) == 0 ) {
38 return utf8_encode( $string );
44 if ( !function_exists( 'mb_substr' ) ) {
46 * Fallback implementation for mb_substr, hardcoded to UTF-8.
47 * Attempts to be at least _moderately_ efficient; best optimized
48 * for relatively small offset and count values -- about 5x slower
49 * than native mb_string in my testing.
51 * Larger offsets are still fairly efficient for Latin text, but
52 * can be up to 100x slower than native if the text is heavily
53 * multibyte and we have to slog through a few hundred kb.
55 function mb_substr( $str, $start, $count='end' ) {
57 $split = mb_substr_split_unicode( $str, intval( $start ) );
58 $str = substr( $str, $split );
61 if( $count !== 'end' ) {
62 $split = mb_substr_split_unicode( $str, intval( $count ) );
63 $str = substr( $str, 0, $split );
69 function mb_substr_split_unicode( $str, $splitPos ) {
70 if( $splitPos == 0 ) {
74 $byteLen = strlen( $str );
77 if( $splitPos > 256 ) {
78 // Optimize large string offsets by skipping ahead N bytes.
79 // This will cut out most of our slow time on Latin-based text,
80 // and 1/2 to 1/3 on East European and Asian scripts.
82 while ( $bytePos < $byteLen && $str{$bytePos} >= "\x80" && $str{$bytePos} < "\xc0" ) {
85 $charPos = mb_strlen( substr( $str, 0, $bytePos ) );
91 while( $charPos++
< $splitPos ) {
93 // Move past any tail bytes
94 while ( $bytePos < $byteLen && $str{$bytePos} >= "\x80" && $str{$bytePos} < "\xc0" ) {
99 $splitPosX = $splitPos +
1;
100 $charPos = 0; // relative to end of string; we don't care about the actual char position here
102 while( $bytePos > 0 && $charPos-- >= $splitPosX ) {
104 // Move past any tail bytes
105 while ( $bytePos > 0 && $str{$bytePos} >= "\x80" && $str{$bytePos} < "\xc0" ) {
115 if ( !function_exists( 'mb_strlen' ) ) {
117 * Fallback implementation of mb_strlen, hardcoded to UTF-8.
119 * @param string $enc optional encoding; ignored
122 function mb_strlen( $str, $enc = '' ) {
123 $counts = count_chars( $str );
127 for( $i = 0; $i < 0x80; $i++
) {
128 $total +
= $counts[$i];
131 // Count multibyte sequence heads
132 for( $i = 0xc0; $i < 0xff; $i++
) {
133 $total +
= $counts[$i];
140 if( !function_exists( 'mb_strpos' ) ) {
142 * Fallback implementation of mb_strpos, hardcoded to UTF-8.
143 * @param $haystack String
144 * @param $needle String
145 * @param $offset String: optional start position
146 * @param $encoding String: optional encoding; ignored
149 function mb_strpos( $haystack, $needle, $offset = 0, $encoding = '' ) {
150 $needle = preg_quote( $needle, '/' );
153 preg_match( '/' . $needle . '/u', $haystack, $ar, PREG_OFFSET_CAPTURE
, $offset );
155 if( isset( $ar[0][1] ) ) {
163 if( !function_exists( 'mb_strrpos' ) ) {
165 * Fallback implementation of mb_strrpos, hardcoded to UTF-8.
166 * @param $haystack String
167 * @param $needle String
168 * @param $offset String: optional start position
169 * @param $encoding String: optional encoding; ignored
172 function mb_strrpos( $haystack, $needle, $offset = 0, $encoding = '' ) {
173 $needle = preg_quote( $needle, '/' );
176 preg_match_all( '/' . $needle . '/u', $haystack, $ar, PREG_OFFSET_CAPTURE
, $offset );
178 if( isset( $ar[0] ) && count( $ar[0] ) > 0 &&
179 isset( $ar[0][count( $ar[0] ) - 1][1] ) ) {
180 return $ar[0][count( $ar[0] ) - 1][1];
187 // Support for Wietse Venema's taint feature
188 if ( !function_exists( 'istainted' ) ) {
189 function istainted( $var ) {
192 function taint( $var, $level = 0 ) {}
193 function untaint( $var, $level = 0 ) {}
194 define( 'TC_HTML', 1 );
195 define( 'TC_SHELL', 1 );
196 define( 'TC_MYSQL', 1 );
197 define( 'TC_PCRE', 1 );
198 define( 'TC_SELF', 1 );
204 * Like array_diff( $a, $b ) except that it works with two-dimensional arrays.
206 function wfArrayDiff2( $a, $b ) {
207 return array_udiff( $a, $b, 'wfArrayDiff2_cmp' );
209 function wfArrayDiff2_cmp( $a, $b ) {
210 if ( !is_array( $a ) ) {
211 return strcmp( $a, $b );
212 } elseif ( count( $a ) !== count( $b ) ) {
213 return count( $a ) < count( $b ) ?
-1 : 1;
217 while( ( list( $keyA, $valueA ) = each( $a ) ) && ( list( $keyB, $valueB ) = each( $b ) ) ) {
218 $cmp = strcmp( $valueA, $valueB );
228 * Seed Mersenne Twister
229 * No-op for compatibility; only necessary in PHP < 4.2.0
230 * @deprecated. Remove in 1.18
232 function wfSeedRandom() {
233 wfDeprecated(__FUNCTION__
);
237 * Get a random decimal value between 0 and 1, in a way
238 * not likely to give duplicate values for any realistic
239 * number of articles.
243 function wfRandom() {
244 # The maximum random value is "only" 2^31-1, so get two random
245 # values to reduce the chance of dupes
246 $max = mt_getrandmax() +
1;
247 $rand = number_format( ( mt_rand() * $max +
mt_rand() )
248 / $max / $max, 12, '.', '' );
253 * We want some things to be included as literal characters in our title URLs
254 * for prettiness, which urlencode encodes by default. According to RFC 1738,
255 * all of the following should be safe:
259 * But + is not safe because it's used to indicate a space; &= are only safe in
260 * paths and not in queries (and we don't distinguish here); ' seems kind of
261 * scary; and urlencode() doesn't touch -_. to begin with. Plus, although /
262 * is reserved, we don't care. So the list we unescape is:
266 * However, IIS7 redirects fail when the url contains a colon (Bug 22709),
267 * so no fancy : for IIS7.
269 * %2F in the page titles seems to fatally break for some reason.
274 function wfUrlencode( $s ) {
276 if ( is_null( $needle ) ) {
277 $needle = array( '%3B', '%40', '%24', '%21', '%2A', '%28', '%29', '%2C', '%2F' );
278 if ( !isset( $_SERVER['SERVER_SOFTWARE'] ) ||
( strpos( $_SERVER['SERVER_SOFTWARE'], 'Microsoft-IIS/7' ) === false ) ) {
283 $s = urlencode( $s );
286 array( ';', '@', '$', '!', '*', '(', ')', ',', '/', ':' ),
294 * Sends a line to the debug log if enabled or, optionally, to a comment in output.
295 * In normal operation this is a NOP.
297 * Controlling globals:
298 * $wgDebugLogFile - points to the log file
299 * $wgProfileOnly - if set, normal debug messages will not be recorded.
300 * $wgDebugRawPage - if false, 'action=raw' hits will not result in debug output.
301 * $wgDebugComments - if on, some debug items may appear in comments in the HTML output.
303 * @param $text String
304 * @param $logonly Bool: set true to avoid appearing in HTML when $wgDebugComments is set
306 function wfDebug( $text, $logonly = false ) {
307 global $wgOut, $wgDebugLogFile, $wgDebugComments, $wgProfileOnly, $wgDebugRawPage;
308 global $wgDebugLogPrefix, $wgShowDebug;
309 static $recursion = 0;
311 static $cache = array(); // Cache of unoutputted messages
312 $text = wfDebugTimer() . $text;
314 # Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
315 if ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' && !$wgDebugRawPage ) {
319 if ( ( $wgDebugComments ||
$wgShowDebug ) && !$logonly ) {
322 if ( !isset( $wgOut ) ) {
325 if ( !StubObject
::isRealObject( $wgOut ) ) {
334 // add the message and possible cached ones to the output
335 array_map( array( $wgOut, 'debug' ), $cache );
338 if ( $wgDebugLogFile != '' && !$wgProfileOnly ) {
339 # Strip unprintables; they can switch terminal modes when binary data
340 # gets dumped, which is pretty annoying.
341 $text = preg_replace( '![\x00-\x08\x0b\x0c\x0e-\x1f]!', ' ', $text );
342 $text = $wgDebugLogPrefix . $text;
343 wfErrorLog( $text, $wgDebugLogFile );
347 function wfDebugTimer() {
348 global $wgDebugTimestamps;
349 if ( !$wgDebugTimestamps ) {
352 static $start = null;
354 if ( $start === null ) {
355 $start = microtime( true );
356 $prefix = "\n$start";
358 $prefix = sprintf( "%6.4f", microtime( true ) - $start );
361 return $prefix . ' ';
365 * Send a line giving PHP memory usage.
366 * @param $exact Bool: print exact values instead of kilobytes (default: false)
368 function wfDebugMem( $exact = false ) {
369 $mem = memory_get_usage();
371 $mem = floor( $mem / 1024 ) . ' kilobytes';
375 wfDebug( "Memory usage: $mem\n" );
379 * Send a line to a supplementary debug log file, if configured, or main debug log if not.
380 * $wgDebugLogGroups[$logGroup] should be set to a filename to send to a separate log.
382 * @param $logGroup String
383 * @param $text String
384 * @param $public Bool: whether to log the event in the public log if no private
385 * log file is specified, (default true)
387 function wfDebugLog( $logGroup, $text, $public = true ) {
388 global $wgDebugLogGroups, $wgShowHostnames;
389 $text = trim( $text ) . "\n";
390 if( isset( $wgDebugLogGroups[$logGroup] ) ) {
391 $time = wfTimestamp( TS_DB
);
393 if ( $wgShowHostnames ) {
394 $host = wfHostname();
398 wfErrorLog( "$time $host $wiki: $text", $wgDebugLogGroups[$logGroup] );
399 } elseif ( $public === true ) {
400 wfDebug( $text, true );
405 * Log for database errors
406 * @param $text String: database error message.
408 function wfLogDBError( $text ) {
409 global $wgDBerrorLog, $wgDBname;
410 if ( $wgDBerrorLog ) {
411 $host = trim(`hostname`
);
412 $text = date( 'D M j G:i:s T Y' ) . "\t$host\t$wgDBname\t$text";
413 wfErrorLog( $text, $wgDBerrorLog );
418 * Log to a file without getting "file size exceeded" signals.
420 * Can also log to TCP or UDP with the syntax udp://host:port/prefix. This will
421 * send lines to the specified port, prefixed by the specified prefix and a space.
423 function wfErrorLog( $text, $file ) {
424 if ( substr( $file, 0, 4 ) == 'udp:' ) {
425 # Needs the sockets extension
426 if ( preg_match( '!^(tcp|udp):(?://)?\[([0-9a-fA-F:]+)\]:(\d+)(?:/(.*))?$!', $file, $m ) ) {
427 // IPv6 bracketed host
429 $port = intval( $m[3] );
430 $prefix = isset( $m[4] ) ?
$m[4] : false;
432 } elseif ( preg_match( '!^(tcp|udp):(?://)?([a-zA-Z0-9.-]+):(\d+)(?:/(.*))?$!', $file, $m ) ) {
434 if ( !IP
::isIPv4( $host ) ) {
435 $host = gethostbyname( $host );
437 $port = intval( $m[3] );
438 $prefix = isset( $m[4] ) ?
$m[4] : false;
441 throw new MWException( __METHOD__
. ': Invalid UDP specification' );
443 // Clean it up for the multiplexer
444 if ( strval( $prefix ) !== '' ) {
445 $text = preg_replace( '/^/m', $prefix . ' ', $text );
446 if ( substr( $text, -1 ) != "\n" ) {
451 $sock = socket_create( $domain, SOCK_DGRAM
, SOL_UDP
);
455 socket_sendto( $sock, $text, strlen( $text ), 0, $host, $port );
456 socket_close( $sock );
458 wfSuppressWarnings();
459 $exists = file_exists( $file );
460 $size = $exists ?
filesize( $file ) : false;
461 if ( !$exists ||
( $size !== false && $size +
strlen( $text ) < 0x7fffffff ) ) {
462 error_log( $text, 3, $file );
471 function wfLogProfilingData() {
472 global $wgRequestTime, $wgDebugLogFile, $wgDebugRawPage, $wgRequest;
473 global $wgProfiler, $wgProfileLimit, $wgUser;
474 # Profiling must actually be enabled...
475 if( is_null( $wgProfiler ) ) {
478 # Get total page request time
480 $elapsed = $now - $wgRequestTime;
481 # Only show pages that longer than $wgProfileLimit time (default is 0)
482 if( $elapsed <= $wgProfileLimit ) {
485 $prof = wfGetProfilingOutput( $wgRequestTime, $elapsed );
487 if( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) {
488 $forward = ' forwarded for ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
490 if( !empty( $_SERVER['HTTP_CLIENT_IP'] ) ) {
491 $forward .= ' client IP ' . $_SERVER['HTTP_CLIENT_IP'];
493 if( !empty( $_SERVER['HTTP_FROM'] ) ) {
494 $forward .= ' from ' . $_SERVER['HTTP_FROM'];
497 $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
499 // Don't unstub $wgUser at this late stage just for statistics purposes
500 // FIXME: We can detect some anons even if it is not loaded. See User::getId()
501 if( $wgUser->mDataLoaded
&& $wgUser->isAnon() ) {
504 $log = sprintf( "%s\t%04.3f\t%s\n",
505 gmdate( 'YmdHis' ), $elapsed,
506 urldecode( $wgRequest->getRequestURL() . $forward ) );
507 if ( $wgDebugLogFile != '' && ( $wgRequest->getVal( 'action' ) != 'raw' ||
$wgDebugRawPage ) ) {
508 wfErrorLog( $log . $prof, $wgDebugLogFile );
513 * Check if the wiki read-only lock file is present. This can be used to lock
514 * off editing functions, but doesn't guarantee that the database will not be
518 function wfReadOnly() {
519 global $wgReadOnlyFile, $wgReadOnly;
521 if ( !is_null( $wgReadOnly ) ) {
522 return (bool)$wgReadOnly;
524 if ( $wgReadOnlyFile == '' ) {
527 // Set $wgReadOnly for faster access next time
528 if ( is_file( $wgReadOnlyFile ) ) {
529 $wgReadOnly = file_get_contents( $wgReadOnlyFile );
533 return (bool)$wgReadOnly;
536 function wfReadOnlyReason() {
543 * Return a Language object from $langcode
544 * @param $langcode Mixed: either:
545 * - a Language object
546 * - code of the language to get the message for, if it is
547 * a valid code create a language for that language, if
548 * it is a string but not a valid code then make a basic
550 * - a boolean: if it's false then use the current users
551 * language (as a fallback for the old parameter
552 * functionality), or if it is true then use the wikis
553 * @return Language object
555 function wfGetLangObj( $langcode = false ) {
556 # Identify which language to get or create a language object for.
557 # Using is_object here due to Stub objects.
558 if( is_object( $langcode ) ) {
559 # Great, we already have the object (hopefully)!
563 global $wgContLang, $wgLanguageCode;
564 if( $langcode === true ||
$langcode === $wgLanguageCode ) {
565 # $langcode is the language code of the wikis content language object.
566 # or it is a boolean and value is true
571 if( $langcode === false ||
$langcode === $wgLang->getCode() ) {
572 # $langcode is the language code of user language object.
573 # or it was a boolean and value is false
577 $validCodes = array_keys( Language
::getLanguageNames() );
578 if( in_array( $langcode, $validCodes ) ) {
579 # $langcode corresponds to a valid language.
580 return Language
::factory( $langcode );
583 # $langcode is a string, but not a valid language code; use content language.
584 wfDebug( "Invalid language code passed to wfGetLangObj, falling back to content language.\n" );
589 * Use this instead of $wgContLang, when working with user interface.
590 * User interface is currently hard coded according to wiki content language
591 * in many ways, especially regarding to text direction. There is lots stuff
592 * to fix, hence this function to keep the old behaviour unless the global
593 * $wgBetterDirectionality is enabled (or removed when everything works).
595 function wfUILang() {
596 global $wgBetterDirectionality;
597 return wfGetLangObj( !$wgBetterDirectionality );
601 * This is the new function for getting translated interface messages.
602 * See the Message class for documentation how to use them.
603 * The intention is that this function replaces all old wfMsg* functions.
604 * @param $key \string Message key.
605 * Varargs: normal message parameters.
606 * @return \type{Message}
609 function wfMessage( $key /*...*/) {
610 $params = func_get_args();
611 array_shift( $params );
612 return new Message( $key, $params );
616 * Get a message from anywhere, for the current user language.
618 * Use wfMsgForContent() instead if the message should NOT
619 * change depending on the user preferences.
621 * @param $key String: lookup key for the message, usually
622 * defined in languages/Language.php
624 * This function also takes extra optional parameters (not
625 * shown in the function definition), which can be used to
626 * insert variable text into the predefined message.
628 function wfMsg( $key ) {
629 $args = func_get_args();
630 array_shift( $args );
631 return wfMsgReal( $key, $args, true );
635 * Same as above except doesn't transform the message
637 function wfMsgNoTrans( $key ) {
638 $args = func_get_args();
639 array_shift( $args );
640 return wfMsgReal( $key, $args, true, false, false );
644 * Get a message from anywhere, for the current global language
645 * set with $wgLanguageCode.
647 * Use this if the message should NOT change dependent on the
648 * language set in the user's preferences. This is the case for
649 * most text written into logs, as well as link targets (such as
650 * the name of the copyright policy page). Link titles, on the
651 * other hand, should be shown in the UI language.
653 * Note that MediaWiki allows users to change the user interface
654 * language in their preferences, but a single installation
655 * typically only contains content in one language.
657 * Be wary of this distinction: If you use wfMsg() where you should
658 * use wfMsgForContent(), a user of the software may have to
659 * customize potentially hundreds of messages in
660 * order to, e.g., fix a link in every possible language.
662 * @param $key String: lookup key for the message, usually
663 * defined in languages/Language.php
665 function wfMsgForContent( $key ) {
666 global $wgForceUIMsgAsContentMsg;
667 $args = func_get_args();
668 array_shift( $args );
670 if( is_array( $wgForceUIMsgAsContentMsg ) &&
671 in_array( $key, $wgForceUIMsgAsContentMsg ) )
675 return wfMsgReal( $key, $args, true, $forcontent );
679 * Same as above except doesn't transform the message
681 function wfMsgForContentNoTrans( $key ) {
682 global $wgForceUIMsgAsContentMsg;
683 $args = func_get_args();
684 array_shift( $args );
686 if( is_array( $wgForceUIMsgAsContentMsg ) &&
687 in_array( $key, $wgForceUIMsgAsContentMsg ) )
691 return wfMsgReal( $key, $args, true, $forcontent, false );
695 * Get a message from the language file, for the UI elements
697 function wfMsgNoDB( $key ) {
698 $args = func_get_args();
699 array_shift( $args );
700 return wfMsgReal( $key, $args, false );
704 * Get a message from the language file, for the content
706 function wfMsgNoDBForContent( $key ) {
707 global $wgForceUIMsgAsContentMsg;
708 $args = func_get_args();
709 array_shift( $args );
711 if( is_array( $wgForceUIMsgAsContentMsg ) &&
712 in_array( $key, $wgForceUIMsgAsContentMsg ) )
716 return wfMsgReal( $key, $args, false, $forcontent );
721 * Really get a message
722 * @param $key String: key to get.
724 * @param $useDB Boolean
725 * @param $forContent Mixed: Language code, or false for user lang, true for content lang.
726 * @param $transform Boolean: Whether or not to transform the message.
727 * @return String: the requested message.
729 function wfMsgReal( $key, $args, $useDB = true, $forContent = false, $transform = true ) {
730 wfProfileIn( __METHOD__
);
731 $message = wfMsgGetKey( $key, $useDB, $forContent, $transform );
732 $message = wfMsgReplaceArgs( $message, $args );
733 wfProfileOut( __METHOD__
);
738 * This function provides the message source for messages to be edited which are *not* stored in the database.
739 * @param $key String:
741 function wfMsgWeirdKey( $key ) {
742 $source = wfMsgGetKey( $key, false, true, false );
743 if ( wfEmptyMsg( $key, $source ) ) {
751 * Fetch a message string value, but don't replace any keys yet.
754 * @param $langCode String: Code of the language to get the message for, or
755 * behaves as a content language switch if it is a boolean.
756 * @param $transform Boolean: whether to parse magic words, etc.
759 function wfMsgGetKey( $key, $useDB, $langCode = false, $transform = true ) {
760 global $wgMessageCache;
762 wfRunHooks( 'NormalizeMessageKey', array( &$key, &$useDB, &$langCode, &$transform ) );
764 if ( !is_object( $wgMessageCache ) ) {
765 throw new MWException( 'Trying to get message before message cache is initialised' );
768 $message = $wgMessageCache->get( $key, $useDB, $langCode );
769 if( $message === false ) {
770 $message = '<' . htmlspecialchars( $key ) . '>';
771 } elseif ( $transform ) {
772 $message = $wgMessageCache->transform( $message );
778 * Replace message parameter keys on the given formatted output.
780 * @param $message String
785 function wfMsgReplaceArgs( $message, $args ) {
786 # Fix windows line-endings
787 # Some messages are split with explode("\n", $msg)
788 $message = str_replace( "\r", '', $message );
791 if ( count( $args ) ) {
792 if ( is_array( $args[0] ) ) {
793 $args = array_values( $args[0] );
795 $replacementKeys = array();
796 foreach( $args as $n => $param ) {
797 $replacementKeys['$' . ( $n +
1 )] = $param;
799 $message = strtr( $message, $replacementKeys );
806 * Return an HTML-escaped version of a message.
807 * Parameter replacements, if any, are done *after* the HTML-escaping,
808 * so parameters may contain HTML (eg links or form controls). Be sure
809 * to pre-escape them if you really do want plaintext, or just wrap
810 * the whole thing in htmlspecialchars().
813 * @param string ... parameters
816 function wfMsgHtml( $key ) {
817 $args = func_get_args();
818 array_shift( $args );
819 return wfMsgReplaceArgs( htmlspecialchars( wfMsgGetKey( $key, true ) ), $args );
823 * Return an HTML version of message
824 * Parameter replacements, if any, are done *after* parsing the wiki-text message,
825 * so parameters may contain HTML (eg links or form controls). Be sure
826 * to pre-escape them if you really do want plaintext, or just wrap
827 * the whole thing in htmlspecialchars().
830 * @param string ... parameters
833 function wfMsgWikiHtml( $key ) {
835 $args = func_get_args();
836 array_shift( $args );
837 return wfMsgReplaceArgs( $wgOut->parse( wfMsgGetKey( $key, true ), /* can't be set to false */ true ), $args );
841 * Returns message in the requested format
842 * @param $key String: key of the message
843 * @param $options Array: processing rules. Can take the following options:
844 * <i>parse</i>: parses wikitext to HTML
845 * <i>parseinline</i>: parses wikitext to HTML and removes the surrounding
846 * p's added by parser or tidy
847 * <i>escape</i>: filters message through htmlspecialchars
848 * <i>escapenoentities</i>: same, but allows entity references like   through
849 * <i>replaceafter</i>: parameters are substituted after parsing or escaping
850 * <i>parsemag</i>: transform the message using magic phrases
851 * <i>content</i>: fetch message for content language instead of interface
852 * Also can accept a single associative argument, of the form 'language' => 'xx':
853 * <i>language</i>: Language object or language code to fetch message for
854 * (overriden by <i>content</i>), its behaviour with parser, parseinline
855 * and parsemag is undefined.
856 * Behavior for conflicting options (e.g., parse+parseinline) is undefined.
858 function wfMsgExt( $key, $options ) {
861 $args = func_get_args();
862 array_shift( $args );
863 array_shift( $args );
864 $options = (array)$options;
866 foreach( $options as $arrayKey => $option ) {
867 if( !preg_match( '/^[0-9]+|language$/', $arrayKey ) ) {
868 # An unknown index, neither numeric nor "language"
869 wfWarn( "wfMsgExt called with incorrect parameter key $arrayKey", 1, E_USER_WARNING
);
870 } elseif( preg_match( '/^[0-9]+$/', $arrayKey ) && !in_array( $option,
871 array( 'parse', 'parseinline', 'escape', 'escapenoentities',
872 'replaceafter', 'parsemag', 'content' ) ) ) {
873 # A numeric index with unknown value
874 wfWarn( "wfMsgExt called with incorrect parameter $option", 1, E_USER_WARNING
);
878 if( in_array( 'content', $options, true ) ) {
881 } elseif( array_key_exists( 'language', $options ) ) {
883 $langCode = wfGetLangObj( $options['language'] );
889 $string = wfMsgGetKey( $key, /*DB*/true, $langCode, /*Transform*/false );
891 if( !in_array( 'replaceafter', $options, true ) ) {
892 $string = wfMsgReplaceArgs( $string, $args );
895 if( in_array( 'parse', $options, true ) ) {
896 $string = $wgOut->parse( $string, true, !$forContent );
897 } elseif ( in_array( 'parseinline', $options, true ) ) {
898 $string = $wgOut->parse( $string, true, !$forContent );
900 if( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $string, $m ) ) {
903 } elseif ( in_array( 'parsemag', $options, true ) ) {
904 global $wgMessageCache;
905 if ( isset( $wgMessageCache ) ) {
906 $string = $wgMessageCache->transform( $string,
908 is_object( $langCode ) ?
$langCode : null );
912 if ( in_array( 'escape', $options, true ) ) {
913 $string = htmlspecialchars ( $string );
914 } elseif ( in_array( 'escapenoentities', $options, true ) ) {
915 $string = Sanitizer
::escapeHtmlAllowEntities( $string );
918 if( in_array( 'replaceafter', $options, true ) ) {
919 $string = wfMsgReplaceArgs( $string, $args );
927 * Just like exit() but makes a note of it.
928 * Commits open transactions except if the error parameter is set
930 * @deprecated Please return control to the caller or throw an exception. Will
931 * be removed in 1.19.
933 function wfAbruptExit( $error = false ) {
934 static $called = false;
940 wfDeprecated( __FUNCTION__
);
941 $bt = wfDebugBacktrace();
943 for( $i = 0; $i < count( $bt ); $i++
) {
944 $file = isset( $bt[$i]['file'] ) ?
$bt[$i]['file'] : 'unknown';
945 $line = isset( $bt[$i]['line'] ) ?
$bt[$i]['line'] : 'unknown';
946 wfDebug( "WARNING: Abrupt exit in $file at line $line\n");
949 wfDebug( "WARNING: Abrupt exit\n" );
952 wfLogProfilingData();
955 wfGetLB()->closeAll();
961 * @deprecated Please return control the caller or throw an exception. Will
962 * be removed in 1.19.
964 function wfErrorExit() {
965 wfDeprecated( __FUNCTION__
);
966 wfAbruptExit( true );
970 * Print a simple message and die, returning nonzero to the shell if any.
971 * Plain die() fails to return nonzero to the shell if you pass a string.
974 function wfDie( $msg = '' ) {
980 * Throw a debugging exception. This function previously once exited the process,
981 * but now throws an exception instead, with similar results.
983 * @param $msg String: message shown when dieing.
985 function wfDebugDieBacktrace( $msg = '' ) {
986 throw new MWException( $msg );
990 * Fetch server name for use in error reporting etc.
991 * Use real server name if available, so we know which machine
992 * in a server farm generated the current page.
995 function wfHostname() {
997 if ( is_null( $host ) ) {
998 if ( function_exists( 'posix_uname' ) ) {
999 // This function not present on Windows
1000 $uname = @posix_uname
();
1004 if( is_array( $uname ) && isset( $uname['nodename'] ) ) {
1005 $host = $uname['nodename'];
1006 } elseif ( getenv( 'COMPUTERNAME' ) ) {
1007 # Windows computer name
1008 $host = getenv( 'COMPUTERNAME' );
1010 # This may be a virtual server.
1011 $host = $_SERVER['SERVER_NAME'];
1018 * Returns a HTML comment with the elapsed time since request.
1019 * This method has no side effects.
1022 function wfReportTime() {
1023 global $wgRequestTime, $wgShowHostnames;
1026 $elapsed = $now - $wgRequestTime;
1028 return $wgShowHostnames
1029 ?
sprintf( '<!-- Served by %s in %01.3f secs. -->', wfHostname(), $elapsed )
1030 : sprintf( '<!-- Served in %01.3f secs. -->', $elapsed );
1034 * Safety wrapper for debug_backtrace().
1036 * With Zend Optimizer 3.2.0 loaded, this causes segfaults under somewhat
1037 * murky circumstances, which may be triggered in part by stub objects
1038 * or other fancy talkin'.
1040 * Will return an empty array if Zend Optimizer is detected or if
1041 * debug_backtrace is disabled, otherwise the output from
1042 * debug_backtrace() (trimmed).
1044 * @return array of backtrace information
1046 function wfDebugBacktrace() {
1047 static $disabled = null;
1049 if( extension_loaded( 'Zend Optimizer' ) ) {
1050 wfDebug( "Zend Optimizer detected; skipping debug_backtrace for safety.\n" );
1054 if ( is_null( $disabled ) ) {
1056 $functions = explode( ',', ini_get( 'disable_functions' ) );
1057 $functions = array_map( 'trim', $functions );
1058 $functions = array_map( 'strtolower', $functions );
1059 if ( in_array( 'debug_backtrace', $functions ) ) {
1060 wfDebug( "debug_backtrace is in disabled_functions\n" );
1068 return array_slice( debug_backtrace(), 1 );
1071 function wfBacktrace() {
1072 global $wgCommandLineMode;
1074 if ( $wgCommandLineMode ) {
1079 $backtrace = wfDebugBacktrace();
1080 foreach( $backtrace as $call ) {
1081 if( isset( $call['file'] ) ) {
1082 $f = explode( DIRECTORY_SEPARATOR
, $call['file'] );
1083 $file = $f[count( $f ) - 1];
1087 if( isset( $call['line'] ) ) {
1088 $line = $call['line'];
1092 if ( $wgCommandLineMode ) {
1093 $msg .= "$file line $line calls ";
1095 $msg .= '<li>' . $file . ' line ' . $line . ' calls ';
1097 if( !empty( $call['class'] ) ) {
1098 $msg .= $call['class'] . '::';
1100 $msg .= $call['function'] . '()';
1102 if ( $wgCommandLineMode ) {
1108 if ( $wgCommandLineMode ) {
1118 /* Some generic result counters, pulled out of SearchEngine */
1124 function wfShowingResults( $offset, $limit ) {
1128 array( 'parseinline' ),
1129 $wgLang->formatNum( $limit ),
1130 $wgLang->formatNum( $offset +
1 )
1137 function wfShowingResultsNum( $offset, $limit, $num ) {
1140 'showingresultsnum',
1141 array( 'parseinline' ),
1142 $wgLang->formatNum( $limit ),
1143 $wgLang->formatNum( $offset +
1 ),
1144 $wgLang->formatNum( $num )
1149 * Generate (prev x| next x) (20|50|100...) type links for paging
1150 * @param $offset String
1151 * @param $limit Integer
1152 * @param $link String
1153 * @param $query String: optional URL query parameter string
1154 * @param $atend Bool: optional param for specified if this is the last page
1156 function wfViewPrevNext( $offset, $limit, $link, $query = '', $atend = false ) {
1158 $fmtLimit = $wgLang->formatNum( $limit );
1159 // FIXME: Why on earth this needs one message for the text and another one for tooltip??
1160 # Get prev/next link display text
1161 $prev = wfMsgExt( 'prevn', array( 'parsemag', 'escape' ), $fmtLimit );
1162 $next = wfMsgExt( 'nextn', array( 'parsemag', 'escape' ), $fmtLimit );
1163 # Get prev/next link title text
1164 $pTitle = wfMsgExt( 'prevn-title', array( 'parsemag', 'escape' ), $fmtLimit );
1165 $nTitle = wfMsgExt( 'nextn-title', array( 'parsemag', 'escape' ), $fmtLimit );
1166 # Fetch the title object
1167 if( is_object( $link ) ) {
1170 $title = Title
::newFromText( $link );
1171 if( is_null( $title ) ) {
1175 # Make 'previous' link
1176 if( 0 != $offset ) {
1177 $po = $offset - $limit;
1178 $po = max( $po, 0 );
1179 $q = "limit={$limit}&offset={$po}";
1180 if( $query != '' ) {
1183 $plink = '<a href="' . $title->escapeLocalURL( $q ) . "\" title=\"{$pTitle}\" class=\"mw-prevlink\">{$prev}</a>";
1188 $no = $offset +
$limit;
1189 $q = "limit={$limit}&offset={$no}";
1190 if( $query != '' ) {
1196 $nlink = '<a href="' . $title->escapeLocalURL( $q ) . "\" title=\"{$nTitle}\" class=\"mw-nextlink\">{$next}</a>";
1198 # Make links to set number of items per page
1199 $nums = $wgLang->pipeList( array(
1200 wfNumLink( $offset, 20, $title, $query ),
1201 wfNumLink( $offset, 50, $title, $query ),
1202 wfNumLink( $offset, 100, $title, $query ),
1203 wfNumLink( $offset, 250, $title, $query ),
1204 wfNumLink( $offset, 500, $title, $query )
1206 return wfMsgHtml( 'viewprevnext', $plink, $nlink, $nums );
1210 * Generate links for (20|50|100...) items-per-page links
1211 * @param $offset String
1212 * @param $limit Integer
1213 * @param $title Title
1214 * @param $query String: optional URL query parameter string
1216 function wfNumLink( $offset, $limit, $title, $query = '' ) {
1218 if( $query == '' ) {
1223 $q .= "limit={$limit}&offset={$offset}";
1224 $fmtLimit = $wgLang->formatNum( $limit );
1225 $lTitle = wfMsgExt( 'shown-title', array( 'parsemag', 'escape' ), $limit );
1226 $s = '<a href="' . $title->escapeLocalURL( $q ) . "\" title=\"{$lTitle}\" class=\"mw-numlink\">{$fmtLimit}</a>";
1232 * @todo FIXME: we may want to blacklist some broken browsers
1234 * @return bool Whereas client accept gzip compression
1236 function wfClientAcceptsGzip() {
1237 if( isset( $_SERVER['HTTP_ACCEPT_ENCODING'] ) ) {
1238 # FIXME: we may want to blacklist some broken browsers
1241 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
1242 $_SERVER['HTTP_ACCEPT_ENCODING'],
1246 if( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) {
1249 wfDebug( " accepts gzip\n" );
1257 * Obtain the offset and limit values from the request string;
1258 * used in special pages
1260 * @param $deflimit Default limit if none supplied
1261 * @param $optionname Name of a user preference to check against
1265 function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) {
1267 return $wgRequest->getLimitOffset( $deflimit, $optionname );
1271 * Escapes the given text so that it may be output using addWikiText()
1272 * without any linking, formatting, etc. making its way through. This
1273 * is achieved by substituting certain characters with HTML entities.
1274 * As required by the callers, <nowiki> is not used. It currently does
1275 * not filter out characters which have special meaning only at the
1276 * start of a line, such as "*".
1278 * @param $text String: text to be escaped
1280 function wfEscapeWikiText( $text ) {
1281 $text = str_replace(
1282 array( '[', '|', ']', '\'', 'ISBN ', 'RFC ', '://', "\n=", '{{' ), # }}
1283 array( '[', '|', ']', ''', 'ISBN ', 'RFC ', '://', "\n=", '{{' ),
1284 htmlspecialchars( $text )
1292 function wfQuotedPrintable( $string, $charset = '' ) {
1293 # Probably incomplete; see RFC 2045
1294 if( empty( $charset ) ) {
1295 global $wgInputEncoding;
1296 $charset = $wgInputEncoding;
1298 $charset = strtoupper( $charset );
1299 $charset = str_replace( 'ISO-8859', 'ISO8859', $charset ); // ?
1301 $illegal = '\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\xff=';
1302 $replace = $illegal . '\t ?_';
1303 if( !preg_match( "/[$illegal]/", $string ) ) {
1306 $out = "=?$charset?Q?";
1307 $out .= preg_replace( "/([$replace])/e", 'sprintf("=%02X",ord("$1"))', $string );
1318 return microtime( true );
1322 * Sets dest to source and returns the original value of dest
1323 * If source is NULL, it just returns the value, it doesn't set the variable
1325 function wfSetVar( &$dest, $source ) {
1327 if ( !is_null( $source ) ) {
1334 * As for wfSetVar except setting a bit
1336 function wfSetBit( &$dest, $bit, $state = true ) {
1337 $temp = (bool)( $dest & $bit );
1338 if ( !is_null( $state ) ) {
1349 * This function takes two arrays as input, and returns a CGI-style string, e.g.
1350 * "days=7&limit=100". Options in the first array override options in the second.
1351 * Options set to "" will not be output.
1353 function wfArrayToCGI( $array1, $array2 = null ) {
1354 if ( !is_null( $array2 ) ) {
1355 $array1 = $array1 +
$array2;
1359 foreach ( $array1 as $key => $value ) {
1360 if ( $value !== '' ) {
1364 if ( is_array( $value ) ) {
1366 foreach ( $value as $v ) {
1367 $cgi .= ( $firstTime ?
'' : '&') .
1368 urlencode( $key . '[]' ) . '=' .
1373 if ( is_object( $value ) ) {
1374 $value = $value->__toString();
1376 $cgi .= urlencode( $key ) . '=' .
1377 urlencode( $value );
1385 * This is the logical opposite of wfArrayToCGI(): it accepts a query string as
1386 * its argument and returns the same string in array form. This allows compa-
1387 * tibility with legacy functions that accept raw query strings instead of nice
1388 * arrays. Of course, keys and values are urldecode()d. Don't try passing in-
1389 * valid query strings, or it will explode.
1391 * @param $query String: query string
1392 * @return array Array version of input
1394 function wfCgiToArray( $query ) {
1395 if( isset( $query[0] ) && $query[0] == '?' ) {
1396 $query = substr( $query, 1 );
1398 $bits = explode( '&', $query );
1400 foreach( $bits as $bit ) {
1404 list( $key, $value ) = explode( '=', $bit );
1405 $key = urldecode( $key );
1406 $value = urldecode( $value );
1407 $ret[$key] = $value;
1413 * Append a query string to an existing URL, which may or may not already
1414 * have query string parameters already. If so, they will be combined.
1416 * @param $url String
1417 * @param $query Mixed: string or associative array
1420 function wfAppendQuery( $url, $query ) {
1421 if ( is_array( $query ) ) {
1422 $query = wfArrayToCGI( $query );
1424 if( $query != '' ) {
1425 if( false === strpos( $url, '?' ) ) {
1436 * Expand a potentially local URL to a fully-qualified URL. Assumes $wgServer
1437 * and $wgProto are correct.
1439 * @todo this won't work with current-path-relative URLs
1440 * like "subdir/foo.html", etc.
1442 * @param $url String: either fully-qualified or a local path + query
1443 * @return string Fully-qualified URL
1445 function wfExpandUrl( $url ) {
1446 if( substr( $url, 0, 2 ) == '//' ) {
1448 return $wgProto . ':' . $url;
1449 } elseif( substr( $url, 0, 1 ) == '/' ) {
1451 return $wgServer . $url;
1458 * Windows-compatible version of escapeshellarg()
1459 * Windows doesn't recognise single-quotes in the shell, but the escapeshellarg()
1460 * function puts single quotes in regardless of OS.
1462 * Also fixes the locale problems on Linux in PHP 5.2.6+ (bug backported to
1463 * earlier distro releases of PHP)
1465 function wfEscapeShellArg( ) {
1466 wfInitShellLocale();
1468 $args = func_get_args();
1471 foreach ( $args as $arg ) {
1478 if ( wfIsWindows() ) {
1479 // Escaping for an MSVC-style command line parser
1480 // Ref: http://mailman.lyra.org/pipermail/scite-interest/2002-March/000436.html
1481 // Double the backslashes before any double quotes. Escape the double quotes.
1482 $tokens = preg_split( '/(\\\\*")/', $arg, -1, PREG_SPLIT_DELIM_CAPTURE
);
1485 foreach ( $tokens as $token ) {
1486 if ( $iteration %
2 == 1 ) {
1487 // Delimiter, a double quote preceded by zero or more slashes
1488 $arg .= str_replace( '\\', '\\\\', substr( $token, 0, -1 ) ) . '\\"';
1489 } elseif ( $iteration %
4 == 2 ) {
1490 // ^ in $token will be outside quotes, need to be escaped
1491 $arg .= str_replace( '^', '^^', $token );
1492 } else { // $iteration % 4 == 0
1493 // ^ in $token will appear inside double quotes, so leave as is
1498 // Double the backslashes before the end of the string, because
1499 // we will soon add a quote
1501 if ( preg_match( '/^(.*?)(\\\\+)$/', $arg, $m ) ) {
1502 $arg = $m[1] . str_replace( '\\', '\\\\', $m[2] );
1505 // Add surrounding quotes
1506 $retVal .= '"' . $arg . '"';
1508 $retVal .= escapeshellarg( $arg );
1515 * wfMerge attempts to merge differences between three texts.
1516 * Returns true for a clean merge and false for failure or a conflict.
1518 function wfMerge( $old, $mine, $yours, &$result ) {
1521 # This check may also protect against code injection in
1522 # case of broken installations.
1523 wfSuppressWarnings();
1524 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
1525 wfRestoreWarnings();
1528 wfDebug( "diff3 not found\n" );
1532 # Make temporary files
1534 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
1535 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
1536 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
1538 fwrite( $oldtextFile, $old );
1539 fclose( $oldtextFile );
1540 fwrite( $mytextFile, $mine );
1541 fclose( $mytextFile );
1542 fwrite( $yourtextFile, $yours );
1543 fclose( $yourtextFile );
1545 # Check for a conflict
1546 $cmd = $wgDiff3 . ' -a --overlap-only ' .
1547 wfEscapeShellArg( $mytextName ) . ' ' .
1548 wfEscapeShellArg( $oldtextName ) . ' ' .
1549 wfEscapeShellArg( $yourtextName );
1550 $handle = popen( $cmd, 'r' );
1552 if( fgets( $handle, 1024 ) ) {
1560 $cmd = $wgDiff3 . ' -a -e --merge ' .
1561 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
1562 $handle = popen( $cmd, 'r' );
1565 $data = fread( $handle, 8192 );
1566 if ( strlen( $data ) == 0 ) {
1572 unlink( $mytextName );
1573 unlink( $oldtextName );
1574 unlink( $yourtextName );
1576 if ( $result === '' && $old !== '' && !$conflict ) {
1577 wfDebug( "Unexpected null result from diff3. Command: $cmd\n" );
1584 * Returns unified plain-text diff of two texts.
1585 * Useful for machine processing of diffs.
1586 * @param $before String: the text before the changes.
1587 * @param $after String: the text after the changes.
1588 * @param $params String: command-line options for the diff command.
1589 * @return String: unified diff of $before and $after
1591 function wfDiff( $before, $after, $params = '-u' ) {
1592 if ( $before == $after ) {
1597 wfSuppressWarnings();
1598 $haveDiff = $wgDiff && file_exists( $wgDiff );
1599 wfRestoreWarnings();
1601 # This check may also protect against code injection in
1602 # case of broken installations.
1604 wfDebug( "diff executable not found\n" );
1605 $diffs = new Diff( explode( "\n", $before ), explode( "\n", $after ) );
1606 $format = new UnifiedDiffFormatter();
1607 return $format->format( $diffs );
1610 # Make temporary files
1612 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
1613 $newtextFile = fopen( $newtextName = tempnam( $td, 'merge-your-' ), 'w' );
1615 fwrite( $oldtextFile, $before );
1616 fclose( $oldtextFile );
1617 fwrite( $newtextFile, $after );
1618 fclose( $newtextFile );
1620 // Get the diff of the two files
1621 $cmd = "$wgDiff " . $params . ' ' . wfEscapeShellArg( $oldtextName, $newtextName );
1623 $h = popen( $cmd, 'r' );
1628 $data = fread( $h, 8192 );
1629 if ( strlen( $data ) == 0 ) {
1637 unlink( $oldtextName );
1638 unlink( $newtextName );
1640 // Kill the --- and +++ lines. They're not useful.
1641 $diff_lines = explode( "\n", $diff );
1642 if ( strpos( $diff_lines[0], '---' ) === 0 ) {
1643 unset( $diff_lines[0] );
1645 if ( strpos( $diff_lines[1], '+++' ) === 0 ) {
1646 unset( $diff_lines[1] );
1649 $diff = implode( "\n", $diff_lines );
1655 * A wrapper around the PHP function var_export().
1656 * Either print it or add it to the regular output ($wgOut).
1658 * @param $var A PHP variable to dump.
1660 function wfVarDump( $var ) {
1662 $s = str_replace( "\n", "<br />\n", var_export( $var, true ) . "\n" );
1663 if ( headers_sent() ||
!@is_object
( $wgOut ) ) {
1666 $wgOut->addHTML( $s );
1671 * Provide a simple HTTP error.
1673 function wfHttpError( $code, $label, $desc ) {
1676 header( "HTTP/1.0 $code $label" );
1677 header( "Status: $code $label" );
1678 $wgOut->sendCacheControl();
1680 header( 'Content-type: text/html; charset=utf-8' );
1681 print "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">".
1682 '<html><head><title>' .
1683 htmlspecialchars( $label ) .
1684 '</title></head><body><h1>' .
1685 htmlspecialchars( $label ) .
1687 nl2br( htmlspecialchars( $desc ) ) .
1688 "</p></body></html>\n";
1692 * Clear away any user-level output buffers, discarding contents.
1694 * Suitable for 'starting afresh', for instance when streaming
1695 * relatively large amounts of data without buffering, or wanting to
1696 * output image files without ob_gzhandler's compression.
1698 * The optional $resetGzipEncoding parameter controls suppression of
1699 * the Content-Encoding header sent by ob_gzhandler; by default it
1700 * is left. See comments for wfClearOutputBuffers() for why it would
1703 * Note that some PHP configuration options may add output buffer
1704 * layers which cannot be removed; these are left in place.
1706 * @param $resetGzipEncoding Bool
1708 function wfResetOutputBuffers( $resetGzipEncoding = true ) {
1709 if( $resetGzipEncoding ) {
1710 // Suppress Content-Encoding and Content-Length
1711 // headers from 1.10+s wfOutputHandler
1712 global $wgDisableOutputCompression;
1713 $wgDisableOutputCompression = true;
1715 while( $status = ob_get_status() ) {
1716 if( $status['type'] == 0 /* PHP_OUTPUT_HANDLER_INTERNAL */ ) {
1717 // Probably from zlib.output_compression or other
1718 // PHP-internal setting which can't be removed.
1720 // Give up, and hope the result doesn't break
1724 if( !ob_end_clean() ) {
1725 // Could not remove output buffer handler; abort now
1726 // to avoid getting in some kind of infinite loop.
1729 if( $resetGzipEncoding ) {
1730 if( $status['name'] == 'ob_gzhandler' ) {
1731 // Reset the 'Content-Encoding' field set by this handler
1732 // so we can start fresh.
1733 header( 'Content-Encoding:' );
1741 * More legible than passing a 'false' parameter to wfResetOutputBuffers():
1743 * Clear away output buffers, but keep the Content-Encoding header
1744 * produced by ob_gzhandler, if any.
1746 * This should be used for HTTP 304 responses, where you need to
1747 * preserve the Content-Encoding header of the real result, but
1748 * also need to suppress the output of ob_gzhandler to keep to spec
1749 * and avoid breaking Firefox in rare cases where the headers and
1750 * body are broken over two packets.
1752 function wfClearOutputBuffers() {
1753 wfResetOutputBuffers( false );
1757 * Converts an Accept-* header into an array mapping string values to quality
1760 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
1761 # No arg means accept anything (per HTTP spec)
1763 return array( $def => 1.0 );
1768 $parts = explode( ',', $accept );
1770 foreach( $parts as $part ) {
1771 # FIXME: doesn't deal with params like 'text/html; level=1'
1772 @list
( $value, $qpart ) = explode( ';', trim( $part ) );
1774 if( !isset( $qpart ) ) {
1775 $prefs[$value] = 1.0;
1776 } elseif( preg_match( '/q\s*=\s*(\d*\.\d+)/', $qpart, $match ) ) {
1777 $prefs[$value] = floatval( $match[1] );
1785 * Checks if a given MIME type matches any of the keys in the given
1786 * array. Basic wildcards are accepted in the array keys.
1788 * Returns the matching MIME type (or wildcard) if a match, otherwise
1791 * @param $type String
1792 * @param $avail Array
1796 function mimeTypeMatch( $type, $avail ) {
1797 if( array_key_exists( $type, $avail ) ) {
1800 $parts = explode( '/', $type );
1801 if( array_key_exists( $parts[0] . '/*', $avail ) ) {
1802 return $parts[0] . '/*';
1803 } elseif( array_key_exists( '*/*', $avail ) ) {
1812 * Returns the 'best' match between a client's requested internet media types
1813 * and the server's list of available types. Each list should be an associative
1814 * array of type to preference (preference is a float between 0.0 and 1.0).
1815 * Wildcards in the types are acceptable.
1817 * @param $cprefs Array: client's acceptable type list
1818 * @param $sprefs Array: server's offered types
1821 * @todo FIXME: doesn't handle params like 'text/plain; charset=UTF-8'
1822 * XXX: generalize to negotiate other stuff
1824 function wfNegotiateType( $cprefs, $sprefs ) {
1827 foreach( array_keys($sprefs) as $type ) {
1828 $parts = explode( '/', $type );
1829 if( $parts[1] != '*' ) {
1830 $ckey = mimeTypeMatch( $type, $cprefs );
1832 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1837 foreach( array_keys( $cprefs ) as $type ) {
1838 $parts = explode( '/', $type );
1839 if( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
1840 $skey = mimeTypeMatch( $type, $sprefs );
1842 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1850 foreach( array_keys( $combine ) as $type ) {
1851 if( $combine[$type] > $bestq ) {
1853 $bestq = $combine[$type];
1862 * Returns an array where the values in the first array are replaced by the
1863 * values in the second array with the corresponding keys
1867 function wfArrayLookup( $a, $b ) {
1868 return array_flip( array_intersect( array_flip( $a ), array_keys( $b ) ) );
1872 * Convenience function; returns MediaWiki timestamp for the present time.
1875 function wfTimestampNow() {
1877 return wfTimestamp( TS_MW
, time() );
1881 * Reference-counted warning suppression
1883 function wfSuppressWarnings( $end = false ) {
1884 static $suppressCount = 0;
1885 static $originalLevel = false;
1888 if ( $suppressCount ) {
1890 if ( !$suppressCount ) {
1891 error_reporting( $originalLevel );
1895 if ( !$suppressCount ) {
1896 $originalLevel = error_reporting( E_ALL
& ~
( E_WARNING | E_NOTICE | E_USER_WARNING | E_USER_NOTICE
) );
1903 * Restore error level to previous value
1905 function wfRestoreWarnings() {
1906 wfSuppressWarnings( true );
1909 # Autodetect, convert and provide timestamps of various types
1912 * Unix time - the number of seconds since 1970-01-01 00:00:00 UTC
1914 define( 'TS_UNIX', 0 );
1917 * MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
1919 define( 'TS_MW', 1 );
1922 * MySQL DATETIME (YYYY-MM-DD HH:MM:SS)
1924 define( 'TS_DB', 2 );
1927 * RFC 2822 format, for E-mail and HTTP headers
1929 define( 'TS_RFC2822', 3 );
1932 * ISO 8601 format with no timezone: 1986-02-09T20:00:00Z
1934 * This is used by Special:Export
1936 define( 'TS_ISO_8601', 4 );
1939 * An Exif timestamp (YYYY:MM:DD HH:MM:SS)
1941 * @see http://exif.org/Exif2-2.PDF The Exif 2.2 spec, see page 28 for the
1942 * DateTime tag and page 36 for the DateTimeOriginal and
1943 * DateTimeDigitized tags.
1945 define( 'TS_EXIF', 5 );
1948 * Oracle format time.
1950 define( 'TS_ORACLE', 6 );
1953 * Postgres format time.
1955 define( 'TS_POSTGRES', 7 );
1960 define( 'TS_DB2', 8 );
1963 * ISO 8601 basic format with no timezone: 19860209T200000Z
1965 * This is used by ResourceLoader
1967 define( 'TS_ISO_8601_BASIC', 9 );
1970 * @param $outputtype Mixed: A timestamp in one of the supported formats, the
1971 * function will autodetect which format is supplied and act
1973 * @param $ts Mixed: the timestamp to convert or 0 for the current timestamp
1974 * @return String: in the format specified in $outputtype
1976 function wfTimestamp( $outputtype = TS_UNIX
, $ts = 0 ) {
1981 } elseif ( preg_match( '/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)$/D', $ts, $da ) ) {
1983 } elseif ( preg_match( '/^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/D', $ts, $da ) ) {
1985 } elseif ( preg_match( '/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/D', $ts, $da ) ) {
1987 } elseif ( preg_match( '/^-?\d{1,13}$/D', $ts ) ) {
1990 } elseif ( preg_match( '/^\d{2}-\d{2}-\d{4} \d{2}:\d{2}:\d{2}.\d{6}$/', $ts ) ) {
1991 # TS_ORACLE // session altered to DD-MM-YYYY HH24:MI:SS.FF6
1992 $uts = strtotime( preg_replace( '/(\d\d)\.(\d\d)\.(\d\d)(\.(\d+))?/', "$1:$2:$3",
1993 str_replace( '+00:00', 'UTC', $ts ) ) );
1994 } elseif ( preg_match( '/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.*\d*)?Z$/', $ts, $da ) ) {
1996 } elseif ( preg_match( '/^(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})(?:\.*\d*)?Z$/', $ts, $da ) ) {
1998 } elseif ( preg_match( '/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.*\d*[\+\- ](\d\d)$/', $ts, $da ) ) {
2000 } elseif ( preg_match( '/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.*\d* GMT$/', $ts, $da ) ) {
2002 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.\d\d\d$/',$ts,$da)) {
2004 } elseif ( preg_match( '/^[A-Z][a-z]{2}, \d\d [A-Z][a-z]{2} \d{4} \d\d:\d\d:\d\d/', $ts ) ) {
2006 $uts = strtotime( $ts );
2008 # Bogus value; fall back to the epoch...
2009 wfDebug("wfTimestamp() fed bogus time value: $outputtype; $ts\n");
2013 if (count( $da ) ) {
2014 // Warning! gmmktime() acts oddly if the month or day is set to 0
2015 // We may want to handle that explicitly at some point
2016 $uts = gmmktime( (int)$da[4], (int)$da[5], (int)$da[6],
2017 (int)$da[2], (int)$da[3], (int)$da[1] );
2020 switch( $outputtype ) {
2024 return gmdate( 'YmdHis', $uts );
2026 return gmdate( 'Y-m-d H:i:s', $uts );
2028 return gmdate( 'Y-m-d\TH:i:s\Z', $uts );
2029 case TS_ISO_8601_BASIC
:
2030 return gmdate( 'Ymd\THis\Z', $uts );
2031 // This shouldn't ever be used, but is included for completeness
2033 return gmdate( 'Y:m:d H:i:s', $uts );
2035 return gmdate( 'D, d M Y H:i:s', $uts ) . ' GMT';
2037 return gmdate( 'd-m-Y H:i:s.000000', $uts );
2038 //return gmdate( 'd-M-y h.i.s A', $uts ) . ' +00:00';
2040 return gmdate( 'Y-m-d H:i:s', $uts ) . ' GMT';
2042 return gmdate( 'Y-m-d H:i:s', $uts );
2044 throw new MWException( 'wfTimestamp() called with illegal output type.' );
2049 * Return a formatted timestamp, or null if input is null.
2050 * For dealing with nullable timestamp columns in the database.
2051 * @param $outputtype Integer
2055 function wfTimestampOrNull( $outputtype = TS_UNIX
, $ts = null ) {
2056 if( is_null( $ts ) ) {
2059 return wfTimestamp( $outputtype, $ts );
2064 * Check if the operating system is Windows
2066 * @return Bool: true if it's Windows, False otherwise.
2068 function wfIsWindows() {
2069 static $isWindows = null;
2070 if ( $isWindows === null ) {
2071 $isWindows = substr( php_uname(), 0, 7 ) == 'Windows';
2077 * Swap two variables
2079 function swap( &$x, &$y ) {
2085 function wfGetCachedNotice( $name ) {
2086 global $wgOut, $wgRenderHashAppend, $parserMemc;
2087 $fname = 'wfGetCachedNotice';
2088 wfProfileIn( $fname );
2092 if( $name === 'default' ) {
2094 global $wgSiteNotice;
2095 $notice = $wgSiteNotice;
2096 if( empty( $notice ) ) {
2097 wfProfileOut( $fname );
2101 $notice = wfMsgForContentNoTrans( $name );
2102 if( wfEmptyMsg( $name, $notice ) ||
$notice == '-' ) {
2103 wfProfileOut( $fname );
2108 // Use the extra hash appender to let eg SSL variants separately cache.
2109 $key = wfMemcKey( $name . $wgRenderHashAppend );
2110 $cachedNotice = $parserMemc->get( $key );
2111 if( is_array( $cachedNotice ) ) {
2112 if( md5( $notice ) == $cachedNotice['hash'] ) {
2113 $notice = $cachedNotice['html'];
2122 if( is_object( $wgOut ) ) {
2123 $parsed = $wgOut->parse( $notice );
2124 $parserMemc->set( $key, array( 'html' => $parsed, 'hash' => md5( $notice ) ), 600 );
2127 wfDebug( 'wfGetCachedNotice called for ' . $name . ' with no $wgOut available' . "\n" );
2131 $notice = '<div id="localNotice">' .$notice . '</div>';
2132 wfProfileOut( $fname );
2136 function wfGetNamespaceNotice() {
2140 if ( !isset( $wgTitle ) ||
!is_object( $wgTitle ) ) {
2144 $fname = 'wfGetNamespaceNotice';
2145 wfProfileIn( $fname );
2147 $key = 'namespacenotice-' . $wgTitle->getNsText();
2148 $namespaceNotice = wfGetCachedNotice( $key );
2149 if ( $namespaceNotice && substr( $namespaceNotice, 0, 7 ) != '<p><' ) {
2150 $namespaceNotice = '<div id="namespacebanner">' . $namespaceNotice . '</div>';
2152 $namespaceNotice = '';
2155 wfProfileOut( $fname );
2156 return $namespaceNotice;
2159 function wfGetSiteNotice() {
2161 $fname = 'wfGetSiteNotice';
2162 wfProfileIn( $fname );
2165 if( wfRunHooks( 'SiteNoticeBefore', array( &$siteNotice ) ) ) {
2166 if( is_object( $wgUser ) && $wgUser->isLoggedIn() ) {
2167 $siteNotice = wfGetCachedNotice( 'sitenotice' );
2169 $anonNotice = wfGetCachedNotice( 'anonnotice' );
2170 if( !$anonNotice ) {
2171 $siteNotice = wfGetCachedNotice( 'sitenotice' );
2173 $siteNotice = $anonNotice;
2176 if( !$siteNotice ) {
2177 $siteNotice = wfGetCachedNotice( 'default' );
2181 wfRunHooks( 'SiteNoticeAfter', array( &$siteNotice ) );
2182 wfProfileOut( $fname );
2187 * BC wrapper for MimeMagic::singleton()
2190 function &wfGetMimeMagic() {
2191 wfDeprecated( __FUNCTION__
);
2192 return MimeMagic
::singleton();
2196 * Tries to get the system directory for temporary files. The TMPDIR, TMP, and
2197 * TEMP environment variables are then checked in sequence, and if none are set
2198 * try sys_get_temp_dir() for PHP >= 5.2.1. All else fails, return /tmp for Unix
2199 * or C:\Windows\Temp for Windows and hope for the best.
2200 * It is common to call it with tempnam().
2202 * NOTE: When possible, use instead the tmpfile() function to create
2203 * temporary files to avoid race conditions on file creation, etc.
2207 function wfTempDir() {
2208 foreach( array( 'TMPDIR', 'TMP', 'TEMP' ) as $var ) {
2209 $tmp = getenv( $var );
2210 if( $tmp && file_exists( $tmp ) && is_dir( $tmp ) && is_writable( $tmp ) ) {
2214 if( function_exists( 'sys_get_temp_dir' ) ) {
2215 return sys_get_temp_dir();
2218 return wfIsWindows() ?
'C:\Windows\Temp' : '/tmp';
2222 * Make directory, and make all parent directories if they don't exist
2224 * @param $dir String: full path to directory to create
2225 * @param $mode Integer: chmod value to use, default is $wgDirectoryMode
2226 * @param $caller String: optional caller param for debugging.
2229 function wfMkdirParents( $dir, $mode = null, $caller = null ) {
2230 global $wgDirectoryMode;
2232 if ( !is_null( $caller ) ) {
2233 wfDebug( "$caller: called wfMkdirParents($dir)" );
2236 if( strval( $dir ) === '' ||
file_exists( $dir ) ) {
2240 $dir = str_replace( array( '\\', '/' ), DIRECTORY_SEPARATOR
, $dir );
2242 if ( is_null( $mode ) ) {
2243 $mode = $wgDirectoryMode;
2246 // Turn off the normal warning, we're doing our own below
2247 wfSuppressWarnings();
2248 $ok = mkdir( $dir, $mode, true ); // PHP5 <3
2249 wfRestoreWarnings();
2252 // PHP doesn't report the path in its warning message, so add our own to aid in diagnosis.
2253 trigger_error( __FUNCTION__
. ": failed to mkdir \"$dir\" mode $mode", E_USER_WARNING
);
2259 * Increment a statistics counter
2261 function wfIncrStats( $key ) {
2262 global $wgStatsMethod;
2264 if( $wgStatsMethod == 'udp' ) {
2265 global $wgUDPProfilerHost, $wgUDPProfilerPort, $wgDBname;
2268 $socket = socket_create( AF_INET
, SOCK_DGRAM
, SOL_UDP
);
2269 $statline = "stats/{$wgDBname} - 1 1 1 1 1 -total\n";
2273 strlen( $statline ),
2279 $statline = "stats/{$wgDBname} - 1 1 1 1 1 {$key}\n";
2280 wfSuppressWarnings();
2284 strlen( $statline ),
2289 wfRestoreWarnings();
2290 } elseif( $wgStatsMethod == 'cache' ) {
2292 $key = wfMemcKey( 'stats', $key );
2293 if ( is_null( $wgMemc->incr( $key ) ) ) {
2294 $wgMemc->add( $key, 1 );
2302 * @param $nr Mixed: the number to format
2303 * @param $acc Integer: the number of digits after the decimal point, default 2
2304 * @param $round Boolean: whether or not to round the value, default true
2307 function wfPercent( $nr, $acc = 2, $round = true ) {
2308 $ret = sprintf( "%.${acc}f", $nr );
2309 return $round ?
round( $ret, $acc ) . '%' : "$ret%";
2313 * Encrypt a username/password.
2315 * @param $userid Integer: ID of the user
2316 * @param $password String: password of the user
2317 * @return String: hashed password
2318 * @deprecated Use User::crypt() or User::oldCrypt() instead
2320 function wfEncryptPassword( $userid, $password ) {
2321 wfDeprecated(__FUNCTION__
);
2322 # Just wrap around User::oldCrypt()
2323 return User
::oldCrypt( $password, $userid );
2327 * Appends to second array if $value differs from that in $default
2329 function wfAppendToArrayIfNotDefault( $key, $value, $default, &$changed ) {
2330 if ( is_null( $changed ) ) {
2331 throw new MWException( 'GlobalFunctions::wfAppendToArrayIfNotDefault got null' );
2333 if ( $default[$key] !== $value ) {
2334 $changed[$key] = $value;
2339 * Since wfMsg() and co suck, they don't return false if the message key they
2340 * looked up didn't exist but a XHTML string, this function checks for the
2341 * nonexistance of messages by looking at wfMsg() output
2343 * @param $key String: the message key looked up
2344 * @return Boolean True if the message *doesn't* exist.
2346 function wfEmptyMsg( $key ) {
2347 global $wgMessageCache;
2348 return $wgMessageCache->get( $key, /*useDB*/true, /*content*/false ) === false;
2352 * Find out whether or not a mixed variable exists in a string
2354 * @param $needle String
2355 * @param $str String
2358 function in_string( $needle, $str ) {
2359 return strpos( $str, $needle ) !== false;
2362 function wfSpecialList( $page, $details ) {
2364 $details = $details ?
' ' . $wgContLang->getDirMark() . "($details)" : '';
2365 return $page . $details;
2369 * Returns a regular expression of url protocols
2373 function wfUrlProtocols() {
2374 global $wgUrlProtocols;
2376 static $retval = null;
2377 if ( !is_null( $retval ) ) {
2381 // Support old-style $wgUrlProtocols strings, for backwards compatibility
2382 // with LocalSettings files from 1.5
2383 if ( is_array( $wgUrlProtocols ) ) {
2384 $protocols = array();
2385 foreach ( $wgUrlProtocols as $protocol ) {
2386 $protocols[] = preg_quote( $protocol, '/' );
2389 $retval = implode( '|', $protocols );
2391 $retval = $wgUrlProtocols;
2397 * Safety wrapper around ini_get() for boolean settings.
2398 * The values returned from ini_get() are pre-normalized for settings
2399 * set via php.ini or php_flag/php_admin_flag... but *not*
2400 * for those set via php_value/php_admin_value.
2402 * It's fairly common for people to use php_value instead of php_flag,
2403 * which can leave you with an 'off' setting giving a false positive
2404 * for code that just takes the ini_get() return value as a boolean.
2406 * To make things extra interesting, setting via php_value accepts
2407 * "true" and "yes" as true, but php.ini and php_flag consider them false. :)
2408 * Unrecognized values go false... again opposite PHP's own coercion
2409 * from string to bool.
2411 * Luckily, 'properly' set settings will always come back as '0' or '1',
2412 * so we only have to worry about them and the 'improper' settings.
2414 * I frickin' hate PHP... :P
2416 * @param $setting String
2419 function wfIniGetBool( $setting ) {
2420 $val = ini_get( $setting );
2421 // 'on' and 'true' can't have whitespace around them, but '1' can.
2422 return strtolower( $val ) == 'on'
2423 ||
strtolower( $val ) == 'true'
2424 ||
strtolower( $val ) == 'yes'
2425 ||
preg_match( "/^\s*[+-]?0*[1-9]/", $val ); // approx C atoi() function
2429 * Wrapper function for PHP's dl(). This doesn't work in most situations from
2430 * PHP 5.3 onward, and is usually disabled in shared environments anyway.
2432 * @param $extension String A PHP extension. The file suffix (.so or .dll)
2434 * @return Bool - Whether or not the extension is loaded
2436 function wfDl( $extension ) {
2437 if( extension_loaded( $extension ) ) {
2441 $canDl = ( function_exists( 'dl' ) && is_callable( 'dl' )
2442 && wfIniGetBool( 'enable_dl' ) && !wfIniGetBool( 'safe_mode' ) );
2445 wfSuppressWarnings();
2446 dl( $extension . '.' . PHP_SHLIB_SUFFIX
);
2447 wfRestoreWarnings();
2449 return extension_loaded( $extension );
2453 * Execute a shell command, with time and memory limits mirrored from the PHP
2454 * configuration if supported.
2455 * @param $cmd String Command line, properly escaped for shell.
2456 * @param &$retval optional, will receive the program's exit code.
2457 * (non-zero is usually failure)
2458 * @param $environ Array optional environment variables which should be
2459 * added to the executed command environment.
2460 * @return collected stdout as a string (trailing newlines stripped)
2462 function wfShellExec( $cmd, &$retval = null, $environ = array() ) {
2463 global $IP, $wgMaxShellMemory, $wgMaxShellFileSize, $wgMaxShellTime;
2466 if ( is_null( $disabled ) ) {
2468 if( wfIniGetBool( 'safe_mode' ) ) {
2469 wfDebug( "wfShellExec can't run in safe_mode, PHP's exec functions are too broken.\n" );
2470 $disabled = 'safemode';
2472 $functions = explode( ',', ini_get( 'disable_functions' ) );
2473 $functions = array_map( 'trim', $functions );
2474 $functions = array_map( 'strtolower', $functions );
2475 if ( in_array( 'passthru', $functions ) ) {
2476 wfDebug( "passthru is in disabled_functions\n" );
2477 $disabled = 'passthru';
2483 return $disabled == 'safemode' ?
2484 'Unable to run external programs in safe mode.' :
2485 'Unable to run external programs, passthru() is disabled.';
2488 wfInitShellLocale();
2491 foreach( $environ as $k => $v ) {
2492 if ( wfIsWindows() ) {
2493 /* Surrounding a set in quotes (method used by wfEscapeShellArg) makes the quotes themselves
2494 * appear in the environment variable, so we must use carat escaping as documented in
2495 * http://technet.microsoft.com/en-us/library/cc723564.aspx
2496 * Note however that the quote isn't listed there, but is needed, and the parentheses
2497 * are listed there but doesn't appear to need it.
2499 $envcmd .= "set $k=" . preg_replace( '/([&|()<>^"])/', '^\\1', $v ) . ' && ';
2501 /* Assume this is a POSIX shell, thus required to accept variable assignments before the command
2502 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_09_01
2504 $envcmd .= "$k=" . escapeshellarg( $v ) . ' ';
2507 $cmd = $envcmd . $cmd;
2509 if ( wfIsWindows() ) {
2510 if ( version_compare( PHP_VERSION
, '5.3.0', '<' ) && /* Fixed in 5.3.0 :) */
2511 ( version_compare( PHP_VERSION
, '5.2.1', '>=' ) ||
php_uname( 's' ) == 'Windows NT' ) )
2513 # Hack to work around PHP's flawed invocation of cmd.exe
2514 # http://news.php.net/php.internals/21796
2515 # Windows 9x doesn't accept any kind of quotes
2516 $cmd = '"' . $cmd . '"';
2518 } elseif ( php_uname( 's' ) == 'Linux' ) {
2519 $time = intval( $wgMaxShellTime );
2520 $mem = intval( $wgMaxShellMemory );
2521 $filesize = intval( $wgMaxShellFileSize );
2523 if ( $time > 0 && $mem > 0 ) {
2524 $script = "$IP/bin/ulimit4.sh";
2525 if ( is_executable( $script ) ) {
2526 $cmd = '/bin/bash ' . escapeshellarg( $script ) . " $time $mem $filesize " . escapeshellarg( $cmd );
2530 wfDebug( "wfShellExec: $cmd\n" );
2532 $retval = 1; // error by default?
2534 passthru( $cmd, $retval );
2535 $output = ob_get_contents();
2538 if ( $retval == 127 ) {
2539 wfDebugLog( 'exec', "Possibly missing executable file: $cmd\n" );
2545 * Workaround for http://bugs.php.net/bug.php?id=45132
2546 * escapeshellarg() destroys non-ASCII characters if LANG is not a UTF-8 locale
2548 function wfInitShellLocale() {
2549 static $done = false;
2554 global $wgShellLocale;
2555 if ( !wfIniGetBool( 'safe_mode' ) ) {
2556 putenv( "LC_CTYPE=$wgShellLocale" );
2557 setlocale( LC_CTYPE
, $wgShellLocale );
2562 * This function works like "use VERSION" in Perl, the program will die with a
2563 * backtrace if the current version of PHP is less than the version provided
2565 * This is useful for extensions which due to their nature are not kept in sync
2566 * with releases, and might depend on other versions of PHP than the main code
2568 * Note: PHP might die due to parsing errors in some cases before it ever
2569 * manages to call this function, such is life
2571 * @see perldoc -f use
2573 * @param $req_ver Mixed: the version to check, can be a string, an integer, or
2576 function wfUsePHP( $req_ver ) {
2577 $php_ver = PHP_VERSION
;
2579 if ( version_compare( $php_ver, (string)$req_ver, '<' ) ) {
2580 throw new MWException( "PHP $req_ver required--this is only $php_ver" );
2585 * This function works like "use VERSION" in Perl except it checks the version
2586 * of MediaWiki, the program will die with a backtrace if the current version
2587 * of MediaWiki is less than the version provided.
2589 * This is useful for extensions which due to their nature are not kept in sync
2592 * @see perldoc -f use
2594 * @param $req_ver Mixed: the version to check, can be a string, an integer, or
2597 function wfUseMW( $req_ver ) {
2600 if ( version_compare( $wgVersion, (string)$req_ver, '<' ) ) {
2601 throw new MWException( "MediaWiki $req_ver required--this is only $wgVersion" );
2606 * Return the final portion of a pathname.
2607 * Reimplemented because PHP5's basename() is buggy with multibyte text.
2608 * http://bugs.php.net/bug.php?id=33898
2610 * PHP's basename() only considers '\' a pathchar on Windows and Netware.
2611 * We'll consider it so always, as we don't want \s in our Unix paths either.
2613 * @param $path String
2614 * @param $suffix String: to remove if present
2617 function wfBaseName( $path, $suffix = '' ) {
2618 $encSuffix = ( $suffix == '' )
2620 : ( '(?:' . preg_quote( $suffix, '#' ) . ')?' );
2622 if( preg_match( "#([^/\\\\]*?){$encSuffix}[/\\\\]*$#", $path, $matches ) ) {
2630 * Generate a relative path name to the given file.
2631 * May explode on non-matching case-insensitive paths,
2632 * funky symlinks, etc.
2634 * @param $path String: absolute destination path including target filename
2635 * @param $from String: Absolute source path, directory only
2638 function wfRelativePath( $path, $from ) {
2639 // Normalize mixed input on Windows...
2640 $path = str_replace( '/', DIRECTORY_SEPARATOR
, $path );
2641 $from = str_replace( '/', DIRECTORY_SEPARATOR
, $from );
2643 // Trim trailing slashes -- fix for drive root
2644 $path = rtrim( $path, DIRECTORY_SEPARATOR
);
2645 $from = rtrim( $from, DIRECTORY_SEPARATOR
);
2647 $pieces = explode( DIRECTORY_SEPARATOR
, dirname( $path ) );
2648 $against = explode( DIRECTORY_SEPARATOR
, $from );
2650 if( $pieces[0] !== $against[0] ) {
2651 // Non-matching Windows drive letters?
2652 // Return a full path.
2656 // Trim off common prefix
2657 while( count( $pieces ) && count( $against )
2658 && $pieces[0] == $against[0] ) {
2659 array_shift( $pieces );
2660 array_shift( $against );
2663 // relative dots to bump us to the parent
2664 while( count( $against ) ) {
2665 array_unshift( $pieces, '..' );
2666 array_shift( $against );
2669 array_push( $pieces, wfBaseName( $path ) );
2671 return implode( DIRECTORY_SEPARATOR
, $pieces );
2675 * Backwards array plus for people who haven't bothered to read the PHP manual
2676 * XXX: will not darn your socks for you.
2678 * @param $array1 Array
2679 * @param [$array2, [...]] Arrays
2682 function wfArrayMerge( $array1/* ... */ ) {
2683 $args = func_get_args();
2684 $args = array_reverse( $args, true );
2686 foreach ( $args as $arg ) {
2693 * Merge arrays in the style of getUserPermissionsErrors, with duplicate removal
2695 * wfMergeErrorArrays(
2696 * array( array( 'x' ) ),
2697 * array( array( 'x', '2' ) ),
2698 * array( array( 'x' ) ),
2699 * array( array( 'y') )
2703 * array( 'x', '2' ),
2708 function wfMergeErrorArrays( /*...*/ ) {
2709 $args = func_get_args();
2711 foreach ( $args as $errors ) {
2712 foreach ( $errors as $params ) {
2713 # FIXME: sometimes get nested arrays for $params,
2714 # which leads to E_NOTICEs
2715 $spec = implode( "\t", $params );
2716 $out[$spec] = $params;
2719 return array_values( $out );
2723 * parse_url() work-alike, but non-broken. Differences:
2725 * 1) Does not raise warnings on bad URLs (just returns false)
2726 * 2) Handles protocols that don't use :// (e.g., mailto: and news:) correctly
2727 * 3) Adds a "delimiter" element to the array, either '://' or ':' (see (2))
2729 * @param $url String: a URL to parse
2730 * @return Array: bits of the URL in an associative array, per PHP docs
2732 function wfParseUrl( $url ) {
2733 global $wgUrlProtocols; // Allow all protocols defined in DefaultSettings/LocalSettings.php
2734 wfSuppressWarnings();
2735 $bits = parse_url( $url );
2736 wfRestoreWarnings();
2741 // most of the protocols are followed by ://, but mailto: and sometimes news: not, check for it
2742 if ( in_array( $bits['scheme'] . '://', $wgUrlProtocols ) ) {
2743 $bits['delimiter'] = '://';
2744 } elseif ( in_array( $bits['scheme'] . ':', $wgUrlProtocols ) ) {
2745 $bits['delimiter'] = ':';
2746 // parse_url detects for news: and mailto: the host part of an url as path
2747 // We have to correct this wrong detection
2748 if ( isset( $bits['path'] ) ) {
2749 $bits['host'] = $bits['path'];
2760 * Make a URL index, appropriate for the el_index field of externallinks.
2762 function wfMakeUrlIndex( $url ) {
2763 $bits = wfParseUrl( $url );
2765 // Reverse the labels in the hostname, convert to lower case
2766 // For emails reverse domainpart only
2767 if ( $bits['scheme'] == 'mailto' ) {
2768 $mailparts = explode( '@', $bits['host'], 2 );
2769 if ( count( $mailparts ) === 2 ) {
2770 $domainpart = strtolower( implode( '.', array_reverse( explode( '.', $mailparts[1] ) ) ) );
2772 // No domain specified, don't mangle it
2775 $reversedHost = $domainpart . '@' . $mailparts[0];
2777 $reversedHost = strtolower( implode( '.', array_reverse( explode( '.', $bits['host'] ) ) ) );
2779 // Add an extra dot to the end
2780 // Why? Is it in wrong place in mailto links?
2781 if ( substr( $reversedHost, -1, 1 ) !== '.' ) {
2782 $reversedHost .= '.';
2784 // Reconstruct the pseudo-URL
2785 $prot = $bits['scheme'];
2786 $index = $prot . $bits['delimiter'] . $reversedHost;
2787 // Leave out user and password. Add the port, path, query and fragment
2788 if ( isset( $bits['port'] ) ) {
2789 $index .= ':' . $bits['port'];
2791 if ( isset( $bits['path'] ) ) {
2792 $index .= $bits['path'];
2796 if ( isset( $bits['query'] ) ) {
2797 $index .= '?' . $bits['query'];
2799 if ( isset( $bits['fragment'] ) ) {
2800 $index .= '#' . $bits['fragment'];
2806 * Do any deferred updates and clear the list
2807 * TODO: This could be in Wiki.php if that class made any sense at all
2809 function wfDoUpdates() {
2810 global $wgPostCommitUpdateList, $wgDeferredUpdateList;
2811 foreach ( $wgDeferredUpdateList as $update ) {
2812 $update->doUpdate();
2814 foreach ( $wgPostCommitUpdateList as $update ) {
2815 $update->doUpdate();
2817 $wgDeferredUpdateList = array();
2818 $wgPostCommitUpdateList = array();
2822 * Convert an arbitrarily-long digit string from one numeric base
2823 * to another, optionally zero-padding to a minimum column width.
2825 * Supports base 2 through 36; digit values 10-36 are represented
2826 * as lowercase letters a-z. Input is case-insensitive.
2828 * @param $input String: of digits
2829 * @param $sourceBase Integer: 2-36
2830 * @param $destBase Integer: 2-36
2831 * @param $pad Integer: 1 or greater
2832 * @param $lowercase Boolean
2833 * @return String or false on invalid input
2835 function wfBaseConvert( $input, $sourceBase, $destBase, $pad = 1, $lowercase = true ) {
2836 $input = strval( $input );
2837 if( $sourceBase < 2 ||
2842 $sourceBase != intval( $sourceBase ) ||
2843 $destBase != intval( $destBase ) ||
2844 $pad != intval( $pad ) ||
2845 !is_string( $input ) ||
2849 $digitChars = ( $lowercase ) ?
'0123456789abcdefghijklmnopqrstuvwxyz' : '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
2850 $inDigits = array();
2853 // Decode and validate input string
2854 $input = strtolower( $input );
2855 for( $i = 0; $i < strlen( $input ); $i++
) {
2856 $n = strpos( $digitChars, $input{$i} );
2857 if( $n === false ||
$n > $sourceBase ) {
2863 // Iterate over the input, modulo-ing out an output digit
2864 // at a time until input is gone.
2865 while( count( $inDigits ) ) {
2867 $workDigits = array();
2870 foreach( $inDigits as $digit ) {
2871 $work *= $sourceBase;
2874 if( $work < $destBase ) {
2875 // Gonna need to pull another digit.
2876 if( count( $workDigits ) ) {
2877 // Avoid zero-padding; this lets us find
2878 // the end of the input very easily when
2879 // length drops to zero.
2883 // Finally! Actual division!
2884 $workDigits[] = intval( $work / $destBase );
2886 // Isn't it annoying that most programming languages
2887 // don't have a single divide-and-remainder operator,
2888 // even though the CPU implements it that way?
2889 $work = $work %
$destBase;
2893 // All that division leaves us with a remainder,
2894 // which is conveniently our next output digit.
2895 $outChars .= $digitChars[$work];
2898 $inDigits = $workDigits;
2901 while( strlen( $outChars ) < $pad ) {
2905 return strrev( $outChars );
2909 * Create an object with a given name and an array of construct parameters
2910 * @param $name String
2911 * @param $p Array: parameters
2913 function wfCreateObject( $name, $p ) {
2914 $p = array_values( $p );
2915 switch ( count( $p ) ) {
2919 return new $name( $p[0] );
2921 return new $name( $p[0], $p[1] );
2923 return new $name( $p[0], $p[1], $p[2] );
2925 return new $name( $p[0], $p[1], $p[2], $p[3] );
2927 return new $name( $p[0], $p[1], $p[2], $p[3], $p[4] );
2929 return new $name( $p[0], $p[1], $p[2], $p[3], $p[4], $p[5] );
2931 throw new MWException( 'Too many arguments to construtor in wfCreateObject' );
2935 function wfHttpOnlySafe() {
2936 global $wgHttpOnlyBlacklist;
2937 if( !version_compare( '5.2', PHP_VERSION
, '<' ) ) {
2941 if( isset( $_SERVER['HTTP_USER_AGENT'] ) ) {
2942 foreach( $wgHttpOnlyBlacklist as $regex ) {
2943 if( preg_match( $regex, $_SERVER['HTTP_USER_AGENT'] ) ) {
2953 * Initialise php session
2955 function wfSetupSession( $sessionId = false ) {
2956 global $wgSessionsInMemcached, $wgCookiePath, $wgCookieDomain,
2957 $wgCookieSecure, $wgCookieHttpOnly, $wgSessionHandler;
2958 if( $wgSessionsInMemcached ) {
2959 require_once( 'MemcachedSessions.php' );
2960 } elseif( $wgSessionHandler && $wgSessionHandler != ini_get( 'session.save_handler' ) ) {
2961 # Only set this if $wgSessionHandler isn't null and session.save_handler
2962 # hasn't already been set to the desired value (that causes errors)
2963 ini_set( 'session.save_handler', $wgSessionHandler );
2965 $httpOnlySafe = wfHttpOnlySafe();
2966 wfDebugLog( 'cookie',
2967 'session_set_cookie_params: "' . implode( '", "',
2973 $httpOnlySafe && $wgCookieHttpOnly ) ) . '"' );
2974 if( $httpOnlySafe && $wgCookieHttpOnly ) {
2975 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookieHttpOnly );
2977 // PHP 5.1 throws warnings if you pass the HttpOnly parameter for 5.2.
2978 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
2980 session_cache_limiter( 'private, must-revalidate' );
2982 session_id( $sessionId );
2984 wfSuppressWarnings();
2986 wfRestoreWarnings();
2990 * Get an object from the precompiled serialized directory
2992 * @return Mixed: the variable on success, false on failure
2994 function wfGetPrecompiledData( $name ) {
2997 $file = "$IP/serialized/$name";
2998 if ( file_exists( $file ) ) {
2999 $blob = file_get_contents( $file );
3001 return unserialize( $blob );
3007 function wfGetCaller( $level = 2 ) {
3008 $backtrace = wfDebugBacktrace();
3009 if ( isset( $backtrace[$level] ) ) {
3010 return wfFormatStackFrame( $backtrace[$level] );
3012 $caller = 'unknown';
3018 * Return a string consisting of callers in the stack. Useful sometimes
3019 * for profiling specific points.
3021 * @param $limit The maximum depth of the stack frame to return, or false for
3024 function wfGetAllCallers( $limit = 3 ) {
3025 $trace = array_reverse( wfDebugBacktrace() );
3026 if ( !$limit ||
$limit > count( $trace ) - 1 ) {
3027 $limit = count( $trace ) - 1;
3029 $trace = array_slice( $trace, -$limit - 1, $limit );
3030 return implode( '/', array_map( 'wfFormatStackFrame', $trace ) );
3034 * Return a string representation of frame
3036 function wfFormatStackFrame( $frame ) {
3037 return isset( $frame['class'] ) ?
3038 $frame['class'] . '::' . $frame['function'] :
3045 function wfMemcKey( /*... */ ) {
3046 $args = func_get_args();
3047 $key = wfWikiID() . ':' . implode( ':', $args );
3048 $key = str_replace( ' ', '_', $key );
3053 * Get a cache key for a foreign DB
3055 function wfForeignMemcKey( $db, $prefix /*, ... */ ) {
3056 $args = array_slice( func_get_args(), 2 );
3058 $key = "$db-$prefix:" . implode( ':', $args );
3060 $key = $db . ':' . implode( ':', $args );
3066 * Get an ASCII string identifying this wiki
3067 * This is used as a prefix in memcached keys
3069 function wfWikiID() {
3070 global $wgDBprefix, $wgDBname;
3071 if ( $wgDBprefix ) {
3072 return "$wgDBname-$wgDBprefix";
3079 * Split a wiki ID into DB name and table prefix
3081 function wfSplitWikiID( $wiki ) {
3082 $bits = explode( '-', $wiki, 2 );
3083 if ( count( $bits ) < 2 ) {
3090 * Get a Database object.
3091 * @param $db Integer: index of the connection to get. May be DB_MASTER for the
3092 * master (for write queries), DB_SLAVE for potentially lagged read
3093 * queries, or an integer >= 0 for a particular server.
3095 * @param $groups Mixed: query groups. An array of group names that this query
3096 * belongs to. May contain a single string if the query is only
3099 * @param $wiki String: the wiki ID, or false for the current wiki
3101 * Note: multiple calls to wfGetDB(DB_SLAVE) during the course of one request
3102 * will always return the same object, unless the underlying connection or load
3103 * balancer is manually destroyed.
3105 * @return DatabaseBase
3107 function &wfGetDB( $db, $groups = array(), $wiki = false ) {
3108 return wfGetLB( $wiki )->getConnection( $db, $groups, $wiki );
3112 * Get a load balancer object.
3114 * @param $wiki String: wiki ID, or false for the current wiki
3115 * @return LoadBalancer
3117 function wfGetLB( $wiki = false ) {
3118 return wfGetLBFactory()->getMainLB( $wiki );
3122 * Get the load balancer factory object
3124 function &wfGetLBFactory() {
3125 return LBFactory
::singleton();
3130 * Shortcut for RepoGroup::singleton()->findFile()
3131 * @param $title String or Title object
3132 * @param $options Associative array of options:
3133 * time: requested time for an archived image, or false for the
3134 * current version. An image object will be returned which was
3135 * created at the specified time.
3137 * ignoreRedirect: If true, do not follow file redirects
3139 * private: If true, return restricted (deleted) files if the current
3140 * user is allowed to view them. Otherwise, such files will not
3143 * bypassCache: If true, do not use the process-local cache of File objects
3145 * @return File, or false if the file does not exist
3147 function wfFindFile( $title, $options = array() ) {
3148 return RepoGroup
::singleton()->findFile( $title, $options );
3152 * Get an object referring to a locally registered file.
3153 * Returns a valid placeholder object if the file does not exist.
3154 * @param $title Either a string or Title object
3155 * @return File, or null if passed an invalid Title
3157 function wfLocalFile( $title ) {
3158 return RepoGroup
::singleton()->getLocalRepo()->newFile( $title );
3162 * Should low-performance queries be disabled?
3166 function wfQueriesMustScale() {
3167 global $wgMiserMode;
3169 ||
( SiteStats
::pages() > 100000
3170 && SiteStats
::edits() > 1000000
3171 && SiteStats
::users() > 10000 );
3175 * Get the path to a specified script file, respecting file
3176 * extensions; this is a wrapper around $wgScriptExtension etc.
3178 * @param $script String: script filename, sans extension
3181 function wfScript( $script = 'index' ) {
3182 global $wgScriptPath, $wgScriptExtension;
3183 return "{$wgScriptPath}/{$script}{$wgScriptExtension}";
3187 * Get the script URL.
3189 * @return script URL
3191 function wfGetScriptUrl() {
3192 if( isset( $_SERVER['SCRIPT_NAME'] ) ) {
3194 # as it was called, minus the query string.
3196 # Some sites use Apache rewrite rules to handle subdomains,
3197 # and have PHP set up in a weird way that causes PHP_SELF
3198 # to contain the rewritten URL instead of the one that the
3199 # outside world sees.
3201 # If in this mode, use SCRIPT_URL instead, which mod_rewrite
3202 # provides containing the "before" URL.
3203 return $_SERVER['SCRIPT_NAME'];
3205 return $_SERVER['URL'];
3210 * Convenience function converts boolean values into "true"
3211 * or "false" (string) values
3213 * @param $value Boolean
3216 function wfBoolToStr( $value ) {
3217 return $value ?
'true' : 'false';
3221 * Load an extension messages file
3222 * @deprecated in 1.16 (warnings in 1.18, removed in ?)
3224 function wfLoadExtensionMessages( $extensionName, $langcode = false ) {
3228 * Get a platform-independent path to the null file, e.g.
3233 function wfGetNull() {
3234 return wfIsWindows()
3240 * Displays a maxlag error
3242 * @param $host String: server that lags the most
3243 * @param $lag Integer: maxlag (actual)
3244 * @param $maxLag Integer: maxlag (requested)
3246 function wfMaxlagError( $host, $lag, $maxLag ) {
3247 global $wgShowHostnames;
3248 header( 'HTTP/1.1 503 Service Unavailable' );
3249 header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
3250 header( 'X-Database-Lag: ' . intval( $lag ) );
3251 header( 'Content-Type: text/plain' );
3252 if( $wgShowHostnames ) {
3253 echo "Waiting for $host: $lag seconds lagged\n";
3255 echo "Waiting for a database server: $lag seconds lagged\n";
3260 * Throws a warning that $function is deprecated
3261 * @param $function String
3264 function wfDeprecated( $function ) {
3265 static $functionsWarned = array();
3266 if ( !isset( $functionsWarned[$function] ) ) {
3267 $functionsWarned[$function] = true;
3268 wfWarn( "Use of $function is deprecated.", 2 );
3273 * Send a warning either to the debug log or in a PHP error depending on
3274 * $wgDevelopmentWarnings
3276 * @param $msg String: message to send
3277 * @param $callerOffset Integer: number of itmes to go back in the backtrace to
3278 * find the correct caller (1 = function calling wfWarn, ...)
3279 * @param $level Integer: PHP error level; only used when $wgDevelopmentWarnings
3282 function wfWarn( $msg, $callerOffset = 1, $level = E_USER_NOTICE
) {
3283 $callers = wfDebugBacktrace();
3284 if( isset( $callers[$callerOffset +
1] ) ){
3285 $callerfunc = $callers[$callerOffset +
1];
3286 $callerfile = $callers[$callerOffset];
3287 if( isset( $callerfile['file'] ) && isset( $callerfile['line'] ) ) {
3288 $file = $callerfile['file'] . ' at line ' . $callerfile['line'];
3290 $file = '(internal function)';
3293 if( isset( $callerfunc['class'] ) ) {
3294 $func .= $callerfunc['class'] . '::';
3296 if( isset( $callerfunc['function'] ) ) {
3297 $func .= $callerfunc['function'];
3299 $msg .= " [Called from $func in $file]";
3302 global $wgDevelopmentWarnings;
3303 if ( $wgDevelopmentWarnings ) {
3304 trigger_error( $msg, $level );
3306 wfDebug( "$msg\n" );
3311 * Sleep until the worst slave's replication lag is less than or equal to
3312 * $maxLag, in seconds. Use this when updating very large numbers of rows, as
3313 * in maintenance scripts, to avoid causing too much lag. Of course, this is
3314 * a no-op if there are no slaves.
3316 * Every time the function has to wait for a slave, it will print a message to
3317 * that effect (and then sleep for a little while), so it's probably not best
3318 * to use this outside maintenance scripts in its present form.
3320 * @param $maxLag Integer
3321 * @param $wiki mixed Wiki identifier accepted by wfGetLB
3324 function wfWaitForSlaves( $maxLag, $wiki = false ) {
3326 $lb = wfGetLB( $wiki );
3327 list( $host, $lag ) = $lb->getMaxLag( $wiki );
3328 while( $lag > $maxLag ) {
3329 wfSuppressWarnings();
3330 $name = gethostbyaddr( $host );
3331 wfRestoreWarnings();
3332 if( $name !== false ) {
3335 print "Waiting for $host (lagged $lag seconds)...\n";
3337 list( $host, $lag ) = $lb->getMaxLag();
3343 * Output some plain text in command-line mode or in the installer (updaters.inc).
3344 * Do not use it in any other context, its behaviour is subject to change.
3346 function wfOut( $s ) {
3347 global $wgCommandLineMode;
3348 if ( $wgCommandLineMode && !defined( 'MEDIAWIKI_INSTALL' ) ) {
3351 echo htmlspecialchars( $s );
3357 * Count down from $n to zero on the terminal, with a one-second pause
3358 * between showing each number. For use in command-line scripts.
3360 function wfCountDown( $n ) {
3361 for ( $i = $n; $i >= 0; $i-- ) {
3363 echo str_repeat( "\x08", strlen( $i +
1 ) );
3375 * Generate a random 32-character hexadecimal token.
3376 * @param $salt Mixed: some sort of salt, if necessary, to add to random
3377 * characters before hashing.
3379 function wfGenerateToken( $salt = '' ) {
3380 $salt = serialize( $salt );
3381 return md5( mt_rand( 0, 0x7fffffff ) . $salt );
3385 * Replace all invalid characters with -
3386 * @param $name Mixed: filename to process
3388 function wfStripIllegalFilenameChars( $name ) {
3389 global $wgIllegalFileChars;
3390 $name = wfBaseName( $name );
3391 $name = preg_replace(
3392 "/[^" . Title
::legalChars() . "]" .
3393 ( $wgIllegalFileChars ?
"|[" . $wgIllegalFileChars . "]" : '' ) .
3402 * Insert array into another array after the specified *KEY*
3403 * @param $array Array: The array.
3404 * @param $insert Array: The array to insert.
3405 * @param $after Mixed: The key to insert after
3407 function wfArrayInsertAfter( $array, $insert, $after ) {
3408 // Find the offset of the element to insert after.
3409 $keys = array_keys( $array );
3410 $offsetByKey = array_flip( $keys );
3412 $offset = $offsetByKey[$after];
3414 // Insert at the specified offset
3415 $before = array_slice( $array, 0, $offset +
1, true );
3416 $after = array_slice( $array, $offset +
1, count( $array ) - $offset, true );
3418 $output = $before +
$insert +
$after;
3423 /* Recursively converts the parameter (an object) to an array with the same data */
3424 function wfObjectToArray( $object, $recursive = true ) {
3426 foreach ( get_object_vars( $object ) as $key => $value ) {
3427 if ( is_object( $value ) && $recursive ) {
3428 $value = wfObjectToArray( $value );
3431 $array[$key] = $value;
3438 * Set PHP's memory limit to the larger of php.ini or $wgMemoryLimit;
3439 * @return Integer value memory was set to.
3441 function wfMemoryLimit() {
3442 global $wgMemoryLimit;
3443 $memlimit = wfShorthandToInteger( ini_get( 'memory_limit' ) );
3444 $conflimit = wfShorthandToInteger( $wgMemoryLimit );
3445 if( $memlimit != -1 ) {
3446 if( $conflimit == -1 ) {
3447 wfDebug( "Removing PHP's memory limit\n" );
3448 wfSuppressWarnings();
3449 ini_set( 'memory_limit', $conflimit );
3450 wfRestoreWarnings();
3452 } elseif ( $conflimit > $memlimit ) {
3453 wfDebug( "Raising PHP's memory limit to $conflimit bytes\n" );
3454 wfSuppressWarnings();
3455 ini_set( 'memory_limit', $conflimit );
3456 wfRestoreWarnings();
3464 * Converts shorthand byte notation to integer form
3465 * @param $string String
3468 function wfShorthandToInteger( $string = '' ) {
3469 $string = trim( $string );
3470 if( empty( $string ) ) {
3473 $last = strtolower( $string[strlen( $string ) - 1] );
3474 $val = intval( $string );
3488 * Get the normalised IETF language tag
3489 * @param $code String: The language code.
3490 * @return $langCode String: The language code which complying with BCP 47 standards.
3492 function wfBCP47( $code ) {
3493 $codeSegment = explode( '-', $code );
3494 foreach ( $codeSegment as $segNo => $seg ) {
3495 if ( count( $codeSegment ) > 0 ) {
3496 // ISO 3166 country code
3497 if ( ( strlen( $seg ) == 2 ) && ( $segNo > 0 ) ) {
3498 $codeBCP[$segNo] = strtoupper( $seg );
3499 // ISO 15924 script code
3500 } elseif ( ( strlen( $seg ) == 4 ) && ( $segNo > 0 ) ) {
3501 $codeBCP[$segNo] = ucfirst( $seg );
3502 // Use lowercase for other cases
3504 $codeBCP[$segNo] = strtolower( $seg );
3507 // Use lowercase for single segment
3508 $codeBCP[$segNo] = strtolower( $seg );
3511 $langCode = implode( '-', $codeBCP );
3515 function wfArrayMap( $function, $input ) {
3516 $ret = array_map( $function, $input );
3517 foreach ( $ret as $key => $value ) {
3518 $taint = istainted( $input[$key] );
3520 taint( $ret[$key], $taint );
3527 * Returns the PackageRepository object for interaction with the package repository.
3529 * TODO: Make the repository type also configurable.
3533 * @return PackageRepository
3535 function wfGetRepository() {
3536 global $wgRepositoryApiLocation;
3537 static $repository = false;
3539 if ( $repository === false ) {
3540 $repository = new DistributionRepository( $wgRepositoryApiLocation );