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.
181 * @param string $logGroup
182 * @param string $text
184 function wfDebugLog( $logGroup, $text ) {
185 global $wgDebugLogGroups, $wgDBname;
186 if( $text{strlen( $text ) - 1} != "\n" ) $text .= "\n";
187 if( isset( $wgDebugLogGroups[$logGroup] ) ) {
188 @error_log
( "$wgDBname: $text", 3, $wgDebugLogGroups[$logGroup] );
190 wfDebug( $text, true );
195 * Log for database errors
196 * @param string $text Database error message.
198 function wfLogDBError( $text ) {
199 global $wgDBerrorLog;
200 if ( $wgDBerrorLog ) {
201 $text = date('D M j G:i:s T Y') . "\t".$text;
202 error_log( $text, 3, $wgDBerrorLog );
209 function logProfilingData() {
210 global $wgRequestTime, $wgDebugLogFile, $wgDebugRawPage, $wgRequest;
211 global $wgProfiling, $wgProfileStack, $wgProfileLimit, $wgUser;
214 list( $usec, $sec ) = explode( ' ', $wgRequestTime );
215 $start = (float)$sec +
(float)$usec;
216 $elapsed = $now - $start;
217 if ( $wgProfiling ) {
218 $prof = wfGetProfilingOutput( $start, $elapsed );
220 if( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) )
221 $forward = ' forwarded for ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
222 if( !empty( $_SERVER['HTTP_CLIENT_IP'] ) )
223 $forward .= ' client IP ' . $_SERVER['HTTP_CLIENT_IP'];
224 if( !empty( $_SERVER['HTTP_FROM'] ) )
225 $forward .= ' from ' . $_SERVER['HTTP_FROM'];
227 $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
228 if( $wgUser->isAnon() )
230 $log = sprintf( "%s\t%04.3f\t%s\n",
231 gmdate( 'YmdHis' ), $elapsed,
232 urldecode( $_SERVER['REQUEST_URI'] . $forward ) );
233 if ( '' != $wgDebugLogFile && ( $wgRequest->getVal('action') != 'raw' ||
$wgDebugRawPage ) ) {
234 error_log( $log . $prof, 3, $wgDebugLogFile );
240 * Check if the wiki read-only lock file is present. This can be used to lock
241 * off editing functions, but doesn't guarantee that the database will not be
245 function wfReadOnly() {
246 global $wgReadOnlyFile, $wgReadOnly;
251 if ( '' == $wgReadOnlyFile ) {
255 // Set $wgReadOnly and unset $wgReadOnlyFile, for faster access next time
256 if ( is_file( $wgReadOnlyFile ) ) {
257 $wgReadOnly = file_get_contents( $wgReadOnlyFile );
261 $wgReadOnlyFile = '';
267 * Get a message from anywhere, for the current user language
271 function wfMsg( $key ) {
272 $args = func_get_args();
273 array_shift( $args );
274 return wfMsgReal( $key, $args, true );
278 * Get a message from anywhere, for the current global language
280 function wfMsgForContent( $key ) {
281 global $wgForceUIMsgAsContentMsg;
282 $args = func_get_args();
283 array_shift( $args );
285 if( is_array( $wgForceUIMsgAsContentMsg ) &&
286 in_array( $key, $wgForceUIMsgAsContentMsg ) )
288 return wfMsgReal( $key, $args, true, $forcontent );
292 * Get a message from the language file, for the UI elements
294 function wfMsgNoDB( $key ) {
295 $args = func_get_args();
296 array_shift( $args );
297 return wfMsgReal( $key, $args, false );
301 * Get a message from the language file, for the content
303 function wfMsgNoDBForContent( $key ) {
304 global $wgForceUIMsgAsContentMsg;
305 $args = func_get_args();
306 array_shift( $args );
308 if( is_array( $wgForceUIMsgAsContentMsg ) &&
309 in_array( $key, $wgForceUIMsgAsContentMsg ) )
311 return wfMsgReal( $key, $args, false, $forcontent );
316 * Really get a message
318 function wfMsgReal( $key, $args, $useDB, $forContent=false ) {
319 $fname = 'wfMsgReal';
320 wfProfileIn( $fname );
322 $message = wfMsgGetKey( $key, $useDB, $forContent );
323 $message = wfMsgReplaceArgs( $message, $args );
324 wfProfileOut( $fname );
329 * Fetch a message string value, but don't replace any keys yet.
332 * @param bool $forContent
336 function wfMsgGetKey( $key, $useDB, $forContent = false ) {
337 global $wgParser, $wgMsgParserOptions;
338 global $wgContLang, $wgLanguageCode;
339 global $wgMessageCache, $wgLang;
341 if( is_object( $wgMessageCache ) ) {
342 $message = $wgMessageCache->get( $key, $useDB, $forContent );
345 $lang = &$wgContLang;
350 wfSuppressWarnings();
352 if( is_object( $lang ) ) {
353 $message = $lang->getMessage( $key );
359 $message = Language
::getMessage($key);
360 if(strstr($message, '{{' ) !== false) {
361 $message = $wgParser->transformMsg($message, $wgMsgParserOptions);
368 * Replace message parameter keys on the given formatted output.
370 * @param string $message
375 function wfMsgReplaceArgs( $message, $args ) {
376 static $replacementKeys = array( '$1', '$2', '$3', '$4', '$5', '$6', '$7', '$8', '$9' );
378 # Fix windows line-endings
379 # Some messages are split with explode("\n", $msg)
380 $message = str_replace( "\r", '', $message );
383 if( count( $args ) ) {
384 $message = str_replace( $replacementKeys, $args, $message );
390 * Return an HTML-escaped version of a message.
391 * Parameter replacements, if any, are done *after* the HTML-escaping,
392 * so parameters may contain HTML (eg links or form controls). Be sure
393 * to pre-escape them if you really do want plaintext, or just wrap
394 * the whole thing in htmlspecialchars().
397 * @param string ... parameters
400 function wfMsgHtml( $key ) {
401 $args = func_get_args();
402 array_shift( $args );
403 return wfMsgReplaceArgs( htmlspecialchars( wfMsgGetKey( $key, true ) ), $args );
407 * Return an HTML version of message
408 * Parameter replacements, if any, are done *after* parsing the wiki-text message,
409 * so parameters may contain HTML (eg links or form controls). Be sure
410 * to pre-escape them if you really do want plaintext, or just wrap
411 * the whole thing in htmlspecialchars().
414 * @param string ... parameters
417 function wfMsgWikiHtml( $key ) {
419 $args = func_get_args();
420 array_shift( $args );
421 return wfMsgReplaceArgs( $wgOut->parse( wfMsgGetKey( $key, true ), /* can't be set to false */ true ), $args );
425 * Just like exit() but makes a note of it.
426 * Commits open transactions except if the error parameter is set
428 function wfAbruptExit( $error = false ){
429 global $wgLoadBalancer;
430 static $called = false;
436 if( function_exists( 'debug_backtrace' ) ){ // PHP >= 4.3
437 $bt = debug_backtrace();
438 for($i = 0; $i < count($bt) ; $i++
){
439 $file = $bt[$i]['file'];
440 $line = $bt[$i]['line'];
441 wfDebug("WARNING: Abrupt exit in $file at line $line\n");
444 wfDebug('WARNING: Abrupt exit\n');
447 $wgLoadBalancer->closeAll();
455 function wfErrorExit() {
456 wfAbruptExit( true );
460 * Die with a backtrace
461 * This is meant as a debugging aid to track down where bad data comes from.
462 * Shouldn't be used in production code except maybe in "shouldn't happen" areas.
464 * @param string $msg Message shown when dieing.
466 function wfDebugDieBacktrace( $msg = '' ) {
467 global $wgCommandLineMode;
469 $backtrace = wfBacktrace();
470 if ( $backtrace !== false ) {
471 if ( $wgCommandLineMode ) {
472 $msg .= "\nBacktrace:\n$backtrace";
474 $msg .= "\n<p>Backtrace:</p>\n$backtrace";
481 function wfBacktrace() {
482 global $wgCommandLineMode;
483 if ( !function_exists( 'debug_backtrace' ) ) {
487 if ( $wgCommandLineMode ) {
492 $backtrace = debug_backtrace();
493 foreach( $backtrace as $call ) {
494 if( isset( $call['file'] ) ) {
495 $f = explode( DIRECTORY_SEPARATOR
, $call['file'] );
496 $file = $f[count($f)-1];
500 if( isset( $call['line'] ) ) {
501 $line = $call['line'];
505 if ( $wgCommandLineMode ) {
506 $msg .= "$file line $line calls ";
508 $msg .= '<li>' . $file . ' line ' . $line . ' calls ';
510 if( !empty( $call['class'] ) ) $msg .= $call['class'] . '::';
511 $msg .= $call['function'] . '()';
513 if ( $wgCommandLineMode ) {
519 if ( $wgCommandLineMode ) {
529 /* Some generic result counters, pulled out of SearchEngine */
535 function wfShowingResults( $offset, $limit ) {
537 return wfMsg( 'showingresults', $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+
1 ) );
543 function wfShowingResultsNum( $offset, $limit, $num ) {
545 return wfMsg( 'showingresultsnum', $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+
1 ), $wgLang->formatNum( $num ) );
551 function wfViewPrevNext( $offset, $limit, $link, $query = '', $atend = false ) {
552 global $wgUser, $wgLang;
553 $fmtLimit = $wgLang->formatNum( $limit );
554 $prev = wfMsg( 'prevn', $fmtLimit );
555 $next = wfMsg( 'nextn', $fmtLimit );
557 if( is_object( $link ) ) {
560 $title = Title
::newFromText( $link );
561 if( is_null( $title ) ) {
566 $sk = $wgUser->getSkin();
567 if ( 0 != $offset ) {
568 $po = $offset - $limit;
569 if ( $po < 0 ) { $po = 0; }
570 $q = "limit={$limit}&offset={$po}";
571 if ( '' != $query ) { $q .= '&'.$query; }
572 $plink = '<a href="' . $title->escapeLocalUrl( $q ) . "\">{$prev}</a>";
573 } else { $plink = $prev; }
575 $no = $offset +
$limit;
576 $q = 'limit='.$limit.'&offset='.$no;
577 if ( '' != $query ) { $q .= '&'.$query; }
582 $nlink = '<a href="' . $title->escapeLocalUrl( $q ) . "\">{$next}</a>";
584 $nums = wfNumLink( $offset, 20, $title, $query ) . ' | ' .
585 wfNumLink( $offset, 50, $title, $query ) . ' | ' .
586 wfNumLink( $offset, 100, $title, $query ) . ' | ' .
587 wfNumLink( $offset, 250, $title, $query ) . ' | ' .
588 wfNumLink( $offset, 500, $title, $query );
590 return wfMsg( 'viewprevnext', $plink, $nlink, $nums );
596 function wfNumLink( $offset, $limit, &$title, $query = '' ) {
597 global $wgUser, $wgLang;
598 if ( '' == $query ) { $q = ''; }
599 else { $q = $query.'&'; }
600 $q .= 'limit='.$limit.'&offset='.$offset;
602 $fmtLimit = $wgLang->formatNum( $limit );
603 $s = '<a href="' . $title->escapeLocalUrl( $q ) . "\">{$fmtLimit}</a>";
609 * @todo FIXME: we may want to blacklist some broken browsers
611 * @return bool Whereas client accept gzip compression
613 function wfClientAcceptsGzip() {
616 # FIXME: we may want to blacklist some broken browsers
618 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
619 $_SERVER['HTTP_ACCEPT_ENCODING'],
621 if( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) return false;
622 wfDebug( " accepts gzip\n" );
630 * Yay, more global functions!
632 function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) {
634 return $wgRequest->getLimitOffset( $deflimit, $optionname );
638 * Escapes the given text so that it may be output using addWikiText()
639 * without any linking, formatting, etc. making its way through. This
640 * is achieved by substituting certain characters with HTML entities.
641 * As required by the callers, <nowiki> is not used. It currently does
642 * not filter out characters which have special meaning only at the
643 * start of a line, such as "*".
645 * @param string $text Text to be escaped
647 function wfEscapeWikiText( $text ) {
649 array( '[', '|', '\'', 'ISBN ' , '://' , "\n=", '{{' ),
650 array( '[', '|', ''', 'ISBN ', '://' , "\n=", '{{' ),
651 htmlspecialchars($text) );
658 function wfQuotedPrintable( $string, $charset = '' ) {
659 # Probably incomplete; see RFC 2045
660 if( empty( $charset ) ) {
661 global $wgInputEncoding;
662 $charset = $wgInputEncoding;
664 $charset = strtoupper( $charset );
665 $charset = str_replace( 'ISO-8859', 'ISO8859', $charset ); // ?
667 $illegal = '\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\xff=';
668 $replace = $illegal . '\t ?_';
669 if( !preg_match( "/[$illegal]/", $string ) ) return $string;
670 $out = "=?$charset?Q?";
671 $out .= preg_replace( "/([$replace])/e", 'sprintf("=%02X",ord("$1"))', $string );
677 * Returns an escaped string suitable for inclusion in a string literal
678 * for JavaScript source code.
679 * Illegal control characters are assumed not to be present.
681 * @param string $string
684 function wfEscapeJsString( $string ) {
685 // See ECMA 262 section 7.8.4 for string literal format
693 # To avoid closing the element or CDATA section
697 return strtr( $string, $pairs );
705 $st = explode( ' ', microtime() );
706 return (float)$st[0] +
(float)$st[1];
710 * Changes the first character to an HTML entity
712 function wfHtmlEscapeFirst( $text ) {
714 $newText = substr($text, 1);
715 return "&#$ord;$newText";
719 * Sets dest to source and returns the original value of dest
720 * If source is NULL, it just returns the value, it doesn't set the variable
722 function wfSetVar( &$dest, $source ) {
724 if ( !is_null( $source ) ) {
731 * As for wfSetVar except setting a bit
733 function wfSetBit( &$dest, $bit, $state = true ) {
734 $temp = (bool)($dest & $bit );
735 if ( !is_null( $state ) ) {
746 * This function takes two arrays as input, and returns a CGI-style string, e.g.
747 * "days=7&limit=100". Options in the first array override options in the second.
748 * Options set to "" will not be output.
750 function wfArrayToCGI( $array1, $array2 = NULL )
752 if ( !is_null( $array2 ) ) {
753 $array1 = $array1 +
$array2;
757 foreach ( $array1 as $key => $value ) {
758 if ( '' !== $value ) {
762 $cgi .= urlencode( $key ) . '=' . urlencode( $value );
769 * This is obsolete, use SquidUpdate::purge()
772 function wfPurgeSquidServers ($urlArr) {
773 SquidUpdate
::purge( $urlArr );
777 * Windows-compatible version of escapeshellarg()
778 * Windows doesn't recognise single-quotes in the shell, but the escapeshellarg()
779 * function puts single quotes in regardless of OS
781 function wfEscapeShellArg( ) {
782 $args = func_get_args();
785 foreach ( $args as $arg ) {
792 if ( wfIsWindows() ) {
793 $retVal .= '"' . str_replace( '"','\"', $arg ) . '"';
795 $retVal .= escapeshellarg( $arg );
802 * wfMerge attempts to merge differences between three texts.
803 * Returns true for a clean merge and false for failure or a conflict.
805 function wfMerge( $old, $mine, $yours, &$result ){
808 # This check may also protect against code injection in
809 # case of broken installations.
810 if(! file_exists( $wgDiff3 ) ){
814 # Make temporary files
816 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
817 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
818 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
820 fwrite( $oldtextFile, $old ); fclose( $oldtextFile );
821 fwrite( $mytextFile, $mine ); fclose( $mytextFile );
822 fwrite( $yourtextFile, $yours ); fclose( $yourtextFile );
824 # Check for a conflict
825 $cmd = wfEscapeShellArg( $wgDiff3 ) . ' -a --overlap-only ' .
826 wfEscapeShellArg( $mytextName ) . ' ' .
827 wfEscapeShellArg( $oldtextName ) . ' ' .
828 wfEscapeShellArg( $yourtextName );
829 $handle = popen( $cmd, 'r' );
831 if( fgets( $handle, 1024 ) ){
839 $cmd = wfEscapeShellArg( $wgDiff3 ) . ' -a -e --merge ' .
840 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
841 $handle = popen( $cmd, 'r' );
844 $data = fread( $handle, 8192 );
845 if ( strlen( $data ) == 0 ) {
851 unlink( $mytextName ); unlink( $oldtextName ); unlink( $yourtextName );
858 function wfVarDump( $var ) {
860 $s = str_replace("\n","<br />\n", var_export( $var, true ) . "\n");
861 if ( headers_sent() ||
!@is_object
( $wgOut ) ) {
864 $wgOut->addHTML( $s );
869 * Provide a simple HTTP error.
871 function wfHttpError( $code, $label, $desc ) {
874 header( "HTTP/1.0 $code $label" );
875 header( "Status: $code $label" );
876 $wgOut->sendCacheControl();
878 header( 'Content-type: text/html' );
879 print "<html><head><title>" .
880 htmlspecialchars( $label ) .
881 "</title></head><body><h1>" .
882 htmlspecialchars( $label ) .
884 htmlspecialchars( $desc ) .
885 "</p></body></html>\n";
889 * Converts an Accept-* header into an array mapping string values to quality
892 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
893 # No arg means accept anything (per HTTP spec)
895 return array( $def => 1 );
900 $parts = explode( ',', $accept );
902 foreach( $parts as $part ) {
903 # FIXME: doesn't deal with params like 'text/html; level=1'
904 @list
( $value, $qpart ) = explode( ';', $part );
905 if( !isset( $qpart ) ) {
907 } elseif( preg_match( '/q\s*=\s*(\d*\.\d+)/', $qpart, $match ) ) {
908 $prefs[$value] = $match[1];
916 * Checks if a given MIME type matches any of the keys in the given
917 * array. Basic wildcards are accepted in the array keys.
919 * Returns the matching MIME type (or wildcard) if a match, otherwise
922 * @param string $type
923 * @param array $avail
927 function mimeTypeMatch( $type, $avail ) {
928 if( array_key_exists($type, $avail) ) {
931 $parts = explode( '/', $type );
932 if( array_key_exists( $parts[0] . '/*', $avail ) ) {
933 return $parts[0] . '/*';
934 } elseif( array_key_exists( '*/*', $avail ) ) {
943 * Returns the 'best' match between a client's requested internet media types
944 * and the server's list of available types. Each list should be an associative
945 * array of type to preference (preference is a float between 0.0 and 1.0).
946 * Wildcards in the types are acceptable.
948 * @param array $cprefs Client's acceptable type list
949 * @param array $sprefs Server's offered types
952 * @todo FIXME: doesn't handle params like 'text/plain; charset=UTF-8'
953 * XXX: generalize to negotiate other stuff
955 function wfNegotiateType( $cprefs, $sprefs ) {
958 foreach( array_keys($sprefs) as $type ) {
959 $parts = explode( '/', $type );
960 if( $parts[1] != '*' ) {
961 $ckey = mimeTypeMatch( $type, $cprefs );
963 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
968 foreach( array_keys( $cprefs ) as $type ) {
969 $parts = explode( '/', $type );
970 if( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
971 $skey = mimeTypeMatch( $type, $sprefs );
973 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
981 foreach( array_keys( $combine ) as $type ) {
982 if( $combine[$type] > $bestq ) {
984 $bestq = $combine[$type];
993 * Returns an array where the values in the first array are replaced by the
994 * values in the second array with the corresponding keys
998 function wfArrayLookup( $a, $b ) {
999 return array_flip( array_intersect( array_flip( $a ), array_keys( $b ) ) );
1003 * Convenience function; returns MediaWiki timestamp for the present time.
1006 function wfTimestampNow() {
1008 return wfTimestamp( TS_MW
, time() );
1012 * Reference-counted warning suppression
1014 function wfSuppressWarnings( $end = false ) {
1015 static $suppressCount = 0;
1016 static $originalLevel = false;
1019 if ( $suppressCount ) {
1021 if ( !$suppressCount ) {
1022 error_reporting( $originalLevel );
1026 if ( !$suppressCount ) {
1027 $originalLevel = error_reporting( E_ALL
& ~
( E_WARNING | E_NOTICE
) );
1034 * Restore error level to previous value
1036 function wfRestoreWarnings() {
1037 wfSuppressWarnings( true );
1040 # Autodetect, convert and provide timestamps of various types
1043 * Unix time - the number of seconds since 1970-01-01 00:00:00 UTC
1045 define('TS_UNIX', 0);
1048 * MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
1053 * MySQL DATETIME (YYYY-MM-DD HH:MM:SS)
1058 * RFC 2822 format, for E-mail and HTTP headers
1060 define('TS_RFC2822', 3);
1063 * An Exif timestamp (YYYY:MM:DD HH:MM:SS)
1065 * @link http://exif.org/Exif2-2.PDF The Exif 2.2 spec, see page 28 for the
1066 * DateTime tag and page 36 for the DateTimeOriginal and
1067 * DateTimeDigitized tags.
1069 define('TS_EXIF', 4);
1072 * Oracle format time.
1074 define('TS_ORACLE', 5);
1077 * @param mixed $outputtype A timestamp in one of the supported formats, the
1078 * function will autodetect which format is supplied
1079 and act accordingly.
1080 * @return string Time in the format specified in $outputtype
1082 function wfTimestamp($outputtype=TS_UNIX
,$ts=0) {
1085 } elseif (preg_match("/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)$/",$ts,$da)) {
1087 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1088 (int)$da[2],(int)$da[3],(int)$da[1]);
1089 } elseif (preg_match("/^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/",$ts,$da)) {
1091 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1092 (int)$da[2],(int)$da[3],(int)$da[1]);
1093 } elseif (preg_match("/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/",$ts,$da)) {
1095 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1096 (int)$da[2],(int)$da[3],(int)$da[1]);
1097 } elseif (preg_match("/^(\d{1,13})$/",$ts,$datearray)) {
1100 } elseif (preg_match('/^(\d{1,2})-(...)-(\d\d(\d\d)?) (\d\d)\.(\d\d)\.(\d\d)/', $ts, $da)) {
1102 $uts = strtotime(preg_replace('/(\d\d)\.(\d\d)\.(\d\d)(\.(\d+))?/', "$1:$2:$3",
1103 str_replace("+00:00", "UTC", $ts)));
1105 # Bogus value; fall back to the epoch...
1106 wfDebug("wfTimestamp() fed bogus time value: $outputtype; $ts\n");
1111 switch($outputtype) {
1115 return gmdate( 'YmdHis', $uts );
1117 return gmdate( 'Y-m-d H:i:s', $uts );
1118 // This shouldn't ever be used, but is included for completeness
1120 return gmdate( 'Y:m:d H:i:s', $uts );
1122 return gmdate( 'D, d M Y H:i:s', $uts ) . ' GMT';
1124 return gmdate( 'd-M-y h.i.s A', $uts) . ' +00:00';
1126 wfDebugDieBacktrace( 'wfTimestamp() called with illegal output type.');
1131 * Return a formatted timestamp, or null if input is null.
1132 * For dealing with nullable timestamp columns in the database.
1133 * @param int $outputtype
1137 function wfTimestampOrNull( $outputtype = TS_UNIX
, $ts = null ) {
1138 if( is_null( $ts ) ) {
1141 return wfTimestamp( $outputtype, $ts );
1146 * Check where as the operating system is Windows
1148 * @return bool True if it's windows, False otherwise.
1150 function wfIsWindows() {
1151 if (substr(php_uname(), 0, 7) == 'Windows') {
1159 * Swap two variables
1161 function swap( &$x, &$y ) {
1167 function wfGetSiteNotice() {
1168 global $wgSiteNotice, $wgTitle, $wgOut;
1169 $fname = 'wfGetSiteNotice';
1170 wfProfileIn( $fname );
1172 $notice = wfMsg( 'sitenotice' );
1173 if( $notice == '<sitenotice>' ||
$notice == '-' ) {
1176 if( $notice == '' ) {
1177 # We may also need to override a message with eg downtime info
1178 # FIXME: make this work!
1179 $notice = $wgSiteNotice;
1181 if($notice != '-' && $notice != '') {
1182 $specialparser = new Parser();
1183 $parserOutput = $specialparser->parse( $notice, $wgTitle, $wgOut->mParserOptions
, false );
1184 $notice = $parserOutput->getText();
1186 wfProfileOut( $fname );
1191 * Format an XML element with given attributes and, optionally, text content.
1192 * Element and attribute names are assumed to be ready for literal inclusion.
1193 * Strings are assumed to not contain XML-illegal characters; special
1194 * characters (<, >, &) are escaped but illegals are not touched.
1196 * @param string $element
1197 * @param array $attribs Name=>value pairs. Values will be escaped.
1198 * @param string $contents NULL to make an open tag only; '' for a contentless closed tag (default)
1201 function wfElement( $element, $attribs = null, $contents = '') {
1202 $out = '<' . $element;
1203 if( !is_null( $attribs ) ) {
1204 foreach( $attribs as $name => $val ) {
1205 $out .= ' ' . $name . '="' . htmlspecialchars( $val ) . '"';
1208 if( is_null( $contents ) ) {
1211 if( $contents == '' ) {
1215 $out .= htmlspecialchars( $contents );
1216 $out .= "</$element>";
1223 * Format an XML element as with wfElement(), but run text through the
1224 * UtfNormal::cleanUp() validator first to ensure that no invalid UTF-8
1227 * @param string $element
1228 * @param array $attribs Name=>value pairs. Values will be escaped.
1229 * @param string $contents NULL to make an open tag only; '' for a contentless closed tag (default)
1232 function wfElementClean( $element, $attribs = array(), $contents = '') {
1234 $attribs = array_map( array( 'UtfNormal', 'cleanUp' ), $attribs );
1237 $contents = UtfNormal
::cleanUp( $contents );
1239 return wfElement( $element, $attribs, $contents );
1243 * Create a namespace selector
1245 * @param mixed $selected The namespace which should be selected, default ''
1246 * @param string $allnamespaces Value of a special item denoting all namespaces. Null to not include (default)
1247 * @return Html string containing the namespace selector
1249 function &HTMLnamespaceselector($selected = '', $allnamespaces = null) {
1251 $s = "<select name='namespace' class='namespaceselector'>\n";
1252 $arr = $wgContLang->getFormattedNamespaces();
1253 if( !is_null($allnamespaces) ) {
1254 $arr = array($allnamespaces => wfMsgHtml('namespacesall')) +
$arr;
1256 foreach ($arr as $index => $name) {
1257 if ($index < NS_MAIN
) continue;
1259 $name = $index !== 0 ?
$name : wfMsgHtml('blanknamespace');
1261 if ($index === $selected) {
1262 $s .= wfElement("option",
1263 array("value" => $index, "selected" => "selected"),
1266 $s .= wfElement("option", array("value" => $index), $name);
1269 $s .= "</select>\n";
1273 /** Global singleton instance of MimeMagic. This is initialized on demand,
1274 * please always use the wfGetMimeMagic() function to get the instance.
1280 /** Factory functions for the global MimeMagic object.
1281 * This function always returns the same singleton instance of MimeMagic.
1282 * That objects will be instantiated on the first call to this function.
1283 * If needed, the MimeMagic.php file is automatically included by this function.
1284 * @return MimeMagic the global MimeMagic objects.
1286 function &wfGetMimeMagic() {
1287 global $wgMimeMagic;
1289 if (!is_null($wgMimeMagic)) {
1290 return $wgMimeMagic;
1293 if (!class_exists("MimeMagic")) {
1295 require_once("MimeMagic.php");
1298 $wgMimeMagic= new MimeMagic();
1300 return $wgMimeMagic;
1305 * Tries to get the system directory for temporary files.
1306 * The TMPDIR, TMP, and TEMP environment variables are checked in sequence,
1307 * and if none are set /tmp is returned as the generic Unix default.
1309 * NOTE: When possible, use the tempfile() function to create temporary
1310 * files to avoid race conditions on file creation, etc.
1314 function wfTempDir() {
1315 foreach( array( 'TMPDIR', 'TMP', 'TEMP' ) as $var ) {
1316 $tmp = getenv( $var );
1317 if( $tmp && file_exists( $tmp ) && is_dir( $tmp ) && is_writable( $tmp ) ) {
1321 # Hope this is Unix of some kind!
1326 * Make directory, and make all parent directories if they don't exist
1328 function wfMkdirParents( $fullDir, $mode ) {
1329 $parts = explode( '/', $fullDir );
1332 foreach ( $parts as $dir ) {
1333 $path .= $dir . '/';
1334 if ( !is_dir( $path ) ) {
1335 if ( !mkdir( $path, $mode ) ) {
1344 * Increment a statistics counter
1346 function wfIncrStats( $key ) {
1347 global $wgDBname, $wgMemc;
1348 $key = "$wgDBname:stats:$key";
1349 if ( is_null( $wgMemc->incr( $key ) ) ) {
1350 $wgMemc->add( $key, 1 );
1355 * @param mixed $nr The number to format
1356 * @param int $acc The number of digits after the decimal point, default 2
1357 * @param bool $round Whether or not to round the value, default true
1360 function wfPercent( $nr, $acc = 2, $round = true ) {
1361 $ret = sprintf( "%.${acc}f", $nr );
1362 return $round ?
round( $ret, $acc ) . '%' : "$ret%";
1366 * Encrypt a username/password.
1368 * @param string $userid ID of the user
1369 * @param string $password Password of the user
1370 * @return string Hashed password
1372 function wfEncryptPassword( $userid, $password ) {
1373 global $wgPasswordSalt;
1374 $p = md5( $password);
1377 return md5( "{$userid}-{$p}" );
1383 * Appends to second array if $value differs from that in $default
1385 function wfAppendToArrayIfNotDefault( $key, $value, $default, &$changed ) {
1386 if ( is_null( $changed ) ) {
1387 wfDebugDieBacktrace('GlobalFunctions::wfAppendToArrayIfNotDefault got null');
1389 if ( $default[$key] !== $value ) {
1390 $changed[$key] = $value;
1395 * Since wfMsg() and co suck, they don't return false if the message key they
1396 * looked up didn't exist but a XHTML string, this function checks for the
1397 * nonexistance of messages by looking at wfMsg() output
1399 * @param $msg The message key looked up
1400 * @param $wfMsgOut The output of wfMsg*()
1403 function wfNoMsg( $msg, $wfMsgOut ) {
1404 return $wfMsgOut === "<$msg>";