4 * Global functions used everywhere
9 * Some globals and requires needed
13 * Total number of articles
14 * @global integer $wgNumberOfArticles
16 $wgNumberOfArticles = -1; # Unset
18 * Total number of views
19 * @global integer $wgTotalViews
23 * Total number of edits
24 * @global integer $wgTotalEdits
29 require_once( 'DatabaseFunctions.php' );
30 require_once( 'UpdateClasses.php' );
31 require_once( 'LogPage.php' );
32 require_once( 'normal/UtfNormalUtil.php' );
35 * Compatibility functions
36 * PHP <4.3.x is not actively supported; 4.1.x and 4.2.x might or might not work.
37 * <4.1.x will not work, as we use a number of features introduced in 4.1.0
38 * such as the new autoglobals.
40 if( !function_exists('iconv') ) {
41 # iconv support is not in the default configuration and so may not be present.
42 # Assume will only ever use utf-8 and iso-8859-1.
43 # This will *not* work in all circumstances.
44 function iconv( $from, $to, $string ) {
45 if(strcasecmp( $from, $to ) == 0) return $string;
46 if(strcasecmp( $from, 'utf-8' ) == 0) return utf8_decode( $string );
47 if(strcasecmp( $to, 'utf-8' ) == 0) return utf8_encode( $string );
52 if( !function_exists('file_get_contents') ) {
53 # Exists in PHP 4.3.0+
54 function file_get_contents( $filename ) {
55 return implode( '', file( $filename ) );
59 if( !function_exists('is_a') ) {
60 # Exists in PHP 4.2.0+
61 function is_a( $object, $class_name ) {
63 (strcasecmp( get_class( $object ), $class_name ) == 0) ||
64 is_subclass_of( $object, $class_name );
68 # UTF-8 substr function based on a PHP manual comment
69 if ( !function_exists( 'mb_substr' ) ) {
70 function mb_substr( $str, $start ) {
71 preg_match_all( '/./us', $str, $ar );
73 if( func_num_args() >= 3 ) {
74 $end = func_get_arg( 2 );
75 return join( '', array_slice( $ar[0], $start, $end ) );
77 return join( '', array_slice( $ar[0], $start ) );
82 if( !function_exists( 'floatval' ) ) {
84 * First defined in PHP 4.2.0
88 function floatval( $var ) {
94 * Where as we got a random seed
95 * @var bool $wgTotalViews
97 $wgRandomSeeded = false;
100 * Seed Mersenne Twister
101 * Only necessary in PHP < 4.2.0
105 function wfSeedRandom() {
106 global $wgRandomSeeded;
108 if ( ! $wgRandomSeeded && version_compare( phpversion(), '4.2.0' ) < 0 ) {
109 $seed = hexdec(substr(md5(microtime()),-8)) & 0x7fffffff;
111 $wgRandomSeeded = true;
116 * Get a random decimal value between 0 and 1, in a way
117 * not likely to give duplicate values for any realistic
118 * number of articles.
122 function wfRandom() {
123 # The maximum random value is "only" 2^31-1, so get two random
124 # values to reduce the chance of dupes
125 $max = mt_getrandmax();
126 $rand = number_format( (mt_rand() * $max +
mt_rand())
127 / $max / $max, 12, '.', '' );
132 * We want / and : to be included as literal characters in our title URLs.
133 * %2F in the page titles seems to fatally break for some reason.
138 function wfUrlencode ( $s ) {
139 $s = urlencode( $s );
140 $s = preg_replace( '/%3[Aa]/', ':', $s );
141 $s = preg_replace( '/%2[Ff]/', '/', $s );
147 * Sends a line to the debug log if enabled or, optionally, to a comment in output.
148 * In normal operation this is a NOP.
150 * Controlling globals:
151 * $wgDebugLogFile - points to the log file
152 * $wgProfileOnly - if set, normal debug messages will not be recorded.
153 * $wgDebugRawPage - if false, 'action=raw' hits will not result in debug output.
154 * $wgDebugComments - if on, some debug items may appear in comments in the HTML output.
156 * @param string $text
157 * @param bool $logonly Set true to avoid appearing in HTML when $wgDebugComments is set
159 function wfDebug( $text, $logonly = false ) {
160 global $wgOut, $wgDebugLogFile, $wgDebugComments, $wgProfileOnly, $wgDebugRawPage;
162 # Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
163 if ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' && !$wgDebugRawPage ) {
167 if ( isset( $wgOut ) && $wgDebugComments && !$logonly ) {
168 $wgOut->debug( $text );
170 if ( '' != $wgDebugLogFile && !$wgProfileOnly ) {
171 # Strip unprintables; they can switch terminal modes when binary data
172 # gets dumped, which is pretty annoying.
173 $text = preg_replace( '![\x00-\x08\x0b\x0c\x0e-\x1f]!', ' ', $text );
174 @error_log
( $text, 3, $wgDebugLogFile );
179 * Send a line to a supplementary debug log file, if configured, or main debug log if not.
180 * $wgDebugLogGroups[$logGroup] should be set to a filename to send to a separate log.
182 * @param string $logGroup
183 * @param string $text
184 * @param bool $public Whether to log the event in the public log if no private
185 * log file is specified, (default true)
187 function wfDebugLog( $logGroup, $text, $public = true ) {
188 global $wgDebugLogGroups, $wgDBname;
189 if( $text{strlen( $text ) - 1} != "\n" ) $text .= "\n";
190 if( isset( $wgDebugLogGroups[$logGroup] ) ) {
191 @error_log
( "$wgDBname: $text", 3, $wgDebugLogGroups[$logGroup] );
192 } else if ( $public === true ) {
193 wfDebug( $text, true );
198 * Log for database errors
199 * @param string $text Database error message.
201 function wfLogDBError( $text ) {
202 global $wgDBerrorLog;
203 if ( $wgDBerrorLog ) {
204 $text = date('D M j G:i:s T Y') . "\t".$text;
205 error_log( $text, 3, $wgDBerrorLog );
212 function logProfilingData() {
213 global $wgRequestTime, $wgDebugLogFile, $wgDebugRawPage, $wgRequest;
214 global $wgProfiling, $wgProfileStack, $wgProfileLimit, $wgUser;
217 list( $usec, $sec ) = explode( ' ', $wgRequestTime );
218 $start = (float)$sec +
(float)$usec;
219 $elapsed = $now - $start;
220 if ( $wgProfiling ) {
221 $prof = wfGetProfilingOutput( $start, $elapsed );
223 if( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) )
224 $forward = ' forwarded for ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
225 if( !empty( $_SERVER['HTTP_CLIENT_IP'] ) )
226 $forward .= ' client IP ' . $_SERVER['HTTP_CLIENT_IP'];
227 if( !empty( $_SERVER['HTTP_FROM'] ) )
228 $forward .= ' from ' . $_SERVER['HTTP_FROM'];
230 $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
231 if( $wgUser->isAnon() )
233 $log = sprintf( "%s\t%04.3f\t%s\n",
234 gmdate( 'YmdHis' ), $elapsed,
235 urldecode( $_SERVER['REQUEST_URI'] . $forward ) );
236 if ( '' != $wgDebugLogFile && ( $wgRequest->getVal('action') != 'raw' ||
$wgDebugRawPage ) ) {
237 error_log( $log . $prof, 3, $wgDebugLogFile );
243 * Check if the wiki read-only lock file is present. This can be used to lock
244 * off editing functions, but doesn't guarantee that the database will not be
248 function wfReadOnly() {
249 global $wgReadOnlyFile, $wgReadOnly;
254 if ( '' == $wgReadOnlyFile ) {
258 // Set $wgReadOnly and unset $wgReadOnlyFile, for faster access next time
259 if ( is_file( $wgReadOnlyFile ) ) {
260 $wgReadOnly = file_get_contents( $wgReadOnlyFile );
264 $wgReadOnlyFile = '';
270 * Get a message from anywhere, for the current user language.
272 * Use wfMsgForContent() instead if the message should NOT
273 * change depending on the user preferences.
275 * Note that the message may contain HTML, and is therefore
276 * not safe for insertion anywhere. Some functions such as
277 * addWikiText will do the escaping for you. Use wfMsgHtml()
278 * if you need an escaped message.
280 * @param string lookup key for the message, usually
281 * defined in languages/Language.php
283 function wfMsg( $key ) {
284 $args = func_get_args();
285 array_shift( $args );
286 return wfMsgReal( $key, $args, true );
290 * Get a message from anywhere, for the current global language
291 * set with $wgLanguageCode.
293 * Use this if the message should NOT change dependent on the
294 * language set in the user's preferences. This is the case for
295 * most text written into logs, as well as link targets (such as
296 * the name of the copyright policy page). Link titles, on the
297 * other hand, should be shown in the UI language.
299 * Note that MediaWiki allows users to change the user interface
300 * language in their preferences, but a single installation
301 * typically only contains content in one language.
303 * Be wary of this distinction: If you use wfMsg() where you should
304 * use wfMsgForContent(), a user of the software may have to
305 * customize over 70 messages in order to, e.g., fix a link in every
308 * @param string lookup key for the message, usually
309 * defined in languages/Language.php
311 function wfMsgForContent( $key ) {
312 global $wgForceUIMsgAsContentMsg;
313 $args = func_get_args();
314 array_shift( $args );
316 if( is_array( $wgForceUIMsgAsContentMsg ) &&
317 in_array( $key, $wgForceUIMsgAsContentMsg ) )
319 return wfMsgReal( $key, $args, true, $forcontent );
323 * Get a message from the language file, for the UI elements
325 function wfMsgNoDB( $key ) {
326 $args = func_get_args();
327 array_shift( $args );
328 return wfMsgReal( $key, $args, false );
332 * Get a message from the language file, for the content
334 function wfMsgNoDBForContent( $key ) {
335 global $wgForceUIMsgAsContentMsg;
336 $args = func_get_args();
337 array_shift( $args );
339 if( is_array( $wgForceUIMsgAsContentMsg ) &&
340 in_array( $key, $wgForceUIMsgAsContentMsg ) )
342 return wfMsgReal( $key, $args, false, $forcontent );
347 * Really get a message
349 function wfMsgReal( $key, $args, $useDB, $forContent=false ) {
350 $fname = 'wfMsgReal';
351 wfProfileIn( $fname );
353 $message = wfMsgGetKey( $key, $useDB, $forContent );
354 $message = wfMsgReplaceArgs( $message, $args );
355 wfProfileOut( $fname );
360 * Fetch a message string value, but don't replace any keys yet.
363 * @param bool $forContent
367 function wfMsgGetKey( $key, $useDB, $forContent = false ) {
368 global $wgParser, $wgMsgParserOptions;
369 global $wgContLang, $wgLanguageCode;
370 global $wgMessageCache, $wgLang;
372 if( is_object( $wgMessageCache ) ) {
373 $message = $wgMessageCache->get( $key, $useDB, $forContent );
376 $lang = &$wgContLang;
381 wfSuppressWarnings();
383 if( is_object( $lang ) ) {
384 $message = $lang->getMessage( $key );
389 if($message === false)
390 $message = Language
::getMessage($key);
391 if(strstr($message, '{{' ) !== false) {
392 $message = $wgParser->transformMsg($message, $wgMsgParserOptions);
399 * Replace message parameter keys on the given formatted output.
401 * @param string $message
406 function wfMsgReplaceArgs( $message, $args ) {
407 static $replacementKeys = array( '$1', '$2', '$3', '$4', '$5', '$6', '$7', '$8', '$9' );
409 # Fix windows line-endings
410 # Some messages are split with explode("\n", $msg)
411 $message = str_replace( "\r", '', $message );
414 if( count( $args ) ) {
415 $message = str_replace( $replacementKeys, $args, $message );
421 * Return an HTML-escaped version of a message.
422 * Parameter replacements, if any, are done *after* the HTML-escaping,
423 * so parameters may contain HTML (eg links or form controls). Be sure
424 * to pre-escape them if you really do want plaintext, or just wrap
425 * the whole thing in htmlspecialchars().
428 * @param string ... parameters
431 function wfMsgHtml( $key ) {
432 $args = func_get_args();
433 array_shift( $args );
434 return wfMsgReplaceArgs( htmlspecialchars( wfMsgGetKey( $key, true ) ), $args );
438 * Return an HTML version of message
439 * Parameter replacements, if any, are done *after* parsing the wiki-text message,
440 * so parameters may contain HTML (eg links or form controls). Be sure
441 * to pre-escape them if you really do want plaintext, or just wrap
442 * the whole thing in htmlspecialchars().
445 * @param string ... parameters
448 function wfMsgWikiHtml( $key ) {
450 $args = func_get_args();
451 array_shift( $args );
452 return wfMsgReplaceArgs( $wgOut->parse( wfMsgGetKey( $key, true ), /* can't be set to false */ true ), $args );
456 * Just like exit() but makes a note of it.
457 * Commits open transactions except if the error parameter is set
459 function wfAbruptExit( $error = false ){
460 global $wgLoadBalancer;
461 static $called = false;
467 if( function_exists( 'debug_backtrace' ) ){ // PHP >= 4.3
468 $bt = debug_backtrace();
469 for($i = 0; $i < count($bt) ; $i++
){
470 $file = $bt[$i]['file'];
471 $line = $bt[$i]['line'];
472 wfDebug("WARNING: Abrupt exit in $file at line $line\n");
475 wfDebug('WARNING: Abrupt exit\n');
478 $wgLoadBalancer->closeAll();
486 function wfErrorExit() {
487 wfAbruptExit( true );
491 * Die with a backtrace
492 * This is meant as a debugging aid to track down where bad data comes from.
493 * Shouldn't be used in production code except maybe in "shouldn't happen" areas.
495 * @param string $msg Message shown when dieing.
497 function wfDebugDieBacktrace( $msg = '' ) {
498 global $wgCommandLineMode;
500 $backtrace = wfBacktrace();
501 if ( $backtrace !== false ) {
502 if ( $wgCommandLineMode ) {
503 $msg .= "\nBacktrace:\n$backtrace";
505 $msg .= "\n<p>Backtrace:</p>\n$backtrace";
509 echo wfReportTime()."\n";
514 * Returns a HTML comment with the elapsed time since request.
515 * This method has no side effects.
518 function wfReportTime() {
519 global $wgRequestTime;
522 list( $usec, $sec ) = explode( ' ', $wgRequestTime );
523 $start = (float)$sec +
(float)$usec;
524 $elapsed = $now - $start;
526 # Use real server name if available, so we know which machine
527 # in a server farm generated the current page.
528 if ( function_exists( 'posix_uname' ) ) {
529 $uname = @posix_uname
();
533 if( is_array( $uname ) && isset( $uname['nodename'] ) ) {
534 $hostname = $uname['nodename'];
536 # This may be a virtual server.
537 $hostname = $_SERVER['SERVER_NAME'];
539 $com = sprintf( "<!-- Served by %s in %01.2f secs. -->",
540 $hostname, $elapsed );
544 function wfBacktrace() {
545 global $wgCommandLineMode;
546 if ( !function_exists( 'debug_backtrace' ) ) {
550 if ( $wgCommandLineMode ) {
555 $backtrace = debug_backtrace();
556 foreach( $backtrace as $call ) {
557 if( isset( $call['file'] ) ) {
558 $f = explode( DIRECTORY_SEPARATOR
, $call['file'] );
559 $file = $f[count($f)-1];
563 if( isset( $call['line'] ) ) {
564 $line = $call['line'];
568 if ( $wgCommandLineMode ) {
569 $msg .= "$file line $line calls ";
571 $msg .= '<li>' . $file . ' line ' . $line . ' calls ';
573 if( !empty( $call['class'] ) ) $msg .= $call['class'] . '::';
574 $msg .= $call['function'] . '()';
576 if ( $wgCommandLineMode ) {
582 if ( $wgCommandLineMode ) {
592 /* Some generic result counters, pulled out of SearchEngine */
598 function wfShowingResults( $offset, $limit ) {
600 return wfMsg( 'showingresults', $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+
1 ) );
606 function wfShowingResultsNum( $offset, $limit, $num ) {
608 return wfMsg( 'showingresultsnum', $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+
1 ), $wgLang->formatNum( $num ) );
614 function wfViewPrevNext( $offset, $limit, $link, $query = '', $atend = false ) {
615 global $wgUser, $wgLang;
616 $fmtLimit = $wgLang->formatNum( $limit );
617 $prev = wfMsg( 'prevn', $fmtLimit );
618 $next = wfMsg( 'nextn', $fmtLimit );
620 if( is_object( $link ) ) {
623 $title = Title
::newFromText( $link );
624 if( is_null( $title ) ) {
629 $sk = $wgUser->getSkin();
630 if ( 0 != $offset ) {
631 $po = $offset - $limit;
632 if ( $po < 0 ) { $po = 0; }
633 $q = "limit={$limit}&offset={$po}";
634 if ( '' != $query ) { $q .= '&'.$query; }
635 $plink = '<a href="' . $title->escapeLocalUrl( $q ) . "\">{$prev}</a>";
636 } else { $plink = $prev; }
638 $no = $offset +
$limit;
639 $q = 'limit='.$limit.'&offset='.$no;
640 if ( '' != $query ) { $q .= '&'.$query; }
645 $nlink = '<a href="' . $title->escapeLocalUrl( $q ) . "\">{$next}</a>";
647 $nums = wfNumLink( $offset, 20, $title, $query ) . ' | ' .
648 wfNumLink( $offset, 50, $title, $query ) . ' | ' .
649 wfNumLink( $offset, 100, $title, $query ) . ' | ' .
650 wfNumLink( $offset, 250, $title, $query ) . ' | ' .
651 wfNumLink( $offset, 500, $title, $query );
653 return wfMsg( 'viewprevnext', $plink, $nlink, $nums );
659 function wfNumLink( $offset, $limit, &$title, $query = '' ) {
660 global $wgUser, $wgLang;
661 if ( '' == $query ) { $q = ''; }
662 else { $q = $query.'&'; }
663 $q .= 'limit='.$limit.'&offset='.$offset;
665 $fmtLimit = $wgLang->formatNum( $limit );
666 $s = '<a href="' . $title->escapeLocalUrl( $q ) . "\">{$fmtLimit}</a>";
672 * @todo FIXME: we may want to blacklist some broken browsers
674 * @return bool Whereas client accept gzip compression
676 function wfClientAcceptsGzip() {
679 # FIXME: we may want to blacklist some broken browsers
681 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
682 $_SERVER['HTTP_ACCEPT_ENCODING'],
684 if( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) return false;
685 wfDebug( " accepts gzip\n" );
693 * Yay, more global functions!
695 function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) {
697 return $wgRequest->getLimitOffset( $deflimit, $optionname );
701 * Escapes the given text so that it may be output using addWikiText()
702 * without any linking, formatting, etc. making its way through. This
703 * is achieved by substituting certain characters with HTML entities.
704 * As required by the callers, <nowiki> is not used. It currently does
705 * not filter out characters which have special meaning only at the
706 * start of a line, such as "*".
708 * @param string $text Text to be escaped
710 function wfEscapeWikiText( $text ) {
712 array( '[', '|', '\'', 'ISBN ' , '://' , "\n=", '{{' ),
713 array( '[', '|', ''', 'ISBN ', '://' , "\n=", '{{' ),
714 htmlspecialchars($text) );
721 function wfQuotedPrintable( $string, $charset = '' ) {
722 # Probably incomplete; see RFC 2045
723 if( empty( $charset ) ) {
724 global $wgInputEncoding;
725 $charset = $wgInputEncoding;
727 $charset = strtoupper( $charset );
728 $charset = str_replace( 'ISO-8859', 'ISO8859', $charset ); // ?
730 $illegal = '\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\xff=';
731 $replace = $illegal . '\t ?_';
732 if( !preg_match( "/[$illegal]/", $string ) ) return $string;
733 $out = "=?$charset?Q?";
734 $out .= preg_replace( "/([$replace])/e", 'sprintf("=%02X",ord("$1"))', $string );
740 * Returns an escaped string suitable for inclusion in a string literal
741 * for JavaScript source code.
742 * Illegal control characters are assumed not to be present.
744 * @param string $string
747 function wfEscapeJsString( $string ) {
748 // See ECMA 262 section 7.8.4 for string literal format
756 # To avoid closing the element or CDATA section
760 return strtr( $string, $pairs );
768 $st = explode( ' ', microtime() );
769 return (float)$st[0] +
(float)$st[1];
773 * Changes the first character to an HTML entity
775 function wfHtmlEscapeFirst( $text ) {
777 $newText = substr($text, 1);
778 return "&#$ord;$newText";
782 * Sets dest to source and returns the original value of dest
783 * If source is NULL, it just returns the value, it doesn't set the variable
785 function wfSetVar( &$dest, $source ) {
787 if ( !is_null( $source ) ) {
794 * As for wfSetVar except setting a bit
796 function wfSetBit( &$dest, $bit, $state = true ) {
797 $temp = (bool)($dest & $bit );
798 if ( !is_null( $state ) ) {
809 * This function takes two arrays as input, and returns a CGI-style string, e.g.
810 * "days=7&limit=100". Options in the first array override options in the second.
811 * Options set to "" will not be output.
813 function wfArrayToCGI( $array1, $array2 = NULL )
815 if ( !is_null( $array2 ) ) {
816 $array1 = $array1 +
$array2;
820 foreach ( $array1 as $key => $value ) {
821 if ( '' !== $value ) {
825 $cgi .= urlencode( $key ) . '=' . urlencode( $value );
832 * This is obsolete, use SquidUpdate::purge()
835 function wfPurgeSquidServers ($urlArr) {
836 SquidUpdate
::purge( $urlArr );
840 * Windows-compatible version of escapeshellarg()
841 * Windows doesn't recognise single-quotes in the shell, but the escapeshellarg()
842 * function puts single quotes in regardless of OS
844 function wfEscapeShellArg( ) {
845 $args = func_get_args();
848 foreach ( $args as $arg ) {
855 if ( wfIsWindows() ) {
856 $retVal .= '"' . str_replace( '"','\"', $arg ) . '"';
858 $retVal .= escapeshellarg( $arg );
865 * wfMerge attempts to merge differences between three texts.
866 * Returns true for a clean merge and false for failure or a conflict.
868 function wfMerge( $old, $mine, $yours, &$result ){
871 # This check may also protect against code injection in
872 # case of broken installations.
873 if(! file_exists( $wgDiff3 ) ){
874 wfDebug( "diff3 not found\n" );
878 # Make temporary files
880 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
881 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
882 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
884 fwrite( $oldtextFile, $old ); fclose( $oldtextFile );
885 fwrite( $mytextFile, $mine ); fclose( $mytextFile );
886 fwrite( $yourtextFile, $yours ); fclose( $yourtextFile );
888 # Check for a conflict
889 $cmd = $wgDiff3 . ' -a --overlap-only ' .
890 wfEscapeShellArg( $mytextName ) . ' ' .
891 wfEscapeShellArg( $oldtextName ) . ' ' .
892 wfEscapeShellArg( $yourtextName );
893 $handle = popen( $cmd, 'r' );
895 if( fgets( $handle, 1024 ) ){
903 $cmd = $wgDiff3 . ' -a -e --merge ' .
904 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
905 $handle = popen( $cmd, 'r' );
908 $data = fread( $handle, 8192 );
909 if ( strlen( $data ) == 0 ) {
915 unlink( $mytextName ); unlink( $oldtextName ); unlink( $yourtextName );
917 if ( $result === '' && $old !== '' && $conflict == false ) {
918 wfDebug( "Unexpected null result from diff3.\nCommand: $cmd\nOutput: " . `
$cmd 2>&1`
. "\n" );
927 function wfVarDump( $var ) {
929 $s = str_replace("\n","<br />\n", var_export( $var, true ) . "\n");
930 if ( headers_sent() ||
!@is_object
( $wgOut ) ) {
933 $wgOut->addHTML( $s );
938 * Provide a simple HTTP error.
940 function wfHttpError( $code, $label, $desc ) {
943 header( "HTTP/1.0 $code $label" );
944 header( "Status: $code $label" );
945 $wgOut->sendCacheControl();
947 header( 'Content-type: text/html' );
948 print "<html><head><title>" .
949 htmlspecialchars( $label ) .
950 "</title></head><body><h1>" .
951 htmlspecialchars( $label ) .
953 htmlspecialchars( $desc ) .
954 "</p></body></html>\n";
958 * Converts an Accept-* header into an array mapping string values to quality
961 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
962 # No arg means accept anything (per HTTP spec)
964 return array( $def => 1 );
969 $parts = explode( ',', $accept );
971 foreach( $parts as $part ) {
972 # FIXME: doesn't deal with params like 'text/html; level=1'
973 @list
( $value, $qpart ) = explode( ';', $part );
974 if( !isset( $qpart ) ) {
976 } elseif( preg_match( '/q\s*=\s*(\d*\.\d+)/', $qpart, $match ) ) {
977 $prefs[$value] = $match[1];
985 * Checks if a given MIME type matches any of the keys in the given
986 * array. Basic wildcards are accepted in the array keys.
988 * Returns the matching MIME type (or wildcard) if a match, otherwise
991 * @param string $type
992 * @param array $avail
996 function mimeTypeMatch( $type, $avail ) {
997 if( array_key_exists($type, $avail) ) {
1000 $parts = explode( '/', $type );
1001 if( array_key_exists( $parts[0] . '/*', $avail ) ) {
1002 return $parts[0] . '/*';
1003 } elseif( array_key_exists( '*/*', $avail ) ) {
1012 * Returns the 'best' match between a client's requested internet media types
1013 * and the server's list of available types. Each list should be an associative
1014 * array of type to preference (preference is a float between 0.0 and 1.0).
1015 * Wildcards in the types are acceptable.
1017 * @param array $cprefs Client's acceptable type list
1018 * @param array $sprefs Server's offered types
1021 * @todo FIXME: doesn't handle params like 'text/plain; charset=UTF-8'
1022 * XXX: generalize to negotiate other stuff
1024 function wfNegotiateType( $cprefs, $sprefs ) {
1027 foreach( array_keys($sprefs) as $type ) {
1028 $parts = explode( '/', $type );
1029 if( $parts[1] != '*' ) {
1030 $ckey = mimeTypeMatch( $type, $cprefs );
1032 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1037 foreach( array_keys( $cprefs ) as $type ) {
1038 $parts = explode( '/', $type );
1039 if( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
1040 $skey = mimeTypeMatch( $type, $sprefs );
1042 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1050 foreach( array_keys( $combine ) as $type ) {
1051 if( $combine[$type] > $bestq ) {
1053 $bestq = $combine[$type];
1062 * Returns an array where the values in the first array are replaced by the
1063 * values in the second array with the corresponding keys
1067 function wfArrayLookup( $a, $b ) {
1068 return array_flip( array_intersect( array_flip( $a ), array_keys( $b ) ) );
1072 * Convenience function; returns MediaWiki timestamp for the present time.
1075 function wfTimestampNow() {
1077 return wfTimestamp( TS_MW
, time() );
1081 * Reference-counted warning suppression
1083 function wfSuppressWarnings( $end = false ) {
1084 static $suppressCount = 0;
1085 static $originalLevel = false;
1088 if ( $suppressCount ) {
1090 if ( !$suppressCount ) {
1091 error_reporting( $originalLevel );
1095 if ( !$suppressCount ) {
1096 $originalLevel = error_reporting( E_ALL
& ~
( E_WARNING | E_NOTICE
) );
1103 * Restore error level to previous value
1105 function wfRestoreWarnings() {
1106 wfSuppressWarnings( true );
1109 # Autodetect, convert and provide timestamps of various types
1112 * Unix time - the number of seconds since 1970-01-01 00:00:00 UTC
1114 define('TS_UNIX', 0);
1117 * MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
1122 * MySQL DATETIME (YYYY-MM-DD HH:MM:SS)
1127 * RFC 2822 format, for E-mail and HTTP headers
1129 define('TS_RFC2822', 3);
1132 * An Exif timestamp (YYYY:MM:DD HH:MM:SS)
1134 * @link http://exif.org/Exif2-2.PDF The Exif 2.2 spec, see page 28 for the
1135 * DateTime tag and page 36 for the DateTimeOriginal and
1136 * DateTimeDigitized tags.
1138 define('TS_EXIF', 4);
1141 * Oracle format time.
1143 define('TS_ORACLE', 5);
1146 * @param mixed $outputtype A timestamp in one of the supported formats, the
1147 * function will autodetect which format is supplied
1148 and act accordingly.
1149 * @return string Time in the format specified in $outputtype
1151 function wfTimestamp($outputtype=TS_UNIX
,$ts=0) {
1155 } elseif (preg_match("/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)$/",$ts,$da)) {
1157 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1158 (int)$da[2],(int)$da[3],(int)$da[1]);
1159 } elseif (preg_match("/^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/",$ts,$da)) {
1161 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1162 (int)$da[2],(int)$da[3],(int)$da[1]);
1163 } elseif (preg_match("/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/",$ts,$da)) {
1165 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1166 (int)$da[2],(int)$da[3],(int)$da[1]);
1167 } elseif (preg_match("/^(\d{1,13})$/",$ts,$datearray)) {
1170 } elseif (preg_match('/^(\d{1,2})-(...)-(\d\d(\d\d)?) (\d\d)\.(\d\d)\.(\d\d)/', $ts, $da)) {
1172 $uts = strtotime(preg_replace('/(\d\d)\.(\d\d)\.(\d\d)(\.(\d+))?/', "$1:$2:$3",
1173 str_replace("+00:00", "UTC", $ts)));
1175 # Bogus value; fall back to the epoch...
1176 wfDebug("wfTimestamp() fed bogus time value: $outputtype; $ts\n");
1181 switch($outputtype) {
1185 return gmdate( 'YmdHis', $uts );
1187 return gmdate( 'Y-m-d H:i:s', $uts );
1188 // This shouldn't ever be used, but is included for completeness
1190 return gmdate( 'Y:m:d H:i:s', $uts );
1192 return gmdate( 'D, d M Y H:i:s', $uts ) . ' GMT';
1194 return gmdate( 'd-M-y h.i.s A', $uts) . ' +00:00';
1196 wfDebugDieBacktrace( 'wfTimestamp() called with illegal output type.');
1201 * Return a formatted timestamp, or null if input is null.
1202 * For dealing with nullable timestamp columns in the database.
1203 * @param int $outputtype
1207 function wfTimestampOrNull( $outputtype = TS_UNIX
, $ts = null ) {
1208 if( is_null( $ts ) ) {
1211 return wfTimestamp( $outputtype, $ts );
1216 * Check where as the operating system is Windows
1218 * @return bool True if it's windows, False otherwise.
1220 function wfIsWindows() {
1221 if (substr(php_uname(), 0, 7) == 'Windows') {
1229 * Swap two variables
1231 function swap( &$x, &$y ) {
1237 function wfGetSiteNotice() {
1238 global $wgSiteNotice, $wgTitle, $wgOut;
1239 $fname = 'wfGetSiteNotice';
1240 wfProfileIn( $fname );
1242 $notice = wfMsg( 'sitenotice' );
1243 if( $notice == '<sitenotice>' ||
$notice == '-' ) {
1246 if( $notice == '' ) {
1247 # We may also need to override a message with eg downtime info
1248 # FIXME: make this work!
1249 $notice = $wgSiteNotice;
1251 if($notice != '-' && $notice != '') {
1252 $specialparser = new Parser();
1253 $parserOutput = $specialparser->parse( $notice, $wgTitle, $wgOut->mParserOptions
, false );
1254 $notice = $parserOutput->getText();
1256 wfProfileOut( $fname );
1261 * Format an XML element with given attributes and, optionally, text content.
1262 * Element and attribute names are assumed to be ready for literal inclusion.
1263 * Strings are assumed to not contain XML-illegal characters; special
1264 * characters (<, >, &) are escaped but illegals are not touched.
1266 * @param string $element
1267 * @param array $attribs Name=>value pairs. Values will be escaped.
1268 * @param string $contents NULL to make an open tag only; '' for a contentless closed tag (default)
1271 function wfElement( $element, $attribs = null, $contents = '') {
1272 $out = '<' . $element;
1273 if( !is_null( $attribs ) ) {
1274 foreach( $attribs as $name => $val ) {
1275 $out .= ' ' . $name . '="' . htmlspecialchars( $val ) . '"';
1278 if( is_null( $contents ) ) {
1281 if( $contents == '' ) {
1285 $out .= htmlspecialchars( $contents );
1286 $out .= "</$element>";
1293 * Format an XML element as with wfElement(), but run text through the
1294 * UtfNormal::cleanUp() validator first to ensure that no invalid UTF-8
1297 * @param string $element
1298 * @param array $attribs Name=>value pairs. Values will be escaped.
1299 * @param string $contents NULL to make an open tag only; '' for a contentless closed tag (default)
1302 function wfElementClean( $element, $attribs = array(), $contents = '') {
1304 $attribs = array_map( array( 'UtfNormal', 'cleanUp' ), $attribs );
1307 $contents = UtfNormal
::cleanUp( $contents );
1309 return wfElement( $element, $attribs, $contents );
1313 function wfOpenElement( $element ) { return "<$element>"; }
1314 function wfCloseElement( $element ) { return "</$element>"; }
1317 * Create a namespace selector
1319 * @param mixed $selected The namespace which should be selected, default ''
1320 * @param string $allnamespaces Value of a special item denoting all namespaces. Null to not include (default)
1321 * @return Html string containing the namespace selector
1323 function &HTMLnamespaceselector($selected = '', $allnamespaces = null) {
1325 $s = "<select name='namespace' class='namespaceselector'>\n\t";
1326 $arr = $wgContLang->getFormattedNamespaces();
1327 if( !is_null($allnamespaces) ) {
1328 $arr = array($allnamespaces => wfMsgHtml('namespacesall')) +
$arr;
1330 foreach ($arr as $index => $name) {
1331 if ($index < NS_MAIN
) continue;
1333 $name = $index !== 0 ?
$name : wfMsgHtml('blanknamespace');
1335 if ($index === $selected) {
1336 $s .= wfElement("option",
1337 array("value" => $index, "selected" => "selected"),
1340 $s .= wfElement("option", array("value" => $index), $name);
1343 $s .= "\n</select>\n";
1347 /** Global singleton instance of MimeMagic. This is initialized on demand,
1348 * please always use the wfGetMimeMagic() function to get the instance.
1354 /** Factory functions for the global MimeMagic object.
1355 * This function always returns the same singleton instance of MimeMagic.
1356 * That objects will be instantiated on the first call to this function.
1357 * If needed, the MimeMagic.php file is automatically included by this function.
1358 * @return MimeMagic the global MimeMagic objects.
1360 function &wfGetMimeMagic() {
1361 global $wgMimeMagic;
1363 if (!is_null($wgMimeMagic)) {
1364 return $wgMimeMagic;
1367 if (!class_exists("MimeMagic")) {
1369 require_once("MimeMagic.php");
1372 $wgMimeMagic= new MimeMagic();
1374 return $wgMimeMagic;
1379 * Tries to get the system directory for temporary files.
1380 * The TMPDIR, TMP, and TEMP environment variables are checked in sequence,
1381 * and if none are set /tmp is returned as the generic Unix default.
1383 * NOTE: When possible, use the tempfile() function to create temporary
1384 * files to avoid race conditions on file creation, etc.
1388 function wfTempDir() {
1389 foreach( array( 'TMPDIR', 'TMP', 'TEMP' ) as $var ) {
1390 $tmp = getenv( $var );
1391 if( $tmp && file_exists( $tmp ) && is_dir( $tmp ) && is_writable( $tmp ) ) {
1395 # Hope this is Unix of some kind!
1400 * Make directory, and make all parent directories if they don't exist
1402 function wfMkdirParents( $fullDir, $mode ) {
1403 $parts = explode( '/', $fullDir );
1406 foreach ( $parts as $dir ) {
1407 $path .= $dir . '/';
1408 if ( !is_dir( $path ) ) {
1409 if ( !mkdir( $path, $mode ) ) {
1418 * Increment a statistics counter
1420 function wfIncrStats( $key ) {
1421 global $wgDBname, $wgMemc;
1422 $key = "$wgDBname:stats:$key";
1423 if ( is_null( $wgMemc->incr( $key ) ) ) {
1424 $wgMemc->add( $key, 1 );
1429 * @param mixed $nr The number to format
1430 * @param int $acc The number of digits after the decimal point, default 2
1431 * @param bool $round Whether or not to round the value, default true
1434 function wfPercent( $nr, $acc = 2, $round = true ) {
1435 $ret = sprintf( "%.${acc}f", $nr );
1436 return $round ?
round( $ret, $acc ) . '%' : "$ret%";
1440 * Encrypt a username/password.
1442 * @param string $userid ID of the user
1443 * @param string $password Password of the user
1444 * @return string Hashed password
1446 function wfEncryptPassword( $userid, $password ) {
1447 global $wgPasswordSalt;
1448 $p = md5( $password);
1451 return md5( "{$userid}-{$p}" );
1457 * Appends to second array if $value differs from that in $default
1459 function wfAppendToArrayIfNotDefault( $key, $value, $default, &$changed ) {
1460 if ( is_null( $changed ) ) {
1461 wfDebugDieBacktrace('GlobalFunctions::wfAppendToArrayIfNotDefault got null');
1463 if ( $default[$key] !== $value ) {
1464 $changed[$key] = $value;
1469 * Since wfMsg() and co suck, they don't return false if the message key they
1470 * looked up didn't exist but a XHTML string, this function checks for the
1471 * nonexistance of messages by looking at wfMsg() output
1473 * @param $msg The message key looked up
1474 * @param $wfMsgOut The output of wfMsg*()
1477 function wfEmptyMsg( $msg, $wfMsgOut ) {
1478 return $wfMsgOut === "<$msg>";