3 * Global functions used everywhere
7 if ( !defined( 'MEDIAWIKI' ) ) {
8 die( "This file is part of MediaWiki, it is not a valid entry point" );
11 require_once dirname( __FILE__ ) . '/normal/UtfNormalUtil.php';
13 // Hide compatibility functions from Doxygen
17 * Compatibility functions
19 * We support PHP 5.1.x and up.
20 * Re-implementations of newer functions or functions in non-standard
21 * PHP extensions may be included here.
23 if( !function_exists( 'iconv' ) ) {
24 # iconv support is not in the default configuration and so may not be present.
25 # Assume will only ever use utf-8 and iso-8859-1.
26 # This will *not* work in all circumstances.
27 function iconv( $from, $to, $string ) {
28 if ( substr( $to, -8 ) == '//IGNORE' ) {
29 $to = substr( $to, 0, strlen( $to ) - 8 );
31 if( strcasecmp( $from, $to ) == 0 ) {
34 if( strcasecmp( $from, 'utf-8' ) == 0 ) {
35 return utf8_decode( $string );
37 if( strcasecmp( $to, 'utf-8' ) == 0 ) {
38 return utf8_encode( $string );
44 if ( !function_exists( 'mb_substr' ) ) {
46 * Fallback implementation for mb_substr, hardcoded to UTF-8.
47 * Attempts to be at least _moderately_ efficient; best optimized
48 * for relatively small offset and count values -- about 5x slower
49 * than native mb_string in my testing.
51 * Larger offsets are still fairly efficient for Latin text, but
52 * can be up to 100x slower than native if the text is heavily
53 * multibyte and we have to slog through a few hundred kb.
55 function mb_substr( $str, $start, $count='end' ) {
57 $split = mb_substr_split_unicode( $str, intval( $start ) );
58 $str = substr( $str, $split );
61 if( $count !== 'end' ) {
62 $split = mb_substr_split_unicode( $str, intval( $count ) );
63 $str = substr( $str, 0, $split );
69 function mb_substr_split_unicode( $str, $splitPos ) {
70 if( $splitPos == 0 ) {
74 $byteLen = strlen( $str );
77 if( $splitPos > 256 ) {
78 // Optimize large string offsets by skipping ahead N bytes.
79 // This will cut out most of our slow time on Latin-based text,
80 // and 1/2 to 1/3 on East European and Asian scripts.
82 while ( $bytePos < $byteLen && $str{$bytePos} >= "\x80" && $str{$bytePos} < "\xc0" ) {
85 $charPos = mb_strlen( substr( $str, 0, $bytePos ) );
91 while( $charPos++ < $splitPos ) {
93 // Move past any tail bytes
94 while ( $bytePos < $byteLen && $str{$bytePos} >= "\x80" && $str{$bytePos} < "\xc0" ) {
99 $splitPosX = $splitPos + 1;
100 $charPos = 0; // relative to end of string; we don't care about the actual char position here
102 while( $bytePos > 0 && $charPos-- >= $splitPosX ) {
104 // Move past any tail bytes
105 while ( $bytePos > 0 && $str{$bytePos} >= "\x80" && $str{$bytePos} < "\xc0" ) {
115 if ( !function_exists( 'mb_strlen' ) ) {
117 * Fallback implementation of mb_strlen, hardcoded to UTF-8.
119 * @param string $enc optional encoding; ignored
122 function mb_strlen( $str, $enc = '' ) {
123 $counts = count_chars( $str );
127 for( $i = 0; $i < 0x80; $i++ ) {
128 $total += $counts[$i];
131 // Count multibyte sequence heads
132 for( $i = 0xc0; $i < 0xff; $i++ ) {
133 $total += $counts[$i];
140 if( !function_exists( 'mb_strpos' ) ) {
142 * Fallback implementation of mb_strpos, hardcoded to UTF-8.
143 * @param $haystack String
144 * @param $needle String
145 * @param $offset String: optional start position
146 * @param $encoding String: optional encoding; ignored
149 function mb_strpos( $haystack, $needle, $offset = 0, $encoding = '' ) {
150 $needle = preg_quote( $needle, '/' );
153 preg_match( '/' . $needle . '/u', $haystack, $ar, PREG_OFFSET_CAPTURE, $offset );
155 if( isset( $ar[0][1] ) ) {
163 if( !function_exists( 'mb_strrpos' ) ) {
165 * Fallback implementation of mb_strrpos, hardcoded to UTF-8.
166 * @param $haystack String
167 * @param $needle String
168 * @param $offset String: optional start position
169 * @param $encoding String: optional encoding; ignored
172 function mb_strrpos( $haystack, $needle, $offset = 0, $encoding = '' ) {
173 $needle = preg_quote( $needle, '/' );
176 preg_match_all( '/' . $needle . '/u', $haystack, $ar, PREG_OFFSET_CAPTURE, $offset );
178 if( isset( $ar[0] ) && count( $ar[0] ) > 0 &&
179 isset( $ar[0][count( $ar[0] ) - 1][1] ) ) {
180 return $ar[0][count( $ar[0] ) - 1][1];
187 // Support for Wietse Venema's taint feature
188 if ( !function_exists( 'istainted' ) ) {
189 function istainted( $var ) {
192 function taint( $var, $level = 0 ) {}
193 function untaint( $var, $level = 0 ) {}
194 define( 'TC_HTML', 1 );
195 define( 'TC_SHELL', 1 );
196 define( 'TC_MYSQL', 1 );
197 define( 'TC_PCRE', 1 );
198 define( 'TC_SELF', 1 );
201 // array_fill_keys() was only added in 5.2, but people use it anyway
202 // add a back-compat layer for 5.1. See bug 27781
203 if( !function_exists( 'array_fill_keys' ) ) {
204 function array_fill_keys( $keys, $value ) {
205 return array_combine( $keys, array_fill( 0, count( $keys ), $value ) );
214 * Like array_diff( $a, $b ) except that it works with two-dimensional arrays.
216 function wfArrayDiff2( $a, $b ) {
217 return array_udiff( $a, $b, 'wfArrayDiff2_cmp' );
219 function wfArrayDiff2_cmp( $a, $b ) {
220 if ( !is_array( $a ) ) {
221 return strcmp( $a, $b );
222 } elseif ( count( $a ) !== count( $b ) ) {
223 return count( $a ) < count( $b ) ? -1 : 1;
227 while( ( list( , $valueA ) = each( $a ) ) && ( list( , $valueB ) = each( $b ) ) ) {
228 $cmp = strcmp( $valueA, $valueB );
238 * Seed Mersenne Twister
239 * No-op for compatibility; only necessary in PHP < 4.2.0
240 * @deprecated. Remove in 1.18
242 function wfSeedRandom() {
243 wfDeprecated(__FUNCTION__);
247 * Get a random decimal value between 0 and 1, in a way
248 * not likely to give duplicate values for any realistic
249 * number of articles.
253 function wfRandom() {
254 # The maximum random value is "only" 2^31-1, so get two random
255 # values to reduce the chance of dupes
256 $max = mt_getrandmax() + 1;
257 $rand = number_format( ( mt_rand() * $max + mt_rand() )
258 / $max / $max, 12, '.', '' );
263 * We want some things to be included as literal characters in our title URLs
264 * for prettiness, which urlencode encodes by default. According to RFC 1738,
265 * all of the following should be safe:
269 * But + is not safe because it's used to indicate a space; &= are only safe in
270 * paths and not in queries (and we don't distinguish here); ' seems kind of
271 * scary; and urlencode() doesn't touch -_. to begin with. Plus, although /
272 * is reserved, we don't care. So the list we unescape is:
276 * However, IIS7 redirects fail when the url contains a colon (Bug 22709),
277 * so no fancy : for IIS7.
279 * %2F in the page titles seems to fatally break for some reason.
284 function wfUrlencode( $s ) {
286 if ( is_null( $needle ) ) {
287 $needle = array( '%3B', '%40', '%24', '%21', '%2A', '%28', '%29', '%2C', '%2F' );
288 if ( !isset( $_SERVER['SERVER_SOFTWARE'] ) || ( strpos( $_SERVER['SERVER_SOFTWARE'], 'Microsoft-IIS/7' ) === false ) ) {
293 $s = urlencode( $s );
296 array( ';', '@', '$', '!', '*', '(', ')', ',', '/', ':' ),
304 * Sends a line to the debug log if enabled or, optionally, to a comment in output.
305 * In normal operation this is a NOP.
307 * Controlling globals:
308 * $wgDebugLogFile - points to the log file
309 * $wgProfileOnly - if set, normal debug messages will not be recorded.
310 * $wgDebugRawPage - if false, 'action=raw' hits will not result in debug output.
311 * $wgDebugComments - if on, some debug items may appear in comments in the HTML output.
313 * @param $text String
314 * @param $logonly Bool: set true to avoid appearing in HTML when $wgDebugComments is set
316 function wfDebug( $text, $logonly = false ) {
317 global $wgOut, $wgDebugLogFile, $wgDebugComments, $wgProfileOnly, $wgDebugRawPage;
318 global $wgDebugLogPrefix, $wgShowDebug;
319 static $recursion = 0;
321 static $cache = array(); // Cache of unoutputted messages
322 $text = wfDebugTimer() . $text;
324 # Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
325 if ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' && !$wgDebugRawPage ) {
329 if ( ( $wgDebugComments || $wgShowDebug ) && !$logonly ) {
332 if ( !isset( $wgOut ) ) {
335 if ( !StubObject::isRealObject( $wgOut ) ) {
344 // add the message and possible cached ones to the output
345 array_map( array( $wgOut, 'debug' ), $cache );
348 if ( $wgDebugLogFile != '' && !$wgProfileOnly ) {
349 # Strip unprintables; they can switch terminal modes when binary data
350 # gets dumped, which is pretty annoying.
351 $text = preg_replace( '![\x00-\x08\x0b\x0c\x0e-\x1f]!', ' ', $text );
352 $text = $wgDebugLogPrefix . $text;
353 wfErrorLog( $text, $wgDebugLogFile );
357 function wfDebugTimer() {
358 global $wgDebugTimestamps;
359 if ( !$wgDebugTimestamps ) {
362 static $start = null;
364 if ( $start === null ) {
365 $start = microtime( true );
366 $prefix = "\n$start";
368 $prefix = sprintf( "%6.4f", microtime( true ) - $start );
371 return $prefix . ' ';
375 * Send a line giving PHP memory usage.
376 * @param $exact Bool: print exact values instead of kilobytes (default: false)
378 function wfDebugMem( $exact = false ) {
379 $mem = memory_get_usage();
381 $mem = floor( $mem / 1024 ) . ' kilobytes';
385 wfDebug( "Memory usage: $mem\n" );
389 * Send a line to a supplementary debug log file, if configured, or main debug log if not.
390 * $wgDebugLogGroups[$logGroup] should be set to a filename to send to a separate log.
392 * @param $logGroup String
393 * @param $text String
394 * @param $public Bool: whether to log the event in the public log if no private
395 * log file is specified, (default true)
397 function wfDebugLog( $logGroup, $text, $public = true ) {
398 global $wgDebugLogGroups, $wgShowHostnames;
399 $text = trim( $text ) . "\n";
400 if( isset( $wgDebugLogGroups[$logGroup] ) ) {
401 $time = wfTimestamp( TS_DB );
403 if ( $wgShowHostnames ) {
404 $host = wfHostname();
408 wfErrorLog( "$time $host $wiki: $text", $wgDebugLogGroups[$logGroup] );
409 } elseif ( $public === true ) {
410 wfDebug( $text, true );
415 * Log for database errors
416 * @param $text String: database error message.
418 function wfLogDBError( $text ) {
419 global $wgDBerrorLog, $wgDBname;
420 if ( $wgDBerrorLog ) {
421 $host = trim(`hostname`);
422 $text = date( 'D M j G:i:s T Y' ) . "\t$host\t$wgDBname\t$text";
423 wfErrorLog( $text, $wgDBerrorLog );
428 * Log to a file without getting "file size exceeded" signals.
430 * Can also log to TCP or UDP with the syntax udp://host:port/prefix. This will
431 * send lines to the specified port, prefixed by the specified prefix and a space.
433 function wfErrorLog( $text, $file ) {
434 if ( substr( $file, 0, 4 ) == 'udp:' ) {
435 # Needs the sockets extension
436 if ( preg_match( '!^(tcp|udp):(?://)?\[([0-9a-fA-F:]+)\]:(\d+)(?:/(.*))?$!', $file, $m ) ) {
437 // IPv6 bracketed host
439 $port = intval( $m[3] );
440 $prefix = isset( $m[4] ) ? $m[4] : false;
442 } elseif ( preg_match( '!^(tcp|udp):(?://)?([a-zA-Z0-9.-]+):(\d+)(?:/(.*))?$!', $file, $m ) ) {
444 if ( !IP::isIPv4( $host ) ) {
445 $host = gethostbyname( $host );
447 $port = intval( $m[3] );
448 $prefix = isset( $m[4] ) ? $m[4] : false;
451 throw new MWException( __METHOD__ . ': Invalid UDP specification' );
453 // Clean it up for the multiplexer
454 if ( strval( $prefix ) !== '' ) {
455 $text = preg_replace( '/^/m', $prefix . ' ', $text );
456 if ( substr( $text, -1 ) != "\n" ) {
461 $sock = socket_create( $domain, SOCK_DGRAM, SOL_UDP );
465 socket_sendto( $sock, $text, strlen( $text ), 0, $host, $port );
466 socket_close( $sock );
468 wfSuppressWarnings();
469 $exists = file_exists( $file );
470 $size = $exists ? filesize( $file ) : false;
471 if ( !$exists || ( $size !== false && $size + strlen( $text ) < 0x7fffffff ) ) {
472 error_log( $text, 3, $file );
481 function wfLogProfilingData() {
482 global $wgRequestTime, $wgDebugLogFile, $wgDebugRawPage, $wgRequest;
483 global $wgProfiler, $wgProfileLimit, $wgUser;
484 # Profiling must actually be enabled...
485 if( is_null( $wgProfiler ) ) {
488 # Get total page request time
490 $elapsed = $now - $wgRequestTime;
491 # Only show pages that longer than $wgProfileLimit time (default is 0)
492 if( $elapsed <= $wgProfileLimit ) {
495 $prof = wfGetProfilingOutput( $wgRequestTime, $elapsed );
497 if( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) {
498 $forward = ' forwarded for ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
500 if( !empty( $_SERVER['HTTP_CLIENT_IP'] ) ) {
501 $forward .= ' client IP ' . $_SERVER['HTTP_CLIENT_IP'];
503 if( !empty( $_SERVER['HTTP_FROM'] ) ) {
504 $forward .= ' from ' . $_SERVER['HTTP_FROM'];
507 $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
509 // Don't unstub $wgUser at this late stage just for statistics purposes
510 // FIXME: We can detect some anons even if it is not loaded. See User::getId()
511 if( $wgUser->mDataLoaded && $wgUser->isAnon() ) {
514 $log = sprintf( "%s\t%04.3f\t%s\n",
515 gmdate( 'YmdHis' ), $elapsed,
516 urldecode( $wgRequest->getRequestURL() . $forward ) );
517 if ( $wgDebugLogFile != '' && ( $wgRequest->getVal( 'action' ) != 'raw' || $wgDebugRawPage ) ) {
518 wfErrorLog( $log . $prof, $wgDebugLogFile );
523 * Check if the wiki read-only lock file is present. This can be used to lock
524 * off editing functions, but doesn't guarantee that the database will not be
528 function wfReadOnly() {
529 global $wgReadOnlyFile, $wgReadOnly;
531 if ( !is_null( $wgReadOnly ) ) {
532 return (bool)$wgReadOnly;
534 if ( $wgReadOnlyFile == '' ) {
537 // Set $wgReadOnly for faster access next time
538 if ( is_file( $wgReadOnlyFile ) ) {
539 $wgReadOnly = file_get_contents( $wgReadOnlyFile );
543 return (bool)$wgReadOnly;
546 function wfReadOnlyReason() {
553 * Return a Language object from $langcode
554 * @param $langcode Mixed: either:
555 * - a Language object
556 * - code of the language to get the message for, if it is
557 * a valid code create a language for that language, if
558 * it is a string but not a valid code then make a basic
560 * - a boolean: if it's false then use the current users
561 * language (as a fallback for the old parameter
562 * functionality), or if it is true then use the wikis
563 * @return Language object
565 function wfGetLangObj( $langcode = false ) {
566 # Identify which language to get or create a language object for.
567 # Using is_object here due to Stub objects.
568 if( is_object( $langcode ) ) {
569 # Great, we already have the object (hopefully)!
573 global $wgContLang, $wgLanguageCode;
574 if( $langcode === true || $langcode === $wgLanguageCode ) {
575 # $langcode is the language code of the wikis content language object.
576 # or it is a boolean and value is true
581 if( $langcode === false || $langcode === $wgLang->getCode() ) {
582 # $langcode is the language code of user language object.
583 # or it was a boolean and value is false
587 $validCodes = array_keys( Language::getLanguageNames() );
588 if( in_array( $langcode, $validCodes ) ) {
589 # $langcode corresponds to a valid language.
590 return Language::factory( $langcode );
593 # $langcode is a string, but not a valid language code; use content language.
594 wfDebug( "Invalid language code passed to wfGetLangObj, falling back to content language.\n" );
599 * Use this instead of $wgContLang, when working with user interface.
600 * User interface is currently hard coded according to wiki content language
601 * in many ways, especially regarding to text direction. There is lots stuff
602 * to fix, hence this function to keep the old behaviour unless the global
603 * $wgBetterDirectionality is enabled (or removed when everything works).
605 function wfUILang() {
606 global $wgBetterDirectionality;
607 return wfGetLangObj( !$wgBetterDirectionality );
611 * This is the new function for getting translated interface messages.
612 * See the Message class for documentation how to use them.
613 * The intention is that this function replaces all old wfMsg* functions.
614 * @param $key \string Message key.
615 * Varargs: normal message parameters.
616 * @return \type{Message}
619 function wfMessage( $key /*...*/) {
620 $params = func_get_args();
621 array_shift( $params );
622 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
623 $params = $params[0];
625 return new Message( $key, $params );
629 * Get a message from anywhere, for the current user language.
631 * Use wfMsgForContent() instead if the message should NOT
632 * change depending on the user preferences.
634 * @param $key String: lookup key for the message, usually
635 * defined in languages/Language.php
637 * This function also takes extra optional parameters (not
638 * shown in the function definition), which can be used to
639 * insert variable text into the predefined message.
641 function wfMsg( $key ) {
642 $args = func_get_args();
643 array_shift( $args );
644 return wfMsgReal( $key, $args, true );
648 * Same as above except doesn't transform the message
650 function wfMsgNoTrans( $key ) {
651 $args = func_get_args();
652 array_shift( $args );
653 return wfMsgReal( $key, $args, true, false, false );
657 * Get a message from anywhere, for the current global language
658 * set with $wgLanguageCode.
660 * Use this if the message should NOT change dependent on the
661 * language set in the user's preferences. This is the case for
662 * most text written into logs, as well as link targets (such as
663 * the name of the copyright policy page). Link titles, on the
664 * other hand, should be shown in the UI language.
666 * Note that MediaWiki allows users to change the user interface
667 * language in their preferences, but a single installation
668 * typically only contains content in one language.
670 * Be wary of this distinction: If you use wfMsg() where you should
671 * use wfMsgForContent(), a user of the software may have to
672 * customize potentially hundreds of messages in
673 * order to, e.g., fix a link in every possible language.
675 * @param $key String: lookup key for the message, usually
676 * defined in languages/Language.php
678 function wfMsgForContent( $key ) {
679 global $wgForceUIMsgAsContentMsg;
680 $args = func_get_args();
681 array_shift( $args );
683 if( is_array( $wgForceUIMsgAsContentMsg ) &&
684 in_array( $key, $wgForceUIMsgAsContentMsg ) )
688 return wfMsgReal( $key, $args, true, $forcontent );
692 * Same as above except doesn't transform the message
694 function wfMsgForContentNoTrans( $key ) {
695 global $wgForceUIMsgAsContentMsg;
696 $args = func_get_args();
697 array_shift( $args );
699 if( is_array( $wgForceUIMsgAsContentMsg ) &&
700 in_array( $key, $wgForceUIMsgAsContentMsg ) )
704 return wfMsgReal( $key, $args, true, $forcontent, false );
708 * Get a message from the language file, for the UI elements
710 function wfMsgNoDB( $key ) {
711 $args = func_get_args();
712 array_shift( $args );
713 return wfMsgReal( $key, $args, false );
717 * Get a message from the language file, for the content
719 function wfMsgNoDBForContent( $key ) {
720 global $wgForceUIMsgAsContentMsg;
721 $args = func_get_args();
722 array_shift( $args );
724 if( is_array( $wgForceUIMsgAsContentMsg ) &&
725 in_array( $key, $wgForceUIMsgAsContentMsg ) )
729 return wfMsgReal( $key, $args, false, $forcontent );
734 * Really get a message
735 * @param $key String: key to get.
737 * @param $useDB Boolean
738 * @param $forContent Mixed: Language code, or false for user lang, true for content lang.
739 * @param $transform Boolean: Whether or not to transform the message.
740 * @return String: the requested message.
742 function wfMsgReal( $key, $args, $useDB = true, $forContent = false, $transform = true ) {
743 wfProfileIn( __METHOD__ );
744 $message = wfMsgGetKey( $key, $useDB, $forContent, $transform );
745 $message = wfMsgReplaceArgs( $message, $args );
746 wfProfileOut( __METHOD__ );
751 * This function provides the message source for messages to be edited which are *not* stored in the database.
752 * @param $key String:
754 function wfMsgWeirdKey( $key ) {
755 $source = wfMsgGetKey( $key, false, true, false );
756 if ( wfEmptyMsg( $key, $source ) ) {
764 * Fetch a message string value, but don't replace any keys yet.
767 * @param $langCode String: Code of the language to get the message for, or
768 * behaves as a content language switch if it is a boolean.
769 * @param $transform Boolean: whether to parse magic words, etc.
772 function wfMsgGetKey( $key, $useDB, $langCode = false, $transform = true ) {
773 global $wgMessageCache;
775 wfRunHooks( 'NormalizeMessageKey', array( &$key, &$useDB, &$langCode, &$transform ) );
777 if ( !is_object( $wgMessageCache ) ) {
778 throw new MWException( 'Trying to get message before message cache is initialised' );
781 $message = $wgMessageCache->get( $key, $useDB, $langCode );
782 if( $message === false ) {
783 $message = '<' . htmlspecialchars( $key ) . '>';
784 } elseif ( $transform ) {
785 $message = $wgMessageCache->transform( $message );
791 * Replace message parameter keys on the given formatted output.
793 * @param $message String
798 function wfMsgReplaceArgs( $message, $args ) {
799 # Fix windows line-endings
800 # Some messages are split with explode("\n", $msg)
801 $message = str_replace( "\r", '', $message );
804 if ( count( $args ) ) {
805 if ( is_array( $args[0] ) ) {
806 $args = array_values( $args[0] );
808 $replacementKeys = array();
809 foreach( $args as $n => $param ) {
810 $replacementKeys['$' . ( $n + 1 )] = $param;
812 $message = strtr( $message, $replacementKeys );
819 * Return an HTML-escaped version of a message.
820 * Parameter replacements, if any, are done *after* the HTML-escaping,
821 * so parameters may contain HTML (eg links or form controls). Be sure
822 * to pre-escape them if you really do want plaintext, or just wrap
823 * the whole thing in htmlspecialchars().
826 * @param string ... parameters
829 function wfMsgHtml( $key ) {
830 $args = func_get_args();
831 array_shift( $args );
832 return wfMsgReplaceArgs( htmlspecialchars( wfMsgGetKey( $key, true ) ), $args );
836 * Return an HTML version of message
837 * Parameter replacements, if any, are done *after* parsing the wiki-text message,
838 * so parameters may contain HTML (eg links or form controls). Be sure
839 * to pre-escape them if you really do want plaintext, or just wrap
840 * the whole thing in htmlspecialchars().
843 * @param string ... parameters
846 function wfMsgWikiHtml( $key ) {
848 $args = func_get_args();
849 array_shift( $args );
850 return wfMsgReplaceArgs( $wgOut->parse( wfMsgGetKey( $key, true ), /* can't be set to false */ true ), $args );
854 * Returns message in the requested format
855 * @param $key String: key of the message
856 * @param $options Array: processing rules. Can take the following options:
857 * <i>parse</i>: parses wikitext to HTML
858 * <i>parseinline</i>: parses wikitext to HTML and removes the surrounding
859 * p's added by parser or tidy
860 * <i>escape</i>: filters message through htmlspecialchars
861 * <i>escapenoentities</i>: same, but allows entity references like   through
862 * <i>replaceafter</i>: parameters are substituted after parsing or escaping
863 * <i>parsemag</i>: transform the message using magic phrases
864 * <i>content</i>: fetch message for content language instead of interface
865 * Also can accept a single associative argument, of the form 'language' => 'xx':
866 * <i>language</i>: Language object or language code to fetch message for
867 * (overriden by <i>content</i>), its behaviour with parse, parseinline
868 * and parsemag is undefined.
869 * Behavior for conflicting options (e.g., parse+parseinline) is undefined.
871 function wfMsgExt( $key, $options ) {
874 $args = func_get_args();
875 array_shift( $args );
876 array_shift( $args );
877 $options = (array)$options;
879 foreach( $options as $arrayKey => $option ) {
880 if( !preg_match( '/^[0-9]+|language$/', $arrayKey ) ) {
881 # An unknown index, neither numeric nor "language"
882 wfWarn( "wfMsgExt called with incorrect parameter key $arrayKey", 1, E_USER_WARNING );
883 } elseif( preg_match( '/^[0-9]+$/', $arrayKey ) && !in_array( $option,
884 array( 'parse', 'parseinline', 'escape', 'escapenoentities',
885 'replaceafter', 'parsemag', 'content' ) ) ) {
886 # A numeric index with unknown value
887 wfWarn( "wfMsgExt called with incorrect parameter $option", 1, E_USER_WARNING );
891 if( in_array( 'content', $options, true ) ) {
894 } elseif( array_key_exists( 'language', $options ) ) {
896 $langCode = wfGetLangObj( $options['language'] );
902 $string = wfMsgGetKey( $key, /*DB*/true, $langCode, /*Transform*/false );
904 if( !in_array( 'replaceafter', $options, true ) ) {
905 $string = wfMsgReplaceArgs( $string, $args );
908 if( in_array( 'parse', $options, true ) ) {
909 $string = $wgOut->parse( $string, true, !$forContent );
910 } elseif ( in_array( 'parseinline', $options, true ) ) {
911 $string = $wgOut->parse( $string, true, !$forContent );
913 if( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $string, $m ) ) {
916 } elseif ( in_array( 'parsemag', $options, true ) ) {
917 global $wgMessageCache;
918 if ( isset( $wgMessageCache ) ) {
919 $string = $wgMessageCache->transform( $string,
921 is_object( $langCode ) ? $langCode : null );
925 if ( in_array( 'escape', $options, true ) ) {
926 $string = htmlspecialchars ( $string );
927 } elseif ( in_array( 'escapenoentities', $options, true ) ) {
928 $string = Sanitizer::escapeHtmlAllowEntities( $string );
931 if( in_array( 'replaceafter', $options, true ) ) {
932 $string = wfMsgReplaceArgs( $string, $args );
940 * Just like exit() but makes a note of it.
941 * Commits open transactions except if the error parameter is set
943 * @deprecated Please return control to the caller or throw an exception. Will
944 * be removed in 1.19.
946 function wfAbruptExit( $error = false ) {
947 static $called = false;
953 wfDeprecated( __FUNCTION__ );
954 $bt = wfDebugBacktrace();
956 for( $i = 0; $i < count( $bt ); $i++ ) {
957 $file = isset( $bt[$i]['file'] ) ? $bt[$i]['file'] : 'unknown';
958 $line = isset( $bt[$i]['line'] ) ? $bt[$i]['line'] : 'unknown';
959 wfDebug( "WARNING: Abrupt exit in $file at line $line\n");
962 wfDebug( "WARNING: Abrupt exit\n" );
965 wfLogProfilingData();
968 wfGetLB()->closeAll();
974 * @deprecated Please return control the caller or throw an exception. Will
975 * be removed in 1.19.
977 function wfErrorExit() {
978 wfDeprecated( __FUNCTION__ );
979 wfAbruptExit( true );
983 * Print a simple message and die, returning nonzero to the shell if any.
984 * Plain die() fails to return nonzero to the shell if you pass a string.
987 function wfDie( $msg = '' ) {
993 * Throw a debugging exception. This function previously once exited the process,
994 * but now throws an exception instead, with similar results.
996 * @param $msg String: message shown when dieing.
998 function wfDebugDieBacktrace( $msg = '' ) {
999 throw new MWException( $msg );
1003 * Fetch server name for use in error reporting etc.
1004 * Use real server name if available, so we know which machine
1005 * in a server farm generated the current page.
1008 function wfHostname() {
1010 if ( is_null( $host ) ) {
1011 if ( function_exists( 'posix_uname' ) ) {
1012 // This function not present on Windows
1013 $uname = @posix_uname();
1017 if( is_array( $uname ) && isset( $uname['nodename'] ) ) {
1018 $host = $uname['nodename'];
1019 } elseif ( getenv( 'COMPUTERNAME' ) ) {
1020 # Windows computer name
1021 $host = getenv( 'COMPUTERNAME' );
1023 # This may be a virtual server.
1024 $host = $_SERVER['SERVER_NAME'];
1031 * Returns a HTML comment with the elapsed time since request.
1032 * This method has no side effects.
1035 function wfReportTime() {
1036 global $wgRequestTime, $wgShowHostnames;
1039 $elapsed = $now - $wgRequestTime;
1041 return $wgShowHostnames
1042 ? sprintf( '<!-- Served by %s in %01.3f secs. -->', wfHostname(), $elapsed )
1043 : sprintf( '<!-- Served in %01.3f secs. -->', $elapsed );
1047 * Safety wrapper for debug_backtrace().
1049 * With Zend Optimizer 3.2.0 loaded, this causes segfaults under somewhat
1050 * murky circumstances, which may be triggered in part by stub objects
1051 * or other fancy talkin'.
1053 * Will return an empty array if Zend Optimizer is detected or if
1054 * debug_backtrace is disabled, otherwise the output from
1055 * debug_backtrace() (trimmed).
1057 * @return array of backtrace information
1059 function wfDebugBacktrace() {
1060 static $disabled = null;
1062 if( extension_loaded( 'Zend Optimizer' ) ) {
1063 wfDebug( "Zend Optimizer detected; skipping debug_backtrace for safety.\n" );
1067 if ( is_null( $disabled ) ) {
1069 $functions = explode( ',', ini_get( 'disable_functions' ) );
1070 $functions = array_map( 'trim', $functions );
1071 $functions = array_map( 'strtolower', $functions );
1072 if ( in_array( 'debug_backtrace', $functions ) ) {
1073 wfDebug( "debug_backtrace is in disabled_functions\n" );
1081 return array_slice( debug_backtrace(), 1 );
1084 function wfBacktrace() {
1085 global $wgCommandLineMode;
1087 if ( $wgCommandLineMode ) {
1092 $backtrace = wfDebugBacktrace();
1093 foreach( $backtrace as $call ) {
1094 if( isset( $call['file'] ) ) {
1095 $f = explode( DIRECTORY_SEPARATOR, $call['file'] );
1096 $file = $f[count( $f ) - 1];
1100 if( isset( $call['line'] ) ) {
1101 $line = $call['line'];
1105 if ( $wgCommandLineMode ) {
1106 $msg .= "$file line $line calls ";
1108 $msg .= '<li>' . $file . ' line ' . $line . ' calls ';
1110 if( !empty( $call['class'] ) ) {
1111 $msg .= $call['class'] . '::';
1113 $msg .= $call['function'] . '()';
1115 if ( $wgCommandLineMode ) {
1121 if ( $wgCommandLineMode ) {
1131 /* Some generic result counters, pulled out of SearchEngine */
1137 function wfShowingResults( $offset, $limit ) {
1141 array( 'parseinline' ),
1142 $wgLang->formatNum( $limit ),
1143 $wgLang->formatNum( $offset + 1 )
1150 function wfShowingResultsNum( $offset, $limit, $num ) {
1153 'showingresultsnum',
1154 array( 'parseinline' ),
1155 $wgLang->formatNum( $limit ),
1156 $wgLang->formatNum( $offset + 1 ),
1157 $wgLang->formatNum( $num )
1162 * Generate (prev x| next x) (20|50|100...) type links for paging
1163 * @param $offset String
1164 * @param $limit Integer
1165 * @param $link String
1166 * @param $query String: optional URL query parameter string
1167 * @param $atend Bool: optional param for specified if this is the last page
1169 function wfViewPrevNext( $offset, $limit, $link, $query = '', $atend = false ) {
1171 $fmtLimit = $wgLang->formatNum( $limit );
1172 // FIXME: Why on earth this needs one message for the text and another one for tooltip??
1173 # Get prev/next link display text
1174 $prev = wfMsgExt( 'prevn', array( 'parsemag', 'escape' ), $fmtLimit );
1175 $next = wfMsgExt( 'nextn', array( 'parsemag', 'escape' ), $fmtLimit );
1176 # Get prev/next link title text
1177 $pTitle = wfMsgExt( 'prevn-title', array( 'parsemag', 'escape' ), $fmtLimit );
1178 $nTitle = wfMsgExt( 'nextn-title', array( 'parsemag', 'escape' ), $fmtLimit );
1179 # Fetch the title object
1180 if( is_object( $link ) ) {
1183 $title = Title::newFromText( $link );
1184 if( is_null( $title ) ) {
1188 # Make 'previous' link
1189 if( 0 != $offset ) {
1190 $po = $offset - $limit;
1191 $po = max( $po, 0 );
1192 $q = "limit={$limit}&offset={$po}";
1193 if( $query != '' ) {
1196 $plink = '<a href="' . $title->escapeLocalURL( $q ) . "\" title=\"{$pTitle}\" class=\"mw-prevlink\">{$prev}</a>";
1201 $no = $offset + $limit;
1202 $q = "limit={$limit}&offset={$no}";
1203 if( $query != '' ) {
1209 $nlink = '<a href="' . $title->escapeLocalURL( $q ) . "\" title=\"{$nTitle}\" class=\"mw-nextlink\">{$next}</a>";
1211 # Make links to set number of items per page
1212 $nums = $wgLang->pipeList( array(
1213 wfNumLink( $offset, 20, $title, $query ),
1214 wfNumLink( $offset, 50, $title, $query ),
1215 wfNumLink( $offset, 100, $title, $query ),
1216 wfNumLink( $offset, 250, $title, $query ),
1217 wfNumLink( $offset, 500, $title, $query )
1219 return wfMsgHtml( 'viewprevnext', $plink, $nlink, $nums );
1223 * Generate links for (20|50|100...) items-per-page links
1224 * @param $offset String
1225 * @param $limit Integer
1226 * @param $title Title
1227 * @param $query String: optional URL query parameter string
1229 function wfNumLink( $offset, $limit, $title, $query = '' ) {
1231 if( $query == '' ) {
1236 $q .= "limit={$limit}&offset={$offset}";
1237 $fmtLimit = $wgLang->formatNum( $limit );
1238 $lTitle = wfMsgExt( 'shown-title', array( 'parsemag', 'escape' ), $limit );
1239 $s = '<a href="' . $title->escapeLocalURL( $q ) . "\" title=\"{$lTitle}\" class=\"mw-numlink\">{$fmtLimit}</a>";
1245 * @todo FIXME: we may want to blacklist some broken browsers
1247 * @return bool Whereas client accept gzip compression
1249 function wfClientAcceptsGzip() {
1250 static $result = null;
1251 if ( $result === null ) {
1253 if( isset( $_SERVER['HTTP_ACCEPT_ENCODING'] ) ) {
1254 # FIXME: we may want to blacklist some broken browsers
1257 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
1258 $_SERVER['HTTP_ACCEPT_ENCODING'],
1262 if( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) {
1266 wfDebug( " accepts gzip\n" );
1275 * Obtain the offset and limit values from the request string;
1276 * used in special pages
1278 * @param $deflimit Default limit if none supplied
1279 * @param $optionname Name of a user preference to check against
1283 function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) {
1285 return $wgRequest->getLimitOffset( $deflimit, $optionname );
1289 * Escapes the given text so that it may be output using addWikiText()
1290 * without any linking, formatting, etc. making its way through. This
1291 * is achieved by substituting certain characters with HTML entities.
1292 * As required by the callers, <nowiki> is not used. It currently does
1293 * not filter out characters which have special meaning only at the
1294 * start of a line, such as "*".
1296 * @param $text String: text to be escaped
1298 function wfEscapeWikiText( $text ) {
1299 $text = str_replace(
1300 array( '[', '|', ']', '\'', 'ISBN ',
1301 'RFC ', '://', "\n=", '{{', '}}' ),
1302 array( '[', '|', ']', ''', 'ISBN ',
1303 'RFC ', '://', "\n=", '{{', '}}' ),
1304 htmlspecialchars( $text )
1312 function wfQuotedPrintable( $string, $charset = '' ) {
1313 # Probably incomplete; see RFC 2045
1314 if( empty( $charset ) ) {
1315 global $wgInputEncoding;
1316 $charset = $wgInputEncoding;
1318 $charset = strtoupper( $charset );
1319 $charset = str_replace( 'ISO-8859', 'ISO8859', $charset ); // ?
1321 $illegal = '\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\xff=';
1322 $replace = $illegal . '\t ?_';
1323 if( !preg_match( "/[$illegal]/", $string ) ) {
1326 $out = "=?$charset?Q?";
1327 $out .= preg_replace( "/([$replace])/e", 'sprintf("=%02X",ord("$1"))', $string );
1338 return microtime( true );
1342 * Sets dest to source and returns the original value of dest
1343 * If source is NULL, it just returns the value, it doesn't set the variable
1344 * If force is true, it will set the value even if source is NULL
1346 function wfSetVar( &$dest, $source, $force = false ) {
1348 if ( !is_null( $source ) || $force ) {
1355 * As for wfSetVar except setting a bit
1357 function wfSetBit( &$dest, $bit, $state = true ) {
1358 $temp = (bool)( $dest & $bit );
1359 if ( !is_null( $state ) ) {
1370 * This function takes two arrays as input, and returns a CGI-style string, e.g.
1371 * "days=7&limit=100". Options in the first array override options in the second.
1372 * Options set to "" will not be output.
1374 function wfArrayToCGI( $array1, $array2 = null ) {
1375 if ( !is_null( $array2 ) ) {
1376 $array1 = $array1 + $array2;
1380 foreach ( $array1 as $key => $value ) {
1381 if ( $value !== '' ) {
1385 if ( is_array( $value ) ) {
1387 foreach ( $value as $v ) {
1388 $cgi .= ( $firstTime ? '' : '&') .
1389 urlencode( $key . '[]' ) . '=' .
1394 if ( is_object( $value ) ) {
1395 $value = $value->__toString();
1397 $cgi .= urlencode( $key ) . '=' .
1398 urlencode( $value );
1406 * This is the logical opposite of wfArrayToCGI(): it accepts a query string as
1407 * its argument and returns the same string in array form. This allows compa-
1408 * tibility with legacy functions that accept raw query strings instead of nice
1409 * arrays. Of course, keys and values are urldecode()d. Don't try passing in-
1410 * valid query strings, or it will explode.
1412 * @param $query String: query string
1413 * @return array Array version of input
1415 function wfCgiToArray( $query ) {
1416 if( isset( $query[0] ) && $query[0] == '?' ) {
1417 $query = substr( $query, 1 );
1419 $bits = explode( '&', $query );
1421 foreach( $bits as $bit ) {
1425 list( $key, $value ) = explode( '=', $bit );
1426 $key = urldecode( $key );
1427 $value = urldecode( $value );
1428 $ret[$key] = $value;
1434 * Append a query string to an existing URL, which may or may not already
1435 * have query string parameters already. If so, they will be combined.
1437 * @param $url String
1438 * @param $query Mixed: string or associative array
1441 function wfAppendQuery( $url, $query ) {
1442 if ( is_array( $query ) ) {
1443 $query = wfArrayToCGI( $query );
1445 if( $query != '' ) {
1446 if( false === strpos( $url, '?' ) ) {
1457 * Expand a potentially local URL to a fully-qualified URL. Assumes $wgServer
1458 * and $wgProto are correct.
1460 * @todo this won't work with current-path-relative URLs
1461 * like "subdir/foo.html", etc.
1463 * @param $url String: either fully-qualified or a local path + query
1464 * @return string Fully-qualified URL
1466 function wfExpandUrl( $url ) {
1467 if( substr( $url, 0, 2 ) == '//' ) {
1469 return $wgProto . ':' . $url;
1470 } elseif( substr( $url, 0, 1 ) == '/' ) {
1472 return $wgServer . $url;
1479 * Windows-compatible version of escapeshellarg()
1480 * Windows doesn't recognise single-quotes in the shell, but the escapeshellarg()
1481 * function puts single quotes in regardless of OS.
1483 * Also fixes the locale problems on Linux in PHP 5.2.6+ (bug backported to
1484 * earlier distro releases of PHP)
1486 function wfEscapeShellArg( ) {
1487 wfInitShellLocale();
1489 $args = func_get_args();
1492 foreach ( $args as $arg ) {
1499 if ( wfIsWindows() ) {
1500 // Escaping for an MSVC-style command line parser
1501 // Ref: http://mailman.lyra.org/pipermail/scite-interest/2002-March/000436.html
1502 // Double the backslashes before any double quotes. Escape the double quotes.
1503 $tokens = preg_split( '/(\\\\*")/', $arg, -1, PREG_SPLIT_DELIM_CAPTURE );
1506 foreach ( $tokens as $token ) {
1507 if ( $iteration % 2 == 1 ) {
1508 // Delimiter, a double quote preceded by zero or more slashes
1509 $arg .= str_replace( '\\', '\\\\', substr( $token, 0, -1 ) ) . '\\"';
1510 } elseif ( $iteration % 4 == 2 ) {
1511 // ^ in $token will be outside quotes, need to be escaped
1512 $arg .= str_replace( '^', '^^', $token );
1513 } else { // $iteration % 4 == 0
1514 // ^ in $token will appear inside double quotes, so leave as is
1519 // Double the backslashes before the end of the string, because
1520 // we will soon add a quote
1522 if ( preg_match( '/^(.*?)(\\\\+)$/', $arg, $m ) ) {
1523 $arg = $m[1] . str_replace( '\\', '\\\\', $m[2] );
1526 // Add surrounding quotes
1527 $retVal .= '"' . $arg . '"';
1529 $retVal .= escapeshellarg( $arg );
1536 * wfMerge attempts to merge differences between three texts.
1537 * Returns true for a clean merge and false for failure or a conflict.
1539 function wfMerge( $old, $mine, $yours, &$result ) {
1542 # This check may also protect against code injection in
1543 # case of broken installations.
1544 wfSuppressWarnings();
1545 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
1546 wfRestoreWarnings();
1549 wfDebug( "diff3 not found\n" );
1553 # Make temporary files
1555 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
1556 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
1557 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
1559 fwrite( $oldtextFile, $old );
1560 fclose( $oldtextFile );
1561 fwrite( $mytextFile, $mine );
1562 fclose( $mytextFile );
1563 fwrite( $yourtextFile, $yours );
1564 fclose( $yourtextFile );
1566 # Check for a conflict
1567 $cmd = $wgDiff3 . ' -a --overlap-only ' .
1568 wfEscapeShellArg( $mytextName ) . ' ' .
1569 wfEscapeShellArg( $oldtextName ) . ' ' .
1570 wfEscapeShellArg( $yourtextName );
1571 $handle = popen( $cmd, 'r' );
1573 if( fgets( $handle, 1024 ) ) {
1581 $cmd = $wgDiff3 . ' -a -e --merge ' .
1582 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
1583 $handle = popen( $cmd, 'r' );
1586 $data = fread( $handle, 8192 );
1587 if ( strlen( $data ) == 0 ) {
1593 unlink( $mytextName );
1594 unlink( $oldtextName );
1595 unlink( $yourtextName );
1597 if ( $result === '' && $old !== '' && !$conflict ) {
1598 wfDebug( "Unexpected null result from diff3. Command: $cmd\n" );
1605 * Returns unified plain-text diff of two texts.
1606 * Useful for machine processing of diffs.
1607 * @param $before String: the text before the changes.
1608 * @param $after String: the text after the changes.
1609 * @param $params String: command-line options for the diff command.
1610 * @return String: unified diff of $before and $after
1612 function wfDiff( $before, $after, $params = '-u' ) {
1613 if ( $before == $after ) {
1618 wfSuppressWarnings();
1619 $haveDiff = $wgDiff && file_exists( $wgDiff );
1620 wfRestoreWarnings();
1622 # This check may also protect against code injection in
1623 # case of broken installations.
1625 wfDebug( "diff executable not found\n" );
1626 $diffs = new Diff( explode( "\n", $before ), explode( "\n", $after ) );
1627 $format = new UnifiedDiffFormatter();
1628 return $format->format( $diffs );
1631 # Make temporary files
1633 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
1634 $newtextFile = fopen( $newtextName = tempnam( $td, 'merge-your-' ), 'w' );
1636 fwrite( $oldtextFile, $before );
1637 fclose( $oldtextFile );
1638 fwrite( $newtextFile, $after );
1639 fclose( $newtextFile );
1641 // Get the diff of the two files
1642 $cmd = "$wgDiff " . $params . ' ' . wfEscapeShellArg( $oldtextName, $newtextName );
1644 $h = popen( $cmd, 'r' );
1649 $data = fread( $h, 8192 );
1650 if ( strlen( $data ) == 0 ) {
1658 unlink( $oldtextName );
1659 unlink( $newtextName );
1661 // Kill the --- and +++ lines. They're not useful.
1662 $diff_lines = explode( "\n", $diff );
1663 if ( strpos( $diff_lines[0], '---' ) === 0 ) {
1664 unset( $diff_lines[0] );
1666 if ( strpos( $diff_lines[1], '+++' ) === 0 ) {
1667 unset( $diff_lines[1] );
1670 $diff = implode( "\n", $diff_lines );
1676 * A wrapper around the PHP function var_export().
1677 * Either print it or add it to the regular output ($wgOut).
1679 * @param $var A PHP variable to dump.
1681 function wfVarDump( $var ) {
1683 $s = str_replace( "\n", "<br />\n", var_export( $var, true ) . "\n" );
1684 if ( headers_sent() || !@is_object( $wgOut ) ) {
1687 $wgOut->addHTML( $s );
1692 * Provide a simple HTTP error.
1694 function wfHttpError( $code, $label, $desc ) {
1697 header( "HTTP/1.0 $code $label" );
1698 header( "Status: $code $label" );
1699 $wgOut->sendCacheControl();
1701 header( 'Content-type: text/html; charset=utf-8' );
1702 print "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">".
1703 '<html><head><title>' .
1704 htmlspecialchars( $label ) .
1705 '</title></head><body><h1>' .
1706 htmlspecialchars( $label ) .
1708 nl2br( htmlspecialchars( $desc ) ) .
1709 "</p></body></html>\n";
1713 * Clear away any user-level output buffers, discarding contents.
1715 * Suitable for 'starting afresh', for instance when streaming
1716 * relatively large amounts of data without buffering, or wanting to
1717 * output image files without ob_gzhandler's compression.
1719 * The optional $resetGzipEncoding parameter controls suppression of
1720 * the Content-Encoding header sent by ob_gzhandler; by default it
1721 * is left. See comments for wfClearOutputBuffers() for why it would
1724 * Note that some PHP configuration options may add output buffer
1725 * layers which cannot be removed; these are left in place.
1727 * @param $resetGzipEncoding Bool
1729 function wfResetOutputBuffers( $resetGzipEncoding = true ) {
1730 if( $resetGzipEncoding ) {
1731 // Suppress Content-Encoding and Content-Length
1732 // headers from 1.10+s wfOutputHandler
1733 global $wgDisableOutputCompression;
1734 $wgDisableOutputCompression = true;
1736 while( $status = ob_get_status() ) {
1737 if( $status['type'] == 0 /* PHP_OUTPUT_HANDLER_INTERNAL */ ) {
1738 // Probably from zlib.output_compression or other
1739 // PHP-internal setting which can't be removed.
1741 // Give up, and hope the result doesn't break
1745 if( !ob_end_clean() ) {
1746 // Could not remove output buffer handler; abort now
1747 // to avoid getting in some kind of infinite loop.
1750 if( $resetGzipEncoding ) {
1751 if( $status['name'] == 'ob_gzhandler' ) {
1752 // Reset the 'Content-Encoding' field set by this handler
1753 // so we can start fresh.
1754 if ( function_exists( 'header_remove' ) ) {
1755 // Available since PHP 5.3.0
1756 header_remove( 'Content-Encoding' );
1758 // We need to provide a valid content-coding. See bug 28069
1759 header( 'Content-Encoding: identity' );
1768 * More legible than passing a 'false' parameter to wfResetOutputBuffers():
1770 * Clear away output buffers, but keep the Content-Encoding header
1771 * produced by ob_gzhandler, if any.
1773 * This should be used for HTTP 304 responses, where you need to
1774 * preserve the Content-Encoding header of the real result, but
1775 * also need to suppress the output of ob_gzhandler to keep to spec
1776 * and avoid breaking Firefox in rare cases where the headers and
1777 * body are broken over two packets.
1779 function wfClearOutputBuffers() {
1780 wfResetOutputBuffers( false );
1784 * Converts an Accept-* header into an array mapping string values to quality
1787 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
1788 # No arg means accept anything (per HTTP spec)
1790 return array( $def => 1.0 );
1795 $parts = explode( ',', $accept );
1797 foreach( $parts as $part ) {
1798 # FIXME: doesn't deal with params like 'text/html; level=1'
1799 @list( $value, $qpart ) = explode( ';', trim( $part ) );
1801 if( !isset( $qpart ) ) {
1802 $prefs[$value] = 1.0;
1803 } elseif( preg_match( '/q\s*=\s*(\d*\.\d+)/', $qpart, $match ) ) {
1804 $prefs[$value] = floatval( $match[1] );
1812 * Checks if a given MIME type matches any of the keys in the given
1813 * array. Basic wildcards are accepted in the array keys.
1815 * Returns the matching MIME type (or wildcard) if a match, otherwise
1818 * @param $type String
1819 * @param $avail Array
1823 function mimeTypeMatch( $type, $avail ) {
1824 if( array_key_exists( $type, $avail ) ) {
1827 $parts = explode( '/', $type );
1828 if( array_key_exists( $parts[0] . '/*', $avail ) ) {
1829 return $parts[0] . '/*';
1830 } elseif( array_key_exists( '*/*', $avail ) ) {
1839 * Returns the 'best' match between a client's requested internet media types
1840 * and the server's list of available types. Each list should be an associative
1841 * array of type to preference (preference is a float between 0.0 and 1.0).
1842 * Wildcards in the types are acceptable.
1844 * @param $cprefs Array: client's acceptable type list
1845 * @param $sprefs Array: server's offered types
1848 * @todo FIXME: doesn't handle params like 'text/plain; charset=UTF-8'
1849 * XXX: generalize to negotiate other stuff
1851 function wfNegotiateType( $cprefs, $sprefs ) {
1854 foreach( array_keys($sprefs) as $type ) {
1855 $parts = explode( '/', $type );
1856 if( $parts[1] != '*' ) {
1857 $ckey = mimeTypeMatch( $type, $cprefs );
1859 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1864 foreach( array_keys( $cprefs ) as $type ) {
1865 $parts = explode( '/', $type );
1866 if( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
1867 $skey = mimeTypeMatch( $type, $sprefs );
1869 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1877 foreach( array_keys( $combine ) as $type ) {
1878 if( $combine[$type] > $bestq ) {
1880 $bestq = $combine[$type];
1889 * Returns an array where the values in the first array are replaced by the
1890 * values in the second array with the corresponding keys
1894 function wfArrayLookup( $a, $b ) {
1895 return array_flip( array_intersect( array_flip( $a ), array_keys( $b ) ) );
1899 * Convenience function; returns MediaWiki timestamp for the present time.
1902 function wfTimestampNow() {
1904 return wfTimestamp( TS_MW, time() );
1908 * Reference-counted warning suppression
1910 function wfSuppressWarnings( $end = false ) {
1911 static $suppressCount = 0;
1912 static $originalLevel = false;
1915 if ( $suppressCount ) {
1917 if ( !$suppressCount ) {
1918 error_reporting( $originalLevel );
1922 if ( !$suppressCount ) {
1923 $originalLevel = error_reporting( E_ALL & ~( E_WARNING | E_NOTICE | E_USER_WARNING | E_USER_NOTICE ) );
1930 * Restore error level to previous value
1932 function wfRestoreWarnings() {
1933 wfSuppressWarnings( true );
1936 # Autodetect, convert and provide timestamps of various types
1939 * Unix time - the number of seconds since 1970-01-01 00:00:00 UTC
1941 define( 'TS_UNIX', 0 );
1944 * MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
1946 define( 'TS_MW', 1 );
1949 * MySQL DATETIME (YYYY-MM-DD HH:MM:SS)
1951 define( 'TS_DB', 2 );
1954 * RFC 2822 format, for E-mail and HTTP headers
1956 define( 'TS_RFC2822', 3 );
1959 * ISO 8601 format with no timezone: 1986-02-09T20:00:00Z
1961 * This is used by Special:Export
1963 define( 'TS_ISO_8601', 4 );
1966 * An Exif timestamp (YYYY:MM:DD HH:MM:SS)
1968 * @see http://exif.org/Exif2-2.PDF The Exif 2.2 spec, see page 28 for the
1969 * DateTime tag and page 36 for the DateTimeOriginal and
1970 * DateTimeDigitized tags.
1972 define( 'TS_EXIF', 5 );
1975 * Oracle format time.
1977 define( 'TS_ORACLE', 6 );
1980 * Postgres format time.
1982 define( 'TS_POSTGRES', 7 );
1987 define( 'TS_DB2', 8 );
1990 * ISO 8601 basic format with no timezone: 19860209T200000Z
1992 * This is used by ResourceLoader
1994 define( 'TS_ISO_8601_BASIC', 9 );
1997 * @param $outputtype Mixed: A timestamp in one of the supported formats, the
1998 * function will autodetect which format is supplied and act
2000 * @param $ts Mixed: the timestamp to convert or 0 for the current timestamp
2001 * @return Mixed: String / false The same date in the format specified in $outputtype or false
2003 function wfTimestamp( $outputtype = TS_UNIX, $ts = 0 ) {
2008 if ( !$ts ) { // We want to catch 0, '', null... but not date strings starting with a letter.
2011 } elseif ( preg_match( '/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)$/D', $ts, $da ) ) {
2013 } elseif ( preg_match( '/^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/D', $ts, $da ) ) {
2015 } elseif ( preg_match( '/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/D', $ts, $da ) ) {
2017 } elseif ( preg_match( '/^-?\d{1,13}$/D', $ts ) ) {
2020 $strtime = "@$ts"; // Undocumented?
2021 } elseif ( preg_match( '/^\d{2}-\d{2}-\d{4} \d{2}:\d{2}:\d{2}.\d{6}$/', $ts ) ) {
2022 # TS_ORACLE // session altered to DD-MM-YYYY HH24:MI:SS.FF6
2023 $strtime = preg_replace( '/(\d\d)\.(\d\d)\.(\d\d)(\.(\d+))?/', "$1:$2:$3",
2024 str_replace( '+00:00', 'UTC', $ts ) );
2025 } elseif ( preg_match( '/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.*\d*)?Z$/', $ts, $da ) ) {
2027 } elseif ( preg_match( '/^(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})(?:\.*\d*)?Z$/', $ts, $da ) ) {
2029 } elseif ( preg_match( '/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.*\d*[\+\- ](\d\d)$/', $ts, $da ) ) {
2031 } elseif ( preg_match( '/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.*\d* GMT$/', $ts, $da ) ) {
2033 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.\d\d\d$/',$ts,$da)) {
2035 } elseif ( preg_match( '/^[ \t\r\n]*([A-Z][a-z]{2},[ \t\r\n]*)?' . # Day of week
2036 '\d\d?[ \t\r\n]*[A-Z][a-z]{2}[ \t\r\n]*\d{2}(?:\d{2})?' . # dd Mon yyyy
2037 '[ \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
2038 # TS_RFC2822, accepting a trailing comment. See http://www.squid-cache.org/mail-archive/squid-users/200307/0122.html / r77171
2039 # The regex is a superset of rfc2822 for readability
2040 $strtime = strtok( $ts, ';' );
2041 } 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 ) ) {
2044 } 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 ) ) {
2049 wfDebug("wfTimestamp() fed bogus time value: $outputtype; $ts\n");
2056 static $formats = array(
2059 TS_DB => 'Y-m-d H:i:s',
2060 TS_ISO_8601 => 'Y-m-d\TH:i:s\Z',
2061 TS_ISO_8601_BASIC => 'Ymd\THis\Z',
2062 TS_EXIF => 'Y:m:d H:i:s', // This shouldn't ever be used, but is included for completeness
2063 TS_RFC2822 => 'D, d M Y H:i:s',
2064 TS_ORACLE => 'd-m-Y H:i:s.000000', // Was 'd-M-y h.i.s A' . ' +00:00' before r51500
2065 TS_POSTGRES => 'Y-m-d H:i:s',
2066 TS_DB2 => 'Y-m-d H:i:s',
2069 if ( !isset( $formats[$outputtype] ) ) {
2070 throw new MWException( 'wfTimestamp() called with illegal output type.' );
2073 if ( function_exists( "date_create" ) ) {
2074 if ( count( $da ) ) {
2075 $ds = sprintf("%04d-%02d-%02dT%02d:%02d:%02d.00+00:00",
2076 (int)$da[1], (int)$da[2], (int)$da[3],
2077 (int)$da[4], (int)$da[5], (int)$da[6]);
2079 $d = date_create( $ds, new DateTimeZone( 'GMT' ) );
2080 } elseif ( $strtime ) {
2081 $d = date_create( $strtime, new DateTimeZone( 'GMT' ) );
2087 wfDebug("wfTimestamp() fed bogus time value: $outputtype; $ts\n");
2091 $output = $d->format( $formats[$outputtype] );
2093 if ( count( $da ) ) {
2094 // Warning! gmmktime() acts oddly if the month or day is set to 0
2095 // We may want to handle that explicitly at some point
2096 $uts = gmmktime( (int)$da[4], (int)$da[5], (int)$da[6],
2097 (int)$da[2], (int)$da[3], (int)$da[1] );
2098 } elseif ( $strtime ) {
2099 $uts = strtotime( $strtime );
2102 if ( $uts === false ) {
2103 wfDebug("wfTimestamp() can't parse the timestamp (non 32-bit time? Update php): $outputtype; $ts\n");
2107 if ( TS_UNIX == $outputtype ) {
2110 $output = gmdate( $formats[$outputtype], $uts );
2113 if ( ( $outputtype == TS_RFC2822 ) || ( $outputtype == TS_POSTGRES ) ) {
2121 * Return a formatted timestamp, or null if input is null.
2122 * For dealing with nullable timestamp columns in the database.
2123 * @param $outputtype Integer
2127 function wfTimestampOrNull( $outputtype = TS_UNIX, $ts = null ) {
2128 if( is_null( $ts ) ) {
2131 return wfTimestamp( $outputtype, $ts );
2136 * Check if the operating system is Windows
2138 * @return Bool: true if it's Windows, False otherwise.
2140 function wfIsWindows() {
2141 static $isWindows = null;
2142 if ( $isWindows === null ) {
2143 $isWindows = substr( php_uname(), 0, 7 ) == 'Windows';
2149 * Swap two variables
2151 function swap( &$x, &$y ) {
2157 function wfGetCachedNotice( $name ) {
2158 global $wgOut, $wgRenderHashAppend, $parserMemc;
2159 $fname = 'wfGetCachedNotice';
2160 wfProfileIn( $fname );
2164 if( $name === 'default' ) {
2166 global $wgSiteNotice;
2167 $notice = $wgSiteNotice;
2168 if( empty( $notice ) ) {
2169 wfProfileOut( $fname );
2173 $notice = wfMsgForContentNoTrans( $name );
2174 if( wfEmptyMsg( $name, $notice ) || $notice == '-' ) {
2175 wfProfileOut( $fname );
2180 // Use the extra hash appender to let eg SSL variants separately cache.
2181 $key = wfMemcKey( $name . $wgRenderHashAppend );
2182 $cachedNotice = $parserMemc->get( $key );
2183 if( is_array( $cachedNotice ) ) {
2184 if( md5( $notice ) == $cachedNotice['hash'] ) {
2185 $notice = $cachedNotice['html'];
2194 if( is_object( $wgOut ) ) {
2195 $parsed = $wgOut->parse( $notice );
2196 $parserMemc->set( $key, array( 'html' => $parsed, 'hash' => md5( $notice ) ), 600 );
2199 wfDebug( 'wfGetCachedNotice called for ' . $name . ' with no $wgOut available' . "\n" );
2203 $notice = '<div id="localNotice">' .$notice . '</div>';
2204 wfProfileOut( $fname );
2208 function wfGetNamespaceNotice() {
2212 if ( !isset( $wgTitle ) || !is_object( $wgTitle ) ) {
2216 $fname = 'wfGetNamespaceNotice';
2217 wfProfileIn( $fname );
2219 $key = 'namespacenotice-' . $wgTitle->getNsText();
2220 $namespaceNotice = wfGetCachedNotice( $key );
2221 if ( $namespaceNotice && substr( $namespaceNotice, 0, 7 ) != '<p><' ) {
2222 $namespaceNotice = '<div id="namespacebanner">' . $namespaceNotice . '</div>';
2224 $namespaceNotice = '';
2227 wfProfileOut( $fname );
2228 return $namespaceNotice;
2231 function wfGetSiteNotice() {
2233 $fname = 'wfGetSiteNotice';
2234 wfProfileIn( $fname );
2237 if( wfRunHooks( 'SiteNoticeBefore', array( &$siteNotice ) ) ) {
2238 if( is_object( $wgUser ) && $wgUser->isLoggedIn() ) {
2239 $siteNotice = wfGetCachedNotice( 'sitenotice' );
2241 $anonNotice = wfGetCachedNotice( 'anonnotice' );
2242 if( !$anonNotice ) {
2243 $siteNotice = wfGetCachedNotice( 'sitenotice' );
2245 $siteNotice = $anonNotice;
2248 if( !$siteNotice ) {
2249 $siteNotice = wfGetCachedNotice( 'default' );
2253 wfRunHooks( 'SiteNoticeAfter', array( &$siteNotice ) );
2254 wfProfileOut( $fname );
2259 * BC wrapper for MimeMagic::singleton()
2260 * @deprecated No longer needed as of 1.17 (r68836).
2262 function &wfGetMimeMagic() {
2263 wfDeprecated( __FUNCTION__ );
2264 return MimeMagic::singleton();
2268 * Tries to get the system directory for temporary files. The TMPDIR, TMP, and
2269 * TEMP environment variables are then checked in sequence, and if none are set
2270 * try sys_get_temp_dir() for PHP >= 5.2.1. All else fails, return /tmp for Unix
2271 * or C:\Windows\Temp for Windows and hope for the best.
2272 * It is common to call it with tempnam().
2274 * NOTE: When possible, use instead the tmpfile() function to create
2275 * temporary files to avoid race conditions on file creation, etc.
2279 function wfTempDir() {
2280 foreach( array( 'TMPDIR', 'TMP', 'TEMP' ) as $var ) {
2281 $tmp = getenv( $var );
2282 if( $tmp && file_exists( $tmp ) && is_dir( $tmp ) && is_writable( $tmp ) ) {
2286 if( function_exists( 'sys_get_temp_dir' ) ) {
2287 return sys_get_temp_dir();
2290 return wfIsWindows() ? 'C:\Windows\Temp' : '/tmp';
2294 * Make directory, and make all parent directories if they don't exist
2296 * @param $dir String: full path to directory to create
2297 * @param $mode Integer: chmod value to use, default is $wgDirectoryMode
2298 * @param $caller String: optional caller param for debugging.
2301 function wfMkdirParents( $dir, $mode = null, $caller = null ) {
2302 global $wgDirectoryMode;
2304 if ( !is_null( $caller ) ) {
2305 wfDebug( "$caller: called wfMkdirParents($dir)" );
2308 if( strval( $dir ) === '' || file_exists( $dir ) ) {
2312 $dir = str_replace( array( '\\', '/' ), DIRECTORY_SEPARATOR, $dir );
2314 if ( is_null( $mode ) ) {
2315 $mode = $wgDirectoryMode;
2318 // Turn off the normal warning, we're doing our own below
2319 wfSuppressWarnings();
2320 $ok = mkdir( $dir, $mode, true ); // PHP5 <3
2321 wfRestoreWarnings();
2324 // PHP doesn't report the path in its warning message, so add our own to aid in diagnosis.
2325 trigger_error( __FUNCTION__ . ": failed to mkdir \"$dir\" mode $mode", E_USER_WARNING );
2331 * Increment a statistics counter
2333 function wfIncrStats( $key ) {
2334 global $wgStatsMethod;
2336 if( $wgStatsMethod == 'udp' ) {
2337 global $wgUDPProfilerHost, $wgUDPProfilerPort, $wgDBname;
2340 $socket = socket_create( AF_INET, SOCK_DGRAM, SOL_UDP );
2341 $statline = "stats/{$wgDBname} - 1 1 1 1 1 -total\n";
2345 strlen( $statline ),
2351 $statline = "stats/{$wgDBname} - 1 1 1 1 1 {$key}\n";
2352 wfSuppressWarnings();
2356 strlen( $statline ),
2361 wfRestoreWarnings();
2362 } elseif( $wgStatsMethod == 'cache' ) {
2364 $key = wfMemcKey( 'stats', $key );
2365 if ( is_null( $wgMemc->incr( $key ) ) ) {
2366 $wgMemc->add( $key, 1 );
2374 * @param $nr Mixed: the number to format
2375 * @param $acc Integer: the number of digits after the decimal point, default 2
2376 * @param $round Boolean: whether or not to round the value, default true
2379 function wfPercent( $nr, $acc = 2, $round = true ) {
2380 $ret = sprintf( "%.${acc}f", $nr );
2381 return $round ? round( $ret, $acc ) . '%' : "$ret%";
2385 * Encrypt a username/password.
2387 * @param $userid Integer: ID of the user
2388 * @param $password String: password of the user
2389 * @return String: hashed password
2390 * @deprecated Use User::crypt() or User::oldCrypt() instead
2392 function wfEncryptPassword( $userid, $password ) {
2393 wfDeprecated(__FUNCTION__);
2394 # Just wrap around User::oldCrypt()
2395 return User::oldCrypt( $password, $userid );
2399 * Appends to second array if $value differs from that in $default
2401 function wfAppendToArrayIfNotDefault( $key, $value, $default, &$changed ) {
2402 if ( is_null( $changed ) ) {
2403 throw new MWException( 'GlobalFunctions::wfAppendToArrayIfNotDefault got null' );
2405 if ( $default[$key] !== $value ) {
2406 $changed[$key] = $value;
2411 * Since wfMsg() and co suck, they don't return false if the message key they
2412 * looked up didn't exist but a XHTML string, this function checks for the
2413 * nonexistance of messages by looking at wfMsg() output
2415 * @param $key String: the message key looked up
2416 * @return Boolean True if the message *doesn't* exist.
2418 function wfEmptyMsg( $key ) {
2419 global $wgMessageCache;
2420 return $wgMessageCache->get( $key, /*useDB*/true, /*content*/false ) === false;
2424 * Find out whether or not a mixed variable exists in a string
2426 * @param $needle String
2427 * @param $str String
2430 function in_string( $needle, $str ) {
2431 return strpos( $str, $needle ) !== false;
2434 function wfSpecialList( $page, $details ) {
2436 $details = $details ? ' ' . $wgContLang->getDirMark() . "($details)" : '';
2437 return $page . $details;
2441 * Returns a regular expression of url protocols
2445 function wfUrlProtocols() {
2446 global $wgUrlProtocols;
2448 static $retval = null;
2449 if ( !is_null( $retval ) ) {
2453 // Support old-style $wgUrlProtocols strings, for backwards compatibility
2454 // with LocalSettings files from 1.5
2455 if ( is_array( $wgUrlProtocols ) ) {
2456 $protocols = array();
2457 foreach ( $wgUrlProtocols as $protocol ) {
2458 $protocols[] = preg_quote( $protocol, '/' );
2461 $retval = implode( '|', $protocols );
2463 $retval = $wgUrlProtocols;
2469 * Safety wrapper around ini_get() for boolean settings.
2470 * The values returned from ini_get() are pre-normalized for settings
2471 * set via php.ini or php_flag/php_admin_flag... but *not*
2472 * for those set via php_value/php_admin_value.
2474 * It's fairly common for people to use php_value instead of php_flag,
2475 * which can leave you with an 'off' setting giving a false positive
2476 * for code that just takes the ini_get() return value as a boolean.
2478 * To make things extra interesting, setting via php_value accepts
2479 * "true" and "yes" as true, but php.ini and php_flag consider them false. :)
2480 * Unrecognized values go false... again opposite PHP's own coercion
2481 * from string to bool.
2483 * Luckily, 'properly' set settings will always come back as '0' or '1',
2484 * so we only have to worry about them and the 'improper' settings.
2486 * I frickin' hate PHP... :P
2488 * @param $setting String
2491 function wfIniGetBool( $setting ) {
2492 $val = ini_get( $setting );
2493 // 'on' and 'true' can't have whitespace around them, but '1' can.
2494 return strtolower( $val ) == 'on'
2495 || strtolower( $val ) == 'true'
2496 || strtolower( $val ) == 'yes'
2497 || preg_match( "/^\s*[+-]?0*[1-9]/", $val ); // approx C atoi() function
2501 * Wrapper function for PHP's dl(). This doesn't work in most situations from
2502 * PHP 5.3 onward, and is usually disabled in shared environments anyway.
2504 * @param $extension String A PHP extension. The file suffix (.so or .dll)
2506 * @return Bool - Whether or not the extension is loaded
2508 function wfDl( $extension ) {
2509 if( extension_loaded( $extension ) ) {
2513 $canDl = ( function_exists( 'dl' ) && is_callable( 'dl' )
2514 && wfIniGetBool( 'enable_dl' ) && !wfIniGetBool( 'safe_mode' ) );
2517 wfSuppressWarnings();
2518 dl( $extension . '.' . PHP_SHLIB_SUFFIX );
2519 wfRestoreWarnings();
2521 return extension_loaded( $extension );
2525 * Execute a shell command, with time and memory limits mirrored from the PHP
2526 * configuration if supported.
2527 * @param $cmd String Command line, properly escaped for shell.
2528 * @param &$retval optional, will receive the program's exit code.
2529 * (non-zero is usually failure)
2530 * @param $environ Array optional environment variables which should be
2531 * added to the executed command environment.
2532 * @return collected stdout as a string (trailing newlines stripped)
2534 function wfShellExec( $cmd, &$retval = null, $environ = array() ) {
2535 global $IP, $wgMaxShellMemory, $wgMaxShellFileSize, $wgMaxShellTime;
2538 if ( is_null( $disabled ) ) {
2540 if( wfIniGetBool( 'safe_mode' ) ) {
2541 wfDebug( "wfShellExec can't run in safe_mode, PHP's exec functions are too broken.\n" );
2542 $disabled = 'safemode';
2544 $functions = explode( ',', ini_get( 'disable_functions' ) );
2545 $functions = array_map( 'trim', $functions );
2546 $functions = array_map( 'strtolower', $functions );
2547 if ( in_array( 'passthru', $functions ) ) {
2548 wfDebug( "passthru is in disabled_functions\n" );
2549 $disabled = 'passthru';
2555 return $disabled == 'safemode' ?
2556 'Unable to run external programs in safe mode.' :
2557 'Unable to run external programs, passthru() is disabled.';
2560 wfInitShellLocale();
2563 foreach( $environ as $k => $v ) {
2564 if ( wfIsWindows() ) {
2565 /* Surrounding a set in quotes (method used by wfEscapeShellArg) makes the quotes themselves
2566 * appear in the environment variable, so we must use carat escaping as documented in
2567 * http://technet.microsoft.com/en-us/library/cc723564.aspx
2568 * Note however that the quote isn't listed there, but is needed, and the parentheses
2569 * are listed there but doesn't appear to need it.
2571 $envcmd .= "set $k=" . preg_replace( '/([&|()<>^"])/', '^\\1', $v ) . '&& ';
2573 /* Assume this is a POSIX shell, thus required to accept variable assignments before the command
2574 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_09_01
2576 $envcmd .= "$k=" . escapeshellarg( $v ) . ' ';
2579 $cmd = $envcmd . $cmd;
2581 if ( wfIsWindows() ) {
2582 if ( version_compare( PHP_VERSION, '5.3.0', '<' ) && /* Fixed in 5.3.0 :) */
2583 ( version_compare( PHP_VERSION, '5.2.1', '>=' ) || php_uname( 's' ) == 'Windows NT' ) )
2585 # Hack to work around PHP's flawed invocation of cmd.exe
2586 # http://news.php.net/php.internals/21796
2587 # Windows 9x doesn't accept any kind of quotes
2588 $cmd = '"' . $cmd . '"';
2590 } elseif ( php_uname( 's' ) == 'Linux' ) {
2591 $time = intval( $wgMaxShellTime );
2592 $mem = intval( $wgMaxShellMemory );
2593 $filesize = intval( $wgMaxShellFileSize );
2595 if ( $time > 0 && $mem > 0 ) {
2596 $script = "$IP/bin/ulimit4.sh";
2597 if ( is_executable( $script ) ) {
2598 $cmd = '/bin/bash ' . escapeshellarg( $script ) . " $time $mem $filesize " . escapeshellarg( $cmd );
2602 wfDebug( "wfShellExec: $cmd\n" );
2604 $retval = 1; // error by default?
2606 passthru( $cmd, $retval );
2607 $output = ob_get_contents();
2610 if ( $retval == 127 ) {
2611 wfDebugLog( 'exec', "Possibly missing executable file: $cmd\n" );
2617 * Workaround for http://bugs.php.net/bug.php?id=45132
2618 * escapeshellarg() destroys non-ASCII characters if LANG is not a UTF-8 locale
2620 function wfInitShellLocale() {
2621 static $done = false;
2626 global $wgShellLocale;
2627 if ( !wfIniGetBool( 'safe_mode' ) ) {
2628 putenv( "LC_CTYPE=$wgShellLocale" );
2629 setlocale( LC_CTYPE, $wgShellLocale );
2634 * This function works like "use VERSION" in Perl, the program will die with a
2635 * backtrace if the current version of PHP is less than the version provided
2637 * This is useful for extensions which due to their nature are not kept in sync
2638 * with releases, and might depend on other versions of PHP than the main code
2640 * Note: PHP might die due to parsing errors in some cases before it ever
2641 * manages to call this function, such is life
2643 * @see perldoc -f use
2645 * @param $req_ver Mixed: the version to check, can be a string, an integer, or
2648 function wfUsePHP( $req_ver ) {
2649 $php_ver = PHP_VERSION;
2651 if ( version_compare( $php_ver, (string)$req_ver, '<' ) ) {
2652 throw new MWException( "PHP $req_ver required--this is only $php_ver" );
2657 * This function works like "use VERSION" in Perl except it checks the version
2658 * of MediaWiki, the program will die with a backtrace if the current version
2659 * of MediaWiki is less than the version provided.
2661 * This is useful for extensions which due to their nature are not kept in sync
2664 * @see perldoc -f use
2666 * @param $req_ver Mixed: the version to check, can be a string, an integer, or
2669 function wfUseMW( $req_ver ) {
2672 if ( version_compare( $wgVersion, (string)$req_ver, '<' ) ) {
2673 throw new MWException( "MediaWiki $req_ver required--this is only $wgVersion" );
2678 * Return the final portion of a pathname.
2679 * Reimplemented because PHP5's basename() is buggy with multibyte text.
2680 * http://bugs.php.net/bug.php?id=33898
2682 * PHP's basename() only considers '\' a pathchar on Windows and Netware.
2683 * We'll consider it so always, as we don't want \s in our Unix paths either.
2685 * @param $path String
2686 * @param $suffix String: to remove if present
2689 function wfBaseName( $path, $suffix = '' ) {
2690 $encSuffix = ( $suffix == '' )
2692 : ( '(?:' . preg_quote( $suffix, '#' ) . ')?' );
2694 if( preg_match( "#([^/\\\\]*?){$encSuffix}[/\\\\]*$#", $path, $matches ) ) {
2702 * Generate a relative path name to the given file.
2703 * May explode on non-matching case-insensitive paths,
2704 * funky symlinks, etc.
2706 * @param $path String: absolute destination path including target filename
2707 * @param $from String: Absolute source path, directory only
2710 function wfRelativePath( $path, $from ) {
2711 // Normalize mixed input on Windows...
2712 $path = str_replace( '/', DIRECTORY_SEPARATOR, $path );
2713 $from = str_replace( '/', DIRECTORY_SEPARATOR, $from );
2715 // Trim trailing slashes -- fix for drive root
2716 $path = rtrim( $path, DIRECTORY_SEPARATOR );
2717 $from = rtrim( $from, DIRECTORY_SEPARATOR );
2719 $pieces = explode( DIRECTORY_SEPARATOR, dirname( $path ) );
2720 $against = explode( DIRECTORY_SEPARATOR, $from );
2722 if( $pieces[0] !== $against[0] ) {
2723 // Non-matching Windows drive letters?
2724 // Return a full path.
2728 // Trim off common prefix
2729 while( count( $pieces ) && count( $against )
2730 && $pieces[0] == $against[0] ) {
2731 array_shift( $pieces );
2732 array_shift( $against );
2735 // relative dots to bump us to the parent
2736 while( count( $against ) ) {
2737 array_unshift( $pieces, '..' );
2738 array_shift( $against );
2741 array_push( $pieces, wfBaseName( $path ) );
2743 return implode( DIRECTORY_SEPARATOR, $pieces );
2747 * Backwards array plus for people who haven't bothered to read the PHP manual
2748 * XXX: will not darn your socks for you.
2750 * @param $array1 Array
2751 * @param [$array2, [...]] Arrays
2754 function wfArrayMerge( $array1/* ... */ ) {
2755 $args = func_get_args();
2756 $args = array_reverse( $args, true );
2758 foreach ( $args as $arg ) {
2765 * Merge arrays in the style of getUserPermissionsErrors, with duplicate removal
2767 * wfMergeErrorArrays(
2768 * array( array( 'x' ) ),
2769 * array( array( 'x', '2' ) ),
2770 * array( array( 'x' ) ),
2771 * array( array( 'y') )
2775 * array( 'x', '2' ),
2780 function wfMergeErrorArrays( /*...*/ ) {
2781 $args = func_get_args();
2783 foreach ( $args as $errors ) {
2784 foreach ( $errors as $params ) {
2785 # FIXME: sometimes get nested arrays for $params,
2786 # which leads to E_NOTICEs
2787 $spec = implode( "\t", $params );
2788 $out[$spec] = $params;
2791 return array_values( $out );
2795 * parse_url() work-alike, but non-broken. Differences:
2797 * 1) Does not raise warnings on bad URLs (just returns false)
2798 * 2) Handles protocols that don't use :// (e.g., mailto: and news:) correctly
2799 * 3) Adds a "delimiter" element to the array, either '://' or ':' (see (2))
2801 * @param $url String: a URL to parse
2802 * @return Array: bits of the URL in an associative array, per PHP docs
2804 function wfParseUrl( $url ) {
2805 global $wgUrlProtocols; // Allow all protocols defined in DefaultSettings/LocalSettings.php
2806 wfSuppressWarnings();
2807 $bits = parse_url( $url );
2808 wfRestoreWarnings();
2813 // most of the protocols are followed by ://, but mailto: and sometimes news: not, check for it
2814 if ( in_array( $bits['scheme'] . '://', $wgUrlProtocols ) ) {
2815 $bits['delimiter'] = '://';
2816 } elseif ( in_array( $bits['scheme'] . ':', $wgUrlProtocols ) ) {
2817 $bits['delimiter'] = ':';
2818 // parse_url detects for news: and mailto: the host part of an url as path
2819 // We have to correct this wrong detection
2820 if ( isset( $bits['path'] ) ) {
2821 $bits['host'] = $bits['path'];
2832 * Make a URL index, appropriate for the el_index field of externallinks.
2834 function wfMakeUrlIndex( $url ) {
2835 $bits = wfParseUrl( $url );
2837 // Reverse the labels in the hostname, convert to lower case
2838 // For emails reverse domainpart only
2839 if ( $bits['scheme'] == 'mailto' ) {
2840 $mailparts = explode( '@', $bits['host'], 2 );
2841 if ( count( $mailparts ) === 2 ) {
2842 $domainpart = strtolower( implode( '.', array_reverse( explode( '.', $mailparts[1] ) ) ) );
2844 // No domain specified, don't mangle it
2847 $reversedHost = $domainpart . '@' . $mailparts[0];
2849 $reversedHost = strtolower( implode( '.', array_reverse( explode( '.', $bits['host'] ) ) ) );
2851 // Add an extra dot to the end
2852 // Why? Is it in wrong place in mailto links?
2853 if ( substr( $reversedHost, -1, 1 ) !== '.' ) {
2854 $reversedHost .= '.';
2856 // Reconstruct the pseudo-URL
2857 $prot = $bits['scheme'];
2858 $index = $prot . $bits['delimiter'] . $reversedHost;
2859 // Leave out user and password. Add the port, path, query and fragment
2860 if ( isset( $bits['port'] ) ) {
2861 $index .= ':' . $bits['port'];
2863 if ( isset( $bits['path'] ) ) {
2864 $index .= $bits['path'];
2868 if ( isset( $bits['query'] ) ) {
2869 $index .= '?' . $bits['query'];
2871 if ( isset( $bits['fragment'] ) ) {
2872 $index .= '#' . $bits['fragment'];
2878 * Do any deferred updates and clear the list
2880 * @param $commit Boolean: commit after every update to prevent lock contention
2882 function wfDoUpdates( $commit = false ) {
2883 global $wgDeferredUpdateList;
2885 wfProfileIn( __METHOD__ );
2887 // No need to get master connections in case of empty updates array
2888 if ( !count( $wgDeferredUpdateList ) ) {
2889 wfProfileOut( __METHOD__ );
2894 $dbw = wfGetDB( DB_MASTER );
2897 foreach ( $wgDeferredUpdateList as $update ) {
2898 $update->doUpdate();
2900 if ( $commit && $dbw->trxLevel() ) {
2905 $wgDeferredUpdateList = array();
2906 wfProfileOut( __METHOD__ );
2910 * Convert an arbitrarily-long digit string from one numeric base
2911 * to another, optionally zero-padding to a minimum column width.
2913 * Supports base 2 through 36; digit values 10-36 are represented
2914 * as lowercase letters a-z. Input is case-insensitive.
2916 * @param $input String: of digits
2917 * @param $sourceBase Integer: 2-36
2918 * @param $destBase Integer: 2-36
2919 * @param $pad Integer: 1 or greater
2920 * @param $lowercase Boolean
2921 * @return String or false on invalid input
2923 function wfBaseConvert( $input, $sourceBase, $destBase, $pad = 1, $lowercase = true ) {
2924 $input = strval( $input );
2925 if( $sourceBase < 2 ||
2930 $sourceBase != intval( $sourceBase ) ||
2931 $destBase != intval( $destBase ) ||
2932 $pad != intval( $pad ) ||
2933 !is_string( $input ) ||
2937 $digitChars = ( $lowercase ) ? '0123456789abcdefghijklmnopqrstuvwxyz' : '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
2938 $inDigits = array();
2941 // Decode and validate input string
2942 $input = strtolower( $input );
2943 for( $i = 0; $i < strlen( $input ); $i++ ) {
2944 $n = strpos( $digitChars, $input{$i} );
2945 if( $n === false || $n > $sourceBase ) {
2951 // Iterate over the input, modulo-ing out an output digit
2952 // at a time until input is gone.
2953 while( count( $inDigits ) ) {
2955 $workDigits = array();
2958 foreach( $inDigits as $digit ) {
2959 $work *= $sourceBase;
2962 if( $work < $destBase ) {
2963 // Gonna need to pull another digit.
2964 if( count( $workDigits ) ) {
2965 // Avoid zero-padding; this lets us find
2966 // the end of the input very easily when
2967 // length drops to zero.
2971 // Finally! Actual division!
2972 $workDigits[] = intval( $work / $destBase );
2974 // Isn't it annoying that most programming languages
2975 // don't have a single divide-and-remainder operator,
2976 // even though the CPU implements it that way?
2977 $work = $work % $destBase;
2981 // All that division leaves us with a remainder,
2982 // which is conveniently our next output digit.
2983 $outChars .= $digitChars[$work];
2986 $inDigits = $workDigits;
2989 while( strlen( $outChars ) < $pad ) {
2993 return strrev( $outChars );
2997 * Create an object with a given name and an array of construct parameters
2998 * @param $name String
2999 * @param $p Array: parameters
3001 function wfCreateObject( $name, $p ) {
3002 $p = array_values( $p );
3003 switch ( count( $p ) ) {
3007 return new $name( $p[0] );
3009 return new $name( $p[0], $p[1] );
3011 return new $name( $p[0], $p[1], $p[2] );
3013 return new $name( $p[0], $p[1], $p[2], $p[3] );
3015 return new $name( $p[0], $p[1], $p[2], $p[3], $p[4] );
3017 return new $name( $p[0], $p[1], $p[2], $p[3], $p[4], $p[5] );
3019 throw new MWException( 'Too many arguments to construtor in wfCreateObject' );
3023 function wfHttpOnlySafe() {
3024 global $wgHttpOnlyBlacklist;
3025 if( !version_compare( '5.2', PHP_VERSION, '<' ) ) {
3029 if( isset( $_SERVER['HTTP_USER_AGENT'] ) ) {
3030 foreach( $wgHttpOnlyBlacklist as $regex ) {
3031 if( preg_match( $regex, $_SERVER['HTTP_USER_AGENT'] ) ) {
3041 * Initialise php session
3043 function wfSetupSession( $sessionId = false ) {
3044 global $wgSessionsInMemcached, $wgCookiePath, $wgCookieDomain,
3045 $wgCookieSecure, $wgCookieHttpOnly, $wgSessionHandler;
3046 if( $wgSessionsInMemcached ) {
3047 require_once( 'MemcachedSessions.php' );
3048 } elseif( $wgSessionHandler && $wgSessionHandler != ini_get( 'session.save_handler' ) ) {
3049 # Only set this if $wgSessionHandler isn't null and session.save_handler
3050 # hasn't already been set to the desired value (that causes errors)
3051 ini_set( 'session.save_handler', $wgSessionHandler );
3053 $httpOnlySafe = wfHttpOnlySafe();
3054 wfDebugLog( 'cookie',
3055 'session_set_cookie_params: "' . implode( '", "',
3061 $httpOnlySafe && $wgCookieHttpOnly ) ) . '"' );
3062 if( $httpOnlySafe && $wgCookieHttpOnly ) {
3063 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookieHttpOnly );
3065 // PHP 5.1 throws warnings if you pass the HttpOnly parameter for 5.2.
3066 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
3068 session_cache_limiter( 'private, must-revalidate' );
3070 session_id( $sessionId );
3072 wfSuppressWarnings();
3074 wfRestoreWarnings();
3078 * Get an object from the precompiled serialized directory
3080 * @return Mixed: the variable on success, false on failure
3082 function wfGetPrecompiledData( $name ) {
3085 $file = "$IP/serialized/$name";
3086 if ( file_exists( $file ) ) {
3087 $blob = file_get_contents( $file );
3089 return unserialize( $blob );
3095 function wfGetCaller( $level = 2 ) {
3096 $backtrace = wfDebugBacktrace();
3097 if ( isset( $backtrace[$level] ) ) {
3098 return wfFormatStackFrame( $backtrace[$level] );
3100 $caller = 'unknown';
3106 * Return a string consisting of callers in the stack. Useful sometimes
3107 * for profiling specific points.
3109 * @param $limit The maximum depth of the stack frame to return, or false for
3112 function wfGetAllCallers( $limit = 3 ) {
3113 $trace = array_reverse( wfDebugBacktrace() );
3114 if ( !$limit || $limit > count( $trace ) - 1 ) {
3115 $limit = count( $trace ) - 1;
3117 $trace = array_slice( $trace, -$limit - 1, $limit );
3118 return implode( '/', array_map( 'wfFormatStackFrame', $trace ) );
3122 * Return a string representation of frame
3124 function wfFormatStackFrame( $frame ) {
3125 return isset( $frame['class'] ) ?
3126 $frame['class'] . '::' . $frame['function'] :
3133 function wfMemcKey( /*... */ ) {
3134 $args = func_get_args();
3135 $key = wfWikiID() . ':' . implode( ':', $args );
3136 $key = str_replace( ' ', '_', $key );
3141 * Get a cache key for a foreign DB
3143 function wfForeignMemcKey( $db, $prefix /*, ... */ ) {
3144 $args = array_slice( func_get_args(), 2 );
3146 $key = "$db-$prefix:" . implode( ':', $args );
3148 $key = $db . ':' . implode( ':', $args );
3154 * Get an ASCII string identifying this wiki
3155 * This is used as a prefix in memcached keys
3157 function wfWikiID() {
3158 global $wgDBprefix, $wgDBname;
3159 if ( $wgDBprefix ) {
3160 return "$wgDBname-$wgDBprefix";
3167 * Split a wiki ID into DB name and table prefix
3169 function wfSplitWikiID( $wiki ) {
3170 $bits = explode( '-', $wiki, 2 );
3171 if ( count( $bits ) < 2 ) {
3178 * Get a Database object.
3179 * @param $db Integer: index of the connection to get. May be DB_MASTER for the
3180 * master (for write queries), DB_SLAVE for potentially lagged read
3181 * queries, or an integer >= 0 for a particular server.
3183 * @param $groups Mixed: query groups. An array of group names that this query
3184 * belongs to. May contain a single string if the query is only
3187 * @param $wiki String: the wiki ID, or false for the current wiki
3189 * Note: multiple calls to wfGetDB(DB_SLAVE) during the course of one request
3190 * will always return the same object, unless the underlying connection or load
3191 * balancer is manually destroyed.
3193 * @return DatabaseBase
3195 function &wfGetDB( $db, $groups = array(), $wiki = false ) {
3196 return wfGetLB( $wiki )->getConnection( $db, $groups, $wiki );
3200 * Get a load balancer object.
3202 * @param $wiki String: wiki ID, or false for the current wiki
3203 * @return LoadBalancer
3205 function wfGetLB( $wiki = false ) {
3206 return wfGetLBFactory()->getMainLB( $wiki );
3210 * Get the load balancer factory object
3212 function &wfGetLBFactory() {
3213 return LBFactory::singleton();
3218 * Shortcut for RepoGroup::singleton()->findFile()
3219 * @param $title String or Title object
3220 * @param $options Associative array of options:
3221 * time: requested time for an archived image, or false for the
3222 * current version. An image object will be returned which was
3223 * created at the specified time.
3225 * ignoreRedirect: If true, do not follow file redirects
3227 * private: If true, return restricted (deleted) files if the current
3228 * user is allowed to view them. Otherwise, such files will not
3231 * bypassCache: If true, do not use the process-local cache of File objects
3233 * @return File, or false if the file does not exist
3235 function wfFindFile( $title, $options = array() ) {
3236 return RepoGroup::singleton()->findFile( $title, $options );
3240 * Get an object referring to a locally registered file.
3241 * Returns a valid placeholder object if the file does not exist.
3242 * @param $title Title or String
3243 * @return File, or null if passed an invalid Title
3245 function wfLocalFile( $title ) {
3246 return RepoGroup::singleton()->getLocalRepo()->newFile( $title );
3250 * Should low-performance queries be disabled?
3254 function wfQueriesMustScale() {
3255 global $wgMiserMode;
3257 || ( SiteStats::pages() > 100000
3258 && SiteStats::edits() > 1000000
3259 && SiteStats::users() > 10000 );
3263 * Get the path to a specified script file, respecting file
3264 * extensions; this is a wrapper around $wgScriptExtension etc.
3266 * @param $script String: script filename, sans extension
3269 function wfScript( $script = 'index' ) {
3270 global $wgScriptPath, $wgScriptExtension;
3271 return "{$wgScriptPath}/{$script}{$wgScriptExtension}";
3275 * Get the script URL.
3277 * @return script URL
3279 function wfGetScriptUrl() {
3280 if( isset( $_SERVER['SCRIPT_NAME'] ) ) {
3282 # as it was called, minus the query string.
3284 # Some sites use Apache rewrite rules to handle subdomains,
3285 # and have PHP set up in a weird way that causes PHP_SELF
3286 # to contain the rewritten URL instead of the one that the
3287 # outside world sees.
3289 # If in this mode, use SCRIPT_URL instead, which mod_rewrite
3290 # provides containing the "before" URL.
3291 return $_SERVER['SCRIPT_NAME'];
3293 return $_SERVER['URL'];
3298 * Convenience function converts boolean values into "true"
3299 * or "false" (string) values
3301 * @param $value Boolean
3304 function wfBoolToStr( $value ) {
3305 return $value ? 'true' : 'false';
3309 * Load an extension messages file
3310 * @deprecated in 1.16 (warnings in 1.18, removed in ?)
3312 function wfLoadExtensionMessages( $extensionName, $langcode = false ) {
3316 * Get a platform-independent path to the null file, e.g.
3321 function wfGetNull() {
3322 return wfIsWindows()
3328 * Displays a maxlag error
3330 * @param $host String: server that lags the most
3331 * @param $lag Integer: maxlag (actual)
3332 * @param $maxLag Integer: maxlag (requested)
3334 function wfMaxlagError( $host, $lag, $maxLag ) {
3335 global $wgShowHostnames;
3336 header( 'HTTP/1.1 503 Service Unavailable' );
3337 header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
3338 header( 'X-Database-Lag: ' . intval( $lag ) );
3339 header( 'Content-Type: text/plain' );
3340 if( $wgShowHostnames ) {
3341 echo "Waiting for $host: $lag seconds lagged\n";
3343 echo "Waiting for a database server: $lag seconds lagged\n";
3348 * Throws a warning that $function is deprecated
3349 * @param $function String
3352 function wfDeprecated( $function ) {
3353 static $functionsWarned = array();
3354 if ( !isset( $functionsWarned[$function] ) ) {
3355 $functionsWarned[$function] = true;
3356 wfWarn( "Use of $function is deprecated.", 2 );
3361 * Send a warning either to the debug log or in a PHP error depending on
3362 * $wgDevelopmentWarnings
3364 * @param $msg String: message to send
3365 * @param $callerOffset Integer: number of itmes to go back in the backtrace to
3366 * find the correct caller (1 = function calling wfWarn, ...)
3367 * @param $level Integer: PHP error level; only used when $wgDevelopmentWarnings
3370 function wfWarn( $msg, $callerOffset = 1, $level = E_USER_NOTICE ) {
3371 $callers = wfDebugBacktrace();
3372 if( isset( $callers[$callerOffset + 1] ) ){
3373 $callerfunc = $callers[$callerOffset + 1];
3374 $callerfile = $callers[$callerOffset];
3375 if( isset( $callerfile['file'] ) && isset( $callerfile['line'] ) ) {
3376 $file = $callerfile['file'] . ' at line ' . $callerfile['line'];
3378 $file = '(internal function)';
3381 if( isset( $callerfunc['class'] ) ) {
3382 $func .= $callerfunc['class'] . '::';
3384 if( isset( $callerfunc['function'] ) ) {
3385 $func .= $callerfunc['function'];
3387 $msg .= " [Called from $func in $file]";
3390 global $wgDevelopmentWarnings;
3391 if ( $wgDevelopmentWarnings ) {
3392 trigger_error( $msg, $level );
3394 wfDebug( "$msg\n" );
3399 * Sleep until the worst slave's replication lag is less than or equal to
3400 * $maxLag, in seconds. Use this when updating very large numbers of rows, as
3401 * in maintenance scripts, to avoid causing too much lag. Of course, this is
3402 * a no-op if there are no slaves.
3404 * Every time the function has to wait for a slave, it will print a message to
3405 * that effect (and then sleep for a little while), so it's probably not best
3406 * to use this outside maintenance scripts in its present form.
3408 * @param $maxLag Integer
3409 * @param $wiki mixed Wiki identifier accepted by wfGetLB
3412 function wfWaitForSlaves( $maxLag, $wiki = false ) {
3414 $lb = wfGetLB( $wiki );
3415 list( $host, $lag ) = $lb->getMaxLag( $wiki );
3416 while( $lag > $maxLag ) {
3417 wfSuppressWarnings();
3418 $name = gethostbyaddr( $host );
3419 wfRestoreWarnings();
3420 if( $name !== false ) {
3423 print "Waiting for $host (lagged $lag seconds)...\n";
3425 list( $host, $lag ) = $lb->getMaxLag();
3431 * Used to be used for outputting text in the installer/updater
3432 * @deprecated Warnings in 1.19, removal in 1.20
3434 function wfOut( $s ) {
3435 global $wgCommandLineMode;
3436 if ( $wgCommandLineMode && !defined( 'MEDIAWIKI_INSTALL' ) ) {
3439 echo htmlspecialchars( $s );
3445 * Count down from $n to zero on the terminal, with a one-second pause
3446 * between showing each number. For use in command-line scripts.
3448 function wfCountDown( $n ) {
3449 for ( $i = $n; $i >= 0; $i-- ) {
3451 echo str_repeat( "\x08", strlen( $i + 1 ) );
3463 * Generate a random 32-character hexadecimal token.
3464 * @param $salt Mixed: some sort of salt, if necessary, to add to random
3465 * characters before hashing.
3467 function wfGenerateToken( $salt = '' ) {
3468 $salt = serialize( $salt );
3469 return md5( mt_rand( 0, 0x7fffffff ) . $salt );
3473 * Replace all invalid characters with -
3474 * @param $name Mixed: filename to process
3476 function wfStripIllegalFilenameChars( $name ) {
3477 global $wgIllegalFileChars;
3478 $name = wfBaseName( $name );
3479 $name = preg_replace(
3480 "/[^" . Title::legalChars() . "]" .
3481 ( $wgIllegalFileChars ? "|[" . $wgIllegalFileChars . "]" : '' ) .
3490 * Insert array into another array after the specified *KEY*
3491 * @param $array Array: The array.
3492 * @param $insert Array: The array to insert.
3493 * @param $after Mixed: The key to insert after
3495 function wfArrayInsertAfter( $array, $insert, $after ) {
3496 // Find the offset of the element to insert after.
3497 $keys = array_keys( $array );
3498 $offsetByKey = array_flip( $keys );
3500 $offset = $offsetByKey[$after];
3502 // Insert at the specified offset
3503 $before = array_slice( $array, 0, $offset + 1, true );
3504 $after = array_slice( $array, $offset + 1, count( $array ) - $offset, true );
3506 $output = $before + $insert + $after;
3511 /* Recursively converts the parameter (an object) to an array with the same data */
3512 function wfObjectToArray( $objOrArray, $recursive = true ) {
3514 if( is_object( $objOrArray ) ) {
3515 $objOrArray = get_object_vars( $objOrArray );
3517 foreach ( $objOrArray as $key => $value ) {
3518 if ( $recursive && ( is_object( $value ) || is_array( $value ) ) ) {
3519 $value = wfObjectToArray( $value );
3522 $array[$key] = $value;
3529 * Set PHP's memory limit to the larger of php.ini or $wgMemoryLimit;
3530 * @return Integer value memory was set to.
3532 function wfMemoryLimit() {
3533 global $wgMemoryLimit;
3534 $memlimit = wfShorthandToInteger( ini_get( 'memory_limit' ) );
3535 if( $memlimit != -1 ) {
3536 $conflimit = wfShorthandToInteger( $wgMemoryLimit );
3537 if( $conflimit == -1 ) {
3538 wfDebug( "Removing PHP's memory limit\n" );
3539 wfSuppressWarnings();
3540 ini_set( 'memory_limit', $conflimit );
3541 wfRestoreWarnings();
3543 } elseif ( $conflimit > $memlimit ) {
3544 wfDebug( "Raising PHP's memory limit to $conflimit bytes\n" );
3545 wfSuppressWarnings();
3546 ini_set( 'memory_limit', $conflimit );
3547 wfRestoreWarnings();
3555 * Converts shorthand byte notation to integer form
3556 * @param $string String
3559 function wfShorthandToInteger( $string = '' ) {
3560 $string = trim( $string );
3561 if( $string === '' ) {
3564 $last = $string[strlen( $string ) - 1];
3565 $val = intval( $string );
3570 // break intentionally missing
3574 // break intentionally missing
3584 * Get the normalised IETF language tag
3585 * @param $code String: The language code.
3586 * @return $langCode String: The language code which complying with BCP 47 standards.
3588 function wfBCP47( $code ) {
3589 $codeSegment = explode( '-', $code );
3590 foreach ( $codeSegment as $segNo => $seg ) {
3591 if ( count( $codeSegment ) > 0 ) {
3592 // ISO 3166 country code
3593 if ( ( strlen( $seg ) == 2 ) && ( $segNo > 0 ) ) {
3594 $codeBCP[$segNo] = strtoupper( $seg );
3595 // ISO 15924 script code
3596 } elseif ( ( strlen( $seg ) == 4 ) && ( $segNo > 0 ) ) {
3597 $codeBCP[$segNo] = ucfirst( $seg );
3598 // Use lowercase for other cases
3600 $codeBCP[$segNo] = strtolower( $seg );
3603 // Use lowercase for single segment
3604 $codeBCP[$segNo] = strtolower( $seg );
3607 $langCode = implode( '-', $codeBCP );
3611 function wfArrayMap( $function, $input ) {
3612 $ret = array_map( $function, $input );
3613 foreach ( $ret as $key => $value ) {
3614 $taint = istainted( $input[$key] );
3616 taint( $ret[$key], $taint );