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 ) );
83 * html_entity_decode exists in PHP 4.3.0+ but is FATALLY BROKEN even then,
84 * with no UTF-8 support.
86 * @param string $string String having html entities
87 * @param $quote_style the quote style to pass as the second argument to
88 * get_html_translation_table()
89 * @param string $charset Encoding set to use (default 'UTF-8')
91 function do_html_entity_decode( $string, $quote_style=ENT_COMPAT
, $charset='UTF-8' ) {
92 $fname = 'do_html_entity_decode';
93 wfProfileIn( $fname );
98 if( !isset( $trans ) ||
$savedCharset != $charset ) {
99 $trans = array_flip( get_html_translation_table( HTML_ENTITIES
, $quote_style ) );
100 $savedCharset = $charset;
102 # Note - mixing latin1 named entities and unicode numbered
103 # ones will result in a bad link.
104 if( strcasecmp( 'utf-8', $charset ) == 0 ) {
105 $trans = array_map( 'utf8_encode', $trans );
109 * Most links will _not_ contain these fun guys,
110 * and on long pages with many links we can get
113 * A regular expression search is faster than
114 * a strtr or str_replace with a hundred-ish
115 * entries, though it may be slower to actually
118 * They all look like '&xxxx;'...
120 foreach( $trans as $key => $val ) {
121 $snip[] = substr( $key, 1, -1 );
123 $regexp = '/(&(?:' . implode( '|', $snip ) . ');)/e';
126 $out = preg_replace( $regexp, '$trans["$1"]', $string );
127 wfProfileOut( $fname );
133 * Where as we got a random seed
134 * @var bool $wgTotalViews
136 $wgRandomSeeded = false;
139 * Seed Mersenne Twister
140 * Only necessary in PHP < 4.2.0
144 function wfSeedRandom() {
145 global $wgRandomSeeded;
147 if ( ! $wgRandomSeeded && version_compare( phpversion(), '4.2.0' ) < 0 ) {
148 $seed = hexdec(substr(md5(microtime()),-8)) & 0x7fffffff;
150 $wgRandomSeeded = true;
155 * Get a random decimal value between 0 and 1, in a way
156 * not likely to give duplicate values for any realistic
157 * number of articles.
161 function wfRandom() {
162 # The maximum random value is "only" 2^31-1, so get two random
163 # values to reduce the chance of dupes
164 $max = mt_getrandmax();
165 $rand = number_format( (mt_rand() * $max +
mt_rand())
166 / $max / $max, 12, '.', '' );
171 * We want / and : to be included as literal characters in our title URLs.
172 * %2F in the page titles seems to fatally break for some reason.
177 function wfUrlencode ( $s ) {
178 $s = urlencode( $s );
179 $s = preg_replace( '/%3[Aa]/', ':', $s );
180 $s = preg_replace( '/%2[Ff]/', '/', $s );
186 * Return the UTF-8 sequence for a given Unicode code point.
187 * Doesn't work for values outside the Basic Multilingual Plane.
189 * @param string $codepoint UTF-8 code point.
190 * @return string An UTF-8 character if the codepoint is in the BMP and
191 * &#$codepoint if it isn't;
193 function wfUtf8Sequence( $codepoint ) {
194 if($codepoint < 0x80)
195 return chr($codepoint);
196 if($codepoint < 0x800)
197 return chr($codepoint >> 6 & 0x3f |
0xc0) . chr($codepoint & 0x3f |
0x80);
198 if($codepoint < 0x10000)
199 return chr($codepoint >> 12 & 0x0f |
0xe0) .
200 chr($codepoint >> 6 & 0x3f |
0x80) .
201 chr($codepoint & 0x3f |
0x80);
202 if($codepoint < 0x110000)
203 return chr($codepoint >> 18 & 0x07 |
0xf0) .
204 chr($codepoint >> 12 & 0x3f |
0x80) .
205 chr($codepoint >> 6 & 0x3f |
0x80) .
206 chr($codepoint & 0x3f |
0x80);
207 # There should be no assigned code points outside this range, but...
208 return "&#$codepoint;";
212 * Converts numeric character entities to UTF-8
214 * @todo Do named entities
216 * @param string $string String to convert.
217 * @return string Converted string.
219 function wfMungeToUtf8( $string ) {
220 global $wgInputEncoding; # This is debatable
221 #$string = iconv($wgInputEncoding, "UTF-8", $string);
222 $string = preg_replace ( '/�*([0-9]+);/e', 'wfUtf8Sequence($1)', $string );
223 $string = preg_replace ( '/&#x([0-9a-f]+);/ie', 'wfUtf8Sequence(0x$1)', $string );
228 * Converts a single UTF-8 character into the corresponding HTML character
229 * entity (for use with preg_replace_callback)
231 * @param array $matches
234 function wfUtf8Entity( $matches ) {
235 $codepoint = utf8ToCodepoint( $matches[0] );
236 return "&#$codepoint;";
240 * Converts all multi-byte characters in a UTF-8 string into the appropriate
243 function wfUtf8ToHTML($string) {
244 return preg_replace_callback( '/[\\xc0-\\xfd][\\x80-\\xbf]*/', 'wfUtf8Entity', $string );
248 * Sends a line to the debug log if enabled or, optionally, to a comment in output.
249 * In normal operation this is a NOP.
251 * Controlling globals:
252 * $wgDebugLogFile - points to the log file
253 * $wgProfileOnly - if set, normal debug messages will not be recorded.
254 * $wgDebugRawPage - if false, 'action=raw' hits will not result in debug output.
255 * $wgDebugComments - if on, some debug items may appear in comments in the HTML output.
257 * @param string $text
258 * @param bool $logonly Set true to avoid appearing in HTML when $wgDebugComments is set
260 function wfDebug( $text, $logonly = false ) {
261 global $wgOut, $wgDebugLogFile, $wgDebugComments, $wgProfileOnly, $wgDebugRawPage;
263 # Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
264 if ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' && !$wgDebugRawPage ) {
268 if ( isset( $wgOut ) && $wgDebugComments && !$logonly ) {
269 $wgOut->debug( $text );
271 if ( '' != $wgDebugLogFile && !$wgProfileOnly ) {
272 # Strip unprintables; they can switch terminal modes when binary data
273 # gets dumped, which is pretty annoying.
274 $text = preg_replace( '![\x00-\x08\x0b\x0c\x0e-\x1f]!', ' ', $text );
275 @error_log
( $text, 3, $wgDebugLogFile );
280 * Log for database errors
281 * @param string $text Database error message.
283 function wfLogDBError( $text ) {
284 global $wgDBerrorLog;
285 if ( $wgDBerrorLog ) {
286 $text = date('D M j G:i:s T Y') . "\t".$text;
287 error_log( $text, 3, $wgDBerrorLog );
294 function logProfilingData() {
295 global $wgRequestTime, $wgDebugLogFile, $wgDebugRawPage, $wgRequest;
296 global $wgProfiling, $wgProfileStack, $wgProfileLimit, $wgUser;
299 list( $usec, $sec ) = explode( ' ', $wgRequestTime );
300 $start = (float)$sec +
(float)$usec;
301 $elapsed = $now - $start;
302 if ( $wgProfiling ) {
303 $prof = wfGetProfilingOutput( $start, $elapsed );
305 if( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) )
306 $forward = ' forwarded for ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
307 if( !empty( $_SERVER['HTTP_CLIENT_IP'] ) )
308 $forward .= ' client IP ' . $_SERVER['HTTP_CLIENT_IP'];
309 if( !empty( $_SERVER['HTTP_FROM'] ) )
310 $forward .= ' from ' . $_SERVER['HTTP_FROM'];
312 $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
313 if( $wgUser->isAnon() )
315 $log = sprintf( "%s\t%04.3f\t%s\n",
316 gmdate( 'YmdHis' ), $elapsed,
317 urldecode( $_SERVER['REQUEST_URI'] . $forward ) );
318 if ( '' != $wgDebugLogFile && ( $wgRequest->getVal('action') != 'raw' ||
$wgDebugRawPage ) ) {
319 error_log( $log . $prof, 3, $wgDebugLogFile );
325 * Check if the wiki read-only lock file is present. This can be used to lock
326 * off editing functions, but doesn't guarantee that the database will not be
330 function wfReadOnly() {
331 global $wgReadOnlyFile;
333 if ( '' == $wgReadOnlyFile ) {
336 return is_file( $wgReadOnlyFile );
341 * Get a message from anywhere, for the current user language
345 function wfMsg( $key ) {
346 $args = func_get_args();
347 array_shift( $args );
348 return wfMsgReal( $key, $args, true );
352 * Get a message from anywhere, for the current global language
354 function wfMsgForContent( $key ) {
355 global $wgForceUIMsgAsContentMsg;
356 $args = func_get_args();
357 array_shift( $args );
359 if( is_array( $wgForceUIMsgAsContentMsg ) &&
360 in_array( $key, $wgForceUIMsgAsContentMsg ) )
362 return wfMsgReal( $key, $args, true, $forcontent );
366 * Get a message from the language file, for the UI elements
368 function wfMsgNoDB( $key ) {
369 $args = func_get_args();
370 array_shift( $args );
371 return wfMsgReal( $key, $args, false );
375 * Get a message from the language file, for the content
377 function wfMsgNoDBForContent( $key ) {
378 global $wgForceUIMsgAsContentMsg;
379 $args = func_get_args();
380 array_shift( $args );
382 if( is_array( $wgForceUIMsgAsContentMsg ) &&
383 in_array( $key, $wgForceUIMsgAsContentMsg ) )
385 return wfMsgReal( $key, $args, false, $forcontent );
390 * Really get a message
392 function wfMsgReal( $key, $args, $useDB, $forContent=false ) {
393 static $replacementKeys = array( '$1', '$2', '$3', '$4', '$5', '$6', '$7', '$8', '$9' );
394 global $wgParser, $wgMsgParserOptions;
395 global $wgContLang, $wgLanguageCode;
396 global $wgMessageCache, $wgLang;
398 $fname = 'wfMsgReal';
399 wfProfileIn( $fname );
401 if( is_object( $wgMessageCache ) ) {
402 $message = $wgMessageCache->get( $key, $useDB, $forContent );
405 $lang = &$wgContLang;
410 wfSuppressWarnings();
412 if( is_object( $lang ) ) {
413 $message = $lang->getMessage( $key );
419 $message = Language
::getMessage($key);
420 if(strstr($message, '{{' ) !== false) {
421 $message = $wgParser->transformMsg($message, $wgMsgParserOptions);
426 if( count( $args ) ) {
427 $message = str_replace( $replacementKeys, $args, $message );
429 wfProfileOut( $fname );
436 * Just like exit() but makes a note of it.
437 * Commits open transactions except if the error parameter is set
439 function wfAbruptExit( $error = false ){
440 global $wgLoadBalancer;
441 static $called = false;
447 if( function_exists( 'debug_backtrace' ) ){ // PHP >= 4.3
448 $bt = debug_backtrace();
449 for($i = 0; $i < count($bt) ; $i++
){
450 $file = $bt[$i]['file'];
451 $line = $bt[$i]['line'];
452 wfDebug("WARNING: Abrupt exit in $file at line $line\n");
455 wfDebug('WARNING: Abrupt exit\n');
458 $wgLoadBalancer->closeAll();
466 function wfErrorExit() {
467 wfAbruptExit( true );
471 * Die with a backtrace
472 * This is meant as a debugging aid to track down where bad data comes from.
473 * Shouldn't be used in production code except maybe in "shouldn't happen" areas.
475 * @param string $msg Message shown when dieing.
477 function wfDebugDieBacktrace( $msg = '' ) {
478 global $wgCommandLineMode;
480 $backtrace = wfBacktrace();
481 if ( $backtrace !== false ) {
482 if ( $wgCommandLineMode ) {
483 $msg .= "\nBacktrace:\n$backtrace";
485 $msg .= "\n<p>Backtrace:</p>\n$backtrace";
491 function wfBacktrace() {
492 global $wgCommandLineMode;
493 if ( !function_exists( 'debug_backtrace' ) ) {
497 if ( $wgCommandLineMode ) {
502 $backtrace = debug_backtrace();
503 foreach( $backtrace as $call ) {
504 if( isset( $call['file'] ) ) {
505 $f = explode( DIRECTORY_SEPARATOR
, $call['file'] );
506 $file = $f[count($f)-1];
510 if( isset( $call['line'] ) ) {
511 $line = $call['line'];
515 if ( $wgCommandLineMode ) {
516 $msg .= "$file line $line calls ";
518 $msg .= '<li>' . $file . ' line ' . $line . ' calls ';
520 if( !empty( $call['class'] ) ) $msg .= $call['class'] . '::';
521 $msg .= $call['function'] . '()';
523 if ( $wgCommandLineMode ) {
529 if ( $wgCommandLineMode ) {
539 /* Some generic result counters, pulled out of SearchEngine */
545 function wfShowingResults( $offset, $limit ) {
547 return wfMsg( 'showingresults', $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+
1 ) );
553 function wfShowingResultsNum( $offset, $limit, $num ) {
555 return wfMsg( 'showingresultsnum', $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+
1 ), $wgLang->formatNum( $num ) );
561 function wfViewPrevNext( $offset, $limit, $link, $query = '', $atend = false ) {
562 global $wgUser, $wgLang;
563 $fmtLimit = $wgLang->formatNum( $limit );
564 $prev = wfMsg( 'prevn', $fmtLimit );
565 $next = wfMsg( 'nextn', $fmtLimit );
567 if( is_object( $link ) ) {
570 $title =& Title
::newFromText( $link );
571 if( is_null( $title ) ) {
576 $sk = $wgUser->getSkin();
577 if ( 0 != $offset ) {
578 $po = $offset - $limit;
579 if ( $po < 0 ) { $po = 0; }
580 $q = "limit={$limit}&offset={$po}";
581 if ( '' != $query ) { $q .= '&'.$query; }
582 $plink = '<a href="' . $title->escapeLocalUrl( $q ) . "\">{$prev}</a>";
583 } else { $plink = $prev; }
585 $no = $offset +
$limit;
586 $q = 'limit='.$limit.'&offset='.$no;
587 if ( '' != $query ) { $q .= '&'.$query; }
592 $nlink = '<a href="' . $title->escapeLocalUrl( $q ) . "\">{$next}</a>";
594 $nums = wfNumLink( $offset, 20, $title, $query ) . ' | ' .
595 wfNumLink( $offset, 50, $title, $query ) . ' | ' .
596 wfNumLink( $offset, 100, $title, $query ) . ' | ' .
597 wfNumLink( $offset, 250, $title, $query ) . ' | ' .
598 wfNumLink( $offset, 500, $title, $query );
600 return wfMsg( 'viewprevnext', $plink, $nlink, $nums );
606 function wfNumLink( $offset, $limit, &$title, $query = '' ) {
607 global $wgUser, $wgLang;
608 if ( '' == $query ) { $q = ''; }
609 else { $q = $query.'&'; }
610 $q .= 'limit='.$limit.'&offset='.$offset;
612 $fmtLimit = $wgLang->formatNum( $limit );
613 $s = '<a href="' . $title->escapeLocalUrl( $q ) . "\">{$fmtLimit}</a>";
619 * @todo FIXME: we may want to blacklist some broken browsers
621 * @return bool Whereas client accept gzip compression
623 function wfClientAcceptsGzip() {
626 # FIXME: we may want to blacklist some broken browsers
628 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
629 $_SERVER['HTTP_ACCEPT_ENCODING'],
631 if( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) return false;
632 wfDebug( " accepts gzip\n" );
640 * Yay, more global functions!
642 function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) {
644 return $wgRequest->getLimitOffset( $deflimit, $optionname );
648 * Escapes the given text so that it may be output using addWikiText()
649 * without any linking, formatting, etc. making its way through. This
650 * is achieved by substituting certain characters with HTML entities.
651 * As required by the callers, <nowiki> is not used. It currently does
652 * not filter out characters which have special meaning only at the
653 * start of a line, such as "*".
655 * @param string $text Text to be escaped
657 function wfEscapeWikiText( $text ) {
659 array( '[', '|', '\'', 'ISBN ' , '://' , "\n=", '{{' ),
660 array( '[', '|', ''', 'ISBN ', '://' , "\n=", '{{' ),
661 htmlspecialchars($text) );
668 function wfQuotedPrintable( $string, $charset = '' ) {
669 # Probably incomplete; see RFC 2045
670 if( empty( $charset ) ) {
671 global $wgInputEncoding;
672 $charset = $wgInputEncoding;
674 $charset = strtoupper( $charset );
675 $charset = str_replace( 'ISO-8859', 'ISO8859', $charset ); // ?
677 $illegal = '\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\xff=';
678 $replace = $illegal . '\t ?_';
679 if( !preg_match( "/[$illegal]/", $string ) ) return $string;
680 $out = "=?$charset?Q?";
681 $out .= preg_replace( "/([$replace])/e", 'sprintf("=%02X",ord("$1"))', $string );
687 * Returns an escaped string suitable for inclusion in a string literal
688 * for JavaScript source code.
689 * Illegal control characters are assumed not to be present.
691 * @param string $string
694 function wfEscapeJsString( $string ) {
695 // See ECMA 262 section 7.8.4 for string literal format
703 # To avoid closing the element or CDATA section
707 return strtr( $string, $pairs );
715 $st = explode( ' ', microtime() );
716 return (float)$st[0] +
(float)$st[1];
720 * Changes the first character to an HTML entity
722 function wfHtmlEscapeFirst( $text ) {
724 $newText = substr($text, 1);
725 return "&#$ord;$newText";
729 * Sets dest to source and returns the original value of dest
730 * If source is NULL, it just returns the value, it doesn't set the variable
732 function wfSetVar( &$dest, $source ) {
734 if ( !is_null( $source ) ) {
741 * As for wfSetVar except setting a bit
743 function wfSetBit( &$dest, $bit, $state = true ) {
744 $temp = (bool)($dest & $bit );
745 if ( !is_null( $state ) ) {
756 * This function takes two arrays as input, and returns a CGI-style string, e.g.
757 * "days=7&limit=100". Options in the first array override options in the second.
758 * Options set to "" will not be output.
760 function wfArrayToCGI( $array1, $array2 = NULL )
762 if ( !is_null( $array2 ) ) {
763 $array1 = $array1 +
$array2;
767 foreach ( $array1 as $key => $value ) {
768 if ( '' !== $value ) {
772 $cgi .= urlencode( $key ) . '=' . urlencode( $value );
779 * This is obsolete, use SquidUpdate::purge()
782 function wfPurgeSquidServers ($urlArr) {
783 SquidUpdate
::purge( $urlArr );
787 * Windows-compatible version of escapeshellarg()
788 * Windows doesn't recognise single-quotes in the shell, but the escapeshellarg()
789 * function puts single quotes in regardless of OS
791 function wfEscapeShellArg( ) {
792 $args = func_get_args();
795 foreach ( $args as $arg ) {
802 if ( wfIsWindows() ) {
803 $retVal .= '"' . str_replace( '"','\"', $arg ) . '"';
805 $retVal .= escapeshellarg( $arg );
812 * wfMerge attempts to merge differences between three texts.
813 * Returns true for a clean merge and false for failure or a conflict.
815 function wfMerge( $old, $mine, $yours, &$result ){
818 # This check may also protect against code injection in
819 # case of broken installations.
820 if(! file_exists( $wgDiff3 ) ){
824 # Make temporary files
826 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
827 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
828 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
830 fwrite( $oldtextFile, $old ); fclose( $oldtextFile );
831 fwrite( $mytextFile, $mine ); fclose( $mytextFile );
832 fwrite( $yourtextFile, $yours ); fclose( $yourtextFile );
834 # Check for a conflict
835 $cmd = wfEscapeShellArg( $wgDiff3 ) . ' -a --overlap-only ' .
836 wfEscapeShellArg( $mytextName ) . ' ' .
837 wfEscapeShellArg( $oldtextName ) . ' ' .
838 wfEscapeShellArg( $yourtextName );
839 $handle = popen( $cmd, 'r' );
841 if( fgets( $handle, 1024 ) ){
849 $cmd = wfEscapeShellArg( $wgDiff3 ) . ' -a -e --merge ' .
850 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
851 $handle = popen( $cmd, 'r' );
854 $data = fread( $handle, 8192 );
855 if ( strlen( $data ) == 0 ) {
861 unlink( $mytextName ); unlink( $oldtextName ); unlink( $yourtextName );
868 function wfVarDump( $var ) {
870 $s = str_replace("\n","<br />\n", var_export( $var, true ) . "\n");
871 if ( headers_sent() ||
!@is_object
( $wgOut ) ) {
874 $wgOut->addHTML( $s );
879 * Provide a simple HTTP error.
881 function wfHttpError( $code, $label, $desc ) {
884 header( "HTTP/1.0 $code $label" );
885 header( "Status: $code $label" );
886 $wgOut->sendCacheControl();
888 header( 'Content-type: text/plain' );
893 * Converts an Accept-* header into an array mapping string values to quality
896 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
897 # No arg means accept anything (per HTTP spec)
899 return array( $def => 1 );
904 $parts = explode( ',', $accept );
906 foreach( $parts as $part ) {
907 # FIXME: doesn't deal with params like 'text/html; level=1'
908 @list
( $value, $qpart ) = explode( ';', $part );
909 if( !isset( $qpart ) ) {
911 } elseif( preg_match( '/q\s*=\s*(\d*\.\d+)/', $qpart, $match ) ) {
912 $prefs[$value] = $match[1];
920 * Checks if a given MIME type matches any of the keys in the given
921 * array. Basic wildcards are accepted in the array keys.
923 * Returns the matching MIME type (or wildcard) if a match, otherwise
926 * @param string $type
927 * @param array $avail
931 function mimeTypeMatch( $type, $avail ) {
932 if( array_key_exists($type, $avail) ) {
935 $parts = explode( '/', $type );
936 if( array_key_exists( $parts[0] . '/*', $avail ) ) {
937 return $parts[0] . '/*';
938 } elseif( array_key_exists( '*/*', $avail ) ) {
947 * Returns the 'best' match between a client's requested internet media types
948 * and the server's list of available types. Each list should be an associative
949 * array of type to preference (preference is a float between 0.0 and 1.0).
950 * Wildcards in the types are acceptable.
952 * @param array $cprefs Client's acceptable type list
953 * @param array $sprefs Server's offered types
956 * @todo FIXME: doesn't handle params like 'text/plain; charset=UTF-8'
957 * XXX: generalize to negotiate other stuff
959 function wfNegotiateType( $cprefs, $sprefs ) {
962 foreach( array_keys($sprefs) as $type ) {
963 $parts = explode( '/', $type );
964 if( $parts[1] != '*' ) {
965 $ckey = mimeTypeMatch( $type, $cprefs );
967 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
972 foreach( array_keys( $cprefs ) as $type ) {
973 $parts = explode( '/', $type );
974 if( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
975 $skey = mimeTypeMatch( $type, $sprefs );
977 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
985 foreach( array_keys( $combine ) as $type ) {
986 if( $combine[$type] > $bestq ) {
988 $bestq = $combine[$type];
997 * Returns an array where the values in the first array are replaced by the
998 * values in the second array with the corresponding keys
1002 function wfArrayLookup( $a, $b ) {
1003 return array_flip( array_intersect( array_flip( $a ), array_keys( $b ) ) );
1007 * Convenience function; returns MediaWiki timestamp for the present time.
1010 function wfTimestampNow() {
1012 return wfTimestamp( TS_MW
, time() );
1016 * Reference-counted warning suppression
1018 function wfSuppressWarnings( $end = false ) {
1019 static $suppressCount = 0;
1020 static $originalLevel = false;
1023 if ( $suppressCount ) {
1025 if ( !$suppressCount ) {
1026 error_reporting( $originalLevel );
1030 if ( !$suppressCount ) {
1031 $originalLevel = error_reporting( E_ALL
& ~
( E_WARNING | E_NOTICE
) );
1038 * Restore error level to previous value
1040 function wfRestoreWarnings() {
1041 wfSuppressWarnings( true );
1044 # Autodetect, convert and provide timestamps of various types
1047 * Unix time - the number of seconds since 1970-01-01 00:00:00 UTC
1049 define('TS_UNIX', 0);
1052 * MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
1057 * MySQL DATETIME (YYYY-MM-DD HH:MM:SS)
1062 * RFC 2822 format, for E-mail and HTTP headers
1064 define('TS_RFC2822', 3);
1067 * An Exif timestamp (YYYY:MM:DD HH:MM:SS)
1069 * @link http://exif.org/Exif2-2.PDF The Exif 2.2 spec, see page 28 for the
1070 * DateTime tag and page 36 for the DateTimeOriginal and
1071 * DateTimeDigitized tags.
1073 define('TS_EXIF', 4);
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)) {
1101 # Bogus value; fall back to the epoch...
1102 wfDebug("wfTimestamp() fed bogus time value: $outputtype; $ts\n");
1107 switch($outputtype) {
1111 return gmdate( 'YmdHis', $uts );
1113 return gmdate( 'Y-m-d H:i:s', $uts );
1114 // This shouldn't ever be used, but is included for completeness
1116 return gmdate( 'Y:m:d H:i:s', $uts );
1118 return gmdate( 'D, d M Y H:i:s', $uts ) . ' GMT';
1120 wfDebugDieBacktrace( 'wfTimestamp() called with illegal output type.');
1125 * Return a formatted timestamp, or null if input is null.
1126 * For dealing with nullable timestamp columns in the database.
1127 * @param int $outputtype
1131 function wfTimestampOrNull( $outputtype = TS_UNIX
, $ts = null ) {
1132 if( is_null( $ts ) ) {
1135 return wfTimestamp( $outputtype, $ts );
1140 * Check where as the operating system is Windows
1142 * @return bool True if it's windows, False otherwise.
1144 function wfIsWindows() {
1145 if (substr(php_uname(), 0, 7) == 'Windows') {
1153 * Swap two variables
1155 function swap( &$x, &$y ) {
1161 function wfGetSiteNotice() {
1162 global $wgSiteNotice, $wgTitle, $wgOut;
1163 $fname = 'wfGetSiteNotice';
1164 wfProfileIn( $fname );
1166 $notice = wfMsg( 'sitenotice' );
1167 if($notice == '<sitenotice>') $notice = '';
1168 # Allow individual wikis to turn it off
1169 if ( $notice == '-' ) {
1172 if ($notice == '') {
1173 $notice = $wgSiteNotice;
1175 if($notice != '-' && $notice != '') {
1176 $specialparser = new Parser();
1177 $parserOutput = $specialparser->parse( $notice, $wgTitle, $wgOut->mParserOptions
, false );
1178 $notice = $parserOutput->getText();
1181 wfProfileOut( $fname );
1186 * Format an XML element with given attributes and, optionally, text content.
1187 * Element and attribute names are assumed to be ready for literal inclusion.
1188 * Strings are assumed to not contain XML-illegal characters; special
1189 * characters (<, >, &) are escaped but illegals are not touched.
1191 * @param string $element
1192 * @param array $attribs Name=>value pairs. Values will be escaped.
1193 * @param bool $contents NULL to make an open tag only; '' for a contentless closed tag (default)
1196 function wfElement( $element, $attribs = array(), $contents = '') {
1197 $out = '<' . $element;
1198 foreach( $attribs as $name => $val ) {
1199 $out .= ' ' . $name . '="' . htmlspecialchars( $val ) . '"';
1201 if( is_null( $contents ) ) {
1204 if( $contents == '' ) {
1208 $out .= htmlspecialchars( $contents );
1209 $out .= "</$element>";
1216 * Format an XML element as with wfElement(), but run text through the
1217 * UtfNormal::cleanUp() validator first to ensure that no invalid UTF-8
1220 * @param string $element
1221 * @param array $attribs Name=>value pairs. Values will be escaped.
1222 * @param bool $contents NULL to make an open tag only; '' for a contentless closed tag (default)
1225 function wfElementClean( $element, $attribs = array(), $contents = '') {
1227 $attribs = array_map( array( 'UtfNormal', 'cleanUp' ), $attribs );
1229 return wfElement( $element, $attribs, UtfNormal
::cleanUp( $contents ) );