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 $dir = dirname(__FILE__
) . '/';
12 require_once $dir . 'LogPage.php';
13 require_once $dir . 'normal/UtfNormalUtil.php';
14 require_once $dir . 'XmlFunctions.php';
16 // Hide compatibility functions from Doxygen
20 * Compatibility functions
22 * We more or less support PHP 5.0.x and up.
23 * Re-implementations of newer functions or functions in non-standard
24 * PHP extensions may be included here.
26 if( !function_exists('iconv') ) {
27 # iconv support is not in the default configuration and so may not be present.
28 # Assume will only ever use utf-8 and iso-8859-1.
29 # This will *not* work in all circumstances.
30 function iconv( $from, $to, $string ) {
31 if(strcasecmp( $from, $to ) == 0) return $string;
32 if(strcasecmp( $from, 'utf-8' ) == 0) return utf8_decode( $string );
33 if(strcasecmp( $to, 'utf-8' ) == 0) return utf8_encode( $string );
38 # UTF-8 substr function based on a PHP manual comment
39 if ( !function_exists( 'mb_substr' ) ) {
40 function mb_substr( $str, $start ) {
42 preg_match_all( '/./us', $str, $ar );
44 if( func_num_args() >= 3 ) {
45 $end = func_get_arg( 2 );
46 return join( '', array_slice( $ar[0], $start, $end ) );
48 return join( '', array_slice( $ar[0], $start ) );
53 if ( !function_exists( 'mb_strlen' ) ) {
55 * Fallback implementation of mb_strlen, hardcoded to UTF-8.
57 * @param string $enc optional encoding; ignored
60 function mb_strlen( $str, $enc="" ) {
61 $counts = count_chars( $str );
65 for( $i = 0; $i < 0x80; $i++
) {
66 $total +
= $counts[$i];
69 // Count multibyte sequence heads
70 for( $i = 0xc0; $i < 0xff; $i++
) {
71 $total +
= $counts[$i];
77 if ( !function_exists( 'array_diff_key' ) ) {
79 * Exists in PHP 5.1.0+
80 * Not quite compatible, two-argument version only
81 * Null values will cause problems due to this use of isset()
83 function array_diff_key( $left, $right ) {
85 foreach ( $left as $key => $unused ) {
86 if ( isset( $right[$key] ) ) {
87 unset( $result[$key] );
98 * Like array_diff( $a, $b ) except that it works with two-dimensional arrays.
100 function wfArrayDiff2( $a, $b ) {
101 return array_udiff( $a, $b, 'wfArrayDiff2_cmp' );
103 function wfArrayDiff2_cmp( $a, $b ) {
104 if ( !is_array( $a ) ) {
105 return strcmp( $a, $b );
106 } elseif ( count( $a ) !== count( $b ) ) {
107 return count( $a ) < count( $b ) ?
-1 : 1;
111 while( ( list( $keyA, $valueA ) = each( $a ) ) && ( list( $keyB, $valueB ) = each( $b ) ) ) {
112 $cmp = strcmp( $valueA, $valueB );
122 * Wrapper for clone(), for compatibility with PHP4-friendly extensions.
123 * PHP 5 won't let you declare a 'clone' function, even conditionally,
124 * so it has to be a wrapper with a different name.
126 function wfClone( $object ) {
127 return clone( $object );
131 * Seed Mersenne Twister
132 * No-op for compatibility; only necessary in PHP < 4.2.0
134 function wfSeedRandom() {
139 * Get a random decimal value between 0 and 1, in a way
140 * not likely to give duplicate values for any realistic
141 * number of articles.
145 function wfRandom() {
146 # The maximum random value is "only" 2^31-1, so get two random
147 # values to reduce the chance of dupes
148 $max = mt_getrandmax() +
1;
149 $rand = number_format( (mt_rand() * $max +
mt_rand())
150 / $max / $max, 12, '.', '' );
155 * We want some things to be included as literal characters in our title URLs
156 * for prettiness, which urlencode encodes by default. According to RFC 1738,
157 * all of the following should be safe:
161 * But + is not safe because it's used to indicate a space; &= are only safe in
162 * paths and not in queries (and we don't distinguish here); ' seems kind of
163 * scary; and urlencode() doesn't touch -_. to begin with. Plus, although /
164 * is reserved, we don't care. So the list we unescape is:
168 * %2F in the page titles seems to fatally break for some reason.
173 function wfUrlencode( $s ) {
174 $s = urlencode( $s );
176 array( '%3B','%3A','%40','%24','%21','%2A','%28','%29','%2C','%2F' ),
177 array( ';', ':', '@', '$', '!', '*', '(', ')', ',', '/' ),
185 * Sends a line to the debug log if enabled or, optionally, to a comment in output.
186 * In normal operation this is a NOP.
188 * Controlling globals:
189 * $wgDebugLogFile - points to the log file
190 * $wgProfileOnly - if set, normal debug messages will not be recorded.
191 * $wgDebugRawPage - if false, 'action=raw' hits will not result in debug output.
192 * $wgDebugComments - if on, some debug items may appear in comments in the HTML output.
194 * @param $text String
195 * @param $logonly Bool: set true to avoid appearing in HTML when $wgDebugComments is set
197 function wfDebug( $text, $logonly = false ) {
198 global $wgOut, $wgDebugLogFile, $wgDebugComments, $wgProfileOnly, $wgDebugRawPage;
199 global $wgDebugLogPrefix;
200 static $recursion = 0;
202 static $cache = array(); // Cache of unoutputted messages
204 # Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
205 if ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' && !$wgDebugRawPage ) {
209 if ( $wgDebugComments && !$logonly ) {
212 if ( !isset( $wgOut ) ) {
215 if ( !StubObject
::isRealObject( $wgOut ) ) {
224 // add the message and possible cached ones to the output
225 array_map( array( $wgOut, 'debug' ), $cache );
228 if ( '' != $wgDebugLogFile && !$wgProfileOnly ) {
229 # Strip unprintables; they can switch terminal modes when binary data
230 # gets dumped, which is pretty annoying.
231 $text = preg_replace( '![\x00-\x08\x0b\x0c\x0e-\x1f]!', ' ', $text );
232 $text = $wgDebugLogPrefix . $text;
233 wfErrorLog( $text, $wgDebugLogFile );
238 * Send a line giving PHP memory usage.
239 * @param $exact Bool : print exact values instead of kilobytes (default: false)
241 function wfDebugMem( $exact = false ) {
242 $mem = memory_get_usage();
244 $mem = floor( $mem / 1024 ) . ' kilobytes';
248 wfDebug( "Memory usage: $mem\n" );
252 * Send a line to a supplementary debug log file, if configured, or main debug log if not.
253 * $wgDebugLogGroups[$logGroup] should be set to a filename to send to a separate log.
255 * @param $logGroup String
256 * @param $text String
257 * @param $public Bool: whether to log the event in the public log if no private
258 * log file is specified, (default true)
260 function wfDebugLog( $logGroup, $text, $public = true ) {
261 global $wgDebugLogGroups, $wgShowHostnames;
262 if( $text{strlen( $text ) - 1} != "\n" ) $text .= "\n";
263 if( isset( $wgDebugLogGroups[$logGroup] ) ) {
264 $time = wfTimestamp( TS_DB
);
266 if ( $wgShowHostnames ) {
267 $host = wfHostname();
271 wfErrorLog( "$time $host $wiki: $text", $wgDebugLogGroups[$logGroup] );
272 } else if ( $public === true ) {
273 wfDebug( $text, true );
278 * Log for database errors
279 * @param $text String: database error message.
281 function wfLogDBError( $text ) {
282 global $wgDBerrorLog, $wgDBname;
283 if ( $wgDBerrorLog ) {
284 $host = trim(`hostname`
);
285 $text = date('D M j G:i:s T Y') . "\t$host\t$wgDBname\t$text";
286 wfErrorLog( $text, $wgDBerrorLog );
291 * Log to a file without getting "file size exceeded" signals.
293 * Can also log to TCP or UDP with the syntax udp://host:port/prefix. This will
294 * send lines to the specified port, prefixed by the specified prefix and a space.
296 function wfErrorLog( $text, $file ) {
297 if ( substr( $file, 0, 4 ) == 'udp:' ) {
298 if ( preg_match( '!^(tcp|udp):(?://)?\[([0-9a-fA-F:]+)\]:(\d+)(?:/(.*))?$!', $file, $m ) ) {
299 // IPv6 bracketed host
303 $prefix = isset( $m[4] ) ?
$m[4] : false;
304 } elseif ( preg_match( '!^(tcp|udp):(?://)?([a-zA-Z0-9.-]+):(\d+)(?:/(.*))?$!', $file, $m ) ) {
308 $prefix = isset( $m[4] ) ?
$m[4] : false;
310 throw new MWException( __METHOD__
.": Invalid UDP specification" );
312 // Clean it up for the multiplexer
313 if ( strval( $prefix ) !== '' ) {
314 $text = preg_replace( '/^/m', $prefix . ' ', $text );
315 if ( substr( $text, -1 ) != "\n" ) {
320 $sock = fsockopen( "$protocol://$host", $port );
324 fwrite( $sock, $text );
327 wfSuppressWarnings();
328 $exists = file_exists( $file );
329 $size = $exists ?
filesize( $file ) : false;
330 if ( !$exists ||
( $size !== false && $size +
strlen( $text ) < 0x7fffffff ) ) {
331 error_log( $text, 3, $file );
340 function wfLogProfilingData() {
341 global $wgRequestTime, $wgDebugLogFile, $wgDebugRawPage, $wgRequest;
342 global $wgProfiler, $wgUser;
343 if ( !isset( $wgProfiler ) )
347 $elapsed = $now - $wgRequestTime;
348 $prof = wfGetProfilingOutput( $wgRequestTime, $elapsed );
350 if( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) )
351 $forward = ' forwarded for ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
352 if( !empty( $_SERVER['HTTP_CLIENT_IP'] ) )
353 $forward .= ' client IP ' . $_SERVER['HTTP_CLIENT_IP'];
354 if( !empty( $_SERVER['HTTP_FROM'] ) )
355 $forward .= ' from ' . $_SERVER['HTTP_FROM'];
357 $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
358 // Don't unstub $wgUser at this late stage just for statistics purposes
359 if( StubObject
::isRealObject($wgUser) && $wgUser->isAnon() )
361 $log = sprintf( "%s\t%04.3f\t%s\n",
362 gmdate( 'YmdHis' ), $elapsed,
363 urldecode( $wgRequest->getRequestURL() . $forward ) );
364 if ( '' != $wgDebugLogFile && ( $wgRequest->getVal('action') != 'raw' ||
$wgDebugRawPage ) ) {
365 wfErrorLog( $log . $prof, $wgDebugLogFile );
370 * Check if the wiki read-only lock file is present. This can be used to lock
371 * off editing functions, but doesn't guarantee that the database will not be
375 function wfReadOnly() {
376 global $wgReadOnlyFile, $wgReadOnly;
378 if ( !is_null( $wgReadOnly ) ) {
379 return (bool)$wgReadOnly;
381 if ( '' == $wgReadOnlyFile ) {
384 // Set $wgReadOnly for faster access next time
385 if ( is_file( $wgReadOnlyFile ) ) {
386 $wgReadOnly = file_get_contents( $wgReadOnlyFile );
390 return (bool)$wgReadOnly;
393 function wfReadOnlyReason() {
400 * Return a Language object from $langcode
401 * @param $langcode Mixed: either:
402 * - a Language object
403 * - code of the language to get the message for, if it is
404 * a valid code create a language for that language, if
405 * it is a string but not a valid code then make a basic
407 * - a boolean: if it's false then use the current users
408 * language (as a fallback for the old parameter
409 * functionality), or if it is true then use the wikis
410 * @return Language object
412 function wfGetLangObj( $langcode = false ){
413 # Identify which language to get or create a language object for.
414 if( $langcode instanceof Language
)
415 # Great, we already have the object!
419 if( $langcode === $wgContLang->getCode() ||
$langcode === true )
420 # $langcode is the language code of the wikis content language object.
421 # or it is a boolean and value is true
425 if( $langcode === $wgLang->getCode() ||
$langcode === false )
426 # $langcode is the language code of user language object.
427 # or it was a boolean and value is false
430 $validCodes = array_keys( Language
::getLanguageNames() );
431 if( in_array( $langcode, $validCodes ) )
432 # $langcode corresponds to a valid language.
433 return Language
::factory( $langcode );
435 # $langcode is a string, but not a valid language code; use content language.
436 wfDebug( 'Invalid language code passed to wfGetLangObj, falling back to content language.' );
441 * Get a message from anywhere, for the current user language.
443 * Use wfMsgForContent() instead if the message should NOT
444 * change depending on the user preferences.
446 * @param $key String: lookup key for the message, usually
447 * defined in languages/Language.php
449 * This function also takes extra optional parameters (not
450 * shown in the function definition), which can by used to
451 * insert variable text into the predefined message.
453 function wfMsg( $key ) {
454 $args = func_get_args();
455 array_shift( $args );
456 return wfMsgReal( $key, $args, true );
460 * Same as above except doesn't transform the message
462 function wfMsgNoTrans( $key ) {
463 $args = func_get_args();
464 array_shift( $args );
465 return wfMsgReal( $key, $args, true, false, false );
469 * Get a message from anywhere, for the current global language
470 * set with $wgLanguageCode.
472 * Use this if the message should NOT change dependent on the
473 * language set in the user's preferences. This is the case for
474 * most text written into logs, as well as link targets (such as
475 * the name of the copyright policy page). Link titles, on the
476 * other hand, should be shown in the UI language.
478 * Note that MediaWiki allows users to change the user interface
479 * language in their preferences, but a single installation
480 * typically only contains content in one language.
482 * Be wary of this distinction: If you use wfMsg() where you should
483 * use wfMsgForContent(), a user of the software may have to
484 * customize over 70 messages in order to, e.g., fix a link in every
487 * @param $key String: lookup key for the message, usually
488 * defined in languages/Language.php
490 function wfMsgForContent( $key ) {
491 global $wgForceUIMsgAsContentMsg;
492 $args = func_get_args();
493 array_shift( $args );
495 if( is_array( $wgForceUIMsgAsContentMsg ) &&
496 in_array( $key, $wgForceUIMsgAsContentMsg ) )
498 return wfMsgReal( $key, $args, true, $forcontent );
502 * Same as above except doesn't transform the message
504 function wfMsgForContentNoTrans( $key ) {
505 global $wgForceUIMsgAsContentMsg;
506 $args = func_get_args();
507 array_shift( $args );
509 if( is_array( $wgForceUIMsgAsContentMsg ) &&
510 in_array( $key, $wgForceUIMsgAsContentMsg ) )
512 return wfMsgReal( $key, $args, true, $forcontent, false );
516 * Get a message from the language file, for the UI elements
518 function wfMsgNoDB( $key ) {
519 $args = func_get_args();
520 array_shift( $args );
521 return wfMsgReal( $key, $args, false );
525 * Get a message from the language file, for the content
527 function wfMsgNoDBForContent( $key ) {
528 global $wgForceUIMsgAsContentMsg;
529 $args = func_get_args();
530 array_shift( $args );
532 if( is_array( $wgForceUIMsgAsContentMsg ) &&
533 in_array( $key, $wgForceUIMsgAsContentMsg ) )
535 return wfMsgReal( $key, $args, false, $forcontent );
540 * Really get a message
541 * @param $key String: key to get.
543 * @param $useDB Boolean
544 * @param $transform Boolean: Whether or not to transform the message.
545 * @param $forContent Boolean
546 * @return String: the requested message.
548 function wfMsgReal( $key, $args, $useDB = true, $forContent=false, $transform = true ) {
549 wfProfileIn( __METHOD__
);
550 $message = wfMsgGetKey( $key, $useDB, $forContent, $transform );
551 $message = wfMsgReplaceArgs( $message, $args );
552 wfProfileOut( __METHOD__
);
557 * This function provides the message source for messages to be edited which are *not* stored in the database.
558 * @param $key String:
560 function wfMsgWeirdKey ( $key ) {
561 $source = wfMsgGetKey( $key, false, true, false );
562 if ( wfEmptyMsg( $key, $source ) )
569 * Fetch a message string value, but don't replace any keys yet.
572 * @param string $langcode Code of the language to get the message for, or
573 * behaves as a content language switch if it is a
578 function wfMsgGetKey( $key, $useDB, $langCode = false, $transform = true ) {
579 global $wgContLang, $wgMessageCache;
581 wfRunHooks('NormalizeMessageKey', array(&$key, &$useDB, &$langCode, &$transform));
583 # If $wgMessageCache isn't initialised yet, try to return something sensible.
584 if( is_object( $wgMessageCache ) ) {
585 $message = $wgMessageCache->get( $key, $useDB, $langCode );
587 $message = $wgMessageCache->transform( $message );
590 $lang = wfGetLangObj( $langCode );
592 # MessageCache::get() does this already, Language::getMessage() doesn't
593 # ISSUE: Should we try to handle "message/lang" here too?
594 $key = str_replace( ' ' , '_' , $wgContLang->lcfirst( $key ) );
596 if( is_object( $lang ) ) {
597 $message = $lang->getMessage( $key );
607 * Replace message parameter keys on the given formatted output.
609 * @param string $message
614 function wfMsgReplaceArgs( $message, $args ) {
615 # Fix windows line-endings
616 # Some messages are split with explode("\n", $msg)
617 $message = str_replace( "\r", '', $message );
620 if ( count( $args ) ) {
621 if ( is_array( $args[0] ) ) {
622 $args = array_values( $args[0] );
624 $replacementKeys = array();
625 foreach( $args as $n => $param ) {
626 $replacementKeys['$' . ($n +
1)] = $param;
628 $message = strtr( $message, $replacementKeys );
635 * Return an HTML-escaped version of a message.
636 * Parameter replacements, if any, are done *after* the HTML-escaping,
637 * so parameters may contain HTML (eg links or form controls). Be sure
638 * to pre-escape them if you really do want plaintext, or just wrap
639 * the whole thing in htmlspecialchars().
642 * @param string ... parameters
645 function wfMsgHtml( $key ) {
646 $args = func_get_args();
647 array_shift( $args );
648 return wfMsgReplaceArgs( htmlspecialchars( wfMsgGetKey( $key, true ) ), $args );
652 * Return an HTML version of message
653 * Parameter replacements, if any, are done *after* parsing the wiki-text message,
654 * so parameters may contain HTML (eg links or form controls). Be sure
655 * to pre-escape them if you really do want plaintext, or just wrap
656 * the whole thing in htmlspecialchars().
659 * @param string ... parameters
662 function wfMsgWikiHtml( $key ) {
664 $args = func_get_args();
665 array_shift( $args );
666 return wfMsgReplaceArgs( $wgOut->parse( wfMsgGetKey( $key, true ), /* can't be set to false */ true ), $args );
670 * Returns message in the requested format
671 * @param string $key Key of the message
672 * @param array $options Processing rules. Can take the following options:
673 * <i>parse</i>: parses wikitext to html
674 * <i>parseinline</i>: parses wikitext to html and removes the surrounding
675 * p's added by parser or tidy
676 * <i>escape</i>: filters message through htmlspecialchars
677 * <i>escapenoentities</i>: same, but allows entity references like through
678 * <i>replaceafter</i>: parameters are substituted after parsing or escaping
679 * <i>parsemag</i>: transform the message using magic phrases
680 * <i>content</i>: fetch message for content language instead of interface
681 * Also can accept a single associative argument, of the form 'language' => 'xx':
682 * <i>language</i>: Language object or language code to fetch message for
683 * (overriden by <i>content</i>), its behaviour with parser, parseinline
684 * and parsemag is undefined.
685 * Behavior for conflicting options (e.g., parse+parseinline) is undefined.
687 function wfMsgExt( $key, $options ) {
690 $args = func_get_args();
691 array_shift( $args );
692 array_shift( $args );
693 $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, true ) ) {
710 } elseif( array_key_exists('language', $options) ) {
712 $langCode = wfGetLangObj( $options['language'] );
718 $string = wfMsgGetKey( $key, /*DB*/true, $langCode, /*Transform*/false );
720 if( !in_array('replaceafter', $options, true ) ) {
721 $string = wfMsgReplaceArgs( $string, $args );
724 if( in_array('parse', $options, true ) ) {
725 $string = $wgOut->parse( $string, true, !$forContent );
726 } elseif ( in_array('parseinline', $options, true ) ) {
727 $string = $wgOut->parse( $string, true, !$forContent );
729 if( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $string, $m ) ) {
732 } elseif ( in_array('parsemag', $options, true ) ) {
733 global $wgMessageCache;
734 if ( isset( $wgMessageCache ) ) {
735 $string = $wgMessageCache->transform( $string,
737 is_object( $langCode ) ?
$langCode : null );
741 if ( in_array('escape', $options, true ) ) {
742 $string = htmlspecialchars ( $string );
743 } elseif ( in_array( 'escapenoentities', $options, true ) ) {
744 $string = Sanitizer
::escapeHtmlAllowEntities( $string );
747 if( in_array('replaceafter', $options, true ) ) {
748 $string = wfMsgReplaceArgs( $string, $args );
756 * Just like exit() but makes a note of it.
757 * Commits open transactions except if the error parameter is set
759 * @deprecated Please return control to the caller or throw an exception
761 function wfAbruptExit( $error = false ){
762 static $called = false;
768 $bt = wfDebugBacktrace();
770 for($i = 0; $i < count($bt) ; $i++
){
771 $file = isset($bt[$i]['file']) ?
$bt[$i]['file'] : "unknown";
772 $line = isset($bt[$i]['line']) ?
$bt[$i]['line'] : "unknown";
773 wfDebug("WARNING: Abrupt exit in $file at line $line\n");
776 wfDebug('WARNING: Abrupt exit\n');
779 wfLogProfilingData();
782 wfGetLB()->closeAll();
788 * @deprecated Please return control the caller or throw an exception
790 function wfErrorExit() {
791 wfAbruptExit( true );
795 * Print a simple message and die, returning nonzero to the shell if any.
796 * Plain die() fails to return nonzero to the shell if you pass a string.
799 function wfDie( $msg='' ) {
805 * Throw a debugging exception. This function previously once exited the process,
806 * but now throws an exception instead, with similar results.
808 * @param string $msg Message shown when dieing.
810 function wfDebugDieBacktrace( $msg = '' ) {
811 throw new MWException( $msg );
815 * Fetch server name for use in error reporting etc.
816 * Use real server name if available, so we know which machine
817 * in a server farm generated the current page.
820 function wfHostname() {
822 if ( is_null( $host ) ) {
823 if ( function_exists( 'posix_uname' ) ) {
824 // This function not present on Windows
825 $uname = @posix_uname
();
829 if( is_array( $uname ) && isset( $uname['nodename'] ) ) {
830 $host = $uname['nodename'];
831 } elseif ( getenv( 'COMPUTERNAME' ) ) {
832 # Windows computer name
833 $host = getenv( 'COMPUTERNAME' );
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 * Also fixes the locale problems on Linux in PHP 5.2.6+ (bug backported to
1226 * earlier distro releases of PHP)
1228 function wfEscapeShellArg( ) {
1229 wfInitShellLocale();
1231 $args = func_get_args();
1234 foreach ( $args as $arg ) {
1241 if ( wfIsWindows() ) {
1242 // Escaping for an MSVC-style command line parser
1243 // Ref: http://mailman.lyra.org/pipermail/scite-interest/2002-March/000436.html
1244 // Double the backslashes before any double quotes. Escape the double quotes.
1245 $tokens = preg_split( '/(\\\\*")/', $arg, -1, PREG_SPLIT_DELIM_CAPTURE
);
1248 foreach ( $tokens as $token ) {
1250 $arg .= str_replace( '\\', '\\\\', substr( $token, 0, -1 ) ) . '\\"';
1256 // Double the backslashes before the end of the string, because
1257 // we will soon add a quote
1259 if ( preg_match( '/^(.*?)(\\\\+)$/', $arg, $m ) ) {
1260 $arg = $m[1] . str_replace( '\\', '\\\\', $m[2] );
1263 // Add surrounding quotes
1264 $retVal .= '"' . $arg . '"';
1266 $retVal .= escapeshellarg( $arg );
1273 * wfMerge attempts to merge differences between three texts.
1274 * Returns true for a clean merge and false for failure or a conflict.
1276 function wfMerge( $old, $mine, $yours, &$result ){
1279 # This check may also protect against code injection in
1280 # case of broken installations.
1281 if( !$wgDiff3 ||
!file_exists( $wgDiff3 ) ) {
1282 wfDebug( "diff3 not found\n" );
1286 # Make temporary files
1288 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
1289 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
1290 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
1292 fwrite( $oldtextFile, $old ); fclose( $oldtextFile );
1293 fwrite( $mytextFile, $mine ); fclose( $mytextFile );
1294 fwrite( $yourtextFile, $yours ); fclose( $yourtextFile );
1296 # Check for a conflict
1297 $cmd = $wgDiff3 . ' -a --overlap-only ' .
1298 wfEscapeShellArg( $mytextName ) . ' ' .
1299 wfEscapeShellArg( $oldtextName ) . ' ' .
1300 wfEscapeShellArg( $yourtextName );
1301 $handle = popen( $cmd, 'r' );
1303 if( fgets( $handle, 1024 ) ){
1311 $cmd = $wgDiff3 . ' -a -e --merge ' .
1312 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
1313 $handle = popen( $cmd, 'r' );
1316 $data = fread( $handle, 8192 );
1317 if ( strlen( $data ) == 0 ) {
1323 unlink( $mytextName ); unlink( $oldtextName ); unlink( $yourtextName );
1325 if ( $result === '' && $old !== '' && $conflict == false ) {
1326 wfDebug( "Unexpected null result from diff3. Command: $cmd\n" );
1333 * Returns unified plain-text diff of two texts.
1334 * Useful for machine processing of diffs.
1335 * @param $before string The text before the changes.
1336 * @param $after string The text after the changes.
1337 * @param $params string Command-line options for the diff command.
1338 * @return string Unified diff of $before and $after
1340 function wfDiff( $before, $after, $params = '-u' ) {
1343 # This check may also protect against code injection in
1344 # case of broken installations.
1345 if( !file_exists( $wgDiff ) ){
1346 wfDebug( "diff executable not found\n" );
1347 $diffs = new Diff( explode( "\n", $before ), explode( "\n", $after ) );
1348 $format = new UnifiedDiffFormatter();
1349 return $format->format( $diffs );
1352 # Make temporary files
1354 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
1355 $newtextFile = fopen( $newtextName = tempnam( $td, 'merge-your-' ), 'w' );
1357 fwrite( $oldtextFile, $before ); fclose( $oldtextFile );
1358 fwrite( $newtextFile, $after ); fclose( $newtextFile );
1360 // Get the diff of the two files
1361 $cmd = "$wgDiff " . $params . ' ' .wfEscapeShellArg( $oldtextName, $newtextName );
1363 $h = popen( $cmd, 'r' );
1368 $data = fread( $h, 8192 );
1369 if ( strlen( $data ) == 0 ) {
1377 unlink( $oldtextName );
1378 unlink( $newtextName );
1380 // Kill the --- and +++ lines. They're not useful.
1381 $diff_lines = explode( "\n", $diff );
1382 if (strpos( $diff_lines[0], '---' ) === 0) {
1383 unset($diff_lines[0]);
1385 if (strpos( $diff_lines[1], '+++' ) === 0) {
1386 unset($diff_lines[1]);
1389 $diff = implode( "\n", $diff_lines );
1395 * A wrapper around the PHP function var_export().
1396 * Either print it or add it to the regular output ($wgOut).
1398 * @param $var A PHP variable to dump.
1400 function wfVarDump( $var ) {
1402 $s = str_replace("\n","<br />\n", var_export( $var, true ) . "\n");
1403 if ( headers_sent() ||
!@is_object
( $wgOut ) ) {
1406 $wgOut->addHTML( $s );
1411 * Provide a simple HTTP error.
1413 function wfHttpError( $code, $label, $desc ) {
1416 header( "HTTP/1.0 $code $label" );
1417 header( "Status: $code $label" );
1418 $wgOut->sendCacheControl();
1420 header( 'Content-type: text/html; charset=utf-8' );
1421 print "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">".
1422 "<html><head><title>" .
1423 htmlspecialchars( $label ) .
1424 "</title></head><body><h1>" .
1425 htmlspecialchars( $label ) .
1427 nl2br( htmlspecialchars( $desc ) ) .
1428 "</p></body></html>\n";
1432 * Clear away any user-level output buffers, discarding contents.
1434 * Suitable for 'starting afresh', for instance when streaming
1435 * relatively large amounts of data without buffering, or wanting to
1436 * output image files without ob_gzhandler's compression.
1438 * The optional $resetGzipEncoding parameter controls suppression of
1439 * the Content-Encoding header sent by ob_gzhandler; by default it
1440 * is left. See comments for wfClearOutputBuffers() for why it would
1443 * Note that some PHP configuration options may add output buffer
1444 * layers which cannot be removed; these are left in place.
1446 * @param bool $resetGzipEncoding
1448 function wfResetOutputBuffers( $resetGzipEncoding=true ) {
1449 if( $resetGzipEncoding ) {
1450 // Suppress Content-Encoding and Content-Length
1451 // headers from 1.10+s wfOutputHandler
1452 global $wgDisableOutputCompression;
1453 $wgDisableOutputCompression = true;
1455 while( $status = ob_get_status() ) {
1456 if( $status['type'] == 0 /* PHP_OUTPUT_HANDLER_INTERNAL */ ) {
1457 // Probably from zlib.output_compression or other
1458 // PHP-internal setting which can't be removed.
1460 // Give up, and hope the result doesn't break
1464 if( !ob_end_clean() ) {
1465 // Could not remove output buffer handler; abort now
1466 // to avoid getting in some kind of infinite loop.
1469 if( $resetGzipEncoding ) {
1470 if( $status['name'] == 'ob_gzhandler' ) {
1471 // Reset the 'Content-Encoding' field set by this handler
1472 // so we can start fresh.
1473 header( 'Content-Encoding:' );
1481 * More legible than passing a 'false' parameter to wfResetOutputBuffers():
1483 * Clear away output buffers, but keep the Content-Encoding header
1484 * produced by ob_gzhandler, if any.
1486 * This should be used for HTTP 304 responses, where you need to
1487 * preserve the Content-Encoding header of the real result, but
1488 * also need to suppress the output of ob_gzhandler to keep to spec
1489 * and avoid breaking Firefox in rare cases where the headers and
1490 * body are broken over two packets.
1492 function wfClearOutputBuffers() {
1493 wfResetOutputBuffers( false );
1497 * Converts an Accept-* header into an array mapping string values to quality
1500 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
1501 # No arg means accept anything (per HTTP spec)
1503 return array( $def => 1.0 );
1508 $parts = explode( ',', $accept );
1510 foreach( $parts as $part ) {
1511 # FIXME: doesn't deal with params like 'text/html; level=1'
1512 @list
( $value, $qpart ) = explode( ';', trim( $part ) );
1514 if( !isset( $qpart ) ) {
1515 $prefs[$value] = 1.0;
1516 } elseif( preg_match( '/q\s*=\s*(\d*\.\d+)/', $qpart, $match ) ) {
1517 $prefs[$value] = floatval($match[1]);
1525 * Checks if a given MIME type matches any of the keys in the given
1526 * array. Basic wildcards are accepted in the array keys.
1528 * Returns the matching MIME type (or wildcard) if a match, otherwise
1531 * @param string $type
1532 * @param array $avail
1536 function mimeTypeMatch( $type, $avail ) {
1537 if( array_key_exists($type, $avail) ) {
1540 $parts = explode( '/', $type );
1541 if( array_key_exists( $parts[0] . '/*', $avail ) ) {
1542 return $parts[0] . '/*';
1543 } elseif( array_key_exists( '*/*', $avail ) ) {
1552 * Returns the 'best' match between a client's requested internet media types
1553 * and the server's list of available types. Each list should be an associative
1554 * array of type to preference (preference is a float between 0.0 and 1.0).
1555 * Wildcards in the types are acceptable.
1557 * @param array $cprefs Client's acceptable type list
1558 * @param array $sprefs Server's offered types
1561 * @todo FIXME: doesn't handle params like 'text/plain; charset=UTF-8'
1562 * XXX: generalize to negotiate other stuff
1564 function wfNegotiateType( $cprefs, $sprefs ) {
1567 foreach( array_keys($sprefs) as $type ) {
1568 $parts = explode( '/', $type );
1569 if( $parts[1] != '*' ) {
1570 $ckey = mimeTypeMatch( $type, $cprefs );
1572 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1577 foreach( array_keys( $cprefs ) as $type ) {
1578 $parts = explode( '/', $type );
1579 if( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
1580 $skey = mimeTypeMatch( $type, $sprefs );
1582 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1590 foreach( array_keys( $combine ) as $type ) {
1591 if( $combine[$type] > $bestq ) {
1593 $bestq = $combine[$type];
1602 * Returns an array where the values in the first array are replaced by the
1603 * values in the second array with the corresponding keys
1607 function wfArrayLookup( $a, $b ) {
1608 return array_flip( array_intersect( array_flip( $a ), array_keys( $b ) ) );
1612 * Convenience function; returns MediaWiki timestamp for the present time.
1615 function wfTimestampNow() {
1617 return wfTimestamp( TS_MW
, time() );
1621 * Reference-counted warning suppression
1623 function wfSuppressWarnings( $end = false ) {
1624 static $suppressCount = 0;
1625 static $originalLevel = false;
1628 if ( $suppressCount ) {
1630 if ( !$suppressCount ) {
1631 error_reporting( $originalLevel );
1635 if ( !$suppressCount ) {
1636 $originalLevel = error_reporting( E_ALL
& ~
( E_WARNING | E_NOTICE
) );
1643 * Restore error level to previous value
1645 function wfRestoreWarnings() {
1646 wfSuppressWarnings( true );
1649 # Autodetect, convert and provide timestamps of various types
1652 * Unix time - the number of seconds since 1970-01-01 00:00:00 UTC
1654 define('TS_UNIX', 0);
1657 * MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
1662 * MySQL DATETIME (YYYY-MM-DD HH:MM:SS)
1667 * RFC 2822 format, for E-mail and HTTP headers
1669 define('TS_RFC2822', 3);
1672 * ISO 8601 format with no timezone: 1986-02-09T20:00:00Z
1674 * This is used by Special:Export
1676 define('TS_ISO_8601', 4);
1679 * An Exif timestamp (YYYY:MM:DD HH:MM:SS)
1681 * @see http://exif.org/Exif2-2.PDF The Exif 2.2 spec, see page 28 for the
1682 * DateTime tag and page 36 for the DateTimeOriginal and
1683 * DateTimeDigitized tags.
1685 define('TS_EXIF', 5);
1688 * Oracle format time.
1690 define('TS_ORACLE', 6);
1693 * Postgres format time.
1695 define('TS_POSTGRES', 7);
1698 * @param mixed $outputtype A timestamp in one of the supported formats, the
1699 * function will autodetect which format is supplied
1700 * and act accordingly.
1701 * @return string Time in the format specified in $outputtype
1703 function wfTimestamp($outputtype=TS_UNIX
,$ts=0) {
1708 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)$/D',$ts,$da)) {
1710 } elseif (preg_match('/^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/D',$ts,$da)) {
1712 } elseif (preg_match('/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/D',$ts,$da)) {
1714 } elseif (preg_match('/^\d{1,13}$/D',$ts)) {
1717 } elseif (preg_match('/^\d{1,2}-...-\d\d(?:\d\d)? \d\d\.\d\d\.\d\d/', $ts)) {
1719 $uts = strtotime(preg_replace('/(\d\d)\.(\d\d)\.(\d\d)(\.(\d+))?/', "$1:$2:$3",
1720 str_replace("+00:00", "UTC", $ts)));
1721 } elseif (preg_match('/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.*\d*)?Z$/', $ts, $da)) {
1723 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.*\d*[\+\- ](\d\d)$/',$ts,$da)) {
1725 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.*\d* GMT$/',$ts,$da)) {
1728 # Bogus value; fall back to the epoch...
1729 wfDebug("wfTimestamp() fed bogus time value: $outputtype; $ts\n");
1733 if (count( $da ) ) {
1734 // Warning! gmmktime() acts oddly if the month or day is set to 0
1735 // We may want to handle that explicitly at some point
1736 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1737 (int)$da[2],(int)$da[3],(int)$da[1]);
1740 switch($outputtype) {
1744 return gmdate( 'YmdHis', $uts );
1746 return gmdate( 'Y-m-d H:i:s', $uts );
1748 return gmdate( 'Y-m-d\TH:i:s\Z', $uts );
1749 // This shouldn't ever be used, but is included for completeness
1751 return gmdate( 'Y:m:d H:i:s', $uts );
1753 return gmdate( 'D, d M Y H:i:s', $uts ) . ' GMT';
1755 return gmdate( 'd-M-y h.i.s A', $uts) . ' +00:00';
1757 return gmdate( 'Y-m-d H:i:s', $uts) . ' GMT';
1759 throw new MWException( 'wfTimestamp() called with illegal output type.');
1764 * Return a formatted timestamp, or null if input is null.
1765 * For dealing with nullable timestamp columns in the database.
1766 * @param int $outputtype
1770 function wfTimestampOrNull( $outputtype = TS_UNIX
, $ts = null ) {
1771 if( is_null( $ts ) ) {
1774 return wfTimestamp( $outputtype, $ts );
1779 * Check if the operating system is Windows
1781 * @return bool True if it's Windows, False otherwise.
1783 function wfIsWindows() {
1784 if (substr(php_uname(), 0, 7) == 'Windows') {
1792 * Swap two variables
1794 function swap( &$x, &$y ) {
1800 function wfGetCachedNotice( $name ) {
1801 global $wgOut, $wgRenderHashAppend, $parserMemc;
1802 $fname = 'wfGetCachedNotice';
1803 wfProfileIn( $fname );
1807 if( $name === 'default' ) {
1809 global $wgSiteNotice;
1810 $notice = $wgSiteNotice;
1811 if( empty( $notice ) ) {
1812 wfProfileOut( $fname );
1816 $notice = wfMsgForContentNoTrans( $name );
1817 if( wfEmptyMsg( $name, $notice ) ||
$notice == '-' ) {
1818 wfProfileOut( $fname );
1823 // Use the extra hash appender to let eg SSL variants separately cache.
1824 $key = wfMemcKey( $name . $wgRenderHashAppend );
1825 $cachedNotice = $parserMemc->get( $key );
1826 if( is_array( $cachedNotice ) ) {
1827 if( md5( $notice ) == $cachedNotice['hash'] ) {
1828 $notice = $cachedNotice['html'];
1837 if( is_object( $wgOut ) ) {
1838 $parsed = $wgOut->parse( $notice );
1839 $parserMemc->set( $key, array( 'html' => $parsed, 'hash' => md5( $notice ) ), 600 );
1842 wfDebug( 'wfGetCachedNotice called for ' . $name . ' with no $wgOut available' );
1847 wfProfileOut( $fname );
1851 function wfGetNamespaceNotice() {
1855 if ( !isset( $wgTitle ) ||
!is_object( $wgTitle ) )
1858 $fname = 'wfGetNamespaceNotice';
1859 wfProfileIn( $fname );
1861 $key = "namespacenotice-" . $wgTitle->getNsText();
1862 $namespaceNotice = wfGetCachedNotice( $key );
1863 if ( $namespaceNotice && substr ( $namespaceNotice , 0 ,7 ) != "<p><" ) {
1864 $namespaceNotice = '<div id="namespacebanner">' . $namespaceNotice . "</div>";
1866 $namespaceNotice = "";
1869 wfProfileOut( $fname );
1870 return $namespaceNotice;
1873 function wfGetSiteNotice() {
1874 global $wgUser, $wgSiteNotice;
1875 $fname = 'wfGetSiteNotice';
1876 wfProfileIn( $fname );
1879 if( wfRunHooks( 'SiteNoticeBefore', array( &$siteNotice ) ) ) {
1880 if( is_object( $wgUser ) && $wgUser->isLoggedIn() ) {
1881 $siteNotice = wfGetCachedNotice( 'sitenotice' );
1883 $anonNotice = wfGetCachedNotice( 'anonnotice' );
1884 if( !$anonNotice ) {
1885 $siteNotice = wfGetCachedNotice( 'sitenotice' );
1887 $siteNotice = $anonNotice;
1890 if( !$siteNotice ) {
1891 $siteNotice = wfGetCachedNotice( 'default' );
1895 wfRunHooks( 'SiteNoticeAfter', array( &$siteNotice ) );
1896 wfProfileOut( $fname );
1901 * BC wrapper for MimeMagic::singleton()
1904 function &wfGetMimeMagic() {
1905 return MimeMagic
::singleton();
1909 * Tries to get the system directory for temporary files.
1910 * The TMPDIR, TMP, and TEMP environment variables are checked in sequence,
1911 * and if none are set /tmp is returned as the generic Unix default.
1913 * NOTE: When possible, use the tempfile() function to create temporary
1914 * files to avoid race conditions on file creation, etc.
1918 function wfTempDir() {
1919 foreach( array( 'TMPDIR', 'TMP', 'TEMP' ) as $var ) {
1920 $tmp = getenv( $var );
1921 if( $tmp && file_exists( $tmp ) && is_dir( $tmp ) && is_writable( $tmp ) ) {
1925 # Hope this is Unix of some kind!
1930 * Make directory, and make all parent directories if they don't exist
1932 * @param string $dir Full path to directory to create
1933 * @param int $mode Chmod value to use, default is $wgDirectoryMode
1936 function wfMkdirParents( $dir, $mode = null ) {
1937 global $wgDirectoryMode;
1939 if( strval( $dir ) === '' ||
file_exists( $dir ) )
1942 if ( is_null( $mode ) )
1943 $mode = $wgDirectoryMode;
1945 return mkdir( $dir, $mode, true ); // PHP5 <3
1949 * Increment a statistics counter
1951 function wfIncrStats( $key ) {
1952 global $wgStatsMethod;
1954 if( $wgStatsMethod == 'udp' ) {
1955 global $wgUDPProfilerHost, $wgUDPProfilerPort, $wgDBname;
1958 $socket=socket_create(AF_INET
, SOCK_DGRAM
, SOL_UDP
);
1959 $statline="stats/{$wgDBname} - 1 1 1 1 1 -total\n";
1960 socket_sendto($socket,$statline,strlen($statline),0,$wgUDPProfilerHost,$wgUDPProfilerPort);
1962 $statline="stats/{$wgDBname} - 1 1 1 1 1 {$key}\n";
1963 @socket_sendto
($socket,$statline,strlen($statline),0,$wgUDPProfilerHost,$wgUDPProfilerPort);
1964 } elseif( $wgStatsMethod == 'cache' ) {
1966 $key = wfMemcKey( 'stats', $key );
1967 if ( is_null( $wgMemc->incr( $key ) ) ) {
1968 $wgMemc->add( $key, 1 );
1976 * @param mixed $nr The number to format
1977 * @param int $acc The number of digits after the decimal point, default 2
1978 * @param bool $round Whether or not to round the value, default true
1981 function wfPercent( $nr, $acc = 2, $round = true ) {
1982 $ret = sprintf( "%.${acc}f", $nr );
1983 return $round ?
round( $ret, $acc ) . '%' : "$ret%";
1987 * Encrypt a username/password.
1989 * @param string $userid ID of the user
1990 * @param string $password Password of the user
1991 * @return string Hashed password
1992 * @deprecated Use User::crypt() or User::oldCrypt() instead
1994 function wfEncryptPassword( $userid, $password ) {
1995 wfDeprecated(__FUNCTION__
);
1996 # Just wrap around User::oldCrypt()
1997 return User
::oldCrypt($password, $userid);
2001 * Appends to second array if $value differs from that in $default
2003 function wfAppendToArrayIfNotDefault( $key, $value, $default, &$changed ) {
2004 if ( is_null( $changed ) ) {
2005 throw new MWException('GlobalFunctions::wfAppendToArrayIfNotDefault got null');
2007 if ( $default[$key] !== $value ) {
2008 $changed[$key] = $value;
2013 * Since wfMsg() and co suck, they don't return false if the message key they
2014 * looked up didn't exist but a XHTML string, this function checks for the
2015 * nonexistance of messages by looking at wfMsg() output
2017 * @param $msg The message key looked up
2018 * @param $wfMsgOut The output of wfMsg*()
2021 function wfEmptyMsg( $msg, $wfMsgOut ) {
2022 return $wfMsgOut === htmlspecialchars( "<$msg>" );
2026 * Find out whether or not a mixed variable exists in a string
2028 * @param mixed needle
2029 * @param string haystack
2032 function in_string( $needle, $str ) {
2033 return strpos( $str, $needle ) !== false;
2036 function wfSpecialList( $page, $details ) {
2038 $details = $details ?
' ' . $wgContLang->getDirMark() . "($details)" : "";
2039 return $page . $details;
2043 * Returns a regular expression of url protocols
2047 function wfUrlProtocols() {
2048 global $wgUrlProtocols;
2050 // Support old-style $wgUrlProtocols strings, for backwards compatibility
2051 // with LocalSettings files from 1.5
2052 if ( is_array( $wgUrlProtocols ) ) {
2053 $protocols = array();
2054 foreach ($wgUrlProtocols as $protocol)
2055 $protocols[] = preg_quote( $protocol, '/' );
2057 return implode( '|', $protocols );
2059 return $wgUrlProtocols;
2064 * Safety wrapper around ini_get() for boolean settings.
2065 * The values returned from ini_get() are pre-normalized for settings
2066 * set via php.ini or php_flag/php_admin_flag... but *not*
2067 * for those set via php_value/php_admin_value.
2069 * It's fairly common for people to use php_value instead of php_flag,
2070 * which can leave you with an 'off' setting giving a false positive
2071 * for code that just takes the ini_get() return value as a boolean.
2073 * To make things extra interesting, setting via php_value accepts
2074 * "true" and "yes" as true, but php.ini and php_flag consider them false. :)
2075 * Unrecognized values go false... again opposite PHP's own coercion
2076 * from string to bool.
2078 * Luckily, 'properly' set settings will always come back as '0' or '1',
2079 * so we only have to worry about them and the 'improper' settings.
2081 * I frickin' hate PHP... :P
2083 * @param string $setting
2086 function wfIniGetBool( $setting ) {
2087 $val = ini_get( $setting );
2088 // 'on' and 'true' can't have whitespace around them, but '1' can.
2089 return strtolower( $val ) == 'on'
2090 ||
strtolower( $val ) == 'true'
2091 ||
strtolower( $val ) == 'yes'
2092 ||
preg_match( "/^\s*[+-]?0*[1-9]/", $val ); // approx C atoi() function
2096 * Execute a shell command, with time and memory limits mirrored from the PHP
2097 * configuration if supported.
2098 * @param $cmd Command line, properly escaped for shell.
2099 * @param &$retval optional, will receive the program's exit code.
2100 * (non-zero is usually failure)
2101 * @return collected stdout as a string (trailing newlines stripped)
2103 function wfShellExec( $cmd, &$retval=null ) {
2104 global $IP, $wgMaxShellMemory, $wgMaxShellFileSize, $wgMaxShellTime;
2106 if( wfIniGetBool( 'safe_mode' ) ) {
2107 wfDebug( "wfShellExec can't run in safe_mode, PHP's exec functions are too broken.\n" );
2109 return "Unable to run external programs in safe mode.";
2111 wfInitShellLocale();
2113 if ( php_uname( 's' ) == 'Linux' ) {
2114 $time = intval( $wgMaxShellTime );
2115 $mem = intval( $wgMaxShellMemory );
2116 $filesize = intval( $wgMaxShellFileSize );
2118 if ( $time > 0 && $mem > 0 ) {
2119 $script = "$IP/bin/ulimit4.sh";
2120 if ( is_executable( $script ) ) {
2121 $cmd = escapeshellarg( $script ) . " $time $mem $filesize " . escapeshellarg( $cmd );
2124 } elseif ( php_uname( 's' ) == 'Windows NT' ) {
2125 # This is a hack to work around PHP's flawed invocation of cmd.exe
2126 # http://news.php.net/php.internals/21796
2127 $cmd = '"' . $cmd . '"';
2129 wfDebug( "wfShellExec: $cmd\n" );
2131 $retval = 1; // error by default?
2133 passthru( $cmd, $retval );
2134 $output = ob_get_contents();
2137 if ( $retval == 127 ) {
2138 wfDebugLog( 'exec', "Possibly missing executable file: $cmd\n" );
2144 * Workaround for http://bugs.php.net/bug.php?id=45132
2145 * escapeshellarg() destroys non-ASCII characters if LANG is not a UTF-8 locale
2147 function wfInitShellLocale() {
2148 static $done = false;
2149 if ( $done ) return;
2151 global $wgShellLocale;
2152 if ( !wfIniGetBool( 'safe_mode' ) ) {
2153 putenv( "LC_CTYPE=$wgShellLocale" );
2154 setlocale( LC_CTYPE
, $wgShellLocale );
2159 * This function works like "use VERSION" in Perl, the program will die with a
2160 * backtrace if the current version of PHP is less than the version provided
2162 * This is useful for extensions which due to their nature are not kept in sync
2163 * with releases, and might depend on other versions of PHP than the main code
2165 * Note: PHP might die due to parsing errors in some cases before it ever
2166 * manages to call this function, such is life
2168 * @see perldoc -f use
2170 * @param mixed $version The version to check, can be a string, an integer, or
2173 function wfUsePHP( $req_ver ) {
2174 $php_ver = PHP_VERSION
;
2176 if ( version_compare( $php_ver, (string)$req_ver, '<' ) )
2177 throw new MWException( "PHP $req_ver required--this is only $php_ver" );
2181 * This function works like "use VERSION" in Perl except it checks the version
2182 * of MediaWiki, the program will die with a backtrace if the current version
2183 * of MediaWiki is less than the version provided.
2185 * This is useful for extensions which due to their nature are not kept in sync
2188 * @see perldoc -f use
2190 * @param mixed $version The version to check, can be a string, an integer, or
2193 function wfUseMW( $req_ver ) {
2196 if ( version_compare( $wgVersion, (string)$req_ver, '<' ) )
2197 throw new MWException( "MediaWiki $req_ver required--this is only $wgVersion" );
2201 * @deprecated use StringUtils::escapeRegexReplacement
2203 function wfRegexReplacement( $string ) {
2204 return StringUtils
::escapeRegexReplacement( $string );
2208 * Return the final portion of a pathname.
2209 * Reimplemented because PHP5's basename() is buggy with multibyte text.
2210 * http://bugs.php.net/bug.php?id=33898
2212 * PHP's basename() only considers '\' a pathchar on Windows and Netware.
2213 * We'll consider it so always, as we don't want \s in our Unix paths either.
2215 * @param string $path
2216 * @param string $suffix to remove if present
2219 function wfBaseName( $path, $suffix='' ) {
2220 $encSuffix = ($suffix == '')
2222 : ( '(?:' . preg_quote( $suffix, '#' ) . ')?' );
2224 if( preg_match( "#([^/\\\\]*?){$encSuffix}[/\\\\]*$#", $path, $matches ) ) {
2232 * Generate a relative path name to the given file.
2233 * May explode on non-matching case-insensitive paths,
2234 * funky symlinks, etc.
2236 * @param string $path Absolute destination path including target filename
2237 * @param string $from Absolute source path, directory only
2240 function wfRelativePath( $path, $from ) {
2241 // Normalize mixed input on Windows...
2242 $path = str_replace( '/', DIRECTORY_SEPARATOR
, $path );
2243 $from = str_replace( '/', DIRECTORY_SEPARATOR
, $from );
2245 // Trim trailing slashes -- fix for drive root
2246 $path = rtrim( $path, DIRECTORY_SEPARATOR
);
2247 $from = rtrim( $from, DIRECTORY_SEPARATOR
);
2249 $pieces = explode( DIRECTORY_SEPARATOR
, dirname( $path ) );
2250 $against = explode( DIRECTORY_SEPARATOR
, $from );
2252 if( $pieces[0] !== $against[0] ) {
2253 // Non-matching Windows drive letters?
2254 // Return a full path.
2258 // Trim off common prefix
2259 while( count( $pieces ) && count( $against )
2260 && $pieces[0] == $against[0] ) {
2261 array_shift( $pieces );
2262 array_shift( $against );
2265 // relative dots to bump us to the parent
2266 while( count( $against ) ) {
2267 array_unshift( $pieces, '..' );
2268 array_shift( $against );
2271 array_push( $pieces, wfBaseName( $path ) );
2273 return implode( DIRECTORY_SEPARATOR
, $pieces );
2277 * Backwards array plus for people who haven't bothered to read the PHP manual
2278 * XXX: will not darn your socks for you.
2280 * @param array $array1, [$array2, [...]]
2283 function wfArrayMerge( $array1/* ... */ ) {
2284 $args = func_get_args();
2285 $args = array_reverse( $args, true );
2287 foreach ( $args as $arg ) {
2294 * Merge arrays in the style of getUserPermissionsErrors, with duplicate removal
2296 * wfMergeErrorArrays(
2297 * array( array( 'x' ) ),
2298 * array( array( 'x', '2' ) ),
2299 * array( array( 'x' ) ),
2300 * array( array( 'y') )
2304 * array( 'x', '2' ),
2309 function wfMergeErrorArrays(/*...*/) {
2310 $args = func_get_args();
2312 foreach ( $args as $errors ) {
2313 foreach ( $errors as $params ) {
2314 $spec = implode( "\t", $params );
2315 $out[$spec] = $params;
2318 return array_values( $out );
2322 * Make a URL index, appropriate for the el_index field of externallinks.
2324 function wfMakeUrlIndex( $url ) {
2325 global $wgUrlProtocols; // Allow all protocols defined in DefaultSettings/LocalSettings.php
2326 wfSuppressWarnings();
2327 $bits = parse_url( $url );
2328 wfRestoreWarnings();
2332 // most of the protocols are followed by ://, but mailto: and sometimes news: not, check for it
2334 if ( in_array( $bits['scheme'] . '://' , $wgUrlProtocols ) ) {
2336 } elseif ( in_array( $bits['scheme'] .':' , $wgUrlProtocols ) ) {
2338 // parse_url detects for news: and mailto: the host part of an url as path
2339 // We have to correct this wrong detection
2340 if ( isset ( $bits['path'] ) ) {
2341 $bits['host'] = $bits['path'];
2348 // Reverse the labels in the hostname, convert to lower case
2349 // For emails reverse domainpart only
2350 if ( $bits['scheme'] == 'mailto' ) {
2351 $mailparts = explode( '@', $bits['host'], 2 );
2352 if ( count($mailparts) === 2 ) {
2353 $domainpart = strtolower( implode( '.', array_reverse( explode( '.', $mailparts[1] ) ) ) );
2355 // No domain specified, don't mangle it
2358 $reversedHost = $domainpart . '@' . $mailparts[0];
2360 $reversedHost = strtolower( implode( '.', array_reverse( explode( '.', $bits['host'] ) ) ) );
2362 // Add an extra dot to the end
2363 // Why? Is it in wrong place in mailto links?
2364 if ( substr( $reversedHost, -1, 1 ) !== '.' ) {
2365 $reversedHost .= '.';
2367 // Reconstruct the pseudo-URL
2368 $prot = $bits['scheme'];
2369 $index = "$prot$delimiter$reversedHost";
2370 // Leave out user and password. Add the port, path, query and fragment
2371 if ( isset( $bits['port'] ) ) $index .= ':' . $bits['port'];
2372 if ( isset( $bits['path'] ) ) {
2373 $index .= $bits['path'];
2377 if ( isset( $bits['query'] ) ) $index .= '?' . $bits['query'];
2378 if ( isset( $bits['fragment'] ) ) $index .= '#' . $bits['fragment'];
2383 * Do any deferred updates and clear the list
2384 * TODO: This could be in Wiki.php if that class made any sense at all
2386 function wfDoUpdates()
2388 global $wgPostCommitUpdateList, $wgDeferredUpdateList;
2389 foreach ( $wgDeferredUpdateList as $update ) {
2390 $update->doUpdate();
2392 foreach ( $wgPostCommitUpdateList as $update ) {
2393 $update->doUpdate();
2395 $wgDeferredUpdateList = array();
2396 $wgPostCommitUpdateList = array();
2400 * @deprecated use StringUtils::explodeMarkup
2402 function wfExplodeMarkup( $separator, $text ) {
2403 return StringUtils
::explodeMarkup( $separator, $text );
2407 * Convert an arbitrarily-long digit string from one numeric base
2408 * to another, optionally zero-padding to a minimum column width.
2410 * Supports base 2 through 36; digit values 10-36 are represented
2411 * as lowercase letters a-z. Input is case-insensitive.
2413 * @param $input string of digits
2414 * @param $sourceBase int 2-36
2415 * @param $destBase int 2-36
2416 * @param $pad int 1 or greater
2417 * @param $lowercase bool
2418 * @return string or false on invalid input
2420 function wfBaseConvert( $input, $sourceBase, $destBase, $pad=1, $lowercase=true ) {
2421 $input = strval( $input );
2422 if( $sourceBase < 2 ||
2427 $sourceBase != intval( $sourceBase ) ||
2428 $destBase != intval( $destBase ) ||
2429 $pad != intval( $pad ) ||
2430 !is_string( $input ) ||
2434 $digitChars = ( $lowercase ) ?
'0123456789abcdefghijklmnopqrstuvwxyz' : '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
2435 $inDigits = array();
2438 // Decode and validate input string
2439 $input = strtolower( $input );
2440 for( $i = 0; $i < strlen( $input ); $i++
) {
2441 $n = strpos( $digitChars, $input{$i} );
2442 if( $n === false ||
$n > $sourceBase ) {
2448 // Iterate over the input, modulo-ing out an output digit
2449 // at a time until input is gone.
2450 while( count( $inDigits ) ) {
2452 $workDigits = array();
2455 foreach( $inDigits as $digit ) {
2456 $work *= $sourceBase;
2459 if( $work < $destBase ) {
2460 // Gonna need to pull another digit.
2461 if( count( $workDigits ) ) {
2462 // Avoid zero-padding; this lets us find
2463 // the end of the input very easily when
2464 // length drops to zero.
2468 // Finally! Actual division!
2469 $workDigits[] = intval( $work / $destBase );
2471 // Isn't it annoying that most programming languages
2472 // don't have a single divide-and-remainder operator,
2473 // even though the CPU implements it that way?
2474 $work = $work %
$destBase;
2478 // All that division leaves us with a remainder,
2479 // which is conveniently our next output digit.
2480 $outChars .= $digitChars[$work];
2483 $inDigits = $workDigits;
2486 while( strlen( $outChars ) < $pad ) {
2490 return strrev( $outChars );
2494 * Create an object with a given name and an array of construct parameters
2495 * @param string $name
2496 * @param array $p parameters
2498 function wfCreateObject( $name, $p ){
2499 $p = array_values( $p );
2500 switch ( count( $p ) ) {
2504 return new $name( $p[0] );
2506 return new $name( $p[0], $p[1] );
2508 return new $name( $p[0], $p[1], $p[2] );
2510 return new $name( $p[0], $p[1], $p[2], $p[3] );
2512 return new $name( $p[0], $p[1], $p[2], $p[3], $p[4] );
2514 return new $name( $p[0], $p[1], $p[2], $p[3], $p[4], $p[5] );
2516 throw new MWException( "Too many arguments to construtor in wfCreateObject" );
2521 * Alias for modularized function
2522 * @deprecated Use Http::get() instead
2524 function wfGetHTTP( $url, $timeout = 'default' ) {
2525 wfDeprecated(__FUNCTION__
);
2526 return Http
::get( $url, $timeout );
2530 * Alias for modularized function
2531 * @deprecated Use Http::isLocalURL() instead
2533 function wfIsLocalURL( $url ) {
2534 wfDeprecated(__FUNCTION__
);
2535 return Http
::isLocalURL( $url );
2538 function wfHttpOnlySafe() {
2539 global $wgHttpOnlyBlacklist;
2540 if( !version_compare("5.2", PHP_VERSION
, "<") )
2543 if( isset( $_SERVER['HTTP_USER_AGENT'] ) ) {
2544 foreach( $wgHttpOnlyBlacklist as $regex ) {
2545 if( preg_match( $regex, $_SERVER['HTTP_USER_AGENT'] ) ) {
2555 * Initialise php session
2557 function wfSetupSession() {
2558 global $wgSessionsInMemcached, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookieHttpOnly;
2559 if( $wgSessionsInMemcached ) {
2560 require_once( 'MemcachedSessions.php' );
2561 } elseif( 'files' != ini_get( 'session.save_handler' ) ) {
2562 # If it's left on 'user' or another setting from another
2563 # application, it will end up failing. Try to recover.
2564 ini_set ( 'session.save_handler', 'files' );
2566 $httpOnlySafe = wfHttpOnlySafe();
2567 wfDebugLog( 'cookie',
2568 'session_set_cookie_params: "' . implode( '", "',
2574 $httpOnlySafe && $wgCookieHttpOnly ) ) . '"' );
2575 if( $httpOnlySafe && $wgCookieHttpOnly ) {
2576 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookieHttpOnly );
2578 // PHP 5.1 throws warnings if you pass the HttpOnly parameter for 5.2.
2579 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
2581 session_cache_limiter( 'private, must-revalidate' );
2582 wfSuppressWarnings();
2584 wfRestoreWarnings();
2588 * Get an object from the precompiled serialized directory
2590 * @return mixed The variable on success, false on failure
2592 function wfGetPrecompiledData( $name ) {
2595 $file = "$IP/serialized/$name";
2596 if ( file_exists( $file ) ) {
2597 $blob = file_get_contents( $file );
2599 return unserialize( $blob );
2605 function wfGetCaller( $level = 2 ) {
2606 $backtrace = wfDebugBacktrace();
2607 if ( isset( $backtrace[$level] ) ) {
2608 return wfFormatStackFrame($backtrace[$level]);
2610 $caller = 'unknown';
2615 /** Return a string consisting all callers in stack, somewhat useful sometimes for profiling specific points */
2616 function wfGetAllCallers() {
2617 return implode('/', array_map('wfFormatStackFrame',array_reverse(wfDebugBacktrace())));
2620 /** Return a string representation of frame */
2621 function wfFormatStackFrame($frame) {
2622 return isset( $frame["class"] )?
2623 $frame["class"]."::".$frame["function"]:
2630 function wfMemcKey( /*... */ ) {
2631 $args = func_get_args();
2632 $key = wfWikiID() . ':' . implode( ':', $args );
2637 * Get a cache key for a foreign DB
2639 function wfForeignMemcKey( $db, $prefix /*, ... */ ) {
2640 $args = array_slice( func_get_args(), 2 );
2642 $key = "$db-$prefix:" . implode( ':', $args );
2644 $key = $db . ':' . implode( ':', $args );
2650 * Get an ASCII string identifying this wiki
2651 * This is used as a prefix in memcached keys
2653 function wfWikiID( $db = null ) {
2654 if( $db instanceof Database
) {
2655 return $db->getWikiID();
2657 global $wgDBprefix, $wgDBname;
2658 if ( $wgDBprefix ) {
2659 return "$wgDBname-$wgDBprefix";
2667 * Split a wiki ID into DB name and table prefix
2669 function wfSplitWikiID( $wiki ) {
2670 $bits = explode( '-', $wiki, 2 );
2671 if ( count( $bits ) < 2 ) {
2678 * Get a Database object.
2679 * @param integer $db Index of the connection to get. May be DB_MASTER for the
2680 * master (for write queries), DB_SLAVE for potentially lagged
2681 * read queries, or an integer >= 0 for a particular server.
2683 * @param mixed $groups Query groups. An array of group names that this query
2684 * belongs to. May contain a single string if the query is only
2687 * @param string $wiki The wiki ID, or false for the current wiki
2689 * Note: multiple calls to wfGetDB(DB_SLAVE) during the course of one request
2690 * will always return the same object, unless the underlying connection or load
2691 * balancer is manually destroyed.
2693 function &wfGetDB( $db, $groups = array(), $wiki = false ) {
2694 return wfGetLB( $wiki )->getConnection( $db, $groups, $wiki );
2698 * Get a load balancer object.
2700 * @param array $groups List of query groups
2701 * @param string $wiki Wiki ID, or false for the current wiki
2702 * @return LoadBalancer
2704 function wfGetLB( $wiki = false ) {
2705 return wfGetLBFactory()->getMainLB( $wiki );
2709 * Get the load balancer factory object
2711 function &wfGetLBFactory() {
2712 return LBFactory
::singleton();
2717 * Shortcut for RepoGroup::singleton()->findFile()
2718 * @param mixed $title Title object or string. May be interwiki.
2719 * @param mixed $time Requested time for an archived image, or false for the
2720 * current version. An image object will be returned which
2721 * was created at the specified time.
2722 * @param mixed $flags FileRepo::FIND_ flags
2723 * @return File, or false if the file does not exist
2725 function wfFindFile( $title, $time = false, $flags = 0 ) {
2726 return RepoGroup
::singleton()->findFile( $title, $time, $flags );
2730 * Get an object referring to a locally registered file.
2731 * Returns a valid placeholder object if the file does not exist.
2733 function wfLocalFile( $title ) {
2734 return RepoGroup
::singleton()->getLocalRepo()->newFile( $title );
2738 * Should low-performance queries be disabled?
2742 function wfQueriesMustScale() {
2743 global $wgMiserMode;
2745 ||
( SiteStats
::pages() > 100000
2746 && SiteStats
::edits() > 1000000
2747 && SiteStats
::users() > 10000 );
2751 * Get the path to a specified script file, respecting file
2752 * extensions; this is a wrapper around $wgScriptExtension etc.
2754 * @param string $script Script filename, sans extension
2757 function wfScript( $script = 'index' ) {
2758 global $wgScriptPath, $wgScriptExtension;
2759 return "{$wgScriptPath}/{$script}{$wgScriptExtension}";
2763 * Convenience function converts boolean values into "true"
2764 * or "false" (string) values
2766 * @param bool $value
2769 function wfBoolToStr( $value ) {
2770 return $value ?
'true' : 'false';
2774 * Load an extension messages file
2776 * @param string $extensionName Name of extension to load messages from\for.
2777 * @param string $langcode Language to load messages for, or false for default
2778 * behvaiour (en, content language and user language).
2779 * @since r24808 (v1.11) Using this method of loading extension messages will not work
2780 * on MediaWiki prior to that
2782 function wfLoadExtensionMessages( $extensionName, $langcode = false ) {
2783 global $wgExtensionMessagesFiles, $wgMessageCache, $wgLang, $wgContLang;
2785 #For recording whether extension message files have been loaded in a given language.
2786 static $loaded = array();
2788 if( !array_key_exists( $extensionName, $loaded ) ) {
2789 $loaded[$extensionName] = array();
2792 if ( !isset($wgExtensionMessagesFiles[$extensionName]) ) {
2793 throw new MWException( "Messages file for extensions $extensionName is not defined" );
2796 if( !$langcode && !array_key_exists( '*', $loaded[$extensionName] ) ) {
2797 # Just do en, content language and user language.
2798 $wgMessageCache->loadMessagesFile( $wgExtensionMessagesFiles[$extensionName], false );
2799 # Mark that they have been loaded.
2800 $loaded[$extensionName]['en'] = true;
2801 $loaded[$extensionName][$wgLang->getCode()] = true;
2802 $loaded[$extensionName][$wgContLang->getCode()] = true;
2803 # Mark that this part has been done to avoid weird if statements.
2804 $loaded[$extensionName]['*'] = true;
2805 } elseif( is_string( $langcode ) && !array_key_exists( $langcode, $loaded[$extensionName] ) ) {
2806 # Load messages for specified language.
2807 $wgMessageCache->loadMessagesFile( $wgExtensionMessagesFiles[$extensionName], $langcode );
2808 # Mark that they have been loaded.
2809 $loaded[$extensionName][$langcode] = true;
2814 * Get a platform-independent path to the null file, e.g.
2819 function wfGetNull() {
2820 return wfIsWindows()
2826 * Displays a maxlag error
2828 * @param string $host Server that lags the most
2829 * @param int $lag Maxlag (actual)
2830 * @param int $maxLag Maxlag (requested)
2832 function wfMaxlagError( $host, $lag, $maxLag ) {
2833 global $wgShowHostnames;
2834 header( 'HTTP/1.1 503 Service Unavailable' );
2835 header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
2836 header( 'X-Database-Lag: ' . intval( $lag ) );
2837 header( 'Content-Type: text/plain' );
2838 if( $wgShowHostnames ) {
2839 echo "Waiting for $host: $lag seconds lagged\n";
2841 echo "Waiting for a database server: $lag seconds lagged\n";
2846 * Throws an E_USER_NOTICE saying that $function is deprecated
2847 * @param string $function
2850 function wfDeprecated( $function ) {
2851 global $wgDebugLogFile;
2852 if ( !$wgDebugLogFile ) {
2855 $callers = wfDebugBacktrace();
2856 if( isset( $callers[2] ) ){
2857 $callerfunc = $callers[2];
2858 $callerfile = $callers[1];
2859 if( isset( $callerfile['file'] ) && isset( $callerfile['line'] ) ){
2860 $file = $callerfile['file'] . ' at line ' . $callerfile['line'];
2862 $file = '(internal function)';
2865 if( isset( $callerfunc['class'] ) )
2866 $func .= $callerfunc['class'] . '::';
2867 $func .= @$callerfunc['function'];
2868 $msg = "Use of $function is deprecated. Called from $func in $file";
2870 $msg = "Use of $function is deprecated.";
2872 wfDebug( "$msg\n" );
2876 * Sleep until the worst slave's replication lag is less than or equal to
2877 * $maxLag, in seconds. Use this when updating very large numbers of rows, as
2878 * in maintenance scripts, to avoid causing too much lag. Of course, this is
2879 * a no-op if there are no slaves.
2881 * Every time the function has to wait for a slave, it will print a message to
2882 * that effect (and then sleep for a little while), so it's probably not best
2883 * to use this outside maintenance scripts in its present form.
2885 * @param int $maxLag
2888 function wfWaitForSlaves( $maxLag ) {
2891 list( $host, $lag ) = $lb->getMaxLag();
2892 while( $lag > $maxLag ) {
2893 $name = @gethostbyaddr
( $host );
2894 if( $name !== false ) {
2897 print "Waiting for $host (lagged $lag seconds)...\n";
2899 list( $host, $lag ) = $lb->getMaxLag();
2904 /** Generate a random 32-character hexadecimal token.
2905 * @param mixed $salt Some sort of salt, if necessary, to add to random characters before hashing.
2907 function wfGenerateToken( $salt = '' ) {
2908 $salt = serialize($salt);
2910 return md5( mt_rand( 0, 0x7fffffff ) . $salt );
2914 * Replace all invalid characters with -
2915 * @param mixed $title Filename to process
2917 function wfStripIllegalFilenameChars( $name ) {
2918 $name = wfBaseName( $name );
2919 $name = preg_replace ( "/[^".Title
::legalChars()."]|:/", '-', $name );