Use of undefined constant h in line 250. Follow up to r81558
[mediawiki.git] / includes / GlobalFunctions.php
blob71847cc0d36a0ed5b27283792f5e18a4a6d713d2
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 support PHP 5.1.x and up.
20 * Re-implementations of newer functions or functions in non-standard
21 * PHP extensions may be included here.
24 if( !function_exists( 'iconv' ) ) {
25 /** @codeCoverageIgnore */
26 function iconv( $from, $to, $string ) {
27 return Fallback::iconv( $from, $to, $string );
31 if ( !function_exists( 'mb_substr' ) ) {
32 /** @codeCoverageIgnore */
33 function mb_substr( $str, $start, $count='end' ) {
34 return Fallback::mb_substr( $str, $start, $count );
37 /** @codeCoverageIgnore */
38 function mb_substr_split_unicode( $str, $splitPos ) {
39 return Fallback::mb_substr_split_unicode( $str, $splitPos );
43 if ( !function_exists( 'mb_strlen' ) ) {
44 /** @codeCoverageIgnore */
45 function mb_strlen( $str, $enc = '' ) {
46 return Fallback::mb_strlen( $str, $enc );
50 if( !function_exists( 'mb_strpos' ) ) {
51 /** @codeCoverageIgnore */
52 function mb_strpos( $haystack, $needle, $offset = 0, $encoding = '' ) {
53 return Fallback::mb_strpos( $haystack, $needle, $offset, $encoding );
58 if( !function_exists( 'mb_strrpos' ) ) {
59 /** @codeCoverageIgnore */
60 function mb_strrpos( $haystack, $needle, $offset = 0, $encoding = '' ) {
61 return Fallback::mb_strrpos( $haystack, $needle, $offset, $encoding );
66 // Support for Wietse Venema's taint feature
67 if ( !function_exists( 'istainted' ) ) {
68 /** @codeCoverageIgnore */
69 function istainted( $var ) {
70 return 0;
72 /** @codeCoverageIgnore */
73 function taint( $var, $level = 0 ) {}
74 /** @codeCoverageIgnore */
75 function untaint( $var, $level = 0 ) {}
76 define( 'TC_HTML', 1 );
77 define( 'TC_SHELL', 1 );
78 define( 'TC_MYSQL', 1 );
79 define( 'TC_PCRE', 1 );
80 define( 'TC_SELF', 1 );
82 /// @endcond
84 /**
85 * Like array_diff( $a, $b ) except that it works with two-dimensional arrays.
87 function wfArrayDiff2( $a, $b ) {
88 return array_udiff( $a, $b, 'wfArrayDiff2_cmp' );
90 function wfArrayDiff2_cmp( $a, $b ) {
91 if ( !is_array( $a ) ) {
92 return strcmp( $a, $b );
93 } elseif ( count( $a ) !== count( $b ) ) {
94 return count( $a ) < count( $b ) ? -1 : 1;
95 } else {
96 reset( $a );
97 reset( $b );
98 while( ( list( , $valueA ) = each( $a ) ) && ( list( , $valueB ) = each( $b ) ) ) {
99 $cmp = strcmp( $valueA, $valueB );
100 if ( $cmp !== 0 ) {
101 return $cmp;
104 return 0;
109 * Get a random decimal value between 0 and 1, in a way
110 * not likely to give duplicate values for any realistic
111 * number of articles.
113 * @return string
115 function wfRandom() {
116 # The maximum random value is "only" 2^31-1, so get two random
117 # values to reduce the chance of dupes
118 $max = mt_getrandmax() + 1;
119 $rand = number_format( ( mt_rand() * $max + mt_rand() )
120 / $max / $max, 12, '.', '' );
121 return $rand;
125 * We want some things to be included as literal characters in our title URLs
126 * for prettiness, which urlencode encodes by default. According to RFC 1738,
127 * all of the following should be safe:
129 * ;:@&=$-_.+!*'(),
131 * But + is not safe because it's used to indicate a space; &= are only safe in
132 * paths and not in queries (and we don't distinguish here); ' seems kind of
133 * scary; and urlencode() doesn't touch -_. to begin with. Plus, although /
134 * is reserved, we don't care. So the list we unescape is:
136 * ;:@$!*(),/
138 * However, IIS7 redirects fail when the url contains a colon (Bug 22709),
139 * so no fancy : for IIS7.
141 * %2F in the page titles seems to fatally break for some reason.
143 * @param $s String:
144 * @return string
146 function wfUrlencode( $s ) {
147 static $needle;
148 if ( is_null( $needle ) ) {
149 $needle = array( '%3B', '%40', '%24', '%21', '%2A', '%28', '%29', '%2C', '%2F' );
150 if ( !isset( $_SERVER['SERVER_SOFTWARE'] ) || ( strpos( $_SERVER['SERVER_SOFTWARE'], 'Microsoft-IIS/7' ) === false ) ) {
151 $needle[] = '%3A';
155 $s = urlencode( $s );
156 $s = str_ireplace(
157 $needle,
158 array( ';', '@', '$', '!', '*', '(', ')', ',', '/', ':' ),
162 return $s;
166 * Sends a line to the debug log if enabled or, optionally, to a comment in output.
167 * In normal operation this is a NOP.
169 * Controlling globals:
170 * $wgDebugLogFile - points to the log file
171 * $wgProfileOnly - if set, normal debug messages will not be recorded.
172 * $wgDebugRawPage - if false, 'action=raw' hits will not result in debug output.
173 * $wgDebugComments - if on, some debug items may appear in comments in the HTML output.
175 * @param $text String
176 * @param $logonly Bool: set true to avoid appearing in HTML when $wgDebugComments is set
178 function wfDebug( $text, $logonly = false ) {
179 global $wgOut, $wgDebugLogFile, $wgDebugComments, $wgProfileOnly, $wgDebugRawPage;
180 global $wgDebugLogPrefix, $wgShowDebug;
182 static $cache = array(); // Cache of unoutputted messages
183 $text = wfDebugTimer() . $text;
185 # Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
186 if ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' && !$wgDebugRawPage ) {
187 return;
190 if ( ( $wgDebugComments || $wgShowDebug ) && !$logonly ) {
191 $cache[] = $text;
193 if ( isset( $wgOut ) && StubObject::isRealObject( $wgOut ) ) {
194 // add the message and any cached messages to the output
195 array_map( array( $wgOut, 'debug' ), $cache );
196 $cache = array();
199 if ( $wgDebugLogFile != '' && !$wgProfileOnly ) {
200 # Strip unprintables; they can switch terminal modes when binary data
201 # gets dumped, which is pretty annoying.
202 $text = preg_replace( '![\x00-\x08\x0b\x0c\x0e-\x1f]!', ' ', $text );
203 $text = $wgDebugLogPrefix . $text;
204 wfErrorLog( $text, $wgDebugLogFile );
208 function wfDebugTimer() {
209 global $wgDebugTimestamps;
210 if ( !$wgDebugTimestamps ) {
211 return '';
213 static $start = null;
215 if ( $start === null ) {
216 $start = microtime( true );
217 $prefix = "\n$start";
218 } else {
219 $prefix = sprintf( "%6.4f", microtime( true ) - $start );
222 return $prefix . ' ';
226 * Send a line giving PHP memory usage.
227 * @param $exact Bool: print exact values instead of kilobytes (default: false)
229 function wfDebugMem( $exact = false ) {
230 $mem = memory_get_usage();
231 if( !$exact ) {
232 $mem = floor( $mem / 1024 ) . ' kilobytes';
233 } else {
234 $mem .= ' bytes';
236 wfDebug( "Memory usage: $mem\n" );
240 * Send a line to a supplementary debug log file, if configured, or main debug log if not.
241 * $wgDebugLogGroups[$logGroup] should be set to a filename to send to a separate log.
243 * @param $logGroup String
244 * @param $text String
245 * @param $public Bool: whether to log the event in the public log if no private
246 * log file is specified, (default true)
248 function wfDebugLog( $logGroup, $text, $public = true ) {
249 global $wgDebugLogGroups, $wgShowHostnames;
250 $text = trim( $text ) . "\n";
251 if( isset( $wgDebugLogGroups[$logGroup] ) ) {
252 $time = wfTimestamp( TS_DB );
253 $wiki = wfWikiID();
254 if ( $wgShowHostnames ) {
255 $host = wfHostname();
256 } else {
257 $host = '';
259 wfErrorLog( "$time $host $wiki: $text", $wgDebugLogGroups[$logGroup] );
260 } elseif ( $public === true ) {
261 wfDebug( $text, true );
266 * Log for database errors
267 * @param $text String: database error message.
269 function wfLogDBError( $text ) {
270 global $wgDBerrorLog, $wgDBname;
271 if ( $wgDBerrorLog ) {
272 $host = trim(`hostname`);
273 $text = date( 'D M j G:i:s T Y' ) . "\t$host\t$wgDBname\t$text";
274 wfErrorLog( $text, $wgDBerrorLog );
279 * Log to a file without getting "file size exceeded" signals.
281 * Can also log to TCP or UDP with the syntax udp://host:port/prefix. This will
282 * send lines to the specified port, prefixed by the specified prefix and a space.
284 function wfErrorLog( $text, $file ) {
285 if ( substr( $file, 0, 4 ) == 'udp:' ) {
286 # Needs the sockets extension
287 if ( preg_match( '!^(tcp|udp):(?://)?\[([0-9a-fA-F:]+)\]:(\d+)(?:/(.*))?$!', $file, $m ) ) {
288 // IPv6 bracketed host
289 $host = $m[2];
290 $port = intval( $m[3] );
291 $prefix = isset( $m[4] ) ? $m[4] : false;
292 $domain = AF_INET6;
293 } elseif ( preg_match( '!^(tcp|udp):(?://)?([a-zA-Z0-9.-]+):(\d+)(?:/(.*))?$!', $file, $m ) ) {
294 $host = $m[2];
295 if ( !IP::isIPv4( $host ) ) {
296 $host = gethostbyname( $host );
298 $port = intval( $m[3] );
299 $prefix = isset( $m[4] ) ? $m[4] : false;
300 $domain = AF_INET;
301 } else {
302 throw new MWException( __METHOD__ . ': Invalid UDP specification' );
305 // Clean it up for the multiplexer
306 if ( strval( $prefix ) !== '' ) {
307 $text = preg_replace( '/^/m', $prefix . ' ', $text );
309 // Limit to 64KB
310 if ( strlen( $text ) > 65534 ) {
311 $text = substr( $text, 0, 65534 );
314 if ( substr( $text, -1 ) != "\n" ) {
315 $text .= "\n";
317 } elseif ( strlen( $text ) > 65535 ) {
318 $text = substr( $text, 0, 65535 );
321 $sock = socket_create( $domain, SOCK_DGRAM, SOL_UDP );
322 if ( !$sock ) {
323 return;
325 socket_sendto( $sock, $text, strlen( $text ), 0, $host, $port );
326 socket_close( $sock );
327 } else {
328 wfSuppressWarnings();
329 $exists = file_exists( $file );
330 $size = $exists ? filesize( $file ) : false;
331 if ( !$exists || ( $size !== false && $size + strlen( $text ) < 0x7fffffff ) ) {
332 error_log( $text, 3, $file );
334 wfRestoreWarnings();
339 * @todo document
341 function wfLogProfilingData() {
342 global $wgRequestTime, $wgDebugLogFile, $wgDebugRawPage, $wgRequest;
343 global $wgProfiler, $wgProfileLimit, $wgUser;
344 # Profiling must actually be enabled...
345 if( is_null( $wgProfiler ) ) {
346 return;
348 # Get total page request time
349 $now = wfTime();
350 $elapsed = $now - $wgRequestTime;
351 # Only show pages that longer than $wgProfileLimit time (default is 0)
352 if( $elapsed <= $wgProfileLimit ) {
353 return;
355 $prof = wfGetProfilingOutput( $wgRequestTime, $elapsed );
356 $forward = '';
357 if( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) {
358 $forward = ' forwarded for ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
360 if( !empty( $_SERVER['HTTP_CLIENT_IP'] ) ) {
361 $forward .= ' client IP ' . $_SERVER['HTTP_CLIENT_IP'];
363 if( !empty( $_SERVER['HTTP_FROM'] ) ) {
364 $forward .= ' from ' . $_SERVER['HTTP_FROM'];
366 if( $forward ) {
367 $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
369 // Don't unstub $wgUser at this late stage just for statistics purposes
370 // FIXME: We can detect some anons even if it is not loaded. See User::getId()
371 if( $wgUser->mDataLoaded && $wgUser->isAnon() ) {
372 $forward .= ' anon';
374 $log = sprintf( "%s\t%04.3f\t%s\n",
375 gmdate( 'YmdHis' ), $elapsed,
376 urldecode( $wgRequest->getRequestURL() . $forward ) );
377 if ( $wgDebugLogFile != '' && ( $wgRequest->getVal( 'action' ) != 'raw' || $wgDebugRawPage ) ) {
378 wfErrorLog( $log . $prof, $wgDebugLogFile );
383 * Check if the wiki read-only lock file is present. This can be used to lock
384 * off editing functions, but doesn't guarantee that the database will not be
385 * modified.
386 * @return bool
388 function wfReadOnly() {
389 global $wgReadOnlyFile, $wgReadOnly;
391 if ( !is_null( $wgReadOnly ) ) {
392 return (bool)$wgReadOnly;
394 if ( $wgReadOnlyFile == '' ) {
395 return false;
397 // Set $wgReadOnly for faster access next time
398 if ( is_file( $wgReadOnlyFile ) ) {
399 $wgReadOnly = file_get_contents( $wgReadOnlyFile );
400 } else {
401 $wgReadOnly = false;
403 return (bool)$wgReadOnly;
406 function wfReadOnlyReason() {
407 global $wgReadOnly;
408 wfReadOnly();
409 return $wgReadOnly;
413 * Return a Language object from $langcode
414 * @param $langcode Mixed: either:
415 * - a Language object
416 * - code of the language to get the message for, if it is
417 * a valid code create a language for that language, if
418 * it is a string but not a valid code then make a basic
419 * language object
420 * - a boolean: if it's false then use the current users
421 * language (as a fallback for the old parameter
422 * functionality), or if it is true then use the wikis
423 * @return Language object
425 function wfGetLangObj( $langcode = false ) {
426 # Identify which language to get or create a language object for.
427 # Using is_object here due to Stub objects.
428 if( is_object( $langcode ) ) {
429 # Great, we already have the object (hopefully)!
430 return $langcode;
433 global $wgContLang, $wgLanguageCode;
434 if( $langcode === true || $langcode === $wgLanguageCode ) {
435 # $langcode is the language code of the wikis content language object.
436 # or it is a boolean and value is true
437 return $wgContLang;
440 global $wgLang;
441 if( $langcode === false || $langcode === $wgLang->getCode() ) {
442 # $langcode is the language code of user language object.
443 # or it was a boolean and value is false
444 return $wgLang;
447 $validCodes = array_keys( Language::getLanguageNames() );
448 if( in_array( $langcode, $validCodes ) ) {
449 # $langcode corresponds to a valid language.
450 return Language::factory( $langcode );
453 # $langcode is a string, but not a valid language code; use content language.
454 wfDebug( "Invalid language code passed to wfGetLangObj, falling back to content language.\n" );
455 return $wgContLang;
459 * Use this instead of $wgContLang, when working with user interface.
460 * User interface is currently hard coded according to wiki content language
461 * in many ways, especially regarding to text direction. There is lots stuff
462 * to fix, hence this function to keep the old behaviour unless the global
463 * $wgBetterDirectionality is enabled (or removed when everything works).
465 function wfUILang() {
466 global $wgBetterDirectionality;
467 return wfGetLangObj( !$wgBetterDirectionality );
471 * This is the new function for getting translated interface messages.
472 * See the Message class for documentation how to use them.
473 * The intention is that this function replaces all old wfMsg* functions.
474 * @param $key \string Message key.
475 * Varargs: normal message parameters.
476 * @return \type{Message}
477 * @since 1.17
479 function wfMessage( $key /*...*/) {
480 $params = func_get_args();
481 array_shift( $params );
482 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
483 $params = $params[0];
485 return new Message( $key, $params );
489 * This function accepts multiple message keys and returns a message instance
490 * for the first message which is non-empty. If all messages are empty then an
491 * instance of the first message key is returned.
492 * Varargs: message keys
493 * @return \type{Message}
494 * @since 1.18
496 function wfMessageFallback( /*...*/ ) {
497 $args = func_get_args();
498 return call_user_func_array( array( 'Message', 'newFallbackSequence' ), $args );
502 * Get a message from anywhere, for the current user language.
504 * Use wfMsgForContent() instead if the message should NOT
505 * change depending on the user preferences.
507 * @param $key String: lookup key for the message, usually
508 * defined in languages/Language.php
510 * This function also takes extra optional parameters (not
511 * shown in the function definition), which can be used to
512 * insert variable text into the predefined message.
514 function wfMsg( $key ) {
515 $args = func_get_args();
516 array_shift( $args );
517 return wfMsgReal( $key, $args, true );
521 * Same as above except doesn't transform the message
523 function wfMsgNoTrans( $key ) {
524 $args = func_get_args();
525 array_shift( $args );
526 return wfMsgReal( $key, $args, true, false, false );
530 * Get a message from anywhere, for the current global language
531 * set with $wgLanguageCode.
533 * Use this if the message should NOT change dependent on the
534 * language set in the user's preferences. This is the case for
535 * most text written into logs, as well as link targets (such as
536 * the name of the copyright policy page). Link titles, on the
537 * other hand, should be shown in the UI language.
539 * Note that MediaWiki allows users to change the user interface
540 * language in their preferences, but a single installation
541 * typically only contains content in one language.
543 * Be wary of this distinction: If you use wfMsg() where you should
544 * use wfMsgForContent(), a user of the software may have to
545 * customize potentially hundreds of messages in
546 * order to, e.g., fix a link in every possible language.
548 * @param $key String: lookup key for the message, usually
549 * defined in languages/Language.php
551 function wfMsgForContent( $key ) {
552 global $wgForceUIMsgAsContentMsg;
553 $args = func_get_args();
554 array_shift( $args );
555 $forcontent = true;
556 if( is_array( $wgForceUIMsgAsContentMsg ) &&
557 in_array( $key, $wgForceUIMsgAsContentMsg ) )
559 $forcontent = false;
561 return wfMsgReal( $key, $args, true, $forcontent );
565 * Same as above except doesn't transform the message
567 function wfMsgForContentNoTrans( $key ) {
568 global $wgForceUIMsgAsContentMsg;
569 $args = func_get_args();
570 array_shift( $args );
571 $forcontent = true;
572 if( is_array( $wgForceUIMsgAsContentMsg ) &&
573 in_array( $key, $wgForceUIMsgAsContentMsg ) )
575 $forcontent = false;
577 return wfMsgReal( $key, $args, true, $forcontent, false );
581 * Get a message from the language file, for the UI elements
583 function wfMsgNoDB( $key ) {
584 $args = func_get_args();
585 array_shift( $args );
586 return wfMsgReal( $key, $args, false );
590 * Get a message from the language file, for the content
592 function wfMsgNoDBForContent( $key ) {
593 global $wgForceUIMsgAsContentMsg;
594 $args = func_get_args();
595 array_shift( $args );
596 $forcontent = true;
597 if( is_array( $wgForceUIMsgAsContentMsg ) &&
598 in_array( $key, $wgForceUIMsgAsContentMsg ) )
600 $forcontent = false;
602 return wfMsgReal( $key, $args, false, $forcontent );
607 * Really get a message
608 * @param $key String: key to get.
609 * @param $args
610 * @param $useDB Boolean
611 * @param $forContent Mixed: Language code, or false for user lang, true for content lang.
612 * @param $transform Boolean: Whether or not to transform the message.
613 * @return String: the requested message.
615 function wfMsgReal( $key, $args, $useDB = true, $forContent = false, $transform = true ) {
616 wfProfileIn( __METHOD__ );
617 $message = wfMsgGetKey( $key, $useDB, $forContent, $transform );
618 $message = wfMsgReplaceArgs( $message, $args );
619 wfProfileOut( __METHOD__ );
620 return $message;
624 * This function provides the message source for messages to be edited which are *not* stored in the database.
626 * @deprecated in 1.18; use wfMessage()
627 * @param $key String
629 function wfMsgWeirdKey( $key ) {
630 $source = wfMsgGetKey( $key, false, true, false );
631 if ( wfEmptyMsg( $key, $source ) ) {
632 return '';
633 } else {
634 return $source;
639 * Fetch a message string value, but don't replace any keys yet.
640 * @param $key String
641 * @param $useDB Bool
642 * @param $langCode String: Code of the language to get the message for, or
643 * behaves as a content language switch if it is a boolean.
644 * @param $transform Boolean: whether to parse magic words, etc.
645 * @return string
647 function wfMsgGetKey( $key, $useDB, $langCode = false, $transform = true ) {
648 wfRunHooks( 'NormalizeMessageKey', array( &$key, &$useDB, &$langCode, &$transform ) );
650 $cache = MessageCache::singleton();
651 $message = $cache->get( $key, $useDB, $langCode );
652 if( $message === false ) {
653 $message = '&lt;' . htmlspecialchars( $key ) . '&gt;';
654 } elseif ( $transform ) {
655 $message = $cache->transform( $message );
657 return $message;
661 * Replace message parameter keys on the given formatted output.
663 * @param $message String
664 * @param $args Array
665 * @return string
666 * @private
668 function wfMsgReplaceArgs( $message, $args ) {
669 # Fix windows line-endings
670 # Some messages are split with explode("\n", $msg)
671 $message = str_replace( "\r", '', $message );
673 // Replace arguments
674 if ( count( $args ) ) {
675 if ( is_array( $args[0] ) ) {
676 $args = array_values( $args[0] );
678 $replacementKeys = array();
679 foreach( $args as $n => $param ) {
680 $replacementKeys['$' . ( $n + 1 )] = $param;
682 $message = strtr( $message, $replacementKeys );
685 return $message;
689 * Return an HTML-escaped version of a message.
690 * Parameter replacements, if any, are done *after* the HTML-escaping,
691 * so parameters may contain HTML (eg links or form controls). Be sure
692 * to pre-escape them if you really do want plaintext, or just wrap
693 * the whole thing in htmlspecialchars().
695 * @param $key String
696 * @param string ... parameters
697 * @return string
699 function wfMsgHtml( $key ) {
700 $args = func_get_args();
701 array_shift( $args );
702 return wfMsgReplaceArgs( htmlspecialchars( wfMsgGetKey( $key, true ) ), $args );
706 * Return an HTML version of message
707 * Parameter replacements, if any, are done *after* parsing the wiki-text message,
708 * so parameters may contain HTML (eg links or form controls). Be sure
709 * to pre-escape them if you really do want plaintext, or just wrap
710 * the whole thing in htmlspecialchars().
712 * @param $key String
713 * @param string ... parameters
714 * @return string
716 function wfMsgWikiHtml( $key ) {
717 global $wgOut;
718 $args = func_get_args();
719 array_shift( $args );
720 return wfMsgReplaceArgs( $wgOut->parse( wfMsgGetKey( $key, true ), /* can't be set to false */ true ), $args );
724 * Returns message in the requested format
725 * @param $key String: key of the message
726 * @param $options Array: processing rules. Can take the following options:
727 * <i>parse</i>: parses wikitext to HTML
728 * <i>parseinline</i>: parses wikitext to HTML and removes the surrounding
729 * p's added by parser or tidy
730 * <i>escape</i>: filters message through htmlspecialchars
731 * <i>escapenoentities</i>: same, but allows entity references like &#160; through
732 * <i>replaceafter</i>: parameters are substituted after parsing or escaping
733 * <i>parsemag</i>: transform the message using magic phrases
734 * <i>content</i>: fetch message for content language instead of interface
735 * Also can accept a single associative argument, of the form 'language' => 'xx':
736 * <i>language</i>: Language object or language code to fetch message for
737 * (overriden by <i>content</i>), its behaviour with parse, parseinline
738 * and parsemag is undefined.
739 * Behavior for conflicting options (e.g., parse+parseinline) is undefined.
741 function wfMsgExt( $key, $options ) {
742 global $wgOut;
744 $args = func_get_args();
745 array_shift( $args );
746 array_shift( $args );
747 $options = (array)$options;
749 foreach( $options as $arrayKey => $option ) {
750 if( !preg_match( '/^[0-9]+|language$/', $arrayKey ) ) {
751 # An unknown index, neither numeric nor "language"
752 wfWarn( "wfMsgExt called with incorrect parameter key $arrayKey", 1, E_USER_WARNING );
753 } elseif( preg_match( '/^[0-9]+$/', $arrayKey ) && !in_array( $option,
754 array( 'parse', 'parseinline', 'escape', 'escapenoentities',
755 'replaceafter', 'parsemag', 'content' ) ) ) {
756 # A numeric index with unknown value
757 wfWarn( "wfMsgExt called with incorrect parameter $option", 1, E_USER_WARNING );
761 if( in_array( 'content', $options, true ) ) {
762 $forContent = true;
763 $langCode = true;
764 $langCodeObj = null;
765 } elseif( array_key_exists( 'language', $options ) ) {
766 $forContent = false;
767 $langCode = wfGetLangObj( $options['language'] );
768 $langCodeObj = $langCode;
769 } else {
770 $forContent = false;
771 $langCode = false;
772 $langCodeObj = null;
775 $string = wfMsgGetKey( $key, /*DB*/true, $langCode, /*Transform*/false );
777 if( !in_array( 'replaceafter', $options, true ) ) {
778 $string = wfMsgReplaceArgs( $string, $args );
781 if( in_array( 'parse', $options, true ) ) {
782 $string = $wgOut->parse( $string, true, !$forContent, $langCodeObj );
783 } elseif ( in_array( 'parseinline', $options, true ) ) {
784 $string = $wgOut->parse( $string, true, !$forContent, $langCodeObj );
785 $m = array();
786 if( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $string, $m ) ) {
787 $string = $m[1];
789 } elseif ( in_array( 'parsemag', $options, true ) ) {
790 $string = MessageCache::singleton()->transform( $string,
791 !$forContent, $langCodeObj );
794 if ( in_array( 'escape', $options, true ) ) {
795 $string = htmlspecialchars ( $string );
796 } elseif ( in_array( 'escapenoentities', $options, true ) ) {
797 $string = Sanitizer::escapeHtmlAllowEntities( $string );
800 if( in_array( 'replaceafter', $options, true ) ) {
801 $string = wfMsgReplaceArgs( $string, $args );
804 return $string;
809 * Just like exit() but makes a note of it.
810 * Commits open transactions except if the error parameter is set
812 * @deprecated Please return control to the caller or throw an exception. Will
813 * be removed in 1.19.
815 function wfAbruptExit( $error = false ) {
816 static $called = false;
817 if ( $called ) {
818 exit( -1 );
820 $called = true;
822 wfDeprecated( __FUNCTION__ );
823 $bt = wfDebugBacktrace();
824 if( $bt ) {
825 for( $i = 0; $i < count( $bt ); $i++ ) {
826 $file = isset( $bt[$i]['file'] ) ? $bt[$i]['file'] : 'unknown';
827 $line = isset( $bt[$i]['line'] ) ? $bt[$i]['line'] : 'unknown';
828 wfDebug( "WARNING: Abrupt exit in $file at line $line\n");
830 } else {
831 wfDebug( "WARNING: Abrupt exit\n" );
834 wfLogProfilingData();
836 if ( !$error ) {
837 wfGetLB()->closeAll();
839 exit( -1 );
843 * @deprecated Please return control the caller or throw an exception. Will
844 * be removed in 1.19.
846 function wfErrorExit() {
847 wfDeprecated( __FUNCTION__ );
848 wfAbruptExit( true );
852 * Print a simple message and die, returning nonzero to the shell if any.
853 * Plain die() fails to return nonzero to the shell if you pass a string.
854 * @param $msg String
856 function wfDie( $msg = '' ) {
857 echo $msg;
858 die( 1 );
862 * Throw a debugging exception. This function previously once exited the process,
863 * but now throws an exception instead, with similar results.
865 * @param $msg String: message shown when dieing.
867 function wfDebugDieBacktrace( $msg = '' ) {
868 throw new MWException( $msg );
872 * Fetch server name for use in error reporting etc.
873 * Use real server name if available, so we know which machine
874 * in a server farm generated the current page.
875 * @return string
877 function wfHostname() {
878 static $host;
879 if ( is_null( $host ) ) {
880 if ( function_exists( 'posix_uname' ) ) {
881 // This function not present on Windows
882 $uname = @posix_uname();
883 } else {
884 $uname = false;
886 if( is_array( $uname ) && isset( $uname['nodename'] ) ) {
887 $host = $uname['nodename'];
888 } elseif ( getenv( 'COMPUTERNAME' ) ) {
889 # Windows computer name
890 $host = getenv( 'COMPUTERNAME' );
891 } else {
892 # This may be a virtual server.
893 $host = $_SERVER['SERVER_NAME'];
896 return $host;
900 * Returns a HTML comment with the elapsed time since request.
901 * This method has no side effects.
902 * @return string
904 function wfReportTime() {
905 global $wgRequestTime, $wgShowHostnames;
907 $now = wfTime();
908 $elapsed = $now - $wgRequestTime;
910 return $wgShowHostnames
911 ? sprintf( '<!-- Served by %s in %01.3f secs. -->', wfHostname(), $elapsed )
912 : sprintf( '<!-- Served in %01.3f secs. -->', $elapsed );
916 * Safety wrapper for debug_backtrace().
918 * With Zend Optimizer 3.2.0 loaded, this causes segfaults under somewhat
919 * murky circumstances, which may be triggered in part by stub objects
920 * or other fancy talkin'.
922 * Will return an empty array if Zend Optimizer is detected or if
923 * debug_backtrace is disabled, otherwise the output from
924 * debug_backtrace() (trimmed).
926 * @return array of backtrace information
928 function wfDebugBacktrace() {
929 static $disabled = null;
931 if( extension_loaded( 'Zend Optimizer' ) ) {
932 wfDebug( "Zend Optimizer detected; skipping debug_backtrace for safety.\n" );
933 return array();
936 if ( is_null( $disabled ) ) {
937 $disabled = false;
938 $functions = explode( ',', ini_get( 'disable_functions' ) );
939 $functions = array_map( 'trim', $functions );
940 $functions = array_map( 'strtolower', $functions );
941 if ( in_array( 'debug_backtrace', $functions ) ) {
942 wfDebug( "debug_backtrace is in disabled_functions\n" );
943 $disabled = true;
946 if ( $disabled ) {
947 return array();
950 return array_slice( debug_backtrace(), 1 );
953 function wfBacktrace() {
954 global $wgCommandLineMode;
956 if ( $wgCommandLineMode ) {
957 $msg = '';
958 } else {
959 $msg = "<ul>\n";
961 $backtrace = wfDebugBacktrace();
962 foreach( $backtrace as $call ) {
963 if( isset( $call['file'] ) ) {
964 $f = explode( DIRECTORY_SEPARATOR, $call['file'] );
965 $file = $f[count( $f ) - 1];
966 } else {
967 $file = '-';
969 if( isset( $call['line'] ) ) {
970 $line = $call['line'];
971 } else {
972 $line = '-';
974 if ( $wgCommandLineMode ) {
975 $msg .= "$file line $line calls ";
976 } else {
977 $msg .= '<li>' . $file . ' line ' . $line . ' calls ';
979 if( !empty( $call['class'] ) ) {
980 $msg .= $call['class'] . '::';
982 $msg .= $call['function'] . '()';
984 if ( $wgCommandLineMode ) {
985 $msg .= "\n";
986 } else {
987 $msg .= "</li>\n";
990 if ( $wgCommandLineMode ) {
991 $msg .= "\n";
992 } else {
993 $msg .= "</ul>\n";
996 return $msg;
1000 /* Some generic result counters, pulled out of SearchEngine */
1004 * @todo document
1006 function wfShowingResults( $offset, $limit ) {
1007 global $wgLang;
1008 return wfMsgExt(
1009 'showingresults',
1010 array( 'parseinline' ),
1011 $wgLang->formatNum( $limit ),
1012 $wgLang->formatNum( $offset + 1 )
1017 * @todo document
1019 function wfShowingResultsNum( $offset, $limit, $num ) {
1020 global $wgLang;
1021 return wfMsgExt(
1022 'showingresultsnum',
1023 array( 'parseinline' ),
1024 $wgLang->formatNum( $limit ),
1025 $wgLang->formatNum( $offset + 1 ),
1026 $wgLang->formatNum( $num )
1031 * Generate (prev x| next x) (20|50|100...) type links for paging
1032 * @param $offset String
1033 * @param $limit Integer
1034 * @param $link String
1035 * @param $query String: optional URL query parameter string
1036 * @param $atend Bool: optional param for specified if this is the last page
1038 function wfViewPrevNext( $offset, $limit, $link, $query = '', $atend = false ) {
1039 global $wgLang;
1040 $fmtLimit = $wgLang->formatNum( $limit );
1041 // FIXME: Why on earth this needs one message for the text and another one for tooltip??
1042 # Get prev/next link display text
1043 $prev = wfMsgExt( 'prevn', array( 'parsemag', 'escape' ), $fmtLimit );
1044 $next = wfMsgExt( 'nextn', array( 'parsemag', 'escape' ), $fmtLimit );
1045 # Get prev/next link title text
1046 $pTitle = wfMsgExt( 'prevn-title', array( 'parsemag', 'escape' ), $fmtLimit );
1047 $nTitle = wfMsgExt( 'nextn-title', array( 'parsemag', 'escape' ), $fmtLimit );
1048 # Fetch the title object
1049 if( is_object( $link ) ) {
1050 $title =& $link;
1051 } else {
1052 $title = Title::newFromText( $link );
1053 if( is_null( $title ) ) {
1054 return false;
1057 # Make 'previous' link
1058 if( 0 != $offset ) {
1059 $po = $offset - $limit;
1060 $po = max( $po, 0 );
1061 $q = "limit={$limit}&offset={$po}";
1062 if( $query != '' ) {
1063 $q .= '&' . $query;
1065 $plink = '<a href="' . $title->escapeLocalURL( $q ) . "\" title=\"{$pTitle}\" class=\"mw-prevlink\">{$prev}</a>";
1066 } else {
1067 $plink = $prev;
1069 # Make 'next' link
1070 $no = $offset + $limit;
1071 $q = "limit={$limit}&offset={$no}";
1072 if( $query != '' ) {
1073 $q .= '&' . $query;
1075 if( $atend ) {
1076 $nlink = $next;
1077 } else {
1078 $nlink = '<a href="' . $title->escapeLocalURL( $q ) . "\" title=\"{$nTitle}\" class=\"mw-nextlink\">{$next}</a>";
1080 # Make links to set number of items per page
1081 $nums = $wgLang->pipeList( array(
1082 wfNumLink( $offset, 20, $title, $query ),
1083 wfNumLink( $offset, 50, $title, $query ),
1084 wfNumLink( $offset, 100, $title, $query ),
1085 wfNumLink( $offset, 250, $title, $query ),
1086 wfNumLink( $offset, 500, $title, $query )
1087 ) );
1088 return wfMsgHtml( 'viewprevnext', $plink, $nlink, $nums );
1092 * Generate links for (20|50|100...) items-per-page links
1093 * @param $offset String
1094 * @param $limit Integer
1095 * @param $title Title
1096 * @param $query String: optional URL query parameter string
1098 function wfNumLink( $offset, $limit, $title, $query = '' ) {
1099 global $wgLang;
1100 if( $query == '' ) {
1101 $q = '';
1102 } else {
1103 $q = $query.'&';
1105 $q .= "limit={$limit}&offset={$offset}";
1106 $fmtLimit = $wgLang->formatNum( $limit );
1107 $lTitle = wfMsgExt( 'shown-title', array( 'parsemag', 'escape' ), $limit );
1108 $s = '<a href="' . $title->escapeLocalURL( $q ) . "\" title=\"{$lTitle}\" class=\"mw-numlink\">{$fmtLimit}</a>";
1109 return $s;
1113 * @todo document
1114 * @todo FIXME: we may want to blacklist some broken browsers
1116 * @return bool Whereas client accept gzip compression
1118 function wfClientAcceptsGzip( $force = false ) {
1119 static $result = null;
1120 if ( $result === null || $force ) {
1121 $result = false;
1122 if( isset( $_SERVER['HTTP_ACCEPT_ENCODING'] ) ) {
1123 # FIXME: we may want to blacklist some broken browsers
1124 $m = array();
1125 if( preg_match(
1126 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
1127 $_SERVER['HTTP_ACCEPT_ENCODING'],
1128 $m )
1131 if( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) {
1132 $result = false;
1133 return $result;
1135 wfDebug( " accepts gzip\n" );
1136 $result = true;
1140 return $result;
1144 * Obtain the offset and limit values from the request string;
1145 * used in special pages
1147 * @param $deflimit Default limit if none supplied
1148 * @param $optionname Name of a user preference to check against
1149 * @return array
1152 function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) {
1153 global $wgRequest;
1154 return $wgRequest->getLimitOffset( $deflimit, $optionname );
1158 * Escapes the given text so that it may be output using addWikiText()
1159 * without any linking, formatting, etc. making its way through. This
1160 * is achieved by substituting certain characters with HTML entities.
1161 * As required by the callers, <nowiki> is not used.
1163 * @param $text String: text to be escaped
1165 function wfEscapeWikiText( $text ) {
1166 $text = strtr( "\n$text", array(
1167 '"' => '&#34;', '&' => '&#38;', "'" => '&#39;', '<' => '&#60;',
1168 '=' => '&#61;', '>' => '&#62;', '[' => '&#91;', ']' => '&#93;',
1169 '{' => '&#123;', '|' => '&#124;', '}' => '&#125;',
1170 "\n#" => "\n&#35;", "\n*" => "\n&#42;",
1171 "\n:" => "\n&#58;", "\n;" => "\n&#59;",
1172 '://' => '&#58;//', 'ISBN ' => 'ISBN&#32;', 'RFC ' => 'RFC&#32;',
1173 ) );
1174 return substr( $text, 1 );
1178 * @todo document
1179 * @return float
1181 function wfTime() {
1182 return microtime( true );
1186 * Sets dest to source and returns the original value of dest
1187 * If source is NULL, it just returns the value, it doesn't set the variable
1188 * If force is true, it will set the value even if source is NULL
1190 function wfSetVar( &$dest, $source, $force = false ) {
1191 $temp = $dest;
1192 if ( !is_null( $source ) || $force ) {
1193 $dest = $source;
1195 return $temp;
1199 * As for wfSetVar except setting a bit
1201 function wfSetBit( &$dest, $bit, $state = true ) {
1202 $temp = (bool)( $dest & $bit );
1203 if ( !is_null( $state ) ) {
1204 if ( $state ) {
1205 $dest |= $bit;
1206 } else {
1207 $dest &= ~$bit;
1210 return $temp;
1214 * This function takes two arrays as input, and returns a CGI-style string, e.g.
1215 * "days=7&limit=100". Options in the first array override options in the second.
1216 * Options set to "" will not be output.
1218 function wfArrayToCGI( $array1, $array2 = null ) {
1219 if ( !is_null( $array2 ) ) {
1220 $array1 = $array1 + $array2;
1223 $cgi = '';
1224 foreach ( $array1 as $key => $value ) {
1225 if ( $value !== '' ) {
1226 if ( $cgi != '' ) {
1227 $cgi .= '&';
1229 if ( is_array( $value ) ) {
1230 $firstTime = true;
1231 foreach ( $value as $v ) {
1232 $cgi .= ( $firstTime ? '' : '&') .
1233 urlencode( $key . '[]' ) . '=' .
1234 urlencode( $v );
1235 $firstTime = false;
1237 } else {
1238 if ( is_object( $value ) ) {
1239 $value = $value->__toString();
1241 $cgi .= urlencode( $key ) . '=' .
1242 urlencode( $value );
1246 return $cgi;
1250 * This is the logical opposite of wfArrayToCGI(): it accepts a query string as
1251 * its argument and returns the same string in array form. This allows compa-
1252 * tibility with legacy functions that accept raw query strings instead of nice
1253 * arrays. Of course, keys and values are urldecode()d. Don't try passing in-
1254 * valid query strings, or it will explode.
1256 * @param $query String: query string
1257 * @return array Array version of input
1259 function wfCgiToArray( $query ) {
1260 if( isset( $query[0] ) && $query[0] == '?' ) {
1261 $query = substr( $query, 1 );
1263 $bits = explode( '&', $query );
1264 $ret = array();
1265 foreach( $bits as $bit ) {
1266 if( $bit === '' ) {
1267 continue;
1269 list( $key, $value ) = explode( '=', $bit );
1270 $key = urldecode( $key );
1271 $value = urldecode( $value );
1272 $ret[$key] = $value;
1274 return $ret;
1278 * Append a query string to an existing URL, which may or may not already
1279 * have query string parameters already. If so, they will be combined.
1281 * @param $url String
1282 * @param $query Mixed: string or associative array
1283 * @return string
1285 function wfAppendQuery( $url, $query ) {
1286 if ( is_array( $query ) ) {
1287 $query = wfArrayToCGI( $query );
1289 if( $query != '' ) {
1290 if( false === strpos( $url, '?' ) ) {
1291 $url .= '?';
1292 } else {
1293 $url .= '&';
1295 $url .= $query;
1297 return $url;
1301 * Expand a potentially local URL to a fully-qualified URL. Assumes $wgServer
1302 * and $wgProto are correct.
1304 * @todo this won't work with current-path-relative URLs
1305 * like "subdir/foo.html", etc.
1307 * @param $url String: either fully-qualified or a local path + query
1308 * @return string Fully-qualified URL
1310 function wfExpandUrl( $url ) {
1311 if( substr( $url, 0, 2 ) == '//' ) {
1312 global $wgProto;
1313 return $wgProto . ':' . $url;
1314 } elseif( substr( $url, 0, 1 ) == '/' ) {
1315 global $wgServer;
1316 return $wgServer . $url;
1317 } else {
1318 return $url;
1323 * Windows-compatible version of escapeshellarg()
1324 * Windows doesn't recognise single-quotes in the shell, but the escapeshellarg()
1325 * function puts single quotes in regardless of OS.
1327 * Also fixes the locale problems on Linux in PHP 5.2.6+ (bug backported to
1328 * earlier distro releases of PHP)
1330 function wfEscapeShellArg( ) {
1331 wfInitShellLocale();
1333 $args = func_get_args();
1334 $first = true;
1335 $retVal = '';
1336 foreach ( $args as $arg ) {
1337 if ( !$first ) {
1338 $retVal .= ' ';
1339 } else {
1340 $first = false;
1343 if ( wfIsWindows() ) {
1344 // Escaping for an MSVC-style command line parser and CMD.EXE
1345 // Refs:
1346 // * http://web.archive.org/web/20020708081031/http://mailman.lyra.org/pipermail/scite-interest/2002-March/000436.html
1347 // * http://technet.microsoft.com/en-us/library/cc723564.aspx
1348 // * Bug #13518
1349 // * CR r63214
1350 // Double the backslashes before any double quotes. Escape the double quotes.
1351 $tokens = preg_split( '/(\\\\*")/', $arg, -1, PREG_SPLIT_DELIM_CAPTURE );
1352 $arg = '';
1353 $iteration = 0;
1354 foreach ( $tokens as $token ) {
1355 if ( $iteration % 2 == 1 ) {
1356 // Delimiter, a double quote preceded by zero or more slashes
1357 $arg .= str_replace( '\\', '\\\\', substr( $token, 0, -1 ) ) . '\\"';
1358 } elseif ( $iteration % 4 == 2 ) {
1359 // ^ in $token will be outside quotes, need to be escaped
1360 $arg .= str_replace( '^', '^^', $token );
1361 } else { // $iteration % 4 == 0
1362 // ^ in $token will appear inside double quotes, so leave as is
1363 $arg .= $token;
1365 $iteration++;
1367 // Double the backslashes before the end of the string, because
1368 // we will soon add a quote
1369 $m = array();
1370 if ( preg_match( '/^(.*?)(\\\\+)$/', $arg, $m ) ) {
1371 $arg = $m[1] . str_replace( '\\', '\\\\', $m[2] );
1374 // Add surrounding quotes
1375 $retVal .= '"' . $arg . '"';
1376 } else {
1377 $retVal .= escapeshellarg( $arg );
1380 return $retVal;
1384 * wfMerge attempts to merge differences between three texts.
1385 * Returns true for a clean merge and false for failure or a conflict.
1387 function wfMerge( $old, $mine, $yours, &$result ) {
1388 global $wgDiff3;
1390 # This check may also protect against code injection in
1391 # case of broken installations.
1392 wfSuppressWarnings();
1393 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
1394 wfRestoreWarnings();
1396 if( !$haveDiff3 ) {
1397 wfDebug( "diff3 not found\n" );
1398 return false;
1401 # Make temporary files
1402 $td = wfTempDir();
1403 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
1404 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
1405 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
1407 fwrite( $oldtextFile, $old );
1408 fclose( $oldtextFile );
1409 fwrite( $mytextFile, $mine );
1410 fclose( $mytextFile );
1411 fwrite( $yourtextFile, $yours );
1412 fclose( $yourtextFile );
1414 # Check for a conflict
1415 $cmd = $wgDiff3 . ' -a --overlap-only ' .
1416 wfEscapeShellArg( $mytextName ) . ' ' .
1417 wfEscapeShellArg( $oldtextName ) . ' ' .
1418 wfEscapeShellArg( $yourtextName );
1419 $handle = popen( $cmd, 'r' );
1421 if( fgets( $handle, 1024 ) ) {
1422 $conflict = true;
1423 } else {
1424 $conflict = false;
1426 pclose( $handle );
1428 # Merge differences
1429 $cmd = $wgDiff3 . ' -a -e --merge ' .
1430 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
1431 $handle = popen( $cmd, 'r' );
1432 $result = '';
1433 do {
1434 $data = fread( $handle, 8192 );
1435 if ( strlen( $data ) == 0 ) {
1436 break;
1438 $result .= $data;
1439 } while ( true );
1440 pclose( $handle );
1441 unlink( $mytextName );
1442 unlink( $oldtextName );
1443 unlink( $yourtextName );
1445 if ( $result === '' && $old !== '' && !$conflict ) {
1446 wfDebug( "Unexpected null result from diff3. Command: $cmd\n" );
1447 $conflict = true;
1449 return !$conflict;
1453 * Returns unified plain-text diff of two texts.
1454 * Useful for machine processing of diffs.
1455 * @param $before String: the text before the changes.
1456 * @param $after String: the text after the changes.
1457 * @param $params String: command-line options for the diff command.
1458 * @return String: unified diff of $before and $after
1460 function wfDiff( $before, $after, $params = '-u' ) {
1461 if ( $before == $after ) {
1462 return '';
1465 global $wgDiff;
1466 wfSuppressWarnings();
1467 $haveDiff = $wgDiff && file_exists( $wgDiff );
1468 wfRestoreWarnings();
1470 # This check may also protect against code injection in
1471 # case of broken installations.
1472 if( !$haveDiff ) {
1473 wfDebug( "diff executable not found\n" );
1474 $diffs = new Diff( explode( "\n", $before ), explode( "\n", $after ) );
1475 $format = new UnifiedDiffFormatter();
1476 return $format->format( $diffs );
1479 # Make temporary files
1480 $td = wfTempDir();
1481 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
1482 $newtextFile = fopen( $newtextName = tempnam( $td, 'merge-your-' ), 'w' );
1484 fwrite( $oldtextFile, $before );
1485 fclose( $oldtextFile );
1486 fwrite( $newtextFile, $after );
1487 fclose( $newtextFile );
1489 // Get the diff of the two files
1490 $cmd = "$wgDiff " . $params . ' ' . wfEscapeShellArg( $oldtextName, $newtextName );
1492 $h = popen( $cmd, 'r' );
1494 $diff = '';
1496 do {
1497 $data = fread( $h, 8192 );
1498 if ( strlen( $data ) == 0 ) {
1499 break;
1501 $diff .= $data;
1502 } while ( true );
1504 // Clean up
1505 pclose( $h );
1506 unlink( $oldtextName );
1507 unlink( $newtextName );
1509 // Kill the --- and +++ lines. They're not useful.
1510 $diff_lines = explode( "\n", $diff );
1511 if ( strpos( $diff_lines[0], '---' ) === 0 ) {
1512 unset( $diff_lines[0] );
1514 if ( strpos( $diff_lines[1], '+++' ) === 0 ) {
1515 unset( $diff_lines[1] );
1518 $diff = implode( "\n", $diff_lines );
1520 return $diff;
1524 * A wrapper around the PHP function var_export().
1525 * Either print it or add it to the regular output ($wgOut).
1527 * @param $var A PHP variable to dump.
1529 function wfVarDump( $var ) {
1530 global $wgOut;
1531 $s = str_replace( "\n", "<br />\n", var_export( $var, true ) . "\n" );
1532 if ( headers_sent() || !@is_object( $wgOut ) ) {
1533 print $s;
1534 } else {
1535 $wgOut->addHTML( $s );
1540 * Provide a simple HTTP error.
1542 function wfHttpError( $code, $label, $desc ) {
1543 global $wgOut;
1544 $wgOut->disable();
1545 header( "HTTP/1.0 $code $label" );
1546 header( "Status: $code $label" );
1547 $wgOut->sendCacheControl();
1549 header( 'Content-type: text/html; charset=utf-8' );
1550 print "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">".
1551 '<html><head><title>' .
1552 htmlspecialchars( $label ) .
1553 '</title></head><body><h1>' .
1554 htmlspecialchars( $label ) .
1555 '</h1><p>' .
1556 nl2br( htmlspecialchars( $desc ) ) .
1557 "</p></body></html>\n";
1561 * Clear away any user-level output buffers, discarding contents.
1563 * Suitable for 'starting afresh', for instance when streaming
1564 * relatively large amounts of data without buffering, or wanting to
1565 * output image files without ob_gzhandler's compression.
1567 * The optional $resetGzipEncoding parameter controls suppression of
1568 * the Content-Encoding header sent by ob_gzhandler; by default it
1569 * is left. See comments for wfClearOutputBuffers() for why it would
1570 * be used.
1572 * Note that some PHP configuration options may add output buffer
1573 * layers which cannot be removed; these are left in place.
1575 * @param $resetGzipEncoding Bool
1577 function wfResetOutputBuffers( $resetGzipEncoding = true ) {
1578 if( $resetGzipEncoding ) {
1579 // Suppress Content-Encoding and Content-Length
1580 // headers from 1.10+s wfOutputHandler
1581 global $wgDisableOutputCompression;
1582 $wgDisableOutputCompression = true;
1584 while( $status = ob_get_status() ) {
1585 if( $status['type'] == 0 /* PHP_OUTPUT_HANDLER_INTERNAL */ ) {
1586 // Probably from zlib.output_compression or other
1587 // PHP-internal setting which can't be removed.
1589 // Give up, and hope the result doesn't break
1590 // output behavior.
1591 break;
1593 if( !ob_end_clean() ) {
1594 // Could not remove output buffer handler; abort now
1595 // to avoid getting in some kind of infinite loop.
1596 break;
1598 if( $resetGzipEncoding ) {
1599 if( $status['name'] == 'ob_gzhandler' ) {
1600 // Reset the 'Content-Encoding' field set by this handler
1601 // so we can start fresh.
1602 header( 'Content-Encoding:' );
1603 break;
1610 * More legible than passing a 'false' parameter to wfResetOutputBuffers():
1612 * Clear away output buffers, but keep the Content-Encoding header
1613 * produced by ob_gzhandler, if any.
1615 * This should be used for HTTP 304 responses, where you need to
1616 * preserve the Content-Encoding header of the real result, but
1617 * also need to suppress the output of ob_gzhandler to keep to spec
1618 * and avoid breaking Firefox in rare cases where the headers and
1619 * body are broken over two packets.
1621 function wfClearOutputBuffers() {
1622 wfResetOutputBuffers( false );
1626 * Converts an Accept-* header into an array mapping string values to quality
1627 * factors
1629 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
1630 # No arg means accept anything (per HTTP spec)
1631 if( !$accept ) {
1632 return array( $def => 1.0 );
1635 $prefs = array();
1637 $parts = explode( ',', $accept );
1639 foreach( $parts as $part ) {
1640 # FIXME: doesn't deal with params like 'text/html; level=1'
1641 @list( $value, $qpart ) = explode( ';', trim( $part ) );
1642 $match = array();
1643 if( !isset( $qpart ) ) {
1644 $prefs[$value] = 1.0;
1645 } elseif( preg_match( '/q\s*=\s*(\d*\.\d+)/', $qpart, $match ) ) {
1646 $prefs[$value] = floatval( $match[1] );
1650 return $prefs;
1654 * Checks if a given MIME type matches any of the keys in the given
1655 * array. Basic wildcards are accepted in the array keys.
1657 * Returns the matching MIME type (or wildcard) if a match, otherwise
1658 * NULL if no match.
1660 * @param $type String
1661 * @param $avail Array
1662 * @return string
1663 * @private
1665 function mimeTypeMatch( $type, $avail ) {
1666 if( array_key_exists( $type, $avail ) ) {
1667 return $type;
1668 } else {
1669 $parts = explode( '/', $type );
1670 if( array_key_exists( $parts[0] . '/*', $avail ) ) {
1671 return $parts[0] . '/*';
1672 } elseif( array_key_exists( '*/*', $avail ) ) {
1673 return '*/*';
1674 } else {
1675 return null;
1681 * Returns the 'best' match between a client's requested internet media types
1682 * and the server's list of available types. Each list should be an associative
1683 * array of type to preference (preference is a float between 0.0 and 1.0).
1684 * Wildcards in the types are acceptable.
1686 * @param $cprefs Array: client's acceptable type list
1687 * @param $sprefs Array: server's offered types
1688 * @return string
1690 * @todo FIXME: doesn't handle params like 'text/plain; charset=UTF-8'
1691 * XXX: generalize to negotiate other stuff
1693 function wfNegotiateType( $cprefs, $sprefs ) {
1694 $combine = array();
1696 foreach( array_keys($sprefs) as $type ) {
1697 $parts = explode( '/', $type );
1698 if( $parts[1] != '*' ) {
1699 $ckey = mimeTypeMatch( $type, $cprefs );
1700 if( $ckey ) {
1701 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1706 foreach( array_keys( $cprefs ) as $type ) {
1707 $parts = explode( '/', $type );
1708 if( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
1709 $skey = mimeTypeMatch( $type, $sprefs );
1710 if( $skey ) {
1711 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1716 $bestq = 0;
1717 $besttype = null;
1719 foreach( array_keys( $combine ) as $type ) {
1720 if( $combine[$type] > $bestq ) {
1721 $besttype = $type;
1722 $bestq = $combine[$type];
1726 return $besttype;
1730 * Array lookup
1731 * Returns an array where the values in the first array are replaced by the
1732 * values in the second array with the corresponding keys
1734 * @return array
1736 function wfArrayLookup( $a, $b ) {
1737 return array_flip( array_intersect( array_flip( $a ), array_keys( $b ) ) );
1741 * Convenience function; returns MediaWiki timestamp for the present time.
1742 * @return string
1744 function wfTimestampNow() {
1745 # return NOW
1746 return wfTimestamp( TS_MW, time() );
1750 * Reference-counted warning suppression
1752 function wfSuppressWarnings( $end = false ) {
1753 static $suppressCount = 0;
1754 static $originalLevel = false;
1756 if ( $end ) {
1757 if ( $suppressCount ) {
1758 --$suppressCount;
1759 if ( !$suppressCount ) {
1760 error_reporting( $originalLevel );
1763 } else {
1764 if ( !$suppressCount ) {
1765 $originalLevel = error_reporting( E_ALL & ~( E_WARNING | E_NOTICE | E_USER_WARNING | E_USER_NOTICE ) );
1767 ++$suppressCount;
1772 * Restore error level to previous value
1774 function wfRestoreWarnings() {
1775 wfSuppressWarnings( true );
1778 # Autodetect, convert and provide timestamps of various types
1781 * Unix time - the number of seconds since 1970-01-01 00:00:00 UTC
1783 define( 'TS_UNIX', 0 );
1786 * MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
1788 define( 'TS_MW', 1 );
1791 * MySQL DATETIME (YYYY-MM-DD HH:MM:SS)
1793 define( 'TS_DB', 2 );
1796 * RFC 2822 format, for E-mail and HTTP headers
1798 define( 'TS_RFC2822', 3 );
1801 * ISO 8601 format with no timezone: 1986-02-09T20:00:00Z
1803 * This is used by Special:Export
1805 define( 'TS_ISO_8601', 4 );
1808 * An Exif timestamp (YYYY:MM:DD HH:MM:SS)
1810 * @see http://exif.org/Exif2-2.PDF The Exif 2.2 spec, see page 28 for the
1811 * DateTime tag and page 36 for the DateTimeOriginal and
1812 * DateTimeDigitized tags.
1814 define( 'TS_EXIF', 5 );
1817 * Oracle format time.
1819 define( 'TS_ORACLE', 6 );
1822 * Postgres format time.
1824 define( 'TS_POSTGRES', 7 );
1827 * DB2 format time
1829 define( 'TS_DB2', 8 );
1832 * ISO 8601 basic format with no timezone: 19860209T200000Z
1834 * This is used by ResourceLoader
1836 define( 'TS_ISO_8601_BASIC', 9 );
1839 * @param $outputtype Mixed: A timestamp in one of the supported formats, the
1840 * function will autodetect which format is supplied and act
1841 * accordingly.
1842 * @param $ts Mixed: the timestamp to convert or 0 for the current timestamp
1843 * @return Mixed: String / false The same date in the format specified in $outputtype or false
1845 function wfTimestamp( $outputtype = TS_UNIX, $ts = 0 ) {
1846 $uts = 0;
1847 $da = array();
1848 $strtime = '';
1850 if ( !$ts ) { // We want to catch 0, '', null... but not date strings starting with a letter.
1851 $uts = time();
1852 $strtime = "@$uts";
1853 } elseif ( preg_match( '/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)$/D', $ts, $da ) ) {
1854 # TS_DB
1855 } elseif ( preg_match( '/^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/D', $ts, $da ) ) {
1856 # TS_EXIF
1857 } elseif ( preg_match( '/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/D', $ts, $da ) ) {
1858 # TS_MW
1859 } elseif ( preg_match( '/^-?\d{1,13}$/D', $ts ) ) {
1860 # TS_UNIX
1861 $uts = $ts;
1862 $strtime = "@$ts"; // Undocumented?
1863 } elseif ( preg_match( '/^\d{2}-\d{2}-\d{4} \d{2}:\d{2}:\d{2}.\d{6}$/', $ts ) ) {
1864 # TS_ORACLE // session altered to DD-MM-YYYY HH24:MI:SS.FF6
1865 $strtime = preg_replace( '/(\d\d)\.(\d\d)\.(\d\d)(\.(\d+))?/', "$1:$2:$3",
1866 str_replace( '+00:00', 'UTC', $ts ) );
1867 } elseif ( preg_match( '/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.*\d*)?Z$/', $ts, $da ) ) {
1868 # TS_ISO_8601
1869 } elseif ( preg_match( '/^(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})(?:\.*\d*)?Z$/', $ts, $da ) ) {
1870 #TS_ISO_8601_BASIC
1871 } elseif ( preg_match( '/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.*\d*[\+\- ](\d\d)$/', $ts, $da ) ) {
1872 # TS_POSTGRES
1873 } elseif ( preg_match( '/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.*\d* GMT$/', $ts, $da ) ) {
1874 # TS_POSTGRES
1875 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.\d\d\d$/',$ts,$da)) {
1876 # TS_DB2
1877 } elseif ( preg_match( '/^[ \t\r\n]*([A-Z][a-z]{2},[ \t\r\n]*)?' . # Day of week
1878 '\d\d?[ \t\r\n]*[A-Z][a-z]{2}[ \t\r\n]*\d{2}(?:\d{2})?' . # dd Mon yyyy
1879 '[ \t\r\n]*\d\d[ \t\r\n]*:[ \t\r\n]*\d\d[ \t\r\n]*:[ \t\r\n]*\d\d/S', $ts ) ) { # hh:mm:ss
1880 # TS_RFC2822, accepting a trailing comment. See http://www.squid-cache.org/mail-archive/squid-users/200307/0122.html / r77171
1881 # The regex is a superset of rfc2822 for readability
1882 $strtime = strtok( $ts, ';' );
1883 } elseif ( preg_match( '/^[A-Z][a-z]{5,8}, \d\d-[A-Z][a-z]{2}-\d{2} \d\d:\d\d:\d\d/', $ts ) ) {
1884 # TS_RFC850
1885 $strtime = $ts;
1886 } elseif ( preg_match( '/^[A-Z][a-z]{2} [A-Z][a-z]{2} +\d{1,2} \d\d:\d\d:\d\d \d{4}/', $ts ) ) {
1887 # asctime
1888 $strtime = $ts;
1889 } else {
1890 # Bogus value...
1891 wfDebug("wfTimestamp() fed bogus time value: TYPE=$outputtype; VALUE=$ts\n");
1893 return false;
1898 static $formats = array(
1899 TS_UNIX => 'U',
1900 TS_MW => 'YmdHis',
1901 TS_DB => 'Y-m-d H:i:s',
1902 TS_ISO_8601 => 'Y-m-d\TH:i:s\Z',
1903 TS_ISO_8601_BASIC => 'Ymd\THis\Z',
1904 TS_EXIF => 'Y:m:d H:i:s', // This shouldn't ever be used, but is included for completeness
1905 TS_RFC2822 => 'D, d M Y H:i:s',
1906 TS_ORACLE => 'd-m-Y H:i:s.000000', // Was 'd-M-y h.i.s A' . ' +00:00' before r51500
1907 TS_POSTGRES => 'Y-m-d H:i:s',
1908 TS_DB2 => 'Y-m-d H:i:s',
1911 if ( !isset( $formats[$outputtype] ) ) {
1912 throw new MWException( 'wfTimestamp() called with illegal output type.' );
1915 if ( function_exists( "date_create" ) ) {
1916 if ( count( $da ) ) {
1917 $ds = sprintf("%04d-%02d-%02dT%02d:%02d:%02d.00+00:00",
1918 (int)$da[1], (int)$da[2], (int)$da[3],
1919 (int)$da[4], (int)$da[5], (int)$da[6]);
1921 $d = date_create( $ds, new DateTimeZone( 'GMT' ) );
1922 } elseif ( $strtime ) {
1923 $d = date_create( $strtime, new DateTimeZone( 'GMT' ) );
1924 } else {
1925 return false;
1928 if ( !$d ) {
1929 wfDebug("wfTimestamp() fed bogus time value: $outputtype; $ts\n");
1930 return false;
1933 $output = $d->format( $formats[$outputtype] );
1934 } else {
1935 if ( count( $da ) ) {
1936 // Warning! gmmktime() acts oddly if the month or day is set to 0
1937 // We may want to handle that explicitly at some point
1938 $uts = gmmktime( (int)$da[4], (int)$da[5], (int)$da[6],
1939 (int)$da[2], (int)$da[3], (int)$da[1] );
1940 } elseif ( $strtime ) {
1941 $uts = strtotime( $strtime );
1944 if ( $uts === false ) {
1945 wfDebug("wfTimestamp() can't parse the timestamp (non 32-bit time? Update php): $outputtype; $ts\n");
1946 return false;
1949 if ( TS_UNIX == $outputtype ) {
1950 return $uts;
1952 $output = gmdate( $formats[$outputtype], $uts );
1955 if ( ( $outputtype == TS_RFC2822 ) || ( $outputtype == TS_POSTGRES ) ) {
1956 $output .= ' GMT';
1959 return $output;
1963 * Return a formatted timestamp, or null if input is null.
1964 * For dealing with nullable timestamp columns in the database.
1965 * @param $outputtype Integer
1966 * @param $ts String
1967 * @return String
1969 function wfTimestampOrNull( $outputtype = TS_UNIX, $ts = null ) {
1970 if( is_null( $ts ) ) {
1971 return null;
1972 } else {
1973 return wfTimestamp( $outputtype, $ts );
1978 * Check if the operating system is Windows
1980 * @return Bool: true if it's Windows, False otherwise.
1982 function wfIsWindows() {
1983 static $isWindows = null;
1984 if ( $isWindows === null ) {
1985 $isWindows = substr( php_uname(), 0, 7 ) == 'Windows';
1987 return $isWindows;
1991 * Swap two variables
1993 function swap( &$x, &$y ) {
1994 $z = $x;
1995 $x = $y;
1996 $y = $z;
1999 function wfGetCachedNotice( $name ) {
2000 global $wgOut, $wgRenderHashAppend, $parserMemc;
2001 $fname = 'wfGetCachedNotice';
2002 wfProfileIn( $fname );
2004 $needParse = false;
2006 if( $name === 'default' ) {
2007 // special case
2008 global $wgSiteNotice;
2009 $notice = $wgSiteNotice;
2010 if( empty( $notice ) ) {
2011 wfProfileOut( $fname );
2012 return false;
2014 } else {
2015 $msg = wfMessage( $name )->inContentLanguage();
2016 if( $msg->isDisabled() ) {
2017 wfProfileOut( $fname );
2018 return( false );
2020 $notice = $msg->plain();
2023 // Use the extra hash appender to let eg SSL variants separately cache.
2024 $key = wfMemcKey( $name . $wgRenderHashAppend );
2025 $cachedNotice = $parserMemc->get( $key );
2026 if( is_array( $cachedNotice ) ) {
2027 if( md5( $notice ) == $cachedNotice['hash'] ) {
2028 $notice = $cachedNotice['html'];
2029 } else {
2030 $needParse = true;
2032 } else {
2033 $needParse = true;
2036 if( $needParse ) {
2037 if( is_object( $wgOut ) ) {
2038 $parsed = $wgOut->parse( $notice );
2039 $parserMemc->set( $key, array( 'html' => $parsed, 'hash' => md5( $notice ) ), 600 );
2040 $notice = $parsed;
2041 } else {
2042 wfDebug( 'wfGetCachedNotice called for ' . $name . ' with no $wgOut available' . "\n" );
2043 $notice = '';
2046 $notice = '<div id="localNotice">' .$notice . '</div>';
2047 wfProfileOut( $fname );
2048 return $notice;
2051 function wfGetNamespaceNotice() {
2052 global $wgTitle;
2054 # Paranoia
2055 if ( !isset( $wgTitle ) || !is_object( $wgTitle ) ) {
2056 return '';
2059 $fname = 'wfGetNamespaceNotice';
2060 wfProfileIn( $fname );
2062 $key = 'namespacenotice-' . $wgTitle->getNsText();
2063 $namespaceNotice = wfGetCachedNotice( $key );
2064 if ( $namespaceNotice && substr( $namespaceNotice, 0, 7 ) != '<p>&lt;' ) {
2065 $namespaceNotice = '<div id="namespacebanner">' . $namespaceNotice . '</div>';
2066 } else {
2067 $namespaceNotice = '';
2070 wfProfileOut( $fname );
2071 return $namespaceNotice;
2074 function wfGetSiteNotice() {
2075 global $wgUser;
2076 $fname = 'wfGetSiteNotice';
2077 wfProfileIn( $fname );
2078 $siteNotice = '';
2080 if( wfRunHooks( 'SiteNoticeBefore', array( &$siteNotice ) ) ) {
2081 if( is_object( $wgUser ) && $wgUser->isLoggedIn() ) {
2082 $siteNotice = wfGetCachedNotice( 'sitenotice' );
2083 } else {
2084 $anonNotice = wfGetCachedNotice( 'anonnotice' );
2085 if( !$anonNotice ) {
2086 $siteNotice = wfGetCachedNotice( 'sitenotice' );
2087 } else {
2088 $siteNotice = $anonNotice;
2091 if( !$siteNotice ) {
2092 $siteNotice = wfGetCachedNotice( 'default' );
2096 wfRunHooks( 'SiteNoticeAfter', array( &$siteNotice ) );
2097 wfProfileOut( $fname );
2098 return $siteNotice;
2102 * BC wrapper for MimeMagic::singleton()
2103 * @deprecated No longer needed as of 1.17 (r68836). Remove in 1.19.
2105 function &wfGetMimeMagic() {
2106 wfDeprecated( __FUNCTION__ );
2107 return MimeMagic::singleton();
2111 * Tries to get the system directory for temporary files. The TMPDIR, TMP, and
2112 * TEMP environment variables are then checked in sequence, and if none are set
2113 * try sys_get_temp_dir() for PHP >= 5.2.1. All else fails, return /tmp for Unix
2114 * or C:\Windows\Temp for Windows and hope for the best.
2115 * It is common to call it with tempnam().
2117 * NOTE: When possible, use instead the tmpfile() function to create
2118 * temporary files to avoid race conditions on file creation, etc.
2120 * @return String
2122 function wfTempDir() {
2123 foreach( array( 'TMPDIR', 'TMP', 'TEMP' ) as $var ) {
2124 $tmp = getenv( $var );
2125 if( $tmp && file_exists( $tmp ) && is_dir( $tmp ) && is_writable( $tmp ) ) {
2126 return $tmp;
2129 if( function_exists( 'sys_get_temp_dir' ) ) {
2130 return sys_get_temp_dir();
2132 # Usual defaults
2133 return wfIsWindows() ? 'C:\Windows\Temp' : '/tmp';
2137 * Make directory, and make all parent directories if they don't exist
2139 * @param $dir String: full path to directory to create
2140 * @param $mode Integer: chmod value to use, default is $wgDirectoryMode
2141 * @param $caller String: optional caller param for debugging.
2142 * @return bool
2144 function wfMkdirParents( $dir, $mode = null, $caller = null ) {
2145 global $wgDirectoryMode;
2147 if ( !is_null( $caller ) ) {
2148 wfDebug( "$caller: called wfMkdirParents($dir)" );
2151 if( strval( $dir ) === '' || file_exists( $dir ) ) {
2152 return true;
2155 $dir = str_replace( array( '\\', '/' ), DIRECTORY_SEPARATOR, $dir );
2157 if ( is_null( $mode ) ) {
2158 $mode = $wgDirectoryMode;
2161 // Turn off the normal warning, we're doing our own below
2162 wfSuppressWarnings();
2163 $ok = mkdir( $dir, $mode, true ); // PHP5 <3
2164 wfRestoreWarnings();
2166 if( !$ok ) {
2167 // PHP doesn't report the path in its warning message, so add our own to aid in diagnosis.
2168 trigger_error( __FUNCTION__ . ": failed to mkdir \"$dir\" mode $mode", E_USER_WARNING );
2170 return $ok;
2174 * Increment a statistics counter
2176 function wfIncrStats( $key ) {
2177 global $wgStatsMethod;
2179 if( $wgStatsMethod == 'udp' ) {
2180 global $wgUDPProfilerHost, $wgUDPProfilerPort, $wgDBname;
2181 static $socket;
2182 if ( !$socket ) {
2183 $socket = socket_create( AF_INET, SOCK_DGRAM, SOL_UDP );
2184 $statline = "stats/{$wgDBname} - 1 1 1 1 1 -total\n";
2185 socket_sendto(
2186 $socket,
2187 $statline,
2188 strlen( $statline ),
2190 $wgUDPProfilerHost,
2191 $wgUDPProfilerPort
2194 $statline = "stats/{$wgDBname} - 1 1 1 1 1 {$key}\n";
2195 wfSuppressWarnings();
2196 socket_sendto(
2197 $socket,
2198 $statline,
2199 strlen( $statline ),
2201 $wgUDPProfilerHost,
2202 $wgUDPProfilerPort
2204 wfRestoreWarnings();
2205 } elseif( $wgStatsMethod == 'cache' ) {
2206 global $wgMemc;
2207 $key = wfMemcKey( 'stats', $key );
2208 if ( is_null( $wgMemc->incr( $key ) ) ) {
2209 $wgMemc->add( $key, 1 );
2211 } else {
2212 // Disabled
2217 * @param $nr Mixed: the number to format
2218 * @param $acc Integer: the number of digits after the decimal point, default 2
2219 * @param $round Boolean: whether or not to round the value, default true
2220 * @return float
2222 function wfPercent( $nr, $acc = 2, $round = true ) {
2223 $ret = sprintf( "%.${acc}f", $nr );
2224 return $round ? round( $ret, $acc ) . '%' : "$ret%";
2228 * Encrypt a username/password.
2230 * @param $userid Integer: ID of the user
2231 * @param $password String: password of the user
2232 * @return String: hashed password
2233 * @deprecated Use User::crypt() or User::oldCrypt() instead
2235 function wfEncryptPassword( $userid, $password ) {
2236 wfDeprecated(__FUNCTION__);
2237 # Just wrap around User::oldCrypt()
2238 return User::oldCrypt( $password, $userid );
2242 * Appends to second array if $value differs from that in $default
2244 function wfAppendToArrayIfNotDefault( $key, $value, $default, &$changed ) {
2245 if ( is_null( $changed ) ) {
2246 throw new MWException( 'GlobalFunctions::wfAppendToArrayIfNotDefault got null' );
2248 if ( $default[$key] !== $value ) {
2249 $changed[$key] = $value;
2254 * Since wfMsg() and co suck, they don't return false if the message key they
2255 * looked up didn't exist but a XHTML string, this function checks for the
2256 * nonexistance of messages by looking at wfMsg() output
2258 * @param $key String: the message key looked up
2259 * @return Boolean True if the message *doesn't* exist.
2261 function wfEmptyMsg( $key ) {
2262 return MessageCache::singleton()->get( $key, /*useDB*/true, /*content*/false ) === false;
2266 * Find out whether or not a mixed variable exists in a string
2268 * @param $needle String
2269 * @param $str String
2270 * @param $insensitive Boolean
2271 * @return Boolean
2273 function in_string( $needle, $str, $insensitive = false ) {
2274 $func = 'strpos';
2275 if( $insensitive ) $func = 'stripos';
2277 return $func( $str, $needle ) !== false;
2280 function wfSpecialList( $page, $details ) {
2281 global $wgContLang;
2282 $details = $details ? ' ' . $wgContLang->getDirMark() . "($details)" : '';
2283 return $page . $details;
2287 * Returns a regular expression of url protocols
2289 * @return String
2291 function wfUrlProtocols() {
2292 global $wgUrlProtocols;
2294 static $retval = null;
2295 if ( !is_null( $retval ) ) {
2296 return $retval;
2299 // Support old-style $wgUrlProtocols strings, for backwards compatibility
2300 // with LocalSettings files from 1.5
2301 if ( is_array( $wgUrlProtocols ) ) {
2302 $protocols = array();
2303 foreach ( $wgUrlProtocols as $protocol ) {
2304 $protocols[] = preg_quote( $protocol, '/' );
2307 $retval = implode( '|', $protocols );
2308 } else {
2309 $retval = $wgUrlProtocols;
2311 return $retval;
2315 * Safety wrapper around ini_get() for boolean settings.
2316 * The values returned from ini_get() are pre-normalized for settings
2317 * set via php.ini or php_flag/php_admin_flag... but *not*
2318 * for those set via php_value/php_admin_value.
2320 * It's fairly common for people to use php_value instead of php_flag,
2321 * which can leave you with an 'off' setting giving a false positive
2322 * for code that just takes the ini_get() return value as a boolean.
2324 * To make things extra interesting, setting via php_value accepts
2325 * "true" and "yes" as true, but php.ini and php_flag consider them false. :)
2326 * Unrecognized values go false... again opposite PHP's own coercion
2327 * from string to bool.
2329 * Luckily, 'properly' set settings will always come back as '0' or '1',
2330 * so we only have to worry about them and the 'improper' settings.
2332 * I frickin' hate PHP... :P
2334 * @param $setting String
2335 * @return Bool
2337 function wfIniGetBool( $setting ) {
2338 $val = ini_get( $setting );
2339 // 'on' and 'true' can't have whitespace around them, but '1' can.
2340 return strtolower( $val ) == 'on'
2341 || strtolower( $val ) == 'true'
2342 || strtolower( $val ) == 'yes'
2343 || preg_match( "/^\s*[+-]?0*[1-9]/", $val ); // approx C atoi() function
2347 * Wrapper function for PHP's dl(). This doesn't work in most situations from
2348 * PHP 5.3 onward, and is usually disabled in shared environments anyway.
2350 * @param $extension String A PHP extension. The file suffix (.so or .dll)
2351 * should be omitted
2352 * @return Bool - Whether or not the extension is loaded
2354 function wfDl( $extension ) {
2355 if( extension_loaded( $extension ) ) {
2356 return true;
2359 $canDl = ( function_exists( 'dl' ) && is_callable( 'dl' )
2360 && wfIniGetBool( 'enable_dl' ) && !wfIniGetBool( 'safe_mode' ) );
2362 if( $canDl ) {
2363 wfSuppressWarnings();
2364 dl( $extension . '.' . PHP_SHLIB_SUFFIX );
2365 wfRestoreWarnings();
2367 return extension_loaded( $extension );
2371 * Execute a shell command, with time and memory limits mirrored from the PHP
2372 * configuration if supported.
2373 * @param $cmd String Command line, properly escaped for shell.
2374 * @param &$retval optional, will receive the program's exit code.
2375 * (non-zero is usually failure)
2376 * @param $environ Array optional environment variables which should be
2377 * added to the executed command environment.
2378 * @return collected stdout as a string (trailing newlines stripped)
2380 function wfShellExec( $cmd, &$retval = null, $environ = array() ) {
2381 global $IP, $wgMaxShellMemory, $wgMaxShellFileSize, $wgMaxShellTime;
2383 static $disabled;
2384 if ( is_null( $disabled ) ) {
2385 $disabled = false;
2386 if( wfIniGetBool( 'safe_mode' ) ) {
2387 wfDebug( "wfShellExec can't run in safe_mode, PHP's exec functions are too broken.\n" );
2388 $disabled = 'safemode';
2389 } else {
2390 $functions = explode( ',', ini_get( 'disable_functions' ) );
2391 $functions = array_map( 'trim', $functions );
2392 $functions = array_map( 'strtolower', $functions );
2393 if ( in_array( 'passthru', $functions ) ) {
2394 wfDebug( "passthru is in disabled_functions\n" );
2395 $disabled = 'passthru';
2399 if ( $disabled ) {
2400 $retval = 1;
2401 return $disabled == 'safemode' ?
2402 'Unable to run external programs in safe mode.' :
2403 'Unable to run external programs, passthru() is disabled.';
2406 wfInitShellLocale();
2408 $envcmd = '';
2409 foreach( $environ as $k => $v ) {
2410 if ( wfIsWindows() ) {
2411 /* Surrounding a set in quotes (method used by wfEscapeShellArg) makes the quotes themselves
2412 * appear in the environment variable, so we must use carat escaping as documented in
2413 * http://technet.microsoft.com/en-us/library/cc723564.aspx
2414 * Note however that the quote isn't listed there, but is needed, and the parentheses
2415 * are listed there but doesn't appear to need it.
2417 $envcmd .= "set $k=" . preg_replace( '/([&|()<>^"])/', '^\\1', $v ) . '&& ';
2418 } else {
2419 /* Assume this is a POSIX shell, thus required to accept variable assignments before the command
2420 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_09_01
2422 $envcmd .= "$k=" . escapeshellarg( $v ) . ' ';
2425 $cmd = $envcmd . $cmd;
2427 if ( wfIsWindows() ) {
2428 if ( version_compare( PHP_VERSION, '5.3.0', '<' ) && /* Fixed in 5.3.0 :) */
2429 ( version_compare( PHP_VERSION, '5.2.1', '>=' ) || php_uname( 's' ) == 'Windows NT' ) )
2431 # Hack to work around PHP's flawed invocation of cmd.exe
2432 # http://news.php.net/php.internals/21796
2433 # Windows 9x doesn't accept any kind of quotes
2434 $cmd = '"' . $cmd . '"';
2436 } elseif ( php_uname( 's' ) == 'Linux' ) {
2437 $time = intval( $wgMaxShellTime );
2438 $mem = intval( $wgMaxShellMemory );
2439 $filesize = intval( $wgMaxShellFileSize );
2441 if ( $time > 0 && $mem > 0 ) {
2442 $script = "$IP/bin/ulimit4.sh";
2443 if ( is_executable( $script ) ) {
2444 $cmd = '/bin/bash ' . escapeshellarg( $script ) . " $time $mem $filesize " . escapeshellarg( $cmd );
2448 wfDebug( "wfShellExec: $cmd\n" );
2450 $retval = 1; // error by default?
2451 ob_start();
2452 passthru( $cmd, $retval );
2453 $output = ob_get_contents();
2454 ob_end_clean();
2456 if ( $retval == 127 ) {
2457 wfDebugLog( 'exec', "Possibly missing executable file: $cmd\n" );
2459 return $output;
2463 * Workaround for http://bugs.php.net/bug.php?id=45132
2464 * escapeshellarg() destroys non-ASCII characters if LANG is not a UTF-8 locale
2466 function wfInitShellLocale() {
2467 static $done = false;
2468 if ( $done ) {
2469 return;
2471 $done = true;
2472 global $wgShellLocale;
2473 if ( !wfIniGetBool( 'safe_mode' ) ) {
2474 putenv( "LC_CTYPE=$wgShellLocale" );
2475 setlocale( LC_CTYPE, $wgShellLocale );
2480 * This function works like "use VERSION" in Perl, the program will die with a
2481 * backtrace if the current version of PHP is less than the version provided
2483 * This is useful for extensions which due to their nature are not kept in sync
2484 * with releases, and might depend on other versions of PHP than the main code
2486 * Note: PHP might die due to parsing errors in some cases before it ever
2487 * manages to call this function, such is life
2489 * @see perldoc -f use
2491 * @param $req_ver Mixed: the version to check, can be a string, an integer, or
2492 * a float
2494 function wfUsePHP( $req_ver ) {
2495 $php_ver = PHP_VERSION;
2497 if ( version_compare( $php_ver, (string)$req_ver, '<' ) ) {
2498 throw new MWException( "PHP $req_ver required--this is only $php_ver" );
2503 * This function works like "use VERSION" in Perl except it checks the version
2504 * of MediaWiki, the program will die with a backtrace if the current version
2505 * of MediaWiki is less than the version provided.
2507 * This is useful for extensions which due to their nature are not kept in sync
2508 * with releases
2510 * @see perldoc -f use
2512 * @param $req_ver Mixed: the version to check, can be a string, an integer, or
2513 * a float
2515 function wfUseMW( $req_ver ) {
2516 global $wgVersion;
2518 if ( version_compare( $wgVersion, (string)$req_ver, '<' ) ) {
2519 throw new MWException( "MediaWiki $req_ver required--this is only $wgVersion" );
2524 * Return the final portion of a pathname.
2525 * Reimplemented because PHP5's basename() is buggy with multibyte text.
2526 * http://bugs.php.net/bug.php?id=33898
2528 * PHP's basename() only considers '\' a pathchar on Windows and Netware.
2529 * We'll consider it so always, as we don't want \s in our Unix paths either.
2531 * @param $path String
2532 * @param $suffix String: to remove if present
2533 * @return String
2535 function wfBaseName( $path, $suffix = '' ) {
2536 $encSuffix = ( $suffix == '' )
2537 ? ''
2538 : ( '(?:' . preg_quote( $suffix, '#' ) . ')?' );
2539 $matches = array();
2540 if( preg_match( "#([^/\\\\]*?){$encSuffix}[/\\\\]*$#", $path, $matches ) ) {
2541 return $matches[1];
2542 } else {
2543 return '';
2548 * Generate a relative path name to the given file.
2549 * May explode on non-matching case-insensitive paths,
2550 * funky symlinks, etc.
2552 * @param $path String: absolute destination path including target filename
2553 * @param $from String: Absolute source path, directory only
2554 * @return String
2556 function wfRelativePath( $path, $from ) {
2557 // Normalize mixed input on Windows...
2558 $path = str_replace( '/', DIRECTORY_SEPARATOR, $path );
2559 $from = str_replace( '/', DIRECTORY_SEPARATOR, $from );
2561 // Trim trailing slashes -- fix for drive root
2562 $path = rtrim( $path, DIRECTORY_SEPARATOR );
2563 $from = rtrim( $from, DIRECTORY_SEPARATOR );
2565 $pieces = explode( DIRECTORY_SEPARATOR, dirname( $path ) );
2566 $against = explode( DIRECTORY_SEPARATOR, $from );
2568 if( $pieces[0] !== $against[0] ) {
2569 // Non-matching Windows drive letters?
2570 // Return a full path.
2571 return $path;
2574 // Trim off common prefix
2575 while( count( $pieces ) && count( $against )
2576 && $pieces[0] == $against[0] ) {
2577 array_shift( $pieces );
2578 array_shift( $against );
2581 // relative dots to bump us to the parent
2582 while( count( $against ) ) {
2583 array_unshift( $pieces, '..' );
2584 array_shift( $against );
2587 array_push( $pieces, wfBaseName( $path ) );
2589 return implode( DIRECTORY_SEPARATOR, $pieces );
2593 * Backwards array plus for people who haven't bothered to read the PHP manual
2594 * XXX: will not darn your socks for you.
2596 * @param $array1 Array
2597 * @param [$array2, [...]] Arrays
2598 * @return Array
2600 function wfArrayMerge( $array1/* ... */ ) {
2601 $args = func_get_args();
2602 $args = array_reverse( $args, true );
2603 $out = array();
2604 foreach ( $args as $arg ) {
2605 $out += $arg;
2607 return $out;
2611 * Merge arrays in the style of getUserPermissionsErrors, with duplicate removal
2612 * e.g.
2613 * wfMergeErrorArrays(
2614 * array( array( 'x' ) ),
2615 * array( array( 'x', '2' ) ),
2616 * array( array( 'x' ) ),
2617 * array( array( 'y') )
2618 * );
2619 * returns:
2620 * array(
2621 * array( 'x', '2' ),
2622 * array( 'x' ),
2623 * array( 'y' )
2626 function wfMergeErrorArrays( /*...*/ ) {
2627 $args = func_get_args();
2628 $out = array();
2629 foreach ( $args as $errors ) {
2630 foreach ( $errors as $params ) {
2631 # FIXME: sometimes get nested arrays for $params,
2632 # which leads to E_NOTICEs
2633 $spec = implode( "\t", $params );
2634 $out[$spec] = $params;
2637 return array_values( $out );
2641 * parse_url() work-alike, but non-broken. Differences:
2643 * 1) Does not raise warnings on bad URLs (just returns false)
2644 * 2) Handles protocols that don't use :// (e.g., mailto: and news:) correctly
2645 * 3) Adds a "delimiter" element to the array, either '://' or ':' (see (2))
2647 * @param $url String: a URL to parse
2648 * @return Array: bits of the URL in an associative array, per PHP docs
2650 function wfParseUrl( $url ) {
2651 global $wgUrlProtocols; // Allow all protocols defined in DefaultSettings/LocalSettings.php
2652 wfSuppressWarnings();
2653 $bits = parse_url( $url );
2654 wfRestoreWarnings();
2655 if ( !$bits ) {
2656 return false;
2659 // most of the protocols are followed by ://, but mailto: and sometimes news: not, check for it
2660 if ( in_array( $bits['scheme'] . '://', $wgUrlProtocols ) ) {
2661 $bits['delimiter'] = '://';
2662 } elseif ( in_array( $bits['scheme'] . ':', $wgUrlProtocols ) ) {
2663 $bits['delimiter'] = ':';
2664 // parse_url detects for news: and mailto: the host part of an url as path
2665 // We have to correct this wrong detection
2666 if ( isset( $bits['path'] ) ) {
2667 $bits['host'] = $bits['path'];
2668 $bits['path'] = '';
2670 } else {
2671 return false;
2674 return $bits;
2678 * Make a URL index, appropriate for the el_index field of externallinks.
2680 function wfMakeUrlIndex( $url ) {
2681 $bits = wfParseUrl( $url );
2683 // Reverse the labels in the hostname, convert to lower case
2684 // For emails reverse domainpart only
2685 if ( $bits['scheme'] == 'mailto' ) {
2686 $mailparts = explode( '@', $bits['host'], 2 );
2687 if ( count( $mailparts ) === 2 ) {
2688 $domainpart = strtolower( implode( '.', array_reverse( explode( '.', $mailparts[1] ) ) ) );
2689 } else {
2690 // No domain specified, don't mangle it
2691 $domainpart = '';
2693 $reversedHost = $domainpart . '@' . $mailparts[0];
2694 } else {
2695 $reversedHost = strtolower( implode( '.', array_reverse( explode( '.', $bits['host'] ) ) ) );
2697 // Add an extra dot to the end
2698 // Why? Is it in wrong place in mailto links?
2699 if ( substr( $reversedHost, -1, 1 ) !== '.' ) {
2700 $reversedHost .= '.';
2702 // Reconstruct the pseudo-URL
2703 $prot = $bits['scheme'];
2704 $index = $prot . $bits['delimiter'] . $reversedHost;
2705 // Leave out user and password. Add the port, path, query and fragment
2706 if ( isset( $bits['port'] ) ) {
2707 $index .= ':' . $bits['port'];
2709 if ( isset( $bits['path'] ) ) {
2710 $index .= $bits['path'];
2711 } else {
2712 $index .= '/';
2714 if ( isset( $bits['query'] ) ) {
2715 $index .= '?' . $bits['query'];
2717 if ( isset( $bits['fragment'] ) ) {
2718 $index .= '#' . $bits['fragment'];
2720 return $index;
2724 * Do any deferred updates and clear the list
2726 * @param $commit String: set to 'commit' to commit after every update to
2727 * prevent lock contention
2729 function wfDoUpdates( $commit = '' ) {
2730 global $wgDeferredUpdateList;
2732 wfProfileIn( __METHOD__ );
2734 // No need to get master connections in case of empty updates array
2735 if ( !count( $wgDeferredUpdateList ) ) {
2736 wfProfileOut( __METHOD__ );
2737 return;
2740 $doCommit = $commit == 'commit';
2741 if ( $doCommit ) {
2742 $dbw = wfGetDB( DB_MASTER );
2745 foreach ( $wgDeferredUpdateList as $update ) {
2746 $update->doUpdate();
2748 if ( $doCommit && $dbw->trxLevel() ) {
2749 $dbw->commit();
2753 $wgDeferredUpdateList = array();
2754 wfProfileOut( __METHOD__ );
2758 * Convert an arbitrarily-long digit string from one numeric base
2759 * to another, optionally zero-padding to a minimum column width.
2761 * Supports base 2 through 36; digit values 10-36 are represented
2762 * as lowercase letters a-z. Input is case-insensitive.
2764 * @param $input String: of digits
2765 * @param $sourceBase Integer: 2-36
2766 * @param $destBase Integer: 2-36
2767 * @param $pad Integer: 1 or greater
2768 * @param $lowercase Boolean
2769 * @return String or false on invalid input
2771 function wfBaseConvert( $input, $sourceBase, $destBase, $pad = 1, $lowercase = true ) {
2772 $input = strval( $input );
2773 if( $sourceBase < 2 ||
2774 $sourceBase > 36 ||
2775 $destBase < 2 ||
2776 $destBase > 36 ||
2777 $pad < 1 ||
2778 $sourceBase != intval( $sourceBase ) ||
2779 $destBase != intval( $destBase ) ||
2780 $pad != intval( $pad ) ||
2781 !is_string( $input ) ||
2782 $input == '' ) {
2783 return false;
2785 $digitChars = ( $lowercase ) ? '0123456789abcdefghijklmnopqrstuvwxyz' : '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
2786 $inDigits = array();
2787 $outChars = '';
2789 // Decode and validate input string
2790 $input = strtolower( $input );
2791 for( $i = 0; $i < strlen( $input ); $i++ ) {
2792 $n = strpos( $digitChars, $input{$i} );
2793 if( $n === false || $n > $sourceBase ) {
2794 return false;
2796 $inDigits[] = $n;
2799 // Iterate over the input, modulo-ing out an output digit
2800 // at a time until input is gone.
2801 while( count( $inDigits ) ) {
2802 $work = 0;
2803 $workDigits = array();
2805 // Long division...
2806 foreach( $inDigits as $digit ) {
2807 $work *= $sourceBase;
2808 $work += $digit;
2810 if( $work < $destBase ) {
2811 // Gonna need to pull another digit.
2812 if( count( $workDigits ) ) {
2813 // Avoid zero-padding; this lets us find
2814 // the end of the input very easily when
2815 // length drops to zero.
2816 $workDigits[] = 0;
2818 } else {
2819 // Finally! Actual division!
2820 $workDigits[] = intval( $work / $destBase );
2822 // Isn't it annoying that most programming languages
2823 // don't have a single divide-and-remainder operator,
2824 // even though the CPU implements it that way?
2825 $work = $work % $destBase;
2829 // All that division leaves us with a remainder,
2830 // which is conveniently our next output digit.
2831 $outChars .= $digitChars[$work];
2833 // And we continue!
2834 $inDigits = $workDigits;
2837 while( strlen( $outChars ) < $pad ) {
2838 $outChars .= '0';
2841 return strrev( $outChars );
2845 * Create an object with a given name and an array of construct parameters
2846 * @param $name String
2847 * @param $p Array: parameters
2848 * @deprecated
2850 function wfCreateObject( $name, $p ) {
2851 return MWFunction::newObj( $name, $p );
2854 function wfHttpOnlySafe() {
2855 global $wgHttpOnlyBlacklist;
2856 if( !version_compare( '5.2', PHP_VERSION, '<' ) ) {
2857 return false;
2860 if( isset( $_SERVER['HTTP_USER_AGENT'] ) ) {
2861 foreach( $wgHttpOnlyBlacklist as $regex ) {
2862 if( preg_match( $regex, $_SERVER['HTTP_USER_AGENT'] ) ) {
2863 return false;
2868 return true;
2872 * Initialise php session
2874 function wfSetupSession( $sessionId = false ) {
2875 global $wgSessionsInMemcached, $wgCookiePath, $wgCookieDomain,
2876 $wgCookieSecure, $wgCookieHttpOnly, $wgSessionHandler;
2877 if( $wgSessionsInMemcached ) {
2878 require_once( 'MemcachedSessions.php' );
2879 } elseif( $wgSessionHandler && $wgSessionHandler != ini_get( 'session.save_handler' ) ) {
2880 # Only set this if $wgSessionHandler isn't null and session.save_handler
2881 # hasn't already been set to the desired value (that causes errors)
2882 ini_set( 'session.save_handler', $wgSessionHandler );
2884 $httpOnlySafe = wfHttpOnlySafe();
2885 wfDebugLog( 'cookie',
2886 'session_set_cookie_params: "' . implode( '", "',
2887 array(
2889 $wgCookiePath,
2890 $wgCookieDomain,
2891 $wgCookieSecure,
2892 $httpOnlySafe && $wgCookieHttpOnly ) ) . '"' );
2893 if( $httpOnlySafe && $wgCookieHttpOnly ) {
2894 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookieHttpOnly );
2895 } else {
2896 // PHP 5.1 throws warnings if you pass the HttpOnly parameter for 5.2.
2897 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
2899 session_cache_limiter( 'private, must-revalidate' );
2900 if ( $sessionId ) {
2901 session_id( $sessionId );
2903 wfSuppressWarnings();
2904 session_start();
2905 wfRestoreWarnings();
2909 * Get an object from the precompiled serialized directory
2911 * @return Mixed: the variable on success, false on failure
2913 function wfGetPrecompiledData( $name ) {
2914 global $IP;
2916 $file = "$IP/serialized/$name";
2917 if ( file_exists( $file ) ) {
2918 $blob = file_get_contents( $file );
2919 if ( $blob ) {
2920 return unserialize( $blob );
2923 return false;
2926 function wfGetCaller( $level = 2 ) {
2927 $backtrace = wfDebugBacktrace();
2928 if ( isset( $backtrace[$level] ) ) {
2929 return wfFormatStackFrame( $backtrace[$level] );
2930 } else {
2931 $caller = 'unknown';
2933 return $caller;
2937 * Return a string consisting of callers in the stack. Useful sometimes
2938 * for profiling specific points.
2940 * @param $limit The maximum depth of the stack frame to return, or false for
2941 * the entire stack.
2943 function wfGetAllCallers( $limit = 3 ) {
2944 $trace = array_reverse( wfDebugBacktrace() );
2945 if ( !$limit || $limit > count( $trace ) - 1 ) {
2946 $limit = count( $trace ) - 1;
2948 $trace = array_slice( $trace, -$limit - 1, $limit );
2949 return implode( '/', array_map( 'wfFormatStackFrame', $trace ) );
2953 * Return a string representation of frame
2955 function wfFormatStackFrame( $frame ) {
2956 return isset( $frame['class'] ) ?
2957 $frame['class'] . '::' . $frame['function'] :
2958 $frame['function'];
2962 * Get a cache key
2964 function wfMemcKey( /*... */ ) {
2965 $args = func_get_args();
2966 $key = wfWikiID() . ':' . implode( ':', $args );
2967 $key = str_replace( ' ', '_', $key );
2968 return $key;
2972 * Get a cache key for a foreign DB
2974 function wfForeignMemcKey( $db, $prefix /*, ... */ ) {
2975 $args = array_slice( func_get_args(), 2 );
2976 if ( $prefix ) {
2977 $key = "$db-$prefix:" . implode( ':', $args );
2978 } else {
2979 $key = $db . ':' . implode( ':', $args );
2981 return $key;
2985 * Get an ASCII string identifying this wiki
2986 * This is used as a prefix in memcached keys
2988 function wfWikiID() {
2989 global $wgDBprefix, $wgDBname;
2990 if ( $wgDBprefix ) {
2991 return "$wgDBname-$wgDBprefix";
2992 } else {
2993 return $wgDBname;
2998 * Split a wiki ID into DB name and table prefix
3000 function wfSplitWikiID( $wiki ) {
3001 $bits = explode( '-', $wiki, 2 );
3002 if ( count( $bits ) < 2 ) {
3003 $bits[] = '';
3005 return $bits;
3009 * Get a Database object.
3010 * @param $db Integer: index of the connection to get. May be DB_MASTER for the
3011 * master (for write queries), DB_SLAVE for potentially lagged read
3012 * queries, or an integer >= 0 for a particular server.
3014 * @param $groups Mixed: query groups. An array of group names that this query
3015 * belongs to. May contain a single string if the query is only
3016 * in one group.
3018 * @param $wiki String: the wiki ID, or false for the current wiki
3020 * Note: multiple calls to wfGetDB(DB_SLAVE) during the course of one request
3021 * will always return the same object, unless the underlying connection or load
3022 * balancer is manually destroyed.
3024 * @return DatabaseBase
3026 function &wfGetDB( $db, $groups = array(), $wiki = false ) {
3027 return wfGetLB( $wiki )->getConnection( $db, $groups, $wiki );
3031 * Get a load balancer object.
3033 * @param $wiki String: wiki ID, or false for the current wiki
3034 * @return LoadBalancer
3036 function wfGetLB( $wiki = false ) {
3037 return wfGetLBFactory()->getMainLB( $wiki );
3041 * Get the load balancer factory object
3042 * @return LBFactory
3044 function &wfGetLBFactory() {
3045 return LBFactory::singleton();
3049 * Find a file.
3050 * Shortcut for RepoGroup::singleton()->findFile()
3051 * @param $title String or Title object
3052 * @param $options Associative array of options:
3053 * time: requested time for an archived image, or false for the
3054 * current version. An image object will be returned which was
3055 * created at the specified time.
3057 * ignoreRedirect: If true, do not follow file redirects
3059 * private: If true, return restricted (deleted) files if the current
3060 * user is allowed to view them. Otherwise, such files will not
3061 * be found.
3063 * bypassCache: If true, do not use the process-local cache of File objects
3065 * @return File, or false if the file does not exist
3067 function wfFindFile( $title, $options = array() ) {
3068 return RepoGroup::singleton()->findFile( $title, $options );
3072 * Get an object referring to a locally registered file.
3073 * Returns a valid placeholder object if the file does not exist.
3074 * @param $title Title or String
3075 * @return File, or null if passed an invalid Title
3077 function wfLocalFile( $title ) {
3078 return RepoGroup::singleton()->getLocalRepo()->newFile( $title );
3082 * Should low-performance queries be disabled?
3084 * @return Boolean
3085 * @codeCoverageIgnore
3087 function wfQueriesMustScale() {
3088 global $wgMiserMode;
3089 return $wgMiserMode
3090 || ( SiteStats::pages() > 100000
3091 && SiteStats::edits() > 1000000
3092 && SiteStats::users() > 10000 );
3096 * Get the path to a specified script file, respecting file
3097 * extensions; this is a wrapper around $wgScriptExtension etc.
3099 * @param $script String: script filename, sans extension
3100 * @return String
3102 function wfScript( $script = 'index' ) {
3103 global $wgScriptPath, $wgScriptExtension;
3104 return "{$wgScriptPath}/{$script}{$wgScriptExtension}";
3108 * Get the script URL.
3110 * @return script URL
3112 function wfGetScriptUrl() {
3113 if( isset( $_SERVER['SCRIPT_NAME'] ) ) {
3115 # as it was called, minus the query string.
3117 # Some sites use Apache rewrite rules to handle subdomains,
3118 # and have PHP set up in a weird way that causes PHP_SELF
3119 # to contain the rewritten URL instead of the one that the
3120 # outside world sees.
3122 # If in this mode, use SCRIPT_URL instead, which mod_rewrite
3123 # provides containing the "before" URL.
3124 return $_SERVER['SCRIPT_NAME'];
3125 } else {
3126 return $_SERVER['URL'];
3131 * Convenience function converts boolean values into "true"
3132 * or "false" (string) values
3134 * @param $value Boolean
3135 * @return String
3137 function wfBoolToStr( $value ) {
3138 return $value ? 'true' : 'false';
3142 * Load an extension messages file
3143 * @deprecated in 1.16, warnings in 1.18, remove in 1.20
3144 * @codeCoverageIgnore
3146 function wfLoadExtensionMessages( $extensionName, $langcode = false ) {
3147 wfDeprecated( __FUNCTION__ );
3151 * Get a platform-independent path to the null file, e.g.
3152 * /dev/null
3154 * @return string
3156 function wfGetNull() {
3157 return wfIsWindows()
3158 ? 'NUL'
3159 : '/dev/null';
3163 * Displays a maxlag error
3165 * @param $host String: server that lags the most
3166 * @param $lag Integer: maxlag (actual)
3167 * @param $maxLag Integer: maxlag (requested)
3169 function wfMaxlagError( $host, $lag, $maxLag ) {
3170 global $wgShowHostnames;
3171 header( 'HTTP/1.1 503 Service Unavailable' );
3172 header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
3173 header( 'X-Database-Lag: ' . intval( $lag ) );
3174 header( 'Content-Type: text/plain' );
3175 if( $wgShowHostnames ) {
3176 echo "Waiting for $host: $lag seconds lagged\n";
3177 } else {
3178 echo "Waiting for a database server: $lag seconds lagged\n";
3183 * Throws a warning that $function is deprecated
3184 * @param $function String
3185 * @return null
3187 function wfDeprecated( $function ) {
3188 static $functionsWarned = array();
3189 if ( !isset( $functionsWarned[$function] ) ) {
3190 $functionsWarned[$function] = true;
3191 wfWarn( "Use of $function is deprecated.", 2 );
3196 * Send a warning either to the debug log or in a PHP error depending on
3197 * $wgDevelopmentWarnings
3199 * @param $msg String: message to send
3200 * @param $callerOffset Integer: number of itmes to go back in the backtrace to
3201 * find the correct caller (1 = function calling wfWarn, ...)
3202 * @param $level Integer: PHP error level; only used when $wgDevelopmentWarnings
3203 * is true
3205 function wfWarn( $msg, $callerOffset = 1, $level = E_USER_NOTICE ) {
3206 $callers = wfDebugBacktrace();
3207 if( isset( $callers[$callerOffset + 1] ) ){
3208 $callerfunc = $callers[$callerOffset + 1];
3209 $callerfile = $callers[$callerOffset];
3210 if( isset( $callerfile['file'] ) && isset( $callerfile['line'] ) ) {
3211 $file = $callerfile['file'] . ' at line ' . $callerfile['line'];
3212 } else {
3213 $file = '(internal function)';
3215 $func = '';
3216 if( isset( $callerfunc['class'] ) ) {
3217 $func .= $callerfunc['class'] . '::';
3219 if( isset( $callerfunc['function'] ) ) {
3220 $func .= $callerfunc['function'];
3222 $msg .= " [Called from $func in $file]";
3225 global $wgDevelopmentWarnings;
3226 if ( $wgDevelopmentWarnings ) {
3227 trigger_error( $msg, $level );
3228 } else {
3229 wfDebug( "$msg\n" );
3234 * Sleep until the worst slave's replication lag is less than or equal to
3235 * $maxLag, in seconds. Use this when updating very large numbers of rows, as
3236 * in maintenance scripts, to avoid causing too much lag. Of course, this is
3237 * a no-op if there are no slaves.
3239 * Every time the function has to wait for a slave, it will print a message to
3240 * that effect (and then sleep for a little while), so it's probably not best
3241 * to use this outside maintenance scripts in its present form.
3243 * @param $maxLag Integer
3244 * @param $wiki mixed Wiki identifier accepted by wfGetLB
3245 * @return null
3247 function wfWaitForSlaves( $maxLag, $wiki = false ) {
3248 if( $maxLag ) {
3249 $lb = wfGetLB( $wiki );
3250 list( $host, $lag ) = $lb->getMaxLag( $wiki );
3251 while( $lag > $maxLag ) {
3252 wfSuppressWarnings();
3253 $name = gethostbyaddr( $host );
3254 wfRestoreWarnings();
3255 if( $name !== false ) {
3256 $host = $name;
3258 print "Waiting for $host (lagged $lag seconds)...\n";
3259 sleep( $maxLag );
3260 list( $host, $lag ) = $lb->getMaxLag();
3266 * Used to be used for outputting text in the installer/updater
3267 * @deprecated Warnings in 1.19, removal in 1.20
3269 function wfOut( $s ) {
3270 global $wgCommandLineMode;
3271 if ( $wgCommandLineMode && !defined( 'MEDIAWIKI_INSTALL' ) ) {
3272 echo $s;
3273 } else {
3274 echo htmlspecialchars( $s );
3276 flush();
3280 * Count down from $n to zero on the terminal, with a one-second pause
3281 * between showing each number. For use in command-line scripts.
3282 * @codeCoverageIgnore
3284 function wfCountDown( $n ) {
3285 for ( $i = $n; $i >= 0; $i-- ) {
3286 if ( $i != $n ) {
3287 echo str_repeat( "\x08", strlen( $i + 1 ) );
3289 echo $i;
3290 flush();
3291 if ( $i ) {
3292 sleep( 1 );
3295 echo "\n";
3299 * Generate a random 32-character hexadecimal token.
3300 * @param $salt Mixed: some sort of salt, if necessary, to add to random
3301 * characters before hashing.
3302 * @codeCoverageIgnore
3304 function wfGenerateToken( $salt = '' ) {
3305 $salt = serialize( $salt );
3306 return md5( mt_rand( 0, 0x7fffffff ) . $salt );
3310 * Replace all invalid characters with -
3311 * @param $name Mixed: filename to process
3313 function wfStripIllegalFilenameChars( $name ) {
3314 global $wgIllegalFileChars;
3315 $name = wfBaseName( $name );
3316 $name = preg_replace(
3317 "/[^" . Title::legalChars() . "]" .
3318 ( $wgIllegalFileChars ? "|[" . $wgIllegalFileChars . "]" : '' ) .
3319 "/",
3320 '-',
3321 $name
3323 return $name;
3327 * Insert array into another array after the specified *KEY*
3328 * @param $array Array: The array.
3329 * @param $insert Array: The array to insert.
3330 * @param $after Mixed: The key to insert after
3332 function wfArrayInsertAfter( $array, $insert, $after ) {
3333 // Find the offset of the element to insert after.
3334 $keys = array_keys( $array );
3335 $offsetByKey = array_flip( $keys );
3337 $offset = $offsetByKey[$after];
3339 // Insert at the specified offset
3340 $before = array_slice( $array, 0, $offset + 1, true );
3341 $after = array_slice( $array, $offset + 1, count( $array ) - $offset, true );
3343 $output = $before + $insert + $after;
3345 return $output;
3348 /* Recursively converts the parameter (an object) to an array with the same data */
3349 function wfObjectToArray( $object, $recursive = true ) {
3350 $array = array();
3351 foreach ( get_object_vars( $object ) as $key => $value ) {
3352 if ( is_object( $value ) && $recursive ) {
3353 $value = wfObjectToArray( $value );
3356 $array[$key] = $value;
3359 return $array;
3363 * Set PHP's memory limit to the larger of php.ini or $wgMemoryLimit;
3364 * @return Integer value memory was set to.
3366 function wfMemoryLimit() {
3367 global $wgMemoryLimit;
3368 $memlimit = wfShorthandToInteger( ini_get( 'memory_limit' ) );
3369 if( $memlimit != -1 ) {
3370 $conflimit = wfShorthandToInteger( $wgMemoryLimit );
3371 if( $conflimit == -1 ) {
3372 wfDebug( "Removing PHP's memory limit\n" );
3373 wfSuppressWarnings();
3374 ini_set( 'memory_limit', $conflimit );
3375 wfRestoreWarnings();
3376 return $conflimit;
3377 } elseif ( $conflimit > $memlimit ) {
3378 wfDebug( "Raising PHP's memory limit to $conflimit bytes\n" );
3379 wfSuppressWarnings();
3380 ini_set( 'memory_limit', $conflimit );
3381 wfRestoreWarnings();
3382 return $conflimit;
3385 return $memlimit;
3389 * Converts shorthand byte notation to integer form
3390 * @param $string String
3391 * @return Integer
3393 function wfShorthandToInteger( $string = '' ) {
3394 $string = trim( $string );
3395 if( $string === '' ) {
3396 return -1;
3398 $last = $string[strlen( $string ) - 1];
3399 $val = intval( $string );
3400 switch( $last ) {
3401 case 'g':
3402 case 'G':
3403 $val *= 1024;
3404 // break intentionally missing
3405 case 'm':
3406 case 'M':
3407 $val *= 1024;
3408 // break intentionally missing
3409 case 'k':
3410 case 'K':
3411 $val *= 1024;
3414 return $val;
3418 * Get the normalised IETF language tag
3419 * See unit test for examples.
3420 * @param $code String: The language code.
3421 * @return $langCode String: The language code which complying with BCP 47 standards.
3423 function wfBCP47( $code ) {
3424 $codeSegment = explode( '-', $code );
3425 foreach ( $codeSegment as $segNo => $seg ) {
3426 if ( count( $codeSegment ) > 0 ) {
3427 // when previous segment is x, it is a private segment and should be lc
3428 if( $segNo > 0 && strtolower( $codeSegment[($segNo - 1)] ) == 'x') {
3429 $codeBCP[$segNo] = strtolower( $seg );
3430 // ISO 3166 country code
3431 } elseif ( ( strlen( $seg ) == 2 ) && ( $segNo > 0 ) ) {
3432 $codeBCP[$segNo] = strtoupper( $seg );
3433 // ISO 15924 script code
3434 } elseif ( ( strlen( $seg ) == 4 ) && ( $segNo > 0 ) ) {
3435 $codeBCP[$segNo] = ucfirst( strtolower( $seg ) );
3436 // Use lowercase for other cases
3437 } else {
3438 $codeBCP[$segNo] = strtolower( $seg );
3440 } else {
3441 // Use lowercase for single segment
3442 $codeBCP[$segNo] = strtolower( $seg );
3445 $langCode = implode( '-', $codeBCP );
3446 return $langCode;
3449 function wfArrayMap( $function, $input ) {
3450 $ret = array_map( $function, $input );
3451 foreach ( $ret as $key => $value ) {
3452 $taint = istainted( $input[$key] );
3453 if ( $taint ) {
3454 taint( $ret[$key], $taint );
3457 return $ret;