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 # 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 fallback_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 );
43 if( !function_exists( 'iconv' ) ) {
44 function iconv( $from, $to, $string ) {
45 return fallback_iconv( $from, $to, $string )
53 * Fallback implementation for mb_substr, hardcoded to UTF-8.
54 * Attempts to be at least _moderately_ efficient; best optimized
55 * for relatively small offset and count values -- about 5x slower
56 * than native mb_string in my testing.
58 * Larger offsets are still fairly efficient for Latin text, but
59 * can be up to 100x slower than native if the text is heavily
60 * multibyte and we have to slog through a few hundred kb.
62 function fallback_mb_substr( $str, $start, $count='end' ) {
64 $split = fallback_mb_substr_split_unicode( $str, intval( $start ) );
65 $str = substr( $str, $split );
68 if( $count !== 'end' ) {
69 $split = fallback_mb_substr_split_unicode( $str, intval( $count ) );
70 $str = substr( $str, 0, $split );
76 function fallback_mb_substr_split_unicode( $str, $splitPos ) {
77 if( $splitPos == 0 ) {
81 $byteLen = strlen( $str );
84 if( $splitPos > 256 ) {
85 // Optimize large string offsets by skipping ahead N bytes.
86 // This will cut out most of our slow time on Latin-based text,
87 // and 1/2 to 1/3 on East European and Asian scripts.
89 while ( $bytePos < $byteLen && $str{$bytePos} >= "\x80" && $str{$bytePos} < "\xc0" ) {
92 $charPos = mb_strlen( substr( $str, 0, $bytePos ) );
98 while( $charPos++
< $splitPos ) {
100 // Move past any tail bytes
101 while ( $bytePos < $byteLen && $str{$bytePos} >= "\x80" && $str{$bytePos} < "\xc0" ) {
106 $splitPosX = $splitPos +
1;
107 $charPos = 0; // relative to end of string; we don't care about the actual char position here
109 while( $bytePos > 0 && $charPos-- >= $splitPosX ) {
111 // Move past any tail bytes
112 while ( $bytePos > 0 && $str{$bytePos} >= "\x80" && $str{$bytePos} < "\xc0" ) {
121 if ( !function_exists( 'mb_substr' ) ) {
122 function mb_substr( $str, $start, $count='end' ) {
123 return fallback_mb_substr( $str, $start, $count )
126 function mb_substr_split_unicode( $str, $splitPos ) {
127 return fallback_mb_substr_split_unicode( $str, $splitPos );
134 * Fallback implementation of mb_strlen, hardcoded to UTF-8.
136 * @param string $enc optional encoding; ignored
139 function fallback_mb_strlen( $str, $enc = '' ) {
140 $counts = count_chars( $str );
144 for( $i = 0; $i < 0x80; $i++
) {
145 $total +
= $counts[$i];
148 // Count multibyte sequence heads
149 for( $i = 0xc0; $i < 0xff; $i++
) {
150 $total +
= $counts[$i];
155 if ( !function_exists( 'mb_strlen' ) ) {
156 function mb_strlen( $str, $enc = '' ) {
157 return fallback_mb_strlen( $str, $enc );
164 * Fallback implementation of mb_strpos, hardcoded to UTF-8.
165 * @param $haystack String
166 * @param $needle String
167 * @param $offset String: optional start position
168 * @param $encoding String: optional encoding; ignored
171 function fallback_mb_strpos( $haystack, $needle, $offset = 0, $encoding = '' ) {
172 $needle = preg_quote( $needle, '/' );
175 preg_match( '/' . $needle . '/u', $haystack, $ar, PREG_OFFSET_CAPTURE
, $offset );
177 if( isset( $ar[0][1] ) ) {
184 if( !function_exists( 'mb_strpos' ) ) {
186 function mb_strpos( $haystack, $needle, $offset = 0, $encoding = '' ) {
187 return fallback_mb_strpos( $haystack, $needle, $offset, $encoding );
195 * Fallback implementation of mb_strrpos, hardcoded to UTF-8.
196 * @param $haystack String
197 * @param $needle String
198 * @param $offset String: optional start position
199 * @param $encoding String: optional encoding; ignored
202 function fallback_mb_strrpos( $haystack, $needle, $offset = 0, $encoding = '' ) {
203 $needle = preg_quote( $needle, '/' );
206 preg_match_all( '/' . $needle . '/u', $haystack, $ar, PREG_OFFSET_CAPTURE
, $offset );
208 if( isset( $ar[0] ) && count( $ar[0] ) > 0 &&
209 isset( $ar[0][count( $ar[0] ) - 1][1] ) ) {
210 return $ar[0][count( $ar[0] ) - 1][1];
216 if( !function_exists( 'mb_strrpos' ) ) {
217 function mb_strrpos( $haystack, $needle, $offset = 0, $encoding = '' ) {
218 return fallback_mb_strrpos( $haystack, $needle, $offset, $encoding );
223 // Support for Wietse Venema's taint feature
224 if ( !function_exists( 'istainted' ) ) {
225 function istainted( $var ) {
228 function taint( $var, $level = 0 ) {}
229 function untaint( $var, $level = 0 ) {}
230 define( 'TC_HTML', 1 );
231 define( 'TC_SHELL', 1 );
232 define( 'TC_MYSQL', 1 );
233 define( 'TC_PCRE', 1 );
234 define( 'TC_SELF', 1 );
241 * Like array_diff( $a, $b ) except that it works with two-dimensional arrays.
243 function wfArrayDiff2( $a, $b ) {
244 return array_udiff( $a, $b, 'wfArrayDiff2_cmp' );
246 function wfArrayDiff2_cmp( $a, $b ) {
247 if ( !is_array( $a ) ) {
248 return strcmp( $a, $b );
249 } elseif ( count( $a ) !== count( $b ) ) {
250 return count( $a ) < count( $b ) ?
-1 : 1;
254 while( ( list( , $valueA ) = each( $a ) ) && ( list( , $valueB ) = each( $b ) ) ) {
255 $cmp = strcmp( $valueA, $valueB );
265 * Get a random decimal value between 0 and 1, in a way
266 * not likely to give duplicate values for any realistic
267 * number of articles.
271 function wfRandom() {
272 # The maximum random value is "only" 2^31-1, so get two random
273 # values to reduce the chance of dupes
274 $max = mt_getrandmax() +
1;
275 $rand = number_format( ( mt_rand() * $max +
mt_rand() )
276 / $max / $max, 12, '.', '' );
281 * We want some things to be included as literal characters in our title URLs
282 * for prettiness, which urlencode encodes by default. According to RFC 1738,
283 * all of the following should be safe:
287 * But + is not safe because it's used to indicate a space; &= are only safe in
288 * paths and not in queries (and we don't distinguish here); ' seems kind of
289 * scary; and urlencode() doesn't touch -_. to begin with. Plus, although /
290 * is reserved, we don't care. So the list we unescape is:
294 * However, IIS7 redirects fail when the url contains a colon (Bug 22709),
295 * so no fancy : for IIS7.
297 * %2F in the page titles seems to fatally break for some reason.
302 function wfUrlencode( $s ) {
304 if ( is_null( $needle ) ) {
305 $needle = array( '%3B', '%40', '%24', '%21', '%2A', '%28', '%29', '%2C', '%2F' );
306 if ( !isset( $_SERVER['SERVER_SOFTWARE'] ) ||
( strpos( $_SERVER['SERVER_SOFTWARE'], 'Microsoft-IIS/7' ) === false ) ) {
311 $s = urlencode( $s );
314 array( ';', '@', '$', '!', '*', '(', ')', ',', '/', ':' ),
322 * Sends a line to the debug log if enabled or, optionally, to a comment in output.
323 * In normal operation this is a NOP.
325 * Controlling globals:
326 * $wgDebugLogFile - points to the log file
327 * $wgProfileOnly - if set, normal debug messages will not be recorded.
328 * $wgDebugRawPage - if false, 'action=raw' hits will not result in debug output.
329 * $wgDebugComments - if on, some debug items may appear in comments in the HTML output.
331 * @param $text String
332 * @param $logonly Bool: set true to avoid appearing in HTML when $wgDebugComments is set
334 function wfDebug( $text, $logonly = false ) {
335 global $wgOut, $wgDebugLogFile, $wgDebugComments, $wgProfileOnly, $wgDebugRawPage;
336 global $wgDebugLogPrefix, $wgShowDebug;
338 static $cache = array(); // Cache of unoutputted messages
339 $text = wfDebugTimer() . $text;
341 # Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
342 if ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' && !$wgDebugRawPage ) {
346 if ( ( $wgDebugComments ||
$wgShowDebug ) && !$logonly ) {
349 if ( isset( $wgOut ) && StubObject
::isRealObject( $wgOut ) ) {
350 // add the message and any cached messages to the output
351 array_map( array( $wgOut, 'debug' ), $cache );
355 if ( $wgDebugLogFile != '' && !$wgProfileOnly ) {
356 # Strip unprintables; they can switch terminal modes when binary data
357 # gets dumped, which is pretty annoying.
358 $text = preg_replace( '![\x00-\x08\x0b\x0c\x0e-\x1f]!', ' ', $text );
359 $text = $wgDebugLogPrefix . $text;
360 wfErrorLog( $text, $wgDebugLogFile );
364 function wfDebugTimer() {
365 global $wgDebugTimestamps;
366 if ( !$wgDebugTimestamps ) {
369 static $start = null;
371 if ( $start === null ) {
372 $start = microtime( true );
373 $prefix = "\n$start";
375 $prefix = sprintf( "%6.4f", microtime( true ) - $start );
378 return $prefix . ' ';
382 * Send a line giving PHP memory usage.
383 * @param $exact Bool: print exact values instead of kilobytes (default: false)
385 function wfDebugMem( $exact = false ) {
386 $mem = memory_get_usage();
388 $mem = floor( $mem / 1024 ) . ' kilobytes';
392 wfDebug( "Memory usage: $mem\n" );
396 * Send a line to a supplementary debug log file, if configured, or main debug log if not.
397 * $wgDebugLogGroups[$logGroup] should be set to a filename to send to a separate log.
399 * @param $logGroup String
400 * @param $text String
401 * @param $public Bool: whether to log the event in the public log if no private
402 * log file is specified, (default true)
404 function wfDebugLog( $logGroup, $text, $public = true ) {
405 global $wgDebugLogGroups, $wgShowHostnames;
406 $text = trim( $text ) . "\n";
407 if( isset( $wgDebugLogGroups[$logGroup] ) ) {
408 $time = wfTimestamp( TS_DB
);
410 if ( $wgShowHostnames ) {
411 $host = wfHostname();
415 wfErrorLog( "$time $host $wiki: $text", $wgDebugLogGroups[$logGroup] );
416 } elseif ( $public === true ) {
417 wfDebug( $text, true );
422 * Log for database errors
423 * @param $text String: database error message.
425 function wfLogDBError( $text ) {
426 global $wgDBerrorLog, $wgDBname;
427 if ( $wgDBerrorLog ) {
428 $host = trim(`hostname`
);
429 $text = date( 'D M j G:i:s T Y' ) . "\t$host\t$wgDBname\t$text";
430 wfErrorLog( $text, $wgDBerrorLog );
435 * Log to a file without getting "file size exceeded" signals.
437 * Can also log to TCP or UDP with the syntax udp://host:port/prefix. This will
438 * send lines to the specified port, prefixed by the specified prefix and a space.
440 function wfErrorLog( $text, $file ) {
441 if ( substr( $file, 0, 4 ) == 'udp:' ) {
442 # Needs the sockets extension
443 if ( preg_match( '!^(tcp|udp):(?://)?\[([0-9a-fA-F:]+)\]:(\d+)(?:/(.*))?$!', $file, $m ) ) {
444 // IPv6 bracketed host
446 $port = intval( $m[3] );
447 $prefix = isset( $m[4] ) ?
$m[4] : false;
449 } elseif ( preg_match( '!^(tcp|udp):(?://)?([a-zA-Z0-9.-]+):(\d+)(?:/(.*))?$!', $file, $m ) ) {
451 if ( !IP
::isIPv4( $host ) ) {
452 $host = gethostbyname( $host );
454 $port = intval( $m[3] );
455 $prefix = isset( $m[4] ) ?
$m[4] : false;
458 throw new MWException( __METHOD__
. ': Invalid UDP specification' );
460 // Clean it up for the multiplexer
461 if ( strval( $prefix ) !== '' ) {
462 $text = preg_replace( '/^/m', $prefix . ' ', $text );
463 if ( substr( $text, -1 ) != "\n" ) {
468 $sock = socket_create( $domain, SOCK_DGRAM
, SOL_UDP
);
472 socket_sendto( $sock, $text, strlen( $text ), 0, $host, $port );
473 socket_close( $sock );
475 wfSuppressWarnings();
476 $exists = file_exists( $file );
477 $size = $exists ?
filesize( $file ) : false;
478 if ( !$exists ||
( $size !== false && $size +
strlen( $text ) < 0x7fffffff ) ) {
479 error_log( $text, 3, $file );
488 function wfLogProfilingData() {
489 global $wgRequestTime, $wgDebugLogFile, $wgDebugRawPage, $wgRequest;
490 global $wgProfiler, $wgProfileLimit, $wgUser;
491 # Profiling must actually be enabled...
492 if( is_null( $wgProfiler ) ) {
495 # Get total page request time
497 $elapsed = $now - $wgRequestTime;
498 # Only show pages that longer than $wgProfileLimit time (default is 0)
499 if( $elapsed <= $wgProfileLimit ) {
502 $prof = wfGetProfilingOutput( $wgRequestTime, $elapsed );
504 if( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) {
505 $forward = ' forwarded for ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
507 if( !empty( $_SERVER['HTTP_CLIENT_IP'] ) ) {
508 $forward .= ' client IP ' . $_SERVER['HTTP_CLIENT_IP'];
510 if( !empty( $_SERVER['HTTP_FROM'] ) ) {
511 $forward .= ' from ' . $_SERVER['HTTP_FROM'];
514 $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
516 // Don't unstub $wgUser at this late stage just for statistics purposes
517 // FIXME: We can detect some anons even if it is not loaded. See User::getId()
518 if( $wgUser->mDataLoaded
&& $wgUser->isAnon() ) {
521 $log = sprintf( "%s\t%04.3f\t%s\n",
522 gmdate( 'YmdHis' ), $elapsed,
523 urldecode( $wgRequest->getRequestURL() . $forward ) );
524 if ( $wgDebugLogFile != '' && ( $wgRequest->getVal( 'action' ) != 'raw' ||
$wgDebugRawPage ) ) {
525 wfErrorLog( $log . $prof, $wgDebugLogFile );
530 * Check if the wiki read-only lock file is present. This can be used to lock
531 * off editing functions, but doesn't guarantee that the database will not be
535 function wfReadOnly() {
536 global $wgReadOnlyFile, $wgReadOnly;
538 if ( !is_null( $wgReadOnly ) ) {
539 return (bool)$wgReadOnly;
541 if ( $wgReadOnlyFile == '' ) {
544 // Set $wgReadOnly for faster access next time
545 if ( is_file( $wgReadOnlyFile ) ) {
546 $wgReadOnly = file_get_contents( $wgReadOnlyFile );
550 return (bool)$wgReadOnly;
553 function wfReadOnlyReason() {
560 * Return a Language object from $langcode
561 * @param $langcode Mixed: either:
562 * - a Language object
563 * - code of the language to get the message for, if it is
564 * a valid code create a language for that language, if
565 * it is a string but not a valid code then make a basic
567 * - a boolean: if it's false then use the current users
568 * language (as a fallback for the old parameter
569 * functionality), or if it is true then use the wikis
570 * @return Language object
572 function wfGetLangObj( $langcode = false ) {
573 # Identify which language to get or create a language object for.
574 # Using is_object here due to Stub objects.
575 if( is_object( $langcode ) ) {
576 # Great, we already have the object (hopefully)!
580 global $wgContLang, $wgLanguageCode;
581 if( $langcode === true ||
$langcode === $wgLanguageCode ) {
582 # $langcode is the language code of the wikis content language object.
583 # or it is a boolean and value is true
588 if( $langcode === false ||
$langcode === $wgLang->getCode() ) {
589 # $langcode is the language code of user language object.
590 # or it was a boolean and value is false
594 $validCodes = array_keys( Language
::getLanguageNames() );
595 if( in_array( $langcode, $validCodes ) ) {
596 # $langcode corresponds to a valid language.
597 return Language
::factory( $langcode );
600 # $langcode is a string, but not a valid language code; use content language.
601 wfDebug( "Invalid language code passed to wfGetLangObj, falling back to content language.\n" );
606 * Use this instead of $wgContLang, when working with user interface.
607 * User interface is currently hard coded according to wiki content language
608 * in many ways, especially regarding to text direction. There is lots stuff
609 * to fix, hence this function to keep the old behaviour unless the global
610 * $wgBetterDirectionality is enabled (or removed when everything works).
612 function wfUILang() {
613 global $wgBetterDirectionality;
614 return wfGetLangObj( !$wgBetterDirectionality );
618 * This is the new function for getting translated interface messages.
619 * See the Message class for documentation how to use them.
620 * The intention is that this function replaces all old wfMsg* functions.
621 * @param $key \string Message key.
622 * Varargs: normal message parameters.
623 * @return \type{Message}
626 function wfMessage( $key /*...*/) {
627 $params = func_get_args();
628 array_shift( $params );
629 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
630 $params = $params[0];
632 return new Message( $key, $params );
636 * This function accepts multiple message keys and returns a message instance
637 * for the first message which is non-empty. If all messages are empty then an
638 * instance of the first message key is returned.
639 * Varargs: message keys
640 * @return \type{Message}
643 function wfMessageFallback( /*...*/ ) {
644 $keys = func_get_args();
646 foreach ( $keys as $key ) {
647 if ( wfEmptyMsg( $key ) ) {
650 return wfMessage( $key );
652 return wfMessage( $first );
656 * Get a message from anywhere, for the current user language.
658 * Use wfMsgForContent() instead if the message should NOT
659 * change depending on the user preferences.
661 * @param $key String: lookup key for the message, usually
662 * defined in languages/Language.php
664 * This function also takes extra optional parameters (not
665 * shown in the function definition), which can be used to
666 * insert variable text into the predefined message.
668 function wfMsg( $key ) {
669 $args = func_get_args();
670 array_shift( $args );
671 return wfMsgReal( $key, $args, true );
675 * Same as above except doesn't transform the message
677 function wfMsgNoTrans( $key ) {
678 $args = func_get_args();
679 array_shift( $args );
680 return wfMsgReal( $key, $args, true, false, false );
684 * Get a message from anywhere, for the current global language
685 * set with $wgLanguageCode.
687 * Use this if the message should NOT change dependent on the
688 * language set in the user's preferences. This is the case for
689 * most text written into logs, as well as link targets (such as
690 * the name of the copyright policy page). Link titles, on the
691 * other hand, should be shown in the UI language.
693 * Note that MediaWiki allows users to change the user interface
694 * language in their preferences, but a single installation
695 * typically only contains content in one language.
697 * Be wary of this distinction: If you use wfMsg() where you should
698 * use wfMsgForContent(), a user of the software may have to
699 * customize potentially hundreds of messages in
700 * order to, e.g., fix a link in every possible language.
702 * @param $key String: lookup key for the message, usually
703 * defined in languages/Language.php
705 function wfMsgForContent( $key ) {
706 global $wgForceUIMsgAsContentMsg;
707 $args = func_get_args();
708 array_shift( $args );
710 if( is_array( $wgForceUIMsgAsContentMsg ) &&
711 in_array( $key, $wgForceUIMsgAsContentMsg ) )
715 return wfMsgReal( $key, $args, true, $forcontent );
719 * Same as above except doesn't transform the message
721 function wfMsgForContentNoTrans( $key ) {
722 global $wgForceUIMsgAsContentMsg;
723 $args = func_get_args();
724 array_shift( $args );
726 if( is_array( $wgForceUIMsgAsContentMsg ) &&
727 in_array( $key, $wgForceUIMsgAsContentMsg ) )
731 return wfMsgReal( $key, $args, true, $forcontent, false );
735 * Get a message from the language file, for the UI elements
737 function wfMsgNoDB( $key ) {
738 $args = func_get_args();
739 array_shift( $args );
740 return wfMsgReal( $key, $args, false );
744 * Get a message from the language file, for the content
746 function wfMsgNoDBForContent( $key ) {
747 global $wgForceUIMsgAsContentMsg;
748 $args = func_get_args();
749 array_shift( $args );
751 if( is_array( $wgForceUIMsgAsContentMsg ) &&
752 in_array( $key, $wgForceUIMsgAsContentMsg ) )
756 return wfMsgReal( $key, $args, false, $forcontent );
761 * Really get a message
762 * @param $key String: key to get.
764 * @param $useDB Boolean
765 * @param $forContent Mixed: Language code, or false for user lang, true for content lang.
766 * @param $transform Boolean: Whether or not to transform the message.
767 * @return String: the requested message.
769 function wfMsgReal( $key, $args, $useDB = true, $forContent = false, $transform = true ) {
770 wfProfileIn( __METHOD__
);
771 $message = wfMsgGetKey( $key, $useDB, $forContent, $transform );
772 $message = wfMsgReplaceArgs( $message, $args );
773 wfProfileOut( __METHOD__
);
778 * This function provides the message source for messages to be edited which are *not* stored in the database.
779 * @param $key String:
781 function wfMsgWeirdKey( $key ) {
782 $source = wfMsgGetKey( $key, false, true, false );
783 if ( wfEmptyMsg( $key, $source ) ) {
791 * Fetch a message string value, but don't replace any keys yet.
794 * @param $langCode String: Code of the language to get the message for, or
795 * behaves as a content language switch if it is a boolean.
796 * @param $transform Boolean: whether to parse magic words, etc.
799 function wfMsgGetKey( $key, $useDB, $langCode = false, $transform = true ) {
800 global $wgMessageCache;
802 wfRunHooks( 'NormalizeMessageKey', array( &$key, &$useDB, &$langCode, &$transform ) );
804 if ( !is_object( $wgMessageCache ) ) {
805 throw new MWException( 'Trying to get message before message cache is initialised' );
808 $message = $wgMessageCache->get( $key, $useDB, $langCode );
809 if( $message === false ) {
810 $message = '<' . htmlspecialchars( $key ) . '>';
811 } elseif ( $transform ) {
812 $message = $wgMessageCache->transform( $message );
818 * Replace message parameter keys on the given formatted output.
820 * @param $message String
825 function wfMsgReplaceArgs( $message, $args ) {
826 # Fix windows line-endings
827 # Some messages are split with explode("\n", $msg)
828 $message = str_replace( "\r", '', $message );
831 if ( count( $args ) ) {
832 if ( is_array( $args[0] ) ) {
833 $args = array_values( $args[0] );
835 $replacementKeys = array();
836 foreach( $args as $n => $param ) {
837 $replacementKeys['$' . ( $n +
1 )] = $param;
839 $message = strtr( $message, $replacementKeys );
846 * Return an HTML-escaped version of a message.
847 * Parameter replacements, if any, are done *after* the HTML-escaping,
848 * so parameters may contain HTML (eg links or form controls). Be sure
849 * to pre-escape them if you really do want plaintext, or just wrap
850 * the whole thing in htmlspecialchars().
853 * @param string ... parameters
856 function wfMsgHtml( $key ) {
857 $args = func_get_args();
858 array_shift( $args );
859 return wfMsgReplaceArgs( htmlspecialchars( wfMsgGetKey( $key, true ) ), $args );
863 * Return an HTML version of message
864 * Parameter replacements, if any, are done *after* parsing the wiki-text message,
865 * so parameters may contain HTML (eg links or form controls). Be sure
866 * to pre-escape them if you really do want plaintext, or just wrap
867 * the whole thing in htmlspecialchars().
870 * @param string ... parameters
873 function wfMsgWikiHtml( $key ) {
875 $args = func_get_args();
876 array_shift( $args );
877 return wfMsgReplaceArgs( $wgOut->parse( wfMsgGetKey( $key, true ), /* can't be set to false */ true ), $args );
881 * Returns message in the requested format
882 * @param $key String: key of the message
883 * @param $options Array: processing rules. Can take the following options:
884 * <i>parse</i>: parses wikitext to HTML
885 * <i>parseinline</i>: parses wikitext to HTML and removes the surrounding
886 * p's added by parser or tidy
887 * <i>escape</i>: filters message through htmlspecialchars
888 * <i>escapenoentities</i>: same, but allows entity references like   through
889 * <i>replaceafter</i>: parameters are substituted after parsing or escaping
890 * <i>parsemag</i>: transform the message using magic phrases
891 * <i>content</i>: fetch message for content language instead of interface
892 * Also can accept a single associative argument, of the form 'language' => 'xx':
893 * <i>language</i>: Language object or language code to fetch message for
894 * (overriden by <i>content</i>), its behaviour with parse, parseinline
895 * and parsemag is undefined.
896 * Behavior for conflicting options (e.g., parse+parseinline) is undefined.
898 function wfMsgExt( $key, $options ) {
901 $args = func_get_args();
902 array_shift( $args );
903 array_shift( $args );
904 $options = (array)$options;
906 foreach( $options as $arrayKey => $option ) {
907 if( !preg_match( '/^[0-9]+|language$/', $arrayKey ) ) {
908 # An unknown index, neither numeric nor "language"
909 wfWarn( "wfMsgExt called with incorrect parameter key $arrayKey", 1, E_USER_WARNING
);
910 } elseif( preg_match( '/^[0-9]+$/', $arrayKey ) && !in_array( $option,
911 array( 'parse', 'parseinline', 'escape', 'escapenoentities',
912 'replaceafter', 'parsemag', 'content' ) ) ) {
913 # A numeric index with unknown value
914 wfWarn( "wfMsgExt called with incorrect parameter $option", 1, E_USER_WARNING
);
918 if( in_array( 'content', $options, true ) ) {
921 } elseif( array_key_exists( 'language', $options ) ) {
923 $langCode = wfGetLangObj( $options['language'] );
929 $string = wfMsgGetKey( $key, /*DB*/true, $langCode, /*Transform*/false );
931 if( !in_array( 'replaceafter', $options, true ) ) {
932 $string = wfMsgReplaceArgs( $string, $args );
935 if( in_array( 'parse', $options, true ) ) {
936 $string = $wgOut->parse( $string, true, !$forContent );
937 } elseif ( in_array( 'parseinline', $options, true ) ) {
938 $string = $wgOut->parse( $string, true, !$forContent );
940 if( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $string, $m ) ) {
943 } elseif ( in_array( 'parsemag', $options, true ) ) {
944 global $wgMessageCache;
945 if ( isset( $wgMessageCache ) ) {
946 $string = $wgMessageCache->transform( $string,
948 is_object( $langCode ) ?
$langCode : null );
952 if ( in_array( 'escape', $options, true ) ) {
953 $string = htmlspecialchars ( $string );
954 } elseif ( in_array( 'escapenoentities', $options, true ) ) {
955 $string = Sanitizer
::escapeHtmlAllowEntities( $string );
958 if( in_array( 'replaceafter', $options, true ) ) {
959 $string = wfMsgReplaceArgs( $string, $args );
967 * Just like exit() but makes a note of it.
968 * Commits open transactions except if the error parameter is set
970 * @deprecated Please return control to the caller or throw an exception. Will
971 * be removed in 1.19.
973 function wfAbruptExit( $error = false ) {
974 static $called = false;
980 wfDeprecated( __FUNCTION__
);
981 $bt = wfDebugBacktrace();
983 for( $i = 0; $i < count( $bt ); $i++
) {
984 $file = isset( $bt[$i]['file'] ) ?
$bt[$i]['file'] : 'unknown';
985 $line = isset( $bt[$i]['line'] ) ?
$bt[$i]['line'] : 'unknown';
986 wfDebug( "WARNING: Abrupt exit in $file at line $line\n");
989 wfDebug( "WARNING: Abrupt exit\n" );
992 wfLogProfilingData();
995 wfGetLB()->closeAll();
1001 * @deprecated Please return control the caller or throw an exception. Will
1002 * be removed in 1.19.
1004 function wfErrorExit() {
1005 wfDeprecated( __FUNCTION__
);
1006 wfAbruptExit( true );
1010 * Print a simple message and die, returning nonzero to the shell if any.
1011 * Plain die() fails to return nonzero to the shell if you pass a string.
1012 * @param $msg String
1014 function wfDie( $msg = '' ) {
1020 * Throw a debugging exception. This function previously once exited the process,
1021 * but now throws an exception instead, with similar results.
1023 * @param $msg String: message shown when dieing.
1025 function wfDebugDieBacktrace( $msg = '' ) {
1026 throw new MWException( $msg );
1030 * Fetch server name for use in error reporting etc.
1031 * Use real server name if available, so we know which machine
1032 * in a server farm generated the current page.
1035 function wfHostname() {
1037 if ( is_null( $host ) ) {
1038 if ( function_exists( 'posix_uname' ) ) {
1039 // This function not present on Windows
1040 $uname = @posix_uname
();
1044 if( is_array( $uname ) && isset( $uname['nodename'] ) ) {
1045 $host = $uname['nodename'];
1046 } elseif ( getenv( 'COMPUTERNAME' ) ) {
1047 # Windows computer name
1048 $host = getenv( 'COMPUTERNAME' );
1050 # This may be a virtual server.
1051 $host = $_SERVER['SERVER_NAME'];
1058 * Returns a HTML comment with the elapsed time since request.
1059 * This method has no side effects.
1062 function wfReportTime() {
1063 global $wgRequestTime, $wgShowHostnames;
1066 $elapsed = $now - $wgRequestTime;
1068 return $wgShowHostnames
1069 ?
sprintf( '<!-- Served by %s in %01.3f secs. -->', wfHostname(), $elapsed )
1070 : sprintf( '<!-- Served in %01.3f secs. -->', $elapsed );
1074 * Safety wrapper for debug_backtrace().
1076 * With Zend Optimizer 3.2.0 loaded, this causes segfaults under somewhat
1077 * murky circumstances, which may be triggered in part by stub objects
1078 * or other fancy talkin'.
1080 * Will return an empty array if Zend Optimizer is detected or if
1081 * debug_backtrace is disabled, otherwise the output from
1082 * debug_backtrace() (trimmed).
1084 * @return array of backtrace information
1086 function wfDebugBacktrace() {
1087 static $disabled = null;
1089 if( extension_loaded( 'Zend Optimizer' ) ) {
1090 wfDebug( "Zend Optimizer detected; skipping debug_backtrace for safety.\n" );
1094 if ( is_null( $disabled ) ) {
1096 $functions = explode( ',', ini_get( 'disable_functions' ) );
1097 $functions = array_map( 'trim', $functions );
1098 $functions = array_map( 'strtolower', $functions );
1099 if ( in_array( 'debug_backtrace', $functions ) ) {
1100 wfDebug( "debug_backtrace is in disabled_functions\n" );
1108 return array_slice( debug_backtrace(), 1 );
1111 function wfBacktrace() {
1112 global $wgCommandLineMode;
1114 if ( $wgCommandLineMode ) {
1119 $backtrace = wfDebugBacktrace();
1120 foreach( $backtrace as $call ) {
1121 if( isset( $call['file'] ) ) {
1122 $f = explode( DIRECTORY_SEPARATOR
, $call['file'] );
1123 $file = $f[count( $f ) - 1];
1127 if( isset( $call['line'] ) ) {
1128 $line = $call['line'];
1132 if ( $wgCommandLineMode ) {
1133 $msg .= "$file line $line calls ";
1135 $msg .= '<li>' . $file . ' line ' . $line . ' calls ';
1137 if( !empty( $call['class'] ) ) {
1138 $msg .= $call['class'] . '::';
1140 $msg .= $call['function'] . '()';
1142 if ( $wgCommandLineMode ) {
1148 if ( $wgCommandLineMode ) {
1158 /* Some generic result counters, pulled out of SearchEngine */
1164 function wfShowingResults( $offset, $limit ) {
1168 array( 'parseinline' ),
1169 $wgLang->formatNum( $limit ),
1170 $wgLang->formatNum( $offset +
1 )
1177 function wfShowingResultsNum( $offset, $limit, $num ) {
1180 'showingresultsnum',
1181 array( 'parseinline' ),
1182 $wgLang->formatNum( $limit ),
1183 $wgLang->formatNum( $offset +
1 ),
1184 $wgLang->formatNum( $num )
1189 * Generate (prev x| next x) (20|50|100...) type links for paging
1190 * @param $offset String
1191 * @param $limit Integer
1192 * @param $link String
1193 * @param $query String: optional URL query parameter string
1194 * @param $atend Bool: optional param for specified if this is the last page
1196 function wfViewPrevNext( $offset, $limit, $link, $query = '', $atend = false ) {
1198 $fmtLimit = $wgLang->formatNum( $limit );
1199 // FIXME: Why on earth this needs one message for the text and another one for tooltip??
1200 # Get prev/next link display text
1201 $prev = wfMsgExt( 'prevn', array( 'parsemag', 'escape' ), $fmtLimit );
1202 $next = wfMsgExt( 'nextn', array( 'parsemag', 'escape' ), $fmtLimit );
1203 # Get prev/next link title text
1204 $pTitle = wfMsgExt( 'prevn-title', array( 'parsemag', 'escape' ), $fmtLimit );
1205 $nTitle = wfMsgExt( 'nextn-title', array( 'parsemag', 'escape' ), $fmtLimit );
1206 # Fetch the title object
1207 if( is_object( $link ) ) {
1210 $title = Title
::newFromText( $link );
1211 if( is_null( $title ) ) {
1215 # Make 'previous' link
1216 if( 0 != $offset ) {
1217 $po = $offset - $limit;
1218 $po = max( $po, 0 );
1219 $q = "limit={$limit}&offset={$po}";
1220 if( $query != '' ) {
1223 $plink = '<a href="' . $title->escapeLocalURL( $q ) . "\" title=\"{$pTitle}\" class=\"mw-prevlink\">{$prev}</a>";
1228 $no = $offset +
$limit;
1229 $q = "limit={$limit}&offset={$no}";
1230 if( $query != '' ) {
1236 $nlink = '<a href="' . $title->escapeLocalURL( $q ) . "\" title=\"{$nTitle}\" class=\"mw-nextlink\">{$next}</a>";
1238 # Make links to set number of items per page
1239 $nums = $wgLang->pipeList( array(
1240 wfNumLink( $offset, 20, $title, $query ),
1241 wfNumLink( $offset, 50, $title, $query ),
1242 wfNumLink( $offset, 100, $title, $query ),
1243 wfNumLink( $offset, 250, $title, $query ),
1244 wfNumLink( $offset, 500, $title, $query )
1246 return wfMsgHtml( 'viewprevnext', $plink, $nlink, $nums );
1250 * Generate links for (20|50|100...) items-per-page links
1251 * @param $offset String
1252 * @param $limit Integer
1253 * @param $title Title
1254 * @param $query String: optional URL query parameter string
1256 function wfNumLink( $offset, $limit, $title, $query = '' ) {
1258 if( $query == '' ) {
1263 $q .= "limit={$limit}&offset={$offset}";
1264 $fmtLimit = $wgLang->formatNum( $limit );
1265 $lTitle = wfMsgExt( 'shown-title', array( 'parsemag', 'escape' ), $limit );
1266 $s = '<a href="' . $title->escapeLocalURL( $q ) . "\" title=\"{$lTitle}\" class=\"mw-numlink\">{$fmtLimit}</a>";
1272 * @todo FIXME: we may want to blacklist some broken browsers
1274 * @return bool Whereas client accept gzip compression
1276 function wfClientAcceptsGzip() {
1277 static $result = null;
1278 if ( $result === null ) {
1280 if( isset( $_SERVER['HTTP_ACCEPT_ENCODING'] ) ) {
1281 # FIXME: we may want to blacklist some broken browsers
1284 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
1285 $_SERVER['HTTP_ACCEPT_ENCODING'],
1289 if( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) {
1293 wfDebug( " accepts gzip\n" );
1302 * Obtain the offset and limit values from the request string;
1303 * used in special pages
1305 * @param $deflimit Default limit if none supplied
1306 * @param $optionname Name of a user preference to check against
1310 function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) {
1312 return $wgRequest->getLimitOffset( $deflimit, $optionname );
1316 * Escapes the given text so that it may be output using addWikiText()
1317 * without any linking, formatting, etc. making its way through. This
1318 * is achieved by substituting certain characters with HTML entities.
1319 * As required by the callers, <nowiki> is not used. It currently does
1320 * not filter out characters which have special meaning only at the
1321 * start of a line, such as "*".
1323 * @param $text String: text to be escaped
1325 function wfEscapeWikiText( $text ) {
1326 $text = str_replace(
1327 array( '[', '|', ']', '\'', 'ISBN ',
1328 'RFC ', '://', "\n=", '{{', '}}' ),
1329 array( '[', '|', ']', ''', 'ISBN ',
1330 'RFC ', '://', "\n=", '{{', '}}' ),
1331 htmlspecialchars( $text )
1341 return microtime( true );
1345 * Sets dest to source and returns the original value of dest
1346 * If source is NULL, it just returns the value, it doesn't set the variable
1347 * If force is true, it will set the value even if source is NULL
1349 function wfSetVar( &$dest, $source, $force = false ) {
1351 if ( !is_null( $source ) ||
$force ) {
1358 * As for wfSetVar except setting a bit
1360 function wfSetBit( &$dest, $bit, $state = true ) {
1361 $temp = (bool)( $dest & $bit );
1362 if ( !is_null( $state ) ) {
1373 * This function takes two arrays as input, and returns a CGI-style string, e.g.
1374 * "days=7&limit=100". Options in the first array override options in the second.
1375 * Options set to "" will not be output.
1377 function wfArrayToCGI( $array1, $array2 = null ) {
1378 if ( !is_null( $array2 ) ) {
1379 $array1 = $array1 +
$array2;
1383 foreach ( $array1 as $key => $value ) {
1384 if ( $value !== '' ) {
1388 if ( is_array( $value ) ) {
1390 foreach ( $value as $v ) {
1391 $cgi .= ( $firstTime ?
'' : '&') .
1392 urlencode( $key . '[]' ) . '=' .
1397 if ( is_object( $value ) ) {
1398 $value = $value->__toString();
1400 $cgi .= urlencode( $key ) . '=' .
1401 urlencode( $value );
1409 * This is the logical opposite of wfArrayToCGI(): it accepts a query string as
1410 * its argument and returns the same string in array form. This allows compa-
1411 * tibility with legacy functions that accept raw query strings instead of nice
1412 * arrays. Of course, keys and values are urldecode()d. Don't try passing in-
1413 * valid query strings, or it will explode.
1415 * @param $query String: query string
1416 * @return array Array version of input
1418 function wfCgiToArray( $query ) {
1419 if( isset( $query[0] ) && $query[0] == '?' ) {
1420 $query = substr( $query, 1 );
1422 $bits = explode( '&', $query );
1424 foreach( $bits as $bit ) {
1428 list( $key, $value ) = explode( '=', $bit );
1429 $key = urldecode( $key );
1430 $value = urldecode( $value );
1431 $ret[$key] = $value;
1437 * Append a query string to an existing URL, which may or may not already
1438 * have query string parameters already. If so, they will be combined.
1440 * @param $url String
1441 * @param $query Mixed: string or associative array
1444 function wfAppendQuery( $url, $query ) {
1445 if ( is_array( $query ) ) {
1446 $query = wfArrayToCGI( $query );
1448 if( $query != '' ) {
1449 if( false === strpos( $url, '?' ) ) {
1460 * Expand a potentially local URL to a fully-qualified URL. Assumes $wgServer
1461 * and $wgProto are correct.
1463 * @todo this won't work with current-path-relative URLs
1464 * like "subdir/foo.html", etc.
1466 * @param $url String: either fully-qualified or a local path + query
1467 * @return string Fully-qualified URL
1469 function wfExpandUrl( $url ) {
1470 if( substr( $url, 0, 2 ) == '//' ) {
1472 return $wgProto . ':' . $url;
1473 } elseif( substr( $url, 0, 1 ) == '/' ) {
1475 return $wgServer . $url;
1482 * Windows-compatible version of escapeshellarg()
1483 * Windows doesn't recognise single-quotes in the shell, but the escapeshellarg()
1484 * function puts single quotes in regardless of OS.
1486 * Also fixes the locale problems on Linux in PHP 5.2.6+ (bug backported to
1487 * earlier distro releases of PHP)
1489 function wfEscapeShellArg( ) {
1490 wfInitShellLocale();
1492 $args = func_get_args();
1495 foreach ( $args as $arg ) {
1502 if ( wfIsWindows() ) {
1503 // Escaping for an MSVC-style command line parser and CMD.EXE
1505 // * http://web.archive.org/web/20020708081031/http://mailman.lyra.org/pipermail/scite-interest/2002-March/000436.html
1506 // * http://technet.microsoft.com/en-us/library/cc723564.aspx
1509 // Double the backslashes before any double quotes. Escape the double quotes.
1510 $tokens = preg_split( '/(\\\\*")/', $arg, -1, PREG_SPLIT_DELIM_CAPTURE
);
1513 foreach ( $tokens as $token ) {
1514 if ( $iteration %
2 == 1 ) {
1515 // Delimiter, a double quote preceded by zero or more slashes
1516 $arg .= str_replace( '\\', '\\\\', substr( $token, 0, -1 ) ) . '\\"';
1517 } elseif ( $iteration %
4 == 2 ) {
1518 // ^ in $token will be outside quotes, need to be escaped
1519 $arg .= str_replace( '^', '^^', $token );
1520 } else { // $iteration % 4 == 0
1521 // ^ in $token will appear inside double quotes, so leave as is
1526 // Double the backslashes before the end of the string, because
1527 // we will soon add a quote
1529 if ( preg_match( '/^(.*?)(\\\\+)$/', $arg, $m ) ) {
1530 $arg = $m[1] . str_replace( '\\', '\\\\', $m[2] );
1533 // Add surrounding quotes
1534 $retVal .= '"' . $arg . '"';
1536 $retVal .= escapeshellarg( $arg );
1543 * wfMerge attempts to merge differences between three texts.
1544 * Returns true for a clean merge and false for failure or a conflict.
1546 function wfMerge( $old, $mine, $yours, &$result ) {
1549 # This check may also protect against code injection in
1550 # case of broken installations.
1551 wfSuppressWarnings();
1552 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
1553 wfRestoreWarnings();
1556 wfDebug( "diff3 not found\n" );
1560 # Make temporary files
1562 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
1563 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
1564 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
1566 fwrite( $oldtextFile, $old );
1567 fclose( $oldtextFile );
1568 fwrite( $mytextFile, $mine );
1569 fclose( $mytextFile );
1570 fwrite( $yourtextFile, $yours );
1571 fclose( $yourtextFile );
1573 # Check for a conflict
1574 $cmd = $wgDiff3 . ' -a --overlap-only ' .
1575 wfEscapeShellArg( $mytextName ) . ' ' .
1576 wfEscapeShellArg( $oldtextName ) . ' ' .
1577 wfEscapeShellArg( $yourtextName );
1578 $handle = popen( $cmd, 'r' );
1580 if( fgets( $handle, 1024 ) ) {
1588 $cmd = $wgDiff3 . ' -a -e --merge ' .
1589 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
1590 $handle = popen( $cmd, 'r' );
1593 $data = fread( $handle, 8192 );
1594 if ( strlen( $data ) == 0 ) {
1600 unlink( $mytextName );
1601 unlink( $oldtextName );
1602 unlink( $yourtextName );
1604 if ( $result === '' && $old !== '' && !$conflict ) {
1605 wfDebug( "Unexpected null result from diff3. Command: $cmd\n" );
1612 * Returns unified plain-text diff of two texts.
1613 * Useful for machine processing of diffs.
1614 * @param $before String: the text before the changes.
1615 * @param $after String: the text after the changes.
1616 * @param $params String: command-line options for the diff command.
1617 * @return String: unified diff of $before and $after
1619 function wfDiff( $before, $after, $params = '-u' ) {
1620 if ( $before == $after ) {
1625 wfSuppressWarnings();
1626 $haveDiff = $wgDiff && file_exists( $wgDiff );
1627 wfRestoreWarnings();
1629 # This check may also protect against code injection in
1630 # case of broken installations.
1632 wfDebug( "diff executable not found\n" );
1633 $diffs = new Diff( explode( "\n", $before ), explode( "\n", $after ) );
1634 $format = new UnifiedDiffFormatter();
1635 return $format->format( $diffs );
1638 # Make temporary files
1640 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
1641 $newtextFile = fopen( $newtextName = tempnam( $td, 'merge-your-' ), 'w' );
1643 fwrite( $oldtextFile, $before );
1644 fclose( $oldtextFile );
1645 fwrite( $newtextFile, $after );
1646 fclose( $newtextFile );
1648 // Get the diff of the two files
1649 $cmd = "$wgDiff " . $params . ' ' . wfEscapeShellArg( $oldtextName, $newtextName );
1651 $h = popen( $cmd, 'r' );
1656 $data = fread( $h, 8192 );
1657 if ( strlen( $data ) == 0 ) {
1665 unlink( $oldtextName );
1666 unlink( $newtextName );
1668 // Kill the --- and +++ lines. They're not useful.
1669 $diff_lines = explode( "\n", $diff );
1670 if ( strpos( $diff_lines[0], '---' ) === 0 ) {
1671 unset( $diff_lines[0] );
1673 if ( strpos( $diff_lines[1], '+++' ) === 0 ) {
1674 unset( $diff_lines[1] );
1677 $diff = implode( "\n", $diff_lines );
1683 * A wrapper around the PHP function var_export().
1684 * Either print it or add it to the regular output ($wgOut).
1686 * @param $var A PHP variable to dump.
1688 function wfVarDump( $var ) {
1690 $s = str_replace( "\n", "<br />\n", var_export( $var, true ) . "\n" );
1691 if ( headers_sent() ||
!@is_object
( $wgOut ) ) {
1694 $wgOut->addHTML( $s );
1699 * Provide a simple HTTP error.
1701 function wfHttpError( $code, $label, $desc ) {
1704 header( "HTTP/1.0 $code $label" );
1705 header( "Status: $code $label" );
1706 $wgOut->sendCacheControl();
1708 header( 'Content-type: text/html; charset=utf-8' );
1709 print "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">".
1710 '<html><head><title>' .
1711 htmlspecialchars( $label ) .
1712 '</title></head><body><h1>' .
1713 htmlspecialchars( $label ) .
1715 nl2br( htmlspecialchars( $desc ) ) .
1716 "</p></body></html>\n";
1720 * Clear away any user-level output buffers, discarding contents.
1722 * Suitable for 'starting afresh', for instance when streaming
1723 * relatively large amounts of data without buffering, or wanting to
1724 * output image files without ob_gzhandler's compression.
1726 * The optional $resetGzipEncoding parameter controls suppression of
1727 * the Content-Encoding header sent by ob_gzhandler; by default it
1728 * is left. See comments for wfClearOutputBuffers() for why it would
1731 * Note that some PHP configuration options may add output buffer
1732 * layers which cannot be removed; these are left in place.
1734 * @param $resetGzipEncoding Bool
1736 function wfResetOutputBuffers( $resetGzipEncoding = true ) {
1737 if( $resetGzipEncoding ) {
1738 // Suppress Content-Encoding and Content-Length
1739 // headers from 1.10+s wfOutputHandler
1740 global $wgDisableOutputCompression;
1741 $wgDisableOutputCompression = true;
1743 while( $status = ob_get_status() ) {
1744 if( $status['type'] == 0 /* PHP_OUTPUT_HANDLER_INTERNAL */ ) {
1745 // Probably from zlib.output_compression or other
1746 // PHP-internal setting which can't be removed.
1748 // Give up, and hope the result doesn't break
1752 if( !ob_end_clean() ) {
1753 // Could not remove output buffer handler; abort now
1754 // to avoid getting in some kind of infinite loop.
1757 if( $resetGzipEncoding ) {
1758 if( $status['name'] == 'ob_gzhandler' ) {
1759 // Reset the 'Content-Encoding' field set by this handler
1760 // so we can start fresh.
1761 header( 'Content-Encoding:' );
1769 * More legible than passing a 'false' parameter to wfResetOutputBuffers():
1771 * Clear away output buffers, but keep the Content-Encoding header
1772 * produced by ob_gzhandler, if any.
1774 * This should be used for HTTP 304 responses, where you need to
1775 * preserve the Content-Encoding header of the real result, but
1776 * also need to suppress the output of ob_gzhandler to keep to spec
1777 * and avoid breaking Firefox in rare cases where the headers and
1778 * body are broken over two packets.
1780 function wfClearOutputBuffers() {
1781 wfResetOutputBuffers( false );
1785 * Converts an Accept-* header into an array mapping string values to quality
1788 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
1789 # No arg means accept anything (per HTTP spec)
1791 return array( $def => 1.0 );
1796 $parts = explode( ',', $accept );
1798 foreach( $parts as $part ) {
1799 # FIXME: doesn't deal with params like 'text/html; level=1'
1800 @list
( $value, $qpart ) = explode( ';', trim( $part ) );
1802 if( !isset( $qpart ) ) {
1803 $prefs[$value] = 1.0;
1804 } elseif( preg_match( '/q\s*=\s*(\d*\.\d+)/', $qpart, $match ) ) {
1805 $prefs[$value] = floatval( $match[1] );
1813 * Checks if a given MIME type matches any of the keys in the given
1814 * array. Basic wildcards are accepted in the array keys.
1816 * Returns the matching MIME type (or wildcard) if a match, otherwise
1819 * @param $type String
1820 * @param $avail Array
1824 function mimeTypeMatch( $type, $avail ) {
1825 if( array_key_exists( $type, $avail ) ) {
1828 $parts = explode( '/', $type );
1829 if( array_key_exists( $parts[0] . '/*', $avail ) ) {
1830 return $parts[0] . '/*';
1831 } elseif( array_key_exists( '*/*', $avail ) ) {
1840 * Returns the 'best' match between a client's requested internet media types
1841 * and the server's list of available types. Each list should be an associative
1842 * array of type to preference (preference is a float between 0.0 and 1.0).
1843 * Wildcards in the types are acceptable.
1845 * @param $cprefs Array: client's acceptable type list
1846 * @param $sprefs Array: server's offered types
1849 * @todo FIXME: doesn't handle params like 'text/plain; charset=UTF-8'
1850 * XXX: generalize to negotiate other stuff
1852 function wfNegotiateType( $cprefs, $sprefs ) {
1855 foreach( array_keys($sprefs) as $type ) {
1856 $parts = explode( '/', $type );
1857 if( $parts[1] != '*' ) {
1858 $ckey = mimeTypeMatch( $type, $cprefs );
1860 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1865 foreach( array_keys( $cprefs ) as $type ) {
1866 $parts = explode( '/', $type );
1867 if( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
1868 $skey = mimeTypeMatch( $type, $sprefs );
1870 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1878 foreach( array_keys( $combine ) as $type ) {
1879 if( $combine[$type] > $bestq ) {
1881 $bestq = $combine[$type];
1890 * Returns an array where the values in the first array are replaced by the
1891 * values in the second array with the corresponding keys
1895 function wfArrayLookup( $a, $b ) {
1896 return array_flip( array_intersect( array_flip( $a ), array_keys( $b ) ) );
1900 * Convenience function; returns MediaWiki timestamp for the present time.
1903 function wfTimestampNow() {
1905 return wfTimestamp( TS_MW
, time() );
1909 * Reference-counted warning suppression
1911 function wfSuppressWarnings( $end = false ) {
1912 static $suppressCount = 0;
1913 static $originalLevel = false;
1916 if ( $suppressCount ) {
1918 if ( !$suppressCount ) {
1919 error_reporting( $originalLevel );
1923 if ( !$suppressCount ) {
1924 $originalLevel = error_reporting( E_ALL
& ~
( E_WARNING | E_NOTICE | E_USER_WARNING | E_USER_NOTICE
) );
1931 * Restore error level to previous value
1933 function wfRestoreWarnings() {
1934 wfSuppressWarnings( true );
1937 # Autodetect, convert and provide timestamps of various types
1940 * Unix time - the number of seconds since 1970-01-01 00:00:00 UTC
1942 define( 'TS_UNIX', 0 );
1945 * MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
1947 define( 'TS_MW', 1 );
1950 * MySQL DATETIME (YYYY-MM-DD HH:MM:SS)
1952 define( 'TS_DB', 2 );
1955 * RFC 2822 format, for E-mail and HTTP headers
1957 define( 'TS_RFC2822', 3 );
1960 * ISO 8601 format with no timezone: 1986-02-09T20:00:00Z
1962 * This is used by Special:Export
1964 define( 'TS_ISO_8601', 4 );
1967 * An Exif timestamp (YYYY:MM:DD HH:MM:SS)
1969 * @see http://exif.org/Exif2-2.PDF The Exif 2.2 spec, see page 28 for the
1970 * DateTime tag and page 36 for the DateTimeOriginal and
1971 * DateTimeDigitized tags.
1973 define( 'TS_EXIF', 5 );
1976 * Oracle format time.
1978 define( 'TS_ORACLE', 6 );
1981 * Postgres format time.
1983 define( 'TS_POSTGRES', 7 );
1988 define( 'TS_DB2', 8 );
1991 * ISO 8601 basic format with no timezone: 19860209T200000Z
1993 * This is used by ResourceLoader
1995 define( 'TS_ISO_8601_BASIC', 9 );
1998 * @param $outputtype Mixed: A timestamp in one of the supported formats, the
1999 * function will autodetect which format is supplied and act
2001 * @param $ts Mixed: the timestamp to convert or 0 for the current timestamp
2002 * @return Mixed: String / false The same date in the format specified in $outputtype or false
2004 function wfTimestamp( $outputtype = TS_UNIX
, $ts = 0 ) {
2009 if ( !$ts ) { // We want to catch 0, '', null... but not date strings starting with a letter.
2012 } elseif ( preg_match( '/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)$/D', $ts, $da ) ) {
2014 } elseif ( preg_match( '/^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/D', $ts, $da ) ) {
2016 } elseif ( preg_match( '/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/D', $ts, $da ) ) {
2018 } elseif ( preg_match( '/^-?\d{1,13}$/D', $ts ) ) {
2021 $strtime = "@$ts"; // Undocumented?
2022 } elseif ( preg_match( '/^\d{2}-\d{2}-\d{4} \d{2}:\d{2}:\d{2}.\d{6}$/', $ts ) ) {
2023 # TS_ORACLE // session altered to DD-MM-YYYY HH24:MI:SS.FF6
2024 $strtime = preg_replace( '/(\d\d)\.(\d\d)\.(\d\d)(\.(\d+))?/', "$1:$2:$3",
2025 str_replace( '+00:00', 'UTC', $ts ) );
2026 } elseif ( preg_match( '/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.*\d*)?Z$/', $ts, $da ) ) {
2028 } elseif ( preg_match( '/^(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})(?:\.*\d*)?Z$/', $ts, $da ) ) {
2030 } elseif ( preg_match( '/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.*\d*[\+\- ](\d\d)$/', $ts, $da ) ) {
2032 } elseif ( preg_match( '/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.*\d* GMT$/', $ts, $da ) ) {
2034 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.\d\d\d$/',$ts,$da)) {
2036 } elseif ( preg_match( '/^[ \t\r\n]*([A-Z][a-z]{2},[ \t\r\n]*)?' . # Day of week
2037 '\d\d?[ \t\r\n]*[A-Z][a-z]{2}[ \t\r\n]*\d{2}(?:\d{2})?' . # dd Mon yyyy
2038 '[ \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
2039 # TS_RFC2822, accepting a trailing comment. See http://www.squid-cache.org/mail-archive/squid-users/200307/0122.html / r77171
2040 # The regex is a superset of rfc2822 for readability
2041 $strtime = strtok( $ts, ';' );
2042 } 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 ) ) {
2045 } 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 ) ) {
2050 wfDebug("wfTimestamp() fed bogus time value: TYPE=$outputtype; VALUE=$ts\n");
2057 static $formats = array(
2060 TS_DB
=> 'Y-m-d H:i:s',
2061 TS_ISO_8601
=> 'Y-m-d\TH:i:s\Z',
2062 TS_ISO_8601_BASIC
=> 'Ymd\THis\Z',
2063 TS_EXIF
=> 'Y:m:d H:i:s', // This shouldn't ever be used, but is included for completeness
2064 TS_RFC2822
=> 'D, d M Y H:i:s',
2065 TS_ORACLE
=> 'd-m-Y H:i:s.000000', // Was 'd-M-y h.i.s A' . ' +00:00' before r51500
2066 TS_POSTGRES
=> 'Y-m-d H:i:s',
2067 TS_DB2
=> 'Y-m-d H:i:s',
2070 if ( !isset( $formats[$outputtype] ) ) {
2071 throw new MWException( 'wfTimestamp() called with illegal output type.' );
2074 if ( function_exists( "date_create" ) ) {
2075 if ( count( $da ) ) {
2076 $ds = sprintf("%04d-%02d-%02dT%02d:%02d:%02d.00+00:00",
2077 (int)$da[1], (int)$da[2], (int)$da[3],
2078 (int)$da[4], (int)$da[5], (int)$da[6]);
2080 $d = date_create( $ds, new DateTimeZone( 'GMT' ) );
2081 } elseif ( $strtime ) {
2082 $d = date_create( $strtime, new DateTimeZone( 'GMT' ) );
2088 wfDebug("wfTimestamp() fed bogus time value: $outputtype; $ts\n");
2092 $output = $d->format( $formats[$outputtype] );
2094 if ( count( $da ) ) {
2095 // Warning! gmmktime() acts oddly if the month or day is set to 0
2096 // We may want to handle that explicitly at some point
2097 $uts = gmmktime( (int)$da[4], (int)$da[5], (int)$da[6],
2098 (int)$da[2], (int)$da[3], (int)$da[1] );
2099 } elseif ( $strtime ) {
2100 $uts = strtotime( $strtime );
2103 if ( $uts === false ) {
2104 wfDebug("wfTimestamp() can't parse the timestamp (non 32-bit time? Update php): $outputtype; $ts\n");
2108 if ( TS_UNIX
== $outputtype ) {
2111 $output = gmdate( $formats[$outputtype], $uts );
2114 if ( ( $outputtype == TS_RFC2822
) ||
( $outputtype == TS_POSTGRES
) ) {
2122 * Return a formatted timestamp, or null if input is null.
2123 * For dealing with nullable timestamp columns in the database.
2124 * @param $outputtype Integer
2128 function wfTimestampOrNull( $outputtype = TS_UNIX
, $ts = null ) {
2129 if( is_null( $ts ) ) {
2132 return wfTimestamp( $outputtype, $ts );
2137 * Check if the operating system is Windows
2139 * @return Bool: true if it's Windows, False otherwise.
2141 function wfIsWindows() {
2142 static $isWindows = null;
2143 if ( $isWindows === null ) {
2144 $isWindows = substr( php_uname(), 0, 7 ) == 'Windows';
2150 * Swap two variables
2152 function swap( &$x, &$y ) {
2158 function wfGetCachedNotice( $name ) {
2159 global $wgOut, $wgRenderHashAppend, $parserMemc;
2160 $fname = 'wfGetCachedNotice';
2161 wfProfileIn( $fname );
2165 if( $name === 'default' ) {
2167 global $wgSiteNotice;
2168 $notice = $wgSiteNotice;
2169 if( empty( $notice ) ) {
2170 wfProfileOut( $fname );
2174 $notice = wfMsgForContentNoTrans( $name );
2175 if( wfEmptyMsg( $name, $notice ) ||
$notice == '-' ) {
2176 wfProfileOut( $fname );
2181 // Use the extra hash appender to let eg SSL variants separately cache.
2182 $key = wfMemcKey( $name . $wgRenderHashAppend );
2183 $cachedNotice = $parserMemc->get( $key );
2184 if( is_array( $cachedNotice ) ) {
2185 if( md5( $notice ) == $cachedNotice['hash'] ) {
2186 $notice = $cachedNotice['html'];
2195 if( is_object( $wgOut ) ) {
2196 $parsed = $wgOut->parse( $notice );
2197 $parserMemc->set( $key, array( 'html' => $parsed, 'hash' => md5( $notice ) ), 600 );
2200 wfDebug( 'wfGetCachedNotice called for ' . $name . ' with no $wgOut available' . "\n" );
2204 $notice = '<div id="localNotice">' .$notice . '</div>';
2205 wfProfileOut( $fname );
2209 function wfGetNamespaceNotice() {
2213 if ( !isset( $wgTitle ) ||
!is_object( $wgTitle ) ) {
2217 $fname = 'wfGetNamespaceNotice';
2218 wfProfileIn( $fname );
2220 $key = 'namespacenotice-' . $wgTitle->getNsText();
2221 $namespaceNotice = wfGetCachedNotice( $key );
2222 if ( $namespaceNotice && substr( $namespaceNotice, 0, 7 ) != '<p><' ) {
2223 $namespaceNotice = '<div id="namespacebanner">' . $namespaceNotice . '</div>';
2225 $namespaceNotice = '';
2228 wfProfileOut( $fname );
2229 return $namespaceNotice;
2232 function wfGetSiteNotice() {
2234 $fname = 'wfGetSiteNotice';
2235 wfProfileIn( $fname );
2238 if( wfRunHooks( 'SiteNoticeBefore', array( &$siteNotice ) ) ) {
2239 if( is_object( $wgUser ) && $wgUser->isLoggedIn() ) {
2240 $siteNotice = wfGetCachedNotice( 'sitenotice' );
2242 $anonNotice = wfGetCachedNotice( 'anonnotice' );
2243 if( !$anonNotice ) {
2244 $siteNotice = wfGetCachedNotice( 'sitenotice' );
2246 $siteNotice = $anonNotice;
2249 if( !$siteNotice ) {
2250 $siteNotice = wfGetCachedNotice( 'default' );
2254 wfRunHooks( 'SiteNoticeAfter', array( &$siteNotice ) );
2255 wfProfileOut( $fname );
2260 * BC wrapper for MimeMagic::singleton()
2261 * @deprecated No longer needed as of 1.17 (r68836). Remove in 1.19.
2263 function &wfGetMimeMagic() {
2264 wfDeprecated( __FUNCTION__
);
2265 return MimeMagic
::singleton();
2269 * Tries to get the system directory for temporary files. The TMPDIR, TMP, and
2270 * TEMP environment variables are then checked in sequence, and if none are set
2271 * try sys_get_temp_dir() for PHP >= 5.2.1. All else fails, return /tmp for Unix
2272 * or C:\Windows\Temp for Windows and hope for the best.
2273 * It is common to call it with tempnam().
2275 * NOTE: When possible, use instead the tmpfile() function to create
2276 * temporary files to avoid race conditions on file creation, etc.
2280 function wfTempDir() {
2281 foreach( array( 'TMPDIR', 'TMP', 'TEMP' ) as $var ) {
2282 $tmp = getenv( $var );
2283 if( $tmp && file_exists( $tmp ) && is_dir( $tmp ) && is_writable( $tmp ) ) {
2287 if( function_exists( 'sys_get_temp_dir' ) ) {
2288 return sys_get_temp_dir();
2291 return wfIsWindows() ?
'C:\Windows\Temp' : '/tmp';
2295 * Make directory, and make all parent directories if they don't exist
2297 * @param $dir String: full path to directory to create
2298 * @param $mode Integer: chmod value to use, default is $wgDirectoryMode
2299 * @param $caller String: optional caller param for debugging.
2302 function wfMkdirParents( $dir, $mode = null, $caller = null ) {
2303 global $wgDirectoryMode;
2305 if ( !is_null( $caller ) ) {
2306 wfDebug( "$caller: called wfMkdirParents($dir)" );
2309 if( strval( $dir ) === '' ||
file_exists( $dir ) ) {
2313 $dir = str_replace( array( '\\', '/' ), DIRECTORY_SEPARATOR
, $dir );
2315 if ( is_null( $mode ) ) {
2316 $mode = $wgDirectoryMode;
2319 // Turn off the normal warning, we're doing our own below
2320 wfSuppressWarnings();
2321 $ok = mkdir( $dir, $mode, true ); // PHP5 <3
2322 wfRestoreWarnings();
2325 // PHP doesn't report the path in its warning message, so add our own to aid in diagnosis.
2326 trigger_error( __FUNCTION__
. ": failed to mkdir \"$dir\" mode $mode", E_USER_WARNING
);
2332 * Increment a statistics counter
2334 function wfIncrStats( $key ) {
2335 global $wgStatsMethod;
2337 if( $wgStatsMethod == 'udp' ) {
2338 global $wgUDPProfilerHost, $wgUDPProfilerPort, $wgDBname;
2341 $socket = socket_create( AF_INET
, SOCK_DGRAM
, SOL_UDP
);
2342 $statline = "stats/{$wgDBname} - 1 1 1 1 1 -total\n";
2346 strlen( $statline ),
2352 $statline = "stats/{$wgDBname} - 1 1 1 1 1 {$key}\n";
2353 wfSuppressWarnings();
2357 strlen( $statline ),
2362 wfRestoreWarnings();
2363 } elseif( $wgStatsMethod == 'cache' ) {
2365 $key = wfMemcKey( 'stats', $key );
2366 if ( is_null( $wgMemc->incr( $key ) ) ) {
2367 $wgMemc->add( $key, 1 );
2375 * @param $nr Mixed: the number to format
2376 * @param $acc Integer: the number of digits after the decimal point, default 2
2377 * @param $round Boolean: whether or not to round the value, default true
2380 function wfPercent( $nr, $acc = 2, $round = true ) {
2381 $ret = sprintf( "%.${acc}f", $nr );
2382 return $round ?
round( $ret, $acc ) . '%' : "$ret%";
2386 * Encrypt a username/password.
2388 * @param $userid Integer: ID of the user
2389 * @param $password String: password of the user
2390 * @return String: hashed password
2391 * @deprecated Use User::crypt() or User::oldCrypt() instead
2393 function wfEncryptPassword( $userid, $password ) {
2394 wfDeprecated(__FUNCTION__
);
2395 # Just wrap around User::oldCrypt()
2396 return User
::oldCrypt( $password, $userid );
2400 * Appends to second array if $value differs from that in $default
2402 function wfAppendToArrayIfNotDefault( $key, $value, $default, &$changed ) {
2403 if ( is_null( $changed ) ) {
2404 throw new MWException( 'GlobalFunctions::wfAppendToArrayIfNotDefault got null' );
2406 if ( $default[$key] !== $value ) {
2407 $changed[$key] = $value;
2412 * Since wfMsg() and co suck, they don't return false if the message key they
2413 * looked up didn't exist but a XHTML string, this function checks for the
2414 * nonexistance of messages by looking at wfMsg() output
2416 * @param $key String: the message key looked up
2417 * @return Boolean True if the message *doesn't* exist.
2419 function wfEmptyMsg( $key ) {
2420 global $wgMessageCache;
2421 return $wgMessageCache->get( $key, /*useDB*/true, /*content*/false ) === false;
2425 * Find out whether or not a mixed variable exists in a string
2427 * @param $needle String
2428 * @param $str String
2431 function in_string( $needle, $str ) {
2432 return strpos( $str, $needle ) !== false;
2435 function wfSpecialList( $page, $details ) {
2437 $details = $details ?
' ' . $wgContLang->getDirMark() . "($details)" : '';
2438 return $page . $details;
2442 * Returns a regular expression of url protocols
2446 function wfUrlProtocols() {
2447 global $wgUrlProtocols;
2449 static $retval = null;
2450 if ( !is_null( $retval ) ) {
2454 // Support old-style $wgUrlProtocols strings, for backwards compatibility
2455 // with LocalSettings files from 1.5
2456 if ( is_array( $wgUrlProtocols ) ) {
2457 $protocols = array();
2458 foreach ( $wgUrlProtocols as $protocol ) {
2459 $protocols[] = preg_quote( $protocol, '/' );
2462 $retval = implode( '|', $protocols );
2464 $retval = $wgUrlProtocols;
2470 * Safety wrapper around ini_get() for boolean settings.
2471 * The values returned from ini_get() are pre-normalized for settings
2472 * set via php.ini or php_flag/php_admin_flag... but *not*
2473 * for those set via php_value/php_admin_value.
2475 * It's fairly common for people to use php_value instead of php_flag,
2476 * which can leave you with an 'off' setting giving a false positive
2477 * for code that just takes the ini_get() return value as a boolean.
2479 * To make things extra interesting, setting via php_value accepts
2480 * "true" and "yes" as true, but php.ini and php_flag consider them false. :)
2481 * Unrecognized values go false... again opposite PHP's own coercion
2482 * from string to bool.
2484 * Luckily, 'properly' set settings will always come back as '0' or '1',
2485 * so we only have to worry about them and the 'improper' settings.
2487 * I frickin' hate PHP... :P
2489 * @param $setting String
2492 function wfIniGetBool( $setting ) {
2493 $val = ini_get( $setting );
2494 // 'on' and 'true' can't have whitespace around them, but '1' can.
2495 return strtolower( $val ) == 'on'
2496 ||
strtolower( $val ) == 'true'
2497 ||
strtolower( $val ) == 'yes'
2498 ||
preg_match( "/^\s*[+-]?0*[1-9]/", $val ); // approx C atoi() function
2502 * Wrapper function for PHP's dl(). This doesn't work in most situations from
2503 * PHP 5.3 onward, and is usually disabled in shared environments anyway.
2505 * @param $extension String A PHP extension. The file suffix (.so or .dll)
2507 * @return Bool - Whether or not the extension is loaded
2509 function wfDl( $extension ) {
2510 if( extension_loaded( $extension ) ) {
2514 $canDl = ( function_exists( 'dl' ) && is_callable( 'dl' )
2515 && wfIniGetBool( 'enable_dl' ) && !wfIniGetBool( 'safe_mode' ) );
2518 wfSuppressWarnings();
2519 dl( $extension . '.' . PHP_SHLIB_SUFFIX
);
2520 wfRestoreWarnings();
2522 return extension_loaded( $extension );
2526 * Execute a shell command, with time and memory limits mirrored from the PHP
2527 * configuration if supported.
2528 * @param $cmd String Command line, properly escaped for shell.
2529 * @param &$retval optional, will receive the program's exit code.
2530 * (non-zero is usually failure)
2531 * @param $environ Array optional environment variables which should be
2532 * added to the executed command environment.
2533 * @return collected stdout as a string (trailing newlines stripped)
2535 function wfShellExec( $cmd, &$retval = null, $environ = array() ) {
2536 global $IP, $wgMaxShellMemory, $wgMaxShellFileSize, $wgMaxShellTime;
2539 if ( is_null( $disabled ) ) {
2541 if( wfIniGetBool( 'safe_mode' ) ) {
2542 wfDebug( "wfShellExec can't run in safe_mode, PHP's exec functions are too broken.\n" );
2543 $disabled = 'safemode';
2545 $functions = explode( ',', ini_get( 'disable_functions' ) );
2546 $functions = array_map( 'trim', $functions );
2547 $functions = array_map( 'strtolower', $functions );
2548 if ( in_array( 'passthru', $functions ) ) {
2549 wfDebug( "passthru is in disabled_functions\n" );
2550 $disabled = 'passthru';
2556 return $disabled == 'safemode' ?
2557 'Unable to run external programs in safe mode.' :
2558 'Unable to run external programs, passthru() is disabled.';
2561 wfInitShellLocale();
2564 foreach( $environ as $k => $v ) {
2565 if ( wfIsWindows() ) {
2566 /* Surrounding a set in quotes (method used by wfEscapeShellArg) makes the quotes themselves
2567 * appear in the environment variable, so we must use carat escaping as documented in
2568 * http://technet.microsoft.com/en-us/library/cc723564.aspx
2569 * Note however that the quote isn't listed there, but is needed, and the parentheses
2570 * are listed there but doesn't appear to need it.
2572 $envcmd .= "set $k=" . preg_replace( '/([&|()<>^"])/', '^\\1', $v ) . '&& ';
2574 /* Assume this is a POSIX shell, thus required to accept variable assignments before the command
2575 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_09_01
2577 $envcmd .= "$k=" . escapeshellarg( $v ) . ' ';
2580 $cmd = $envcmd . $cmd;
2582 if ( wfIsWindows() ) {
2583 if ( version_compare( PHP_VERSION
, '5.3.0', '<' ) && /* Fixed in 5.3.0 :) */
2584 ( version_compare( PHP_VERSION
, '5.2.1', '>=' ) ||
php_uname( 's' ) == 'Windows NT' ) )
2586 # Hack to work around PHP's flawed invocation of cmd.exe
2587 # http://news.php.net/php.internals/21796
2588 # Windows 9x doesn't accept any kind of quotes
2589 $cmd = '"' . $cmd . '"';
2591 } elseif ( php_uname( 's' ) == 'Linux' ) {
2592 $time = intval( $wgMaxShellTime );
2593 $mem = intval( $wgMaxShellMemory );
2594 $filesize = intval( $wgMaxShellFileSize );
2596 if ( $time > 0 && $mem > 0 ) {
2597 $script = "$IP/bin/ulimit4.sh";
2598 if ( is_executable( $script ) ) {
2599 $cmd = '/bin/bash ' . escapeshellarg( $script ) . " $time $mem $filesize " . escapeshellarg( $cmd );
2603 wfDebug( "wfShellExec: $cmd\n" );
2605 $retval = 1; // error by default?
2607 passthru( $cmd, $retval );
2608 $output = ob_get_contents();
2611 if ( $retval == 127 ) {
2612 wfDebugLog( 'exec', "Possibly missing executable file: $cmd\n" );
2618 * Workaround for http://bugs.php.net/bug.php?id=45132
2619 * escapeshellarg() destroys non-ASCII characters if LANG is not a UTF-8 locale
2621 function wfInitShellLocale() {
2622 static $done = false;
2627 global $wgShellLocale;
2628 if ( !wfIniGetBool( 'safe_mode' ) ) {
2629 putenv( "LC_CTYPE=$wgShellLocale" );
2630 setlocale( LC_CTYPE
, $wgShellLocale );
2635 * This function works like "use VERSION" in Perl, the program will die with a
2636 * backtrace if the current version of PHP is less than the version provided
2638 * This is useful for extensions which due to their nature are not kept in sync
2639 * with releases, and might depend on other versions of PHP than the main code
2641 * Note: PHP might die due to parsing errors in some cases before it ever
2642 * manages to call this function, such is life
2644 * @see perldoc -f use
2646 * @param $req_ver Mixed: the version to check, can be a string, an integer, or
2649 function wfUsePHP( $req_ver ) {
2650 $php_ver = PHP_VERSION
;
2652 if ( version_compare( $php_ver, (string)$req_ver, '<' ) ) {
2653 throw new MWException( "PHP $req_ver required--this is only $php_ver" );
2658 * This function works like "use VERSION" in Perl except it checks the version
2659 * of MediaWiki, the program will die with a backtrace if the current version
2660 * of MediaWiki is less than the version provided.
2662 * This is useful for extensions which due to their nature are not kept in sync
2665 * @see perldoc -f use
2667 * @param $req_ver Mixed: the version to check, can be a string, an integer, or
2670 function wfUseMW( $req_ver ) {
2673 if ( version_compare( $wgVersion, (string)$req_ver, '<' ) ) {
2674 throw new MWException( "MediaWiki $req_ver required--this is only $wgVersion" );
2679 * Return the final portion of a pathname.
2680 * Reimplemented because PHP5's basename() is buggy with multibyte text.
2681 * http://bugs.php.net/bug.php?id=33898
2683 * PHP's basename() only considers '\' a pathchar on Windows and Netware.
2684 * We'll consider it so always, as we don't want \s in our Unix paths either.
2686 * @param $path String
2687 * @param $suffix String: to remove if present
2690 function wfBaseName( $path, $suffix = '' ) {
2691 $encSuffix = ( $suffix == '' )
2693 : ( '(?:' . preg_quote( $suffix, '#' ) . ')?' );
2695 if( preg_match( "#([^/\\\\]*?){$encSuffix}[/\\\\]*$#", $path, $matches ) ) {
2703 * Generate a relative path name to the given file.
2704 * May explode on non-matching case-insensitive paths,
2705 * funky symlinks, etc.
2707 * @param $path String: absolute destination path including target filename
2708 * @param $from String: Absolute source path, directory only
2711 function wfRelativePath( $path, $from ) {
2712 // Normalize mixed input on Windows...
2713 $path = str_replace( '/', DIRECTORY_SEPARATOR
, $path );
2714 $from = str_replace( '/', DIRECTORY_SEPARATOR
, $from );
2716 // Trim trailing slashes -- fix for drive root
2717 $path = rtrim( $path, DIRECTORY_SEPARATOR
);
2718 $from = rtrim( $from, DIRECTORY_SEPARATOR
);
2720 $pieces = explode( DIRECTORY_SEPARATOR
, dirname( $path ) );
2721 $against = explode( DIRECTORY_SEPARATOR
, $from );
2723 if( $pieces[0] !== $against[0] ) {
2724 // Non-matching Windows drive letters?
2725 // Return a full path.
2729 // Trim off common prefix
2730 while( count( $pieces ) && count( $against )
2731 && $pieces[0] == $against[0] ) {
2732 array_shift( $pieces );
2733 array_shift( $against );
2736 // relative dots to bump us to the parent
2737 while( count( $against ) ) {
2738 array_unshift( $pieces, '..' );
2739 array_shift( $against );
2742 array_push( $pieces, wfBaseName( $path ) );
2744 return implode( DIRECTORY_SEPARATOR
, $pieces );
2748 * Backwards array plus for people who haven't bothered to read the PHP manual
2749 * XXX: will not darn your socks for you.
2751 * @param $array1 Array
2752 * @param [$array2, [...]] Arrays
2755 function wfArrayMerge( $array1/* ... */ ) {
2756 $args = func_get_args();
2757 $args = array_reverse( $args, true );
2759 foreach ( $args as $arg ) {
2766 * Merge arrays in the style of getUserPermissionsErrors, with duplicate removal
2768 * wfMergeErrorArrays(
2769 * array( array( 'x' ) ),
2770 * array( array( 'x', '2' ) ),
2771 * array( array( 'x' ) ),
2772 * array( array( 'y') )
2776 * array( 'x', '2' ),
2781 function wfMergeErrorArrays( /*...*/ ) {
2782 $args = func_get_args();
2784 foreach ( $args as $errors ) {
2785 foreach ( $errors as $params ) {
2786 # FIXME: sometimes get nested arrays for $params,
2787 # which leads to E_NOTICEs
2788 $spec = implode( "\t", $params );
2789 $out[$spec] = $params;
2792 return array_values( $out );
2796 * parse_url() work-alike, but non-broken. Differences:
2798 * 1) Does not raise warnings on bad URLs (just returns false)
2799 * 2) Handles protocols that don't use :// (e.g., mailto: and news:) correctly
2800 * 3) Adds a "delimiter" element to the array, either '://' or ':' (see (2))
2802 * @param $url String: a URL to parse
2803 * @return Array: bits of the URL in an associative array, per PHP docs
2805 function wfParseUrl( $url ) {
2806 global $wgUrlProtocols; // Allow all protocols defined in DefaultSettings/LocalSettings.php
2807 wfSuppressWarnings();
2808 $bits = parse_url( $url );
2809 wfRestoreWarnings();
2814 // most of the protocols are followed by ://, but mailto: and sometimes news: not, check for it
2815 if ( in_array( $bits['scheme'] . '://', $wgUrlProtocols ) ) {
2816 $bits['delimiter'] = '://';
2817 } elseif ( in_array( $bits['scheme'] . ':', $wgUrlProtocols ) ) {
2818 $bits['delimiter'] = ':';
2819 // parse_url detects for news: and mailto: the host part of an url as path
2820 // We have to correct this wrong detection
2821 if ( isset( $bits['path'] ) ) {
2822 $bits['host'] = $bits['path'];
2833 * Make a URL index, appropriate for the el_index field of externallinks.
2835 function wfMakeUrlIndex( $url ) {
2836 $bits = wfParseUrl( $url );
2838 // Reverse the labels in the hostname, convert to lower case
2839 // For emails reverse domainpart only
2840 if ( $bits['scheme'] == 'mailto' ) {
2841 $mailparts = explode( '@', $bits['host'], 2 );
2842 if ( count( $mailparts ) === 2 ) {
2843 $domainpart = strtolower( implode( '.', array_reverse( explode( '.', $mailparts[1] ) ) ) );
2845 // No domain specified, don't mangle it
2848 $reversedHost = $domainpart . '@' . $mailparts[0];
2850 $reversedHost = strtolower( implode( '.', array_reverse( explode( '.', $bits['host'] ) ) ) );
2852 // Add an extra dot to the end
2853 // Why? Is it in wrong place in mailto links?
2854 if ( substr( $reversedHost, -1, 1 ) !== '.' ) {
2855 $reversedHost .= '.';
2857 // Reconstruct the pseudo-URL
2858 $prot = $bits['scheme'];
2859 $index = $prot . $bits['delimiter'] . $reversedHost;
2860 // Leave out user and password. Add the port, path, query and fragment
2861 if ( isset( $bits['port'] ) ) {
2862 $index .= ':' . $bits['port'];
2864 if ( isset( $bits['path'] ) ) {
2865 $index .= $bits['path'];
2869 if ( isset( $bits['query'] ) ) {
2870 $index .= '?' . $bits['query'];
2872 if ( isset( $bits['fragment'] ) ) {
2873 $index .= '#' . $bits['fragment'];
2879 * Do any deferred updates and clear the list
2881 * @param $commit String: set to 'commit' to commit after every update to
2882 * prevent lock contention
2884 function wfDoUpdates( $commit = '' ) {
2885 global $wgDeferredUpdateList;
2887 wfProfileIn( __METHOD__
);
2889 // No need to get master connections in case of empty updates array
2890 if ( !count( $wgDeferredUpdateList ) ) {
2891 wfProfileOut( __METHOD__
);
2895 $doCommit = $commit == 'commit';
2897 $dbw = wfGetDB( DB_MASTER
);
2900 foreach ( $wgDeferredUpdateList as $update ) {
2901 $update->doUpdate();
2903 if ( $doCommit && $dbw->trxLevel() ) {
2908 $wgDeferredUpdateList = array();
2909 wfProfileOut( __METHOD__
);
2913 * Convert an arbitrarily-long digit string from one numeric base
2914 * to another, optionally zero-padding to a minimum column width.
2916 * Supports base 2 through 36; digit values 10-36 are represented
2917 * as lowercase letters a-z. Input is case-insensitive.
2919 * @param $input String: of digits
2920 * @param $sourceBase Integer: 2-36
2921 * @param $destBase Integer: 2-36
2922 * @param $pad Integer: 1 or greater
2923 * @param $lowercase Boolean
2924 * @return String or false on invalid input
2926 function wfBaseConvert( $input, $sourceBase, $destBase, $pad = 1, $lowercase = true ) {
2927 $input = strval( $input );
2928 if( $sourceBase < 2 ||
2933 $sourceBase != intval( $sourceBase ) ||
2934 $destBase != intval( $destBase ) ||
2935 $pad != intval( $pad ) ||
2936 !is_string( $input ) ||
2940 $digitChars = ( $lowercase ) ?
'0123456789abcdefghijklmnopqrstuvwxyz' : '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
2941 $inDigits = array();
2944 // Decode and validate input string
2945 $input = strtolower( $input );
2946 for( $i = 0; $i < strlen( $input ); $i++
) {
2947 $n = strpos( $digitChars, $input{$i} );
2948 if( $n === false ||
$n > $sourceBase ) {
2954 // Iterate over the input, modulo-ing out an output digit
2955 // at a time until input is gone.
2956 while( count( $inDigits ) ) {
2958 $workDigits = array();
2961 foreach( $inDigits as $digit ) {
2962 $work *= $sourceBase;
2965 if( $work < $destBase ) {
2966 // Gonna need to pull another digit.
2967 if( count( $workDigits ) ) {
2968 // Avoid zero-padding; this lets us find
2969 // the end of the input very easily when
2970 // length drops to zero.
2974 // Finally! Actual division!
2975 $workDigits[] = intval( $work / $destBase );
2977 // Isn't it annoying that most programming languages
2978 // don't have a single divide-and-remainder operator,
2979 // even though the CPU implements it that way?
2980 $work = $work %
$destBase;
2984 // All that division leaves us with a remainder,
2985 // which is conveniently our next output digit.
2986 $outChars .= $digitChars[$work];
2989 $inDigits = $workDigits;
2992 while( strlen( $outChars ) < $pad ) {
2996 return strrev( $outChars );
3000 * Create an object with a given name and an array of construct parameters
3001 * @param $name String
3002 * @param $p Array: parameters
3004 function wfCreateObject( $name, $p ) {
3005 $p = array_values( $p );
3006 switch ( count( $p ) ) {
3010 return new $name( $p[0] );
3012 return new $name( $p[0], $p[1] );
3014 return new $name( $p[0], $p[1], $p[2] );
3016 return new $name( $p[0], $p[1], $p[2], $p[3] );
3018 return new $name( $p[0], $p[1], $p[2], $p[3], $p[4] );
3020 return new $name( $p[0], $p[1], $p[2], $p[3], $p[4], $p[5] );
3022 throw new MWException( 'Too many arguments to construtor in wfCreateObject' );
3026 function wfHttpOnlySafe() {
3027 global $wgHttpOnlyBlacklist;
3028 if( !version_compare( '5.2', PHP_VERSION
, '<' ) ) {
3032 if( isset( $_SERVER['HTTP_USER_AGENT'] ) ) {
3033 foreach( $wgHttpOnlyBlacklist as $regex ) {
3034 if( preg_match( $regex, $_SERVER['HTTP_USER_AGENT'] ) ) {
3044 * Initialise php session
3046 function wfSetupSession( $sessionId = false ) {
3047 global $wgSessionsInMemcached, $wgCookiePath, $wgCookieDomain,
3048 $wgCookieSecure, $wgCookieHttpOnly, $wgSessionHandler;
3049 if( $wgSessionsInMemcached ) {
3050 require_once( 'MemcachedSessions.php' );
3051 } elseif( $wgSessionHandler && $wgSessionHandler != ini_get( 'session.save_handler' ) ) {
3052 # Only set this if $wgSessionHandler isn't null and session.save_handler
3053 # hasn't already been set to the desired value (that causes errors)
3054 ini_set( 'session.save_handler', $wgSessionHandler );
3056 $httpOnlySafe = wfHttpOnlySafe();
3057 wfDebugLog( 'cookie',
3058 'session_set_cookie_params: "' . implode( '", "',
3064 $httpOnlySafe && $wgCookieHttpOnly ) ) . '"' );
3065 if( $httpOnlySafe && $wgCookieHttpOnly ) {
3066 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookieHttpOnly );
3068 // PHP 5.1 throws warnings if you pass the HttpOnly parameter for 5.2.
3069 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
3071 session_cache_limiter( 'private, must-revalidate' );
3073 session_id( $sessionId );
3075 wfSuppressWarnings();
3077 wfRestoreWarnings();
3081 * Get an object from the precompiled serialized directory
3083 * @return Mixed: the variable on success, false on failure
3085 function wfGetPrecompiledData( $name ) {
3088 $file = "$IP/serialized/$name";
3089 if ( file_exists( $file ) ) {
3090 $blob = file_get_contents( $file );
3092 return unserialize( $blob );
3098 function wfGetCaller( $level = 2 ) {
3099 $backtrace = wfDebugBacktrace();
3100 if ( isset( $backtrace[$level] ) ) {
3101 return wfFormatStackFrame( $backtrace[$level] );
3103 $caller = 'unknown';
3109 * Return a string consisting of callers in the stack. Useful sometimes
3110 * for profiling specific points.
3112 * @param $limit The maximum depth of the stack frame to return, or false for
3115 function wfGetAllCallers( $limit = 3 ) {
3116 $trace = array_reverse( wfDebugBacktrace() );
3117 if ( !$limit ||
$limit > count( $trace ) - 1 ) {
3118 $limit = count( $trace ) - 1;
3120 $trace = array_slice( $trace, -$limit - 1, $limit );
3121 return implode( '/', array_map( 'wfFormatStackFrame', $trace ) );
3125 * Return a string representation of frame
3127 function wfFormatStackFrame( $frame ) {
3128 return isset( $frame['class'] ) ?
3129 $frame['class'] . '::' . $frame['function'] :
3136 function wfMemcKey( /*... */ ) {
3137 $args = func_get_args();
3138 $key = wfWikiID() . ':' . implode( ':', $args );
3139 $key = str_replace( ' ', '_', $key );
3144 * Get a cache key for a foreign DB
3146 function wfForeignMemcKey( $db, $prefix /*, ... */ ) {
3147 $args = array_slice( func_get_args(), 2 );
3149 $key = "$db-$prefix:" . implode( ':', $args );
3151 $key = $db . ':' . implode( ':', $args );
3157 * Get an ASCII string identifying this wiki
3158 * This is used as a prefix in memcached keys
3160 function wfWikiID() {
3161 global $wgDBprefix, $wgDBname;
3162 if ( $wgDBprefix ) {
3163 return "$wgDBname-$wgDBprefix";
3170 * Split a wiki ID into DB name and table prefix
3172 function wfSplitWikiID( $wiki ) {
3173 $bits = explode( '-', $wiki, 2 );
3174 if ( count( $bits ) < 2 ) {
3181 * Get a Database object.
3182 * @param $db Integer: index of the connection to get. May be DB_MASTER for the
3183 * master (for write queries), DB_SLAVE for potentially lagged read
3184 * queries, or an integer >= 0 for a particular server.
3186 * @param $groups Mixed: query groups. An array of group names that this query
3187 * belongs to. May contain a single string if the query is only
3190 * @param $wiki String: the wiki ID, or false for the current wiki
3192 * Note: multiple calls to wfGetDB(DB_SLAVE) during the course of one request
3193 * will always return the same object, unless the underlying connection or load
3194 * balancer is manually destroyed.
3196 * @return DatabaseBase
3198 function &wfGetDB( $db, $groups = array(), $wiki = false ) {
3199 return wfGetLB( $wiki )->getConnection( $db, $groups, $wiki );
3203 * Get a load balancer object.
3205 * @param $wiki String: wiki ID, or false for the current wiki
3206 * @return LoadBalancer
3208 function wfGetLB( $wiki = false ) {
3209 return wfGetLBFactory()->getMainLB( $wiki );
3213 * Get the load balancer factory object
3216 function &wfGetLBFactory() {
3217 return LBFactory
::singleton();
3222 * Shortcut for RepoGroup::singleton()->findFile()
3223 * @param $title String or Title object
3224 * @param $options Associative array of options:
3225 * time: requested time for an archived image, or false for the
3226 * current version. An image object will be returned which was
3227 * created at the specified time.
3229 * ignoreRedirect: If true, do not follow file redirects
3231 * private: If true, return restricted (deleted) files if the current
3232 * user is allowed to view them. Otherwise, such files will not
3235 * bypassCache: If true, do not use the process-local cache of File objects
3237 * @return File, or false if the file does not exist
3239 function wfFindFile( $title, $options = array() ) {
3240 return RepoGroup
::singleton()->findFile( $title, $options );
3244 * Get an object referring to a locally registered file.
3245 * Returns a valid placeholder object if the file does not exist.
3246 * @param $title Title or String
3247 * @return File, or null if passed an invalid Title
3249 function wfLocalFile( $title ) {
3250 return RepoGroup
::singleton()->getLocalRepo()->newFile( $title );
3254 * Should low-performance queries be disabled?
3258 function wfQueriesMustScale() {
3259 global $wgMiserMode;
3261 ||
( SiteStats
::pages() > 100000
3262 && SiteStats
::edits() > 1000000
3263 && SiteStats
::users() > 10000 );
3267 * Get the path to a specified script file, respecting file
3268 * extensions; this is a wrapper around $wgScriptExtension etc.
3270 * @param $script String: script filename, sans extension
3273 function wfScript( $script = 'index' ) {
3274 global $wgScriptPath, $wgScriptExtension;
3275 return "{$wgScriptPath}/{$script}{$wgScriptExtension}";
3279 * Get the script URL.
3281 * @return script URL
3283 function wfGetScriptUrl() {
3284 if( isset( $_SERVER['SCRIPT_NAME'] ) ) {
3286 # as it was called, minus the query string.
3288 # Some sites use Apache rewrite rules to handle subdomains,
3289 # and have PHP set up in a weird way that causes PHP_SELF
3290 # to contain the rewritten URL instead of the one that the
3291 # outside world sees.
3293 # If in this mode, use SCRIPT_URL instead, which mod_rewrite
3294 # provides containing the "before" URL.
3295 return $_SERVER['SCRIPT_NAME'];
3297 return $_SERVER['URL'];
3302 * Convenience function converts boolean values into "true"
3303 * or "false" (string) values
3305 * @param $value Boolean
3308 function wfBoolToStr( $value ) {
3309 return $value ?
'true' : 'false';
3313 * Load an extension messages file
3314 * @deprecated in 1.16, warnings in 1.18, remove in 1.20
3316 function wfLoadExtensionMessages( $extensionName, $langcode = false ) {
3317 wfDeprecated( __FUNCTION__
);
3321 * Get a platform-independent path to the null file, e.g.
3326 function wfGetNull() {
3327 return wfIsWindows()
3333 * Displays a maxlag error
3335 * @param $host String: server that lags the most
3336 * @param $lag Integer: maxlag (actual)
3337 * @param $maxLag Integer: maxlag (requested)
3339 function wfMaxlagError( $host, $lag, $maxLag ) {
3340 global $wgShowHostnames;
3341 header( 'HTTP/1.1 503 Service Unavailable' );
3342 header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
3343 header( 'X-Database-Lag: ' . intval( $lag ) );
3344 header( 'Content-Type: text/plain' );
3345 if( $wgShowHostnames ) {
3346 echo "Waiting for $host: $lag seconds lagged\n";
3348 echo "Waiting for a database server: $lag seconds lagged\n";
3353 * Throws a warning that $function is deprecated
3354 * @param $function String
3357 function wfDeprecated( $function ) {
3358 static $functionsWarned = array();
3359 if ( !isset( $functionsWarned[$function] ) ) {
3360 $functionsWarned[$function] = true;
3361 wfWarn( "Use of $function is deprecated.", 2 );
3366 * Send a warning either to the debug log or in a PHP error depending on
3367 * $wgDevelopmentWarnings
3369 * @param $msg String: message to send
3370 * @param $callerOffset Integer: number of itmes to go back in the backtrace to
3371 * find the correct caller (1 = function calling wfWarn, ...)
3372 * @param $level Integer: PHP error level; only used when $wgDevelopmentWarnings
3375 function wfWarn( $msg, $callerOffset = 1, $level = E_USER_NOTICE
) {
3376 $callers = wfDebugBacktrace();
3377 if( isset( $callers[$callerOffset +
1] ) ){
3378 $callerfunc = $callers[$callerOffset +
1];
3379 $callerfile = $callers[$callerOffset];
3380 if( isset( $callerfile['file'] ) && isset( $callerfile['line'] ) ) {
3381 $file = $callerfile['file'] . ' at line ' . $callerfile['line'];
3383 $file = '(internal function)';
3386 if( isset( $callerfunc['class'] ) ) {
3387 $func .= $callerfunc['class'] . '::';
3389 if( isset( $callerfunc['function'] ) ) {
3390 $func .= $callerfunc['function'];
3392 $msg .= " [Called from $func in $file]";
3395 global $wgDevelopmentWarnings;
3396 if ( $wgDevelopmentWarnings ) {
3397 trigger_error( $msg, $level );
3399 wfDebug( "$msg\n" );
3404 * Sleep until the worst slave's replication lag is less than or equal to
3405 * $maxLag, in seconds. Use this when updating very large numbers of rows, as
3406 * in maintenance scripts, to avoid causing too much lag. Of course, this is
3407 * a no-op if there are no slaves.
3409 * Every time the function has to wait for a slave, it will print a message to
3410 * that effect (and then sleep for a little while), so it's probably not best
3411 * to use this outside maintenance scripts in its present form.
3413 * @param $maxLag Integer
3414 * @param $wiki mixed Wiki identifier accepted by wfGetLB
3417 function wfWaitForSlaves( $maxLag, $wiki = false ) {
3419 $lb = wfGetLB( $wiki );
3420 list( $host, $lag ) = $lb->getMaxLag( $wiki );
3421 while( $lag > $maxLag ) {
3422 wfSuppressWarnings();
3423 $name = gethostbyaddr( $host );
3424 wfRestoreWarnings();
3425 if( $name !== false ) {
3428 print "Waiting for $host (lagged $lag seconds)...\n";
3430 list( $host, $lag ) = $lb->getMaxLag();
3436 * Used to be used for outputting text in the installer/updater
3437 * @deprecated Warnings in 1.19, removal in 1.20
3439 function wfOut( $s ) {
3440 global $wgCommandLineMode;
3441 if ( $wgCommandLineMode && !defined( 'MEDIAWIKI_INSTALL' ) ) {
3444 echo htmlspecialchars( $s );
3450 * Count down from $n to zero on the terminal, with a one-second pause
3451 * between showing each number. For use in command-line scripts.
3453 function wfCountDown( $n ) {
3454 for ( $i = $n; $i >= 0; $i-- ) {
3456 echo str_repeat( "\x08", strlen( $i +
1 ) );
3468 * Generate a random 32-character hexadecimal token.
3469 * @param $salt Mixed: some sort of salt, if necessary, to add to random
3470 * characters before hashing.
3472 function wfGenerateToken( $salt = '' ) {
3473 $salt = serialize( $salt );
3474 return md5( mt_rand( 0, 0x7fffffff ) . $salt );
3478 * Replace all invalid characters with -
3479 * @param $name Mixed: filename to process
3481 function wfStripIllegalFilenameChars( $name ) {
3482 global $wgIllegalFileChars;
3483 $name = wfBaseName( $name );
3484 $name = preg_replace(
3485 "/[^" . Title
::legalChars() . "]" .
3486 ( $wgIllegalFileChars ?
"|[" . $wgIllegalFileChars . "]" : '' ) .
3495 * Insert array into another array after the specified *KEY*
3496 * @param $array Array: The array.
3497 * @param $insert Array: The array to insert.
3498 * @param $after Mixed: The key to insert after
3500 function wfArrayInsertAfter( $array, $insert, $after ) {
3501 // Find the offset of the element to insert after.
3502 $keys = array_keys( $array );
3503 $offsetByKey = array_flip( $keys );
3505 $offset = $offsetByKey[$after];
3507 // Insert at the specified offset
3508 $before = array_slice( $array, 0, $offset +
1, true );
3509 $after = array_slice( $array, $offset +
1, count( $array ) - $offset, true );
3511 $output = $before +
$insert +
$after;
3516 /* Recursively converts the parameter (an object) to an array with the same data */
3517 function wfObjectToArray( $object, $recursive = true ) {
3519 foreach ( get_object_vars( $object ) as $key => $value ) {
3520 if ( is_object( $value ) && $recursive ) {
3521 $value = wfObjectToArray( $value );
3524 $array[$key] = $value;
3531 * Set PHP's memory limit to the larger of php.ini or $wgMemoryLimit;
3532 * @return Integer value memory was set to.
3534 function wfMemoryLimit() {
3535 global $wgMemoryLimit;
3536 $memlimit = wfShorthandToInteger( ini_get( 'memory_limit' ) );
3537 if( $memlimit != -1 ) {
3538 $conflimit = wfShorthandToInteger( $wgMemoryLimit );
3539 if( $conflimit == -1 ) {
3540 wfDebug( "Removing PHP's memory limit\n" );
3541 wfSuppressWarnings();
3542 ini_set( 'memory_limit', $conflimit );
3543 wfRestoreWarnings();
3545 } elseif ( $conflimit > $memlimit ) {
3546 wfDebug( "Raising PHP's memory limit to $conflimit bytes\n" );
3547 wfSuppressWarnings();
3548 ini_set( 'memory_limit', $conflimit );
3549 wfRestoreWarnings();
3557 * Converts shorthand byte notation to integer form
3558 * @param $string String
3561 function wfShorthandToInteger( $string = '' ) {
3562 $string = trim( $string );
3563 if( $string === '' ) {
3566 $last = $string[strlen( $string ) - 1];
3567 $val = intval( $string );
3572 // break intentionally missing
3576 // break intentionally missing
3586 * Get the normalised IETF language tag
3587 * @param $code String: The language code.
3588 * @return $langCode String: The language code which complying with BCP 47 standards.
3590 function wfBCP47( $code ) {
3591 $codeSegment = explode( '-', $code );
3592 foreach ( $codeSegment as $segNo => $seg ) {
3593 if ( count( $codeSegment ) > 0 ) {
3594 // ISO 3166 country code
3595 if ( ( strlen( $seg ) == 2 ) && ( $segNo > 0 ) ) {
3596 $codeBCP[$segNo] = strtoupper( $seg );
3597 // ISO 15924 script code
3598 } elseif ( ( strlen( $seg ) == 4 ) && ( $segNo > 0 ) ) {
3599 $codeBCP[$segNo] = ucfirst( $seg );
3600 // Use lowercase for other cases
3602 $codeBCP[$segNo] = strtolower( $seg );
3605 // Use lowercase for single segment
3606 $codeBCP[$segNo] = strtolower( $seg );
3609 $langCode = implode( '-', $codeBCP );
3613 function wfArrayMap( $function, $input ) {
3614 $ret = array_map( $function, $input );
3615 foreach ( $ret as $key => $value ) {
3616 $taint = istainted( $input[$key] );
3618 taint( $ret[$key], $taint );