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;
248 if ( !is_null( $wgReadOnly ) ) {
249 return (bool)$wgReadOnly;
251 if ( '' == $wgReadOnlyFile ) {
255 // Set $wgReadOnly for faster access next time
256 if ( is_file( $wgReadOnlyFile ) ) {
257 $wgReadOnly = file_get_contents( $wgReadOnlyFile );
266 * Get a message from anywhere, for the current user language
270 function wfMsg( $key ) {
271 $args = func_get_args();
272 array_shift( $args );
273 return wfMsgReal( $key, $args, true );
277 * Get a message from anywhere, for the current global language
279 function wfMsgForContent( $key ) {
280 global $wgForceUIMsgAsContentMsg;
281 $args = func_get_args();
282 array_shift( $args );
284 if( is_array( $wgForceUIMsgAsContentMsg ) &&
285 in_array( $key, $wgForceUIMsgAsContentMsg ) )
287 return wfMsgReal( $key, $args, true, $forcontent );
291 * Get a message from the language file, for the UI elements
293 function wfMsgNoDB( $key ) {
294 $args = func_get_args();
295 array_shift( $args );
296 return wfMsgReal( $key, $args, false );
300 * Get a message from the language file, for the content
302 function wfMsgNoDBForContent( $key ) {
303 global $wgForceUIMsgAsContentMsg;
304 $args = func_get_args();
305 array_shift( $args );
307 if( is_array( $wgForceUIMsgAsContentMsg ) &&
308 in_array( $key, $wgForceUIMsgAsContentMsg ) )
310 return wfMsgReal( $key, $args, false, $forcontent );
315 * Really get a message
317 function wfMsgReal( $key, $args, $useDB, $forContent=false ) {
318 $fname = 'wfMsgReal';
319 wfProfileIn( $fname );
321 $message = wfMsgGetKey( $key, $useDB, $forContent );
322 $message = wfMsgReplaceArgs( $message, $args );
323 wfProfileOut( $fname );
328 * Fetch a message string value, but don't replace any keys yet.
331 * @param bool $forContent
335 function wfMsgGetKey( $key, $useDB, $forContent = false ) {
336 global $wgParser, $wgMsgParserOptions;
337 global $wgContLang, $wgLanguageCode;
338 global $wgMessageCache, $wgLang;
340 if( is_object( $wgMessageCache ) ) {
341 $message = $wgMessageCache->get( $key, $useDB, $forContent );
344 $lang = &$wgContLang;
349 wfSuppressWarnings();
351 if( is_object( $lang ) ) {
352 $message = $lang->getMessage( $key );
358 $message = Language::getMessage($key);
359 if(strstr($message, '{{' ) !== false) {
360 $message = $wgParser->transformMsg($message, $wgMsgParserOptions);
367 * Replace message parameter keys on the given formatted output.
369 * @param string $message
374 function wfMsgReplaceArgs( $message, $args ) {
375 static $replacementKeys = array( '$1', '$2', '$3', '$4', '$5', '$6', '$7', '$8', '$9' );
377 # Fix windows line-endings
378 # Some messages are split with explode("\n", $msg)
379 $message = str_replace( "\r", '', $message );
382 if( count( $args ) ) {
383 $message = str_replace( $replacementKeys, $args, $message );
389 * Return an HTML-escaped version of a message.
390 * Parameter replacements, if any, are done *after* the HTML-escaping,
391 * so parameters may contain HTML (eg links or form controls). Be sure
392 * to pre-escape them if you really do want plaintext, or just wrap
393 * the whole thing in htmlspecialchars().
396 * @param string ... parameters
399 function wfMsgHtml( $key ) {
400 $args = func_get_args();
401 array_shift( $args );
402 return wfMsgReplaceArgs( htmlspecialchars( wfMsgGetKey( $key, true ) ), $args );
406 * Just like exit() but makes a note of it.
407 * Commits open transactions except if the error parameter is set
409 function wfAbruptExit( $error = false ){
410 global $wgLoadBalancer;
411 static $called = false;
417 if( function_exists( 'debug_backtrace' ) ){ // PHP >= 4.3
418 $bt = debug_backtrace();
419 for($i = 0; $i < count($bt) ; $i++){
420 $file = isset($bt[$i]['file']) ? $bt[$i]['file'] : "unknown";
421 $line = isset($bt[$i]['line']) ? $bt[$i]['line'] : "unknown";
422 wfDebug("WARNING: Abrupt exit in $file at line $line\n");
425 wfDebug('WARNING: Abrupt exit\n');
428 $wgLoadBalancer->closeAll();
436 function wfErrorExit() {
437 wfAbruptExit( true );
441 * Die with a backtrace
442 * This is meant as a debugging aid to track down where bad data comes from.
443 * Shouldn't be used in production code except maybe in "shouldn't happen" areas.
445 * @param string $msg Message shown when dieing.
447 function wfDebugDieBacktrace( $msg = '' ) {
448 global $wgCommandLineMode;
450 $backtrace = wfBacktrace();
451 if ( $backtrace !== false ) {
452 if ( $wgCommandLineMode ) {
453 $msg .= "\nBacktrace:\n$backtrace";
455 $msg .= "\n<p>Backtrace:</p>\n$backtrace";
462 function wfBacktrace() {
463 global $wgCommandLineMode;
464 if ( !function_exists( 'debug_backtrace' ) ) {
468 if ( $wgCommandLineMode ) {
473 $backtrace = debug_backtrace();
474 foreach( $backtrace as $call ) {
475 if( isset( $call['file'] ) ) {
476 $f = explode( DIRECTORY_SEPARATOR, $call['file'] );
477 $file = $f[count($f)-1];
481 if( isset( $call['line'] ) ) {
482 $line = $call['line'];
486 if ( $wgCommandLineMode ) {
487 $msg .= "$file line $line calls ";
489 $msg .= '<li>' . $file . ' line ' . $line . ' calls ';
491 if( !empty( $call['class'] ) ) $msg .= $call['class'] . '::';
492 $msg .= $call['function'] . '()';
494 if ( $wgCommandLineMode ) {
500 if ( $wgCommandLineMode ) {
510 /* Some generic result counters, pulled out of SearchEngine */
516 function wfShowingResults( $offset, $limit ) {
518 return wfMsg( 'showingresults', $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+1 ) );
524 function wfShowingResultsNum( $offset, $limit, $num ) {
526 return wfMsg( 'showingresultsnum', $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+1 ), $wgLang->formatNum( $num ) );
532 function wfViewPrevNext( $offset, $limit, $link, $query = '', $atend = false ) {
533 global $wgUser, $wgLang;
534 $fmtLimit = $wgLang->formatNum( $limit );
535 $prev = wfMsg( 'prevn', $fmtLimit );
536 $next = wfMsg( 'nextn', $fmtLimit );
538 if( is_object( $link ) ) {
541 $title = Title::newFromText( $link );
542 if( is_null( $title ) ) {
547 $sk = $wgUser->getSkin();
548 if ( 0 != $offset ) {
549 $po = $offset - $limit;
550 if ( $po < 0 ) { $po = 0; }
551 $q = "limit={$limit}&offset={$po}";
552 if ( '' != $query ) { $q .= '&'.$query; }
553 $plink = '<a href="' . $title->escapeLocalUrl( $q ) . "\">{$prev}</a>";
554 } else { $plink = $prev; }
556 $no = $offset + $limit;
557 $q = 'limit='.$limit.'&offset='.$no;
558 if ( '' != $query ) { $q .= '&'.$query; }
563 $nlink = '<a href="' . $title->escapeLocalUrl( $q ) . "\">{$next}</a>";
565 $nums = wfNumLink( $offset, 20, $title, $query ) . ' | ' .
566 wfNumLink( $offset, 50, $title, $query ) . ' | ' .
567 wfNumLink( $offset, 100, $title, $query ) . ' | ' .
568 wfNumLink( $offset, 250, $title, $query ) . ' | ' .
569 wfNumLink( $offset, 500, $title, $query );
571 return wfMsg( 'viewprevnext', $plink, $nlink, $nums );
577 function wfNumLink( $offset, $limit, &$title, $query = '' ) {
578 global $wgUser, $wgLang;
579 if ( '' == $query ) { $q = ''; }
580 else { $q = $query.'&'; }
581 $q .= 'limit='.$limit.'&offset='.$offset;
583 $fmtLimit = $wgLang->formatNum( $limit );
584 $s = '<a href="' . $title->escapeLocalUrl( $q ) . "\">{$fmtLimit}</a>";
590 * @todo FIXME: we may want to blacklist some broken browsers
592 * @return bool Whereas client accept gzip compression
594 function wfClientAcceptsGzip() {
597 # FIXME: we may want to blacklist some broken browsers
599 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
600 $_SERVER['HTTP_ACCEPT_ENCODING'],
602 if( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) return false;
603 wfDebug( " accepts gzip\n" );
611 * Yay, more global functions!
613 function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) {
615 return $wgRequest->getLimitOffset( $deflimit, $optionname );
619 * Escapes the given text so that it may be output using addWikiText()
620 * without any linking, formatting, etc. making its way through. This
621 * is achieved by substituting certain characters with HTML entities.
622 * As required by the callers, <nowiki> is not used. It currently does
623 * not filter out characters which have special meaning only at the
624 * start of a line, such as "*".
626 * @param string $text Text to be escaped
628 function wfEscapeWikiText( $text ) {
630 array( '[', '|', '\'', 'ISBN ' , '://' , "\n=", '{{' ),
631 array( '[', '|', ''', 'ISBN ', '://' , "\n=", '{{' ),
632 htmlspecialchars($text) );
639 function wfQuotedPrintable( $string, $charset = '' ) {
640 # Probably incomplete; see RFC 2045
641 if( empty( $charset ) ) {
642 global $wgInputEncoding;
643 $charset = $wgInputEncoding;
645 $charset = strtoupper( $charset );
646 $charset = str_replace( 'ISO-8859', 'ISO8859', $charset ); // ?
648 $illegal = '\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\xff=';
649 $replace = $illegal . '\t ?_';
650 if( !preg_match( "/[$illegal]/", $string ) ) return $string;
651 $out = "=?$charset?Q?";
652 $out .= preg_replace( "/([$replace])/e", 'sprintf("=%02X",ord("$1"))', $string );
658 * Returns an escaped string suitable for inclusion in a string literal
659 * for JavaScript source code.
660 * Illegal control characters are assumed not to be present.
662 * @param string $string
665 function wfEscapeJsString( $string ) {
666 // See ECMA 262 section 7.8.4 for string literal format
674 # To avoid closing the element or CDATA section
678 return strtr( $string, $pairs );
686 $st = explode( ' ', microtime() );
687 return (float)$st[0] + (float)$st[1];
691 * Changes the first character to an HTML entity
693 function wfHtmlEscapeFirst( $text ) {
695 $newText = substr($text, 1);
696 return "&#$ord;$newText";
700 * Sets dest to source and returns the original value of dest
701 * If source is NULL, it just returns the value, it doesn't set the variable
703 function wfSetVar( &$dest, $source ) {
705 if ( !is_null( $source ) ) {
712 * As for wfSetVar except setting a bit
714 function wfSetBit( &$dest, $bit, $state = true ) {
715 $temp = (bool)($dest & $bit );
716 if ( !is_null( $state ) ) {
727 * This function takes two arrays as input, and returns a CGI-style string, e.g.
728 * "days=7&limit=100". Options in the first array override options in the second.
729 * Options set to "" will not be output.
731 function wfArrayToCGI( $array1, $array2 = NULL )
733 if ( !is_null( $array2 ) ) {
734 $array1 = $array1 + $array2;
738 foreach ( $array1 as $key => $value ) {
739 if ( '' !== $value ) {
743 $cgi .= urlencode( $key ) . '=' . urlencode( $value );
750 * This is obsolete, use SquidUpdate::purge()
753 function wfPurgeSquidServers ($urlArr) {
754 SquidUpdate::purge( $urlArr );
758 * Windows-compatible version of escapeshellarg()
759 * Windows doesn't recognise single-quotes in the shell, but the escapeshellarg()
760 * function puts single quotes in regardless of OS
762 function wfEscapeShellArg( ) {
763 $args = func_get_args();
766 foreach ( $args as $arg ) {
773 if ( wfIsWindows() ) {
774 $retVal .= '"' . str_replace( '"','\"', $arg ) . '"';
776 $retVal .= escapeshellarg( $arg );
783 * wfMerge attempts to merge differences between three texts.
784 * Returns true for a clean merge and false for failure or a conflict.
786 function wfMerge( $old, $mine, $yours, &$result ){
789 # This check may also protect against code injection in
790 # case of broken installations.
791 if(! file_exists( $wgDiff3 ) ){
792 wfDebug( "diff3 not found\n" );
796 # Make temporary files
798 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
799 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
800 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
802 fwrite( $oldtextFile, $old ); fclose( $oldtextFile );
803 fwrite( $mytextFile, $mine ); fclose( $mytextFile );
804 fwrite( $yourtextFile, $yours ); fclose( $yourtextFile );
806 # Check for a conflict
807 $cmd = $wgDiff3 . ' -a --overlap-only ' .
808 wfEscapeShellArg( $mytextName ) . ' ' .
809 wfEscapeShellArg( $oldtextName ) . ' ' .
810 wfEscapeShellArg( $yourtextName );
811 $handle = popen( $cmd, 'r' );
813 if( fgets( $handle, 1024 ) ){
821 $cmd = $wgDiff3 . ' -a -e --merge ' .
822 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
823 $handle = popen( $cmd, 'r' );
826 $data = fread( $handle, 8192 );
827 if ( strlen( $data ) == 0 ) {
833 unlink( $mytextName ); unlink( $oldtextName ); unlink( $yourtextName );
835 if ( $result === '' && $old !== '' && $conflict == false ) {
836 wfDebug( "Unexpected null result from diff3. Command: $cmd\n" );
845 function wfVarDump( $var ) {
847 $s = str_replace("\n","<br />\n", var_export( $var, true ) . "\n");
848 if ( headers_sent() || !@is_object( $wgOut ) ) {
851 $wgOut->addHTML( $s );
856 * Provide a simple HTTP error.
858 function wfHttpError( $code, $label, $desc ) {
861 header( "HTTP/1.0 $code $label" );
862 header( "Status: $code $label" );
863 $wgOut->sendCacheControl();
865 header( 'Content-type: text/html' );
866 print "<html><head><title>" .
867 htmlspecialchars( $label ) .
868 "</title></head><body><h1>" .
869 htmlspecialchars( $label ) .
871 htmlspecialchars( $desc ) .
872 "</p></body></html>\n";
876 * Converts an Accept-* header into an array mapping string values to quality
879 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
880 # No arg means accept anything (per HTTP spec)
882 return array( $def => 1 );
887 $parts = explode( ',', $accept );
889 foreach( $parts as $part ) {
890 # FIXME: doesn't deal with params like 'text/html; level=1'
891 @list( $value, $qpart ) = explode( ';', $part );
892 if( !isset( $qpart ) ) {
894 } elseif( preg_match( '/q\s*=\s*(\d*\.\d+)/', $qpart, $match ) ) {
895 $prefs[$value] = $match[1];
903 * Checks if a given MIME type matches any of the keys in the given
904 * array. Basic wildcards are accepted in the array keys.
906 * Returns the matching MIME type (or wildcard) if a match, otherwise
909 * @param string $type
910 * @param array $avail
914 function mimeTypeMatch( $type, $avail ) {
915 if( array_key_exists($type, $avail) ) {
918 $parts = explode( '/', $type );
919 if( array_key_exists( $parts[0] . '/*', $avail ) ) {
920 return $parts[0] . '/*';
921 } elseif( array_key_exists( '*/*', $avail ) ) {
930 * Returns the 'best' match between a client's requested internet media types
931 * and the server's list of available types. Each list should be an associative
932 * array of type to preference (preference is a float between 0.0 and 1.0).
933 * Wildcards in the types are acceptable.
935 * @param array $cprefs Client's acceptable type list
936 * @param array $sprefs Server's offered types
939 * @todo FIXME: doesn't handle params like 'text/plain; charset=UTF-8'
940 * XXX: generalize to negotiate other stuff
942 function wfNegotiateType( $cprefs, $sprefs ) {
945 foreach( array_keys($sprefs) as $type ) {
946 $parts = explode( '/', $type );
947 if( $parts[1] != '*' ) {
948 $ckey = mimeTypeMatch( $type, $cprefs );
950 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
955 foreach( array_keys( $cprefs ) as $type ) {
956 $parts = explode( '/', $type );
957 if( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
958 $skey = mimeTypeMatch( $type, $sprefs );
960 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
968 foreach( array_keys( $combine ) as $type ) {
969 if( $combine[$type] > $bestq ) {
971 $bestq = $combine[$type];
980 * Returns an array where the values in the first array are replaced by the
981 * values in the second array with the corresponding keys
985 function wfArrayLookup( $a, $b ) {
986 return array_flip( array_intersect( array_flip( $a ), array_keys( $b ) ) );
990 * Convenience function; returns MediaWiki timestamp for the present time.
993 function wfTimestampNow() {
995 return wfTimestamp( TS_MW, time() );
999 * Reference-counted warning suppression
1001 function wfSuppressWarnings( $end = false ) {
1002 static $suppressCount = 0;
1003 static $originalLevel = false;
1006 if ( $suppressCount ) {
1008 if ( !$suppressCount ) {
1009 error_reporting( $originalLevel );
1013 if ( !$suppressCount ) {
1014 $originalLevel = error_reporting( E_ALL & ~( E_WARNING | E_NOTICE ) );
1021 * Restore error level to previous value
1023 function wfRestoreWarnings() {
1024 wfSuppressWarnings( true );
1027 # Autodetect, convert and provide timestamps of various types
1030 * Unix time - the number of seconds since 1970-01-01 00:00:00 UTC
1032 define('TS_UNIX', 0);
1035 * MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
1040 * MySQL DATETIME (YYYY-MM-DD HH:MM:SS)
1045 * RFC 2822 format, for E-mail and HTTP headers
1047 define('TS_RFC2822', 3);
1050 * An Exif timestamp (YYYY:MM:DD HH:MM:SS)
1052 * @link http://exif.org/Exif2-2.PDF The Exif 2.2 spec, see page 28 for the
1053 * DateTime tag and page 36 for the DateTimeOriginal and
1054 * DateTimeDigitized tags.
1056 define('TS_EXIF', 4);
1060 * @param mixed $outputtype A timestamp in one of the supported formats, the
1061 * function will autodetect which format is supplied
1062 and act accordingly.
1063 * @return string Time in the format specified in $outputtype
1065 function wfTimestamp($outputtype=TS_UNIX,$ts=0) {
1069 } elseif (preg_match("/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)$/",$ts,$da)) {
1071 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1072 (int)$da[2],(int)$da[3],(int)$da[1]);
1073 } elseif (preg_match("/^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/",$ts,$da)) {
1075 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1076 (int)$da[2],(int)$da[3],(int)$da[1]);
1077 } elseif (preg_match("/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/",$ts,$da)) {
1079 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1080 (int)$da[2],(int)$da[3],(int)$da[1]);
1081 } elseif (preg_match("/^(\d{1,13})$/",$ts,$datearray)) {
1085 # Bogus value; fall back to the epoch...
1086 wfDebug("wfTimestamp() fed bogus time value: $outputtype; $ts\n");
1091 switch($outputtype) {
1095 return gmdate( 'YmdHis', $uts );
1097 return gmdate( 'Y-m-d H:i:s', $uts );
1098 // This shouldn't ever be used, but is included for completeness
1100 return gmdate( 'Y:m:d H:i:s', $uts );
1102 return gmdate( 'D, d M Y H:i:s', $uts ) . ' GMT';
1104 wfDebugDieBacktrace( 'wfTimestamp() called with illegal output type.');
1109 * Return a formatted timestamp, or null if input is null.
1110 * For dealing with nullable timestamp columns in the database.
1111 * @param int $outputtype
1115 function wfTimestampOrNull( $outputtype = TS_UNIX, $ts = null ) {
1116 if( is_null( $ts ) ) {
1119 return wfTimestamp( $outputtype, $ts );
1124 * Check where as the operating system is Windows
1126 * @return bool True if it's windows, False otherwise.
1128 function wfIsWindows() {
1129 if (substr(php_uname(), 0, 7) == 'Windows') {
1137 * Swap two variables
1139 function swap( &$x, &$y ) {
1145 function wfGetSiteNotice() {
1146 global $wgSiteNotice, $wgTitle, $wgOut;
1147 $fname = 'wfGetSiteNotice';
1148 wfProfileIn( $fname );
1150 $notice = wfMsg( 'sitenotice' );
1151 if( $notice == '<sitenotice>' || $notice == '-' ) {
1154 if( $notice == '' ) {
1155 # We may also need to override a message with eg downtime info
1156 # FIXME: make this work!
1157 $notice = $wgSiteNotice;
1159 if($notice != '-' && $notice != '') {
1160 $specialparser = new Parser();
1161 $parserOutput = $specialparser->parse( $notice, $wgTitle, $wgOut->mParserOptions, false );
1162 $notice = $parserOutput->getText();
1164 wfProfileOut( $fname );
1169 * Format an XML element with given attributes and, optionally, text content.
1170 * Element and attribute names are assumed to be ready for literal inclusion.
1171 * Strings are assumed to not contain XML-illegal characters; special
1172 * characters (<, >, &) are escaped but illegals are not touched.
1174 * @param string $element
1175 * @param array $attribs Name=>value pairs. Values will be escaped.
1176 * @param string $contents NULL to make an open tag only; '' for a contentless closed tag (default)
1179 function wfElement( $element, $attribs = null, $contents = '') {
1180 $out = '<' . $element;
1181 if( !is_null( $attribs ) ) {
1182 foreach( $attribs as $name => $val ) {
1183 $out .= ' ' . $name . '="' . htmlspecialchars( $val ) . '"';
1186 if( is_null( $contents ) ) {
1189 if( $contents == '' ) {
1193 $out .= htmlspecialchars( $contents );
1194 $out .= "</$element>";
1201 * Format an XML element as with wfElement(), but run text through the
1202 * UtfNormal::cleanUp() validator first to ensure that no invalid UTF-8
1205 * @param string $element
1206 * @param array $attribs Name=>value pairs. Values will be escaped.
1207 * @param string $contents NULL to make an open tag only; '' for a contentless closed tag (default)
1210 function wfElementClean( $element, $attribs = array(), $contents = '') {
1212 $attribs = array_map( array( 'UtfNormal', 'cleanUp' ), $attribs );
1215 $contents = UtfNormal::cleanUp( $contents );
1217 return wfElement( $element, $attribs, $contents );
1221 * Create a namespace selector
1223 * @param mixed $selected The namespace which should be selected, default ''
1224 * @param string $allnamespaces Value of a special item denoting all namespaces. Null to not include (default)
1225 * @return Html string containing the namespace selector
1227 function &HTMLnamespaceselector($selected = '', $allnamespaces = null) {
1229 $s = "<select name='namespace' class='namespaceselector'>\n";
1230 $arr = $wgContLang->getFormattedNamespaces();
1231 if( !is_null($allnamespaces) ) {
1232 $arr = array($allnamespaces => wfMsgHtml('namespacesall')) + $arr;
1234 foreach ($arr as $index => $name) {
1235 if ($index < NS_MAIN) continue;
1237 $name = $index !== 0 ? $name : wfMsgHtml('blanknamespace');
1239 if ($index === $selected) {
1240 $s .= wfElement("option",
1241 array("value" => $index, "selected" => "selected"),
1244 $s .= wfElement("option", array("value" => $index), $name);
1247 $s .= "</select>\n";
1251 /** Global singleton instance of MimeMagic. This is initialized on demand,
1252 * please always use the wfGetMimeMagic() function to get the instance.
1258 /** Factory functions for the global MimeMagic object.
1259 * This function always returns the same singleton instance of MimeMagic.
1260 * That objects will be instantiated on the first call to this function.
1261 * If needed, the MimeMagic.php file is automatically included by this function.
1262 * @return MimeMagic the global MimeMagic objects.
1264 function &wfGetMimeMagic() {
1265 global $wgMimeMagic;
1267 if (!is_null($wgMimeMagic)) {
1268 return $wgMimeMagic;
1271 if (!class_exists("MimeMagic")) {
1273 require_once("MimeMagic.php");
1276 $wgMimeMagic= new MimeMagic();
1278 return $wgMimeMagic;
1283 * Tries to get the system directory for temporary files.
1284 * The TMPDIR, TMP, and TEMP environment variables are checked in sequence,
1285 * and if none are set /tmp is returned as the generic Unix default.
1287 * NOTE: When possible, use the tempfile() function to create temporary
1288 * files to avoid race conditions on file creation, etc.
1292 function wfTempDir() {
1293 foreach( array( 'TMPDIR', 'TMP', 'TEMP' ) as $var ) {
1294 $tmp = getenv( $var );
1295 if( $tmp && file_exists( $tmp ) && is_dir( $tmp ) && is_writable( $tmp ) ) {
1299 # Hope this is Unix of some kind!
1304 * Make directory, and make all parent directories if they don't exist
1306 function wfMkdirParents( $fullDir, $mode ) {
1307 $parts = explode( '/', $fullDir );
1310 foreach ( $parts as $dir ) {
1311 $path .= $dir . '/';
1312 if ( !is_dir( $path ) ) {
1313 if ( !mkdir( $path, $mode ) ) {
1322 * Increment a statistics counter
1324 function wfIncrStats( $key ) {
1325 global $wgDBname, $wgMemc;
1326 $key = "$wgDBname:stats:$key";
1327 if ( is_null( $wgMemc->incr( $key ) ) ) {
1328 $wgMemc->add( $key, 1 );
1333 * @param mixed $nr The number to format
1334 * @param int $acc The number of digits after the decimal point, default 2
1335 * @param bool $round Whether or not to round the value, default true
1338 function wfPercent( $nr, $acc = 2, $round = true ) {
1339 $ret = sprintf( "%.${acc}f", $nr );
1340 return $round ? round( $ret, $acc ) . '%' : "$ret%";
1344 * Encrypt a username/password.
1346 * @param string $userid ID of the user
1347 * @param string $password Password of the user
1348 * @return string Hashed password
1350 function wfEncryptPassword( $userid, $password ) {
1351 global $wgPasswordSalt;
1352 $p = md5( $password);
1355 return md5( "{$userid}-{$p}" );
1361 * Appends to second array if $value differs from that in $default
1363 function wfAppendToArrayIfNotDefault( $key, $value, $default, &$changed ) {
1364 if ( is_null( $changed ) ) {
1365 wfDebugDieBacktrace('GlobalFunctions::wfAppendToArrayIfNotDefault got null');
1367 if ( $default[$key] !== $value ) {
1368 $changed[$key] = $value;
1373 * Since wfMsg() and co suck, they don't return false if the message key they
1374 * looked up didn't exist but a XHTML string, this function checks for the
1375 * nonexistance of messages by looking at wfMsg() output
1377 * @param $msg The message key looked up
1378 * @param $wfMsgOut The output of wfMsg*()
1381 function wfNoMsg( $msg, $wfMsgOut ) {
1382 return $wfMsgOut === "<$msg>";