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';
13 // Hide compatibility functions from Doxygen
17 * Compatibility functions
19 * We more or less support PHP 5.0.x and up.
20 * Re-implementations of newer functions or functions in non-standard
21 * PHP extensions may be included here.
23 if( !function_exists('iconv') ) {
24 # iconv support is not in the default configuration and so may not be present.
25 # Assume will only ever use utf-8 and iso-8859-1.
26 # This will *not* work in all circumstances.
27 function iconv( $from, $to, $string ) {
28 if(strcasecmp( $from, $to ) == 0) return $string;
29 if(strcasecmp( $from, 'utf-8' ) == 0) return utf8_decode( $string );
30 if(strcasecmp( $to, 'utf-8' ) == 0) return utf8_encode( $string );
35 if ( !function_exists( 'mb_substr' ) ) {
37 * Fallback implementation for mb_substr, hardcoded to UTF-8.
38 * Attempts to be at least _moderately_ efficient; best optimized
39 * for relatively small offset and count values -- about 5x slower
40 * than native mb_string in my testing.
42 * Larger offsets are still fairly efficient for Latin text, but
43 * can be up to 100x slower than native if the text is heavily
44 * multibyte and we have to slog through a few hundred kb.
46 function mb_substr( $str, $start, $count='end' ) {
48 $split = mb_substr_split_unicode( $str, intval( $start ) );
49 $str = substr( $str, $split );
52 if( $count !== 'end' ) {
53 $split = mb_substr_split_unicode( $str, intval( $count ) );
54 $str = substr( $str, 0, $split );
60 function mb_substr_split_unicode( $str, $splitPos ) {
61 if( $splitPos == 0 ) {
65 $byteLen = strlen( $str );
68 if( $splitPos > 256 ) {
69 // Optimize large string offsets by skipping ahead N bytes.
70 // This will cut out most of our slow time on Latin-based text,
71 // and 1/2 to 1/3 on East European and Asian scripts.
73 while ($bytePos < $byteLen && $str{$bytePos} >= "\x80" && $str{$bytePos} < "\xc0")
75 $charPos = mb_strlen( substr( $str, 0, $bytePos ) );
81 while( $charPos++
< $splitPos ) {
83 // Move past any tail bytes
84 while ($bytePos < $byteLen && $str{$bytePos} >= "\x80" && $str{$bytePos} < "\xc0")
88 $splitPosX = $splitPos +
1;
89 $charPos = 0; // relative to end of string; we don't care about the actual char position here
91 while( $bytePos > 0 && $charPos-- >= $splitPosX ) {
93 // Move past any tail bytes
94 while ($bytePos > 0 && $str{$bytePos} >= "\x80" && $str{$bytePos} < "\xc0")
103 if ( !function_exists( 'mb_strlen' ) ) {
105 * Fallback implementation of mb_strlen, hardcoded to UTF-8.
107 * @param string $enc optional encoding; ignored
110 function mb_strlen( $str, $enc="" ) {
111 $counts = count_chars( $str );
115 for( $i = 0; $i < 0x80; $i++
) {
116 $total +
= $counts[$i];
119 // Count multibyte sequence heads
120 for( $i = 0xc0; $i < 0xff; $i++
) {
121 $total +
= $counts[$i];
128 if( !function_exists( 'mb_strpos' ) ) {
130 * Fallback implementation of mb_strpos, hardcoded to UTF-8.
131 * @param $haystack String
132 * @param $needle String
133 * @param $offset String: optional start position
134 * @param $encoding String: optional encoding; ignored
137 function mb_strpos( $haystack, $needle, $offset = 0, $encoding="" ) {
138 $needle = preg_quote( $needle, '/' );
141 preg_match( '/'.$needle.'/u', $haystack, $ar, PREG_OFFSET_CAPTURE
, $offset );
143 if( isset( $ar[0][1] ) ) {
151 if( !function_exists( 'mb_strrpos' ) ) {
153 * Fallback implementation of mb_strrpos, hardcoded to UTF-8.
154 * @param $haystack String
155 * @param $needle String
156 * @param $offset String: optional start position
157 * @param $encoding String: optional encoding; ignored
160 function mb_strrpos( $haystack, $needle, $offset = 0, $encoding = "" ) {
161 $needle = preg_quote( $needle, '/' );
164 preg_match_all( '/'.$needle.'/u', $haystack, $ar, PREG_OFFSET_CAPTURE
, $offset );
166 if( isset( $ar[0] ) && count( $ar[0] ) > 0 &&
167 isset( $ar[0][count($ar[0])-1][1] ) ) {
168 return $ar[0][count($ar[0])-1][1];
175 // Support for Wietse Venema's taint feature
176 if ( !function_exists( 'istainted' ) ) {
177 function istainted( $var ) {
180 function taint( $var, $level = 0 ) {}
181 function untaint( $var, $level = 0 ) {}
182 define( 'TC_HTML', 1 );
183 define( 'TC_SHELL', 1 );
184 define( 'TC_MYSQL', 1 );
185 define( 'TC_PCRE', 1 );
186 define( 'TC_SELF', 1 );
192 * Like array_diff( $a, $b ) except that it works with two-dimensional arrays.
194 function wfArrayDiff2( $a, $b ) {
195 return array_udiff( $a, $b, 'wfArrayDiff2_cmp' );
197 function wfArrayDiff2_cmp( $a, $b ) {
198 if ( !is_array( $a ) ) {
199 return strcmp( $a, $b );
200 } elseif ( count( $a ) !== count( $b ) ) {
201 return count( $a ) < count( $b ) ?
-1 : 1;
205 while( ( list( $keyA, $valueA ) = each( $a ) ) && ( list( $keyB, $valueB ) = each( $b ) ) ) {
206 $cmp = strcmp( $valueA, $valueB );
216 * Seed Mersenne Twister
217 * No-op for compatibility; only necessary in PHP < 4.2.0
219 function wfSeedRandom() {
224 * Get a random decimal value between 0 and 1, in a way
225 * not likely to give duplicate values for any realistic
226 * number of articles.
230 function wfRandom() {
231 # The maximum random value is "only" 2^31-1, so get two random
232 # values to reduce the chance of dupes
233 $max = mt_getrandmax() +
1;
234 $rand = number_format( (mt_rand() * $max +
mt_rand())
235 / $max / $max, 12, '.', '' );
240 * We want some things to be included as literal characters in our title URLs
241 * for prettiness, which urlencode encodes by default. According to RFC 1738,
242 * all of the following should be safe:
246 * But + is not safe because it's used to indicate a space; &= are only safe in
247 * paths and not in queries (and we don't distinguish here); ' seems kind of
248 * scary; and urlencode() doesn't touch -_. to begin with. Plus, although /
249 * is reserved, we don't care. So the list we unescape is:
253 * However, IIS7 redirects fail when the url contains a colon (Bug 22709),
254 * so no fancy : for IIS7.
256 * %2F in the page titles seems to fatally break for some reason.
261 function wfUrlencode( $s ) {
263 if ( is_null( $needle ) ) {
264 $needle = array( '%3B','%40','%24','%21','%2A','%28','%29','%2C','%2F' );
265 if (! isset($_SERVER['SERVER_SOFTWARE']) ||
( strpos($_SERVER['SERVER_SOFTWARE'], "Microsoft-IIS/7") === false)) {
270 $s = urlencode( $s );
273 array( ';', '@', '$', '!', '*', '(', ')', ',', '/', ':' ),
281 * Sends a line to the debug log if enabled or, optionally, to a comment in output.
282 * In normal operation this is a NOP.
284 * Controlling globals:
285 * $wgDebugLogFile - points to the log file
286 * $wgProfileOnly - if set, normal debug messages will not be recorded.
287 * $wgDebugRawPage - if false, 'action=raw' hits will not result in debug output.
288 * $wgDebugComments - if on, some debug items may appear in comments in the HTML output.
290 * @param $text String
291 * @param $logonly Bool: set true to avoid appearing in HTML when $wgDebugComments is set
293 function wfDebug( $text, $logonly = false ) {
294 global $wgOut, $wgDebugLogFile, $wgDebugComments, $wgProfileOnly, $wgDebugRawPage;
295 global $wgDebugLogPrefix, $wgShowDebug;
296 static $recursion = 0;
298 static $cache = array(); // Cache of unoutputted messages
299 $text = wfDebugTimer() . $text;
301 # Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
302 if ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' && !$wgDebugRawPage ) {
306 if ( ( $wgDebugComments ||
$wgShowDebug ) && !$logonly ) {
309 if ( !isset( $wgOut ) ) {
312 if ( !StubObject
::isRealObject( $wgOut ) ) {
321 // add the message and possible cached ones to the output
322 array_map( array( $wgOut, 'debug' ), $cache );
325 if ( $wgDebugLogFile != '' && !$wgProfileOnly ) {
326 # Strip unprintables; they can switch terminal modes when binary data
327 # gets dumped, which is pretty annoying.
328 $text = preg_replace( '![\x00-\x08\x0b\x0c\x0e-\x1f]!', ' ', $text );
329 $text = $wgDebugLogPrefix . $text;
330 wfErrorLog( $text, $wgDebugLogFile );
334 function wfDebugTimer() {
335 global $wgDebugTimestamps;
336 if ( !$wgDebugTimestamps ) return '';
337 static $start = null;
339 if ( $start === null ) {
340 $start = microtime( true );
341 $prefix = "\n$start";
343 $prefix = sprintf( "%6.4f", microtime( true ) - $start );
346 return $prefix . ' ';
350 * Send a line giving PHP memory usage.
351 * @param $exact Bool: print exact values instead of kilobytes (default: false)
353 function wfDebugMem( $exact = false ) {
354 $mem = memory_get_usage();
356 $mem = floor( $mem / 1024 ) . ' kilobytes';
360 wfDebug( "Memory usage: $mem\n" );
364 * Send a line to a supplementary debug log file, if configured, or main debug log if not.
365 * $wgDebugLogGroups[$logGroup] should be set to a filename to send to a separate log.
367 * @param $logGroup String
368 * @param $text String
369 * @param $public Bool: whether to log the event in the public log if no private
370 * log file is specified, (default true)
372 function wfDebugLog( $logGroup, $text, $public = true ) {
373 global $wgDebugLogGroups, $wgShowHostnames;
374 $text = trim($text)."\n";
375 if( isset( $wgDebugLogGroups[$logGroup] ) ) {
376 $time = wfTimestamp( TS_DB
);
378 if ( $wgShowHostnames ) {
379 $host = wfHostname();
383 wfErrorLog( "$time $host $wiki: $text", $wgDebugLogGroups[$logGroup] );
384 } else if ( $public === true ) {
385 wfDebug( $text, true );
390 * Log for database errors
391 * @param $text String: database error message.
393 function wfLogDBError( $text ) {
394 global $wgDBerrorLog, $wgDBname;
395 if ( $wgDBerrorLog ) {
396 $host = trim(`hostname`
);
397 $text = date('D M j G:i:s T Y') . "\t$host\t$wgDBname\t$text";
398 wfErrorLog( $text, $wgDBerrorLog );
403 * Log to a file without getting "file size exceeded" signals.
405 * Can also log to TCP or UDP with the syntax udp://host:port/prefix. This will
406 * send lines to the specified port, prefixed by the specified prefix and a space.
408 function wfErrorLog( $text, $file ) {
409 if ( substr( $file, 0, 4 ) == 'udp:' ) {
410 if ( preg_match( '!^(tcp|udp):(?://)?\[([0-9a-fA-F:]+)\]:(\d+)(?:/(.*))?$!', $file, $m ) ) {
411 // IPv6 bracketed host
414 $port = intval( $m[3] );
415 $prefix = isset( $m[4] ) ?
$m[4] : false;
417 } elseif ( preg_match( '!^(tcp|udp):(?://)?([a-zA-Z0-9.-]+):(\d+)(?:/(.*))?$!', $file, $m ) ) {
420 if ( !IP
::isIPv4( $host ) ) {
421 $host = gethostbyname( $host );
423 $port = intval( $m[3] );
424 $prefix = isset( $m[4] ) ?
$m[4] : false;
427 throw new MWException( __METHOD__
.": Invalid UDP specification" );
429 // Clean it up for the multiplexer
430 if ( strval( $prefix ) !== '' ) {
431 $text = preg_replace( '/^/m', $prefix . ' ', $text );
432 if ( substr( $text, -1 ) != "\n" ) {
437 $sock = socket_create( $domain, SOCK_DGRAM
, SOL_UDP
);
441 socket_sendto( $sock, $text, strlen( $text ), 0, $host, $port );
442 socket_close( $sock );
444 wfSuppressWarnings();
445 $exists = file_exists( $file );
446 $size = $exists ?
filesize( $file ) : false;
447 if ( !$exists ||
( $size !== false && $size +
strlen( $text ) < 0x7fffffff ) ) {
448 error_log( $text, 3, $file );
457 function wfLogProfilingData() {
458 global $wgRequestTime, $wgDebugLogFile, $wgDebugRawPage, $wgRequest;
459 global $wgProfiler, $wgProfileLimit, $wgUser;
460 # Profiling must actually be enabled...
461 if( is_null( $wgProfiler ) ) return;
462 # Get total page request time
464 $elapsed = $now - $wgRequestTime;
465 # Only show pages that longer than $wgProfileLimit time (default is 0)
466 if( $elapsed <= $wgProfileLimit ) return;
467 $prof = wfGetProfilingOutput( $wgRequestTime, $elapsed );
469 if( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) )
470 $forward = ' forwarded for ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
471 if( !empty( $_SERVER['HTTP_CLIENT_IP'] ) )
472 $forward .= ' client IP ' . $_SERVER['HTTP_CLIENT_IP'];
473 if( !empty( $_SERVER['HTTP_FROM'] ) )
474 $forward .= ' from ' . $_SERVER['HTTP_FROM'];
476 $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
477 // Don't unstub $wgUser at this late stage just for statistics purposes
478 if( StubObject
::isRealObject($wgUser) && $wgUser->isAnon() )
480 $log = sprintf( "%s\t%04.3f\t%s\n",
481 gmdate( 'YmdHis' ), $elapsed,
482 urldecode( $wgRequest->getRequestURL() . $forward ) );
483 if ( $wgDebugLogFile != '' && ( $wgRequest->getVal('action') != 'raw' ||
$wgDebugRawPage ) ) {
484 wfErrorLog( $log . $prof, $wgDebugLogFile );
489 * Check if the wiki read-only lock file is present. This can be used to lock
490 * off editing functions, but doesn't guarantee that the database will not be
494 function wfReadOnly() {
495 global $wgReadOnlyFile, $wgReadOnly;
497 if ( !is_null( $wgReadOnly ) ) {
498 return (bool)$wgReadOnly;
500 if ( $wgReadOnlyFile == '' ) {
503 // Set $wgReadOnly for faster access next time
504 if ( is_file( $wgReadOnlyFile ) ) {
505 $wgReadOnly = file_get_contents( $wgReadOnlyFile );
509 return (bool)$wgReadOnly;
512 function wfReadOnlyReason() {
519 * Return a Language object from $langcode
520 * @param $langcode Mixed: either:
521 * - a Language object
522 * - code of the language to get the message for, if it is
523 * a valid code create a language for that language, if
524 * it is a string but not a valid code then make a basic
526 * - a boolean: if it's false then use the current users
527 * language (as a fallback for the old parameter
528 * functionality), or if it is true then use the wikis
529 * @return Language object
531 function wfGetLangObj( $langcode = false ) {
532 # Identify which language to get or create a language object for.
533 # Using is_object here due to Stub objects.
534 if( is_object( $langcode ) ) {
535 # Great, we already have the object (hopefully)!
539 global $wgContLang, $wgLanguageCode;
540 if( $langcode === true ||
$langcode === $wgLanguageCode ) {
541 # $langcode is the language code of the wikis content language object.
542 # or it is a boolean and value is true
547 if( $langcode === false ||
$langcode === $wgLang->getCode() ) {
548 # $langcode is the language code of user language object.
549 # or it was a boolean and value is false
553 $validCodes = array_keys( Language
::getLanguageNames() );
554 if( in_array( $langcode, $validCodes ) ) {
555 # $langcode corresponds to a valid language.
556 return Language
::factory( $langcode );
559 # $langcode is a string, but not a valid language code; use content language.
560 wfDebug( "Invalid language code passed to wfGetLangObj, falling back to content language.\n" );
564 function wfUILang() {
565 global $wgBetterDirectionality;
566 return wfGetLangObj( $wgBetterDirectionality ?
false: true );
570 * Get a message from anywhere, for the current user language.
572 * Use wfMsgForContent() instead if the message should NOT
573 * change depending on the user preferences.
575 * @param $key String: lookup key for the message, usually
576 * defined in languages/Language.php
578 * This function also takes extra optional parameters (not
579 * shown in the function definition), which can by used to
580 * insert variable text into the predefined message.
582 function wfMsg( $key ) {
583 $args = func_get_args();
584 array_shift( $args );
585 return wfMsgReal( $key, $args, true );
589 * Same as above except doesn't transform the message
591 function wfMsgNoTrans( $key ) {
592 $args = func_get_args();
593 array_shift( $args );
594 return wfMsgReal( $key, $args, true, false, false );
598 * Get a message from anywhere, for the current global language
599 * set with $wgLanguageCode.
601 * Use this if the message should NOT change dependent on the
602 * language set in the user's preferences. This is the case for
603 * most text written into logs, as well as link targets (such as
604 * the name of the copyright policy page). Link titles, on the
605 * other hand, should be shown in the UI language.
607 * Note that MediaWiki allows users to change the user interface
608 * language in their preferences, but a single installation
609 * typically only contains content in one language.
611 * Be wary of this distinction: If you use wfMsg() where you should
612 * use wfMsgForContent(), a user of the software may have to
613 * customize potentially hundreds of messages in
614 * order to, e.g., fix a link in every possible language.
616 * @param $key String: lookup key for the message, usually
617 * defined in languages/Language.php
619 function wfMsgForContent( $key ) {
620 global $wgForceUIMsgAsContentMsg;
621 $args = func_get_args();
622 array_shift( $args );
624 if( is_array( $wgForceUIMsgAsContentMsg ) &&
625 in_array( $key, $wgForceUIMsgAsContentMsg ) )
627 return wfMsgReal( $key, $args, true, $forcontent );
631 * Same as above except doesn't transform the message
633 function wfMsgForContentNoTrans( $key ) {
634 global $wgForceUIMsgAsContentMsg;
635 $args = func_get_args();
636 array_shift( $args );
638 if( is_array( $wgForceUIMsgAsContentMsg ) &&
639 in_array( $key, $wgForceUIMsgAsContentMsg ) )
641 return wfMsgReal( $key, $args, true, $forcontent, false );
645 * Get a message from the language file, for the UI elements
647 function wfMsgNoDB( $key ) {
648 $args = func_get_args();
649 array_shift( $args );
650 return wfMsgReal( $key, $args, false );
654 * Get a message from the language file, for the content
656 function wfMsgNoDBForContent( $key ) {
657 global $wgForceUIMsgAsContentMsg;
658 $args = func_get_args();
659 array_shift( $args );
661 if( is_array( $wgForceUIMsgAsContentMsg ) &&
662 in_array( $key, $wgForceUIMsgAsContentMsg ) )
664 return wfMsgReal( $key, $args, false, $forcontent );
669 * Really get a message
670 * @param $key String: key to get.
672 * @param $useDB Boolean
673 * @param $forContent Mixed: Language code, or false for user lang, true for content lang.
674 * @param $transform Boolean: Whether or not to transform the message.
675 * @return String: the requested message.
677 function wfMsgReal( $key, $args, $useDB = true, $forContent = false, $transform = true ) {
678 wfProfileIn( __METHOD__
);
679 $message = wfMsgGetKey( $key, $useDB, $forContent, $transform );
680 $message = wfMsgReplaceArgs( $message, $args );
681 wfProfileOut( __METHOD__
);
686 * This function provides the message source for messages to be edited which are *not* stored in the database.
687 * @param $key String:
689 function wfMsgWeirdKey( $key ) {
690 $source = wfMsgGetKey( $key, false, true, false );
691 if ( wfEmptyMsg( $key, $source ) )
698 * Fetch a message string value, but don't replace any keys yet.
701 * @param $langCode String: Code of the language to get the message for, or
702 * behaves as a content language switch if it is a boolean.
703 * @param $transform Boolean: whether to parse magic words, etc.
706 function wfMsgGetKey( $key, $useDB, $langCode = false, $transform = true ) {
707 global $wgContLang, $wgMessageCache;
709 wfRunHooks('NormalizeMessageKey', array(&$key, &$useDB, &$langCode, &$transform));
711 if ( !is_object( $wgMessageCache ) ) {
712 throw new MWException( "Trying to get message before message cache is initialised" );
715 $message = $wgMessageCache->get( $key, $useDB, $langCode );
716 if( $message === false ){
717 $message = '<' . htmlspecialchars( $key ) . '>';
718 } elseif ( $transform ) {
719 $message = $wgMessageCache->transform( $message );
725 * Replace message parameter keys on the given formatted output.
727 * @param $message String
732 function wfMsgReplaceArgs( $message, $args ) {
733 # Fix windows line-endings
734 # Some messages are split with explode("\n", $msg)
735 $message = str_replace( "\r", '', $message );
738 if ( count( $args ) ) {
739 if ( is_array( $args[0] ) ) {
740 $args = array_values( $args[0] );
742 $replacementKeys = array();
743 foreach( $args as $n => $param ) {
744 $replacementKeys['$' . ($n +
1)] = $param;
746 $message = strtr( $message, $replacementKeys );
753 * Return an HTML-escaped version of a message.
754 * Parameter replacements, if any, are done *after* the HTML-escaping,
755 * so parameters may contain HTML (eg links or form controls). Be sure
756 * to pre-escape them if you really do want plaintext, or just wrap
757 * the whole thing in htmlspecialchars().
760 * @param string ... parameters
763 function wfMsgHtml( $key ) {
764 $args = func_get_args();
765 array_shift( $args );
766 return wfMsgReplaceArgs( htmlspecialchars( wfMsgGetKey( $key, true ) ), $args );
770 * Return an HTML version of message
771 * Parameter replacements, if any, are done *after* parsing the wiki-text message,
772 * so parameters may contain HTML (eg links or form controls). Be sure
773 * to pre-escape them if you really do want plaintext, or just wrap
774 * the whole thing in htmlspecialchars().
777 * @param string ... parameters
780 function wfMsgWikiHtml( $key ) {
782 $args = func_get_args();
783 array_shift( $args );
784 return wfMsgReplaceArgs( $wgOut->parse( wfMsgGetKey( $key, true ), /* can't be set to false */ true ), $args );
788 * Returns message in the requested format
789 * @param $key String: key of the message
790 * @param $options Array: processing rules. Can take the following options:
791 * <i>parse</i>: parses wikitext to html
792 * <i>parseinline</i>: parses wikitext to html and removes the surrounding
793 * p's added by parser or tidy
794 * <i>escape</i>: filters message through htmlspecialchars
795 * <i>escapenoentities</i>: same, but allows entity references like   through
796 * <i>replaceafter</i>: parameters are substituted after parsing or escaping
797 * <i>parsemag</i>: transform the message using magic phrases
798 * <i>content</i>: fetch message for content language instead of interface
799 * Also can accept a single associative argument, of the form 'language' => 'xx':
800 * <i>language</i>: Language object or language code to fetch message for
801 * (overriden by <i>content</i>), its behaviour with parser, parseinline
802 * and parsemag is undefined.
803 * Behavior for conflicting options (e.g., parse+parseinline) is undefined.
805 function wfMsgExt( $key, $options ) {
808 $args = func_get_args();
809 array_shift( $args );
810 array_shift( $args );
811 $options = (array)$options;
813 foreach( $options as $arrayKey => $option ) {
814 if( !preg_match( '/^[0-9]+|language$/', $arrayKey ) ) {
815 # An unknown index, neither numeric nor "language"
816 wfWarn( "wfMsgExt called with incorrect parameter key $arrayKey", 1, E_USER_WARNING
);
817 } elseif( preg_match( '/^[0-9]+$/', $arrayKey ) && !in_array( $option,
818 array( 'parse', 'parseinline', 'escape', 'escapenoentities',
819 'replaceafter', 'parsemag', 'content' ) ) ) {
820 # A numeric index with unknown value
821 wfWarn( "wfMsgExt called with incorrect parameter $option", 1, E_USER_WARNING
);
825 if( in_array('content', $options, true ) ) {
828 } elseif( array_key_exists('language', $options) ) {
830 $langCode = wfGetLangObj( $options['language'] );
836 $string = wfMsgGetKey( $key, /*DB*/true, $langCode, /*Transform*/false );
838 if( !in_array('replaceafter', $options, true ) ) {
839 $string = wfMsgReplaceArgs( $string, $args );
842 if( in_array('parse', $options, true ) ) {
843 $string = $wgOut->parse( $string, true, !$forContent );
844 } elseif ( in_array('parseinline', $options, true ) ) {
845 $string = $wgOut->parse( $string, true, !$forContent );
847 if( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $string, $m ) ) {
850 } elseif ( in_array('parsemag', $options, true ) ) {
851 global $wgMessageCache;
852 if ( isset( $wgMessageCache ) ) {
853 $string = $wgMessageCache->transform( $string,
855 is_object( $langCode ) ?
$langCode : null );
859 if ( in_array('escape', $options, true ) ) {
860 $string = htmlspecialchars ( $string );
861 } elseif ( in_array( 'escapenoentities', $options, true ) ) {
862 $string = Sanitizer
::escapeHtmlAllowEntities( $string );
865 if( in_array('replaceafter', $options, true ) ) {
866 $string = wfMsgReplaceArgs( $string, $args );
874 * Just like exit() but makes a note of it.
875 * Commits open transactions except if the error parameter is set
877 * @deprecated Please return control to the caller or throw an exception
879 function wfAbruptExit( $error = false ){
880 static $called = false;
886 $bt = wfDebugBacktrace();
888 for($i = 0; $i < count($bt) ; $i++
){
889 $file = isset($bt[$i]['file']) ?
$bt[$i]['file'] : "unknown";
890 $line = isset($bt[$i]['line']) ?
$bt[$i]['line'] : "unknown";
891 wfDebug("WARNING: Abrupt exit in $file at line $line\n");
894 wfDebug("WARNING: Abrupt exit\n");
897 wfLogProfilingData();
900 wfGetLB()->closeAll();
906 * @deprecated Please return control the caller or throw an exception
908 function wfErrorExit() {
909 wfAbruptExit( true );
913 * Print a simple message and die, returning nonzero to the shell if any.
914 * Plain die() fails to return nonzero to the shell if you pass a string.
917 function wfDie( $msg='' ) {
923 * Throw a debugging exception. This function previously once exited the process,
924 * but now throws an exception instead, with similar results.
926 * @param $msg String: message shown when dieing.
928 function wfDebugDieBacktrace( $msg = '' ) {
929 throw new MWException( $msg );
933 * Fetch server name for use in error reporting etc.
934 * Use real server name if available, so we know which machine
935 * in a server farm generated the current page.
938 function wfHostname() {
940 if ( is_null( $host ) ) {
941 if ( function_exists( 'posix_uname' ) ) {
942 // This function not present on Windows
943 $uname = @posix_uname
();
947 if( is_array( $uname ) && isset( $uname['nodename'] ) ) {
948 $host = $uname['nodename'];
949 } elseif ( getenv( 'COMPUTERNAME' ) ) {
950 # Windows computer name
951 $host = getenv( 'COMPUTERNAME' );
953 # This may be a virtual server.
954 $host = $_SERVER['SERVER_NAME'];
961 * Returns a HTML comment with the elapsed time since request.
962 * This method has no side effects.
965 function wfReportTime() {
966 global $wgRequestTime, $wgShowHostnames;
969 $elapsed = $now - $wgRequestTime;
971 return $wgShowHostnames
972 ?
sprintf( "<!-- Served by %s in %01.3f secs. -->", wfHostname(), $elapsed )
973 : sprintf( "<!-- Served in %01.3f secs. -->", $elapsed );
977 * Safety wrapper for debug_backtrace().
979 * With Zend Optimizer 3.2.0 loaded, this causes segfaults under somewhat
980 * murky circumstances, which may be triggered in part by stub objects
981 * or other fancy talkin'.
983 * Will return an empty array if Zend Optimizer is detected or if
984 * debug_backtrace is disabled, otherwise the output from
985 * debug_backtrace() (trimmed).
987 * @return array of backtrace information
989 function wfDebugBacktrace() {
990 static $disabled = null;
992 if( extension_loaded( 'Zend Optimizer' ) ) {
993 wfDebug( "Zend Optimizer detected; skipping debug_backtrace for safety.\n" );
997 if ( is_null( $disabled ) ) {
999 $functions = explode( ',', ini_get( 'disable_functions' ) );
1000 $functions = array_map( 'trim', $functions );
1001 $functions = array_map( 'strtolower', $functions );
1002 if ( in_array( 'debug_backtrace', $functions ) ) {
1003 wfDebug( "debug_backtrace is in disabled_functions\n" );
1011 return array_slice( debug_backtrace(), 1 );
1014 function wfBacktrace() {
1015 global $wgCommandLineMode;
1017 if ( $wgCommandLineMode ) {
1022 $backtrace = wfDebugBacktrace();
1023 foreach( $backtrace as $call ) {
1024 if( isset( $call['file'] ) ) {
1025 $f = explode( DIRECTORY_SEPARATOR
, $call['file'] );
1026 $file = $f[count($f)-1];
1030 if( isset( $call['line'] ) ) {
1031 $line = $call['line'];
1035 if ( $wgCommandLineMode ) {
1036 $msg .= "$file line $line calls ";
1038 $msg .= '<li>' . $file . ' line ' . $line . ' calls ';
1040 if( !empty( $call['class'] ) ) $msg .= $call['class'] . '::';
1041 $msg .= $call['function'] . '()';
1043 if ( $wgCommandLineMode ) {
1049 if ( $wgCommandLineMode ) {
1059 /* Some generic result counters, pulled out of SearchEngine */
1065 function wfShowingResults( $offset, $limit ) {
1067 return wfMsgExt( 'showingresults', array( 'parseinline' ), $wgLang->formatNum( $limit ),
1068 $wgLang->formatNum( $offset+
1 ) );
1074 function wfShowingResultsNum( $offset, $limit, $num ) {
1076 return wfMsgExt( 'showingresultsnum', array( 'parseinline' ), $wgLang->formatNum( $limit ),
1077 $wgLang->formatNum( $offset+
1 ), $wgLang->formatNum( $num ) );
1081 * Generate (prev x| next x) (20|50|100...) type links for paging
1082 * @param $offset String
1083 * @param $limit Integer
1084 * @param $link String
1085 * @param $query String: optional URL query parameter string
1086 * @param $atend Bool: optional param for specified if this is the last page
1088 function wfViewPrevNext( $offset, $limit, $link, $query = '', $atend = false ) {
1090 $fmtLimit = $wgLang->formatNum( $limit );
1091 // FIXME: Why on earth this needs one message for the text and another one for tooltip??
1092 # Get prev/next link display text
1093 $prev = wfMsgExt( 'prevn', array('parsemag','escape'), $fmtLimit );
1094 $next = wfMsgExt( 'nextn', array('parsemag','escape'), $fmtLimit );
1095 # Get prev/next link title text
1096 $pTitle = wfMsgExt( 'prevn-title', array('parsemag','escape'), $fmtLimit );
1097 $nTitle = wfMsgExt( 'nextn-title', array('parsemag','escape'), $fmtLimit );
1098 # Fetch the title object
1099 if( is_object( $link ) ) {
1102 $title = Title
::newFromText( $link );
1103 if( is_null( $title ) ) {
1107 # Make 'previous' link
1108 if( 0 != $offset ) {
1109 $po = $offset - $limit;
1111 $q = "limit={$limit}&offset={$po}";
1112 if( $query != '' ) {
1115 $plink = '<a href="' . $title->escapeLocalUrl( $q ) . "\" title=\"{$pTitle}\" class=\"mw-prevlink\">{$prev}</a>";
1120 $no = $offset +
$limit;
1121 $q = "limit={$limit}&offset={$no}";
1122 if( $query != '' ) {
1128 $nlink = '<a href="' . $title->escapeLocalUrl( $q ) . "\" title=\"{$nTitle}\" class=\"mw-nextlink\">{$next}</a>";
1130 # Make links to set number of items per page
1131 $nums = $wgLang->pipeList( array(
1132 wfNumLink( $offset, 20, $title, $query ),
1133 wfNumLink( $offset, 50, $title, $query ),
1134 wfNumLink( $offset, 100, $title, $query ),
1135 wfNumLink( $offset, 250, $title, $query ),
1136 wfNumLink( $offset, 500, $title, $query )
1138 return wfMsgHtml( 'viewprevnext', $plink, $nlink, $nums );
1142 * Generate links for (20|50|100...) items-per-page links
1143 * @param $offset String
1144 * @param $limit Integer
1145 * @param $title Title
1146 * @param $query String: optional URL query parameter string
1148 function wfNumLink( $offset, $limit, $title, $query = '' ) {
1150 if( $query == '' ) {
1155 $q .= "limit={$limit}&offset={$offset}";
1156 $fmtLimit = $wgLang->formatNum( $limit );
1157 $lTitle = wfMsgExt('shown-title',array('parsemag','escape'),$limit);
1158 $s = '<a href="' . $title->escapeLocalUrl( $q ) . "\" title=\"{$lTitle}\" class=\"mw-numlink\">{$fmtLimit}</a>";
1164 * @todo FIXME: we may want to blacklist some broken browsers
1166 * @return bool Whereas client accept gzip compression
1168 function wfClientAcceptsGzip() {
1169 if( isset( $_SERVER['HTTP_ACCEPT_ENCODING'] ) ) {
1170 # FIXME: we may want to blacklist some broken browsers
1173 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
1174 $_SERVER['HTTP_ACCEPT_ENCODING'],
1176 if( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) return false;
1177 wfDebug( " accepts gzip\n" );
1185 * Obtain the offset and limit values from the request string;
1186 * used in special pages
1188 * @param $deflimit Default limit if none supplied
1189 * @param $optionname Name of a user preference to check against
1193 function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) {
1195 return $wgRequest->getLimitOffset( $deflimit, $optionname );
1199 * Escapes the given text so that it may be output using addWikiText()
1200 * without any linking, formatting, etc. making its way through. This
1201 * is achieved by substituting certain characters with HTML entities.
1202 * As required by the callers, <nowiki> is not used. It currently does
1203 * not filter out characters which have special meaning only at the
1204 * start of a line, such as "*".
1206 * @param $text String: text to be escaped
1208 function wfEscapeWikiText( $text ) {
1209 $text = str_replace(
1210 array( '[', '|', ']', '\'', 'ISBN ', 'RFC ', '://', "\n=", '{{' ), # }}
1211 array( '[', '|', ']', ''', 'ISBN ', 'RFC ', '://', "\n=", '{{' ),
1212 htmlspecialchars($text) );
1219 function wfQuotedPrintable( $string, $charset = '' ) {
1220 # Probably incomplete; see RFC 2045
1221 if( empty( $charset ) ) {
1222 global $wgInputEncoding;
1223 $charset = $wgInputEncoding;
1225 $charset = strtoupper( $charset );
1226 $charset = str_replace( 'ISO-8859', 'ISO8859', $charset ); // ?
1228 $illegal = '\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\xff=';
1229 $replace = $illegal . '\t ?_';
1230 if( !preg_match( "/[$illegal]/", $string ) ) return $string;
1231 $out = "=?$charset?Q?";
1232 $out .= preg_replace( "/([$replace])/e", 'sprintf("=%02X",ord("$1"))', $string );
1243 return microtime(true);
1247 * Sets dest to source and returns the original value of dest
1248 * If source is NULL, it just returns the value, it doesn't set the variable
1250 function wfSetVar( &$dest, $source ) {
1252 if ( !is_null( $source ) ) {
1259 * As for wfSetVar except setting a bit
1261 function wfSetBit( &$dest, $bit, $state = true ) {
1262 $temp = (bool)($dest & $bit );
1263 if ( !is_null( $state ) ) {
1274 * This function takes two arrays as input, and returns a CGI-style string, e.g.
1275 * "days=7&limit=100". Options in the first array override options in the second.
1276 * Options set to "" will not be output.
1278 function wfArrayToCGI( $array1, $array2 = null )
1280 if ( !is_null( $array2 ) ) {
1281 $array1 = $array1 +
$array2;
1285 foreach ( $array1 as $key => $value ) {
1286 if ( $value !== '' ) {
1290 if ( is_array( $value ) ) {
1292 foreach ( $value as $v ) {
1293 $cgi .= ( $firstTime ?
'' : '&') .
1294 urlencode( $key . '[]' ) . '=' .
1299 if ( is_object( $value ) ) {
1300 $value = $value->__toString();
1302 $cgi .= urlencode( $key ) . '=' .
1303 urlencode( $value );
1311 * This is the logical opposite of wfArrayToCGI(): it accepts a query string as
1312 * its argument and returns the same string in array form. This allows compa-
1313 * tibility with legacy functions that accept raw query strings instead of nice
1314 * arrays. Of course, keys and values are urldecode()d. Don't try passing in-
1315 * valid query strings, or it will explode.
1317 * @param $query String: query string
1318 * @return array Array version of input
1320 function wfCgiToArray( $query ) {
1321 if( isset( $query[0] ) and $query[0] == '?' ) {
1322 $query = substr( $query, 1 );
1324 $bits = explode( '&', $query );
1326 foreach( $bits as $bit ) {
1330 list( $key, $value ) = explode( '=', $bit );
1331 $key = urldecode( $key );
1332 $value = urldecode( $value );
1333 $ret[$key] = $value;
1339 * Append a query string to an existing URL, which may or may not already
1340 * have query string parameters already. If so, they will be combined.
1342 * @param $url String
1343 * @param $query Mixed: string or associative array
1346 function wfAppendQuery( $url, $query ) {
1347 if ( is_array( $query ) ) {
1348 $query = wfArrayToCGI( $query );
1350 if( $query != '' ) {
1351 if( false === strpos( $url, '?' ) ) {
1362 * Expand a potentially local URL to a fully-qualified URL. Assumes $wgServer
1363 * and $wgProto are correct.
1365 * @todo this won't work with current-path-relative URLs
1366 * like "subdir/foo.html", etc.
1368 * @param $url String: either fully-qualified or a local path + query
1369 * @return string Fully-qualified URL
1371 function wfExpandUrl( $url ) {
1372 if( substr( $url, 0, 2 ) == '//' ) {
1374 return $wgProto . ':' . $url;
1375 } elseif( substr( $url, 0, 1 ) == '/' ) {
1377 return $wgServer . $url;
1384 * This is obsolete, use SquidUpdate::purge()
1387 function wfPurgeSquidServers ($urlArr) {
1388 SquidUpdate
::purge( $urlArr );
1392 * Windows-compatible version of escapeshellarg()
1393 * Windows doesn't recognise single-quotes in the shell, but the escapeshellarg()
1394 * function puts single quotes in regardless of OS.
1396 * Also fixes the locale problems on Linux in PHP 5.2.6+ (bug backported to
1397 * earlier distro releases of PHP)
1399 function wfEscapeShellArg( ) {
1400 wfInitShellLocale();
1402 $args = func_get_args();
1405 foreach ( $args as $arg ) {
1412 if ( wfIsWindows() ) {
1413 // Escaping for an MSVC-style command line parser
1414 // Ref: http://mailman.lyra.org/pipermail/scite-interest/2002-March/000436.html
1415 // Double the backslashes before any double quotes. Escape the double quotes.
1416 $tokens = preg_split( '/(\\\\*")/', $arg, -1, PREG_SPLIT_DELIM_CAPTURE
);
1419 foreach ( $tokens as $token ) {
1421 $arg .= str_replace( '\\', '\\\\', substr( $token, 0, -1 ) ) . '\\"';
1428 // Double the backslashes before the end of the string, because
1429 // we will soon add a quote
1431 if ( preg_match( '/^(.*?)(\\\\+)$/', $arg, $m ) ) {
1432 $arg = $m[1] . str_replace( '\\', '\\\\', $m[2] );
1435 // The caret is also an special character
1436 $arg = str_replace( "^", "^^", $arg );
1438 // Add surrounding quotes
1439 $retVal .= '"' . $arg . '"';
1441 $retVal .= escapeshellarg( $arg );
1448 * wfMerge attempts to merge differences between three texts.
1449 * Returns true for a clean merge and false for failure or a conflict.
1451 function wfMerge( $old, $mine, $yours, &$result ){
1454 # This check may also protect against code injection in
1455 # case of broken installations.
1456 if( !$wgDiff3 ||
!file_exists( $wgDiff3 ) ) {
1457 wfDebug( "diff3 not found\n" );
1461 # Make temporary files
1463 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
1464 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
1465 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
1467 fwrite( $oldtextFile, $old ); fclose( $oldtextFile );
1468 fwrite( $mytextFile, $mine ); fclose( $mytextFile );
1469 fwrite( $yourtextFile, $yours ); fclose( $yourtextFile );
1471 # Check for a conflict
1472 $cmd = $wgDiff3 . ' -a --overlap-only ' .
1473 wfEscapeShellArg( $mytextName ) . ' ' .
1474 wfEscapeShellArg( $oldtextName ) . ' ' .
1475 wfEscapeShellArg( $yourtextName );
1476 $handle = popen( $cmd, 'r' );
1478 if( fgets( $handle, 1024 ) ){
1486 $cmd = $wgDiff3 . ' -a -e --merge ' .
1487 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
1488 $handle = popen( $cmd, 'r' );
1491 $data = fread( $handle, 8192 );
1492 if ( strlen( $data ) == 0 ) {
1498 unlink( $mytextName ); unlink( $oldtextName ); unlink( $yourtextName );
1500 if ( $result === '' && $old !== '' && !$conflict ) {
1501 wfDebug( "Unexpected null result from diff3. Command: $cmd\n" );
1508 * Returns unified plain-text diff of two texts.
1509 * Useful for machine processing of diffs.
1510 * @param $before String: the text before the changes.
1511 * @param $after String: the text after the changes.
1512 * @param $params String: command-line options for the diff command.
1513 * @return String: unified diff of $before and $after
1515 function wfDiff( $before, $after, $params = '-u' ) {
1516 if ($before == $after) {
1522 # This check may also protect against code injection in
1523 # case of broken installations.
1524 if( !file_exists( $wgDiff ) ){
1525 wfDebug( "diff executable not found\n" );
1526 $diffs = new Diff( explode( "\n", $before ), explode( "\n", $after ) );
1527 $format = new UnifiedDiffFormatter();
1528 return $format->format( $diffs );
1531 # Make temporary files
1533 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
1534 $newtextFile = fopen( $newtextName = tempnam( $td, 'merge-your-' ), 'w' );
1536 fwrite( $oldtextFile, $before ); fclose( $oldtextFile );
1537 fwrite( $newtextFile, $after ); fclose( $newtextFile );
1539 // Get the diff of the two files
1540 $cmd = "$wgDiff " . $params . ' ' .wfEscapeShellArg( $oldtextName, $newtextName );
1542 $h = popen( $cmd, 'r' );
1547 $data = fread( $h, 8192 );
1548 if ( strlen( $data ) == 0 ) {
1556 unlink( $oldtextName );
1557 unlink( $newtextName );
1559 // Kill the --- and +++ lines. They're not useful.
1560 $diff_lines = explode( "\n", $diff );
1561 if (strpos( $diff_lines[0], '---' ) === 0) {
1562 unset($diff_lines[0]);
1564 if (strpos( $diff_lines[1], '+++' ) === 0) {
1565 unset($diff_lines[1]);
1568 $diff = implode( "\n", $diff_lines );
1574 * A wrapper around the PHP function var_export().
1575 * Either print it or add it to the regular output ($wgOut).
1577 * @param $var A PHP variable to dump.
1579 function wfVarDump( $var ) {
1581 $s = str_replace("\n","<br />\n", var_export( $var, true ) . "\n");
1582 if ( headers_sent() ||
!@is_object
( $wgOut ) ) {
1585 $wgOut->addHTML( $s );
1590 * Provide a simple HTTP error.
1592 function wfHttpError( $code, $label, $desc ) {
1595 header( "HTTP/1.0 $code $label" );
1596 header( "Status: $code $label" );
1597 $wgOut->sendCacheControl();
1599 header( 'Content-type: text/html; charset=utf-8' );
1600 print "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">".
1601 "<html><head><title>" .
1602 htmlspecialchars( $label ) .
1603 "</title></head><body><h1>" .
1604 htmlspecialchars( $label ) .
1606 nl2br( htmlspecialchars( $desc ) ) .
1607 "</p></body></html>\n";
1611 * Clear away any user-level output buffers, discarding contents.
1613 * Suitable for 'starting afresh', for instance when streaming
1614 * relatively large amounts of data without buffering, or wanting to
1615 * output image files without ob_gzhandler's compression.
1617 * The optional $resetGzipEncoding parameter controls suppression of
1618 * the Content-Encoding header sent by ob_gzhandler; by default it
1619 * is left. See comments for wfClearOutputBuffers() for why it would
1622 * Note that some PHP configuration options may add output buffer
1623 * layers which cannot be removed; these are left in place.
1625 * @param $resetGzipEncoding Bool
1627 function wfResetOutputBuffers( $resetGzipEncoding=true ) {
1628 if( $resetGzipEncoding ) {
1629 // Suppress Content-Encoding and Content-Length
1630 // headers from 1.10+s wfOutputHandler
1631 global $wgDisableOutputCompression;
1632 $wgDisableOutputCompression = true;
1634 while( $status = ob_get_status() ) {
1635 if( $status['type'] == 0 /* PHP_OUTPUT_HANDLER_INTERNAL */ ) {
1636 // Probably from zlib.output_compression or other
1637 // PHP-internal setting which can't be removed.
1639 // Give up, and hope the result doesn't break
1643 if( !ob_end_clean() ) {
1644 // Could not remove output buffer handler; abort now
1645 // to avoid getting in some kind of infinite loop.
1648 if( $resetGzipEncoding ) {
1649 if( $status['name'] == 'ob_gzhandler' ) {
1650 // Reset the 'Content-Encoding' field set by this handler
1651 // so we can start fresh.
1652 header( 'Content-Encoding:' );
1660 * More legible than passing a 'false' parameter to wfResetOutputBuffers():
1662 * Clear away output buffers, but keep the Content-Encoding header
1663 * produced by ob_gzhandler, if any.
1665 * This should be used for HTTP 304 responses, where you need to
1666 * preserve the Content-Encoding header of the real result, but
1667 * also need to suppress the output of ob_gzhandler to keep to spec
1668 * and avoid breaking Firefox in rare cases where the headers and
1669 * body are broken over two packets.
1671 function wfClearOutputBuffers() {
1672 wfResetOutputBuffers( false );
1676 * Converts an Accept-* header into an array mapping string values to quality
1679 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
1680 # No arg means accept anything (per HTTP spec)
1682 return array( $def => 1.0 );
1687 $parts = explode( ',', $accept );
1689 foreach( $parts as $part ) {
1690 # FIXME: doesn't deal with params like 'text/html; level=1'
1691 @list
( $value, $qpart ) = explode( ';', trim( $part ) );
1693 if( !isset( $qpart ) ) {
1694 $prefs[$value] = 1.0;
1695 } elseif( preg_match( '/q\s*=\s*(\d*\.\d+)/', $qpart, $match ) ) {
1696 $prefs[$value] = floatval($match[1]);
1704 * Checks if a given MIME type matches any of the keys in the given
1705 * array. Basic wildcards are accepted in the array keys.
1707 * Returns the matching MIME type (or wildcard) if a match, otherwise
1710 * @param $type String
1711 * @param $avail Array
1715 function mimeTypeMatch( $type, $avail ) {
1716 if( array_key_exists($type, $avail) ) {
1719 $parts = explode( '/', $type );
1720 if( array_key_exists( $parts[0] . '/*', $avail ) ) {
1721 return $parts[0] . '/*';
1722 } elseif( array_key_exists( '*/*', $avail ) ) {
1731 * Returns the 'best' match between a client's requested internet media types
1732 * and the server's list of available types. Each list should be an associative
1733 * array of type to preference (preference is a float between 0.0 and 1.0).
1734 * Wildcards in the types are acceptable.
1736 * @param $cprefs Array: client's acceptable type list
1737 * @param $sprefs Array: server's offered types
1740 * @todo FIXME: doesn't handle params like 'text/plain; charset=UTF-8'
1741 * XXX: generalize to negotiate other stuff
1743 function wfNegotiateType( $cprefs, $sprefs ) {
1746 foreach( array_keys($sprefs) as $type ) {
1747 $parts = explode( '/', $type );
1748 if( $parts[1] != '*' ) {
1749 $ckey = mimeTypeMatch( $type, $cprefs );
1751 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1756 foreach( array_keys( $cprefs ) as $type ) {
1757 $parts = explode( '/', $type );
1758 if( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
1759 $skey = mimeTypeMatch( $type, $sprefs );
1761 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1769 foreach( array_keys( $combine ) as $type ) {
1770 if( $combine[$type] > $bestq ) {
1772 $bestq = $combine[$type];
1781 * Returns an array where the values in the first array are replaced by the
1782 * values in the second array with the corresponding keys
1786 function wfArrayLookup( $a, $b ) {
1787 return array_flip( array_intersect( array_flip( $a ), array_keys( $b ) ) );
1791 * Convenience function; returns MediaWiki timestamp for the present time.
1794 function wfTimestampNow() {
1796 return wfTimestamp( TS_MW
, time() );
1800 * Reference-counted warning suppression
1802 function wfSuppressWarnings( $end = false ) {
1803 static $suppressCount = 0;
1804 static $originalLevel = false;
1807 if ( $suppressCount ) {
1809 if ( !$suppressCount ) {
1810 error_reporting( $originalLevel );
1814 if ( !$suppressCount ) {
1815 $originalLevel = error_reporting( E_ALL
& ~
( E_WARNING | E_NOTICE | E_USER_WARNING | E_USER_NOTICE
) );
1822 * Restore error level to previous value
1824 function wfRestoreWarnings() {
1825 wfSuppressWarnings( true );
1828 # Autodetect, convert and provide timestamps of various types
1831 * Unix time - the number of seconds since 1970-01-01 00:00:00 UTC
1833 define('TS_UNIX', 0);
1836 * MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
1841 * MySQL DATETIME (YYYY-MM-DD HH:MM:SS)
1846 * RFC 2822 format, for E-mail and HTTP headers
1848 define('TS_RFC2822', 3);
1851 * ISO 8601 format with no timezone: 1986-02-09T20:00:00Z
1853 * This is used by Special:Export
1855 define('TS_ISO_8601', 4);
1858 * An Exif timestamp (YYYY:MM:DD HH:MM:SS)
1860 * @see http://exif.org/Exif2-2.PDF The Exif 2.2 spec, see page 28 for the
1861 * DateTime tag and page 36 for the DateTimeOriginal and
1862 * DateTimeDigitized tags.
1864 define('TS_EXIF', 5);
1867 * Oracle format time.
1869 define('TS_ORACLE', 6);
1872 * Postgres format time.
1874 define('TS_POSTGRES', 7);
1879 define('TS_DB2', 8);
1882 * @param $outputtype Mixed: A timestamp in one of the supported formats, the
1883 * function will autodetect which format is supplied and act
1885 * @param $ts Mixed: the timestamp to convert or 0 for the current timestamp
1886 * @return String: in the format specified in $outputtype
1888 function wfTimestamp( $outputtype = TS_UNIX
, $ts = 0 ) {
1893 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)$/D',$ts,$da)) {
1895 } elseif (preg_match('/^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/D',$ts,$da)) {
1897 } elseif (preg_match('/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/D',$ts,$da)) {
1899 } elseif (preg_match('/^\d{1,13}$/D',$ts)) {
1902 } elseif (preg_match('/^\d{2}-\d{2}-\d{4} \d{2}:\d{2}:\d{2}.\d{6}$/', $ts)) {
1903 # TS_ORACLE // session altered to DD-MM-YYYY HH24:MI:SS.FF6
1904 $uts = strtotime(preg_replace('/(\d\d)\.(\d\d)\.(\d\d)(\.(\d+))?/', "$1:$2:$3",
1905 str_replace("+00:00", "UTC", $ts)));
1906 } elseif (preg_match('/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.*\d*)?Z$/', $ts, $da)) {
1908 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.*\d*[\+\- ](\d\d)$/',$ts,$da)) {
1910 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.*\d* GMT$/',$ts,$da)) {
1913 # Bogus value; fall back to the epoch...
1914 wfDebug("wfTimestamp() fed bogus time value: $outputtype; $ts\n");
1918 if (count( $da ) ) {
1919 // Warning! gmmktime() acts oddly if the month or day is set to 0
1920 // We may want to handle that explicitly at some point
1921 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1922 (int)$da[2],(int)$da[3],(int)$da[1]);
1925 switch($outputtype) {
1929 return gmdate( 'YmdHis', $uts );
1931 return gmdate( 'Y-m-d H:i:s', $uts );
1933 return gmdate( 'Y-m-d\TH:i:s\Z', $uts );
1934 // This shouldn't ever be used, but is included for completeness
1936 return gmdate( 'Y:m:d H:i:s', $uts );
1938 return gmdate( 'D, d M Y H:i:s', $uts ) . ' GMT';
1940 return gmdate( 'd-m-Y H:i:s.000000', $uts);
1941 //return gmdate( 'd-M-y h.i.s A', $uts) . ' +00:00';
1943 return gmdate( 'Y-m-d H:i:s', $uts) . ' GMT';
1945 return gmdate( 'Y-m-d H:i:s', $uts);
1947 throw new MWException( 'wfTimestamp() called with illegal output type.');
1952 * Return a formatted timestamp, or null if input is null.
1953 * For dealing with nullable timestamp columns in the database.
1954 * @param $outputtype Integer
1958 function wfTimestampOrNull( $outputtype = TS_UNIX
, $ts = null ) {
1959 if( is_null( $ts ) ) {
1962 return wfTimestamp( $outputtype, $ts );
1967 * Check if the operating system is Windows
1969 * @return Bool: true if it's Windows, False otherwise.
1971 function wfIsWindows() {
1972 if (substr(php_uname(), 0, 7) == 'Windows') {
1980 * Swap two variables
1982 function swap( &$x, &$y ) {
1988 function wfGetCachedNotice( $name ) {
1989 global $wgOut, $wgRenderHashAppend, $parserMemc;
1990 $fname = 'wfGetCachedNotice';
1991 wfProfileIn( $fname );
1995 if( $name === 'default' ) {
1997 global $wgSiteNotice;
1998 $notice = $wgSiteNotice;
1999 if( empty( $notice ) ) {
2000 wfProfileOut( $fname );
2004 $notice = wfMsgForContentNoTrans( $name );
2005 if( wfEmptyMsg( $name, $notice ) ||
$notice == '-' ) {
2006 wfProfileOut( $fname );
2011 // Use the extra hash appender to let eg SSL variants separately cache.
2012 $key = wfMemcKey( $name . $wgRenderHashAppend );
2013 $cachedNotice = $parserMemc->get( $key );
2014 if( is_array( $cachedNotice ) ) {
2015 if( md5( $notice ) == $cachedNotice['hash'] ) {
2016 $notice = $cachedNotice['html'];
2025 if( is_object( $wgOut ) ) {
2026 $parsed = $wgOut->parse( $notice );
2027 $parserMemc->set( $key, array( 'html' => $parsed, 'hash' => md5( $notice ) ), 600 );
2030 wfDebug( 'wfGetCachedNotice called for ' . $name . ' with no $wgOut available'."\n" );
2034 $notice = '<div id="localNotice">'.$notice.'</div>';
2035 wfProfileOut( $fname );
2039 function wfGetNamespaceNotice() {
2043 if ( !isset( $wgTitle ) ||
!is_object( $wgTitle ) )
2046 $fname = 'wfGetNamespaceNotice';
2047 wfProfileIn( $fname );
2049 $key = "namespacenotice-" . $wgTitle->getNsText();
2050 $namespaceNotice = wfGetCachedNotice( $key );
2051 if ( $namespaceNotice && substr ( $namespaceNotice , 0 ,7 ) != "<p><" ) {
2052 $namespaceNotice = '<div id="namespacebanner">' . $namespaceNotice . "</div>";
2054 $namespaceNotice = "";
2057 wfProfileOut( $fname );
2058 return $namespaceNotice;
2061 function wfGetSiteNotice() {
2062 global $wgUser, $wgSiteNotice;
2063 $fname = 'wfGetSiteNotice';
2064 wfProfileIn( $fname );
2067 if( wfRunHooks( 'SiteNoticeBefore', array( &$siteNotice ) ) ) {
2068 if( is_object( $wgUser ) && $wgUser->isLoggedIn() ) {
2069 $siteNotice = wfGetCachedNotice( 'sitenotice' );
2071 $anonNotice = wfGetCachedNotice( 'anonnotice' );
2072 if( !$anonNotice ) {
2073 $siteNotice = wfGetCachedNotice( 'sitenotice' );
2075 $siteNotice = $anonNotice;
2078 if( !$siteNotice ) {
2079 $siteNotice = wfGetCachedNotice( 'default' );
2083 wfRunHooks( 'SiteNoticeAfter', array( &$siteNotice ) );
2084 wfProfileOut( $fname );
2089 * BC wrapper for MimeMagic::singleton()
2092 function &wfGetMimeMagic() {
2093 wfDeprecated( __FUNCTION__
);
2094 return MimeMagic
::singleton();
2098 * Tries to get the system directory for temporary files. For PHP >= 5.2.1,
2099 * we'll use sys_get_temp_dir(). The TMPDIR, TMP, and TEMP environment
2100 * variables are then checked in sequence, and if none are set /tmp is
2101 * returned as the generic Unix default.
2103 * NOTE: When possible, use the tempfile() function to create temporary
2104 * files to avoid race conditions on file creation, etc.
2108 function wfTempDir() {
2109 if( function_exists( 'sys_get_temp_dir' ) ) {
2110 return sys_get_temp_dir();
2112 foreach( array( 'TMPDIR', 'TMP', 'TEMP' ) as $var ) {
2113 $tmp = getenv( $var );
2114 if( $tmp && file_exists( $tmp ) && is_dir( $tmp ) && is_writable( $tmp ) ) {
2118 # Hope this is Unix of some kind!
2123 * Make directory, and make all parent directories if they don't exist
2125 * @param $dir String: full path to directory to create
2126 * @param $mode Integer: chmod value to use, default is $wgDirectoryMode
2127 * @param $caller String: optional caller param for debugging.
2130 function wfMkdirParents( $dir, $mode = null, $caller = null ) {
2131 global $wgDirectoryMode;
2133 if ( !is_null( $caller ) ) {
2134 wfDebug( "$caller: called wfMkdirParents($dir)" );
2137 if( strval( $dir ) === '' ||
file_exists( $dir ) )
2140 $dir = str_replace( array( '\\', '/' ), DIRECTORY_SEPARATOR
, $dir );
2142 if ( is_null( $mode ) )
2143 $mode = $wgDirectoryMode;
2145 // Turn off the normal warning, we're doing our own below
2146 wfSuppressWarnings();
2147 $ok = mkdir( $dir, $mode, true ); // PHP5 <3
2148 wfRestoreWarnings();
2151 // PHP doesn't report the path in its warning message, so add our own to aid in diagnosis.
2152 trigger_error( __FUNCTION__
. ": failed to mkdir \"$dir\" mode $mode", E_USER_WARNING
);
2158 * Increment a statistics counter
2160 function wfIncrStats( $key ) {
2161 global $wgStatsMethod;
2163 if( $wgStatsMethod == 'udp' ) {
2164 global $wgUDPProfilerHost, $wgUDPProfilerPort, $wgDBname;
2167 $socket=socket_create(AF_INET
, SOCK_DGRAM
, SOL_UDP
);
2168 $statline="stats/{$wgDBname} - 1 1 1 1 1 -total\n";
2169 socket_sendto($socket,$statline,strlen($statline),0,$wgUDPProfilerHost,$wgUDPProfilerPort);
2171 $statline="stats/{$wgDBname} - 1 1 1 1 1 {$key}\n";
2172 @socket_sendto
($socket,$statline,strlen($statline),0,$wgUDPProfilerHost,$wgUDPProfilerPort);
2173 } elseif( $wgStatsMethod == 'cache' ) {
2175 $key = wfMemcKey( 'stats', $key );
2176 if ( is_null( $wgMemc->incr( $key ) ) ) {
2177 $wgMemc->add( $key, 1 );
2185 * @param $nr Mixed: the number to format
2186 * @param $acc Integer: the number of digits after the decimal point, default 2
2187 * @param $round Boolean: whether or not to round the value, default true
2190 function wfPercent( $nr, $acc = 2, $round = true ) {
2191 $ret = sprintf( "%.${acc}f", $nr );
2192 return $round ?
round( $ret, $acc ) . '%' : "$ret%";
2196 * Encrypt a username/password.
2198 * @param $userid Integer: ID of the user
2199 * @param $password String: password of the user
2200 * @return String: hashed password
2201 * @deprecated Use User::crypt() or User::oldCrypt() instead
2203 function wfEncryptPassword( $userid, $password ) {
2204 wfDeprecated(__FUNCTION__
);
2205 # Just wrap around User::oldCrypt()
2206 return User
::oldCrypt($password, $userid);
2210 * Appends to second array if $value differs from that in $default
2212 function wfAppendToArrayIfNotDefault( $key, $value, $default, &$changed ) {
2213 if ( is_null( $changed ) ) {
2214 throw new MWException('GlobalFunctions::wfAppendToArrayIfNotDefault got null');
2216 if ( $default[$key] !== $value ) {
2217 $changed[$key] = $value;
2222 * Since wfMsg() and co suck, they don't return false if the message key they
2223 * looked up didn't exist but a XHTML string, this function checks for the
2224 * nonexistance of messages by looking at wfMsg() output
2226 * @param $key String: the message key looked up
2227 * @return Boolean True if the message *doesn't* exist.
2229 function wfEmptyMsg( $key ) {
2230 global $wgMessageCache;
2231 return $wgMessageCache->get( $key, /*useDB*/true, /*content*/false ) === false;
2235 * Find out whether or not a mixed variable exists in a string
2237 * @param $needle String
2238 * @param $str String
2241 function in_string( $needle, $str ) {
2242 return strpos( $str, $needle ) !== false;
2245 function wfSpecialList( $page, $details ) {
2247 $details = $details ?
' ' . $wgContLang->getDirMark() . "($details)" : "";
2248 return $page . $details;
2252 * Returns a regular expression of url protocols
2256 function wfUrlProtocols() {
2257 global $wgUrlProtocols;
2259 static $retval = null;
2260 if ( !is_null( $retval ) )
2263 // Support old-style $wgUrlProtocols strings, for backwards compatibility
2264 // with LocalSettings files from 1.5
2265 if ( is_array( $wgUrlProtocols ) ) {
2266 $protocols = array();
2267 foreach ($wgUrlProtocols as $protocol)
2268 $protocols[] = preg_quote( $protocol, '/' );
2270 $retval = implode( '|', $protocols );
2272 $retval = $wgUrlProtocols;
2278 * Safety wrapper around ini_get() for boolean settings.
2279 * The values returned from ini_get() are pre-normalized for settings
2280 * set via php.ini or php_flag/php_admin_flag... but *not*
2281 * for those set via php_value/php_admin_value.
2283 * It's fairly common for people to use php_value instead of php_flag,
2284 * which can leave you with an 'off' setting giving a false positive
2285 * for code that just takes the ini_get() return value as a boolean.
2287 * To make things extra interesting, setting via php_value accepts
2288 * "true" and "yes" as true, but php.ini and php_flag consider them false. :)
2289 * Unrecognized values go false... again opposite PHP's own coercion
2290 * from string to bool.
2292 * Luckily, 'properly' set settings will always come back as '0' or '1',
2293 * so we only have to worry about them and the 'improper' settings.
2295 * I frickin' hate PHP... :P
2297 * @param $setting String
2300 function wfIniGetBool( $setting ) {
2301 $val = ini_get( $setting );
2302 // 'on' and 'true' can't have whitespace around them, but '1' can.
2303 return strtolower( $val ) == 'on'
2304 ||
strtolower( $val ) == 'true'
2305 ||
strtolower( $val ) == 'yes'
2306 ||
preg_match( "/^\s*[+-]?0*[1-9]/", $val ); // approx C atoi() function
2310 * Wrapper function for PHP's dl(). This doesn't work in most situations from
2311 * PHP 5.3 onward, and is usually disabled in shared environments anyway.
2313 * @param $extension String A PHP extension. The file suffix (.so or .dll)
2315 * @return Bool - Whether or not the extension is loaded
2317 function wfDl( $extension ) {
2318 if( extension_loaded( $extension ) ) {
2322 $canDl = ( function_exists( 'dl' ) && is_callable( 'dl' )
2323 && wfIniGetBool( 'enable_dl' ) && !wfIniGetBool( 'safe_mode' ) );
2326 wfSuppressWarnings();
2327 dl( $extension . '.' . PHP_SHLIB_SUFFIX
);
2328 wfRestoreWarnings();
2330 return extension_loaded( $extension );
2334 * Execute a shell command, with time and memory limits mirrored from the PHP
2335 * configuration if supported.
2336 * @param $cmd Command line, properly escaped for shell.
2337 * @param &$retval optional, will receive the program's exit code.
2338 * (non-zero is usually failure)
2339 * @return collected stdout as a string (trailing newlines stripped)
2341 function wfShellExec( $cmd, &$retval=null ) {
2342 global $IP, $wgMaxShellMemory, $wgMaxShellFileSize, $wgMaxShellTime;
2345 if ( is_null( $disabled ) ) {
2347 if( wfIniGetBool( 'safe_mode' ) ) {
2348 wfDebug( "wfShellExec can't run in safe_mode, PHP's exec functions are too broken.\n" );
2351 $functions = explode( ',', ini_get( 'disable_functions' ) );
2352 $functions = array_map( 'trim', $functions );
2353 $functions = array_map( 'strtolower', $functions );
2354 if ( in_array( 'passthru', $functions ) ) {
2355 wfDebug( "passthru is in disabled_functions\n" );
2361 return "Unable to run external programs in safe mode.";
2364 wfInitShellLocale();
2366 if ( php_uname( 's' ) == 'Linux' ) {
2367 $time = intval( $wgMaxShellTime );
2368 $mem = intval( $wgMaxShellMemory );
2369 $filesize = intval( $wgMaxShellFileSize );
2371 if ( $time > 0 && $mem > 0 ) {
2372 $script = "$IP/bin/ulimit4.sh";
2373 if ( is_executable( $script ) ) {
2374 $cmd = escapeshellarg( $script ) . " $time $mem $filesize " . escapeshellarg( $cmd );
2377 } elseif ( php_uname( 's' ) == 'Windows NT' &&
2378 version_compare( PHP_VERSION
, '5.3.0', '<' ) )
2380 # This is a hack to work around PHP's flawed invocation of cmd.exe
2381 # http://news.php.net/php.internals/21796
2382 # Which is fixed in 5.3.0 :)
2383 $cmd = '"' . $cmd . '"';
2385 wfDebug( "wfShellExec: $cmd\n" );
2387 $retval = 1; // error by default?
2389 passthru( $cmd, $retval );
2390 $output = ob_get_contents();
2393 if ( $retval == 127 ) {
2394 wfDebugLog( 'exec', "Possibly missing executable file: $cmd\n" );
2400 * Workaround for http://bugs.php.net/bug.php?id=45132
2401 * escapeshellarg() destroys non-ASCII characters if LANG is not a UTF-8 locale
2403 function wfInitShellLocale() {
2404 static $done = false;
2405 if ( $done ) return;
2407 global $wgShellLocale;
2408 if ( !wfIniGetBool( 'safe_mode' ) ) {
2409 putenv( "LC_CTYPE=$wgShellLocale" );
2410 setlocale( LC_CTYPE
, $wgShellLocale );
2415 * This function works like "use VERSION" in Perl, the program will die with a
2416 * backtrace if the current version of PHP is less than the version provided
2418 * This is useful for extensions which due to their nature are not kept in sync
2419 * with releases, and might depend on other versions of PHP than the main code
2421 * Note: PHP might die due to parsing errors in some cases before it ever
2422 * manages to call this function, such is life
2424 * @see perldoc -f use
2426 * @param $req_ver Mixed: the version to check, can be a string, an integer, or
2429 function wfUsePHP( $req_ver ) {
2430 $php_ver = PHP_VERSION
;
2432 if ( version_compare( $php_ver, (string)$req_ver, '<' ) )
2433 throw new MWException( "PHP $req_ver required--this is only $php_ver" );
2437 * This function works like "use VERSION" in Perl except it checks the version
2438 * of MediaWiki, the program will die with a backtrace if the current version
2439 * of MediaWiki is less than the version provided.
2441 * This is useful for extensions which due to their nature are not kept in sync
2444 * @see perldoc -f use
2446 * @param $req_ver Mixed: the version to check, can be a string, an integer, or
2449 function wfUseMW( $req_ver ) {
2452 if ( version_compare( $wgVersion, (string)$req_ver, '<' ) )
2453 throw new MWException( "MediaWiki $req_ver required--this is only $wgVersion" );
2457 * Return the final portion of a pathname.
2458 * Reimplemented because PHP5's basename() is buggy with multibyte text.
2459 * http://bugs.php.net/bug.php?id=33898
2461 * PHP's basename() only considers '\' a pathchar on Windows and Netware.
2462 * We'll consider it so always, as we don't want \s in our Unix paths either.
2464 * @param $path String
2465 * @param $suffix String: to remove if present
2468 function wfBaseName( $path, $suffix='' ) {
2469 $encSuffix = ($suffix == '')
2471 : ( '(?:' . preg_quote( $suffix, '#' ) . ')?' );
2473 if( preg_match( "#([^/\\\\]*?){$encSuffix}[/\\\\]*$#", $path, $matches ) ) {
2481 * Generate a relative path name to the given file.
2482 * May explode on non-matching case-insensitive paths,
2483 * funky symlinks, etc.
2485 * @param $path String: absolute destination path including target filename
2486 * @param $from String: Absolute source path, directory only
2489 function wfRelativePath( $path, $from ) {
2490 // Normalize mixed input on Windows...
2491 $path = str_replace( '/', DIRECTORY_SEPARATOR
, $path );
2492 $from = str_replace( '/', DIRECTORY_SEPARATOR
, $from );
2494 // Trim trailing slashes -- fix for drive root
2495 $path = rtrim( $path, DIRECTORY_SEPARATOR
);
2496 $from = rtrim( $from, DIRECTORY_SEPARATOR
);
2498 $pieces = explode( DIRECTORY_SEPARATOR
, dirname( $path ) );
2499 $against = explode( DIRECTORY_SEPARATOR
, $from );
2501 if( $pieces[0] !== $against[0] ) {
2502 // Non-matching Windows drive letters?
2503 // Return a full path.
2507 // Trim off common prefix
2508 while( count( $pieces ) && count( $against )
2509 && $pieces[0] == $against[0] ) {
2510 array_shift( $pieces );
2511 array_shift( $against );
2514 // relative dots to bump us to the parent
2515 while( count( $against ) ) {
2516 array_unshift( $pieces, '..' );
2517 array_shift( $against );
2520 array_push( $pieces, wfBaseName( $path ) );
2522 return implode( DIRECTORY_SEPARATOR
, $pieces );
2526 * Backwards array plus for people who haven't bothered to read the PHP manual
2527 * XXX: will not darn your socks for you.
2529 * @param $array1 Array
2530 * @param [$array2, [...]] Arrays
2533 function wfArrayMerge( $array1/* ... */ ) {
2534 $args = func_get_args();
2535 $args = array_reverse( $args, true );
2537 foreach ( $args as $arg ) {
2544 * Merge arrays in the style of getUserPermissionsErrors, with duplicate removal
2546 * wfMergeErrorArrays(
2547 * array( array( 'x' ) ),
2548 * array( array( 'x', '2' ) ),
2549 * array( array( 'x' ) ),
2550 * array( array( 'y') )
2554 * array( 'x', '2' ),
2559 function wfMergeErrorArrays( /*...*/ ) {
2560 $args = func_get_args();
2562 foreach ( $args as $errors ) {
2563 foreach ( $errors as $params ) {
2564 # FIXME: sometimes get nested arrays for $params,
2565 # which leads to E_NOTICEs
2566 $spec = implode( "\t", $params );
2567 $out[$spec] = $params;
2570 return array_values( $out );
2574 * parse_url() work-alike, but non-broken. Differences:
2576 * 1) Does not raise warnings on bad URLs (just returns false)
2577 * 2) Handles protocols that don't use :// (e.g., mailto: and news:) correctly
2578 * 3) Adds a "delimiter" element to the array, either '://' or ':' (see (2))
2580 * @param $url String: a URL to parse
2581 * @return Array: bits of the URL in an associative array, per PHP docs
2583 function wfParseUrl( $url ) {
2584 global $wgUrlProtocols; // Allow all protocols defined in DefaultSettings/LocalSettings.php
2585 wfSuppressWarnings();
2586 $bits = parse_url( $url );
2587 wfRestoreWarnings();
2592 // most of the protocols are followed by ://, but mailto: and sometimes news: not, check for it
2593 if ( in_array( $bits['scheme'] . '://', $wgUrlProtocols ) ) {
2594 $bits['delimiter'] = '://';
2595 } elseif ( in_array( $bits['scheme'] . ':', $wgUrlProtocols ) ) {
2596 $bits['delimiter'] = ':';
2597 // parse_url detects for news: and mailto: the host part of an url as path
2598 // We have to correct this wrong detection
2599 if ( isset ( $bits['path'] ) ) {
2600 $bits['host'] = $bits['path'];
2611 * Make a URL index, appropriate for the el_index field of externallinks.
2613 function wfMakeUrlIndex( $url ) {
2614 $bits = wfParseUrl( $url );
2616 // Reverse the labels in the hostname, convert to lower case
2617 // For emails reverse domainpart only
2618 if ( $bits['scheme'] == 'mailto' ) {
2619 $mailparts = explode( '@', $bits['host'], 2 );
2620 if ( count($mailparts) === 2 ) {
2621 $domainpart = strtolower( implode( '.', array_reverse( explode( '.', $mailparts[1] ) ) ) );
2623 // No domain specified, don't mangle it
2626 $reversedHost = $domainpart . '@' . $mailparts[0];
2628 $reversedHost = strtolower( implode( '.', array_reverse( explode( '.', $bits['host'] ) ) ) );
2630 // Add an extra dot to the end
2631 // Why? Is it in wrong place in mailto links?
2632 if ( substr( $reversedHost, -1, 1 ) !== '.' ) {
2633 $reversedHost .= '.';
2635 // Reconstruct the pseudo-URL
2636 $prot = $bits['scheme'];
2637 $index = $prot . $bits['delimiter'] . $reversedHost;
2638 // Leave out user and password. Add the port, path, query and fragment
2639 if ( isset( $bits['port'] ) ) $index .= ':' . $bits['port'];
2640 if ( isset( $bits['path'] ) ) {
2641 $index .= $bits['path'];
2645 if ( isset( $bits['query'] ) ) $index .= '?' . $bits['query'];
2646 if ( isset( $bits['fragment'] ) ) $index .= '#' . $bits['fragment'];
2651 * Do any deferred updates and clear the list
2652 * TODO: This could be in Wiki.php if that class made any sense at all
2654 function wfDoUpdates()
2656 global $wgPostCommitUpdateList, $wgDeferredUpdateList;
2657 foreach ( $wgDeferredUpdateList as $update ) {
2658 $update->doUpdate();
2660 foreach ( $wgPostCommitUpdateList as $update ) {
2661 $update->doUpdate();
2663 $wgDeferredUpdateList = array();
2664 $wgPostCommitUpdateList = array();
2668 * Convert an arbitrarily-long digit string from one numeric base
2669 * to another, optionally zero-padding to a minimum column width.
2671 * Supports base 2 through 36; digit values 10-36 are represented
2672 * as lowercase letters a-z. Input is case-insensitive.
2674 * @param $input String: of digits
2675 * @param $sourceBase Integer: 2-36
2676 * @param $destBase Integer: 2-36
2677 * @param $pad Integer: 1 or greater
2678 * @param $lowercase Boolean
2679 * @return String or false on invalid input
2681 function wfBaseConvert( $input, $sourceBase, $destBase, $pad=1, $lowercase=true ) {
2682 $input = strval( $input );
2683 if( $sourceBase < 2 ||
2688 $sourceBase != intval( $sourceBase ) ||
2689 $destBase != intval( $destBase ) ||
2690 $pad != intval( $pad ) ||
2691 !is_string( $input ) ||
2695 $digitChars = ( $lowercase ) ?
'0123456789abcdefghijklmnopqrstuvwxyz' : '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
2696 $inDigits = array();
2699 // Decode and validate input string
2700 $input = strtolower( $input );
2701 for( $i = 0; $i < strlen( $input ); $i++
) {
2702 $n = strpos( $digitChars, $input{$i} );
2703 if( $n === false ||
$n > $sourceBase ) {
2709 // Iterate over the input, modulo-ing out an output digit
2710 // at a time until input is gone.
2711 while( count( $inDigits ) ) {
2713 $workDigits = array();
2716 foreach( $inDigits as $digit ) {
2717 $work *= $sourceBase;
2720 if( $work < $destBase ) {
2721 // Gonna need to pull another digit.
2722 if( count( $workDigits ) ) {
2723 // Avoid zero-padding; this lets us find
2724 // the end of the input very easily when
2725 // length drops to zero.
2729 // Finally! Actual division!
2730 $workDigits[] = intval( $work / $destBase );
2732 // Isn't it annoying that most programming languages
2733 // don't have a single divide-and-remainder operator,
2734 // even though the CPU implements it that way?
2735 $work = $work %
$destBase;
2739 // All that division leaves us with a remainder,
2740 // which is conveniently our next output digit.
2741 $outChars .= $digitChars[$work];
2744 $inDigits = $workDigits;
2747 while( strlen( $outChars ) < $pad ) {
2751 return strrev( $outChars );
2755 * Create an object with a given name and an array of construct parameters
2756 * @param $name String
2757 * @param $p Array: parameters
2759 function wfCreateObject( $name, $p ){
2760 $p = array_values( $p );
2761 switch ( count( $p ) ) {
2765 return new $name( $p[0] );
2767 return new $name( $p[0], $p[1] );
2769 return new $name( $p[0], $p[1], $p[2] );
2771 return new $name( $p[0], $p[1], $p[2], $p[3] );
2773 return new $name( $p[0], $p[1], $p[2], $p[3], $p[4] );
2775 return new $name( $p[0], $p[1], $p[2], $p[3], $p[4], $p[5] );
2777 throw new MWException( "Too many arguments to construtor in wfCreateObject" );
2781 function wfHttpOnlySafe() {
2782 global $wgHttpOnlyBlacklist;
2783 if( !version_compare("5.2", PHP_VERSION
, "<") )
2786 if( isset( $_SERVER['HTTP_USER_AGENT'] ) ) {
2787 foreach( $wgHttpOnlyBlacklist as $regex ) {
2788 if( preg_match( $regex, $_SERVER['HTTP_USER_AGENT'] ) ) {
2798 * Initialise php session
2800 function wfSetupSession() {
2801 global $wgSessionsInMemcached, $wgCookiePath, $wgCookieDomain,
2802 $wgCookieSecure, $wgCookieHttpOnly, $wgSessionHandler;
2803 if( $wgSessionsInMemcached ) {
2804 require_once( 'MemcachedSessions.php' );
2805 } elseif( $wgSessionHandler && $wgSessionHandler != ini_get( 'session.save_handler' ) ) {
2806 # Only set this if $wgSessionHandler isn't null and session.save_handler
2807 # hasn't already been set to the desired value (that causes errors)
2808 ini_set ( 'session.save_handler', $wgSessionHandler );
2810 $httpOnlySafe = wfHttpOnlySafe();
2811 wfDebugLog( 'cookie',
2812 'session_set_cookie_params: "' . implode( '", "',
2818 $httpOnlySafe && $wgCookieHttpOnly ) ) . '"' );
2819 if( $httpOnlySafe && $wgCookieHttpOnly ) {
2820 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookieHttpOnly );
2822 // PHP 5.1 throws warnings if you pass the HttpOnly parameter for 5.2.
2823 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
2825 session_cache_limiter( 'private, must-revalidate' );
2826 wfSuppressWarnings();
2828 wfRestoreWarnings();
2832 * Get an object from the precompiled serialized directory
2834 * @return Mixed: the variable on success, false on failure
2836 function wfGetPrecompiledData( $name ) {
2839 $file = "$IP/serialized/$name";
2840 if ( file_exists( $file ) ) {
2841 $blob = file_get_contents( $file );
2843 return unserialize( $blob );
2849 function wfGetCaller( $level = 2 ) {
2850 $backtrace = wfDebugBacktrace();
2851 if ( isset( $backtrace[$level] ) ) {
2852 return wfFormatStackFrame($backtrace[$level]);
2854 $caller = 'unknown';
2860 * Return a string consisting of callers in the stack. Useful sometimes
2861 * for profiling specific points.
2863 * @param $limit The maximum depth of the stack frame to return, or false for
2866 function wfGetAllCallers( $limit = 3 ) {
2867 $trace = array_reverse( wfDebugBacktrace() );
2868 if ( !$limit ||
$limit > count( $trace ) - 1 ) {
2869 $limit = count( $trace ) - 1;
2871 $trace = array_slice( $trace, -$limit - 1, $limit );
2872 return implode( '/', array_map( 'wfFormatStackFrame', $trace ) );
2876 * Return a string representation of frame
2878 function wfFormatStackFrame($frame) {
2879 return isset( $frame["class"] )?
2880 $frame["class"]."::".$frame["function"]:
2887 function wfMemcKey( /*... */ ) {
2888 $args = func_get_args();
2889 $key = wfWikiID() . ':' . implode( ':', $args );
2890 $key = str_replace( ' ', '_', $key );
2895 * Get a cache key for a foreign DB
2897 function wfForeignMemcKey( $db, $prefix /*, ... */ ) {
2898 $args = array_slice( func_get_args(), 2 );
2900 $key = "$db-$prefix:" . implode( ':', $args );
2902 $key = $db . ':' . implode( ':', $args );
2908 * Get an ASCII string identifying this wiki
2909 * This is used as a prefix in memcached keys
2911 function wfWikiID() {
2912 global $wgDBprefix, $wgDBname;
2913 if ( $wgDBprefix ) {
2914 return "$wgDBname-$wgDBprefix";
2921 * Split a wiki ID into DB name and table prefix
2923 function wfSplitWikiID( $wiki ) {
2924 $bits = explode( '-', $wiki, 2 );
2925 if ( count( $bits ) < 2 ) {
2932 * Get a Database object.
2933 * @param $db Integer: index of the connection to get. May be DB_MASTER for the
2934 * master (for write queries), DB_SLAVE for potentially lagged read
2935 * queries, or an integer >= 0 for a particular server.
2937 * @param $groups Mixed: query groups. An array of group names that this query
2938 * belongs to. May contain a single string if the query is only
2941 * @param $wiki String: the wiki ID, or false for the current wiki
2943 * Note: multiple calls to wfGetDB(DB_SLAVE) during the course of one request
2944 * will always return the same object, unless the underlying connection or load
2945 * balancer is manually destroyed.
2947 function &wfGetDB( $db, $groups = array(), $wiki = false ) {
2948 return wfGetLB( $wiki )->getConnection( $db, $groups, $wiki );
2952 * Get a load balancer object.
2954 * @param $wiki String: wiki ID, or false for the current wiki
2955 * @return LoadBalancer
2957 function wfGetLB( $wiki = false ) {
2958 return wfGetLBFactory()->getMainLB( $wiki );
2962 * Get the load balancer factory object
2964 function &wfGetLBFactory() {
2965 return LBFactory
::singleton();
2970 * Shortcut for RepoGroup::singleton()->findFile()
2971 * @param $title Either a string or Title object
2972 * @param $options Associative array of options:
2973 * time: requested time for an archived image, or false for the
2974 * current version. An image object will be returned which was
2975 * created at the specified time.
2977 * ignoreRedirect: If true, do not follow file redirects
2979 * private: If true, return restricted (deleted) files if the current
2980 * user is allowed to view them. Otherwise, such files will not
2983 * bypassCache: If true, do not use the process-local cache of File objects
2985 * @return File, or false if the file does not exist
2987 function wfFindFile( $title, $options = array() ) {
2988 return RepoGroup
::singleton()->findFile( $title, $options );
2992 * Get an object referring to a locally registered file.
2993 * Returns a valid placeholder object if the file does not exist.
2994 * @param $title Either a string or Title object
2995 * @return File, or null if passed an invalid Title
2997 function wfLocalFile( $title ) {
2998 return RepoGroup
::singleton()->getLocalRepo()->newFile( $title );
3002 * Should low-performance queries be disabled?
3006 function wfQueriesMustScale() {
3007 global $wgMiserMode;
3009 ||
( SiteStats
::pages() > 100000
3010 && SiteStats
::edits() > 1000000
3011 && SiteStats
::users() > 10000 );
3015 * Get the path to a specified script file, respecting file
3016 * extensions; this is a wrapper around $wgScriptExtension etc.
3018 * @param $script String: script filename, sans extension
3021 function wfScript( $script = 'index' ) {
3022 global $wgScriptPath, $wgScriptExtension;
3023 return "{$wgScriptPath}/{$script}{$wgScriptExtension}";
3026 * Get the script url.
3028 * @return script url
3030 function wfGetScriptUrl(){
3031 if( isset( $_SERVER['SCRIPT_NAME'] ) ) {
3033 # as it was called, minus the query string.
3035 # Some sites use Apache rewrite rules to handle subdomains,
3036 # and have PHP set up in a weird way that causes PHP_SELF
3037 # to contain the rewritten URL instead of the one that the
3038 # outside world sees.
3040 # If in this mode, use SCRIPT_URL instead, which mod_rewrite
3041 # provides containing the "before" URL.
3042 return $_SERVER['SCRIPT_NAME'];
3044 return $_SERVER['URL'];
3049 * Convenience function converts boolean values into "true"
3050 * or "false" (string) values
3052 * @param $value Boolean
3055 function wfBoolToStr( $value ) {
3056 return $value ?
'true' : 'false';
3060 * Load an extension messages file
3061 * @deprecated in 1.16 (warnings in 1.18, removed in ?)
3063 function wfLoadExtensionMessages( $extensionName, $langcode = false ) {
3067 * Get a platform-independent path to the null file, e.g.
3072 function wfGetNull() {
3073 return wfIsWindows()
3079 * Displays a maxlag error
3081 * @param $host String: server that lags the most
3082 * @param $lag Integer: maxlag (actual)
3083 * @param $maxLag Integer: maxlag (requested)
3085 function wfMaxlagError( $host, $lag, $maxLag ) {
3086 global $wgShowHostnames;
3087 header( 'HTTP/1.1 503 Service Unavailable' );
3088 header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
3089 header( 'X-Database-Lag: ' . intval( $lag ) );
3090 header( 'Content-Type: text/plain' );
3091 if( $wgShowHostnames ) {
3092 echo "Waiting for $host: $lag seconds lagged\n";
3094 echo "Waiting for a database server: $lag seconds lagged\n";
3099 * Throws a warning that $function is deprecated
3100 * @param $function String
3103 function wfDeprecated( $function ) {
3104 static $functionsWarned = array();
3105 if ( !isset( $functionsWarned[$function] ) ) {
3106 $functionsWarned[$function] = true;
3107 wfWarn( "Use of $function is deprecated.", 2 );
3112 * Send a warning either to the debug log or in a PHP error depending on
3113 * $wgDevelopmentWarnings
3115 * @param $msg String: message to send
3116 * @param $callerOffset Integer: number of itmes to go back in the backtrace to
3117 * find the correct caller (1 = function calling wfWarn, ...)
3118 * @param $level Integer: PHP error level; only used when $wgDevelopmentWarnings
3121 function wfWarn( $msg, $callerOffset = 1, $level = E_USER_NOTICE
) {
3122 $callers = wfDebugBacktrace();
3123 if( isset( $callers[$callerOffset+
1] ) ){
3124 $callerfunc = $callers[$callerOffset+
1];
3125 $callerfile = $callers[$callerOffset];
3126 if( isset( $callerfile['file'] ) && isset( $callerfile['line'] ) ){
3127 $file = $callerfile['file'] . ' at line ' . $callerfile['line'];
3129 $file = '(internal function)';
3132 if( isset( $callerfunc['class'] ) )
3133 $func .= $callerfunc['class'] . '::';
3134 $func .= @$callerfunc['function'];
3135 $msg .= " [Called from $func in $file]";
3138 global $wgDevelopmentWarnings;
3139 if ( $wgDevelopmentWarnings ) {
3140 trigger_error( $msg, $level );
3142 wfDebug( "$msg\n" );
3147 * Sleep until the worst slave's replication lag is less than or equal to
3148 * $maxLag, in seconds. Use this when updating very large numbers of rows, as
3149 * in maintenance scripts, to avoid causing too much lag. Of course, this is
3150 * a no-op if there are no slaves.
3152 * Every time the function has to wait for a slave, it will print a message to
3153 * that effect (and then sleep for a little while), so it's probably not best
3154 * to use this outside maintenance scripts in its present form.
3156 * @param $maxLag Integer
3157 * @param $wiki mixed Wiki identifier accepted by wfGetLB
3160 function wfWaitForSlaves( $maxLag, $wiki = false ) {
3162 $lb = wfGetLB( $wiki );
3163 list( $host, $lag ) = $lb->getMaxLag( $wiki );
3164 while( $lag > $maxLag ) {
3165 $name = @gethostbyaddr
( $host );
3166 if( $name !== false ) {
3169 print "Waiting for $host (lagged $lag seconds)...\n";
3171 list( $host, $lag ) = $lb->getMaxLag();
3177 * Output some plain text in command-line mode or in the installer (updaters.inc).
3178 * Do not use it in any other context, its behaviour is subject to change.
3180 function wfOut( $s ) {
3181 static $lineStarted = false;
3182 global $wgCommandLineMode;
3183 if ( $wgCommandLineMode && !defined( 'MEDIAWIKI_INSTALL' ) ) {
3186 echo htmlspecialchars( $s );
3192 * Count down from $n to zero on the terminal, with a one-second pause
3193 * between showing each number. For use in command-line scripts.
3195 function wfCountDown( $n ) {
3196 for ( $i = $n; $i >= 0; $i-- ) {
3198 echo str_repeat( "\x08", strlen( $i +
1 ) );
3209 /** Generate a random 32-character hexadecimal token.
3210 * @param $salt Mixed: some sort of salt, if necessary, to add to random
3211 * characters before hashing.
3213 function wfGenerateToken( $salt = '' ) {
3214 $salt = serialize($salt);
3216 return md5( mt_rand( 0, 0x7fffffff ) . $salt );
3220 * Replace all invalid characters with -
3221 * @param $name Mixed: filename to process
3223 function wfStripIllegalFilenameChars( $name ) {
3224 global $wgIllegalFileChars;
3225 $name = wfBaseName( $name );
3226 $name = preg_replace("/[^".Title
::legalChars()."]".($wgIllegalFileChars ?
"|[".$wgIllegalFileChars."]":"")."/",'-',$name);
3231 * Insert array into another array after the specified *KEY*
3232 * @param $array Array: The array.
3233 * @param $insert Array: The array to insert.
3234 * @param $after Mixed: The key to insert after
3236 function wfArrayInsertAfter( $array, $insert, $after ) {
3237 // Find the offset of the element to insert after.
3238 $keys = array_keys($array);
3239 $offsetByKey = array_flip( $keys );
3241 $offset = $offsetByKey[$after];
3243 // Insert at the specified offset
3244 $before = array_slice( $array, 0, $offset +
1, true );
3245 $after = array_slice( $array, $offset +
1, count($array)-$offset, true );
3247 $output = $before +
$insert +
$after;
3252 /* Recursively converts the parameter (an object) to an array with the same data */
3253 function wfObjectToArray( $object, $recursive = true ) {
3255 foreach ( get_object_vars($object) as $key => $value ) {
3256 if ( is_object($value) && $recursive ) {
3257 $value = wfObjectToArray( $value );
3260 $array[$key] = $value;
3267 * Set PHP's memory limit to the larger of php.ini or $wgMemoryLimit;
3268 * @return Integer value memory was set to.
3271 function wfMemoryLimit () {
3272 global $wgMemoryLimit;
3273 $memlimit = wfShorthandToInteger( ini_get( "memory_limit" ) );
3274 $conflimit = wfShorthandToInteger( $wgMemoryLimit );
3275 if( $memlimit != -1 ) {
3276 if( $conflimit == -1 ) {
3277 wfDebug( "Removing PHP's memory limit\n" );
3278 wfSuppressWarnings();
3279 ini_set( "memory_limit", $conflimit );
3280 wfRestoreWarnings();
3282 } elseif ( $conflimit > $memlimit ) {
3283 wfDebug( "Raising PHP's memory limit to $conflimit bytes\n" );
3284 wfSuppressWarnings();
3285 ini_set( "memory_limit", $conflimit );
3286 wfRestoreWarnings();
3294 * Converts shorthand byte notation to integer form
3295 * @param $string String
3298 function wfShorthandToInteger ( $string = '' ) {
3299 $string = trim($string);
3300 if( empty($string) ) { return -1; }
3301 $last = strtolower($string[strlen($string)-1]);
3302 $val = intval($string);
3315 /* Get the normalised IETF language tag
3316 * @param $code String: The language code.
3317 * @return $langCode String: The language code which complying with BCP 47 standards.
3319 function wfBCP47( $code ) {
3320 $codeSegment = explode( '-', $code );
3321 foreach ( $codeSegment as $segNo => $seg ) {
3322 if ( count( $codeSegment ) > 0 ) {
3323 // ISO 3166 country code
3324 if ( ( strlen( $seg ) == 2 ) && ( $segNo > 0 ) )
3325 $codeBCP[$segNo] = strtoupper( $seg );
3326 // ISO 15924 script code
3327 else if ( ( strlen( $seg ) == 4 ) && ( $segNo > 0 ) )
3328 $codeBCP[$segNo] = ucfirst( $seg );
3329 // Use lowercase for other cases
3331 $codeBCP[$segNo] = strtolower( $seg );
3333 // Use lowercase for single segment
3334 $codeBCP[$segNo] = strtolower( $seg );
3337 $langCode = implode ( '-' , $codeBCP );
3341 function wfArrayMap( $function, $input ) {
3342 $ret = array_map( $function, $input );
3343 foreach ( $ret as $key => $value ) {
3344 $taint = istainted( $input[$key] );
3346 taint( $ret[$key], $taint );