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 * Seed Mersenne Twister
266 * No-op for compatibility; only necessary in PHP < 4.2.0
268 function wfSeedRandom() {
273 * Get a random decimal value between 0 and 1, in a way
274 * not likely to give duplicate values for any realistic
275 * number of articles.
279 function wfRandom() {
280 # The maximum random value is "only" 2^31-1, so get two random
281 # values to reduce the chance of dupes
282 $max = mt_getrandmax() +
1;
283 $rand = number_format( (mt_rand() * $max +
mt_rand())
284 / $max / $max, 12, '.', '' );
289 * We want some things to be included as literal characters in our title URLs
290 * for prettiness, which urlencode encodes by default. According to RFC 1738,
291 * all of the following should be safe:
295 * But + is not safe because it's used to indicate a space; &= are only safe in
296 * paths and not in queries (and we don't distinguish here); ' seems kind of
297 * scary; and urlencode() doesn't touch -_. to begin with. Plus, although /
298 * is reserved, we don't care. So the list we unescape is:
302 * %2F in the page titles seems to fatally break for some reason.
307 function wfUrlencode( $s ) {
308 $s = urlencode( $s );
310 array( '%3B','%3A','%40','%24','%21','%2A','%28','%29','%2C','%2F' ),
311 array( ';', ':', '@', '$', '!', '*', '(', ')', ',', '/' ),
319 * Sends a line to the debug log if enabled or, optionally, to a comment in output.
320 * In normal operation this is a NOP.
322 * Controlling globals:
323 * $wgDebugLogFile - points to the log file
324 * $wgProfileOnly - if set, normal debug messages will not be recorded.
325 * $wgDebugRawPage - if false, 'action=raw' hits will not result in debug output.
326 * $wgDebugComments - if on, some debug items may appear in comments in the HTML output.
328 * @param $text String
329 * @param $logonly Bool: set true to avoid appearing in HTML when $wgDebugComments is set
331 function wfDebug( $text, $logonly = false ) {
332 global $wgOut, $wgDebugLogFile, $wgDebugComments, $wgProfileOnly, $wgDebugRawPage;
333 global $wgDebugLogPrefix, $wgShowDebug;
334 static $recursion = 0;
336 static $cache = array(); // Cache of unoutputted messages
337 $text = wfDebugTimer() . $text;
339 # Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
340 if ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' && !$wgDebugRawPage ) {
344 if ( ( $wgDebugComments ||
$wgShowDebug ) && !$logonly ) {
347 if ( !isset( $wgOut ) ) {
350 if ( !StubObject
::isRealObject( $wgOut ) ) {
359 // add the message and possible cached ones to the output
360 array_map( array( $wgOut, 'debug' ), $cache );
363 if ( $wgDebugLogFile != '' && !$wgProfileOnly ) {
364 # Strip unprintables; they can switch terminal modes when binary data
365 # gets dumped, which is pretty annoying.
366 $text = preg_replace( '![\x00-\x08\x0b\x0c\x0e-\x1f]!', ' ', $text );
367 $text = $wgDebugLogPrefix . $text;
368 wfErrorLog( $text, $wgDebugLogFile );
372 function wfDebugTimer() {
373 global $wgDebugTimestamps;
374 if ( !$wgDebugTimestamps ) return '';
375 static $start = null;
377 if ( $start === null ) {
378 $start = microtime( true );
379 $prefix = "\n$start";
381 $prefix = sprintf( "%6.4f", microtime( true ) - $start );
384 return $prefix . ' ';
388 * Send a line giving PHP memory usage.
389 * @param $exact Bool: print exact values instead of kilobytes (default: false)
391 function wfDebugMem( $exact = false ) {
392 $mem = memory_get_usage();
394 $mem = floor( $mem / 1024 ) . ' kilobytes';
398 wfDebug( "Memory usage: $mem\n" );
402 * Send a line to a supplementary debug log file, if configured, or main debug log if not.
403 * $wgDebugLogGroups[$logGroup] should be set to a filename to send to a separate log.
405 * @param $logGroup String
406 * @param $text String
407 * @param $public Bool: whether to log the event in the public log if no private
408 * log file is specified, (default true)
410 function wfDebugLog( $logGroup, $text, $public = true ) {
411 global $wgDebugLogGroups, $wgShowHostnames;
412 $text = trim($text)."\n";
413 if( isset( $wgDebugLogGroups[$logGroup] ) ) {
414 $time = wfTimestamp( TS_DB
);
416 if ( $wgShowHostnames ) {
417 $host = wfHostname();
421 wfErrorLog( "$time $host $wiki: $text", $wgDebugLogGroups[$logGroup] );
422 } else if ( $public === true ) {
423 wfDebug( $text, true );
428 * Log for database errors
429 * @param $text String: database error message.
431 function wfLogDBError( $text ) {
432 global $wgDBerrorLog, $wgDBname;
433 if ( $wgDBerrorLog ) {
434 $host = trim(`hostname`
);
435 $text = date('D M j G:i:s T Y') . "\t$host\t$wgDBname\t$text";
436 wfErrorLog( $text, $wgDBerrorLog );
441 * Log to a file without getting "file size exceeded" signals.
443 * Can also log to TCP or UDP with the syntax udp://host:port/prefix. This will
444 * send lines to the specified port, prefixed by the specified prefix and a space.
446 function wfErrorLog( $text, $file ) {
447 if ( substr( $file, 0, 4 ) == 'udp:' ) {
448 if ( preg_match( '!^(tcp|udp):(?://)?\[([0-9a-fA-F:]+)\]:(\d+)(?:/(.*))?$!', $file, $m ) ) {
449 // IPv6 bracketed host
452 $port = intval( $m[3] );
453 $prefix = isset( $m[4] ) ?
$m[4] : false;
455 } elseif ( preg_match( '!^(tcp|udp):(?://)?([a-zA-Z0-9.-]+):(\d+)(?:/(.*))?$!', $file, $m ) ) {
458 if ( !IP
::isIPv4( $host ) ) {
459 $host = gethostbyname( $host );
461 $port = intval( $m[3] );
462 $prefix = isset( $m[4] ) ?
$m[4] : false;
465 throw new MWException( __METHOD__
.": Invalid UDP specification" );
467 // Clean it up for the multiplexer
468 if ( strval( $prefix ) !== '' ) {
469 $text = preg_replace( '/^/m', $prefix . ' ', $text );
470 if ( substr( $text, -1 ) != "\n" ) {
475 $sock = socket_create( $domain, SOCK_DGRAM
, SOL_UDP
);
479 socket_sendto( $sock, $text, strlen( $text ), 0, $host, $port );
480 socket_close( $sock );
482 wfSuppressWarnings();
483 $exists = file_exists( $file );
484 $size = $exists ?
filesize( $file ) : false;
485 if ( !$exists ||
( $size !== false && $size +
strlen( $text ) < 0x7fffffff ) ) {
486 error_log( $text, 3, $file );
495 function wfLogProfilingData() {
496 global $wgRequestTime, $wgDebugLogFile, $wgDebugRawPage, $wgRequest;
497 global $wgProfiler, $wgProfileLimit, $wgUser;
498 # Profiling must actually be enabled...
499 if( is_null( $wgProfiler ) ) return;
500 # Get total page request time
502 $elapsed = $now - $wgRequestTime;
503 # Only show pages that longer than $wgProfileLimit time (default is 0)
504 if( $elapsed <= $wgProfileLimit ) return;
505 $prof = wfGetProfilingOutput( $wgRequestTime, $elapsed );
507 if( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) )
508 $forward = ' forwarded for ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
509 if( !empty( $_SERVER['HTTP_CLIENT_IP'] ) )
510 $forward .= ' client IP ' . $_SERVER['HTTP_CLIENT_IP'];
511 if( !empty( $_SERVER['HTTP_FROM'] ) )
512 $forward .= ' from ' . $_SERVER['HTTP_FROM'];
514 $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
515 // Don't unstub $wgUser at this late stage just for statistics purposes
516 if( StubObject
::isRealObject($wgUser) && $wgUser->isAnon() )
518 $log = sprintf( "%s\t%04.3f\t%s\n",
519 gmdate( 'YmdHis' ), $elapsed,
520 urldecode( $wgRequest->getRequestURL() . $forward ) );
521 if ( $wgDebugLogFile != '' && ( $wgRequest->getVal('action') != 'raw' ||
$wgDebugRawPage ) ) {
522 wfErrorLog( $log . $prof, $wgDebugLogFile );
527 * Check if the wiki read-only lock file is present. This can be used to lock
528 * off editing functions, but doesn't guarantee that the database will not be
532 function wfReadOnly() {
533 global $wgReadOnlyFile, $wgReadOnly;
535 if ( !is_null( $wgReadOnly ) ) {
536 return (bool)$wgReadOnly;
538 if ( $wgReadOnlyFile == '' ) {
541 // Set $wgReadOnly for faster access next time
542 if ( is_file( $wgReadOnlyFile ) ) {
543 $wgReadOnly = file_get_contents( $wgReadOnlyFile );
547 return (bool)$wgReadOnly;
550 function wfReadOnlyReason() {
557 * Return a Language object from $langcode
558 * @param $langcode Mixed: either:
559 * - a Language object
560 * - code of the language to get the message for, if it is
561 * a valid code create a language for that language, if
562 * it is a string but not a valid code then make a basic
564 * - a boolean: if it's false then use the current users
565 * language (as a fallback for the old parameter
566 * functionality), or if it is true then use the wikis
567 * @return Language object
569 function wfGetLangObj( $langcode = false ){
570 # Identify which language to get or create a language object for.
571 if( $langcode instanceof Language
)
572 # Great, we already have the object!
576 if( $langcode === $wgContLang->getCode() ||
$langcode === true )
577 # $langcode is the language code of the wikis content language object.
578 # or it is a boolean and value is true
582 if( $langcode === $wgLang->getCode() ||
$langcode === false )
583 # $langcode is the language code of user language object.
584 # or it was a boolean and value is false
587 $validCodes = array_keys( Language
::getLanguageNames() );
588 if( in_array( $langcode, $validCodes ) )
589 # $langcode corresponds to a valid language.
590 return Language
::factory( $langcode );
592 # $langcode is a string, but not a valid language code; use content language.
593 wfDebug( "Invalid language code passed to wfGetLangObj, falling back to content language.\n" );
598 * Get a message from anywhere, for the current user language.
600 * Use wfMsgForContent() instead if the message should NOT
601 * change depending on the user preferences.
603 * @param $key String: lookup key for the message, usually
604 * defined in languages/Language.php
606 * This function also takes extra optional parameters (not
607 * shown in the function definition), which can by used to
608 * insert variable text into the predefined message.
610 function wfMsg( $key ) {
611 $args = func_get_args();
612 array_shift( $args );
613 return wfMsgReal( $key, $args, true );
617 * Same as above except doesn't transform the message
619 function wfMsgNoTrans( $key ) {
620 $args = func_get_args();
621 array_shift( $args );
622 return wfMsgReal( $key, $args, true, false, false );
626 * Get a message from anywhere, for the current global language
627 * set with $wgLanguageCode.
629 * Use this if the message should NOT change dependent on the
630 * language set in the user's preferences. This is the case for
631 * most text written into logs, as well as link targets (such as
632 * the name of the copyright policy page). Link titles, on the
633 * other hand, should be shown in the UI language.
635 * Note that MediaWiki allows users to change the user interface
636 * language in their preferences, but a single installation
637 * typically only contains content in one language.
639 * Be wary of this distinction: If you use wfMsg() where you should
640 * use wfMsgForContent(), a user of the software may have to
641 * customize over 70 messages in order to, e.g., fix a link in every
644 * @param $key String: lookup key for the message, usually
645 * defined in languages/Language.php
647 function wfMsgForContent( $key ) {
648 global $wgForceUIMsgAsContentMsg;
649 $args = func_get_args();
650 array_shift( $args );
652 if( is_array( $wgForceUIMsgAsContentMsg ) &&
653 in_array( $key, $wgForceUIMsgAsContentMsg ) )
655 return wfMsgReal( $key, $args, true, $forcontent );
659 * Same as above except doesn't transform the message
661 function wfMsgForContentNoTrans( $key ) {
662 global $wgForceUIMsgAsContentMsg;
663 $args = func_get_args();
664 array_shift( $args );
666 if( is_array( $wgForceUIMsgAsContentMsg ) &&
667 in_array( $key, $wgForceUIMsgAsContentMsg ) )
669 return wfMsgReal( $key, $args, true, $forcontent, false );
673 * Get a message from the language file, for the UI elements
675 function wfMsgNoDB( $key ) {
676 $args = func_get_args();
677 array_shift( $args );
678 return wfMsgReal( $key, $args, false );
682 * Get a message from the language file, for the content
684 function wfMsgNoDBForContent( $key ) {
685 global $wgForceUIMsgAsContentMsg;
686 $args = func_get_args();
687 array_shift( $args );
689 if( is_array( $wgForceUIMsgAsContentMsg ) &&
690 in_array( $key, $wgForceUIMsgAsContentMsg ) )
692 return wfMsgReal( $key, $args, false, $forcontent );
697 * Really get a message
698 * @param $key String: key to get.
700 * @param $useDB Boolean
701 * @param $transform Boolean: Whether or not to transform the message.
702 * @param $forContent Mixed: Language code, or false for user lang, true for content lang.
703 * @return String: the requested message.
705 function wfMsgReal( $key, $args, $useDB = true, $forContent = false, $transform = true ) {
706 wfProfileIn( __METHOD__
);
707 $message = wfMsgGetKey( $key, $useDB, $forContent, $transform );
708 $message = wfMsgReplaceArgs( $message, $args );
709 wfProfileOut( __METHOD__
);
714 * This function provides the message source for messages to be edited which are *not* stored in the database.
715 * @param $key String:
717 function wfMsgWeirdKey( $key ) {
718 $source = wfMsgGetKey( $key, false, true, false );
719 if ( wfEmptyMsg( $key, $source ) )
726 * Fetch a message string value, but don't replace any keys yet.
729 * @param $langCode String: Code of the language to get the message for, or
730 * behaves as a content language switch if it is a boolean.
731 * @param $transform Boolean: whether to parse magic words, etc.
735 function wfMsgGetKey( $key, $useDB, $langCode = false, $transform = true ) {
736 global $wgContLang, $wgMessageCache;
738 wfRunHooks('NormalizeMessageKey', array(&$key, &$useDB, &$langCode, &$transform));
740 # If $wgMessageCache isn't initialised yet, try to return something sensible.
741 if( is_object( $wgMessageCache ) ) {
742 $message = $wgMessageCache->get( $key, $useDB, $langCode );
744 $message = $wgMessageCache->transform( $message );
747 $lang = wfGetLangObj( $langCode );
749 # MessageCache::get() does this already, Language::getMessage() doesn't
750 # ISSUE: Should we try to handle "message/lang" here too?
751 $key = str_replace( ' ' , '_' , $wgContLang->lcfirst( $key ) );
753 if( is_object( $lang ) ) {
754 $message = $lang->getMessage( $key );
764 * Replace message parameter keys on the given formatted output.
766 * @param $message String
771 function wfMsgReplaceArgs( $message, $args ) {
772 # Fix windows line-endings
773 # Some messages are split with explode("\n", $msg)
774 $message = str_replace( "\r", '', $message );
777 if ( count( $args ) ) {
778 if ( is_array( $args[0] ) ) {
779 $args = array_values( $args[0] );
781 $replacementKeys = array();
782 foreach( $args as $n => $param ) {
783 $replacementKeys['$' . ($n +
1)] = $param;
785 $message = strtr( $message, $replacementKeys );
792 * Return an HTML-escaped version of a message.
793 * Parameter replacements, if any, are done *after* the HTML-escaping,
794 * so parameters may contain HTML (eg links or form controls). Be sure
795 * to pre-escape them if you really do want plaintext, or just wrap
796 * the whole thing in htmlspecialchars().
799 * @param string ... parameters
802 function wfMsgHtml( $key ) {
803 $args = func_get_args();
804 array_shift( $args );
805 return wfMsgReplaceArgs( htmlspecialchars( wfMsgGetKey( $key, true ) ), $args );
809 * Return an HTML version of message
810 * Parameter replacements, if any, are done *after* parsing the wiki-text message,
811 * so parameters may contain HTML (eg links or form controls). Be sure
812 * to pre-escape them if you really do want plaintext, or just wrap
813 * the whole thing in htmlspecialchars().
816 * @param string ... parameters
819 function wfMsgWikiHtml( $key ) {
821 $args = func_get_args();
822 array_shift( $args );
823 return wfMsgReplaceArgs( $wgOut->parse( wfMsgGetKey( $key, true ), /* can't be set to false */ true ), $args );
827 * Returns message in the requested format
828 * @param $key String: key of the message
829 * @param $options Array: processing rules. Can take the following options:
830 * <i>parse</i>: parses wikitext to html
831 * <i>parseinline</i>: parses wikitext to html and removes the surrounding
832 * p's added by parser or tidy
833 * <i>escape</i>: filters message through htmlspecialchars
834 * <i>escapenoentities</i>: same, but allows entity references like through
835 * <i>replaceafter</i>: parameters are substituted after parsing or escaping
836 * <i>parsemag</i>: transform the message using magic phrases
837 * <i>content</i>: fetch message for content language instead of interface
838 * Also can accept a single associative argument, of the form 'language' => 'xx':
839 * <i>language</i>: Language object or language code to fetch message for
840 * (overriden by <i>content</i>), its behaviour with parser, parseinline
841 * and parsemag is undefined.
842 * Behavior for conflicting options (e.g., parse+parseinline) is undefined.
844 function wfMsgExt( $key, $options ) {
847 $args = func_get_args();
848 array_shift( $args );
849 array_shift( $args );
850 $options = (array)$options;
852 foreach( $options as $arrayKey => $option ) {
853 if( !preg_match( '/^[0-9]+|language$/', $arrayKey ) ) {
854 # An unknown index, neither numeric nor "language"
855 wfWarn( "wfMsgExt called with incorrect parameter key $arrayKey", 1, E_USER_WARNING
);
856 } elseif( preg_match( '/^[0-9]+$/', $arrayKey ) && !in_array( $option,
857 array( 'parse', 'parseinline', 'escape', 'escapenoentities',
858 'replaceafter', 'parsemag', 'content' ) ) ) {
859 # A numeric index with unknown value
860 wfWarn( "wfMsgExt called with incorrect parameter $option", 1, E_USER_WARNING
);
864 if( in_array('content', $options, true ) ) {
867 } elseif( array_key_exists('language', $options) ) {
869 $langCode = wfGetLangObj( $options['language'] );
875 $string = wfMsgGetKey( $key, /*DB*/true, $langCode, /*Transform*/false );
877 if( !in_array('replaceafter', $options, true ) ) {
878 $string = wfMsgReplaceArgs( $string, $args );
881 if( in_array('parse', $options, true ) ) {
882 $string = $wgOut->parse( $string, true, !$forContent );
883 } elseif ( in_array('parseinline', $options, true ) ) {
884 $string = $wgOut->parse( $string, true, !$forContent );
886 if( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $string, $m ) ) {
889 } elseif ( in_array('parsemag', $options, true ) ) {
890 global $wgMessageCache;
891 if ( isset( $wgMessageCache ) ) {
892 $string = $wgMessageCache->transform( $string,
894 is_object( $langCode ) ?
$langCode : null );
898 if ( in_array('escape', $options, true ) ) {
899 $string = htmlspecialchars ( $string );
900 } elseif ( in_array( 'escapenoentities', $options, true ) ) {
901 $string = Sanitizer
::escapeHtmlAllowEntities( $string );
904 if( in_array('replaceafter', $options, true ) ) {
905 $string = wfMsgReplaceArgs( $string, $args );
913 * Just like exit() but makes a note of it.
914 * Commits open transactions except if the error parameter is set
916 * @deprecated Please return control to the caller or throw an exception
918 function wfAbruptExit( $error = false ){
919 static $called = false;
925 $bt = wfDebugBacktrace();
927 for($i = 0; $i < count($bt) ; $i++
){
928 $file = isset($bt[$i]['file']) ?
$bt[$i]['file'] : "unknown";
929 $line = isset($bt[$i]['line']) ?
$bt[$i]['line'] : "unknown";
930 wfDebug("WARNING: Abrupt exit in $file at line $line\n");
933 wfDebug("WARNING: Abrupt exit\n");
936 wfLogProfilingData();
939 wfGetLB()->closeAll();
945 * @deprecated Please return control the caller or throw an exception
947 function wfErrorExit() {
948 wfAbruptExit( true );
952 * Print a simple message and die, returning nonzero to the shell if any.
953 * Plain die() fails to return nonzero to the shell if you pass a string.
956 function wfDie( $msg='' ) {
962 * Throw a debugging exception. This function previously once exited the process,
963 * but now throws an exception instead, with similar results.
965 * @param $msg String: message shown when dieing.
967 function wfDebugDieBacktrace( $msg = '' ) {
968 throw new MWException( $msg );
972 * Fetch server name for use in error reporting etc.
973 * Use real server name if available, so we know which machine
974 * in a server farm generated the current page.
977 function wfHostname() {
979 if ( is_null( $host ) ) {
980 if ( function_exists( 'posix_uname' ) ) {
981 // This function not present on Windows
982 $uname = @posix_uname
();
986 if( is_array( $uname ) && isset( $uname['nodename'] ) ) {
987 $host = $uname['nodename'];
988 } elseif ( getenv( 'COMPUTERNAME' ) ) {
989 # Windows computer name
990 $host = getenv( 'COMPUTERNAME' );
992 # This may be a virtual server.
993 $host = $_SERVER['SERVER_NAME'];
1000 * Returns a HTML comment with the elapsed time since request.
1001 * This method has no side effects.
1004 function wfReportTime() {
1005 global $wgRequestTime, $wgShowHostnames;
1008 $elapsed = $now - $wgRequestTime;
1010 return $wgShowHostnames
1011 ?
sprintf( "<!-- Served by %s in %01.3f secs. -->", wfHostname(), $elapsed )
1012 : sprintf( "<!-- Served in %01.3f secs. -->", $elapsed );
1016 * Safety wrapper for debug_backtrace().
1018 * With Zend Optimizer 3.2.0 loaded, this causes segfaults under somewhat
1019 * murky circumstances, which may be triggered in part by stub objects
1020 * or other fancy talkin'.
1022 * Will return an empty array if Zend Optimizer is detected or if
1023 * debug_backtrace is disabled, otherwise the output from
1024 * debug_backtrace() (trimmed).
1026 * @return array of backtrace information
1028 function wfDebugBacktrace() {
1029 static $disabled = null;
1031 if( extension_loaded( 'Zend Optimizer' ) ) {
1032 wfDebug( "Zend Optimizer detected; skipping debug_backtrace for safety.\n" );
1036 if ( is_null( $disabled ) ) {
1038 $functions = explode( ',', ini_get( 'disable_functions' ) );
1039 $functions = array_map( 'trim', $functions );
1040 $functions = array_map( 'strtolower', $functions );
1041 if ( in_array( 'debug_backtrace', $functions ) ) {
1042 wfDebug( "debug_backtrace is in disabled_functions\n" );
1050 return array_slice( debug_backtrace(), 1 );
1053 function wfBacktrace() {
1054 global $wgCommandLineMode;
1056 if ( $wgCommandLineMode ) {
1061 $backtrace = wfDebugBacktrace();
1062 foreach( $backtrace as $call ) {
1063 if( isset( $call['file'] ) ) {
1064 $f = explode( DIRECTORY_SEPARATOR
, $call['file'] );
1065 $file = $f[count($f)-1];
1069 if( isset( $call['line'] ) ) {
1070 $line = $call['line'];
1074 if ( $wgCommandLineMode ) {
1075 $msg .= "$file line $line calls ";
1077 $msg .= '<li>' . $file . ' line ' . $line . ' calls ';
1079 if( !empty( $call['class'] ) ) $msg .= $call['class'] . '::';
1080 $msg .= $call['function'] . '()';
1082 if ( $wgCommandLineMode ) {
1088 if ( $wgCommandLineMode ) {
1098 /* Some generic result counters, pulled out of SearchEngine */
1104 function wfShowingResults( $offset, $limit ) {
1106 return wfMsgExt( 'showingresults', array( 'parseinline' ), $wgLang->formatNum( $limit ),
1107 $wgLang->formatNum( $offset+
1 ) );
1113 function wfShowingResultsNum( $offset, $limit, $num ) {
1115 return wfMsgExt( 'showingresultsnum', array( 'parseinline' ), $wgLang->formatNum( $limit ),
1116 $wgLang->formatNum( $offset+
1 ), $wgLang->formatNum( $num ) );
1120 * Generate (prev x| next x) (20|50|100...) type links for paging
1121 * @param $offset String
1122 * @param $limit Integer
1123 * @param $link String
1124 * @param $query String: optional URL query parameter string
1125 * @param $atend Bool: optional param for specified if this is the last page
1127 function wfViewPrevNext( $offset, $limit, $link, $query = '', $atend = false ) {
1129 $fmtLimit = $wgLang->formatNum( $limit );
1130 // FIXME: Why on earth this needs one message for the text and another one for tooltip??
1131 # Get prev/next link display text
1132 $prev = wfMsgExt( 'prevn', array('parsemag','escape'), $fmtLimit );
1133 $next = wfMsgExt( 'nextn', array('parsemag','escape'), $fmtLimit );
1134 # Get prev/next link title text
1135 $pTitle = wfMsgExt( 'prevn-title', array('parsemag','escape'), $fmtLimit );
1136 $nTitle = wfMsgExt( 'nextn-title', array('parsemag','escape'), $fmtLimit );
1137 # Fetch the title object
1138 if( is_object( $link ) ) {
1141 $title = Title
::newFromText( $link );
1142 if( is_null( $title ) ) {
1146 # Make 'previous' link
1147 if( 0 != $offset ) {
1148 $po = $offset - $limit;
1150 $q = "limit={$limit}&offset={$po}";
1151 if( $query != '' ) {
1154 $plink = '<a href="' . $title->escapeLocalUrl( $q ) . "\" title=\"{$pTitle}\" class=\"mw-prevlink\">{$prev}</a>";
1159 $no = $offset +
$limit;
1160 $q = "limit={$limit}&offset={$no}";
1161 if( $query != '' ) {
1167 $nlink = '<a href="' . $title->escapeLocalUrl( $q ) . "\" title=\"{$nTitle}\" class=\"mw-nextlink\">{$next}</a>";
1169 # Make links to set number of items per page
1170 $nums = $wgLang->pipeList( array(
1171 wfNumLink( $offset, 20, $title, $query ),
1172 wfNumLink( $offset, 50, $title, $query ),
1173 wfNumLink( $offset, 100, $title, $query ),
1174 wfNumLink( $offset, 250, $title, $query ),
1175 wfNumLink( $offset, 500, $title, $query )
1177 return wfMsgHtml( 'viewprevnext', $plink, $nlink, $nums );
1181 * Generate links for (20|50|100...) items-per-page links
1182 * @param $offset String
1183 * @param $limit Integer
1184 * @param $title Title
1185 * @param $query String: optional URL query parameter string
1187 function wfNumLink( $offset, $limit, $title, $query = '' ) {
1189 if( $query == '' ) {
1194 $q .= "limit={$limit}&offset={$offset}";
1195 $fmtLimit = $wgLang->formatNum( $limit );
1196 $lTitle = wfMsgExt('shown-title',array('parsemag','escape'),$limit);
1197 $s = '<a href="' . $title->escapeLocalUrl( $q ) . "\" title=\"{$lTitle}\" class=\"mw-numlink\">{$fmtLimit}</a>";
1203 * @todo FIXME: we may want to blacklist some broken browsers
1205 * @return bool Whereas client accept gzip compression
1207 function wfClientAcceptsGzip() {
1208 if( isset( $_SERVER['HTTP_ACCEPT_ENCODING'] ) ) {
1209 # FIXME: we may want to blacklist some broken browsers
1212 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
1213 $_SERVER['HTTP_ACCEPT_ENCODING'],
1215 if( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) return false;
1216 wfDebug( " accepts gzip\n" );
1224 * Obtain the offset and limit values from the request string;
1225 * used in special pages
1227 * @param $deflimit Default limit if none supplied
1228 * @param $optionname Name of a user preference to check against
1232 function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) {
1234 return $wgRequest->getLimitOffset( $deflimit, $optionname );
1238 * Escapes the given text so that it may be output using addWikiText()
1239 * without any linking, formatting, etc. making its way through. This
1240 * is achieved by substituting certain characters with HTML entities.
1241 * As required by the callers, <nowiki> is not used. It currently does
1242 * not filter out characters which have special meaning only at the
1243 * start of a line, such as "*".
1245 * @param $text String: text to be escaped
1247 function wfEscapeWikiText( $text ) {
1248 $text = str_replace(
1249 array( '[', '|', ']', '\'', 'ISBN ', 'RFC ', '://', "\n=", '{{' ), # }}
1250 array( '[', '|', ']', ''', 'ISBN ', 'RFC ', '://', "\n=", '{{' ),
1251 htmlspecialchars($text) );
1258 function wfQuotedPrintable( $string, $charset = '' ) {
1259 # Probably incomplete; see RFC 2045
1260 if( empty( $charset ) ) {
1261 global $wgInputEncoding;
1262 $charset = $wgInputEncoding;
1264 $charset = strtoupper( $charset );
1265 $charset = str_replace( 'ISO-8859', 'ISO8859', $charset ); // ?
1267 $illegal = '\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\xff=';
1268 $replace = $illegal . '\t ?_';
1269 if( !preg_match( "/[$illegal]/", $string ) ) return $string;
1270 $out = "=?$charset?Q?";
1271 $out .= preg_replace( "/([$replace])/e", 'sprintf("=%02X",ord("$1"))', $string );
1282 return microtime(true);
1286 * Sets dest to source and returns the original value of dest
1287 * If source is NULL, it just returns the value, it doesn't set the variable
1289 function wfSetVar( &$dest, $source ) {
1291 if ( !is_null( $source ) ) {
1298 * As for wfSetVar except setting a bit
1300 function wfSetBit( &$dest, $bit, $state = true ) {
1301 $temp = (bool)($dest & $bit );
1302 if ( !is_null( $state ) ) {
1313 * This function takes two arrays as input, and returns a CGI-style string, e.g.
1314 * "days=7&limit=100". Options in the first array override options in the second.
1315 * Options set to "" will not be output.
1317 function wfArrayToCGI( $array1, $array2 = null )
1319 if ( !is_null( $array2 ) ) {
1320 $array1 = $array1 +
$array2;
1324 foreach ( $array1 as $key => $value ) {
1325 if ( $value !== '' ) {
1329 if ( is_array( $value ) ) {
1331 foreach ( $value as $v ) {
1332 $cgi .= ( $firstTime ?
'' : '&') .
1333 urlencode( $key . '[]' ) . '=' .
1338 if ( is_object( $value ) ) {
1339 $value = $value->__toString();
1341 $cgi .= urlencode( $key ) . '=' .
1342 urlencode( $value );
1350 * This is the logical opposite of wfArrayToCGI(): it accepts a query string as
1351 * its argument and returns the same string in array form. This allows compa-
1352 * tibility with legacy functions that accept raw query strings instead of nice
1353 * arrays. Of course, keys and values are urldecode()d. Don't try passing in-
1354 * valid query strings, or it will explode.
1356 * @param $query String: query string
1357 * @return array Array version of input
1359 function wfCgiToArray( $query ) {
1360 if( isset( $query[0] ) and $query[0] == '?' ) {
1361 $query = substr( $query, 1 );
1363 $bits = explode( '&', $query );
1365 foreach( $bits as $bit ) {
1369 list( $key, $value ) = explode( '=', $bit );
1370 $key = urldecode( $key );
1371 $value = urldecode( $value );
1372 $ret[$key] = $value;
1378 * Append a query string to an existing URL, which may or may not already
1379 * have query string parameters already. If so, they will be combined.
1381 * @param $url String
1382 * @param $query Mixed: string or associative array
1385 function wfAppendQuery( $url, $query ) {
1386 if ( is_array( $query ) ) {
1387 $query = wfArrayToCGI( $query );
1389 if( $query != '' ) {
1390 if( false === strpos( $url, '?' ) ) {
1401 * Expand a potentially local URL to a fully-qualified URL. Assumes $wgServer
1402 * is correct. Also doesn't handle any type of relative URL except one
1403 * starting with a single "/": this won't work with current-path-relative URLs
1404 * like "subdir/foo.html", protocol-relative URLs like
1405 * "//en.wikipedia.org/wiki/", etc. TODO: improve this!
1407 * @param $url String: either fully-qualified or a local path + query
1408 * @return string Fully-qualified URL
1410 function wfExpandUrl( $url ) {
1411 if( substr( $url, 0, 1 ) == '/' ) {
1413 return $wgServer . $url;
1420 * This is obsolete, use SquidUpdate::purge()
1423 function wfPurgeSquidServers ($urlArr) {
1424 SquidUpdate
::purge( $urlArr );
1428 * Windows-compatible version of escapeshellarg()
1429 * Windows doesn't recognise single-quotes in the shell, but the escapeshellarg()
1430 * function puts single quotes in regardless of OS.
1432 * Also fixes the locale problems on Linux in PHP 5.2.6+ (bug backported to
1433 * earlier distro releases of PHP)
1435 function wfEscapeShellArg( ) {
1436 wfInitShellLocale();
1438 $args = func_get_args();
1441 foreach ( $args as $arg ) {
1448 if ( wfIsWindows() ) {
1449 // Escaping for an MSVC-style command line parser
1450 // Ref: http://mailman.lyra.org/pipermail/scite-interest/2002-March/000436.html
1451 // Double the backslashes before any double quotes. Escape the double quotes.
1452 $tokens = preg_split( '/(\\\\*")/', $arg, -1, PREG_SPLIT_DELIM_CAPTURE
);
1455 foreach ( $tokens as $token ) {
1457 $arg .= str_replace( '\\', '\\\\', substr( $token, 0, -1 ) ) . '\\"';
1463 // Double the backslashes before the end of the string, because
1464 // we will soon add a quote
1466 if ( preg_match( '/^(.*?)(\\\\+)$/', $arg, $m ) ) {
1467 $arg = $m[1] . str_replace( '\\', '\\\\', $m[2] );
1470 // Add surrounding quotes
1471 $retVal .= '"' . $arg . '"';
1473 $retVal .= escapeshellarg( $arg );
1480 * wfMerge attempts to merge differences between three texts.
1481 * Returns true for a clean merge and false for failure or a conflict.
1483 function wfMerge( $old, $mine, $yours, &$result ){
1486 # This check may also protect against code injection in
1487 # case of broken installations.
1488 if( !$wgDiff3 ||
!file_exists( $wgDiff3 ) ) {
1489 wfDebug( "diff3 not found\n" );
1493 # Make temporary files
1495 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
1496 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
1497 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
1499 fwrite( $oldtextFile, $old ); fclose( $oldtextFile );
1500 fwrite( $mytextFile, $mine ); fclose( $mytextFile );
1501 fwrite( $yourtextFile, $yours ); fclose( $yourtextFile );
1503 # Check for a conflict
1504 $cmd = $wgDiff3 . ' -a --overlap-only ' .
1505 wfEscapeShellArg( $mytextName ) . ' ' .
1506 wfEscapeShellArg( $oldtextName ) . ' ' .
1507 wfEscapeShellArg( $yourtextName );
1508 $handle = popen( $cmd, 'r' );
1510 if( fgets( $handle, 1024 ) ){
1518 $cmd = $wgDiff3 . ' -a -e --merge ' .
1519 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
1520 $handle = popen( $cmd, 'r' );
1523 $data = fread( $handle, 8192 );
1524 if ( strlen( $data ) == 0 ) {
1530 unlink( $mytextName ); unlink( $oldtextName ); unlink( $yourtextName );
1532 if ( $result === '' && $old !== '' && $conflict == false ) {
1533 wfDebug( "Unexpected null result from diff3. Command: $cmd\n" );
1540 * Returns unified plain-text diff of two texts.
1541 * Useful for machine processing of diffs.
1542 * @param $before String: the text before the changes.
1543 * @param $after String: the text after the changes.
1544 * @param $params String: command-line options for the diff command.
1545 * @return String: unified diff of $before and $after
1547 function wfDiff( $before, $after, $params = '-u' ) {
1548 if ($before == $after) {
1554 # This check may also protect against code injection in
1555 # case of broken installations.
1556 if( !file_exists( $wgDiff ) ){
1557 wfDebug( "diff executable not found\n" );
1558 $diffs = new Diff( explode( "\n", $before ), explode( "\n", $after ) );
1559 $format = new UnifiedDiffFormatter();
1560 return $format->format( $diffs );
1563 # Make temporary files
1565 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
1566 $newtextFile = fopen( $newtextName = tempnam( $td, 'merge-your-' ), 'w' );
1568 fwrite( $oldtextFile, $before ); fclose( $oldtextFile );
1569 fwrite( $newtextFile, $after ); fclose( $newtextFile );
1571 // Get the diff of the two files
1572 $cmd = "$wgDiff " . $params . ' ' .wfEscapeShellArg( $oldtextName, $newtextName );
1574 $h = popen( $cmd, 'r' );
1579 $data = fread( $h, 8192 );
1580 if ( strlen( $data ) == 0 ) {
1588 unlink( $oldtextName );
1589 unlink( $newtextName );
1591 // Kill the --- and +++ lines. They're not useful.
1592 $diff_lines = explode( "\n", $diff );
1593 if (strpos( $diff_lines[0], '---' ) === 0) {
1594 unset($diff_lines[0]);
1596 if (strpos( $diff_lines[1], '+++' ) === 0) {
1597 unset($diff_lines[1]);
1600 $diff = implode( "\n", $diff_lines );
1606 * A wrapper around the PHP function var_export().
1607 * Either print it or add it to the regular output ($wgOut).
1609 * @param $var A PHP variable to dump.
1611 function wfVarDump( $var ) {
1613 $s = str_replace("\n","<br />\n", var_export( $var, true ) . "\n");
1614 if ( headers_sent() ||
!@is_object
( $wgOut ) ) {
1617 $wgOut->addHTML( $s );
1622 * Provide a simple HTTP error.
1624 function wfHttpError( $code, $label, $desc ) {
1627 header( "HTTP/1.0 $code $label" );
1628 header( "Status: $code $label" );
1629 $wgOut->sendCacheControl();
1631 header( 'Content-type: text/html; charset=utf-8' );
1632 print "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">".
1633 "<html><head><title>" .
1634 htmlspecialchars( $label ) .
1635 "</title></head><body><h1>" .
1636 htmlspecialchars( $label ) .
1638 nl2br( htmlspecialchars( $desc ) ) .
1639 "</p></body></html>\n";
1643 * Clear away any user-level output buffers, discarding contents.
1645 * Suitable for 'starting afresh', for instance when streaming
1646 * relatively large amounts of data without buffering, or wanting to
1647 * output image files without ob_gzhandler's compression.
1649 * The optional $resetGzipEncoding parameter controls suppression of
1650 * the Content-Encoding header sent by ob_gzhandler; by default it
1651 * is left. See comments for wfClearOutputBuffers() for why it would
1654 * Note that some PHP configuration options may add output buffer
1655 * layers which cannot be removed; these are left in place.
1657 * @param $resetGzipEncoding Bool
1659 function wfResetOutputBuffers( $resetGzipEncoding=true ) {
1660 if( $resetGzipEncoding ) {
1661 // Suppress Content-Encoding and Content-Length
1662 // headers from 1.10+s wfOutputHandler
1663 global $wgDisableOutputCompression;
1664 $wgDisableOutputCompression = true;
1666 while( $status = ob_get_status() ) {
1667 if( $status['type'] == 0 /* PHP_OUTPUT_HANDLER_INTERNAL */ ) {
1668 // Probably from zlib.output_compression or other
1669 // PHP-internal setting which can't be removed.
1671 // Give up, and hope the result doesn't break
1675 if( !ob_end_clean() ) {
1676 // Could not remove output buffer handler; abort now
1677 // to avoid getting in some kind of infinite loop.
1680 if( $resetGzipEncoding ) {
1681 if( $status['name'] == 'ob_gzhandler' ) {
1682 // Reset the 'Content-Encoding' field set by this handler
1683 // so we can start fresh.
1684 header( 'Content-Encoding:' );
1692 * More legible than passing a 'false' parameter to wfResetOutputBuffers():
1694 * Clear away output buffers, but keep the Content-Encoding header
1695 * produced by ob_gzhandler, if any.
1697 * This should be used for HTTP 304 responses, where you need to
1698 * preserve the Content-Encoding header of the real result, but
1699 * also need to suppress the output of ob_gzhandler to keep to spec
1700 * and avoid breaking Firefox in rare cases where the headers and
1701 * body are broken over two packets.
1703 function wfClearOutputBuffers() {
1704 wfResetOutputBuffers( false );
1708 * Converts an Accept-* header into an array mapping string values to quality
1711 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
1712 # No arg means accept anything (per HTTP spec)
1714 return array( $def => 1.0 );
1719 $parts = explode( ',', $accept );
1721 foreach( $parts as $part ) {
1722 # FIXME: doesn't deal with params like 'text/html; level=1'
1723 @list
( $value, $qpart ) = explode( ';', trim( $part ) );
1725 if( !isset( $qpart ) ) {
1726 $prefs[$value] = 1.0;
1727 } elseif( preg_match( '/q\s*=\s*(\d*\.\d+)/', $qpart, $match ) ) {
1728 $prefs[$value] = floatval($match[1]);
1736 * Checks if a given MIME type matches any of the keys in the given
1737 * array. Basic wildcards are accepted in the array keys.
1739 * Returns the matching MIME type (or wildcard) if a match, otherwise
1742 * @param $type String
1743 * @param $avail Array
1747 function mimeTypeMatch( $type, $avail ) {
1748 if( array_key_exists($type, $avail) ) {
1751 $parts = explode( '/', $type );
1752 if( array_key_exists( $parts[0] . '/*', $avail ) ) {
1753 return $parts[0] . '/*';
1754 } elseif( array_key_exists( '*/*', $avail ) ) {
1763 * Returns the 'best' match between a client's requested internet media types
1764 * and the server's list of available types. Each list should be an associative
1765 * array of type to preference (preference is a float between 0.0 and 1.0).
1766 * Wildcards in the types are acceptable.
1768 * @param $cprefs Array: client's acceptable type list
1769 * @param $sprefs Array: server's offered types
1772 * @todo FIXME: doesn't handle params like 'text/plain; charset=UTF-8'
1773 * XXX: generalize to negotiate other stuff
1775 function wfNegotiateType( $cprefs, $sprefs ) {
1778 foreach( array_keys($sprefs) as $type ) {
1779 $parts = explode( '/', $type );
1780 if( $parts[1] != '*' ) {
1781 $ckey = mimeTypeMatch( $type, $cprefs );
1783 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1788 foreach( array_keys( $cprefs ) as $type ) {
1789 $parts = explode( '/', $type );
1790 if( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
1791 $skey = mimeTypeMatch( $type, $sprefs );
1793 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1801 foreach( array_keys( $combine ) as $type ) {
1802 if( $combine[$type] > $bestq ) {
1804 $bestq = $combine[$type];
1813 * Returns an array where the values in the first array are replaced by the
1814 * values in the second array with the corresponding keys
1818 function wfArrayLookup( $a, $b ) {
1819 return array_flip( array_intersect( array_flip( $a ), array_keys( $b ) ) );
1823 * Convenience function; returns MediaWiki timestamp for the present time.
1826 function wfTimestampNow() {
1828 return wfTimestamp( TS_MW
, time() );
1832 * Reference-counted warning suppression
1834 function wfSuppressWarnings( $end = false ) {
1835 static $suppressCount = 0;
1836 static $originalLevel = false;
1839 if ( $suppressCount ) {
1841 if ( !$suppressCount ) {
1842 error_reporting( $originalLevel );
1846 if ( !$suppressCount ) {
1847 $originalLevel = error_reporting( E_ALL
& ~
( E_WARNING | E_NOTICE
) );
1854 * Restore error level to previous value
1856 function wfRestoreWarnings() {
1857 wfSuppressWarnings( true );
1860 # Autodetect, convert and provide timestamps of various types
1863 * Unix time - the number of seconds since 1970-01-01 00:00:00 UTC
1865 define('TS_UNIX', 0);
1868 * MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
1873 * MySQL DATETIME (YYYY-MM-DD HH:MM:SS)
1878 * RFC 2822 format, for E-mail and HTTP headers
1880 define('TS_RFC2822', 3);
1883 * ISO 8601 format with no timezone: 1986-02-09T20:00:00Z
1885 * This is used by Special:Export
1887 define('TS_ISO_8601', 4);
1890 * An Exif timestamp (YYYY:MM:DD HH:MM:SS)
1892 * @see http://exif.org/Exif2-2.PDF The Exif 2.2 spec, see page 28 for the
1893 * DateTime tag and page 36 for the DateTimeOriginal and
1894 * DateTimeDigitized tags.
1896 define('TS_EXIF', 5);
1899 * Oracle format time.
1901 define('TS_ORACLE', 6);
1904 * Postgres format time.
1906 define('TS_POSTGRES', 7);
1911 define('TS_DB2', 8);
1914 * @param $outputtype Mixed: A timestamp in one of the supported formats, the
1915 * function will autodetect which format is supplied and act
1917 * @param $ts Mixed: the timestamp to convert or 0 for the current timestamp
1918 * @return String: in the format specified in $outputtype
1920 function wfTimestamp( $outputtype = TS_UNIX
, $ts = 0 ) {
1925 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)$/D',$ts,$da)) {
1927 } elseif (preg_match('/^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/D',$ts,$da)) {
1929 } elseif (preg_match('/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/D',$ts,$da)) {
1931 } elseif (preg_match('/^\d{1,13}$/D',$ts)) {
1934 } elseif (preg_match('/^\d{2}-\d{2}-\d{4} \d{2}:\d{2}:\d{2}.\d{6}$/', $ts)) {
1935 # TS_ORACLE // session altered to DD-MM-YYYY HH24:MI:SS.FF6
1936 $uts = strtotime(preg_replace('/(\d\d)\.(\d\d)\.(\d\d)(\.(\d+))?/', "$1:$2:$3",
1937 str_replace("+00:00", "UTC", $ts)));
1938 } elseif (preg_match('/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.*\d*)?Z$/', $ts, $da)) {
1940 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.*\d*[\+\- ](\d\d)$/',$ts,$da)) {
1942 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.*\d* GMT$/',$ts,$da)) {
1945 # Bogus value; fall back to the epoch...
1946 wfDebug("wfTimestamp() fed bogus time value: $outputtype; $ts\n");
1950 if (count( $da ) ) {
1951 // Warning! gmmktime() acts oddly if the month or day is set to 0
1952 // We may want to handle that explicitly at some point
1953 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1954 (int)$da[2],(int)$da[3],(int)$da[1]);
1957 switch($outputtype) {
1961 return gmdate( 'YmdHis', $uts );
1963 return gmdate( 'Y-m-d H:i:s', $uts );
1965 return gmdate( 'Y-m-d\TH:i:s\Z', $uts );
1966 // This shouldn't ever be used, but is included for completeness
1968 return gmdate( 'Y:m:d H:i:s', $uts );
1970 return gmdate( 'D, d M Y H:i:s', $uts ) . ' GMT';
1972 return gmdate( 'd-m-Y H:i:s.000000', $uts);
1973 //return gmdate( 'd-M-y h.i.s A', $uts) . ' +00:00';
1975 return gmdate( 'Y-m-d H:i:s', $uts) . ' GMT';
1977 return gmdate( 'Y-m-d H:i:s', $uts);
1979 throw new MWException( 'wfTimestamp() called with illegal output type.');
1984 * Return a formatted timestamp, or null if input is null.
1985 * For dealing with nullable timestamp columns in the database.
1986 * @param $outputtype Integer
1990 function wfTimestampOrNull( $outputtype = TS_UNIX
, $ts = null ) {
1991 if( is_null( $ts ) ) {
1994 return wfTimestamp( $outputtype, $ts );
1999 * Check if the operating system is Windows
2001 * @return Bool: true if it's Windows, False otherwise.
2003 function wfIsWindows() {
2004 if (substr(php_uname(), 0, 7) == 'Windows') {
2012 * Swap two variables
2014 function swap( &$x, &$y ) {
2020 function wfGetCachedNotice( $name ) {
2021 global $wgOut, $wgRenderHashAppend, $parserMemc;
2022 $fname = 'wfGetCachedNotice';
2023 wfProfileIn( $fname );
2027 if( $name === 'default' ) {
2029 global $wgSiteNotice;
2030 $notice = $wgSiteNotice;
2031 if( empty( $notice ) ) {
2032 wfProfileOut( $fname );
2036 $notice = wfMsgForContentNoTrans( $name );
2037 if( wfEmptyMsg( $name, $notice ) ||
$notice == '-' ) {
2038 wfProfileOut( $fname );
2043 // Use the extra hash appender to let eg SSL variants separately cache.
2044 $key = wfMemcKey( $name . $wgRenderHashAppend );
2045 $cachedNotice = $parserMemc->get( $key );
2046 if( is_array( $cachedNotice ) ) {
2047 if( md5( $notice ) == $cachedNotice['hash'] ) {
2048 $notice = $cachedNotice['html'];
2057 if( is_object( $wgOut ) ) {
2058 $parsed = $wgOut->parse( $notice );
2059 $parserMemc->set( $key, array( 'html' => $parsed, 'hash' => md5( $notice ) ), 600 );
2062 wfDebug( 'wfGetCachedNotice called for ' . $name . ' with no $wgOut available'."\n" );
2067 wfProfileOut( $fname );
2071 function wfGetNamespaceNotice() {
2075 if ( !isset( $wgTitle ) ||
!is_object( $wgTitle ) )
2078 $fname = 'wfGetNamespaceNotice';
2079 wfProfileIn( $fname );
2081 $key = "namespacenotice-" . $wgTitle->getNsText();
2082 $namespaceNotice = wfGetCachedNotice( $key );
2083 if ( $namespaceNotice && substr ( $namespaceNotice , 0 ,7 ) != "<p><" ) {
2084 $namespaceNotice = '<div id="namespacebanner">' . $namespaceNotice . "</div>";
2086 $namespaceNotice = "";
2089 wfProfileOut( $fname );
2090 return $namespaceNotice;
2093 function wfGetSiteNotice() {
2094 global $wgUser, $wgSiteNotice;
2095 $fname = 'wfGetSiteNotice';
2096 wfProfileIn( $fname );
2099 if( wfRunHooks( 'SiteNoticeBefore', array( &$siteNotice ) ) ) {
2100 if( is_object( $wgUser ) && $wgUser->isLoggedIn() ) {
2101 $siteNotice = wfGetCachedNotice( 'sitenotice' );
2103 $anonNotice = wfGetCachedNotice( 'anonnotice' );
2104 if( !$anonNotice ) {
2105 $siteNotice = wfGetCachedNotice( 'sitenotice' );
2107 $siteNotice = $anonNotice;
2110 if( !$siteNotice ) {
2111 $siteNotice = wfGetCachedNotice( 'default' );
2115 wfRunHooks( 'SiteNoticeAfter', array( &$siteNotice ) );
2116 wfProfileOut( $fname );
2121 * BC wrapper for MimeMagic::singleton()
2124 function &wfGetMimeMagic() {
2125 return MimeMagic
::singleton();
2129 * Tries to get the system directory for temporary files. For PHP >= 5.2.1,
2130 * we'll use sys_get_temp_dir(). The TMPDIR, TMP, and TEMP environment
2131 * variables are then checked in sequence, and if none are set /tmp is
2132 * returned as the generic Unix default.
2134 * NOTE: When possible, use the tempfile() function to create temporary
2135 * files to avoid race conditions on file creation, etc.
2139 function wfTempDir() {
2140 if( function_exists( 'sys_get_temp_dir' ) ) {
2141 return sys_get_temp_dir();
2143 foreach( array( 'TMPDIR', 'TMP', 'TEMP' ) as $var ) {
2144 $tmp = getenv( $var );
2145 if( $tmp && file_exists( $tmp ) && is_dir( $tmp ) && is_writable( $tmp ) ) {
2149 # Hope this is Unix of some kind!
2154 * Make directory, and make all parent directories if they don't exist
2156 * @param $dir String: full path to directory to create
2157 * @param $mode Integer: chmod value to use, default is $wgDirectoryMode
2158 * @param $caller String: optional caller param for debugging.
2161 function wfMkdirParents( $dir, $mode = null, $caller = null ) {
2162 global $wgDirectoryMode;
2164 if ( !is_null( $caller ) ) {
2165 wfDebug( "$caller: called wfMkdirParents($dir)" );
2168 if( strval( $dir ) === '' ||
file_exists( $dir ) )
2171 $dir = str_replace( array( '\\', '/' ), DIRECTORY_SEPARATOR
, $dir );
2173 if ( is_null( $mode ) )
2174 $mode = $wgDirectoryMode;
2176 $ok = mkdir( $dir, $mode, true ); // PHP5 <3
2178 // PHP doesn't report the path in its warning message, so add our own to aid in diagnosis.
2179 trigger_error( __FUNCTION__
. ": failed to mkdir \"$dir\" mode $mode", E_USER_WARNING
);
2185 * Increment a statistics counter
2187 function wfIncrStats( $key ) {
2188 global $wgStatsMethod;
2190 if( $wgStatsMethod == 'udp' ) {
2191 global $wgUDPProfilerHost, $wgUDPProfilerPort, $wgDBname;
2194 $socket=socket_create(AF_INET
, SOCK_DGRAM
, SOL_UDP
);
2195 $statline="stats/{$wgDBname} - 1 1 1 1 1 -total\n";
2196 socket_sendto($socket,$statline,strlen($statline),0,$wgUDPProfilerHost,$wgUDPProfilerPort);
2198 $statline="stats/{$wgDBname} - 1 1 1 1 1 {$key}\n";
2199 @socket_sendto
($socket,$statline,strlen($statline),0,$wgUDPProfilerHost,$wgUDPProfilerPort);
2200 } elseif( $wgStatsMethod == 'cache' ) {
2202 $key = wfMemcKey( 'stats', $key );
2203 if ( is_null( $wgMemc->incr( $key ) ) ) {
2204 $wgMemc->add( $key, 1 );
2212 * @param $nr Mixed: the number to format
2213 * @param $acc Integer: the number of digits after the decimal point, default 2
2214 * @param $round Boolean: whether or not to round the value, default true
2217 function wfPercent( $nr, $acc = 2, $round = true ) {
2218 $ret = sprintf( "%.${acc}f", $nr );
2219 return $round ?
round( $ret, $acc ) . '%' : "$ret%";
2223 * Encrypt a username/password.
2225 * @param $userid Integer: ID of the user
2226 * @param $password String: password of the user
2227 * @return String: hashed password
2228 * @deprecated Use User::crypt() or User::oldCrypt() instead
2230 function wfEncryptPassword( $userid, $password ) {
2231 wfDeprecated(__FUNCTION__
);
2232 # Just wrap around User::oldCrypt()
2233 return User
::oldCrypt($password, $userid);
2237 * Appends to second array if $value differs from that in $default
2239 function wfAppendToArrayIfNotDefault( $key, $value, $default, &$changed ) {
2240 if ( is_null( $changed ) ) {
2241 throw new MWException('GlobalFunctions::wfAppendToArrayIfNotDefault got null');
2243 if ( $default[$key] !== $value ) {
2244 $changed[$key] = $value;
2249 * Since wfMsg() and co suck, they don't return false if the message key they
2250 * looked up didn't exist but a XHTML string, this function checks for the
2251 * nonexistance of messages by looking at wfMsg() output
2253 * @param $msg String: the message key looked up
2254 * @param $wfMsgOut String: the output of wfMsg*()
2257 function wfEmptyMsg( $msg, $wfMsgOut ) {
2258 return $wfMsgOut === htmlspecialchars( "<$msg>" );
2262 * Find out whether or not a mixed variable exists in a string
2264 * @param $needle String
2265 * @param $str String
2268 function in_string( $needle, $str ) {
2269 return strpos( $str, $needle ) !== false;
2272 function wfSpecialList( $page, $details ) {
2274 $details = $details ?
' ' . $wgContLang->getDirMark() . "($details)" : "";
2275 return $page . $details;
2279 * Returns a regular expression of url protocols
2283 function wfUrlProtocols() {
2284 global $wgUrlProtocols;
2286 static $retval = null;
2287 if ( !is_null( $retval ) )
2290 // Support old-style $wgUrlProtocols strings, for backwards compatibility
2291 // with LocalSettings files from 1.5
2292 if ( is_array( $wgUrlProtocols ) ) {
2293 $protocols = array();
2294 foreach ($wgUrlProtocols as $protocol)
2295 $protocols[] = preg_quote( $protocol, '/' );
2297 $retval = implode( '|', $protocols );
2299 $retval = $wgUrlProtocols;
2305 * Safety wrapper around ini_get() for boolean settings.
2306 * The values returned from ini_get() are pre-normalized for settings
2307 * set via php.ini or php_flag/php_admin_flag... but *not*
2308 * for those set via php_value/php_admin_value.
2310 * It's fairly common for people to use php_value instead of php_flag,
2311 * which can leave you with an 'off' setting giving a false positive
2312 * for code that just takes the ini_get() return value as a boolean.
2314 * To make things extra interesting, setting via php_value accepts
2315 * "true" and "yes" as true, but php.ini and php_flag consider them false. :)
2316 * Unrecognized values go false... again opposite PHP's own coercion
2317 * from string to bool.
2319 * Luckily, 'properly' set settings will always come back as '0' or '1',
2320 * so we only have to worry about them and the 'improper' settings.
2322 * I frickin' hate PHP... :P
2324 * @param $setting String
2327 function wfIniGetBool( $setting ) {
2328 $val = ini_get( $setting );
2329 // 'on' and 'true' can't have whitespace around them, but '1' can.
2330 return strtolower( $val ) == 'on'
2331 ||
strtolower( $val ) == 'true'
2332 ||
strtolower( $val ) == 'yes'
2333 ||
preg_match( "/^\s*[+-]?0*[1-9]/", $val ); // approx C atoi() function
2337 * Execute a shell command, with time and memory limits mirrored from the PHP
2338 * configuration if supported.
2339 * @param $cmd Command line, properly escaped for shell.
2340 * @param &$retval optional, will receive the program's exit code.
2341 * (non-zero is usually failure)
2342 * @return collected stdout as a string (trailing newlines stripped)
2344 function wfShellExec( $cmd, &$retval=null ) {
2345 global $IP, $wgMaxShellMemory, $wgMaxShellFileSize, $wgMaxShellTime;
2348 if ( is_null( $disabled ) ) {
2350 if( wfIniGetBool( 'safe_mode' ) ) {
2351 wfDebug( "wfShellExec can't run in safe_mode, PHP's exec functions are too broken.\n" );
2354 $functions = explode( ',', ini_get( 'disable_functions' ) );
2355 $functions = array_map( 'trim', $functions );
2356 $functions = array_map( 'strtolower', $functions );
2357 if ( in_array( 'passthru', $functions ) ) {
2358 wfDebug( "passthru is in disabled_functions\n" );
2364 return "Unable to run external programs in safe mode.";
2367 wfInitShellLocale();
2369 if ( php_uname( 's' ) == 'Linux' ) {
2370 $time = intval( $wgMaxShellTime );
2371 $mem = intval( $wgMaxShellMemory );
2372 $filesize = intval( $wgMaxShellFileSize );
2374 if ( $time > 0 && $mem > 0 ) {
2375 $script = "$IP/bin/ulimit4.sh";
2376 if ( is_executable( $script ) ) {
2377 $cmd = escapeshellarg( $script ) . " $time $mem $filesize " . escapeshellarg( $cmd );
2380 } elseif ( php_uname( 's' ) == 'Windows NT' &&
2381 version_compare( PHP_VERSION
, '5.3.0', '<' ) )
2383 # This is a hack to work around PHP's flawed invocation of cmd.exe
2384 # http://news.php.net/php.internals/21796
2385 # Which is fixed in 5.3.0 :)
2386 $cmd = '"' . $cmd . '"';
2388 wfDebug( "wfShellExec: $cmd\n" );
2390 $retval = 1; // error by default?
2392 passthru( $cmd, $retval );
2393 $output = ob_get_contents();
2396 if ( $retval == 127 ) {
2397 wfDebugLog( 'exec', "Possibly missing executable file: $cmd\n" );
2403 * Workaround for http://bugs.php.net/bug.php?id=45132
2404 * escapeshellarg() destroys non-ASCII characters if LANG is not a UTF-8 locale
2406 function wfInitShellLocale() {
2407 static $done = false;
2408 if ( $done ) return;
2410 global $wgShellLocale;
2411 if ( !wfIniGetBool( 'safe_mode' ) ) {
2412 putenv( "LC_CTYPE=$wgShellLocale" );
2413 setlocale( LC_CTYPE
, $wgShellLocale );
2418 * This function works like "use VERSION" in Perl, the program will die with a
2419 * backtrace if the current version of PHP is less than the version provided
2421 * This is useful for extensions which due to their nature are not kept in sync
2422 * with releases, and might depend on other versions of PHP than the main code
2424 * Note: PHP might die due to parsing errors in some cases before it ever
2425 * manages to call this function, such is life
2427 * @see perldoc -f use
2429 * @param $req_ver Mixed: the version to check, can be a string, an integer, or
2432 function wfUsePHP( $req_ver ) {
2433 $php_ver = PHP_VERSION
;
2435 if ( version_compare( $php_ver, (string)$req_ver, '<' ) )
2436 throw new MWException( "PHP $req_ver required--this is only $php_ver" );
2440 * This function works like "use VERSION" in Perl except it checks the version
2441 * of MediaWiki, the program will die with a backtrace if the current version
2442 * of MediaWiki is less than the version provided.
2444 * This is useful for extensions which due to their nature are not kept in sync
2447 * @see perldoc -f use
2449 * @param $req_ver Mixed: the version to check, can be a string, an integer, or
2452 function wfUseMW( $req_ver ) {
2455 if ( version_compare( $wgVersion, (string)$req_ver, '<' ) )
2456 throw new MWException( "MediaWiki $req_ver required--this is only $wgVersion" );
2460 * @deprecated use StringUtils::escapeRegexReplacement
2462 function wfRegexReplacement( $string ) {
2463 return StringUtils
::escapeRegexReplacement( $string );
2467 * Return the final portion of a pathname.
2468 * Reimplemented because PHP5's basename() is buggy with multibyte text.
2469 * http://bugs.php.net/bug.php?id=33898
2471 * PHP's basename() only considers '\' a pathchar on Windows and Netware.
2472 * We'll consider it so always, as we don't want \s in our Unix paths either.
2474 * @param $path String
2475 * @param $suffix String: to remove if present
2478 function wfBaseName( $path, $suffix='' ) {
2479 $encSuffix = ($suffix == '')
2481 : ( '(?:' . preg_quote( $suffix, '#' ) . ')?' );
2483 if( preg_match( "#([^/\\\\]*?){$encSuffix}[/\\\\]*$#", $path, $matches ) ) {
2491 * Generate a relative path name to the given file.
2492 * May explode on non-matching case-insensitive paths,
2493 * funky symlinks, etc.
2495 * @param $path String: absolute destination path including target filename
2496 * @param $from String: Absolute source path, directory only
2499 function wfRelativePath( $path, $from ) {
2500 // Normalize mixed input on Windows...
2501 $path = str_replace( '/', DIRECTORY_SEPARATOR
, $path );
2502 $from = str_replace( '/', DIRECTORY_SEPARATOR
, $from );
2504 // Trim trailing slashes -- fix for drive root
2505 $path = rtrim( $path, DIRECTORY_SEPARATOR
);
2506 $from = rtrim( $from, DIRECTORY_SEPARATOR
);
2508 $pieces = explode( DIRECTORY_SEPARATOR
, dirname( $path ) );
2509 $against = explode( DIRECTORY_SEPARATOR
, $from );
2511 if( $pieces[0] !== $against[0] ) {
2512 // Non-matching Windows drive letters?
2513 // Return a full path.
2517 // Trim off common prefix
2518 while( count( $pieces ) && count( $against )
2519 && $pieces[0] == $against[0] ) {
2520 array_shift( $pieces );
2521 array_shift( $against );
2524 // relative dots to bump us to the parent
2525 while( count( $against ) ) {
2526 array_unshift( $pieces, '..' );
2527 array_shift( $against );
2530 array_push( $pieces, wfBaseName( $path ) );
2532 return implode( DIRECTORY_SEPARATOR
, $pieces );
2536 * Backwards array plus for people who haven't bothered to read the PHP manual
2537 * XXX: will not darn your socks for you.
2539 * @param $array1 Array
2540 * @param [$array2, [...]] Arrays
2543 function wfArrayMerge( $array1/* ... */ ) {
2544 $args = func_get_args();
2545 $args = array_reverse( $args, true );
2547 foreach ( $args as $arg ) {
2554 * Merge arrays in the style of getUserPermissionsErrors, with duplicate removal
2556 * wfMergeErrorArrays(
2557 * array( array( 'x' ) ),
2558 * array( array( 'x', '2' ) ),
2559 * array( array( 'x' ) ),
2560 * array( array( 'y') )
2564 * array( 'x', '2' ),
2569 function wfMergeErrorArrays(/*...*/) {
2570 $args = func_get_args();
2572 foreach ( $args as $errors ) {
2573 foreach ( $errors as $params ) {
2574 $spec = implode( "\t", $params );
2575 $out[$spec] = $params;
2578 return array_values( $out );
2582 * parse_url() work-alike, but non-broken. Differences:
2584 * 1) Does not raise warnings on bad URLs (just returns false)
2585 * 2) Handles protocols that don't use :// (e.g., mailto: and news:) correctly
2586 * 3) Adds a "delimiter" element to the array, either '://' or ':' (see (2))
2588 * @param $url String: a URL to parse
2589 * @return Array: bits of the URL in an associative array, per PHP docs
2591 function wfParseUrl( $url ) {
2592 global $wgUrlProtocols; // Allow all protocols defined in DefaultSettings/LocalSettings.php
2593 wfSuppressWarnings();
2594 $bits = parse_url( $url );
2595 wfRestoreWarnings();
2600 // most of the protocols are followed by ://, but mailto: and sometimes news: not, check for it
2601 if ( in_array( $bits['scheme'] . '://', $wgUrlProtocols ) ) {
2602 $bits['delimiter'] = '://';
2603 } elseif ( in_array( $bits['scheme'] . ':', $wgUrlProtocols ) ) {
2604 $bits['delimiter'] = ':';
2605 // parse_url detects for news: and mailto: the host part of an url as path
2606 // We have to correct this wrong detection
2607 if ( isset ( $bits['path'] ) ) {
2608 $bits['host'] = $bits['path'];
2619 * Make a URL index, appropriate for the el_index field of externallinks.
2621 function wfMakeUrlIndex( $url ) {
2622 $bits = wfParseUrl( $url );
2624 // Reverse the labels in the hostname, convert to lower case
2625 // For emails reverse domainpart only
2626 if ( $bits['scheme'] == 'mailto' ) {
2627 $mailparts = explode( '@', $bits['host'], 2 );
2628 if ( count($mailparts) === 2 ) {
2629 $domainpart = strtolower( implode( '.', array_reverse( explode( '.', $mailparts[1] ) ) ) );
2631 // No domain specified, don't mangle it
2634 $reversedHost = $domainpart . '@' . $mailparts[0];
2636 $reversedHost = strtolower( implode( '.', array_reverse( explode( '.', $bits['host'] ) ) ) );
2638 // Add an extra dot to the end
2639 // Why? Is it in wrong place in mailto links?
2640 if ( substr( $reversedHost, -1, 1 ) !== '.' ) {
2641 $reversedHost .= '.';
2643 // Reconstruct the pseudo-URL
2644 $prot = $bits['scheme'];
2645 $index = $prot . $bits['delimiter'] . $reversedHost;
2646 // Leave out user and password. Add the port, path, query and fragment
2647 if ( isset( $bits['port'] ) ) $index .= ':' . $bits['port'];
2648 if ( isset( $bits['path'] ) ) {
2649 $index .= $bits['path'];
2653 if ( isset( $bits['query'] ) ) $index .= '?' . $bits['query'];
2654 if ( isset( $bits['fragment'] ) ) $index .= '#' . $bits['fragment'];
2659 * Do any deferred updates and clear the list
2660 * TODO: This could be in Wiki.php if that class made any sense at all
2662 function wfDoUpdates()
2664 global $wgPostCommitUpdateList, $wgDeferredUpdateList;
2665 foreach ( $wgDeferredUpdateList as $update ) {
2666 $update->doUpdate();
2668 foreach ( $wgPostCommitUpdateList as $update ) {
2669 $update->doUpdate();
2671 $wgDeferredUpdateList = array();
2672 $wgPostCommitUpdateList = array();
2676 * @deprecated use StringUtils::explodeMarkup
2678 function wfExplodeMarkup( $separator, $text ) {
2679 return StringUtils
::explodeMarkup( $separator, $text );
2683 * Convert an arbitrarily-long digit string from one numeric base
2684 * to another, optionally zero-padding to a minimum column width.
2686 * Supports base 2 through 36; digit values 10-36 are represented
2687 * as lowercase letters a-z. Input is case-insensitive.
2689 * @param $input String: of digits
2690 * @param $sourceBase Integer: 2-36
2691 * @param $destBase Integer: 2-36
2692 * @param $pad Integer: 1 or greater
2693 * @param $lowercase Boolean
2694 * @return String or false on invalid input
2696 function wfBaseConvert( $input, $sourceBase, $destBase, $pad=1, $lowercase=true ) {
2697 $input = strval( $input );
2698 if( $sourceBase < 2 ||
2703 $sourceBase != intval( $sourceBase ) ||
2704 $destBase != intval( $destBase ) ||
2705 $pad != intval( $pad ) ||
2706 !is_string( $input ) ||
2710 $digitChars = ( $lowercase ) ?
'0123456789abcdefghijklmnopqrstuvwxyz' : '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
2711 $inDigits = array();
2714 // Decode and validate input string
2715 $input = strtolower( $input );
2716 for( $i = 0; $i < strlen( $input ); $i++
) {
2717 $n = strpos( $digitChars, $input{$i} );
2718 if( $n === false ||
$n > $sourceBase ) {
2724 // Iterate over the input, modulo-ing out an output digit
2725 // at a time until input is gone.
2726 while( count( $inDigits ) ) {
2728 $workDigits = array();
2731 foreach( $inDigits as $digit ) {
2732 $work *= $sourceBase;
2735 if( $work < $destBase ) {
2736 // Gonna need to pull another digit.
2737 if( count( $workDigits ) ) {
2738 // Avoid zero-padding; this lets us find
2739 // the end of the input very easily when
2740 // length drops to zero.
2744 // Finally! Actual division!
2745 $workDigits[] = intval( $work / $destBase );
2747 // Isn't it annoying that most programming languages
2748 // don't have a single divide-and-remainder operator,
2749 // even though the CPU implements it that way?
2750 $work = $work %
$destBase;
2754 // All that division leaves us with a remainder,
2755 // which is conveniently our next output digit.
2756 $outChars .= $digitChars[$work];
2759 $inDigits = $workDigits;
2762 while( strlen( $outChars ) < $pad ) {
2766 return strrev( $outChars );
2770 * Create an object with a given name and an array of construct parameters
2771 * @param $name String
2772 * @param $p Array: parameters
2774 function wfCreateObject( $name, $p ){
2775 $p = array_values( $p );
2776 switch ( count( $p ) ) {
2780 return new $name( $p[0] );
2782 return new $name( $p[0], $p[1] );
2784 return new $name( $p[0], $p[1], $p[2] );
2786 return new $name( $p[0], $p[1], $p[2], $p[3] );
2788 return new $name( $p[0], $p[1], $p[2], $p[3], $p[4] );
2790 return new $name( $p[0], $p[1], $p[2], $p[3], $p[4], $p[5] );
2792 throw new MWException( "Too many arguments to construtor in wfCreateObject" );
2797 * Alias for modularized function
2798 * @deprecated Use Http::get() instead
2800 function wfGetHTTP( $url ) {
2801 wfDeprecated(__FUNCTION__
);
2802 return Http
::get( $url );
2806 * Alias for modularized function
2807 * @deprecated Use Http::isLocalURL() instead
2809 function wfIsLocalURL( $url ) {
2810 wfDeprecated(__FUNCTION__
);
2811 return Http
::isLocalURL( $url );
2814 function wfHttpOnlySafe() {
2815 global $wgHttpOnlyBlacklist;
2816 if( !version_compare("5.2", PHP_VERSION
, "<") )
2819 if( isset( $_SERVER['HTTP_USER_AGENT'] ) ) {
2820 foreach( $wgHttpOnlyBlacklist as $regex ) {
2821 if( preg_match( $regex, $_SERVER['HTTP_USER_AGENT'] ) ) {
2831 * Initialise php session
2833 function wfSetupSession() {
2834 global $wgSessionsInMemcached, $wgCookiePath, $wgCookieDomain,
2835 $wgCookieSecure, $wgCookieHttpOnly, $wgSessionHandler;
2836 if( $wgSessionsInMemcached ) {
2837 require_once( 'MemcachedSessions.php' );
2838 } elseif( $wgSessionHandler && $wgSessionHandler != ini_get( 'session.save_handler' ) ) {
2839 # Only set this if $wgSessionHandler isn't null and session.save_handler
2840 # hasn't already been set to the desired value (that causes errors)
2841 ini_set ( 'session.save_handler', $wgSessionHandler );
2843 $httpOnlySafe = wfHttpOnlySafe();
2844 wfDebugLog( 'cookie',
2845 'session_set_cookie_params: "' . implode( '", "',
2851 $httpOnlySafe && $wgCookieHttpOnly ) ) . '"' );
2852 if( $httpOnlySafe && $wgCookieHttpOnly ) {
2853 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookieHttpOnly );
2855 // PHP 5.1 throws warnings if you pass the HttpOnly parameter for 5.2.
2856 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
2858 session_cache_limiter( 'private, must-revalidate' );
2859 wfSuppressWarnings();
2861 wfRestoreWarnings();
2865 * Get an object from the precompiled serialized directory
2867 * @return Mixed: the variable on success, false on failure
2869 function wfGetPrecompiledData( $name ) {
2872 $file = "$IP/serialized/$name";
2873 if ( file_exists( $file ) ) {
2874 $blob = file_get_contents( $file );
2876 return unserialize( $blob );
2882 function wfGetCaller( $level = 2 ) {
2883 $backtrace = wfDebugBacktrace();
2884 if ( isset( $backtrace[$level] ) ) {
2885 return wfFormatStackFrame($backtrace[$level]);
2887 $caller = 'unknown';
2893 * Return a string consisting all callers in stack, somewhat useful sometimes
2894 * for profiling specific points
2896 function wfGetAllCallers() {
2897 return implode('/', array_map('wfFormatStackFrame',array_reverse(wfDebugBacktrace())));
2901 * Return a string representation of frame
2903 function wfFormatStackFrame($frame) {
2904 return isset( $frame["class"] )?
2905 $frame["class"]."::".$frame["function"]:
2912 function wfMemcKey( /*... */ ) {
2913 $args = func_get_args();
2914 $key = wfWikiID() . ':' . implode( ':', $args );
2915 $key = str_replace( ' ', '_', $key );
2920 * Get a cache key for a foreign DB
2922 function wfForeignMemcKey( $db, $prefix /*, ... */ ) {
2923 $args = array_slice( func_get_args(), 2 );
2925 $key = "$db-$prefix:" . implode( ':', $args );
2927 $key = $db . ':' . implode( ':', $args );
2933 * Get an ASCII string identifying this wiki
2934 * This is used as a prefix in memcached keys
2936 function wfWikiID() {
2937 global $wgDBprefix, $wgDBname;
2938 if ( $wgDBprefix ) {
2939 return "$wgDBname-$wgDBprefix";
2946 * Split a wiki ID into DB name and table prefix
2948 function wfSplitWikiID( $wiki ) {
2949 $bits = explode( '-', $wiki, 2 );
2950 if ( count( $bits ) < 2 ) {
2957 * Get a Database object.
2958 * @param $db Integer: index of the connection to get. May be DB_MASTER for the
2959 * master (for write queries), DB_SLAVE for potentially lagged read
2960 * queries, or an integer >= 0 for a particular server.
2962 * @param $groups Mixed: query groups. An array of group names that this query
2963 * belongs to. May contain a single string if the query is only
2966 * @param $wiki String: the wiki ID, or false for the current wiki
2968 * Note: multiple calls to wfGetDB(DB_SLAVE) during the course of one request
2969 * will always return the same object, unless the underlying connection or load
2970 * balancer is manually destroyed.
2972 function &wfGetDB( $db, $groups = array(), $wiki = false ) {
2973 return wfGetLB( $wiki )->getConnection( $db, $groups, $wiki );
2977 * Get a load balancer object.
2979 * @param $wiki String: wiki ID, or false for the current wiki
2980 * @return LoadBalancer
2982 function wfGetLB( $wiki = false ) {
2983 return wfGetLBFactory()->getMainLB( $wiki );
2987 * Get the load balancer factory object
2989 function &wfGetLBFactory() {
2990 return LBFactory
::singleton();
2995 * Shortcut for RepoGroup::singleton()->findFile()
2996 * @param $title Either a string or Title object
2997 * @param $options Associative array of options:
2998 * time: requested time for an archived image, or false for the
2999 * current version. An image object will be returned which was
3000 * created at the specified time.
3002 * ignoreRedirect: If true, do not follow file redirects
3004 * private: If true, return restricted (deleted) files if the current
3005 * user is allowed to view them. Otherwise, such files will not
3008 * bypassCache: If true, do not use the process-local cache of File objects
3010 * @return File, or false if the file does not exist
3012 function wfFindFile( $title, $options = array() ) {
3013 return RepoGroup
::singleton()->findFile( $title, $options );
3017 * Get an object referring to a locally registered file.
3018 * Returns a valid placeholder object if the file does not exist.
3019 * @param $title Either a string or Title object
3020 * @return File, or null if passed an invalid Title
3022 function wfLocalFile( $title ) {
3023 return RepoGroup
::singleton()->getLocalRepo()->newFile( $title );
3027 * Should low-performance queries be disabled?
3031 function wfQueriesMustScale() {
3032 global $wgMiserMode;
3034 ||
( SiteStats
::pages() > 100000
3035 && SiteStats
::edits() > 1000000
3036 && SiteStats
::users() > 10000 );
3040 * Get the path to a specified script file, respecting file
3041 * extensions; this is a wrapper around $wgScriptExtension etc.
3043 * @param $script String: script filename, sans extension
3046 function wfScript( $script = 'index' ) {
3047 global $wgScriptPath, $wgScriptExtension;
3048 return "{$wgScriptPath}/{$script}{$wgScriptExtension}";
3051 * Get the script url.
3053 * @return script url
3055 function wfGetScriptUrl(){
3056 if( isset( $_SERVER['SCRIPT_NAME'] ) ) {
3058 # as it was called, minus the query string.
3060 # Some sites use Apache rewrite rules to handle subdomains,
3061 # and have PHP set up in a weird way that causes PHP_SELF
3062 # to contain the rewritten URL instead of the one that the
3063 # outside world sees.
3065 # If in this mode, use SCRIPT_URL instead, which mod_rewrite
3066 # provides containing the "before" URL.
3067 return $_SERVER['SCRIPT_NAME'];
3069 return $_SERVER['URL'];
3074 * Convenience function converts boolean values into "true"
3075 * or "false" (string) values
3077 * @param $value Boolean
3080 function wfBoolToStr( $value ) {
3081 return $value ?
'true' : 'false';
3085 * Load an extension messages file
3086 * @deprecated in 1.16 (warnings in 1.18, removed in ?)
3088 function wfLoadExtensionMessages( $extensionName, $langcode = false ) {
3092 * Get a platform-independent path to the null file, e.g.
3097 function wfGetNull() {
3098 return wfIsWindows()
3104 * Displays a maxlag error
3106 * @param $host String: server that lags the most
3107 * @param $lag Integer: maxlag (actual)
3108 * @param $maxLag Integer: maxlag (requested)
3110 function wfMaxlagError( $host, $lag, $maxLag ) {
3111 global $wgShowHostnames;
3112 header( 'HTTP/1.1 503 Service Unavailable' );
3113 header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
3114 header( 'X-Database-Lag: ' . intval( $lag ) );
3115 header( 'Content-Type: text/plain' );
3116 if( $wgShowHostnames ) {
3117 echo "Waiting for $host: $lag seconds lagged\n";
3119 echo "Waiting for a database server: $lag seconds lagged\n";
3124 * Throws a warning that $function is deprecated
3125 * @param $function String
3128 function wfDeprecated( $function ) {
3129 static $functionsWarned = array();
3130 if ( !isset( $functionsWarned[$function] ) ) {
3131 $functionsWarned[$function] = true;
3132 wfWarn( "Use of $function is deprecated.", 2 );
3137 * Send a warning either to the debug log or in a PHP error depending on
3138 * $wgDevelopmentWarnings
3140 * @param $msg String: message to send
3141 * @param $callerOffset Integer: number of itmes to go back in the backtrace to
3142 * find the correct caller (1 = function calling wfWarn, ...)
3143 * @param $level Integer: PHP error level; only used when $wgDevelopmentWarnings
3146 function wfWarn( $msg, $callerOffset = 1, $level = E_USER_NOTICE
) {
3147 $callers = wfDebugBacktrace();
3148 if( isset( $callers[$callerOffset+
1] ) ){
3149 $callerfunc = $callers[$callerOffset+
1];
3150 $callerfile = $callers[$callerOffset];
3151 if( isset( $callerfile['file'] ) && isset( $callerfile['line'] ) ){
3152 $file = $callerfile['file'] . ' at line ' . $callerfile['line'];
3154 $file = '(internal function)';
3157 if( isset( $callerfunc['class'] ) )
3158 $func .= $callerfunc['class'] . '::';
3159 $func .= @$callerfunc['function'];
3160 $msg .= " [Called from $func in $file]";
3163 global $wgDevelopmentWarnings;
3164 if ( $wgDevelopmentWarnings ) {
3165 trigger_error( $msg, $level );
3167 wfDebug( "$msg\n" );
3172 * Sleep until the worst slave's replication lag is less than or equal to
3173 * $maxLag, in seconds. Use this when updating very large numbers of rows, as
3174 * in maintenance scripts, to avoid causing too much lag. Of course, this is
3175 * a no-op if there are no slaves.
3177 * Every time the function has to wait for a slave, it will print a message to
3178 * that effect (and then sleep for a little while), so it's probably not best
3179 * to use this outside maintenance scripts in its present form.
3181 * @param $maxLag Integer
3182 * @param $wiki mixed Wiki identifier accepted by wfGetLB
3185 function wfWaitForSlaves( $maxLag, $wiki = false ) {
3187 $lb = wfGetLB( $wiki );
3188 list( $host, $lag ) = $lb->getMaxLag( $wiki );
3189 while( $lag > $maxLag ) {
3190 $name = @gethostbyaddr
( $host );
3191 if( $name !== false ) {
3194 print "Waiting for $host (lagged $lag seconds)...\n";
3196 list( $host, $lag ) = $lb->getMaxLag();
3202 * Output some plain text in command-line mode or in the installer (updaters.inc).
3203 * Do not use it in any other context, its behaviour is subject to change.
3205 function wfOut( $s ) {
3206 static $lineStarted = false;
3207 global $wgCommandLineMode;
3208 if ( $wgCommandLineMode && !defined( 'MEDIAWIKI_INSTALL' ) ) {
3211 echo htmlspecialchars( $s );
3217 * Count down from $n to zero on the terminal, with a one-second pause
3218 * between showing each number. For use in command-line scripts.
3220 function wfCountDown( $n ) {
3221 for ( $i = $n; $i >= 0; $i-- ) {
3223 echo str_repeat( "\x08", strlen( $i +
1 ) );
3234 /** Generate a random 32-character hexadecimal token.
3235 * @param $salt Mixed: some sort of salt, if necessary, to add to random
3236 * characters before hashing.
3238 function wfGenerateToken( $salt = '' ) {
3239 $salt = serialize($salt);
3241 return md5( mt_rand( 0, 0x7fffffff ) . $salt );
3245 * Replace all invalid characters with -
3246 * @param $name Mixed: filename to process
3248 function wfStripIllegalFilenameChars( $name ) {
3249 global $wgIllegalFileChars;
3250 $name = wfBaseName( $name );
3251 $name = preg_replace("/[^".Title
::legalChars()."]".($wgIllegalFileChars ?
"|[".$wgIllegalFileChars."]":"")."/",'-',$name);
3256 * Insert array into another array after the specified *KEY*
3257 * @param $array Array: The array.
3258 * @param $insert Array: The array to insert.
3259 * @param $after Mixed: The key to insert after
3261 function wfArrayInsertAfter( $array, $insert, $after ) {
3262 // Find the offset of the element to insert after.
3263 $keys = array_keys($array);
3264 $offsetByKey = array_flip( $keys );
3266 $offset = $offsetByKey[$after];
3268 // Insert at the specified offset
3269 $before = array_slice( $array, 0, $offset +
1, true );
3270 $after = array_slice( $array, $offset +
1, count($array)-$offset, true );
3272 $output = $before +
$insert +
$after;
3277 /* Recursively converts the parameter (an object) to an array with the same data */
3278 function wfObjectToArray( $object, $recursive = true ) {
3280 foreach ( get_object_vars($object) as $key => $value ) {
3281 if ( is_object($value) && $recursive ) {
3282 $value = wfObjectToArray( $value );
3285 $array[$key] = $value;
3292 * Set PHP's memory limit to the larger of php.ini or $wgMemoryLimit;
3293 * @return Integer value memory was set to.
3296 function wfMemoryLimit () {
3297 global $wgMemoryLimit;
3298 $memlimit = wfShorthandToInteger( ini_get( "memory_limit" ) );
3299 $conflimit = wfShorthandToInteger( $wgMemoryLimit );
3300 if( $memlimit != -1 ) {
3301 if( $conflimit == -1 ) {
3302 wfDebug( "Removing PHP's memory limit\n" );
3303 wfSuppressWarnings();
3304 ini_set( "memory_limit", $conflimit );
3305 wfRestoreWarnings();
3307 } elseif ( $conflimit > $memlimit ) {
3308 wfDebug( "Raising PHP's memory limit to $conflimit bytes\n" );
3309 wfSuppressWarnings();
3310 ini_set( "memory_limit", $conflimit );
3311 wfRestoreWarnings();
3319 * Converts shorthand byte notation to integer form
3320 * @param $string String
3323 function wfShorthandToInteger ( $string = '' ) {
3324 $string = trim($string);
3325 if( empty($string) ) { return -1; }
3326 $last = strtolower($string[strlen($string)-1]);
3327 $val = intval($string);
3340 /* Get the normalised IETF language tag
3341 * @param $code String: The language code.
3342 * @return $langCode String: The language code which complying with BCP 47 standards.
3344 function wfBCP47( $code ) {
3345 $codeSegment = explode( '-', $code );
3346 foreach ( $codeSegment as $segNo => $seg ) {
3347 if ( count( $codeSegment ) > 0 ) {
3348 // ISO 3166 country code
3349 if ( ( strlen( $seg ) == 2 ) && ( $segNo > 0 ) )
3350 $codeBCP[$segNo] = strtoupper( $seg );
3351 // ISO 15924 script code
3352 else if ( ( strlen( $seg ) == 4 ) && ( $segNo > 0 ) )
3353 $codeBCP[$segNo] = ucfirst( $seg );
3354 // Use lowercase for other cases
3356 $codeBCP[$segNo] = strtolower( $seg );
3358 // Use lowercase for single segment
3359 $codeBCP[$segNo] = strtolower( $seg );
3362 $langCode = implode ( '-' , $codeBCP );