3 * Global functions used everywhere
7 if ( !defined( 'MEDIAWIKI' ) ) {
8 die( "This file is part of MediaWiki, it is not a valid entry point" );
11 require_once dirname(__FILE__
) . '/normal/UtfNormalUtil.php';
13 // Hide compatibility functions from Doxygen
17 * Compatibility functions
19 * We 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 ( substr( $to, -8 ) == '//IGNORE' ) $to = substr( $to, 0, strlen( $to ) - 8 );
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 // Support for Wietse Venema's taint feature
177 if ( !function_exists( 'istainted' ) ) {
178 function istainted( $var ) {
181 function taint( $var, $level = 0 ) {}
182 function untaint( $var, $level = 0 ) {}
183 define( 'TC_HTML', 1 );
184 define( 'TC_SHELL', 1 );
185 define( 'TC_MYSQL', 1 );
186 define( 'TC_PCRE', 1 );
187 define( 'TC_SELF', 1 );
193 * Like array_diff( $a, $b ) except that it works with two-dimensional arrays.
195 function wfArrayDiff2( $a, $b ) {
196 return array_udiff( $a, $b, 'wfArrayDiff2_cmp' );
198 function wfArrayDiff2_cmp( $a, $b ) {
199 if ( !is_array( $a ) ) {
200 return strcmp( $a, $b );
201 } elseif ( count( $a ) !== count( $b ) ) {
202 return count( $a ) < count( $b ) ?
-1 : 1;
206 while( ( list( $keyA, $valueA ) = each( $a ) ) && ( list( $keyB, $valueB ) = each( $b ) ) ) {
207 $cmp = strcmp( $valueA, $valueB );
217 * Seed Mersenne Twister
218 * No-op for compatibility; only necessary in PHP < 4.2.0
220 function wfSeedRandom() {
225 * Get a random decimal value between 0 and 1, in a way
226 * not likely to give duplicate values for any realistic
227 * number of articles.
231 function wfRandom() {
232 # The maximum random value is "only" 2^31-1, so get two random
233 # values to reduce the chance of dupes
234 $max = mt_getrandmax() +
1;
235 $rand = number_format( (mt_rand() * $max +
mt_rand())
236 / $max / $max, 12, '.', '' );
241 * We want some things to be included as literal characters in our title URLs
242 * for prettiness, which urlencode encodes by default. According to RFC 1738,
243 * all of the following should be safe:
247 * But + is not safe because it's used to indicate a space; &= are only safe in
248 * paths and not in queries (and we don't distinguish here); ' seems kind of
249 * scary; and urlencode() doesn't touch -_. to begin with. Plus, although /
250 * is reserved, we don't care. So the list we unescape is:
254 * However, IIS7 redirects fail when the url contains a colon (Bug 22709),
255 * so no fancy : for IIS7.
257 * %2F in the page titles seems to fatally break for some reason.
262 function wfUrlencode( $s ) {
264 if ( is_null( $needle ) ) {
265 $needle = array( '%3B','%40','%24','%21','%2A','%28','%29','%2C','%2F' );
266 if (! isset($_SERVER['SERVER_SOFTWARE']) ||
( strpos($_SERVER['SERVER_SOFTWARE'], "Microsoft-IIS/7") === false)) {
271 $s = urlencode( $s );
274 array( ';', '@', '$', '!', '*', '(', ')', ',', '/', ':' ),
282 * Sends a line to the debug log if enabled or, optionally, to a comment in output.
283 * In normal operation this is a NOP.
285 * Controlling globals:
286 * $wgDebugLogFile - points to the log file
287 * $wgProfileOnly - if set, normal debug messages will not be recorded.
288 * $wgDebugRawPage - if false, 'action=raw' hits will not result in debug output.
289 * $wgDebugComments - if on, some debug items may appear in comments in the HTML output.
291 * @param $text String
292 * @param $logonly Bool: set true to avoid appearing in HTML when $wgDebugComments is set
294 function wfDebug( $text, $logonly = false ) {
295 global $wgOut, $wgDebugLogFile, $wgDebugComments, $wgProfileOnly, $wgDebugRawPage;
296 global $wgDebugLogPrefix, $wgShowDebug;
297 static $recursion = 0;
299 static $cache = array(); // Cache of unoutputted messages
300 $text = wfDebugTimer() . $text;
302 # Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
303 if ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' && !$wgDebugRawPage ) {
307 if ( ( $wgDebugComments ||
$wgShowDebug ) && !$logonly ) {
310 if ( !isset( $wgOut ) ) {
313 if ( !StubObject
::isRealObject( $wgOut ) ) {
322 // add the message and possible cached ones to the output
323 array_map( array( $wgOut, 'debug' ), $cache );
326 if ( $wgDebugLogFile != '' && !$wgProfileOnly ) {
327 # Strip unprintables; they can switch terminal modes when binary data
328 # gets dumped, which is pretty annoying.
329 $text = preg_replace( '![\x00-\x08\x0b\x0c\x0e-\x1f]!', ' ', $text );
330 $text = $wgDebugLogPrefix . $text;
331 wfErrorLog( $text, $wgDebugLogFile );
335 function wfDebugTimer() {
336 global $wgDebugTimestamps;
337 if ( !$wgDebugTimestamps ) return '';
338 static $start = null;
340 if ( $start === null ) {
341 $start = microtime( true );
342 $prefix = "\n$start";
344 $prefix = sprintf( "%6.4f", microtime( true ) - $start );
347 return $prefix . ' ';
351 * Send a line giving PHP memory usage.
352 * @param $exact Bool: print exact values instead of kilobytes (default: false)
354 function wfDebugMem( $exact = false ) {
355 $mem = memory_get_usage();
357 $mem = floor( $mem / 1024 ) . ' kilobytes';
361 wfDebug( "Memory usage: $mem\n" );
365 * Send a line to a supplementary debug log file, if configured, or main debug log if not.
366 * $wgDebugLogGroups[$logGroup] should be set to a filename to send to a separate log.
368 * @param $logGroup String
369 * @param $text String
370 * @param $public Bool: whether to log the event in the public log if no private
371 * log file is specified, (default true)
373 function wfDebugLog( $logGroup, $text, $public = true ) {
374 global $wgDebugLogGroups, $wgShowHostnames;
375 $text = trim($text)."\n";
376 if( isset( $wgDebugLogGroups[$logGroup] ) ) {
377 $time = wfTimestamp( TS_DB
);
379 if ( $wgShowHostnames ) {
380 $host = wfHostname();
384 wfErrorLog( "$time $host $wiki: $text", $wgDebugLogGroups[$logGroup] );
385 } else if ( $public === true ) {
386 wfDebug( $text, true );
391 * Log for database errors
392 * @param $text String: database error message.
394 function wfLogDBError( $text ) {
395 global $wgDBerrorLog, $wgDBname;
396 if ( $wgDBerrorLog ) {
397 $host = trim(`hostname`
);
398 $text = date('D M j G:i:s T Y') . "\t$host\t$wgDBname\t$text";
399 wfErrorLog( $text, $wgDBerrorLog );
404 * Log to a file without getting "file size exceeded" signals.
406 * Can also log to TCP or UDP with the syntax udp://host:port/prefix. This will
407 * send lines to the specified port, prefixed by the specified prefix and a space.
409 function wfErrorLog( $text, $file ) {
410 if ( substr( $file, 0, 4 ) == 'udp:' ) {
411 # Needs the sockets extension
412 if ( preg_match( '!^(tcp|udp):(?://)?\[([0-9a-fA-F:]+)\]:(\d+)(?:/(.*))?$!', $file, $m ) ) {
413 // IPv6 bracketed host
416 $port = intval( $m[3] );
417 $prefix = isset( $m[4] ) ?
$m[4] : false;
419 } elseif ( preg_match( '!^(tcp|udp):(?://)?([a-zA-Z0-9.-]+):(\d+)(?:/(.*))?$!', $file, $m ) ) {
422 if ( !IP
::isIPv4( $host ) ) {
423 $host = gethostbyname( $host );
425 $port = intval( $m[3] );
426 $prefix = isset( $m[4] ) ?
$m[4] : false;
429 throw new MWException( __METHOD__
.": Invalid UDP specification" );
431 // Clean it up for the multiplexer
432 if ( strval( $prefix ) !== '' ) {
433 $text = preg_replace( '/^/m', $prefix . ' ', $text );
434 if ( substr( $text, -1 ) != "\n" ) {
439 $sock = socket_create( $domain, SOCK_DGRAM
, SOL_UDP
);
443 socket_sendto( $sock, $text, strlen( $text ), 0, $host, $port );
444 socket_close( $sock );
446 wfSuppressWarnings();
447 $exists = file_exists( $file );
448 $size = $exists ?
filesize( $file ) : false;
449 if ( !$exists ||
( $size !== false && $size +
strlen( $text ) < 0x7fffffff ) ) {
450 error_log( $text, 3, $file );
459 function wfLogProfilingData() {
460 global $wgRequestTime, $wgDebugLogFile, $wgDebugRawPage, $wgRequest;
461 global $wgProfiler, $wgProfileLimit, $wgUser;
462 # Profiling must actually be enabled...
463 if( is_null( $wgProfiler ) ) return;
464 # Get total page request time
466 $elapsed = $now - $wgRequestTime;
467 # Only show pages that longer than $wgProfileLimit time (default is 0)
468 if( $elapsed <= $wgProfileLimit ) return;
469 $prof = wfGetProfilingOutput( $wgRequestTime, $elapsed );
471 if( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) )
472 $forward = ' forwarded for ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
473 if( !empty( $_SERVER['HTTP_CLIENT_IP'] ) )
474 $forward .= ' client IP ' . $_SERVER['HTTP_CLIENT_IP'];
475 if( !empty( $_SERVER['HTTP_FROM'] ) )
476 $forward .= ' from ' . $_SERVER['HTTP_FROM'];
478 $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
479 // Don't unstub $wgUser at this late stage just for statistics purposes
480 if( StubObject
::isRealObject($wgUser) && $wgUser->isAnon() )
482 $log = sprintf( "%s\t%04.3f\t%s\n",
483 gmdate( 'YmdHis' ), $elapsed,
484 urldecode( $wgRequest->getRequestURL() . $forward ) );
485 if ( $wgDebugLogFile != '' && ( $wgRequest->getVal('action') != 'raw' ||
$wgDebugRawPage ) ) {
486 wfErrorLog( $log . $prof, $wgDebugLogFile );
491 * Check if the wiki read-only lock file is present. This can be used to lock
492 * off editing functions, but doesn't guarantee that the database will not be
496 function wfReadOnly() {
497 global $wgReadOnlyFile, $wgReadOnly;
499 if ( !is_null( $wgReadOnly ) ) {
500 return (bool)$wgReadOnly;
502 if ( $wgReadOnlyFile == '' ) {
505 // Set $wgReadOnly for faster access next time
506 if ( is_file( $wgReadOnlyFile ) ) {
507 $wgReadOnly = file_get_contents( $wgReadOnlyFile );
511 return (bool)$wgReadOnly;
514 function wfReadOnlyReason() {
521 * Return a Language object from $langcode
522 * @param $langcode Mixed: either:
523 * - a Language object
524 * - code of the language to get the message for, if it is
525 * a valid code create a language for that language, if
526 * it is a string but not a valid code then make a basic
528 * - a boolean: if it's false then use the current users
529 * language (as a fallback for the old parameter
530 * functionality), or if it is true then use the wikis
531 * @return Language object
533 function wfGetLangObj( $langcode = false ) {
534 # Identify which language to get or create a language object for.
535 # Using is_object here due to Stub objects.
536 if( is_object( $langcode ) ) {
537 # Great, we already have the object (hopefully)!
541 global $wgContLang, $wgLanguageCode;
542 if( $langcode === true ||
$langcode === $wgLanguageCode ) {
543 # $langcode is the language code of the wikis content language object.
544 # or it is a boolean and value is true
549 if( $langcode === false ||
$langcode === $wgLang->getCode() ) {
550 # $langcode is the language code of user language object.
551 # or it was a boolean and value is false
555 $validCodes = array_keys( Language
::getLanguageNames() );
556 if( in_array( $langcode, $validCodes ) ) {
557 # $langcode corresponds to a valid language.
558 return Language
::factory( $langcode );
561 # $langcode is a string, but not a valid language code; use content language.
562 wfDebug( "Invalid language code passed to wfGetLangObj, falling back to content language.\n" );
566 function wfUILang() {
567 global $wgBetterDirectionality;
568 return wfGetLangObj( $wgBetterDirectionality ?
false: true );
572 * Get a message from anywhere, for the current user language.
574 * Use wfMsgForContent() instead if the message should NOT
575 * change depending on the user preferences.
577 * @param $key String: lookup key for the message, usually
578 * defined in languages/Language.php
580 * This function also takes extra optional parameters (not
581 * shown in the function definition), which can by used to
582 * insert variable text into the predefined message.
584 function wfMsg( $key ) {
585 $args = func_get_args();
586 array_shift( $args );
587 return wfMsgReal( $key, $args, true );
591 * Same as above except doesn't transform the message
593 function wfMsgNoTrans( $key ) {
594 $args = func_get_args();
595 array_shift( $args );
596 return wfMsgReal( $key, $args, true, false, false );
600 * Get a message from anywhere, for the current global language
601 * set with $wgLanguageCode.
603 * Use this if the message should NOT change dependent on the
604 * language set in the user's preferences. This is the case for
605 * most text written into logs, as well as link targets (such as
606 * the name of the copyright policy page). Link titles, on the
607 * other hand, should be shown in the UI language.
609 * Note that MediaWiki allows users to change the user interface
610 * language in their preferences, but a single installation
611 * typically only contains content in one language.
613 * Be wary of this distinction: If you use wfMsg() where you should
614 * use wfMsgForContent(), a user of the software may have to
615 * customize potentially hundreds of messages in
616 * order to, e.g., fix a link in every possible language.
618 * @param $key String: lookup key for the message, usually
619 * defined in languages/Language.php
621 function wfMsgForContent( $key ) {
622 global $wgForceUIMsgAsContentMsg;
623 $args = func_get_args();
624 array_shift( $args );
626 if( is_array( $wgForceUIMsgAsContentMsg ) &&
627 in_array( $key, $wgForceUIMsgAsContentMsg ) )
629 return wfMsgReal( $key, $args, true, $forcontent );
633 * Same as above except doesn't transform the message
635 function wfMsgForContentNoTrans( $key ) {
636 global $wgForceUIMsgAsContentMsg;
637 $args = func_get_args();
638 array_shift( $args );
640 if( is_array( $wgForceUIMsgAsContentMsg ) &&
641 in_array( $key, $wgForceUIMsgAsContentMsg ) )
643 return wfMsgReal( $key, $args, true, $forcontent, false );
647 * Get a message from the language file, for the UI elements
649 function wfMsgNoDB( $key ) {
650 $args = func_get_args();
651 array_shift( $args );
652 return wfMsgReal( $key, $args, false );
656 * Get a message from the language file, for the content
658 function wfMsgNoDBForContent( $key ) {
659 global $wgForceUIMsgAsContentMsg;
660 $args = func_get_args();
661 array_shift( $args );
663 if( is_array( $wgForceUIMsgAsContentMsg ) &&
664 in_array( $key, $wgForceUIMsgAsContentMsg ) )
666 return wfMsgReal( $key, $args, false, $forcontent );
671 * Really get a message
672 * @param $key String: key to get.
674 * @param $useDB Boolean
675 * @param $forContent Mixed: Language code, or false for user lang, true for content lang.
676 * @param $transform Boolean: Whether or not to transform the message.
677 * @return String: the requested message.
679 function wfMsgReal( $key, $args, $useDB = true, $forContent = false, $transform = true ) {
680 wfProfileIn( __METHOD__
);
681 $message = wfMsgGetKey( $key, $useDB, $forContent, $transform );
682 $message = wfMsgReplaceArgs( $message, $args );
683 wfProfileOut( __METHOD__
);
688 * This function provides the message source for messages to be edited which are *not* stored in the database.
689 * @param $key String:
691 function wfMsgWeirdKey( $key ) {
692 $source = wfMsgGetKey( $key, false, true, false );
693 if ( wfEmptyMsg( $key, $source ) )
700 * Fetch a message string value, but don't replace any keys yet.
703 * @param $langCode String: Code of the language to get the message for, or
704 * behaves as a content language switch if it is a boolean.
705 * @param $transform Boolean: whether to parse magic words, etc.
708 function wfMsgGetKey( $key, $useDB, $langCode = false, $transform = true ) {
709 global $wgMessageCache;
711 wfRunHooks('NormalizeMessageKey', array(&$key, &$useDB, &$langCode, &$transform));
713 if ( !is_object( $wgMessageCache ) ) {
714 throw new MWException( "Trying to get message before message cache is initialised" );
717 $message = $wgMessageCache->get( $key, $useDB, $langCode );
718 if( $message === false ){
719 $message = '<' . htmlspecialchars( $key ) . '>';
720 } elseif ( $transform ) {
721 $message = $wgMessageCache->transform( $message );
727 * Replace message parameter keys on the given formatted output.
729 * @param $message String
734 function wfMsgReplaceArgs( $message, $args ) {
735 # Fix windows line-endings
736 # Some messages are split with explode("\n", $msg)
737 $message = str_replace( "\r", '', $message );
740 if ( count( $args ) ) {
741 if ( is_array( $args[0] ) ) {
742 $args = array_values( $args[0] );
744 $replacementKeys = array();
745 foreach( $args as $n => $param ) {
746 $replacementKeys['$' . ($n +
1)] = $param;
748 $message = strtr( $message, $replacementKeys );
755 * Return an HTML-escaped version of a message.
756 * Parameter replacements, if any, are done *after* the HTML-escaping,
757 * so parameters may contain HTML (eg links or form controls). Be sure
758 * to pre-escape them if you really do want plaintext, or just wrap
759 * the whole thing in htmlspecialchars().
762 * @param string ... parameters
765 function wfMsgHtml( $key ) {
766 $args = func_get_args();
767 array_shift( $args );
768 return wfMsgReplaceArgs( htmlspecialchars( wfMsgGetKey( $key, true ) ), $args );
772 * Return an HTML version of message
773 * Parameter replacements, if any, are done *after* parsing the wiki-text message,
774 * so parameters may contain HTML (eg links or form controls). Be sure
775 * to pre-escape them if you really do want plaintext, or just wrap
776 * the whole thing in htmlspecialchars().
779 * @param string ... parameters
782 function wfMsgWikiHtml( $key ) {
784 $args = func_get_args();
785 array_shift( $args );
786 return wfMsgReplaceArgs( $wgOut->parse( wfMsgGetKey( $key, true ), /* can't be set to false */ true ), $args );
790 * Returns message in the requested format
791 * @param $key String: key of the message
792 * @param $options Array: processing rules. Can take the following options:
793 * <i>parse</i>: parses wikitext to html
794 * <i>parseinline</i>: parses wikitext to html and removes the surrounding
795 * p's added by parser or tidy
796 * <i>escape</i>: filters message through htmlspecialchars
797 * <i>escapenoentities</i>: same, but allows entity references like   through
798 * <i>replaceafter</i>: parameters are substituted after parsing or escaping
799 * <i>parsemag</i>: transform the message using magic phrases
800 * <i>content</i>: fetch message for content language instead of interface
801 * Also can accept a single associative argument, of the form 'language' => 'xx':
802 * <i>language</i>: Language object or language code to fetch message for
803 * (overriden by <i>content</i>), its behaviour with parser, parseinline
804 * and parsemag is undefined.
805 * Behavior for conflicting options (e.g., parse+parseinline) is undefined.
807 function wfMsgExt( $key, $options ) {
810 $args = func_get_args();
811 array_shift( $args );
812 array_shift( $args );
813 $options = (array)$options;
815 foreach( $options as $arrayKey => $option ) {
816 if( !preg_match( '/^[0-9]+|language$/', $arrayKey ) ) {
817 # An unknown index, neither numeric nor "language"
818 wfWarn( "wfMsgExt called with incorrect parameter key $arrayKey", 1, E_USER_WARNING
);
819 } elseif( preg_match( '/^[0-9]+$/', $arrayKey ) && !in_array( $option,
820 array( 'parse', 'parseinline', 'escape', 'escapenoentities',
821 'replaceafter', 'parsemag', 'content' ) ) ) {
822 # A numeric index with unknown value
823 wfWarn( "wfMsgExt called with incorrect parameter $option", 1, E_USER_WARNING
);
827 if( in_array('content', $options, true ) ) {
830 } elseif( array_key_exists('language', $options) ) {
832 $langCode = wfGetLangObj( $options['language'] );
838 $string = wfMsgGetKey( $key, /*DB*/true, $langCode, /*Transform*/false );
840 if( !in_array('replaceafter', $options, true ) ) {
841 $string = wfMsgReplaceArgs( $string, $args );
844 if( in_array('parse', $options, true ) ) {
845 $string = $wgOut->parse( $string, true, !$forContent );
846 } elseif ( in_array('parseinline', $options, true ) ) {
847 $string = $wgOut->parse( $string, true, !$forContent );
849 if( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $string, $m ) ) {
852 } elseif ( in_array('parsemag', $options, true ) ) {
853 global $wgMessageCache;
854 if ( isset( $wgMessageCache ) ) {
855 $string = $wgMessageCache->transform( $string,
857 is_object( $langCode ) ?
$langCode : null );
861 if ( in_array('escape', $options, true ) ) {
862 $string = htmlspecialchars ( $string );
863 } elseif ( in_array( 'escapenoentities', $options, true ) ) {
864 $string = Sanitizer
::escapeHtmlAllowEntities( $string );
867 if( in_array('replaceafter', $options, true ) ) {
868 $string = wfMsgReplaceArgs( $string, $args );
876 * Just like exit() but makes a note of it.
877 * Commits open transactions except if the error parameter is set
879 * @deprecated Please return control to the caller or throw an exception
881 function wfAbruptExit( $error = false ){
882 static $called = false;
888 $bt = wfDebugBacktrace();
890 for($i = 0; $i < count($bt) ; $i++
){
891 $file = isset($bt[$i]['file']) ?
$bt[$i]['file'] : "unknown";
892 $line = isset($bt[$i]['line']) ?
$bt[$i]['line'] : "unknown";
893 wfDebug("WARNING: Abrupt exit in $file at line $line\n");
896 wfDebug("WARNING: Abrupt exit\n");
899 wfLogProfilingData();
902 wfGetLB()->closeAll();
908 * @deprecated Please return control the caller or throw an exception
910 function wfErrorExit() {
911 wfAbruptExit( true );
915 * Print a simple message and die, returning nonzero to the shell if any.
916 * Plain die() fails to return nonzero to the shell if you pass a string.
919 function wfDie( $msg='' ) {
925 * Throw a debugging exception. This function previously once exited the process,
926 * but now throws an exception instead, with similar results.
928 * @param $msg String: message shown when dieing.
930 function wfDebugDieBacktrace( $msg = '' ) {
931 throw new MWException( $msg );
935 * Fetch server name for use in error reporting etc.
936 * Use real server name if available, so we know which machine
937 * in a server farm generated the current page.
940 function wfHostname() {
942 if ( is_null( $host ) ) {
943 if ( function_exists( 'posix_uname' ) ) {
944 // This function not present on Windows
945 $uname = @posix_uname
();
949 if( is_array( $uname ) && isset( $uname['nodename'] ) ) {
950 $host = $uname['nodename'];
951 } elseif ( getenv( 'COMPUTERNAME' ) ) {
952 # Windows computer name
953 $host = getenv( 'COMPUTERNAME' );
955 # This may be a virtual server.
956 $host = $_SERVER['SERVER_NAME'];
963 * Returns a HTML comment with the elapsed time since request.
964 * This method has no side effects.
967 function wfReportTime() {
968 global $wgRequestTime, $wgShowHostnames;
971 $elapsed = $now - $wgRequestTime;
973 return $wgShowHostnames
974 ?
sprintf( "<!-- Served by %s in %01.3f secs. -->", wfHostname(), $elapsed )
975 : sprintf( "<!-- Served in %01.3f secs. -->", $elapsed );
979 * Safety wrapper for debug_backtrace().
981 * With Zend Optimizer 3.2.0 loaded, this causes segfaults under somewhat
982 * murky circumstances, which may be triggered in part by stub objects
983 * or other fancy talkin'.
985 * Will return an empty array if Zend Optimizer is detected or if
986 * debug_backtrace is disabled, otherwise the output from
987 * debug_backtrace() (trimmed).
989 * @return array of backtrace information
991 function wfDebugBacktrace() {
992 static $disabled = null;
994 if( extension_loaded( 'Zend Optimizer' ) ) {
995 wfDebug( "Zend Optimizer detected; skipping debug_backtrace for safety.\n" );
999 if ( is_null( $disabled ) ) {
1001 $functions = explode( ',', ini_get( 'disable_functions' ) );
1002 $functions = array_map( 'trim', $functions );
1003 $functions = array_map( 'strtolower', $functions );
1004 if ( in_array( 'debug_backtrace', $functions ) ) {
1005 wfDebug( "debug_backtrace is in disabled_functions\n" );
1013 return array_slice( debug_backtrace(), 1 );
1016 function wfBacktrace() {
1017 global $wgCommandLineMode;
1019 if ( $wgCommandLineMode ) {
1024 $backtrace = wfDebugBacktrace();
1025 foreach( $backtrace as $call ) {
1026 if( isset( $call['file'] ) ) {
1027 $f = explode( DIRECTORY_SEPARATOR
, $call['file'] );
1028 $file = $f[count($f)-1];
1032 if( isset( $call['line'] ) ) {
1033 $line = $call['line'];
1037 if ( $wgCommandLineMode ) {
1038 $msg .= "$file line $line calls ";
1040 $msg .= '<li>' . $file . ' line ' . $line . ' calls ';
1042 if( !empty( $call['class'] ) ) $msg .= $call['class'] . '::';
1043 $msg .= $call['function'] . '()';
1045 if ( $wgCommandLineMode ) {
1051 if ( $wgCommandLineMode ) {
1061 /* Some generic result counters, pulled out of SearchEngine */
1067 function wfShowingResults( $offset, $limit ) {
1069 return wfMsgExt( 'showingresults', array( 'parseinline' ), $wgLang->formatNum( $limit ),
1070 $wgLang->formatNum( $offset+
1 ) );
1076 function wfShowingResultsNum( $offset, $limit, $num ) {
1078 return wfMsgExt( 'showingresultsnum', array( 'parseinline' ), $wgLang->formatNum( $limit ),
1079 $wgLang->formatNum( $offset+
1 ), $wgLang->formatNum( $num ) );
1083 * Generate (prev x| next x) (20|50|100...) type links for paging
1084 * @param $offset String
1085 * @param $limit Integer
1086 * @param $link String
1087 * @param $query String: optional URL query parameter string
1088 * @param $atend Bool: optional param for specified if this is the last page
1090 function wfViewPrevNext( $offset, $limit, $link, $query = '', $atend = false ) {
1092 $fmtLimit = $wgLang->formatNum( $limit );
1093 // FIXME: Why on earth this needs one message for the text and another one for tooltip??
1094 # Get prev/next link display text
1095 $prev = wfMsgExt( 'prevn', array('parsemag','escape'), $fmtLimit );
1096 $next = wfMsgExt( 'nextn', array('parsemag','escape'), $fmtLimit );
1097 # Get prev/next link title text
1098 $pTitle = wfMsgExt( 'prevn-title', array('parsemag','escape'), $fmtLimit );
1099 $nTitle = wfMsgExt( 'nextn-title', array('parsemag','escape'), $fmtLimit );
1100 # Fetch the title object
1101 if( is_object( $link ) ) {
1104 $title = Title
::newFromText( $link );
1105 if( is_null( $title ) ) {
1109 # Make 'previous' link
1110 if( 0 != $offset ) {
1111 $po = $offset - $limit;
1113 $q = "limit={$limit}&offset={$po}";
1114 if( $query != '' ) {
1117 $plink = '<a href="' . $title->escapeLocalUrl( $q ) . "\" title=\"{$pTitle}\" class=\"mw-prevlink\">{$prev}</a>";
1122 $no = $offset +
$limit;
1123 $q = "limit={$limit}&offset={$no}";
1124 if( $query != '' ) {
1130 $nlink = '<a href="' . $title->escapeLocalUrl( $q ) . "\" title=\"{$nTitle}\" class=\"mw-nextlink\">{$next}</a>";
1132 # Make links to set number of items per page
1133 $nums = $wgLang->pipeList( array(
1134 wfNumLink( $offset, 20, $title, $query ),
1135 wfNumLink( $offset, 50, $title, $query ),
1136 wfNumLink( $offset, 100, $title, $query ),
1137 wfNumLink( $offset, 250, $title, $query ),
1138 wfNumLink( $offset, 500, $title, $query )
1140 return wfMsgHtml( 'viewprevnext', $plink, $nlink, $nums );
1144 * Generate links for (20|50|100...) items-per-page links
1145 * @param $offset String
1146 * @param $limit Integer
1147 * @param $title Title
1148 * @param $query String: optional URL query parameter string
1150 function wfNumLink( $offset, $limit, $title, $query = '' ) {
1152 if( $query == '' ) {
1157 $q .= "limit={$limit}&offset={$offset}";
1158 $fmtLimit = $wgLang->formatNum( $limit );
1159 $lTitle = wfMsgExt('shown-title',array('parsemag','escape'),$limit);
1160 $s = '<a href="' . $title->escapeLocalUrl( $q ) . "\" title=\"{$lTitle}\" class=\"mw-numlink\">{$fmtLimit}</a>";
1166 * @todo FIXME: we may want to blacklist some broken browsers
1168 * @return bool Whereas client accept gzip compression
1170 function wfClientAcceptsGzip() {
1171 if( isset( $_SERVER['HTTP_ACCEPT_ENCODING'] ) ) {
1172 # FIXME: we may want to blacklist some broken browsers
1175 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
1176 $_SERVER['HTTP_ACCEPT_ENCODING'],
1178 if( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) return false;
1179 wfDebug( " accepts gzip\n" );
1187 * Obtain the offset and limit values from the request string;
1188 * used in special pages
1190 * @param $deflimit Default limit if none supplied
1191 * @param $optionname Name of a user preference to check against
1195 function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) {
1197 return $wgRequest->getLimitOffset( $deflimit, $optionname );
1201 * Escapes the given text so that it may be output using addWikiText()
1202 * without any linking, formatting, etc. making its way through. This
1203 * is achieved by substituting certain characters with HTML entities.
1204 * As required by the callers, <nowiki> is not used. It currently does
1205 * not filter out characters which have special meaning only at the
1206 * start of a line, such as "*".
1208 * @param $text String: text to be escaped
1210 function wfEscapeWikiText( $text ) {
1211 $text = str_replace(
1212 array( '[', '|', ']', '\'', 'ISBN ', 'RFC ', '://', "\n=", '{{' ), # }}
1213 array( '[', '|', ']', ''', 'ISBN ', 'RFC ', '://', "\n=", '{{' ),
1214 htmlspecialchars($text) );
1221 function wfQuotedPrintable( $string, $charset = '' ) {
1222 # Probably incomplete; see RFC 2045
1223 if( empty( $charset ) ) {
1224 global $wgInputEncoding;
1225 $charset = $wgInputEncoding;
1227 $charset = strtoupper( $charset );
1228 $charset = str_replace( 'ISO-8859', 'ISO8859', $charset ); // ?
1230 $illegal = '\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\xff=';
1231 $replace = $illegal . '\t ?_';
1232 if( !preg_match( "/[$illegal]/", $string ) ) return $string;
1233 $out = "=?$charset?Q?";
1234 $out .= preg_replace( "/([$replace])/e", 'sprintf("=%02X",ord("$1"))', $string );
1245 return microtime(true);
1249 * Sets dest to source and returns the original value of dest
1250 * If source is NULL, it just returns the value, it doesn't set the variable
1252 function wfSetVar( &$dest, $source ) {
1254 if ( !is_null( $source ) ) {
1261 * As for wfSetVar except setting a bit
1263 function wfSetBit( &$dest, $bit, $state = true ) {
1264 $temp = (bool)($dest & $bit );
1265 if ( !is_null( $state ) ) {
1276 * This function takes two arrays as input, and returns a CGI-style string, e.g.
1277 * "days=7&limit=100". Options in the first array override options in the second.
1278 * Options set to "" will not be output.
1280 function wfArrayToCGI( $array1, $array2 = null )
1282 if ( !is_null( $array2 ) ) {
1283 $array1 = $array1 +
$array2;
1287 foreach ( $array1 as $key => $value ) {
1288 if ( $value !== '' ) {
1292 if ( is_array( $value ) ) {
1294 foreach ( $value as $v ) {
1295 $cgi .= ( $firstTime ?
'' : '&') .
1296 urlencode( $key . '[]' ) . '=' .
1301 if ( is_object( $value ) ) {
1302 $value = $value->__toString();
1304 $cgi .= urlencode( $key ) . '=' .
1305 urlencode( $value );
1313 * This is the logical opposite of wfArrayToCGI(): it accepts a query string as
1314 * its argument and returns the same string in array form. This allows compa-
1315 * tibility with legacy functions that accept raw query strings instead of nice
1316 * arrays. Of course, keys and values are urldecode()d. Don't try passing in-
1317 * valid query strings, or it will explode.
1319 * @param $query String: query string
1320 * @return array Array version of input
1322 function wfCgiToArray( $query ) {
1323 if( isset( $query[0] ) and $query[0] == '?' ) {
1324 $query = substr( $query, 1 );
1326 $bits = explode( '&', $query );
1328 foreach( $bits as $bit ) {
1332 list( $key, $value ) = explode( '=', $bit );
1333 $key = urldecode( $key );
1334 $value = urldecode( $value );
1335 $ret[$key] = $value;
1341 * Append a query string to an existing URL, which may or may not already
1342 * have query string parameters already. If so, they will be combined.
1344 * @param $url String
1345 * @param $query Mixed: string or associative array
1348 function wfAppendQuery( $url, $query ) {
1349 if ( is_array( $query ) ) {
1350 $query = wfArrayToCGI( $query );
1352 if( $query != '' ) {
1353 if( false === strpos( $url, '?' ) ) {
1364 * Expand a potentially local URL to a fully-qualified URL. Assumes $wgServer
1365 * and $wgProto are correct.
1367 * @todo this won't work with current-path-relative URLs
1368 * like "subdir/foo.html", etc.
1370 * @param $url String: either fully-qualified or a local path + query
1371 * @return string Fully-qualified URL
1373 function wfExpandUrl( $url ) {
1374 if( substr( $url, 0, 2 ) == '//' ) {
1376 return $wgProto . ':' . $url;
1377 } elseif( substr( $url, 0, 1 ) == '/' ) {
1379 return $wgServer . $url;
1386 * This is obsolete, use SquidUpdate::purge()
1389 function wfPurgeSquidServers ($urlArr) {
1390 SquidUpdate
::purge( $urlArr );
1394 * Windows-compatible version of escapeshellarg()
1395 * Windows doesn't recognise single-quotes in the shell, but the escapeshellarg()
1396 * function puts single quotes in regardless of OS.
1398 * Also fixes the locale problems on Linux in PHP 5.2.6+ (bug backported to
1399 * earlier distro releases of PHP)
1401 function wfEscapeShellArg( ) {
1402 wfInitShellLocale();
1404 $args = func_get_args();
1407 foreach ( $args as $arg ) {
1414 if ( wfIsWindows() ) {
1415 // Escaping for an MSVC-style command line parser
1416 // Ref: http://mailman.lyra.org/pipermail/scite-interest/2002-March/000436.html
1417 // Double the backslashes before any double quotes. Escape the double quotes.
1418 $tokens = preg_split( '/(\\\\*")/', $arg, -1, PREG_SPLIT_DELIM_CAPTURE
);
1421 foreach ( $tokens as $token ) {
1422 if ( $iteration %
2 == 1 ) {
1423 // Delimiter, a double quote preceded by zero or more slashes
1424 $arg .= str_replace( '\\', '\\\\', substr( $token, 0, -1 ) ) . '\\"';
1425 } else if ( $iteration %
4 == 2 ) {
1426 // ^ in $token will be outside quotes, need to be escaped
1427 $arg .= str_replace( '^', '^^', $token );
1428 } else { // $iteration % 4 == 0
1429 // ^ in $token will appear inside double quotes, so leave as is
1434 // Double the backslashes before the end of the string, because
1435 // we will soon add a quote
1437 if ( preg_match( '/^(.*?)(\\\\+)$/', $arg, $m ) ) {
1438 $arg = $m[1] . str_replace( '\\', '\\\\', $m[2] );
1441 // Add surrounding quotes
1442 $retVal .= '"' . $arg . '"';
1444 $retVal .= escapeshellarg( $arg );
1451 * wfMerge attempts to merge differences between three texts.
1452 * Returns true for a clean merge and false for failure or a conflict.
1454 function wfMerge( $old, $mine, $yours, &$result ){
1457 # This check may also protect against code injection in
1458 # case of broken installations.
1459 if( !$wgDiff3 ||
!file_exists( $wgDiff3 ) ) {
1460 wfDebug( "diff3 not found\n" );
1464 # Make temporary files
1466 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
1467 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
1468 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
1470 fwrite( $oldtextFile, $old ); fclose( $oldtextFile );
1471 fwrite( $mytextFile, $mine ); fclose( $mytextFile );
1472 fwrite( $yourtextFile, $yours ); fclose( $yourtextFile );
1474 # Check for a conflict
1475 $cmd = $wgDiff3 . ' -a --overlap-only ' .
1476 wfEscapeShellArg( $mytextName ) . ' ' .
1477 wfEscapeShellArg( $oldtextName ) . ' ' .
1478 wfEscapeShellArg( $yourtextName );
1479 $handle = popen( $cmd, 'r' );
1481 if( fgets( $handle, 1024 ) ){
1489 $cmd = $wgDiff3 . ' -a -e --merge ' .
1490 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
1491 $handle = popen( $cmd, 'r' );
1494 $data = fread( $handle, 8192 );
1495 if ( strlen( $data ) == 0 ) {
1501 unlink( $mytextName ); unlink( $oldtextName ); unlink( $yourtextName );
1503 if ( $result === '' && $old !== '' && !$conflict ) {
1504 wfDebug( "Unexpected null result from diff3. Command: $cmd\n" );
1511 * Returns unified plain-text diff of two texts.
1512 * Useful for machine processing of diffs.
1513 * @param $before String: the text before the changes.
1514 * @param $after String: the text after the changes.
1515 * @param $params String: command-line options for the diff command.
1516 * @return String: unified diff of $before and $after
1518 function wfDiff( $before, $after, $params = '-u' ) {
1519 if ($before == $after) {
1525 # This check may also protect against code injection in
1526 # case of broken installations.
1527 if( !file_exists( $wgDiff ) ){
1528 wfDebug( "diff executable not found\n" );
1529 $diffs = new Diff( explode( "\n", $before ), explode( "\n", $after ) );
1530 $format = new UnifiedDiffFormatter();
1531 return $format->format( $diffs );
1534 # Make temporary files
1536 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
1537 $newtextFile = fopen( $newtextName = tempnam( $td, 'merge-your-' ), 'w' );
1539 fwrite( $oldtextFile, $before ); fclose( $oldtextFile );
1540 fwrite( $newtextFile, $after ); fclose( $newtextFile );
1542 // Get the diff of the two files
1543 $cmd = "$wgDiff " . $params . ' ' .wfEscapeShellArg( $oldtextName, $newtextName );
1545 $h = popen( $cmd, 'r' );
1550 $data = fread( $h, 8192 );
1551 if ( strlen( $data ) == 0 ) {
1559 unlink( $oldtextName );
1560 unlink( $newtextName );
1562 // Kill the --- and +++ lines. They're not useful.
1563 $diff_lines = explode( "\n", $diff );
1564 if (strpos( $diff_lines[0], '---' ) === 0) {
1565 unset($diff_lines[0]);
1567 if (strpos( $diff_lines[1], '+++' ) === 0) {
1568 unset($diff_lines[1]);
1571 $diff = implode( "\n", $diff_lines );
1577 * A wrapper around the PHP function var_export().
1578 * Either print it or add it to the regular output ($wgOut).
1580 * @param $var A PHP variable to dump.
1582 function wfVarDump( $var ) {
1584 $s = str_replace("\n","<br />\n", var_export( $var, true ) . "\n");
1585 if ( headers_sent() ||
!@is_object
( $wgOut ) ) {
1588 $wgOut->addHTML( $s );
1593 * Provide a simple HTTP error.
1595 function wfHttpError( $code, $label, $desc ) {
1598 header( "HTTP/1.0 $code $label" );
1599 header( "Status: $code $label" );
1600 $wgOut->sendCacheControl();
1602 header( 'Content-type: text/html; charset=utf-8' );
1603 print "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">".
1604 "<html><head><title>" .
1605 htmlspecialchars( $label ) .
1606 "</title></head><body><h1>" .
1607 htmlspecialchars( $label ) .
1609 nl2br( htmlspecialchars( $desc ) ) .
1610 "</p></body></html>\n";
1614 * Clear away any user-level output buffers, discarding contents.
1616 * Suitable for 'starting afresh', for instance when streaming
1617 * relatively large amounts of data without buffering, or wanting to
1618 * output image files without ob_gzhandler's compression.
1620 * The optional $resetGzipEncoding parameter controls suppression of
1621 * the Content-Encoding header sent by ob_gzhandler; by default it
1622 * is left. See comments for wfClearOutputBuffers() for why it would
1625 * Note that some PHP configuration options may add output buffer
1626 * layers which cannot be removed; these are left in place.
1628 * @param $resetGzipEncoding Bool
1630 function wfResetOutputBuffers( $resetGzipEncoding=true ) {
1631 if( $resetGzipEncoding ) {
1632 // Suppress Content-Encoding and Content-Length
1633 // headers from 1.10+s wfOutputHandler
1634 global $wgDisableOutputCompression;
1635 $wgDisableOutputCompression = true;
1637 while( $status = ob_get_status() ) {
1638 if( $status['type'] == 0 /* PHP_OUTPUT_HANDLER_INTERNAL */ ) {
1639 // Probably from zlib.output_compression or other
1640 // PHP-internal setting which can't be removed.
1642 // Give up, and hope the result doesn't break
1646 if( !ob_end_clean() ) {
1647 // Could not remove output buffer handler; abort now
1648 // to avoid getting in some kind of infinite loop.
1651 if( $resetGzipEncoding ) {
1652 if( $status['name'] == 'ob_gzhandler' ) {
1653 // Reset the 'Content-Encoding' field set by this handler
1654 // so we can start fresh.
1655 header( 'Content-Encoding:' );
1663 * More legible than passing a 'false' parameter to wfResetOutputBuffers():
1665 * Clear away output buffers, but keep the Content-Encoding header
1666 * produced by ob_gzhandler, if any.
1668 * This should be used for HTTP 304 responses, where you need to
1669 * preserve the Content-Encoding header of the real result, but
1670 * also need to suppress the output of ob_gzhandler to keep to spec
1671 * and avoid breaking Firefox in rare cases where the headers and
1672 * body are broken over two packets.
1674 function wfClearOutputBuffers() {
1675 wfResetOutputBuffers( false );
1679 * Converts an Accept-* header into an array mapping string values to quality
1682 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
1683 # No arg means accept anything (per HTTP spec)
1685 return array( $def => 1.0 );
1690 $parts = explode( ',', $accept );
1692 foreach( $parts as $part ) {
1693 # FIXME: doesn't deal with params like 'text/html; level=1'
1694 @list
( $value, $qpart ) = explode( ';', trim( $part ) );
1696 if( !isset( $qpart ) ) {
1697 $prefs[$value] = 1.0;
1698 } elseif( preg_match( '/q\s*=\s*(\d*\.\d+)/', $qpart, $match ) ) {
1699 $prefs[$value] = floatval($match[1]);
1707 * Checks if a given MIME type matches any of the keys in the given
1708 * array. Basic wildcards are accepted in the array keys.
1710 * Returns the matching MIME type (or wildcard) if a match, otherwise
1713 * @param $type String
1714 * @param $avail Array
1718 function mimeTypeMatch( $type, $avail ) {
1719 if( array_key_exists($type, $avail) ) {
1722 $parts = explode( '/', $type );
1723 if( array_key_exists( $parts[0] . '/*', $avail ) ) {
1724 return $parts[0] . '/*';
1725 } elseif( array_key_exists( '*/*', $avail ) ) {
1734 * Returns the 'best' match between a client's requested internet media types
1735 * and the server's list of available types. Each list should be an associative
1736 * array of type to preference (preference is a float between 0.0 and 1.0).
1737 * Wildcards in the types are acceptable.
1739 * @param $cprefs Array: client's acceptable type list
1740 * @param $sprefs Array: server's offered types
1743 * @todo FIXME: doesn't handle params like 'text/plain; charset=UTF-8'
1744 * XXX: generalize to negotiate other stuff
1746 function wfNegotiateType( $cprefs, $sprefs ) {
1749 foreach( array_keys($sprefs) as $type ) {
1750 $parts = explode( '/', $type );
1751 if( $parts[1] != '*' ) {
1752 $ckey = mimeTypeMatch( $type, $cprefs );
1754 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1759 foreach( array_keys( $cprefs ) as $type ) {
1760 $parts = explode( '/', $type );
1761 if( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
1762 $skey = mimeTypeMatch( $type, $sprefs );
1764 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1772 foreach( array_keys( $combine ) as $type ) {
1773 if( $combine[$type] > $bestq ) {
1775 $bestq = $combine[$type];
1784 * Returns an array where the values in the first array are replaced by the
1785 * values in the second array with the corresponding keys
1789 function wfArrayLookup( $a, $b ) {
1790 return array_flip( array_intersect( array_flip( $a ), array_keys( $b ) ) );
1794 * Convenience function; returns MediaWiki timestamp for the present time.
1797 function wfTimestampNow() {
1799 return wfTimestamp( TS_MW
, time() );
1803 * Reference-counted warning suppression
1805 function wfSuppressWarnings( $end = false ) {
1806 static $suppressCount = 0;
1807 static $originalLevel = false;
1810 if ( $suppressCount ) {
1812 if ( !$suppressCount ) {
1813 error_reporting( $originalLevel );
1817 if ( !$suppressCount ) {
1818 $originalLevel = error_reporting( E_ALL
& ~
( E_WARNING | E_NOTICE | E_USER_WARNING | E_USER_NOTICE
) );
1825 * Restore error level to previous value
1827 function wfRestoreWarnings() {
1828 wfSuppressWarnings( true );
1831 # Autodetect, convert and provide timestamps of various types
1834 * Unix time - the number of seconds since 1970-01-01 00:00:00 UTC
1836 define('TS_UNIX', 0);
1839 * MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
1844 * MySQL DATETIME (YYYY-MM-DD HH:MM:SS)
1849 * RFC 2822 format, for E-mail and HTTP headers
1851 define('TS_RFC2822', 3);
1854 * ISO 8601 format with no timezone: 1986-02-09T20:00:00Z
1856 * This is used by Special:Export
1858 define('TS_ISO_8601', 4);
1861 * An Exif timestamp (YYYY:MM:DD HH:MM:SS)
1863 * @see http://exif.org/Exif2-2.PDF The Exif 2.2 spec, see page 28 for the
1864 * DateTime tag and page 36 for the DateTimeOriginal and
1865 * DateTimeDigitized tags.
1867 define('TS_EXIF', 5);
1870 * Oracle format time.
1872 define('TS_ORACLE', 6);
1875 * Postgres format time.
1877 define('TS_POSTGRES', 7);
1882 define('TS_DB2', 8);
1885 * @param $outputtype Mixed: A timestamp in one of the supported formats, the
1886 * function will autodetect which format is supplied and act
1888 * @param $ts Mixed: the timestamp to convert or 0 for the current timestamp
1889 * @return String: in the format specified in $outputtype
1891 function wfTimestamp( $outputtype = TS_UNIX
, $ts = 0 ) {
1896 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)$/D',$ts,$da)) {
1898 } elseif (preg_match('/^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/D',$ts,$da)) {
1900 } elseif (preg_match('/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/D',$ts,$da)) {
1902 } elseif (preg_match('/^-?\d{1,13}$/D',$ts)) {
1905 } elseif (preg_match('/^\d{2}-\d{2}-\d{4} \d{2}:\d{2}:\d{2}.\d{6}$/', $ts)) {
1906 # TS_ORACLE // session altered to DD-MM-YYYY HH24:MI:SS.FF6
1907 $uts = strtotime(preg_replace('/(\d\d)\.(\d\d)\.(\d\d)(\.(\d+))?/', "$1:$2:$3",
1908 str_replace("+00:00", "UTC", $ts)));
1909 } elseif (preg_match('/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.*\d*)?Z$/', $ts, $da)) {
1911 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.*\d*[\+\- ](\d\d)$/',$ts,$da)) {
1913 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.*\d* GMT$/',$ts,$da)) {
1916 # Bogus value; fall back to the epoch...
1917 wfDebug("wfTimestamp() fed bogus time value: $outputtype; $ts\n");
1921 if (count( $da ) ) {
1922 // Warning! gmmktime() acts oddly if the month or day is set to 0
1923 // We may want to handle that explicitly at some point
1924 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1925 (int)$da[2],(int)$da[3],(int)$da[1]);
1928 switch($outputtype) {
1932 return gmdate( 'YmdHis', $uts );
1934 return gmdate( 'Y-m-d H:i:s', $uts );
1936 return gmdate( 'Y-m-d\TH:i:s\Z', $uts );
1937 // This shouldn't ever be used, but is included for completeness
1939 return gmdate( 'Y:m:d H:i:s', $uts );
1941 return gmdate( 'D, d M Y H:i:s', $uts ) . ' GMT';
1943 return gmdate( 'd-m-Y H:i:s.000000', $uts);
1944 //return gmdate( 'd-M-y h.i.s A', $uts) . ' +00:00';
1946 return gmdate( 'Y-m-d H:i:s', $uts) . ' GMT';
1948 return gmdate( 'Y-m-d H:i:s', $uts);
1950 throw new MWException( 'wfTimestamp() called with illegal output type.');
1955 * Return a formatted timestamp, or null if input is null.
1956 * For dealing with nullable timestamp columns in the database.
1957 * @param $outputtype Integer
1961 function wfTimestampOrNull( $outputtype = TS_UNIX
, $ts = null ) {
1962 if( is_null( $ts ) ) {
1965 return wfTimestamp( $outputtype, $ts );
1970 * Check if the operating system is Windows
1972 * @return Bool: true if it's Windows, False otherwise.
1974 function wfIsWindows() {
1975 if (substr(php_uname(), 0, 7) == 'Windows') {
1983 * Swap two variables
1985 function swap( &$x, &$y ) {
1991 function wfGetCachedNotice( $name ) {
1992 global $wgOut, $wgRenderHashAppend, $parserMemc;
1993 $fname = 'wfGetCachedNotice';
1994 wfProfileIn( $fname );
1998 if( $name === 'default' ) {
2000 global $wgSiteNotice;
2001 $notice = $wgSiteNotice;
2002 if( empty( $notice ) ) {
2003 wfProfileOut( $fname );
2007 $notice = wfMsgForContentNoTrans( $name );
2008 if( wfEmptyMsg( $name, $notice ) ||
$notice == '-' ) {
2009 wfProfileOut( $fname );
2014 // Use the extra hash appender to let eg SSL variants separately cache.
2015 $key = wfMemcKey( $name . $wgRenderHashAppend );
2016 $cachedNotice = $parserMemc->get( $key );
2017 if( is_array( $cachedNotice ) ) {
2018 if( md5( $notice ) == $cachedNotice['hash'] ) {
2019 $notice = $cachedNotice['html'];
2028 if( is_object( $wgOut ) ) {
2029 $parsed = $wgOut->parse( $notice );
2030 $parserMemc->set( $key, array( 'html' => $parsed, 'hash' => md5( $notice ) ), 600 );
2033 wfDebug( 'wfGetCachedNotice called for ' . $name . ' with no $wgOut available'."\n" );
2037 $notice = '<div id="localNotice">'.$notice.'</div>';
2038 wfProfileOut( $fname );
2042 function wfGetNamespaceNotice() {
2046 if ( !isset( $wgTitle ) ||
!is_object( $wgTitle ) )
2049 $fname = 'wfGetNamespaceNotice';
2050 wfProfileIn( $fname );
2052 $key = "namespacenotice-" . $wgTitle->getNsText();
2053 $namespaceNotice = wfGetCachedNotice( $key );
2054 if ( $namespaceNotice && substr ( $namespaceNotice , 0 ,7 ) != "<p><" ) {
2055 $namespaceNotice = '<div id="namespacebanner">' . $namespaceNotice . "</div>";
2057 $namespaceNotice = "";
2060 wfProfileOut( $fname );
2061 return $namespaceNotice;
2064 function wfGetSiteNotice() {
2066 $fname = 'wfGetSiteNotice';
2067 wfProfileIn( $fname );
2070 if( wfRunHooks( 'SiteNoticeBefore', array( &$siteNotice ) ) ) {
2071 if( is_object( $wgUser ) && $wgUser->isLoggedIn() ) {
2072 $siteNotice = wfGetCachedNotice( 'sitenotice' );
2074 $anonNotice = wfGetCachedNotice( 'anonnotice' );
2075 if( !$anonNotice ) {
2076 $siteNotice = wfGetCachedNotice( 'sitenotice' );
2078 $siteNotice = $anonNotice;
2081 if( !$siteNotice ) {
2082 $siteNotice = wfGetCachedNotice( 'default' );
2086 wfRunHooks( 'SiteNoticeAfter', array( &$siteNotice ) );
2087 wfProfileOut( $fname );
2092 * BC wrapper for MimeMagic::singleton()
2095 function &wfGetMimeMagic() {
2096 wfDeprecated( __FUNCTION__
);
2097 return MimeMagic
::singleton();
2101 * Tries to get the system directory for temporary files. For PHP >= 5.2.1,
2102 * we'll use sys_get_temp_dir(). The TMPDIR, TMP, and TEMP environment
2103 * variables are then checked in sequence, and if none are set /tmp is
2104 * returned as the generic Unix default.
2105 * It is common to call it with tempnam().
2107 * NOTE: When possible, use instead the tmpfile() function to create
2108 * temporary files to avoid race conditions on file creation, etc.
2112 function wfTempDir() {
2113 if( function_exists( 'sys_get_temp_dir' ) ) {
2114 return sys_get_temp_dir();
2116 foreach( array( 'TMPDIR', 'TMP', 'TEMP' ) as $var ) {
2117 $tmp = getenv( $var );
2118 if( $tmp && file_exists( $tmp ) && is_dir( $tmp ) && is_writable( $tmp ) ) {
2122 # Hope this is Unix of some kind!
2127 * Make directory, and make all parent directories if they don't exist
2129 * @param $dir String: full path to directory to create
2130 * @param $mode Integer: chmod value to use, default is $wgDirectoryMode
2131 * @param $caller String: optional caller param for debugging.
2134 function wfMkdirParents( $dir, $mode = null, $caller = null ) {
2135 global $wgDirectoryMode;
2137 if ( !is_null( $caller ) ) {
2138 wfDebug( "$caller: called wfMkdirParents($dir)" );
2141 if( strval( $dir ) === '' ||
file_exists( $dir ) )
2144 $dir = str_replace( array( '\\', '/' ), DIRECTORY_SEPARATOR
, $dir );
2146 if ( is_null( $mode ) )
2147 $mode = $wgDirectoryMode;
2149 // Turn off the normal warning, we're doing our own below
2150 wfSuppressWarnings();
2151 $ok = mkdir( $dir, $mode, true ); // PHP5 <3
2152 wfRestoreWarnings();
2155 // PHP doesn't report the path in its warning message, so add our own to aid in diagnosis.
2156 trigger_error( __FUNCTION__
. ": failed to mkdir \"$dir\" mode $mode", E_USER_WARNING
);
2162 * Increment a statistics counter
2164 function wfIncrStats( $key ) {
2165 global $wgStatsMethod;
2167 if( $wgStatsMethod == 'udp' ) {
2168 global $wgUDPProfilerHost, $wgUDPProfilerPort, $wgDBname;
2171 $socket=socket_create(AF_INET
, SOCK_DGRAM
, SOL_UDP
);
2172 $statline="stats/{$wgDBname} - 1 1 1 1 1 -total\n";
2173 socket_sendto($socket,$statline,strlen($statline),0,$wgUDPProfilerHost,$wgUDPProfilerPort);
2175 $statline="stats/{$wgDBname} - 1 1 1 1 1 {$key}\n";
2176 @socket_sendto
($socket,$statline,strlen($statline),0,$wgUDPProfilerHost,$wgUDPProfilerPort);
2177 } elseif( $wgStatsMethod == 'cache' ) {
2179 $key = wfMemcKey( 'stats', $key );
2180 if ( is_null( $wgMemc->incr( $key ) ) ) {
2181 $wgMemc->add( $key, 1 );
2189 * @param $nr Mixed: the number to format
2190 * @param $acc Integer: the number of digits after the decimal point, default 2
2191 * @param $round Boolean: whether or not to round the value, default true
2194 function wfPercent( $nr, $acc = 2, $round = true ) {
2195 $ret = sprintf( "%.${acc}f", $nr );
2196 return $round ?
round( $ret, $acc ) . '%' : "$ret%";
2200 * Encrypt a username/password.
2202 * @param $userid Integer: ID of the user
2203 * @param $password String: password of the user
2204 * @return String: hashed password
2205 * @deprecated Use User::crypt() or User::oldCrypt() instead
2207 function wfEncryptPassword( $userid, $password ) {
2208 wfDeprecated(__FUNCTION__
);
2209 # Just wrap around User::oldCrypt()
2210 return User
::oldCrypt($password, $userid);
2214 * Appends to second array if $value differs from that in $default
2216 function wfAppendToArrayIfNotDefault( $key, $value, $default, &$changed ) {
2217 if ( is_null( $changed ) ) {
2218 throw new MWException('GlobalFunctions::wfAppendToArrayIfNotDefault got null');
2220 if ( $default[$key] !== $value ) {
2221 $changed[$key] = $value;
2226 * Since wfMsg() and co suck, they don't return false if the message key they
2227 * looked up didn't exist but a XHTML string, this function checks for the
2228 * nonexistance of messages by looking at wfMsg() output
2230 * @param $key String: the message key looked up
2231 * @return Boolean True if the message *doesn't* exist.
2233 function wfEmptyMsg( $key ) {
2234 global $wgMessageCache;
2235 return $wgMessageCache->get( $key, /*useDB*/true, /*content*/false ) === false;
2239 * Find out whether or not a mixed variable exists in a string
2241 * @param $needle String
2242 * @param $str String
2245 function in_string( $needle, $str ) {
2246 return strpos( $str, $needle ) !== false;
2249 function wfSpecialList( $page, $details ) {
2251 $details = $details ?
' ' . $wgContLang->getDirMark() . "($details)" : "";
2252 return $page . $details;
2256 * Returns a regular expression of url protocols
2260 function wfUrlProtocols() {
2261 global $wgUrlProtocols;
2263 static $retval = null;
2264 if ( !is_null( $retval ) )
2267 // Support old-style $wgUrlProtocols strings, for backwards compatibility
2268 // with LocalSettings files from 1.5
2269 if ( is_array( $wgUrlProtocols ) ) {
2270 $protocols = array();
2271 foreach ($wgUrlProtocols as $protocol)
2272 $protocols[] = preg_quote( $protocol, '/' );
2274 $retval = implode( '|', $protocols );
2276 $retval = $wgUrlProtocols;
2282 * Safety wrapper around ini_get() for boolean settings.
2283 * The values returned from ini_get() are pre-normalized for settings
2284 * set via php.ini or php_flag/php_admin_flag... but *not*
2285 * for those set via php_value/php_admin_value.
2287 * It's fairly common for people to use php_value instead of php_flag,
2288 * which can leave you with an 'off' setting giving a false positive
2289 * for code that just takes the ini_get() return value as a boolean.
2291 * To make things extra interesting, setting via php_value accepts
2292 * "true" and "yes" as true, but php.ini and php_flag consider them false. :)
2293 * Unrecognized values go false... again opposite PHP's own coercion
2294 * from string to bool.
2296 * Luckily, 'properly' set settings will always come back as '0' or '1',
2297 * so we only have to worry about them and the 'improper' settings.
2299 * I frickin' hate PHP... :P
2301 * @param $setting String
2304 function wfIniGetBool( $setting ) {
2305 $val = ini_get( $setting );
2306 // 'on' and 'true' can't have whitespace around them, but '1' can.
2307 return strtolower( $val ) == 'on'
2308 ||
strtolower( $val ) == 'true'
2309 ||
strtolower( $val ) == 'yes'
2310 ||
preg_match( "/^\s*[+-]?0*[1-9]/", $val ); // approx C atoi() function
2314 * Wrapper function for PHP's dl(). This doesn't work in most situations from
2315 * PHP 5.3 onward, and is usually disabled in shared environments anyway.
2317 * @param $extension String A PHP extension. The file suffix (.so or .dll)
2319 * @return Bool - Whether or not the extension is loaded
2321 function wfDl( $extension ) {
2322 if( extension_loaded( $extension ) ) {
2326 $canDl = ( function_exists( 'dl' ) && is_callable( 'dl' )
2327 && wfIniGetBool( 'enable_dl' ) && !wfIniGetBool( 'safe_mode' ) );
2330 wfSuppressWarnings();
2331 dl( $extension . '.' . PHP_SHLIB_SUFFIX
);
2332 wfRestoreWarnings();
2334 return extension_loaded( $extension );
2338 * Execute a shell command, with time and memory limits mirrored from the PHP
2339 * configuration if supported.
2340 * @param $cmd Command line, properly escaped for shell.
2341 * @param &$retval optional, will receive the program's exit code.
2342 * (non-zero is usually failure)
2343 * @return collected stdout as a string (trailing newlines stripped)
2345 function wfShellExec( $cmd, &$retval=null ) {
2346 global $IP, $wgMaxShellMemory, $wgMaxShellFileSize, $wgMaxShellTime;
2349 if ( is_null( $disabled ) ) {
2351 if( wfIniGetBool( 'safe_mode' ) ) {
2352 wfDebug( "wfShellExec can't run in safe_mode, PHP's exec functions are too broken.\n" );
2355 $functions = explode( ',', ini_get( 'disable_functions' ) );
2356 $functions = array_map( 'trim', $functions );
2357 $functions = array_map( 'strtolower', $functions );
2358 if ( in_array( 'passthru', $functions ) ) {
2359 wfDebug( "passthru is in disabled_functions\n" );
2365 return "Unable to run external programs in safe mode.";
2368 wfInitShellLocale();
2370 if ( php_uname( 's' ) == 'Linux' ) {
2371 $time = intval( $wgMaxShellTime );
2372 $mem = intval( $wgMaxShellMemory );
2373 $filesize = intval( $wgMaxShellFileSize );
2375 if ( $time > 0 && $mem > 0 ) {
2376 $script = "$IP/bin/ulimit4.sh";
2377 if ( is_executable( $script ) ) {
2378 $cmd = escapeshellarg( $script ) . " $time $mem $filesize " . escapeshellarg( $cmd );
2381 } elseif ( php_uname( 's' ) == 'Windows NT' &&
2382 version_compare( PHP_VERSION
, '5.3.0', '<' ) )
2384 # This is a hack to work around PHP's flawed invocation of cmd.exe
2385 # http://news.php.net/php.internals/21796
2386 # Which is fixed in 5.3.0 :)
2387 $cmd = '"' . $cmd . '"';
2389 wfDebug( "wfShellExec: $cmd\n" );
2391 $retval = 1; // error by default?
2393 passthru( $cmd, $retval );
2394 $output = ob_get_contents();
2397 if ( $retval == 127 ) {
2398 wfDebugLog( 'exec', "Possibly missing executable file: $cmd\n" );
2404 * Workaround for http://bugs.php.net/bug.php?id=45132
2405 * escapeshellarg() destroys non-ASCII characters if LANG is not a UTF-8 locale
2407 function wfInitShellLocale() {
2408 static $done = false;
2409 if ( $done ) return;
2411 global $wgShellLocale;
2412 if ( !wfIniGetBool( 'safe_mode' ) ) {
2413 putenv( "LC_CTYPE=$wgShellLocale" );
2414 setlocale( LC_CTYPE
, $wgShellLocale );
2419 * This function works like "use VERSION" in Perl, the program will die with a
2420 * backtrace if the current version of PHP is less than the version provided
2422 * This is useful for extensions which due to their nature are not kept in sync
2423 * with releases, and might depend on other versions of PHP than the main code
2425 * Note: PHP might die due to parsing errors in some cases before it ever
2426 * manages to call this function, such is life
2428 * @see perldoc -f use
2430 * @param $req_ver Mixed: the version to check, can be a string, an integer, or
2433 function wfUsePHP( $req_ver ) {
2434 $php_ver = PHP_VERSION
;
2436 if ( version_compare( $php_ver, (string)$req_ver, '<' ) )
2437 throw new MWException( "PHP $req_ver required--this is only $php_ver" );
2441 * This function works like "use VERSION" in Perl except it checks the version
2442 * of MediaWiki, the program will die with a backtrace if the current version
2443 * of MediaWiki is less than the version provided.
2445 * This is useful for extensions which due to their nature are not kept in sync
2448 * @see perldoc -f use
2450 * @param $req_ver Mixed: the version to check, can be a string, an integer, or
2453 function wfUseMW( $req_ver ) {
2456 if ( version_compare( $wgVersion, (string)$req_ver, '<' ) )
2457 throw new MWException( "MediaWiki $req_ver required--this is only $wgVersion" );
2461 * Return the final portion of a pathname.
2462 * Reimplemented because PHP5's basename() is buggy with multibyte text.
2463 * http://bugs.php.net/bug.php?id=33898
2465 * PHP's basename() only considers '\' a pathchar on Windows and Netware.
2466 * We'll consider it so always, as we don't want \s in our Unix paths either.
2468 * @param $path String
2469 * @param $suffix String: to remove if present
2472 function wfBaseName( $path, $suffix='' ) {
2473 $encSuffix = ($suffix == '')
2475 : ( '(?:' . preg_quote( $suffix, '#' ) . ')?' );
2477 if( preg_match( "#([^/\\\\]*?){$encSuffix}[/\\\\]*$#", $path, $matches ) ) {
2485 * Generate a relative path name to the given file.
2486 * May explode on non-matching case-insensitive paths,
2487 * funky symlinks, etc.
2489 * @param $path String: absolute destination path including target filename
2490 * @param $from String: Absolute source path, directory only
2493 function wfRelativePath( $path, $from ) {
2494 // Normalize mixed input on Windows...
2495 $path = str_replace( '/', DIRECTORY_SEPARATOR
, $path );
2496 $from = str_replace( '/', DIRECTORY_SEPARATOR
, $from );
2498 // Trim trailing slashes -- fix for drive root
2499 $path = rtrim( $path, DIRECTORY_SEPARATOR
);
2500 $from = rtrim( $from, DIRECTORY_SEPARATOR
);
2502 $pieces = explode( DIRECTORY_SEPARATOR
, dirname( $path ) );
2503 $against = explode( DIRECTORY_SEPARATOR
, $from );
2505 if( $pieces[0] !== $against[0] ) {
2506 // Non-matching Windows drive letters?
2507 // Return a full path.
2511 // Trim off common prefix
2512 while( count( $pieces ) && count( $against )
2513 && $pieces[0] == $against[0] ) {
2514 array_shift( $pieces );
2515 array_shift( $against );
2518 // relative dots to bump us to the parent
2519 while( count( $against ) ) {
2520 array_unshift( $pieces, '..' );
2521 array_shift( $against );
2524 array_push( $pieces, wfBaseName( $path ) );
2526 return implode( DIRECTORY_SEPARATOR
, $pieces );
2530 * Backwards array plus for people who haven't bothered to read the PHP manual
2531 * XXX: will not darn your socks for you.
2533 * @param $array1 Array
2534 * @param [$array2, [...]] Arrays
2537 function wfArrayMerge( $array1/* ... */ ) {
2538 $args = func_get_args();
2539 $args = array_reverse( $args, true );
2541 foreach ( $args as $arg ) {
2548 * Merge arrays in the style of getUserPermissionsErrors, with duplicate removal
2550 * wfMergeErrorArrays(
2551 * array( array( 'x' ) ),
2552 * array( array( 'x', '2' ) ),
2553 * array( array( 'x' ) ),
2554 * array( array( 'y') )
2558 * array( 'x', '2' ),
2563 function wfMergeErrorArrays( /*...*/ ) {
2564 $args = func_get_args();
2566 foreach ( $args as $errors ) {
2567 foreach ( $errors as $params ) {
2568 # FIXME: sometimes get nested arrays for $params,
2569 # which leads to E_NOTICEs
2570 $spec = implode( "\t", $params );
2571 $out[$spec] = $params;
2574 return array_values( $out );
2578 * parse_url() work-alike, but non-broken. Differences:
2580 * 1) Does not raise warnings on bad URLs (just returns false)
2581 * 2) Handles protocols that don't use :// (e.g., mailto: and news:) correctly
2582 * 3) Adds a "delimiter" element to the array, either '://' or ':' (see (2))
2584 * @param $url String: a URL to parse
2585 * @return Array: bits of the URL in an associative array, per PHP docs
2587 function wfParseUrl( $url ) {
2588 global $wgUrlProtocols; // Allow all protocols defined in DefaultSettings/LocalSettings.php
2589 wfSuppressWarnings();
2590 $bits = parse_url( $url );
2591 wfRestoreWarnings();
2596 // most of the protocols are followed by ://, but mailto: and sometimes news: not, check for it
2597 if ( in_array( $bits['scheme'] . '://', $wgUrlProtocols ) ) {
2598 $bits['delimiter'] = '://';
2599 } elseif ( in_array( $bits['scheme'] . ':', $wgUrlProtocols ) ) {
2600 $bits['delimiter'] = ':';
2601 // parse_url detects for news: and mailto: the host part of an url as path
2602 // We have to correct this wrong detection
2603 if ( isset ( $bits['path'] ) ) {
2604 $bits['host'] = $bits['path'];
2615 * Make a URL index, appropriate for the el_index field of externallinks.
2617 function wfMakeUrlIndex( $url ) {
2618 $bits = wfParseUrl( $url );
2620 // Reverse the labels in the hostname, convert to lower case
2621 // For emails reverse domainpart only
2622 if ( $bits['scheme'] == 'mailto' ) {
2623 $mailparts = explode( '@', $bits['host'], 2 );
2624 if ( count($mailparts) === 2 ) {
2625 $domainpart = strtolower( implode( '.', array_reverse( explode( '.', $mailparts[1] ) ) ) );
2627 // No domain specified, don't mangle it
2630 $reversedHost = $domainpart . '@' . $mailparts[0];
2632 $reversedHost = strtolower( implode( '.', array_reverse( explode( '.', $bits['host'] ) ) ) );
2634 // Add an extra dot to the end
2635 // Why? Is it in wrong place in mailto links?
2636 if ( substr( $reversedHost, -1, 1 ) !== '.' ) {
2637 $reversedHost .= '.';
2639 // Reconstruct the pseudo-URL
2640 $prot = $bits['scheme'];
2641 $index = $prot . $bits['delimiter'] . $reversedHost;
2642 // Leave out user and password. Add the port, path, query and fragment
2643 if ( isset( $bits['port'] ) ) $index .= ':' . $bits['port'];
2644 if ( isset( $bits['path'] ) ) {
2645 $index .= $bits['path'];
2649 if ( isset( $bits['query'] ) ) $index .= '?' . $bits['query'];
2650 if ( isset( $bits['fragment'] ) ) $index .= '#' . $bits['fragment'];
2655 * Do any deferred updates and clear the list
2656 * TODO: This could be in Wiki.php if that class made any sense at all
2658 function wfDoUpdates()
2660 global $wgPostCommitUpdateList, $wgDeferredUpdateList;
2661 foreach ( $wgDeferredUpdateList as $update ) {
2662 $update->doUpdate();
2664 foreach ( $wgPostCommitUpdateList as $update ) {
2665 $update->doUpdate();
2667 $wgDeferredUpdateList = array();
2668 $wgPostCommitUpdateList = array();
2672 * Convert an arbitrarily-long digit string from one numeric base
2673 * to another, optionally zero-padding to a minimum column width.
2675 * Supports base 2 through 36; digit values 10-36 are represented
2676 * as lowercase letters a-z. Input is case-insensitive.
2678 * @param $input String: of digits
2679 * @param $sourceBase Integer: 2-36
2680 * @param $destBase Integer: 2-36
2681 * @param $pad Integer: 1 or greater
2682 * @param $lowercase Boolean
2683 * @return String or false on invalid input
2685 function wfBaseConvert( $input, $sourceBase, $destBase, $pad=1, $lowercase=true ) {
2686 $input = strval( $input );
2687 if( $sourceBase < 2 ||
2692 $sourceBase != intval( $sourceBase ) ||
2693 $destBase != intval( $destBase ) ||
2694 $pad != intval( $pad ) ||
2695 !is_string( $input ) ||
2699 $digitChars = ( $lowercase ) ?
'0123456789abcdefghijklmnopqrstuvwxyz' : '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
2700 $inDigits = array();
2703 // Decode and validate input string
2704 $input = strtolower( $input );
2705 for( $i = 0; $i < strlen( $input ); $i++
) {
2706 $n = strpos( $digitChars, $input{$i} );
2707 if( $n === false ||
$n > $sourceBase ) {
2713 // Iterate over the input, modulo-ing out an output digit
2714 // at a time until input is gone.
2715 while( count( $inDigits ) ) {
2717 $workDigits = array();
2720 foreach( $inDigits as $digit ) {
2721 $work *= $sourceBase;
2724 if( $work < $destBase ) {
2725 // Gonna need to pull another digit.
2726 if( count( $workDigits ) ) {
2727 // Avoid zero-padding; this lets us find
2728 // the end of the input very easily when
2729 // length drops to zero.
2733 // Finally! Actual division!
2734 $workDigits[] = intval( $work / $destBase );
2736 // Isn't it annoying that most programming languages
2737 // don't have a single divide-and-remainder operator,
2738 // even though the CPU implements it that way?
2739 $work = $work %
$destBase;
2743 // All that division leaves us with a remainder,
2744 // which is conveniently our next output digit.
2745 $outChars .= $digitChars[$work];
2748 $inDigits = $workDigits;
2751 while( strlen( $outChars ) < $pad ) {
2755 return strrev( $outChars );
2759 * Create an object with a given name and an array of construct parameters
2760 * @param $name String
2761 * @param $p Array: parameters
2763 function wfCreateObject( $name, $p ){
2764 $p = array_values( $p );
2765 switch ( count( $p ) ) {
2769 return new $name( $p[0] );
2771 return new $name( $p[0], $p[1] );
2773 return new $name( $p[0], $p[1], $p[2] );
2775 return new $name( $p[0], $p[1], $p[2], $p[3] );
2777 return new $name( $p[0], $p[1], $p[2], $p[3], $p[4] );
2779 return new $name( $p[0], $p[1], $p[2], $p[3], $p[4], $p[5] );
2781 throw new MWException( "Too many arguments to construtor in wfCreateObject" );
2785 function wfHttpOnlySafe() {
2786 global $wgHttpOnlyBlacklist;
2787 if( !version_compare("5.2", PHP_VERSION
, "<") )
2790 if( isset( $_SERVER['HTTP_USER_AGENT'] ) ) {
2791 foreach( $wgHttpOnlyBlacklist as $regex ) {
2792 if( preg_match( $regex, $_SERVER['HTTP_USER_AGENT'] ) ) {
2802 * Initialise php session
2804 function wfSetupSession() {
2805 global $wgSessionsInMemcached, $wgCookiePath, $wgCookieDomain,
2806 $wgCookieSecure, $wgCookieHttpOnly, $wgSessionHandler;
2807 if( $wgSessionsInMemcached ) {
2808 require_once( 'MemcachedSessions.php' );
2809 } elseif( $wgSessionHandler && $wgSessionHandler != ini_get( 'session.save_handler' ) ) {
2810 # Only set this if $wgSessionHandler isn't null and session.save_handler
2811 # hasn't already been set to the desired value (that causes errors)
2812 ini_set ( 'session.save_handler', $wgSessionHandler );
2814 $httpOnlySafe = wfHttpOnlySafe();
2815 wfDebugLog( 'cookie',
2816 'session_set_cookie_params: "' . implode( '", "',
2822 $httpOnlySafe && $wgCookieHttpOnly ) ) . '"' );
2823 if( $httpOnlySafe && $wgCookieHttpOnly ) {
2824 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookieHttpOnly );
2826 // PHP 5.1 throws warnings if you pass the HttpOnly parameter for 5.2.
2827 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
2829 session_cache_limiter( 'private, must-revalidate' );
2830 wfSuppressWarnings();
2832 wfRestoreWarnings();
2836 * Get an object from the precompiled serialized directory
2838 * @return Mixed: the variable on success, false on failure
2840 function wfGetPrecompiledData( $name ) {
2843 $file = "$IP/serialized/$name";
2844 if ( file_exists( $file ) ) {
2845 $blob = file_get_contents( $file );
2847 return unserialize( $blob );
2853 function wfGetCaller( $level = 2 ) {
2854 $backtrace = wfDebugBacktrace();
2855 if ( isset( $backtrace[$level] ) ) {
2856 return wfFormatStackFrame($backtrace[$level]);
2858 $caller = 'unknown';
2864 * Return a string consisting of callers in the stack. Useful sometimes
2865 * for profiling specific points.
2867 * @param $limit The maximum depth of the stack frame to return, or false for
2870 function wfGetAllCallers( $limit = 3 ) {
2871 $trace = array_reverse( wfDebugBacktrace() );
2872 if ( !$limit ||
$limit > count( $trace ) - 1 ) {
2873 $limit = count( $trace ) - 1;
2875 $trace = array_slice( $trace, -$limit - 1, $limit );
2876 return implode( '/', array_map( 'wfFormatStackFrame', $trace ) );
2880 * Return a string representation of frame
2882 function wfFormatStackFrame($frame) {
2883 return isset( $frame["class"] )?
2884 $frame["class"]."::".$frame["function"]:
2891 function wfMemcKey( /*... */ ) {
2892 $args = func_get_args();
2893 $key = wfWikiID() . ':' . implode( ':', $args );
2894 $key = str_replace( ' ', '_', $key );
2899 * Get a cache key for a foreign DB
2901 function wfForeignMemcKey( $db, $prefix /*, ... */ ) {
2902 $args = array_slice( func_get_args(), 2 );
2904 $key = "$db-$prefix:" . implode( ':', $args );
2906 $key = $db . ':' . implode( ':', $args );
2912 * Get an ASCII string identifying this wiki
2913 * This is used as a prefix in memcached keys
2915 function wfWikiID() {
2916 global $wgDBprefix, $wgDBname;
2917 if ( $wgDBprefix ) {
2918 return "$wgDBname-$wgDBprefix";
2925 * Split a wiki ID into DB name and table prefix
2927 function wfSplitWikiID( $wiki ) {
2928 $bits = explode( '-', $wiki, 2 );
2929 if ( count( $bits ) < 2 ) {
2936 * Get a Database object.
2937 * @param $db Integer: index of the connection to get. May be DB_MASTER for the
2938 * master (for write queries), DB_SLAVE for potentially lagged read
2939 * queries, or an integer >= 0 for a particular server.
2941 * @param $groups Mixed: query groups. An array of group names that this query
2942 * belongs to. May contain a single string if the query is only
2945 * @param $wiki String: the wiki ID, or false for the current wiki
2947 * Note: multiple calls to wfGetDB(DB_SLAVE) during the course of one request
2948 * will always return the same object, unless the underlying connection or load
2949 * balancer is manually destroyed.
2951 function &wfGetDB( $db, $groups = array(), $wiki = false ) {
2952 return wfGetLB( $wiki )->getConnection( $db, $groups, $wiki );
2956 * Get a load balancer object.
2958 * @param $wiki String: wiki ID, or false for the current wiki
2959 * @return LoadBalancer
2961 function wfGetLB( $wiki = false ) {
2962 return wfGetLBFactory()->getMainLB( $wiki );
2966 * Get the load balancer factory object
2968 function &wfGetLBFactory() {
2969 return LBFactory
::singleton();
2974 * Shortcut for RepoGroup::singleton()->findFile()
2975 * @param $title Either a string or Title object
2976 * @param $options Associative array of options:
2977 * time: requested time for an archived image, or false for the
2978 * current version. An image object will be returned which was
2979 * created at the specified time.
2981 * ignoreRedirect: If true, do not follow file redirects
2983 * private: If true, return restricted (deleted) files if the current
2984 * user is allowed to view them. Otherwise, such files will not
2987 * bypassCache: If true, do not use the process-local cache of File objects
2989 * @return File, or false if the file does not exist
2991 function wfFindFile( $title, $options = array() ) {
2992 return RepoGroup
::singleton()->findFile( $title, $options );
2996 * Get an object referring to a locally registered file.
2997 * Returns a valid placeholder object if the file does not exist.
2998 * @param $title Either a string or Title object
2999 * @return File, or null if passed an invalid Title
3001 function wfLocalFile( $title ) {
3002 return RepoGroup
::singleton()->getLocalRepo()->newFile( $title );
3006 * Should low-performance queries be disabled?
3010 function wfQueriesMustScale() {
3011 global $wgMiserMode;
3013 ||
( SiteStats
::pages() > 100000
3014 && SiteStats
::edits() > 1000000
3015 && SiteStats
::users() > 10000 );
3019 * Get the path to a specified script file, respecting file
3020 * extensions; this is a wrapper around $wgScriptExtension etc.
3022 * @param $script String: script filename, sans extension
3025 function wfScript( $script = 'index' ) {
3026 global $wgScriptPath, $wgScriptExtension;
3027 return "{$wgScriptPath}/{$script}{$wgScriptExtension}";
3030 * Get the script url.
3032 * @return script url
3034 function wfGetScriptUrl(){
3035 if( isset( $_SERVER['SCRIPT_NAME'] ) ) {
3037 # as it was called, minus the query string.
3039 # Some sites use Apache rewrite rules to handle subdomains,
3040 # and have PHP set up in a weird way that causes PHP_SELF
3041 # to contain the rewritten URL instead of the one that the
3042 # outside world sees.
3044 # If in this mode, use SCRIPT_URL instead, which mod_rewrite
3045 # provides containing the "before" URL.
3046 return $_SERVER['SCRIPT_NAME'];
3048 return $_SERVER['URL'];
3053 * Convenience function converts boolean values into "true"
3054 * or "false" (string) values
3056 * @param $value Boolean
3059 function wfBoolToStr( $value ) {
3060 return $value ?
'true' : 'false';
3064 * Load an extension messages file
3065 * @deprecated in 1.16 (warnings in 1.18, removed in ?)
3067 function wfLoadExtensionMessages( $extensionName, $langcode = false ) {
3071 * Get a platform-independent path to the null file, e.g.
3076 function wfGetNull() {
3077 return wfIsWindows()
3083 * Displays a maxlag error
3085 * @param $host String: server that lags the most
3086 * @param $lag Integer: maxlag (actual)
3087 * @param $maxLag Integer: maxlag (requested)
3089 function wfMaxlagError( $host, $lag, $maxLag ) {
3090 global $wgShowHostnames;
3091 header( 'HTTP/1.1 503 Service Unavailable' );
3092 header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
3093 header( 'X-Database-Lag: ' . intval( $lag ) );
3094 header( 'Content-Type: text/plain' );
3095 if( $wgShowHostnames ) {
3096 echo "Waiting for $host: $lag seconds lagged\n";
3098 echo "Waiting for a database server: $lag seconds lagged\n";
3103 * Throws a warning that $function is deprecated
3104 * @param $function String
3107 function wfDeprecated( $function ) {
3108 static $functionsWarned = array();
3109 if ( !isset( $functionsWarned[$function] ) ) {
3110 $functionsWarned[$function] = true;
3111 wfWarn( "Use of $function is deprecated.", 2 );
3116 * Send a warning either to the debug log or in a PHP error depending on
3117 * $wgDevelopmentWarnings
3119 * @param $msg String: message to send
3120 * @param $callerOffset Integer: number of itmes to go back in the backtrace to
3121 * find the correct caller (1 = function calling wfWarn, ...)
3122 * @param $level Integer: PHP error level; only used when $wgDevelopmentWarnings
3125 function wfWarn( $msg, $callerOffset = 1, $level = E_USER_NOTICE
) {
3126 $callers = wfDebugBacktrace();
3127 if( isset( $callers[$callerOffset+
1] ) ){
3128 $callerfunc = $callers[$callerOffset+
1];
3129 $callerfile = $callers[$callerOffset];
3130 if( isset( $callerfile['file'] ) && isset( $callerfile['line'] ) ){
3131 $file = $callerfile['file'] . ' at line ' . $callerfile['line'];
3133 $file = '(internal function)';
3136 if( isset( $callerfunc['class'] ) )
3137 $func .= $callerfunc['class'] . '::';
3138 $func .= @$callerfunc['function'];
3139 $msg .= " [Called from $func in $file]";
3142 global $wgDevelopmentWarnings;
3143 if ( $wgDevelopmentWarnings ) {
3144 trigger_error( $msg, $level );
3146 wfDebug( "$msg\n" );
3151 * Sleep until the worst slave's replication lag is less than or equal to
3152 * $maxLag, in seconds. Use this when updating very large numbers of rows, as
3153 * in maintenance scripts, to avoid causing too much lag. Of course, this is
3154 * a no-op if there are no slaves.
3156 * Every time the function has to wait for a slave, it will print a message to
3157 * that effect (and then sleep for a little while), so it's probably not best
3158 * to use this outside maintenance scripts in its present form.
3160 * @param $maxLag Integer
3161 * @param $wiki mixed Wiki identifier accepted by wfGetLB
3164 function wfWaitForSlaves( $maxLag, $wiki = false ) {
3166 $lb = wfGetLB( $wiki );
3167 list( $host, $lag ) = $lb->getMaxLag( $wiki );
3168 while( $lag > $maxLag ) {
3169 $name = @gethostbyaddr
( $host );
3170 if( $name !== false ) {
3173 print "Waiting for $host (lagged $lag seconds)...\n";
3175 list( $host, $lag ) = $lb->getMaxLag();
3181 * Output some plain text in command-line mode or in the installer (updaters.inc).
3182 * Do not use it in any other context, its behaviour is subject to change.
3184 function wfOut( $s ) {
3185 static $lineStarted = false;
3186 global $wgCommandLineMode;
3187 if ( $wgCommandLineMode && !defined( 'MEDIAWIKI_INSTALL' ) ) {
3190 echo htmlspecialchars( $s );
3196 * Count down from $n to zero on the terminal, with a one-second pause
3197 * between showing each number. For use in command-line scripts.
3199 function wfCountDown( $n ) {
3200 for ( $i = $n; $i >= 0; $i-- ) {
3202 echo str_repeat( "\x08", strlen( $i +
1 ) );
3213 /** Generate a random 32-character hexadecimal token.
3214 * @param $salt Mixed: some sort of salt, if necessary, to add to random
3215 * characters before hashing.
3217 function wfGenerateToken( $salt = '' ) {
3218 $salt = serialize($salt);
3220 return md5( mt_rand( 0, 0x7fffffff ) . $salt );
3224 * Replace all invalid characters with -
3225 * @param $name Mixed: filename to process
3227 function wfStripIllegalFilenameChars( $name ) {
3228 global $wgIllegalFileChars;
3229 $name = wfBaseName( $name );
3230 $name = preg_replace("/[^".Title
::legalChars()."]".($wgIllegalFileChars ?
"|[".$wgIllegalFileChars."]":"")."/",'-',$name);
3235 * Insert array into another array after the specified *KEY*
3236 * @param $array Array: The array.
3237 * @param $insert Array: The array to insert.
3238 * @param $after Mixed: The key to insert after
3240 function wfArrayInsertAfter( $array, $insert, $after ) {
3241 // Find the offset of the element to insert after.
3242 $keys = array_keys($array);
3243 $offsetByKey = array_flip( $keys );
3245 $offset = $offsetByKey[$after];
3247 // Insert at the specified offset
3248 $before = array_slice( $array, 0, $offset +
1, true );
3249 $after = array_slice( $array, $offset +
1, count($array)-$offset, true );
3251 $output = $before +
$insert +
$after;
3256 /* Recursively converts the parameter (an object) to an array with the same data */
3257 function wfObjectToArray( $object, $recursive = true ) {
3259 foreach ( get_object_vars( $object ) as $key => $value ) {
3260 if ( is_object( $value ) && $recursive ) {
3261 $value = wfObjectToArray( $value );
3264 $array[$key] = $value;
3271 * Set PHP's memory limit to the larger of php.ini or $wgMemoryLimit;
3272 * @return Integer value memory was set to.
3274 function wfMemoryLimit() {
3275 global $wgMemoryLimit;
3276 $memlimit = wfShorthandToInteger( ini_get( "memory_limit" ) );
3277 $conflimit = wfShorthandToInteger( $wgMemoryLimit );
3278 if( $memlimit != -1 ) {
3279 if( $conflimit == -1 ) {
3280 wfDebug( "Removing PHP's memory limit\n" );
3281 wfSuppressWarnings();
3282 ini_set( "memory_limit", $conflimit );
3283 wfRestoreWarnings();
3285 } elseif ( $conflimit > $memlimit ) {
3286 wfDebug( "Raising PHP's memory limit to $conflimit bytes\n" );
3287 wfSuppressWarnings();
3288 ini_set( "memory_limit", $conflimit );
3289 wfRestoreWarnings();
3297 * Converts shorthand byte notation to integer form
3298 * @param $string String
3301 function wfShorthandToInteger ( $string = '' ) {
3302 $string = trim($string);
3303 if( empty($string) ) { return -1; }
3304 $last = strtolower($string[strlen($string)-1]);
3305 $val = intval($string);
3318 /* Get the normalised IETF language tag
3319 * @param $code String: The language code.
3320 * @return $langCode String: The language code which complying with BCP 47 standards.
3322 function wfBCP47( $code ) {
3323 $codeSegment = explode( '-', $code );
3324 foreach ( $codeSegment as $segNo => $seg ) {
3325 if ( count( $codeSegment ) > 0 ) {
3326 // ISO 3166 country code
3327 if ( ( strlen( $seg ) == 2 ) && ( $segNo > 0 ) )
3328 $codeBCP[$segNo] = strtoupper( $seg );
3329 // ISO 15924 script code
3330 else if ( ( strlen( $seg ) == 4 ) && ( $segNo > 0 ) )
3331 $codeBCP[$segNo] = ucfirst( $seg );
3332 // Use lowercase for other cases
3334 $codeBCP[$segNo] = strtolower( $seg );
3336 // Use lowercase for single segment
3337 $codeBCP[$segNo] = strtolower( $seg );
3340 $langCode = implode ( '-' , $codeBCP );
3344 function wfArrayMap( $function, $input ) {
3345 $ret = array_map( $function, $input );
3346 foreach ( $ret as $key => $value ) {
3347 $taint = istainted( $input[$key] );
3349 taint( $ret[$key], $taint );