de8e6d98127261f23b663ed7b15215d0863ecee3
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 if ( !function_exists( 'array_intersect_key' ) ) {
196 * Define our own array_intersect_key function
198 function array_intersect_key( $isec, $keys ) {
199 $argc = func_num_args();
202 for ( $i = 1; $isec && $i < $argc; $i++
) {
203 $arr = func_get_arg( $i );
205 foreach ( array_keys( $isec ) as $key ) {
206 if ( !isset( $arr[$key] ) )
207 unset( $isec[$key] );
214 foreach ( array_keys( $isec ) as $key ) {
215 if ( isset( $keys[$key] ) )
216 $res[$key] = $isec[$key];
224 // Support for Wietse Venema's taint feature
225 if ( !function_exists( 'istainted' ) ) {
226 function istainted( $var ) {
229 function taint( $var, $level = 0 ) {}
230 function untaint( $var, $level = 0 ) {}
231 define( 'TC_HTML', 1 );
232 define( 'TC_SHELL', 1 );
233 define( 'TC_MYSQL', 1 );
234 define( 'TC_PCRE', 1 );
235 define( 'TC_SELF', 1 );
241 * Like array_diff( $a, $b ) except that it works with two-dimensional arrays.
243 function wfArrayDiff2( $a, $b ) {
244 return array_udiff( $a, $b, 'wfArrayDiff2_cmp' );
246 function wfArrayDiff2_cmp( $a, $b ) {
247 if ( !is_array( $a ) ) {
248 return strcmp( $a, $b );
249 } elseif ( count( $a ) !== count( $b ) ) {
250 return count( $a ) < count( $b ) ?
-1 : 1;
254 while( ( list( $keyA, $valueA ) = each( $a ) ) && ( list( $keyB, $valueB ) = each( $b ) ) ) {
255 $cmp = strcmp( $valueA, $valueB );
265 * Wrapper for clone(), for compatibility with PHP4-friendly extensions.
266 * PHP 5 won't let you declare a 'clone' function, even conditionally,
267 * so it has to be a wrapper with a different name.
269 function wfClone( $object ) {
270 return clone( $object );
274 * Seed Mersenne Twister
275 * No-op for compatibility; only necessary in PHP < 4.2.0
277 function wfSeedRandom() {
282 * Get a random decimal value between 0 and 1, in a way
283 * not likely to give duplicate values for any realistic
284 * number of articles.
288 function wfRandom() {
289 # The maximum random value is "only" 2^31-1, so get two random
290 # values to reduce the chance of dupes
291 $max = mt_getrandmax() +
1;
292 $rand = number_format( (mt_rand() * $max +
mt_rand())
293 / $max / $max, 12, '.', '' );
298 * We want some things to be included as literal characters in our title URLs
299 * for prettiness, which urlencode encodes by default. According to RFC 1738,
300 * all of the following should be safe:
304 * But + is not safe because it's used to indicate a space; &= are only safe in
305 * paths and not in queries (and we don't distinguish here); ' seems kind of
306 * scary; and urlencode() doesn't touch -_. to begin with. Plus, although /
307 * is reserved, we don't care. So the list we unescape is:
311 * %2F in the page titles seems to fatally break for some reason.
316 function wfUrlencode( $s ) {
317 $s = urlencode( $s );
319 array( '%3B','%3A','%40','%24','%21','%2A','%28','%29','%2C','%2F' ),
320 array( ';', ':', '@', '$', '!', '*', '(', ')', ',', '/' ),
328 * Sends a line to the debug log if enabled or, optionally, to a comment in output.
329 * In normal operation this is a NOP.
331 * Controlling globals:
332 * $wgDebugLogFile - points to the log file
333 * $wgProfileOnly - if set, normal debug messages will not be recorded.
334 * $wgDebugRawPage - if false, 'action=raw' hits will not result in debug output.
335 * $wgDebugComments - if on, some debug items may appear in comments in the HTML output.
337 * @param $text String
338 * @param $logonly Bool: set true to avoid appearing in HTML when $wgDebugComments is set
340 function wfDebug( $text, $logonly = false ) {
341 global $wgOut, $wgDebugLogFile, $wgDebugComments, $wgProfileOnly, $wgDebugRawPage;
342 global $wgDebugLogPrefix, $wgShowDebug;
343 static $recursion = 0;
345 static $cache = array(); // Cache of unoutputted messages
347 # Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
348 if ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' && !$wgDebugRawPage ) {
352 if ( ( $wgDebugComments ||
$wgShowDebug ) && !$logonly ) {
355 if ( !isset( $wgOut ) ) {
358 if ( !StubObject
::isRealObject( $wgOut ) ) {
367 // add the message and possible cached ones to the output
368 array_map( array( $wgOut, 'debug' ), $cache );
371 if ( $wgDebugLogFile != '' && !$wgProfileOnly ) {
372 # Strip unprintables; they can switch terminal modes when binary data
373 # gets dumped, which is pretty annoying.
374 $text = preg_replace( '![\x00-\x08\x0b\x0c\x0e-\x1f]!', ' ', $text );
375 $text = $wgDebugLogPrefix . $text;
376 wfErrorLog( $text, $wgDebugLogFile );
381 * Send a line giving PHP memory usage.
382 * @param $exact Bool: print exact values instead of kilobytes (default: false)
384 function wfDebugMem( $exact = false ) {
385 $mem = memory_get_usage();
387 $mem = floor( $mem / 1024 ) . ' kilobytes';
391 wfDebug( "Memory usage: $mem\n" );
395 * Send a line to a supplementary debug log file, if configured, or main debug log if not.
396 * $wgDebugLogGroups[$logGroup] should be set to a filename to send to a separate log.
398 * @param $logGroup String
399 * @param $text String
400 * @param $public Bool: whether to log the event in the public log if no private
401 * log file is specified, (default true)
403 function wfDebugLog( $logGroup, $text, $public = true ) {
404 global $wgDebugLogGroups, $wgShowHostnames;
405 $text = trim($text)."\n";
406 if( isset( $wgDebugLogGroups[$logGroup] ) ) {
407 $time = wfTimestamp( TS_DB
);
409 if ( $wgShowHostnames ) {
410 $host = wfHostname();
414 wfErrorLog( "$time $host $wiki: $text", $wgDebugLogGroups[$logGroup] );
415 } else if ( $public === true ) {
416 wfDebug( $text, true );
421 * Log for database errors
422 * @param $text String: database error message.
424 function wfLogDBError( $text ) {
425 global $wgDBerrorLog, $wgDBname;
426 if ( $wgDBerrorLog ) {
427 $host = trim(`hostname`
);
428 $text = date('D M j G:i:s T Y') . "\t$host\t$wgDBname\t$text";
429 wfErrorLog( $text, $wgDBerrorLog );
434 * Log to a file without getting "file size exceeded" signals.
436 * Can also log to TCP or UDP with the syntax udp://host:port/prefix. This will
437 * send lines to the specified port, prefixed by the specified prefix and a space.
439 function wfErrorLog( $text, $file ) {
440 if ( substr( $file, 0, 4 ) == 'udp:' ) {
441 if ( preg_match( '!^(tcp|udp):(?://)?\[([0-9a-fA-F:]+)\]:(\d+)(?:/(.*))?$!', $file, $m ) ) {
442 // IPv6 bracketed host
445 $port = intval( $m[3] );
446 $prefix = isset( $m[4] ) ?
$m[4] : false;
448 } elseif ( preg_match( '!^(tcp|udp):(?://)?([a-zA-Z0-9.-]+):(\d+)(?:/(.*))?$!', $file, $m ) ) {
451 if ( !IP
::isIPv4( $host ) ) {
452 $host = gethostbyname( $host );
454 $port = intval( $m[3] );
455 $prefix = isset( $m[4] ) ?
$m[4] : false;
458 throw new MWException( __METHOD__
.": Invalid UDP specification" );
460 // Clean it up for the multiplexer
461 if ( strval( $prefix ) !== '' ) {
462 $text = preg_replace( '/^/m', $prefix . ' ', $text );
463 if ( substr( $text, -1 ) != "\n" ) {
468 $sock = socket_create( $domain, SOCK_DGRAM
, SOL_UDP
);
472 socket_sendto( $sock, $text, strlen( $text ), 0, $host, $port );
473 socket_close( $sock );
475 wfSuppressWarnings();
476 $exists = file_exists( $file );
477 $size = $exists ?
filesize( $file ) : false;
478 if ( !$exists ||
( $size !== false && $size +
strlen( $text ) < 0x7fffffff ) ) {
479 error_log( $text, 3, $file );
488 function wfLogProfilingData() {
489 global $wgRequestTime, $wgDebugLogFile, $wgDebugRawPage, $wgRequest;
490 global $wgProfiler, $wgProfileLimit, $wgUser;
491 # Profiling must actually be enabled...
492 if( !isset( $wgProfiler ) ) return;
493 # Get total page request time
495 $elapsed = $now - $wgRequestTime;
496 # Only show pages that longer than $wgProfileLimit time (default is 0)
497 if( $elapsed <= $wgProfileLimit ) return;
498 $prof = wfGetProfilingOutput( $wgRequestTime, $elapsed );
500 if( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) )
501 $forward = ' forwarded for ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
502 if( !empty( $_SERVER['HTTP_CLIENT_IP'] ) )
503 $forward .= ' client IP ' . $_SERVER['HTTP_CLIENT_IP'];
504 if( !empty( $_SERVER['HTTP_FROM'] ) )
505 $forward .= ' from ' . $_SERVER['HTTP_FROM'];
507 $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
508 // Don't unstub $wgUser at this late stage just for statistics purposes
509 if( StubObject
::isRealObject($wgUser) && $wgUser->isAnon() )
511 $log = sprintf( "%s\t%04.3f\t%s\n",
512 gmdate( 'YmdHis' ), $elapsed,
513 urldecode( $wgRequest->getRequestURL() . $forward ) );
514 if ( $wgDebugLogFile != '' && ( $wgRequest->getVal('action') != 'raw' ||
$wgDebugRawPage ) ) {
515 wfErrorLog( $log . $prof, $wgDebugLogFile );
520 * Check if the wiki read-only lock file is present. This can be used to lock
521 * off editing functions, but doesn't guarantee that the database will not be
525 function wfReadOnly() {
526 global $wgReadOnlyFile, $wgReadOnly;
528 if ( !is_null( $wgReadOnly ) ) {
529 return (bool)$wgReadOnly;
531 if ( $wgReadOnlyFile == '' ) {
534 // Set $wgReadOnly for faster access next time
535 if ( is_file( $wgReadOnlyFile ) ) {
536 $wgReadOnly = file_get_contents( $wgReadOnlyFile );
540 return (bool)$wgReadOnly;
543 function wfReadOnlyReason() {
550 * Return a Language object from $langcode
551 * @param $langcode Mixed: either:
552 * - a Language object
553 * - code of the language to get the message for, if it is
554 * a valid code create a language for that language, if
555 * it is a string but not a valid code then make a basic
557 * - a boolean: if it's false then use the current users
558 * language (as a fallback for the old parameter
559 * functionality), or if it is true then use the wikis
560 * @return Language object
562 function wfGetLangObj( $langcode = false ){
563 # Identify which language to get or create a language object for.
564 if( $langcode instanceof Language
)
565 # Great, we already have the object!
569 if( $langcode === $wgContLang->getCode() ||
$langcode === true )
570 # $langcode is the language code of the wikis content language object.
571 # or it is a boolean and value is true
575 if( $langcode === $wgLang->getCode() ||
$langcode === false )
576 # $langcode is the language code of user language object.
577 # or it was a boolean and value is false
580 $validCodes = array_keys( Language
::getLanguageNames() );
581 if( in_array( $langcode, $validCodes ) )
582 # $langcode corresponds to a valid language.
583 return Language
::factory( $langcode );
585 # $langcode is a string, but not a valid language code; use content language.
586 wfDebug( "Invalid language code passed to wfGetLangObj, falling back to content language.\n" );
591 * Get a message from anywhere, for the current user language.
593 * Use wfMsgForContent() instead if the message should NOT
594 * change depending on the user preferences.
596 * @param $key String: lookup key for the message, usually
597 * defined in languages/Language.php
599 * This function also takes extra optional parameters (not
600 * shown in the function definition), which can by used to
601 * insert variable text into the predefined message.
603 function wfMsg( $key ) {
604 $args = func_get_args();
605 array_shift( $args );
606 return wfMsgReal( $key, $args, true );
610 * Same as above except doesn't transform the message
612 function wfMsgNoTrans( $key ) {
613 $args = func_get_args();
614 array_shift( $args );
615 return wfMsgReal( $key, $args, true, false, false );
619 * Get a message from anywhere, for the current global language
620 * set with $wgLanguageCode.
622 * Use this if the message should NOT change dependent on the
623 * language set in the user's preferences. This is the case for
624 * most text written into logs, as well as link targets (such as
625 * the name of the copyright policy page). Link titles, on the
626 * other hand, should be shown in the UI language.
628 * Note that MediaWiki allows users to change the user interface
629 * language in their preferences, but a single installation
630 * typically only contains content in one language.
632 * Be wary of this distinction: If you use wfMsg() where you should
633 * use wfMsgForContent(), a user of the software may have to
634 * customize over 70 messages in order to, e.g., fix a link in every
637 * @param $key String: lookup key for the message, usually
638 * defined in languages/Language.php
640 function wfMsgForContent( $key ) {
641 global $wgForceUIMsgAsContentMsg;
642 $args = func_get_args();
643 array_shift( $args );
645 if( is_array( $wgForceUIMsgAsContentMsg ) &&
646 in_array( $key, $wgForceUIMsgAsContentMsg ) )
648 return wfMsgReal( $key, $args, true, $forcontent );
652 * Same as above except doesn't transform the message
654 function wfMsgForContentNoTrans( $key ) {
655 global $wgForceUIMsgAsContentMsg;
656 $args = func_get_args();
657 array_shift( $args );
659 if( is_array( $wgForceUIMsgAsContentMsg ) &&
660 in_array( $key, $wgForceUIMsgAsContentMsg ) )
662 return wfMsgReal( $key, $args, true, $forcontent, false );
666 * Get a message from the language file, for the UI elements
668 function wfMsgNoDB( $key ) {
669 $args = func_get_args();
670 array_shift( $args );
671 return wfMsgReal( $key, $args, false );
675 * Get a message from the language file, for the content
677 function wfMsgNoDBForContent( $key ) {
678 global $wgForceUIMsgAsContentMsg;
679 $args = func_get_args();
680 array_shift( $args );
682 if( is_array( $wgForceUIMsgAsContentMsg ) &&
683 in_array( $key, $wgForceUIMsgAsContentMsg ) )
685 return wfMsgReal( $key, $args, false, $forcontent );
690 * Really get a message
691 * @param $key String: key to get.
693 * @param $useDB Boolean
694 * @param $transform Boolean: Whether or not to transform the message.
695 * @param $forContent Mixed: Language code, or false for user lang, true for content lang.
696 * @return String: the requested message.
698 function wfMsgReal( $key, $args, $useDB = true, $forContent = false, $transform = true ) {
699 wfProfileIn( __METHOD__
);
700 $message = wfMsgGetKey( $key, $useDB, $forContent, $transform );
701 $message = wfMsgReplaceArgs( $message, $args );
702 wfProfileOut( __METHOD__
);
707 * This function provides the message source for messages to be edited which are *not* stored in the database.
708 * @param $key String:
710 function wfMsgWeirdKey( $key ) {
711 $source = wfMsgGetKey( $key, false, true, false );
712 if ( wfEmptyMsg( $key, $source ) )
719 * Fetch a message string value, but don't replace any keys yet.
722 * @param $langCode String: Code of the language to get the message for, or
723 * behaves as a content language switch if it is a boolean.
724 * @param $transform Boolean: whether to parse magic words, etc.
728 function wfMsgGetKey( $key, $useDB, $langCode = false, $transform = true ) {
729 global $wgContLang, $wgMessageCache;
731 wfRunHooks('NormalizeMessageKey', array(&$key, &$useDB, &$langCode, &$transform));
733 # If $wgMessageCache isn't initialised yet, try to return something sensible.
734 if( is_object( $wgMessageCache ) ) {
735 $message = $wgMessageCache->get( $key, $useDB, $langCode );
737 $message = $wgMessageCache->transform( $message );
740 $lang = wfGetLangObj( $langCode );
742 # MessageCache::get() does this already, Language::getMessage() doesn't
743 # ISSUE: Should we try to handle "message/lang" here too?
744 $key = str_replace( ' ' , '_' , $wgContLang->lcfirst( $key ) );
746 if( is_object( $lang ) ) {
747 $message = $lang->getMessage( $key );
757 * Replace message parameter keys on the given formatted output.
759 * @param $message String
764 function wfMsgReplaceArgs( $message, $args ) {
765 # Fix windows line-endings
766 # Some messages are split with explode("\n", $msg)
767 $message = str_replace( "\r", '', $message );
770 if ( count( $args ) ) {
771 if ( is_array( $args[0] ) ) {
772 $args = array_values( $args[0] );
774 $replacementKeys = array();
775 foreach( $args as $n => $param ) {
776 $replacementKeys['$' . ($n +
1)] = $param;
778 $message = strtr( $message, $replacementKeys );
785 * Return an HTML-escaped version of a message.
786 * Parameter replacements, if any, are done *after* the HTML-escaping,
787 * so parameters may contain HTML (eg links or form controls). Be sure
788 * to pre-escape them if you really do want plaintext, or just wrap
789 * the whole thing in htmlspecialchars().
792 * @param string ... parameters
795 function wfMsgHtml( $key ) {
796 $args = func_get_args();
797 array_shift( $args );
798 return wfMsgReplaceArgs( htmlspecialchars( wfMsgGetKey( $key, true ) ), $args );
802 * Return an HTML version of message
803 * Parameter replacements, if any, are done *after* parsing the wiki-text message,
804 * so parameters may contain HTML (eg links or form controls). Be sure
805 * to pre-escape them if you really do want plaintext, or just wrap
806 * the whole thing in htmlspecialchars().
809 * @param string ... parameters
812 function wfMsgWikiHtml( $key ) {
814 $args = func_get_args();
815 array_shift( $args );
816 return wfMsgReplaceArgs( $wgOut->parse( wfMsgGetKey( $key, true ), /* can't be set to false */ true ), $args );
820 * Returns message in the requested format
821 * @param $key String: key of the message
822 * @param $options Array: processing rules. Can take the following options:
823 * <i>parse</i>: parses wikitext to html
824 * <i>parseinline</i>: parses wikitext to html and removes the surrounding
825 * p's added by parser or tidy
826 * <i>escape</i>: filters message through htmlspecialchars
827 * <i>escapenoentities</i>: same, but allows entity references like through
828 * <i>replaceafter</i>: parameters are substituted after parsing or escaping
829 * <i>parsemag</i>: transform the message using magic phrases
830 * <i>content</i>: fetch message for content language instead of interface
831 * Also can accept a single associative argument, of the form 'language' => 'xx':
832 * <i>language</i>: Language object or language code to fetch message for
833 * (overriden by <i>content</i>), its behaviour with parser, parseinline
834 * and parsemag is undefined.
835 * Behavior for conflicting options (e.g., parse+parseinline) is undefined.
837 function wfMsgExt( $key, $options ) {
840 $args = func_get_args();
841 array_shift( $args );
842 array_shift( $args );
843 $options = (array)$options;
845 foreach( $options as $arrayKey => $option ) {
846 if( !preg_match( '/^[0-9]+|language$/', $arrayKey ) ) {
847 # An unknown index, neither numeric nor "language"
848 wfWarn( "wfMsgExt called with incorrect parameter key $arrayKey", 1, E_USER_WARNING
);
849 } elseif( preg_match( '/^[0-9]+$/', $arrayKey ) && !in_array( $option,
850 array( 'parse', 'parseinline', 'escape', 'escapenoentities',
851 'replaceafter', 'parsemag', 'content' ) ) ) {
852 # A numeric index with unknown value
853 wfWarn( "wfMsgExt called with incorrect parameter $option", 1, E_USER_WARNING
);
857 if( in_array('content', $options, true ) ) {
860 } elseif( array_key_exists('language', $options) ) {
862 $langCode = wfGetLangObj( $options['language'] );
868 $string = wfMsgGetKey( $key, /*DB*/true, $langCode, /*Transform*/false );
870 if( !in_array('replaceafter', $options, true ) ) {
871 $string = wfMsgReplaceArgs( $string, $args );
874 if( in_array('parse', $options, true ) ) {
875 $string = $wgOut->parse( $string, true, !$forContent );
876 } elseif ( in_array('parseinline', $options, true ) ) {
877 $string = $wgOut->parse( $string, true, !$forContent );
879 if( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $string, $m ) ) {
882 } elseif ( in_array('parsemag', $options, true ) ) {
883 global $wgMessageCache;
884 if ( isset( $wgMessageCache ) ) {
885 $string = $wgMessageCache->transform( $string,
887 is_object( $langCode ) ?
$langCode : null );
891 if ( in_array('escape', $options, true ) ) {
892 $string = htmlspecialchars ( $string );
893 } elseif ( in_array( 'escapenoentities', $options, true ) ) {
894 $string = Sanitizer
::escapeHtmlAllowEntities( $string );
897 if( in_array('replaceafter', $options, true ) ) {
898 $string = wfMsgReplaceArgs( $string, $args );
906 * Just like exit() but makes a note of it.
907 * Commits open transactions except if the error parameter is set
909 * @deprecated Please return control to the caller or throw an exception
911 function wfAbruptExit( $error = false ){
912 static $called = false;
918 $bt = wfDebugBacktrace();
920 for($i = 0; $i < count($bt) ; $i++
){
921 $file = isset($bt[$i]['file']) ?
$bt[$i]['file'] : "unknown";
922 $line = isset($bt[$i]['line']) ?
$bt[$i]['line'] : "unknown";
923 wfDebug("WARNING: Abrupt exit in $file at line $line\n");
926 wfDebug("WARNING: Abrupt exit\n");
929 wfLogProfilingData();
932 wfGetLB()->closeAll();
938 * @deprecated Please return control the caller or throw an exception
940 function wfErrorExit() {
941 wfAbruptExit( true );
945 * Print a simple message and die, returning nonzero to the shell if any.
946 * Plain die() fails to return nonzero to the shell if you pass a string.
949 function wfDie( $msg='' ) {
955 * Throw a debugging exception. This function previously once exited the process,
956 * but now throws an exception instead, with similar results.
958 * @param $msg String: message shown when dieing.
960 function wfDebugDieBacktrace( $msg = '' ) {
961 throw new MWException( $msg );
965 * Fetch server name for use in error reporting etc.
966 * Use real server name if available, so we know which machine
967 * in a server farm generated the current page.
970 function wfHostname() {
972 if ( is_null( $host ) ) {
973 if ( function_exists( 'posix_uname' ) ) {
974 // This function not present on Windows
975 $uname = @posix_uname
();
979 if( is_array( $uname ) && isset( $uname['nodename'] ) ) {
980 $host = $uname['nodename'];
981 } elseif ( getenv( 'COMPUTERNAME' ) ) {
982 # Windows computer name
983 $host = getenv( 'COMPUTERNAME' );
985 # This may be a virtual server.
986 $host = $_SERVER['SERVER_NAME'];
993 * Returns a HTML comment with the elapsed time since request.
994 * This method has no side effects.
997 function wfReportTime() {
998 global $wgRequestTime, $wgShowHostnames;
1001 $elapsed = $now - $wgRequestTime;
1003 return $wgShowHostnames
1004 ?
sprintf( "<!-- Served by %s in %01.3f secs. -->", wfHostname(), $elapsed )
1005 : sprintf( "<!-- Served in %01.3f secs. -->", $elapsed );
1009 * Safety wrapper for debug_backtrace().
1011 * With Zend Optimizer 3.2.0 loaded, this causes segfaults under somewhat
1012 * murky circumstances, which may be triggered in part by stub objects
1013 * or other fancy talkin'.
1015 * Will return an empty array if Zend Optimizer is detected or if
1016 * debug_backtrace is disabled, otherwise the output from
1017 * debug_backtrace() (trimmed).
1019 * @return array of backtrace information
1021 function wfDebugBacktrace() {
1022 static $disabled = null;
1024 if( extension_loaded( 'Zend Optimizer' ) ) {
1025 wfDebug( "Zend Optimizer detected; skipping debug_backtrace for safety.\n" );
1029 if ( is_null( $disabled ) ) {
1031 $functions = explode( ',', ini_get( 'disable_functions' ) );
1032 $functions = array_map( 'trim', $functions );
1033 $functions = array_map( 'strtolower', $functions );
1034 if ( in_array( 'debug_backtrace', $functions ) ) {
1035 wfDebug( "debug_backtrace is in disabled_functions\n" );
1043 return array_slice( debug_backtrace(), 1 );
1046 function wfBacktrace() {
1047 global $wgCommandLineMode;
1049 if ( $wgCommandLineMode ) {
1054 $backtrace = wfDebugBacktrace();
1055 foreach( $backtrace as $call ) {
1056 if( isset( $call['file'] ) ) {
1057 $f = explode( DIRECTORY_SEPARATOR
, $call['file'] );
1058 $file = $f[count($f)-1];
1062 if( isset( $call['line'] ) ) {
1063 $line = $call['line'];
1067 if ( $wgCommandLineMode ) {
1068 $msg .= "$file line $line calls ";
1070 $msg .= '<li>' . $file . ' line ' . $line . ' calls ';
1072 if( !empty( $call['class'] ) ) $msg .= $call['class'] . '::';
1073 $msg .= $call['function'] . '()';
1075 if ( $wgCommandLineMode ) {
1081 if ( $wgCommandLineMode ) {
1091 /* Some generic result counters, pulled out of SearchEngine */
1097 function wfShowingResults( $offset, $limit ) {
1099 return wfMsgExt( 'showingresults', array( 'parseinline' ), $wgLang->formatNum( $limit ),
1100 $wgLang->formatNum( $offset+
1 ) );
1106 function wfShowingResultsNum( $offset, $limit, $num ) {
1108 return wfMsgExt( 'showingresultsnum', array( 'parseinline' ), $wgLang->formatNum( $limit ),
1109 $wgLang->formatNum( $offset+
1 ), $wgLang->formatNum( $num ) );
1113 * Generate (prev x| next x) (20|50|100...) type links for paging
1114 * @param $offset String
1115 * @param $limit Integer
1116 * @param $link String
1117 * @param $query String: optional URL query parameter string
1118 * @param $atend Bool: optional param for specified if this is the last page
1120 function wfViewPrevNext( $offset, $limit, $link, $query = '', $atend = false ) {
1122 $fmtLimit = $wgLang->formatNum( $limit );
1123 // FIXME: Why on earth this needs one message for the text and another one for tooltip??
1124 # Get prev/next link display text
1125 $prev = wfMsgExt( 'prevn', array('parsemag','escape'), $fmtLimit );
1126 $next = wfMsgExt( 'nextn', array('parsemag','escape'), $fmtLimit );
1127 # Get prev/next link title text
1128 $pTitle = wfMsgExt( 'prevn-title', array('parsemag','escape'), $fmtLimit );
1129 $nTitle = wfMsgExt( 'nextn-title', array('parsemag','escape'), $fmtLimit );
1130 # Fetch the title object
1131 if( is_object( $link ) ) {
1134 $title = Title
::newFromText( $link );
1135 if( is_null( $title ) ) {
1139 # Make 'previous' link
1140 if( 0 != $offset ) {
1141 $po = $offset - $limit;
1143 $q = "limit={$limit}&offset={$po}";
1144 if( $query != '' ) {
1147 $plink = '<a href="' . $title->escapeLocalUrl( $q ) . "\" title=\"{$pTitle}\" class=\"mw-prevlink\">{$prev}</a>";
1152 $no = $offset +
$limit;
1153 $q = "limit={$limit}&offset={$no}";
1154 if( $query != '' ) {
1160 $nlink = '<a href="' . $title->escapeLocalUrl( $q ) . "\" title=\"{$nTitle}\" class=\"mw-nextlink\">{$next}</a>";
1162 # Make links to set number of items per page
1163 $nums = $wgLang->pipeList( array(
1164 wfNumLink( $offset, 20, $title, $query ),
1165 wfNumLink( $offset, 50, $title, $query ),
1166 wfNumLink( $offset, 100, $title, $query ),
1167 wfNumLink( $offset, 250, $title, $query ),
1168 wfNumLink( $offset, 500, $title, $query )
1170 return wfMsgHtml( 'viewprevnext', $plink, $nlink, $nums );
1174 * Generate links for (20|50|100...) items-per-page links
1175 * @param $offset String
1176 * @param $limit Integer
1177 * @param $title Title
1178 * @param $query String: optional URL query parameter string
1180 function wfNumLink( $offset, $limit, $title, $query = '' ) {
1182 if( $query == '' ) {
1187 $q .= "limit={$limit}&offset={$offset}";
1188 $fmtLimit = $wgLang->formatNum( $limit );
1189 $lTitle = wfMsgExt('shown-title',array('parsemag','escape'),$limit);
1190 $s = '<a href="' . $title->escapeLocalUrl( $q ) . "\" title=\"{$lTitle}\" class=\"mw-numlink\">{$fmtLimit}</a>";
1196 * @todo FIXME: we may want to blacklist some broken browsers
1198 * @return bool Whereas client accept gzip compression
1200 function wfClientAcceptsGzip() {
1201 if( isset( $_SERVER['HTTP_ACCEPT_ENCODING'] ) ) {
1202 # FIXME: we may want to blacklist some broken browsers
1205 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
1206 $_SERVER['HTTP_ACCEPT_ENCODING'],
1208 if( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) return false;
1209 wfDebug( " accepts gzip\n" );
1217 * Obtain the offset and limit values from the request string;
1218 * used in special pages
1220 * @param $deflimit Default limit if none supplied
1221 * @param $optionname Name of a user preference to check against
1225 function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) {
1227 return $wgRequest->getLimitOffset( $deflimit, $optionname );
1231 * Escapes the given text so that it may be output using addWikiText()
1232 * without any linking, formatting, etc. making its way through. This
1233 * is achieved by substituting certain characters with HTML entities.
1234 * As required by the callers, <nowiki> is not used. It currently does
1235 * not filter out characters which have special meaning only at the
1236 * start of a line, such as "*".
1238 * @param $text String: text to be escaped
1240 function wfEscapeWikiText( $text ) {
1241 $text = str_replace(
1242 array( '[', '|', ']', '\'', 'ISBN ', 'RFC ', '://', "\n=", '{{' ), # }}
1243 array( '[', '|', ']', ''', 'ISBN ', 'RFC ', '://', "\n=", '{{' ),
1244 htmlspecialchars($text) );
1251 function wfQuotedPrintable( $string, $charset = '' ) {
1252 # Probably incomplete; see RFC 2045
1253 if( empty( $charset ) ) {
1254 global $wgInputEncoding;
1255 $charset = $wgInputEncoding;
1257 $charset = strtoupper( $charset );
1258 $charset = str_replace( 'ISO-8859', 'ISO8859', $charset ); // ?
1260 $illegal = '\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\xff=';
1261 $replace = $illegal . '\t ?_';
1262 if( !preg_match( "/[$illegal]/", $string ) ) return $string;
1263 $out = "=?$charset?Q?";
1264 $out .= preg_replace( "/([$replace])/e", 'sprintf("=%02X",ord("$1"))', $string );
1275 return microtime(true);
1279 * Sets dest to source and returns the original value of dest
1280 * If source is NULL, it just returns the value, it doesn't set the variable
1282 function wfSetVar( &$dest, $source ) {
1284 if ( !is_null( $source ) ) {
1291 * As for wfSetVar except setting a bit
1293 function wfSetBit( &$dest, $bit, $state = true ) {
1294 $temp = (bool)($dest & $bit );
1295 if ( !is_null( $state ) ) {
1306 * This function takes two arrays as input, and returns a CGI-style string, e.g.
1307 * "days=7&limit=100". Options in the first array override options in the second.
1308 * Options set to "" will not be output.
1310 function wfArrayToCGI( $array1, $array2 = null )
1312 if ( !is_null( $array2 ) ) {
1313 $array1 = $array1 +
$array2;
1317 foreach ( $array1 as $key => $value ) {
1318 if ( $value !== '' ) {
1322 if ( is_array( $value ) ) {
1324 foreach ( $value as $v ) {
1325 $cgi .= ( $firstTime ?
'' : '&') .
1326 urlencode( $key . '[]' ) . '=' .
1331 if ( is_object( $value ) ) {
1332 $value = $value->__toString();
1334 $cgi .= urlencode( $key ) . '=' .
1335 urlencode( $value );
1343 * This is the logical opposite of wfArrayToCGI(): it accepts a query string as
1344 * its argument and returns the same string in array form. This allows compa-
1345 * tibility with legacy functions that accept raw query strings instead of nice
1346 * arrays. Of course, keys and values are urldecode()d. Don't try passing in-
1347 * valid query strings, or it will explode.
1349 * @param $query String: query string
1350 * @return array Array version of input
1352 function wfCgiToArray( $query ) {
1353 if( isset( $query[0] ) and $query[0] == '?' ) {
1354 $query = substr( $query, 1 );
1356 $bits = explode( '&', $query );
1358 foreach( $bits as $bit ) {
1362 list( $key, $value ) = explode( '=', $bit );
1363 $key = urldecode( $key );
1364 $value = urldecode( $value );
1365 $ret[$key] = $value;
1371 * Append a query string to an existing URL, which may or may not already
1372 * have query string parameters already. If so, they will be combined.
1374 * @param $url String
1375 * @param $query Mixed: string or associative array
1378 function wfAppendQuery( $url, $query ) {
1379 if ( is_array( $query ) ) {
1380 $query = wfArrayToCGI( $query );
1382 if( $query != '' ) {
1383 if( false === strpos( $url, '?' ) ) {
1394 * Expand a potentially local URL to a fully-qualified URL. Assumes $wgServer
1395 * is correct. Also doesn't handle any type of relative URL except one
1396 * starting with a single "/": this won't work with current-path-relative URLs
1397 * like "subdir/foo.html", protocol-relative URLs like
1398 * "//en.wikipedia.org/wiki/", etc. TODO: improve this!
1400 * @param $url String: either fully-qualified or a local path + query
1401 * @return string Fully-qualified URL
1403 function wfExpandUrl( $url ) {
1404 if( substr( $url, 0, 1 ) == '/' ) {
1406 return $wgServer . $url;
1413 * This is obsolete, use SquidUpdate::purge()
1416 function wfPurgeSquidServers ($urlArr) {
1417 SquidUpdate
::purge( $urlArr );
1421 * Windows-compatible version of escapeshellarg()
1422 * Windows doesn't recognise single-quotes in the shell, but the escapeshellarg()
1423 * function puts single quotes in regardless of OS.
1425 * Also fixes the locale problems on Linux in PHP 5.2.6+ (bug backported to
1426 * earlier distro releases of PHP)
1428 function wfEscapeShellArg( ) {
1429 wfInitShellLocale();
1431 $args = func_get_args();
1434 foreach ( $args as $arg ) {
1441 if ( wfIsWindows() ) {
1442 // Escaping for an MSVC-style command line parser
1443 // Ref: http://mailman.lyra.org/pipermail/scite-interest/2002-March/000436.html
1444 // Double the backslashes before any double quotes. Escape the double quotes.
1445 $tokens = preg_split( '/(\\\\*")/', $arg, -1, PREG_SPLIT_DELIM_CAPTURE
);
1448 foreach ( $tokens as $token ) {
1450 $arg .= str_replace( '\\', '\\\\', substr( $token, 0, -1 ) ) . '\\"';
1456 // Double the backslashes before the end of the string, because
1457 // we will soon add a quote
1459 if ( preg_match( '/^(.*?)(\\\\+)$/', $arg, $m ) ) {
1460 $arg = $m[1] . str_replace( '\\', '\\\\', $m[2] );
1463 // Add surrounding quotes
1464 $retVal .= '"' . $arg . '"';
1466 $retVal .= escapeshellarg( $arg );
1473 * wfMerge attempts to merge differences between three texts.
1474 * Returns true for a clean merge and false for failure or a conflict.
1476 function wfMerge( $old, $mine, $yours, &$result ){
1479 # This check may also protect against code injection in
1480 # case of broken installations.
1481 if( !$wgDiff3 ||
!file_exists( $wgDiff3 ) ) {
1482 wfDebug( "diff3 not found\n" );
1486 # Make temporary files
1488 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
1489 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
1490 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
1492 fwrite( $oldtextFile, $old ); fclose( $oldtextFile );
1493 fwrite( $mytextFile, $mine ); fclose( $mytextFile );
1494 fwrite( $yourtextFile, $yours ); fclose( $yourtextFile );
1496 # Check for a conflict
1497 $cmd = $wgDiff3 . ' -a --overlap-only ' .
1498 wfEscapeShellArg( $mytextName ) . ' ' .
1499 wfEscapeShellArg( $oldtextName ) . ' ' .
1500 wfEscapeShellArg( $yourtextName );
1501 $handle = popen( $cmd, 'r' );
1503 if( fgets( $handle, 1024 ) ){
1511 $cmd = $wgDiff3 . ' -a -e --merge ' .
1512 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
1513 $handle = popen( $cmd, 'r' );
1516 $data = fread( $handle, 8192 );
1517 if ( strlen( $data ) == 0 ) {
1523 unlink( $mytextName ); unlink( $oldtextName ); unlink( $yourtextName );
1525 if ( $result === '' && $old !== '' && $conflict == false ) {
1526 wfDebug( "Unexpected null result from diff3. Command: $cmd\n" );
1533 * Returns unified plain-text diff of two texts.
1534 * Useful for machine processing of diffs.
1535 * @param $before String: the text before the changes.
1536 * @param $after String: the text after the changes.
1537 * @param $params String: command-line options for the diff command.
1538 * @return String: unified diff of $before and $after
1540 function wfDiff( $before, $after, $params = '-u' ) {
1541 if ($before == $after) {
1547 # This check may also protect against code injection in
1548 # case of broken installations.
1549 if( !file_exists( $wgDiff ) ){
1550 wfDebug( "diff executable not found\n" );
1551 $diffs = new Diff( explode( "\n", $before ), explode( "\n", $after ) );
1552 $format = new UnifiedDiffFormatter();
1553 return $format->format( $diffs );
1556 # Make temporary files
1558 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
1559 $newtextFile = fopen( $newtextName = tempnam( $td, 'merge-your-' ), 'w' );
1561 fwrite( $oldtextFile, $before ); fclose( $oldtextFile );
1562 fwrite( $newtextFile, $after ); fclose( $newtextFile );
1564 // Get the diff of the two files
1565 $cmd = "$wgDiff " . $params . ' ' .wfEscapeShellArg( $oldtextName, $newtextName );
1567 $h = popen( $cmd, 'r' );
1572 $data = fread( $h, 8192 );
1573 if ( strlen( $data ) == 0 ) {
1581 unlink( $oldtextName );
1582 unlink( $newtextName );
1584 // Kill the --- and +++ lines. They're not useful.
1585 $diff_lines = explode( "\n", $diff );
1586 if (strpos( $diff_lines[0], '---' ) === 0) {
1587 unset($diff_lines[0]);
1589 if (strpos( $diff_lines[1], '+++' ) === 0) {
1590 unset($diff_lines[1]);
1593 $diff = implode( "\n", $diff_lines );
1599 * A wrapper around the PHP function var_export().
1600 * Either print it or add it to the regular output ($wgOut).
1602 * @param $var A PHP variable to dump.
1604 function wfVarDump( $var ) {
1606 $s = str_replace("\n","<br />\n", var_export( $var, true ) . "\n");
1607 if ( headers_sent() ||
!@is_object
( $wgOut ) ) {
1610 $wgOut->addHTML( $s );
1615 * Provide a simple HTTP error.
1617 function wfHttpError( $code, $label, $desc ) {
1620 header( "HTTP/1.0 $code $label" );
1621 header( "Status: $code $label" );
1622 $wgOut->sendCacheControl();
1624 header( 'Content-type: text/html; charset=utf-8' );
1625 print "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">".
1626 "<html><head><title>" .
1627 htmlspecialchars( $label ) .
1628 "</title></head><body><h1>" .
1629 htmlspecialchars( $label ) .
1631 nl2br( htmlspecialchars( $desc ) ) .
1632 "</p></body></html>\n";
1636 * Clear away any user-level output buffers, discarding contents.
1638 * Suitable for 'starting afresh', for instance when streaming
1639 * relatively large amounts of data without buffering, or wanting to
1640 * output image files without ob_gzhandler's compression.
1642 * The optional $resetGzipEncoding parameter controls suppression of
1643 * the Content-Encoding header sent by ob_gzhandler; by default it
1644 * is left. See comments for wfClearOutputBuffers() for why it would
1647 * Note that some PHP configuration options may add output buffer
1648 * layers which cannot be removed; these are left in place.
1650 * @param $resetGzipEncoding Bool
1652 function wfResetOutputBuffers( $resetGzipEncoding=true ) {
1653 if( $resetGzipEncoding ) {
1654 // Suppress Content-Encoding and Content-Length
1655 // headers from 1.10+s wfOutputHandler
1656 global $wgDisableOutputCompression;
1657 $wgDisableOutputCompression = true;
1659 while( $status = ob_get_status() ) {
1660 if( $status['type'] == 0 /* PHP_OUTPUT_HANDLER_INTERNAL */ ) {
1661 // Probably from zlib.output_compression or other
1662 // PHP-internal setting which can't be removed.
1664 // Give up, and hope the result doesn't break
1668 if( !ob_end_clean() ) {
1669 // Could not remove output buffer handler; abort now
1670 // to avoid getting in some kind of infinite loop.
1673 if( $resetGzipEncoding ) {
1674 if( $status['name'] == 'ob_gzhandler' ) {
1675 // Reset the 'Content-Encoding' field set by this handler
1676 // so we can start fresh.
1677 header( 'Content-Encoding:' );
1685 * More legible than passing a 'false' parameter to wfResetOutputBuffers():
1687 * Clear away output buffers, but keep the Content-Encoding header
1688 * produced by ob_gzhandler, if any.
1690 * This should be used for HTTP 304 responses, where you need to
1691 * preserve the Content-Encoding header of the real result, but
1692 * also need to suppress the output of ob_gzhandler to keep to spec
1693 * and avoid breaking Firefox in rare cases where the headers and
1694 * body are broken over two packets.
1696 function wfClearOutputBuffers() {
1697 wfResetOutputBuffers( false );
1701 * Converts an Accept-* header into an array mapping string values to quality
1704 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
1705 # No arg means accept anything (per HTTP spec)
1707 return array( $def => 1.0 );
1712 $parts = explode( ',', $accept );
1714 foreach( $parts as $part ) {
1715 # FIXME: doesn't deal with params like 'text/html; level=1'
1716 @list
( $value, $qpart ) = explode( ';', trim( $part ) );
1718 if( !isset( $qpart ) ) {
1719 $prefs[$value] = 1.0;
1720 } elseif( preg_match( '/q\s*=\s*(\d*\.\d+)/', $qpart, $match ) ) {
1721 $prefs[$value] = floatval($match[1]);
1729 * Checks if a given MIME type matches any of the keys in the given
1730 * array. Basic wildcards are accepted in the array keys.
1732 * Returns the matching MIME type (or wildcard) if a match, otherwise
1735 * @param $type String
1736 * @param $avail Array
1740 function mimeTypeMatch( $type, $avail ) {
1741 if( array_key_exists($type, $avail) ) {
1744 $parts = explode( '/', $type );
1745 if( array_key_exists( $parts[0] . '/*', $avail ) ) {
1746 return $parts[0] . '/*';
1747 } elseif( array_key_exists( '*/*', $avail ) ) {
1756 * Returns the 'best' match between a client's requested internet media types
1757 * and the server's list of available types. Each list should be an associative
1758 * array of type to preference (preference is a float between 0.0 and 1.0).
1759 * Wildcards in the types are acceptable.
1761 * @param $cprefs Array: client's acceptable type list
1762 * @param $sprefs Array: server's offered types
1765 * @todo FIXME: doesn't handle params like 'text/plain; charset=UTF-8'
1766 * XXX: generalize to negotiate other stuff
1768 function wfNegotiateType( $cprefs, $sprefs ) {
1771 foreach( array_keys($sprefs) as $type ) {
1772 $parts = explode( '/', $type );
1773 if( $parts[1] != '*' ) {
1774 $ckey = mimeTypeMatch( $type, $cprefs );
1776 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1781 foreach( array_keys( $cprefs ) as $type ) {
1782 $parts = explode( '/', $type );
1783 if( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
1784 $skey = mimeTypeMatch( $type, $sprefs );
1786 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1794 foreach( array_keys( $combine ) as $type ) {
1795 if( $combine[$type] > $bestq ) {
1797 $bestq = $combine[$type];
1806 * Returns an array where the values in the first array are replaced by the
1807 * values in the second array with the corresponding keys
1811 function wfArrayLookup( $a, $b ) {
1812 return array_flip( array_intersect( array_flip( $a ), array_keys( $b ) ) );
1816 * Convenience function; returns MediaWiki timestamp for the present time.
1819 function wfTimestampNow() {
1821 return wfTimestamp( TS_MW
, time() );
1825 * Reference-counted warning suppression
1827 function wfSuppressWarnings( $end = false ) {
1828 static $suppressCount = 0;
1829 static $originalLevel = false;
1832 if ( $suppressCount ) {
1834 if ( !$suppressCount ) {
1835 error_reporting( $originalLevel );
1839 if ( !$suppressCount ) {
1840 $originalLevel = error_reporting( E_ALL
& ~
( E_WARNING | E_NOTICE
) );
1847 * Restore error level to previous value
1849 function wfRestoreWarnings() {
1850 wfSuppressWarnings( true );
1853 # Autodetect, convert and provide timestamps of various types
1856 * Unix time - the number of seconds since 1970-01-01 00:00:00 UTC
1858 define('TS_UNIX', 0);
1861 * MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
1866 * MySQL DATETIME (YYYY-MM-DD HH:MM:SS)
1871 * RFC 2822 format, for E-mail and HTTP headers
1873 define('TS_RFC2822', 3);
1876 * ISO 8601 format with no timezone: 1986-02-09T20:00:00Z
1878 * This is used by Special:Export
1880 define('TS_ISO_8601', 4);
1883 * An Exif timestamp (YYYY:MM:DD HH:MM:SS)
1885 * @see http://exif.org/Exif2-2.PDF The Exif 2.2 spec, see page 28 for the
1886 * DateTime tag and page 36 for the DateTimeOriginal and
1887 * DateTimeDigitized tags.
1889 define('TS_EXIF', 5);
1892 * Oracle format time.
1894 define('TS_ORACLE', 6);
1897 * Postgres format time.
1899 define('TS_POSTGRES', 7);
1904 define('TS_DB2', 8);
1907 * @param $outputtype Mixed: A timestamp in one of the supported formats, the
1908 * function will autodetect which format is supplied and act
1910 * @param $ts Mixed: the timestamp to convert or 0 for the current timestamp
1911 * @return String: in the format specified in $outputtype
1913 function wfTimestamp( $outputtype = TS_UNIX
, $ts = 0 ) {
1918 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)$/D',$ts,$da)) {
1920 } elseif (preg_match('/^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/D',$ts,$da)) {
1922 } elseif (preg_match('/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/D',$ts,$da)) {
1924 } elseif (preg_match('/^\d{1,13}$/D',$ts)) {
1927 } elseif (preg_match('/^\d{2}-\d{2}-\d{4} \d{2}:\d{2}:\d{2}.\d{6}$/', $ts)) {
1928 # TS_ORACLE // session altered to DD-MM-YYYY HH24:MI:SS.FF6
1929 $uts = strtotime(preg_replace('/(\d\d)\.(\d\d)\.(\d\d)(\.(\d+))?/', "$1:$2:$3",
1930 str_replace("+00:00", "UTC", $ts)));
1931 } elseif (preg_match('/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.*\d*)?Z$/', $ts, $da)) {
1933 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.*\d*[\+\- ](\d\d)$/',$ts,$da)) {
1935 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.*\d* GMT$/',$ts,$da)) {
1938 # Bogus value; fall back to the epoch...
1939 wfDebug("wfTimestamp() fed bogus time value: $outputtype; $ts\n");
1943 if (count( $da ) ) {
1944 // Warning! gmmktime() acts oddly if the month or day is set to 0
1945 // We may want to handle that explicitly at some point
1946 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1947 (int)$da[2],(int)$da[3],(int)$da[1]);
1950 switch($outputtype) {
1954 return gmdate( 'YmdHis', $uts );
1956 return gmdate( 'Y-m-d H:i:s', $uts );
1958 return gmdate( 'Y-m-d\TH:i:s\Z', $uts );
1959 // This shouldn't ever be used, but is included for completeness
1961 return gmdate( 'Y:m:d H:i:s', $uts );
1963 return gmdate( 'D, d M Y H:i:s', $uts ) . ' GMT';
1965 return gmdate( 'd-m-Y H:i:s.000000', $uts);
1966 //return gmdate( 'd-M-y h.i.s A', $uts) . ' +00:00';
1968 return gmdate( 'Y-m-d H:i:s', $uts) . ' GMT';
1970 return gmdate( 'Y-m-d H:i:s', $uts);
1972 throw new MWException( 'wfTimestamp() called with illegal output type.');
1977 * Return a formatted timestamp, or null if input is null.
1978 * For dealing with nullable timestamp columns in the database.
1979 * @param $outputtype Integer
1983 function wfTimestampOrNull( $outputtype = TS_UNIX
, $ts = null ) {
1984 if( is_null( $ts ) ) {
1987 return wfTimestamp( $outputtype, $ts );
1992 * Check if the operating system is Windows
1994 * @return Bool: true if it's Windows, False otherwise.
1996 function wfIsWindows() {
1997 if (substr(php_uname(), 0, 7) == 'Windows') {
2005 * Swap two variables
2007 function swap( &$x, &$y ) {
2013 function wfGetCachedNotice( $name ) {
2014 global $wgOut, $wgRenderHashAppend, $parserMemc;
2015 $fname = 'wfGetCachedNotice';
2016 wfProfileIn( $fname );
2020 if( $name === 'default' ) {
2022 global $wgSiteNotice;
2023 $notice = $wgSiteNotice;
2024 if( empty( $notice ) ) {
2025 wfProfileOut( $fname );
2029 $notice = wfMsgForContentNoTrans( $name );
2030 if( wfEmptyMsg( $name, $notice ) ||
$notice == '-' ) {
2031 wfProfileOut( $fname );
2036 // Use the extra hash appender to let eg SSL variants separately cache.
2037 $key = wfMemcKey( $name . $wgRenderHashAppend );
2038 $cachedNotice = $parserMemc->get( $key );
2039 if( is_array( $cachedNotice ) ) {
2040 if( md5( $notice ) == $cachedNotice['hash'] ) {
2041 $notice = $cachedNotice['html'];
2050 if( is_object( $wgOut ) ) {
2051 $parsed = $wgOut->parse( $notice );
2052 $parserMemc->set( $key, array( 'html' => $parsed, 'hash' => md5( $notice ) ), 600 );
2055 wfDebug( 'wfGetCachedNotice called for ' . $name . ' with no $wgOut available'."\n" );
2060 wfProfileOut( $fname );
2064 function wfGetNamespaceNotice() {
2068 if ( !isset( $wgTitle ) ||
!is_object( $wgTitle ) )
2071 $fname = 'wfGetNamespaceNotice';
2072 wfProfileIn( $fname );
2074 $key = "namespacenotice-" . $wgTitle->getNsText();
2075 $namespaceNotice = wfGetCachedNotice( $key );
2076 if ( $namespaceNotice && substr ( $namespaceNotice , 0 ,7 ) != "<p><" ) {
2077 $namespaceNotice = '<div id="namespacebanner">' . $namespaceNotice . "</div>";
2079 $namespaceNotice = "";
2082 wfProfileOut( $fname );
2083 return $namespaceNotice;
2086 function wfGetSiteNotice() {
2087 global $wgUser, $wgSiteNotice;
2088 $fname = 'wfGetSiteNotice';
2089 wfProfileIn( $fname );
2092 if( wfRunHooks( 'SiteNoticeBefore', array( &$siteNotice ) ) ) {
2093 if( is_object( $wgUser ) && $wgUser->isLoggedIn() ) {
2094 $siteNotice = wfGetCachedNotice( 'sitenotice' );
2096 $anonNotice = wfGetCachedNotice( 'anonnotice' );
2097 if( !$anonNotice ) {
2098 $siteNotice = wfGetCachedNotice( 'sitenotice' );
2100 $siteNotice = $anonNotice;
2103 if( !$siteNotice ) {
2104 $siteNotice = wfGetCachedNotice( 'default' );
2108 wfRunHooks( 'SiteNoticeAfter', array( &$siteNotice ) );
2109 wfProfileOut( $fname );
2114 * BC wrapper for MimeMagic::singleton()
2117 function &wfGetMimeMagic() {
2118 return MimeMagic
::singleton();
2122 * Tries to get the system directory for temporary files.
2123 * The TMPDIR, TMP, and TEMP environment variables are checked in sequence,
2124 * and if none are set /tmp is returned as the generic Unix default.
2126 * NOTE: When possible, use the tempfile() function to create temporary
2127 * files to avoid race conditions on file creation, etc.
2131 function wfTempDir() {
2132 foreach( array( 'TMPDIR', 'TMP', 'TEMP' ) as $var ) {
2133 $tmp = getenv( $var );
2134 if( $tmp && file_exists( $tmp ) && is_dir( $tmp ) && is_writable( $tmp ) ) {
2138 # Hope this is Unix of some kind!
2143 * Make directory, and make all parent directories if they don't exist
2145 * @param $dir String: full path to directory to create
2146 * @param $mode Integer: chmod value to use, default is $wgDirectoryMode
2147 * @param $caller String: optional caller param for debugging.
2150 function wfMkdirParents( $dir, $mode = null, $caller = null ) {
2151 global $wgDirectoryMode;
2153 if ( !is_null( $caller ) ) {
2154 wfDebug( "$caller: called wfMkdirParents($dir)" );
2157 if( strval( $dir ) === '' ||
file_exists( $dir ) )
2160 $dir = str_replace( array( '\\', '/' ), DIRECTORY_SEPARATOR
, $dir );
2162 if ( is_null( $mode ) )
2163 $mode = $wgDirectoryMode;
2165 $ok = mkdir( $dir, $mode, true ); // PHP5 <3
2167 // PHP doesn't report the path in its warning message, so add our own to aid in diagnosis.
2168 trigger_error( __FUNCTION__
. ": failed to mkdir \"$dir\" mode $mode", E_USER_WARNING
);
2174 * Increment a statistics counter
2176 function wfIncrStats( $key ) {
2177 global $wgStatsMethod;
2179 if( $wgStatsMethod == 'udp' ) {
2180 global $wgUDPProfilerHost, $wgUDPProfilerPort, $wgDBname;
2183 $socket=socket_create(AF_INET
, SOCK_DGRAM
, SOL_UDP
);
2184 $statline="stats/{$wgDBname} - 1 1 1 1 1 -total\n";
2185 socket_sendto($socket,$statline,strlen($statline),0,$wgUDPProfilerHost,$wgUDPProfilerPort);
2187 $statline="stats/{$wgDBname} - 1 1 1 1 1 {$key}\n";
2188 @socket_sendto
($socket,$statline,strlen($statline),0,$wgUDPProfilerHost,$wgUDPProfilerPort);
2189 } elseif( $wgStatsMethod == 'cache' ) {
2191 $key = wfMemcKey( 'stats', $key );
2192 if ( is_null( $wgMemc->incr( $key ) ) ) {
2193 $wgMemc->add( $key, 1 );
2201 * @param $nr Mixed: the number to format
2202 * @param $acc Integer: the number of digits after the decimal point, default 2
2203 * @param $round Boolean: whether or not to round the value, default true
2206 function wfPercent( $nr, $acc = 2, $round = true ) {
2207 $ret = sprintf( "%.${acc}f", $nr );
2208 return $round ?
round( $ret, $acc ) . '%' : "$ret%";
2212 * Encrypt a username/password.
2214 * @param $userid Integer: ID of the user
2215 * @param $password String: password of the user
2216 * @return String: hashed password
2217 * @deprecated Use User::crypt() or User::oldCrypt() instead
2219 function wfEncryptPassword( $userid, $password ) {
2220 wfDeprecated(__FUNCTION__
);
2221 # Just wrap around User::oldCrypt()
2222 return User
::oldCrypt($password, $userid);
2226 * Appends to second array if $value differs from that in $default
2228 function wfAppendToArrayIfNotDefault( $key, $value, $default, &$changed ) {
2229 if ( is_null( $changed ) ) {
2230 throw new MWException('GlobalFunctions::wfAppendToArrayIfNotDefault got null');
2232 if ( $default[$key] !== $value ) {
2233 $changed[$key] = $value;
2238 * Since wfMsg() and co suck, they don't return false if the message key they
2239 * looked up didn't exist but a XHTML string, this function checks for the
2240 * nonexistance of messages by looking at wfMsg() output
2242 * @param $msg String: the message key looked up
2243 * @param $wfMsgOut String: the output of wfMsg*()
2246 function wfEmptyMsg( $msg, $wfMsgOut ) {
2247 return $wfMsgOut === htmlspecialchars( "<$msg>" );
2251 * Find out whether or not a mixed variable exists in a string
2253 * @param $needle String
2254 * @param $str String
2257 function in_string( $needle, $str ) {
2258 return strpos( $str, $needle ) !== false;
2261 function wfSpecialList( $page, $details ) {
2263 $details = $details ?
' ' . $wgContLang->getDirMark() . "($details)" : "";
2264 return $page . $details;
2268 * Returns a regular expression of url protocols
2272 function wfUrlProtocols() {
2273 global $wgUrlProtocols;
2275 static $retval = null;
2276 if ( !is_null( $retval ) )
2279 // Support old-style $wgUrlProtocols strings, for backwards compatibility
2280 // with LocalSettings files from 1.5
2281 if ( is_array( $wgUrlProtocols ) ) {
2282 $protocols = array();
2283 foreach ($wgUrlProtocols as $protocol)
2284 $protocols[] = preg_quote( $protocol, '/' );
2286 $retval = implode( '|', $protocols );
2288 $retval = $wgUrlProtocols;
2294 * Safety wrapper around ini_get() for boolean settings.
2295 * The values returned from ini_get() are pre-normalized for settings
2296 * set via php.ini or php_flag/php_admin_flag... but *not*
2297 * for those set via php_value/php_admin_value.
2299 * It's fairly common for people to use php_value instead of php_flag,
2300 * which can leave you with an 'off' setting giving a false positive
2301 * for code that just takes the ini_get() return value as a boolean.
2303 * To make things extra interesting, setting via php_value accepts
2304 * "true" and "yes" as true, but php.ini and php_flag consider them false. :)
2305 * Unrecognized values go false... again opposite PHP's own coercion
2306 * from string to bool.
2308 * Luckily, 'properly' set settings will always come back as '0' or '1',
2309 * so we only have to worry about them and the 'improper' settings.
2311 * I frickin' hate PHP... :P
2313 * @param $setting String
2316 function wfIniGetBool( $setting ) {
2317 $val = ini_get( $setting );
2318 // 'on' and 'true' can't have whitespace around them, but '1' can.
2319 return strtolower( $val ) == 'on'
2320 ||
strtolower( $val ) == 'true'
2321 ||
strtolower( $val ) == 'yes'
2322 ||
preg_match( "/^\s*[+-]?0*[1-9]/", $val ); // approx C atoi() function
2326 * Execute a shell command, with time and memory limits mirrored from the PHP
2327 * configuration if supported.
2328 * @param $cmd Command line, properly escaped for shell.
2329 * @param &$retval optional, will receive the program's exit code.
2330 * (non-zero is usually failure)
2331 * @return collected stdout as a string (trailing newlines stripped)
2333 function wfShellExec( $cmd, &$retval=null ) {
2334 global $IP, $wgMaxShellMemory, $wgMaxShellFileSize, $wgMaxShellTime;
2337 if ( is_null( $disabled ) ) {
2339 if( wfIniGetBool( 'safe_mode' ) ) {
2340 wfDebug( "wfShellExec can't run in safe_mode, PHP's exec functions are too broken.\n" );
2343 $functions = explode( ',', ini_get( 'disable_functions' ) );
2344 $functions = array_map( 'trim', $functions );
2345 $functions = array_map( 'strtolower', $functions );
2346 if ( in_array( 'passthru', $functions ) ) {
2347 wfDebug( "passthru is in disabled_functions\n" );
2353 return "Unable to run external programs in safe mode.";
2356 wfInitShellLocale();
2358 if ( php_uname( 's' ) == 'Linux' ) {
2359 $time = intval( $wgMaxShellTime );
2360 $mem = intval( $wgMaxShellMemory );
2361 $filesize = intval( $wgMaxShellFileSize );
2363 if ( $time > 0 && $mem > 0 ) {
2364 $script = "$IP/bin/ulimit4.sh";
2365 if ( is_executable( $script ) ) {
2366 $cmd = escapeshellarg( $script ) . " $time $mem $filesize " . escapeshellarg( $cmd );
2369 } elseif ( php_uname( 's' ) == 'Windows NT' &&
2370 version_compare( PHP_VERSION
, '5.3.0', '<' ) )
2372 # This is a hack to work around PHP's flawed invocation of cmd.exe
2373 # http://news.php.net/php.internals/21796
2374 # Which is fixed in 5.3.0 :)
2375 $cmd = '"' . $cmd . '"';
2377 wfDebug( "wfShellExec: $cmd\n" );
2379 $retval = 1; // error by default?
2381 passthru( $cmd, $retval );
2382 $output = ob_get_contents();
2385 if ( $retval == 127 ) {
2386 wfDebugLog( 'exec', "Possibly missing executable file: $cmd\n" );
2392 * Workaround for http://bugs.php.net/bug.php?id=45132
2393 * escapeshellarg() destroys non-ASCII characters if LANG is not a UTF-8 locale
2395 function wfInitShellLocale() {
2396 static $done = false;
2397 if ( $done ) return;
2399 global $wgShellLocale;
2400 if ( !wfIniGetBool( 'safe_mode' ) ) {
2401 putenv( "LC_CTYPE=$wgShellLocale" );
2402 setlocale( LC_CTYPE
, $wgShellLocale );
2407 * This function works like "use VERSION" in Perl, the program will die with a
2408 * backtrace if the current version of PHP is less than the version provided
2410 * This is useful for extensions which due to their nature are not kept in sync
2411 * with releases, and might depend on other versions of PHP than the main code
2413 * Note: PHP might die due to parsing errors in some cases before it ever
2414 * manages to call this function, such is life
2416 * @see perldoc -f use
2418 * @param $req_ver Mixed: the version to check, can be a string, an integer, or
2421 function wfUsePHP( $req_ver ) {
2422 $php_ver = PHP_VERSION
;
2424 if ( version_compare( $php_ver, (string)$req_ver, '<' ) )
2425 throw new MWException( "PHP $req_ver required--this is only $php_ver" );
2429 * This function works like "use VERSION" in Perl except it checks the version
2430 * of MediaWiki, the program will die with a backtrace if the current version
2431 * of MediaWiki is less than the version provided.
2433 * This is useful for extensions which due to their nature are not kept in sync
2436 * @see perldoc -f use
2438 * @param $req_ver Mixed: the version to check, can be a string, an integer, or
2441 function wfUseMW( $req_ver ) {
2444 if ( version_compare( $wgVersion, (string)$req_ver, '<' ) )
2445 throw new MWException( "MediaWiki $req_ver required--this is only $wgVersion" );
2449 * @deprecated use StringUtils::escapeRegexReplacement
2451 function wfRegexReplacement( $string ) {
2452 return StringUtils
::escapeRegexReplacement( $string );
2456 * Return the final portion of a pathname.
2457 * Reimplemented because PHP5's basename() is buggy with multibyte text.
2458 * http://bugs.php.net/bug.php?id=33898
2460 * PHP's basename() only considers '\' a pathchar on Windows and Netware.
2461 * We'll consider it so always, as we don't want \s in our Unix paths either.
2463 * @param $path String
2464 * @param $suffix String: to remove if present
2467 function wfBaseName( $path, $suffix='' ) {
2468 $encSuffix = ($suffix == '')
2470 : ( '(?:' . preg_quote( $suffix, '#' ) . ')?' );
2472 if( preg_match( "#([^/\\\\]*?){$encSuffix}[/\\\\]*$#", $path, $matches ) ) {
2480 * Generate a relative path name to the given file.
2481 * May explode on non-matching case-insensitive paths,
2482 * funky symlinks, etc.
2484 * @param $path String: absolute destination path including target filename
2485 * @param $from String: Absolute source path, directory only
2488 function wfRelativePath( $path, $from ) {
2489 // Normalize mixed input on Windows...
2490 $path = str_replace( '/', DIRECTORY_SEPARATOR
, $path );
2491 $from = str_replace( '/', DIRECTORY_SEPARATOR
, $from );
2493 // Trim trailing slashes -- fix for drive root
2494 $path = rtrim( $path, DIRECTORY_SEPARATOR
);
2495 $from = rtrim( $from, DIRECTORY_SEPARATOR
);
2497 $pieces = explode( DIRECTORY_SEPARATOR
, dirname( $path ) );
2498 $against = explode( DIRECTORY_SEPARATOR
, $from );
2500 if( $pieces[0] !== $against[0] ) {
2501 // Non-matching Windows drive letters?
2502 // Return a full path.
2506 // Trim off common prefix
2507 while( count( $pieces ) && count( $against )
2508 && $pieces[0] == $against[0] ) {
2509 array_shift( $pieces );
2510 array_shift( $against );
2513 // relative dots to bump us to the parent
2514 while( count( $against ) ) {
2515 array_unshift( $pieces, '..' );
2516 array_shift( $against );
2519 array_push( $pieces, wfBaseName( $path ) );
2521 return implode( DIRECTORY_SEPARATOR
, $pieces );
2525 * Backwards array plus for people who haven't bothered to read the PHP manual
2526 * XXX: will not darn your socks for you.
2528 * @param $array1 Array
2529 * @param [$array2, [...]] Arrays
2532 function wfArrayMerge( $array1/* ... */ ) {
2533 $args = func_get_args();
2534 $args = array_reverse( $args, true );
2536 foreach ( $args as $arg ) {
2543 * Merge arrays in the style of getUserPermissionsErrors, with duplicate removal
2545 * wfMergeErrorArrays(
2546 * array( array( 'x' ) ),
2547 * array( array( 'x', '2' ) ),
2548 * array( array( 'x' ) ),
2549 * array( array( 'y') )
2553 * array( 'x', '2' ),
2558 function wfMergeErrorArrays(/*...*/) {
2559 $args = func_get_args();
2561 foreach ( $args as $errors ) {
2562 foreach ( $errors as $params ) {
2563 $spec = implode( "\t", $params );
2564 $out[$spec] = $params;
2567 return array_values( $out );
2571 * parse_url() work-alike, but non-broken. Differences:
2573 * 1) Does not raise warnings on bad URLs (just returns false)
2574 * 2) Handles protocols that don't use :// (e.g., mailto: and news:) correctly
2575 * 3) Adds a "delimiter" element to the array, either '://' or ':' (see (2))
2577 * @param $url String: a URL to parse
2578 * @return Array: bits of the URL in an associative array, per PHP docs
2580 function wfParseUrl( $url ) {
2581 global $wgUrlProtocols; // Allow all protocols defined in DefaultSettings/LocalSettings.php
2582 wfSuppressWarnings();
2583 $bits = parse_url( $url );
2584 wfRestoreWarnings();
2589 // most of the protocols are followed by ://, but mailto: and sometimes news: not, check for it
2590 if ( in_array( $bits['scheme'] . '://', $wgUrlProtocols ) ) {
2591 $bits['delimiter'] = '://';
2592 } elseif ( in_array( $bits['scheme'] . ':', $wgUrlProtocols ) ) {
2593 $bits['delimiter'] = ':';
2594 // parse_url detects for news: and mailto: the host part of an url as path
2595 // We have to correct this wrong detection
2596 if ( isset ( $bits['path'] ) ) {
2597 $bits['host'] = $bits['path'];
2608 * Make a URL index, appropriate for the el_index field of externallinks.
2610 function wfMakeUrlIndex( $url ) {
2611 $bits = wfParseUrl( $url );
2613 // Reverse the labels in the hostname, convert to lower case
2614 // For emails reverse domainpart only
2615 if ( $bits['scheme'] == 'mailto' ) {
2616 $mailparts = explode( '@', $bits['host'], 2 );
2617 if ( count($mailparts) === 2 ) {
2618 $domainpart = strtolower( implode( '.', array_reverse( explode( '.', $mailparts[1] ) ) ) );
2620 // No domain specified, don't mangle it
2623 $reversedHost = $domainpart . '@' . $mailparts[0];
2625 $reversedHost = strtolower( implode( '.', array_reverse( explode( '.', $bits['host'] ) ) ) );
2627 // Add an extra dot to the end
2628 // Why? Is it in wrong place in mailto links?
2629 if ( substr( $reversedHost, -1, 1 ) !== '.' ) {
2630 $reversedHost .= '.';
2632 // Reconstruct the pseudo-URL
2633 $prot = $bits['scheme'];
2634 $index = $prot . $bits['delimiter'] . $reversedHost;
2635 // Leave out user and password. Add the port, path, query and fragment
2636 if ( isset( $bits['port'] ) ) $index .= ':' . $bits['port'];
2637 if ( isset( $bits['path'] ) ) {
2638 $index .= $bits['path'];
2642 if ( isset( $bits['query'] ) ) $index .= '?' . $bits['query'];
2643 if ( isset( $bits['fragment'] ) ) $index .= '#' . $bits['fragment'];
2648 * Do any deferred updates and clear the list
2649 * TODO: This could be in Wiki.php if that class made any sense at all
2651 function wfDoUpdates()
2653 global $wgPostCommitUpdateList, $wgDeferredUpdateList;
2654 foreach ( $wgDeferredUpdateList as $update ) {
2655 $update->doUpdate();
2657 foreach ( $wgPostCommitUpdateList as $update ) {
2658 $update->doUpdate();
2660 $wgDeferredUpdateList = array();
2661 $wgPostCommitUpdateList = array();
2665 * @deprecated use StringUtils::explodeMarkup
2667 function wfExplodeMarkup( $separator, $text ) {
2668 return StringUtils
::explodeMarkup( $separator, $text );
2672 * Convert an arbitrarily-long digit string from one numeric base
2673 * to another, optionally zero-padding to a minimum column width.
2675 * Supports base 2 through 36; digit values 10-36 are represented
2676 * as lowercase letters a-z. Input is case-insensitive.
2678 * @param $input String: of digits
2679 * @param $sourceBase Integer: 2-36
2680 * @param $destBase Integer: 2-36
2681 * @param $pad Integer: 1 or greater
2682 * @param $lowercase Boolean
2683 * @return String or false on invalid input
2685 function wfBaseConvert( $input, $sourceBase, $destBase, $pad=1, $lowercase=true ) {
2686 $input = strval( $input );
2687 if( $sourceBase < 2 ||
2692 $sourceBase != intval( $sourceBase ) ||
2693 $destBase != intval( $destBase ) ||
2694 $pad != intval( $pad ) ||
2695 !is_string( $input ) ||
2699 $digitChars = ( $lowercase ) ?
'0123456789abcdefghijklmnopqrstuvwxyz' : '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
2700 $inDigits = array();
2703 // Decode and validate input string
2704 $input = strtolower( $input );
2705 for( $i = 0; $i < strlen( $input ); $i++
) {
2706 $n = strpos( $digitChars, $input{$i} );
2707 if( $n === false ||
$n > $sourceBase ) {
2713 // Iterate over the input, modulo-ing out an output digit
2714 // at a time until input is gone.
2715 while( count( $inDigits ) ) {
2717 $workDigits = array();
2720 foreach( $inDigits as $digit ) {
2721 $work *= $sourceBase;
2724 if( $work < $destBase ) {
2725 // Gonna need to pull another digit.
2726 if( count( $workDigits ) ) {
2727 // Avoid zero-padding; this lets us find
2728 // the end of the input very easily when
2729 // length drops to zero.
2733 // Finally! Actual division!
2734 $workDigits[] = intval( $work / $destBase );
2736 // Isn't it annoying that most programming languages
2737 // don't have a single divide-and-remainder operator,
2738 // even though the CPU implements it that way?
2739 $work = $work %
$destBase;
2743 // All that division leaves us with a remainder,
2744 // which is conveniently our next output digit.
2745 $outChars .= $digitChars[$work];
2748 $inDigits = $workDigits;
2751 while( strlen( $outChars ) < $pad ) {
2755 return strrev( $outChars );
2759 * Create an object with a given name and an array of construct parameters
2760 * @param $name String
2761 * @param $p Array: parameters
2763 function wfCreateObject( $name, $p ){
2764 $p = array_values( $p );
2765 switch ( count( $p ) ) {
2769 return new $name( $p[0] );
2771 return new $name( $p[0], $p[1] );
2773 return new $name( $p[0], $p[1], $p[2] );
2775 return new $name( $p[0], $p[1], $p[2], $p[3] );
2777 return new $name( $p[0], $p[1], $p[2], $p[3], $p[4] );
2779 return new $name( $p[0], $p[1], $p[2], $p[3], $p[4], $p[5] );
2781 throw new MWException( "Too many arguments to construtor in wfCreateObject" );
2786 * Alias for modularized function
2787 * @deprecated Use Http::get() instead
2789 function wfGetHTTP( $url ) {
2790 wfDeprecated(__FUNCTION__
);
2791 return Http
::get( $url );
2795 * Alias for modularized function
2796 * @deprecated Use Http::isLocalURL() instead
2798 function wfIsLocalURL( $url ) {
2799 wfDeprecated(__FUNCTION__
);
2800 return Http
::isLocalURL( $url );
2803 function wfHttpOnlySafe() {
2804 global $wgHttpOnlyBlacklist;
2805 if( !version_compare("5.2", PHP_VERSION
, "<") )
2808 if( isset( $_SERVER['HTTP_USER_AGENT'] ) ) {
2809 foreach( $wgHttpOnlyBlacklist as $regex ) {
2810 if( preg_match( $regex, $_SERVER['HTTP_USER_AGENT'] ) ) {
2820 * Initialise php session
2822 function wfSetupSession() {
2823 global $wgSessionsInMemcached, $wgCookiePath, $wgCookieDomain,
2824 $wgCookieSecure, $wgCookieHttpOnly, $wgSessionHandler;
2825 if( $wgSessionsInMemcached ) {
2826 require_once( 'MemcachedSessions.php' );
2827 } elseif( $wgSessionHandler && $wgSessionHandler != ini_get( 'session.save_handler' ) ) {
2828 # Only set this if $wgSessionHandler isn't null and session.save_handler
2829 # hasn't already been set to the desired value (that causes errors)
2830 ini_set ( 'session.save_handler', $wgSessionHandler );
2832 $httpOnlySafe = wfHttpOnlySafe();
2833 wfDebugLog( 'cookie',
2834 'session_set_cookie_params: "' . implode( '", "',
2840 $httpOnlySafe && $wgCookieHttpOnly ) ) . '"' );
2841 if( $httpOnlySafe && $wgCookieHttpOnly ) {
2842 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookieHttpOnly );
2844 // PHP 5.1 throws warnings if you pass the HttpOnly parameter for 5.2.
2845 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
2847 session_cache_limiter( 'private, must-revalidate' );
2848 wfSuppressWarnings();
2850 wfRestoreWarnings();
2854 * Get an object from the precompiled serialized directory
2856 * @return Mixed: the variable on success, false on failure
2858 function wfGetPrecompiledData( $name ) {
2861 $file = "$IP/serialized/$name";
2862 if ( file_exists( $file ) ) {
2863 $blob = file_get_contents( $file );
2865 return unserialize( $blob );
2871 function wfGetCaller( $level = 2 ) {
2872 $backtrace = wfDebugBacktrace();
2873 if ( isset( $backtrace[$level] ) ) {
2874 return wfFormatStackFrame($backtrace[$level]);
2876 $caller = 'unknown';
2882 * Return a string consisting all callers in stack, somewhat useful sometimes
2883 * for profiling specific points
2885 function wfGetAllCallers() {
2886 return implode('/', array_map('wfFormatStackFrame',array_reverse(wfDebugBacktrace())));
2890 * Return a string representation of frame
2892 function wfFormatStackFrame($frame) {
2893 return isset( $frame["class"] )?
2894 $frame["class"]."::".$frame["function"]:
2901 function wfMemcKey( /*... */ ) {
2902 $args = func_get_args();
2903 $key = wfWikiID() . ':' . implode( ':', $args );
2904 $key = str_replace( ' ', '_', $key );
2909 * Get a cache key for a foreign DB
2911 function wfForeignMemcKey( $db, $prefix /*, ... */ ) {
2912 $args = array_slice( func_get_args(), 2 );
2914 $key = "$db-$prefix:" . implode( ':', $args );
2916 $key = $db . ':' . implode( ':', $args );
2922 * Get an ASCII string identifying this wiki
2923 * This is used as a prefix in memcached keys
2925 function wfWikiID() {
2926 global $wgDBprefix, $wgDBname;
2927 if ( $wgDBprefix ) {
2928 return "$wgDBname-$wgDBprefix";
2935 * Split a wiki ID into DB name and table prefix
2937 function wfSplitWikiID( $wiki ) {
2938 $bits = explode( '-', $wiki, 2 );
2939 if ( count( $bits ) < 2 ) {
2946 * Get a Database object.
2947 * @param $db Integer: index of the connection to get. May be DB_MASTER for the
2948 * master (for write queries), DB_SLAVE for potentially lagged read
2949 * queries, or an integer >= 0 for a particular server.
2951 * @param $groups Mixed: query groups. An array of group names that this query
2952 * belongs to. May contain a single string if the query is only
2955 * @param $wiki String: the wiki ID, or false for the current wiki
2957 * Note: multiple calls to wfGetDB(DB_SLAVE) during the course of one request
2958 * will always return the same object, unless the underlying connection or load
2959 * balancer is manually destroyed.
2961 function &wfGetDB( $db, $groups = array(), $wiki = false ) {
2962 return wfGetLB( $wiki )->getConnection( $db, $groups, $wiki );
2966 * Get a load balancer object.
2968 * @param $wiki String: wiki ID, or false for the current wiki
2969 * @return LoadBalancer
2971 function wfGetLB( $wiki = false ) {
2972 return wfGetLBFactory()->getMainLB( $wiki );
2976 * Get the load balancer factory object
2978 function &wfGetLBFactory() {
2979 return LBFactory
::singleton();
2984 * Shortcut for RepoGroup::singleton()->findFile()
2985 * @param $title Either a string or Title object
2986 * @param $options Associative array of options:
2987 * time: requested time for an archived image, or false for the
2988 * current version. An image object will be returned which was
2989 * created at the specified time.
2991 * ignoreRedirect: If true, do not follow file redirects
2993 * private: If true, return restricted (deleted) files if the current
2994 * user is allowed to view them. Otherwise, such files will not
2997 * bypassCache: If true, do not use the process-local cache of File objects
2999 * @return File, or false if the file does not exist
3001 function wfFindFile( $title, $options = array() ) {
3002 return RepoGroup
::singleton()->findFile( $title, $options );
3006 * Get an object referring to a locally registered file.
3007 * Returns a valid placeholder object if the file does not exist.
3008 * @param $title Either a string or Title object
3009 * @return File, or null if passed an invalid Title
3011 function wfLocalFile( $title ) {
3012 return RepoGroup
::singleton()->getLocalRepo()->newFile( $title );
3016 * Should low-performance queries be disabled?
3020 function wfQueriesMustScale() {
3021 global $wgMiserMode;
3023 ||
( SiteStats
::pages() > 100000
3024 && SiteStats
::edits() > 1000000
3025 && SiteStats
::users() > 10000 );
3029 * Get the path to a specified script file, respecting file
3030 * extensions; this is a wrapper around $wgScriptExtension etc.
3032 * @param $script String: script filename, sans extension
3035 function wfScript( $script = 'index' ) {
3036 global $wgScriptPath, $wgScriptExtension;
3037 return "{$wgScriptPath}/{$script}{$wgScriptExtension}";
3040 * Get the script url.
3042 * @return script url
3044 function wfGetScriptUrl(){
3045 if( isset( $_SERVER['SCRIPT_NAME'] ) ) {
3047 # as it was called, minus the query string.
3049 # Some sites use Apache rewrite rules to handle subdomains,
3050 # and have PHP set up in a weird way that causes PHP_SELF
3051 # to contain the rewritten URL instead of the one that the
3052 # outside world sees.
3054 # If in this mode, use SCRIPT_URL instead, which mod_rewrite
3055 # provides containing the "before" URL.
3056 return $_SERVER['SCRIPT_NAME'];
3058 return $_SERVER['URL'];
3063 * Convenience function converts boolean values into "true"
3064 * or "false" (string) values
3066 * @param $value Boolean
3069 function wfBoolToStr( $value ) {
3070 return $value ?
'true' : 'false';
3074 * Load an extension messages file
3077 function wfLoadExtensionMessages( $extensionName, $langcode = false ) {
3081 * Get a platform-independent path to the null file, e.g.
3086 function wfGetNull() {
3087 return wfIsWindows()
3093 * Displays a maxlag error
3095 * @param $host String: server that lags the most
3096 * @param $lag Integer: maxlag (actual)
3097 * @param $maxLag Integer: maxlag (requested)
3099 function wfMaxlagError( $host, $lag, $maxLag ) {
3100 global $wgShowHostnames;
3101 header( 'HTTP/1.1 503 Service Unavailable' );
3102 header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
3103 header( 'X-Database-Lag: ' . intval( $lag ) );
3104 header( 'Content-Type: text/plain' );
3105 if( $wgShowHostnames ) {
3106 echo "Waiting for $host: $lag seconds lagged\n";
3108 echo "Waiting for a database server: $lag seconds lagged\n";
3113 * Throws a warning that $function is deprecated
3114 * @param $function String
3117 function wfDeprecated( $function ) {
3118 static $functionsWarned = array();
3119 if ( !isset( $functionsWarned[$function] ) ) {
3120 $functionsWarned[$function] = true;
3121 wfWarn( "Use of $function is deprecated.", 2 );
3126 * Send a warning either to the debug log or in a PHP error depending on
3127 * $wgDevelopmentWarnings
3129 * @param $msg String: message to send
3130 * @param $callerOffset Integer: number of itmes to go back in the backtrace to
3131 * find the correct caller (1 = function calling wfWarn, ...)
3132 * @param $level Integer: PHP error level; only used when $wgDevelopmentWarnings
3135 function wfWarn( $msg, $callerOffset = 1, $level = E_USER_NOTICE
) {
3136 $callers = wfDebugBacktrace();
3137 if( isset( $callers[$callerOffset+
1] ) ){
3138 $callerfunc = $callers[$callerOffset+
1];
3139 $callerfile = $callers[$callerOffset];
3140 if( isset( $callerfile['file'] ) && isset( $callerfile['line'] ) ){
3141 $file = $callerfile['file'] . ' at line ' . $callerfile['line'];
3143 $file = '(internal function)';
3146 if( isset( $callerfunc['class'] ) )
3147 $func .= $callerfunc['class'] . '::';
3148 $func .= @$callerfunc['function'];
3149 $msg .= " [Called from $func in $file]";
3152 global $wgDevelopmentWarnings;
3153 if ( $wgDevelopmentWarnings ) {
3154 trigger_error( $msg, $level );
3156 wfDebug( "$msg\n" );
3161 * Sleep until the worst slave's replication lag is less than or equal to
3162 * $maxLag, in seconds. Use this when updating very large numbers of rows, as
3163 * in maintenance scripts, to avoid causing too much lag. Of course, this is
3164 * a no-op if there are no slaves.
3166 * Every time the function has to wait for a slave, it will print a message to
3167 * that effect (and then sleep for a little while), so it's probably not best
3168 * to use this outside maintenance scripts in its present form.
3170 * @param $maxLag Integer
3171 * @param $wiki mixed Wiki identifier accepted by wfGetLB
3174 function wfWaitForSlaves( $maxLag, $wiki = false ) {
3176 $lb = wfGetLB( $wiki );
3177 list( $host, $lag ) = $lb->getMaxLag( $wiki );
3178 while( $lag > $maxLag ) {
3179 $name = @gethostbyaddr
( $host );
3180 if( $name !== false ) {
3183 print "Waiting for $host (lagged $lag seconds)...\n";
3185 list( $host, $lag ) = $lb->getMaxLag();
3191 * Output some plain text in command-line mode or in the installer (updaters.inc).
3192 * Do not use it in any other context, its behaviour is subject to change.
3194 function wfOut( $s ) {
3195 static $lineStarted = false;
3196 global $wgCommandLineMode;
3197 if ( $wgCommandLineMode && !defined( 'MEDIAWIKI_INSTALL' ) ) {
3200 echo htmlspecialchars( $s );
3206 * Count down from $n to zero on the terminal, with a one-second pause
3207 * between showing each number. For use in command-line scripts.
3209 function wfCountDown( $n ) {
3210 for ( $i = $n; $i >= 0; $i-- ) {
3212 echo str_repeat( "\x08", strlen( $i +
1 ) );
3223 /** Generate a random 32-character hexadecimal token.
3224 * @param $salt Mixed: some sort of salt, if necessary, to add to random
3225 * characters before hashing.
3227 function wfGenerateToken( $salt = '' ) {
3228 $salt = serialize($salt);
3230 return md5( mt_rand( 0, 0x7fffffff ) . $salt );
3234 * Replace all invalid characters with -
3235 * @param $name Mixed: filename to process
3237 function wfStripIllegalFilenameChars( $name ) {
3238 global $wgIllegalFileChars;
3239 $name = wfBaseName( $name );
3240 $name = preg_replace("/[^".Title
::legalChars()."]".($wgIllegalFileChars ?
"|[".$wgIllegalFileChars."]":"")."/",'-',$name);
3245 * Insert array into another array after the specified *KEY*
3246 * @param $array Array: The array.
3247 * @param $insert Array: The array to insert.
3248 * @param $after Mixed: The key to insert after
3250 function wfArrayInsertAfter( $array, $insert, $after ) {
3251 // Find the offset of the element to insert after.
3252 $keys = array_keys($array);
3253 $offsetByKey = array_flip( $keys );
3255 $offset = $offsetByKey[$after];
3257 // Insert at the specified offset
3258 $before = array_slice( $array, 0, $offset +
1, true );
3259 $after = array_slice( $array, $offset +
1, count($array)-$offset, true );
3261 $output = $before +
$insert +
$after;
3266 /* Recursively converts the parameter (an object) to an array with the same data */
3267 function wfObjectToArray( $object, $recursive = true ) {
3269 foreach ( get_object_vars($object) as $key => $value ) {
3270 if ( is_object($value) && $recursive ) {
3271 $value = wfObjectToArray( $value );
3274 $array[$key] = $value;
3281 * Set PHP's memory limit to the larger of php.ini or $wgMemoryLimit;
3282 * @return Integer value memory was set to.
3285 function wfMemoryLimit () {
3286 global $wgMemoryLimit;
3287 $memlimit = wfShorthandToInteger( ini_get( "memory_limit" ) );
3288 $conflimit = wfShorthandToInteger( $wgMemoryLimit );
3289 if( $memlimit != -1 ) {
3290 if( $conflimit == -1 ) {
3291 wfDebug( "Removing PHP's memory limit\n" );
3292 wfSuppressWarnings();
3293 ini_set( "memory_limit", $conflimit );
3294 wfRestoreWarnings();
3296 } elseif ( $conflimit > $memlimit ) {
3297 wfDebug( "Raising PHP's memory limit to $conflimit bytes\n" );
3298 wfSuppressWarnings();
3299 ini_set( "memory_limit", $conflimit );
3300 wfRestoreWarnings();
3308 * Converts shorthand byte notation to integer form
3309 * @param $string String
3312 function wfShorthandToInteger ( $string = '' ) {
3313 $string = trim($string);
3314 if( empty($string) ) { return -1; }
3315 $last = strtolower($string[strlen($string)-1]);
3316 $val = intval($string);
3329 /* Get the normalised IETF language tag
3330 * @param $code String: The language code.
3331 * @return $langCode String: The language code which complying with BCP 47 standards.
3333 function wfBCP47( $code ) {
3334 $codeSegment = explode( '-', $code );
3335 foreach ( $codeSegment as $segNo => $seg ) {
3336 if ( count( $codeSegment ) > 0 ) {
3337 // ISO 3166 country code
3338 if ( ( strlen( $seg ) == 2 ) && ( $segNo > 0 ) )
3339 $codeBCP[$segNo] = strtoupper( $seg );
3340 // ISO 15924 script code
3341 else if ( ( strlen( $seg ) == 4 ) && ( $segNo > 0 ) )
3342 $codeBCP[$segNo] = ucfirst( $seg );
3343 // Use lowercase for other cases
3345 $codeBCP[$segNo] = strtolower( $seg );
3347 // Use lowercase for single segment
3348 $codeBCP[$segNo] = strtolower( $seg );
3351 $langCode = implode ( '-' , $codeBCP );