3 if ( !defined( 'MEDIAWIKI' ) ) {
4 die( "This file is part of MediaWiki, it is not a valid entry point" );
8 * Global functions used everywhere
11 require_once dirname(__FILE__
) . '/normal/UtfNormalUtil.php';
12 require_once dirname(__FILE__
) . '/XmlFunctions.php';
14 // Hide compatibility functions from Doxygen
18 * Compatibility functions
20 * We more or less support PHP 5.0.x and up.
21 * Re-implementations of newer functions or functions in non-standard
22 * PHP extensions may be included here.
24 if( !function_exists('iconv') ) {
25 # iconv support is not in the default configuration and so may not be present.
26 # Assume will only ever use utf-8 and iso-8859-1.
27 # This will *not* work in all circumstances.
28 function iconv( $from, $to, $string ) {
29 if(strcasecmp( $from, $to ) == 0) return $string;
30 if(strcasecmp( $from, 'utf-8' ) == 0) return utf8_decode( $string );
31 if(strcasecmp( $to, 'utf-8' ) == 0) return utf8_encode( $string );
36 if ( !function_exists( 'mb_substr' ) ) {
38 * Fallback implementation for mb_substr, hardcoded to UTF-8.
39 * Attempts to be at least _moderately_ efficient; best optimized
40 * for relatively small offset and count values -- about 5x slower
41 * than native mb_string in my testing.
43 * Larger offsets are still fairly efficient for Latin text, but
44 * can be up to 100x slower than native if the text is heavily
45 * multibyte and we have to slog through a few hundred kb.
47 function mb_substr( $str, $start, $count='end' ) {
49 $split = mb_substr_split_unicode( $str, intval( $start ) );
50 $str = substr( $str, $split );
53 if( $count !== 'end' ) {
54 $split = mb_substr_split_unicode( $str, intval( $count ) );
55 $str = substr( $str, 0, $split );
61 function mb_substr_split_unicode( $str, $splitPos ) {
62 if( $splitPos == 0 ) {
66 $byteLen = strlen( $str );
69 if( $splitPos > 256 ) {
70 // Optimize large string offsets by skipping ahead N bytes.
71 // This will cut out most of our slow time on Latin-based text,
72 // and 1/2 to 1/3 on East European and Asian scripts.
74 while ($bytePos < $byteLen && $str{$bytePos} >= "\x80" && $str{$bytePos} < "\xc0")
76 $charPos = mb_strlen( substr( $str, 0, $bytePos ) );
82 while( $charPos++
< $splitPos ) {
84 // Move past any tail bytes
85 while ($bytePos < $byteLen && $str{$bytePos} >= "\x80" && $str{$bytePos} < "\xc0")
89 $splitPosX = $splitPos +
1;
90 $charPos = 0; // relative to end of string; we don't care about the actual char position here
92 while( $bytePos > 0 && $charPos-- >= $splitPosX ) {
94 // Move past any tail bytes
95 while ($bytePos > 0 && $str{$bytePos} >= "\x80" && $str{$bytePos} < "\xc0")
104 if ( !function_exists( 'mb_strlen' ) ) {
106 * Fallback implementation of mb_strlen, hardcoded to UTF-8.
108 * @param string $enc optional encoding; ignored
111 function mb_strlen( $str, $enc="" ) {
112 $counts = count_chars( $str );
116 for( $i = 0; $i < 0x80; $i++
) {
117 $total +
= $counts[$i];
120 // Count multibyte sequence heads
121 for( $i = 0xc0; $i < 0xff; $i++
) {
122 $total +
= $counts[$i];
129 if( !function_exists( 'mb_strpos' ) ) {
131 * Fallback implementation of mb_strpos, hardcoded to UTF-8.
132 * @param $haystack String
133 * @param $needle String
134 * @param $offset String: optional start position
135 * @param $encoding String: optional encoding; ignored
138 function mb_strpos( $haystack, $needle, $offset = 0, $encoding="" ) {
139 $needle = preg_quote( $needle, '/' );
142 preg_match( '/'.$needle.'/u', $haystack, $ar, PREG_OFFSET_CAPTURE
, $offset );
144 if( isset( $ar[0][1] ) ) {
152 if( !function_exists( 'mb_strrpos' ) ) {
154 * Fallback implementation of mb_strrpos, hardcoded to UTF-8.
155 * @param $haystack String
156 * @param $needle String
157 * @param $offset String: optional start position
158 * @param $encoding String: optional encoding; ignored
161 function mb_strrpos( $haystack, $needle, $offset = 0, $encoding = "" ) {
162 $needle = preg_quote( $needle, '/' );
165 preg_match_all( '/'.$needle.'/u', $haystack, $ar, PREG_OFFSET_CAPTURE
, $offset );
167 if( isset( $ar[0] ) && count( $ar[0] ) > 0 &&
168 isset( $ar[0][count($ar[0])-1][1] ) ) {
169 return $ar[0][count($ar[0])-1][1];
176 if ( !function_exists( 'array_diff_key' ) ) {
178 * Exists in PHP 5.1.0+
179 * Not quite compatible, two-argument version only
180 * Null values will cause problems due to this use of isset()
182 function array_diff_key( $left, $right ) {
184 foreach ( $left as $key => $unused ) {
185 if ( isset( $right[$key] ) ) {
186 unset( $result[$key] );
193 // Support for Wietse Venema's taint feature
194 if ( !function_exists( 'istainted' ) ) {
195 function istainted( $var ) {
198 function taint( $var, $level = 0 ) {}
199 function untaint( $var, $level = 0 ) {}
200 define( 'TC_HTML', 1 );
201 define( 'TC_SHELL', 1 );
202 define( 'TC_MYSQL', 1 );
203 define( 'TC_PCRE', 1 );
204 define( 'TC_SELF', 1 );
210 * Like array_diff( $a, $b ) except that it works with two-dimensional arrays.
212 function wfArrayDiff2( $a, $b ) {
213 return array_udiff( $a, $b, 'wfArrayDiff2_cmp' );
215 function wfArrayDiff2_cmp( $a, $b ) {
216 if ( !is_array( $a ) ) {
217 return strcmp( $a, $b );
218 } elseif ( count( $a ) !== count( $b ) ) {
219 return count( $a ) < count( $b ) ?
-1 : 1;
223 while( ( list( $keyA, $valueA ) = each( $a ) ) && ( list( $keyB, $valueB ) = each( $b ) ) ) {
224 $cmp = strcmp( $valueA, $valueB );
234 * Wrapper for clone(), for compatibility with PHP4-friendly extensions.
235 * PHP 5 won't let you declare a 'clone' function, even conditionally,
236 * so it has to be a wrapper with a different name.
238 function wfClone( $object ) {
239 return clone( $object );
243 * Seed Mersenne Twister
244 * No-op for compatibility; only necessary in PHP < 4.2.0
246 function wfSeedRandom() {
251 * Get a random decimal value between 0 and 1, in a way
252 * not likely to give duplicate values for any realistic
253 * number of articles.
257 function wfRandom() {
258 # The maximum random value is "only" 2^31-1, so get two random
259 # values to reduce the chance of dupes
260 $max = mt_getrandmax() +
1;
261 $rand = number_format( (mt_rand() * $max +
mt_rand())
262 / $max / $max, 12, '.', '' );
267 * We want some things to be included as literal characters in our title URLs
268 * for prettiness, which urlencode encodes by default. According to RFC 1738,
269 * all of the following should be safe:
273 * But + is not safe because it's used to indicate a space; &= are only safe in
274 * paths and not in queries (and we don't distinguish here); ' seems kind of
275 * scary; and urlencode() doesn't touch -_. to begin with. Plus, although /
276 * is reserved, we don't care. So the list we unescape is:
280 * %2F in the page titles seems to fatally break for some reason.
285 function wfUrlencode( $s ) {
286 $s = urlencode( $s );
288 array( '%3B','%3A','%40','%24','%21','%2A','%28','%29','%2C','%2F' ),
289 array( ';', ':', '@', '$', '!', '*', '(', ')', ',', '/' ),
297 * Sends a line to the debug log if enabled or, optionally, to a comment in output.
298 * In normal operation this is a NOP.
300 * Controlling globals:
301 * $wgDebugLogFile - points to the log file
302 * $wgProfileOnly - if set, normal debug messages will not be recorded.
303 * $wgDebugRawPage - if false, 'action=raw' hits will not result in debug output.
304 * $wgDebugComments - if on, some debug items may appear in comments in the HTML output.
306 * @param $text String
307 * @param $logonly Bool: set true to avoid appearing in HTML when $wgDebugComments is set
309 function wfDebug( $text, $logonly = false ) {
310 global $wgOut, $wgDebugLogFile, $wgDebugComments, $wgProfileOnly, $wgDebugRawPage;
311 global $wgDebugLogPrefix, $wgShowDebug;
312 static $recursion = 0;
314 static $cache = array(); // Cache of unoutputted messages
316 # Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
317 if ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' && !$wgDebugRawPage ) {
321 if ( ( $wgDebugComments ||
$wgShowDebug ) && !$logonly ) {
324 if ( !isset( $wgOut ) ) {
327 if ( !StubObject
::isRealObject( $wgOut ) ) {
336 // add the message and possible cached ones to the output
337 array_map( array( $wgOut, 'debug' ), $cache );
340 if ( '' != $wgDebugLogFile && !$wgProfileOnly ) {
341 # Strip unprintables; they can switch terminal modes when binary data
342 # gets dumped, which is pretty annoying.
343 $text = preg_replace( '![\x00-\x08\x0b\x0c\x0e-\x1f]!', ' ', $text );
344 $text = $wgDebugLogPrefix . $text;
345 wfErrorLog( $text, $wgDebugLogFile );
350 * Send a line giving PHP memory usage.
351 * @param $exact Bool: print exact values instead of kilobytes (default: false)
353 function wfDebugMem( $exact = false ) {
354 $mem = memory_get_usage();
356 $mem = floor( $mem / 1024 ) . ' kilobytes';
360 wfDebug( "Memory usage: $mem\n" );
364 * Send a line to a supplementary debug log file, if configured, or main debug log if not.
365 * $wgDebugLogGroups[$logGroup] should be set to a filename to send to a separate log.
367 * @param $logGroup String
368 * @param $text String
369 * @param $public Bool: whether to log the event in the public log if no private
370 * log file is specified, (default true)
372 function wfDebugLog( $logGroup, $text, $public = true ) {
373 global $wgDebugLogGroups, $wgShowHostnames;
374 $text = trim($text)."\n";
375 if( isset( $wgDebugLogGroups[$logGroup] ) ) {
376 $time = wfTimestamp( TS_DB
);
378 if ( $wgShowHostnames ) {
379 $host = wfHostname();
383 wfErrorLog( "$time $host $wiki: $text", $wgDebugLogGroups[$logGroup] );
384 } else if ( $public === true ) {
385 wfDebug( $text, true );
390 * Log for database errors
391 * @param $text String: database error message.
393 function wfLogDBError( $text ) {
394 global $wgDBerrorLog, $wgDBname;
395 if ( $wgDBerrorLog ) {
396 $host = trim(`hostname`
);
397 $text = date('D M j G:i:s T Y') . "\t$host\t$wgDBname\t$text";
398 wfErrorLog( $text, $wgDBerrorLog );
403 * Log to a file without getting "file size exceeded" signals.
405 * Can also log to TCP or UDP with the syntax udp://host:port/prefix. This will
406 * send lines to the specified port, prefixed by the specified prefix and a space.
408 function wfErrorLog( $text, $file ) {
409 if ( substr( $file, 0, 4 ) == 'udp:' ) {
410 if ( preg_match( '!^(tcp|udp):(?://)?\[([0-9a-fA-F:]+)\]:(\d+)(?:/(.*))?$!', $file, $m ) ) {
411 // IPv6 bracketed host
415 $prefix = isset( $m[4] ) ?
$m[4] : false;
416 } elseif ( preg_match( '!^(tcp|udp):(?://)?([a-zA-Z0-9.-]+):(\d+)(?:/(.*))?$!', $file, $m ) ) {
420 $prefix = isset( $m[4] ) ?
$m[4] : false;
422 throw new MWException( __METHOD__
.": Invalid UDP specification" );
424 // Clean it up for the multiplexer
425 if ( strval( $prefix ) !== '' ) {
426 $text = preg_replace( '/^/m', $prefix . ' ', $text );
427 if ( substr( $text, -1 ) != "\n" ) {
432 $sock = fsockopen( "$protocol://$host", $port );
436 fwrite( $sock, $text );
439 wfSuppressWarnings();
440 $exists = file_exists( $file );
441 $size = $exists ?
filesize( $file ) : false;
442 if ( !$exists ||
( $size !== false && $size +
strlen( $text ) < 0x7fffffff ) ) {
443 error_log( $text, 3, $file );
452 function wfLogProfilingData() {
453 global $wgRequestTime, $wgDebugLogFile, $wgDebugRawPage, $wgRequest;
454 global $wgProfiler, $wgProfileLimit, $wgUser;
455 # Profiling must actually be enabled...
456 if( !isset( $wgProfiler ) ) return;
457 # Get total page request time
459 $elapsed = $now - $wgRequestTime;
460 # Only show pages that longer than $wgProfileLimit time (default is 0)
461 if( $elapsed <= $wgProfileLimit ) return;
462 $prof = wfGetProfilingOutput( $wgRequestTime, $elapsed );
464 if( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) )
465 $forward = ' forwarded for ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
466 if( !empty( $_SERVER['HTTP_CLIENT_IP'] ) )
467 $forward .= ' client IP ' . $_SERVER['HTTP_CLIENT_IP'];
468 if( !empty( $_SERVER['HTTP_FROM'] ) )
469 $forward .= ' from ' . $_SERVER['HTTP_FROM'];
471 $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
472 // Don't unstub $wgUser at this late stage just for statistics purposes
473 if( StubObject
::isRealObject($wgUser) && $wgUser->isAnon() )
475 $log = sprintf( "%s\t%04.3f\t%s\n",
476 gmdate( 'YmdHis' ), $elapsed,
477 urldecode( $wgRequest->getRequestURL() . $forward ) );
478 if ( '' != $wgDebugLogFile && ( $wgRequest->getVal('action') != 'raw' ||
$wgDebugRawPage ) ) {
479 wfErrorLog( $log . $prof, $wgDebugLogFile );
484 * Check if the wiki read-only lock file is present. This can be used to lock
485 * off editing functions, but doesn't guarantee that the database will not be
489 function wfReadOnly() {
490 global $wgReadOnlyFile, $wgReadOnly;
492 if ( !is_null( $wgReadOnly ) ) {
493 return (bool)$wgReadOnly;
495 if ( '' == $wgReadOnlyFile ) {
498 // Set $wgReadOnly for faster access next time
499 if ( is_file( $wgReadOnlyFile ) ) {
500 $wgReadOnly = file_get_contents( $wgReadOnlyFile );
504 return (bool)$wgReadOnly;
507 function wfReadOnlyReason() {
514 * Return a Language object from $langcode
515 * @param $langcode Mixed: either:
516 * - a Language object
517 * - code of the language to get the message for, if it is
518 * a valid code create a language for that language, if
519 * it is a string but not a valid code then make a basic
521 * - a boolean: if it's false then use the current users
522 * language (as a fallback for the old parameter
523 * functionality), or if it is true then use the wikis
524 * @return Language object
526 function wfGetLangObj( $langcode = false ){
527 # Identify which language to get or create a language object for.
528 if( $langcode instanceof Language
)
529 # Great, we already have the object!
533 if( $langcode === $wgContLang->getCode() ||
$langcode === true )
534 # $langcode is the language code of the wikis content language object.
535 # or it is a boolean and value is true
539 if( $langcode === $wgLang->getCode() ||
$langcode === false )
540 # $langcode is the language code of user language object.
541 # or it was a boolean and value is false
544 $validCodes = array_keys( Language
::getLanguageNames() );
545 if( in_array( $langcode, $validCodes ) )
546 # $langcode corresponds to a valid language.
547 return Language
::factory( $langcode );
549 # $langcode is a string, but not a valid language code; use content language.
550 wfDebug( "Invalid language code passed to wfGetLangObj, falling back to content language.\n" );
555 * Get a message from anywhere, for the current user language.
557 * Use wfMsgForContent() instead if the message should NOT
558 * change depending on the user preferences.
560 * @param $key String: lookup key for the message, usually
561 * defined in languages/Language.php
563 * This function also takes extra optional parameters (not
564 * shown in the function definition), which can by used to
565 * insert variable text into the predefined message.
567 function wfMsg( $key ) {
568 $args = func_get_args();
569 array_shift( $args );
570 return wfMsgReal( $key, $args, true );
574 * Same as above except doesn't transform the message
576 function wfMsgNoTrans( $key ) {
577 $args = func_get_args();
578 array_shift( $args );
579 return wfMsgReal( $key, $args, true, false, false );
583 * Get a message from anywhere, for the current global language
584 * set with $wgLanguageCode.
586 * Use this if the message should NOT change dependent on the
587 * language set in the user's preferences. This is the case for
588 * most text written into logs, as well as link targets (such as
589 * the name of the copyright policy page). Link titles, on the
590 * other hand, should be shown in the UI language.
592 * Note that MediaWiki allows users to change the user interface
593 * language in their preferences, but a single installation
594 * typically only contains content in one language.
596 * Be wary of this distinction: If you use wfMsg() where you should
597 * use wfMsgForContent(), a user of the software may have to
598 * customize over 70 messages in order to, e.g., fix a link in every
601 * @param $key String: lookup key for the message, usually
602 * defined in languages/Language.php
604 function wfMsgForContent( $key ) {
605 global $wgForceUIMsgAsContentMsg;
606 $args = func_get_args();
607 array_shift( $args );
609 if( is_array( $wgForceUIMsgAsContentMsg ) &&
610 in_array( $key, $wgForceUIMsgAsContentMsg ) )
612 return wfMsgReal( $key, $args, true, $forcontent );
616 * Same as above except doesn't transform the message
618 function wfMsgForContentNoTrans( $key ) {
619 global $wgForceUIMsgAsContentMsg;
620 $args = func_get_args();
621 array_shift( $args );
623 if( is_array( $wgForceUIMsgAsContentMsg ) &&
624 in_array( $key, $wgForceUIMsgAsContentMsg ) )
626 return wfMsgReal( $key, $args, true, $forcontent, false );
630 * Get a message from the language file, for the UI elements
632 function wfMsgNoDB( $key ) {
633 $args = func_get_args();
634 array_shift( $args );
635 return wfMsgReal( $key, $args, false );
639 * Get a message from the language file, for the content
641 function wfMsgNoDBForContent( $key ) {
642 global $wgForceUIMsgAsContentMsg;
643 $args = func_get_args();
644 array_shift( $args );
646 if( is_array( $wgForceUIMsgAsContentMsg ) &&
647 in_array( $key, $wgForceUIMsgAsContentMsg ) )
649 return wfMsgReal( $key, $args, false, $forcontent );
654 * Really get a message
655 * @param $key String: key to get.
657 * @param $useDB Boolean
658 * @param $transform Boolean: Whether or not to transform the message.
659 * @param $forContent Mixed: Language code, or false for user lang, true for content lang.
660 * @return String: the requested message.
662 function wfMsgReal( $key, $args, $useDB = true, $forContent = false, $transform = true ) {
663 wfProfileIn( __METHOD__
);
664 $message = wfMsgGetKey( $key, $useDB, $forContent, $transform );
665 $message = wfMsgReplaceArgs( $message, $args );
666 wfProfileOut( __METHOD__
);
671 * This function provides the message source for messages to be edited which are *not* stored in the database.
672 * @param $key String:
674 function wfMsgWeirdKey( $key ) {
675 $source = wfMsgGetKey( $key, false, true, false );
676 if ( wfEmptyMsg( $key, $source ) )
683 * Fetch a message string value, but don't replace any keys yet.
686 * @param $langCode String: Code of the language to get the message for, or
687 * behaves as a content language switch if it is a boolean.
688 * @param $transform Boolean: whether to parse magic words, etc.
692 function wfMsgGetKey( $key, $useDB, $langCode = false, $transform = true ) {
693 global $wgContLang, $wgMessageCache;
695 wfRunHooks('NormalizeMessageKey', array(&$key, &$useDB, &$langCode, &$transform));
697 # If $wgMessageCache isn't initialised yet, try to return something sensible.
698 if( is_object( $wgMessageCache ) ) {
699 $message = $wgMessageCache->get( $key, $useDB, $langCode );
701 $message = $wgMessageCache->transform( $message );
704 $lang = wfGetLangObj( $langCode );
706 # MessageCache::get() does this already, Language::getMessage() doesn't
707 # ISSUE: Should we try to handle "message/lang" here too?
708 $key = str_replace( ' ' , '_' , $wgContLang->lcfirst( $key ) );
710 if( is_object( $lang ) ) {
711 $message = $lang->getMessage( $key );
721 * Replace message parameter keys on the given formatted output.
723 * @param $message String
728 function wfMsgReplaceArgs( $message, $args ) {
729 # Fix windows line-endings
730 # Some messages are split with explode("\n", $msg)
731 $message = str_replace( "\r", '', $message );
734 if ( count( $args ) ) {
735 if ( is_array( $args[0] ) ) {
736 $args = array_values( $args[0] );
738 $replacementKeys = array();
739 foreach( $args as $n => $param ) {
740 $replacementKeys['$' . ($n +
1)] = $param;
742 $message = strtr( $message, $replacementKeys );
749 * Return an HTML-escaped version of a message.
750 * Parameter replacements, if any, are done *after* the HTML-escaping,
751 * so parameters may contain HTML (eg links or form controls). Be sure
752 * to pre-escape them if you really do want plaintext, or just wrap
753 * the whole thing in htmlspecialchars().
756 * @param string ... parameters
759 function wfMsgHtml( $key ) {
760 $args = func_get_args();
761 array_shift( $args );
762 return wfMsgReplaceArgs( htmlspecialchars( wfMsgGetKey( $key, true ) ), $args );
766 * Return an HTML version of message
767 * Parameter replacements, if any, are done *after* parsing the wiki-text message,
768 * so parameters may contain HTML (eg links or form controls). Be sure
769 * to pre-escape them if you really do want plaintext, or just wrap
770 * the whole thing in htmlspecialchars().
773 * @param string ... parameters
776 function wfMsgWikiHtml( $key ) {
778 $args = func_get_args();
779 array_shift( $args );
780 return wfMsgReplaceArgs( $wgOut->parse( wfMsgGetKey( $key, true ), /* can't be set to false */ true ), $args );
784 * Returns message in the requested format
785 * @param $key String: key of the message
786 * @param $options Array: processing rules. Can take the following options:
787 * <i>parse</i>: parses wikitext to html
788 * <i>parseinline</i>: parses wikitext to html and removes the surrounding
789 * p's added by parser or tidy
790 * <i>escape</i>: filters message through htmlspecialchars
791 * <i>escapenoentities</i>: same, but allows entity references like through
792 * <i>replaceafter</i>: parameters are substituted after parsing or escaping
793 * <i>parsemag</i>: transform the message using magic phrases
794 * <i>content</i>: fetch message for content language instead of interface
795 * Also can accept a single associative argument, of the form 'language' => 'xx':
796 * <i>language</i>: Language object or language code to fetch message for
797 * (overriden by <i>content</i>), its behaviour with parser, parseinline
798 * and parsemag is undefined.
799 * Behavior for conflicting options (e.g., parse+parseinline) is undefined.
801 function wfMsgExt( $key, $options ) {
804 $args = func_get_args();
805 array_shift( $args );
806 array_shift( $args );
807 $options = (array)$options;
809 foreach( $options as $arrayKey => $option ) {
810 if( !preg_match( '/^[0-9]+|language$/', $arrayKey ) ) {
811 # An unknown index, neither numeric nor "language"
812 wfWarn( "wfMsgExt called with incorrect parameter key $arrayKey", 1, E_USER_WARNING
);
813 } elseif( preg_match( '/^[0-9]+$/', $arrayKey ) && !in_array( $option,
814 array( 'parse', 'parseinline', 'escape', 'escapenoentities',
815 'replaceafter', 'parsemag', 'content' ) ) ) {
816 # A numeric index with unknown value
817 wfWarn( "wfMsgExt called with incorrect parameter $option", 1, E_USER_WARNING
);
821 if( in_array('content', $options, true ) ) {
824 } elseif( array_key_exists('language', $options) ) {
826 $langCode = wfGetLangObj( $options['language'] );
832 $string = wfMsgGetKey( $key, /*DB*/true, $langCode, /*Transform*/false );
834 if( !in_array('replaceafter', $options, true ) ) {
835 $string = wfMsgReplaceArgs( $string, $args );
838 if( in_array('parse', $options, true ) ) {
839 $string = $wgOut->parse( $string, true, !$forContent );
840 } elseif ( in_array('parseinline', $options, true ) ) {
841 $string = $wgOut->parse( $string, true, !$forContent );
843 if( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $string, $m ) ) {
846 } elseif ( in_array('parsemag', $options, true ) ) {
847 global $wgMessageCache;
848 if ( isset( $wgMessageCache ) ) {
849 $string = $wgMessageCache->transform( $string,
851 is_object( $langCode ) ?
$langCode : null );
855 if ( in_array('escape', $options, true ) ) {
856 $string = htmlspecialchars ( $string );
857 } elseif ( in_array( 'escapenoentities', $options, true ) ) {
858 $string = Sanitizer
::escapeHtmlAllowEntities( $string );
861 if( in_array('replaceafter', $options, true ) ) {
862 $string = wfMsgReplaceArgs( $string, $args );
870 * Just like exit() but makes a note of it.
871 * Commits open transactions except if the error parameter is set
873 * @deprecated Please return control to the caller or throw an exception
875 function wfAbruptExit( $error = false ){
876 static $called = false;
882 $bt = wfDebugBacktrace();
884 for($i = 0; $i < count($bt) ; $i++
){
885 $file = isset($bt[$i]['file']) ?
$bt[$i]['file'] : "unknown";
886 $line = isset($bt[$i]['line']) ?
$bt[$i]['line'] : "unknown";
887 wfDebug("WARNING: Abrupt exit in $file at line $line\n");
890 wfDebug("WARNING: Abrupt exit\n");
893 wfLogProfilingData();
896 wfGetLB()->closeAll();
902 * @deprecated Please return control the caller or throw an exception
904 function wfErrorExit() {
905 wfAbruptExit( true );
909 * Print a simple message and die, returning nonzero to the shell if any.
910 * Plain die() fails to return nonzero to the shell if you pass a string.
913 function wfDie( $msg='' ) {
919 * Throw a debugging exception. This function previously once exited the process,
920 * but now throws an exception instead, with similar results.
922 * @param $msg String: message shown when dieing.
924 function wfDebugDieBacktrace( $msg = '' ) {
925 throw new MWException( $msg );
929 * Fetch server name for use in error reporting etc.
930 * Use real server name if available, so we know which machine
931 * in a server farm generated the current page.
934 function wfHostname() {
936 if ( is_null( $host ) ) {
937 if ( function_exists( 'posix_uname' ) ) {
938 // This function not present on Windows
939 $uname = @posix_uname
();
943 if( is_array( $uname ) && isset( $uname['nodename'] ) ) {
944 $host = $uname['nodename'];
945 } elseif ( getenv( 'COMPUTERNAME' ) ) {
946 # Windows computer name
947 $host = getenv( 'COMPUTERNAME' );
949 # This may be a virtual server.
950 $host = $_SERVER['SERVER_NAME'];
957 * Returns a HTML comment with the elapsed time since request.
958 * This method has no side effects.
961 function wfReportTime() {
962 global $wgRequestTime, $wgShowHostnames;
965 $elapsed = $now - $wgRequestTime;
967 return $wgShowHostnames
968 ?
sprintf( "<!-- Served by %s in %01.3f secs. -->", wfHostname(), $elapsed )
969 : sprintf( "<!-- Served in %01.3f secs. -->", $elapsed );
973 * Safety wrapper for debug_backtrace().
975 * With Zend Optimizer 3.2.0 loaded, this causes segfaults under somewhat
976 * murky circumstances, which may be triggered in part by stub objects
977 * or other fancy talkin'.
979 * Will return an empty array if Zend Optimizer is detected or if
980 * debug_backtrace is disabled, otherwise the output from
981 * debug_backtrace() (trimmed).
983 * @return array of backtrace information
985 function wfDebugBacktrace() {
986 static $disabled = null;
988 if( extension_loaded( 'Zend Optimizer' ) ) {
989 wfDebug( "Zend Optimizer detected; skipping debug_backtrace for safety.\n" );
993 if ( is_null( $disabled ) ) {
995 $functions = explode( ',', ini_get( 'disable_functions' ) );
996 $functions = array_map( 'trim', $functions );
997 $functions = array_map( 'strtolower', $functions );
998 if ( in_array( 'debug_backtrace', $functions ) ) {
999 wfDebug( "debug_backtrace is in disabled_functions\n" );
1007 return array_slice( debug_backtrace(), 1 );
1010 function wfBacktrace() {
1011 global $wgCommandLineMode;
1013 if ( $wgCommandLineMode ) {
1018 $backtrace = wfDebugBacktrace();
1019 foreach( $backtrace as $call ) {
1020 if( isset( $call['file'] ) ) {
1021 $f = explode( DIRECTORY_SEPARATOR
, $call['file'] );
1022 $file = $f[count($f)-1];
1026 if( isset( $call['line'] ) ) {
1027 $line = $call['line'];
1031 if ( $wgCommandLineMode ) {
1032 $msg .= "$file line $line calls ";
1034 $msg .= '<li>' . $file . ' line ' . $line . ' calls ';
1036 if( !empty( $call['class'] ) ) $msg .= $call['class'] . '::';
1037 $msg .= $call['function'] . '()';
1039 if ( $wgCommandLineMode ) {
1045 if ( $wgCommandLineMode ) {
1055 /* Some generic result counters, pulled out of SearchEngine */
1061 function wfShowingResults( $offset, $limit ) {
1063 return wfMsgExt( 'showingresults', array( 'parseinline' ), $wgLang->formatNum( $limit ),
1064 $wgLang->formatNum( $offset+
1 ) );
1070 function wfShowingResultsNum( $offset, $limit, $num ) {
1072 return wfMsgExt( 'showingresultsnum', array( 'parseinline' ), $wgLang->formatNum( $limit ),
1073 $wgLang->formatNum( $offset+
1 ), $wgLang->formatNum( $num ) );
1077 * Generate (prev x| next x) (20|50|100...) type links for paging
1078 * @param $offset String
1079 * @param $limit Integer
1080 * @param $link String
1081 * @param $query String: optional URL query parameter string
1082 * @param $atend Bool: optional param for specified if this is the last page
1084 function wfViewPrevNext( $offset, $limit, $link, $query = '', $atend = false ) {
1086 $fmtLimit = $wgLang->formatNum( $limit );
1087 // FIXME: Why on earth this needs one message for the text and another one for tooltip??
1088 # Get prev/next link display text
1089 $prev = wfMsgExt( 'prevn', array('parsemag','escape'), $fmtLimit );
1090 $next = wfMsgExt( 'nextn', array('parsemag','escape'), $fmtLimit );
1091 # Get prev/next link title text
1092 $pTitle = wfMsgExt( 'prevn-title', array('parsemag','escape'), $fmtLimit );
1093 $nTitle = wfMsgExt( 'nextn-title', array('parsemag','escape'), $fmtLimit );
1094 # Fetch the title object
1095 if( is_object( $link ) ) {
1098 $title = Title
::newFromText( $link );
1099 if( is_null( $title ) ) {
1103 # Make 'previous' link
1104 if( 0 != $offset ) {
1105 $po = $offset - $limit;
1107 $q = "limit={$limit}&offset={$po}";
1108 if( $query != '' ) {
1111 $plink = '<a href="' . $title->escapeLocalUrl( $q ) . "\" title=\"{$pTitle}\" class=\"mw-prevlink\">{$prev}</a>";
1116 $no = $offset +
$limit;
1117 $q = "limit={$limit}&offset={$no}";
1118 if( $query != '' ) {
1124 $nlink = '<a href="' . $title->escapeLocalUrl( $q ) . "\" title=\"{$nTitle}\" class=\"mw-nextlink\">{$next}</a>";
1126 # Make links to set number of items per page
1127 $nums = $wgLang->pipeList( array(
1128 wfNumLink( $offset, 20, $title, $query ),
1129 wfNumLink( $offset, 50, $title, $query ),
1130 wfNumLink( $offset, 100, $title, $query ),
1131 wfNumLink( $offset, 250, $title, $query ),
1132 wfNumLink( $offset, 500, $title, $query )
1134 return wfMsgHtml( 'viewprevnext', $plink, $nlink, $nums );
1138 * Generate links for (20|50|100...) items-per-page links
1139 * @param $offset String
1140 * @param $limit Integer
1141 * @param $title Title
1142 * @param $query String: optional URL query parameter string
1144 function wfNumLink( $offset, $limit, $title, $query = '' ) {
1146 if( $query == '' ) {
1151 $q .= "limit={$limit}&offset={$offset}";
1152 $fmtLimit = $wgLang->formatNum( $limit );
1153 $lTitle = wfMsgExt('shown-title',array('parsemag','escape'),$limit);
1154 $s = '<a href="' . $title->escapeLocalUrl( $q ) . "\" title=\"{$lTitle}\" class=\"mw-numlink\">{$fmtLimit}</a>";
1160 * @todo FIXME: we may want to blacklist some broken browsers
1162 * @return bool Whereas client accept gzip compression
1164 function wfClientAcceptsGzip() {
1167 # FIXME: we may want to blacklist some broken browsers
1170 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
1171 $_SERVER['HTTP_ACCEPT_ENCODING'],
1173 if( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) return false;
1174 wfDebug( " accepts gzip\n" );
1182 * Obtain the offset and limit values from the request string;
1183 * used in special pages
1185 * @param $deflimit Default limit if none supplied
1186 * @param $optionname Name of a user preference to check against
1190 function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) {
1192 return $wgRequest->getLimitOffset( $deflimit, $optionname );
1196 * Escapes the given text so that it may be output using addWikiText()
1197 * without any linking, formatting, etc. making its way through. This
1198 * is achieved by substituting certain characters with HTML entities.
1199 * As required by the callers, <nowiki> is not used. It currently does
1200 * not filter out characters which have special meaning only at the
1201 * start of a line, such as "*".
1203 * @param $text String: text to be escaped
1205 function wfEscapeWikiText( $text ) {
1206 $text = str_replace(
1207 array( '[', '|', ']', '\'', 'ISBN ', 'RFC ', '://', "\n=", '{{' ), # }}
1208 array( '[', '|', ']', ''', 'ISBN ', 'RFC ', '://', "\n=", '{{' ),
1209 htmlspecialchars($text) );
1216 function wfQuotedPrintable( $string, $charset = '' ) {
1217 # Probably incomplete; see RFC 2045
1218 if( empty( $charset ) ) {
1219 global $wgInputEncoding;
1220 $charset = $wgInputEncoding;
1222 $charset = strtoupper( $charset );
1223 $charset = str_replace( 'ISO-8859', 'ISO8859', $charset ); // ?
1225 $illegal = '\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\xff=';
1226 $replace = $illegal . '\t ?_';
1227 if( !preg_match( "/[$illegal]/", $string ) ) return $string;
1228 $out = "=?$charset?Q?";
1229 $out .= preg_replace( "/([$replace])/e", 'sprintf("=%02X",ord("$1"))', $string );
1240 return microtime(true);
1244 * Sets dest to source and returns the original value of dest
1245 * If source is NULL, it just returns the value, it doesn't set the variable
1247 function wfSetVar( &$dest, $source ) {
1249 if ( !is_null( $source ) ) {
1256 * As for wfSetVar except setting a bit
1258 function wfSetBit( &$dest, $bit, $state = true ) {
1259 $temp = (bool)($dest & $bit );
1260 if ( !is_null( $state ) ) {
1271 * This function takes two arrays as input, and returns a CGI-style string, e.g.
1272 * "days=7&limit=100". Options in the first array override options in the second.
1273 * Options set to "" will not be output.
1275 function wfArrayToCGI( $array1, $array2 = NULL )
1277 if ( !is_null( $array2 ) ) {
1278 $array1 = $array1 +
$array2;
1282 foreach ( $array1 as $key => $value ) {
1283 if ( '' !== $value ) {
1287 if ( is_array( $value ) ) {
1289 foreach ( $value as $v ) {
1290 $cgi .= ( $firstTime ?
'' : '&') .
1291 urlencode( $key . '[]' ) . '=' .
1296 if ( is_object( $value ) ) {
1297 $value = $value->__toString();
1299 $cgi .= urlencode( $key ) . '=' .
1300 urlencode( $value );
1308 * This is the logical opposite of wfArrayToCGI(): it accepts a query string as
1309 * its argument and returns the same string in array form. This allows compa-
1310 * tibility with legacy functions that accept raw query strings instead of nice
1311 * arrays. Of course, keys and values are urldecode()d. Don't try passing in-
1312 * valid query strings, or it will explode.
1314 * @param $query String: query string
1315 * @return array Array version of input
1317 function wfCgiToArray( $query ) {
1318 if( isset( $query[0] ) and $query[0] == '?' ) {
1319 $query = substr( $query, 1 );
1321 $bits = explode( '&', $query );
1323 foreach( $bits as $bit ) {
1327 list( $key, $value ) = explode( '=', $bit );
1328 $key = urldecode( $key );
1329 $value = urldecode( $value );
1330 $ret[$key] = $value;
1336 * Append a query string to an existing URL, which may or may not already
1337 * have query string parameters already. If so, they will be combined.
1339 * @param $url String
1340 * @param $query Mixed: string or associative array
1343 function wfAppendQuery( $url, $query ) {
1344 if ( is_array( $query ) ) {
1345 $query = wfArrayToCGI( $query );
1347 if( $query != '' ) {
1348 if( false === strpos( $url, '?' ) ) {
1359 * Expand a potentially local URL to a fully-qualified URL. Assumes $wgServer
1360 * is correct. Also doesn't handle any type of relative URL except one
1361 * starting with a single "/": this won't work with current-path-relative URLs
1362 * like "subdir/foo.html", protocol-relative URLs like
1363 * "//en.wikipedia.org/wiki/", etc. TODO: improve this!
1365 * @param $url String: either fully-qualified or a local path + query
1366 * @return string Fully-qualified URL
1368 function wfExpandUrl( $url ) {
1369 if( substr( $url, 0, 1 ) == '/' ) {
1371 return $wgServer . $url;
1378 * This is obsolete, use SquidUpdate::purge()
1381 function wfPurgeSquidServers ($urlArr) {
1382 SquidUpdate
::purge( $urlArr );
1386 * Windows-compatible version of escapeshellarg()
1387 * Windows doesn't recognise single-quotes in the shell, but the escapeshellarg()
1388 * function puts single quotes in regardless of OS.
1390 * Also fixes the locale problems on Linux in PHP 5.2.6+ (bug backported to
1391 * earlier distro releases of PHP)
1393 function wfEscapeShellArg( ) {
1394 wfInitShellLocale();
1396 $args = func_get_args();
1399 foreach ( $args as $arg ) {
1406 if ( wfIsWindows() ) {
1407 // Escaping for an MSVC-style command line parser
1408 // Ref: http://mailman.lyra.org/pipermail/scite-interest/2002-March/000436.html
1409 // Double the backslashes before any double quotes. Escape the double quotes.
1410 $tokens = preg_split( '/(\\\\*")/', $arg, -1, PREG_SPLIT_DELIM_CAPTURE
);
1413 foreach ( $tokens as $token ) {
1415 $arg .= str_replace( '\\', '\\\\', substr( $token, 0, -1 ) ) . '\\"';
1421 // Double the backslashes before the end of the string, because
1422 // we will soon add a quote
1424 if ( preg_match( '/^(.*?)(\\\\+)$/', $arg, $m ) ) {
1425 $arg = $m[1] . str_replace( '\\', '\\\\', $m[2] );
1428 // Add surrounding quotes
1429 $retVal .= '"' . $arg . '"';
1431 $retVal .= escapeshellarg( $arg );
1438 * wfMerge attempts to merge differences between three texts.
1439 * Returns true for a clean merge and false for failure or a conflict.
1441 function wfMerge( $old, $mine, $yours, &$result ){
1444 # This check may also protect against code injection in
1445 # case of broken installations.
1446 if( !$wgDiff3 ||
!file_exists( $wgDiff3 ) ) {
1447 wfDebug( "diff3 not found\n" );
1451 # Make temporary files
1453 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
1454 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
1455 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
1457 fwrite( $oldtextFile, $old ); fclose( $oldtextFile );
1458 fwrite( $mytextFile, $mine ); fclose( $mytextFile );
1459 fwrite( $yourtextFile, $yours ); fclose( $yourtextFile );
1461 # Check for a conflict
1462 $cmd = $wgDiff3 . ' -a --overlap-only ' .
1463 wfEscapeShellArg( $mytextName ) . ' ' .
1464 wfEscapeShellArg( $oldtextName ) . ' ' .
1465 wfEscapeShellArg( $yourtextName );
1466 $handle = popen( $cmd, 'r' );
1468 if( fgets( $handle, 1024 ) ){
1476 $cmd = $wgDiff3 . ' -a -e --merge ' .
1477 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
1478 $handle = popen( $cmd, 'r' );
1481 $data = fread( $handle, 8192 );
1482 if ( strlen( $data ) == 0 ) {
1488 unlink( $mytextName ); unlink( $oldtextName ); unlink( $yourtextName );
1490 if ( $result === '' && $old !== '' && $conflict == false ) {
1491 wfDebug( "Unexpected null result from diff3. Command: $cmd\n" );
1498 * Returns unified plain-text diff of two texts.
1499 * Useful for machine processing of diffs.
1500 * @param $before String: the text before the changes.
1501 * @param $after String: the text after the changes.
1502 * @param $params String: command-line options for the diff command.
1503 * @return String: unified diff of $before and $after
1505 function wfDiff( $before, $after, $params = '-u' ) {
1506 if ($before == $after) {
1512 # This check may also protect against code injection in
1513 # case of broken installations.
1514 if( !file_exists( $wgDiff ) ){
1515 wfDebug( "diff executable not found\n" );
1516 $diffs = new Diff( explode( "\n", $before ), explode( "\n", $after ) );
1517 $format = new UnifiedDiffFormatter();
1518 return $format->format( $diffs );
1521 # Make temporary files
1523 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
1524 $newtextFile = fopen( $newtextName = tempnam( $td, 'merge-your-' ), 'w' );
1526 fwrite( $oldtextFile, $before ); fclose( $oldtextFile );
1527 fwrite( $newtextFile, $after ); fclose( $newtextFile );
1529 // Get the diff of the two files
1530 $cmd = "$wgDiff " . $params . ' ' .wfEscapeShellArg( $oldtextName, $newtextName );
1532 $h = popen( $cmd, 'r' );
1537 $data = fread( $h, 8192 );
1538 if ( strlen( $data ) == 0 ) {
1546 unlink( $oldtextName );
1547 unlink( $newtextName );
1549 // Kill the --- and +++ lines. They're not useful.
1550 $diff_lines = explode( "\n", $diff );
1551 if (strpos( $diff_lines[0], '---' ) === 0) {
1552 unset($diff_lines[0]);
1554 if (strpos( $diff_lines[1], '+++' ) === 0) {
1555 unset($diff_lines[1]);
1558 $diff = implode( "\n", $diff_lines );
1564 * A wrapper around the PHP function var_export().
1565 * Either print it or add it to the regular output ($wgOut).
1567 * @param $var A PHP variable to dump.
1569 function wfVarDump( $var ) {
1571 $s = str_replace("\n","<br />\n", var_export( $var, true ) . "\n");
1572 if ( headers_sent() ||
!@is_object
( $wgOut ) ) {
1575 $wgOut->addHTML( $s );
1580 * Provide a simple HTTP error.
1582 function wfHttpError( $code, $label, $desc ) {
1585 header( "HTTP/1.0 $code $label" );
1586 header( "Status: $code $label" );
1587 $wgOut->sendCacheControl();
1589 header( 'Content-type: text/html; charset=utf-8' );
1590 print "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">".
1591 "<html><head><title>" .
1592 htmlspecialchars( $label ) .
1593 "</title></head><body><h1>" .
1594 htmlspecialchars( $label ) .
1596 nl2br( htmlspecialchars( $desc ) ) .
1597 "</p></body></html>\n";
1601 * Clear away any user-level output buffers, discarding contents.
1603 * Suitable for 'starting afresh', for instance when streaming
1604 * relatively large amounts of data without buffering, or wanting to
1605 * output image files without ob_gzhandler's compression.
1607 * The optional $resetGzipEncoding parameter controls suppression of
1608 * the Content-Encoding header sent by ob_gzhandler; by default it
1609 * is left. See comments for wfClearOutputBuffers() for why it would
1612 * Note that some PHP configuration options may add output buffer
1613 * layers which cannot be removed; these are left in place.
1615 * @param $resetGzipEncoding Bool
1617 function wfResetOutputBuffers( $resetGzipEncoding=true ) {
1618 if( $resetGzipEncoding ) {
1619 // Suppress Content-Encoding and Content-Length
1620 // headers from 1.10+s wfOutputHandler
1621 global $wgDisableOutputCompression;
1622 $wgDisableOutputCompression = true;
1624 while( $status = ob_get_status() ) {
1625 if( $status['type'] == 0 /* PHP_OUTPUT_HANDLER_INTERNAL */ ) {
1626 // Probably from zlib.output_compression or other
1627 // PHP-internal setting which can't be removed.
1629 // Give up, and hope the result doesn't break
1633 if( !ob_end_clean() ) {
1634 // Could not remove output buffer handler; abort now
1635 // to avoid getting in some kind of infinite loop.
1638 if( $resetGzipEncoding ) {
1639 if( $status['name'] == 'ob_gzhandler' ) {
1640 // Reset the 'Content-Encoding' field set by this handler
1641 // so we can start fresh.
1642 header( 'Content-Encoding:' );
1650 * More legible than passing a 'false' parameter to wfResetOutputBuffers():
1652 * Clear away output buffers, but keep the Content-Encoding header
1653 * produced by ob_gzhandler, if any.
1655 * This should be used for HTTP 304 responses, where you need to
1656 * preserve the Content-Encoding header of the real result, but
1657 * also need to suppress the output of ob_gzhandler to keep to spec
1658 * and avoid breaking Firefox in rare cases where the headers and
1659 * body are broken over two packets.
1661 function wfClearOutputBuffers() {
1662 wfResetOutputBuffers( false );
1666 * Converts an Accept-* header into an array mapping string values to quality
1669 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
1670 # No arg means accept anything (per HTTP spec)
1672 return array( $def => 1.0 );
1677 $parts = explode( ',', $accept );
1679 foreach( $parts as $part ) {
1680 # FIXME: doesn't deal with params like 'text/html; level=1'
1681 @list
( $value, $qpart ) = explode( ';', trim( $part ) );
1683 if( !isset( $qpart ) ) {
1684 $prefs[$value] = 1.0;
1685 } elseif( preg_match( '/q\s*=\s*(\d*\.\d+)/', $qpart, $match ) ) {
1686 $prefs[$value] = floatval($match[1]);
1694 * Checks if a given MIME type matches any of the keys in the given
1695 * array. Basic wildcards are accepted in the array keys.
1697 * Returns the matching MIME type (or wildcard) if a match, otherwise
1700 * @param $type String
1701 * @param $avail Array
1705 function mimeTypeMatch( $type, $avail ) {
1706 if( array_key_exists($type, $avail) ) {
1709 $parts = explode( '/', $type );
1710 if( array_key_exists( $parts[0] . '/*', $avail ) ) {
1711 return $parts[0] . '/*';
1712 } elseif( array_key_exists( '*/*', $avail ) ) {
1721 * Returns the 'best' match between a client's requested internet media types
1722 * and the server's list of available types. Each list should be an associative
1723 * array of type to preference (preference is a float between 0.0 and 1.0).
1724 * Wildcards in the types are acceptable.
1726 * @param $cprefs Array: client's acceptable type list
1727 * @param $sprefs Array: server's offered types
1730 * @todo FIXME: doesn't handle params like 'text/plain; charset=UTF-8'
1731 * XXX: generalize to negotiate other stuff
1733 function wfNegotiateType( $cprefs, $sprefs ) {
1736 foreach( array_keys($sprefs) as $type ) {
1737 $parts = explode( '/', $type );
1738 if( $parts[1] != '*' ) {
1739 $ckey = mimeTypeMatch( $type, $cprefs );
1741 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1746 foreach( array_keys( $cprefs ) as $type ) {
1747 $parts = explode( '/', $type );
1748 if( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
1749 $skey = mimeTypeMatch( $type, $sprefs );
1751 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1759 foreach( array_keys( $combine ) as $type ) {
1760 if( $combine[$type] > $bestq ) {
1762 $bestq = $combine[$type];
1771 * Returns an array where the values in the first array are replaced by the
1772 * values in the second array with the corresponding keys
1776 function wfArrayLookup( $a, $b ) {
1777 return array_flip( array_intersect( array_flip( $a ), array_keys( $b ) ) );
1781 * Convenience function; returns MediaWiki timestamp for the present time.
1784 function wfTimestampNow() {
1786 return wfTimestamp( TS_MW
, time() );
1790 * Reference-counted warning suppression
1792 function wfSuppressWarnings( $end = false ) {
1793 static $suppressCount = 0;
1794 static $originalLevel = false;
1797 if ( $suppressCount ) {
1799 if ( !$suppressCount ) {
1800 error_reporting( $originalLevel );
1804 if ( !$suppressCount ) {
1805 $originalLevel = error_reporting( E_ALL
& ~
( E_WARNING | E_NOTICE
) );
1812 * Restore error level to previous value
1814 function wfRestoreWarnings() {
1815 wfSuppressWarnings( true );
1818 # Autodetect, convert and provide timestamps of various types
1821 * Unix time - the number of seconds since 1970-01-01 00:00:00 UTC
1823 define('TS_UNIX', 0);
1826 * MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
1831 * MySQL DATETIME (YYYY-MM-DD HH:MM:SS)
1836 * RFC 2822 format, for E-mail and HTTP headers
1838 define('TS_RFC2822', 3);
1841 * ISO 8601 format with no timezone: 1986-02-09T20:00:00Z
1843 * This is used by Special:Export
1845 define('TS_ISO_8601', 4);
1848 * An Exif timestamp (YYYY:MM:DD HH:MM:SS)
1850 * @see http://exif.org/Exif2-2.PDF The Exif 2.2 spec, see page 28 for the
1851 * DateTime tag and page 36 for the DateTimeOriginal and
1852 * DateTimeDigitized tags.
1854 define('TS_EXIF', 5);
1857 * Oracle format time.
1859 define('TS_ORACLE', 6);
1862 * Postgres format time.
1864 define('TS_POSTGRES', 7);
1869 define('TS_DB2', 8);
1872 * @param $outputtype Mixed: A timestamp in one of the supported formats, the
1873 * function will autodetect which format is supplied and act
1875 * @param $ts Mixed: the timestamp to convert or 0 for the current timestamp
1876 * @return String: in the format specified in $outputtype
1878 function wfTimestamp( $outputtype = TS_UNIX
, $ts = 0 ) {
1883 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)$/D',$ts,$da)) {
1885 } elseif (preg_match('/^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/D',$ts,$da)) {
1887 } elseif (preg_match('/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/D',$ts,$da)) {
1889 } elseif (preg_match('/^\d{1,13}$/D',$ts)) {
1892 } elseif (preg_match('/^\d{2}-\d{2}-\d{4} \d{2}:\d{2}:\d{2}.\d{6}$/', $ts)) {
1893 # TS_ORACLE // session altered to DD-MM-YYYY HH24:MI:SS.FF6
1894 $uts = strtotime(preg_replace('/(\d\d)\.(\d\d)\.(\d\d)(\.(\d+))?/', "$1:$2:$3",
1895 str_replace("+00:00", "UTC", $ts)));
1896 } elseif (preg_match('/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.*\d*)?Z$/', $ts, $da)) {
1898 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.*\d*[\+\- ](\d\d)$/',$ts,$da)) {
1900 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.*\d* GMT$/',$ts,$da)) {
1903 # Bogus value; fall back to the epoch...
1904 wfDebug("wfTimestamp() fed bogus time value: $outputtype; $ts\n");
1908 if (count( $da ) ) {
1909 // Warning! gmmktime() acts oddly if the month or day is set to 0
1910 // We may want to handle that explicitly at some point
1911 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1912 (int)$da[2],(int)$da[3],(int)$da[1]);
1915 switch($outputtype) {
1919 return gmdate( 'YmdHis', $uts );
1921 return gmdate( 'Y-m-d H:i:s', $uts );
1923 return gmdate( 'Y-m-d\TH:i:s\Z', $uts );
1924 // This shouldn't ever be used, but is included for completeness
1926 return gmdate( 'Y:m:d H:i:s', $uts );
1928 return gmdate( 'D, d M Y H:i:s', $uts ) . ' GMT';
1930 return gmdate( 'd-m-Y H:i:s.000000', $uts);
1931 //return gmdate( 'd-M-y h.i.s A', $uts) . ' +00:00';
1933 return gmdate( 'Y-m-d H:i:s', $uts) . ' GMT';
1935 return gmdate( 'Y-m-d H:i:s', $uts);
1937 throw new MWException( 'wfTimestamp() called with illegal output type.');
1942 * Return a formatted timestamp, or null if input is null.
1943 * For dealing with nullable timestamp columns in the database.
1944 * @param $outputtype Integer
1948 function wfTimestampOrNull( $outputtype = TS_UNIX
, $ts = null ) {
1949 if( is_null( $ts ) ) {
1952 return wfTimestamp( $outputtype, $ts );
1957 * Check if the operating system is Windows
1959 * @return Bool: true if it's Windows, False otherwise.
1961 function wfIsWindows() {
1962 if (substr(php_uname(), 0, 7) == 'Windows') {
1970 * Swap two variables
1972 function swap( &$x, &$y ) {
1978 function wfGetCachedNotice( $name ) {
1979 global $wgOut, $wgRenderHashAppend, $parserMemc;
1980 $fname = 'wfGetCachedNotice';
1981 wfProfileIn( $fname );
1985 if( $name === 'default' ) {
1987 global $wgSiteNotice;
1988 $notice = $wgSiteNotice;
1989 if( empty( $notice ) ) {
1990 wfProfileOut( $fname );
1994 $notice = wfMsgForContentNoTrans( $name );
1995 if( wfEmptyMsg( $name, $notice ) ||
$notice == '-' ) {
1996 wfProfileOut( $fname );
2001 // Use the extra hash appender to let eg SSL variants separately cache.
2002 $key = wfMemcKey( $name . $wgRenderHashAppend );
2003 $cachedNotice = $parserMemc->get( $key );
2004 if( is_array( $cachedNotice ) ) {
2005 if( md5( $notice ) == $cachedNotice['hash'] ) {
2006 $notice = $cachedNotice['html'];
2015 if( is_object( $wgOut ) ) {
2016 $parsed = $wgOut->parse( $notice );
2017 $parserMemc->set( $key, array( 'html' => $parsed, 'hash' => md5( $notice ) ), 600 );
2020 wfDebug( 'wfGetCachedNotice called for ' . $name . ' with no $wgOut available'."\n" );
2025 wfProfileOut( $fname );
2029 function wfGetNamespaceNotice() {
2033 if ( !isset( $wgTitle ) ||
!is_object( $wgTitle ) )
2036 $fname = 'wfGetNamespaceNotice';
2037 wfProfileIn( $fname );
2039 $key = "namespacenotice-" . $wgTitle->getNsText();
2040 $namespaceNotice = wfGetCachedNotice( $key );
2041 if ( $namespaceNotice && substr ( $namespaceNotice , 0 ,7 ) != "<p><" ) {
2042 $namespaceNotice = '<div id="namespacebanner">' . $namespaceNotice . "</div>";
2044 $namespaceNotice = "";
2047 wfProfileOut( $fname );
2048 return $namespaceNotice;
2051 function wfGetSiteNotice() {
2052 global $wgUser, $wgSiteNotice;
2053 $fname = 'wfGetSiteNotice';
2054 wfProfileIn( $fname );
2057 if( wfRunHooks( 'SiteNoticeBefore', array( &$siteNotice ) ) ) {
2058 if( is_object( $wgUser ) && $wgUser->isLoggedIn() ) {
2059 $siteNotice = wfGetCachedNotice( 'sitenotice' );
2061 $anonNotice = wfGetCachedNotice( 'anonnotice' );
2062 if( !$anonNotice ) {
2063 $siteNotice = wfGetCachedNotice( 'sitenotice' );
2065 $siteNotice = $anonNotice;
2068 if( !$siteNotice ) {
2069 $siteNotice = wfGetCachedNotice( 'default' );
2073 wfRunHooks( 'SiteNoticeAfter', array( &$siteNotice ) );
2074 wfProfileOut( $fname );
2079 * BC wrapper for MimeMagic::singleton()
2082 function &wfGetMimeMagic() {
2083 return MimeMagic
::singleton();
2087 * Tries to get the system directory for temporary files.
2088 * The TMPDIR, TMP, and TEMP environment variables are checked in sequence,
2089 * and if none are set /tmp is returned as the generic Unix default.
2091 * NOTE: When possible, use the tempfile() function to create temporary
2092 * files to avoid race conditions on file creation, etc.
2096 function wfTempDir() {
2097 foreach( array( 'TMPDIR', 'TMP', 'TEMP' ) as $var ) {
2098 $tmp = getenv( $var );
2099 if( $tmp && file_exists( $tmp ) && is_dir( $tmp ) && is_writable( $tmp ) ) {
2103 # Hope this is Unix of some kind!
2108 * Make directory, and make all parent directories if they don't exist
2110 * @param $dir String: full path to directory to create
2111 * @param $mode Integer: chmod value to use, default is $wgDirectoryMode
2112 * @param $caller String: optional caller param for debugging.
2115 function wfMkdirParents( $dir, $mode = null, $caller = null ) {
2116 global $wgDirectoryMode;
2118 if ( !is_null( $caller ) ) {
2119 wfDebug( "$caller: called wfMkdirParents($dir)" );
2122 if( strval( $dir ) === '' ||
file_exists( $dir ) )
2125 $dir = str_replace( array( '\\', '/' ), DIRECTORY_SEPARATOR
, $dir );
2127 if ( is_null( $mode ) )
2128 $mode = $wgDirectoryMode;
2130 $ok = mkdir( $dir, $mode, true ); // PHP5 <3
2132 // PHP doesn't report the path in its warning message, so add our own to aid in diagnosis.
2133 trigger_error( __FUNCTION__
. ": failed to mkdir \"$dir\" mode $mode", E_USER_WARNING
);
2139 * Increment a statistics counter
2141 function wfIncrStats( $key ) {
2142 global $wgStatsMethod;
2144 if( $wgStatsMethod == 'udp' ) {
2145 global $wgUDPProfilerHost, $wgUDPProfilerPort, $wgDBname;
2148 $socket=socket_create(AF_INET
, SOCK_DGRAM
, SOL_UDP
);
2149 $statline="stats/{$wgDBname} - 1 1 1 1 1 -total\n";
2150 socket_sendto($socket,$statline,strlen($statline),0,$wgUDPProfilerHost,$wgUDPProfilerPort);
2152 $statline="stats/{$wgDBname} - 1 1 1 1 1 {$key}\n";
2153 @socket_sendto
($socket,$statline,strlen($statline),0,$wgUDPProfilerHost,$wgUDPProfilerPort);
2154 } elseif( $wgStatsMethod == 'cache' ) {
2156 $key = wfMemcKey( 'stats', $key );
2157 if ( is_null( $wgMemc->incr( $key ) ) ) {
2158 $wgMemc->add( $key, 1 );
2166 * @param $nr Mixed: the number to format
2167 * @param $acc Integer: the number of digits after the decimal point, default 2
2168 * @param $round Boolean: whether or not to round the value, default true
2171 function wfPercent( $nr, $acc = 2, $round = true ) {
2172 $ret = sprintf( "%.${acc}f", $nr );
2173 return $round ?
round( $ret, $acc ) . '%' : "$ret%";
2177 * Encrypt a username/password.
2179 * @param $userid Integer: ID of the user
2180 * @param $password String: password of the user
2181 * @return String: hashed password
2182 * @deprecated Use User::crypt() or User::oldCrypt() instead
2184 function wfEncryptPassword( $userid, $password ) {
2185 wfDeprecated(__FUNCTION__
);
2186 # Just wrap around User::oldCrypt()
2187 return User
::oldCrypt($password, $userid);
2191 * Appends to second array if $value differs from that in $default
2193 function wfAppendToArrayIfNotDefault( $key, $value, $default, &$changed ) {
2194 if ( is_null( $changed ) ) {
2195 throw new MWException('GlobalFunctions::wfAppendToArrayIfNotDefault got null');
2197 if ( $default[$key] !== $value ) {
2198 $changed[$key] = $value;
2203 * Since wfMsg() and co suck, they don't return false if the message key they
2204 * looked up didn't exist but a XHTML string, this function checks for the
2205 * nonexistance of messages by looking at wfMsg() output
2207 * @param $msg String: the message key looked up
2208 * @param $wfMsgOut String: the output of wfMsg*()
2211 function wfEmptyMsg( $msg, $wfMsgOut ) {
2212 return $wfMsgOut === htmlspecialchars( "<$msg>" );
2216 * Find out whether or not a mixed variable exists in a string
2218 * @param $needle String
2219 * @param $str String
2222 function in_string( $needle, $str ) {
2223 return strpos( $str, $needle ) !== false;
2226 function wfSpecialList( $page, $details ) {
2228 $details = $details ?
' ' . $wgContLang->getDirMark() . "($details)" : "";
2229 return $page . $details;
2233 * Returns a regular expression of url protocols
2237 function wfUrlProtocols() {
2238 global $wgUrlProtocols;
2240 // Support old-style $wgUrlProtocols strings, for backwards compatibility
2241 // with LocalSettings files from 1.5
2242 if ( is_array( $wgUrlProtocols ) ) {
2243 $protocols = array();
2244 foreach ($wgUrlProtocols as $protocol)
2245 $protocols[] = preg_quote( $protocol, '/' );
2247 return implode( '|', $protocols );
2249 return $wgUrlProtocols;
2254 * Safety wrapper around ini_get() for boolean settings.
2255 * The values returned from ini_get() are pre-normalized for settings
2256 * set via php.ini or php_flag/php_admin_flag... but *not*
2257 * for those set via php_value/php_admin_value.
2259 * It's fairly common for people to use php_value instead of php_flag,
2260 * which can leave you with an 'off' setting giving a false positive
2261 * for code that just takes the ini_get() return value as a boolean.
2263 * To make things extra interesting, setting via php_value accepts
2264 * "true" and "yes" as true, but php.ini and php_flag consider them false. :)
2265 * Unrecognized values go false... again opposite PHP's own coercion
2266 * from string to bool.
2268 * Luckily, 'properly' set settings will always come back as '0' or '1',
2269 * so we only have to worry about them and the 'improper' settings.
2271 * I frickin' hate PHP... :P
2273 * @param $setting String
2276 function wfIniGetBool( $setting ) {
2277 $val = ini_get( $setting );
2278 // 'on' and 'true' can't have whitespace around them, but '1' can.
2279 return strtolower( $val ) == 'on'
2280 ||
strtolower( $val ) == 'true'
2281 ||
strtolower( $val ) == 'yes'
2282 ||
preg_match( "/^\s*[+-]?0*[1-9]/", $val ); // approx C atoi() function
2286 * Execute a shell command, with time and memory limits mirrored from the PHP
2287 * configuration if supported.
2288 * @param $cmd Command line, properly escaped for shell.
2289 * @param &$retval optional, will receive the program's exit code.
2290 * (non-zero is usually failure)
2291 * @return collected stdout as a string (trailing newlines stripped)
2293 function wfShellExec( $cmd, &$retval=null ) {
2294 global $IP, $wgMaxShellMemory, $wgMaxShellFileSize, $wgMaxShellTime;
2297 if ( is_null( $disabled ) ) {
2299 if( wfIniGetBool( 'safe_mode' ) ) {
2300 wfDebug( "wfShellExec can't run in safe_mode, PHP's exec functions are too broken.\n" );
2303 $functions = explode( ',', ini_get( 'disable_functions' ) );
2304 $functions = array_map( 'trim', $functions );
2305 $functions = array_map( 'strtolower', $functions );
2306 if ( in_array( 'passthru', $functions ) ) {
2307 wfDebug( "passthru is in disabled_functions\n" );
2313 return "Unable to run external programs in safe mode.";
2316 wfInitShellLocale();
2318 if ( php_uname( 's' ) == 'Linux' ) {
2319 $time = intval( $wgMaxShellTime );
2320 $mem = intval( $wgMaxShellMemory );
2321 $filesize = intval( $wgMaxShellFileSize );
2323 if ( $time > 0 && $mem > 0 ) {
2324 $script = "$IP/bin/ulimit4.sh";
2325 if ( is_executable( $script ) ) {
2326 $cmd = escapeshellarg( $script ) . " $time $mem $filesize " . escapeshellarg( $cmd );
2329 } elseif ( php_uname( 's' ) == 'Windows NT' && substr( php_uname( 'v' ), 6, 4 ) <= 6001 ) {
2330 # This is a hack to work around PHP's flawed invocation of cmd.exe
2331 # http://news.php.net/php.internals/21796
2332 $cmd = '"' . $cmd . '"';
2334 wfDebug( "wfShellExec: $cmd\n" );
2336 $retval = 1; // error by default?
2338 passthru( $cmd, $retval );
2339 $output = ob_get_contents();
2342 if ( $retval == 127 ) {
2343 wfDebugLog( 'exec', "Possibly missing executable file: $cmd\n" );
2349 * Executes a shell command in the background. Returns true if successful.
2351 * @param $cmd String
2353 function wfShellBackgroundExec( $cmd ) {
2354 wfDebug( "wfShellBackgroundExec: $cmd\n" );
2356 if ( !wfShellExecEnabled() ) {
2360 if ( wfIsWindows() ) {
2361 shell_exec( "start /b $cmd >nul" );
2364 $pid = shell_exec( "nohup $cmd > /dev/null & echo $!" );
2370 * Return true if we can execute a shell command (i.e. not safe mode, etc.)
2372 function wfShellExecEnabled() {
2373 if( wfIniGetBool( 'safe_mode' ) ) {
2374 wfDebug( "wfShellExec can't run in safe_mode, PHP's exec functions are too broken.\n" );
2377 $functions = explode( ',', ini_get( 'disable_functions' ) );
2378 $functions = array_map( 'trim', $functions );
2379 $functions = array_map( 'strtolower', $functions );
2380 if ( in_array( 'passthru', $functions ) ) {
2381 wfDebug( "passthru is in disabled_functions\n" );
2388 * Workaround for http://bugs.php.net/bug.php?id=45132
2389 * escapeshellarg() destroys non-ASCII characters if LANG is not a UTF-8 locale
2391 function wfInitShellLocale() {
2392 static $done = false;
2393 if ( $done ) return;
2395 global $wgShellLocale;
2396 if ( !wfIniGetBool( 'safe_mode' ) ) {
2397 putenv( "LC_CTYPE=$wgShellLocale" );
2398 setlocale( LC_CTYPE
, $wgShellLocale );
2403 * This function works like "use VERSION" in Perl, the program will die with a
2404 * backtrace if the current version of PHP is less than the version provided
2406 * This is useful for extensions which due to their nature are not kept in sync
2407 * with releases, and might depend on other versions of PHP than the main code
2409 * Note: PHP might die due to parsing errors in some cases before it ever
2410 * manages to call this function, such is life
2412 * @see perldoc -f use
2414 * @param $req_ver Mixed: the version to check, can be a string, an integer, or
2417 function wfUsePHP( $req_ver ) {
2418 $php_ver = PHP_VERSION
;
2420 if ( version_compare( $php_ver, (string)$req_ver, '<' ) )
2421 throw new MWException( "PHP $req_ver required--this is only $php_ver" );
2425 * This function works like "use VERSION" in Perl except it checks the version
2426 * of MediaWiki, the program will die with a backtrace if the current version
2427 * of MediaWiki is less than the version provided.
2429 * This is useful for extensions which due to their nature are not kept in sync
2432 * @see perldoc -f use
2434 * @param $req_ver Mixed: the version to check, can be a string, an integer, or
2437 function wfUseMW( $req_ver ) {
2440 if ( version_compare( $wgVersion, (string)$req_ver, '<' ) )
2441 throw new MWException( "MediaWiki $req_ver required--this is only $wgVersion" );
2445 * @deprecated use StringUtils::escapeRegexReplacement
2447 function wfRegexReplacement( $string ) {
2448 return StringUtils
::escapeRegexReplacement( $string );
2452 * Return the final portion of a pathname.
2453 * Reimplemented because PHP5's basename() is buggy with multibyte text.
2454 * http://bugs.php.net/bug.php?id=33898
2456 * PHP's basename() only considers '\' a pathchar on Windows and Netware.
2457 * We'll consider it so always, as we don't want \s in our Unix paths either.
2459 * @param $path String
2460 * @param $suffix String: to remove if present
2463 function wfBaseName( $path, $suffix='' ) {
2464 $encSuffix = ($suffix == '')
2466 : ( '(?:' . preg_quote( $suffix, '#' ) . ')?' );
2468 if( preg_match( "#([^/\\\\]*?){$encSuffix}[/\\\\]*$#", $path, $matches ) ) {
2476 * Generate a relative path name to the given file.
2477 * May explode on non-matching case-insensitive paths,
2478 * funky symlinks, etc.
2480 * @param $path String: absolute destination path including target filename
2481 * @param $from String: Absolute source path, directory only
2484 function wfRelativePath( $path, $from ) {
2485 // Normalize mixed input on Windows...
2486 $path = str_replace( '/', DIRECTORY_SEPARATOR
, $path );
2487 $from = str_replace( '/', DIRECTORY_SEPARATOR
, $from );
2489 // Trim trailing slashes -- fix for drive root
2490 $path = rtrim( $path, DIRECTORY_SEPARATOR
);
2491 $from = rtrim( $from, DIRECTORY_SEPARATOR
);
2493 $pieces = explode( DIRECTORY_SEPARATOR
, dirname( $path ) );
2494 $against = explode( DIRECTORY_SEPARATOR
, $from );
2496 if( $pieces[0] !== $against[0] ) {
2497 // Non-matching Windows drive letters?
2498 // Return a full path.
2502 // Trim off common prefix
2503 while( count( $pieces ) && count( $against )
2504 && $pieces[0] == $against[0] ) {
2505 array_shift( $pieces );
2506 array_shift( $against );
2509 // relative dots to bump us to the parent
2510 while( count( $against ) ) {
2511 array_unshift( $pieces, '..' );
2512 array_shift( $against );
2515 array_push( $pieces, wfBaseName( $path ) );
2517 return implode( DIRECTORY_SEPARATOR
, $pieces );
2521 * Backwards array plus for people who haven't bothered to read the PHP manual
2522 * XXX: will not darn your socks for you.
2524 * @param $array1 Array
2525 * @param [$array2, [...]] Arrays
2528 function wfArrayMerge( $array1/* ... */ ) {
2529 $args = func_get_args();
2530 $args = array_reverse( $args, true );
2532 foreach ( $args as $arg ) {
2539 * Merge arrays in the style of getUserPermissionsErrors, with duplicate removal
2541 * wfMergeErrorArrays(
2542 * array( array( 'x' ) ),
2543 * array( array( 'x', '2' ) ),
2544 * array( array( 'x' ) ),
2545 * array( array( 'y') )
2549 * array( 'x', '2' ),
2554 function wfMergeErrorArrays(/*...*/) {
2555 $args = func_get_args();
2557 foreach ( $args as $errors ) {
2558 foreach ( $errors as $params ) {
2559 $spec = implode( "\t", $params );
2560 $out[$spec] = $params;
2563 return array_values( $out );
2567 * parse_url() work-alike, but non-broken. Differences:
2569 * 1) Does not raise warnings on bad URLs (just returns false)
2570 * 2) Handles protocols that don't use :// (e.g., mailto: and news:) correctly
2571 * 3) Adds a "delimiter" element to the array, either '://' or ':' (see (2))
2573 * @param $url String: a URL to parse
2574 * @return Array: bits of the URL in an associative array, per PHP docs
2576 function wfParseUrl( $url ) {
2577 global $wgUrlProtocols; // Allow all protocols defined in DefaultSettings/LocalSettings.php
2578 wfSuppressWarnings();
2579 $bits = parse_url( $url );
2580 wfRestoreWarnings();
2585 // most of the protocols are followed by ://, but mailto: and sometimes news: not, check for it
2586 if ( in_array( $bits['scheme'] . '://', $wgUrlProtocols ) ) {
2587 $bits['delimiter'] = '://';
2588 } elseif ( in_array( $bits['scheme'] . ':', $wgUrlProtocols ) ) {
2589 $bits['delimiter'] = ':';
2590 // parse_url detects for news: and mailto: the host part of an url as path
2591 // We have to correct this wrong detection
2592 if ( isset ( $bits['path'] ) ) {
2593 $bits['host'] = $bits['path'];
2604 * Make a URL index, appropriate for the el_index field of externallinks.
2606 function wfMakeUrlIndex( $url ) {
2607 $bits = wfParseUrl( $url );
2609 // Reverse the labels in the hostname, convert to lower case
2610 // For emails reverse domainpart only
2611 if ( $bits['scheme'] == 'mailto' ) {
2612 $mailparts = explode( '@', $bits['host'], 2 );
2613 if ( count($mailparts) === 2 ) {
2614 $domainpart = strtolower( implode( '.', array_reverse( explode( '.', $mailparts[1] ) ) ) );
2616 // No domain specified, don't mangle it
2619 $reversedHost = $domainpart . '@' . $mailparts[0];
2621 $reversedHost = strtolower( implode( '.', array_reverse( explode( '.', $bits['host'] ) ) ) );
2623 // Add an extra dot to the end
2624 // Why? Is it in wrong place in mailto links?
2625 if ( substr( $reversedHost, -1, 1 ) !== '.' ) {
2626 $reversedHost .= '.';
2628 // Reconstruct the pseudo-URL
2629 $prot = $bits['scheme'];
2630 $index = $prot . $bits['delimiter'] . $reversedHost;
2631 // Leave out user and password. Add the port, path, query and fragment
2632 if ( isset( $bits['port'] ) ) $index .= ':' . $bits['port'];
2633 if ( isset( $bits['path'] ) ) {
2634 $index .= $bits['path'];
2638 if ( isset( $bits['query'] ) ) $index .= '?' . $bits['query'];
2639 if ( isset( $bits['fragment'] ) ) $index .= '#' . $bits['fragment'];
2644 * Do any deferred updates and clear the list
2645 * TODO: This could be in Wiki.php if that class made any sense at all
2647 function wfDoUpdates()
2649 global $wgPostCommitUpdateList, $wgDeferredUpdateList;
2650 foreach ( $wgDeferredUpdateList as $update ) {
2651 $update->doUpdate();
2653 foreach ( $wgPostCommitUpdateList as $update ) {
2654 $update->doUpdate();
2656 $wgDeferredUpdateList = array();
2657 $wgPostCommitUpdateList = array();
2661 * @deprecated use StringUtils::explodeMarkup
2663 function wfExplodeMarkup( $separator, $text ) {
2664 return StringUtils
::explodeMarkup( $separator, $text );
2668 * Convert an arbitrarily-long digit string from one numeric base
2669 * to another, optionally zero-padding to a minimum column width.
2671 * Supports base 2 through 36; digit values 10-36 are represented
2672 * as lowercase letters a-z. Input is case-insensitive.
2674 * @param $input String: of digits
2675 * @param $sourceBase Integer: 2-36
2676 * @param $destBase Integer: 2-36
2677 * @param $pad Integer: 1 or greater
2678 * @param $lowercase Boolean
2679 * @return String or false on invalid input
2681 function wfBaseConvert( $input, $sourceBase, $destBase, $pad=1, $lowercase=true ) {
2682 $input = strval( $input );
2683 if( $sourceBase < 2 ||
2688 $sourceBase != intval( $sourceBase ) ||
2689 $destBase != intval( $destBase ) ||
2690 $pad != intval( $pad ) ||
2691 !is_string( $input ) ||
2695 $digitChars = ( $lowercase ) ?
'0123456789abcdefghijklmnopqrstuvwxyz' : '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
2696 $inDigits = array();
2699 // Decode and validate input string
2700 $input = strtolower( $input );
2701 for( $i = 0; $i < strlen( $input ); $i++
) {
2702 $n = strpos( $digitChars, $input{$i} );
2703 if( $n === false ||
$n > $sourceBase ) {
2709 // Iterate over the input, modulo-ing out an output digit
2710 // at a time until input is gone.
2711 while( count( $inDigits ) ) {
2713 $workDigits = array();
2716 foreach( $inDigits as $digit ) {
2717 $work *= $sourceBase;
2720 if( $work < $destBase ) {
2721 // Gonna need to pull another digit.
2722 if( count( $workDigits ) ) {
2723 // Avoid zero-padding; this lets us find
2724 // the end of the input very easily when
2725 // length drops to zero.
2729 // Finally! Actual division!
2730 $workDigits[] = intval( $work / $destBase );
2732 // Isn't it annoying that most programming languages
2733 // don't have a single divide-and-remainder operator,
2734 // even though the CPU implements it that way?
2735 $work = $work %
$destBase;
2739 // All that division leaves us with a remainder,
2740 // which is conveniently our next output digit.
2741 $outChars .= $digitChars[$work];
2744 $inDigits = $workDigits;
2747 while( strlen( $outChars ) < $pad ) {
2751 return strrev( $outChars );
2755 * Create an object with a given name and an array of construct parameters
2756 * @param $name String
2757 * @param $p Array: parameters
2759 function wfCreateObject( $name, $p ){
2760 $p = array_values( $p );
2761 switch ( count( $p ) ) {
2765 return new $name( $p[0] );
2767 return new $name( $p[0], $p[1] );
2769 return new $name( $p[0], $p[1], $p[2] );
2771 return new $name( $p[0], $p[1], $p[2], $p[3] );
2773 return new $name( $p[0], $p[1], $p[2], $p[3], $p[4] );
2775 return new $name( $p[0], $p[1], $p[2], $p[3], $p[4], $p[5] );
2777 throw new MWException( "Too many arguments to construtor in wfCreateObject" );
2782 * Alias for modularized function
2783 * @deprecated Use Http::get() instead
2785 function wfGetHTTP( $url ) {
2786 wfDeprecated(__FUNCTION__
);
2787 return Http
::get( $url );
2791 * Alias for modularized function
2792 * @deprecated Use Http::isLocalURL() instead
2794 function wfIsLocalURL( $url ) {
2795 wfDeprecated(__FUNCTION__
);
2796 return Http
::isLocalURL( $url );
2799 function wfHttpOnlySafe() {
2800 global $wgHttpOnlyBlacklist;
2801 if( !version_compare("5.2", PHP_VERSION
, "<") )
2804 if( isset( $_SERVER['HTTP_USER_AGENT'] ) ) {
2805 foreach( $wgHttpOnlyBlacklist as $regex ) {
2806 if( preg_match( $regex, $_SERVER['HTTP_USER_AGENT'] ) ) {
2816 * Initialise php session
2818 function wfSetupSession() {
2819 global $wgSessionsInMemcached, $wgCookiePath, $wgCookieDomain,
2820 $wgCookieSecure, $wgCookieHttpOnly, $wgSessionHandler;
2821 if( $wgSessionsInMemcached ) {
2822 require_once( 'MemcachedSessions.php' );
2823 } elseif( $wgSessionHandler && $wgSessionHandler != ini_get( 'session.save_handler' ) ) {
2824 # Only set this if $wgSessionHandler isn't null and session.save_handler
2825 # hasn't already been set to the desired value (that causes errors)
2826 ini_set ( 'session.save_handler', $wgSessionHandler );
2828 $httpOnlySafe = wfHttpOnlySafe();
2829 wfDebugLog( 'cookie',
2830 'session_set_cookie_params: "' . implode( '", "',
2836 $httpOnlySafe && $wgCookieHttpOnly ) ) . '"' );
2837 if( $httpOnlySafe && $wgCookieHttpOnly ) {
2838 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookieHttpOnly );
2840 // PHP 5.1 throws warnings if you pass the HttpOnly parameter for 5.2.
2841 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
2843 session_cache_limiter( 'private, must-revalidate' );
2844 wfSuppressWarnings();
2846 wfRestoreWarnings();
2850 * Get an object from the precompiled serialized directory
2852 * @return Mixed: the variable on success, false on failure
2854 function wfGetPrecompiledData( $name ) {
2857 $file = "$IP/serialized/$name";
2858 if ( file_exists( $file ) ) {
2859 $blob = file_get_contents( $file );
2861 return unserialize( $blob );
2867 function wfGetCaller( $level = 2 ) {
2868 $backtrace = wfDebugBacktrace();
2869 if ( isset( $backtrace[$level] ) ) {
2870 return wfFormatStackFrame($backtrace[$level]);
2872 $caller = 'unknown';
2878 * Return a string consisting all callers in stack, somewhat useful sometimes
2879 * for profiling specific points
2881 function wfGetAllCallers() {
2882 return implode('/', array_map('wfFormatStackFrame',array_reverse(wfDebugBacktrace())));
2886 * Return a string representation of frame
2888 function wfFormatStackFrame($frame) {
2889 return isset( $frame["class"] )?
2890 $frame["class"]."::".$frame["function"]:
2897 function wfMemcKey( /*... */ ) {
2898 $args = func_get_args();
2899 $key = wfWikiID() . ':' . implode( ':', $args );
2900 $key = str_replace( ' ', '_', $key );
2905 * Get a cache key for a foreign DB
2907 function wfForeignMemcKey( $db, $prefix /*, ... */ ) {
2908 $args = array_slice( func_get_args(), 2 );
2910 $key = "$db-$prefix:" . implode( ':', $args );
2912 $key = $db . ':' . implode( ':', $args );
2918 * Get an ASCII string identifying this wiki
2919 * This is used as a prefix in memcached keys
2921 function wfWikiID() {
2922 global $wgDBprefix, $wgDBname;
2923 if ( $wgDBprefix ) {
2924 return "$wgDBname-$wgDBprefix";
2931 * Split a wiki ID into DB name and table prefix
2933 function wfSplitWikiID( $wiki ) {
2934 $bits = explode( '-', $wiki, 2 );
2935 if ( count( $bits ) < 2 ) {
2942 * Get a Database object.
2943 * @param $db Integer: index of the connection to get. May be DB_MASTER for the
2944 * master (for write queries), DB_SLAVE for potentially lagged read
2945 * queries, or an integer >= 0 for a particular server.
2947 * @param $groups Mixed: query groups. An array of group names that this query
2948 * belongs to. May contain a single string if the query is only
2951 * @param $wiki String: the wiki ID, or false for the current wiki
2953 * Note: multiple calls to wfGetDB(DB_SLAVE) during the course of one request
2954 * will always return the same object, unless the underlying connection or load
2955 * balancer is manually destroyed.
2957 function &wfGetDB( $db, $groups = array(), $wiki = false ) {
2958 return wfGetLB( $wiki )->getConnection( $db, $groups, $wiki );
2962 * Get a load balancer object.
2964 * @param $wiki String: wiki ID, or false for the current wiki
2965 * @return LoadBalancer
2967 function wfGetLB( $wiki = false ) {
2968 return wfGetLBFactory()->getMainLB( $wiki );
2972 * Get the load balancer factory object
2974 function &wfGetLBFactory() {
2975 return LBFactory
::singleton();
2980 * Shortcut for RepoGroup::singleton()->findFile()
2981 * @param $options Associative array of options:
2982 * time: requested time for an archived image, or false for the
2983 * current version. An image object will be returned which was
2984 * created at the specified time.
2986 * ignoreRedirect: If true, do not follow file redirects
2988 * private: If true, return restricted (deleted) files if the current
2989 * user is allowed to view them. Otherwise, such files will not
2992 * bypassCache: If true, do not use the process-local cache of File objects
2994 * @return File, or false if the file does not exist
2996 function wfFindFile( $title, $options = array() ) {
2997 return RepoGroup
::singleton()->findFile( $title, $options );
3001 * Get an object referring to a locally registered file.
3002 * Returns a valid placeholder object if the file does not exist.
3004 function wfLocalFile( $title ) {
3005 return RepoGroup
::singleton()->getLocalRepo()->newFile( $title );
3009 * Should low-performance queries be disabled?
3013 function wfQueriesMustScale() {
3014 global $wgMiserMode;
3016 ||
( SiteStats
::pages() > 100000
3017 && SiteStats
::edits() > 1000000
3018 && SiteStats
::users() > 10000 );
3022 * Get the path to a specified script file, respecting file
3023 * extensions; this is a wrapper around $wgScriptExtension etc.
3025 * @param $script String: script filename, sans extension
3028 function wfScript( $script = 'index' ) {
3029 global $wgScriptPath, $wgScriptExtension;
3030 return "{$wgScriptPath}/{$script}{$wgScriptExtension}";
3033 * Get the script url.
3035 * @return script url
3037 function wfGetScriptUrl(){
3038 if( isset( $_SERVER['SCRIPT_NAME'] ) ) {
3040 # as it was called, minus the query string.
3042 # Some sites use Apache rewrite rules to handle subdomains,
3043 # and have PHP set up in a weird way that causes PHP_SELF
3044 # to contain the rewritten URL instead of the one that the
3045 # outside world sees.
3047 # If in this mode, use SCRIPT_URL instead, which mod_rewrite
3048 # provides containing the "before" URL.
3049 return $_SERVER['SCRIPT_NAME'];
3051 return $_SERVER['URL'];
3056 * Convenience function converts boolean values into "true"
3057 * or "false" (string) values
3059 * @param $value Boolean
3062 function wfBoolToStr( $value ) {
3063 return $value ?
'true' : 'false';
3067 * Load an extension messages file
3070 function wfLoadExtensionMessages( $extensionName, $langcode = false ) {
3074 * Get a platform-independent path to the null file, e.g.
3079 function wfGetNull() {
3080 return wfIsWindows()
3086 * Displays a maxlag error
3088 * @param $host String: server that lags the most
3089 * @param $lag Integer: maxlag (actual)
3090 * @param $maxLag Integer: maxlag (requested)
3092 function wfMaxlagError( $host, $lag, $maxLag ) {
3093 global $wgShowHostnames;
3094 header( 'HTTP/1.1 503 Service Unavailable' );
3095 header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
3096 header( 'X-Database-Lag: ' . intval( $lag ) );
3097 header( 'Content-Type: text/plain' );
3098 if( $wgShowHostnames ) {
3099 echo "Waiting for $host: $lag seconds lagged\n";
3101 echo "Waiting for a database server: $lag seconds lagged\n";
3106 * Throws a warning that $function is deprecated
3107 * @param $function String
3110 function wfDeprecated( $function ) {
3111 static $functionsWarned = array();
3112 if ( !isset( $functionsWarned[$function] ) ) {
3113 $functionsWarned[$function] = true;
3114 wfWarn( "Use of $function is deprecated.", 2 );
3119 * Send a warning either to the debug log or in a PHP error depending on
3120 * $wgDevelopmentWarnings
3122 * @param $msg String: message to send
3123 * @param $callerOffset Integer: number of itmes to go back in the backtrace to
3124 * find the correct caller (1 = function calling wfWarn, ...)
3125 * @param $level Integer: PHP error level; only used when $wgDevelopmentWarnings
3128 function wfWarn( $msg, $callerOffset = 1, $level = E_USER_NOTICE
) {
3129 $callers = wfDebugBacktrace();
3130 if( isset( $callers[$callerOffset+
1] ) ){
3131 $callerfunc = $callers[$callerOffset+
1];
3132 $callerfile = $callers[$callerOffset];
3133 if( isset( $callerfile['file'] ) && isset( $callerfile['line'] ) ){
3134 $file = $callerfile['file'] . ' at line ' . $callerfile['line'];
3136 $file = '(internal function)';
3139 if( isset( $callerfunc['class'] ) )
3140 $func .= $callerfunc['class'] . '::';
3141 $func .= @$callerfunc['function'];
3142 $msg .= " [Called from $func in $file]";
3145 global $wgDevelopmentWarnings;
3146 if ( $wgDevelopmentWarnings ) {
3147 trigger_error( $msg, $level );
3149 wfDebug( "$msg\n" );
3154 * Sleep until the worst slave's replication lag is less than or equal to
3155 * $maxLag, in seconds. Use this when updating very large numbers of rows, as
3156 * in maintenance scripts, to avoid causing too much lag. Of course, this is
3157 * a no-op if there are no slaves.
3159 * Every time the function has to wait for a slave, it will print a message to
3160 * that effect (and then sleep for a little while), so it's probably not best
3161 * to use this outside maintenance scripts in its present form.
3163 * @param $maxLag Integer
3166 function wfWaitForSlaves( $maxLag ) {
3169 list( $host, $lag ) = $lb->getMaxLag();
3170 while( $lag > $maxLag ) {
3171 $name = @gethostbyaddr
( $host );
3172 if( $name !== false ) {
3175 print "Waiting for $host (lagged $lag seconds)...\n";
3177 list( $host, $lag ) = $lb->getMaxLag();
3183 * Output some plain text in command-line mode or in the installer (updaters.inc).
3184 * Do not use it in any other context, its behaviour is subject to change.
3186 function wfOut( $s ) {
3187 static $lineStarted = false;
3188 global $wgCommandLineMode;
3189 if ( $wgCommandLineMode && !defined( 'MEDIAWIKI_INSTALL' ) ) {
3192 echo htmlspecialchars( $s );
3198 * Count down from $n to zero on the terminal, with a one-second pause
3199 * between showing each number. For use in command-line scripts.
3201 function wfCountDown( $n ) {
3202 for ( $i = $n; $i >= 0; $i-- ) {
3204 echo str_repeat( "\x08", strlen( $i +
1 ) );
3215 /** Generate a random 32-character hexadecimal token.
3216 * @param $salt Mixed: some sort of salt, if necessary, to add to random
3217 * characters before hashing.
3219 function wfGenerateToken( $salt = '' ) {
3220 $salt = serialize($salt);
3222 return md5( mt_rand( 0, 0x7fffffff ) . $salt );
3226 * Replace all invalid characters with -
3227 * @param $name Mixed: filename to process
3229 function wfStripIllegalFilenameChars( $name ) {
3230 global $wgIllegalFileChars;
3231 $name = wfBaseName( $name );
3232 $name = preg_replace("/[^".Title
::legalChars()."]".($wgIllegalFileChars ?
"|[".$wgIllegalFileChars."]":"")."/",'-',$name);
3237 * Insert array into another array after the specified *KEY*
3238 * @param $array Array: The array.
3239 * @param $insert Array: The array to insert.
3240 * @param $after Mixed: The key to insert after
3242 function wfArrayInsertAfter( $array, $insert, $after ) {
3243 // Find the offset of the element to insert after.
3244 $keys = array_keys($array);
3245 $offsetByKey = array_flip( $keys );
3247 $offset = $offsetByKey[$after];
3249 // Insert at the specified offset
3250 $before = array_slice( $array, 0, $offset +
1, true );
3251 $after = array_slice( $array, $offset +
1, count($array)-$offset, true );
3253 $output = $before +
$insert +
$after;
3258 /* Recursively converts the parameter (an object) to an array with the same data */
3259 function wfObjectToArray( $object, $recursive = true ) {
3261 foreach ( get_object_vars($object) as $key => $value ) {
3262 if ( is_object($value) && $recursive ) {
3263 $value = wfObjectToArray( $value );
3266 $array[$key] = $value;
3273 * Set PHP's memory limit to the larger of php.ini or $wgMemoryLimit;
3274 * @return Integer value memory was set to.
3277 function wfMemoryLimit () {
3278 global $wgMemoryLimit;
3279 $memlimit = wfShorthandToInteger( ini_get( "memory_limit" ) );
3280 $conflimit = wfShorthandToInteger( $wgMemoryLimit );
3281 if( $memlimit != -1 ) {
3282 if( $conflimit == -1 ) {
3283 wfDebug( "Removing PHP's memory limit\n" );
3284 wfSuppressWarnings();
3285 ini_set( "memory_limit", $conflimit );
3286 wfRestoreWarnings();
3288 } elseif ( $conflimit > $memlimit ) {
3289 wfDebug( "Raising PHP's memory limit to $conflimit bytes\n" );
3290 wfSuppressWarnings();
3291 ini_set( "memory_limit", $conflimit );
3292 wfRestoreWarnings();
3300 * Converts shorthand byte notation to integer form
3301 * @param $string String
3304 function wfShorthandToInteger ( $string = '' ) {
3305 $string = trim($string);
3306 if( empty($string) ) { return -1; }
3307 $last = strtolower($string[strlen($string)-1]);
3308 $val = intval($string);
3321 /* Get the normalised IETF language tag
3322 * @param $code String: The language code.
3323 * @return $langCode String: The language code which complying with BCP 47 standards.
3325 function wfBCP47( $code ) {
3326 $codeSegment = explode( '-', $code );
3327 foreach ( $codeSegment as $segNo => $seg ) {
3328 if ( count( $codeSegment ) > 0 ) {
3329 // ISO 3166 country code
3330 if ( ( strlen( $seg ) == 2 ) && ( $segNo > 0 ) )
3331 $codeBCP[$segNo] = strtoupper( $seg );
3332 // ISO 15924 script code
3333 else if ( ( strlen( $seg ) == 4 ) && ( $segNo > 0 ) )
3334 $codeBCP[$segNo] = ucfirst( $seg );
3335 // Use lowercase for other cases
3337 $codeBCP[$segNo] = strtolower( $seg );
3339 // Use lowercase for single segment
3340 $codeBCP[$segNo] = strtolower( $seg );
3343 $langCode = implode ( '-' , $codeBCP );