3 if ( !defined( 'MEDIAWIKI' ) ) {
4 die( "This file is part of MediaWiki, it is not a valid entry point" );
8 * Global functions used everywhere
11 require_once dirname(__FILE__
) . '/normal/UtfNormalUtil.php';
12 require_once dirname(__FILE__
) . '/XmlFunctions.php';
14 // Hide compatibility functions from Doxygen
18 * Compatibility functions
20 * We more or less support PHP 5.0.x and up.
21 * Re-implementations of newer functions or functions in non-standard
22 * PHP extensions may be included here.
24 if( !function_exists('iconv') ) {
25 # iconv support is not in the default configuration and so may not be present.
26 # Assume will only ever use utf-8 and iso-8859-1.
27 # This will *not* work in all circumstances.
28 function iconv( $from, $to, $string ) {
29 if(strcasecmp( $from, $to ) == 0) return $string;
30 if(strcasecmp( $from, 'utf-8' ) == 0) return utf8_decode( $string );
31 if(strcasecmp( $to, 'utf-8' ) == 0) return utf8_encode( $string );
36 # UTF-8 substr function based on a PHP manual comment
37 if ( !function_exists( 'mb_substr' ) ) {
38 function mb_substr( $str, $start ) {
40 preg_match_all( '/./us', $str, $ar );
42 if( func_num_args() >= 3 ) {
43 $end = func_get_arg( 2 );
44 return join( '', array_slice( $ar[0], $start, $end ) );
46 return join( '', array_slice( $ar[0], $start ) );
51 if ( !function_exists( 'mb_strlen' ) ) {
53 * Fallback implementation of mb_strlen, hardcoded to UTF-8.
55 * @param string $enc optional encoding; ignored
58 function mb_strlen( $str, $enc="" ) {
59 $counts = count_chars( $str );
63 for( $i = 0; $i < 0x80; $i++
) {
64 $total +
= $counts[$i];
67 // Count multibyte sequence heads
68 for( $i = 0xc0; $i < 0xff; $i++
) {
69 $total +
= $counts[$i];
76 if( !function_exists( 'mb_strpos' ) ) {
78 * Fallback implementation of mb_strpos, hardcoded to UTF-8.
79 * @param string $haystack
80 * @param string $needle
81 * @param string $offset optional start position
82 * @param string $encoding optional encoding; ignored
85 function mb_strpos( $haystack, $needle, $offset = 0, $encoding="" ) {
86 $needle = preg_quote( $needle, '/' );
89 preg_match( '/'.$needle.'/u', $haystack, $ar, PREG_OFFSET_CAPTURE
, $offset );
91 if( isset( $ar[0][1] ) ) {
99 if( !function_exists( 'mb_strrpos' ) ) {
101 * Fallback implementation of mb_strrpos, hardcoded to UTF-8.
102 * @param string $haystack
103 * @param string $needle
104 * @param string $offset optional start position
105 * @param string $encoding optional encoding; ignored
108 function mb_strrpos( $haystack, $needle, $offset = 0, $encoding = "" ) {
109 $needle = preg_quote( $needle, '/' );
112 preg_match_all( '/'.$needle.'/u', $haystack, $ar, PREG_OFFSET_CAPTURE
, $offset );
114 if( isset( $ar[0] ) && count( $ar[0] ) > 0 &&
115 isset( $ar[0][count($ar[0])-1][1] ) ) {
116 return $ar[0][count($ar[0])-1][1];
123 if ( !function_exists( 'array_diff_key' ) ) {
125 * Exists in PHP 5.1.0+
126 * Not quite compatible, two-argument version only
127 * Null values will cause problems due to this use of isset()
129 function array_diff_key( $left, $right ) {
131 foreach ( $left as $key => $unused ) {
132 if ( isset( $right[$key] ) ) {
133 unset( $result[$key] );
140 // Support for Wietse Venema's taint feature
141 if ( !function_exists( 'istainted' ) ) {
142 function istainted( $var ) {
145 function taint( $var, $level = 0 ) {}
146 function untaint( $var, $level = 0 ) {}
147 define( 'TC_HTML', 1 );
148 define( 'TC_SHELL', 1 );
149 define( 'TC_MYSQL', 1 );
150 define( 'TC_PCRE', 1 );
151 define( 'TC_SELF', 1 );
157 * Like array_diff( $a, $b ) except that it works with two-dimensional arrays.
159 function wfArrayDiff2( $a, $b ) {
160 return array_udiff( $a, $b, 'wfArrayDiff2_cmp' );
162 function wfArrayDiff2_cmp( $a, $b ) {
163 if ( !is_array( $a ) ) {
164 return strcmp( $a, $b );
165 } elseif ( count( $a ) !== count( $b ) ) {
166 return count( $a ) < count( $b ) ?
-1 : 1;
170 while( ( list( $keyA, $valueA ) = each( $a ) ) && ( list( $keyB, $valueB ) = each( $b ) ) ) {
171 $cmp = strcmp( $valueA, $valueB );
181 * Wrapper for clone(), for compatibility with PHP4-friendly extensions.
182 * PHP 5 won't let you declare a 'clone' function, even conditionally,
183 * so it has to be a wrapper with a different name.
185 function wfClone( $object ) {
186 return clone( $object );
190 * Seed Mersenne Twister
191 * No-op for compatibility; only necessary in PHP < 4.2.0
193 function wfSeedRandom() {
198 * Get a random decimal value between 0 and 1, in a way
199 * not likely to give duplicate values for any realistic
200 * number of articles.
204 function wfRandom() {
205 # The maximum random value is "only" 2^31-1, so get two random
206 # values to reduce the chance of dupes
207 $max = mt_getrandmax() +
1;
208 $rand = number_format( (mt_rand() * $max +
mt_rand())
209 / $max / $max, 12, '.', '' );
214 * We want some things to be included as literal characters in our title URLs
215 * for prettiness, which urlencode encodes by default. According to RFC 1738,
216 * all of the following should be safe:
220 * But + is not safe because it's used to indicate a space; &= are only safe in
221 * paths and not in queries (and we don't distinguish here); ' seems kind of
222 * scary; and urlencode() doesn't touch -_. to begin with. Plus, although /
223 * is reserved, we don't care. So the list we unescape is:
227 * %2F in the page titles seems to fatally break for some reason.
232 function wfUrlencode( $s ) {
233 $s = urlencode( $s );
235 array( '%3B','%3A','%40','%24','%21','%2A','%28','%29','%2C','%2F' ),
236 array( ';', ':', '@', '$', '!', '*', '(', ')', ',', '/' ),
244 * Sends a line to the debug log if enabled or, optionally, to a comment in output.
245 * In normal operation this is a NOP.
247 * Controlling globals:
248 * $wgDebugLogFile - points to the log file
249 * $wgProfileOnly - if set, normal debug messages will not be recorded.
250 * $wgDebugRawPage - if false, 'action=raw' hits will not result in debug output.
251 * $wgDebugComments - if on, some debug items may appear in comments in the HTML output.
253 * @param $text String
254 * @param $logonly Bool: set true to avoid appearing in HTML when $wgDebugComments is set
256 function wfDebug( $text, $logonly = false ) {
257 global $wgOut, $wgDebugLogFile, $wgDebugComments, $wgProfileOnly, $wgDebugRawPage;
258 global $wgDebugLogPrefix;
259 static $recursion = 0;
261 static $cache = array(); // Cache of unoutputted messages
263 # Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
264 if ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' && !$wgDebugRawPage ) {
268 if ( $wgDebugComments && !$logonly ) {
271 if ( !isset( $wgOut ) ) {
274 if ( !StubObject
::isRealObject( $wgOut ) ) {
283 // add the message and possible cached ones to the output
284 array_map( array( $wgOut, 'debug' ), $cache );
287 if ( '' != $wgDebugLogFile && !$wgProfileOnly ) {
288 # Strip unprintables; they can switch terminal modes when binary data
289 # gets dumped, which is pretty annoying.
290 $text = preg_replace( '![\x00-\x08\x0b\x0c\x0e-\x1f]!', ' ', $text );
291 $text = $wgDebugLogPrefix . $text;
292 wfErrorLog( $text, $wgDebugLogFile );
297 * Send a line giving PHP memory usage.
298 * @param $exact Bool : print exact values instead of kilobytes (default: false)
300 function wfDebugMem( $exact = false ) {
301 $mem = memory_get_usage();
303 $mem = floor( $mem / 1024 ) . ' kilobytes';
307 wfDebug( "Memory usage: $mem\n" );
311 * Send a line to a supplementary debug log file, if configured, or main debug log if not.
312 * $wgDebugLogGroups[$logGroup] should be set to a filename to send to a separate log.
314 * @param $logGroup String
315 * @param $text String
316 * @param $public Bool: whether to log the event in the public log if no private
317 * log file is specified, (default true)
319 function wfDebugLog( $logGroup, $text, $public = true ) {
320 global $wgDebugLogGroups, $wgShowHostnames;
321 $text = trim($text)."\n";
322 if( isset( $wgDebugLogGroups[$logGroup] ) ) {
323 $time = wfTimestamp( TS_DB
);
325 if ( $wgShowHostnames ) {
326 $host = wfHostname();
330 wfErrorLog( "$time $host $wiki: $text", $wgDebugLogGroups[$logGroup] );
331 } else if ( $public === true ) {
332 wfDebug( $text, true );
337 * Log for database errors
338 * @param $text String: database error message.
340 function wfLogDBError( $text ) {
341 global $wgDBerrorLog, $wgDBname;
342 if ( $wgDBerrorLog ) {
343 $host = trim(`hostname`
);
344 $text = date('D M j G:i:s T Y') . "\t$host\t$wgDBname\t$text";
345 wfErrorLog( $text, $wgDBerrorLog );
350 * Log to a file without getting "file size exceeded" signals.
352 * Can also log to TCP or UDP with the syntax udp://host:port/prefix. This will
353 * send lines to the specified port, prefixed by the specified prefix and a space.
355 function wfErrorLog( $text, $file ) {
356 if ( substr( $file, 0, 4 ) == 'udp:' ) {
357 if ( preg_match( '!^(tcp|udp):(?://)?\[([0-9a-fA-F:]+)\]:(\d+)(?:/(.*))?$!', $file, $m ) ) {
358 // IPv6 bracketed host
362 $prefix = isset( $m[4] ) ?
$m[4] : false;
363 } elseif ( preg_match( '!^(tcp|udp):(?://)?([a-zA-Z0-9.-]+):(\d+)(?:/(.*))?$!', $file, $m ) ) {
367 $prefix = isset( $m[4] ) ?
$m[4] : false;
369 throw new MWException( __METHOD__
.": Invalid UDP specification" );
371 // Clean it up for the multiplexer
372 if ( strval( $prefix ) !== '' ) {
373 $text = preg_replace( '/^/m', $prefix . ' ', $text );
374 if ( substr( $text, -1 ) != "\n" ) {
379 $sock = fsockopen( "$protocol://$host", $port );
383 fwrite( $sock, $text );
386 wfSuppressWarnings();
387 $exists = file_exists( $file );
388 $size = $exists ?
filesize( $file ) : false;
389 if ( !$exists ||
( $size !== false && $size +
strlen( $text ) < 0x7fffffff ) ) {
390 error_log( $text, 3, $file );
399 function wfLogProfilingData() {
400 global $wgRequestTime, $wgDebugLogFile, $wgDebugRawPage, $wgRequest;
401 global $wgProfiler, $wgProfileLimit, $wgUser;
402 # Profiling must actually be enabled...
403 if( !isset( $wgProfiler ) ) return;
404 # Get total page request time
406 $elapsed = $now - $wgRequestTime;
407 # Only show pages that longer than $wgProfileLimit time (default is 0)
408 if( $elapsed <= $wgProfileLimit ) return;
409 $prof = wfGetProfilingOutput( $wgRequestTime, $elapsed );
411 if( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) )
412 $forward = ' forwarded for ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
413 if( !empty( $_SERVER['HTTP_CLIENT_IP'] ) )
414 $forward .= ' client IP ' . $_SERVER['HTTP_CLIENT_IP'];
415 if( !empty( $_SERVER['HTTP_FROM'] ) )
416 $forward .= ' from ' . $_SERVER['HTTP_FROM'];
418 $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
419 // Don't unstub $wgUser at this late stage just for statistics purposes
420 if( StubObject
::isRealObject($wgUser) && $wgUser->isAnon() )
422 $log = sprintf( "%s\t%04.3f\t%s\n",
423 gmdate( 'YmdHis' ), $elapsed,
424 urldecode( $wgRequest->getRequestURL() . $forward ) );
425 if ( '' != $wgDebugLogFile && ( $wgRequest->getVal('action') != 'raw' ||
$wgDebugRawPage ) ) {
426 wfErrorLog( $log . $prof, $wgDebugLogFile );
431 * Check if the wiki read-only lock file is present. This can be used to lock
432 * off editing functions, but doesn't guarantee that the database will not be
436 function wfReadOnly() {
437 global $wgReadOnlyFile, $wgReadOnly;
439 if ( !is_null( $wgReadOnly ) ) {
440 return (bool)$wgReadOnly;
442 if ( '' == $wgReadOnlyFile ) {
445 // Set $wgReadOnly for faster access next time
446 if ( is_file( $wgReadOnlyFile ) ) {
447 $wgReadOnly = file_get_contents( $wgReadOnlyFile );
451 return (bool)$wgReadOnly;
454 function wfReadOnlyReason() {
461 * Return a Language object from $langcode
462 * @param $langcode Mixed: either:
463 * - a Language object
464 * - code of the language to get the message for, if it is
465 * a valid code create a language for that language, if
466 * it is a string but not a valid code then make a basic
468 * - a boolean: if it's false then use the current users
469 * language (as a fallback for the old parameter
470 * functionality), or if it is true then use the wikis
471 * @return Language object
473 function wfGetLangObj( $langcode = false ){
474 # Identify which language to get or create a language object for.
475 if( $langcode instanceof Language
)
476 # Great, we already have the object!
480 if( $langcode === $wgContLang->getCode() ||
$langcode === true )
481 # $langcode is the language code of the wikis content language object.
482 # or it is a boolean and value is true
486 if( $langcode === $wgLang->getCode() ||
$langcode === false )
487 # $langcode is the language code of user language object.
488 # or it was a boolean and value is false
491 $validCodes = array_keys( Language
::getLanguageNames() );
492 if( in_array( $langcode, $validCodes ) )
493 # $langcode corresponds to a valid language.
494 return Language
::factory( $langcode );
496 # $langcode is a string, but not a valid language code; use content language.
497 wfDebug( "Invalid language code passed to wfGetLangObj, falling back to content language.\n" );
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 by 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 over 70 messages in order to, e.g., fix a link in every
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 );
556 if( is_array( $wgForceUIMsgAsContentMsg ) &&
557 in_array( $key, $wgForceUIMsgAsContentMsg ) )
559 return wfMsgReal( $key, $args, true, $forcontent );
563 * Same as above except doesn't transform the message
565 function wfMsgForContentNoTrans( $key ) {
566 global $wgForceUIMsgAsContentMsg;
567 $args = func_get_args();
568 array_shift( $args );
570 if( is_array( $wgForceUIMsgAsContentMsg ) &&
571 in_array( $key, $wgForceUIMsgAsContentMsg ) )
573 return wfMsgReal( $key, $args, true, $forcontent, false );
577 * Get a message from the language file, for the UI elements
579 function wfMsgNoDB( $key ) {
580 $args = func_get_args();
581 array_shift( $args );
582 return wfMsgReal( $key, $args, false );
586 * Get a message from the language file, for the content
588 function wfMsgNoDBForContent( $key ) {
589 global $wgForceUIMsgAsContentMsg;
590 $args = func_get_args();
591 array_shift( $args );
593 if( is_array( $wgForceUIMsgAsContentMsg ) &&
594 in_array( $key, $wgForceUIMsgAsContentMsg ) )
596 return wfMsgReal( $key, $args, false, $forcontent );
601 * Really get a message
602 * @param $key String: key to get.
604 * @param $useDB Boolean
605 * @param $transform Boolean: Whether or not to transform the message.
606 * @param $forContent Boolean
607 * @return String: the requested message.
609 function wfMsgReal( $key, $args, $useDB = true, $forContent = false, $transform = true ) {
610 wfProfileIn( __METHOD__
);
611 $message = wfMsgGetKey( $key, $useDB, $forContent, $transform );
612 $message = wfMsgReplaceArgs( $message, $args );
613 wfProfileOut( __METHOD__
);
618 * This function provides the message source for messages to be edited which are *not* stored in the database.
619 * @param $key String:
621 function wfMsgWeirdKey( $key ) {
622 $source = wfMsgGetKey( $key, false, true, false );
623 if ( wfEmptyMsg( $key, $source ) )
630 * Fetch a message string value, but don't replace any keys yet.
633 * @param string $langcode Code of the language to get the message for, or
634 * behaves as a content language switch if it is a
639 function wfMsgGetKey( $key, $useDB, $langCode = false, $transform = true ) {
640 global $wgContLang, $wgMessageCache;
642 wfRunHooks('NormalizeMessageKey', array(&$key, &$useDB, &$langCode, &$transform));
644 # If $wgMessageCache isn't initialised yet, try to return something sensible.
645 if( is_object( $wgMessageCache ) ) {
646 $message = $wgMessageCache->get( $key, $useDB, $langCode );
648 $message = $wgMessageCache->transform( $message );
651 $lang = wfGetLangObj( $langCode );
653 # MessageCache::get() does this already, Language::getMessage() doesn't
654 # ISSUE: Should we try to handle "message/lang" here too?
655 $key = str_replace( ' ' , '_' , $wgContLang->lcfirst( $key ) );
657 if( is_object( $lang ) ) {
658 $message = $lang->getMessage( $key );
668 * Replace message parameter keys on the given formatted output.
670 * @param string $message
675 function wfMsgReplaceArgs( $message, $args ) {
676 # Fix windows line-endings
677 # Some messages are split with explode("\n", $msg)
678 $message = str_replace( "\r", '', $message );
681 if ( count( $args ) ) {
682 if ( is_array( $args[0] ) ) {
683 $args = array_values( $args[0] );
685 $replacementKeys = array();
686 foreach( $args as $n => $param ) {
687 $replacementKeys['$' . ($n +
1)] = $param;
689 $message = strtr( $message, $replacementKeys );
696 * Return an HTML-escaped version of a message.
697 * Parameter replacements, if any, are done *after* the HTML-escaping,
698 * so parameters may contain HTML (eg links or form controls). Be sure
699 * to pre-escape them if you really do want plaintext, or just wrap
700 * the whole thing in htmlspecialchars().
703 * @param string ... parameters
706 function wfMsgHtml( $key ) {
707 $args = func_get_args();
708 array_shift( $args );
709 return wfMsgReplaceArgs( htmlspecialchars( wfMsgGetKey( $key, true ) ), $args );
713 * Return an HTML version of message
714 * Parameter replacements, if any, are done *after* parsing the wiki-text message,
715 * so parameters may contain HTML (eg links or form controls). Be sure
716 * to pre-escape them if you really do want plaintext, or just wrap
717 * the whole thing in htmlspecialchars().
720 * @param string ... parameters
723 function wfMsgWikiHtml( $key ) {
725 $args = func_get_args();
726 array_shift( $args );
727 return wfMsgReplaceArgs( $wgOut->parse( wfMsgGetKey( $key, true ), /* can't be set to false */ true ), $args );
731 * Returns message in the requested format
732 * @param string $key Key of the message
733 * @param array $options Processing rules. Can take the following options:
734 * <i>parse</i>: parses wikitext to html
735 * <i>parseinline</i>: parses wikitext to html and removes the surrounding
736 * p's added by parser or tidy
737 * <i>escape</i>: filters message through htmlspecialchars
738 * <i>escapenoentities</i>: same, but allows entity references like through
739 * <i>replaceafter</i>: parameters are substituted after parsing or escaping
740 * <i>parsemag</i>: transform the message using magic phrases
741 * <i>content</i>: fetch message for content language instead of interface
742 * Also can accept a single associative argument, of the form 'language' => 'xx':
743 * <i>language</i>: Language object or language code to fetch message for
744 * (overriden by <i>content</i>), its behaviour with parser, parseinline
745 * and parsemag is undefined.
746 * Behavior for conflicting options (e.g., parse+parseinline) is undefined.
748 function wfMsgExt( $key, $options ) {
751 $args = func_get_args();
752 array_shift( $args );
753 array_shift( $args );
754 $options = (array)$options;
756 foreach( $options as $arrayKey => $option ) {
757 if( !preg_match( '/^[0-9]+|language$/', $arrayKey ) ) {
758 # An unknown index, neither numeric nor "language"
759 wfWarn( "wfMsgExt called with incorrect parameter key $arrayKey", 1, E_USER_WARNING
);
760 } elseif( preg_match( '/^[0-9]+$/', $arrayKey ) && !in_array( $option,
761 array( 'parse', 'parseinline', 'escape', 'escapenoentities',
762 'replaceafter', 'parsemag', 'content' ) ) ) {
763 # A numeric index with unknown value
764 wfWarn( "wfMsgExt called with incorrect parameter $option", 1, E_USER_WARNING
);
768 if( in_array('content', $options, true ) ) {
771 } elseif( array_key_exists('language', $options) ) {
773 $langCode = wfGetLangObj( $options['language'] );
779 $string = wfMsgGetKey( $key, /*DB*/true, $langCode, /*Transform*/false );
781 if( !in_array('replaceafter', $options, true ) ) {
782 $string = wfMsgReplaceArgs( $string, $args );
785 if( in_array('parse', $options, true ) ) {
786 $string = $wgOut->parse( $string, true, !$forContent );
787 } elseif ( in_array('parseinline', $options, true ) ) {
788 $string = $wgOut->parse( $string, true, !$forContent );
790 if( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $string, $m ) ) {
793 } elseif ( in_array('parsemag', $options, true ) ) {
794 global $wgMessageCache;
795 if ( isset( $wgMessageCache ) ) {
796 $string = $wgMessageCache->transform( $string,
798 is_object( $langCode ) ?
$langCode : null );
802 if ( in_array('escape', $options, true ) ) {
803 $string = htmlspecialchars ( $string );
804 } elseif ( in_array( 'escapenoentities', $options, true ) ) {
805 $string = Sanitizer
::escapeHtmlAllowEntities( $string );
808 if( in_array('replaceafter', $options, true ) ) {
809 $string = wfMsgReplaceArgs( $string, $args );
817 * Just like exit() but makes a note of it.
818 * Commits open transactions except if the error parameter is set
820 * @deprecated Please return control to the caller or throw an exception
822 function wfAbruptExit( $error = false ){
823 static $called = false;
829 $bt = wfDebugBacktrace();
831 for($i = 0; $i < count($bt) ; $i++
){
832 $file = isset($bt[$i]['file']) ?
$bt[$i]['file'] : "unknown";
833 $line = isset($bt[$i]['line']) ?
$bt[$i]['line'] : "unknown";
834 wfDebug("WARNING: Abrupt exit in $file at line $line\n");
837 wfDebug("WARNING: Abrupt exit\n");
840 wfLogProfilingData();
843 wfGetLB()->closeAll();
849 * @deprecated Please return control the caller or throw an exception
851 function wfErrorExit() {
852 wfAbruptExit( true );
856 * Print a simple message and die, returning nonzero to the shell if any.
857 * Plain die() fails to return nonzero to the shell if you pass a string.
860 function wfDie( $msg='' ) {
866 * Throw a debugging exception. This function previously once exited the process,
867 * but now throws an exception instead, with similar results.
869 * @param string $msg Message shown when dieing.
871 function wfDebugDieBacktrace( $msg = '' ) {
872 throw new MWException( $msg );
876 * Fetch server name for use in error reporting etc.
877 * Use real server name if available, so we know which machine
878 * in a server farm generated the current page.
881 function wfHostname() {
883 if ( is_null( $host ) ) {
884 if ( function_exists( 'posix_uname' ) ) {
885 // This function not present on Windows
886 $uname = @posix_uname
();
890 if( is_array( $uname ) && isset( $uname['nodename'] ) ) {
891 $host = $uname['nodename'];
892 } elseif ( getenv( 'COMPUTERNAME' ) ) {
893 # Windows computer name
894 $host = getenv( 'COMPUTERNAME' );
896 # This may be a virtual server.
897 $host = $_SERVER['SERVER_NAME'];
904 * Returns a HTML comment with the elapsed time since request.
905 * This method has no side effects.
908 function wfReportTime() {
909 global $wgRequestTime, $wgShowHostnames;
912 $elapsed = $now - $wgRequestTime;
914 return $wgShowHostnames
915 ?
sprintf( "<!-- Served by %s in %01.3f secs. -->", wfHostname(), $elapsed )
916 : sprintf( "<!-- Served in %01.3f secs. -->", $elapsed );
920 * Safety wrapper for debug_backtrace().
922 * With Zend Optimizer 3.2.0 loaded, this causes segfaults under somewhat
923 * murky circumstances, which may be triggered in part by stub objects
924 * or other fancy talkin'.
926 * Will return an empty array if Zend Optimizer is detected or if
927 * debug_backtrace is disabled, otherwise the output from
928 * debug_backtrace() (trimmed).
930 * @return array of backtrace information
932 function wfDebugBacktrace() {
933 static $disabled = null;
935 if( extension_loaded( 'Zend Optimizer' ) ) {
936 wfDebug( "Zend Optimizer detected; skipping debug_backtrace for safety.\n" );
940 if ( is_null( $disabled ) ) {
942 $functions = explode( ',', ini_get( 'disable_functions' ) );
943 $functions = array_map( 'trim', $functions );
944 $functions = array_map( 'strtolower', $functions );
945 if ( in_array( 'debug_backtrace', $functions ) ) {
946 wfDebug( "debug_backtrace is in disabled_functions\n" );
954 return array_slice( debug_backtrace(), 1 );
957 function wfBacktrace() {
958 global $wgCommandLineMode;
960 if ( $wgCommandLineMode ) {
965 $backtrace = wfDebugBacktrace();
966 foreach( $backtrace as $call ) {
967 if( isset( $call['file'] ) ) {
968 $f = explode( DIRECTORY_SEPARATOR
, $call['file'] );
969 $file = $f[count($f)-1];
973 if( isset( $call['line'] ) ) {
974 $line = $call['line'];
978 if ( $wgCommandLineMode ) {
979 $msg .= "$file line $line calls ";
981 $msg .= '<li>' . $file . ' line ' . $line . ' calls ';
983 if( !empty( $call['class'] ) ) $msg .= $call['class'] . '::';
984 $msg .= $call['function'] . '()';
986 if ( $wgCommandLineMode ) {
992 if ( $wgCommandLineMode ) {
1002 /* Some generic result counters, pulled out of SearchEngine */
1008 function wfShowingResults( $offset, $limit ) {
1010 return wfMsgExt( 'showingresults', array( 'parseinline' ), $wgLang->formatNum( $limit ),
1011 $wgLang->formatNum( $offset+
1 ) );
1017 function wfShowingResultsNum( $offset, $limit, $num ) {
1019 return wfMsgExt( 'showingresultsnum', array( 'parseinline' ), $wgLang->formatNum( $limit ),
1020 $wgLang->formatNum( $offset+
1 ), $wgLang->formatNum( $num ) );
1024 * Generate (prev x| next x) (20|50|100...) type links for paging
1025 * @param $offset string
1027 * @param $link string
1028 * @param $query string, optional URL query parameter string
1029 * @param $atend bool, optional param for specified if this is the last page
1031 function wfViewPrevNext( $offset, $limit, $link, $query = '', $atend = false ) {
1033 $fmtLimit = $wgLang->formatNum( $limit );
1034 // FIXME: Why on earth this needs one message for the text and another one for tooltip??
1035 # Get prev/next link display text
1036 $prev = wfMsgExt( 'prevn', array('parsemag','escape'), $fmtLimit );
1037 $next = wfMsgExt( 'nextn', array('parsemag','escape'), $fmtLimit );
1038 # Get prev/next link title text
1039 $pTitle = wfMsgExt( 'prevn-title', array('parsemag','escape'), $fmtLimit );
1040 $nTitle = wfMsgExt( 'nextn-title', array('parsemag','escape'), $fmtLimit );
1041 # Fetch the title object
1042 if( is_object( $link ) ) {
1045 $title = Title
::newFromText( $link );
1046 if( is_null( $title ) ) {
1050 # Make 'previous' link
1051 if( 0 != $offset ) {
1052 $po = $offset - $limit;
1054 $q = "limit={$limit}&offset={$po}";
1055 if( $query != '' ) {
1058 $plink = '<a href="' . $title->escapeLocalUrl( $q ) . "\" title=\"{$pTitle}\" class=\"mw-prevlink\">{$prev}</a>";
1063 $no = $offset +
$limit;
1064 $q = "limit={$limit}&offset={$no}";
1065 if( $query != '' ) {
1071 $nlink = '<a href="' . $title->escapeLocalUrl( $q ) . "\" title=\"{$nTitle}\" class=\"mw-nextlink\">{$next}</a>";
1073 # Make links to set number of items per page
1074 $nums = $wgLang->pipeList( array(
1075 wfNumLink( $offset, 20, $title, $query ),
1076 wfNumLink( $offset, 50, $title, $query ),
1077 wfNumLink( $offset, 100, $title, $query ),
1078 wfNumLink( $offset, 250, $title, $query ),
1079 wfNumLink( $offset, 500, $title, $query )
1081 return wfMsgHtml( 'viewprevnext', $plink, $nlink, $nums );
1085 * Generate links for (20|50|100...) items-per-page links
1086 * @param $offset string
1088 * @param $title Title
1089 * @param $query string, optional URL query parameter string
1091 function wfNumLink( $offset, $limit, $title, $query = '' ) {
1093 if( $query == '' ) {
1098 $q .= "limit={$limit}&offset={$offset}";
1099 $fmtLimit = $wgLang->formatNum( $limit );
1100 $lTitle = wfMsgExt('shown-title',array('parsemag','escape'),$limit);
1101 $s = '<a href="' . $title->escapeLocalUrl( $q ) . "\" title=\"{$lTitle}\" class=\"mw-numlink\">{$fmtLimit}</a>";
1107 * @todo FIXME: we may want to blacklist some broken browsers
1109 * @return bool Whereas client accept gzip compression
1111 function wfClientAcceptsGzip() {
1114 # FIXME: we may want to blacklist some broken browsers
1117 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
1118 $_SERVER['HTTP_ACCEPT_ENCODING'],
1120 if( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) return false;
1121 wfDebug( " accepts gzip\n" );
1129 * Obtain the offset and limit values from the request string;
1130 * used in special pages
1132 * @param $deflimit Default limit if none supplied
1133 * @param $optionname Name of a user preference to check against
1137 function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) {
1139 return $wgRequest->getLimitOffset( $deflimit, $optionname );
1143 * Escapes the given text so that it may be output using addWikiText()
1144 * without any linking, formatting, etc. making its way through. This
1145 * is achieved by substituting certain characters with HTML entities.
1146 * As required by the callers, <nowiki> is not used. It currently does
1147 * not filter out characters which have special meaning only at the
1148 * start of a line, such as "*".
1150 * @param string $text Text to be escaped
1152 function wfEscapeWikiText( $text ) {
1153 $text = str_replace(
1154 array( '[', '|', ']', '\'', 'ISBN ', 'RFC ', '://', "\n=", '{{' ), # }}
1155 array( '[', '|', ']', ''', 'ISBN ', 'RFC ', '://', "\n=", '{{' ),
1156 htmlspecialchars($text) );
1163 function wfQuotedPrintable( $string, $charset = '' ) {
1164 # Probably incomplete; see RFC 2045
1165 if( empty( $charset ) ) {
1166 global $wgInputEncoding;
1167 $charset = $wgInputEncoding;
1169 $charset = strtoupper( $charset );
1170 $charset = str_replace( 'ISO-8859', 'ISO8859', $charset ); // ?
1172 $illegal = '\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\xff=';
1173 $replace = $illegal . '\t ?_';
1174 if( !preg_match( "/[$illegal]/", $string ) ) return $string;
1175 $out = "=?$charset?Q?";
1176 $out .= preg_replace( "/([$replace])/e", 'sprintf("=%02X",ord("$1"))', $string );
1187 return microtime(true);
1191 * Sets dest to source and returns the original value of dest
1192 * If source is NULL, it just returns the value, it doesn't set the variable
1194 function wfSetVar( &$dest, $source ) {
1196 if ( !is_null( $source ) ) {
1203 * As for wfSetVar except setting a bit
1205 function wfSetBit( &$dest, $bit, $state = true ) {
1206 $temp = (bool)($dest & $bit );
1207 if ( !is_null( $state ) ) {
1218 * This function takes two arrays as input, and returns a CGI-style string, e.g.
1219 * "days=7&limit=100". Options in the first array override options in the second.
1220 * Options set to "" will not be output.
1222 function wfArrayToCGI( $array1, $array2 = NULL )
1224 if ( !is_null( $array2 ) ) {
1225 $array1 = $array1 +
$array2;
1229 foreach ( $array1 as $key => $value ) {
1230 if ( '' !== $value ) {
1234 if ( is_array( $value ) ) {
1236 foreach ( $value as $v ) {
1237 $cgi .= ( $firstTime ?
'' : '&') .
1238 urlencode( $key . '[]' ) . '=' .
1243 if ( is_object( $value ) ) {
1244 $value = $value->__toString();
1246 $cgi .= urlencode( $key ) . '=' .
1247 urlencode( $value );
1255 * This is the logical opposite of wfArrayToCGI(): it accepts a query string as
1256 * its argument and returns the same string in array form. This allows compa-
1257 * tibility with legacy functions that accept raw query strings instead of nice
1258 * arrays. Of course, keys and values are urldecode()d. Don't try passing in-
1259 * valid query strings, or it will explode.
1261 * @param $query string Query string
1262 * @return array Array version of input
1264 function wfCgiToArray( $query ) {
1265 if( isset( $query[0] ) and $query[0] == '?' ) {
1266 $query = substr( $query, 1 );
1268 $bits = explode( '&', $query );
1270 foreach( $bits as $bit ) {
1274 list( $key, $value ) = explode( '=', $bit );
1275 $key = urldecode( $key );
1276 $value = urldecode( $value );
1277 $ret[$key] = $value;
1283 * Append a query string to an existing URL, which may or may not already
1284 * have query string parameters already. If so, they will be combined.
1286 * @param string $url
1287 * @param mixed $query String or associative array
1290 function wfAppendQuery( $url, $query ) {
1291 if ( is_array( $query ) ) {
1292 $query = wfArrayToCGI( $query );
1294 if( $query != '' ) {
1295 if( false === strpos( $url, '?' ) ) {
1306 * Expand a potentially local URL to a fully-qualified URL.
1307 * Assumes $wgServer is correct. :)
1308 * @param string $url, either fully-qualified or a local path + query
1309 * @return string Fully-qualified URL
1311 function wfExpandUrl( $url ) {
1312 if( substr( $url, 0, 1 ) == '/' ) {
1314 return $wgServer . $url;
1321 * This is obsolete, use SquidUpdate::purge()
1324 function wfPurgeSquidServers ($urlArr) {
1325 SquidUpdate
::purge( $urlArr );
1329 * Windows-compatible version of escapeshellarg()
1330 * Windows doesn't recognise single-quotes in the shell, but the escapeshellarg()
1331 * function puts single quotes in regardless of OS.
1333 * Also fixes the locale problems on Linux in PHP 5.2.6+ (bug backported to
1334 * earlier distro releases of PHP)
1336 function wfEscapeShellArg( ) {
1337 wfInitShellLocale();
1339 $args = func_get_args();
1342 foreach ( $args as $arg ) {
1349 if ( wfIsWindows() ) {
1350 // Escaping for an MSVC-style command line parser
1351 // Ref: http://mailman.lyra.org/pipermail/scite-interest/2002-March/000436.html
1352 // Double the backslashes before any double quotes. Escape the double quotes.
1353 $tokens = preg_split( '/(\\\\*")/', $arg, -1, PREG_SPLIT_DELIM_CAPTURE
);
1356 foreach ( $tokens as $token ) {
1358 $arg .= str_replace( '\\', '\\\\', substr( $token, 0, -1 ) ) . '\\"';
1364 // Double the backslashes before the end of the string, because
1365 // we will soon add a quote
1367 if ( preg_match( '/^(.*?)(\\\\+)$/', $arg, $m ) ) {
1368 $arg = $m[1] . str_replace( '\\', '\\\\', $m[2] );
1371 // Add surrounding quotes
1372 $retVal .= '"' . $arg . '"';
1374 $retVal .= escapeshellarg( $arg );
1381 * wfMerge attempts to merge differences between three texts.
1382 * Returns true for a clean merge and false for failure or a conflict.
1384 function wfMerge( $old, $mine, $yours, &$result ){
1387 # This check may also protect against code injection in
1388 # case of broken installations.
1389 if( !$wgDiff3 ||
!file_exists( $wgDiff3 ) ) {
1390 wfDebug( "diff3 not found\n" );
1394 # Make temporary files
1396 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
1397 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
1398 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
1400 fwrite( $oldtextFile, $old ); fclose( $oldtextFile );
1401 fwrite( $mytextFile, $mine ); fclose( $mytextFile );
1402 fwrite( $yourtextFile, $yours ); fclose( $yourtextFile );
1404 # Check for a conflict
1405 $cmd = $wgDiff3 . ' -a --overlap-only ' .
1406 wfEscapeShellArg( $mytextName ) . ' ' .
1407 wfEscapeShellArg( $oldtextName ) . ' ' .
1408 wfEscapeShellArg( $yourtextName );
1409 $handle = popen( $cmd, 'r' );
1411 if( fgets( $handle, 1024 ) ){
1419 $cmd = $wgDiff3 . ' -a -e --merge ' .
1420 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
1421 $handle = popen( $cmd, 'r' );
1424 $data = fread( $handle, 8192 );
1425 if ( strlen( $data ) == 0 ) {
1431 unlink( $mytextName ); unlink( $oldtextName ); unlink( $yourtextName );
1433 if ( $result === '' && $old !== '' && $conflict == false ) {
1434 wfDebug( "Unexpected null result from diff3. Command: $cmd\n" );
1441 * Returns unified plain-text diff of two texts.
1442 * Useful for machine processing of diffs.
1443 * @param $before string The text before the changes.
1444 * @param $after string The text after the changes.
1445 * @param $params string Command-line options for the diff command.
1446 * @return string Unified diff of $before and $after
1448 function wfDiff( $before, $after, $params = '-u' ) {
1449 if ($before == $after) {
1455 # This check may also protect against code injection in
1456 # case of broken installations.
1457 if( !file_exists( $wgDiff ) ){
1458 wfDebug( "diff executable not found\n" );
1459 $diffs = new Diff( explode( "\n", $before ), explode( "\n", $after ) );
1460 $format = new UnifiedDiffFormatter();
1461 return $format->format( $diffs );
1464 # Make temporary files
1466 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
1467 $newtextFile = fopen( $newtextName = tempnam( $td, 'merge-your-' ), 'w' );
1469 fwrite( $oldtextFile, $before ); fclose( $oldtextFile );
1470 fwrite( $newtextFile, $after ); fclose( $newtextFile );
1472 // Get the diff of the two files
1473 $cmd = "$wgDiff " . $params . ' ' .wfEscapeShellArg( $oldtextName, $newtextName );
1475 $h = popen( $cmd, 'r' );
1480 $data = fread( $h, 8192 );
1481 if ( strlen( $data ) == 0 ) {
1489 unlink( $oldtextName );
1490 unlink( $newtextName );
1492 // Kill the --- and +++ lines. They're not useful.
1493 $diff_lines = explode( "\n", $diff );
1494 if (strpos( $diff_lines[0], '---' ) === 0) {
1495 unset($diff_lines[0]);
1497 if (strpos( $diff_lines[1], '+++' ) === 0) {
1498 unset($diff_lines[1]);
1501 $diff = implode( "\n", $diff_lines );
1507 * A wrapper around the PHP function var_export().
1508 * Either print it or add it to the regular output ($wgOut).
1510 * @param $var A PHP variable to dump.
1512 function wfVarDump( $var ) {
1514 $s = str_replace("\n","<br />\n", var_export( $var, true ) . "\n");
1515 if ( headers_sent() ||
!@is_object
( $wgOut ) ) {
1518 $wgOut->addHTML( $s );
1523 * Provide a simple HTTP error.
1525 function wfHttpError( $code, $label, $desc ) {
1528 header( "HTTP/1.0 $code $label" );
1529 header( "Status: $code $label" );
1530 $wgOut->sendCacheControl();
1532 header( 'Content-type: text/html; charset=utf-8' );
1533 print "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">".
1534 "<html><head><title>" .
1535 htmlspecialchars( $label ) .
1536 "</title></head><body><h1>" .
1537 htmlspecialchars( $label ) .
1539 nl2br( htmlspecialchars( $desc ) ) .
1540 "</p></body></html>\n";
1544 * Clear away any user-level output buffers, discarding contents.
1546 * Suitable for 'starting afresh', for instance when streaming
1547 * relatively large amounts of data without buffering, or wanting to
1548 * output image files without ob_gzhandler's compression.
1550 * The optional $resetGzipEncoding parameter controls suppression of
1551 * the Content-Encoding header sent by ob_gzhandler; by default it
1552 * is left. See comments for wfClearOutputBuffers() for why it would
1555 * Note that some PHP configuration options may add output buffer
1556 * layers which cannot be removed; these are left in place.
1558 * @param bool $resetGzipEncoding
1560 function wfResetOutputBuffers( $resetGzipEncoding=true ) {
1561 if( $resetGzipEncoding ) {
1562 // Suppress Content-Encoding and Content-Length
1563 // headers from 1.10+s wfOutputHandler
1564 global $wgDisableOutputCompression;
1565 $wgDisableOutputCompression = true;
1567 while( $status = ob_get_status() ) {
1568 if( $status['type'] == 0 /* PHP_OUTPUT_HANDLER_INTERNAL */ ) {
1569 // Probably from zlib.output_compression or other
1570 // PHP-internal setting which can't be removed.
1572 // Give up, and hope the result doesn't break
1576 if( !ob_end_clean() ) {
1577 // Could not remove output buffer handler; abort now
1578 // to avoid getting in some kind of infinite loop.
1581 if( $resetGzipEncoding ) {
1582 if( $status['name'] == 'ob_gzhandler' ) {
1583 // Reset the 'Content-Encoding' field set by this handler
1584 // so we can start fresh.
1585 header( 'Content-Encoding:' );
1593 * More legible than passing a 'false' parameter to wfResetOutputBuffers():
1595 * Clear away output buffers, but keep the Content-Encoding header
1596 * produced by ob_gzhandler, if any.
1598 * This should be used for HTTP 304 responses, where you need to
1599 * preserve the Content-Encoding header of the real result, but
1600 * also need to suppress the output of ob_gzhandler to keep to spec
1601 * and avoid breaking Firefox in rare cases where the headers and
1602 * body are broken over two packets.
1604 function wfClearOutputBuffers() {
1605 wfResetOutputBuffers( false );
1609 * Converts an Accept-* header into an array mapping string values to quality
1612 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
1613 # No arg means accept anything (per HTTP spec)
1615 return array( $def => 1.0 );
1620 $parts = explode( ',', $accept );
1622 foreach( $parts as $part ) {
1623 # FIXME: doesn't deal with params like 'text/html; level=1'
1624 @list
( $value, $qpart ) = explode( ';', trim( $part ) );
1626 if( !isset( $qpart ) ) {
1627 $prefs[$value] = 1.0;
1628 } elseif( preg_match( '/q\s*=\s*(\d*\.\d+)/', $qpart, $match ) ) {
1629 $prefs[$value] = floatval($match[1]);
1637 * Checks if a given MIME type matches any of the keys in the given
1638 * array. Basic wildcards are accepted in the array keys.
1640 * Returns the matching MIME type (or wildcard) if a match, otherwise
1643 * @param string $type
1644 * @param array $avail
1648 function mimeTypeMatch( $type, $avail ) {
1649 if( array_key_exists($type, $avail) ) {
1652 $parts = explode( '/', $type );
1653 if( array_key_exists( $parts[0] . '/*', $avail ) ) {
1654 return $parts[0] . '/*';
1655 } elseif( array_key_exists( '*/*', $avail ) ) {
1664 * Returns the 'best' match between a client's requested internet media types
1665 * and the server's list of available types. Each list should be an associative
1666 * array of type to preference (preference is a float between 0.0 and 1.0).
1667 * Wildcards in the types are acceptable.
1669 * @param array $cprefs Client's acceptable type list
1670 * @param array $sprefs Server's offered types
1673 * @todo FIXME: doesn't handle params like 'text/plain; charset=UTF-8'
1674 * XXX: generalize to negotiate other stuff
1676 function wfNegotiateType( $cprefs, $sprefs ) {
1679 foreach( array_keys($sprefs) as $type ) {
1680 $parts = explode( '/', $type );
1681 if( $parts[1] != '*' ) {
1682 $ckey = mimeTypeMatch( $type, $cprefs );
1684 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1689 foreach( array_keys( $cprefs ) as $type ) {
1690 $parts = explode( '/', $type );
1691 if( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
1692 $skey = mimeTypeMatch( $type, $sprefs );
1694 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1702 foreach( array_keys( $combine ) as $type ) {
1703 if( $combine[$type] > $bestq ) {
1705 $bestq = $combine[$type];
1714 * Returns an array where the values in the first array are replaced by the
1715 * values in the second array with the corresponding keys
1719 function wfArrayLookup( $a, $b ) {
1720 return array_flip( array_intersect( array_flip( $a ), array_keys( $b ) ) );
1724 * Convenience function; returns MediaWiki timestamp for the present time.
1727 function wfTimestampNow() {
1729 return wfTimestamp( TS_MW
, time() );
1733 * Reference-counted warning suppression
1735 function wfSuppressWarnings( $end = false ) {
1736 static $suppressCount = 0;
1737 static $originalLevel = false;
1740 if ( $suppressCount ) {
1742 if ( !$suppressCount ) {
1743 error_reporting( $originalLevel );
1747 if ( !$suppressCount ) {
1748 $originalLevel = error_reporting( E_ALL
& ~
( E_WARNING | E_NOTICE
) );
1755 * Restore error level to previous value
1757 function wfRestoreWarnings() {
1758 wfSuppressWarnings( true );
1761 # Autodetect, convert and provide timestamps of various types
1764 * Unix time - the number of seconds since 1970-01-01 00:00:00 UTC
1766 define('TS_UNIX', 0);
1769 * MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
1774 * MySQL DATETIME (YYYY-MM-DD HH:MM:SS)
1779 * RFC 2822 format, for E-mail and HTTP headers
1781 define('TS_RFC2822', 3);
1784 * ISO 8601 format with no timezone: 1986-02-09T20:00:00Z
1786 * This is used by Special:Export
1788 define('TS_ISO_8601', 4);
1791 * An Exif timestamp (YYYY:MM:DD HH:MM:SS)
1793 * @see http://exif.org/Exif2-2.PDF The Exif 2.2 spec, see page 28 for the
1794 * DateTime tag and page 36 for the DateTimeOriginal and
1795 * DateTimeDigitized tags.
1797 define('TS_EXIF', 5);
1800 * Oracle format time.
1802 define('TS_ORACLE', 6);
1805 * Postgres format time.
1807 define('TS_POSTGRES', 7);
1812 define('TS_DB2', 8);
1815 * @param mixed $outputtype A timestamp in one of the supported formats, the
1816 * function will autodetect which format is supplied
1817 * and act accordingly.
1818 * @return string Time in the format specified in $outputtype
1820 function wfTimestamp($outputtype=TS_UNIX
,$ts=0) {
1825 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)$/D',$ts,$da)) {
1827 } elseif (preg_match('/^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/D',$ts,$da)) {
1829 } elseif (preg_match('/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/D',$ts,$da)) {
1831 } elseif (preg_match('/^\d{1,13}$/D',$ts)) {
1834 } elseif (preg_match('/^\d{2}-\d{2}-\d{4} \d{2}:\d{2}:\d{2}.\d{6}$/', $ts)) {
1835 # TS_ORACLE // session altered to DD-MM-YYYY HH24:MI:SS.FF6
1836 $uts = strtotime(preg_replace('/(\d\d)\.(\d\d)\.(\d\d)(\.(\d+))?/', "$1:$2:$3",
1837 str_replace("+00:00", "UTC", $ts)));
1838 } elseif (preg_match('/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.*\d*)?Z$/', $ts, $da)) {
1840 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.*\d*[\+\- ](\d\d)$/',$ts,$da)) {
1842 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.*\d* GMT$/',$ts,$da)) {
1845 # Bogus value; fall back to the epoch...
1846 wfDebug("wfTimestamp() fed bogus time value: $outputtype; $ts\n");
1850 if (count( $da ) ) {
1851 // Warning! gmmktime() acts oddly if the month or day is set to 0
1852 // We may want to handle that explicitly at some point
1853 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1854 (int)$da[2],(int)$da[3],(int)$da[1]);
1857 switch($outputtype) {
1861 return gmdate( 'YmdHis', $uts );
1863 return gmdate( 'Y-m-d H:i:s', $uts );
1865 return gmdate( 'Y-m-d\TH:i:s\Z', $uts );
1866 // This shouldn't ever be used, but is included for completeness
1868 return gmdate( 'Y:m:d H:i:s', $uts );
1870 return gmdate( 'D, d M Y H:i:s', $uts ) . ' GMT';
1872 return gmdate( 'd-m-Y H:i:s.000000', $uts);
1873 //return gmdate( 'd-M-y h.i.s A', $uts) . ' +00:00';
1875 return gmdate( 'Y-m-d H:i:s', $uts) . ' GMT';
1877 return gmdate( 'Y-m-d H:i:s', $uts);
1879 throw new MWException( 'wfTimestamp() called with illegal output type.');
1884 * Return a formatted timestamp, or null if input is null.
1885 * For dealing with nullable timestamp columns in the database.
1886 * @param int $outputtype
1890 function wfTimestampOrNull( $outputtype = TS_UNIX
, $ts = null ) {
1891 if( is_null( $ts ) ) {
1894 return wfTimestamp( $outputtype, $ts );
1899 * Check if the operating system is Windows
1901 * @return bool True if it's Windows, False otherwise.
1903 function wfIsWindows() {
1904 if (substr(php_uname(), 0, 7) == 'Windows') {
1912 * Swap two variables
1914 function swap( &$x, &$y ) {
1920 function wfGetCachedNotice( $name ) {
1921 global $wgOut, $wgRenderHashAppend, $parserMemc;
1922 $fname = 'wfGetCachedNotice';
1923 wfProfileIn( $fname );
1927 if( $name === 'default' ) {
1929 global $wgSiteNotice;
1930 $notice = $wgSiteNotice;
1931 if( empty( $notice ) ) {
1932 wfProfileOut( $fname );
1936 $notice = wfMsgForContentNoTrans( $name );
1937 if( wfEmptyMsg( $name, $notice ) ||
$notice == '-' ) {
1938 wfProfileOut( $fname );
1943 // Use the extra hash appender to let eg SSL variants separately cache.
1944 $key = wfMemcKey( $name . $wgRenderHashAppend );
1945 $cachedNotice = $parserMemc->get( $key );
1946 if( is_array( $cachedNotice ) ) {
1947 if( md5( $notice ) == $cachedNotice['hash'] ) {
1948 $notice = $cachedNotice['html'];
1957 if( is_object( $wgOut ) ) {
1958 $parsed = $wgOut->parse( $notice );
1959 $parserMemc->set( $key, array( 'html' => $parsed, 'hash' => md5( $notice ) ), 600 );
1962 wfDebug( 'wfGetCachedNotice called for ' . $name . ' with no $wgOut available'."\n" );
1967 wfProfileOut( $fname );
1971 function wfGetNamespaceNotice() {
1975 if ( !isset( $wgTitle ) ||
!is_object( $wgTitle ) )
1978 $fname = 'wfGetNamespaceNotice';
1979 wfProfileIn( $fname );
1981 $key = "namespacenotice-" . $wgTitle->getNsText();
1982 $namespaceNotice = wfGetCachedNotice( $key );
1983 if ( $namespaceNotice && substr ( $namespaceNotice , 0 ,7 ) != "<p><" ) {
1984 $namespaceNotice = '<div id="namespacebanner">' . $namespaceNotice . "</div>";
1986 $namespaceNotice = "";
1989 wfProfileOut( $fname );
1990 return $namespaceNotice;
1993 function wfGetSiteNotice() {
1994 global $wgUser, $wgSiteNotice;
1995 $fname = 'wfGetSiteNotice';
1996 wfProfileIn( $fname );
1999 if( wfRunHooks( 'SiteNoticeBefore', array( &$siteNotice ) ) ) {
2000 if( is_object( $wgUser ) && $wgUser->isLoggedIn() ) {
2001 $siteNotice = wfGetCachedNotice( 'sitenotice' );
2003 $anonNotice = wfGetCachedNotice( 'anonnotice' );
2004 if( !$anonNotice ) {
2005 $siteNotice = wfGetCachedNotice( 'sitenotice' );
2007 $siteNotice = $anonNotice;
2010 if( !$siteNotice ) {
2011 $siteNotice = wfGetCachedNotice( 'default' );
2015 wfRunHooks( 'SiteNoticeAfter', array( &$siteNotice ) );
2016 wfProfileOut( $fname );
2021 * BC wrapper for MimeMagic::singleton()
2024 function &wfGetMimeMagic() {
2025 return MimeMagic
::singleton();
2029 * Tries to get the system directory for temporary files.
2030 * The TMPDIR, TMP, and TEMP environment variables are checked in sequence,
2031 * and if none are set /tmp is returned as the generic Unix default.
2033 * NOTE: When possible, use the tempfile() function to create temporary
2034 * files to avoid race conditions on file creation, etc.
2038 function wfTempDir() {
2039 foreach( array( 'TMPDIR', 'TMP', 'TEMP' ) as $var ) {
2040 $tmp = getenv( $var );
2041 if( $tmp && file_exists( $tmp ) && is_dir( $tmp ) && is_writable( $tmp ) ) {
2045 # Hope this is Unix of some kind!
2050 * Make directory, and make all parent directories if they don't exist
2052 * @param string $dir Full path to directory to create
2053 * @param int $mode Chmod value to use, default is $wgDirectoryMode
2054 * @param string $caller Optional caller param for debugging.
2057 function wfMkdirParents( $dir, $mode = null, $caller = null ) {
2058 global $wgDirectoryMode;
2060 if ( !is_null( $caller ) ) {
2061 wfDebug( "$caller: called wfMkdirParents($dir)" );
2064 if( strval( $dir ) === '' ||
file_exists( $dir ) )
2067 $dir = str_replace( array( '\\', '/' ), DIRECTORY_SEPARATOR
, $dir );
2069 if ( is_null( $mode ) )
2070 $mode = $wgDirectoryMode;
2072 return mkdir( $dir, $mode, true ); // PHP5 <3
2076 * Increment a statistics counter
2078 function wfIncrStats( $key ) {
2079 global $wgStatsMethod;
2081 if( $wgStatsMethod == 'udp' ) {
2082 global $wgUDPProfilerHost, $wgUDPProfilerPort, $wgDBname;
2085 $socket=socket_create(AF_INET
, SOCK_DGRAM
, SOL_UDP
);
2086 $statline="stats/{$wgDBname} - 1 1 1 1 1 -total\n";
2087 socket_sendto($socket,$statline,strlen($statline),0,$wgUDPProfilerHost,$wgUDPProfilerPort);
2089 $statline="stats/{$wgDBname} - 1 1 1 1 1 {$key}\n";
2090 @socket_sendto
($socket,$statline,strlen($statline),0,$wgUDPProfilerHost,$wgUDPProfilerPort);
2091 } elseif( $wgStatsMethod == 'cache' ) {
2093 $key = wfMemcKey( 'stats', $key );
2094 if ( is_null( $wgMemc->incr( $key ) ) ) {
2095 $wgMemc->add( $key, 1 );
2103 * @param mixed $nr The number to format
2104 * @param int $acc The number of digits after the decimal point, default 2
2105 * @param bool $round Whether or not to round the value, default true
2108 function wfPercent( $nr, $acc = 2, $round = true ) {
2109 $ret = sprintf( "%.${acc}f", $nr );
2110 return $round ?
round( $ret, $acc ) . '%' : "$ret%";
2114 * Encrypt a username/password.
2116 * @param string $userid ID of the user
2117 * @param string $password Password of the user
2118 * @return string Hashed password
2119 * @deprecated Use User::crypt() or User::oldCrypt() instead
2121 function wfEncryptPassword( $userid, $password ) {
2122 wfDeprecated(__FUNCTION__
);
2123 # Just wrap around User::oldCrypt()
2124 return User
::oldCrypt($password, $userid);
2128 * Appends to second array if $value differs from that in $default
2130 function wfAppendToArrayIfNotDefault( $key, $value, $default, &$changed ) {
2131 if ( is_null( $changed ) ) {
2132 throw new MWException('GlobalFunctions::wfAppendToArrayIfNotDefault got null');
2134 if ( $default[$key] !== $value ) {
2135 $changed[$key] = $value;
2140 * Since wfMsg() and co suck, they don't return false if the message key they
2141 * looked up didn't exist but a XHTML string, this function checks for the
2142 * nonexistance of messages by looking at wfMsg() output
2144 * @param $msg The message key looked up
2145 * @param $wfMsgOut The output of wfMsg*()
2148 function wfEmptyMsg( $msg, $wfMsgOut ) {
2149 return $wfMsgOut === htmlspecialchars( "<$msg>" );
2153 * Find out whether or not a mixed variable exists in a string
2155 * @param mixed needle
2156 * @param string haystack
2159 function in_string( $needle, $str ) {
2160 return strpos( $str, $needle ) !== false;
2163 function wfSpecialList( $page, $details ) {
2165 $details = $details ?
' ' . $wgContLang->getDirMark() . "($details)" : "";
2166 return $page . $details;
2170 * Returns a regular expression of url protocols
2174 function wfUrlProtocols() {
2175 global $wgUrlProtocols;
2177 // Support old-style $wgUrlProtocols strings, for backwards compatibility
2178 // with LocalSettings files from 1.5
2179 if ( is_array( $wgUrlProtocols ) ) {
2180 $protocols = array();
2181 foreach ($wgUrlProtocols as $protocol)
2182 $protocols[] = preg_quote( $protocol, '/' );
2184 return implode( '|', $protocols );
2186 return $wgUrlProtocols;
2191 * Safety wrapper around ini_get() for boolean settings.
2192 * The values returned from ini_get() are pre-normalized for settings
2193 * set via php.ini or php_flag/php_admin_flag... but *not*
2194 * for those set via php_value/php_admin_value.
2196 * It's fairly common for people to use php_value instead of php_flag,
2197 * which can leave you with an 'off' setting giving a false positive
2198 * for code that just takes the ini_get() return value as a boolean.
2200 * To make things extra interesting, setting via php_value accepts
2201 * "true" and "yes" as true, but php.ini and php_flag consider them false. :)
2202 * Unrecognized values go false... again opposite PHP's own coercion
2203 * from string to bool.
2205 * Luckily, 'properly' set settings will always come back as '0' or '1',
2206 * so we only have to worry about them and the 'improper' settings.
2208 * I frickin' hate PHP... :P
2210 * @param string $setting
2213 function wfIniGetBool( $setting ) {
2214 $val = ini_get( $setting );
2215 // 'on' and 'true' can't have whitespace around them, but '1' can.
2216 return strtolower( $val ) == 'on'
2217 ||
strtolower( $val ) == 'true'
2218 ||
strtolower( $val ) == 'yes'
2219 ||
preg_match( "/^\s*[+-]?0*[1-9]/", $val ); // approx C atoi() function
2223 * Execute a shell command, with time and memory limits mirrored from the PHP
2224 * configuration if supported.
2225 * @param $cmd Command line, properly escaped for shell.
2226 * @param &$retval optional, will receive the program's exit code.
2227 * (non-zero is usually failure)
2228 * @return collected stdout as a string (trailing newlines stripped)
2230 function wfShellExec( $cmd, &$retval=null ) {
2231 global $IP, $wgMaxShellMemory, $wgMaxShellFileSize, $wgMaxShellTime;
2234 if ( is_null( $disabled ) ) {
2236 if( wfIniGetBool( 'safe_mode' ) ) {
2237 wfDebug( "wfShellExec can't run in safe_mode, PHP's exec functions are too broken.\n" );
2240 $functions = explode( ',', ini_get( 'disable_functions' ) );
2241 $functions = array_map( 'trim', $functions );
2242 $functions = array_map( 'strtolower', $functions );
2243 if ( in_array( 'passthru', $functions ) ) {
2244 wfDebug( "passthru is in disabled_functions\n" );
2250 return "Unable to run external programs in safe mode.";
2253 wfInitShellLocale();
2255 if ( php_uname( 's' ) == 'Linux' ) {
2256 $time = intval( $wgMaxShellTime );
2257 $mem = intval( $wgMaxShellMemory );
2258 $filesize = intval( $wgMaxShellFileSize );
2260 if ( $time > 0 && $mem > 0 ) {
2261 $script = "$IP/bin/ulimit4.sh";
2262 if ( is_executable( $script ) ) {
2263 $cmd = escapeshellarg( $script ) . " $time $mem $filesize " . escapeshellarg( $cmd );
2266 } elseif ( php_uname( 's' ) == 'Windows NT' ) {
2267 # This is a hack to work around PHP's flawed invocation of cmd.exe
2268 # http://news.php.net/php.internals/21796
2269 $cmd = '"' . $cmd . '"';
2271 wfDebug( "wfShellExec: $cmd\n" );
2273 $retval = 1; // error by default?
2275 passthru( $cmd, $retval );
2276 $output = ob_get_contents();
2279 if ( $retval == 127 ) {
2280 wfDebugLog( 'exec', "Possibly missing executable file: $cmd\n" );
2286 * Workaround for http://bugs.php.net/bug.php?id=45132
2287 * escapeshellarg() destroys non-ASCII characters if LANG is not a UTF-8 locale
2289 function wfInitShellLocale() {
2290 static $done = false;
2291 if ( $done ) return;
2293 global $wgShellLocale;
2294 if ( !wfIniGetBool( 'safe_mode' ) ) {
2295 putenv( "LC_CTYPE=$wgShellLocale" );
2296 setlocale( LC_CTYPE
, $wgShellLocale );
2301 * This function works like "use VERSION" in Perl, the program will die with a
2302 * backtrace if the current version of PHP is less than the version provided
2304 * This is useful for extensions which due to their nature are not kept in sync
2305 * with releases, and might depend on other versions of PHP than the main code
2307 * Note: PHP might die due to parsing errors in some cases before it ever
2308 * manages to call this function, such is life
2310 * @see perldoc -f use
2312 * @param mixed $version The version to check, can be a string, an integer, or
2315 function wfUsePHP( $req_ver ) {
2316 $php_ver = PHP_VERSION
;
2318 if ( version_compare( $php_ver, (string)$req_ver, '<' ) )
2319 throw new MWException( "PHP $req_ver required--this is only $php_ver" );
2323 * This function works like "use VERSION" in Perl except it checks the version
2324 * of MediaWiki, the program will die with a backtrace if the current version
2325 * of MediaWiki is less than the version provided.
2327 * This is useful for extensions which due to their nature are not kept in sync
2330 * @see perldoc -f use
2332 * @param mixed $version The version to check, can be a string, an integer, or
2335 function wfUseMW( $req_ver ) {
2338 if ( version_compare( $wgVersion, (string)$req_ver, '<' ) )
2339 throw new MWException( "MediaWiki $req_ver required--this is only $wgVersion" );
2343 * @deprecated use StringUtils::escapeRegexReplacement
2345 function wfRegexReplacement( $string ) {
2346 return StringUtils
::escapeRegexReplacement( $string );
2350 * Return the final portion of a pathname.
2351 * Reimplemented because PHP5's basename() is buggy with multibyte text.
2352 * http://bugs.php.net/bug.php?id=33898
2354 * PHP's basename() only considers '\' a pathchar on Windows and Netware.
2355 * We'll consider it so always, as we don't want \s in our Unix paths either.
2357 * @param string $path
2358 * @param string $suffix to remove if present
2361 function wfBaseName( $path, $suffix='' ) {
2362 $encSuffix = ($suffix == '')
2364 : ( '(?:' . preg_quote( $suffix, '#' ) . ')?' );
2366 if( preg_match( "#([^/\\\\]*?){$encSuffix}[/\\\\]*$#", $path, $matches ) ) {
2374 * Generate a relative path name to the given file.
2375 * May explode on non-matching case-insensitive paths,
2376 * funky symlinks, etc.
2378 * @param string $path Absolute destination path including target filename
2379 * @param string $from Absolute source path, directory only
2382 function wfRelativePath( $path, $from ) {
2383 // Normalize mixed input on Windows...
2384 $path = str_replace( '/', DIRECTORY_SEPARATOR
, $path );
2385 $from = str_replace( '/', DIRECTORY_SEPARATOR
, $from );
2387 // Trim trailing slashes -- fix for drive root
2388 $path = rtrim( $path, DIRECTORY_SEPARATOR
);
2389 $from = rtrim( $from, DIRECTORY_SEPARATOR
);
2391 $pieces = explode( DIRECTORY_SEPARATOR
, dirname( $path ) );
2392 $against = explode( DIRECTORY_SEPARATOR
, $from );
2394 if( $pieces[0] !== $against[0] ) {
2395 // Non-matching Windows drive letters?
2396 // Return a full path.
2400 // Trim off common prefix
2401 while( count( $pieces ) && count( $against )
2402 && $pieces[0] == $against[0] ) {
2403 array_shift( $pieces );
2404 array_shift( $against );
2407 // relative dots to bump us to the parent
2408 while( count( $against ) ) {
2409 array_unshift( $pieces, '..' );
2410 array_shift( $against );
2413 array_push( $pieces, wfBaseName( $path ) );
2415 return implode( DIRECTORY_SEPARATOR
, $pieces );
2419 * Backwards array plus for people who haven't bothered to read the PHP manual
2420 * XXX: will not darn your socks for you.
2422 * @param array $array1, [$array2, [...]]
2425 function wfArrayMerge( $array1/* ... */ ) {
2426 $args = func_get_args();
2427 $args = array_reverse( $args, true );
2429 foreach ( $args as $arg ) {
2436 * Merge arrays in the style of getUserPermissionsErrors, with duplicate removal
2438 * wfMergeErrorArrays(
2439 * array( array( 'x' ) ),
2440 * array( array( 'x', '2' ) ),
2441 * array( array( 'x' ) ),
2442 * array( array( 'y') )
2446 * array( 'x', '2' ),
2451 function wfMergeErrorArrays(/*...*/) {
2452 $args = func_get_args();
2454 foreach ( $args as $errors ) {
2455 foreach ( $errors as $params ) {
2456 $spec = implode( "\t", $params );
2457 $out[$spec] = $params;
2460 return array_values( $out );
2464 * parse_url() work-alike, but non-broken. Differences:
2466 * 1) Does not raise warnings on bad URLs (just returns false)
2467 * 2) Handles protocols that don't use :// (e.g., mailto: and news:) correctly
2468 * 3) Adds a "delimiter" element to the array, either '://' or ':' (see (2))
2470 * @param string $url A URL to parse
2471 * @return array Bits of the URL in an associative array, per PHP docs
2473 function wfParseUrl( $url ) {
2474 global $wgUrlProtocols; // Allow all protocols defined in DefaultSettings/LocalSettings.php
2475 wfSuppressWarnings();
2476 $bits = parse_url( $url );
2477 wfRestoreWarnings();
2482 // most of the protocols are followed by ://, but mailto: and sometimes news: not, check for it
2483 if ( in_array( $bits['scheme'] . '://', $wgUrlProtocols ) ) {
2484 $bits['delimiter'] = '://';
2485 } elseif ( in_array( $bits['scheme'] . ':', $wgUrlProtocols ) ) {
2486 $bits['delimiter'] = ':';
2487 // parse_url detects for news: and mailto: the host part of an url as path
2488 // We have to correct this wrong detection
2489 if ( isset ( $bits['path'] ) ) {
2490 $bits['host'] = $bits['path'];
2501 * Make a URL index, appropriate for the el_index field of externallinks.
2503 function wfMakeUrlIndex( $url ) {
2504 $bits = wfParseUrl( $url );
2506 // Reverse the labels in the hostname, convert to lower case
2507 // For emails reverse domainpart only
2508 if ( $bits['scheme'] == 'mailto' ) {
2509 $mailparts = explode( '@', $bits['host'], 2 );
2510 if ( count($mailparts) === 2 ) {
2511 $domainpart = strtolower( implode( '.', array_reverse( explode( '.', $mailparts[1] ) ) ) );
2513 // No domain specified, don't mangle it
2516 $reversedHost = $domainpart . '@' . $mailparts[0];
2518 $reversedHost = strtolower( implode( '.', array_reverse( explode( '.', $bits['host'] ) ) ) );
2520 // Add an extra dot to the end
2521 // Why? Is it in wrong place in mailto links?
2522 if ( substr( $reversedHost, -1, 1 ) !== '.' ) {
2523 $reversedHost .= '.';
2525 // Reconstruct the pseudo-URL
2526 $prot = $bits['scheme'];
2527 $index = $prot . $bits['delimiter'] . $reversedHost;
2528 // Leave out user and password. Add the port, path, query and fragment
2529 if ( isset( $bits['port'] ) ) $index .= ':' . $bits['port'];
2530 if ( isset( $bits['path'] ) ) {
2531 $index .= $bits['path'];
2535 if ( isset( $bits['query'] ) ) $index .= '?' . $bits['query'];
2536 if ( isset( $bits['fragment'] ) ) $index .= '#' . $bits['fragment'];
2541 * Do any deferred updates and clear the list
2542 * TODO: This could be in Wiki.php if that class made any sense at all
2544 function wfDoUpdates()
2546 global $wgPostCommitUpdateList, $wgDeferredUpdateList;
2547 foreach ( $wgDeferredUpdateList as $update ) {
2548 $update->doUpdate();
2550 foreach ( $wgPostCommitUpdateList as $update ) {
2551 $update->doUpdate();
2553 $wgDeferredUpdateList = array();
2554 $wgPostCommitUpdateList = array();
2558 * @deprecated use StringUtils::explodeMarkup
2560 function wfExplodeMarkup( $separator, $text ) {
2561 return StringUtils
::explodeMarkup( $separator, $text );
2565 * Convert an arbitrarily-long digit string from one numeric base
2566 * to another, optionally zero-padding to a minimum column width.
2568 * Supports base 2 through 36; digit values 10-36 are represented
2569 * as lowercase letters a-z. Input is case-insensitive.
2571 * @param $input string of digits
2572 * @param $sourceBase int 2-36
2573 * @param $destBase int 2-36
2574 * @param $pad int 1 or greater
2575 * @param $lowercase bool
2576 * @return string or false on invalid input
2578 function wfBaseConvert( $input, $sourceBase, $destBase, $pad=1, $lowercase=true ) {
2579 $input = strval( $input );
2580 if( $sourceBase < 2 ||
2585 $sourceBase != intval( $sourceBase ) ||
2586 $destBase != intval( $destBase ) ||
2587 $pad != intval( $pad ) ||
2588 !is_string( $input ) ||
2592 $digitChars = ( $lowercase ) ?
'0123456789abcdefghijklmnopqrstuvwxyz' : '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
2593 $inDigits = array();
2596 // Decode and validate input string
2597 $input = strtolower( $input );
2598 for( $i = 0; $i < strlen( $input ); $i++
) {
2599 $n = strpos( $digitChars, $input{$i} );
2600 if( $n === false ||
$n > $sourceBase ) {
2606 // Iterate over the input, modulo-ing out an output digit
2607 // at a time until input is gone.
2608 while( count( $inDigits ) ) {
2610 $workDigits = array();
2613 foreach( $inDigits as $digit ) {
2614 $work *= $sourceBase;
2617 if( $work < $destBase ) {
2618 // Gonna need to pull another digit.
2619 if( count( $workDigits ) ) {
2620 // Avoid zero-padding; this lets us find
2621 // the end of the input very easily when
2622 // length drops to zero.
2626 // Finally! Actual division!
2627 $workDigits[] = intval( $work / $destBase );
2629 // Isn't it annoying that most programming languages
2630 // don't have a single divide-and-remainder operator,
2631 // even though the CPU implements it that way?
2632 $work = $work %
$destBase;
2636 // All that division leaves us with a remainder,
2637 // which is conveniently our next output digit.
2638 $outChars .= $digitChars[$work];
2641 $inDigits = $workDigits;
2644 while( strlen( $outChars ) < $pad ) {
2648 return strrev( $outChars );
2652 * Create an object with a given name and an array of construct parameters
2653 * @param string $name
2654 * @param array $p parameters
2656 function wfCreateObject( $name, $p ){
2657 $p = array_values( $p );
2658 switch ( count( $p ) ) {
2662 return new $name( $p[0] );
2664 return new $name( $p[0], $p[1] );
2666 return new $name( $p[0], $p[1], $p[2] );
2668 return new $name( $p[0], $p[1], $p[2], $p[3] );
2670 return new $name( $p[0], $p[1], $p[2], $p[3], $p[4] );
2672 return new $name( $p[0], $p[1], $p[2], $p[3], $p[4], $p[5] );
2674 throw new MWException( "Too many arguments to construtor in wfCreateObject" );
2679 * Alias for modularized function
2680 * @deprecated Use Http::get() instead
2682 function wfGetHTTP( $url, $timeout = 'default' ) {
2683 wfDeprecated(__FUNCTION__
);
2684 return Http
::get( $url, $timeout );
2688 * Alias for modularized function
2689 * @deprecated Use Http::isLocalURL() instead
2691 function wfIsLocalURL( $url ) {
2692 wfDeprecated(__FUNCTION__
);
2693 return Http
::isLocalURL( $url );
2696 function wfHttpOnlySafe() {
2697 global $wgHttpOnlyBlacklist;
2698 if( !version_compare("5.2", PHP_VERSION
, "<") )
2701 if( isset( $_SERVER['HTTP_USER_AGENT'] ) ) {
2702 foreach( $wgHttpOnlyBlacklist as $regex ) {
2703 if( preg_match( $regex, $_SERVER['HTTP_USER_AGENT'] ) ) {
2713 * Initialise php session
2715 function wfSetupSession() {
2716 global $wgSessionsInMemcached, $wgCookiePath, $wgCookieDomain,
2717 $wgCookieSecure, $wgCookieHttpOnly, $wgSessionHandler;
2718 if( $wgSessionsInMemcached ) {
2719 require_once( 'MemcachedSessions.php' );
2720 } elseif( $wgSessionHandler && $wgSessionHandler != ini_get( 'session.save_handler' ) ) {
2721 # Only set this if $wgSessionHandler isn't null and session.save_handler
2722 # hasn't already been set to the desired value (that causes errors)
2723 ini_set ( 'session.save_handler', $wgSessionHandler );
2725 $httpOnlySafe = wfHttpOnlySafe();
2726 wfDebugLog( 'cookie',
2727 'session_set_cookie_params: "' . implode( '", "',
2733 $httpOnlySafe && $wgCookieHttpOnly ) ) . '"' );
2734 if( $httpOnlySafe && $wgCookieHttpOnly ) {
2735 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookieHttpOnly );
2737 // PHP 5.1 throws warnings if you pass the HttpOnly parameter for 5.2.
2738 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
2740 session_cache_limiter( 'private, must-revalidate' );
2741 wfSuppressWarnings();
2743 wfRestoreWarnings();
2747 * Get an object from the precompiled serialized directory
2749 * @return mixed The variable on success, false on failure
2751 function wfGetPrecompiledData( $name ) {
2754 $file = "$IP/serialized/$name";
2755 if ( file_exists( $file ) ) {
2756 $blob = file_get_contents( $file );
2758 return unserialize( $blob );
2764 function wfGetCaller( $level = 2 ) {
2765 $backtrace = wfDebugBacktrace();
2766 if ( isset( $backtrace[$level] ) ) {
2767 return wfFormatStackFrame($backtrace[$level]);
2769 $caller = 'unknown';
2774 /** Return a string consisting all callers in stack, somewhat useful sometimes for profiling specific points */
2775 function wfGetAllCallers() {
2776 return implode('/', array_map('wfFormatStackFrame',array_reverse(wfDebugBacktrace())));
2779 /** Return a string representation of frame */
2780 function wfFormatStackFrame($frame) {
2781 return isset( $frame["class"] )?
2782 $frame["class"]."::".$frame["function"]:
2789 function wfMemcKey( /*... */ ) {
2790 $args = func_get_args();
2791 $key = wfWikiID() . ':' . implode( ':', $args );
2796 * Get a cache key for a foreign DB
2798 function wfForeignMemcKey( $db, $prefix /*, ... */ ) {
2799 $args = array_slice( func_get_args(), 2 );
2801 $key = "$db-$prefix:" . implode( ':', $args );
2803 $key = $db . ':' . implode( ':', $args );
2809 * Get an ASCII string identifying this wiki
2810 * This is used as a prefix in memcached keys
2812 function wfWikiID() {
2813 global $wgDBprefix, $wgDBname;
2814 if ( $wgDBprefix ) {
2815 return "$wgDBname-$wgDBprefix";
2822 * Split a wiki ID into DB name and table prefix
2824 function wfSplitWikiID( $wiki ) {
2825 $bits = explode( '-', $wiki, 2 );
2826 if ( count( $bits ) < 2 ) {
2833 * Get a Database object.
2834 * @param integer $db Index of the connection to get. May be DB_MASTER for the
2835 * master (for write queries), DB_SLAVE for potentially lagged
2836 * read queries, or an integer >= 0 for a particular server.
2838 * @param mixed $groups Query groups. An array of group names that this query
2839 * belongs to. May contain a single string if the query is only
2842 * @param string $wiki The wiki ID, or false for the current wiki
2844 * Note: multiple calls to wfGetDB(DB_SLAVE) during the course of one request
2845 * will always return the same object, unless the underlying connection or load
2846 * balancer is manually destroyed.
2848 function &wfGetDB( $db, $groups = array(), $wiki = false ) {
2849 return wfGetLB( $wiki )->getConnection( $db, $groups, $wiki );
2853 * Get a load balancer object.
2855 * @param array $groups List of query groups
2856 * @param string $wiki Wiki ID, or false for the current wiki
2857 * @return LoadBalancer
2859 function wfGetLB( $wiki = false ) {
2860 return wfGetLBFactory()->getMainLB( $wiki );
2864 * Get the load balancer factory object
2866 function &wfGetLBFactory() {
2867 return LBFactory
::singleton();
2872 * Shortcut for RepoGroup::singleton()->findFile()
2873 * @param mixed $title Title object or string. May be interwiki.
2874 * @param mixed $time Requested time for an archived image, or false for the
2875 * current version. An image object will be returned which
2876 * was created at the specified time.
2877 * @param mixed $flags FileRepo::FIND_ flags
2878 * @param boolean $bypass Bypass the file cache even if it could be used
2879 * @return File, or false if the file does not exist
2881 function wfFindFile( $title, $time = false, $flags = 0, $bypass = false ) {
2882 if( !$time && !$flags && !$bypass ) {
2883 return FileCache
::singleton()->findFile( $title );
2885 return RepoGroup
::singleton()->findFile( $title, $time, $flags );
2890 * Get an object referring to a locally registered file.
2891 * Returns a valid placeholder object if the file does not exist.
2893 function wfLocalFile( $title ) {
2894 return RepoGroup
::singleton()->getLocalRepo()->newFile( $title );
2898 * Should low-performance queries be disabled?
2902 function wfQueriesMustScale() {
2903 global $wgMiserMode;
2905 ||
( SiteStats
::pages() > 100000
2906 && SiteStats
::edits() > 1000000
2907 && SiteStats
::users() > 10000 );
2911 * Get the path to a specified script file, respecting file
2912 * extensions; this is a wrapper around $wgScriptExtension etc.
2914 * @param string $script Script filename, sans extension
2917 function wfScript( $script = 'index' ) {
2918 global $wgScriptPath, $wgScriptExtension;
2919 return "{$wgScriptPath}/{$script}{$wgScriptExtension}";
2923 * Convenience function converts boolean values into "true"
2924 * or "false" (string) values
2926 * @param bool $value
2929 function wfBoolToStr( $value ) {
2930 return $value ?
'true' : 'false';
2934 * Load an extension messages file
2937 function wfLoadExtensionMessages( $extensionName, $langcode = false ) {
2941 * Get a platform-independent path to the null file, e.g.
2946 function wfGetNull() {
2947 return wfIsWindows()
2953 * Displays a maxlag error
2955 * @param string $host Server that lags the most
2956 * @param int $lag Maxlag (actual)
2957 * @param int $maxLag Maxlag (requested)
2959 function wfMaxlagError( $host, $lag, $maxLag ) {
2960 global $wgShowHostnames;
2961 header( 'HTTP/1.1 503 Service Unavailable' );
2962 header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
2963 header( 'X-Database-Lag: ' . intval( $lag ) );
2964 header( 'Content-Type: text/plain' );
2965 if( $wgShowHostnames ) {
2966 echo "Waiting for $host: $lag seconds lagged\n";
2968 echo "Waiting for a database server: $lag seconds lagged\n";
2973 * Throws a warning that $function is deprecated
2974 * @param string $function
2977 function wfDeprecated( $function ) {
2978 wfWarn( "Use of $function is deprecated.", 2 );
2981 function wfWarn( $msg, $callerOffset = 1, $level = E_USER_NOTICE
) {
2982 $callers = wfDebugBacktrace();
2983 if( isset( $callers[$callerOffset+
1] ) ){
2984 $callerfunc = $callers[$callerOffset+
1];
2985 $callerfile = $callers[$callerOffset];
2986 if( isset( $callerfile['file'] ) && isset( $callerfile['line'] ) ){
2987 $file = $callerfile['file'] . ' at line ' . $callerfile['line'];
2989 $file = '(internal function)';
2992 if( isset( $callerfunc['class'] ) )
2993 $func .= $callerfunc['class'] . '::';
2994 $func .= @$callerfunc['function'];
2995 $msg .= " [Called from $func in $file]";
2998 global $wgDevelopmentWarnings;
2999 if ( $wgDevelopmentWarnings ) {
3000 trigger_error( $msg, $level );
3002 wfDebug( "$msg\n" );
3007 * Sleep until the worst slave's replication lag is less than or equal to
3008 * $maxLag, in seconds. Use this when updating very large numbers of rows, as
3009 * in maintenance scripts, to avoid causing too much lag. Of course, this is
3010 * a no-op if there are no slaves.
3012 * Every time the function has to wait for a slave, it will print a message to
3013 * that effect (and then sleep for a little while), so it's probably not best
3014 * to use this outside maintenance scripts in its present form.
3016 * @param int $maxLag
3019 function wfWaitForSlaves( $maxLag ) {
3022 list( $host, $lag ) = $lb->getMaxLag();
3023 while( $lag > $maxLag ) {
3024 $name = @gethostbyaddr
( $host );
3025 if( $name !== false ) {
3028 print "Waiting for $host (lagged $lag seconds)...\n";
3030 list( $host, $lag ) = $lb->getMaxLag();
3036 * Output some plain text in command-line mode or in the installer (updaters.inc).
3037 * Do not use it in any other context, its behaviour is subject to change.
3039 function wfOut( $s ) {
3040 static $lineStarted = false;
3041 global $wgCommandLineMode;
3042 if ( $wgCommandLineMode && !defined( 'MEDIAWIKI_INSTALL' ) ) {
3045 echo htmlspecialchars( $s );
3051 * Count down from $n to zero on the terminal, with a one-second pause
3052 * between showing each number. For use in command-line scripts.
3054 function wfCountDown( $n ) {
3055 for ( $i = $n; $i >= 0; $i-- ) {
3057 echo str_repeat( "\x08", strlen( $i +
1 ) );
3068 /** Generate a random 32-character hexadecimal token.
3069 * @param mixed $salt Some sort of salt, if necessary, to add to random characters before hashing.
3071 function wfGenerateToken( $salt = '' ) {
3072 $salt = serialize($salt);
3074 return md5( mt_rand( 0, 0x7fffffff ) . $salt );
3078 * Replace all invalid characters with -
3079 * @param mixed $title Filename to process
3081 function wfStripIllegalFilenameChars( $name ) {
3082 $name = wfBaseName( $name );
3083 $name = preg_replace ( "/[^".Title
::legalChars()."]|:/", '-', $name );
3088 * Insert array into another array after the specified *KEY*
3089 * @param array $array The array.
3090 * @param array $insert The array to insert.
3091 * @param mixed $after The key to insert after
3093 function wfArrayInsertAfter( $array, $insert, $after ) {
3094 // Find the offset of the element to insert after.
3095 $keys = array_keys($array);
3096 $offsetByKey = array_flip( $keys );
3098 $offset = $offsetByKey[$after];
3100 // Insert at the specified offset
3101 $before = array_slice( $array, 0, $offset +
1, true );
3102 $after = array_slice( $array, $offset +
1, count($array)-$offset, true );
3104 $output = $before +
$insert +
$after;
3109 /* Recursively converts the parameter (an object) to an array with the same data */
3110 function wfObjectToArray( $object, $recursive = true ) {
3112 foreach ( get_object_vars($object) as $key => $value ) {
3113 if ( is_object($value) && $recursive ) {
3114 $value = wfObjectToArray( $value );
3117 $array[$key] = $value;