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" );
567 * Use this instead of $wgContLang, when working with user interface.
568 * User interface is currently hard coded according to wiki content language
569 * in many ways, especially regarding to text direction. There is lots stuff
570 * to fix, hence this function to keep the old behaviour unless the global
571 * $wgBetterDirectionality is enabled (or removed when everything works).
573 function wfUILang() {
574 global $wgBetterDirectionality;
575 return wfGetLangObj( !$wgBetterDirectionality );
579 * Get a message from anywhere, for the current user language.
581 * Use wfMsgForContent() instead if the message should NOT
582 * change depending on the user preferences.
584 * @param $key String: lookup key for the message, usually
585 * defined in languages/Language.php
587 * This function also takes extra optional parameters (not
588 * shown in the function definition), which can be used to
589 * insert variable text into the predefined message.
591 function wfMsg( $key ) {
592 $args = func_get_args();
593 array_shift( $args );
594 return wfMsgReal( $key, $args, true );
598 * Same as above except doesn't transform the message
600 function wfMsgNoTrans( $key ) {
601 $args = func_get_args();
602 array_shift( $args );
603 return wfMsgReal( $key, $args, true, false, false );
607 * Get a message from anywhere, for the current global language
608 * set with $wgLanguageCode.
610 * Use this if the message should NOT change dependent on the
611 * language set in the user's preferences. This is the case for
612 * most text written into logs, as well as link targets (such as
613 * the name of the copyright policy page). Link titles, on the
614 * other hand, should be shown in the UI language.
616 * Note that MediaWiki allows users to change the user interface
617 * language in their preferences, but a single installation
618 * typically only contains content in one language.
620 * Be wary of this distinction: If you use wfMsg() where you should
621 * use wfMsgForContent(), a user of the software may have to
622 * customize potentially hundreds of messages in
623 * order to, e.g., fix a link in every possible language.
625 * @param $key String: lookup key for the message, usually
626 * defined in languages/Language.php
628 function wfMsgForContent( $key ) {
629 global $wgForceUIMsgAsContentMsg;
630 $args = func_get_args();
631 array_shift( $args );
633 if( is_array( $wgForceUIMsgAsContentMsg ) &&
634 in_array( $key, $wgForceUIMsgAsContentMsg ) )
636 return wfMsgReal( $key, $args, true, $forcontent );
640 * Same as above except doesn't transform the message
642 function wfMsgForContentNoTrans( $key ) {
643 global $wgForceUIMsgAsContentMsg;
644 $args = func_get_args();
645 array_shift( $args );
647 if( is_array( $wgForceUIMsgAsContentMsg ) &&
648 in_array( $key, $wgForceUIMsgAsContentMsg ) )
650 return wfMsgReal( $key, $args, true, $forcontent, false );
654 * Get a message from the language file, for the UI elements
656 function wfMsgNoDB( $key ) {
657 $args = func_get_args();
658 array_shift( $args );
659 return wfMsgReal( $key, $args, false );
663 * Get a message from the language file, for the content
665 function wfMsgNoDBForContent( $key ) {
666 global $wgForceUIMsgAsContentMsg;
667 $args = func_get_args();
668 array_shift( $args );
670 if( is_array( $wgForceUIMsgAsContentMsg ) &&
671 in_array( $key, $wgForceUIMsgAsContentMsg ) )
673 return wfMsgReal( $key, $args, false, $forcontent );
678 * Really get a message
679 * @param $key String: key to get.
681 * @param $useDB Boolean
682 * @param $forContent Mixed: Language code, or false for user lang, true for content lang.
683 * @param $transform Boolean: Whether or not to transform the message.
684 * @return String: the requested message.
686 function wfMsgReal( $key, $args, $useDB = true, $forContent = false, $transform = true ) {
687 wfProfileIn( __METHOD__
);
688 $message = wfMsgGetKey( $key, $useDB, $forContent, $transform );
689 $message = wfMsgReplaceArgs( $message, $args );
690 wfProfileOut( __METHOD__
);
695 * This function provides the message source for messages to be edited which are *not* stored in the database.
696 * @param $key String:
698 function wfMsgWeirdKey( $key ) {
699 $source = wfMsgGetKey( $key, false, true, false );
700 if ( wfEmptyMsg( $key, $source ) )
707 * Fetch a message string value, but don't replace any keys yet.
710 * @param $langCode String: Code of the language to get the message for, or
711 * behaves as a content language switch if it is a boolean.
712 * @param $transform Boolean: whether to parse magic words, etc.
715 function wfMsgGetKey( $key, $useDB, $langCode = false, $transform = true ) {
716 global $wgMessageCache;
718 wfRunHooks('NormalizeMessageKey', array(&$key, &$useDB, &$langCode, &$transform));
720 if ( !is_object( $wgMessageCache ) ) {
721 throw new MWException( "Trying to get message before message cache is initialised" );
724 $message = $wgMessageCache->get( $key, $useDB, $langCode );
725 if( $message === false ){
726 $message = '<' . htmlspecialchars( $key ) . '>';
727 } elseif ( $transform ) {
728 $message = $wgMessageCache->transform( $message );
734 * Replace message parameter keys on the given formatted output.
736 * @param $message String
741 function wfMsgReplaceArgs( $message, $args ) {
742 # Fix windows line-endings
743 # Some messages are split with explode("\n", $msg)
744 $message = str_replace( "\r", '', $message );
747 if ( count( $args ) ) {
748 if ( is_array( $args[0] ) ) {
749 $args = array_values( $args[0] );
751 $replacementKeys = array();
752 foreach( $args as $n => $param ) {
753 $replacementKeys['$' . ($n +
1)] = $param;
755 $message = strtr( $message, $replacementKeys );
762 * Return an HTML-escaped version of a message.
763 * Parameter replacements, if any, are done *after* the HTML-escaping,
764 * so parameters may contain HTML (eg links or form controls). Be sure
765 * to pre-escape them if you really do want plaintext, or just wrap
766 * the whole thing in htmlspecialchars().
769 * @param string ... parameters
772 function wfMsgHtml( $key ) {
773 $args = func_get_args();
774 array_shift( $args );
775 return wfMsgReplaceArgs( htmlspecialchars( wfMsgGetKey( $key, true ) ), $args );
779 * Return an HTML version of message
780 * Parameter replacements, if any, are done *after* parsing the wiki-text message,
781 * so parameters may contain HTML (eg links or form controls). Be sure
782 * to pre-escape them if you really do want plaintext, or just wrap
783 * the whole thing in htmlspecialchars().
786 * @param string ... parameters
789 function wfMsgWikiHtml( $key ) {
791 $args = func_get_args();
792 array_shift( $args );
793 return wfMsgReplaceArgs( $wgOut->parse( wfMsgGetKey( $key, true ), /* can't be set to false */ true ), $args );
797 * Returns message in the requested format
798 * @param $key String: key of the message
799 * @param $options Array: processing rules. Can take the following options:
800 * <i>parse</i>: parses wikitext to html
801 * <i>parseinline</i>: parses wikitext to html and removes the surrounding
802 * p's added by parser or tidy
803 * <i>escape</i>: filters message through htmlspecialchars
804 * <i>escapenoentities</i>: same, but allows entity references like   through
805 * <i>replaceafter</i>: parameters are substituted after parsing or escaping
806 * <i>parsemag</i>: transform the message using magic phrases
807 * <i>content</i>: fetch message for content language instead of interface
808 * Also can accept a single associative argument, of the form 'language' => 'xx':
809 * <i>language</i>: Language object or language code to fetch message for
810 * (overriden by <i>content</i>), its behaviour with parser, parseinline
811 * and parsemag is undefined.
812 * Behavior for conflicting options (e.g., parse+parseinline) is undefined.
814 function wfMsgExt( $key, $options ) {
817 $args = func_get_args();
818 array_shift( $args );
819 array_shift( $args );
820 $options = (array)$options;
822 foreach( $options as $arrayKey => $option ) {
823 if( !preg_match( '/^[0-9]+|language$/', $arrayKey ) ) {
824 # An unknown index, neither numeric nor "language"
825 wfWarn( "wfMsgExt called with incorrect parameter key $arrayKey", 1, E_USER_WARNING
);
826 } elseif( preg_match( '/^[0-9]+$/', $arrayKey ) && !in_array( $option,
827 array( 'parse', 'parseinline', 'escape', 'escapenoentities',
828 'replaceafter', 'parsemag', 'content' ) ) ) {
829 # A numeric index with unknown value
830 wfWarn( "wfMsgExt called with incorrect parameter $option", 1, E_USER_WARNING
);
834 if( in_array('content', $options, true ) ) {
837 } elseif( array_key_exists('language', $options) ) {
839 $langCode = wfGetLangObj( $options['language'] );
845 $string = wfMsgGetKey( $key, /*DB*/true, $langCode, /*Transform*/false );
847 if( !in_array('replaceafter', $options, true ) ) {
848 $string = wfMsgReplaceArgs( $string, $args );
851 if( in_array('parse', $options, true ) ) {
852 $string = $wgOut->parse( $string, true, !$forContent );
853 } elseif ( in_array('parseinline', $options, true ) ) {
854 $string = $wgOut->parse( $string, true, !$forContent );
856 if( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $string, $m ) ) {
859 } elseif ( in_array('parsemag', $options, true ) ) {
860 global $wgMessageCache;
861 if ( isset( $wgMessageCache ) ) {
862 $string = $wgMessageCache->transform( $string,
864 is_object( $langCode ) ?
$langCode : null );
868 if ( in_array('escape', $options, true ) ) {
869 $string = htmlspecialchars ( $string );
870 } elseif ( in_array( 'escapenoentities', $options, true ) ) {
871 $string = Sanitizer
::escapeHtmlAllowEntities( $string );
874 if( in_array('replaceafter', $options, true ) ) {
875 $string = wfMsgReplaceArgs( $string, $args );
883 * Just like exit() but makes a note of it.
884 * Commits open transactions except if the error parameter is set
886 * @deprecated Please return control to the caller or throw an exception
888 function wfAbruptExit( $error = false ){
889 static $called = false;
895 $bt = wfDebugBacktrace();
897 for($i = 0; $i < count($bt) ; $i++
){
898 $file = isset($bt[$i]['file']) ?
$bt[$i]['file'] : "unknown";
899 $line = isset($bt[$i]['line']) ?
$bt[$i]['line'] : "unknown";
900 wfDebug("WARNING: Abrupt exit in $file at line $line\n");
903 wfDebug("WARNING: Abrupt exit\n");
906 wfLogProfilingData();
909 wfGetLB()->closeAll();
915 * @deprecated Please return control the caller or throw an exception
917 function wfErrorExit() {
918 wfAbruptExit( true );
922 * Print a simple message and die, returning nonzero to the shell if any.
923 * Plain die() fails to return nonzero to the shell if you pass a string.
926 function wfDie( $msg='' ) {
932 * Throw a debugging exception. This function previously once exited the process,
933 * but now throws an exception instead, with similar results.
935 * @param $msg String: message shown when dieing.
937 function wfDebugDieBacktrace( $msg = '' ) {
938 throw new MWException( $msg );
942 * Fetch server name for use in error reporting etc.
943 * Use real server name if available, so we know which machine
944 * in a server farm generated the current page.
947 function wfHostname() {
949 if ( is_null( $host ) ) {
950 if ( function_exists( 'posix_uname' ) ) {
951 // This function not present on Windows
952 $uname = @posix_uname
();
956 if( is_array( $uname ) && isset( $uname['nodename'] ) ) {
957 $host = $uname['nodename'];
958 } elseif ( getenv( 'COMPUTERNAME' ) ) {
959 # Windows computer name
960 $host = getenv( 'COMPUTERNAME' );
962 # This may be a virtual server.
963 $host = $_SERVER['SERVER_NAME'];
970 * Returns a HTML comment with the elapsed time since request.
971 * This method has no side effects.
974 function wfReportTime() {
975 global $wgRequestTime, $wgShowHostnames;
978 $elapsed = $now - $wgRequestTime;
980 return $wgShowHostnames
981 ?
sprintf( "<!-- Served by %s in %01.3f secs. -->", wfHostname(), $elapsed )
982 : sprintf( "<!-- Served in %01.3f secs. -->", $elapsed );
986 * Safety wrapper for debug_backtrace().
988 * With Zend Optimizer 3.2.0 loaded, this causes segfaults under somewhat
989 * murky circumstances, which may be triggered in part by stub objects
990 * or other fancy talkin'.
992 * Will return an empty array if Zend Optimizer is detected or if
993 * debug_backtrace is disabled, otherwise the output from
994 * debug_backtrace() (trimmed).
996 * @return array of backtrace information
998 function wfDebugBacktrace() {
999 static $disabled = null;
1001 if( extension_loaded( 'Zend Optimizer' ) ) {
1002 wfDebug( "Zend Optimizer detected; skipping debug_backtrace for safety.\n" );
1006 if ( is_null( $disabled ) ) {
1008 $functions = explode( ',', ini_get( 'disable_functions' ) );
1009 $functions = array_map( 'trim', $functions );
1010 $functions = array_map( 'strtolower', $functions );
1011 if ( in_array( 'debug_backtrace', $functions ) ) {
1012 wfDebug( "debug_backtrace is in disabled_functions\n" );
1020 return array_slice( debug_backtrace(), 1 );
1023 function wfBacktrace() {
1024 global $wgCommandLineMode;
1026 if ( $wgCommandLineMode ) {
1031 $backtrace = wfDebugBacktrace();
1032 foreach( $backtrace as $call ) {
1033 if( isset( $call['file'] ) ) {
1034 $f = explode( DIRECTORY_SEPARATOR
, $call['file'] );
1035 $file = $f[count($f)-1];
1039 if( isset( $call['line'] ) ) {
1040 $line = $call['line'];
1044 if ( $wgCommandLineMode ) {
1045 $msg .= "$file line $line calls ";
1047 $msg .= '<li>' . $file . ' line ' . $line . ' calls ';
1049 if( !empty( $call['class'] ) ) $msg .= $call['class'] . '::';
1050 $msg .= $call['function'] . '()';
1052 if ( $wgCommandLineMode ) {
1058 if ( $wgCommandLineMode ) {
1068 /* Some generic result counters, pulled out of SearchEngine */
1074 function wfShowingResults( $offset, $limit ) {
1076 return wfMsgExt( 'showingresults', array( 'parseinline' ), $wgLang->formatNum( $limit ),
1077 $wgLang->formatNum( $offset+
1 ) );
1083 function wfShowingResultsNum( $offset, $limit, $num ) {
1085 return wfMsgExt( 'showingresultsnum', array( 'parseinline' ), $wgLang->formatNum( $limit ),
1086 $wgLang->formatNum( $offset+
1 ), $wgLang->formatNum( $num ) );
1090 * Generate (prev x| next x) (20|50|100...) type links for paging
1091 * @param $offset String
1092 * @param $limit Integer
1093 * @param $link String
1094 * @param $query String: optional URL query parameter string
1095 * @param $atend Bool: optional param for specified if this is the last page
1097 function wfViewPrevNext( $offset, $limit, $link, $query = '', $atend = false ) {
1099 $fmtLimit = $wgLang->formatNum( $limit );
1100 // FIXME: Why on earth this needs one message for the text and another one for tooltip??
1101 # Get prev/next link display text
1102 $prev = wfMsgExt( 'prevn', array('parsemag','escape'), $fmtLimit );
1103 $next = wfMsgExt( 'nextn', array('parsemag','escape'), $fmtLimit );
1104 # Get prev/next link title text
1105 $pTitle = wfMsgExt( 'prevn-title', array('parsemag','escape'), $fmtLimit );
1106 $nTitle = wfMsgExt( 'nextn-title', array('parsemag','escape'), $fmtLimit );
1107 # Fetch the title object
1108 if( is_object( $link ) ) {
1111 $title = Title
::newFromText( $link );
1112 if( is_null( $title ) ) {
1116 # Make 'previous' link
1117 if( 0 != $offset ) {
1118 $po = $offset - $limit;
1120 $q = "limit={$limit}&offset={$po}";
1121 if( $query != '' ) {
1124 $plink = '<a href="' . $title->escapeLocalUrl( $q ) . "\" title=\"{$pTitle}\" class=\"mw-prevlink\">{$prev}</a>";
1129 $no = $offset +
$limit;
1130 $q = "limit={$limit}&offset={$no}";
1131 if( $query != '' ) {
1137 $nlink = '<a href="' . $title->escapeLocalUrl( $q ) . "\" title=\"{$nTitle}\" class=\"mw-nextlink\">{$next}</a>";
1139 # Make links to set number of items per page
1140 $nums = $wgLang->pipeList( array(
1141 wfNumLink( $offset, 20, $title, $query ),
1142 wfNumLink( $offset, 50, $title, $query ),
1143 wfNumLink( $offset, 100, $title, $query ),
1144 wfNumLink( $offset, 250, $title, $query ),
1145 wfNumLink( $offset, 500, $title, $query )
1147 return wfMsgHtml( 'viewprevnext', $plink, $nlink, $nums );
1151 * Generate links for (20|50|100...) items-per-page links
1152 * @param $offset String
1153 * @param $limit Integer
1154 * @param $title Title
1155 * @param $query String: optional URL query parameter string
1157 function wfNumLink( $offset, $limit, $title, $query = '' ) {
1159 if( $query == '' ) {
1164 $q .= "limit={$limit}&offset={$offset}";
1165 $fmtLimit = $wgLang->formatNum( $limit );
1166 $lTitle = wfMsgExt('shown-title',array('parsemag','escape'),$limit);
1167 $s = '<a href="' . $title->escapeLocalUrl( $q ) . "\" title=\"{$lTitle}\" class=\"mw-numlink\">{$fmtLimit}</a>";
1173 * @todo FIXME: we may want to blacklist some broken browsers
1175 * @return bool Whereas client accept gzip compression
1177 function wfClientAcceptsGzip() {
1178 if( isset( $_SERVER['HTTP_ACCEPT_ENCODING'] ) ) {
1179 # FIXME: we may want to blacklist some broken browsers
1182 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
1183 $_SERVER['HTTP_ACCEPT_ENCODING'],
1185 if( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) return false;
1186 wfDebug( " accepts gzip\n" );
1194 * Obtain the offset and limit values from the request string;
1195 * used in special pages
1197 * @param $deflimit Default limit if none supplied
1198 * @param $optionname Name of a user preference to check against
1202 function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) {
1204 return $wgRequest->getLimitOffset( $deflimit, $optionname );
1208 * Escapes the given text so that it may be output using addWikiText()
1209 * without any linking, formatting, etc. making its way through. This
1210 * is achieved by substituting certain characters with HTML entities.
1211 * As required by the callers, <nowiki> is not used. It currently does
1212 * not filter out characters which have special meaning only at the
1213 * start of a line, such as "*".
1215 * @param $text String: text to be escaped
1217 function wfEscapeWikiText( $text ) {
1218 $text = str_replace(
1219 array( '[', '|', ']', '\'', 'ISBN ', 'RFC ', '://', "\n=", '{{' ), # }}
1220 array( '[', '|', ']', ''', 'ISBN ', 'RFC ', '://', "\n=", '{{' ),
1221 htmlspecialchars($text) );
1228 function wfQuotedPrintable( $string, $charset = '' ) {
1229 # Probably incomplete; see RFC 2045
1230 if( empty( $charset ) ) {
1231 global $wgInputEncoding;
1232 $charset = $wgInputEncoding;
1234 $charset = strtoupper( $charset );
1235 $charset = str_replace( 'ISO-8859', 'ISO8859', $charset ); // ?
1237 $illegal = '\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\xff=';
1238 $replace = $illegal . '\t ?_';
1239 if( !preg_match( "/[$illegal]/", $string ) ) return $string;
1240 $out = "=?$charset?Q?";
1241 $out .= preg_replace( "/([$replace])/e", 'sprintf("=%02X",ord("$1"))', $string );
1252 return microtime(true);
1256 * Sets dest to source and returns the original value of dest
1257 * If source is NULL, it just returns the value, it doesn't set the variable
1259 function wfSetVar( &$dest, $source ) {
1261 if ( !is_null( $source ) ) {
1268 * As for wfSetVar except setting a bit
1270 function wfSetBit( &$dest, $bit, $state = true ) {
1271 $temp = (bool)($dest & $bit );
1272 if ( !is_null( $state ) ) {
1283 * This function takes two arrays as input, and returns a CGI-style string, e.g.
1284 * "days=7&limit=100". Options in the first array override options in the second.
1285 * Options set to "" will not be output.
1287 function wfArrayToCGI( $array1, $array2 = null )
1289 if ( !is_null( $array2 ) ) {
1290 $array1 = $array1 +
$array2;
1294 foreach ( $array1 as $key => $value ) {
1295 if ( $value !== '' ) {
1299 if ( is_array( $value ) ) {
1301 foreach ( $value as $v ) {
1302 $cgi .= ( $firstTime ?
'' : '&') .
1303 urlencode( $key . '[]' ) . '=' .
1308 if ( is_object( $value ) ) {
1309 $value = $value->__toString();
1311 $cgi .= urlencode( $key ) . '=' .
1312 urlencode( $value );
1320 * This is the logical opposite of wfArrayToCGI(): it accepts a query string as
1321 * its argument and returns the same string in array form. This allows compa-
1322 * tibility with legacy functions that accept raw query strings instead of nice
1323 * arrays. Of course, keys and values are urldecode()d. Don't try passing in-
1324 * valid query strings, or it will explode.
1326 * @param $query String: query string
1327 * @return array Array version of input
1329 function wfCgiToArray( $query ) {
1330 if( isset( $query[0] ) and $query[0] == '?' ) {
1331 $query = substr( $query, 1 );
1333 $bits = explode( '&', $query );
1335 foreach( $bits as $bit ) {
1339 list( $key, $value ) = explode( '=', $bit );
1340 $key = urldecode( $key );
1341 $value = urldecode( $value );
1342 $ret[$key] = $value;
1348 * Append a query string to an existing URL, which may or may not already
1349 * have query string parameters already. If so, they will be combined.
1351 * @param $url String
1352 * @param $query Mixed: string or associative array
1355 function wfAppendQuery( $url, $query ) {
1356 if ( is_array( $query ) ) {
1357 $query = wfArrayToCGI( $query );
1359 if( $query != '' ) {
1360 if( false === strpos( $url, '?' ) ) {
1371 * Expand a potentially local URL to a fully-qualified URL. Assumes $wgServer
1372 * and $wgProto are correct.
1374 * @todo this won't work with current-path-relative URLs
1375 * like "subdir/foo.html", etc.
1377 * @param $url String: either fully-qualified or a local path + query
1378 * @return string Fully-qualified URL
1380 function wfExpandUrl( $url ) {
1381 if( substr( $url, 0, 2 ) == '//' ) {
1383 return $wgProto . ':' . $url;
1384 } elseif( substr( $url, 0, 1 ) == '/' ) {
1386 return $wgServer . $url;
1393 * This is obsolete, use SquidUpdate::purge()
1396 function wfPurgeSquidServers ($urlArr) {
1397 SquidUpdate
::purge( $urlArr );
1401 * Windows-compatible version of escapeshellarg()
1402 * Windows doesn't recognise single-quotes in the shell, but the escapeshellarg()
1403 * function puts single quotes in regardless of OS.
1405 * Also fixes the locale problems on Linux in PHP 5.2.6+ (bug backported to
1406 * earlier distro releases of PHP)
1408 function wfEscapeShellArg( ) {
1409 wfInitShellLocale();
1411 $args = func_get_args();
1414 foreach ( $args as $arg ) {
1421 if ( wfIsWindows() ) {
1422 // Escaping for an MSVC-style command line parser
1423 // Ref: http://mailman.lyra.org/pipermail/scite-interest/2002-March/000436.html
1424 // Double the backslashes before any double quotes. Escape the double quotes.
1425 $tokens = preg_split( '/(\\\\*")/', $arg, -1, PREG_SPLIT_DELIM_CAPTURE
);
1428 foreach ( $tokens as $token ) {
1429 if ( $iteration %
2 == 1 ) {
1430 // Delimiter, a double quote preceded by zero or more slashes
1431 $arg .= str_replace( '\\', '\\\\', substr( $token, 0, -1 ) ) . '\\"';
1432 } else if ( $iteration %
4 == 2 ) {
1433 // ^ in $token will be outside quotes, need to be escaped
1434 $arg .= str_replace( '^', '^^', $token );
1435 } else { // $iteration % 4 == 0
1436 // ^ in $token will appear inside double quotes, so leave as is
1441 // Double the backslashes before the end of the string, because
1442 // we will soon add a quote
1444 if ( preg_match( '/^(.*?)(\\\\+)$/', $arg, $m ) ) {
1445 $arg = $m[1] . str_replace( '\\', '\\\\', $m[2] );
1448 // Add surrounding quotes
1449 $retVal .= '"' . $arg . '"';
1451 $retVal .= escapeshellarg( $arg );
1458 * wfMerge attempts to merge differences between three texts.
1459 * Returns true for a clean merge and false for failure or a conflict.
1461 function wfMerge( $old, $mine, $yours, &$result ){
1464 # This check may also protect against code injection in
1465 # case of broken installations.
1466 if( !$wgDiff3 ||
!file_exists( $wgDiff3 ) ) {
1467 wfDebug( "diff3 not found\n" );
1471 # Make temporary files
1473 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
1474 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
1475 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
1477 fwrite( $oldtextFile, $old ); fclose( $oldtextFile );
1478 fwrite( $mytextFile, $mine ); fclose( $mytextFile );
1479 fwrite( $yourtextFile, $yours ); fclose( $yourtextFile );
1481 # Check for a conflict
1482 $cmd = $wgDiff3 . ' -a --overlap-only ' .
1483 wfEscapeShellArg( $mytextName ) . ' ' .
1484 wfEscapeShellArg( $oldtextName ) . ' ' .
1485 wfEscapeShellArg( $yourtextName );
1486 $handle = popen( $cmd, 'r' );
1488 if( fgets( $handle, 1024 ) ){
1496 $cmd = $wgDiff3 . ' -a -e --merge ' .
1497 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
1498 $handle = popen( $cmd, 'r' );
1501 $data = fread( $handle, 8192 );
1502 if ( strlen( $data ) == 0 ) {
1508 unlink( $mytextName ); unlink( $oldtextName ); unlink( $yourtextName );
1510 if ( $result === '' && $old !== '' && !$conflict ) {
1511 wfDebug( "Unexpected null result from diff3. Command: $cmd\n" );
1518 * Returns unified plain-text diff of two texts.
1519 * Useful for machine processing of diffs.
1520 * @param $before String: the text before the changes.
1521 * @param $after String: the text after the changes.
1522 * @param $params String: command-line options for the diff command.
1523 * @return String: unified diff of $before and $after
1525 function wfDiff( $before, $after, $params = '-u' ) {
1526 if ($before == $after) {
1532 # This check may also protect against code injection in
1533 # case of broken installations.
1534 if( !file_exists( $wgDiff ) ){
1535 wfDebug( "diff executable not found\n" );
1536 $diffs = new Diff( explode( "\n", $before ), explode( "\n", $after ) );
1537 $format = new UnifiedDiffFormatter();
1538 return $format->format( $diffs );
1541 # Make temporary files
1543 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
1544 $newtextFile = fopen( $newtextName = tempnam( $td, 'merge-your-' ), 'w' );
1546 fwrite( $oldtextFile, $before ); fclose( $oldtextFile );
1547 fwrite( $newtextFile, $after ); fclose( $newtextFile );
1549 // Get the diff of the two files
1550 $cmd = "$wgDiff " . $params . ' ' .wfEscapeShellArg( $oldtextName, $newtextName );
1552 $h = popen( $cmd, 'r' );
1557 $data = fread( $h, 8192 );
1558 if ( strlen( $data ) == 0 ) {
1566 unlink( $oldtextName );
1567 unlink( $newtextName );
1569 // Kill the --- and +++ lines. They're not useful.
1570 $diff_lines = explode( "\n", $diff );
1571 if (strpos( $diff_lines[0], '---' ) === 0) {
1572 unset($diff_lines[0]);
1574 if (strpos( $diff_lines[1], '+++' ) === 0) {
1575 unset($diff_lines[1]);
1578 $diff = implode( "\n", $diff_lines );
1584 * A wrapper around the PHP function var_export().
1585 * Either print it or add it to the regular output ($wgOut).
1587 * @param $var A PHP variable to dump.
1589 function wfVarDump( $var ) {
1591 $s = str_replace("\n","<br />\n", var_export( $var, true ) . "\n");
1592 if ( headers_sent() ||
!@is_object
( $wgOut ) ) {
1595 $wgOut->addHTML( $s );
1600 * Provide a simple HTTP error.
1602 function wfHttpError( $code, $label, $desc ) {
1605 header( "HTTP/1.0 $code $label" );
1606 header( "Status: $code $label" );
1607 $wgOut->sendCacheControl();
1609 header( 'Content-type: text/html; charset=utf-8' );
1610 print "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">".
1611 "<html><head><title>" .
1612 htmlspecialchars( $label ) .
1613 "</title></head><body><h1>" .
1614 htmlspecialchars( $label ) .
1616 nl2br( htmlspecialchars( $desc ) ) .
1617 "</p></body></html>\n";
1621 * Clear away any user-level output buffers, discarding contents.
1623 * Suitable for 'starting afresh', for instance when streaming
1624 * relatively large amounts of data without buffering, or wanting to
1625 * output image files without ob_gzhandler's compression.
1627 * The optional $resetGzipEncoding parameter controls suppression of
1628 * the Content-Encoding header sent by ob_gzhandler; by default it
1629 * is left. See comments for wfClearOutputBuffers() for why it would
1632 * Note that some PHP configuration options may add output buffer
1633 * layers which cannot be removed; these are left in place.
1635 * @param $resetGzipEncoding Bool
1637 function wfResetOutputBuffers( $resetGzipEncoding=true ) {
1638 if( $resetGzipEncoding ) {
1639 // Suppress Content-Encoding and Content-Length
1640 // headers from 1.10+s wfOutputHandler
1641 global $wgDisableOutputCompression;
1642 $wgDisableOutputCompression = true;
1644 while( $status = ob_get_status() ) {
1645 if( $status['type'] == 0 /* PHP_OUTPUT_HANDLER_INTERNAL */ ) {
1646 // Probably from zlib.output_compression or other
1647 // PHP-internal setting which can't be removed.
1649 // Give up, and hope the result doesn't break
1653 if( !ob_end_clean() ) {
1654 // Could not remove output buffer handler; abort now
1655 // to avoid getting in some kind of infinite loop.
1658 if( $resetGzipEncoding ) {
1659 if( $status['name'] == 'ob_gzhandler' ) {
1660 // Reset the 'Content-Encoding' field set by this handler
1661 // so we can start fresh.
1662 header( 'Content-Encoding:' );
1670 * More legible than passing a 'false' parameter to wfResetOutputBuffers():
1672 * Clear away output buffers, but keep the Content-Encoding header
1673 * produced by ob_gzhandler, if any.
1675 * This should be used for HTTP 304 responses, where you need to
1676 * preserve the Content-Encoding header of the real result, but
1677 * also need to suppress the output of ob_gzhandler to keep to spec
1678 * and avoid breaking Firefox in rare cases where the headers and
1679 * body are broken over two packets.
1681 function wfClearOutputBuffers() {
1682 wfResetOutputBuffers( false );
1686 * Converts an Accept-* header into an array mapping string values to quality
1689 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
1690 # No arg means accept anything (per HTTP spec)
1692 return array( $def => 1.0 );
1697 $parts = explode( ',', $accept );
1699 foreach( $parts as $part ) {
1700 # FIXME: doesn't deal with params like 'text/html; level=1'
1701 @list
( $value, $qpart ) = explode( ';', trim( $part ) );
1703 if( !isset( $qpart ) ) {
1704 $prefs[$value] = 1.0;
1705 } elseif( preg_match( '/q\s*=\s*(\d*\.\d+)/', $qpart, $match ) ) {
1706 $prefs[$value] = floatval($match[1]);
1714 * Checks if a given MIME type matches any of the keys in the given
1715 * array. Basic wildcards are accepted in the array keys.
1717 * Returns the matching MIME type (or wildcard) if a match, otherwise
1720 * @param $type String
1721 * @param $avail Array
1725 function mimeTypeMatch( $type, $avail ) {
1726 if( array_key_exists($type, $avail) ) {
1729 $parts = explode( '/', $type );
1730 if( array_key_exists( $parts[0] . '/*', $avail ) ) {
1731 return $parts[0] . '/*';
1732 } elseif( array_key_exists( '*/*', $avail ) ) {
1741 * Returns the 'best' match between a client's requested internet media types
1742 * and the server's list of available types. Each list should be an associative
1743 * array of type to preference (preference is a float between 0.0 and 1.0).
1744 * Wildcards in the types are acceptable.
1746 * @param $cprefs Array: client's acceptable type list
1747 * @param $sprefs Array: server's offered types
1750 * @todo FIXME: doesn't handle params like 'text/plain; charset=UTF-8'
1751 * XXX: generalize to negotiate other stuff
1753 function wfNegotiateType( $cprefs, $sprefs ) {
1756 foreach( array_keys($sprefs) as $type ) {
1757 $parts = explode( '/', $type );
1758 if( $parts[1] != '*' ) {
1759 $ckey = mimeTypeMatch( $type, $cprefs );
1761 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1766 foreach( array_keys( $cprefs ) as $type ) {
1767 $parts = explode( '/', $type );
1768 if( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
1769 $skey = mimeTypeMatch( $type, $sprefs );
1771 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1779 foreach( array_keys( $combine ) as $type ) {
1780 if( $combine[$type] > $bestq ) {
1782 $bestq = $combine[$type];
1791 * Returns an array where the values in the first array are replaced by the
1792 * values in the second array with the corresponding keys
1796 function wfArrayLookup( $a, $b ) {
1797 return array_flip( array_intersect( array_flip( $a ), array_keys( $b ) ) );
1801 * Convenience function; returns MediaWiki timestamp for the present time.
1804 function wfTimestampNow() {
1806 return wfTimestamp( TS_MW
, time() );
1810 * Reference-counted warning suppression
1812 function wfSuppressWarnings( $end = false ) {
1813 static $suppressCount = 0;
1814 static $originalLevel = false;
1817 if ( $suppressCount ) {
1819 if ( !$suppressCount ) {
1820 error_reporting( $originalLevel );
1824 if ( !$suppressCount ) {
1825 $originalLevel = error_reporting( E_ALL
& ~
( E_WARNING | E_NOTICE | E_USER_WARNING | E_USER_NOTICE
) );
1832 * Restore error level to previous value
1834 function wfRestoreWarnings() {
1835 wfSuppressWarnings( true );
1838 # Autodetect, convert and provide timestamps of various types
1841 * Unix time - the number of seconds since 1970-01-01 00:00:00 UTC
1843 define('TS_UNIX', 0);
1846 * MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
1851 * MySQL DATETIME (YYYY-MM-DD HH:MM:SS)
1856 * RFC 2822 format, for E-mail and HTTP headers
1858 define('TS_RFC2822', 3);
1861 * ISO 8601 format with no timezone: 1986-02-09T20:00:00Z
1863 * This is used by Special:Export
1865 define('TS_ISO_8601', 4);
1868 * An Exif timestamp (YYYY:MM:DD HH:MM:SS)
1870 * @see http://exif.org/Exif2-2.PDF The Exif 2.2 spec, see page 28 for the
1871 * DateTime tag and page 36 for the DateTimeOriginal and
1872 * DateTimeDigitized tags.
1874 define('TS_EXIF', 5);
1877 * Oracle format time.
1879 define('TS_ORACLE', 6);
1882 * Postgres format time.
1884 define('TS_POSTGRES', 7);
1889 define('TS_DB2', 8);
1892 * @param $outputtype Mixed: A timestamp in one of the supported formats, the
1893 * function will autodetect which format is supplied and act
1895 * @param $ts Mixed: the timestamp to convert or 0 for the current timestamp
1896 * @return String: in the format specified in $outputtype
1898 function wfTimestamp( $outputtype = TS_UNIX
, $ts = 0 ) {
1903 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)$/D',$ts,$da)) {
1905 } elseif (preg_match('/^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/D',$ts,$da)) {
1907 } elseif (preg_match('/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/D',$ts,$da)) {
1909 } elseif (preg_match('/^-?\d{1,13}$/D',$ts)) {
1912 } elseif (preg_match('/^\d{2}-\d{2}-\d{4} \d{2}:\d{2}:\d{2}.\d{6}$/', $ts)) {
1913 # TS_ORACLE // session altered to DD-MM-YYYY HH24:MI:SS.FF6
1914 $uts = strtotime(preg_replace('/(\d\d)\.(\d\d)\.(\d\d)(\.(\d+))?/', "$1:$2:$3",
1915 str_replace("+00:00", "UTC", $ts)));
1916 } elseif (preg_match('/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.*\d*)?Z$/', $ts, $da)) {
1918 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.*\d*[\+\- ](\d\d)$/',$ts,$da)) {
1920 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.*\d* GMT$/',$ts,$da)) {
1923 # Bogus value; fall back to the epoch...
1924 wfDebug("wfTimestamp() fed bogus time value: $outputtype; $ts\n");
1928 if (count( $da ) ) {
1929 // Warning! gmmktime() acts oddly if the month or day is set to 0
1930 // We may want to handle that explicitly at some point
1931 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1932 (int)$da[2],(int)$da[3],(int)$da[1]);
1935 switch($outputtype) {
1939 return gmdate( 'YmdHis', $uts );
1941 return gmdate( 'Y-m-d H:i:s', $uts );
1943 return gmdate( 'Y-m-d\TH:i:s\Z', $uts );
1944 // This shouldn't ever be used, but is included for completeness
1946 return gmdate( 'Y:m:d H:i:s', $uts );
1948 return gmdate( 'D, d M Y H:i:s', $uts ) . ' GMT';
1950 return gmdate( 'd-m-Y H:i:s.000000', $uts);
1951 //return gmdate( 'd-M-y h.i.s A', $uts) . ' +00:00';
1953 return gmdate( 'Y-m-d H:i:s', $uts) . ' GMT';
1955 return gmdate( 'Y-m-d H:i:s', $uts);
1957 throw new MWException( 'wfTimestamp() called with illegal output type.');
1962 * Return a formatted timestamp, or null if input is null.
1963 * For dealing with nullable timestamp columns in the database.
1964 * @param $outputtype Integer
1968 function wfTimestampOrNull( $outputtype = TS_UNIX
, $ts = null ) {
1969 if( is_null( $ts ) ) {
1972 return wfTimestamp( $outputtype, $ts );
1977 * Check if the operating system is Windows
1979 * @return Bool: true if it's Windows, False otherwise.
1981 function wfIsWindows() {
1982 if (substr(php_uname(), 0, 7) == 'Windows') {
1990 * Swap two variables
1992 function swap( &$x, &$y ) {
1998 function wfGetCachedNotice( $name ) {
1999 global $wgOut, $wgRenderHashAppend, $parserMemc;
2000 $fname = 'wfGetCachedNotice';
2001 wfProfileIn( $fname );
2005 if( $name === 'default' ) {
2007 global $wgSiteNotice;
2008 $notice = $wgSiteNotice;
2009 if( empty( $notice ) ) {
2010 wfProfileOut( $fname );
2014 $notice = wfMsgForContentNoTrans( $name );
2015 if( wfEmptyMsg( $name, $notice ) ||
$notice == '-' ) {
2016 wfProfileOut( $fname );
2021 // Use the extra hash appender to let eg SSL variants separately cache.
2022 $key = wfMemcKey( $name . $wgRenderHashAppend );
2023 $cachedNotice = $parserMemc->get( $key );
2024 if( is_array( $cachedNotice ) ) {
2025 if( md5( $notice ) == $cachedNotice['hash'] ) {
2026 $notice = $cachedNotice['html'];
2035 if( is_object( $wgOut ) ) {
2036 $parsed = $wgOut->parse( $notice );
2037 $parserMemc->set( $key, array( 'html' => $parsed, 'hash' => md5( $notice ) ), 600 );
2040 wfDebug( 'wfGetCachedNotice called for ' . $name . ' with no $wgOut available'."\n" );
2044 $notice = '<div id="localNotice">'.$notice.'</div>';
2045 wfProfileOut( $fname );
2049 function wfGetNamespaceNotice() {
2053 if ( !isset( $wgTitle ) ||
!is_object( $wgTitle ) )
2056 $fname = 'wfGetNamespaceNotice';
2057 wfProfileIn( $fname );
2059 $key = "namespacenotice-" . $wgTitle->getNsText();
2060 $namespaceNotice = wfGetCachedNotice( $key );
2061 if ( $namespaceNotice && substr ( $namespaceNotice , 0 ,7 ) != "<p><" ) {
2062 $namespaceNotice = '<div id="namespacebanner">' . $namespaceNotice . "</div>";
2064 $namespaceNotice = "";
2067 wfProfileOut( $fname );
2068 return $namespaceNotice;
2071 function wfGetSiteNotice() {
2073 $fname = 'wfGetSiteNotice';
2074 wfProfileIn( $fname );
2077 if( wfRunHooks( 'SiteNoticeBefore', array( &$siteNotice ) ) ) {
2078 if( is_object( $wgUser ) && $wgUser->isLoggedIn() ) {
2079 $siteNotice = wfGetCachedNotice( 'sitenotice' );
2081 $anonNotice = wfGetCachedNotice( 'anonnotice' );
2082 if( !$anonNotice ) {
2083 $siteNotice = wfGetCachedNotice( 'sitenotice' );
2085 $siteNotice = $anonNotice;
2088 if( !$siteNotice ) {
2089 $siteNotice = wfGetCachedNotice( 'default' );
2093 wfRunHooks( 'SiteNoticeAfter', array( &$siteNotice ) );
2094 wfProfileOut( $fname );
2099 * BC wrapper for MimeMagic::singleton()
2102 function &wfGetMimeMagic() {
2103 wfDeprecated( __FUNCTION__
);
2104 return MimeMagic
::singleton();
2108 * Tries to get the system directory for temporary files. For PHP >= 5.2.1,
2109 * we'll use sys_get_temp_dir(). The TMPDIR, TMP, and TEMP environment
2110 * variables are then checked in sequence, and if none are set /tmp is
2111 * returned as the generic Unix default.
2112 * It is common to call it with tempnam().
2114 * NOTE: When possible, use instead the tmpfile() function to create
2115 * temporary files to avoid race conditions on file creation, etc.
2119 function wfTempDir() {
2120 if( function_exists( 'sys_get_temp_dir' ) ) {
2121 return sys_get_temp_dir();
2123 foreach( array( 'TMPDIR', 'TMP', 'TEMP' ) as $var ) {
2124 $tmp = getenv( $var );
2125 if( $tmp && file_exists( $tmp ) && is_dir( $tmp ) && is_writable( $tmp ) ) {
2129 # Hope this is Unix of some kind!
2134 * Make directory, and make all parent directories if they don't exist
2136 * @param $dir String: full path to directory to create
2137 * @param $mode Integer: chmod value to use, default is $wgDirectoryMode
2138 * @param $caller String: optional caller param for debugging.
2141 function wfMkdirParents( $dir, $mode = null, $caller = null ) {
2142 global $wgDirectoryMode;
2144 if ( !is_null( $caller ) ) {
2145 wfDebug( "$caller: called wfMkdirParents($dir)" );
2148 if( strval( $dir ) === '' ||
file_exists( $dir ) )
2151 $dir = str_replace( array( '\\', '/' ), DIRECTORY_SEPARATOR
, $dir );
2153 if ( is_null( $mode ) )
2154 $mode = $wgDirectoryMode;
2156 // Turn off the normal warning, we're doing our own below
2157 wfSuppressWarnings();
2158 $ok = mkdir( $dir, $mode, true ); // PHP5 <3
2159 wfRestoreWarnings();
2162 // PHP doesn't report the path in its warning message, so add our own to aid in diagnosis.
2163 trigger_error( __FUNCTION__
. ": failed to mkdir \"$dir\" mode $mode", E_USER_WARNING
);
2169 * Increment a statistics counter
2171 function wfIncrStats( $key ) {
2172 global $wgStatsMethod;
2174 if( $wgStatsMethod == 'udp' ) {
2175 global $wgUDPProfilerHost, $wgUDPProfilerPort, $wgDBname;
2178 $socket=socket_create(AF_INET
, SOCK_DGRAM
, SOL_UDP
);
2179 $statline="stats/{$wgDBname} - 1 1 1 1 1 -total\n";
2180 socket_sendto($socket,$statline,strlen($statline),0,$wgUDPProfilerHost,$wgUDPProfilerPort);
2182 $statline="stats/{$wgDBname} - 1 1 1 1 1 {$key}\n";
2183 @socket_sendto
($socket,$statline,strlen($statline),0,$wgUDPProfilerHost,$wgUDPProfilerPort);
2184 } elseif( $wgStatsMethod == 'cache' ) {
2186 $key = wfMemcKey( 'stats', $key );
2187 if ( is_null( $wgMemc->incr( $key ) ) ) {
2188 $wgMemc->add( $key, 1 );
2196 * @param $nr Mixed: the number to format
2197 * @param $acc Integer: the number of digits after the decimal point, default 2
2198 * @param $round Boolean: whether or not to round the value, default true
2201 function wfPercent( $nr, $acc = 2, $round = true ) {
2202 $ret = sprintf( "%.${acc}f", $nr );
2203 return $round ?
round( $ret, $acc ) . '%' : "$ret%";
2207 * Encrypt a username/password.
2209 * @param $userid Integer: ID of the user
2210 * @param $password String: password of the user
2211 * @return String: hashed password
2212 * @deprecated Use User::crypt() or User::oldCrypt() instead
2214 function wfEncryptPassword( $userid, $password ) {
2215 wfDeprecated(__FUNCTION__
);
2216 # Just wrap around User::oldCrypt()
2217 return User
::oldCrypt($password, $userid);
2221 * Appends to second array if $value differs from that in $default
2223 function wfAppendToArrayIfNotDefault( $key, $value, $default, &$changed ) {
2224 if ( is_null( $changed ) ) {
2225 throw new MWException('GlobalFunctions::wfAppendToArrayIfNotDefault got null');
2227 if ( $default[$key] !== $value ) {
2228 $changed[$key] = $value;
2233 * Since wfMsg() and co suck, they don't return false if the message key they
2234 * looked up didn't exist but a XHTML string, this function checks for the
2235 * nonexistance of messages by looking at wfMsg() output
2237 * @param $key String: the message key looked up
2238 * @return Boolean True if the message *doesn't* exist.
2240 function wfEmptyMsg( $key ) {
2241 global $wgMessageCache;
2242 return $wgMessageCache->get( $key, /*useDB*/true, /*content*/false ) === false;
2246 * Find out whether or not a mixed variable exists in a string
2248 * @param $needle String
2249 * @param $str String
2252 function in_string( $needle, $str ) {
2253 return strpos( $str, $needle ) !== false;
2256 function wfSpecialList( $page, $details ) {
2258 $details = $details ?
' ' . $wgContLang->getDirMark() . "($details)" : "";
2259 return $page . $details;
2263 * Returns a regular expression of url protocols
2267 function wfUrlProtocols() {
2268 global $wgUrlProtocols;
2270 static $retval = null;
2271 if ( !is_null( $retval ) )
2274 // Support old-style $wgUrlProtocols strings, for backwards compatibility
2275 // with LocalSettings files from 1.5
2276 if ( is_array( $wgUrlProtocols ) ) {
2277 $protocols = array();
2278 foreach ($wgUrlProtocols as $protocol)
2279 $protocols[] = preg_quote( $protocol, '/' );
2281 $retval = implode( '|', $protocols );
2283 $retval = $wgUrlProtocols;
2289 * Safety wrapper around ini_get() for boolean settings.
2290 * The values returned from ini_get() are pre-normalized for settings
2291 * set via php.ini or php_flag/php_admin_flag... but *not*
2292 * for those set via php_value/php_admin_value.
2294 * It's fairly common for people to use php_value instead of php_flag,
2295 * which can leave you with an 'off' setting giving a false positive
2296 * for code that just takes the ini_get() return value as a boolean.
2298 * To make things extra interesting, setting via php_value accepts
2299 * "true" and "yes" as true, but php.ini and php_flag consider them false. :)
2300 * Unrecognized values go false... again opposite PHP's own coercion
2301 * from string to bool.
2303 * Luckily, 'properly' set settings will always come back as '0' or '1',
2304 * so we only have to worry about them and the 'improper' settings.
2306 * I frickin' hate PHP... :P
2308 * @param $setting String
2311 function wfIniGetBool( $setting ) {
2312 $val = ini_get( $setting );
2313 // 'on' and 'true' can't have whitespace around them, but '1' can.
2314 return strtolower( $val ) == 'on'
2315 ||
strtolower( $val ) == 'true'
2316 ||
strtolower( $val ) == 'yes'
2317 ||
preg_match( "/^\s*[+-]?0*[1-9]/", $val ); // approx C atoi() function
2321 * Wrapper function for PHP's dl(). This doesn't work in most situations from
2322 * PHP 5.3 onward, and is usually disabled in shared environments anyway.
2324 * @param $extension String A PHP extension. The file suffix (.so or .dll)
2326 * @return Bool - Whether or not the extension is loaded
2328 function wfDl( $extension ) {
2329 if( extension_loaded( $extension ) ) {
2333 $canDl = ( function_exists( 'dl' ) && is_callable( 'dl' )
2334 && wfIniGetBool( 'enable_dl' ) && !wfIniGetBool( 'safe_mode' ) );
2337 wfSuppressWarnings();
2338 dl( $extension . '.' . PHP_SHLIB_SUFFIX
);
2339 wfRestoreWarnings();
2341 return extension_loaded( $extension );
2345 * Execute a shell command, with time and memory limits mirrored from the PHP
2346 * configuration if supported.
2347 * @param $cmd Command line, properly escaped for shell.
2348 * @param &$retval optional, will receive the program's exit code.
2349 * (non-zero is usually failure)
2350 * @return collected stdout as a string (trailing newlines stripped)
2352 function wfShellExec( $cmd, &$retval=null ) {
2353 global $IP, $wgMaxShellMemory, $wgMaxShellFileSize, $wgMaxShellTime;
2356 if ( is_null( $disabled ) ) {
2358 if( wfIniGetBool( 'safe_mode' ) ) {
2359 wfDebug( "wfShellExec can't run in safe_mode, PHP's exec functions are too broken.\n" );
2362 $functions = explode( ',', ini_get( 'disable_functions' ) );
2363 $functions = array_map( 'trim', $functions );
2364 $functions = array_map( 'strtolower', $functions );
2365 if ( in_array( 'passthru', $functions ) ) {
2366 wfDebug( "passthru is in disabled_functions\n" );
2372 return "Unable to run external programs in safe mode.";
2375 wfInitShellLocale();
2377 if ( php_uname( 's' ) == 'Linux' ) {
2378 $time = intval( $wgMaxShellTime );
2379 $mem = intval( $wgMaxShellMemory );
2380 $filesize = intval( $wgMaxShellFileSize );
2382 if ( $time > 0 && $mem > 0 ) {
2383 $script = "$IP/bin/ulimit4.sh";
2384 if ( is_executable( $script ) ) {
2385 $cmd = escapeshellarg( $script ) . " $time $mem $filesize " . escapeshellarg( $cmd );
2388 } elseif ( php_uname( 's' ) == 'Windows NT' &&
2389 version_compare( PHP_VERSION
, '5.3.0', '<' ) )
2391 # This is a hack to work around PHP's flawed invocation of cmd.exe
2392 # http://news.php.net/php.internals/21796
2393 # Which is fixed in 5.3.0 :)
2394 $cmd = '"' . $cmd . '"';
2396 wfDebug( "wfShellExec: $cmd\n" );
2398 $retval = 1; // error by default?
2400 passthru( $cmd, $retval );
2401 $output = ob_get_contents();
2404 if ( $retval == 127 ) {
2405 wfDebugLog( 'exec', "Possibly missing executable file: $cmd\n" );
2411 * Workaround for http://bugs.php.net/bug.php?id=45132
2412 * escapeshellarg() destroys non-ASCII characters if LANG is not a UTF-8 locale
2414 function wfInitShellLocale() {
2415 static $done = false;
2416 if ( $done ) return;
2418 global $wgShellLocale;
2419 if ( !wfIniGetBool( 'safe_mode' ) ) {
2420 putenv( "LC_CTYPE=$wgShellLocale" );
2421 setlocale( LC_CTYPE
, $wgShellLocale );
2426 * This function works like "use VERSION" in Perl, the program will die with a
2427 * backtrace if the current version of PHP is less than the version provided
2429 * This is useful for extensions which due to their nature are not kept in sync
2430 * with releases, and might depend on other versions of PHP than the main code
2432 * Note: PHP might die due to parsing errors in some cases before it ever
2433 * manages to call this function, such is life
2435 * @see perldoc -f use
2437 * @param $req_ver Mixed: the version to check, can be a string, an integer, or
2440 function wfUsePHP( $req_ver ) {
2441 $php_ver = PHP_VERSION
;
2443 if ( version_compare( $php_ver, (string)$req_ver, '<' ) )
2444 throw new MWException( "PHP $req_ver required--this is only $php_ver" );
2448 * This function works like "use VERSION" in Perl except it checks the version
2449 * of MediaWiki, the program will die with a backtrace if the current version
2450 * of MediaWiki is less than the version provided.
2452 * This is useful for extensions which due to their nature are not kept in sync
2455 * @see perldoc -f use
2457 * @param $req_ver Mixed: the version to check, can be a string, an integer, or
2460 function wfUseMW( $req_ver ) {
2463 if ( version_compare( $wgVersion, (string)$req_ver, '<' ) )
2464 throw new MWException( "MediaWiki $req_ver required--this is only $wgVersion" );
2468 * Return the final portion of a pathname.
2469 * Reimplemented because PHP5's basename() is buggy with multibyte text.
2470 * http://bugs.php.net/bug.php?id=33898
2472 * PHP's basename() only considers '\' a pathchar on Windows and Netware.
2473 * We'll consider it so always, as we don't want \s in our Unix paths either.
2475 * @param $path String
2476 * @param $suffix String: to remove if present
2479 function wfBaseName( $path, $suffix='' ) {
2480 $encSuffix = ($suffix == '')
2482 : ( '(?:' . preg_quote( $suffix, '#' ) . ')?' );
2484 if( preg_match( "#([^/\\\\]*?){$encSuffix}[/\\\\]*$#", $path, $matches ) ) {
2492 * Generate a relative path name to the given file.
2493 * May explode on non-matching case-insensitive paths,
2494 * funky symlinks, etc.
2496 * @param $path String: absolute destination path including target filename
2497 * @param $from String: Absolute source path, directory only
2500 function wfRelativePath( $path, $from ) {
2501 // Normalize mixed input on Windows...
2502 $path = str_replace( '/', DIRECTORY_SEPARATOR
, $path );
2503 $from = str_replace( '/', DIRECTORY_SEPARATOR
, $from );
2505 // Trim trailing slashes -- fix for drive root
2506 $path = rtrim( $path, DIRECTORY_SEPARATOR
);
2507 $from = rtrim( $from, DIRECTORY_SEPARATOR
);
2509 $pieces = explode( DIRECTORY_SEPARATOR
, dirname( $path ) );
2510 $against = explode( DIRECTORY_SEPARATOR
, $from );
2512 if( $pieces[0] !== $against[0] ) {
2513 // Non-matching Windows drive letters?
2514 // Return a full path.
2518 // Trim off common prefix
2519 while( count( $pieces ) && count( $against )
2520 && $pieces[0] == $against[0] ) {
2521 array_shift( $pieces );
2522 array_shift( $against );
2525 // relative dots to bump us to the parent
2526 while( count( $against ) ) {
2527 array_unshift( $pieces, '..' );
2528 array_shift( $against );
2531 array_push( $pieces, wfBaseName( $path ) );
2533 return implode( DIRECTORY_SEPARATOR
, $pieces );
2537 * Backwards array plus for people who haven't bothered to read the PHP manual
2538 * XXX: will not darn your socks for you.
2540 * @param $array1 Array
2541 * @param [$array2, [...]] Arrays
2544 function wfArrayMerge( $array1/* ... */ ) {
2545 $args = func_get_args();
2546 $args = array_reverse( $args, true );
2548 foreach ( $args as $arg ) {
2555 * Merge arrays in the style of getUserPermissionsErrors, with duplicate removal
2557 * wfMergeErrorArrays(
2558 * array( array( 'x' ) ),
2559 * array( array( 'x', '2' ) ),
2560 * array( array( 'x' ) ),
2561 * array( array( 'y') )
2565 * array( 'x', '2' ),
2570 function wfMergeErrorArrays( /*...*/ ) {
2571 $args = func_get_args();
2573 foreach ( $args as $errors ) {
2574 foreach ( $errors as $params ) {
2575 # FIXME: sometimes get nested arrays for $params,
2576 # which leads to E_NOTICEs
2577 $spec = implode( "\t", $params );
2578 $out[$spec] = $params;
2581 return array_values( $out );
2585 * parse_url() work-alike, but non-broken. Differences:
2587 * 1) Does not raise warnings on bad URLs (just returns false)
2588 * 2) Handles protocols that don't use :// (e.g., mailto: and news:) correctly
2589 * 3) Adds a "delimiter" element to the array, either '://' or ':' (see (2))
2591 * @param $url String: a URL to parse
2592 * @return Array: bits of the URL in an associative array, per PHP docs
2594 function wfParseUrl( $url ) {
2595 global $wgUrlProtocols; // Allow all protocols defined in DefaultSettings/LocalSettings.php
2596 wfSuppressWarnings();
2597 $bits = parse_url( $url );
2598 wfRestoreWarnings();
2603 // most of the protocols are followed by ://, but mailto: and sometimes news: not, check for it
2604 if ( in_array( $bits['scheme'] . '://', $wgUrlProtocols ) ) {
2605 $bits['delimiter'] = '://';
2606 } elseif ( in_array( $bits['scheme'] . ':', $wgUrlProtocols ) ) {
2607 $bits['delimiter'] = ':';
2608 // parse_url detects for news: and mailto: the host part of an url as path
2609 // We have to correct this wrong detection
2610 if ( isset ( $bits['path'] ) ) {
2611 $bits['host'] = $bits['path'];
2622 * Make a URL index, appropriate for the el_index field of externallinks.
2624 function wfMakeUrlIndex( $url ) {
2625 $bits = wfParseUrl( $url );
2627 // Reverse the labels in the hostname, convert to lower case
2628 // For emails reverse domainpart only
2629 if ( $bits['scheme'] == 'mailto' ) {
2630 $mailparts = explode( '@', $bits['host'], 2 );
2631 if ( count($mailparts) === 2 ) {
2632 $domainpart = strtolower( implode( '.', array_reverse( explode( '.', $mailparts[1] ) ) ) );
2634 // No domain specified, don't mangle it
2637 $reversedHost = $domainpart . '@' . $mailparts[0];
2639 $reversedHost = strtolower( implode( '.', array_reverse( explode( '.', $bits['host'] ) ) ) );
2641 // Add an extra dot to the end
2642 // Why? Is it in wrong place in mailto links?
2643 if ( substr( $reversedHost, -1, 1 ) !== '.' ) {
2644 $reversedHost .= '.';
2646 // Reconstruct the pseudo-URL
2647 $prot = $bits['scheme'];
2648 $index = $prot . $bits['delimiter'] . $reversedHost;
2649 // Leave out user and password. Add the port, path, query and fragment
2650 if ( isset( $bits['port'] ) ) $index .= ':' . $bits['port'];
2651 if ( isset( $bits['path'] ) ) {
2652 $index .= $bits['path'];
2656 if ( isset( $bits['query'] ) ) $index .= '?' . $bits['query'];
2657 if ( isset( $bits['fragment'] ) ) $index .= '#' . $bits['fragment'];
2662 * Do any deferred updates and clear the list
2663 * TODO: This could be in Wiki.php if that class made any sense at all
2665 function wfDoUpdates()
2667 global $wgPostCommitUpdateList, $wgDeferredUpdateList;
2668 foreach ( $wgDeferredUpdateList as $update ) {
2669 $update->doUpdate();
2671 foreach ( $wgPostCommitUpdateList as $update ) {
2672 $update->doUpdate();
2674 $wgDeferredUpdateList = array();
2675 $wgPostCommitUpdateList = array();
2679 * Convert an arbitrarily-long digit string from one numeric base
2680 * to another, optionally zero-padding to a minimum column width.
2682 * Supports base 2 through 36; digit values 10-36 are represented
2683 * as lowercase letters a-z. Input is case-insensitive.
2685 * @param $input String: of digits
2686 * @param $sourceBase Integer: 2-36
2687 * @param $destBase Integer: 2-36
2688 * @param $pad Integer: 1 or greater
2689 * @param $lowercase Boolean
2690 * @return String or false on invalid input
2692 function wfBaseConvert( $input, $sourceBase, $destBase, $pad=1, $lowercase=true ) {
2693 $input = strval( $input );
2694 if( $sourceBase < 2 ||
2699 $sourceBase != intval( $sourceBase ) ||
2700 $destBase != intval( $destBase ) ||
2701 $pad != intval( $pad ) ||
2702 !is_string( $input ) ||
2706 $digitChars = ( $lowercase ) ?
'0123456789abcdefghijklmnopqrstuvwxyz' : '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
2707 $inDigits = array();
2710 // Decode and validate input string
2711 $input = strtolower( $input );
2712 for( $i = 0; $i < strlen( $input ); $i++
) {
2713 $n = strpos( $digitChars, $input{$i} );
2714 if( $n === false ||
$n > $sourceBase ) {
2720 // Iterate over the input, modulo-ing out an output digit
2721 // at a time until input is gone.
2722 while( count( $inDigits ) ) {
2724 $workDigits = array();
2727 foreach( $inDigits as $digit ) {
2728 $work *= $sourceBase;
2731 if( $work < $destBase ) {
2732 // Gonna need to pull another digit.
2733 if( count( $workDigits ) ) {
2734 // Avoid zero-padding; this lets us find
2735 // the end of the input very easily when
2736 // length drops to zero.
2740 // Finally! Actual division!
2741 $workDigits[] = intval( $work / $destBase );
2743 // Isn't it annoying that most programming languages
2744 // don't have a single divide-and-remainder operator,
2745 // even though the CPU implements it that way?
2746 $work = $work %
$destBase;
2750 // All that division leaves us with a remainder,
2751 // which is conveniently our next output digit.
2752 $outChars .= $digitChars[$work];
2755 $inDigits = $workDigits;
2758 while( strlen( $outChars ) < $pad ) {
2762 return strrev( $outChars );
2766 * Create an object with a given name and an array of construct parameters
2767 * @param $name String
2768 * @param $p Array: parameters
2770 function wfCreateObject( $name, $p ){
2771 $p = array_values( $p );
2772 switch ( count( $p ) ) {
2776 return new $name( $p[0] );
2778 return new $name( $p[0], $p[1] );
2780 return new $name( $p[0], $p[1], $p[2] );
2782 return new $name( $p[0], $p[1], $p[2], $p[3] );
2784 return new $name( $p[0], $p[1], $p[2], $p[3], $p[4] );
2786 return new $name( $p[0], $p[1], $p[2], $p[3], $p[4], $p[5] );
2788 throw new MWException( "Too many arguments to construtor in wfCreateObject" );
2792 function wfHttpOnlySafe() {
2793 global $wgHttpOnlyBlacklist;
2794 if( !version_compare("5.2", PHP_VERSION
, "<") )
2797 if( isset( $_SERVER['HTTP_USER_AGENT'] ) ) {
2798 foreach( $wgHttpOnlyBlacklist as $regex ) {
2799 if( preg_match( $regex, $_SERVER['HTTP_USER_AGENT'] ) ) {
2809 * Initialise php session
2811 function wfSetupSession() {
2812 global $wgSessionsInMemcached, $wgCookiePath, $wgCookieDomain,
2813 $wgCookieSecure, $wgCookieHttpOnly, $wgSessionHandler;
2814 if( $wgSessionsInMemcached ) {
2815 require_once( 'MemcachedSessions.php' );
2816 } elseif( $wgSessionHandler && $wgSessionHandler != ini_get( 'session.save_handler' ) ) {
2817 # Only set this if $wgSessionHandler isn't null and session.save_handler
2818 # hasn't already been set to the desired value (that causes errors)
2819 ini_set ( 'session.save_handler', $wgSessionHandler );
2821 $httpOnlySafe = wfHttpOnlySafe();
2822 wfDebugLog( 'cookie',
2823 'session_set_cookie_params: "' . implode( '", "',
2829 $httpOnlySafe && $wgCookieHttpOnly ) ) . '"' );
2830 if( $httpOnlySafe && $wgCookieHttpOnly ) {
2831 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookieHttpOnly );
2833 // PHP 5.1 throws warnings if you pass the HttpOnly parameter for 5.2.
2834 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
2836 session_cache_limiter( 'private, must-revalidate' );
2837 wfSuppressWarnings();
2839 wfRestoreWarnings();
2843 * Get an object from the precompiled serialized directory
2845 * @return Mixed: the variable on success, false on failure
2847 function wfGetPrecompiledData( $name ) {
2850 $file = "$IP/serialized/$name";
2851 if ( file_exists( $file ) ) {
2852 $blob = file_get_contents( $file );
2854 return unserialize( $blob );
2860 function wfGetCaller( $level = 2 ) {
2861 $backtrace = wfDebugBacktrace();
2862 if ( isset( $backtrace[$level] ) ) {
2863 return wfFormatStackFrame($backtrace[$level]);
2865 $caller = 'unknown';
2871 * Return a string consisting of callers in the stack. Useful sometimes
2872 * for profiling specific points.
2874 * @param $limit The maximum depth of the stack frame to return, or false for
2877 function wfGetAllCallers( $limit = 3 ) {
2878 $trace = array_reverse( wfDebugBacktrace() );
2879 if ( !$limit ||
$limit > count( $trace ) - 1 ) {
2880 $limit = count( $trace ) - 1;
2882 $trace = array_slice( $trace, -$limit - 1, $limit );
2883 return implode( '/', array_map( 'wfFormatStackFrame', $trace ) );
2887 * Return a string representation of frame
2889 function wfFormatStackFrame($frame) {
2890 return isset( $frame["class"] )?
2891 $frame["class"]."::".$frame["function"]:
2898 function wfMemcKey( /*... */ ) {
2899 $args = func_get_args();
2900 $key = wfWikiID() . ':' . implode( ':', $args );
2901 $key = str_replace( ' ', '_', $key );
2906 * Get a cache key for a foreign DB
2908 function wfForeignMemcKey( $db, $prefix /*, ... */ ) {
2909 $args = array_slice( func_get_args(), 2 );
2911 $key = "$db-$prefix:" . implode( ':', $args );
2913 $key = $db . ':' . implode( ':', $args );
2919 * Get an ASCII string identifying this wiki
2920 * This is used as a prefix in memcached keys
2922 function wfWikiID() {
2923 global $wgDBprefix, $wgDBname;
2924 if ( $wgDBprefix ) {
2925 return "$wgDBname-$wgDBprefix";
2932 * Split a wiki ID into DB name and table prefix
2934 function wfSplitWikiID( $wiki ) {
2935 $bits = explode( '-', $wiki, 2 );
2936 if ( count( $bits ) < 2 ) {
2943 * Get a Database object.
2944 * @param $db Integer: index of the connection to get. May be DB_MASTER for the
2945 * master (for write queries), DB_SLAVE for potentially lagged read
2946 * queries, or an integer >= 0 for a particular server.
2948 * @param $groups Mixed: query groups. An array of group names that this query
2949 * belongs to. May contain a single string if the query is only
2952 * @param $wiki String: the wiki ID, or false for the current wiki
2954 * Note: multiple calls to wfGetDB(DB_SLAVE) during the course of one request
2955 * will always return the same object, unless the underlying connection or load
2956 * balancer is manually destroyed.
2958 function &wfGetDB( $db, $groups = array(), $wiki = false ) {
2959 return wfGetLB( $wiki )->getConnection( $db, $groups, $wiki );
2963 * Get a load balancer object.
2965 * @param $wiki String: wiki ID, or false for the current wiki
2966 * @return LoadBalancer
2968 function wfGetLB( $wiki = false ) {
2969 return wfGetLBFactory()->getMainLB( $wiki );
2973 * Get the load balancer factory object
2975 function &wfGetLBFactory() {
2976 return LBFactory
::singleton();
2981 * Shortcut for RepoGroup::singleton()->findFile()
2982 * @param $title Either a string or Title object
2983 * @param $options Associative array of options:
2984 * time: requested time for an archived image, or false for the
2985 * current version. An image object will be returned which was
2986 * created at the specified time.
2988 * ignoreRedirect: If true, do not follow file redirects
2990 * private: If true, return restricted (deleted) files if the current
2991 * user is allowed to view them. Otherwise, such files will not
2994 * bypassCache: If true, do not use the process-local cache of File objects
2996 * @return File, or false if the file does not exist
2998 function wfFindFile( $title, $options = array() ) {
2999 return RepoGroup
::singleton()->findFile( $title, $options );
3003 * Get an object referring to a locally registered file.
3004 * Returns a valid placeholder object if the file does not exist.
3005 * @param $title Either a string or Title object
3006 * @return File, or null if passed an invalid Title
3008 function wfLocalFile( $title ) {
3009 return RepoGroup
::singleton()->getLocalRepo()->newFile( $title );
3013 * Should low-performance queries be disabled?
3017 function wfQueriesMustScale() {
3018 global $wgMiserMode;
3020 ||
( SiteStats
::pages() > 100000
3021 && SiteStats
::edits() > 1000000
3022 && SiteStats
::users() > 10000 );
3026 * Get the path to a specified script file, respecting file
3027 * extensions; this is a wrapper around $wgScriptExtension etc.
3029 * @param $script String: script filename, sans extension
3032 function wfScript( $script = 'index' ) {
3033 global $wgScriptPath, $wgScriptExtension;
3034 return "{$wgScriptPath}/{$script}{$wgScriptExtension}";
3037 * Get the script url.
3039 * @return script url
3041 function wfGetScriptUrl(){
3042 if( isset( $_SERVER['SCRIPT_NAME'] ) ) {
3044 # as it was called, minus the query string.
3046 # Some sites use Apache rewrite rules to handle subdomains,
3047 # and have PHP set up in a weird way that causes PHP_SELF
3048 # to contain the rewritten URL instead of the one that the
3049 # outside world sees.
3051 # If in this mode, use SCRIPT_URL instead, which mod_rewrite
3052 # provides containing the "before" URL.
3053 return $_SERVER['SCRIPT_NAME'];
3055 return $_SERVER['URL'];
3060 * Convenience function converts boolean values into "true"
3061 * or "false" (string) values
3063 * @param $value Boolean
3066 function wfBoolToStr( $value ) {
3067 return $value ?
'true' : 'false';
3071 * Load an extension messages file
3072 * @deprecated in 1.16 (warnings in 1.18, removed in ?)
3074 function wfLoadExtensionMessages( $extensionName, $langcode = false ) {
3078 * Get a platform-independent path to the null file, e.g.
3083 function wfGetNull() {
3084 return wfIsWindows()
3090 * Displays a maxlag error
3092 * @param $host String: server that lags the most
3093 * @param $lag Integer: maxlag (actual)
3094 * @param $maxLag Integer: maxlag (requested)
3096 function wfMaxlagError( $host, $lag, $maxLag ) {
3097 global $wgShowHostnames;
3098 header( 'HTTP/1.1 503 Service Unavailable' );
3099 header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
3100 header( 'X-Database-Lag: ' . intval( $lag ) );
3101 header( 'Content-Type: text/plain' );
3102 if( $wgShowHostnames ) {
3103 echo "Waiting for $host: $lag seconds lagged\n";
3105 echo "Waiting for a database server: $lag seconds lagged\n";
3110 * Throws a warning that $function is deprecated
3111 * @param $function String
3114 function wfDeprecated( $function ) {
3115 static $functionsWarned = array();
3116 if ( !isset( $functionsWarned[$function] ) ) {
3117 $functionsWarned[$function] = true;
3118 wfWarn( "Use of $function is deprecated.", 2 );
3123 * Send a warning either to the debug log or in a PHP error depending on
3124 * $wgDevelopmentWarnings
3126 * @param $msg String: message to send
3127 * @param $callerOffset Integer: number of itmes to go back in the backtrace to
3128 * find the correct caller (1 = function calling wfWarn, ...)
3129 * @param $level Integer: PHP error level; only used when $wgDevelopmentWarnings
3132 function wfWarn( $msg, $callerOffset = 1, $level = E_USER_NOTICE
) {
3133 $callers = wfDebugBacktrace();
3134 if( isset( $callers[$callerOffset+
1] ) ){
3135 $callerfunc = $callers[$callerOffset+
1];
3136 $callerfile = $callers[$callerOffset];
3137 if( isset( $callerfile['file'] ) && isset( $callerfile['line'] ) ){
3138 $file = $callerfile['file'] . ' at line ' . $callerfile['line'];
3140 $file = '(internal function)';
3143 if( isset( $callerfunc['class'] ) )
3144 $func .= $callerfunc['class'] . '::';
3145 $func .= @$callerfunc['function'];
3146 $msg .= " [Called from $func in $file]";
3149 global $wgDevelopmentWarnings;
3150 if ( $wgDevelopmentWarnings ) {
3151 trigger_error( $msg, $level );
3153 wfDebug( "$msg\n" );
3158 * Sleep until the worst slave's replication lag is less than or equal to
3159 * $maxLag, in seconds. Use this when updating very large numbers of rows, as
3160 * in maintenance scripts, to avoid causing too much lag. Of course, this is
3161 * a no-op if there are no slaves.
3163 * Every time the function has to wait for a slave, it will print a message to
3164 * that effect (and then sleep for a little while), so it's probably not best
3165 * to use this outside maintenance scripts in its present form.
3167 * @param $maxLag Integer
3168 * @param $wiki mixed Wiki identifier accepted by wfGetLB
3171 function wfWaitForSlaves( $maxLag, $wiki = false ) {
3173 $lb = wfGetLB( $wiki );
3174 list( $host, $lag ) = $lb->getMaxLag( $wiki );
3175 while( $lag > $maxLag ) {
3176 $name = @gethostbyaddr
( $host );
3177 if( $name !== false ) {
3180 print "Waiting for $host (lagged $lag seconds)...\n";
3182 list( $host, $lag ) = $lb->getMaxLag();
3188 * Output some plain text in command-line mode or in the installer (updaters.inc).
3189 * Do not use it in any other context, its behaviour is subject to change.
3191 function wfOut( $s ) {
3192 static $lineStarted = false;
3193 global $wgCommandLineMode;
3194 if ( $wgCommandLineMode && !defined( 'MEDIAWIKI_INSTALL' ) ) {
3197 echo htmlspecialchars( $s );
3203 * Count down from $n to zero on the terminal, with a one-second pause
3204 * between showing each number. For use in command-line scripts.
3206 function wfCountDown( $n ) {
3207 for ( $i = $n; $i >= 0; $i-- ) {
3209 echo str_repeat( "\x08", strlen( $i +
1 ) );
3220 /** Generate a random 32-character hexadecimal token.
3221 * @param $salt Mixed: some sort of salt, if necessary, to add to random
3222 * characters before hashing.
3224 function wfGenerateToken( $salt = '' ) {
3225 $salt = serialize($salt);
3227 return md5( mt_rand( 0, 0x7fffffff ) . $salt );
3231 * Replace all invalid characters with -
3232 * @param $name Mixed: filename to process
3234 function wfStripIllegalFilenameChars( $name ) {
3235 global $wgIllegalFileChars;
3236 $name = wfBaseName( $name );
3237 $name = preg_replace("/[^".Title
::legalChars()."]".($wgIllegalFileChars ?
"|[".$wgIllegalFileChars."]":"")."/",'-',$name);
3242 * Insert array into another array after the specified *KEY*
3243 * @param $array Array: The array.
3244 * @param $insert Array: The array to insert.
3245 * @param $after Mixed: The key to insert after
3247 function wfArrayInsertAfter( $array, $insert, $after ) {
3248 // Find the offset of the element to insert after.
3249 $keys = array_keys($array);
3250 $offsetByKey = array_flip( $keys );
3252 $offset = $offsetByKey[$after];
3254 // Insert at the specified offset
3255 $before = array_slice( $array, 0, $offset +
1, true );
3256 $after = array_slice( $array, $offset +
1, count($array)-$offset, true );
3258 $output = $before +
$insert +
$after;
3263 /* Recursively converts the parameter (an object) to an array with the same data */
3264 function wfObjectToArray( $object, $recursive = true ) {
3266 foreach ( get_object_vars( $object ) as $key => $value ) {
3267 if ( is_object( $value ) && $recursive ) {
3268 $value = wfObjectToArray( $value );
3271 $array[$key] = $value;
3278 * Set PHP's memory limit to the larger of php.ini or $wgMemoryLimit;
3279 * @return Integer value memory was set to.
3281 function wfMemoryLimit() {
3282 global $wgMemoryLimit;
3283 $memlimit = wfShorthandToInteger( ini_get( "memory_limit" ) );
3284 $conflimit = wfShorthandToInteger( $wgMemoryLimit );
3285 if( $memlimit != -1 ) {
3286 if( $conflimit == -1 ) {
3287 wfDebug( "Removing PHP's memory limit\n" );
3288 wfSuppressWarnings();
3289 ini_set( "memory_limit", $conflimit );
3290 wfRestoreWarnings();
3292 } elseif ( $conflimit > $memlimit ) {
3293 wfDebug( "Raising PHP's memory limit to $conflimit bytes\n" );
3294 wfSuppressWarnings();
3295 ini_set( "memory_limit", $conflimit );
3296 wfRestoreWarnings();
3304 * Converts shorthand byte notation to integer form
3305 * @param $string String
3308 function wfShorthandToInteger ( $string = '' ) {
3309 $string = trim($string);
3310 if( empty($string) ) { return -1; }
3311 $last = strtolower($string[strlen($string)-1]);
3312 $val = intval($string);
3325 /* Get the normalised IETF language tag
3326 * @param $code String: The language code.
3327 * @return $langCode String: The language code which complying with BCP 47 standards.
3329 function wfBCP47( $code ) {
3330 $codeSegment = explode( '-', $code );
3331 foreach ( $codeSegment as $segNo => $seg ) {
3332 if ( count( $codeSegment ) > 0 ) {
3333 // ISO 3166 country code
3334 if ( ( strlen( $seg ) == 2 ) && ( $segNo > 0 ) )
3335 $codeBCP[$segNo] = strtoupper( $seg );
3336 // ISO 15924 script code
3337 else if ( ( strlen( $seg ) == 4 ) && ( $segNo > 0 ) )
3338 $codeBCP[$segNo] = ucfirst( $seg );
3339 // Use lowercase for other cases
3341 $codeBCP[$segNo] = strtolower( $seg );
3343 // Use lowercase for single segment
3344 $codeBCP[$segNo] = strtolower( $seg );
3347 $langCode = implode ( '-' , $codeBCP );
3351 function wfArrayMap( $function, $input ) {
3352 $ret = array_map( $function, $input );
3353 foreach ( $ret as $key => $value ) {
3354 $taint = istainted( $input[$key] );
3356 taint( $ret[$key], $taint );