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__
) . '/LogPage.php';
12 require_once dirname(__FILE__
) . '/normal/UtfNormalUtil.php';
13 require_once dirname(__FILE__
) . '/XmlFunctions.php';
15 // Hide compatibility functions from Doxygen
19 * Compatibility functions
21 * We more or less support PHP 5.0.x and up.
22 * Re-implementations of newer functions or functions in non-standard
23 * PHP extensions may be included here.
25 if( !function_exists('iconv') ) {
26 # iconv support is not in the default configuration and so may not be present.
27 # Assume will only ever use utf-8 and iso-8859-1.
28 # This will *not* work in all circumstances.
29 function iconv( $from, $to, $string ) {
30 if(strcasecmp( $from, $to ) == 0) return $string;
31 if(strcasecmp( $from, 'utf-8' ) == 0) return utf8_decode( $string );
32 if(strcasecmp( $to, 'utf-8' ) == 0) return utf8_encode( $string );
37 # UTF-8 substr function based on a PHP manual comment
38 if ( !function_exists( 'mb_substr' ) ) {
39 function mb_substr( $str, $start ) {
41 preg_match_all( '/./us', $str, $ar );
43 if( func_num_args() >= 3 ) {
44 $end = func_get_arg( 2 );
45 return join( '', array_slice( $ar[0], $start, $end ) );
47 return join( '', array_slice( $ar[0], $start ) );
52 if ( !function_exists( 'mb_strlen' ) ) {
54 * Fallback implementation of mb_strlen, hardcoded to UTF-8.
56 * @param string $enc optional encoding; ignored
59 function mb_strlen( $str, $enc="" ) {
60 $counts = count_chars( $str );
64 for( $i = 0; $i < 0x80; $i++
) {
65 $total +
= $counts[$i];
68 // Count multibyte sequence heads
69 for( $i = 0xc0; $i < 0xff; $i++
) {
70 $total +
= $counts[$i];
76 if ( !function_exists( 'array_diff_key' ) ) {
78 * Exists in PHP 5.1.0+
79 * Not quite compatible, two-argument version only
80 * Null values will cause problems due to this use of isset()
82 function array_diff_key( $left, $right ) {
84 foreach ( $left as $key => $unused ) {
85 if ( isset( $right[$key] ) ) {
86 unset( $result[$key] );
97 * Like array_diff( $a, $b ) except that it works with two-dimensional arrays.
99 function wfArrayDiff2( $a, $b ) {
100 return array_udiff( $a, $b, 'wfArrayDiff2_cmp' );
102 function wfArrayDiff2_cmp( $a, $b ) {
103 if ( !is_array( $a ) ) {
104 return strcmp( $a, $b );
105 } elseif ( count( $a ) !== count( $b ) ) {
106 return count( $a ) < count( $b ) ?
-1 : 1;
110 while( ( list( $keyA, $valueA ) = each( $a ) ) && ( list( $keyB, $valueB ) = each( $b ) ) ) {
111 $cmp = strcmp( $valueA, $valueB );
121 * Wrapper for clone(), for compatibility with PHP4-friendly extensions.
122 * PHP 5 won't let you declare a 'clone' function, even conditionally,
123 * so it has to be a wrapper with a different name.
125 function wfClone( $object ) {
126 return clone( $object );
130 * Seed Mersenne Twister
131 * No-op for compatibility; only necessary in PHP < 4.2.0
133 function wfSeedRandom() {
138 * Get a random decimal value between 0 and 1, in a way
139 * not likely to give duplicate values for any realistic
140 * number of articles.
144 function wfRandom() {
145 # The maximum random value is "only" 2^31-1, so get two random
146 # values to reduce the chance of dupes
147 $max = mt_getrandmax() +
1;
148 $rand = number_format( (mt_rand() * $max +
mt_rand())
149 / $max / $max, 12, '.', '' );
154 * We want some things to be included as literal characters in our title URLs
155 * for prettiness, which urlencode encodes by default. According to RFC 1738,
156 * all of the following should be safe:
160 * But + is not safe because it's used to indicate a space; &= are only safe in
161 * paths and not in queries (and we don't distinguish here); ' seems kind of
162 * scary; and urlencode() doesn't touch -_. to begin with. Plus, although /
163 * is reserved, we don't care. So the list we unescape is:
167 * %2F in the page titles seems to fatally break for some reason.
172 function wfUrlencode( $s ) {
173 $s = urlencode( $s );
175 array( '%3B','%3A','%40','%24','%21','%2A','%28','%29','%2C','%2F' ),
176 array( ';', ':', '@', '$', '!', '*', '(', ')', ',', '/' ),
184 * Sends a line to the debug log if enabled or, optionally, to a comment in output.
185 * In normal operation this is a NOP.
187 * Controlling globals:
188 * $wgDebugLogFile - points to the log file
189 * $wgProfileOnly - if set, normal debug messages will not be recorded.
190 * $wgDebugRawPage - if false, 'action=raw' hits will not result in debug output.
191 * $wgDebugComments - if on, some debug items may appear in comments in the HTML output.
193 * @param $text String
194 * @param $logonly Bool: set true to avoid appearing in HTML when $wgDebugComments is set
196 function wfDebug( $text, $logonly = false ) {
197 global $wgOut, $wgDebugLogFile, $wgDebugComments, $wgProfileOnly, $wgDebugRawPage;
198 static $recursion = 0;
200 static $cache = array(); // Cache of unoutputted messages
202 # Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
203 if ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' && !$wgDebugRawPage ) {
207 if ( $wgDebugComments && !$logonly ) {
210 if ( !isset( $wgOut ) ) {
213 if ( !StubObject
::isRealObject( $wgOut ) ) {
222 // add the message and possible cached ones to the output
223 array_map( array( $wgOut, 'debug' ), $cache );
226 if ( '' != $wgDebugLogFile && !$wgProfileOnly ) {
227 # Strip unprintables; they can switch terminal modes when binary data
228 # gets dumped, which is pretty annoying.
229 $text = preg_replace( '![\x00-\x08\x0b\x0c\x0e-\x1f]!', ' ', $text );
230 wfErrorLog( $text, $wgDebugLogFile );
235 * Send a line giving PHP memory usage.
236 * @param $exact Bool : print exact values instead of kilobytes (default: false)
238 function wfDebugMem( $exact = false ) {
239 $mem = memory_get_usage();
241 $mem = floor( $mem / 1024 ) . ' kilobytes';
245 wfDebug( "Memory usage: $mem\n" );
249 * Send a line to a supplementary debug log file, if configured, or main debug log if not.
250 * $wgDebugLogGroups[$logGroup] should be set to a filename to send to a separate log.
252 * @param $logGroup String
253 * @param $text String
254 * @param $public Bool: whether to log the event in the public log if no private
255 * log file is specified, (default true)
257 function wfDebugLog( $logGroup, $text, $public = true ) {
258 global $wgDebugLogGroups, $wgShowHostnames;
259 if( $text{strlen( $text ) - 1} != "\n" ) $text .= "\n";
260 if( isset( $wgDebugLogGroups[$logGroup] ) ) {
261 $time = wfTimestamp( TS_DB
);
263 if ( $wgShowHostnames ) {
264 $host = wfHostname();
268 wfErrorLog( "$time $host $wiki: $text", $wgDebugLogGroups[$logGroup] );
269 } else if ( $public === true ) {
270 wfDebug( $text, true );
275 * Log for database errors
276 * @param $text String: database error message.
278 function wfLogDBError( $text ) {
279 global $wgDBerrorLog, $wgDBname;
280 if ( $wgDBerrorLog ) {
281 $host = trim(`hostname`
);
282 $text = date('D M j G:i:s T Y') . "\t$host\t$wgDBname\t$text";
283 wfErrorLog( $text, $wgDBerrorLog );
288 * Log to a file without getting "file size exceeded" signals.
290 * Can also log to TCP or UDP with the syntax udp://host:port/prefix. This will
291 * send lines to the specified port, prefixed by the specified prefix and a space.
293 function wfErrorLog( $text, $file ) {
294 if ( substr( $file, 0, 4 ) == 'udp:' ) {
295 if ( preg_match( '!^(tcp|udp):(?://)?\[([0-9a-fA-F:]+)\]:(\d+)(?:/(.*))?$!', $file, $m ) ) {
296 // IPv6 bracketed host
300 $prefix = isset( $m[4] ) ?
$m[4] : false;
301 } elseif ( preg_match( '!^(tcp|udp):(?://)?([a-zA-Z0-9-]+):(\d+)(?:/(.*))?$!', $file, $m ) ) {
305 $prefix = isset( $m[4] ) ?
$m[4] : false;
307 throw new MWException( __METHOD__
.": Invalid UDP specification" );
309 // Clean it up for the multiplexer
310 if ( strval( $prefix ) !== '' ) {
311 $text = preg_replace( '/^/m', $prefix . ' ', $text );
312 if ( substr( $text, -1 ) != "\n" ) {
317 $sock = fsockopen( "$protocol://$host", $port );
321 fwrite( $sock, $text );
324 wfSuppressWarnings();
325 $exists = file_exists( $file );
326 $size = $exists ?
filesize( $file ) : false;
327 if ( !$exists ||
( $size !== false && $size +
strlen( $text ) < 0x7fffffff ) ) {
328 error_log( $text, 3, $file );
337 function wfLogProfilingData() {
338 global $wgRequestTime, $wgDebugLogFile, $wgDebugRawPage, $wgRequest;
339 global $wgProfiler, $wgUser;
340 if ( !isset( $wgProfiler ) )
344 $elapsed = $now - $wgRequestTime;
345 $prof = wfGetProfilingOutput( $wgRequestTime, $elapsed );
347 if( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) )
348 $forward = ' forwarded for ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
349 if( !empty( $_SERVER['HTTP_CLIENT_IP'] ) )
350 $forward .= ' client IP ' . $_SERVER['HTTP_CLIENT_IP'];
351 if( !empty( $_SERVER['HTTP_FROM'] ) )
352 $forward .= ' from ' . $_SERVER['HTTP_FROM'];
354 $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
355 // Don't unstub $wgUser at this late stage just for statistics purposes
356 if( StubObject
::isRealObject($wgUser) && $wgUser->isAnon() )
358 $log = sprintf( "%s\t%04.3f\t%s\n",
359 gmdate( 'YmdHis' ), $elapsed,
360 urldecode( $wgRequest->getRequestURL() . $forward ) );
361 if ( '' != $wgDebugLogFile && ( $wgRequest->getVal('action') != 'raw' ||
$wgDebugRawPage ) ) {
362 wfErrorLog( $log . $prof, $wgDebugLogFile );
367 * Check if the wiki read-only lock file is present. This can be used to lock
368 * off editing functions, but doesn't guarantee that the database will not be
372 function wfReadOnly() {
373 global $wgReadOnlyFile, $wgReadOnly;
375 if ( !is_null( $wgReadOnly ) ) {
376 return (bool)$wgReadOnly;
378 if ( '' == $wgReadOnlyFile ) {
381 // Set $wgReadOnly for faster access next time
382 if ( is_file( $wgReadOnlyFile ) ) {
383 $wgReadOnly = file_get_contents( $wgReadOnlyFile );
387 return (bool)$wgReadOnly;
390 function wfReadOnlyReason() {
397 * Return a Language object from $langcode
398 * @param $langcode Mixed: either:
399 * - a Language object
400 * - code of the language to get the message for, if it is
401 * a valid code create a language for that language, if
402 * it is a string but not a valid code then make a basic
404 * - a boolean: if it's false then use the current users
405 * language (as a fallback for the old parameter
406 * functionality), or if it is true then use the wikis
407 * @return Language object
409 function wfGetLangObj( $langcode = false ){
410 # Identify which language to get or create a language object for.
411 if( $langcode instanceof Language
)
412 # Great, we already have the object!
416 if( $langcode === $wgContLang->getCode() ||
$langcode === true )
417 # $langcode is the language code of the wikis content language object.
418 # or it is a boolean and value is true
422 if( $langcode === $wgLang->getCode() ||
$langcode === false )
423 # $langcode is the language code of user language object.
424 # or it was a boolean and value is false
427 $validCodes = array_keys( Language
::getLanguageNames() );
428 if( in_array( $langcode, $validCodes ) )
429 # $langcode corresponds to a valid language.
430 return Language
::factory( $langcode );
432 # $langcode is a string, but not a valid language code; use content language.
433 wfDebug( 'Invalid language code passed to wfGetLangObj, falling back to content language.' );
438 * Get a message from anywhere, for the current user language.
440 * Use wfMsgForContent() instead if the message should NOT
441 * change depending on the user preferences.
443 * @param $key String: lookup key for the message, usually
444 * defined in languages/Language.php
446 * This function also takes extra optional parameters (not
447 * shown in the function definition), which can by used to
448 * insert variable text into the predefined message.
450 function wfMsg( $key ) {
451 $args = func_get_args();
452 array_shift( $args );
453 return wfMsgReal( $key, $args, true );
457 * Same as above except doesn't transform the message
459 function wfMsgNoTrans( $key ) {
460 $args = func_get_args();
461 array_shift( $args );
462 return wfMsgReal( $key, $args, true, false, false );
466 * Get a message from anywhere, for the current global language
467 * set with $wgLanguageCode.
469 * Use this if the message should NOT change dependent on the
470 * language set in the user's preferences. This is the case for
471 * most text written into logs, as well as link targets (such as
472 * the name of the copyright policy page). Link titles, on the
473 * other hand, should be shown in the UI language.
475 * Note that MediaWiki allows users to change the user interface
476 * language in their preferences, but a single installation
477 * typically only contains content in one language.
479 * Be wary of this distinction: If you use wfMsg() where you should
480 * use wfMsgForContent(), a user of the software may have to
481 * customize over 70 messages in order to, e.g., fix a link in every
484 * @param $key String: lookup key for the message, usually
485 * defined in languages/Language.php
487 function wfMsgForContent( $key ) {
488 global $wgForceUIMsgAsContentMsg;
489 $args = func_get_args();
490 array_shift( $args );
492 if( is_array( $wgForceUIMsgAsContentMsg ) &&
493 in_array( $key, $wgForceUIMsgAsContentMsg ) )
495 return wfMsgReal( $key, $args, true, $forcontent );
499 * Same as above except doesn't transform the message
501 function wfMsgForContentNoTrans( $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, false );
513 * Get a message from the language file, for the UI elements
515 function wfMsgNoDB( $key ) {
516 $args = func_get_args();
517 array_shift( $args );
518 return wfMsgReal( $key, $args, false );
522 * Get a message from the language file, for the content
524 function wfMsgNoDBForContent( $key ) {
525 global $wgForceUIMsgAsContentMsg;
526 $args = func_get_args();
527 array_shift( $args );
529 if( is_array( $wgForceUIMsgAsContentMsg ) &&
530 in_array( $key, $wgForceUIMsgAsContentMsg ) )
532 return wfMsgReal( $key, $args, false, $forcontent );
537 * Really get a message
538 * @param $key String: key to get.
540 * @param $useDB Boolean
541 * @param $transform Boolean: Whether or not to transform the message.
542 * @param $forContent Boolean
543 * @return String: the requested message.
545 function wfMsgReal( $key, $args, $useDB = true, $forContent=false, $transform = true ) {
546 wfProfileIn( __METHOD__
);
547 $message = wfMsgGetKey( $key, $useDB, $forContent, $transform );
548 $message = wfMsgReplaceArgs( $message, $args );
549 wfProfileOut( __METHOD__
);
554 * This function provides the message source for messages to be edited which are *not* stored in the database.
555 * @param $key String:
557 function wfMsgWeirdKey ( $key ) {
558 $source = wfMsgGetKey( $key, false, true, false );
559 if ( wfEmptyMsg( $key, $source ) )
566 * Fetch a message string value, but don't replace any keys yet.
569 * @param string $langcode Code of the language to get the message for, or
570 * behaves as a content language switch if it is a
575 function wfMsgGetKey( $key, $useDB, $langCode = false, $transform = true ) {
576 global $wgContLang, $wgMessageCache;
578 wfRunHooks('NormalizeMessageKey', array(&$key, &$useDB, &$langCode, &$transform));
580 # If $wgMessageCache isn't initialised yet, try to return something sensible.
581 if( is_object( $wgMessageCache ) ) {
582 $message = $wgMessageCache->get( $key, $useDB, $langCode );
584 $message = $wgMessageCache->transform( $message );
587 $lang = wfGetLangObj( $langCode );
589 # MessageCache::get() does this already, Language::getMessage() doesn't
590 # ISSUE: Should we try to handle "message/lang" here too?
591 $key = str_replace( ' ' , '_' , $wgContLang->lcfirst( $key ) );
593 if( is_object( $lang ) ) {
594 $message = $lang->getMessage( $key );
604 * Replace message parameter keys on the given formatted output.
606 * @param string $message
611 function wfMsgReplaceArgs( $message, $args ) {
612 # Fix windows line-endings
613 # Some messages are split with explode("\n", $msg)
614 $message = str_replace( "\r", '', $message );
617 if ( count( $args ) ) {
618 if ( is_array( $args[0] ) ) {
619 $args = array_values( $args[0] );
621 $replacementKeys = array();
622 foreach( $args as $n => $param ) {
623 $replacementKeys['$' . ($n +
1)] = $param;
625 $message = strtr( $message, $replacementKeys );
632 * Return an HTML-escaped version of a message.
633 * Parameter replacements, if any, are done *after* the HTML-escaping,
634 * so parameters may contain HTML (eg links or form controls). Be sure
635 * to pre-escape them if you really do want plaintext, or just wrap
636 * the whole thing in htmlspecialchars().
639 * @param string ... parameters
642 function wfMsgHtml( $key ) {
643 $args = func_get_args();
644 array_shift( $args );
645 return wfMsgReplaceArgs( htmlspecialchars( wfMsgGetKey( $key, true ) ), $args );
649 * Return an HTML version of message
650 * Parameter replacements, if any, are done *after* parsing the wiki-text message,
651 * so parameters may contain HTML (eg links or form controls). Be sure
652 * to pre-escape them if you really do want plaintext, or just wrap
653 * the whole thing in htmlspecialchars().
656 * @param string ... parameters
659 function wfMsgWikiHtml( $key ) {
661 $args = func_get_args();
662 array_shift( $args );
663 return wfMsgReplaceArgs( $wgOut->parse( wfMsgGetKey( $key, true ), /* can't be set to false */ true ), $args );
667 * Returns message in the requested format
668 * @param string $key Key of the message
669 * @param array $options Processing rules. Can take the following options:
670 * <i>parse</i>: parses wikitext to html
671 * <i>parseinline</i>: parses wikitext to html and removes the surrounding
672 * p's added by parser or tidy
673 * <i>escape</i>: filters message through htmlspecialchars
674 * <i>escapenoentities</i>: same, but allows entity references like through
675 * <i>replaceafter</i>: parameters are substituted after parsing or escaping
676 * <i>parsemag</i>: transform the message using magic phrases
677 * <i>content</i>: fetch message for content language instead of interface
678 * Also can accept a single associative argument, of the form 'language' => 'xx':
679 * <i>language</i>: language code to fetch message for (overriden by
680 * <i>content</i>), its behaviour with parser, parseinline and parsemag
682 * Behavior for conflicting options (e.g., parse+parseinline) is undefined.
684 function wfMsgExt( $key, $options ) {
685 global $wgOut, $wgParser;
687 $args = func_get_args();
688 array_shift( $args );
689 array_shift( $args );
691 if( !is_array($options) ) {
692 $options = array($options);
695 foreach( $options as $arrayKey => $option ) {
696 if( !preg_match( '/^[0-9]+|language$/', $arrayKey ) ) {
697 # An unknown index, neither numeric nor "language"
698 trigger_error( "wfMsgExt called with incorrect parameter key $arrayKey", E_USER_WARNING
);
699 } elseif( preg_match( '/^[0-9]+$/', $arrayKey ) && !in_array( $option,
700 array( 'parse', 'parseinline', 'escape', 'escapenoentities',
701 'replaceafter', 'parsemag', 'content' ) ) ) {
702 # A numeric index with unknown value
703 trigger_error( "wfMsgExt called with incorrect parameter $option", E_USER_WARNING
);
707 if( in_array('content', $options) ) {
710 } elseif( array_key_exists('language', $options) ) {
712 $langCode = $options['language'];
713 $validCodes = array_keys( Language
::getLanguageNames() );
714 if( !in_array($options['language'], $validCodes) ) {
715 # Fallback to en, instead of whatever interface language we might have
723 $string = wfMsgGetKey( $key, /*DB*/true, $langCode, /*Transform*/false );
725 if( !in_array('replaceafter', $options) ) {
726 $string = wfMsgReplaceArgs( $string, $args );
729 if( in_array('parse', $options) ) {
730 $string = $wgOut->parse( $string, true, !$forContent );
731 } elseif ( in_array('parseinline', $options) ) {
732 $string = $wgOut->parse( $string, true, !$forContent );
734 if( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $string, $m ) ) {
737 } elseif ( in_array('parsemag', $options) ) {
738 global $wgMessageCache;
739 if ( isset( $wgMessageCache ) ) {
740 $string = $wgMessageCache->transform( $string, !$forContent );
744 if ( in_array('escape', $options) ) {
745 $string = htmlspecialchars ( $string );
746 } elseif ( in_array( 'escapenoentities', $options ) ) {
747 $string = Sanitizer
::escapeHtmlAllowEntities( $string );
750 if( in_array('replaceafter', $options) ) {
751 $string = wfMsgReplaceArgs( $string, $args );
759 * Just like exit() but makes a note of it.
760 * Commits open transactions except if the error parameter is set
762 * @deprecated Please return control to the caller or throw an exception
764 function wfAbruptExit( $error = false ){
765 static $called = false;
771 $bt = wfDebugBacktrace();
773 for($i = 0; $i < count($bt) ; $i++
){
774 $file = isset($bt[$i]['file']) ?
$bt[$i]['file'] : "unknown";
775 $line = isset($bt[$i]['line']) ?
$bt[$i]['line'] : "unknown";
776 wfDebug("WARNING: Abrupt exit in $file at line $line\n");
779 wfDebug('WARNING: Abrupt exit\n');
782 wfLogProfilingData();
785 wfGetLB()->closeAll();
791 * @deprecated Please return control the caller or throw an exception
793 function wfErrorExit() {
794 wfAbruptExit( true );
798 * Print a simple message and die, returning nonzero to the shell if any.
799 * Plain die() fails to return nonzero to the shell if you pass a string.
802 function wfDie( $msg='' ) {
808 * Throw a debugging exception. This function previously once exited the process,
809 * but now throws an exception instead, with similar results.
811 * @param string $msg Message shown when dieing.
813 function wfDebugDieBacktrace( $msg = '' ) {
814 throw new MWException( $msg );
818 * Fetch server name for use in error reporting etc.
819 * Use real server name if available, so we know which machine
820 * in a server farm generated the current page.
823 function wfHostname() {
825 if ( is_null( $host ) ) {
826 if ( function_exists( 'posix_uname' ) ) {
827 // This function not present on Windows
828 $uname = @posix_uname
();
832 if( is_array( $uname ) && isset( $uname['nodename'] ) ) {
833 $host = $uname['nodename'];
835 # This may be a virtual server.
836 $host = $_SERVER['SERVER_NAME'];
843 * Returns a HTML comment with the elapsed time since request.
844 * This method has no side effects.
847 function wfReportTime() {
848 global $wgRequestTime, $wgShowHostnames;
851 $elapsed = $now - $wgRequestTime;
853 return $wgShowHostnames
854 ?
sprintf( "<!-- Served by %s in %01.3f secs. -->", wfHostname(), $elapsed )
855 : sprintf( "<!-- Served in %01.3f secs. -->", $elapsed );
859 * Safety wrapper for debug_backtrace().
861 * With Zend Optimizer 3.2.0 loaded, this causes segfaults under somewhat
862 * murky circumstances, which may be triggered in part by stub objects
863 * or other fancy talkin'.
865 * Will return an empty array if Zend Optimizer is detected, otherwise
866 * the output from debug_backtrace() (trimmed).
868 * @return array of backtrace information
870 function wfDebugBacktrace() {
871 if( extension_loaded( 'Zend Optimizer' ) ) {
872 wfDebug( "Zend Optimizer detected; skipping debug_backtrace for safety.\n" );
875 return array_slice( debug_backtrace(), 1 );
879 function wfBacktrace() {
880 global $wgCommandLineMode;
882 if ( $wgCommandLineMode ) {
887 $backtrace = wfDebugBacktrace();
888 foreach( $backtrace as $call ) {
889 if( isset( $call['file'] ) ) {
890 $f = explode( DIRECTORY_SEPARATOR
, $call['file'] );
891 $file = $f[count($f)-1];
895 if( isset( $call['line'] ) ) {
896 $line = $call['line'];
900 if ( $wgCommandLineMode ) {
901 $msg .= "$file line $line calls ";
903 $msg .= '<li>' . $file . ' line ' . $line . ' calls ';
905 if( !empty( $call['class'] ) ) $msg .= $call['class'] . '::';
906 $msg .= $call['function'] . '()';
908 if ( $wgCommandLineMode ) {
914 if ( $wgCommandLineMode ) {
924 /* Some generic result counters, pulled out of SearchEngine */
930 function wfShowingResults( $offset, $limit ) {
932 return wfMsgExt( 'showingresults', array( 'parseinline' ), $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+
1 ) );
938 function wfShowingResultsNum( $offset, $limit, $num ) {
940 return wfMsgExt( 'showingresultsnum', array( 'parseinline' ), $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+
1 ), $wgLang->formatNum( $num ) );
946 function wfViewPrevNext( $offset, $limit, $link, $query = '', $atend = false ) {
948 $fmtLimit = $wgLang->formatNum( $limit );
949 $prev = wfMsg( 'prevn', $fmtLimit );
950 $next = wfMsg( 'nextn', $fmtLimit );
952 if( is_object( $link ) ) {
955 $title = Title
::newFromText( $link );
956 if( is_null( $title ) ) {
961 if ( 0 != $offset ) {
962 $po = $offset - $limit;
963 if ( $po < 0 ) { $po = 0; }
964 $q = "limit={$limit}&offset={$po}";
965 if ( '' != $query ) { $q .= '&'.$query; }
966 $plink = '<a href="' . $title->escapeLocalUrl( $q ) . "\" class=\"mw-prevlink\">{$prev}</a>";
967 } else { $plink = $prev; }
969 $no = $offset +
$limit;
970 $q = 'limit='.$limit.'&offset='.$no;
971 if ( '' != $query ) { $q .= '&'.$query; }
976 $nlink = '<a href="' . $title->escapeLocalUrl( $q ) . "\" class=\"mw-nextlink\">{$next}</a>";
978 $nums = wfNumLink( $offset, 20, $title, $query ) . ' | ' .
979 wfNumLink( $offset, 50, $title, $query ) . ' | ' .
980 wfNumLink( $offset, 100, $title, $query ) . ' | ' .
981 wfNumLink( $offset, 250, $title, $query ) . ' | ' .
982 wfNumLink( $offset, 500, $title, $query );
984 return wfMsg( 'viewprevnext', $plink, $nlink, $nums );
990 function wfNumLink( $offset, $limit, &$title, $query = '' ) {
992 if ( '' == $query ) { $q = ''; }
993 else { $q = $query.'&'; }
994 $q .= 'limit='.$limit.'&offset='.$offset;
996 $fmtLimit = $wgLang->formatNum( $limit );
997 $s = '<a href="' . $title->escapeLocalUrl( $q ) . "\" class=\"mw-numlink\">{$fmtLimit}</a>";
1003 * @todo FIXME: we may want to blacklist some broken browsers
1005 * @return bool Whereas client accept gzip compression
1007 function wfClientAcceptsGzip() {
1010 # FIXME: we may want to blacklist some broken browsers
1013 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
1014 $_SERVER['HTTP_ACCEPT_ENCODING'],
1016 if( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) return false;
1017 wfDebug( " accepts gzip\n" );
1025 * Obtain the offset and limit values from the request string;
1026 * used in special pages
1028 * @param $deflimit Default limit if none supplied
1029 * @param $optionname Name of a user preference to check against
1033 function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) {
1035 return $wgRequest->getLimitOffset( $deflimit, $optionname );
1039 * Escapes the given text so that it may be output using addWikiText()
1040 * without any linking, formatting, etc. making its way through. This
1041 * is achieved by substituting certain characters with HTML entities.
1042 * As required by the callers, <nowiki> is not used. It currently does
1043 * not filter out characters which have special meaning only at the
1044 * start of a line, such as "*".
1046 * @param string $text Text to be escaped
1048 function wfEscapeWikiText( $text ) {
1049 $text = str_replace(
1050 array( '[', '|', ']', '\'', 'ISBN ', 'RFC ', '://', "\n=", '{{' ),
1051 array( '[', '|', ']', ''', 'ISBN ', 'RFC ', '://', "\n=", '{{' ),
1052 htmlspecialchars($text) );
1059 function wfQuotedPrintable( $string, $charset = '' ) {
1060 # Probably incomplete; see RFC 2045
1061 if( empty( $charset ) ) {
1062 global $wgInputEncoding;
1063 $charset = $wgInputEncoding;
1065 $charset = strtoupper( $charset );
1066 $charset = str_replace( 'ISO-8859', 'ISO8859', $charset ); // ?
1068 $illegal = '\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\xff=';
1069 $replace = $illegal . '\t ?_';
1070 if( !preg_match( "/[$illegal]/", $string ) ) return $string;
1071 $out = "=?$charset?Q?";
1072 $out .= preg_replace( "/([$replace])/e", 'sprintf("=%02X",ord("$1"))', $string );
1083 return microtime(true);
1087 * Sets dest to source and returns the original value of dest
1088 * If source is NULL, it just returns the value, it doesn't set the variable
1090 function wfSetVar( &$dest, $source ) {
1092 if ( !is_null( $source ) ) {
1099 * As for wfSetVar except setting a bit
1101 function wfSetBit( &$dest, $bit, $state = true ) {
1102 $temp = (bool)($dest & $bit );
1103 if ( !is_null( $state ) ) {
1114 * This function takes two arrays as input, and returns a CGI-style string, e.g.
1115 * "days=7&limit=100". Options in the first array override options in the second.
1116 * Options set to "" will not be output.
1118 function wfArrayToCGI( $array1, $array2 = NULL )
1120 if ( !is_null( $array2 ) ) {
1121 $array1 = $array1 +
$array2;
1125 foreach ( $array1 as $key => $value ) {
1126 if ( '' !== $value ) {
1130 if(is_array($value))
1133 foreach($value as $v)
1135 $cgi .= ($firstTime ?
'' : '&') .
1136 urlencode( $key . '[]' ) . '=' .
1142 $cgi .= urlencode( $key ) . '=' .
1143 urlencode( $value );
1150 * This is the logical opposite of wfArrayToCGI(): it accepts a query string as
1151 * its argument and returns the same string in array form. This allows compa-
1152 * tibility with legacy functions that accept raw query strings instead of nice
1153 * arrays. Of course, keys and values are urldecode()d. Don't try passing in-
1154 * valid query strings, or it will explode.
1156 * @param $query string Query string
1157 * @return array Array version of input
1159 function wfCgiToArray( $query ) {
1160 if( isset( $query[0] ) and $query[0] == '?' ) {
1161 $query = substr( $query, 1 );
1163 $bits = explode( '&', $query );
1165 foreach( $bits as $bit ) {
1169 list( $key, $value ) = explode( '=', $bit );
1170 $key = urldecode( $key );
1171 $value = urldecode( $value );
1172 $ret[$key] = $value;
1178 * Append a query string to an existing URL, which may or may not already
1179 * have query string parameters already. If so, they will be combined.
1181 * @param string $url
1182 * @param string $query
1185 function wfAppendQuery( $url, $query ) {
1186 if( $query != '' ) {
1187 if( false === strpos( $url, '?' ) ) {
1198 * Expand a potentially local URL to a fully-qualified URL.
1199 * Assumes $wgServer is correct. :)
1200 * @param string $url, either fully-qualified or a local path + query
1201 * @return string Fully-qualified URL
1203 function wfExpandUrl( $url ) {
1204 if( substr( $url, 0, 1 ) == '/' ) {
1206 return $wgServer . $url;
1213 * This is obsolete, use SquidUpdate::purge()
1216 function wfPurgeSquidServers ($urlArr) {
1217 SquidUpdate
::purge( $urlArr );
1221 * Windows-compatible version of escapeshellarg()
1222 * Windows doesn't recognise single-quotes in the shell, but the escapeshellarg()
1223 * function puts single quotes in regardless of OS
1225 function wfEscapeShellArg( ) {
1226 $args = func_get_args();
1229 foreach ( $args as $arg ) {
1236 if ( wfIsWindows() ) {
1237 // Escaping for an MSVC-style command line parser
1238 // Ref: http://mailman.lyra.org/pipermail/scite-interest/2002-March/000436.html
1239 // Double the backslashes before any double quotes. Escape the double quotes.
1240 $tokens = preg_split( '/(\\\\*")/', $arg, -1, PREG_SPLIT_DELIM_CAPTURE
);
1243 foreach ( $tokens as $token ) {
1245 $arg .= str_replace( '\\', '\\\\', substr( $token, 0, -1 ) ) . '\\"';
1251 // Double the backslashes before the end of the string, because
1252 // we will soon add a quote
1254 if ( preg_match( '/^(.*?)(\\\\+)$/', $arg, $m ) ) {
1255 $arg = $m[1] . str_replace( '\\', '\\\\', $m[2] );
1258 // Add surrounding quotes
1259 $retVal .= '"' . $arg . '"';
1261 $retVal .= escapeshellarg( $arg );
1268 * wfMerge attempts to merge differences between three texts.
1269 * Returns true for a clean merge and false for failure or a conflict.
1271 function wfMerge( $old, $mine, $yours, &$result ){
1274 # This check may also protect against code injection in
1275 # case of broken installations.
1276 if(! file_exists( $wgDiff3 ) ){
1277 wfDebug( "diff3 not found\n" );
1281 # Make temporary files
1283 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
1284 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
1285 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
1287 fwrite( $oldtextFile, $old ); fclose( $oldtextFile );
1288 fwrite( $mytextFile, $mine ); fclose( $mytextFile );
1289 fwrite( $yourtextFile, $yours ); fclose( $yourtextFile );
1291 # Check for a conflict
1292 $cmd = $wgDiff3 . ' -a --overlap-only ' .
1293 wfEscapeShellArg( $mytextName ) . ' ' .
1294 wfEscapeShellArg( $oldtextName ) . ' ' .
1295 wfEscapeShellArg( $yourtextName );
1296 $handle = popen( $cmd, 'r' );
1298 if( fgets( $handle, 1024 ) ){
1306 $cmd = $wgDiff3 . ' -a -e --merge ' .
1307 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
1308 $handle = popen( $cmd, 'r' );
1311 $data = fread( $handle, 8192 );
1312 if ( strlen( $data ) == 0 ) {
1318 unlink( $mytextName ); unlink( $oldtextName ); unlink( $yourtextName );
1320 if ( $result === '' && $old !== '' && $conflict == false ) {
1321 wfDebug( "Unexpected null result from diff3. Command: $cmd\n" );
1328 * Returns unified plain-text diff of two texts.
1329 * Useful for machine processing of diffs.
1330 * @param $before string The text before the changes.
1331 * @param $after string The text after the changes.
1332 * @param $params string Command-line options for the diff command.
1333 * @return string Unified diff of $before and $after
1335 function wfDiff( $before, $after, $params = '-u' ) {
1338 # This check may also protect against code injection in
1339 # case of broken installations.
1340 if( !file_exists( $wgDiff ) ){
1341 wfDebug( "diff executable not found\n" );
1342 $diffs = new Diff( explode( "\n", $before ), explode( "\n", $after ) );
1343 $format = new UnifiedDiffFormatter();
1344 return $format->format( $diffs );
1347 # Make temporary files
1349 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
1350 $newtextFile = fopen( $newtextName = tempnam( $td, 'merge-your-' ), 'w' );
1352 fwrite( $oldtextFile, $before ); fclose( $oldtextFile );
1353 fwrite( $newtextFile, $after ); fclose( $newtextFile );
1355 // Get the diff of the two files
1356 $cmd = "$wgDiff " . $params . ' ' .wfEscapeShellArg( $oldtextName, $newtextName );
1358 $h = popen( $cmd, 'r' );
1363 $data = fread( $h, 8192 );
1364 if ( strlen( $data ) == 0 ) {
1372 unlink( $oldtextName );
1373 unlink( $newtextName );
1375 // Kill the --- and +++ lines. They're not useful.
1376 $diff_lines = explode( "\n", $diff );
1377 if (strpos( $diff_lines[0], '---' ) === 0) {
1378 unset($diff_lines[0]);
1380 if (strpos( $diff_lines[1], '+++' ) === 0) {
1381 unset($diff_lines[1]);
1384 $diff = implode( "\n", $diff_lines );
1392 function wfVarDump( $var ) {
1394 $s = str_replace("\n","<br />\n", var_export( $var, true ) . "\n");
1395 if ( headers_sent() ||
!@is_object
( $wgOut ) ) {
1398 $wgOut->addHTML( $s );
1403 * Provide a simple HTTP error.
1405 function wfHttpError( $code, $label, $desc ) {
1408 header( "HTTP/1.0 $code $label" );
1409 header( "Status: $code $label" );
1410 $wgOut->sendCacheControl();
1412 header( 'Content-type: text/html; charset=utf-8' );
1413 print "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">".
1414 "<html><head><title>" .
1415 htmlspecialchars( $label ) .
1416 "</title></head><body><h1>" .
1417 htmlspecialchars( $label ) .
1419 nl2br( htmlspecialchars( $desc ) ) .
1420 "</p></body></html>\n";
1424 * Clear away any user-level output buffers, discarding contents.
1426 * Suitable for 'starting afresh', for instance when streaming
1427 * relatively large amounts of data without buffering, or wanting to
1428 * output image files without ob_gzhandler's compression.
1430 * The optional $resetGzipEncoding parameter controls suppression of
1431 * the Content-Encoding header sent by ob_gzhandler; by default it
1432 * is left. See comments for wfClearOutputBuffers() for why it would
1435 * Note that some PHP configuration options may add output buffer
1436 * layers which cannot be removed; these are left in place.
1438 * @param bool $resetGzipEncoding
1440 function wfResetOutputBuffers( $resetGzipEncoding=true ) {
1441 if( $resetGzipEncoding ) {
1442 // Suppress Content-Encoding and Content-Length
1443 // headers from 1.10+s wfOutputHandler
1444 global $wgDisableOutputCompression;
1445 $wgDisableOutputCompression = true;
1447 while( $status = ob_get_status() ) {
1448 if( $status['type'] == 0 /* PHP_OUTPUT_HANDLER_INTERNAL */ ) {
1449 // Probably from zlib.output_compression or other
1450 // PHP-internal setting which can't be removed.
1452 // Give up, and hope the result doesn't break
1456 if( !ob_end_clean() ) {
1457 // Could not remove output buffer handler; abort now
1458 // to avoid getting in some kind of infinite loop.
1461 if( $resetGzipEncoding ) {
1462 if( $status['name'] == 'ob_gzhandler' ) {
1463 // Reset the 'Content-Encoding' field set by this handler
1464 // so we can start fresh.
1465 header( 'Content-Encoding:' );
1473 * More legible than passing a 'false' parameter to wfResetOutputBuffers():
1475 * Clear away output buffers, but keep the Content-Encoding header
1476 * produced by ob_gzhandler, if any.
1478 * This should be used for HTTP 304 responses, where you need to
1479 * preserve the Content-Encoding header of the real result, but
1480 * also need to suppress the output of ob_gzhandler to keep to spec
1481 * and avoid breaking Firefox in rare cases where the headers and
1482 * body are broken over two packets.
1484 function wfClearOutputBuffers() {
1485 wfResetOutputBuffers( false );
1489 * Converts an Accept-* header into an array mapping string values to quality
1492 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
1493 # No arg means accept anything (per HTTP spec)
1495 return array( $def => 1.0 );
1500 $parts = explode( ',', $accept );
1502 foreach( $parts as $part ) {
1503 # FIXME: doesn't deal with params like 'text/html; level=1'
1504 @list
( $value, $qpart ) = explode( ';', trim( $part ) );
1506 if( !isset( $qpart ) ) {
1507 $prefs[$value] = 1.0;
1508 } elseif( preg_match( '/q\s*=\s*(\d*\.\d+)/', $qpart, $match ) ) {
1509 $prefs[$value] = floatval($match[1]);
1517 * Checks if a given MIME type matches any of the keys in the given
1518 * array. Basic wildcards are accepted in the array keys.
1520 * Returns the matching MIME type (or wildcard) if a match, otherwise
1523 * @param string $type
1524 * @param array $avail
1528 function mimeTypeMatch( $type, $avail ) {
1529 if( array_key_exists($type, $avail) ) {
1532 $parts = explode( '/', $type );
1533 if( array_key_exists( $parts[0] . '/*', $avail ) ) {
1534 return $parts[0] . '/*';
1535 } elseif( array_key_exists( '*/*', $avail ) ) {
1544 * Returns the 'best' match between a client's requested internet media types
1545 * and the server's list of available types. Each list should be an associative
1546 * array of type to preference (preference is a float between 0.0 and 1.0).
1547 * Wildcards in the types are acceptable.
1549 * @param array $cprefs Client's acceptable type list
1550 * @param array $sprefs Server's offered types
1553 * @todo FIXME: doesn't handle params like 'text/plain; charset=UTF-8'
1554 * XXX: generalize to negotiate other stuff
1556 function wfNegotiateType( $cprefs, $sprefs ) {
1559 foreach( array_keys($sprefs) as $type ) {
1560 $parts = explode( '/', $type );
1561 if( $parts[1] != '*' ) {
1562 $ckey = mimeTypeMatch( $type, $cprefs );
1564 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1569 foreach( array_keys( $cprefs ) as $type ) {
1570 $parts = explode( '/', $type );
1571 if( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
1572 $skey = mimeTypeMatch( $type, $sprefs );
1574 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1582 foreach( array_keys( $combine ) as $type ) {
1583 if( $combine[$type] > $bestq ) {
1585 $bestq = $combine[$type];
1594 * Returns an array where the values in the first array are replaced by the
1595 * values in the second array with the corresponding keys
1599 function wfArrayLookup( $a, $b ) {
1600 return array_flip( array_intersect( array_flip( $a ), array_keys( $b ) ) );
1604 * Convenience function; returns MediaWiki timestamp for the present time.
1607 function wfTimestampNow() {
1609 return wfTimestamp( TS_MW
, time() );
1613 * Reference-counted warning suppression
1615 function wfSuppressWarnings( $end = false ) {
1616 static $suppressCount = 0;
1617 static $originalLevel = false;
1620 if ( $suppressCount ) {
1622 if ( !$suppressCount ) {
1623 error_reporting( $originalLevel );
1627 if ( !$suppressCount ) {
1628 $originalLevel = error_reporting( E_ALL
& ~
( E_WARNING | E_NOTICE
) );
1635 * Restore error level to previous value
1637 function wfRestoreWarnings() {
1638 wfSuppressWarnings( true );
1641 # Autodetect, convert and provide timestamps of various types
1644 * Unix time - the number of seconds since 1970-01-01 00:00:00 UTC
1646 define('TS_UNIX', 0);
1649 * MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
1654 * MySQL DATETIME (YYYY-MM-DD HH:MM:SS)
1659 * RFC 2822 format, for E-mail and HTTP headers
1661 define('TS_RFC2822', 3);
1664 * ISO 8601 format with no timezone: 1986-02-09T20:00:00Z
1666 * This is used by Special:Export
1668 define('TS_ISO_8601', 4);
1671 * An Exif timestamp (YYYY:MM:DD HH:MM:SS)
1673 * @see http://exif.org/Exif2-2.PDF The Exif 2.2 spec, see page 28 for the
1674 * DateTime tag and page 36 for the DateTimeOriginal and
1675 * DateTimeDigitized tags.
1677 define('TS_EXIF', 5);
1680 * Oracle format time.
1682 define('TS_ORACLE', 6);
1685 * Postgres format time.
1687 define('TS_POSTGRES', 7);
1690 * @param mixed $outputtype A timestamp in one of the supported formats, the
1691 * function will autodetect which format is supplied
1692 * and act accordingly.
1693 * @return string Time in the format specified in $outputtype
1695 function wfTimestamp($outputtype=TS_UNIX
,$ts=0) {
1700 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)$/D',$ts,$da)) {
1702 } elseif (preg_match('/^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/D',$ts,$da)) {
1704 } elseif (preg_match('/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/D',$ts,$da)) {
1706 } elseif (preg_match('/^\d{1,13}$/D',$ts)) {
1709 } elseif (preg_match('/^\d{1,2}-...-\d\d(?:\d\d)? \d\d\.\d\d\.\d\d/', $ts)) {
1711 $uts = strtotime(preg_replace('/(\d\d)\.(\d\d)\.(\d\d)(\.(\d+))?/', "$1:$2:$3",
1712 str_replace("+00:00", "UTC", $ts)));
1713 } elseif (preg_match('/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})Z$/', $ts, $da)) {
1715 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)[\+\- ](\d\d)$/',$ts,$da)) {
1717 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d) GMT$/',$ts,$da)) {
1720 # Bogus value; fall back to the epoch...
1721 wfDebug("wfTimestamp() fed bogus time value: $outputtype; $ts\n");
1725 if (count( $da ) ) {
1726 // Warning! gmmktime() acts oddly if the month or day is set to 0
1727 // We may want to handle that explicitly at some point
1728 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1729 (int)$da[2],(int)$da[3],(int)$da[1]);
1732 switch($outputtype) {
1736 return gmdate( 'YmdHis', $uts );
1738 return gmdate( 'Y-m-d H:i:s', $uts );
1740 return gmdate( 'Y-m-d\TH:i:s\Z', $uts );
1741 // This shouldn't ever be used, but is included for completeness
1743 return gmdate( 'Y:m:d H:i:s', $uts );
1745 return gmdate( 'D, d M Y H:i:s', $uts ) . ' GMT';
1747 return gmdate( 'd-M-y h.i.s A', $uts) . ' +00:00';
1749 return gmdate( 'Y-m-d H:i:s', $uts) . ' GMT';
1751 throw new MWException( 'wfTimestamp() called with illegal output type.');
1756 * Return a formatted timestamp, or null if input is null.
1757 * For dealing with nullable timestamp columns in the database.
1758 * @param int $outputtype
1762 function wfTimestampOrNull( $outputtype = TS_UNIX
, $ts = null ) {
1763 if( is_null( $ts ) ) {
1766 return wfTimestamp( $outputtype, $ts );
1771 * Check if the operating system is Windows
1773 * @return bool True if it's Windows, False otherwise.
1775 function wfIsWindows() {
1776 if (substr(php_uname(), 0, 7) == 'Windows') {
1784 * Swap two variables
1786 function swap( &$x, &$y ) {
1792 function wfGetCachedNotice( $name ) {
1793 global $wgOut, $wgRenderHashAppend, $parserMemc;
1794 $fname = 'wfGetCachedNotice';
1795 wfProfileIn( $fname );
1799 if( $name === 'default' ) {
1801 global $wgSiteNotice;
1802 $notice = $wgSiteNotice;
1803 if( empty( $notice ) ) {
1804 wfProfileOut( $fname );
1808 $notice = wfMsgForContentNoTrans( $name );
1809 if( wfEmptyMsg( $name, $notice ) ||
$notice == '-' ) {
1810 wfProfileOut( $fname );
1815 // Use the extra hash appender to let eg SSL variants separately cache.
1816 $key = wfMemcKey( $name . $wgRenderHashAppend );
1817 $cachedNotice = $parserMemc->get( $key );
1818 if( is_array( $cachedNotice ) ) {
1819 if( md5( $notice ) == $cachedNotice['hash'] ) {
1820 $notice = $cachedNotice['html'];
1829 if( is_object( $wgOut ) ) {
1830 $parsed = $wgOut->parse( $notice );
1831 $parserMemc->set( $key, array( 'html' => $parsed, 'hash' => md5( $notice ) ), 600 );
1834 wfDebug( 'wfGetCachedNotice called for ' . $name . ' with no $wgOut available' );
1839 wfProfileOut( $fname );
1843 function wfGetNamespaceNotice() {
1847 if ( !isset( $wgTitle ) ||
!is_object( $wgTitle ) )
1850 $fname = 'wfGetNamespaceNotice';
1851 wfProfileIn( $fname );
1853 $key = "namespacenotice-" . $wgTitle->getNsText();
1854 $namespaceNotice = wfGetCachedNotice( $key );
1855 if ( $namespaceNotice && substr ( $namespaceNotice , 0 ,7 ) != "<p><" ) {
1856 $namespaceNotice = '<div id="namespacebanner">' . $namespaceNotice . "</div>";
1858 $namespaceNotice = "";
1861 wfProfileOut( $fname );
1862 return $namespaceNotice;
1865 function wfGetSiteNotice() {
1866 global $wgUser, $wgSiteNotice;
1867 $fname = 'wfGetSiteNotice';
1868 wfProfileIn( $fname );
1871 if( wfRunHooks( 'SiteNoticeBefore', array( &$siteNotice ) ) ) {
1872 if( is_object( $wgUser ) && $wgUser->isLoggedIn() ) {
1873 $siteNotice = wfGetCachedNotice( 'sitenotice' );
1875 $anonNotice = wfGetCachedNotice( 'anonnotice' );
1876 if( !$anonNotice ) {
1877 $siteNotice = wfGetCachedNotice( 'sitenotice' );
1879 $siteNotice = $anonNotice;
1882 if( !$siteNotice ) {
1883 $siteNotice = wfGetCachedNotice( 'default' );
1887 wfRunHooks( 'SiteNoticeAfter', array( &$siteNotice ) );
1888 wfProfileOut( $fname );
1893 * BC wrapper for MimeMagic::singleton()
1896 function &wfGetMimeMagic() {
1897 return MimeMagic
::singleton();
1901 * Tries to get the system directory for temporary files.
1902 * The TMPDIR, TMP, and TEMP environment variables are checked in sequence,
1903 * and if none are set /tmp is returned as the generic Unix default.
1905 * NOTE: When possible, use the tempfile() function to create temporary
1906 * files to avoid race conditions on file creation, etc.
1910 function wfTempDir() {
1911 foreach( array( 'TMPDIR', 'TMP', 'TEMP' ) as $var ) {
1912 $tmp = getenv( $var );
1913 if( $tmp && file_exists( $tmp ) && is_dir( $tmp ) && is_writable( $tmp ) ) {
1917 # Hope this is Unix of some kind!
1922 * Make directory, and make all parent directories if they don't exist
1924 * @param string $fullDir Full path to directory to create
1925 * @param int $mode Chmod value to use, default is $wgDirectoryMode
1928 function wfMkdirParents( $fullDir, $mode = null ) {
1929 global $wgDirectoryMode;
1930 if( strval( $fullDir ) === '' )
1932 if( file_exists( $fullDir ) )
1934 // If not defined or isn't an int, set to default
1935 if ( is_null( $mode ) ) {
1936 $mode = $wgDirectoryMode;
1940 # Go back through the paths to find the first directory that exists
1941 $currentDir = $fullDir;
1942 $createList = array();
1943 while ( strval( $currentDir ) !== '' && !file_exists( $currentDir ) ) {
1944 # Strip trailing slashes
1945 $currentDir = rtrim( $currentDir, '/\\' );
1947 # Add to create list
1948 $createList[] = $currentDir;
1950 # Find next delimiter searching from the end
1951 $p = max( strrpos( $currentDir, '/' ), strrpos( $currentDir, '\\' ) );
1952 if ( $p === false ) {
1953 $currentDir = false;
1955 $currentDir = substr( $currentDir, 0, $p );
1959 if ( count( $createList ) == 0 ) {
1960 # Directory specified already exists
1962 } elseif ( $currentDir === false ) {
1963 # Went all the way back to root and it apparently doesn't exist
1964 wfDebugLog( 'mkdir', "Root doesn't exist?\n" );
1967 # Now go forward creating directories
1968 $createList = array_reverse( $createList );
1970 # Is the parent directory writable?
1971 if ( $currentDir === '' ) {
1974 if ( !is_writable( $currentDir ) ) {
1975 wfDebugLog( 'mkdir', "Not writable: $currentDir\n" );
1979 foreach ( $createList as $dir ) {
1980 # use chmod to override the umask, as suggested by the PHP manual
1981 if ( !mkdir( $dir, $mode ) ||
!chmod( $dir, $mode ) ) {
1982 wfDebugLog( 'mkdir', "Unable to create directory $dir\n" );
1990 * Increment a statistics counter
1992 function wfIncrStats( $key ) {
1993 global $wgStatsMethod;
1995 if( $wgStatsMethod == 'udp' ) {
1996 global $wgUDPProfilerHost, $wgUDPProfilerPort, $wgDBname;
1999 $socket=socket_create(AF_INET
, SOCK_DGRAM
, SOL_UDP
);
2000 $statline="stats/{$wgDBname} - 1 1 1 1 1 -total\n";
2001 socket_sendto($socket,$statline,strlen($statline),0,$wgUDPProfilerHost,$wgUDPProfilerPort);
2003 $statline="stats/{$wgDBname} - 1 1 1 1 1 {$key}\n";
2004 @socket_sendto
($socket,$statline,strlen($statline),0,$wgUDPProfilerHost,$wgUDPProfilerPort);
2005 } elseif( $wgStatsMethod == 'cache' ) {
2007 $key = wfMemcKey( 'stats', $key );
2008 if ( is_null( $wgMemc->incr( $key ) ) ) {
2009 $wgMemc->add( $key, 1 );
2017 * @param mixed $nr The number to format
2018 * @param int $acc The number of digits after the decimal point, default 2
2019 * @param bool $round Whether or not to round the value, default true
2022 function wfPercent( $nr, $acc = 2, $round = true ) {
2023 $ret = sprintf( "%.${acc}f", $nr );
2024 return $round ?
round( $ret, $acc ) . '%' : "$ret%";
2028 * Encrypt a username/password.
2030 * @param string $userid ID of the user
2031 * @param string $password Password of the user
2032 * @return string Hashed password
2033 * @deprecated Use User::crypt() or User::oldCrypt() instead
2035 function wfEncryptPassword( $userid, $password ) {
2036 wfDeprecated(__FUNCTION__
);
2037 # Just wrap around User::oldCrypt()
2038 return User
::oldCrypt($password, $userid);
2042 * Appends to second array if $value differs from that in $default
2044 function wfAppendToArrayIfNotDefault( $key, $value, $default, &$changed ) {
2045 if ( is_null( $changed ) ) {
2046 throw new MWException('GlobalFunctions::wfAppendToArrayIfNotDefault got null');
2048 if ( $default[$key] !== $value ) {
2049 $changed[$key] = $value;
2054 * Since wfMsg() and co suck, they don't return false if the message key they
2055 * looked up didn't exist but a XHTML string, this function checks for the
2056 * nonexistance of messages by looking at wfMsg() output
2058 * @param $msg The message key looked up
2059 * @param $wfMsgOut The output of wfMsg*()
2062 function wfEmptyMsg( $msg, $wfMsgOut ) {
2063 return $wfMsgOut === htmlspecialchars( "<$msg>" );
2067 * Find out whether or not a mixed variable exists in a string
2069 * @param mixed needle
2070 * @param string haystack
2073 function in_string( $needle, $str ) {
2074 return strpos( $str, $needle ) !== false;
2077 function wfSpecialList( $page, $details ) {
2079 $details = $details ?
' ' . $wgContLang->getDirMark() . "($details)" : "";
2080 return $page . $details;
2084 * Returns a regular expression of url protocols
2088 function wfUrlProtocols() {
2089 global $wgUrlProtocols;
2091 // Support old-style $wgUrlProtocols strings, for backwards compatibility
2092 // with LocalSettings files from 1.5
2093 if ( is_array( $wgUrlProtocols ) ) {
2094 $protocols = array();
2095 foreach ($wgUrlProtocols as $protocol)
2096 $protocols[] = preg_quote( $protocol, '/' );
2098 return implode( '|', $protocols );
2100 return $wgUrlProtocols;
2105 * Safety wrapper around ini_get() for boolean settings.
2106 * The values returned from ini_get() are pre-normalized for settings
2107 * set via php.ini or php_flag/php_admin_flag... but *not*
2108 * for those set via php_value/php_admin_value.
2110 * It's fairly common for people to use php_value instead of php_flag,
2111 * which can leave you with an 'off' setting giving a false positive
2112 * for code that just takes the ini_get() return value as a boolean.
2114 * To make things extra interesting, setting via php_value accepts
2115 * "true" and "yes" as true, but php.ini and php_flag consider them false. :)
2116 * Unrecognized values go false... again opposite PHP's own coercion
2117 * from string to bool.
2119 * Luckily, 'properly' set settings will always come back as '0' or '1',
2120 * so we only have to worry about them and the 'improper' settings.
2122 * I frickin' hate PHP... :P
2124 * @param string $setting
2127 function wfIniGetBool( $setting ) {
2128 $val = ini_get( $setting );
2129 // 'on' and 'true' can't have whitespace around them, but '1' can.
2130 return strtolower( $val ) == 'on'
2131 ||
strtolower( $val ) == 'true'
2132 ||
strtolower( $val ) == 'yes'
2133 ||
preg_match( "/^\s*[+-]?0*[1-9]/", $val ); // approx C atoi() function
2137 * Execute a shell command, with time and memory limits mirrored from the PHP
2138 * configuration if supported.
2139 * @param $cmd Command line, properly escaped for shell.
2140 * @param &$retval optional, will receive the program's exit code.
2141 * (non-zero is usually failure)
2142 * @return collected stdout as a string (trailing newlines stripped)
2144 function wfShellExec( $cmd, &$retval=null ) {
2145 global $IP, $wgMaxShellMemory, $wgMaxShellFileSize;
2147 if( wfIniGetBool( 'safe_mode' ) ) {
2148 wfDebug( "wfShellExec can't run in safe_mode, PHP's exec functions are too broken.\n" );
2150 return "Unable to run external programs in safe mode.";
2153 if ( php_uname( 's' ) == 'Linux' ) {
2154 $time = intval( ini_get( 'max_execution_time' ) );
2155 $mem = intval( $wgMaxShellMemory );
2156 $filesize = intval( $wgMaxShellFileSize );
2158 if ( $time > 0 && $mem > 0 ) {
2159 $script = "$IP/bin/ulimit4.sh";
2160 if ( is_executable( $script ) ) {
2161 $cmd = escapeshellarg( $script ) . " $time $mem $filesize " . escapeshellarg( $cmd );
2164 } elseif ( php_uname( 's' ) == 'Windows NT' ) {
2165 # This is a hack to work around PHP's flawed invocation of cmd.exe
2166 # http://news.php.net/php.internals/21796
2167 $cmd = '"' . $cmd . '"';
2169 wfDebug( "wfShellExec: $cmd\n" );
2171 $retval = 1; // error by default?
2173 passthru( $cmd, $retval );
2174 $output = ob_get_contents();
2177 if ( $retval == 127 ) {
2178 wfDebugLog( 'exec', "Possibly missing executable file: $cmd\n" );
2185 * This function works like "use VERSION" in Perl, the program will die with a
2186 * backtrace if the current version of PHP is less than the version provided
2188 * This is useful for extensions which due to their nature are not kept in sync
2189 * with releases, and might depend on other versions of PHP than the main code
2191 * Note: PHP might die due to parsing errors in some cases before it ever
2192 * manages to call this function, such is life
2194 * @see perldoc -f use
2196 * @param mixed $version The version to check, can be a string, an integer, or
2199 function wfUsePHP( $req_ver ) {
2200 $php_ver = PHP_VERSION
;
2202 if ( version_compare( $php_ver, (string)$req_ver, '<' ) )
2203 throw new MWException( "PHP $req_ver required--this is only $php_ver" );
2207 * This function works like "use VERSION" in Perl except it checks the version
2208 * of MediaWiki, the program will die with a backtrace if the current version
2209 * of MediaWiki is less than the version provided.
2211 * This is useful for extensions which due to their nature are not kept in sync
2214 * @see perldoc -f use
2216 * @param mixed $version The version to check, can be a string, an integer, or
2219 function wfUseMW( $req_ver ) {
2222 if ( version_compare( $wgVersion, (string)$req_ver, '<' ) )
2223 throw new MWException( "MediaWiki $req_ver required--this is only $wgVersion" );
2227 * @deprecated use StringUtils::escapeRegexReplacement
2229 function wfRegexReplacement( $string ) {
2230 return StringUtils
::escapeRegexReplacement( $string );
2234 * Return the final portion of a pathname.
2235 * Reimplemented because PHP5's basename() is buggy with multibyte text.
2236 * http://bugs.php.net/bug.php?id=33898
2238 * PHP's basename() only considers '\' a pathchar on Windows and Netware.
2239 * We'll consider it so always, as we don't want \s in our Unix paths either.
2241 * @param string $path
2242 * @param string $suffix to remove if present
2245 function wfBaseName( $path, $suffix='' ) {
2246 $encSuffix = ($suffix == '')
2248 : ( '(?:' . preg_quote( $suffix, '#' ) . ')?' );
2250 if( preg_match( "#([^/\\\\]*?){$encSuffix}[/\\\\]*$#", $path, $matches ) ) {
2258 * Generate a relative path name to the given file.
2259 * May explode on non-matching case-insensitive paths,
2260 * funky symlinks, etc.
2262 * @param string $path Absolute destination path including target filename
2263 * @param string $from Absolute source path, directory only
2266 function wfRelativePath( $path, $from ) {
2267 // Normalize mixed input on Windows...
2268 $path = str_replace( '/', DIRECTORY_SEPARATOR
, $path );
2269 $from = str_replace( '/', DIRECTORY_SEPARATOR
, $from );
2271 // Trim trailing slashes -- fix for drive root
2272 $path = rtrim( $path, DIRECTORY_SEPARATOR
);
2273 $from = rtrim( $from, DIRECTORY_SEPARATOR
);
2275 $pieces = explode( DIRECTORY_SEPARATOR
, dirname( $path ) );
2276 $against = explode( DIRECTORY_SEPARATOR
, $from );
2278 if( $pieces[0] !== $against[0] ) {
2279 // Non-matching Windows drive letters?
2280 // Return a full path.
2284 // Trim off common prefix
2285 while( count( $pieces ) && count( $against )
2286 && $pieces[0] == $against[0] ) {
2287 array_shift( $pieces );
2288 array_shift( $against );
2291 // relative dots to bump us to the parent
2292 while( count( $against ) ) {
2293 array_unshift( $pieces, '..' );
2294 array_shift( $against );
2297 array_push( $pieces, wfBaseName( $path ) );
2299 return implode( DIRECTORY_SEPARATOR
, $pieces );
2303 * array_merge() does awful things with "numeric" indexes, including
2304 * string indexes when happen to look like integers. When we want
2305 * to merge arrays with arbitrary string indexes, we don't want our
2306 * arrays to be randomly corrupted just because some of them consist
2309 * Fuck you, PHP. Fuck you in the ear!
2311 * @param array $array1, [$array2, [...]]
2314 function wfArrayMerge( $array1/* ... */ ) {
2316 for( $i = 1; $i < func_num_args(); $i++
) {
2317 foreach( func_get_arg( $i ) as $key => $value ) {
2318 $out[$key] = $value;
2325 * Make a URL index, appropriate for the el_index field of externallinks.
2327 function wfMakeUrlIndex( $url ) {
2328 global $wgUrlProtocols; // Allow all protocols defined in DefaultSettings/LocalSettings.php
2329 wfSuppressWarnings();
2330 $bits = parse_url( $url );
2331 wfRestoreWarnings();
2335 // most of the protocols are followed by ://, but mailto: and sometimes news: not, check for it
2337 if ( in_array( $bits['scheme'] . '://' , $wgUrlProtocols ) ) {
2339 } elseif ( in_array( $bits['scheme'] .':' , $wgUrlProtocols ) ) {
2341 // parse_url detects for news: and mailto: the host part of an url as path
2342 // We have to correct this wrong detection
2343 if ( isset ( $bits['path'] ) ) {
2344 $bits['host'] = $bits['path'];
2351 // Reverse the labels in the hostname, convert to lower case
2352 // For emails reverse domainpart only
2353 if ( $bits['scheme'] == 'mailto' ) {
2354 $mailparts = explode( '@', $bits['host'], 2 );
2355 if ( count($mailparts) === 2 ) {
2356 $domainpart = strtolower( implode( '.', array_reverse( explode( '.', $mailparts[1] ) ) ) );
2358 // No domain specified, don't mangle it
2361 $reversedHost = $domainpart . '@' . $mailparts[0];
2363 $reversedHost = strtolower( implode( '.', array_reverse( explode( '.', $bits['host'] ) ) ) );
2365 // Add an extra dot to the end
2366 // Why? Is it in wrong place in mailto links?
2367 if ( substr( $reversedHost, -1, 1 ) !== '.' ) {
2368 $reversedHost .= '.';
2370 // Reconstruct the pseudo-URL
2371 $prot = $bits['scheme'];
2372 $index = "$prot$delimiter$reversedHost";
2373 // Leave out user and password. Add the port, path, query and fragment
2374 if ( isset( $bits['port'] ) ) $index .= ':' . $bits['port'];
2375 if ( isset( $bits['path'] ) ) {
2376 $index .= $bits['path'];
2380 if ( isset( $bits['query'] ) ) $index .= '?' . $bits['query'];
2381 if ( isset( $bits['fragment'] ) ) $index .= '#' . $bits['fragment'];
2386 * Do any deferred updates and clear the list
2387 * TODO: This could be in Wiki.php if that class made any sense at all
2389 function wfDoUpdates()
2391 global $wgPostCommitUpdateList, $wgDeferredUpdateList;
2392 foreach ( $wgDeferredUpdateList as $update ) {
2393 $update->doUpdate();
2395 foreach ( $wgPostCommitUpdateList as $update ) {
2396 $update->doUpdate();
2398 $wgDeferredUpdateList = array();
2399 $wgPostCommitUpdateList = array();
2403 * @deprecated use StringUtils::explodeMarkup
2405 function wfExplodeMarkup( $separator, $text ) {
2406 return StringUtils
::explodeMarkup( $separator, $text );
2410 * Convert an arbitrarily-long digit string from one numeric base
2411 * to another, optionally zero-padding to a minimum column width.
2413 * Supports base 2 through 36; digit values 10-36 are represented
2414 * as lowercase letters a-z. Input is case-insensitive.
2416 * @param $input string of digits
2417 * @param $sourceBase int 2-36
2418 * @param $destBase int 2-36
2419 * @param $pad int 1 or greater
2420 * @param $lowercase bool
2421 * @return string or false on invalid input
2423 function wfBaseConvert( $input, $sourceBase, $destBase, $pad=1, $lowercase=true ) {
2424 $input = strval( $input );
2425 if( $sourceBase < 2 ||
2430 $sourceBase != intval( $sourceBase ) ||
2431 $destBase != intval( $destBase ) ||
2432 $pad != intval( $pad ) ||
2433 !is_string( $input ) ||
2437 $digitChars = ( $lowercase ) ?
'0123456789abcdefghijklmnopqrstuvwxyz' : '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
2438 $inDigits = array();
2441 // Decode and validate input string
2442 $input = strtolower( $input );
2443 for( $i = 0; $i < strlen( $input ); $i++
) {
2444 $n = strpos( $digitChars, $input{$i} );
2445 if( $n === false ||
$n > $sourceBase ) {
2451 // Iterate over the input, modulo-ing out an output digit
2452 // at a time until input is gone.
2453 while( count( $inDigits ) ) {
2455 $workDigits = array();
2458 foreach( $inDigits as $digit ) {
2459 $work *= $sourceBase;
2462 if( $work < $destBase ) {
2463 // Gonna need to pull another digit.
2464 if( count( $workDigits ) ) {
2465 // Avoid zero-padding; this lets us find
2466 // the end of the input very easily when
2467 // length drops to zero.
2471 // Finally! Actual division!
2472 $workDigits[] = intval( $work / $destBase );
2474 // Isn't it annoying that most programming languages
2475 // don't have a single divide-and-remainder operator,
2476 // even though the CPU implements it that way?
2477 $work = $work %
$destBase;
2481 // All that division leaves us with a remainder,
2482 // which is conveniently our next output digit.
2483 $outChars .= $digitChars[$work];
2486 $inDigits = $workDigits;
2489 while( strlen( $outChars ) < $pad ) {
2493 return strrev( $outChars );
2497 * Create an object with a given name and an array of construct parameters
2498 * @param string $name
2499 * @param array $p parameters
2501 function wfCreateObject( $name, $p ){
2502 $p = array_values( $p );
2503 switch ( count( $p ) ) {
2507 return new $name( $p[0] );
2509 return new $name( $p[0], $p[1] );
2511 return new $name( $p[0], $p[1], $p[2] );
2513 return new $name( $p[0], $p[1], $p[2], $p[3] );
2515 return new $name( $p[0], $p[1], $p[2], $p[3], $p[4] );
2517 return new $name( $p[0], $p[1], $p[2], $p[3], $p[4], $p[5] );
2519 throw new MWException( "Too many arguments to construtor in wfCreateObject" );
2524 * Alias for modularized function
2525 * @deprecated Use Http::get() instead
2527 function wfGetHTTP( $url, $timeout = 'default' ) {
2528 wfDeprecated(__FUNCTION__
);
2529 return Http
::get( $url, $timeout );
2533 * Alias for modularized function
2534 * @deprecated Use Http::isLocalURL() instead
2536 function wfIsLocalURL( $url ) {
2537 wfDeprecated(__FUNCTION__
);
2538 return Http
::isLocalURL( $url );
2541 function wfHttpOnlySafe() {
2542 global $wgHttpOnlyBlacklist;
2543 if( !version_compare("5.2", PHP_VERSION
, "<") )
2546 if( isset( $_SERVER['HTTP_USER_AGENT'] ) ) {
2547 foreach( $wgHttpOnlyBlacklist as $regex ) {
2548 if( preg_match( $regex, $_SERVER['HTTP_USER_AGENT'] ) ) {
2558 * Initialise php session
2560 function wfSetupSession() {
2561 global $wgSessionsInMemcached, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookieHttpOnly;
2562 if( $wgSessionsInMemcached ) {
2563 require_once( 'MemcachedSessions.php' );
2564 } elseif( 'files' != ini_get( 'session.save_handler' ) ) {
2565 # If it's left on 'user' or another setting from another
2566 # application, it will end up failing. Try to recover.
2567 ini_set ( 'session.save_handler', 'files' );
2569 $httpOnlySafe = wfHttpOnlySafe();
2570 wfDebugLog( 'cookie',
2571 'session_set_cookie_params: "' . implode( '", "',
2577 $httpOnlySafe && $wgCookieHttpOnly ) ) . '"' );
2578 if( $httpOnlySafe && $wgCookieHttpOnly ) {
2579 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookieHttpOnly );
2581 // PHP 5.1 throws warnings if you pass the HttpOnly parameter for 5.2.
2582 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
2584 session_cache_limiter( 'private, must-revalidate' );
2585 wfSuppressWarnings();
2587 wfRestoreWarnings();
2591 * Get an object from the precompiled serialized directory
2593 * @return mixed The variable on success, false on failure
2595 function wfGetPrecompiledData( $name ) {
2598 $file = "$IP/serialized/$name";
2599 if ( file_exists( $file ) ) {
2600 $blob = file_get_contents( $file );
2602 return unserialize( $blob );
2608 function wfGetCaller( $level = 2 ) {
2609 $backtrace = wfDebugBacktrace();
2610 if ( isset( $backtrace[$level] ) ) {
2611 return wfFormatStackFrame($backtrace[$level]);
2613 $caller = 'unknown';
2618 /** Return a string consisting all callers in stack, somewhat useful sometimes for profiling specific points */
2619 function wfGetAllCallers() {
2620 return implode('/', array_map('wfFormatStackFrame',array_reverse(wfDebugBacktrace())));
2623 /** Return a string representation of frame */
2624 function wfFormatStackFrame($frame) {
2625 return isset( $frame["class"] )?
2626 $frame["class"]."::".$frame["function"]:
2633 function wfMemcKey( /*... */ ) {
2634 $args = func_get_args();
2635 $key = wfWikiID() . ':' . implode( ':', $args );
2640 * Get a cache key for a foreign DB
2642 function wfForeignMemcKey( $db, $prefix /*, ... */ ) {
2643 $args = array_slice( func_get_args(), 2 );
2645 $key = "$db-$prefix:" . implode( ':', $args );
2647 $key = $db . ':' . implode( ':', $args );
2653 * Get an ASCII string identifying this wiki
2654 * This is used as a prefix in memcached keys
2656 function wfWikiID( $db = null ) {
2657 if( $db instanceof Database
) {
2658 return $db->getWikiID();
2660 global $wgDBprefix, $wgDBname;
2661 if ( $wgDBprefix ) {
2662 return "$wgDBname-$wgDBprefix";
2670 * Split a wiki ID into DB name and table prefix
2672 function wfSplitWikiID( $wiki ) {
2673 $bits = explode( '-', $wiki, 2 );
2674 if ( count( $bits ) < 2 ) {
2681 * Get a Database object.
2682 * @param integer $db Index of the connection to get. May be DB_MASTER for the
2683 * master (for write queries), DB_SLAVE for potentially lagged
2684 * read queries, or an integer >= 0 for a particular server.
2686 * @param mixed $groups Query groups. An array of group names that this query
2687 * belongs to. May contain a single string if the query is only
2690 * @param string $wiki The wiki ID, or false for the current wiki
2692 * Note: multiple calls to wfGetDB(DB_SLAVE) during the course of one request
2693 * will always return the same object, unless the underlying connection or load
2694 * balancer is manually destroyed.
2696 function &wfGetDB( $db, $groups = array(), $wiki = false ) {
2697 return wfGetLB( $wiki )->getConnection( $db, $groups, $wiki );
2701 * Get a load balancer object.
2703 * @param array $groups List of query groups
2704 * @param string $wiki Wiki ID, or false for the current wiki
2705 * @return LoadBalancer
2707 function wfGetLB( $wiki = false ) {
2708 return wfGetLBFactory()->getMainLB( $wiki );
2712 * Get the load balancer factory object
2714 function &wfGetLBFactory() {
2715 return LBFactory
::singleton();
2720 * Shortcut for RepoGroup::singleton()->findFile()
2721 * @param mixed $title Title object or string. May be interwiki.
2722 * @param mixed $time Requested time for an archived image, or false for the
2723 * current version. An image object will be returned which
2724 * was created at the specified time.
2725 * @param mixed $flags FileRepo::FIND_ flags
2726 * @return File, or false if the file does not exist
2728 function wfFindFile( $title, $time = false, $flags = 0 ) {
2729 return RepoGroup
::singleton()->findFile( $title, $time, $flags );
2733 * Get an object referring to a locally registered file.
2734 * Returns a valid placeholder object if the file does not exist.
2736 function wfLocalFile( $title ) {
2737 return RepoGroup
::singleton()->getLocalRepo()->newFile( $title );
2741 * Should low-performance queries be disabled?
2745 function wfQueriesMustScale() {
2746 global $wgMiserMode;
2748 ||
( SiteStats
::pages() > 100000
2749 && SiteStats
::edits() > 1000000
2750 && SiteStats
::users() > 10000 );
2754 * Get the path to a specified script file, respecting file
2755 * extensions; this is a wrapper around $wgScriptExtension etc.
2757 * @param string $script Script filename, sans extension
2760 function wfScript( $script = 'index' ) {
2761 global $wgScriptPath, $wgScriptExtension;
2762 return "{$wgScriptPath}/{$script}{$wgScriptExtension}";
2766 * Convenience function converts boolean values into "true"
2767 * or "false" (string) values
2769 * @param bool $value
2772 function wfBoolToStr( $value ) {
2773 return $value ?
'true' : 'false';
2777 * Load an extension messages file
2779 * @param string $extensionName Name of extension to load messages from\for.
2780 * @param string $langcode Language to load messages for, or false for default
2781 * behvaiour (en, content language and user language).
2782 * @since r24808 (v1.11) Using this method of loading extension messages will not work
2783 * on MediaWiki prior to that
2785 function wfLoadExtensionMessages( $extensionName, $langcode = false ) {
2786 global $wgExtensionMessagesFiles, $wgMessageCache, $wgLang, $wgContLang;
2788 #For recording whether extension message files have been loaded in a given language.
2789 static $loaded = array();
2791 if( !array_key_exists( $extensionName, $loaded ) ) {
2792 $loaded[$extensionName] = array();
2795 if ( !isset($wgExtensionMessagesFiles[$extensionName]) ) {
2796 throw new MWException( "Messages file for extensions $extensionName is not defined" );
2799 if( !$langcode && !array_key_exists( '*', $loaded[$extensionName] ) ) {
2800 # Just do en, content language and user language.
2801 $wgMessageCache->loadMessagesFile( $wgExtensionMessagesFiles[$extensionName], false );
2802 # Mark that they have been loaded.
2803 $loaded[$extensionName]['en'] = true;
2804 $loaded[$extensionName][$wgLang->getCode()] = true;
2805 $loaded[$extensionName][$wgContLang->getCode()] = true;
2806 # Mark that this part has been done to avoid weird if statements.
2807 $loaded[$extensionName]['*'] = true;
2808 } elseif( is_string( $langcode ) && !array_key_exists( $langcode, $loaded[$extensionName] ) ) {
2809 # Load messages for specified language.
2810 $wgMessageCache->loadMessagesFile( $wgExtensionMessagesFiles[$extensionName], $langcode );
2811 # Mark that they have been loaded.
2812 $loaded[$extensionName][$langcode] = true;
2817 * Get a platform-independent path to the null file, e.g.
2822 function wfGetNull() {
2823 return wfIsWindows()
2829 * Displays a maxlag error
2831 * @param string $host Server that lags the most
2832 * @param int $lag Maxlag (actual)
2833 * @param int $maxLag Maxlag (requested)
2835 function wfMaxlagError( $host, $lag, $maxLag ) {
2836 global $wgShowHostnames;
2837 header( 'HTTP/1.1 503 Service Unavailable' );
2838 header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
2839 header( 'X-Database-Lag: ' . intval( $lag ) );
2840 header( 'Content-Type: text/plain' );
2841 if( $wgShowHostnames ) {
2842 echo "Waiting for $host: $lag seconds lagged\n";
2844 echo "Waiting for a database server: $lag seconds lagged\n";
2849 * Throws an E_USER_NOTICE saying that $function is deprecated
2850 * @param string $function
2853 function wfDeprecated( $function ) {
2854 global $wgDebugLogFile;
2855 if ( !$wgDebugLogFile ) {
2858 $callers = wfDebugBacktrace();
2859 if( isset( $callers[2] ) ){
2860 $callerfunc = $callers[2];
2861 $callerfile = $callers[1];
2862 if( isset( $callerfile['file'] ) && isset( $callerfile['line'] ) ){
2863 $file = $callerfile['file'] . ' at line ' . $callerfile['line'];
2865 $file = '(internal function)';
2868 if( isset( $callerfunc['class'] ) )
2869 $func .= $callerfunc['class'] . '::';
2870 $func .= @$callerfunc['function'];
2871 $msg = "Use of $function is deprecated. Called from $func in $file";
2873 $msg = "Use of $function is deprecated.";
2875 wfDebug( "$msg\n" );
2879 * Sleep until the worst slave's replication lag is less than or equal to
2880 * $maxLag, in seconds. Use this when updating very large numbers of rows, as
2881 * in maintenance scripts, to avoid causing too much lag. Of course, this is
2882 * a no-op if there are no slaves.
2884 * Every time the function has to wait for a slave, it will print a message to
2885 * that effect (and then sleep for a little while), so it's probably not best
2886 * to use this outside maintenance scripts in its present form.
2888 * @param int $maxLag
2891 function wfWaitForSlaves( $maxLag ) {
2894 list( $host, $lag ) = $lb->getMaxLag();
2895 while( $lag > $maxLag ) {
2896 $name = @gethostbyaddr
( $host );
2897 if( $name !== false ) {
2900 print "Waiting for $host (lagged $lag seconds)...\n";
2902 list( $host, $lag ) = $lb->getMaxLag();
2907 /** Generate a random 32-character hexadecimal token.
2908 * @param mixed $salt Some sort of salt, if necessary, to add to random characters before hashing.
2910 function wfGenerateToken( $salt = '' ) {
2911 $salt = serialize($salt);
2913 return md5( mt_rand( 0, 0x7fffffff ) . $salt );
2917 * Replace all invalid characters with -
2918 * @param mixed $title Filename to process
2920 function wfStripIllegalFilenameChars( $name ) {
2921 $name = wfBaseName( $name );
2922 $name = preg_replace ( "/[^".Title
::legalChars()."]|:/", '-', $name );