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 global $wgDebugLogPrefix;
199 static $recursion = 0;
201 static $cache = array(); // Cache of unoutputted messages
203 # Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
204 if ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' && !$wgDebugRawPage ) {
208 if ( $wgDebugComments && !$logonly ) {
211 if ( !isset( $wgOut ) ) {
214 if ( !StubObject
::isRealObject( $wgOut ) ) {
223 // add the message and possible cached ones to the output
224 array_map( array( $wgOut, 'debug' ), $cache );
227 if ( '' != $wgDebugLogFile && !$wgProfileOnly ) {
228 # Strip unprintables; they can switch terminal modes when binary data
229 # gets dumped, which is pretty annoying.
230 $text = preg_replace( '![\x00-\x08\x0b\x0c\x0e-\x1f]!', ' ', $text );
231 $text = $wgDebugLogPrefix . $text;
232 wfErrorLog( $text, $wgDebugLogFile );
237 * Send a line giving PHP memory usage.
238 * @param $exact Bool : print exact values instead of kilobytes (default: false)
240 function wfDebugMem( $exact = false ) {
241 $mem = memory_get_usage();
243 $mem = floor( $mem / 1024 ) . ' kilobytes';
247 wfDebug( "Memory usage: $mem\n" );
251 * Send a line to a supplementary debug log file, if configured, or main debug log if not.
252 * $wgDebugLogGroups[$logGroup] should be set to a filename to send to a separate log.
254 * @param $logGroup String
255 * @param $text String
256 * @param $public Bool: whether to log the event in the public log if no private
257 * log file is specified, (default true)
259 function wfDebugLog( $logGroup, $text, $public = true ) {
260 global $wgDebugLogGroups, $wgShowHostnames;
261 if( $text{strlen( $text ) - 1} != "\n" ) $text .= "\n";
262 if( isset( $wgDebugLogGroups[$logGroup] ) ) {
263 $time = wfTimestamp( TS_DB
);
265 if ( $wgShowHostnames ) {
266 $host = wfHostname();
270 wfErrorLog( "$time $host $wiki: $text", $wgDebugLogGroups[$logGroup] );
271 } else if ( $public === true ) {
272 wfDebug( $text, true );
277 * Log for database errors
278 * @param $text String: database error message.
280 function wfLogDBError( $text ) {
281 global $wgDBerrorLog, $wgDBname;
282 if ( $wgDBerrorLog ) {
283 $host = trim(`hostname`
);
284 $text = date('D M j G:i:s T Y') . "\t$host\t$wgDBname\t$text";
285 wfErrorLog( $text, $wgDBerrorLog );
290 * Log to a file without getting "file size exceeded" signals.
292 * Can also log to TCP or UDP with the syntax udp://host:port/prefix. This will
293 * send lines to the specified port, prefixed by the specified prefix and a space.
295 function wfErrorLog( $text, $file ) {
296 if ( substr( $file, 0, 4 ) == 'udp:' ) {
297 if ( preg_match( '!^(tcp|udp):(?://)?\[([0-9a-fA-F:]+)\]:(\d+)(?:/(.*))?$!', $file, $m ) ) {
298 // IPv6 bracketed host
302 $prefix = isset( $m[4] ) ?
$m[4] : false;
303 } elseif ( preg_match( '!^(tcp|udp):(?://)?([a-zA-Z0-9.-]+):(\d+)(?:/(.*))?$!', $file, $m ) ) {
307 $prefix = isset( $m[4] ) ?
$m[4] : false;
309 throw new MWException( __METHOD__
.": Invalid UDP specification" );
311 // Clean it up for the multiplexer
312 if ( strval( $prefix ) !== '' ) {
313 $text = preg_replace( '/^/m', $prefix . ' ', $text );
314 if ( substr( $text, -1 ) != "\n" ) {
319 $sock = fsockopen( "$protocol://$host", $port );
323 fwrite( $sock, $text );
326 wfSuppressWarnings();
327 $exists = file_exists( $file );
328 $size = $exists ?
filesize( $file ) : false;
329 if ( !$exists ||
( $size !== false && $size +
strlen( $text ) < 0x7fffffff ) ) {
330 error_log( $text, 3, $file );
339 function wfLogProfilingData() {
340 global $wgRequestTime, $wgDebugLogFile, $wgDebugRawPage, $wgRequest;
341 global $wgProfiler, $wgUser;
342 if ( !isset( $wgProfiler ) )
346 $elapsed = $now - $wgRequestTime;
347 $prof = wfGetProfilingOutput( $wgRequestTime, $elapsed );
349 if( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) )
350 $forward = ' forwarded for ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
351 if( !empty( $_SERVER['HTTP_CLIENT_IP'] ) )
352 $forward .= ' client IP ' . $_SERVER['HTTP_CLIENT_IP'];
353 if( !empty( $_SERVER['HTTP_FROM'] ) )
354 $forward .= ' from ' . $_SERVER['HTTP_FROM'];
356 $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
357 // Don't unstub $wgUser at this late stage just for statistics purposes
358 if( StubObject
::isRealObject($wgUser) && $wgUser->isAnon() )
360 $log = sprintf( "%s\t%04.3f\t%s\n",
361 gmdate( 'YmdHis' ), $elapsed,
362 urldecode( $wgRequest->getRequestURL() . $forward ) );
363 if ( '' != $wgDebugLogFile && ( $wgRequest->getVal('action') != 'raw' ||
$wgDebugRawPage ) ) {
364 wfErrorLog( $log . $prof, $wgDebugLogFile );
369 * Check if the wiki read-only lock file is present. This can be used to lock
370 * off editing functions, but doesn't guarantee that the database will not be
374 function wfReadOnly() {
375 global $wgReadOnlyFile, $wgReadOnly;
377 if ( !is_null( $wgReadOnly ) ) {
378 return (bool)$wgReadOnly;
380 if ( '' == $wgReadOnlyFile ) {
383 // Set $wgReadOnly for faster access next time
384 if ( is_file( $wgReadOnlyFile ) ) {
385 $wgReadOnly = file_get_contents( $wgReadOnlyFile );
389 return (bool)$wgReadOnly;
392 function wfReadOnlyReason() {
399 * Return a Language object from $langcode
400 * @param $langcode Mixed: either:
401 * - a Language object
402 * - code of the language to get the message for, if it is
403 * a valid code create a language for that language, if
404 * it is a string but not a valid code then make a basic
406 * - a boolean: if it's false then use the current users
407 * language (as a fallback for the old parameter
408 * functionality), or if it is true then use the wikis
409 * @return Language object
411 function wfGetLangObj( $langcode = false ){
412 # Identify which language to get or create a language object for.
413 if( $langcode instanceof Language
)
414 # Great, we already have the object!
418 if( $langcode === $wgContLang->getCode() ||
$langcode === true )
419 # $langcode is the language code of the wikis content language object.
420 # or it is a boolean and value is true
424 if( $langcode === $wgLang->getCode() ||
$langcode === false )
425 # $langcode is the language code of user language object.
426 # or it was a boolean and value is false
429 $validCodes = array_keys( Language
::getLanguageNames() );
430 if( in_array( $langcode, $validCodes ) )
431 # $langcode corresponds to a valid language.
432 return Language
::factory( $langcode );
434 # $langcode is a string, but not a valid language code; use content language.
435 wfDebug( 'Invalid language code passed to wfGetLangObj, falling back to content language.' );
440 * Get a message from anywhere, for the current user language.
442 * Use wfMsgForContent() instead if the message should NOT
443 * change depending on the user preferences.
445 * @param $key String: lookup key for the message, usually
446 * defined in languages/Language.php
448 * This function also takes extra optional parameters (not
449 * shown in the function definition), which can by used to
450 * insert variable text into the predefined message.
452 function wfMsg( $key ) {
453 $args = func_get_args();
454 array_shift( $args );
455 return wfMsgReal( $key, $args, true );
459 * Same as above except doesn't transform the message
461 function wfMsgNoTrans( $key ) {
462 $args = func_get_args();
463 array_shift( $args );
464 return wfMsgReal( $key, $args, true, false, false );
468 * Get a message from anywhere, for the current global language
469 * set with $wgLanguageCode.
471 * Use this if the message should NOT change dependent on the
472 * language set in the user's preferences. This is the case for
473 * most text written into logs, as well as link targets (such as
474 * the name of the copyright policy page). Link titles, on the
475 * other hand, should be shown in the UI language.
477 * Note that MediaWiki allows users to change the user interface
478 * language in their preferences, but a single installation
479 * typically only contains content in one language.
481 * Be wary of this distinction: If you use wfMsg() where you should
482 * use wfMsgForContent(), a user of the software may have to
483 * customize over 70 messages in order to, e.g., fix a link in every
486 * @param $key String: lookup key for the message, usually
487 * defined in languages/Language.php
489 function wfMsgForContent( $key ) {
490 global $wgForceUIMsgAsContentMsg;
491 $args = func_get_args();
492 array_shift( $args );
494 if( is_array( $wgForceUIMsgAsContentMsg ) &&
495 in_array( $key, $wgForceUIMsgAsContentMsg ) )
497 return wfMsgReal( $key, $args, true, $forcontent );
501 * Same as above except doesn't transform the message
503 function wfMsgForContentNoTrans( $key ) {
504 global $wgForceUIMsgAsContentMsg;
505 $args = func_get_args();
506 array_shift( $args );
508 if( is_array( $wgForceUIMsgAsContentMsg ) &&
509 in_array( $key, $wgForceUIMsgAsContentMsg ) )
511 return wfMsgReal( $key, $args, true, $forcontent, false );
515 * Get a message from the language file, for the UI elements
517 function wfMsgNoDB( $key ) {
518 $args = func_get_args();
519 array_shift( $args );
520 return wfMsgReal( $key, $args, false );
524 * Get a message from the language file, for the content
526 function wfMsgNoDBForContent( $key ) {
527 global $wgForceUIMsgAsContentMsg;
528 $args = func_get_args();
529 array_shift( $args );
531 if( is_array( $wgForceUIMsgAsContentMsg ) &&
532 in_array( $key, $wgForceUIMsgAsContentMsg ) )
534 return wfMsgReal( $key, $args, false, $forcontent );
539 * Really get a message
540 * @param $key String: key to get.
542 * @param $useDB Boolean
543 * @param $transform Boolean: Whether or not to transform the message.
544 * @param $forContent Boolean
545 * @return String: the requested message.
547 function wfMsgReal( $key, $args, $useDB = true, $forContent=false, $transform = true ) {
548 wfProfileIn( __METHOD__
);
549 $message = wfMsgGetKey( $key, $useDB, $forContent, $transform );
550 $message = wfMsgReplaceArgs( $message, $args );
551 wfProfileOut( __METHOD__
);
556 * This function provides the message source for messages to be edited which are *not* stored in the database.
557 * @param $key String:
559 function wfMsgWeirdKey ( $key ) {
560 $source = wfMsgGetKey( $key, false, true, false );
561 if ( wfEmptyMsg( $key, $source ) )
568 * Fetch a message string value, but don't replace any keys yet.
571 * @param string $langcode Code of the language to get the message for, or
572 * behaves as a content language switch if it is a
577 function wfMsgGetKey( $key, $useDB, $langCode = false, $transform = true ) {
578 global $wgContLang, $wgMessageCache;
580 wfRunHooks('NormalizeMessageKey', array(&$key, &$useDB, &$langCode, &$transform));
582 # If $wgMessageCache isn't initialised yet, try to return something sensible.
583 if( is_object( $wgMessageCache ) ) {
584 $message = $wgMessageCache->get( $key, $useDB, $langCode );
586 $message = $wgMessageCache->transform( $message );
589 $lang = wfGetLangObj( $langCode );
591 # MessageCache::get() does this already, Language::getMessage() doesn't
592 # ISSUE: Should we try to handle "message/lang" here too?
593 $key = str_replace( ' ' , '_' , $wgContLang->lcfirst( $key ) );
595 if( is_object( $lang ) ) {
596 $message = $lang->getMessage( $key );
606 * Replace message parameter keys on the given formatted output.
608 * @param string $message
613 function wfMsgReplaceArgs( $message, $args ) {
614 # Fix windows line-endings
615 # Some messages are split with explode("\n", $msg)
616 $message = str_replace( "\r", '', $message );
619 if ( count( $args ) ) {
620 if ( is_array( $args[0] ) ) {
621 $args = array_values( $args[0] );
623 $replacementKeys = array();
624 foreach( $args as $n => $param ) {
625 $replacementKeys['$' . ($n +
1)] = $param;
627 $message = strtr( $message, $replacementKeys );
634 * Return an HTML-escaped version of a message.
635 * Parameter replacements, if any, are done *after* the HTML-escaping,
636 * so parameters may contain HTML (eg links or form controls). Be sure
637 * to pre-escape them if you really do want plaintext, or just wrap
638 * the whole thing in htmlspecialchars().
641 * @param string ... parameters
644 function wfMsgHtml( $key ) {
645 $args = func_get_args();
646 array_shift( $args );
647 return wfMsgReplaceArgs( htmlspecialchars( wfMsgGetKey( $key, true ) ), $args );
651 * Return an HTML version of message
652 * Parameter replacements, if any, are done *after* parsing the wiki-text message,
653 * so parameters may contain HTML (eg links or form controls). Be sure
654 * to pre-escape them if you really do want plaintext, or just wrap
655 * the whole thing in htmlspecialchars().
658 * @param string ... parameters
661 function wfMsgWikiHtml( $key ) {
663 $args = func_get_args();
664 array_shift( $args );
665 return wfMsgReplaceArgs( $wgOut->parse( wfMsgGetKey( $key, true ), /* can't be set to false */ true ), $args );
669 * Returns message in the requested format
670 * @param string $key Key of the message
671 * @param array $options Processing rules. Can take the following options:
672 * <i>parse</i>: parses wikitext to html
673 * <i>parseinline</i>: parses wikitext to html and removes the surrounding
674 * p's added by parser or tidy
675 * <i>escape</i>: filters message through htmlspecialchars
676 * <i>escapenoentities</i>: same, but allows entity references like through
677 * <i>replaceafter</i>: parameters are substituted after parsing or escaping
678 * <i>parsemag</i>: transform the message using magic phrases
679 * <i>content</i>: fetch message for content language instead of interface
680 * Also can accept a single associative argument, of the form 'language' => 'xx':
681 * <i>language</i>: Language object or language code to fetch message for
682 * (overriden by <i>content</i>), its behaviour with parser, parseinline
683 * and parsemag is undefined.
684 * Behavior for conflicting options (e.g., parse+parseinline) is undefined.
686 function wfMsgExt( $key, $options ) {
689 $args = func_get_args();
690 array_shift( $args );
691 array_shift( $args );
692 $options = (array)$options;
694 foreach( $options as $arrayKey => $option ) {
695 if( !preg_match( '/^[0-9]+|language$/', $arrayKey ) ) {
696 # An unknown index, neither numeric nor "language"
697 trigger_error( "wfMsgExt called with incorrect parameter key $arrayKey", E_USER_WARNING
);
698 } elseif( preg_match( '/^[0-9]+$/', $arrayKey ) && !in_array( $option,
699 array( 'parse', 'parseinline', 'escape', 'escapenoentities',
700 'replaceafter', 'parsemag', 'content' ) ) ) {
701 # A numeric index with unknown value
702 trigger_error( "wfMsgExt called with incorrect parameter $option", E_USER_WARNING
);
706 if( in_array('content', $options) ) {
709 } elseif( array_key_exists('language', $options) ) {
711 $langCode = wfGetLangObj( $options['language'] );
717 $string = wfMsgGetKey( $key, /*DB*/true, $langCode, /*Transform*/false );
719 if( !in_array('replaceafter', $options) ) {
720 $string = wfMsgReplaceArgs( $string, $args );
723 if( in_array('parse', $options) ) {
724 $string = $wgOut->parse( $string, true, !$forContent );
725 } elseif ( in_array('parseinline', $options) ) {
726 $string = $wgOut->parse( $string, true, !$forContent );
728 if( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $string, $m ) ) {
731 } elseif ( in_array('parsemag', $options) ) {
732 global $wgMessageCache;
733 if ( isset( $wgMessageCache ) ) {
734 $string = $wgMessageCache->transform( $string,
736 is_object( $langCode ) ?
$langCode : null );
740 if ( in_array('escape', $options) ) {
741 $string = htmlspecialchars ( $string );
742 } elseif ( in_array( 'escapenoentities', $options ) ) {
743 $string = Sanitizer
::escapeHtmlAllowEntities( $string );
746 if( in_array('replaceafter', $options) ) {
747 $string = wfMsgReplaceArgs( $string, $args );
755 * Just like exit() but makes a note of it.
756 * Commits open transactions except if the error parameter is set
758 * @deprecated Please return control to the caller or throw an exception
760 function wfAbruptExit( $error = false ){
761 static $called = false;
767 $bt = wfDebugBacktrace();
769 for($i = 0; $i < count($bt) ; $i++
){
770 $file = isset($bt[$i]['file']) ?
$bt[$i]['file'] : "unknown";
771 $line = isset($bt[$i]['line']) ?
$bt[$i]['line'] : "unknown";
772 wfDebug("WARNING: Abrupt exit in $file at line $line\n");
775 wfDebug('WARNING: Abrupt exit\n');
778 wfLogProfilingData();
781 wfGetLB()->closeAll();
787 * @deprecated Please return control the caller or throw an exception
789 function wfErrorExit() {
790 wfAbruptExit( true );
794 * Print a simple message and die, returning nonzero to the shell if any.
795 * Plain die() fails to return nonzero to the shell if you pass a string.
798 function wfDie( $msg='' ) {
804 * Throw a debugging exception. This function previously once exited the process,
805 * but now throws an exception instead, with similar results.
807 * @param string $msg Message shown when dieing.
809 function wfDebugDieBacktrace( $msg = '' ) {
810 throw new MWException( $msg );
814 * Fetch server name for use in error reporting etc.
815 * Use real server name if available, so we know which machine
816 * in a server farm generated the current page.
819 function wfHostname() {
821 if ( is_null( $host ) ) {
822 if ( function_exists( 'posix_uname' ) ) {
823 // This function not present on Windows
824 $uname = @posix_uname
();
828 if( is_array( $uname ) && isset( $uname['nodename'] ) ) {
829 $host = $uname['nodename'];
830 } elseif ( getenv( 'COMPUTERNAME' ) ) {
831 # Windows computer name
832 $host = getenv( 'COMPUTERNAME' );
834 # This may be a virtual server.
835 $host = $_SERVER['SERVER_NAME'];
842 * Returns a HTML comment with the elapsed time since request.
843 * This method has no side effects.
846 function wfReportTime() {
847 global $wgRequestTime, $wgShowHostnames;
850 $elapsed = $now - $wgRequestTime;
852 return $wgShowHostnames
853 ?
sprintf( "<!-- Served by %s in %01.3f secs. -->", wfHostname(), $elapsed )
854 : sprintf( "<!-- Served in %01.3f secs. -->", $elapsed );
858 * Safety wrapper for debug_backtrace().
860 * With Zend Optimizer 3.2.0 loaded, this causes segfaults under somewhat
861 * murky circumstances, which may be triggered in part by stub objects
862 * or other fancy talkin'.
864 * Will return an empty array if Zend Optimizer is detected, otherwise
865 * the output from debug_backtrace() (trimmed).
867 * @return array of backtrace information
869 function wfDebugBacktrace() {
870 if( extension_loaded( 'Zend Optimizer' ) ) {
871 wfDebug( "Zend Optimizer detected; skipping debug_backtrace for safety.\n" );
874 return array_slice( debug_backtrace(), 1 );
878 function wfBacktrace() {
879 global $wgCommandLineMode;
881 if ( $wgCommandLineMode ) {
886 $backtrace = wfDebugBacktrace();
887 foreach( $backtrace as $call ) {
888 if( isset( $call['file'] ) ) {
889 $f = explode( DIRECTORY_SEPARATOR
, $call['file'] );
890 $file = $f[count($f)-1];
894 if( isset( $call['line'] ) ) {
895 $line = $call['line'];
899 if ( $wgCommandLineMode ) {
900 $msg .= "$file line $line calls ";
902 $msg .= '<li>' . $file . ' line ' . $line . ' calls ';
904 if( !empty( $call['class'] ) ) $msg .= $call['class'] . '::';
905 $msg .= $call['function'] . '()';
907 if ( $wgCommandLineMode ) {
913 if ( $wgCommandLineMode ) {
923 /* Some generic result counters, pulled out of SearchEngine */
929 function wfShowingResults( $offset, $limit ) {
931 return wfMsgExt( 'showingresults', array( 'parseinline' ), $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+
1 ) );
937 function wfShowingResultsNum( $offset, $limit, $num ) {
939 return wfMsgExt( 'showingresultsnum', array( 'parseinline' ), $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+
1 ), $wgLang->formatNum( $num ) );
945 function wfViewPrevNext( $offset, $limit, $link, $query = '', $atend = false ) {
947 $fmtLimit = $wgLang->formatNum( $limit );
948 $prev = wfMsg( 'prevn', $fmtLimit );
949 $next = wfMsg( 'nextn', $fmtLimit );
951 if( is_object( $link ) ) {
954 $title = Title
::newFromText( $link );
955 if( is_null( $title ) ) {
960 if ( 0 != $offset ) {
961 $po = $offset - $limit;
962 if ( $po < 0 ) { $po = 0; }
963 $q = "limit={$limit}&offset={$po}";
964 if ( '' != $query ) { $q .= '&'.$query; }
965 $plink = '<a href="' . $title->escapeLocalUrl( $q ) . "\" class=\"mw-prevlink\">{$prev}</a>";
966 } else { $plink = $prev; }
968 $no = $offset +
$limit;
969 $q = 'limit='.$limit.'&offset='.$no;
970 if ( '' != $query ) { $q .= '&'.$query; }
975 $nlink = '<a href="' . $title->escapeLocalUrl( $q ) . "\" class=\"mw-nextlink\">{$next}</a>";
977 $nums = wfNumLink( $offset, 20, $title, $query ) . ' | ' .
978 wfNumLink( $offset, 50, $title, $query ) . ' | ' .
979 wfNumLink( $offset, 100, $title, $query ) . ' | ' .
980 wfNumLink( $offset, 250, $title, $query ) . ' | ' .
981 wfNumLink( $offset, 500, $title, $query );
983 return wfMsg( 'viewprevnext', $plink, $nlink, $nums );
989 function wfNumLink( $offset, $limit, &$title, $query = '' ) {
991 if ( '' == $query ) { $q = ''; }
992 else { $q = $query.'&'; }
993 $q .= 'limit='.$limit.'&offset='.$offset;
995 $fmtLimit = $wgLang->formatNum( $limit );
996 $s = '<a href="' . $title->escapeLocalUrl( $q ) . "\" class=\"mw-numlink\">{$fmtLimit}</a>";
1002 * @todo FIXME: we may want to blacklist some broken browsers
1004 * @return bool Whereas client accept gzip compression
1006 function wfClientAcceptsGzip() {
1009 # FIXME: we may want to blacklist some broken browsers
1012 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
1013 $_SERVER['HTTP_ACCEPT_ENCODING'],
1015 if( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) return false;
1016 wfDebug( " accepts gzip\n" );
1024 * Obtain the offset and limit values from the request string;
1025 * used in special pages
1027 * @param $deflimit Default limit if none supplied
1028 * @param $optionname Name of a user preference to check against
1032 function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) {
1034 return $wgRequest->getLimitOffset( $deflimit, $optionname );
1038 * Escapes the given text so that it may be output using addWikiText()
1039 * without any linking, formatting, etc. making its way through. This
1040 * is achieved by substituting certain characters with HTML entities.
1041 * As required by the callers, <nowiki> is not used. It currently does
1042 * not filter out characters which have special meaning only at the
1043 * start of a line, such as "*".
1045 * @param string $text Text to be escaped
1047 function wfEscapeWikiText( $text ) {
1048 $text = str_replace(
1049 array( '[', '|', ']', '\'', 'ISBN ', 'RFC ', '://', "\n=", '{{' ), # }}
1050 array( '[', '|', ']', ''', 'ISBN ', 'RFC ', '://', "\n=", '{{' ),
1051 htmlspecialchars($text) );
1058 function wfQuotedPrintable( $string, $charset = '' ) {
1059 # Probably incomplete; see RFC 2045
1060 if( empty( $charset ) ) {
1061 global $wgInputEncoding;
1062 $charset = $wgInputEncoding;
1064 $charset = strtoupper( $charset );
1065 $charset = str_replace( 'ISO-8859', 'ISO8859', $charset ); // ?
1067 $illegal = '\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\xff=';
1068 $replace = $illegal . '\t ?_';
1069 if( !preg_match( "/[$illegal]/", $string ) ) return $string;
1070 $out = "=?$charset?Q?";
1071 $out .= preg_replace( "/([$replace])/e", 'sprintf("=%02X",ord("$1"))', $string );
1082 return microtime(true);
1086 * Sets dest to source and returns the original value of dest
1087 * If source is NULL, it just returns the value, it doesn't set the variable
1089 function wfSetVar( &$dest, $source ) {
1091 if ( !is_null( $source ) ) {
1098 * As for wfSetVar except setting a bit
1100 function wfSetBit( &$dest, $bit, $state = true ) {
1101 $temp = (bool)($dest & $bit );
1102 if ( !is_null( $state ) ) {
1113 * This function takes two arrays as input, and returns a CGI-style string, e.g.
1114 * "days=7&limit=100". Options in the first array override options in the second.
1115 * Options set to "" will not be output.
1117 function wfArrayToCGI( $array1, $array2 = NULL )
1119 if ( !is_null( $array2 ) ) {
1120 $array1 = $array1 +
$array2;
1124 foreach ( $array1 as $key => $value ) {
1125 if ( '' !== $value ) {
1129 if(is_array($value))
1132 foreach($value as $v)
1134 $cgi .= ($firstTime ?
'' : '&') .
1135 urlencode( $key . '[]' ) . '=' .
1141 $cgi .= urlencode( $key ) . '=' .
1142 urlencode( $value );
1149 * This is the logical opposite of wfArrayToCGI(): it accepts a query string as
1150 * its argument and returns the same string in array form. This allows compa-
1151 * tibility with legacy functions that accept raw query strings instead of nice
1152 * arrays. Of course, keys and values are urldecode()d. Don't try passing in-
1153 * valid query strings, or it will explode.
1155 * @param $query string Query string
1156 * @return array Array version of input
1158 function wfCgiToArray( $query ) {
1159 if( isset( $query[0] ) and $query[0] == '?' ) {
1160 $query = substr( $query, 1 );
1162 $bits = explode( '&', $query );
1164 foreach( $bits as $bit ) {
1168 list( $key, $value ) = explode( '=', $bit );
1169 $key = urldecode( $key );
1170 $value = urldecode( $value );
1171 $ret[$key] = $value;
1177 * Append a query string to an existing URL, which may or may not already
1178 * have query string parameters already. If so, they will be combined.
1180 * @param string $url
1181 * @param string $query
1184 function wfAppendQuery( $url, $query ) {
1185 if( $query != '' ) {
1186 if( false === strpos( $url, '?' ) ) {
1197 * Expand a potentially local URL to a fully-qualified URL.
1198 * Assumes $wgServer is correct. :)
1199 * @param string $url, either fully-qualified or a local path + query
1200 * @return string Fully-qualified URL
1202 function wfExpandUrl( $url ) {
1203 if( substr( $url, 0, 1 ) == '/' ) {
1205 return $wgServer . $url;
1212 * This is obsolete, use SquidUpdate::purge()
1215 function wfPurgeSquidServers ($urlArr) {
1216 SquidUpdate
::purge( $urlArr );
1220 * Windows-compatible version of escapeshellarg()
1221 * Windows doesn't recognise single-quotes in the shell, but the escapeshellarg()
1222 * function puts single quotes in regardless of OS.
1224 * Also fixes the locale problems on Linux in PHP 5.2.6+ (bug backported to
1225 * earlier distro releases of PHP)
1227 function wfEscapeShellArg( ) {
1228 wfInitShellLocale();
1230 $args = func_get_args();
1233 foreach ( $args as $arg ) {
1240 if ( wfIsWindows() ) {
1241 // Escaping for an MSVC-style command line parser
1242 // Ref: http://mailman.lyra.org/pipermail/scite-interest/2002-March/000436.html
1243 // Double the backslashes before any double quotes. Escape the double quotes.
1244 $tokens = preg_split( '/(\\\\*")/', $arg, -1, PREG_SPLIT_DELIM_CAPTURE
);
1247 foreach ( $tokens as $token ) {
1249 $arg .= str_replace( '\\', '\\\\', substr( $token, 0, -1 ) ) . '\\"';
1255 // Double the backslashes before the end of the string, because
1256 // we will soon add a quote
1258 if ( preg_match( '/^(.*?)(\\\\+)$/', $arg, $m ) ) {
1259 $arg = $m[1] . str_replace( '\\', '\\\\', $m[2] );
1262 // Add surrounding quotes
1263 $retVal .= '"' . $arg . '"';
1265 $retVal .= escapeshellarg( $arg );
1272 * wfMerge attempts to merge differences between three texts.
1273 * Returns true for a clean merge and false for failure or a conflict.
1275 function wfMerge( $old, $mine, $yours, &$result ){
1278 # This check may also protect against code injection in
1279 # case of broken installations.
1280 if( !$wgDiff3 ||
!file_exists( $wgDiff3 ) ) {
1281 wfDebug( "diff3 not found\n" );
1285 # Make temporary files
1287 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
1288 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
1289 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
1291 fwrite( $oldtextFile, $old ); fclose( $oldtextFile );
1292 fwrite( $mytextFile, $mine ); fclose( $mytextFile );
1293 fwrite( $yourtextFile, $yours ); fclose( $yourtextFile );
1295 # Check for a conflict
1296 $cmd = $wgDiff3 . ' -a --overlap-only ' .
1297 wfEscapeShellArg( $mytextName ) . ' ' .
1298 wfEscapeShellArg( $oldtextName ) . ' ' .
1299 wfEscapeShellArg( $yourtextName );
1300 $handle = popen( $cmd, 'r' );
1302 if( fgets( $handle, 1024 ) ){
1310 $cmd = $wgDiff3 . ' -a -e --merge ' .
1311 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
1312 $handle = popen( $cmd, 'r' );
1315 $data = fread( $handle, 8192 );
1316 if ( strlen( $data ) == 0 ) {
1322 unlink( $mytextName ); unlink( $oldtextName ); unlink( $yourtextName );
1324 if ( $result === '' && $old !== '' && $conflict == false ) {
1325 wfDebug( "Unexpected null result from diff3. Command: $cmd\n" );
1332 * Returns unified plain-text diff of two texts.
1333 * Useful for machine processing of diffs.
1334 * @param $before string The text before the changes.
1335 * @param $after string The text after the changes.
1336 * @param $params string Command-line options for the diff command.
1337 * @return string Unified diff of $before and $after
1339 function wfDiff( $before, $after, $params = '-u' ) {
1342 # This check may also protect against code injection in
1343 # case of broken installations.
1344 if( !file_exists( $wgDiff ) ){
1345 wfDebug( "diff executable not found\n" );
1346 $diffs = new Diff( explode( "\n", $before ), explode( "\n", $after ) );
1347 $format = new UnifiedDiffFormatter();
1348 return $format->format( $diffs );
1351 # Make temporary files
1353 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
1354 $newtextFile = fopen( $newtextName = tempnam( $td, 'merge-your-' ), 'w' );
1356 fwrite( $oldtextFile, $before ); fclose( $oldtextFile );
1357 fwrite( $newtextFile, $after ); fclose( $newtextFile );
1359 // Get the diff of the two files
1360 $cmd = "$wgDiff " . $params . ' ' .wfEscapeShellArg( $oldtextName, $newtextName );
1362 $h = popen( $cmd, 'r' );
1367 $data = fread( $h, 8192 );
1368 if ( strlen( $data ) == 0 ) {
1376 unlink( $oldtextName );
1377 unlink( $newtextName );
1379 // Kill the --- and +++ lines. They're not useful.
1380 $diff_lines = explode( "\n", $diff );
1381 if (strpos( $diff_lines[0], '---' ) === 0) {
1382 unset($diff_lines[0]);
1384 if (strpos( $diff_lines[1], '+++' ) === 0) {
1385 unset($diff_lines[1]);
1388 $diff = implode( "\n", $diff_lines );
1394 * A wrapper around the PHP function var_export().
1395 * Either print it or add it to the regular output ($wgOut).
1397 * @param $var A PHP variable to dump.
1399 function wfVarDump( $var ) {
1401 $s = str_replace("\n","<br />\n", var_export( $var, true ) . "\n");
1402 if ( headers_sent() ||
!@is_object
( $wgOut ) ) {
1405 $wgOut->addHTML( $s );
1410 * Provide a simple HTTP error.
1412 function wfHttpError( $code, $label, $desc ) {
1415 header( "HTTP/1.0 $code $label" );
1416 header( "Status: $code $label" );
1417 $wgOut->sendCacheControl();
1419 header( 'Content-type: text/html; charset=utf-8' );
1420 print "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">".
1421 "<html><head><title>" .
1422 htmlspecialchars( $label ) .
1423 "</title></head><body><h1>" .
1424 htmlspecialchars( $label ) .
1426 nl2br( htmlspecialchars( $desc ) ) .
1427 "</p></body></html>\n";
1431 * Clear away any user-level output buffers, discarding contents.
1433 * Suitable for 'starting afresh', for instance when streaming
1434 * relatively large amounts of data without buffering, or wanting to
1435 * output image files without ob_gzhandler's compression.
1437 * The optional $resetGzipEncoding parameter controls suppression of
1438 * the Content-Encoding header sent by ob_gzhandler; by default it
1439 * is left. See comments for wfClearOutputBuffers() for why it would
1442 * Note that some PHP configuration options may add output buffer
1443 * layers which cannot be removed; these are left in place.
1445 * @param bool $resetGzipEncoding
1447 function wfResetOutputBuffers( $resetGzipEncoding=true ) {
1448 if( $resetGzipEncoding ) {
1449 // Suppress Content-Encoding and Content-Length
1450 // headers from 1.10+s wfOutputHandler
1451 global $wgDisableOutputCompression;
1452 $wgDisableOutputCompression = true;
1454 while( $status = ob_get_status() ) {
1455 if( $status['type'] == 0 /* PHP_OUTPUT_HANDLER_INTERNAL */ ) {
1456 // Probably from zlib.output_compression or other
1457 // PHP-internal setting which can't be removed.
1459 // Give up, and hope the result doesn't break
1463 if( !ob_end_clean() ) {
1464 // Could not remove output buffer handler; abort now
1465 // to avoid getting in some kind of infinite loop.
1468 if( $resetGzipEncoding ) {
1469 if( $status['name'] == 'ob_gzhandler' ) {
1470 // Reset the 'Content-Encoding' field set by this handler
1471 // so we can start fresh.
1472 header( 'Content-Encoding:' );
1480 * More legible than passing a 'false' parameter to wfResetOutputBuffers():
1482 * Clear away output buffers, but keep the Content-Encoding header
1483 * produced by ob_gzhandler, if any.
1485 * This should be used for HTTP 304 responses, where you need to
1486 * preserve the Content-Encoding header of the real result, but
1487 * also need to suppress the output of ob_gzhandler to keep to spec
1488 * and avoid breaking Firefox in rare cases where the headers and
1489 * body are broken over two packets.
1491 function wfClearOutputBuffers() {
1492 wfResetOutputBuffers( false );
1496 * Converts an Accept-* header into an array mapping string values to quality
1499 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
1500 # No arg means accept anything (per HTTP spec)
1502 return array( $def => 1.0 );
1507 $parts = explode( ',', $accept );
1509 foreach( $parts as $part ) {
1510 # FIXME: doesn't deal with params like 'text/html; level=1'
1511 @list
( $value, $qpart ) = explode( ';', trim( $part ) );
1513 if( !isset( $qpart ) ) {
1514 $prefs[$value] = 1.0;
1515 } elseif( preg_match( '/q\s*=\s*(\d*\.\d+)/', $qpart, $match ) ) {
1516 $prefs[$value] = floatval($match[1]);
1524 * Checks if a given MIME type matches any of the keys in the given
1525 * array. Basic wildcards are accepted in the array keys.
1527 * Returns the matching MIME type (or wildcard) if a match, otherwise
1530 * @param string $type
1531 * @param array $avail
1535 function mimeTypeMatch( $type, $avail ) {
1536 if( array_key_exists($type, $avail) ) {
1539 $parts = explode( '/', $type );
1540 if( array_key_exists( $parts[0] . '/*', $avail ) ) {
1541 return $parts[0] . '/*';
1542 } elseif( array_key_exists( '*/*', $avail ) ) {
1551 * Returns the 'best' match between a client's requested internet media types
1552 * and the server's list of available types. Each list should be an associative
1553 * array of type to preference (preference is a float between 0.0 and 1.0).
1554 * Wildcards in the types are acceptable.
1556 * @param array $cprefs Client's acceptable type list
1557 * @param array $sprefs Server's offered types
1560 * @todo FIXME: doesn't handle params like 'text/plain; charset=UTF-8'
1561 * XXX: generalize to negotiate other stuff
1563 function wfNegotiateType( $cprefs, $sprefs ) {
1566 foreach( array_keys($sprefs) as $type ) {
1567 $parts = explode( '/', $type );
1568 if( $parts[1] != '*' ) {
1569 $ckey = mimeTypeMatch( $type, $cprefs );
1571 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1576 foreach( array_keys( $cprefs ) as $type ) {
1577 $parts = explode( '/', $type );
1578 if( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
1579 $skey = mimeTypeMatch( $type, $sprefs );
1581 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1589 foreach( array_keys( $combine ) as $type ) {
1590 if( $combine[$type] > $bestq ) {
1592 $bestq = $combine[$type];
1601 * Returns an array where the values in the first array are replaced by the
1602 * values in the second array with the corresponding keys
1606 function wfArrayLookup( $a, $b ) {
1607 return array_flip( array_intersect( array_flip( $a ), array_keys( $b ) ) );
1611 * Convenience function; returns MediaWiki timestamp for the present time.
1614 function wfTimestampNow() {
1616 return wfTimestamp( TS_MW
, time() );
1620 * Reference-counted warning suppression
1622 function wfSuppressWarnings( $end = false ) {
1623 static $suppressCount = 0;
1624 static $originalLevel = false;
1627 if ( $suppressCount ) {
1629 if ( !$suppressCount ) {
1630 error_reporting( $originalLevel );
1634 if ( !$suppressCount ) {
1635 $originalLevel = error_reporting( E_ALL
& ~
( E_WARNING | E_NOTICE
) );
1642 * Restore error level to previous value
1644 function wfRestoreWarnings() {
1645 wfSuppressWarnings( true );
1648 # Autodetect, convert and provide timestamps of various types
1651 * Unix time - the number of seconds since 1970-01-01 00:00:00 UTC
1653 define('TS_UNIX', 0);
1656 * MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
1661 * MySQL DATETIME (YYYY-MM-DD HH:MM:SS)
1666 * RFC 2822 format, for E-mail and HTTP headers
1668 define('TS_RFC2822', 3);
1671 * ISO 8601 format with no timezone: 1986-02-09T20:00:00Z
1673 * This is used by Special:Export
1675 define('TS_ISO_8601', 4);
1678 * An Exif timestamp (YYYY:MM:DD HH:MM:SS)
1680 * @see http://exif.org/Exif2-2.PDF The Exif 2.2 spec, see page 28 for the
1681 * DateTime tag and page 36 for the DateTimeOriginal and
1682 * DateTimeDigitized tags.
1684 define('TS_EXIF', 5);
1687 * Oracle format time.
1689 define('TS_ORACLE', 6);
1692 * Postgres format time.
1694 define('TS_POSTGRES', 7);
1697 * @param mixed $outputtype A timestamp in one of the supported formats, the
1698 * function will autodetect which format is supplied
1699 * and act accordingly.
1700 * @return string Time in the format specified in $outputtype
1702 function wfTimestamp($outputtype=TS_UNIX
,$ts=0) {
1707 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)$/D',$ts,$da)) {
1709 } elseif (preg_match('/^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/D',$ts,$da)) {
1711 } elseif (preg_match('/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/D',$ts,$da)) {
1713 } elseif (preg_match('/^\d{1,13}$/D',$ts)) {
1716 } elseif (preg_match('/^\d{1,2}-...-\d\d(?:\d\d)? \d\d\.\d\d\.\d\d/', $ts)) {
1718 $uts = strtotime(preg_replace('/(\d\d)\.(\d\d)\.(\d\d)(\.(\d+))?/', "$1:$2:$3",
1719 str_replace("+00:00", "UTC", $ts)));
1720 } elseif (preg_match('/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.*\d*)?Z$/', $ts, $da)) {
1722 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.*\d*[\+\- ](\d\d)$/',$ts,$da)) {
1724 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.*\d* GMT$/',$ts,$da)) {
1727 # Bogus value; fall back to the epoch...
1728 wfDebug("wfTimestamp() fed bogus time value: $outputtype; $ts\n");
1732 if (count( $da ) ) {
1733 // Warning! gmmktime() acts oddly if the month or day is set to 0
1734 // We may want to handle that explicitly at some point
1735 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1736 (int)$da[2],(int)$da[3],(int)$da[1]);
1739 switch($outputtype) {
1743 return gmdate( 'YmdHis', $uts );
1745 return gmdate( 'Y-m-d H:i:s', $uts );
1747 return gmdate( 'Y-m-d\TH:i:s\Z', $uts );
1748 // This shouldn't ever be used, but is included for completeness
1750 return gmdate( 'Y:m:d H:i:s', $uts );
1752 return gmdate( 'D, d M Y H:i:s', $uts ) . ' GMT';
1754 return gmdate( 'd-M-y h.i.s A', $uts) . ' +00:00';
1756 return gmdate( 'Y-m-d H:i:s', $uts) . ' GMT';
1758 throw new MWException( 'wfTimestamp() called with illegal output type.');
1763 * Return a formatted timestamp, or null if input is null.
1764 * For dealing with nullable timestamp columns in the database.
1765 * @param int $outputtype
1769 function wfTimestampOrNull( $outputtype = TS_UNIX
, $ts = null ) {
1770 if( is_null( $ts ) ) {
1773 return wfTimestamp( $outputtype, $ts );
1778 * Check if the operating system is Windows
1780 * @return bool True if it's Windows, False otherwise.
1782 function wfIsWindows() {
1783 if (substr(php_uname(), 0, 7) == 'Windows') {
1791 * Swap two variables
1793 function swap( &$x, &$y ) {
1799 function wfGetCachedNotice( $name ) {
1800 global $wgOut, $wgRenderHashAppend, $parserMemc;
1801 $fname = 'wfGetCachedNotice';
1802 wfProfileIn( $fname );
1806 if( $name === 'default' ) {
1808 global $wgSiteNotice;
1809 $notice = $wgSiteNotice;
1810 if( empty( $notice ) ) {
1811 wfProfileOut( $fname );
1815 $notice = wfMsgForContentNoTrans( $name );
1816 if( wfEmptyMsg( $name, $notice ) ||
$notice == '-' ) {
1817 wfProfileOut( $fname );
1822 // Use the extra hash appender to let eg SSL variants separately cache.
1823 $key = wfMemcKey( $name . $wgRenderHashAppend );
1824 $cachedNotice = $parserMemc->get( $key );
1825 if( is_array( $cachedNotice ) ) {
1826 if( md5( $notice ) == $cachedNotice['hash'] ) {
1827 $notice = $cachedNotice['html'];
1836 if( is_object( $wgOut ) ) {
1837 $parsed = $wgOut->parse( $notice );
1838 $parserMemc->set( $key, array( 'html' => $parsed, 'hash' => md5( $notice ) ), 600 );
1841 wfDebug( 'wfGetCachedNotice called for ' . $name . ' with no $wgOut available' );
1846 wfProfileOut( $fname );
1850 function wfGetNamespaceNotice() {
1854 if ( !isset( $wgTitle ) ||
!is_object( $wgTitle ) )
1857 $fname = 'wfGetNamespaceNotice';
1858 wfProfileIn( $fname );
1860 $key = "namespacenotice-" . $wgTitle->getNsText();
1861 $namespaceNotice = wfGetCachedNotice( $key );
1862 if ( $namespaceNotice && substr ( $namespaceNotice , 0 ,7 ) != "<p><" ) {
1863 $namespaceNotice = '<div id="namespacebanner">' . $namespaceNotice . "</div>";
1865 $namespaceNotice = "";
1868 wfProfileOut( $fname );
1869 return $namespaceNotice;
1872 function wfGetSiteNotice() {
1873 global $wgUser, $wgSiteNotice;
1874 $fname = 'wfGetSiteNotice';
1875 wfProfileIn( $fname );
1878 if( wfRunHooks( 'SiteNoticeBefore', array( &$siteNotice ) ) ) {
1879 if( is_object( $wgUser ) && $wgUser->isLoggedIn() ) {
1880 $siteNotice = wfGetCachedNotice( 'sitenotice' );
1882 $anonNotice = wfGetCachedNotice( 'anonnotice' );
1883 if( !$anonNotice ) {
1884 $siteNotice = wfGetCachedNotice( 'sitenotice' );
1886 $siteNotice = $anonNotice;
1889 if( !$siteNotice ) {
1890 $siteNotice = wfGetCachedNotice( 'default' );
1894 wfRunHooks( 'SiteNoticeAfter', array( &$siteNotice ) );
1895 wfProfileOut( $fname );
1900 * BC wrapper for MimeMagic::singleton()
1903 function &wfGetMimeMagic() {
1904 return MimeMagic
::singleton();
1908 * Tries to get the system directory for temporary files.
1909 * The TMPDIR, TMP, and TEMP environment variables are checked in sequence,
1910 * and if none are set /tmp is returned as the generic Unix default.
1912 * NOTE: When possible, use the tempfile() function to create temporary
1913 * files to avoid race conditions on file creation, etc.
1917 function wfTempDir() {
1918 foreach( array( 'TMPDIR', 'TMP', 'TEMP' ) as $var ) {
1919 $tmp = getenv( $var );
1920 if( $tmp && file_exists( $tmp ) && is_dir( $tmp ) && is_writable( $tmp ) ) {
1924 # Hope this is Unix of some kind!
1929 * Make directory, and make all parent directories if they don't exist
1931 * @param string $fullDir Full path to directory to create
1932 * @param int $mode Chmod value to use, default is $wgDirectoryMode
1935 function wfMkdirParents( $fullDir, $mode = null ) {
1936 global $wgDirectoryMode;
1937 if( strval( $fullDir ) === '' )
1939 if( file_exists( $fullDir ) )
1941 // If not defined or isn't an int, set to default
1942 if ( is_null( $mode ) ) {
1943 $mode = $wgDirectoryMode;
1947 # Go back through the paths to find the first directory that exists
1948 $currentDir = $fullDir;
1949 $createList = array();
1950 while ( strval( $currentDir ) !== '' && !file_exists( $currentDir ) ) {
1951 # Strip trailing slashes
1952 $currentDir = rtrim( $currentDir, '/\\' );
1954 # Add to create list
1955 $createList[] = $currentDir;
1957 # Find next delimiter searching from the end
1958 $p = max( strrpos( $currentDir, '/' ), strrpos( $currentDir, '\\' ) );
1959 if ( $p === false ) {
1960 $currentDir = false;
1962 $currentDir = substr( $currentDir, 0, $p );
1966 if ( count( $createList ) == 0 ) {
1967 # Directory specified already exists
1969 } elseif ( $currentDir === false ) {
1970 # Went all the way back to root and it apparently doesn't exist
1971 wfDebugLog( 'mkdir', "Root doesn't exist?\n" );
1974 # Now go forward creating directories
1975 $createList = array_reverse( $createList );
1977 # Is the parent directory writable?
1978 if ( $currentDir === '' ) {
1981 if ( !is_writable( $currentDir ) ) {
1982 wfDebugLog( 'mkdir', "Not writable: $currentDir\n" );
1986 foreach ( $createList as $dir ) {
1987 # use chmod to override the umask, as suggested by the PHP manual
1988 if ( !mkdir( $dir, $mode ) ||
!chmod( $dir, $mode ) ) {
1989 wfDebugLog( 'mkdir', "Unable to create directory $dir\n" );
1997 * Increment a statistics counter
1999 function wfIncrStats( $key ) {
2000 global $wgStatsMethod;
2002 if( $wgStatsMethod == 'udp' ) {
2003 global $wgUDPProfilerHost, $wgUDPProfilerPort, $wgDBname;
2006 $socket=socket_create(AF_INET
, SOCK_DGRAM
, SOL_UDP
);
2007 $statline="stats/{$wgDBname} - 1 1 1 1 1 -total\n";
2008 socket_sendto($socket,$statline,strlen($statline),0,$wgUDPProfilerHost,$wgUDPProfilerPort);
2010 $statline="stats/{$wgDBname} - 1 1 1 1 1 {$key}\n";
2011 @socket_sendto
($socket,$statline,strlen($statline),0,$wgUDPProfilerHost,$wgUDPProfilerPort);
2012 } elseif( $wgStatsMethod == 'cache' ) {
2014 $key = wfMemcKey( 'stats', $key );
2015 if ( is_null( $wgMemc->incr( $key ) ) ) {
2016 $wgMemc->add( $key, 1 );
2024 * @param mixed $nr The number to format
2025 * @param int $acc The number of digits after the decimal point, default 2
2026 * @param bool $round Whether or not to round the value, default true
2029 function wfPercent( $nr, $acc = 2, $round = true ) {
2030 $ret = sprintf( "%.${acc}f", $nr );
2031 return $round ?
round( $ret, $acc ) . '%' : "$ret%";
2035 * Encrypt a username/password.
2037 * @param string $userid ID of the user
2038 * @param string $password Password of the user
2039 * @return string Hashed password
2040 * @deprecated Use User::crypt() or User::oldCrypt() instead
2042 function wfEncryptPassword( $userid, $password ) {
2043 wfDeprecated(__FUNCTION__
);
2044 # Just wrap around User::oldCrypt()
2045 return User
::oldCrypt($password, $userid);
2049 * Appends to second array if $value differs from that in $default
2051 function wfAppendToArrayIfNotDefault( $key, $value, $default, &$changed ) {
2052 if ( is_null( $changed ) ) {
2053 throw new MWException('GlobalFunctions::wfAppendToArrayIfNotDefault got null');
2055 if ( $default[$key] !== $value ) {
2056 $changed[$key] = $value;
2061 * Since wfMsg() and co suck, they don't return false if the message key they
2062 * looked up didn't exist but a XHTML string, this function checks for the
2063 * nonexistance of messages by looking at wfMsg() output
2065 * @param $msg The message key looked up
2066 * @param $wfMsgOut The output of wfMsg*()
2069 function wfEmptyMsg( $msg, $wfMsgOut ) {
2070 return $wfMsgOut === htmlspecialchars( "<$msg>" );
2074 * Find out whether or not a mixed variable exists in a string
2076 * @param mixed needle
2077 * @param string haystack
2080 function in_string( $needle, $str ) {
2081 return strpos( $str, $needle ) !== false;
2084 function wfSpecialList( $page, $details ) {
2086 $details = $details ?
' ' . $wgContLang->getDirMark() . "($details)" : "";
2087 return $page . $details;
2091 * Returns a regular expression of url protocols
2095 function wfUrlProtocols() {
2096 global $wgUrlProtocols;
2098 // Support old-style $wgUrlProtocols strings, for backwards compatibility
2099 // with LocalSettings files from 1.5
2100 if ( is_array( $wgUrlProtocols ) ) {
2101 $protocols = array();
2102 foreach ($wgUrlProtocols as $protocol)
2103 $protocols[] = preg_quote( $protocol, '/' );
2105 return implode( '|', $protocols );
2107 return $wgUrlProtocols;
2112 * Safety wrapper around ini_get() for boolean settings.
2113 * The values returned from ini_get() are pre-normalized for settings
2114 * set via php.ini or php_flag/php_admin_flag... but *not*
2115 * for those set via php_value/php_admin_value.
2117 * It's fairly common for people to use php_value instead of php_flag,
2118 * which can leave you with an 'off' setting giving a false positive
2119 * for code that just takes the ini_get() return value as a boolean.
2121 * To make things extra interesting, setting via php_value accepts
2122 * "true" and "yes" as true, but php.ini and php_flag consider them false. :)
2123 * Unrecognized values go false... again opposite PHP's own coercion
2124 * from string to bool.
2126 * Luckily, 'properly' set settings will always come back as '0' or '1',
2127 * so we only have to worry about them and the 'improper' settings.
2129 * I frickin' hate PHP... :P
2131 * @param string $setting
2134 function wfIniGetBool( $setting ) {
2135 $val = ini_get( $setting );
2136 // 'on' and 'true' can't have whitespace around them, but '1' can.
2137 return strtolower( $val ) == 'on'
2138 ||
strtolower( $val ) == 'true'
2139 ||
strtolower( $val ) == 'yes'
2140 ||
preg_match( "/^\s*[+-]?0*[1-9]/", $val ); // approx C atoi() function
2144 * Execute a shell command, with time and memory limits mirrored from the PHP
2145 * configuration if supported.
2146 * @param $cmd Command line, properly escaped for shell.
2147 * @param &$retval optional, will receive the program's exit code.
2148 * (non-zero is usually failure)
2149 * @return collected stdout as a string (trailing newlines stripped)
2151 function wfShellExec( $cmd, &$retval=null ) {
2152 global $IP, $wgMaxShellMemory, $wgMaxShellFileSize, $wgMaxShellTime;
2154 if( wfIniGetBool( 'safe_mode' ) ) {
2155 wfDebug( "wfShellExec can't run in safe_mode, PHP's exec functions are too broken.\n" );
2157 return "Unable to run external programs in safe mode.";
2159 wfInitShellLocale();
2161 if ( php_uname( 's' ) == 'Linux' ) {
2162 $time = intval( $wgMaxShellTime );
2163 $mem = intval( $wgMaxShellMemory );
2164 $filesize = intval( $wgMaxShellFileSize );
2166 if ( $time > 0 && $mem > 0 ) {
2167 $script = "$IP/bin/ulimit4.sh";
2168 if ( is_executable( $script ) ) {
2169 $cmd = escapeshellarg( $script ) . " $time $mem $filesize " . escapeshellarg( $cmd );
2172 } elseif ( php_uname( 's' ) == 'Windows NT' ) {
2173 # This is a hack to work around PHP's flawed invocation of cmd.exe
2174 # http://news.php.net/php.internals/21796
2175 $cmd = '"' . $cmd . '"';
2177 wfDebug( "wfShellExec: $cmd\n" );
2179 $retval = 1; // error by default?
2181 passthru( $cmd, $retval );
2182 $output = ob_get_contents();
2185 if ( $retval == 127 ) {
2186 wfDebugLog( 'exec', "Possibly missing executable file: $cmd\n" );
2192 * Workaround for http://bugs.php.net/bug.php?id=45132
2193 * escapeshellarg() destroys non-ASCII characters if LANG is not a UTF-8 locale
2195 function wfInitShellLocale() {
2196 static $done = false;
2197 if ( $done ) return;
2199 global $wgShellLocale;
2200 if ( !wfIniGetBool( 'safe_mode' ) ) {
2201 putenv( "LC_CTYPE=$wgShellLocale" );
2202 setlocale( LC_CTYPE
, $wgShellLocale );
2207 * This function works like "use VERSION" in Perl, the program will die with a
2208 * backtrace if the current version of PHP is less than the version provided
2210 * This is useful for extensions which due to their nature are not kept in sync
2211 * with releases, and might depend on other versions of PHP than the main code
2213 * Note: PHP might die due to parsing errors in some cases before it ever
2214 * manages to call this function, such is life
2216 * @see perldoc -f use
2218 * @param mixed $version The version to check, can be a string, an integer, or
2221 function wfUsePHP( $req_ver ) {
2222 $php_ver = PHP_VERSION
;
2224 if ( version_compare( $php_ver, (string)$req_ver, '<' ) )
2225 throw new MWException( "PHP $req_ver required--this is only $php_ver" );
2229 * This function works like "use VERSION" in Perl except it checks the version
2230 * of MediaWiki, the program will die with a backtrace if the current version
2231 * of MediaWiki is less than the version provided.
2233 * This is useful for extensions which due to their nature are not kept in sync
2236 * @see perldoc -f use
2238 * @param mixed $version The version to check, can be a string, an integer, or
2241 function wfUseMW( $req_ver ) {
2244 if ( version_compare( $wgVersion, (string)$req_ver, '<' ) )
2245 throw new MWException( "MediaWiki $req_ver required--this is only $wgVersion" );
2249 * @deprecated use StringUtils::escapeRegexReplacement
2251 function wfRegexReplacement( $string ) {
2252 return StringUtils
::escapeRegexReplacement( $string );
2256 * Return the final portion of a pathname.
2257 * Reimplemented because PHP5's basename() is buggy with multibyte text.
2258 * http://bugs.php.net/bug.php?id=33898
2260 * PHP's basename() only considers '\' a pathchar on Windows and Netware.
2261 * We'll consider it so always, as we don't want \s in our Unix paths either.
2263 * @param string $path
2264 * @param string $suffix to remove if present
2267 function wfBaseName( $path, $suffix='' ) {
2268 $encSuffix = ($suffix == '')
2270 : ( '(?:' . preg_quote( $suffix, '#' ) . ')?' );
2272 if( preg_match( "#([^/\\\\]*?){$encSuffix}[/\\\\]*$#", $path, $matches ) ) {
2280 * Generate a relative path name to the given file.
2281 * May explode on non-matching case-insensitive paths,
2282 * funky symlinks, etc.
2284 * @param string $path Absolute destination path including target filename
2285 * @param string $from Absolute source path, directory only
2288 function wfRelativePath( $path, $from ) {
2289 // Normalize mixed input on Windows...
2290 $path = str_replace( '/', DIRECTORY_SEPARATOR
, $path );
2291 $from = str_replace( '/', DIRECTORY_SEPARATOR
, $from );
2293 // Trim trailing slashes -- fix for drive root
2294 $path = rtrim( $path, DIRECTORY_SEPARATOR
);
2295 $from = rtrim( $from, DIRECTORY_SEPARATOR
);
2297 $pieces = explode( DIRECTORY_SEPARATOR
, dirname( $path ) );
2298 $against = explode( DIRECTORY_SEPARATOR
, $from );
2300 if( $pieces[0] !== $against[0] ) {
2301 // Non-matching Windows drive letters?
2302 // Return a full path.
2306 // Trim off common prefix
2307 while( count( $pieces ) && count( $against )
2308 && $pieces[0] == $against[0] ) {
2309 array_shift( $pieces );
2310 array_shift( $against );
2313 // relative dots to bump us to the parent
2314 while( count( $against ) ) {
2315 array_unshift( $pieces, '..' );
2316 array_shift( $against );
2319 array_push( $pieces, wfBaseName( $path ) );
2321 return implode( DIRECTORY_SEPARATOR
, $pieces );
2325 * Backwards array plus for people who haven't bothered to read the PHP manual
2326 * XXX: will not darn your socks for you.
2328 * @param array $array1, [$array2, [...]]
2331 function wfArrayMerge( $array1/* ... */ ) {
2332 $args = func_get_args();
2333 $args = array_reverse( $args, true );
2335 foreach ( $args as $arg ) {
2342 * Merge arrays in the style of getUserPermissionsErrors, with duplicate removal
2344 * wfMergeErrorArrays(
2345 * array( array( 'x' ) ),
2346 * array( array( 'x', '2' ) ),
2347 * array( array( 'x' ) ),
2348 * array( array( 'y') )
2352 * array( 'x', '2' ),
2357 function wfMergeErrorArrays(/*...*/) {
2358 $args = func_get_args();
2360 foreach ( $args as $errors ) {
2361 foreach ( $errors as $params ) {
2362 $spec = implode( "\t", $params );
2363 $out[$spec] = $params;
2366 return array_values( $out );
2370 * Make a URL index, appropriate for the el_index field of externallinks.
2372 function wfMakeUrlIndex( $url ) {
2373 global $wgUrlProtocols; // Allow all protocols defined in DefaultSettings/LocalSettings.php
2374 wfSuppressWarnings();
2375 $bits = parse_url( $url );
2376 wfRestoreWarnings();
2380 // most of the protocols are followed by ://, but mailto: and sometimes news: not, check for it
2382 if ( in_array( $bits['scheme'] . '://' , $wgUrlProtocols ) ) {
2384 } elseif ( in_array( $bits['scheme'] .':' , $wgUrlProtocols ) ) {
2386 // parse_url detects for news: and mailto: the host part of an url as path
2387 // We have to correct this wrong detection
2388 if ( isset ( $bits['path'] ) ) {
2389 $bits['host'] = $bits['path'];
2396 // Reverse the labels in the hostname, convert to lower case
2397 // For emails reverse domainpart only
2398 if ( $bits['scheme'] == 'mailto' ) {
2399 $mailparts = explode( '@', $bits['host'], 2 );
2400 if ( count($mailparts) === 2 ) {
2401 $domainpart = strtolower( implode( '.', array_reverse( explode( '.', $mailparts[1] ) ) ) );
2403 // No domain specified, don't mangle it
2406 $reversedHost = $domainpart . '@' . $mailparts[0];
2408 $reversedHost = strtolower( implode( '.', array_reverse( explode( '.', $bits['host'] ) ) ) );
2410 // Add an extra dot to the end
2411 // Why? Is it in wrong place in mailto links?
2412 if ( substr( $reversedHost, -1, 1 ) !== '.' ) {
2413 $reversedHost .= '.';
2415 // Reconstruct the pseudo-URL
2416 $prot = $bits['scheme'];
2417 $index = "$prot$delimiter$reversedHost";
2418 // Leave out user and password. Add the port, path, query and fragment
2419 if ( isset( $bits['port'] ) ) $index .= ':' . $bits['port'];
2420 if ( isset( $bits['path'] ) ) {
2421 $index .= $bits['path'];
2425 if ( isset( $bits['query'] ) ) $index .= '?' . $bits['query'];
2426 if ( isset( $bits['fragment'] ) ) $index .= '#' . $bits['fragment'];
2431 * Do any deferred updates and clear the list
2432 * TODO: This could be in Wiki.php if that class made any sense at all
2434 function wfDoUpdates()
2436 global $wgPostCommitUpdateList, $wgDeferredUpdateList;
2437 foreach ( $wgDeferredUpdateList as $update ) {
2438 $update->doUpdate();
2440 foreach ( $wgPostCommitUpdateList as $update ) {
2441 $update->doUpdate();
2443 $wgDeferredUpdateList = array();
2444 $wgPostCommitUpdateList = array();
2448 * @deprecated use StringUtils::explodeMarkup
2450 function wfExplodeMarkup( $separator, $text ) {
2451 return StringUtils
::explodeMarkup( $separator, $text );
2455 * Convert an arbitrarily-long digit string from one numeric base
2456 * to another, optionally zero-padding to a minimum column width.
2458 * Supports base 2 through 36; digit values 10-36 are represented
2459 * as lowercase letters a-z. Input is case-insensitive.
2461 * @param $input string of digits
2462 * @param $sourceBase int 2-36
2463 * @param $destBase int 2-36
2464 * @param $pad int 1 or greater
2465 * @param $lowercase bool
2466 * @return string or false on invalid input
2468 function wfBaseConvert( $input, $sourceBase, $destBase, $pad=1, $lowercase=true ) {
2469 $input = strval( $input );
2470 if( $sourceBase < 2 ||
2475 $sourceBase != intval( $sourceBase ) ||
2476 $destBase != intval( $destBase ) ||
2477 $pad != intval( $pad ) ||
2478 !is_string( $input ) ||
2482 $digitChars = ( $lowercase ) ?
'0123456789abcdefghijklmnopqrstuvwxyz' : '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
2483 $inDigits = array();
2486 // Decode and validate input string
2487 $input = strtolower( $input );
2488 for( $i = 0; $i < strlen( $input ); $i++
) {
2489 $n = strpos( $digitChars, $input{$i} );
2490 if( $n === false ||
$n > $sourceBase ) {
2496 // Iterate over the input, modulo-ing out an output digit
2497 // at a time until input is gone.
2498 while( count( $inDigits ) ) {
2500 $workDigits = array();
2503 foreach( $inDigits as $digit ) {
2504 $work *= $sourceBase;
2507 if( $work < $destBase ) {
2508 // Gonna need to pull another digit.
2509 if( count( $workDigits ) ) {
2510 // Avoid zero-padding; this lets us find
2511 // the end of the input very easily when
2512 // length drops to zero.
2516 // Finally! Actual division!
2517 $workDigits[] = intval( $work / $destBase );
2519 // Isn't it annoying that most programming languages
2520 // don't have a single divide-and-remainder operator,
2521 // even though the CPU implements it that way?
2522 $work = $work %
$destBase;
2526 // All that division leaves us with a remainder,
2527 // which is conveniently our next output digit.
2528 $outChars .= $digitChars[$work];
2531 $inDigits = $workDigits;
2534 while( strlen( $outChars ) < $pad ) {
2538 return strrev( $outChars );
2542 * Create an object with a given name and an array of construct parameters
2543 * @param string $name
2544 * @param array $p parameters
2546 function wfCreateObject( $name, $p ){
2547 $p = array_values( $p );
2548 switch ( count( $p ) ) {
2552 return new $name( $p[0] );
2554 return new $name( $p[0], $p[1] );
2556 return new $name( $p[0], $p[1], $p[2] );
2558 return new $name( $p[0], $p[1], $p[2], $p[3] );
2560 return new $name( $p[0], $p[1], $p[2], $p[3], $p[4] );
2562 return new $name( $p[0], $p[1], $p[2], $p[3], $p[4], $p[5] );
2564 throw new MWException( "Too many arguments to construtor in wfCreateObject" );
2569 * Alias for modularized function
2570 * @deprecated Use Http::get() instead
2572 function wfGetHTTP( $url, $timeout = 'default' ) {
2573 wfDeprecated(__FUNCTION__
);
2574 return Http
::get( $url, $timeout );
2578 * Alias for modularized function
2579 * @deprecated Use Http::isLocalURL() instead
2581 function wfIsLocalURL( $url ) {
2582 wfDeprecated(__FUNCTION__
);
2583 return Http
::isLocalURL( $url );
2586 function wfHttpOnlySafe() {
2587 global $wgHttpOnlyBlacklist;
2588 if( !version_compare("5.2", PHP_VERSION
, "<") )
2591 if( isset( $_SERVER['HTTP_USER_AGENT'] ) ) {
2592 foreach( $wgHttpOnlyBlacklist as $regex ) {
2593 if( preg_match( $regex, $_SERVER['HTTP_USER_AGENT'] ) ) {
2603 * Initialise php session
2605 function wfSetupSession() {
2606 global $wgSessionsInMemcached, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookieHttpOnly;
2607 if( $wgSessionsInMemcached ) {
2608 require_once( 'MemcachedSessions.php' );
2609 } elseif( 'files' != ini_get( 'session.save_handler' ) ) {
2610 # If it's left on 'user' or another setting from another
2611 # application, it will end up failing. Try to recover.
2612 ini_set ( 'session.save_handler', 'files' );
2614 $httpOnlySafe = wfHttpOnlySafe();
2615 wfDebugLog( 'cookie',
2616 'session_set_cookie_params: "' . implode( '", "',
2622 $httpOnlySafe && $wgCookieHttpOnly ) ) . '"' );
2623 if( $httpOnlySafe && $wgCookieHttpOnly ) {
2624 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookieHttpOnly );
2626 // PHP 5.1 throws warnings if you pass the HttpOnly parameter for 5.2.
2627 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
2629 session_cache_limiter( 'private, must-revalidate' );
2630 wfSuppressWarnings();
2632 wfRestoreWarnings();
2636 * Get an object from the precompiled serialized directory
2638 * @return mixed The variable on success, false on failure
2640 function wfGetPrecompiledData( $name ) {
2643 $file = "$IP/serialized/$name";
2644 if ( file_exists( $file ) ) {
2645 $blob = file_get_contents( $file );
2647 return unserialize( $blob );
2653 function wfGetCaller( $level = 2 ) {
2654 $backtrace = wfDebugBacktrace();
2655 if ( isset( $backtrace[$level] ) ) {
2656 return wfFormatStackFrame($backtrace[$level]);
2658 $caller = 'unknown';
2663 /** Return a string consisting all callers in stack, somewhat useful sometimes for profiling specific points */
2664 function wfGetAllCallers() {
2665 return implode('/', array_map('wfFormatStackFrame',array_reverse(wfDebugBacktrace())));
2668 /** Return a string representation of frame */
2669 function wfFormatStackFrame($frame) {
2670 return isset( $frame["class"] )?
2671 $frame["class"]."::".$frame["function"]:
2678 function wfMemcKey( /*... */ ) {
2679 $args = func_get_args();
2680 $key = wfWikiID() . ':' . implode( ':', $args );
2685 * Get a cache key for a foreign DB
2687 function wfForeignMemcKey( $db, $prefix /*, ... */ ) {
2688 $args = array_slice( func_get_args(), 2 );
2690 $key = "$db-$prefix:" . implode( ':', $args );
2692 $key = $db . ':' . implode( ':', $args );
2698 * Get an ASCII string identifying this wiki
2699 * This is used as a prefix in memcached keys
2701 function wfWikiID( $db = null ) {
2702 if( $db instanceof Database
) {
2703 return $db->getWikiID();
2705 global $wgDBprefix, $wgDBname;
2706 if ( $wgDBprefix ) {
2707 return "$wgDBname-$wgDBprefix";
2715 * Split a wiki ID into DB name and table prefix
2717 function wfSplitWikiID( $wiki ) {
2718 $bits = explode( '-', $wiki, 2 );
2719 if ( count( $bits ) < 2 ) {
2726 * Get a Database object.
2727 * @param integer $db Index of the connection to get. May be DB_MASTER for the
2728 * master (for write queries), DB_SLAVE for potentially lagged
2729 * read queries, or an integer >= 0 for a particular server.
2731 * @param mixed $groups Query groups. An array of group names that this query
2732 * belongs to. May contain a single string if the query is only
2735 * @param string $wiki The wiki ID, or false for the current wiki
2737 * Note: multiple calls to wfGetDB(DB_SLAVE) during the course of one request
2738 * will always return the same object, unless the underlying connection or load
2739 * balancer is manually destroyed.
2741 function &wfGetDB( $db, $groups = array(), $wiki = false ) {
2742 return wfGetLB( $wiki )->getConnection( $db, $groups, $wiki );
2746 * Get a load balancer object.
2748 * @param array $groups List of query groups
2749 * @param string $wiki Wiki ID, or false for the current wiki
2750 * @return LoadBalancer
2752 function wfGetLB( $wiki = false ) {
2753 return wfGetLBFactory()->getMainLB( $wiki );
2757 * Get the load balancer factory object
2759 function &wfGetLBFactory() {
2760 return LBFactory
::singleton();
2765 * Shortcut for RepoGroup::singleton()->findFile()
2766 * @param mixed $title Title object or string. May be interwiki.
2767 * @param mixed $time Requested time for an archived image, or false for the
2768 * current version. An image object will be returned which
2769 * was created at the specified time.
2770 * @param mixed $flags FileRepo::FIND_ flags
2771 * @return File, or false if the file does not exist
2773 function wfFindFile( $title, $time = false, $flags = 0 ) {
2774 return RepoGroup
::singleton()->findFile( $title, $time, $flags );
2778 * Get an object referring to a locally registered file.
2779 * Returns a valid placeholder object if the file does not exist.
2781 function wfLocalFile( $title ) {
2782 return RepoGroup
::singleton()->getLocalRepo()->newFile( $title );
2786 * Should low-performance queries be disabled?
2790 function wfQueriesMustScale() {
2791 global $wgMiserMode;
2793 ||
( SiteStats
::pages() > 100000
2794 && SiteStats
::edits() > 1000000
2795 && SiteStats
::users() > 10000 );
2799 * Get the path to a specified script file, respecting file
2800 * extensions; this is a wrapper around $wgScriptExtension etc.
2802 * @param string $script Script filename, sans extension
2805 function wfScript( $script = 'index' ) {
2806 global $wgScriptPath, $wgScriptExtension;
2807 return "{$wgScriptPath}/{$script}{$wgScriptExtension}";
2811 * Convenience function converts boolean values into "true"
2812 * or "false" (string) values
2814 * @param bool $value
2817 function wfBoolToStr( $value ) {
2818 return $value ?
'true' : 'false';
2822 * Load an extension messages file
2824 * @param string $extensionName Name of extension to load messages from\for.
2825 * @param string $langcode Language to load messages for, or false for default
2826 * behvaiour (en, content language and user language).
2827 * @since r24808 (v1.11) Using this method of loading extension messages will not work
2828 * on MediaWiki prior to that
2830 function wfLoadExtensionMessages( $extensionName, $langcode = false ) {
2831 global $wgExtensionMessagesFiles, $wgMessageCache, $wgLang, $wgContLang;
2833 #For recording whether extension message files have been loaded in a given language.
2834 static $loaded = array();
2836 if( !array_key_exists( $extensionName, $loaded ) ) {
2837 $loaded[$extensionName] = array();
2840 if ( !isset($wgExtensionMessagesFiles[$extensionName]) ) {
2841 throw new MWException( "Messages file for extensions $extensionName is not defined" );
2844 if( !$langcode && !array_key_exists( '*', $loaded[$extensionName] ) ) {
2845 # Just do en, content language and user language.
2846 $wgMessageCache->loadMessagesFile( $wgExtensionMessagesFiles[$extensionName], false );
2847 # Mark that they have been loaded.
2848 $loaded[$extensionName]['en'] = true;
2849 $loaded[$extensionName][$wgLang->getCode()] = true;
2850 $loaded[$extensionName][$wgContLang->getCode()] = true;
2851 # Mark that this part has been done to avoid weird if statements.
2852 $loaded[$extensionName]['*'] = true;
2853 } elseif( is_string( $langcode ) && !array_key_exists( $langcode, $loaded[$extensionName] ) ) {
2854 # Load messages for specified language.
2855 $wgMessageCache->loadMessagesFile( $wgExtensionMessagesFiles[$extensionName], $langcode );
2856 # Mark that they have been loaded.
2857 $loaded[$extensionName][$langcode] = true;
2862 * Get a platform-independent path to the null file, e.g.
2867 function wfGetNull() {
2868 return wfIsWindows()
2874 * Displays a maxlag error
2876 * @param string $host Server that lags the most
2877 * @param int $lag Maxlag (actual)
2878 * @param int $maxLag Maxlag (requested)
2880 function wfMaxlagError( $host, $lag, $maxLag ) {
2881 global $wgShowHostnames;
2882 header( 'HTTP/1.1 503 Service Unavailable' );
2883 header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
2884 header( 'X-Database-Lag: ' . intval( $lag ) );
2885 header( 'Content-Type: text/plain' );
2886 if( $wgShowHostnames ) {
2887 echo "Waiting for $host: $lag seconds lagged\n";
2889 echo "Waiting for a database server: $lag seconds lagged\n";
2894 * Throws an E_USER_NOTICE saying that $function is deprecated
2895 * @param string $function
2898 function wfDeprecated( $function ) {
2899 global $wgDebugLogFile;
2900 if ( !$wgDebugLogFile ) {
2903 $callers = wfDebugBacktrace();
2904 if( isset( $callers[2] ) ){
2905 $callerfunc = $callers[2];
2906 $callerfile = $callers[1];
2907 if( isset( $callerfile['file'] ) && isset( $callerfile['line'] ) ){
2908 $file = $callerfile['file'] . ' at line ' . $callerfile['line'];
2910 $file = '(internal function)';
2913 if( isset( $callerfunc['class'] ) )
2914 $func .= $callerfunc['class'] . '::';
2915 $func .= @$callerfunc['function'];
2916 $msg = "Use of $function is deprecated. Called from $func in $file";
2918 $msg = "Use of $function is deprecated.";
2920 wfDebug( "$msg\n" );
2924 * Sleep until the worst slave's replication lag is less than or equal to
2925 * $maxLag, in seconds. Use this when updating very large numbers of rows, as
2926 * in maintenance scripts, to avoid causing too much lag. Of course, this is
2927 * a no-op if there are no slaves.
2929 * Every time the function has to wait for a slave, it will print a message to
2930 * that effect (and then sleep for a little while), so it's probably not best
2931 * to use this outside maintenance scripts in its present form.
2933 * @param int $maxLag
2936 function wfWaitForSlaves( $maxLag ) {
2939 list( $host, $lag ) = $lb->getMaxLag();
2940 while( $lag > $maxLag ) {
2941 $name = @gethostbyaddr
( $host );
2942 if( $name !== false ) {
2945 print "Waiting for $host (lagged $lag seconds)...\n";
2947 list( $host, $lag ) = $lb->getMaxLag();
2952 /** Generate a random 32-character hexadecimal token.
2953 * @param mixed $salt Some sort of salt, if necessary, to add to random characters before hashing.
2955 function wfGenerateToken( $salt = '' ) {
2956 $salt = serialize($salt);
2958 return md5( mt_rand( 0, 0x7fffffff ) . $salt );
2962 * Replace all invalid characters with -
2963 * @param mixed $title Filename to process
2965 function wfStripIllegalFilenameChars( $name ) {
2966 $name = wfBaseName( $name );
2967 $name = preg_replace ( "/[^".Title
::legalChars()."]|:/", '-', $name );