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( $force = false ) {
1277 static $result = null;
1278 if ( $result === null ||
$force ) {
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
2429 * @param $insensitive Boolean
2432 function in_string( $needle, $str, $insensitive = false ) {
2434 if( $insensitive ) $func = 'stripos';
2436 return $func( $str, $needle ) !== false;
2439 function wfSpecialList( $page, $details ) {
2441 $details = $details ?
' ' . $wgContLang->getDirMark() . "($details)" : '';
2442 return $page . $details;
2446 * Returns a regular expression of url protocols
2450 function wfUrlProtocols() {
2451 global $wgUrlProtocols;
2453 static $retval = null;
2454 if ( !is_null( $retval ) ) {
2458 // Support old-style $wgUrlProtocols strings, for backwards compatibility
2459 // with LocalSettings files from 1.5
2460 if ( is_array( $wgUrlProtocols ) ) {
2461 $protocols = array();
2462 foreach ( $wgUrlProtocols as $protocol ) {
2463 $protocols[] = preg_quote( $protocol, '/' );
2466 $retval = implode( '|', $protocols );
2468 $retval = $wgUrlProtocols;
2474 * Safety wrapper around ini_get() for boolean settings.
2475 * The values returned from ini_get() are pre-normalized for settings
2476 * set via php.ini or php_flag/php_admin_flag... but *not*
2477 * for those set via php_value/php_admin_value.
2479 * It's fairly common for people to use php_value instead of php_flag,
2480 * which can leave you with an 'off' setting giving a false positive
2481 * for code that just takes the ini_get() return value as a boolean.
2483 * To make things extra interesting, setting via php_value accepts
2484 * "true" and "yes" as true, but php.ini and php_flag consider them false. :)
2485 * Unrecognized values go false... again opposite PHP's own coercion
2486 * from string to bool.
2488 * Luckily, 'properly' set settings will always come back as '0' or '1',
2489 * so we only have to worry about them and the 'improper' settings.
2491 * I frickin' hate PHP... :P
2493 * @param $setting String
2496 function wfIniGetBool( $setting ) {
2497 $val = ini_get( $setting );
2498 // 'on' and 'true' can't have whitespace around them, but '1' can.
2499 return strtolower( $val ) == 'on'
2500 ||
strtolower( $val ) == 'true'
2501 ||
strtolower( $val ) == 'yes'
2502 ||
preg_match( "/^\s*[+-]?0*[1-9]/", $val ); // approx C atoi() function
2506 * Wrapper function for PHP's dl(). This doesn't work in most situations from
2507 * PHP 5.3 onward, and is usually disabled in shared environments anyway.
2509 * @param $extension String A PHP extension. The file suffix (.so or .dll)
2511 * @return Bool - Whether or not the extension is loaded
2513 function wfDl( $extension ) {
2514 if( extension_loaded( $extension ) ) {
2518 $canDl = ( function_exists( 'dl' ) && is_callable( 'dl' )
2519 && wfIniGetBool( 'enable_dl' ) && !wfIniGetBool( 'safe_mode' ) );
2522 wfSuppressWarnings();
2523 dl( $extension . '.' . PHP_SHLIB_SUFFIX
);
2524 wfRestoreWarnings();
2526 return extension_loaded( $extension );
2530 * Execute a shell command, with time and memory limits mirrored from the PHP
2531 * configuration if supported.
2532 * @param $cmd String Command line, properly escaped for shell.
2533 * @param &$retval optional, will receive the program's exit code.
2534 * (non-zero is usually failure)
2535 * @param $environ Array optional environment variables which should be
2536 * added to the executed command environment.
2537 * @return collected stdout as a string (trailing newlines stripped)
2539 function wfShellExec( $cmd, &$retval = null, $environ = array() ) {
2540 global $IP, $wgMaxShellMemory, $wgMaxShellFileSize, $wgMaxShellTime;
2543 if ( is_null( $disabled ) ) {
2545 if( wfIniGetBool( 'safe_mode' ) ) {
2546 wfDebug( "wfShellExec can't run in safe_mode, PHP's exec functions are too broken.\n" );
2547 $disabled = 'safemode';
2549 $functions = explode( ',', ini_get( 'disable_functions' ) );
2550 $functions = array_map( 'trim', $functions );
2551 $functions = array_map( 'strtolower', $functions );
2552 if ( in_array( 'passthru', $functions ) ) {
2553 wfDebug( "passthru is in disabled_functions\n" );
2554 $disabled = 'passthru';
2560 return $disabled == 'safemode' ?
2561 'Unable to run external programs in safe mode.' :
2562 'Unable to run external programs, passthru() is disabled.';
2565 wfInitShellLocale();
2568 foreach( $environ as $k => $v ) {
2569 if ( wfIsWindows() ) {
2570 /* Surrounding a set in quotes (method used by wfEscapeShellArg) makes the quotes themselves
2571 * appear in the environment variable, so we must use carat escaping as documented in
2572 * http://technet.microsoft.com/en-us/library/cc723564.aspx
2573 * Note however that the quote isn't listed there, but is needed, and the parentheses
2574 * are listed there but doesn't appear to need it.
2576 $envcmd .= "set $k=" . preg_replace( '/([&|()<>^"])/', '^\\1', $v ) . '&& ';
2578 /* Assume this is a POSIX shell, thus required to accept variable assignments before the command
2579 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_09_01
2581 $envcmd .= "$k=" . escapeshellarg( $v ) . ' ';
2584 $cmd = $envcmd . $cmd;
2586 if ( wfIsWindows() ) {
2587 if ( version_compare( PHP_VERSION
, '5.3.0', '<' ) && /* Fixed in 5.3.0 :) */
2588 ( version_compare( PHP_VERSION
, '5.2.1', '>=' ) ||
php_uname( 's' ) == 'Windows NT' ) )
2590 # Hack to work around PHP's flawed invocation of cmd.exe
2591 # http://news.php.net/php.internals/21796
2592 # Windows 9x doesn't accept any kind of quotes
2593 $cmd = '"' . $cmd . '"';
2595 } elseif ( php_uname( 's' ) == 'Linux' ) {
2596 $time = intval( $wgMaxShellTime );
2597 $mem = intval( $wgMaxShellMemory );
2598 $filesize = intval( $wgMaxShellFileSize );
2600 if ( $time > 0 && $mem > 0 ) {
2601 $script = "$IP/bin/ulimit4.sh";
2602 if ( is_executable( $script ) ) {
2603 $cmd = '/bin/bash ' . escapeshellarg( $script ) . " $time $mem $filesize " . escapeshellarg( $cmd );
2607 wfDebug( "wfShellExec: $cmd\n" );
2609 $retval = 1; // error by default?
2611 passthru( $cmd, $retval );
2612 $output = ob_get_contents();
2615 if ( $retval == 127 ) {
2616 wfDebugLog( 'exec', "Possibly missing executable file: $cmd\n" );
2622 * Workaround for http://bugs.php.net/bug.php?id=45132
2623 * escapeshellarg() destroys non-ASCII characters if LANG is not a UTF-8 locale
2625 function wfInitShellLocale() {
2626 static $done = false;
2631 global $wgShellLocale;
2632 if ( !wfIniGetBool( 'safe_mode' ) ) {
2633 putenv( "LC_CTYPE=$wgShellLocale" );
2634 setlocale( LC_CTYPE
, $wgShellLocale );
2639 * This function works like "use VERSION" in Perl, the program will die with a
2640 * backtrace if the current version of PHP is less than the version provided
2642 * This is useful for extensions which due to their nature are not kept in sync
2643 * with releases, and might depend on other versions of PHP than the main code
2645 * Note: PHP might die due to parsing errors in some cases before it ever
2646 * manages to call this function, such is life
2648 * @see perldoc -f use
2650 * @param $req_ver Mixed: the version to check, can be a string, an integer, or
2653 function wfUsePHP( $req_ver ) {
2654 $php_ver = PHP_VERSION
;
2656 if ( version_compare( $php_ver, (string)$req_ver, '<' ) ) {
2657 throw new MWException( "PHP $req_ver required--this is only $php_ver" );
2662 * This function works like "use VERSION" in Perl except it checks the version
2663 * of MediaWiki, the program will die with a backtrace if the current version
2664 * of MediaWiki is less than the version provided.
2666 * This is useful for extensions which due to their nature are not kept in sync
2669 * @see perldoc -f use
2671 * @param $req_ver Mixed: the version to check, can be a string, an integer, or
2674 function wfUseMW( $req_ver ) {
2677 if ( version_compare( $wgVersion, (string)$req_ver, '<' ) ) {
2678 throw new MWException( "MediaWiki $req_ver required--this is only $wgVersion" );
2683 * Return the final portion of a pathname.
2684 * Reimplemented because PHP5's basename() is buggy with multibyte text.
2685 * http://bugs.php.net/bug.php?id=33898
2687 * PHP's basename() only considers '\' a pathchar on Windows and Netware.
2688 * We'll consider it so always, as we don't want \s in our Unix paths either.
2690 * @param $path String
2691 * @param $suffix String: to remove if present
2694 function wfBaseName( $path, $suffix = '' ) {
2695 $encSuffix = ( $suffix == '' )
2697 : ( '(?:' . preg_quote( $suffix, '#' ) . ')?' );
2699 if( preg_match( "#([^/\\\\]*?){$encSuffix}[/\\\\]*$#", $path, $matches ) ) {
2707 * Generate a relative path name to the given file.
2708 * May explode on non-matching case-insensitive paths,
2709 * funky symlinks, etc.
2711 * @param $path String: absolute destination path including target filename
2712 * @param $from String: Absolute source path, directory only
2715 function wfRelativePath( $path, $from ) {
2716 // Normalize mixed input on Windows...
2717 $path = str_replace( '/', DIRECTORY_SEPARATOR
, $path );
2718 $from = str_replace( '/', DIRECTORY_SEPARATOR
, $from );
2720 // Trim trailing slashes -- fix for drive root
2721 $path = rtrim( $path, DIRECTORY_SEPARATOR
);
2722 $from = rtrim( $from, DIRECTORY_SEPARATOR
);
2724 $pieces = explode( DIRECTORY_SEPARATOR
, dirname( $path ) );
2725 $against = explode( DIRECTORY_SEPARATOR
, $from );
2727 if( $pieces[0] !== $against[0] ) {
2728 // Non-matching Windows drive letters?
2729 // Return a full path.
2733 // Trim off common prefix
2734 while( count( $pieces ) && count( $against )
2735 && $pieces[0] == $against[0] ) {
2736 array_shift( $pieces );
2737 array_shift( $against );
2740 // relative dots to bump us to the parent
2741 while( count( $against ) ) {
2742 array_unshift( $pieces, '..' );
2743 array_shift( $against );
2746 array_push( $pieces, wfBaseName( $path ) );
2748 return implode( DIRECTORY_SEPARATOR
, $pieces );
2752 * Backwards array plus for people who haven't bothered to read the PHP manual
2753 * XXX: will not darn your socks for you.
2755 * @param $array1 Array
2756 * @param [$array2, [...]] Arrays
2759 function wfArrayMerge( $array1/* ... */ ) {
2760 $args = func_get_args();
2761 $args = array_reverse( $args, true );
2763 foreach ( $args as $arg ) {
2770 * Merge arrays in the style of getUserPermissionsErrors, with duplicate removal
2772 * wfMergeErrorArrays(
2773 * array( array( 'x' ) ),
2774 * array( array( 'x', '2' ) ),
2775 * array( array( 'x' ) ),
2776 * array( array( 'y') )
2780 * array( 'x', '2' ),
2785 function wfMergeErrorArrays( /*...*/ ) {
2786 $args = func_get_args();
2788 foreach ( $args as $errors ) {
2789 foreach ( $errors as $params ) {
2790 # FIXME: sometimes get nested arrays for $params,
2791 # which leads to E_NOTICEs
2792 $spec = implode( "\t", $params );
2793 $out[$spec] = $params;
2796 return array_values( $out );
2800 * parse_url() work-alike, but non-broken. Differences:
2802 * 1) Does not raise warnings on bad URLs (just returns false)
2803 * 2) Handles protocols that don't use :// (e.g., mailto: and news:) correctly
2804 * 3) Adds a "delimiter" element to the array, either '://' or ':' (see (2))
2806 * @param $url String: a URL to parse
2807 * @return Array: bits of the URL in an associative array, per PHP docs
2809 function wfParseUrl( $url ) {
2810 global $wgUrlProtocols; // Allow all protocols defined in DefaultSettings/LocalSettings.php
2811 wfSuppressWarnings();
2812 $bits = parse_url( $url );
2813 wfRestoreWarnings();
2818 // most of the protocols are followed by ://, but mailto: and sometimes news: not, check for it
2819 if ( in_array( $bits['scheme'] . '://', $wgUrlProtocols ) ) {
2820 $bits['delimiter'] = '://';
2821 } elseif ( in_array( $bits['scheme'] . ':', $wgUrlProtocols ) ) {
2822 $bits['delimiter'] = ':';
2823 // parse_url detects for news: and mailto: the host part of an url as path
2824 // We have to correct this wrong detection
2825 if ( isset( $bits['path'] ) ) {
2826 $bits['host'] = $bits['path'];
2837 * Make a URL index, appropriate for the el_index field of externallinks.
2839 function wfMakeUrlIndex( $url ) {
2840 $bits = wfParseUrl( $url );
2842 // Reverse the labels in the hostname, convert to lower case
2843 // For emails reverse domainpart only
2844 if ( $bits['scheme'] == 'mailto' ) {
2845 $mailparts = explode( '@', $bits['host'], 2 );
2846 if ( count( $mailparts ) === 2 ) {
2847 $domainpart = strtolower( implode( '.', array_reverse( explode( '.', $mailparts[1] ) ) ) );
2849 // No domain specified, don't mangle it
2852 $reversedHost = $domainpart . '@' . $mailparts[0];
2854 $reversedHost = strtolower( implode( '.', array_reverse( explode( '.', $bits['host'] ) ) ) );
2856 // Add an extra dot to the end
2857 // Why? Is it in wrong place in mailto links?
2858 if ( substr( $reversedHost, -1, 1 ) !== '.' ) {
2859 $reversedHost .= '.';
2861 // Reconstruct the pseudo-URL
2862 $prot = $bits['scheme'];
2863 $index = $prot . $bits['delimiter'] . $reversedHost;
2864 // Leave out user and password. Add the port, path, query and fragment
2865 if ( isset( $bits['port'] ) ) {
2866 $index .= ':' . $bits['port'];
2868 if ( isset( $bits['path'] ) ) {
2869 $index .= $bits['path'];
2873 if ( isset( $bits['query'] ) ) {
2874 $index .= '?' . $bits['query'];
2876 if ( isset( $bits['fragment'] ) ) {
2877 $index .= '#' . $bits['fragment'];
2883 * Do any deferred updates and clear the list
2885 * @param $commit String: set to 'commit' to commit after every update to
2886 * prevent lock contention
2888 function wfDoUpdates( $commit = '' ) {
2889 global $wgDeferredUpdateList;
2891 wfProfileIn( __METHOD__
);
2893 // No need to get master connections in case of empty updates array
2894 if ( !count( $wgDeferredUpdateList ) ) {
2895 wfProfileOut( __METHOD__
);
2899 $doCommit = $commit == 'commit';
2901 $dbw = wfGetDB( DB_MASTER
);
2904 foreach ( $wgDeferredUpdateList as $update ) {
2905 $update->doUpdate();
2907 if ( $doCommit && $dbw->trxLevel() ) {
2912 $wgDeferredUpdateList = array();
2913 wfProfileOut( __METHOD__
);
2917 * Convert an arbitrarily-long digit string from one numeric base
2918 * to another, optionally zero-padding to a minimum column width.
2920 * Supports base 2 through 36; digit values 10-36 are represented
2921 * as lowercase letters a-z. Input is case-insensitive.
2923 * @param $input String: of digits
2924 * @param $sourceBase Integer: 2-36
2925 * @param $destBase Integer: 2-36
2926 * @param $pad Integer: 1 or greater
2927 * @param $lowercase Boolean
2928 * @return String or false on invalid input
2930 function wfBaseConvert( $input, $sourceBase, $destBase, $pad = 1, $lowercase = true ) {
2931 $input = strval( $input );
2932 if( $sourceBase < 2 ||
2937 $sourceBase != intval( $sourceBase ) ||
2938 $destBase != intval( $destBase ) ||
2939 $pad != intval( $pad ) ||
2940 !is_string( $input ) ||
2944 $digitChars = ( $lowercase ) ?
'0123456789abcdefghijklmnopqrstuvwxyz' : '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
2945 $inDigits = array();
2948 // Decode and validate input string
2949 $input = strtolower( $input );
2950 for( $i = 0; $i < strlen( $input ); $i++
) {
2951 $n = strpos( $digitChars, $input{$i} );
2952 if( $n === false ||
$n > $sourceBase ) {
2958 // Iterate over the input, modulo-ing out an output digit
2959 // at a time until input is gone.
2960 while( count( $inDigits ) ) {
2962 $workDigits = array();
2965 foreach( $inDigits as $digit ) {
2966 $work *= $sourceBase;
2969 if( $work < $destBase ) {
2970 // Gonna need to pull another digit.
2971 if( count( $workDigits ) ) {
2972 // Avoid zero-padding; this lets us find
2973 // the end of the input very easily when
2974 // length drops to zero.
2978 // Finally! Actual division!
2979 $workDigits[] = intval( $work / $destBase );
2981 // Isn't it annoying that most programming languages
2982 // don't have a single divide-and-remainder operator,
2983 // even though the CPU implements it that way?
2984 $work = $work %
$destBase;
2988 // All that division leaves us with a remainder,
2989 // which is conveniently our next output digit.
2990 $outChars .= $digitChars[$work];
2993 $inDigits = $workDigits;
2996 while( strlen( $outChars ) < $pad ) {
3000 return strrev( $outChars );
3004 * Create an object with a given name and an array of construct parameters
3005 * @param $name String
3006 * @param $p Array: parameters
3008 function wfCreateObject( $name, $p ) {
3009 $p = array_values( $p );
3010 switch ( count( $p ) ) {
3014 return new $name( $p[0] );
3016 return new $name( $p[0], $p[1] );
3018 return new $name( $p[0], $p[1], $p[2] );
3020 return new $name( $p[0], $p[1], $p[2], $p[3] );
3022 return new $name( $p[0], $p[1], $p[2], $p[3], $p[4] );
3024 return new $name( $p[0], $p[1], $p[2], $p[3], $p[4], $p[5] );
3026 throw new MWException( 'Too many arguments to construtor in wfCreateObject' );
3030 function wfHttpOnlySafe() {
3031 global $wgHttpOnlyBlacklist;
3032 if( !version_compare( '5.2', PHP_VERSION
, '<' ) ) {
3036 if( isset( $_SERVER['HTTP_USER_AGENT'] ) ) {
3037 foreach( $wgHttpOnlyBlacklist as $regex ) {
3038 if( preg_match( $regex, $_SERVER['HTTP_USER_AGENT'] ) ) {
3048 * Initialise php session
3050 function wfSetupSession( $sessionId = false ) {
3051 global $wgSessionsInMemcached, $wgCookiePath, $wgCookieDomain,
3052 $wgCookieSecure, $wgCookieHttpOnly, $wgSessionHandler;
3053 if( $wgSessionsInMemcached ) {
3054 require_once( 'MemcachedSessions.php' );
3055 } elseif( $wgSessionHandler && $wgSessionHandler != ini_get( 'session.save_handler' ) ) {
3056 # Only set this if $wgSessionHandler isn't null and session.save_handler
3057 # hasn't already been set to the desired value (that causes errors)
3058 ini_set( 'session.save_handler', $wgSessionHandler );
3060 $httpOnlySafe = wfHttpOnlySafe();
3061 wfDebugLog( 'cookie',
3062 'session_set_cookie_params: "' . implode( '", "',
3068 $httpOnlySafe && $wgCookieHttpOnly ) ) . '"' );
3069 if( $httpOnlySafe && $wgCookieHttpOnly ) {
3070 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookieHttpOnly );
3072 // PHP 5.1 throws warnings if you pass the HttpOnly parameter for 5.2.
3073 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
3075 session_cache_limiter( 'private, must-revalidate' );
3077 session_id( $sessionId );
3079 wfSuppressWarnings();
3081 wfRestoreWarnings();
3085 * Get an object from the precompiled serialized directory
3087 * @return Mixed: the variable on success, false on failure
3089 function wfGetPrecompiledData( $name ) {
3092 $file = "$IP/serialized/$name";
3093 if ( file_exists( $file ) ) {
3094 $blob = file_get_contents( $file );
3096 return unserialize( $blob );
3102 function wfGetCaller( $level = 2 ) {
3103 $backtrace = wfDebugBacktrace();
3104 if ( isset( $backtrace[$level] ) ) {
3105 return wfFormatStackFrame( $backtrace[$level] );
3107 $caller = 'unknown';
3113 * Return a string consisting of callers in the stack. Useful sometimes
3114 * for profiling specific points.
3116 * @param $limit The maximum depth of the stack frame to return, or false for
3119 function wfGetAllCallers( $limit = 3 ) {
3120 $trace = array_reverse( wfDebugBacktrace() );
3121 if ( !$limit ||
$limit > count( $trace ) - 1 ) {
3122 $limit = count( $trace ) - 1;
3124 $trace = array_slice( $trace, -$limit - 1, $limit );
3125 return implode( '/', array_map( 'wfFormatStackFrame', $trace ) );
3129 * Return a string representation of frame
3131 function wfFormatStackFrame( $frame ) {
3132 return isset( $frame['class'] ) ?
3133 $frame['class'] . '::' . $frame['function'] :
3140 function wfMemcKey( /*... */ ) {
3141 $args = func_get_args();
3142 $key = wfWikiID() . ':' . implode( ':', $args );
3143 $key = str_replace( ' ', '_', $key );
3148 * Get a cache key for a foreign DB
3150 function wfForeignMemcKey( $db, $prefix /*, ... */ ) {
3151 $args = array_slice( func_get_args(), 2 );
3153 $key = "$db-$prefix:" . implode( ':', $args );
3155 $key = $db . ':' . implode( ':', $args );
3161 * Get an ASCII string identifying this wiki
3162 * This is used as a prefix in memcached keys
3164 function wfWikiID() {
3165 global $wgDBprefix, $wgDBname;
3166 if ( $wgDBprefix ) {
3167 return "$wgDBname-$wgDBprefix";
3174 * Split a wiki ID into DB name and table prefix
3176 function wfSplitWikiID( $wiki ) {
3177 $bits = explode( '-', $wiki, 2 );
3178 if ( count( $bits ) < 2 ) {
3185 * Get a Database object.
3186 * @param $db Integer: index of the connection to get. May be DB_MASTER for the
3187 * master (for write queries), DB_SLAVE for potentially lagged read
3188 * queries, or an integer >= 0 for a particular server.
3190 * @param $groups Mixed: query groups. An array of group names that this query
3191 * belongs to. May contain a single string if the query is only
3194 * @param $wiki String: the wiki ID, or false for the current wiki
3196 * Note: multiple calls to wfGetDB(DB_SLAVE) during the course of one request
3197 * will always return the same object, unless the underlying connection or load
3198 * balancer is manually destroyed.
3200 * @return DatabaseBase
3202 function &wfGetDB( $db, $groups = array(), $wiki = false ) {
3203 return wfGetLB( $wiki )->getConnection( $db, $groups, $wiki );
3207 * Get a load balancer object.
3209 * @param $wiki String: wiki ID, or false for the current wiki
3210 * @return LoadBalancer
3212 function wfGetLB( $wiki = false ) {
3213 return wfGetLBFactory()->getMainLB( $wiki );
3217 * Get the load balancer factory object
3220 function &wfGetLBFactory() {
3221 return LBFactory
::singleton();
3226 * Shortcut for RepoGroup::singleton()->findFile()
3227 * @param $title String or Title object
3228 * @param $options Associative array of options:
3229 * time: requested time for an archived image, or false for the
3230 * current version. An image object will be returned which was
3231 * created at the specified time.
3233 * ignoreRedirect: If true, do not follow file redirects
3235 * private: If true, return restricted (deleted) files if the current
3236 * user is allowed to view them. Otherwise, such files will not
3239 * bypassCache: If true, do not use the process-local cache of File objects
3241 * @return File, or false if the file does not exist
3243 function wfFindFile( $title, $options = array() ) {
3244 return RepoGroup
::singleton()->findFile( $title, $options );
3248 * Get an object referring to a locally registered file.
3249 * Returns a valid placeholder object if the file does not exist.
3250 * @param $title Title or String
3251 * @return File, or null if passed an invalid Title
3253 function wfLocalFile( $title ) {
3254 return RepoGroup
::singleton()->getLocalRepo()->newFile( $title );
3258 * Should low-performance queries be disabled?
3262 function wfQueriesMustScale() {
3263 global $wgMiserMode;
3265 ||
( SiteStats
::pages() > 100000
3266 && SiteStats
::edits() > 1000000
3267 && SiteStats
::users() > 10000 );
3271 * Get the path to a specified script file, respecting file
3272 * extensions; this is a wrapper around $wgScriptExtension etc.
3274 * @param $script String: script filename, sans extension
3277 function wfScript( $script = 'index' ) {
3278 global $wgScriptPath, $wgScriptExtension;
3279 return "{$wgScriptPath}/{$script}{$wgScriptExtension}";
3283 * Get the script URL.
3285 * @return script URL
3287 function wfGetScriptUrl() {
3288 if( isset( $_SERVER['SCRIPT_NAME'] ) ) {
3290 # as it was called, minus the query string.
3292 # Some sites use Apache rewrite rules to handle subdomains,
3293 # and have PHP set up in a weird way that causes PHP_SELF
3294 # to contain the rewritten URL instead of the one that the
3295 # outside world sees.
3297 # If in this mode, use SCRIPT_URL instead, which mod_rewrite
3298 # provides containing the "before" URL.
3299 return $_SERVER['SCRIPT_NAME'];
3301 return $_SERVER['URL'];
3306 * Convenience function converts boolean values into "true"
3307 * or "false" (string) values
3309 * @param $value Boolean
3312 function wfBoolToStr( $value ) {
3313 return $value ?
'true' : 'false';
3317 * Load an extension messages file
3318 * @deprecated in 1.16, warnings in 1.18, remove in 1.20
3320 function wfLoadExtensionMessages( $extensionName, $langcode = false ) {
3321 wfDeprecated( __FUNCTION__
);
3325 * Get a platform-independent path to the null file, e.g.
3330 function wfGetNull() {
3331 return wfIsWindows()
3337 * Displays a maxlag error
3339 * @param $host String: server that lags the most
3340 * @param $lag Integer: maxlag (actual)
3341 * @param $maxLag Integer: maxlag (requested)
3343 function wfMaxlagError( $host, $lag, $maxLag ) {
3344 global $wgShowHostnames;
3345 header( 'HTTP/1.1 503 Service Unavailable' );
3346 header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
3347 header( 'X-Database-Lag: ' . intval( $lag ) );
3348 header( 'Content-Type: text/plain' );
3349 if( $wgShowHostnames ) {
3350 echo "Waiting for $host: $lag seconds lagged\n";
3352 echo "Waiting for a database server: $lag seconds lagged\n";
3357 * Throws a warning that $function is deprecated
3358 * @param $function String
3361 function wfDeprecated( $function ) {
3362 static $functionsWarned = array();
3363 if ( !isset( $functionsWarned[$function] ) ) {
3364 $functionsWarned[$function] = true;
3365 wfWarn( "Use of $function is deprecated.", 2 );
3370 * Send a warning either to the debug log or in a PHP error depending on
3371 * $wgDevelopmentWarnings
3373 * @param $msg String: message to send
3374 * @param $callerOffset Integer: number of itmes to go back in the backtrace to
3375 * find the correct caller (1 = function calling wfWarn, ...)
3376 * @param $level Integer: PHP error level; only used when $wgDevelopmentWarnings
3379 function wfWarn( $msg, $callerOffset = 1, $level = E_USER_NOTICE
) {
3380 $callers = wfDebugBacktrace();
3381 if( isset( $callers[$callerOffset +
1] ) ){
3382 $callerfunc = $callers[$callerOffset +
1];
3383 $callerfile = $callers[$callerOffset];
3384 if( isset( $callerfile['file'] ) && isset( $callerfile['line'] ) ) {
3385 $file = $callerfile['file'] . ' at line ' . $callerfile['line'];
3387 $file = '(internal function)';
3390 if( isset( $callerfunc['class'] ) ) {
3391 $func .= $callerfunc['class'] . '::';
3393 if( isset( $callerfunc['function'] ) ) {
3394 $func .= $callerfunc['function'];
3396 $msg .= " [Called from $func in $file]";
3399 global $wgDevelopmentWarnings;
3400 if ( $wgDevelopmentWarnings ) {
3401 trigger_error( $msg, $level );
3403 wfDebug( "$msg\n" );
3408 * Sleep until the worst slave's replication lag is less than or equal to
3409 * $maxLag, in seconds. Use this when updating very large numbers of rows, as
3410 * in maintenance scripts, to avoid causing too much lag. Of course, this is
3411 * a no-op if there are no slaves.
3413 * Every time the function has to wait for a slave, it will print a message to
3414 * that effect (and then sleep for a little while), so it's probably not best
3415 * to use this outside maintenance scripts in its present form.
3417 * @param $maxLag Integer
3418 * @param $wiki mixed Wiki identifier accepted by wfGetLB
3421 function wfWaitForSlaves( $maxLag, $wiki = false ) {
3423 $lb = wfGetLB( $wiki );
3424 list( $host, $lag ) = $lb->getMaxLag( $wiki );
3425 while( $lag > $maxLag ) {
3426 wfSuppressWarnings();
3427 $name = gethostbyaddr( $host );
3428 wfRestoreWarnings();
3429 if( $name !== false ) {
3432 print "Waiting for $host (lagged $lag seconds)...\n";
3434 list( $host, $lag ) = $lb->getMaxLag();
3440 * Used to be used for outputting text in the installer/updater
3441 * @deprecated Warnings in 1.19, removal in 1.20
3443 function wfOut( $s ) {
3444 global $wgCommandLineMode;
3445 if ( $wgCommandLineMode && !defined( 'MEDIAWIKI_INSTALL' ) ) {
3448 echo htmlspecialchars( $s );
3454 * Count down from $n to zero on the terminal, with a one-second pause
3455 * between showing each number. For use in command-line scripts.
3457 function wfCountDown( $n ) {
3458 for ( $i = $n; $i >= 0; $i-- ) {
3460 echo str_repeat( "\x08", strlen( $i +
1 ) );
3472 * Generate a random 32-character hexadecimal token.
3473 * @param $salt Mixed: some sort of salt, if necessary, to add to random
3474 * characters before hashing.
3476 function wfGenerateToken( $salt = '' ) {
3477 $salt = serialize( $salt );
3478 return md5( mt_rand( 0, 0x7fffffff ) . $salt );
3482 * Replace all invalid characters with -
3483 * @param $name Mixed: filename to process
3485 function wfStripIllegalFilenameChars( $name ) {
3486 global $wgIllegalFileChars;
3487 $name = wfBaseName( $name );
3488 $name = preg_replace(
3489 "/[^" . Title
::legalChars() . "]" .
3490 ( $wgIllegalFileChars ?
"|[" . $wgIllegalFileChars . "]" : '' ) .
3499 * Insert array into another array after the specified *KEY*
3500 * @param $array Array: The array.
3501 * @param $insert Array: The array to insert.
3502 * @param $after Mixed: The key to insert after
3504 function wfArrayInsertAfter( $array, $insert, $after ) {
3505 // Find the offset of the element to insert after.
3506 $keys = array_keys( $array );
3507 $offsetByKey = array_flip( $keys );
3509 $offset = $offsetByKey[$after];
3511 // Insert at the specified offset
3512 $before = array_slice( $array, 0, $offset +
1, true );
3513 $after = array_slice( $array, $offset +
1, count( $array ) - $offset, true );
3515 $output = $before +
$insert +
$after;
3520 /* Recursively converts the parameter (an object) to an array with the same data */
3521 function wfObjectToArray( $object, $recursive = true ) {
3523 foreach ( get_object_vars( $object ) as $key => $value ) {
3524 if ( is_object( $value ) && $recursive ) {
3525 $value = wfObjectToArray( $value );
3528 $array[$key] = $value;
3535 * Set PHP's memory limit to the larger of php.ini or $wgMemoryLimit;
3536 * @return Integer value memory was set to.
3538 function wfMemoryLimit() {
3539 global $wgMemoryLimit;
3540 $memlimit = wfShorthandToInteger( ini_get( 'memory_limit' ) );
3541 if( $memlimit != -1 ) {
3542 $conflimit = wfShorthandToInteger( $wgMemoryLimit );
3543 if( $conflimit == -1 ) {
3544 wfDebug( "Removing PHP's memory limit\n" );
3545 wfSuppressWarnings();
3546 ini_set( 'memory_limit', $conflimit );
3547 wfRestoreWarnings();
3549 } elseif ( $conflimit > $memlimit ) {
3550 wfDebug( "Raising PHP's memory limit to $conflimit bytes\n" );
3551 wfSuppressWarnings();
3552 ini_set( 'memory_limit', $conflimit );
3553 wfRestoreWarnings();
3561 * Converts shorthand byte notation to integer form
3562 * @param $string String
3565 function wfShorthandToInteger( $string = '' ) {
3566 $string = trim( $string );
3567 if( $string === '' ) {
3570 $last = $string[strlen( $string ) - 1];
3571 $val = intval( $string );
3576 // break intentionally missing
3580 // break intentionally missing
3590 * Get the normalised IETF language tag
3591 * @param $code String: The language code.
3592 * @return $langCode String: The language code which complying with BCP 47 standards.
3594 function wfBCP47( $code ) {
3595 $codeSegment = explode( '-', $code );
3596 foreach ( $codeSegment as $segNo => $seg ) {
3597 if ( count( $codeSegment ) > 0 ) {
3598 // ISO 3166 country code
3599 if ( ( strlen( $seg ) == 2 ) && ( $segNo > 0 ) ) {
3600 $codeBCP[$segNo] = strtoupper( $seg );
3601 // ISO 15924 script code
3602 } elseif ( ( strlen( $seg ) == 4 ) && ( $segNo > 0 ) ) {
3603 $codeBCP[$segNo] = ucfirst( $seg );
3604 // Use lowercase for other cases
3606 $codeBCP[$segNo] = strtolower( $seg );
3609 // Use lowercase for single segment
3610 $codeBCP[$segNo] = strtolower( $seg );
3613 $langCode = implode( '-', $codeBCP );
3617 function wfArrayMap( $function, $input ) {
3618 $ret = array_map( $function, $input );
3619 foreach ( $ret as $key => $value ) {
3620 $taint = istainted( $input[$key] );
3622 taint( $ret[$key], $taint );