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];
75 if ( !function_exists( 'array_diff_key' ) ) {
77 * Exists in PHP 5.1.0+
78 * Not quite compatible, two-argument version only
79 * Null values will cause problems due to this use of isset()
81 function array_diff_key( $left, $right ) {
83 foreach ( $left as $key => $unused ) {
84 if ( isset( $right[$key] ) ) {
85 unset( $result[$key] );
92 // Support for Wietse Venema's taint feature
93 if ( !function_exists( 'istainted' ) ) {
94 function istainted( $var ) {
97 function taint( $var, $level = 0 ) {}
98 function untaint( $var, $level = 0 ) {}
99 define( 'TC_HTML', 1 );
100 define( 'TC_SHELL', 1 );
101 define( 'TC_MYSQL', 1 );
102 define( 'TC_PCRE', 1 );
103 define( 'TC_SELF', 1 );
109 * Like array_diff( $a, $b ) except that it works with two-dimensional arrays.
111 function wfArrayDiff2( $a, $b ) {
112 return array_udiff( $a, $b, 'wfArrayDiff2_cmp' );
114 function wfArrayDiff2_cmp( $a, $b ) {
115 if ( !is_array( $a ) ) {
116 return strcmp( $a, $b );
117 } elseif ( count( $a ) !== count( $b ) ) {
118 return count( $a ) < count( $b ) ?
-1 : 1;
122 while( ( list( $keyA, $valueA ) = each( $a ) ) && ( list( $keyB, $valueB ) = each( $b ) ) ) {
123 $cmp = strcmp( $valueA, $valueB );
133 * Wrapper for clone(), for compatibility with PHP4-friendly extensions.
134 * PHP 5 won't let you declare a 'clone' function, even conditionally,
135 * so it has to be a wrapper with a different name.
137 function wfClone( $object ) {
138 return clone( $object );
142 * Seed Mersenne Twister
143 * No-op for compatibility; only necessary in PHP < 4.2.0
145 function wfSeedRandom() {
150 * Get a random decimal value between 0 and 1, in a way
151 * not likely to give duplicate values for any realistic
152 * number of articles.
156 function wfRandom() {
157 # The maximum random value is "only" 2^31-1, so get two random
158 # values to reduce the chance of dupes
159 $max = mt_getrandmax() +
1;
160 $rand = number_format( (mt_rand() * $max +
mt_rand())
161 / $max / $max, 12, '.', '' );
166 * We want some things to be included as literal characters in our title URLs
167 * for prettiness, which urlencode encodes by default. According to RFC 1738,
168 * all of the following should be safe:
172 * But + is not safe because it's used to indicate a space; &= are only safe in
173 * paths and not in queries (and we don't distinguish here); ' seems kind of
174 * scary; and urlencode() doesn't touch -_. to begin with. Plus, although /
175 * is reserved, we don't care. So the list we unescape is:
179 * %2F in the page titles seems to fatally break for some reason.
184 function wfUrlencode( $s ) {
185 $s = urlencode( $s );
187 array( '%3B','%3A','%40','%24','%21','%2A','%28','%29','%2C','%2F' ),
188 array( ';', ':', '@', '$', '!', '*', '(', ')', ',', '/' ),
196 * Sends a line to the debug log if enabled or, optionally, to a comment in output.
197 * In normal operation this is a NOP.
199 * Controlling globals:
200 * $wgDebugLogFile - points to the log file
201 * $wgProfileOnly - if set, normal debug messages will not be recorded.
202 * $wgDebugRawPage - if false, 'action=raw' hits will not result in debug output.
203 * $wgDebugComments - if on, some debug items may appear in comments in the HTML output.
205 * @param $text String
206 * @param $logonly Bool: set true to avoid appearing in HTML when $wgDebugComments is set
208 function wfDebug( $text, $logonly = false ) {
209 global $wgOut, $wgDebugLogFile, $wgDebugComments, $wgProfileOnly, $wgDebugRawPage;
210 global $wgDebugLogPrefix;
211 static $recursion = 0;
213 static $cache = array(); // Cache of unoutputted messages
215 # Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
216 if ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' && !$wgDebugRawPage ) {
220 if ( $wgDebugComments && !$logonly ) {
223 if ( !isset( $wgOut ) ) {
226 if ( !StubObject
::isRealObject( $wgOut ) ) {
235 // add the message and possible cached ones to the output
236 array_map( array( $wgOut, 'debug' ), $cache );
239 if ( '' != $wgDebugLogFile && !$wgProfileOnly ) {
240 # Strip unprintables; they can switch terminal modes when binary data
241 # gets dumped, which is pretty annoying.
242 $text = preg_replace( '![\x00-\x08\x0b\x0c\x0e-\x1f]!', ' ', $text );
243 $text = $wgDebugLogPrefix . $text;
244 wfErrorLog( $text, $wgDebugLogFile );
249 * Send a line giving PHP memory usage.
250 * @param $exact Bool : print exact values instead of kilobytes (default: false)
252 function wfDebugMem( $exact = false ) {
253 $mem = memory_get_usage();
255 $mem = floor( $mem / 1024 ) . ' kilobytes';
259 wfDebug( "Memory usage: $mem\n" );
263 * Send a line to a supplementary debug log file, if configured, or main debug log if not.
264 * $wgDebugLogGroups[$logGroup] should be set to a filename to send to a separate log.
266 * @param $logGroup String
267 * @param $text String
268 * @param $public Bool: whether to log the event in the public log if no private
269 * log file is specified, (default true)
271 function wfDebugLog( $logGroup, $text, $public = true ) {
272 global $wgDebugLogGroups, $wgShowHostnames;
273 $text = trim($text)."\n";
274 if( isset( $wgDebugLogGroups[$logGroup] ) ) {
275 $time = wfTimestamp( TS_DB
);
277 if ( $wgShowHostnames ) {
278 $host = wfHostname();
282 wfErrorLog( "$time $host $wiki: $text", $wgDebugLogGroups[$logGroup] );
283 } else if ( $public === true ) {
284 wfDebug( $text, true );
289 * Log for database errors
290 * @param $text String: database error message.
292 function wfLogDBError( $text ) {
293 global $wgDBerrorLog, $wgDBname;
294 if ( $wgDBerrorLog ) {
295 $host = trim(`hostname`
);
296 $text = date('D M j G:i:s T Y') . "\t$host\t$wgDBname\t$text";
297 wfErrorLog( $text, $wgDBerrorLog );
302 * Log to a file without getting "file size exceeded" signals.
304 * Can also log to TCP or UDP with the syntax udp://host:port/prefix. This will
305 * send lines to the specified port, prefixed by the specified prefix and a space.
307 function wfErrorLog( $text, $file ) {
308 if ( substr( $file, 0, 4 ) == 'udp:' ) {
309 if ( preg_match( '!^(tcp|udp):(?://)?\[([0-9a-fA-F:]+)\]:(\d+)(?:/(.*))?$!', $file, $m ) ) {
310 // IPv6 bracketed host
314 $prefix = isset( $m[4] ) ?
$m[4] : false;
315 } elseif ( preg_match( '!^(tcp|udp):(?://)?([a-zA-Z0-9.-]+):(\d+)(?:/(.*))?$!', $file, $m ) ) {
319 $prefix = isset( $m[4] ) ?
$m[4] : false;
321 throw new MWException( __METHOD__
.": Invalid UDP specification" );
323 // Clean it up for the multiplexer
324 if ( strval( $prefix ) !== '' ) {
325 $text = preg_replace( '/^/m', $prefix . ' ', $text );
326 if ( substr( $text, -1 ) != "\n" ) {
331 $sock = fsockopen( "$protocol://$host", $port );
335 fwrite( $sock, $text );
338 wfSuppressWarnings();
339 $exists = file_exists( $file );
340 $size = $exists ?
filesize( $file ) : false;
341 if ( !$exists ||
( $size !== false && $size +
strlen( $text ) < 0x7fffffff ) ) {
342 error_log( $text, 3, $file );
351 function wfLogProfilingData() {
352 global $wgRequestTime, $wgDebugLogFile, $wgDebugRawPage, $wgRequest;
353 global $wgProfiler, $wgUser;
354 if ( !isset( $wgProfiler ) )
358 $elapsed = $now - $wgRequestTime;
359 $prof = wfGetProfilingOutput( $wgRequestTime, $elapsed );
361 if( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) )
362 $forward = ' forwarded for ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
363 if( !empty( $_SERVER['HTTP_CLIENT_IP'] ) )
364 $forward .= ' client IP ' . $_SERVER['HTTP_CLIENT_IP'];
365 if( !empty( $_SERVER['HTTP_FROM'] ) )
366 $forward .= ' from ' . $_SERVER['HTTP_FROM'];
368 $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
369 // Don't unstub $wgUser at this late stage just for statistics purposes
370 if( StubObject
::isRealObject($wgUser) && $wgUser->isAnon() )
372 $log = sprintf( "%s\t%04.3f\t%s\n",
373 gmdate( 'YmdHis' ), $elapsed,
374 urldecode( $wgRequest->getRequestURL() . $forward ) );
375 if ( '' != $wgDebugLogFile && ( $wgRequest->getVal('action') != 'raw' ||
$wgDebugRawPage ) ) {
376 wfErrorLog( $log . $prof, $wgDebugLogFile );
381 * Check if the wiki read-only lock file is present. This can be used to lock
382 * off editing functions, but doesn't guarantee that the database will not be
386 function wfReadOnly() {
387 global $wgReadOnlyFile, $wgReadOnly;
389 if ( !is_null( $wgReadOnly ) ) {
390 return (bool)$wgReadOnly;
392 if ( '' == $wgReadOnlyFile ) {
395 // Set $wgReadOnly for faster access next time
396 if ( is_file( $wgReadOnlyFile ) ) {
397 $wgReadOnly = file_get_contents( $wgReadOnlyFile );
401 return (bool)$wgReadOnly;
404 function wfReadOnlyReason() {
411 * Return a Language object from $langcode
412 * @param $langcode Mixed: either:
413 * - a Language object
414 * - code of the language to get the message for, if it is
415 * a valid code create a language for that language, if
416 * it is a string but not a valid code then make a basic
418 * - a boolean: if it's false then use the current users
419 * language (as a fallback for the old parameter
420 * functionality), or if it is true then use the wikis
421 * @return Language object
423 function wfGetLangObj( $langcode = false ){
424 # Identify which language to get or create a language object for.
425 if( $langcode instanceof Language
)
426 # Great, we already have the object!
430 if( $langcode === $wgContLang->getCode() ||
$langcode === true )
431 # $langcode is the language code of the wikis content language object.
432 # or it is a boolean and value is true
436 if( $langcode === $wgLang->getCode() ||
$langcode === false )
437 # $langcode is the language code of user language object.
438 # or it was a boolean and value is false
441 $validCodes = array_keys( Language
::getLanguageNames() );
442 if( in_array( $langcode, $validCodes ) )
443 # $langcode corresponds to a valid language.
444 return Language
::factory( $langcode );
446 # $langcode is a string, but not a valid language code; use content language.
447 wfDebug( "Invalid language code passed to wfGetLangObj, falling back to content language.\n" );
452 * Get a message from anywhere, for the current user language.
454 * Use wfMsgForContent() instead if the message should NOT
455 * change depending on the user preferences.
457 * @param $key String: lookup key for the message, usually
458 * defined in languages/Language.php
460 * This function also takes extra optional parameters (not
461 * shown in the function definition), which can by used to
462 * insert variable text into the predefined message.
464 function wfMsg( $key ) {
465 $args = func_get_args();
466 array_shift( $args );
467 return wfMsgReal( $key, $args, true );
471 * Same as above except doesn't transform the message
473 function wfMsgNoTrans( $key ) {
474 $args = func_get_args();
475 array_shift( $args );
476 return wfMsgReal( $key, $args, true, false, false );
480 * Get a message from anywhere, for the current global language
481 * set with $wgLanguageCode.
483 * Use this if the message should NOT change dependent on the
484 * language set in the user's preferences. This is the case for
485 * most text written into logs, as well as link targets (such as
486 * the name of the copyright policy page). Link titles, on the
487 * other hand, should be shown in the UI language.
489 * Note that MediaWiki allows users to change the user interface
490 * language in their preferences, but a single installation
491 * typically only contains content in one language.
493 * Be wary of this distinction: If you use wfMsg() where you should
494 * use wfMsgForContent(), a user of the software may have to
495 * customize over 70 messages in order to, e.g., fix a link in every
498 * @param $key String: lookup key for the message, usually
499 * defined in languages/Language.php
501 function wfMsgForContent( $key ) {
502 global $wgForceUIMsgAsContentMsg;
503 $args = func_get_args();
504 array_shift( $args );
506 if( is_array( $wgForceUIMsgAsContentMsg ) &&
507 in_array( $key, $wgForceUIMsgAsContentMsg ) )
509 return wfMsgReal( $key, $args, true, $forcontent );
513 * Same as above except doesn't transform the message
515 function wfMsgForContentNoTrans( $key ) {
516 global $wgForceUIMsgAsContentMsg;
517 $args = func_get_args();
518 array_shift( $args );
520 if( is_array( $wgForceUIMsgAsContentMsg ) &&
521 in_array( $key, $wgForceUIMsgAsContentMsg ) )
523 return wfMsgReal( $key, $args, true, $forcontent, false );
527 * Get a message from the language file, for the UI elements
529 function wfMsgNoDB( $key ) {
530 $args = func_get_args();
531 array_shift( $args );
532 return wfMsgReal( $key, $args, false );
536 * Get a message from the language file, for the content
538 function wfMsgNoDBForContent( $key ) {
539 global $wgForceUIMsgAsContentMsg;
540 $args = func_get_args();
541 array_shift( $args );
543 if( is_array( $wgForceUIMsgAsContentMsg ) &&
544 in_array( $key, $wgForceUIMsgAsContentMsg ) )
546 return wfMsgReal( $key, $args, false, $forcontent );
551 * Really get a message
552 * @param $key String: key to get.
554 * @param $useDB Boolean
555 * @param $transform Boolean: Whether or not to transform the message.
556 * @param $forContent Boolean
557 * @return String: the requested message.
559 function wfMsgReal( $key, $args, $useDB = true, $forContent=false, $transform = true ) {
560 wfProfileIn( __METHOD__
);
561 $message = wfMsgGetKey( $key, $useDB, $forContent, $transform );
562 $message = wfMsgReplaceArgs( $message, $args );
563 wfProfileOut( __METHOD__
);
568 * This function provides the message source for messages to be edited which are *not* stored in the database.
569 * @param $key String:
571 function wfMsgWeirdKey ( $key ) {
572 $source = wfMsgGetKey( $key, false, true, false );
573 if ( wfEmptyMsg( $key, $source ) )
580 * Fetch a message string value, but don't replace any keys yet.
583 * @param string $langcode Code of the language to get the message for, or
584 * behaves as a content language switch if it is a
589 function wfMsgGetKey( $key, $useDB, $langCode = false, $transform = true ) {
590 global $wgContLang, $wgMessageCache;
592 wfRunHooks('NormalizeMessageKey', array(&$key, &$useDB, &$langCode, &$transform));
594 # If $wgMessageCache isn't initialised yet, try to return something sensible.
595 if( is_object( $wgMessageCache ) ) {
596 $message = $wgMessageCache->get( $key, $useDB, $langCode );
598 $message = $wgMessageCache->transform( $message );
601 $lang = wfGetLangObj( $langCode );
603 # MessageCache::get() does this already, Language::getMessage() doesn't
604 # ISSUE: Should we try to handle "message/lang" here too?
605 $key = str_replace( ' ' , '_' , $wgContLang->lcfirst( $key ) );
607 if( is_object( $lang ) ) {
608 $message = $lang->getMessage( $key );
618 * Replace message parameter keys on the given formatted output.
620 * @param string $message
625 function wfMsgReplaceArgs( $message, $args ) {
626 # Fix windows line-endings
627 # Some messages are split with explode("\n", $msg)
628 $message = str_replace( "\r", '', $message );
631 if ( count( $args ) ) {
632 if ( is_array( $args[0] ) ) {
633 $args = array_values( $args[0] );
635 $replacementKeys = array();
636 foreach( $args as $n => $param ) {
637 $replacementKeys['$' . ($n +
1)] = $param;
639 $message = strtr( $message, $replacementKeys );
646 * Return an HTML-escaped version of a message.
647 * Parameter replacements, if any, are done *after* the HTML-escaping,
648 * so parameters may contain HTML (eg links or form controls). Be sure
649 * to pre-escape them if you really do want plaintext, or just wrap
650 * the whole thing in htmlspecialchars().
653 * @param string ... parameters
656 function wfMsgHtml( $key ) {
657 $args = func_get_args();
658 array_shift( $args );
659 return wfMsgReplaceArgs( htmlspecialchars( wfMsgGetKey( $key, true ) ), $args );
663 * Return an HTML version of message
664 * Parameter replacements, if any, are done *after* parsing the wiki-text message,
665 * so parameters may contain HTML (eg links or form controls). Be sure
666 * to pre-escape them if you really do want plaintext, or just wrap
667 * the whole thing in htmlspecialchars().
670 * @param string ... parameters
673 function wfMsgWikiHtml( $key ) {
675 $args = func_get_args();
676 array_shift( $args );
677 return wfMsgReplaceArgs( $wgOut->parse( wfMsgGetKey( $key, true ), /* can't be set to false */ true ), $args );
681 * Returns message in the requested format
682 * @param string $key Key of the message
683 * @param array $options Processing rules. Can take the following options:
684 * <i>parse</i>: parses wikitext to html
685 * <i>parseinline</i>: parses wikitext to html and removes the surrounding
686 * p's added by parser or tidy
687 * <i>escape</i>: filters message through htmlspecialchars
688 * <i>escapenoentities</i>: same, but allows entity references like through
689 * <i>replaceafter</i>: parameters are substituted after parsing or escaping
690 * <i>parsemag</i>: transform the message using magic phrases
691 * <i>content</i>: fetch message for content language instead of interface
692 * Also can accept a single associative argument, of the form 'language' => 'xx':
693 * <i>language</i>: Language object or language code to fetch message for
694 * (overriden by <i>content</i>), its behaviour with parser, parseinline
695 * and parsemag is undefined.
696 * Behavior for conflicting options (e.g., parse+parseinline) is undefined.
698 function wfMsgExt( $key, $options ) {
701 $args = func_get_args();
702 array_shift( $args );
703 array_shift( $args );
704 $options = (array)$options;
706 foreach( $options as $arrayKey => $option ) {
707 if( !preg_match( '/^[0-9]+|language$/', $arrayKey ) ) {
708 # An unknown index, neither numeric nor "language"
709 trigger_error( "wfMsgExt called with incorrect parameter key $arrayKey", E_USER_WARNING
);
710 } elseif( preg_match( '/^[0-9]+$/', $arrayKey ) && !in_array( $option,
711 array( 'parse', 'parseinline', 'escape', 'escapenoentities',
712 'replaceafter', 'parsemag', 'content' ) ) ) {
713 # A numeric index with unknown value
714 trigger_error( "wfMsgExt called with incorrect parameter $option", E_USER_WARNING
);
718 if( in_array('content', $options, true ) ) {
721 } elseif( array_key_exists('language', $options) ) {
723 $langCode = wfGetLangObj( $options['language'] );
729 $string = wfMsgGetKey( $key, /*DB*/true, $langCode, /*Transform*/false );
731 if( !in_array('replaceafter', $options, true ) ) {
732 $string = wfMsgReplaceArgs( $string, $args );
735 if( in_array('parse', $options, true ) ) {
736 $string = $wgOut->parse( $string, true, !$forContent );
737 } elseif ( in_array('parseinline', $options, true ) ) {
738 $string = $wgOut->parse( $string, true, !$forContent );
740 if( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $string, $m ) ) {
743 } elseif ( in_array('parsemag', $options, true ) ) {
744 global $wgMessageCache;
745 if ( isset( $wgMessageCache ) ) {
746 $string = $wgMessageCache->transform( $string,
748 is_object( $langCode ) ?
$langCode : null );
752 if ( in_array('escape', $options, true ) ) {
753 $string = htmlspecialchars ( $string );
754 } elseif ( in_array( 'escapenoentities', $options, true ) ) {
755 $string = Sanitizer
::escapeHtmlAllowEntities( $string );
758 if( in_array('replaceafter', $options, true ) ) {
759 $string = wfMsgReplaceArgs( $string, $args );
767 * Just like exit() but makes a note of it.
768 * Commits open transactions except if the error parameter is set
770 * @deprecated Please return control to the caller or throw an exception
772 function wfAbruptExit( $error = false ){
773 static $called = false;
779 $bt = wfDebugBacktrace();
781 for($i = 0; $i < count($bt) ; $i++
){
782 $file = isset($bt[$i]['file']) ?
$bt[$i]['file'] : "unknown";
783 $line = isset($bt[$i]['line']) ?
$bt[$i]['line'] : "unknown";
784 wfDebug("WARNING: Abrupt exit in $file at line $line\n");
787 wfDebug("WARNING: Abrupt exit\n");
790 wfLogProfilingData();
793 wfGetLB()->closeAll();
799 * @deprecated Please return control the caller or throw an exception
801 function wfErrorExit() {
802 wfAbruptExit( true );
806 * Print a simple message and die, returning nonzero to the shell if any.
807 * Plain die() fails to return nonzero to the shell if you pass a string.
810 function wfDie( $msg='' ) {
816 * Throw a debugging exception. This function previously once exited the process,
817 * but now throws an exception instead, with similar results.
819 * @param string $msg Message shown when dieing.
821 function wfDebugDieBacktrace( $msg = '' ) {
822 throw new MWException( $msg );
826 * Fetch server name for use in error reporting etc.
827 * Use real server name if available, so we know which machine
828 * in a server farm generated the current page.
831 function wfHostname() {
833 if ( is_null( $host ) ) {
834 if ( function_exists( 'posix_uname' ) ) {
835 // This function not present on Windows
836 $uname = @posix_uname
();
840 if( is_array( $uname ) && isset( $uname['nodename'] ) ) {
841 $host = $uname['nodename'];
842 } elseif ( getenv( 'COMPUTERNAME' ) ) {
843 # Windows computer name
844 $host = getenv( 'COMPUTERNAME' );
846 # This may be a virtual server.
847 $host = $_SERVER['SERVER_NAME'];
854 * Returns a HTML comment with the elapsed time since request.
855 * This method has no side effects.
858 function wfReportTime() {
859 global $wgRequestTime, $wgShowHostnames;
862 $elapsed = $now - $wgRequestTime;
864 return $wgShowHostnames
865 ?
sprintf( "<!-- Served by %s in %01.3f secs. -->", wfHostname(), $elapsed )
866 : sprintf( "<!-- Served in %01.3f secs. -->", $elapsed );
870 * Safety wrapper for debug_backtrace().
872 * With Zend Optimizer 3.2.0 loaded, this causes segfaults under somewhat
873 * murky circumstances, which may be triggered in part by stub objects
874 * or other fancy talkin'.
876 * Will return an empty array if Zend Optimizer is detected, otherwise
877 * the output from debug_backtrace() (trimmed).
879 * @return array of backtrace information
881 function wfDebugBacktrace() {
882 if( extension_loaded( 'Zend Optimizer' ) ) {
883 wfDebug( "Zend Optimizer detected; skipping debug_backtrace for safety.\n" );
886 return array_slice( debug_backtrace(), 1 );
890 function wfBacktrace() {
891 global $wgCommandLineMode;
893 if ( $wgCommandLineMode ) {
898 $backtrace = wfDebugBacktrace();
899 foreach( $backtrace as $call ) {
900 if( isset( $call['file'] ) ) {
901 $f = explode( DIRECTORY_SEPARATOR
, $call['file'] );
902 $file = $f[count($f)-1];
906 if( isset( $call['line'] ) ) {
907 $line = $call['line'];
911 if ( $wgCommandLineMode ) {
912 $msg .= "$file line $line calls ";
914 $msg .= '<li>' . $file . ' line ' . $line . ' calls ';
916 if( !empty( $call['class'] ) ) $msg .= $call['class'] . '::';
917 $msg .= $call['function'] . '()';
919 if ( $wgCommandLineMode ) {
925 if ( $wgCommandLineMode ) {
935 /* Some generic result counters, pulled out of SearchEngine */
941 function wfShowingResults( $offset, $limit ) {
943 return wfMsgExt( 'showingresults', array( 'parseinline' ), $wgLang->formatNum( $limit ),
944 $wgLang->formatNum( $offset+
1 ) );
950 function wfShowingResultsNum( $offset, $limit, $num ) {
952 return wfMsgExt( 'showingresultsnum', array( 'parseinline' ), $wgLang->formatNum( $limit ),
953 $wgLang->formatNum( $offset+
1 ), $wgLang->formatNum( $num ) );
957 * Generate (prev x| next x) (20|50|100...) type links for paging
958 * @param $offset string
960 * @param $link string
961 * @param $query string, optional URL query parameter string
962 * @param $atend bool, optional param for specified if this is the last page
964 function wfViewPrevNext( $offset, $limit, $link, $query = '', $atend = false ) {
966 $fmtLimit = $wgLang->formatNum( $limit );
967 # Get prev/next link display text
968 $prev = wfMsgHtml( 'prevn', $fmtLimit );
969 $next = wfMsgHtml( 'nextn', $fmtLimit );
970 # Get prev/next link title text
971 $pTitle = wfMsgExt( 'prevn-title', array('parsemag','escape'), $fmtLimit );
972 $nTitle = wfMsgExt( 'nextn-title', array('parsemag','escape'), $fmtLimit );
973 # Fetch the title object
974 if( is_object( $link ) ) {
977 $title = Title
::newFromText( $link );
978 if( is_null( $title ) ) {
982 # Make 'previous' link
984 $po = $offset - $limit;
986 $q = "limit={$limit}&offset={$po}";
990 $plink = '<a href="' . $title->escapeLocalUrl( $q ) . "\" title=\"{$pTitle}\" class=\"mw-prevlink\">{$prev}</a>";
995 $no = $offset +
$limit;
996 $q = "limit={$limit}&offset={$no}";
1003 $nlink = '<a href="' . $title->escapeLocalUrl( $q ) . "\" title=\"{$nTitle}\" class=\"mw-nextlink\">{$next}</a>";
1005 # Make links to set number of items per page
1006 $nums = $wgLang->pipeList( array(
1007 wfNumLink( $offset, 20, $title, $query ),
1008 wfNumLink( $offset, 50, $title, $query ),
1009 wfNumLink( $offset, 100, $title, $query ),
1010 wfNumLink( $offset, 250, $title, $query ),
1011 wfNumLink( $offset, 500, $title, $query )
1013 return wfMsg( 'viewprevnext', $plink, $nlink, $nums );
1017 * Generate links for (20|50|100...) items-per-page links
1018 * @param $offset string
1020 * @param $title Title
1021 * @param $query string, optional URL query parameter string
1023 function wfNumLink( $offset, $limit, $title, $query = '' ) {
1025 if( $query == '' ) {
1030 $q .= "limit={$limit}&offset={$offset}";
1031 $fmtLimit = $wgLang->formatNum( $limit );
1032 $lTitle = wfMsgExt('shown-title',array('parsemag','escape'),$limit);
1033 $s = '<a href="' . $title->escapeLocalUrl( $q ) . "\" title=\"{$lTitle}\" class=\"mw-numlink\">{$fmtLimit}</a>";
1039 * @todo FIXME: we may want to blacklist some broken browsers
1041 * @return bool Whereas client accept gzip compression
1043 function wfClientAcceptsGzip() {
1046 # FIXME: we may want to blacklist some broken browsers
1049 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
1050 $_SERVER['HTTP_ACCEPT_ENCODING'],
1052 if( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) return false;
1053 wfDebug( " accepts gzip\n" );
1061 * Obtain the offset and limit values from the request string;
1062 * used in special pages
1064 * @param $deflimit Default limit if none supplied
1065 * @param $optionname Name of a user preference to check against
1069 function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) {
1071 return $wgRequest->getLimitOffset( $deflimit, $optionname );
1075 * Escapes the given text so that it may be output using addWikiText()
1076 * without any linking, formatting, etc. making its way through. This
1077 * is achieved by substituting certain characters with HTML entities.
1078 * As required by the callers, <nowiki> is not used. It currently does
1079 * not filter out characters which have special meaning only at the
1080 * start of a line, such as "*".
1082 * @param string $text Text to be escaped
1084 function wfEscapeWikiText( $text ) {
1085 $text = str_replace(
1086 array( '[', '|', ']', '\'', 'ISBN ', 'RFC ', '://', "\n=", '{{' ), # }}
1087 array( '[', '|', ']', ''', 'ISBN ', 'RFC ', '://', "\n=", '{{' ),
1088 htmlspecialchars($text) );
1095 function wfQuotedPrintable( $string, $charset = '' ) {
1096 # Probably incomplete; see RFC 2045
1097 if( empty( $charset ) ) {
1098 global $wgInputEncoding;
1099 $charset = $wgInputEncoding;
1101 $charset = strtoupper( $charset );
1102 $charset = str_replace( 'ISO-8859', 'ISO8859', $charset ); // ?
1104 $illegal = '\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\xff=';
1105 $replace = $illegal . '\t ?_';
1106 if( !preg_match( "/[$illegal]/", $string ) ) return $string;
1107 $out = "=?$charset?Q?";
1108 $out .= preg_replace( "/([$replace])/e", 'sprintf("=%02X",ord("$1"))', $string );
1119 return microtime(true);
1123 * Sets dest to source and returns the original value of dest
1124 * If source is NULL, it just returns the value, it doesn't set the variable
1126 function wfSetVar( &$dest, $source ) {
1128 if ( !is_null( $source ) ) {
1135 * As for wfSetVar except setting a bit
1137 function wfSetBit( &$dest, $bit, $state = true ) {
1138 $temp = (bool)($dest & $bit );
1139 if ( !is_null( $state ) ) {
1150 * This function takes two arrays as input, and returns a CGI-style string, e.g.
1151 * "days=7&limit=100". Options in the first array override options in the second.
1152 * Options set to "" will not be output.
1154 function wfArrayToCGI( $array1, $array2 = NULL )
1156 if ( !is_null( $array2 ) ) {
1157 $array1 = $array1 +
$array2;
1161 foreach ( $array1 as $key => $value ) {
1162 if ( '' !== $value ) {
1166 if(is_array($value))
1169 foreach($value as $v)
1171 $cgi .= ($firstTime ?
'' : '&') .
1172 urlencode( $key . '[]' ) . '=' .
1178 $cgi .= urlencode( $key ) . '=' .
1179 urlencode( $value );
1186 * This is the logical opposite of wfArrayToCGI(): it accepts a query string as
1187 * its argument and returns the same string in array form. This allows compa-
1188 * tibility with legacy functions that accept raw query strings instead of nice
1189 * arrays. Of course, keys and values are urldecode()d. Don't try passing in-
1190 * valid query strings, or it will explode.
1192 * @param $query string Query string
1193 * @return array Array version of input
1195 function wfCgiToArray( $query ) {
1196 if( isset( $query[0] ) and $query[0] == '?' ) {
1197 $query = substr( $query, 1 );
1199 $bits = explode( '&', $query );
1201 foreach( $bits as $bit ) {
1205 list( $key, $value ) = explode( '=', $bit );
1206 $key = urldecode( $key );
1207 $value = urldecode( $value );
1208 $ret[$key] = $value;
1214 * Append a query string to an existing URL, which may or may not already
1215 * have query string parameters already. If so, they will be combined.
1217 * @param string $url
1218 * @param string $query
1221 function wfAppendQuery( $url, $query ) {
1222 if( $query != '' ) {
1223 if( false === strpos( $url, '?' ) ) {
1234 * Expand a potentially local URL to a fully-qualified URL.
1235 * Assumes $wgServer is correct. :)
1236 * @param string $url, either fully-qualified or a local path + query
1237 * @return string Fully-qualified URL
1239 function wfExpandUrl( $url ) {
1240 if( substr( $url, 0, 1 ) == '/' ) {
1242 return $wgServer . $url;
1249 * This is obsolete, use SquidUpdate::purge()
1252 function wfPurgeSquidServers ($urlArr) {
1253 SquidUpdate
::purge( $urlArr );
1257 * Windows-compatible version of escapeshellarg()
1258 * Windows doesn't recognise single-quotes in the shell, but the escapeshellarg()
1259 * function puts single quotes in regardless of OS.
1261 * Also fixes the locale problems on Linux in PHP 5.2.6+ (bug backported to
1262 * earlier distro releases of PHP)
1264 function wfEscapeShellArg( ) {
1265 wfInitShellLocale();
1267 $args = func_get_args();
1270 foreach ( $args as $arg ) {
1277 if ( wfIsWindows() ) {
1278 // Escaping for an MSVC-style command line parser
1279 // Ref: http://mailman.lyra.org/pipermail/scite-interest/2002-March/000436.html
1280 // Double the backslashes before any double quotes. Escape the double quotes.
1281 $tokens = preg_split( '/(\\\\*")/', $arg, -1, PREG_SPLIT_DELIM_CAPTURE
);
1284 foreach ( $tokens as $token ) {
1286 $arg .= str_replace( '\\', '\\\\', substr( $token, 0, -1 ) ) . '\\"';
1292 // Double the backslashes before the end of the string, because
1293 // we will soon add a quote
1295 if ( preg_match( '/^(.*?)(\\\\+)$/', $arg, $m ) ) {
1296 $arg = $m[1] . str_replace( '\\', '\\\\', $m[2] );
1299 // Add surrounding quotes
1300 $retVal .= '"' . $arg . '"';
1302 $retVal .= escapeshellarg( $arg );
1309 * wfMerge attempts to merge differences between three texts.
1310 * Returns true for a clean merge and false for failure or a conflict.
1312 function wfMerge( $old, $mine, $yours, &$result ){
1315 # This check may also protect against code injection in
1316 # case of broken installations.
1317 if( !$wgDiff3 ||
!file_exists( $wgDiff3 ) ) {
1318 wfDebug( "diff3 not found\n" );
1322 # Make temporary files
1324 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
1325 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
1326 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
1328 fwrite( $oldtextFile, $old ); fclose( $oldtextFile );
1329 fwrite( $mytextFile, $mine ); fclose( $mytextFile );
1330 fwrite( $yourtextFile, $yours ); fclose( $yourtextFile );
1332 # Check for a conflict
1333 $cmd = $wgDiff3 . ' -a --overlap-only ' .
1334 wfEscapeShellArg( $mytextName ) . ' ' .
1335 wfEscapeShellArg( $oldtextName ) . ' ' .
1336 wfEscapeShellArg( $yourtextName );
1337 $handle = popen( $cmd, 'r' );
1339 if( fgets( $handle, 1024 ) ){
1347 $cmd = $wgDiff3 . ' -a -e --merge ' .
1348 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
1349 $handle = popen( $cmd, 'r' );
1352 $data = fread( $handle, 8192 );
1353 if ( strlen( $data ) == 0 ) {
1359 unlink( $mytextName ); unlink( $oldtextName ); unlink( $yourtextName );
1361 if ( $result === '' && $old !== '' && $conflict == false ) {
1362 wfDebug( "Unexpected null result from diff3. Command: $cmd\n" );
1369 * Returns unified plain-text diff of two texts.
1370 * Useful for machine processing of diffs.
1371 * @param $before string The text before the changes.
1372 * @param $after string The text after the changes.
1373 * @param $params string Command-line options for the diff command.
1374 * @return string Unified diff of $before and $after
1376 function wfDiff( $before, $after, $params = '-u' ) {
1379 # This check may also protect against code injection in
1380 # case of broken installations.
1381 if( !file_exists( $wgDiff ) ){
1382 wfDebug( "diff executable not found\n" );
1383 $diffs = new Diff( explode( "\n", $before ), explode( "\n", $after ) );
1384 $format = new UnifiedDiffFormatter();
1385 return $format->format( $diffs );
1388 # Make temporary files
1390 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
1391 $newtextFile = fopen( $newtextName = tempnam( $td, 'merge-your-' ), 'w' );
1393 fwrite( $oldtextFile, $before ); fclose( $oldtextFile );
1394 fwrite( $newtextFile, $after ); fclose( $newtextFile );
1396 // Get the diff of the two files
1397 $cmd = "$wgDiff " . $params . ' ' .wfEscapeShellArg( $oldtextName, $newtextName );
1399 $h = popen( $cmd, 'r' );
1404 $data = fread( $h, 8192 );
1405 if ( strlen( $data ) == 0 ) {
1413 unlink( $oldtextName );
1414 unlink( $newtextName );
1416 // Kill the --- and +++ lines. They're not useful.
1417 $diff_lines = explode( "\n", $diff );
1418 if (strpos( $diff_lines[0], '---' ) === 0) {
1419 unset($diff_lines[0]);
1421 if (strpos( $diff_lines[1], '+++' ) === 0) {
1422 unset($diff_lines[1]);
1425 $diff = implode( "\n", $diff_lines );
1431 * A wrapper around the PHP function var_export().
1432 * Either print it or add it to the regular output ($wgOut).
1434 * @param $var A PHP variable to dump.
1436 function wfVarDump( $var ) {
1438 $s = str_replace("\n","<br />\n", var_export( $var, true ) . "\n");
1439 if ( headers_sent() ||
!@is_object
( $wgOut ) ) {
1442 $wgOut->addHTML( $s );
1447 * Provide a simple HTTP error.
1449 function wfHttpError( $code, $label, $desc ) {
1452 header( "HTTP/1.0 $code $label" );
1453 header( "Status: $code $label" );
1454 $wgOut->sendCacheControl();
1456 header( 'Content-type: text/html; charset=utf-8' );
1457 print "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">".
1458 "<html><head><title>" .
1459 htmlspecialchars( $label ) .
1460 "</title></head><body><h1>" .
1461 htmlspecialchars( $label ) .
1463 nl2br( htmlspecialchars( $desc ) ) .
1464 "</p></body></html>\n";
1468 * Clear away any user-level output buffers, discarding contents.
1470 * Suitable for 'starting afresh', for instance when streaming
1471 * relatively large amounts of data without buffering, or wanting to
1472 * output image files without ob_gzhandler's compression.
1474 * The optional $resetGzipEncoding parameter controls suppression of
1475 * the Content-Encoding header sent by ob_gzhandler; by default it
1476 * is left. See comments for wfClearOutputBuffers() for why it would
1479 * Note that some PHP configuration options may add output buffer
1480 * layers which cannot be removed; these are left in place.
1482 * @param bool $resetGzipEncoding
1484 function wfResetOutputBuffers( $resetGzipEncoding=true ) {
1485 if( $resetGzipEncoding ) {
1486 // Suppress Content-Encoding and Content-Length
1487 // headers from 1.10+s wfOutputHandler
1488 global $wgDisableOutputCompression;
1489 $wgDisableOutputCompression = true;
1491 while( $status = ob_get_status() ) {
1492 if( $status['type'] == 0 /* PHP_OUTPUT_HANDLER_INTERNAL */ ) {
1493 // Probably from zlib.output_compression or other
1494 // PHP-internal setting which can't be removed.
1496 // Give up, and hope the result doesn't break
1500 if( !ob_end_clean() ) {
1501 // Could not remove output buffer handler; abort now
1502 // to avoid getting in some kind of infinite loop.
1505 if( $resetGzipEncoding ) {
1506 if( $status['name'] == 'ob_gzhandler' ) {
1507 // Reset the 'Content-Encoding' field set by this handler
1508 // so we can start fresh.
1509 header( 'Content-Encoding:' );
1517 * More legible than passing a 'false' parameter to wfResetOutputBuffers():
1519 * Clear away output buffers, but keep the Content-Encoding header
1520 * produced by ob_gzhandler, if any.
1522 * This should be used for HTTP 304 responses, where you need to
1523 * preserve the Content-Encoding header of the real result, but
1524 * also need to suppress the output of ob_gzhandler to keep to spec
1525 * and avoid breaking Firefox in rare cases where the headers and
1526 * body are broken over two packets.
1528 function wfClearOutputBuffers() {
1529 wfResetOutputBuffers( false );
1533 * Converts an Accept-* header into an array mapping string values to quality
1536 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
1537 # No arg means accept anything (per HTTP spec)
1539 return array( $def => 1.0 );
1544 $parts = explode( ',', $accept );
1546 foreach( $parts as $part ) {
1547 # FIXME: doesn't deal with params like 'text/html; level=1'
1548 @list
( $value, $qpart ) = explode( ';', trim( $part ) );
1550 if( !isset( $qpart ) ) {
1551 $prefs[$value] = 1.0;
1552 } elseif( preg_match( '/q\s*=\s*(\d*\.\d+)/', $qpart, $match ) ) {
1553 $prefs[$value] = floatval($match[1]);
1561 * Checks if a given MIME type matches any of the keys in the given
1562 * array. Basic wildcards are accepted in the array keys.
1564 * Returns the matching MIME type (or wildcard) if a match, otherwise
1567 * @param string $type
1568 * @param array $avail
1572 function mimeTypeMatch( $type, $avail ) {
1573 if( array_key_exists($type, $avail) ) {
1576 $parts = explode( '/', $type );
1577 if( array_key_exists( $parts[0] . '/*', $avail ) ) {
1578 return $parts[0] . '/*';
1579 } elseif( array_key_exists( '*/*', $avail ) ) {
1588 * Returns the 'best' match between a client's requested internet media types
1589 * and the server's list of available types. Each list should be an associative
1590 * array of type to preference (preference is a float between 0.0 and 1.0).
1591 * Wildcards in the types are acceptable.
1593 * @param array $cprefs Client's acceptable type list
1594 * @param array $sprefs Server's offered types
1597 * @todo FIXME: doesn't handle params like 'text/plain; charset=UTF-8'
1598 * XXX: generalize to negotiate other stuff
1600 function wfNegotiateType( $cprefs, $sprefs ) {
1603 foreach( array_keys($sprefs) as $type ) {
1604 $parts = explode( '/', $type );
1605 if( $parts[1] != '*' ) {
1606 $ckey = mimeTypeMatch( $type, $cprefs );
1608 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1613 foreach( array_keys( $cprefs ) as $type ) {
1614 $parts = explode( '/', $type );
1615 if( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
1616 $skey = mimeTypeMatch( $type, $sprefs );
1618 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1626 foreach( array_keys( $combine ) as $type ) {
1627 if( $combine[$type] > $bestq ) {
1629 $bestq = $combine[$type];
1638 * Returns an array where the values in the first array are replaced by the
1639 * values in the second array with the corresponding keys
1643 function wfArrayLookup( $a, $b ) {
1644 return array_flip( array_intersect( array_flip( $a ), array_keys( $b ) ) );
1648 * Convenience function; returns MediaWiki timestamp for the present time.
1651 function wfTimestampNow() {
1653 return wfTimestamp( TS_MW
, time() );
1657 * Reference-counted warning suppression
1659 function wfSuppressWarnings( $end = false ) {
1660 static $suppressCount = 0;
1661 static $originalLevel = false;
1664 if ( $suppressCount ) {
1666 if ( !$suppressCount ) {
1667 error_reporting( $originalLevel );
1671 if ( !$suppressCount ) {
1672 $originalLevel = error_reporting( E_ALL
& ~
( E_WARNING | E_NOTICE
) );
1679 * Restore error level to previous value
1681 function wfRestoreWarnings() {
1682 wfSuppressWarnings( true );
1685 # Autodetect, convert and provide timestamps of various types
1688 * Unix time - the number of seconds since 1970-01-01 00:00:00 UTC
1690 define('TS_UNIX', 0);
1693 * MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
1698 * MySQL DATETIME (YYYY-MM-DD HH:MM:SS)
1703 * RFC 2822 format, for E-mail and HTTP headers
1705 define('TS_RFC2822', 3);
1708 * ISO 8601 format with no timezone: 1986-02-09T20:00:00Z
1710 * This is used by Special:Export
1712 define('TS_ISO_8601', 4);
1715 * An Exif timestamp (YYYY:MM:DD HH:MM:SS)
1717 * @see http://exif.org/Exif2-2.PDF The Exif 2.2 spec, see page 28 for the
1718 * DateTime tag and page 36 for the DateTimeOriginal and
1719 * DateTimeDigitized tags.
1721 define('TS_EXIF', 5);
1724 * Oracle format time.
1726 define('TS_ORACLE', 6);
1729 * Postgres format time.
1731 define('TS_POSTGRES', 7);
1736 define('TS_DB2', 8);
1739 * @param mixed $outputtype A timestamp in one of the supported formats, the
1740 * function will autodetect which format is supplied
1741 * and act accordingly.
1742 * @return string Time in the format specified in $outputtype
1744 function wfTimestamp($outputtype=TS_UNIX
,$ts=0) {
1749 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)$/D',$ts,$da)) {
1751 } elseif (preg_match('/^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/D',$ts,$da)) {
1753 } elseif (preg_match('/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/D',$ts,$da)) {
1755 } elseif (preg_match('/^\d{1,13}$/D',$ts)) {
1758 } elseif (preg_match('/^\d{1,2}-...-\d\d(?:\d\d)? \d\d\.\d\d\.\d\d/', $ts)) {
1760 $uts = strtotime(preg_replace('/(\d\d)\.(\d\d)\.(\d\d)(\.(\d+))?/', "$1:$2:$3",
1761 str_replace("+00:00", "UTC", $ts)));
1762 } elseif (preg_match('/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.*\d*)?Z$/', $ts, $da)) {
1764 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.*\d*[\+\- ](\d\d)$/',$ts,$da)) {
1766 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.*\d* GMT$/',$ts,$da)) {
1769 # Bogus value; fall back to the epoch...
1770 wfDebug("wfTimestamp() fed bogus time value: $outputtype; $ts\n");
1774 if (count( $da ) ) {
1775 // Warning! gmmktime() acts oddly if the month or day is set to 0
1776 // We may want to handle that explicitly at some point
1777 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1778 (int)$da[2],(int)$da[3],(int)$da[1]);
1781 switch($outputtype) {
1785 return gmdate( 'YmdHis', $uts );
1787 return gmdate( 'Y-m-d H:i:s', $uts );
1789 return gmdate( 'Y-m-d\TH:i:s\Z', $uts );
1790 // This shouldn't ever be used, but is included for completeness
1792 return gmdate( 'Y:m:d H:i:s', $uts );
1794 return gmdate( 'D, d M Y H:i:s', $uts ) . ' GMT';
1796 return gmdate( 'd-M-y h.i.s A', $uts) . ' +00:00';
1798 return gmdate( 'Y-m-d H:i:s', $uts) . ' GMT';
1800 return gmdate( 'Y-m-d H:i:s', $uts);
1802 throw new MWException( 'wfTimestamp() called with illegal output type.');
1807 * Return a formatted timestamp, or null if input is null.
1808 * For dealing with nullable timestamp columns in the database.
1809 * @param int $outputtype
1813 function wfTimestampOrNull( $outputtype = TS_UNIX
, $ts = null ) {
1814 if( is_null( $ts ) ) {
1817 return wfTimestamp( $outputtype, $ts );
1822 * Check if the operating system is Windows
1824 * @return bool True if it's Windows, False otherwise.
1826 function wfIsWindows() {
1827 if (substr(php_uname(), 0, 7) == 'Windows') {
1835 * Swap two variables
1837 function swap( &$x, &$y ) {
1843 function wfGetCachedNotice( $name ) {
1844 global $wgOut, $wgRenderHashAppend, $parserMemc;
1845 $fname = 'wfGetCachedNotice';
1846 wfProfileIn( $fname );
1850 if( $name === 'default' ) {
1852 global $wgSiteNotice;
1853 $notice = $wgSiteNotice;
1854 if( empty( $notice ) ) {
1855 wfProfileOut( $fname );
1859 $notice = wfMsgForContentNoTrans( $name );
1860 if( wfEmptyMsg( $name, $notice ) ||
$notice == '-' ) {
1861 wfProfileOut( $fname );
1866 // Use the extra hash appender to let eg SSL variants separately cache.
1867 $key = wfMemcKey( $name . $wgRenderHashAppend );
1868 $cachedNotice = $parserMemc->get( $key );
1869 if( is_array( $cachedNotice ) ) {
1870 if( md5( $notice ) == $cachedNotice['hash'] ) {
1871 $notice = $cachedNotice['html'];
1880 if( is_object( $wgOut ) ) {
1881 $parsed = $wgOut->parse( $notice );
1882 $parserMemc->set( $key, array( 'html' => $parsed, 'hash' => md5( $notice ) ), 600 );
1885 wfDebug( 'wfGetCachedNotice called for ' . $name . ' with no $wgOut available'."\n" );
1890 wfProfileOut( $fname );
1894 function wfGetNamespaceNotice() {
1898 if ( !isset( $wgTitle ) ||
!is_object( $wgTitle ) )
1901 $fname = 'wfGetNamespaceNotice';
1902 wfProfileIn( $fname );
1904 $key = "namespacenotice-" . $wgTitle->getNsText();
1905 $namespaceNotice = wfGetCachedNotice( $key );
1906 if ( $namespaceNotice && substr ( $namespaceNotice , 0 ,7 ) != "<p><" ) {
1907 $namespaceNotice = '<div id="namespacebanner">' . $namespaceNotice . "</div>";
1909 $namespaceNotice = "";
1912 wfProfileOut( $fname );
1913 return $namespaceNotice;
1916 function wfGetSiteNotice() {
1917 global $wgUser, $wgSiteNotice;
1918 $fname = 'wfGetSiteNotice';
1919 wfProfileIn( $fname );
1922 if( wfRunHooks( 'SiteNoticeBefore', array( &$siteNotice ) ) ) {
1923 if( is_object( $wgUser ) && $wgUser->isLoggedIn() ) {
1924 $siteNotice = wfGetCachedNotice( 'sitenotice' );
1926 $anonNotice = wfGetCachedNotice( 'anonnotice' );
1927 if( !$anonNotice ) {
1928 $siteNotice = wfGetCachedNotice( 'sitenotice' );
1930 $siteNotice = $anonNotice;
1933 if( !$siteNotice ) {
1934 $siteNotice = wfGetCachedNotice( 'default' );
1938 wfRunHooks( 'SiteNoticeAfter', array( &$siteNotice ) );
1939 wfProfileOut( $fname );
1944 * BC wrapper for MimeMagic::singleton()
1947 function &wfGetMimeMagic() {
1948 return MimeMagic
::singleton();
1952 * Tries to get the system directory for temporary files.
1953 * The TMPDIR, TMP, and TEMP environment variables are checked in sequence,
1954 * and if none are set /tmp is returned as the generic Unix default.
1956 * NOTE: When possible, use the tempfile() function to create temporary
1957 * files to avoid race conditions on file creation, etc.
1961 function wfTempDir() {
1962 foreach( array( 'TMPDIR', 'TMP', 'TEMP' ) as $var ) {
1963 $tmp = getenv( $var );
1964 if( $tmp && file_exists( $tmp ) && is_dir( $tmp ) && is_writable( $tmp ) ) {
1968 # Hope this is Unix of some kind!
1973 * Make directory, and make all parent directories if they don't exist
1975 * @param string $dir Full path to directory to create
1976 * @param int $mode Chmod value to use, default is $wgDirectoryMode
1979 function wfMkdirParents( $dir, $mode = null ) {
1980 global $wgDirectoryMode;
1982 if( strval( $dir ) === '' ||
file_exists( $dir ) )
1985 if ( is_null( $mode ) )
1986 $mode = $wgDirectoryMode;
1988 return mkdir( $dir, $mode, true ); // PHP5 <3
1992 * Increment a statistics counter
1994 function wfIncrStats( $key ) {
1995 global $wgStatsMethod;
1997 if( $wgStatsMethod == 'udp' ) {
1998 global $wgUDPProfilerHost, $wgUDPProfilerPort, $wgDBname;
2001 $socket=socket_create(AF_INET
, SOCK_DGRAM
, SOL_UDP
);
2002 $statline="stats/{$wgDBname} - 1 1 1 1 1 -total\n";
2003 socket_sendto($socket,$statline,strlen($statline),0,$wgUDPProfilerHost,$wgUDPProfilerPort);
2005 $statline="stats/{$wgDBname} - 1 1 1 1 1 {$key}\n";
2006 @socket_sendto
($socket,$statline,strlen($statline),0,$wgUDPProfilerHost,$wgUDPProfilerPort);
2007 } elseif( $wgStatsMethod == 'cache' ) {
2009 $key = wfMemcKey( 'stats', $key );
2010 if ( is_null( $wgMemc->incr( $key ) ) ) {
2011 $wgMemc->add( $key, 1 );
2019 * @param mixed $nr The number to format
2020 * @param int $acc The number of digits after the decimal point, default 2
2021 * @param bool $round Whether or not to round the value, default true
2024 function wfPercent( $nr, $acc = 2, $round = true ) {
2025 $ret = sprintf( "%.${acc}f", $nr );
2026 return $round ?
round( $ret, $acc ) . '%' : "$ret%";
2030 * Encrypt a username/password.
2032 * @param string $userid ID of the user
2033 * @param string $password Password of the user
2034 * @return string Hashed password
2035 * @deprecated Use User::crypt() or User::oldCrypt() instead
2037 function wfEncryptPassword( $userid, $password ) {
2038 wfDeprecated(__FUNCTION__
);
2039 # Just wrap around User::oldCrypt()
2040 return User
::oldCrypt($password, $userid);
2044 * Appends to second array if $value differs from that in $default
2046 function wfAppendToArrayIfNotDefault( $key, $value, $default, &$changed ) {
2047 if ( is_null( $changed ) ) {
2048 throw new MWException('GlobalFunctions::wfAppendToArrayIfNotDefault got null');
2050 if ( $default[$key] !== $value ) {
2051 $changed[$key] = $value;
2056 * Since wfMsg() and co suck, they don't return false if the message key they
2057 * looked up didn't exist but a XHTML string, this function checks for the
2058 * nonexistance of messages by looking at wfMsg() output
2060 * @param $msg The message key looked up
2061 * @param $wfMsgOut The output of wfMsg*()
2064 function wfEmptyMsg( $msg, $wfMsgOut ) {
2065 return $wfMsgOut === htmlspecialchars( "<$msg>" );
2069 * Find out whether or not a mixed variable exists in a string
2071 * @param mixed needle
2072 * @param string haystack
2075 function in_string( $needle, $str ) {
2076 return strpos( $str, $needle ) !== false;
2079 function wfSpecialList( $page, $details ) {
2081 $details = $details ?
' ' . $wgContLang->getDirMark() . "($details)" : "";
2082 return $page . $details;
2086 * Returns a regular expression of url protocols
2090 function wfUrlProtocols() {
2091 global $wgUrlProtocols;
2093 // Support old-style $wgUrlProtocols strings, for backwards compatibility
2094 // with LocalSettings files from 1.5
2095 if ( is_array( $wgUrlProtocols ) ) {
2096 $protocols = array();
2097 foreach ($wgUrlProtocols as $protocol)
2098 $protocols[] = preg_quote( $protocol, '/' );
2100 return implode( '|', $protocols );
2102 return $wgUrlProtocols;
2107 * Safety wrapper around ini_get() for boolean settings.
2108 * The values returned from ini_get() are pre-normalized for settings
2109 * set via php.ini or php_flag/php_admin_flag... but *not*
2110 * for those set via php_value/php_admin_value.
2112 * It's fairly common for people to use php_value instead of php_flag,
2113 * which can leave you with an 'off' setting giving a false positive
2114 * for code that just takes the ini_get() return value as a boolean.
2116 * To make things extra interesting, setting via php_value accepts
2117 * "true" and "yes" as true, but php.ini and php_flag consider them false. :)
2118 * Unrecognized values go false... again opposite PHP's own coercion
2119 * from string to bool.
2121 * Luckily, 'properly' set settings will always come back as '0' or '1',
2122 * so we only have to worry about them and the 'improper' settings.
2124 * I frickin' hate PHP... :P
2126 * @param string $setting
2129 function wfIniGetBool( $setting ) {
2130 $val = ini_get( $setting );
2131 // 'on' and 'true' can't have whitespace around them, but '1' can.
2132 return strtolower( $val ) == 'on'
2133 ||
strtolower( $val ) == 'true'
2134 ||
strtolower( $val ) == 'yes'
2135 ||
preg_match( "/^\s*[+-]?0*[1-9]/", $val ); // approx C atoi() function
2139 * Execute a shell command, with time and memory limits mirrored from the PHP
2140 * configuration if supported.
2141 * @param $cmd Command line, properly escaped for shell.
2142 * @param &$retval optional, will receive the program's exit code.
2143 * (non-zero is usually failure)
2144 * @return collected stdout as a string (trailing newlines stripped)
2146 function wfShellExec( $cmd, &$retval=null ) {
2147 global $IP, $wgMaxShellMemory, $wgMaxShellFileSize, $wgMaxShellTime;
2150 if ( is_null( $disabled ) ) {
2152 if( wfIniGetBool( 'safe_mode' ) ) {
2153 wfDebug( "wfShellExec can't run in safe_mode, PHP's exec functions are too broken.\n" );
2156 $functions = explode( ',', ini_get( 'disable_functions' ) );
2157 $functions = array_map( 'trim', $functions );
2158 $functions = array_map( 'strtolower', $functions );
2159 if ( in_array( 'passthru', $functions ) ) {
2160 wfDebug( "passthru is in disabled_functions\n" );
2166 return "Unable to run external programs in safe mode.";
2169 wfInitShellLocale();
2171 if ( php_uname( 's' ) == 'Linux' ) {
2172 $time = intval( $wgMaxShellTime );
2173 $mem = intval( $wgMaxShellMemory );
2174 $filesize = intval( $wgMaxShellFileSize );
2176 if ( $time > 0 && $mem > 0 ) {
2177 $script = "$IP/bin/ulimit4.sh";
2178 if ( is_executable( $script ) ) {
2179 $cmd = escapeshellarg( $script ) . " $time $mem $filesize " . escapeshellarg( $cmd );
2182 } elseif ( php_uname( 's' ) == 'Windows NT' ) {
2183 # This is a hack to work around PHP's flawed invocation of cmd.exe
2184 # http://news.php.net/php.internals/21796
2185 $cmd = '"' . $cmd . '"';
2187 wfDebug( "wfShellExec: $cmd\n" );
2189 $retval = 1; // error by default?
2191 passthru( $cmd, $retval );
2192 $output = ob_get_contents();
2195 if ( $retval == 127 ) {
2196 wfDebugLog( 'exec', "Possibly missing executable file: $cmd\n" );
2202 * Workaround for http://bugs.php.net/bug.php?id=45132
2203 * escapeshellarg() destroys non-ASCII characters if LANG is not a UTF-8 locale
2205 function wfInitShellLocale() {
2206 static $done = false;
2207 if ( $done ) return;
2209 global $wgShellLocale;
2210 if ( !wfIniGetBool( 'safe_mode' ) ) {
2211 putenv( "LC_CTYPE=$wgShellLocale" );
2212 setlocale( LC_CTYPE
, $wgShellLocale );
2217 * This function works like "use VERSION" in Perl, the program will die with a
2218 * backtrace if the current version of PHP is less than the version provided
2220 * This is useful for extensions which due to their nature are not kept in sync
2221 * with releases, and might depend on other versions of PHP than the main code
2223 * Note: PHP might die due to parsing errors in some cases before it ever
2224 * manages to call this function, such is life
2226 * @see perldoc -f use
2228 * @param mixed $version The version to check, can be a string, an integer, or
2231 function wfUsePHP( $req_ver ) {
2232 $php_ver = PHP_VERSION
;
2234 if ( version_compare( $php_ver, (string)$req_ver, '<' ) )
2235 throw new MWException( "PHP $req_ver required--this is only $php_ver" );
2239 * This function works like "use VERSION" in Perl except it checks the version
2240 * of MediaWiki, the program will die with a backtrace if the current version
2241 * of MediaWiki is less than the version provided.
2243 * This is useful for extensions which due to their nature are not kept in sync
2246 * @see perldoc -f use
2248 * @param mixed $version The version to check, can be a string, an integer, or
2251 function wfUseMW( $req_ver ) {
2254 if ( version_compare( $wgVersion, (string)$req_ver, '<' ) )
2255 throw new MWException( "MediaWiki $req_ver required--this is only $wgVersion" );
2259 * @deprecated use StringUtils::escapeRegexReplacement
2261 function wfRegexReplacement( $string ) {
2262 return StringUtils
::escapeRegexReplacement( $string );
2266 * Return the final portion of a pathname.
2267 * Reimplemented because PHP5's basename() is buggy with multibyte text.
2268 * http://bugs.php.net/bug.php?id=33898
2270 * PHP's basename() only considers '\' a pathchar on Windows and Netware.
2271 * We'll consider it so always, as we don't want \s in our Unix paths either.
2273 * @param string $path
2274 * @param string $suffix to remove if present
2277 function wfBaseName( $path, $suffix='' ) {
2278 $encSuffix = ($suffix == '')
2280 : ( '(?:' . preg_quote( $suffix, '#' ) . ')?' );
2282 if( preg_match( "#([^/\\\\]*?){$encSuffix}[/\\\\]*$#", $path, $matches ) ) {
2290 * Generate a relative path name to the given file.
2291 * May explode on non-matching case-insensitive paths,
2292 * funky symlinks, etc.
2294 * @param string $path Absolute destination path including target filename
2295 * @param string $from Absolute source path, directory only
2298 function wfRelativePath( $path, $from ) {
2299 // Normalize mixed input on Windows...
2300 $path = str_replace( '/', DIRECTORY_SEPARATOR
, $path );
2301 $from = str_replace( '/', DIRECTORY_SEPARATOR
, $from );
2303 // Trim trailing slashes -- fix for drive root
2304 $path = rtrim( $path, DIRECTORY_SEPARATOR
);
2305 $from = rtrim( $from, DIRECTORY_SEPARATOR
);
2307 $pieces = explode( DIRECTORY_SEPARATOR
, dirname( $path ) );
2308 $against = explode( DIRECTORY_SEPARATOR
, $from );
2310 if( $pieces[0] !== $against[0] ) {
2311 // Non-matching Windows drive letters?
2312 // Return a full path.
2316 // Trim off common prefix
2317 while( count( $pieces ) && count( $against )
2318 && $pieces[0] == $against[0] ) {
2319 array_shift( $pieces );
2320 array_shift( $against );
2323 // relative dots to bump us to the parent
2324 while( count( $against ) ) {
2325 array_unshift( $pieces, '..' );
2326 array_shift( $against );
2329 array_push( $pieces, wfBaseName( $path ) );
2331 return implode( DIRECTORY_SEPARATOR
, $pieces );
2335 * Backwards array plus for people who haven't bothered to read the PHP manual
2336 * XXX: will not darn your socks for you.
2338 * @param array $array1, [$array2, [...]]
2341 function wfArrayMerge( $array1/* ... */ ) {
2342 $args = func_get_args();
2343 $args = array_reverse( $args, true );
2345 foreach ( $args as $arg ) {
2352 * Merge arrays in the style of getUserPermissionsErrors, with duplicate removal
2354 * wfMergeErrorArrays(
2355 * array( array( 'x' ) ),
2356 * array( array( 'x', '2' ) ),
2357 * array( array( 'x' ) ),
2358 * array( array( 'y') )
2362 * array( 'x', '2' ),
2367 function wfMergeErrorArrays(/*...*/) {
2368 $args = func_get_args();
2370 foreach ( $args as $errors ) {
2371 foreach ( $errors as $params ) {
2372 $spec = implode( "\t", $params );
2373 $out[$spec] = $params;
2376 return array_values( $out );
2380 * parse_url() work-alike, but non-broken. Differences:
2382 * 1) Does not raise warnings on bad URLs (just returns false)
2383 * 2) Handles protocols that don't use :// (e.g., mailto: and news:) correctly
2384 * 3) Adds a "delimiter" element to the array, either '://' or ':' (see (2))
2386 * @param string $url A URL to parse
2387 * @return array Bits of the URL in an associative array, per PHP docs
2389 function wfParseUrl( $url ) {
2390 global $wgUrlProtocols; // Allow all protocols defined in DefaultSettings/LocalSettings.php
2391 wfSuppressWarnings();
2392 $bits = parse_url( $url );
2393 wfRestoreWarnings();
2398 // most of the protocols are followed by ://, but mailto: and sometimes news: not, check for it
2399 if ( in_array( $bits['scheme'] . '://', $wgUrlProtocols ) ) {
2400 $bits['delimiter'] = '://';
2401 } elseif ( in_array( $bits['scheme'] . ':', $wgUrlProtocols ) ) {
2402 $bits['delimiter'] = ':';
2403 // parse_url detects for news: and mailto: the host part of an url as path
2404 // We have to correct this wrong detection
2405 if ( isset ( $bits['path'] ) ) {
2406 $bits['host'] = $bits['path'];
2417 * Make a URL index, appropriate for the el_index field of externallinks.
2419 function wfMakeUrlIndex( $url ) {
2420 $bits = wfParseUrl( $url );
2422 // Reverse the labels in the hostname, convert to lower case
2423 // For emails reverse domainpart only
2424 if ( $bits['scheme'] == 'mailto' ) {
2425 $mailparts = explode( '@', $bits['host'], 2 );
2426 if ( count($mailparts) === 2 ) {
2427 $domainpart = strtolower( implode( '.', array_reverse( explode( '.', $mailparts[1] ) ) ) );
2429 // No domain specified, don't mangle it
2432 $reversedHost = $domainpart . '@' . $mailparts[0];
2434 $reversedHost = strtolower( implode( '.', array_reverse( explode( '.', $bits['host'] ) ) ) );
2436 // Add an extra dot to the end
2437 // Why? Is it in wrong place in mailto links?
2438 if ( substr( $reversedHost, -1, 1 ) !== '.' ) {
2439 $reversedHost .= '.';
2441 // Reconstruct the pseudo-URL
2442 $prot = $bits['scheme'];
2443 $index = $prot . $bits['delimiter'] . $reversedHost;
2444 // Leave out user and password. Add the port, path, query and fragment
2445 if ( isset( $bits['port'] ) ) $index .= ':' . $bits['port'];
2446 if ( isset( $bits['path'] ) ) {
2447 $index .= $bits['path'];
2451 if ( isset( $bits['query'] ) ) $index .= '?' . $bits['query'];
2452 if ( isset( $bits['fragment'] ) ) $index .= '#' . $bits['fragment'];
2457 * Do any deferred updates and clear the list
2458 * TODO: This could be in Wiki.php if that class made any sense at all
2460 function wfDoUpdates()
2462 global $wgPostCommitUpdateList, $wgDeferredUpdateList;
2463 foreach ( $wgDeferredUpdateList as $update ) {
2464 $update->doUpdate();
2466 foreach ( $wgPostCommitUpdateList as $update ) {
2467 $update->doUpdate();
2469 $wgDeferredUpdateList = array();
2470 $wgPostCommitUpdateList = array();
2474 * @deprecated use StringUtils::explodeMarkup
2476 function wfExplodeMarkup( $separator, $text ) {
2477 return StringUtils
::explodeMarkup( $separator, $text );
2481 * Convert an arbitrarily-long digit string from one numeric base
2482 * to another, optionally zero-padding to a minimum column width.
2484 * Supports base 2 through 36; digit values 10-36 are represented
2485 * as lowercase letters a-z. Input is case-insensitive.
2487 * @param $input string of digits
2488 * @param $sourceBase int 2-36
2489 * @param $destBase int 2-36
2490 * @param $pad int 1 or greater
2491 * @param $lowercase bool
2492 * @return string or false on invalid input
2494 function wfBaseConvert( $input, $sourceBase, $destBase, $pad=1, $lowercase=true ) {
2495 $input = strval( $input );
2496 if( $sourceBase < 2 ||
2501 $sourceBase != intval( $sourceBase ) ||
2502 $destBase != intval( $destBase ) ||
2503 $pad != intval( $pad ) ||
2504 !is_string( $input ) ||
2508 $digitChars = ( $lowercase ) ?
'0123456789abcdefghijklmnopqrstuvwxyz' : '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
2509 $inDigits = array();
2512 // Decode and validate input string
2513 $input = strtolower( $input );
2514 for( $i = 0; $i < strlen( $input ); $i++
) {
2515 $n = strpos( $digitChars, $input{$i} );
2516 if( $n === false ||
$n > $sourceBase ) {
2522 // Iterate over the input, modulo-ing out an output digit
2523 // at a time until input is gone.
2524 while( count( $inDigits ) ) {
2526 $workDigits = array();
2529 foreach( $inDigits as $digit ) {
2530 $work *= $sourceBase;
2533 if( $work < $destBase ) {
2534 // Gonna need to pull another digit.
2535 if( count( $workDigits ) ) {
2536 // Avoid zero-padding; this lets us find
2537 // the end of the input very easily when
2538 // length drops to zero.
2542 // Finally! Actual division!
2543 $workDigits[] = intval( $work / $destBase );
2545 // Isn't it annoying that most programming languages
2546 // don't have a single divide-and-remainder operator,
2547 // even though the CPU implements it that way?
2548 $work = $work %
$destBase;
2552 // All that division leaves us with a remainder,
2553 // which is conveniently our next output digit.
2554 $outChars .= $digitChars[$work];
2557 $inDigits = $workDigits;
2560 while( strlen( $outChars ) < $pad ) {
2564 return strrev( $outChars );
2568 * Create an object with a given name and an array of construct parameters
2569 * @param string $name
2570 * @param array $p parameters
2572 function wfCreateObject( $name, $p ){
2573 $p = array_values( $p );
2574 switch ( count( $p ) ) {
2578 return new $name( $p[0] );
2580 return new $name( $p[0], $p[1] );
2582 return new $name( $p[0], $p[1], $p[2] );
2584 return new $name( $p[0], $p[1], $p[2], $p[3] );
2586 return new $name( $p[0], $p[1], $p[2], $p[3], $p[4] );
2588 return new $name( $p[0], $p[1], $p[2], $p[3], $p[4], $p[5] );
2590 throw new MWException( "Too many arguments to construtor in wfCreateObject" );
2595 * Alias for modularized function
2596 * @deprecated Use Http::get() instead
2598 function wfGetHTTP( $url, $timeout = 'default' ) {
2599 wfDeprecated(__FUNCTION__
);
2600 return Http
::get( $url, $timeout );
2604 * Alias for modularized function
2605 * @deprecated Use Http::isLocalURL() instead
2607 function wfIsLocalURL( $url ) {
2608 wfDeprecated(__FUNCTION__
);
2609 return Http
::isLocalURL( $url );
2612 function wfHttpOnlySafe() {
2613 global $wgHttpOnlyBlacklist;
2614 if( !version_compare("5.2", PHP_VERSION
, "<") )
2617 if( isset( $_SERVER['HTTP_USER_AGENT'] ) ) {
2618 foreach( $wgHttpOnlyBlacklist as $regex ) {
2619 if( preg_match( $regex, $_SERVER['HTTP_USER_AGENT'] ) ) {
2629 * Initialise php session
2631 function wfSetupSession() {
2632 global $wgSessionsInMemcached, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookieHttpOnly;
2633 if( $wgSessionsInMemcached ) {
2634 require_once( 'MemcachedSessions.php' );
2635 } elseif( 'files' != ini_get( 'session.save_handler' ) ) {
2636 # If it's left on 'user' or another setting from another
2637 # application, it will end up failing. Try to recover.
2638 ini_set ( 'session.save_handler', 'files' );
2640 $httpOnlySafe = wfHttpOnlySafe();
2641 wfDebugLog( 'cookie',
2642 'session_set_cookie_params: "' . implode( '", "',
2648 $httpOnlySafe && $wgCookieHttpOnly ) ) . '"' );
2649 if( $httpOnlySafe && $wgCookieHttpOnly ) {
2650 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookieHttpOnly );
2652 // PHP 5.1 throws warnings if you pass the HttpOnly parameter for 5.2.
2653 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
2655 session_cache_limiter( 'private, must-revalidate' );
2656 wfSuppressWarnings();
2658 wfRestoreWarnings();
2662 * Get an object from the precompiled serialized directory
2664 * @return mixed The variable on success, false on failure
2666 function wfGetPrecompiledData( $name ) {
2669 $file = "$IP/serialized/$name";
2670 if ( file_exists( $file ) ) {
2671 $blob = file_get_contents( $file );
2673 return unserialize( $blob );
2679 function wfGetCaller( $level = 2 ) {
2680 $backtrace = wfDebugBacktrace();
2681 if ( isset( $backtrace[$level] ) ) {
2682 return wfFormatStackFrame($backtrace[$level]);
2684 $caller = 'unknown';
2689 /** Return a string consisting all callers in stack, somewhat useful sometimes for profiling specific points */
2690 function wfGetAllCallers() {
2691 return implode('/', array_map('wfFormatStackFrame',array_reverse(wfDebugBacktrace())));
2694 /** Return a string representation of frame */
2695 function wfFormatStackFrame($frame) {
2696 return isset( $frame["class"] )?
2697 $frame["class"]."::".$frame["function"]:
2704 function wfMemcKey( /*... */ ) {
2705 $args = func_get_args();
2706 $key = wfWikiID() . ':' . implode( ':', $args );
2711 * Get a cache key for a foreign DB
2713 function wfForeignMemcKey( $db, $prefix /*, ... */ ) {
2714 $args = array_slice( func_get_args(), 2 );
2716 $key = "$db-$prefix:" . implode( ':', $args );
2718 $key = $db . ':' . implode( ':', $args );
2724 * Get an ASCII string identifying this wiki
2725 * This is used as a prefix in memcached keys
2727 function wfWikiID( $db = null ) {
2728 if( $db instanceof Database
) {
2729 return $db->getWikiID();
2731 global $wgDBprefix, $wgDBname;
2732 if ( $wgDBprefix ) {
2733 return "$wgDBname-$wgDBprefix";
2741 * Split a wiki ID into DB name and table prefix
2743 function wfSplitWikiID( $wiki ) {
2744 $bits = explode( '-', $wiki, 2 );
2745 if ( count( $bits ) < 2 ) {
2752 * Get a Database object.
2753 * @param integer $db Index of the connection to get. May be DB_MASTER for the
2754 * master (for write queries), DB_SLAVE for potentially lagged
2755 * read queries, or an integer >= 0 for a particular server.
2757 * @param mixed $groups Query groups. An array of group names that this query
2758 * belongs to. May contain a single string if the query is only
2761 * @param string $wiki The wiki ID, or false for the current wiki
2763 * Note: multiple calls to wfGetDB(DB_SLAVE) during the course of one request
2764 * will always return the same object, unless the underlying connection or load
2765 * balancer is manually destroyed.
2767 function &wfGetDB( $db, $groups = array(), $wiki = false ) {
2768 return wfGetLB( $wiki )->getConnection( $db, $groups, $wiki );
2772 * Get a load balancer object.
2774 * @param array $groups List of query groups
2775 * @param string $wiki Wiki ID, or false for the current wiki
2776 * @return LoadBalancer
2778 function wfGetLB( $wiki = false ) {
2779 return wfGetLBFactory()->getMainLB( $wiki );
2783 * Get the load balancer factory object
2785 function &wfGetLBFactory() {
2786 return LBFactory
::singleton();
2791 * Shortcut for RepoGroup::singleton()->findFile()
2792 * @param mixed $title Title object or string. May be interwiki.
2793 * @param mixed $time Requested time for an archived image, or false for the
2794 * current version. An image object will be returned which
2795 * was created at the specified time.
2796 * @param mixed $flags FileRepo::FIND_ flags
2797 * @param boolean $bypass Bypass the file cache even if it could be used
2798 * @return File, or false if the file does not exist
2800 function wfFindFile( $title, $time = false, $flags = 0, $bypass = false ) {
2801 if( !$time && !$flags && !$bypass ) {
2802 return FileCache
::singleton()->findFile( $title );
2804 return RepoGroup
::singleton()->findFile( $title, $time, $flags );
2809 * Get an object referring to a locally registered file.
2810 * Returns a valid placeholder object if the file does not exist.
2812 function wfLocalFile( $title ) {
2813 return RepoGroup
::singleton()->getLocalRepo()->newFile( $title );
2817 * Should low-performance queries be disabled?
2821 function wfQueriesMustScale() {
2822 global $wgMiserMode;
2824 ||
( SiteStats
::pages() > 100000
2825 && SiteStats
::edits() > 1000000
2826 && SiteStats
::users() > 10000 );
2830 * Get the path to a specified script file, respecting file
2831 * extensions; this is a wrapper around $wgScriptExtension etc.
2833 * @param string $script Script filename, sans extension
2836 function wfScript( $script = 'index' ) {
2837 global $wgScriptPath, $wgScriptExtension;
2838 return "{$wgScriptPath}/{$script}{$wgScriptExtension}";
2842 * Convenience function converts boolean values into "true"
2843 * or "false" (string) values
2845 * @param bool $value
2848 function wfBoolToStr( $value ) {
2849 return $value ?
'true' : 'false';
2853 * Load an extension messages file
2855 * @param string $extensionName Name of extension to load messages from\for.
2856 * @param string $langcode Language to load messages for, or false for default
2857 * behvaiour (en, content language and user language).
2858 * @since r24808 (v1.11) Using this method of loading extension messages will not work
2859 * on MediaWiki prior to that
2861 function wfLoadExtensionMessages( $extensionName, $langcode = false ) {
2862 global $wgExtensionMessagesFiles, $wgMessageCache, $wgLang, $wgContLang;
2864 #For recording whether extension message files have been loaded in a given language.
2865 static $loaded = array();
2867 if( !array_key_exists( $extensionName, $loaded ) ) {
2868 $loaded[$extensionName] = array();
2871 if ( !isset($wgExtensionMessagesFiles[$extensionName]) ) {
2872 throw new MWException( "Messages file for extensions $extensionName is not defined" );
2875 if( !$langcode && !array_key_exists( '*', $loaded[$extensionName] ) ) {
2876 # Just do en, content language and user language.
2877 $wgMessageCache->loadMessagesFile( $wgExtensionMessagesFiles[$extensionName], false );
2878 # Mark that they have been loaded.
2879 $loaded[$extensionName]['en'] = true;
2880 $loaded[$extensionName][$wgLang->getCode()] = true;
2881 $loaded[$extensionName][$wgContLang->getCode()] = true;
2882 # Mark that this part has been done to avoid weird if statements.
2883 $loaded[$extensionName]['*'] = true;
2884 } elseif( is_string( $langcode ) && !array_key_exists( $langcode, $loaded[$extensionName] ) ) {
2885 # Load messages for specified language.
2886 $wgMessageCache->loadMessagesFile( $wgExtensionMessagesFiles[$extensionName], $langcode );
2887 # Mark that they have been loaded.
2888 $loaded[$extensionName][$langcode] = true;
2893 * Get a platform-independent path to the null file, e.g.
2898 function wfGetNull() {
2899 return wfIsWindows()
2905 * Displays a maxlag error
2907 * @param string $host Server that lags the most
2908 * @param int $lag Maxlag (actual)
2909 * @param int $maxLag Maxlag (requested)
2911 function wfMaxlagError( $host, $lag, $maxLag ) {
2912 global $wgShowHostnames;
2913 header( 'HTTP/1.1 503 Service Unavailable' );
2914 header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
2915 header( 'X-Database-Lag: ' . intval( $lag ) );
2916 header( 'Content-Type: text/plain' );
2917 if( $wgShowHostnames ) {
2918 echo "Waiting for $host: $lag seconds lagged\n";
2920 echo "Waiting for a database server: $lag seconds lagged\n";
2925 * Throws an E_USER_NOTICE saying that $function is deprecated
2926 * @param string $function
2929 function wfDeprecated( $function ) {
2930 global $wgDebugLogFile;
2931 if ( !$wgDebugLogFile ) {
2934 $callers = wfDebugBacktrace();
2935 if( isset( $callers[2] ) ){
2936 $callerfunc = $callers[2];
2937 $callerfile = $callers[1];
2938 if( isset( $callerfile['file'] ) && isset( $callerfile['line'] ) ){
2939 $file = $callerfile['file'] . ' at line ' . $callerfile['line'];
2941 $file = '(internal function)';
2944 if( isset( $callerfunc['class'] ) )
2945 $func .= $callerfunc['class'] . '::';
2946 $func .= @$callerfunc['function'];
2947 $msg = "Use of $function is deprecated. Called from $func in $file";
2949 $msg = "Use of $function is deprecated.";
2951 wfDebug( "$msg\n" );
2955 * Sleep until the worst slave's replication lag is less than or equal to
2956 * $maxLag, in seconds. Use this when updating very large numbers of rows, as
2957 * in maintenance scripts, to avoid causing too much lag. Of course, this is
2958 * a no-op if there are no slaves.
2960 * Every time the function has to wait for a slave, it will print a message to
2961 * that effect (and then sleep for a little while), so it's probably not best
2962 * to use this outside maintenance scripts in its present form.
2964 * @param int $maxLag
2967 function wfWaitForSlaves( $maxLag ) {
2970 list( $host, $lag ) = $lb->getMaxLag();
2971 while( $lag > $maxLag ) {
2972 $name = @gethostbyaddr
( $host );
2973 if( $name !== false ) {
2976 print "Waiting for $host (lagged $lag seconds)...\n";
2978 list( $host, $lag ) = $lb->getMaxLag();
2984 * Output some plain text in command-line mode or in the installer (updaters.inc).
2985 * Do not use it in any other context, its behaviour is subject to change.
2987 function wfOut( $s ) {
2988 static $lineStarted = false;
2989 global $wgCommandLineMode;
2990 if ( $wgCommandLineMode && !defined( 'MEDIAWIKI_INSTALL' ) ) {
2993 echo htmlspecialchars( $s );
2998 /** Generate a random 32-character hexadecimal token.
2999 * @param mixed $salt Some sort of salt, if necessary, to add to random characters before hashing.
3001 function wfGenerateToken( $salt = '' ) {
3002 $salt = serialize($salt);
3004 return md5( mt_rand( 0, 0x7fffffff ) . $salt );
3008 * Replace all invalid characters with -
3009 * @param mixed $title Filename to process
3011 function wfStripIllegalFilenameChars( $name ) {
3012 $name = wfBaseName( $name );
3013 $name = preg_replace ( "/[^".Title
::legalChars()."]|:/", '-', $name );