Fix logic error in IMS check introduced in r72940. Was sending 304 even for modified...
[mediawiki.git] / includes / GlobalFunctions.php
blob0e00c693651d7d2bf7107a7dcdf8df7fd3fcb7ca
1 <?php
2 /**
3 * Global functions used everywhere
4 * @file
5 */
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
14 /// @cond
16 /**
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' ) {
29 $to = substr( $to, 0, strlen( $to ) - 8 );
31 if( strcasecmp( $from, $to ) == 0 ) {
32 return $string;
34 if( strcasecmp( $from, 'utf-8' ) == 0 ) {
35 return utf8_decode( $string );
37 if( strcasecmp( $to, 'utf-8' ) == 0 ) {
38 return utf8_encode( $string );
40 return $string;
44 if ( !function_exists( 'mb_substr' ) ) {
45 /**
46 * Fallback implementation for mb_substr, hardcoded to UTF-8.
47 * Attempts to be at least _moderately_ efficient; best optimized
48 * for relatively small offset and count values -- about 5x slower
49 * than native mb_string in my testing.
51 * Larger offsets are still fairly efficient for Latin text, but
52 * can be up to 100x slower than native if the text is heavily
53 * multibyte and we have to slog through a few hundred kb.
55 function mb_substr( $str, $start, $count='end' ) {
56 if( $start != 0 ) {
57 $split = mb_substr_split_unicode( $str, intval( $start ) );
58 $str = substr( $str, $split );
61 if( $count !== 'end' ) {
62 $split = mb_substr_split_unicode( $str, intval( $count ) );
63 $str = substr( $str, 0, $split );
66 return $str;
69 function mb_substr_split_unicode( $str, $splitPos ) {
70 if( $splitPos == 0 ) {
71 return 0;
74 $byteLen = strlen( $str );
76 if( $splitPos > 0 ) {
77 if( $splitPos > 256 ) {
78 // Optimize large string offsets by skipping ahead N bytes.
79 // This will cut out most of our slow time on Latin-based text,
80 // and 1/2 to 1/3 on East European and Asian scripts.
81 $bytePos = $splitPos;
82 while ( $bytePos < $byteLen && $str{$bytePos} >= "\x80" && $str{$bytePos} < "\xc0" ) {
83 ++$bytePos;
85 $charPos = mb_strlen( substr( $str, 0, $bytePos ) );
86 } else {
87 $charPos = 0;
88 $bytePos = 0;
91 while( $charPos++ < $splitPos ) {
92 ++$bytePos;
93 // Move past any tail bytes
94 while ( $bytePos < $byteLen && $str{$bytePos} >= "\x80" && $str{$bytePos} < "\xc0" ) {
95 ++$bytePos;
98 } else {
99 $splitPosX = $splitPos + 1;
100 $charPos = 0; // relative to end of string; we don't care about the actual char position here
101 $bytePos = $byteLen;
102 while( $bytePos > 0 && $charPos-- >= $splitPosX ) {
103 --$bytePos;
104 // Move past any tail bytes
105 while ( $bytePos > 0 && $str{$bytePos} >= "\x80" && $str{$bytePos} < "\xc0" ) {
106 --$bytePos;
111 return $bytePos;
115 if ( !function_exists( 'mb_strlen' ) ) {
117 * Fallback implementation of mb_strlen, hardcoded to UTF-8.
118 * @param string $str
119 * @param string $enc optional encoding; ignored
120 * @return int
122 function mb_strlen( $str, $enc = '' ) {
123 $counts = count_chars( $str );
124 $total = 0;
126 // Count ASCII bytes
127 for( $i = 0; $i < 0x80; $i++ ) {
128 $total += $counts[$i];
131 // Count multibyte sequence heads
132 for( $i = 0xc0; $i < 0xff; $i++ ) {
133 $total += $counts[$i];
135 return $total;
140 if( !function_exists( 'mb_strpos' ) ) {
142 * Fallback implementation of mb_strpos, hardcoded to UTF-8.
143 * @param $haystack String
144 * @param $needle String
145 * @param $offset String: optional start position
146 * @param $encoding String: optional encoding; ignored
147 * @return int
149 function mb_strpos( $haystack, $needle, $offset = 0, $encoding = '' ) {
150 $needle = preg_quote( $needle, '/' );
152 $ar = array();
153 preg_match( '/' . $needle . '/u', $haystack, $ar, PREG_OFFSET_CAPTURE, $offset );
155 if( isset( $ar[0][1] ) ) {
156 return $ar[0][1];
157 } else {
158 return false;
163 if( !function_exists( 'mb_strrpos' ) ) {
165 * Fallback implementation of mb_strrpos, hardcoded to UTF-8.
166 * @param $haystack String
167 * @param $needle String
168 * @param $offset String: optional start position
169 * @param $encoding String: optional encoding; ignored
170 * @return int
172 function mb_strrpos( $haystack, $needle, $offset = 0, $encoding = '' ) {
173 $needle = preg_quote( $needle, '/' );
175 $ar = array();
176 preg_match_all( '/' . $needle . '/u', $haystack, $ar, PREG_OFFSET_CAPTURE, $offset );
178 if( isset( $ar[0] ) && count( $ar[0] ) > 0 &&
179 isset( $ar[0][count( $ar[0] ) - 1][1] ) ) {
180 return $ar[0][count( $ar[0] ) - 1][1];
181 } else {
182 return false;
187 // Support for Wietse Venema's taint feature
188 if ( !function_exists( 'istainted' ) ) {
189 function istainted( $var ) {
190 return 0;
192 function taint( $var, $level = 0 ) {}
193 function untaint( $var, $level = 0 ) {}
194 define( 'TC_HTML', 1 );
195 define( 'TC_SHELL', 1 );
196 define( 'TC_MYSQL', 1 );
197 define( 'TC_PCRE', 1 );
198 define( 'TC_SELF', 1 );
200 /// @endcond
204 * Like array_diff( $a, $b ) except that it works with two-dimensional arrays.
206 function wfArrayDiff2( $a, $b ) {
207 return array_udiff( $a, $b, 'wfArrayDiff2_cmp' );
209 function wfArrayDiff2_cmp( $a, $b ) {
210 if ( !is_array( $a ) ) {
211 return strcmp( $a, $b );
212 } elseif ( count( $a ) !== count( $b ) ) {
213 return count( $a ) < count( $b ) ? -1 : 1;
214 } else {
215 reset( $a );
216 reset( $b );
217 while( ( list( $keyA, $valueA ) = each( $a ) ) && ( list( $keyB, $valueB ) = each( $b ) ) ) {
218 $cmp = strcmp( $valueA, $valueB );
219 if ( $cmp !== 0 ) {
220 return $cmp;
223 return 0;
228 * Seed Mersenne Twister
229 * No-op for compatibility; only necessary in PHP < 4.2.0
230 * @deprecated. Remove in 1.18
232 function wfSeedRandom() {
233 wfDeprecated(__FUNCTION__);
237 * Get a random decimal value between 0 and 1, in a way
238 * not likely to give duplicate values for any realistic
239 * number of articles.
241 * @return string
243 function wfRandom() {
244 # The maximum random value is "only" 2^31-1, so get two random
245 # values to reduce the chance of dupes
246 $max = mt_getrandmax() + 1;
247 $rand = number_format( ( mt_rand() * $max + mt_rand() )
248 / $max / $max, 12, '.', '' );
249 return $rand;
253 * We want some things to be included as literal characters in our title URLs
254 * for prettiness, which urlencode encodes by default. According to RFC 1738,
255 * all of the following should be safe:
257 * ;:@&=$-_.+!*'(),
259 * But + is not safe because it's used to indicate a space; &= are only safe in
260 * paths and not in queries (and we don't distinguish here); ' seems kind of
261 * scary; and urlencode() doesn't touch -_. to begin with. Plus, although /
262 * is reserved, we don't care. So the list we unescape is:
264 * ;:@$!*(),/
266 * However, IIS7 redirects fail when the url contains a colon (Bug 22709),
267 * so no fancy : for IIS7.
269 * %2F in the page titles seems to fatally break for some reason.
271 * @param $s String:
272 * @return string
274 function wfUrlencode( $s ) {
275 static $needle;
276 if ( is_null( $needle ) ) {
277 $needle = array( '%3B', '%40', '%24', '%21', '%2A', '%28', '%29', '%2C', '%2F' );
278 if ( !isset( $_SERVER['SERVER_SOFTWARE'] ) || ( strpos( $_SERVER['SERVER_SOFTWARE'], 'Microsoft-IIS/7' ) === false ) ) {
279 $needle[] = '%3A';
283 $s = urlencode( $s );
284 $s = str_ireplace(
285 $needle,
286 array( ';', '@', '$', '!', '*', '(', ')', ',', '/', ':' ),
290 return $s;
294 * Sends a line to the debug log if enabled or, optionally, to a comment in output.
295 * In normal operation this is a NOP.
297 * Controlling globals:
298 * $wgDebugLogFile - points to the log file
299 * $wgProfileOnly - if set, normal debug messages will not be recorded.
300 * $wgDebugRawPage - if false, 'action=raw' hits will not result in debug output.
301 * $wgDebugComments - if on, some debug items may appear in comments in the HTML output.
303 * @param $text String
304 * @param $logonly Bool: set true to avoid appearing in HTML when $wgDebugComments is set
306 function wfDebug( $text, $logonly = false ) {
307 global $wgOut, $wgDebugLogFile, $wgDebugComments, $wgProfileOnly, $wgDebugRawPage;
308 global $wgDebugLogPrefix, $wgShowDebug;
309 static $recursion = 0;
311 static $cache = array(); // Cache of unoutputted messages
312 $text = wfDebugTimer() . $text;
314 # Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
315 if ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' && !$wgDebugRawPage ) {
316 return;
319 if ( ( $wgDebugComments || $wgShowDebug ) && !$logonly ) {
320 $cache[] = $text;
322 if ( !isset( $wgOut ) ) {
323 return;
325 if ( !StubObject::isRealObject( $wgOut ) ) {
326 if ( $recursion ) {
327 return;
329 $recursion++;
330 $wgOut->_unstub();
331 $recursion--;
334 // add the message and possible cached ones to the output
335 array_map( array( $wgOut, 'debug' ), $cache );
336 $cache = array();
338 if ( $wgDebugLogFile != '' && !$wgProfileOnly ) {
339 # Strip unprintables; they can switch terminal modes when binary data
340 # gets dumped, which is pretty annoying.
341 $text = preg_replace( '![\x00-\x08\x0b\x0c\x0e-\x1f]!', ' ', $text );
342 $text = $wgDebugLogPrefix . $text;
343 wfErrorLog( $text, $wgDebugLogFile );
347 function wfDebugTimer() {
348 global $wgDebugTimestamps;
349 if ( !$wgDebugTimestamps ) {
350 return '';
352 static $start = null;
354 if ( $start === null ) {
355 $start = microtime( true );
356 $prefix = "\n$start";
357 } else {
358 $prefix = sprintf( "%6.4f", microtime( true ) - $start );
361 return $prefix . ' ';
365 * Send a line giving PHP memory usage.
366 * @param $exact Bool: print exact values instead of kilobytes (default: false)
368 function wfDebugMem( $exact = false ) {
369 $mem = memory_get_usage();
370 if( !$exact ) {
371 $mem = floor( $mem / 1024 ) . ' kilobytes';
372 } else {
373 $mem .= ' bytes';
375 wfDebug( "Memory usage: $mem\n" );
379 * Send a line to a supplementary debug log file, if configured, or main debug log if not.
380 * $wgDebugLogGroups[$logGroup] should be set to a filename to send to a separate log.
382 * @param $logGroup String
383 * @param $text String
384 * @param $public Bool: whether to log the event in the public log if no private
385 * log file is specified, (default true)
387 function wfDebugLog( $logGroup, $text, $public = true ) {
388 global $wgDebugLogGroups, $wgShowHostnames;
389 $text = trim( $text ) . "\n";
390 if( isset( $wgDebugLogGroups[$logGroup] ) ) {
391 $time = wfTimestamp( TS_DB );
392 $wiki = wfWikiID();
393 if ( $wgShowHostnames ) {
394 $host = wfHostname();
395 } else {
396 $host = '';
398 wfErrorLog( "$time $host $wiki: $text", $wgDebugLogGroups[$logGroup] );
399 } elseif ( $public === true ) {
400 wfDebug( $text, true );
405 * Log for database errors
406 * @param $text String: database error message.
408 function wfLogDBError( $text ) {
409 global $wgDBerrorLog, $wgDBname;
410 if ( $wgDBerrorLog ) {
411 $host = trim(`hostname`);
412 $text = date( 'D M j G:i:s T Y' ) . "\t$host\t$wgDBname\t$text";
413 wfErrorLog( $text, $wgDBerrorLog );
418 * Log to a file without getting "file size exceeded" signals.
420 * Can also log to TCP or UDP with the syntax udp://host:port/prefix. This will
421 * send lines to the specified port, prefixed by the specified prefix and a space.
423 function wfErrorLog( $text, $file ) {
424 if ( substr( $file, 0, 4 ) == 'udp:' ) {
425 # Needs the sockets extension
426 if ( preg_match( '!^(tcp|udp):(?://)?\[([0-9a-fA-F:]+)\]:(\d+)(?:/(.*))?$!', $file, $m ) ) {
427 // IPv6 bracketed host
428 $protocol = $m[1];
429 $host = $m[2];
430 $port = intval( $m[3] );
431 $prefix = isset( $m[4] ) ? $m[4] : false;
432 $domain = AF_INET6;
433 } elseif ( preg_match( '!^(tcp|udp):(?://)?([a-zA-Z0-9.-]+):(\d+)(?:/(.*))?$!', $file, $m ) ) {
434 $protocol = $m[1];
435 $host = $m[2];
436 if ( !IP::isIPv4( $host ) ) {
437 $host = gethostbyname( $host );
439 $port = intval( $m[3] );
440 $prefix = isset( $m[4] ) ? $m[4] : false;
441 $domain = AF_INET;
442 } else {
443 throw new MWException( __METHOD__ . ': Invalid UDP specification' );
445 // Clean it up for the multiplexer
446 if ( strval( $prefix ) !== '' ) {
447 $text = preg_replace( '/^/m', $prefix . ' ', $text );
448 if ( substr( $text, -1 ) != "\n" ) {
449 $text .= "\n";
453 $sock = socket_create( $domain, SOCK_DGRAM, SOL_UDP );
454 if ( !$sock ) {
455 return;
457 socket_sendto( $sock, $text, strlen( $text ), 0, $host, $port );
458 socket_close( $sock );
459 } else {
460 wfSuppressWarnings();
461 $exists = file_exists( $file );
462 $size = $exists ? filesize( $file ) : false;
463 if ( !$exists || ( $size !== false && $size + strlen( $text ) < 0x7fffffff ) ) {
464 error_log( $text, 3, $file );
466 wfRestoreWarnings();
471 * @todo document
473 function wfLogProfilingData() {
474 global $wgRequestTime, $wgDebugLogFile, $wgDebugRawPage, $wgRequest;
475 global $wgProfiler, $wgProfileLimit, $wgUser;
476 # Profiling must actually be enabled...
477 if( is_null( $wgProfiler ) ) {
478 return;
480 # Get total page request time
481 $now = wfTime();
482 $elapsed = $now - $wgRequestTime;
483 # Only show pages that longer than $wgProfileLimit time (default is 0)
484 if( $elapsed <= $wgProfileLimit ) {
485 return;
487 $prof = wfGetProfilingOutput( $wgRequestTime, $elapsed );
488 $forward = '';
489 if( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) {
490 $forward = ' forwarded for ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
492 if( !empty( $_SERVER['HTTP_CLIENT_IP'] ) ) {
493 $forward .= ' client IP ' . $_SERVER['HTTP_CLIENT_IP'];
495 if( !empty( $_SERVER['HTTP_FROM'] ) ) {
496 $forward .= ' from ' . $_SERVER['HTTP_FROM'];
498 if( $forward ) {
499 $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
501 // Don't unstub $wgUser at this late stage just for statistics purposes
502 if( StubObject::isRealObject( $wgUser ) && $wgUser->isAnon() ) {
503 $forward .= ' anon';
505 $log = sprintf( "%s\t%04.3f\t%s\n",
506 gmdate( 'YmdHis' ), $elapsed,
507 urldecode( $wgRequest->getRequestURL() . $forward ) );
508 if ( $wgDebugLogFile != '' && ( $wgRequest->getVal( 'action' ) != 'raw' || $wgDebugRawPage ) ) {
509 wfErrorLog( $log . $prof, $wgDebugLogFile );
514 * Check if the wiki read-only lock file is present. This can be used to lock
515 * off editing functions, but doesn't guarantee that the database will not be
516 * modified.
517 * @return bool
519 function wfReadOnly() {
520 global $wgReadOnlyFile, $wgReadOnly;
522 if ( !is_null( $wgReadOnly ) ) {
523 return (bool)$wgReadOnly;
525 if ( $wgReadOnlyFile == '' ) {
526 return false;
528 // Set $wgReadOnly for faster access next time
529 if ( is_file( $wgReadOnlyFile ) ) {
530 $wgReadOnly = file_get_contents( $wgReadOnlyFile );
531 } else {
532 $wgReadOnly = false;
534 return (bool)$wgReadOnly;
537 function wfReadOnlyReason() {
538 global $wgReadOnly;
539 wfReadOnly();
540 return $wgReadOnly;
544 * Return a Language object from $langcode
545 * @param $langcode Mixed: either:
546 * - a Language object
547 * - code of the language to get the message for, if it is
548 * a valid code create a language for that language, if
549 * it is a string but not a valid code then make a basic
550 * language object
551 * - a boolean: if it's false then use the current users
552 * language (as a fallback for the old parameter
553 * functionality), or if it is true then use the wikis
554 * @return Language object
556 function wfGetLangObj( $langcode = false ) {
557 # Identify which language to get or create a language object for.
558 # Using is_object here due to Stub objects.
559 if( is_object( $langcode ) ) {
560 # Great, we already have the object (hopefully)!
561 return $langcode;
564 global $wgContLang, $wgLanguageCode;
565 if( $langcode === true || $langcode === $wgLanguageCode ) {
566 # $langcode is the language code of the wikis content language object.
567 # or it is a boolean and value is true
568 return $wgContLang;
571 global $wgLang;
572 if( $langcode === false || $langcode === $wgLang->getCode() ) {
573 # $langcode is the language code of user language object.
574 # or it was a boolean and value is false
575 return $wgLang;
578 $validCodes = array_keys( Language::getLanguageNames() );
579 if( in_array( $langcode, $validCodes ) ) {
580 # $langcode corresponds to a valid language.
581 return Language::factory( $langcode );
584 # $langcode is a string, but not a valid language code; use content language.
585 wfDebug( "Invalid language code passed to wfGetLangObj, falling back to content language.\n" );
586 return $wgContLang;
590 * Use this instead of $wgContLang, when working with user interface.
591 * User interface is currently hard coded according to wiki content language
592 * in many ways, especially regarding to text direction. There is lots stuff
593 * to fix, hence this function to keep the old behaviour unless the global
594 * $wgBetterDirectionality is enabled (or removed when everything works).
596 function wfUILang() {
597 global $wgBetterDirectionality;
598 return wfGetLangObj( !$wgBetterDirectionality );
602 * This is the new function for getting translated interface messages.
603 * See the Message class for documentation how to use them.
604 * The intention is that this function replaces all old wfMsg* functions.
605 * @param $key \string Message key.
606 * Varargs: normal message parameters.
607 * @return \type{Message}
608 * @since 1.17
610 function wfMessage( $key /*...*/) {
611 $params = func_get_args();
612 array_shift( $params );
613 return new Message( $key, $params );
617 * Get a message from anywhere, for the current user language.
619 * Use wfMsgForContent() instead if the message should NOT
620 * change depending on the user preferences.
622 * @param $key String: lookup key for the message, usually
623 * defined in languages/Language.php
625 * This function also takes extra optional parameters (not
626 * shown in the function definition), which can be used to
627 * insert variable text into the predefined message.
629 function wfMsg( $key ) {
630 $args = func_get_args();
631 array_shift( $args );
632 return wfMsgReal( $key, $args, true );
636 * Same as above except doesn't transform the message
638 function wfMsgNoTrans( $key ) {
639 $args = func_get_args();
640 array_shift( $args );
641 return wfMsgReal( $key, $args, true, false, false );
645 * Get a message from anywhere, for the current global language
646 * set with $wgLanguageCode.
648 * Use this if the message should NOT change dependent on the
649 * language set in the user's preferences. This is the case for
650 * most text written into logs, as well as link targets (such as
651 * the name of the copyright policy page). Link titles, on the
652 * other hand, should be shown in the UI language.
654 * Note that MediaWiki allows users to change the user interface
655 * language in their preferences, but a single installation
656 * typically only contains content in one language.
658 * Be wary of this distinction: If you use wfMsg() where you should
659 * use wfMsgForContent(), a user of the software may have to
660 * customize potentially hundreds of messages in
661 * order to, e.g., fix a link in every possible language.
663 * @param $key String: lookup key for the message, usually
664 * defined in languages/Language.php
666 function wfMsgForContent( $key ) {
667 global $wgForceUIMsgAsContentMsg;
668 $args = func_get_args();
669 array_shift( $args );
670 $forcontent = true;
671 if( is_array( $wgForceUIMsgAsContentMsg ) &&
672 in_array( $key, $wgForceUIMsgAsContentMsg ) )
674 $forcontent = false;
676 return wfMsgReal( $key, $args, true, $forcontent );
680 * Same as above except doesn't transform the message
682 function wfMsgForContentNoTrans( $key ) {
683 global $wgForceUIMsgAsContentMsg;
684 $args = func_get_args();
685 array_shift( $args );
686 $forcontent = true;
687 if( is_array( $wgForceUIMsgAsContentMsg ) &&
688 in_array( $key, $wgForceUIMsgAsContentMsg ) )
690 $forcontent = false;
692 return wfMsgReal( $key, $args, true, $forcontent, false );
696 * Get a message from the language file, for the UI elements
698 function wfMsgNoDB( $key ) {
699 $args = func_get_args();
700 array_shift( $args );
701 return wfMsgReal( $key, $args, false );
705 * Get a message from the language file, for the content
707 function wfMsgNoDBForContent( $key ) {
708 global $wgForceUIMsgAsContentMsg;
709 $args = func_get_args();
710 array_shift( $args );
711 $forcontent = true;
712 if( is_array( $wgForceUIMsgAsContentMsg ) &&
713 in_array( $key, $wgForceUIMsgAsContentMsg ) )
715 $forcontent = false;
717 return wfMsgReal( $key, $args, false, $forcontent );
722 * Really get a message
723 * @param $key String: key to get.
724 * @param $args
725 * @param $useDB Boolean
726 * @param $forContent Mixed: Language code, or false for user lang, true for content lang.
727 * @param $transform Boolean: Whether or not to transform the message.
728 * @return String: the requested message.
730 function wfMsgReal( $key, $args, $useDB = true, $forContent = false, $transform = true ) {
731 wfProfileIn( __METHOD__ );
732 $message = wfMsgGetKey( $key, $useDB, $forContent, $transform );
733 $message = wfMsgReplaceArgs( $message, $args );
734 wfProfileOut( __METHOD__ );
735 return $message;
739 * This function provides the message source for messages to be edited which are *not* stored in the database.
740 * @param $key String:
742 function wfMsgWeirdKey( $key ) {
743 $source = wfMsgGetKey( $key, false, true, false );
744 if ( wfEmptyMsg( $key, $source ) ) {
745 return '';
746 } else {
747 return $source;
752 * Fetch a message string value, but don't replace any keys yet.
753 * @param $key String
754 * @param $useDB Bool
755 * @param $langCode String: Code of the language to get the message for, or
756 * behaves as a content language switch if it is a boolean.
757 * @param $transform Boolean: whether to parse magic words, etc.
758 * @return string
760 function wfMsgGetKey( $key, $useDB, $langCode = false, $transform = true ) {
761 global $wgMessageCache;
763 wfRunHooks( 'NormalizeMessageKey', array( &$key, &$useDB, &$langCode, &$transform ) );
765 if ( !is_object( $wgMessageCache ) ) {
766 throw new MWException( 'Trying to get message before message cache is initialised' );
769 $message = $wgMessageCache->get( $key, $useDB, $langCode );
770 if( $message === false ) {
771 $message = '&lt;' . htmlspecialchars( $key ) . '&gt;';
772 } elseif ( $transform ) {
773 $message = $wgMessageCache->transform( $message );
775 return $message;
779 * Replace message parameter keys on the given formatted output.
781 * @param $message String
782 * @param $args Array
783 * @return string
784 * @private
786 function wfMsgReplaceArgs( $message, $args ) {
787 # Fix windows line-endings
788 # Some messages are split with explode("\n", $msg)
789 $message = str_replace( "\r", '', $message );
791 // Replace arguments
792 if ( count( $args ) ) {
793 if ( is_array( $args[0] ) ) {
794 $args = array_values( $args[0] );
796 $replacementKeys = array();
797 foreach( $args as $n => $param ) {
798 $replacementKeys['$' . ( $n + 1 )] = $param;
800 $message = strtr( $message, $replacementKeys );
803 return $message;
807 * Return an HTML-escaped version of a message.
808 * Parameter replacements, if any, are done *after* the HTML-escaping,
809 * so parameters may contain HTML (eg links or form controls). Be sure
810 * to pre-escape them if you really do want plaintext, or just wrap
811 * the whole thing in htmlspecialchars().
813 * @param $key String
814 * @param string ... parameters
815 * @return string
817 function wfMsgHtml( $key ) {
818 $args = func_get_args();
819 array_shift( $args );
820 return wfMsgReplaceArgs( htmlspecialchars( wfMsgGetKey( $key, true ) ), $args );
824 * Return an HTML version of message
825 * Parameter replacements, if any, are done *after* parsing the wiki-text message,
826 * so parameters may contain HTML (eg links or form controls). Be sure
827 * to pre-escape them if you really do want plaintext, or just wrap
828 * the whole thing in htmlspecialchars().
830 * @param $key String
831 * @param string ... parameters
832 * @return string
834 function wfMsgWikiHtml( $key ) {
835 global $wgOut;
836 $args = func_get_args();
837 array_shift( $args );
838 return wfMsgReplaceArgs( $wgOut->parse( wfMsgGetKey( $key, true ), /* can't be set to false */ true ), $args );
842 * Returns message in the requested format
843 * @param $key String: key of the message
844 * @param $options Array: processing rules. Can take the following options:
845 * <i>parse</i>: parses wikitext to HTML
846 * <i>parseinline</i>: parses wikitext to HTML and removes the surrounding
847 * p's added by parser or tidy
848 * <i>escape</i>: filters message through htmlspecialchars
849 * <i>escapenoentities</i>: same, but allows entity references like &#160; through
850 * <i>replaceafter</i>: parameters are substituted after parsing or escaping
851 * <i>parsemag</i>: transform the message using magic phrases
852 * <i>content</i>: fetch message for content language instead of interface
853 * Also can accept a single associative argument, of the form 'language' => 'xx':
854 * <i>language</i>: Language object or language code to fetch message for
855 * (overriden by <i>content</i>), its behaviour with parser, parseinline
856 * and parsemag is undefined.
857 * Behavior for conflicting options (e.g., parse+parseinline) is undefined.
859 function wfMsgExt( $key, $options ) {
860 global $wgOut;
862 $args = func_get_args();
863 array_shift( $args );
864 array_shift( $args );
865 $options = (array)$options;
867 foreach( $options as $arrayKey => $option ) {
868 if( !preg_match( '/^[0-9]+|language$/', $arrayKey ) ) {
869 # An unknown index, neither numeric nor "language"
870 wfWarn( "wfMsgExt called with incorrect parameter key $arrayKey", 1, E_USER_WARNING );
871 } elseif( preg_match( '/^[0-9]+$/', $arrayKey ) && !in_array( $option,
872 array( 'parse', 'parseinline', 'escape', 'escapenoentities',
873 'replaceafter', 'parsemag', 'content' ) ) ) {
874 # A numeric index with unknown value
875 wfWarn( "wfMsgExt called with incorrect parameter $option", 1, E_USER_WARNING );
879 if( in_array( 'content', $options, true ) ) {
880 $forContent = true;
881 $langCode = true;
882 } elseif( array_key_exists( 'language', $options ) ) {
883 $forContent = false;
884 $langCode = wfGetLangObj( $options['language'] );
885 } else {
886 $forContent = false;
887 $langCode = false;
890 $string = wfMsgGetKey( $key, /*DB*/true, $langCode, /*Transform*/false );
892 if( !in_array( 'replaceafter', $options, true ) ) {
893 $string = wfMsgReplaceArgs( $string, $args );
896 if( in_array( 'parse', $options, true ) ) {
897 $string = $wgOut->parse( $string, true, !$forContent );
898 } elseif ( in_array( 'parseinline', $options, true ) ) {
899 $string = $wgOut->parse( $string, true, !$forContent );
900 $m = array();
901 if( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $string, $m ) ) {
902 $string = $m[1];
904 } elseif ( in_array( 'parsemag', $options, true ) ) {
905 global $wgMessageCache;
906 if ( isset( $wgMessageCache ) ) {
907 $string = $wgMessageCache->transform( $string,
908 !$forContent,
909 is_object( $langCode ) ? $langCode : null );
913 if ( in_array( 'escape', $options, true ) ) {
914 $string = htmlspecialchars ( $string );
915 } elseif ( in_array( 'escapenoentities', $options, true ) ) {
916 $string = Sanitizer::escapeHtmlAllowEntities( $string );
919 if( in_array( 'replaceafter', $options, true ) ) {
920 $string = wfMsgReplaceArgs( $string, $args );
923 return $string;
928 * Just like exit() but makes a note of it.
929 * Commits open transactions except if the error parameter is set
931 * @deprecated Please return control to the caller or throw an exception
933 function wfAbruptExit( $error = false ) {
934 static $called = false;
935 if ( $called ) {
936 exit( -1 );
938 $called = true;
940 $bt = wfDebugBacktrace();
941 if( $bt ) {
942 for( $i = 0; $i < count( $bt ); $i++ ) {
943 $file = isset( $bt[$i]['file'] ) ? $bt[$i]['file'] : 'unknown';
944 $line = isset( $bt[$i]['line'] ) ? $bt[$i]['line'] : 'unknown';
945 wfDebug( "WARNING: Abrupt exit in $file at line $line\n");
947 } else {
948 wfDebug( "WARNING: Abrupt exit\n" );
951 wfLogProfilingData();
953 if ( !$error ) {
954 wfGetLB()->closeAll();
956 exit( -1 );
960 * @deprecated Please return control the caller or throw an exception
962 function wfErrorExit() {
963 wfAbruptExit( true );
967 * Print a simple message and die, returning nonzero to the shell if any.
968 * Plain die() fails to return nonzero to the shell if you pass a string.
969 * @param $msg String
971 function wfDie( $msg = '' ) {
972 echo $msg;
973 die( 1 );
977 * Throw a debugging exception. This function previously once exited the process,
978 * but now throws an exception instead, with similar results.
980 * @param $msg String: message shown when dieing.
982 function wfDebugDieBacktrace( $msg = '' ) {
983 throw new MWException( $msg );
987 * Fetch server name for use in error reporting etc.
988 * Use real server name if available, so we know which machine
989 * in a server farm generated the current page.
990 * @return string
992 function wfHostname() {
993 static $host;
994 if ( is_null( $host ) ) {
995 if ( function_exists( 'posix_uname' ) ) {
996 // This function not present on Windows
997 $uname = @posix_uname();
998 } else {
999 $uname = false;
1001 if( is_array( $uname ) && isset( $uname['nodename'] ) ) {
1002 $host = $uname['nodename'];
1003 } elseif ( getenv( 'COMPUTERNAME' ) ) {
1004 # Windows computer name
1005 $host = getenv( 'COMPUTERNAME' );
1006 } else {
1007 # This may be a virtual server.
1008 $host = $_SERVER['SERVER_NAME'];
1011 return $host;
1015 * Returns a HTML comment with the elapsed time since request.
1016 * This method has no side effects.
1017 * @return string
1019 function wfReportTime() {
1020 global $wgRequestTime, $wgShowHostnames;
1022 $now = wfTime();
1023 $elapsed = $now - $wgRequestTime;
1025 return $wgShowHostnames
1026 ? sprintf( '<!-- Served by %s in %01.3f secs. -->', wfHostname(), $elapsed )
1027 : sprintf( '<!-- Served in %01.3f secs. -->', $elapsed );
1031 * Safety wrapper for debug_backtrace().
1033 * With Zend Optimizer 3.2.0 loaded, this causes segfaults under somewhat
1034 * murky circumstances, which may be triggered in part by stub objects
1035 * or other fancy talkin'.
1037 * Will return an empty array if Zend Optimizer is detected or if
1038 * debug_backtrace is disabled, otherwise the output from
1039 * debug_backtrace() (trimmed).
1041 * @return array of backtrace information
1043 function wfDebugBacktrace() {
1044 static $disabled = null;
1046 if( extension_loaded( 'Zend Optimizer' ) ) {
1047 wfDebug( "Zend Optimizer detected; skipping debug_backtrace for safety.\n" );
1048 return array();
1051 if ( is_null( $disabled ) ) {
1052 $disabled = false;
1053 $functions = explode( ',', ini_get( 'disable_functions' ) );
1054 $functions = array_map( 'trim', $functions );
1055 $functions = array_map( 'strtolower', $functions );
1056 if ( in_array( 'debug_backtrace', $functions ) ) {
1057 wfDebug( "debug_backtrace is in disabled_functions\n" );
1058 $disabled = true;
1061 if ( $disabled ) {
1062 return array();
1065 return array_slice( debug_backtrace(), 1 );
1068 function wfBacktrace() {
1069 global $wgCommandLineMode;
1071 if ( $wgCommandLineMode ) {
1072 $msg = '';
1073 } else {
1074 $msg = "<ul>\n";
1076 $backtrace = wfDebugBacktrace();
1077 foreach( $backtrace as $call ) {
1078 if( isset( $call['file'] ) ) {
1079 $f = explode( DIRECTORY_SEPARATOR, $call['file'] );
1080 $file = $f[count( $f ) - 1];
1081 } else {
1082 $file = '-';
1084 if( isset( $call['line'] ) ) {
1085 $line = $call['line'];
1086 } else {
1087 $line = '-';
1089 if ( $wgCommandLineMode ) {
1090 $msg .= "$file line $line calls ";
1091 } else {
1092 $msg .= '<li>' . $file . ' line ' . $line . ' calls ';
1094 if( !empty( $call['class'] ) ) {
1095 $msg .= $call['class'] . '::';
1097 $msg .= $call['function'] . '()';
1099 if ( $wgCommandLineMode ) {
1100 $msg .= "\n";
1101 } else {
1102 $msg .= "</li>\n";
1105 if ( $wgCommandLineMode ) {
1106 $msg .= "\n";
1107 } else {
1108 $msg .= "</ul>\n";
1111 return $msg;
1115 /* Some generic result counters, pulled out of SearchEngine */
1119 * @todo document
1121 function wfShowingResults( $offset, $limit ) {
1122 global $wgLang;
1123 return wfMsgExt(
1124 'showingresults',
1125 array( 'parseinline' ),
1126 $wgLang->formatNum( $limit ),
1127 $wgLang->formatNum( $offset + 1 )
1132 * @todo document
1134 function wfShowingResultsNum( $offset, $limit, $num ) {
1135 global $wgLang;
1136 return wfMsgExt(
1137 'showingresultsnum',
1138 array( 'parseinline' ),
1139 $wgLang->formatNum( $limit ),
1140 $wgLang->formatNum( $offset + 1 ),
1141 $wgLang->formatNum( $num )
1146 * Generate (prev x| next x) (20|50|100...) type links for paging
1147 * @param $offset String
1148 * @param $limit Integer
1149 * @param $link String
1150 * @param $query String: optional URL query parameter string
1151 * @param $atend Bool: optional param for specified if this is the last page
1153 function wfViewPrevNext( $offset, $limit, $link, $query = '', $atend = false ) {
1154 global $wgLang;
1155 $fmtLimit = $wgLang->formatNum( $limit );
1156 // FIXME: Why on earth this needs one message for the text and another one for tooltip??
1157 # Get prev/next link display text
1158 $prev = wfMsgExt( 'prevn', array( 'parsemag', 'escape' ), $fmtLimit );
1159 $next = wfMsgExt( 'nextn', array( 'parsemag', 'escape' ), $fmtLimit );
1160 # Get prev/next link title text
1161 $pTitle = wfMsgExt( 'prevn-title', array( 'parsemag', 'escape' ), $fmtLimit );
1162 $nTitle = wfMsgExt( 'nextn-title', array( 'parsemag', 'escape' ), $fmtLimit );
1163 # Fetch the title object
1164 if( is_object( $link ) ) {
1165 $title =& $link;
1166 } else {
1167 $title = Title::newFromText( $link );
1168 if( is_null( $title ) ) {
1169 return false;
1172 # Make 'previous' link
1173 if( 0 != $offset ) {
1174 $po = $offset - $limit;
1175 $po = max( $po, 0 );
1176 $q = "limit={$limit}&offset={$po}";
1177 if( $query != '' ) {
1178 $q .= '&' . $query;
1180 $plink = '<a href="' . $title->escapeLocalURL( $q ) . "\" title=\"{$pTitle}\" class=\"mw-prevlink\">{$prev}</a>";
1181 } else {
1182 $plink = $prev;
1184 # Make 'next' link
1185 $no = $offset + $limit;
1186 $q = "limit={$limit}&offset={$no}";
1187 if( $query != '' ) {
1188 $q .= '&' . $query;
1190 if( $atend ) {
1191 $nlink = $next;
1192 } else {
1193 $nlink = '<a href="' . $title->escapeLocalURL( $q ) . "\" title=\"{$nTitle}\" class=\"mw-nextlink\">{$next}</a>";
1195 # Make links to set number of items per page
1196 $nums = $wgLang->pipeList( array(
1197 wfNumLink( $offset, 20, $title, $query ),
1198 wfNumLink( $offset, 50, $title, $query ),
1199 wfNumLink( $offset, 100, $title, $query ),
1200 wfNumLink( $offset, 250, $title, $query ),
1201 wfNumLink( $offset, 500, $title, $query )
1202 ) );
1203 return wfMsgHtml( 'viewprevnext', $plink, $nlink, $nums );
1207 * Generate links for (20|50|100...) items-per-page links
1208 * @param $offset String
1209 * @param $limit Integer
1210 * @param $title Title
1211 * @param $query String: optional URL query parameter string
1213 function wfNumLink( $offset, $limit, $title, $query = '' ) {
1214 global $wgLang;
1215 if( $query == '' ) {
1216 $q = '';
1217 } else {
1218 $q = $query.'&';
1220 $q .= "limit={$limit}&offset={$offset}";
1221 $fmtLimit = $wgLang->formatNum( $limit );
1222 $lTitle = wfMsgExt( 'shown-title', array( 'parsemag', 'escape' ), $limit );
1223 $s = '<a href="' . $title->escapeLocalURL( $q ) . "\" title=\"{$lTitle}\" class=\"mw-numlink\">{$fmtLimit}</a>";
1224 return $s;
1228 * @todo document
1229 * @todo FIXME: we may want to blacklist some broken browsers
1231 * @return bool Whereas client accept gzip compression
1233 function wfClientAcceptsGzip() {
1234 if( isset( $_SERVER['HTTP_ACCEPT_ENCODING'] ) ) {
1235 # FIXME: we may want to blacklist some broken browsers
1236 $m = array();
1237 if( preg_match(
1238 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
1239 $_SERVER['HTTP_ACCEPT_ENCODING'],
1240 $m )
1243 if( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) {
1244 return false;
1246 wfDebug( " accepts gzip\n" );
1247 return true;
1250 return false;
1254 * Obtain the offset and limit values from the request string;
1255 * used in special pages
1257 * @param $deflimit Default limit if none supplied
1258 * @param $optionname Name of a user preference to check against
1259 * @return array
1262 function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) {
1263 global $wgRequest;
1264 return $wgRequest->getLimitOffset( $deflimit, $optionname );
1268 * Escapes the given text so that it may be output using addWikiText()
1269 * without any linking, formatting, etc. making its way through. This
1270 * is achieved by substituting certain characters with HTML entities.
1271 * As required by the callers, <nowiki> is not used. It currently does
1272 * not filter out characters which have special meaning only at the
1273 * start of a line, such as "*".
1275 * @param $text String: text to be escaped
1277 function wfEscapeWikiText( $text ) {
1278 $text = str_replace(
1279 array( '[', '|', ']', '\'', 'ISBN ', 'RFC ', '://', "\n=", '{{' ), # }}
1280 array( '&#91;', '&#124;', '&#93;', '&#39;', 'ISBN&#32;', 'RFC&#32;', '&#58;//', "\n&#61;", '&#123;&#123;' ),
1281 htmlspecialchars( $text )
1283 return $text;
1287 * @todo document
1289 function wfQuotedPrintable( $string, $charset = '' ) {
1290 # Probably incomplete; see RFC 2045
1291 if( empty( $charset ) ) {
1292 global $wgInputEncoding;
1293 $charset = $wgInputEncoding;
1295 $charset = strtoupper( $charset );
1296 $charset = str_replace( 'ISO-8859', 'ISO8859', $charset ); // ?
1298 $illegal = '\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\xff=';
1299 $replace = $illegal . '\t ?_';
1300 if( !preg_match( "/[$illegal]/", $string ) ) {
1301 return $string;
1303 $out = "=?$charset?Q?";
1304 $out .= preg_replace( "/([$replace])/e", 'sprintf("=%02X",ord("$1"))', $string );
1305 $out .= '?=';
1306 return $out;
1311 * @todo document
1312 * @return float
1314 function wfTime() {
1315 return microtime( true );
1319 * Sets dest to source and returns the original value of dest
1320 * If source is NULL, it just returns the value, it doesn't set the variable
1322 function wfSetVar( &$dest, $source ) {
1323 $temp = $dest;
1324 if ( !is_null( $source ) ) {
1325 $dest = $source;
1327 return $temp;
1331 * As for wfSetVar except setting a bit
1333 function wfSetBit( &$dest, $bit, $state = true ) {
1334 $temp = (bool)( $dest & $bit );
1335 if ( !is_null( $state ) ) {
1336 if ( $state ) {
1337 $dest |= $bit;
1338 } else {
1339 $dest &= ~$bit;
1342 return $temp;
1346 * This function takes two arrays as input, and returns a CGI-style string, e.g.
1347 * "days=7&limit=100". Options in the first array override options in the second.
1348 * Options set to "" will not be output.
1350 function wfArrayToCGI( $array1, $array2 = null ) {
1351 if ( !is_null( $array2 ) ) {
1352 $array1 = $array1 + $array2;
1355 $cgi = '';
1356 foreach ( $array1 as $key => $value ) {
1357 if ( $value !== '' ) {
1358 if ( $cgi != '' ) {
1359 $cgi .= '&';
1361 if ( is_array( $value ) ) {
1362 $firstTime = true;
1363 foreach ( $value as $v ) {
1364 $cgi .= ( $firstTime ? '' : '&') .
1365 urlencode( $key . '[]' ) . '=' .
1366 urlencode( $v );
1367 $firstTime = false;
1369 } else {
1370 if ( is_object( $value ) ) {
1371 $value = $value->__toString();
1373 $cgi .= urlencode( $key ) . '=' .
1374 urlencode( $value );
1378 return $cgi;
1382 * This is the logical opposite of wfArrayToCGI(): it accepts a query string as
1383 * its argument and returns the same string in array form. This allows compa-
1384 * tibility with legacy functions that accept raw query strings instead of nice
1385 * arrays. Of course, keys and values are urldecode()d. Don't try passing in-
1386 * valid query strings, or it will explode.
1388 * @param $query String: query string
1389 * @return array Array version of input
1391 function wfCgiToArray( $query ) {
1392 if( isset( $query[0] ) && $query[0] == '?' ) {
1393 $query = substr( $query, 1 );
1395 $bits = explode( '&', $query );
1396 $ret = array();
1397 foreach( $bits as $bit ) {
1398 if( $bit === '' ) {
1399 continue;
1401 list( $key, $value ) = explode( '=', $bit );
1402 $key = urldecode( $key );
1403 $value = urldecode( $value );
1404 $ret[$key] = $value;
1406 return $ret;
1410 * Append a query string to an existing URL, which may or may not already
1411 * have query string parameters already. If so, they will be combined.
1413 * @param $url String
1414 * @param $query Mixed: string or associative array
1415 * @return string
1417 function wfAppendQuery( $url, $query ) {
1418 if ( is_array( $query ) ) {
1419 $query = wfArrayToCGI( $query );
1421 if( $query != '' ) {
1422 if( false === strpos( $url, '?' ) ) {
1423 $url .= '?';
1424 } else {
1425 $url .= '&';
1427 $url .= $query;
1429 return $url;
1433 * Expand a potentially local URL to a fully-qualified URL. Assumes $wgServer
1434 * and $wgProto are correct.
1436 * @todo this won't work with current-path-relative URLs
1437 * like "subdir/foo.html", etc.
1439 * @param $url String: either fully-qualified or a local path + query
1440 * @return string Fully-qualified URL
1442 function wfExpandUrl( $url ) {
1443 if( substr( $url, 0, 2 ) == '//' ) {
1444 global $wgProto;
1445 return $wgProto . ':' . $url;
1446 } elseif( substr( $url, 0, 1 ) == '/' ) {
1447 global $wgServer;
1448 return $wgServer . $url;
1449 } else {
1450 return $url;
1455 * Windows-compatible version of escapeshellarg()
1456 * Windows doesn't recognise single-quotes in the shell, but the escapeshellarg()
1457 * function puts single quotes in regardless of OS.
1459 * Also fixes the locale problems on Linux in PHP 5.2.6+ (bug backported to
1460 * earlier distro releases of PHP)
1462 function wfEscapeShellArg( ) {
1463 wfInitShellLocale();
1465 $args = func_get_args();
1466 $first = true;
1467 $retVal = '';
1468 foreach ( $args as $arg ) {
1469 if ( !$first ) {
1470 $retVal .= ' ';
1471 } else {
1472 $first = false;
1475 if ( wfIsWindows() ) {
1476 // Escaping for an MSVC-style command line parser
1477 // Ref: http://mailman.lyra.org/pipermail/scite-interest/2002-March/000436.html
1478 // Double the backslashes before any double quotes. Escape the double quotes.
1479 $tokens = preg_split( '/(\\\\*")/', $arg, -1, PREG_SPLIT_DELIM_CAPTURE );
1480 $arg = '';
1481 $iteration = 0;
1482 foreach ( $tokens as $token ) {
1483 if ( $iteration % 2 == 1 ) {
1484 // Delimiter, a double quote preceded by zero or more slashes
1485 $arg .= str_replace( '\\', '\\\\', substr( $token, 0, -1 ) ) . '\\"';
1486 } elseif ( $iteration % 4 == 2 ) {
1487 // ^ in $token will be outside quotes, need to be escaped
1488 $arg .= str_replace( '^', '^^', $token );
1489 } else { // $iteration % 4 == 0
1490 // ^ in $token will appear inside double quotes, so leave as is
1491 $arg .= $token;
1493 $iteration++;
1495 // Double the backslashes before the end of the string, because
1496 // we will soon add a quote
1497 $m = array();
1498 if ( preg_match( '/^(.*?)(\\\\+)$/', $arg, $m ) ) {
1499 $arg = $m[1] . str_replace( '\\', '\\\\', $m[2] );
1502 // Add surrounding quotes
1503 $retVal .= '"' . $arg . '"';
1504 } else {
1505 $retVal .= escapeshellarg( $arg );
1508 return $retVal;
1512 * wfMerge attempts to merge differences between three texts.
1513 * Returns true for a clean merge and false for failure or a conflict.
1515 function wfMerge( $old, $mine, $yours, &$result ) {
1516 global $wgDiff3;
1518 # This check may also protect against code injection in
1519 # case of broken installations.
1520 wfSuppressWarnings();
1521 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
1522 wfRestoreWarnings();
1524 if( !$haveDiff3 ) {
1525 wfDebug( "diff3 not found\n" );
1526 return false;
1529 # Make temporary files
1530 $td = wfTempDir();
1531 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
1532 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
1533 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
1535 fwrite( $oldtextFile, $old );
1536 fclose( $oldtextFile );
1537 fwrite( $mytextFile, $mine );
1538 fclose( $mytextFile );
1539 fwrite( $yourtextFile, $yours );
1540 fclose( $yourtextFile );
1542 # Check for a conflict
1543 $cmd = $wgDiff3 . ' -a --overlap-only ' .
1544 wfEscapeShellArg( $mytextName ) . ' ' .
1545 wfEscapeShellArg( $oldtextName ) . ' ' .
1546 wfEscapeShellArg( $yourtextName );
1547 $handle = popen( $cmd, 'r' );
1549 if( fgets( $handle, 1024 ) ) {
1550 $conflict = true;
1551 } else {
1552 $conflict = false;
1554 pclose( $handle );
1556 # Merge differences
1557 $cmd = $wgDiff3 . ' -a -e --merge ' .
1558 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
1559 $handle = popen( $cmd, 'r' );
1560 $result = '';
1561 do {
1562 $data = fread( $handle, 8192 );
1563 if ( strlen( $data ) == 0 ) {
1564 break;
1566 $result .= $data;
1567 } while ( true );
1568 pclose( $handle );
1569 unlink( $mytextName );
1570 unlink( $oldtextName );
1571 unlink( $yourtextName );
1573 if ( $result === '' && $old !== '' && !$conflict ) {
1574 wfDebug( "Unexpected null result from diff3. Command: $cmd\n" );
1575 $conflict = true;
1577 return !$conflict;
1581 * Returns unified plain-text diff of two texts.
1582 * Useful for machine processing of diffs.
1583 * @param $before String: the text before the changes.
1584 * @param $after String: the text after the changes.
1585 * @param $params String: command-line options for the diff command.
1586 * @return String: unified diff of $before and $after
1588 function wfDiff( $before, $after, $params = '-u' ) {
1589 if ( $before == $after ) {
1590 return '';
1593 global $wgDiff;
1594 wfSuppressWarnings();
1595 $haveDiff = $wgDiff && file_exists( $wgDiff );
1596 wfRestoreWarnings();
1598 # This check may also protect against code injection in
1599 # case of broken installations.
1600 if( !$haveDiff ) {
1601 wfDebug( "diff executable not found\n" );
1602 $diffs = new Diff( explode( "\n", $before ), explode( "\n", $after ) );
1603 $format = new UnifiedDiffFormatter();
1604 return $format->format( $diffs );
1607 # Make temporary files
1608 $td = wfTempDir();
1609 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
1610 $newtextFile = fopen( $newtextName = tempnam( $td, 'merge-your-' ), 'w' );
1612 fwrite( $oldtextFile, $before );
1613 fclose( $oldtextFile );
1614 fwrite( $newtextFile, $after );
1615 fclose( $newtextFile );
1617 // Get the diff of the two files
1618 $cmd = "$wgDiff " . $params . ' ' . wfEscapeShellArg( $oldtextName, $newtextName );
1620 $h = popen( $cmd, 'r' );
1622 $diff = '';
1624 do {
1625 $data = fread( $h, 8192 );
1626 if ( strlen( $data ) == 0 ) {
1627 break;
1629 $diff .= $data;
1630 } while ( true );
1632 // Clean up
1633 pclose( $h );
1634 unlink( $oldtextName );
1635 unlink( $newtextName );
1637 // Kill the --- and +++ lines. They're not useful.
1638 $diff_lines = explode( "\n", $diff );
1639 if ( strpos( $diff_lines[0], '---' ) === 0 ) {
1640 unset( $diff_lines[0] );
1642 if ( strpos( $diff_lines[1], '+++' ) === 0 ) {
1643 unset( $diff_lines[1] );
1646 $diff = implode( "\n", $diff_lines );
1648 return $diff;
1652 * A wrapper around the PHP function var_export().
1653 * Either print it or add it to the regular output ($wgOut).
1655 * @param $var A PHP variable to dump.
1657 function wfVarDump( $var ) {
1658 global $wgOut;
1659 $s = str_replace( "\n", "<br />\n", var_export( $var, true ) . "\n" );
1660 if ( headers_sent() || !@is_object( $wgOut ) ) {
1661 print $s;
1662 } else {
1663 $wgOut->addHTML( $s );
1668 * Provide a simple HTTP error.
1670 function wfHttpError( $code, $label, $desc ) {
1671 global $wgOut;
1672 $wgOut->disable();
1673 header( "HTTP/1.0 $code $label" );
1674 header( "Status: $code $label" );
1675 $wgOut->sendCacheControl();
1677 header( 'Content-type: text/html; charset=utf-8' );
1678 print "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">".
1679 '<html><head><title>' .
1680 htmlspecialchars( $label ) .
1681 '</title></head><body><h1>' .
1682 htmlspecialchars( $label ) .
1683 '</h1><p>' .
1684 nl2br( htmlspecialchars( $desc ) ) .
1685 "</p></body></html>\n";
1689 * Clear away any user-level output buffers, discarding contents.
1691 * Suitable for 'starting afresh', for instance when streaming
1692 * relatively large amounts of data without buffering, or wanting to
1693 * output image files without ob_gzhandler's compression.
1695 * The optional $resetGzipEncoding parameter controls suppression of
1696 * the Content-Encoding header sent by ob_gzhandler; by default it
1697 * is left. See comments for wfClearOutputBuffers() for why it would
1698 * be used.
1700 * Note that some PHP configuration options may add output buffer
1701 * layers which cannot be removed; these are left in place.
1703 * @param $resetGzipEncoding Bool
1705 function wfResetOutputBuffers( $resetGzipEncoding = true ) {
1706 if( $resetGzipEncoding ) {
1707 // Suppress Content-Encoding and Content-Length
1708 // headers from 1.10+s wfOutputHandler
1709 global $wgDisableOutputCompression;
1710 $wgDisableOutputCompression = true;
1712 while( $status = ob_get_status() ) {
1713 if( $status['type'] == 0 /* PHP_OUTPUT_HANDLER_INTERNAL */ ) {
1714 // Probably from zlib.output_compression or other
1715 // PHP-internal setting which can't be removed.
1717 // Give up, and hope the result doesn't break
1718 // output behavior.
1719 break;
1721 if( !ob_end_clean() ) {
1722 // Could not remove output buffer handler; abort now
1723 // to avoid getting in some kind of infinite loop.
1724 break;
1726 if( $resetGzipEncoding ) {
1727 if( $status['name'] == 'ob_gzhandler' ) {
1728 // Reset the 'Content-Encoding' field set by this handler
1729 // so we can start fresh.
1730 header( 'Content-Encoding:' );
1731 break;
1738 * More legible than passing a 'false' parameter to wfResetOutputBuffers():
1740 * Clear away output buffers, but keep the Content-Encoding header
1741 * produced by ob_gzhandler, if any.
1743 * This should be used for HTTP 304 responses, where you need to
1744 * preserve the Content-Encoding header of the real result, but
1745 * also need to suppress the output of ob_gzhandler to keep to spec
1746 * and avoid breaking Firefox in rare cases where the headers and
1747 * body are broken over two packets.
1749 function wfClearOutputBuffers() {
1750 wfResetOutputBuffers( false );
1754 * Converts an Accept-* header into an array mapping string values to quality
1755 * factors
1757 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
1758 # No arg means accept anything (per HTTP spec)
1759 if( !$accept ) {
1760 return array( $def => 1.0 );
1763 $prefs = array();
1765 $parts = explode( ',', $accept );
1767 foreach( $parts as $part ) {
1768 # FIXME: doesn't deal with params like 'text/html; level=1'
1769 @list( $value, $qpart ) = explode( ';', trim( $part ) );
1770 $match = array();
1771 if( !isset( $qpart ) ) {
1772 $prefs[$value] = 1.0;
1773 } elseif( preg_match( '/q\s*=\s*(\d*\.\d+)/', $qpart, $match ) ) {
1774 $prefs[$value] = floatval( $match[1] );
1778 return $prefs;
1782 * Checks if a given MIME type matches any of the keys in the given
1783 * array. Basic wildcards are accepted in the array keys.
1785 * Returns the matching MIME type (or wildcard) if a match, otherwise
1786 * NULL if no match.
1788 * @param $type String
1789 * @param $avail Array
1790 * @return string
1791 * @private
1793 function mimeTypeMatch( $type, $avail ) {
1794 if( array_key_exists( $type, $avail ) ) {
1795 return $type;
1796 } else {
1797 $parts = explode( '/', $type );
1798 if( array_key_exists( $parts[0] . '/*', $avail ) ) {
1799 return $parts[0] . '/*';
1800 } elseif( array_key_exists( '*/*', $avail ) ) {
1801 return '*/*';
1802 } else {
1803 return null;
1809 * Returns the 'best' match between a client's requested internet media types
1810 * and the server's list of available types. Each list should be an associative
1811 * array of type to preference (preference is a float between 0.0 and 1.0).
1812 * Wildcards in the types are acceptable.
1814 * @param $cprefs Array: client's acceptable type list
1815 * @param $sprefs Array: server's offered types
1816 * @return string
1818 * @todo FIXME: doesn't handle params like 'text/plain; charset=UTF-8'
1819 * XXX: generalize to negotiate other stuff
1821 function wfNegotiateType( $cprefs, $sprefs ) {
1822 $combine = array();
1824 foreach( array_keys($sprefs) as $type ) {
1825 $parts = explode( '/', $type );
1826 if( $parts[1] != '*' ) {
1827 $ckey = mimeTypeMatch( $type, $cprefs );
1828 if( $ckey ) {
1829 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1834 foreach( array_keys( $cprefs ) as $type ) {
1835 $parts = explode( '/', $type );
1836 if( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
1837 $skey = mimeTypeMatch( $type, $sprefs );
1838 if( $skey ) {
1839 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1844 $bestq = 0;
1845 $besttype = null;
1847 foreach( array_keys( $combine ) as $type ) {
1848 if( $combine[$type] > $bestq ) {
1849 $besttype = $type;
1850 $bestq = $combine[$type];
1854 return $besttype;
1858 * Array lookup
1859 * Returns an array where the values in the first array are replaced by the
1860 * values in the second array with the corresponding keys
1862 * @return array
1864 function wfArrayLookup( $a, $b ) {
1865 return array_flip( array_intersect( array_flip( $a ), array_keys( $b ) ) );
1869 * Convenience function; returns MediaWiki timestamp for the present time.
1870 * @return string
1872 function wfTimestampNow() {
1873 # return NOW
1874 return wfTimestamp( TS_MW, time() );
1878 * Reference-counted warning suppression
1880 function wfSuppressWarnings( $end = false ) {
1881 static $suppressCount = 0;
1882 static $originalLevel = false;
1884 if ( $end ) {
1885 if ( $suppressCount ) {
1886 --$suppressCount;
1887 if ( !$suppressCount ) {
1888 error_reporting( $originalLevel );
1891 } else {
1892 if ( !$suppressCount ) {
1893 $originalLevel = error_reporting( E_ALL & ~( E_WARNING | E_NOTICE | E_USER_WARNING | E_USER_NOTICE ) );
1895 ++$suppressCount;
1900 * Restore error level to previous value
1902 function wfRestoreWarnings() {
1903 wfSuppressWarnings( true );
1906 # Autodetect, convert and provide timestamps of various types
1909 * Unix time - the number of seconds since 1970-01-01 00:00:00 UTC
1911 define( 'TS_UNIX', 0 );
1914 * MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
1916 define( 'TS_MW', 1 );
1919 * MySQL DATETIME (YYYY-MM-DD HH:MM:SS)
1921 define( 'TS_DB', 2 );
1924 * RFC 2822 format, for E-mail and HTTP headers
1926 define( 'TS_RFC2822', 3 );
1929 * ISO 8601 format with no timezone: 1986-02-09T20:00:00Z
1931 * This is used by Special:Export
1933 define( 'TS_ISO_8601', 4 );
1936 * An Exif timestamp (YYYY:MM:DD HH:MM:SS)
1938 * @see http://exif.org/Exif2-2.PDF The Exif 2.2 spec, see page 28 for the
1939 * DateTime tag and page 36 for the DateTimeOriginal and
1940 * DateTimeDigitized tags.
1942 define( 'TS_EXIF', 5 );
1945 * Oracle format time.
1947 define( 'TS_ORACLE', 6 );
1950 * Postgres format time.
1952 define( 'TS_POSTGRES', 7 );
1955 * DB2 format time
1957 define( 'TS_DB2', 8 );
1960 * ISO 8601 basic format with no timezone: 19860209T200000Z
1962 * This is used by ResourceLoader
1964 define( 'TS_ISO_8601_BASIC', 9 );
1967 * @param $outputtype Mixed: A timestamp in one of the supported formats, the
1968 * function will autodetect which format is supplied and act
1969 * accordingly.
1970 * @param $ts Mixed: the timestamp to convert or 0 for the current timestamp
1971 * @return String: in the format specified in $outputtype
1973 function wfTimestamp( $outputtype = TS_UNIX, $ts = 0 ) {
1974 $uts = 0;
1975 $da = array();
1976 if ( $ts === 0 ) {
1977 $uts = time();
1978 } elseif ( preg_match( '/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)$/D', $ts, $da ) ) {
1979 # TS_DB
1980 } elseif ( preg_match( '/^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/D', $ts, $da ) ) {
1981 # TS_EXIF
1982 } elseif ( preg_match( '/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/D', $ts, $da ) ) {
1983 # TS_MW
1984 } elseif ( preg_match( '/^-?\d{1,13}$/D', $ts ) ) {
1985 # TS_UNIX
1986 $uts = $ts;
1987 } elseif ( preg_match( '/^\d{2}-\d{2}-\d{4} \d{2}:\d{2}:\d{2}.\d{6}$/', $ts ) ) {
1988 # TS_ORACLE // session altered to DD-MM-YYYY HH24:MI:SS.FF6
1989 $uts = strtotime( preg_replace( '/(\d\d)\.(\d\d)\.(\d\d)(\.(\d+))?/', "$1:$2:$3",
1990 str_replace( '+00:00', 'UTC', $ts ) ) );
1991 } elseif ( preg_match( '/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.*\d*)?Z$/', $ts, $da ) ) {
1992 # TS_ISO_8601
1993 } elseif ( preg_match( '/^(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})(?:\.*\d*)?Z$/', $ts, $da ) ) {
1994 #TS_ISO_8601_BASIC
1995 } elseif ( preg_match( '/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.*\d*[\+\- ](\d\d)$/', $ts, $da ) ) {
1996 # TS_POSTGRES
1997 } elseif ( preg_match( '/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.*\d* GMT$/', $ts, $da ) ) {
1998 # TS_POSTGRES
1999 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.\d\d\d$/',$ts,$da)) {
2000 # TS_DB2
2001 } elseif ( preg_match( '/^[A-Z][a-z]{2}, \d\d [A-Z][a-z]{2} \d{4} \d\d:\d\d:\d\d/', $ts ) ) {
2002 # TS_RFC2822
2003 $uts = strtotime( $ts );
2004 } else {
2005 # Bogus value; fall back to the epoch...
2006 wfDebug("wfTimestamp() fed bogus time value: $outputtype; $ts\n");
2007 $uts = 0;
2010 if (count( $da ) ) {
2011 // Warning! gmmktime() acts oddly if the month or day is set to 0
2012 // We may want to handle that explicitly at some point
2013 $uts = gmmktime( (int)$da[4], (int)$da[5], (int)$da[6],
2014 (int)$da[2], (int)$da[3], (int)$da[1] );
2017 switch( $outputtype ) {
2018 case TS_UNIX:
2019 return $uts;
2020 case TS_MW:
2021 return gmdate( 'YmdHis', $uts );
2022 case TS_DB:
2023 return gmdate( 'Y-m-d H:i:s', $uts );
2024 case TS_ISO_8601:
2025 return gmdate( 'Y-m-d\TH:i:s\Z', $uts );
2026 case TS_ISO_8601_BASIC:
2027 return gmdate( 'Ymd\THis\Z', $uts );
2028 // This shouldn't ever be used, but is included for completeness
2029 case TS_EXIF:
2030 return gmdate( 'Y:m:d H:i:s', $uts );
2031 case TS_RFC2822:
2032 return gmdate( 'D, d M Y H:i:s', $uts ) . ' GMT';
2033 case TS_ORACLE:
2034 return gmdate( 'd-m-Y H:i:s.000000', $uts );
2035 //return gmdate( 'd-M-y h.i.s A', $uts ) . ' +00:00';
2036 case TS_POSTGRES:
2037 return gmdate( 'Y-m-d H:i:s', $uts ) . ' GMT';
2038 case TS_DB2:
2039 return gmdate( 'Y-m-d H:i:s', $uts );
2040 default:
2041 throw new MWException( 'wfTimestamp() called with illegal output type.' );
2046 * Return a formatted timestamp, or null if input is null.
2047 * For dealing with nullable timestamp columns in the database.
2048 * @param $outputtype Integer
2049 * @param $ts String
2050 * @return String
2052 function wfTimestampOrNull( $outputtype = TS_UNIX, $ts = null ) {
2053 if( is_null( $ts ) ) {
2054 return null;
2055 } else {
2056 return wfTimestamp( $outputtype, $ts );
2061 * Check if the operating system is Windows
2063 * @return Bool: true if it's Windows, False otherwise.
2065 function wfIsWindows() {
2066 if ( substr( php_uname(), 0, 7 ) == 'Windows' ) {
2067 return true;
2068 } else {
2069 return false;
2074 * Swap two variables
2076 function swap( &$x, &$y ) {
2077 $z = $x;
2078 $x = $y;
2079 $y = $z;
2082 function wfGetCachedNotice( $name ) {
2083 global $wgOut, $wgRenderHashAppend, $parserMemc;
2084 $fname = 'wfGetCachedNotice';
2085 wfProfileIn( $fname );
2087 $needParse = false;
2089 if( $name === 'default' ) {
2090 // special case
2091 global $wgSiteNotice;
2092 $notice = $wgSiteNotice;
2093 if( empty( $notice ) ) {
2094 wfProfileOut( $fname );
2095 return false;
2097 } else {
2098 $notice = wfMsgForContentNoTrans( $name );
2099 if( wfEmptyMsg( $name, $notice ) || $notice == '-' ) {
2100 wfProfileOut( $fname );
2101 return( false );
2105 // Use the extra hash appender to let eg SSL variants separately cache.
2106 $key = wfMemcKey( $name . $wgRenderHashAppend );
2107 $cachedNotice = $parserMemc->get( $key );
2108 if( is_array( $cachedNotice ) ) {
2109 if( md5( $notice ) == $cachedNotice['hash'] ) {
2110 $notice = $cachedNotice['html'];
2111 } else {
2112 $needParse = true;
2114 } else {
2115 $needParse = true;
2118 if( $needParse ) {
2119 if( is_object( $wgOut ) ) {
2120 $parsed = $wgOut->parse( $notice );
2121 $parserMemc->set( $key, array( 'html' => $parsed, 'hash' => md5( $notice ) ), 600 );
2122 $notice = $parsed;
2123 } else {
2124 wfDebug( 'wfGetCachedNotice called for ' . $name . ' with no $wgOut available' . "\n" );
2125 $notice = '';
2128 $notice = '<div id="localNotice">' .$notice . '</div>';
2129 wfProfileOut( $fname );
2130 return $notice;
2133 function wfGetNamespaceNotice() {
2134 global $wgTitle;
2136 # Paranoia
2137 if ( !isset( $wgTitle ) || !is_object( $wgTitle ) ) {
2138 return '';
2141 $fname = 'wfGetNamespaceNotice';
2142 wfProfileIn( $fname );
2144 $key = 'namespacenotice-' . $wgTitle->getNsText();
2145 $namespaceNotice = wfGetCachedNotice( $key );
2146 if ( $namespaceNotice && substr( $namespaceNotice, 0, 7 ) != '<p>&lt;' ) {
2147 $namespaceNotice = '<div id="namespacebanner">' . $namespaceNotice . '</div>';
2148 } else {
2149 $namespaceNotice = '';
2152 wfProfileOut( $fname );
2153 return $namespaceNotice;
2156 function wfGetSiteNotice() {
2157 global $wgUser;
2158 $fname = 'wfGetSiteNotice';
2159 wfProfileIn( $fname );
2160 $siteNotice = '';
2162 if( wfRunHooks( 'SiteNoticeBefore', array( &$siteNotice ) ) ) {
2163 if( is_object( $wgUser ) && $wgUser->isLoggedIn() ) {
2164 $siteNotice = wfGetCachedNotice( 'sitenotice' );
2165 } else {
2166 $anonNotice = wfGetCachedNotice( 'anonnotice' );
2167 if( !$anonNotice ) {
2168 $siteNotice = wfGetCachedNotice( 'sitenotice' );
2169 } else {
2170 $siteNotice = $anonNotice;
2173 if( !$siteNotice ) {
2174 $siteNotice = wfGetCachedNotice( 'default' );
2178 wfRunHooks( 'SiteNoticeAfter', array( &$siteNotice ) );
2179 wfProfileOut( $fname );
2180 return $siteNotice;
2184 * BC wrapper for MimeMagic::singleton()
2185 * @deprecated
2187 function &wfGetMimeMagic() {
2188 wfDeprecated( __FUNCTION__ );
2189 return MimeMagic::singleton();
2193 * Tries to get the system directory for temporary files. The TMPDIR, TMP, and
2194 * TEMP environment variables are then checked in sequence, and if none are set
2195 * try sys_get_temp_dir() for PHP >= 5.2.1. All else fails, return /tmp for Unix
2196 * or C:\Windows\Temp for Windows and hope for the best.
2197 * It is common to call it with tempnam().
2199 * NOTE: When possible, use instead the tmpfile() function to create
2200 * temporary files to avoid race conditions on file creation, etc.
2202 * @return String
2204 function wfTempDir() {
2205 foreach( array( 'TMPDIR', 'TMP', 'TEMP' ) as $var ) {
2206 $tmp = getenv( $var );
2207 if( $tmp && file_exists( $tmp ) && is_dir( $tmp ) && is_writable( $tmp ) ) {
2208 return $tmp;
2211 if( function_exists( 'sys_get_temp_dir' ) ) {
2212 return sys_get_temp_dir();
2214 # Usual defaults
2215 return wfIsWindows() ? 'C:\Windows\Temp' : '/tmp';
2219 * Make directory, and make all parent directories if they don't exist
2221 * @param $dir String: full path to directory to create
2222 * @param $mode Integer: chmod value to use, default is $wgDirectoryMode
2223 * @param $caller String: optional caller param for debugging.
2224 * @return bool
2226 function wfMkdirParents( $dir, $mode = null, $caller = null ) {
2227 global $wgDirectoryMode;
2229 if ( !is_null( $caller ) ) {
2230 wfDebug( "$caller: called wfMkdirParents($dir)" );
2233 if( strval( $dir ) === '' || file_exists( $dir ) ) {
2234 return true;
2237 $dir = str_replace( array( '\\', '/' ), DIRECTORY_SEPARATOR, $dir );
2239 if ( is_null( $mode ) ) {
2240 $mode = $wgDirectoryMode;
2243 // Turn off the normal warning, we're doing our own below
2244 wfSuppressWarnings();
2245 $ok = mkdir( $dir, $mode, true ); // PHP5 <3
2246 wfRestoreWarnings();
2248 if( !$ok ) {
2249 // PHP doesn't report the path in its warning message, so add our own to aid in diagnosis.
2250 trigger_error( __FUNCTION__ . ": failed to mkdir \"$dir\" mode $mode", E_USER_WARNING );
2252 return $ok;
2256 * Increment a statistics counter
2258 function wfIncrStats( $key ) {
2259 global $wgStatsMethod;
2261 if( $wgStatsMethod == 'udp' ) {
2262 global $wgUDPProfilerHost, $wgUDPProfilerPort, $wgDBname;
2263 static $socket;
2264 if ( !$socket ) {
2265 $socket = socket_create( AF_INET, SOCK_DGRAM, SOL_UDP );
2266 $statline = "stats/{$wgDBname} - 1 1 1 1 1 -total\n";
2267 socket_sendto(
2268 $socket,
2269 $statline,
2270 strlen( $statline ),
2272 $wgUDPProfilerHost,
2273 $wgUDPProfilerPort
2276 $statline = "stats/{$wgDBname} - 1 1 1 1 1 {$key}\n";
2277 @socket_sendto(
2278 $socket,
2279 $statline,
2280 strlen( $statline ),
2282 $wgUDPProfilerHost,
2283 $wgUDPProfilerPort
2285 } elseif( $wgStatsMethod == 'cache' ) {
2286 global $wgMemc;
2287 $key = wfMemcKey( 'stats', $key );
2288 if ( is_null( $wgMemc->incr( $key ) ) ) {
2289 $wgMemc->add( $key, 1 );
2291 } else {
2292 // Disabled
2297 * @param $nr Mixed: the number to format
2298 * @param $acc Integer: the number of digits after the decimal point, default 2
2299 * @param $round Boolean: whether or not to round the value, default true
2300 * @return float
2302 function wfPercent( $nr, $acc = 2, $round = true ) {
2303 $ret = sprintf( "%.${acc}f", $nr );
2304 return $round ? round( $ret, $acc ) . '%' : "$ret%";
2308 * Encrypt a username/password.
2310 * @param $userid Integer: ID of the user
2311 * @param $password String: password of the user
2312 * @return String: hashed password
2313 * @deprecated Use User::crypt() or User::oldCrypt() instead
2315 function wfEncryptPassword( $userid, $password ) {
2316 wfDeprecated(__FUNCTION__);
2317 # Just wrap around User::oldCrypt()
2318 return User::oldCrypt( $password, $userid );
2322 * Appends to second array if $value differs from that in $default
2324 function wfAppendToArrayIfNotDefault( $key, $value, $default, &$changed ) {
2325 if ( is_null( $changed ) ) {
2326 throw new MWException( 'GlobalFunctions::wfAppendToArrayIfNotDefault got null' );
2328 if ( $default[$key] !== $value ) {
2329 $changed[$key] = $value;
2334 * Since wfMsg() and co suck, they don't return false if the message key they
2335 * looked up didn't exist but a XHTML string, this function checks for the
2336 * nonexistance of messages by looking at wfMsg() output
2338 * @param $key String: the message key looked up
2339 * @return Boolean True if the message *doesn't* exist.
2341 function wfEmptyMsg( $key ) {
2342 global $wgMessageCache;
2343 return $wgMessageCache->get( $key, /*useDB*/true, /*content*/false ) === false;
2347 * Find out whether or not a mixed variable exists in a string
2349 * @param $needle String
2350 * @param $str String
2351 * @return Boolean
2353 function in_string( $needle, $str ) {
2354 return strpos( $str, $needle ) !== false;
2357 function wfSpecialList( $page, $details ) {
2358 global $wgContLang;
2359 $details = $details ? ' ' . $wgContLang->getDirMark() . "($details)" : '';
2360 return $page . $details;
2364 * Returns a regular expression of url protocols
2366 * @return String
2368 function wfUrlProtocols() {
2369 global $wgUrlProtocols;
2371 static $retval = null;
2372 if ( !is_null( $retval ) ) {
2373 return $retval;
2376 // Support old-style $wgUrlProtocols strings, for backwards compatibility
2377 // with LocalSettings files from 1.5
2378 if ( is_array( $wgUrlProtocols ) ) {
2379 $protocols = array();
2380 foreach ( $wgUrlProtocols as $protocol ) {
2381 $protocols[] = preg_quote( $protocol, '/' );
2384 $retval = implode( '|', $protocols );
2385 } else {
2386 $retval = $wgUrlProtocols;
2388 return $retval;
2392 * Safety wrapper around ini_get() for boolean settings.
2393 * The values returned from ini_get() are pre-normalized for settings
2394 * set via php.ini or php_flag/php_admin_flag... but *not*
2395 * for those set via php_value/php_admin_value.
2397 * It's fairly common for people to use php_value instead of php_flag,
2398 * which can leave you with an 'off' setting giving a false positive
2399 * for code that just takes the ini_get() return value as a boolean.
2401 * To make things extra interesting, setting via php_value accepts
2402 * "true" and "yes" as true, but php.ini and php_flag consider them false. :)
2403 * Unrecognized values go false... again opposite PHP's own coercion
2404 * from string to bool.
2406 * Luckily, 'properly' set settings will always come back as '0' or '1',
2407 * so we only have to worry about them and the 'improper' settings.
2409 * I frickin' hate PHP... :P
2411 * @param $setting String
2412 * @return Bool
2414 function wfIniGetBool( $setting ) {
2415 $val = ini_get( $setting );
2416 // 'on' and 'true' can't have whitespace around them, but '1' can.
2417 return strtolower( $val ) == 'on'
2418 || strtolower( $val ) == 'true'
2419 || strtolower( $val ) == 'yes'
2420 || preg_match( "/^\s*[+-]?0*[1-9]/", $val ); // approx C atoi() function
2424 * Wrapper function for PHP's dl(). This doesn't work in most situations from
2425 * PHP 5.3 onward, and is usually disabled in shared environments anyway.
2427 * @param $extension String A PHP extension. The file suffix (.so or .dll)
2428 * should be omitted
2429 * @return Bool - Whether or not the extension is loaded
2431 function wfDl( $extension ) {
2432 if( extension_loaded( $extension ) ) {
2433 return true;
2436 $canDl = ( function_exists( 'dl' ) && is_callable( 'dl' )
2437 && wfIniGetBool( 'enable_dl' ) && !wfIniGetBool( 'safe_mode' ) );
2439 if( $canDl ) {
2440 wfSuppressWarnings();
2441 dl( $extension . '.' . PHP_SHLIB_SUFFIX );
2442 wfRestoreWarnings();
2444 return extension_loaded( $extension );
2448 * Execute a shell command, with time and memory limits mirrored from the PHP
2449 * configuration if supported.
2450 * @param $cmd Command line, properly escaped for shell.
2451 * @param &$retval optional, will receive the program's exit code.
2452 * (non-zero is usually failure)
2453 * @return collected stdout as a string (trailing newlines stripped)
2455 function wfShellExec( $cmd, &$retval = null ) {
2456 global $IP, $wgMaxShellMemory, $wgMaxShellFileSize, $wgMaxShellTime;
2458 static $disabled;
2459 if ( is_null( $disabled ) ) {
2460 $disabled = false;
2461 if( wfIniGetBool( 'safe_mode' ) ) {
2462 wfDebug( "wfShellExec can't run in safe_mode, PHP's exec functions are too broken.\n" );
2463 $disabled = 'safemode';
2465 $functions = explode( ',', ini_get( 'disable_functions' ) );
2466 $functions = array_map( 'trim', $functions );
2467 $functions = array_map( 'strtolower', $functions );
2468 if ( in_array( 'passthru', $functions ) ) {
2469 wfDebug( "passthru is in disabled_functions\n" );
2470 $disabled = 'passthru';
2473 if ( $disabled ) {
2474 $retval = 1;
2475 return $disabled == 'safemode' ?
2476 'Unable to run external programs in safe mode.' :
2477 'Unable to run external programs, passthru() is disabled.';
2480 wfInitShellLocale();
2482 if ( php_uname( 's' ) == 'Linux' ) {
2483 $time = intval( $wgMaxShellTime );
2484 $mem = intval( $wgMaxShellMemory );
2485 $filesize = intval( $wgMaxShellFileSize );
2487 if ( $time > 0 && $mem > 0 ) {
2488 $script = "$IP/bin/ulimit4.sh";
2489 if ( is_executable( $script ) ) {
2490 $cmd = '/bin/bash ' . escapeshellarg( $script ) . " $time $mem $filesize " . escapeshellarg( $cmd );
2493 } elseif ( php_uname( 's' ) == 'Windows NT' &&
2494 version_compare( PHP_VERSION, '5.3.0', '<' ) )
2496 # This is a hack to work around PHP's flawed invocation of cmd.exe
2497 # http://news.php.net/php.internals/21796
2498 # Which is fixed in 5.3.0 :)
2499 $cmd = '"' . $cmd . '"';
2501 wfDebug( "wfShellExec: $cmd\n" );
2503 $retval = 1; // error by default?
2504 ob_start();
2505 passthru( $cmd, $retval );
2506 $output = ob_get_contents();
2507 ob_end_clean();
2509 if ( $retval == 127 ) {
2510 wfDebugLog( 'exec', "Possibly missing executable file: $cmd\n" );
2512 return $output;
2516 * Workaround for http://bugs.php.net/bug.php?id=45132
2517 * escapeshellarg() destroys non-ASCII characters if LANG is not a UTF-8 locale
2519 function wfInitShellLocale() {
2520 static $done = false;
2521 if ( $done ) {
2522 return;
2524 $done = true;
2525 global $wgShellLocale;
2526 if ( !wfIniGetBool( 'safe_mode' ) ) {
2527 putenv( "LC_CTYPE=$wgShellLocale" );
2528 setlocale( LC_CTYPE, $wgShellLocale );
2533 * This function works like "use VERSION" in Perl, the program will die with a
2534 * backtrace if the current version of PHP is less than the version provided
2536 * This is useful for extensions which due to their nature are not kept in sync
2537 * with releases, and might depend on other versions of PHP than the main code
2539 * Note: PHP might die due to parsing errors in some cases before it ever
2540 * manages to call this function, such is life
2542 * @see perldoc -f use
2544 * @param $req_ver Mixed: the version to check, can be a string, an integer, or
2545 * a float
2547 function wfUsePHP( $req_ver ) {
2548 $php_ver = PHP_VERSION;
2550 if ( version_compare( $php_ver, (string)$req_ver, '<' ) ) {
2551 throw new MWException( "PHP $req_ver required--this is only $php_ver" );
2556 * This function works like "use VERSION" in Perl except it checks the version
2557 * of MediaWiki, the program will die with a backtrace if the current version
2558 * of MediaWiki is less than the version provided.
2560 * This is useful for extensions which due to their nature are not kept in sync
2561 * with releases
2563 * @see perldoc -f use
2565 * @param $req_ver Mixed: the version to check, can be a string, an integer, or
2566 * a float
2568 function wfUseMW( $req_ver ) {
2569 global $wgVersion;
2571 if ( version_compare( $wgVersion, (string)$req_ver, '<' ) ) {
2572 throw new MWException( "MediaWiki $req_ver required--this is only $wgVersion" );
2577 * Return the final portion of a pathname.
2578 * Reimplemented because PHP5's basename() is buggy with multibyte text.
2579 * http://bugs.php.net/bug.php?id=33898
2581 * PHP's basename() only considers '\' a pathchar on Windows and Netware.
2582 * We'll consider it so always, as we don't want \s in our Unix paths either.
2584 * @param $path String
2585 * @param $suffix String: to remove if present
2586 * @return String
2588 function wfBaseName( $path, $suffix = '' ) {
2589 $encSuffix = ( $suffix == '' )
2590 ? ''
2591 : ( '(?:' . preg_quote( $suffix, '#' ) . ')?' );
2592 $matches = array();
2593 if( preg_match( "#([^/\\\\]*?){$encSuffix}[/\\\\]*$#", $path, $matches ) ) {
2594 return $matches[1];
2595 } else {
2596 return '';
2601 * Generate a relative path name to the given file.
2602 * May explode on non-matching case-insensitive paths,
2603 * funky symlinks, etc.
2605 * @param $path String: absolute destination path including target filename
2606 * @param $from String: Absolute source path, directory only
2607 * @return String
2609 function wfRelativePath( $path, $from ) {
2610 // Normalize mixed input on Windows...
2611 $path = str_replace( '/', DIRECTORY_SEPARATOR, $path );
2612 $from = str_replace( '/', DIRECTORY_SEPARATOR, $from );
2614 // Trim trailing slashes -- fix for drive root
2615 $path = rtrim( $path, DIRECTORY_SEPARATOR );
2616 $from = rtrim( $from, DIRECTORY_SEPARATOR );
2618 $pieces = explode( DIRECTORY_SEPARATOR, dirname( $path ) );
2619 $against = explode( DIRECTORY_SEPARATOR, $from );
2621 if( $pieces[0] !== $against[0] ) {
2622 // Non-matching Windows drive letters?
2623 // Return a full path.
2624 return $path;
2627 // Trim off common prefix
2628 while( count( $pieces ) && count( $against )
2629 && $pieces[0] == $against[0] ) {
2630 array_shift( $pieces );
2631 array_shift( $against );
2634 // relative dots to bump us to the parent
2635 while( count( $against ) ) {
2636 array_unshift( $pieces, '..' );
2637 array_shift( $against );
2640 array_push( $pieces, wfBaseName( $path ) );
2642 return implode( DIRECTORY_SEPARATOR, $pieces );
2646 * Backwards array plus for people who haven't bothered to read the PHP manual
2647 * XXX: will not darn your socks for you.
2649 * @param $array1 Array
2650 * @param [$array2, [...]] Arrays
2651 * @return Array
2653 function wfArrayMerge( $array1/* ... */ ) {
2654 $args = func_get_args();
2655 $args = array_reverse( $args, true );
2656 $out = array();
2657 foreach ( $args as $arg ) {
2658 $out += $arg;
2660 return $out;
2664 * Merge arrays in the style of getUserPermissionsErrors, with duplicate removal
2665 * e.g.
2666 * wfMergeErrorArrays(
2667 * array( array( 'x' ) ),
2668 * array( array( 'x', '2' ) ),
2669 * array( array( 'x' ) ),
2670 * array( array( 'y') )
2671 * );
2672 * returns:
2673 * array(
2674 * array( 'x', '2' ),
2675 * array( 'x' ),
2676 * array( 'y' )
2679 function wfMergeErrorArrays( /*...*/ ) {
2680 $args = func_get_args();
2681 $out = array();
2682 foreach ( $args as $errors ) {
2683 foreach ( $errors as $params ) {
2684 # FIXME: sometimes get nested arrays for $params,
2685 # which leads to E_NOTICEs
2686 $spec = implode( "\t", $params );
2687 $out[$spec] = $params;
2690 return array_values( $out );
2694 * parse_url() work-alike, but non-broken. Differences:
2696 * 1) Does not raise warnings on bad URLs (just returns false)
2697 * 2) Handles protocols that don't use :// (e.g., mailto: and news:) correctly
2698 * 3) Adds a "delimiter" element to the array, either '://' or ':' (see (2))
2700 * @param $url String: a URL to parse
2701 * @return Array: bits of the URL in an associative array, per PHP docs
2703 function wfParseUrl( $url ) {
2704 global $wgUrlProtocols; // Allow all protocols defined in DefaultSettings/LocalSettings.php
2705 wfSuppressWarnings();
2706 $bits = parse_url( $url );
2707 wfRestoreWarnings();
2708 if ( !$bits ) {
2709 return false;
2712 // most of the protocols are followed by ://, but mailto: and sometimes news: not, check for it
2713 if ( in_array( $bits['scheme'] . '://', $wgUrlProtocols ) ) {
2714 $bits['delimiter'] = '://';
2715 } elseif ( in_array( $bits['scheme'] . ':', $wgUrlProtocols ) ) {
2716 $bits['delimiter'] = ':';
2717 // parse_url detects for news: and mailto: the host part of an url as path
2718 // We have to correct this wrong detection
2719 if ( isset( $bits['path'] ) ) {
2720 $bits['host'] = $bits['path'];
2721 $bits['path'] = '';
2723 } else {
2724 return false;
2727 return $bits;
2731 * Make a URL index, appropriate for the el_index field of externallinks.
2733 function wfMakeUrlIndex( $url ) {
2734 $bits = wfParseUrl( $url );
2736 // Reverse the labels in the hostname, convert to lower case
2737 // For emails reverse domainpart only
2738 if ( $bits['scheme'] == 'mailto' ) {
2739 $mailparts = explode( '@', $bits['host'], 2 );
2740 if ( count( $mailparts ) === 2 ) {
2741 $domainpart = strtolower( implode( '.', array_reverse( explode( '.', $mailparts[1] ) ) ) );
2742 } else {
2743 // No domain specified, don't mangle it
2744 $domainpart = '';
2746 $reversedHost = $domainpart . '@' . $mailparts[0];
2747 } else {
2748 $reversedHost = strtolower( implode( '.', array_reverse( explode( '.', $bits['host'] ) ) ) );
2750 // Add an extra dot to the end
2751 // Why? Is it in wrong place in mailto links?
2752 if ( substr( $reversedHost, -1, 1 ) !== '.' ) {
2753 $reversedHost .= '.';
2755 // Reconstruct the pseudo-URL
2756 $prot = $bits['scheme'];
2757 $index = $prot . $bits['delimiter'] . $reversedHost;
2758 // Leave out user and password. Add the port, path, query and fragment
2759 if ( isset( $bits['port'] ) ) {
2760 $index .= ':' . $bits['port'];
2762 if ( isset( $bits['path'] ) ) {
2763 $index .= $bits['path'];
2764 } else {
2765 $index .= '/';
2767 if ( isset( $bits['query'] ) ) {
2768 $index .= '?' . $bits['query'];
2770 if ( isset( $bits['fragment'] ) ) {
2771 $index .= '#' . $bits['fragment'];
2773 return $index;
2777 * Do any deferred updates and clear the list
2778 * TODO: This could be in Wiki.php if that class made any sense at all
2780 function wfDoUpdates() {
2781 global $wgPostCommitUpdateList, $wgDeferredUpdateList;
2782 foreach ( $wgDeferredUpdateList as $update ) {
2783 $update->doUpdate();
2785 foreach ( $wgPostCommitUpdateList as $update ) {
2786 $update->doUpdate();
2788 $wgDeferredUpdateList = array();
2789 $wgPostCommitUpdateList = array();
2793 * Convert an arbitrarily-long digit string from one numeric base
2794 * to another, optionally zero-padding to a minimum column width.
2796 * Supports base 2 through 36; digit values 10-36 are represented
2797 * as lowercase letters a-z. Input is case-insensitive.
2799 * @param $input String: of digits
2800 * @param $sourceBase Integer: 2-36
2801 * @param $destBase Integer: 2-36
2802 * @param $pad Integer: 1 or greater
2803 * @param $lowercase Boolean
2804 * @return String or false on invalid input
2806 function wfBaseConvert( $input, $sourceBase, $destBase, $pad = 1, $lowercase = true ) {
2807 $input = strval( $input );
2808 if( $sourceBase < 2 ||
2809 $sourceBase > 36 ||
2810 $destBase < 2 ||
2811 $destBase > 36 ||
2812 $pad < 1 ||
2813 $sourceBase != intval( $sourceBase ) ||
2814 $destBase != intval( $destBase ) ||
2815 $pad != intval( $pad ) ||
2816 !is_string( $input ) ||
2817 $input == '' ) {
2818 return false;
2820 $digitChars = ( $lowercase ) ? '0123456789abcdefghijklmnopqrstuvwxyz' : '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
2821 $inDigits = array();
2822 $outChars = '';
2824 // Decode and validate input string
2825 $input = strtolower( $input );
2826 for( $i = 0; $i < strlen( $input ); $i++ ) {
2827 $n = strpos( $digitChars, $input{$i} );
2828 if( $n === false || $n > $sourceBase ) {
2829 return false;
2831 $inDigits[] = $n;
2834 // Iterate over the input, modulo-ing out an output digit
2835 // at a time until input is gone.
2836 while( count( $inDigits ) ) {
2837 $work = 0;
2838 $workDigits = array();
2840 // Long division...
2841 foreach( $inDigits as $digit ) {
2842 $work *= $sourceBase;
2843 $work += $digit;
2845 if( $work < $destBase ) {
2846 // Gonna need to pull another digit.
2847 if( count( $workDigits ) ) {
2848 // Avoid zero-padding; this lets us find
2849 // the end of the input very easily when
2850 // length drops to zero.
2851 $workDigits[] = 0;
2853 } else {
2854 // Finally! Actual division!
2855 $workDigits[] = intval( $work / $destBase );
2857 // Isn't it annoying that most programming languages
2858 // don't have a single divide-and-remainder operator,
2859 // even though the CPU implements it that way?
2860 $work = $work % $destBase;
2864 // All that division leaves us with a remainder,
2865 // which is conveniently our next output digit.
2866 $outChars .= $digitChars[$work];
2868 // And we continue!
2869 $inDigits = $workDigits;
2872 while( strlen( $outChars ) < $pad ) {
2873 $outChars .= '0';
2876 return strrev( $outChars );
2880 * Create an object with a given name and an array of construct parameters
2881 * @param $name String
2882 * @param $p Array: parameters
2884 function wfCreateObject( $name, $p ) {
2885 $p = array_values( $p );
2886 switch ( count( $p ) ) {
2887 case 0:
2888 return new $name;
2889 case 1:
2890 return new $name( $p[0] );
2891 case 2:
2892 return new $name( $p[0], $p[1] );
2893 case 3:
2894 return new $name( $p[0], $p[1], $p[2] );
2895 case 4:
2896 return new $name( $p[0], $p[1], $p[2], $p[3] );
2897 case 5:
2898 return new $name( $p[0], $p[1], $p[2], $p[3], $p[4] );
2899 case 6:
2900 return new $name( $p[0], $p[1], $p[2], $p[3], $p[4], $p[5] );
2901 default:
2902 throw new MWException( 'Too many arguments to construtor in wfCreateObject' );
2906 function wfHttpOnlySafe() {
2907 global $wgHttpOnlyBlacklist;
2908 if( !version_compare( '5.2', PHP_VERSION, '<' ) ) {
2909 return false;
2912 if( isset( $_SERVER['HTTP_USER_AGENT'] ) ) {
2913 foreach( $wgHttpOnlyBlacklist as $regex ) {
2914 if( preg_match( $regex, $_SERVER['HTTP_USER_AGENT'] ) ) {
2915 return false;
2920 return true;
2924 * Initialise php session
2926 function wfSetupSession( $sessionId = false ) {
2927 global $wgSessionsInMemcached, $wgCookiePath, $wgCookieDomain,
2928 $wgCookieSecure, $wgCookieHttpOnly, $wgSessionHandler;
2929 if( $wgSessionsInMemcached ) {
2930 require_once( 'MemcachedSessions.php' );
2931 } elseif( $wgSessionHandler && $wgSessionHandler != ini_get( 'session.save_handler' ) ) {
2932 # Only set this if $wgSessionHandler isn't null and session.save_handler
2933 # hasn't already been set to the desired value (that causes errors)
2934 ini_set( 'session.save_handler', $wgSessionHandler );
2936 $httpOnlySafe = wfHttpOnlySafe();
2937 wfDebugLog( 'cookie',
2938 'session_set_cookie_params: "' . implode( '", "',
2939 array(
2941 $wgCookiePath,
2942 $wgCookieDomain,
2943 $wgCookieSecure,
2944 $httpOnlySafe && $wgCookieHttpOnly ) ) . '"' );
2945 if( $httpOnlySafe && $wgCookieHttpOnly ) {
2946 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookieHttpOnly );
2947 } else {
2948 // PHP 5.1 throws warnings if you pass the HttpOnly parameter for 5.2.
2949 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
2951 session_cache_limiter( 'private, must-revalidate' );
2952 if ( $sessionId ) {
2953 session_id( $sessionId );
2955 wfSuppressWarnings();
2956 session_start();
2957 wfRestoreWarnings();
2961 * Get an object from the precompiled serialized directory
2963 * @return Mixed: the variable on success, false on failure
2965 function wfGetPrecompiledData( $name ) {
2966 global $IP;
2968 $file = "$IP/serialized/$name";
2969 if ( file_exists( $file ) ) {
2970 $blob = file_get_contents( $file );
2971 if ( $blob ) {
2972 return unserialize( $blob );
2975 return false;
2978 function wfGetCaller( $level = 2 ) {
2979 $backtrace = wfDebugBacktrace();
2980 if ( isset( $backtrace[$level] ) ) {
2981 return wfFormatStackFrame( $backtrace[$level] );
2982 } else {
2983 $caller = 'unknown';
2985 return $caller;
2989 * Return a string consisting of callers in the stack. Useful sometimes
2990 * for profiling specific points.
2992 * @param $limit The maximum depth of the stack frame to return, or false for
2993 * the entire stack.
2995 function wfGetAllCallers( $limit = 3 ) {
2996 $trace = array_reverse( wfDebugBacktrace() );
2997 if ( !$limit || $limit > count( $trace ) - 1 ) {
2998 $limit = count( $trace ) - 1;
3000 $trace = array_slice( $trace, -$limit - 1, $limit );
3001 return implode( '/', array_map( 'wfFormatStackFrame', $trace ) );
3005 * Return a string representation of frame
3007 function wfFormatStackFrame( $frame ) {
3008 return isset( $frame['class'] ) ?
3009 $frame['class'] . '::' . $frame['function'] :
3010 $frame['function'];
3014 * Get a cache key
3016 function wfMemcKey( /*... */ ) {
3017 $args = func_get_args();
3018 $key = wfWikiID() . ':' . implode( ':', $args );
3019 $key = str_replace( ' ', '_', $key );
3020 return $key;
3024 * Get a cache key for a foreign DB
3026 function wfForeignMemcKey( $db, $prefix /*, ... */ ) {
3027 $args = array_slice( func_get_args(), 2 );
3028 if ( $prefix ) {
3029 $key = "$db-$prefix:" . implode( ':', $args );
3030 } else {
3031 $key = $db . ':' . implode( ':', $args );
3033 return $key;
3037 * Get an ASCII string identifying this wiki
3038 * This is used as a prefix in memcached keys
3040 function wfWikiID() {
3041 global $wgDBprefix, $wgDBname;
3042 if ( $wgDBprefix ) {
3043 return "$wgDBname-$wgDBprefix";
3044 } else {
3045 return $wgDBname;
3050 * Split a wiki ID into DB name and table prefix
3052 function wfSplitWikiID( $wiki ) {
3053 $bits = explode( '-', $wiki, 2 );
3054 if ( count( $bits ) < 2 ) {
3055 $bits[] = '';
3057 return $bits;
3061 * Get a Database object.
3062 * @param $db Integer: index of the connection to get. May be DB_MASTER for the
3063 * master (for write queries), DB_SLAVE for potentially lagged read
3064 * queries, or an integer >= 0 for a particular server.
3066 * @param $groups Mixed: query groups. An array of group names that this query
3067 * belongs to. May contain a single string if the query is only
3068 * in one group.
3070 * @param $wiki String: the wiki ID, or false for the current wiki
3072 * Note: multiple calls to wfGetDB(DB_SLAVE) during the course of one request
3073 * will always return the same object, unless the underlying connection or load
3074 * balancer is manually destroyed.
3076 * @return DatabaseBase
3078 function &wfGetDB( $db, $groups = array(), $wiki = false ) {
3079 return wfGetLB( $wiki )->getConnection( $db, $groups, $wiki );
3083 * Get a load balancer object.
3085 * @param $wiki String: wiki ID, or false for the current wiki
3086 * @return LoadBalancer
3088 function wfGetLB( $wiki = false ) {
3089 return wfGetLBFactory()->getMainLB( $wiki );
3093 * Get the load balancer factory object
3095 function &wfGetLBFactory() {
3096 return LBFactory::singleton();
3100 * Find a file.
3101 * Shortcut for RepoGroup::singleton()->findFile()
3102 * @param $title String or Title object
3103 * @param $options Associative array of options:
3104 * time: requested time for an archived image, or false for the
3105 * current version. An image object will be returned which was
3106 * created at the specified time.
3108 * ignoreRedirect: If true, do not follow file redirects
3110 * private: If true, return restricted (deleted) files if the current
3111 * user is allowed to view them. Otherwise, such files will not
3112 * be found.
3114 * bypassCache: If true, do not use the process-local cache of File objects
3116 * @return File, or false if the file does not exist
3118 function wfFindFile( $title, $options = array() ) {
3119 return RepoGroup::singleton()->findFile( $title, $options );
3123 * Get an object referring to a locally registered file.
3124 * Returns a valid placeholder object if the file does not exist.
3125 * @param $title Either a string or Title object
3126 * @return File, or null if passed an invalid Title
3128 function wfLocalFile( $title ) {
3129 return RepoGroup::singleton()->getLocalRepo()->newFile( $title );
3133 * Should low-performance queries be disabled?
3135 * @return Boolean
3137 function wfQueriesMustScale() {
3138 global $wgMiserMode;
3139 return $wgMiserMode
3140 || ( SiteStats::pages() > 100000
3141 && SiteStats::edits() > 1000000
3142 && SiteStats::users() > 10000 );
3146 * Get the path to a specified script file, respecting file
3147 * extensions; this is a wrapper around $wgScriptExtension etc.
3149 * @param $script String: script filename, sans extension
3150 * @return String
3152 function wfScript( $script = 'index' ) {
3153 global $wgScriptPath, $wgScriptExtension;
3154 return "{$wgScriptPath}/{$script}{$wgScriptExtension}";
3158 * Get the script URL.
3160 * @return script URL
3162 function wfGetScriptUrl() {
3163 if( isset( $_SERVER['SCRIPT_NAME'] ) ) {
3165 # as it was called, minus the query string.
3167 # Some sites use Apache rewrite rules to handle subdomains,
3168 # and have PHP set up in a weird way that causes PHP_SELF
3169 # to contain the rewritten URL instead of the one that the
3170 # outside world sees.
3172 # If in this mode, use SCRIPT_URL instead, which mod_rewrite
3173 # provides containing the "before" URL.
3174 return $_SERVER['SCRIPT_NAME'];
3175 } else {
3176 return $_SERVER['URL'];
3181 * Convenience function converts boolean values into "true"
3182 * or "false" (string) values
3184 * @param $value Boolean
3185 * @return String
3187 function wfBoolToStr( $value ) {
3188 return $value ? 'true' : 'false';
3192 * Load an extension messages file
3193 * @deprecated in 1.16 (warnings in 1.18, removed in ?)
3195 function wfLoadExtensionMessages( $extensionName, $langcode = false ) {
3199 * Get a platform-independent path to the null file, e.g.
3200 * /dev/null
3202 * @return string
3204 function wfGetNull() {
3205 return wfIsWindows()
3206 ? 'NUL'
3207 : '/dev/null';
3211 * Displays a maxlag error
3213 * @param $host String: server that lags the most
3214 * @param $lag Integer: maxlag (actual)
3215 * @param $maxLag Integer: maxlag (requested)
3217 function wfMaxlagError( $host, $lag, $maxLag ) {
3218 global $wgShowHostnames;
3219 header( 'HTTP/1.1 503 Service Unavailable' );
3220 header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
3221 header( 'X-Database-Lag: ' . intval( $lag ) );
3222 header( 'Content-Type: text/plain' );
3223 if( $wgShowHostnames ) {
3224 echo "Waiting for $host: $lag seconds lagged\n";
3225 } else {
3226 echo "Waiting for a database server: $lag seconds lagged\n";
3231 * Throws a warning that $function is deprecated
3232 * @param $function String
3233 * @return null
3235 function wfDeprecated( $function ) {
3236 static $functionsWarned = array();
3237 if ( !isset( $functionsWarned[$function] ) ) {
3238 $functionsWarned[$function] = true;
3239 wfWarn( "Use of $function is deprecated.", 2 );
3244 * Send a warning either to the debug log or in a PHP error depending on
3245 * $wgDevelopmentWarnings
3247 * @param $msg String: message to send
3248 * @param $callerOffset Integer: number of itmes to go back in the backtrace to
3249 * find the correct caller (1 = function calling wfWarn, ...)
3250 * @param $level Integer: PHP error level; only used when $wgDevelopmentWarnings
3251 * is true
3253 function wfWarn( $msg, $callerOffset = 1, $level = E_USER_NOTICE ) {
3254 $callers = wfDebugBacktrace();
3255 if( isset( $callers[$callerOffset + 1] ) ){
3256 $callerfunc = $callers[$callerOffset + 1];
3257 $callerfile = $callers[$callerOffset];
3258 if( isset( $callerfile['file'] ) && isset( $callerfile['line'] ) ) {
3259 $file = $callerfile['file'] . ' at line ' . $callerfile['line'];
3260 } else {
3261 $file = '(internal function)';
3263 $func = '';
3264 if( isset( $callerfunc['class'] ) ) {
3265 $func .= $callerfunc['class'] . '::';
3267 $func .= @$callerfunc['function'];
3268 $msg .= " [Called from $func in $file]";
3271 global $wgDevelopmentWarnings;
3272 if ( $wgDevelopmentWarnings ) {
3273 trigger_error( $msg, $level );
3274 } else {
3275 wfDebug( "$msg\n" );
3280 * Sleep until the worst slave's replication lag is less than or equal to
3281 * $maxLag, in seconds. Use this when updating very large numbers of rows, as
3282 * in maintenance scripts, to avoid causing too much lag. Of course, this is
3283 * a no-op if there are no slaves.
3285 * Every time the function has to wait for a slave, it will print a message to
3286 * that effect (and then sleep for a little while), so it's probably not best
3287 * to use this outside maintenance scripts in its present form.
3289 * @param $maxLag Integer
3290 * @param $wiki mixed Wiki identifier accepted by wfGetLB
3291 * @return null
3293 function wfWaitForSlaves( $maxLag, $wiki = false ) {
3294 if( $maxLag ) {
3295 $lb = wfGetLB( $wiki );
3296 list( $host, $lag ) = $lb->getMaxLag( $wiki );
3297 while( $lag > $maxLag ) {
3298 $name = @gethostbyaddr( $host );
3299 if( $name !== false ) {
3300 $host = $name;
3302 print "Waiting for $host (lagged $lag seconds)...\n";
3303 sleep( $maxLag );
3304 list( $host, $lag ) = $lb->getMaxLag();
3310 * Output some plain text in command-line mode or in the installer (updaters.inc).
3311 * Do not use it in any other context, its behaviour is subject to change.
3313 function wfOut( $s ) {
3314 global $wgCommandLineMode;
3315 if ( $wgCommandLineMode && !defined( 'MEDIAWIKI_INSTALL' ) ) {
3316 echo $s;
3317 } else {
3318 echo htmlspecialchars( $s );
3320 flush();
3324 * Count down from $n to zero on the terminal, with a one-second pause
3325 * between showing each number. For use in command-line scripts.
3327 function wfCountDown( $n ) {
3328 for ( $i = $n; $i >= 0; $i-- ) {
3329 if ( $i != $n ) {
3330 echo str_repeat( "\x08", strlen( $i + 1 ) );
3332 echo $i;
3333 flush();
3334 if ( $i ) {
3335 sleep( 1 );
3338 echo "\n";
3342 * Generate a random 32-character hexadecimal token.
3343 * @param $salt Mixed: some sort of salt, if necessary, to add to random
3344 * characters before hashing.
3346 function wfGenerateToken( $salt = '' ) {
3347 $salt = serialize( $salt );
3348 return md5( mt_rand( 0, 0x7fffffff ) . $salt );
3352 * Replace all invalid characters with -
3353 * @param $name Mixed: filename to process
3355 function wfStripIllegalFilenameChars( $name ) {
3356 global $wgIllegalFileChars;
3357 $name = wfBaseName( $name );
3358 $name = preg_replace(
3359 "/[^" . Title::legalChars() . "]" .
3360 ( $wgIllegalFileChars ? "|[" . $wgIllegalFileChars . "]" : '' ) .
3361 "/",
3362 '-',
3363 $name
3365 return $name;
3369 * Insert array into another array after the specified *KEY*
3370 * @param $array Array: The array.
3371 * @param $insert Array: The array to insert.
3372 * @param $after Mixed: The key to insert after
3374 function wfArrayInsertAfter( $array, $insert, $after ) {
3375 // Find the offset of the element to insert after.
3376 $keys = array_keys( $array );
3377 $offsetByKey = array_flip( $keys );
3379 $offset = $offsetByKey[$after];
3381 // Insert at the specified offset
3382 $before = array_slice( $array, 0, $offset + 1, true );
3383 $after = array_slice( $array, $offset + 1, count( $array ) - $offset, true );
3385 $output = $before + $insert + $after;
3387 return $output;
3390 /* Recursively converts the parameter (an object) to an array with the same data */
3391 function wfObjectToArray( $object, $recursive = true ) {
3392 $array = array();
3393 foreach ( get_object_vars( $object ) as $key => $value ) {
3394 if ( is_object( $value ) && $recursive ) {
3395 $value = wfObjectToArray( $value );
3398 $array[$key] = $value;
3401 return $array;
3405 * Set PHP's memory limit to the larger of php.ini or $wgMemoryLimit;
3406 * @return Integer value memory was set to.
3408 function wfMemoryLimit() {
3409 global $wgMemoryLimit;
3410 $memlimit = wfShorthandToInteger( ini_get( 'memory_limit' ) );
3411 $conflimit = wfShorthandToInteger( $wgMemoryLimit );
3412 if( $memlimit != -1 ) {
3413 if( $conflimit == -1 ) {
3414 wfDebug( "Removing PHP's memory limit\n" );
3415 wfSuppressWarnings();
3416 ini_set( 'memory_limit', $conflimit );
3417 wfRestoreWarnings();
3418 return $conflimit;
3419 } elseif ( $conflimit > $memlimit ) {
3420 wfDebug( "Raising PHP's memory limit to $conflimit bytes\n" );
3421 wfSuppressWarnings();
3422 ini_set( 'memory_limit', $conflimit );
3423 wfRestoreWarnings();
3424 return $conflimit;
3427 return $memlimit;
3431 * Converts shorthand byte notation to integer form
3432 * @param $string String
3433 * @return Integer
3435 function wfShorthandToInteger( $string = '' ) {
3436 $string = trim( $string );
3437 if( empty( $string ) ) {
3438 return -1;
3440 $last = strtolower( $string[strlen( $string ) - 1] );
3441 $val = intval( $string );
3442 switch( $last ) {
3443 case 'g':
3444 $val *= 1024;
3445 case 'm':
3446 $val *= 1024;
3447 case 'k':
3448 $val *= 1024;
3451 return $val;
3455 * Get the normalised IETF language tag
3456 * @param $code String: The language code.
3457 * @return $langCode String: The language code which complying with BCP 47 standards.
3459 function wfBCP47( $code ) {
3460 $codeSegment = explode( '-', $code );
3461 foreach ( $codeSegment as $segNo => $seg ) {
3462 if ( count( $codeSegment ) > 0 ) {
3463 // ISO 3166 country code
3464 if ( ( strlen( $seg ) == 2 ) && ( $segNo > 0 ) ) {
3465 $codeBCP[$segNo] = strtoupper( $seg );
3466 // ISO 15924 script code
3467 } elseif ( ( strlen( $seg ) == 4 ) && ( $segNo > 0 ) ) {
3468 $codeBCP[$segNo] = ucfirst( $seg );
3469 // Use lowercase for other cases
3470 } else {
3471 $codeBCP[$segNo] = strtolower( $seg );
3473 } else {
3474 // Use lowercase for single segment
3475 $codeBCP[$segNo] = strtolower( $seg );
3478 $langCode = implode( '-', $codeBCP );
3479 return $langCode;
3482 function wfArrayMap( $function, $input ) {
3483 $ret = array_map( $function, $input );
3484 foreach ( $ret as $key => $value ) {
3485 $taint = istainted( $input[$key] );
3486 if ( $taint ) {
3487 taint( $ret[$key], $taint );
3490 return $ret;
3494 * Returns the PackageRepository object for interaction with the package repository.
3496 * TODO: Make the repository type also configurable.
3498 * @since 1.17
3500 * @return PackageRepository
3502 function wfGetRepository() {
3503 global $wgRepositoryApiLocation;
3504 static $repository = false;
3506 if ( $repository === false ) {
3507 $repository = new DistributionRepository( $wgRepositoryApiLocation );
3510 return $repository;