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 * Log for database errors
180 * @param string $text Database error message.
182 function wfLogDBError( $text ) {
183 global $wgDBerrorLog;
184 if ( $wgDBerrorLog ) {
185 $text = date('D M j G:i:s T Y') . "\t".$text;
186 error_log( $text, 3, $wgDBerrorLog );
193 function logProfilingData() {
194 global $wgRequestTime, $wgDebugLogFile, $wgDebugRawPage, $wgRequest;
195 global $wgProfiling, $wgProfileStack, $wgProfileLimit, $wgUser;
198 list( $usec, $sec ) = explode( ' ', $wgRequestTime );
199 $start = (float)$sec +
(float)$usec;
200 $elapsed = $now - $start;
201 if ( $wgProfiling ) {
202 $prof = wfGetProfilingOutput( $start, $elapsed );
204 if( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) )
205 $forward = ' forwarded for ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
206 if( !empty( $_SERVER['HTTP_CLIENT_IP'] ) )
207 $forward .= ' client IP ' . $_SERVER['HTTP_CLIENT_IP'];
208 if( !empty( $_SERVER['HTTP_FROM'] ) )
209 $forward .= ' from ' . $_SERVER['HTTP_FROM'];
211 $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
212 if( $wgUser->isAnon() )
214 $log = sprintf( "%s\t%04.3f\t%s\n",
215 gmdate( 'YmdHis' ), $elapsed,
216 urldecode( $_SERVER['REQUEST_URI'] . $forward ) );
217 if ( '' != $wgDebugLogFile && ( $wgRequest->getVal('action') != 'raw' ||
$wgDebugRawPage ) ) {
218 error_log( $log . $prof, 3, $wgDebugLogFile );
224 * Check if the wiki read-only lock file is present. This can be used to lock
225 * off editing functions, but doesn't guarantee that the database will not be
229 function wfReadOnly() {
230 global $wgReadOnlyFile, $wgReadOnly;
235 if ( '' == $wgReadOnlyFile ) {
239 // Set $wgReadOnly and unset $wgReadOnlyFile, for faster access next time
240 if ( is_file( $wgReadOnlyFile ) ) {
245 $wgReadOnlyFile = '';
251 * Get a message from anywhere, for the current user language
255 function wfMsg( $key ) {
256 $args = func_get_args();
257 array_shift( $args );
258 return wfMsgReal( $key, $args, true );
262 * Get a message from anywhere, for the current global language
264 function wfMsgForContent( $key ) {
265 global $wgForceUIMsgAsContentMsg;
266 $args = func_get_args();
267 array_shift( $args );
269 if( is_array( $wgForceUIMsgAsContentMsg ) &&
270 in_array( $key, $wgForceUIMsgAsContentMsg ) )
272 return wfMsgReal( $key, $args, true, $forcontent );
276 * Get a message from the language file, for the UI elements
278 function wfMsgNoDB( $key ) {
279 $args = func_get_args();
280 array_shift( $args );
281 return wfMsgReal( $key, $args, false );
285 * Get a message from the language file, for the content
287 function wfMsgNoDBForContent( $key ) {
288 global $wgForceUIMsgAsContentMsg;
289 $args = func_get_args();
290 array_shift( $args );
292 if( is_array( $wgForceUIMsgAsContentMsg ) &&
293 in_array( $key, $wgForceUIMsgAsContentMsg ) )
295 return wfMsgReal( $key, $args, false, $forcontent );
300 * Really get a message
302 function wfMsgReal( $key, $args, $useDB, $forContent=false ) {
303 $fname = 'wfMsgReal';
304 wfProfileIn( $fname );
306 $message = wfMsgGetKey( $key, $useDB, $forContent );
307 $message = wfMsgReplaceArgs( $message, $args );
308 wfProfileOut( $fname );
313 * Fetch a message string value, but don't replace any keys yet.
316 * @param bool $forContent
320 function wfMsgGetKey( $key, $useDB, $forContent = false ) {
321 global $wgParser, $wgMsgParserOptions;
322 global $wgContLang, $wgLanguageCode;
323 global $wgMessageCache, $wgLang;
325 if( is_object( $wgMessageCache ) ) {
326 $message = $wgMessageCache->get( $key, $useDB, $forContent );
329 $lang = &$wgContLang;
334 wfSuppressWarnings();
336 if( is_object( $lang ) ) {
337 $message = $lang->getMessage( $key );
343 $message = Language
::getMessage($key);
344 if(strstr($message, '{{' ) !== false) {
345 $message = $wgParser->transformMsg($message, $wgMsgParserOptions);
352 * Replace message parameter keys on the given formatted output.
354 * @param string $message
359 function wfMsgReplaceArgs( $message, $args ) {
360 static $replacementKeys = array( '$1', '$2', '$3', '$4', '$5', '$6', '$7', '$8', '$9' );
362 # Fix windows line-endings
363 # Some messages are split with explode("\n", $msg)
364 $message = str_replace( "\r", '', $message );
367 if( count( $args ) ) {
368 $message = str_replace( $replacementKeys, $args, $message );
374 * Return an HTML-escaped version of a message.
375 * Parameter replacements, if any, are done *after* the HTML-escaping,
376 * so parameters may contain HTML (eg links or form controls). Be sure
377 * to pre-escape them if you really do want plaintext, or just wrap
378 * the whole thing in htmlspecialchars().
381 * @param string ... parameters
384 function wfMsgHtml( $key ) {
385 $args = func_get_args();
386 array_shift( $args );
387 return wfMsgReplaceArgs( htmlspecialchars( wfMsgGetKey( $key, true ) ), $args );
391 * Return an HTML version of message
392 * Parameter replacements, if any, are done *after* parsing the wiki-text message,
393 * so parameters may contain HTML (eg links or form controls). Be sure
394 * to pre-escape them if you really do want plaintext, or just wrap
395 * the whole thing in htmlspecialchars().
398 * @param string ... parameters
401 function wfMsgWikiHtml( $key ) {
403 $args = func_get_args();
404 array_shift( $args );
405 return wfMsgReplaceArgs( $wgOut->parse( wfMsgGetKey( $key, true ), /* can't be set to false */ true ), $args );
409 * Just like exit() but makes a note of it.
410 * Commits open transactions except if the error parameter is set
412 function wfAbruptExit( $error = false ){
413 global $wgLoadBalancer;
414 static $called = false;
420 if( function_exists( 'debug_backtrace' ) ){ // PHP >= 4.3
421 $bt = debug_backtrace();
422 for($i = 0; $i < count($bt) ; $i++
){
423 $file = $bt[$i]['file'];
424 $line = $bt[$i]['line'];
425 wfDebug("WARNING: Abrupt exit in $file at line $line\n");
428 wfDebug('WARNING: Abrupt exit\n');
431 $wgLoadBalancer->closeAll();
439 function wfErrorExit() {
440 wfAbruptExit( true );
444 * Die with a backtrace
445 * This is meant as a debugging aid to track down where bad data comes from.
446 * Shouldn't be used in production code except maybe in "shouldn't happen" areas.
448 * @param string $msg Message shown when dieing.
450 function wfDebugDieBacktrace( $msg = '' ) {
451 global $wgCommandLineMode;
453 $backtrace = wfBacktrace();
454 if ( $backtrace !== false ) {
455 if ( $wgCommandLineMode ) {
456 $msg .= "\nBacktrace:\n$backtrace";
458 $msg .= "\n<p>Backtrace:</p>\n$backtrace";
465 function wfBacktrace() {
466 global $wgCommandLineMode;
467 if ( !function_exists( 'debug_backtrace' ) ) {
471 if ( $wgCommandLineMode ) {
476 $backtrace = debug_backtrace();
477 foreach( $backtrace as $call ) {
478 if( isset( $call['file'] ) ) {
479 $f = explode( DIRECTORY_SEPARATOR
, $call['file'] );
480 $file = $f[count($f)-1];
484 if( isset( $call['line'] ) ) {
485 $line = $call['line'];
489 if ( $wgCommandLineMode ) {
490 $msg .= "$file line $line calls ";
492 $msg .= '<li>' . $file . ' line ' . $line . ' calls ';
494 if( !empty( $call['class'] ) ) $msg .= $call['class'] . '::';
495 $msg .= $call['function'] . '()';
497 if ( $wgCommandLineMode ) {
503 if ( $wgCommandLineMode ) {
513 /* Some generic result counters, pulled out of SearchEngine */
519 function wfShowingResults( $offset, $limit ) {
521 return wfMsg( 'showingresults', $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+
1 ) );
527 function wfShowingResultsNum( $offset, $limit, $num ) {
529 return wfMsg( 'showingresultsnum', $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+
1 ), $wgLang->formatNum( $num ) );
535 function wfViewPrevNext( $offset, $limit, $link, $query = '', $atend = false ) {
536 global $wgUser, $wgLang;
537 $fmtLimit = $wgLang->formatNum( $limit );
538 $prev = wfMsg( 'prevn', $fmtLimit );
539 $next = wfMsg( 'nextn', $fmtLimit );
541 if( is_object( $link ) ) {
544 $title = Title
::newFromText( $link );
545 if( is_null( $title ) ) {
550 $sk = $wgUser->getSkin();
551 if ( 0 != $offset ) {
552 $po = $offset - $limit;
553 if ( $po < 0 ) { $po = 0; }
554 $q = "limit={$limit}&offset={$po}";
555 if ( '' != $query ) { $q .= '&'.$query; }
556 $plink = '<a href="' . $title->escapeLocalUrl( $q ) . "\">{$prev}</a>";
557 } else { $plink = $prev; }
559 $no = $offset +
$limit;
560 $q = 'limit='.$limit.'&offset='.$no;
561 if ( '' != $query ) { $q .= '&'.$query; }
566 $nlink = '<a href="' . $title->escapeLocalUrl( $q ) . "\">{$next}</a>";
568 $nums = wfNumLink( $offset, 20, $title, $query ) . ' | ' .
569 wfNumLink( $offset, 50, $title, $query ) . ' | ' .
570 wfNumLink( $offset, 100, $title, $query ) . ' | ' .
571 wfNumLink( $offset, 250, $title, $query ) . ' | ' .
572 wfNumLink( $offset, 500, $title, $query );
574 return wfMsg( 'viewprevnext', $plink, $nlink, $nums );
580 function wfNumLink( $offset, $limit, &$title, $query = '' ) {
581 global $wgUser, $wgLang;
582 if ( '' == $query ) { $q = ''; }
583 else { $q = $query.'&'; }
584 $q .= 'limit='.$limit.'&offset='.$offset;
586 $fmtLimit = $wgLang->formatNum( $limit );
587 $s = '<a href="' . $title->escapeLocalUrl( $q ) . "\">{$fmtLimit}</a>";
593 * @todo FIXME: we may want to blacklist some broken browsers
595 * @return bool Whereas client accept gzip compression
597 function wfClientAcceptsGzip() {
600 # FIXME: we may want to blacklist some broken browsers
602 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
603 $_SERVER['HTTP_ACCEPT_ENCODING'],
605 if( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) return false;
606 wfDebug( " accepts gzip\n" );
614 * Yay, more global functions!
616 function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) {
618 return $wgRequest->getLimitOffset( $deflimit, $optionname );
622 * Escapes the given text so that it may be output using addWikiText()
623 * without any linking, formatting, etc. making its way through. This
624 * is achieved by substituting certain characters with HTML entities.
625 * As required by the callers, <nowiki> is not used. It currently does
626 * not filter out characters which have special meaning only at the
627 * start of a line, such as "*".
629 * @param string $text Text to be escaped
631 function wfEscapeWikiText( $text ) {
633 array( '[', '|', '\'', 'ISBN ' , '://' , "\n=", '{{' ),
634 array( '[', '|', ''', 'ISBN ', '://' , "\n=", '{{' ),
635 htmlspecialchars($text) );
642 function wfQuotedPrintable( $string, $charset = '' ) {
643 # Probably incomplete; see RFC 2045
644 if( empty( $charset ) ) {
645 global $wgInputEncoding;
646 $charset = $wgInputEncoding;
648 $charset = strtoupper( $charset );
649 $charset = str_replace( 'ISO-8859', 'ISO8859', $charset ); // ?
651 $illegal = '\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\xff=';
652 $replace = $illegal . '\t ?_';
653 if( !preg_match( "/[$illegal]/", $string ) ) return $string;
654 $out = "=?$charset?Q?";
655 $out .= preg_replace( "/([$replace])/e", 'sprintf("=%02X",ord("$1"))', $string );
661 * Returns an escaped string suitable for inclusion in a string literal
662 * for JavaScript source code.
663 * Illegal control characters are assumed not to be present.
665 * @param string $string
668 function wfEscapeJsString( $string ) {
669 // See ECMA 262 section 7.8.4 for string literal format
677 # To avoid closing the element or CDATA section
681 return strtr( $string, $pairs );
689 $st = explode( ' ', microtime() );
690 return (float)$st[0] +
(float)$st[1];
694 * Changes the first character to an HTML entity
696 function wfHtmlEscapeFirst( $text ) {
698 $newText = substr($text, 1);
699 return "&#$ord;$newText";
703 * Sets dest to source and returns the original value of dest
704 * If source is NULL, it just returns the value, it doesn't set the variable
706 function wfSetVar( &$dest, $source ) {
708 if ( !is_null( $source ) ) {
715 * As for wfSetVar except setting a bit
717 function wfSetBit( &$dest, $bit, $state = true ) {
718 $temp = (bool)($dest & $bit );
719 if ( !is_null( $state ) ) {
730 * This function takes two arrays as input, and returns a CGI-style string, e.g.
731 * "days=7&limit=100". Options in the first array override options in the second.
732 * Options set to "" will not be output.
734 function wfArrayToCGI( $array1, $array2 = NULL )
736 if ( !is_null( $array2 ) ) {
737 $array1 = $array1 +
$array2;
741 foreach ( $array1 as $key => $value ) {
742 if ( '' !== $value ) {
746 $cgi .= urlencode( $key ) . '=' . urlencode( $value );
753 * This is obsolete, use SquidUpdate::purge()
756 function wfPurgeSquidServers ($urlArr) {
757 SquidUpdate
::purge( $urlArr );
761 * Windows-compatible version of escapeshellarg()
762 * Windows doesn't recognise single-quotes in the shell, but the escapeshellarg()
763 * function puts single quotes in regardless of OS
765 function wfEscapeShellArg( ) {
766 $args = func_get_args();
769 foreach ( $args as $arg ) {
776 if ( wfIsWindows() ) {
777 $retVal .= '"' . str_replace( '"','\"', $arg ) . '"';
779 $retVal .= escapeshellarg( $arg );
786 * wfMerge attempts to merge differences between three texts.
787 * Returns true for a clean merge and false for failure or a conflict.
789 function wfMerge( $old, $mine, $yours, &$result ){
792 # This check may also protect against code injection in
793 # case of broken installations.
794 if(! file_exists( $wgDiff3 ) ){
798 # Make temporary files
800 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
801 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
802 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
804 fwrite( $oldtextFile, $old ); fclose( $oldtextFile );
805 fwrite( $mytextFile, $mine ); fclose( $mytextFile );
806 fwrite( $yourtextFile, $yours ); fclose( $yourtextFile );
808 # Check for a conflict
809 $cmd = wfEscapeShellArg( $wgDiff3 ) . ' -a --overlap-only ' .
810 wfEscapeShellArg( $mytextName ) . ' ' .
811 wfEscapeShellArg( $oldtextName ) . ' ' .
812 wfEscapeShellArg( $yourtextName );
813 $handle = popen( $cmd, 'r' );
815 if( fgets( $handle, 1024 ) ){
823 $cmd = wfEscapeShellArg( $wgDiff3 ) . ' -a -e --merge ' .
824 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
825 $handle = popen( $cmd, 'r' );
828 $data = fread( $handle, 8192 );
829 if ( strlen( $data ) == 0 ) {
835 unlink( $mytextName ); unlink( $oldtextName ); unlink( $yourtextName );
842 function wfVarDump( $var ) {
844 $s = str_replace("\n","<br />\n", var_export( $var, true ) . "\n");
845 if ( headers_sent() ||
!@is_object
( $wgOut ) ) {
848 $wgOut->addHTML( $s );
853 * Provide a simple HTTP error.
855 function wfHttpError( $code, $label, $desc ) {
858 header( "HTTP/1.0 $code $label" );
859 header( "Status: $code $label" );
860 $wgOut->sendCacheControl();
862 header( 'Content-type: text/html' );
863 print "<html><head><title>" .
864 htmlspecialchars( $label ) .
865 "</title></head><body><h1>" .
866 htmlspecialchars( $label ) .
868 htmlspecialchars( $desc ) .
869 "</p></body></html>\n";
873 * Converts an Accept-* header into an array mapping string values to quality
876 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
877 # No arg means accept anything (per HTTP spec)
879 return array( $def => 1 );
884 $parts = explode( ',', $accept );
886 foreach( $parts as $part ) {
887 # FIXME: doesn't deal with params like 'text/html; level=1'
888 @list
( $value, $qpart ) = explode( ';', $part );
889 if( !isset( $qpart ) ) {
891 } elseif( preg_match( '/q\s*=\s*(\d*\.\d+)/', $qpart, $match ) ) {
892 $prefs[$value] = $match[1];
900 * Checks if a given MIME type matches any of the keys in the given
901 * array. Basic wildcards are accepted in the array keys.
903 * Returns the matching MIME type (or wildcard) if a match, otherwise
906 * @param string $type
907 * @param array $avail
911 function mimeTypeMatch( $type, $avail ) {
912 if( array_key_exists($type, $avail) ) {
915 $parts = explode( '/', $type );
916 if( array_key_exists( $parts[0] . '/*', $avail ) ) {
917 return $parts[0] . '/*';
918 } elseif( array_key_exists( '*/*', $avail ) ) {
927 * Returns the 'best' match between a client's requested internet media types
928 * and the server's list of available types. Each list should be an associative
929 * array of type to preference (preference is a float between 0.0 and 1.0).
930 * Wildcards in the types are acceptable.
932 * @param array $cprefs Client's acceptable type list
933 * @param array $sprefs Server's offered types
936 * @todo FIXME: doesn't handle params like 'text/plain; charset=UTF-8'
937 * XXX: generalize to negotiate other stuff
939 function wfNegotiateType( $cprefs, $sprefs ) {
942 foreach( array_keys($sprefs) as $type ) {
943 $parts = explode( '/', $type );
944 if( $parts[1] != '*' ) {
945 $ckey = mimeTypeMatch( $type, $cprefs );
947 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
952 foreach( array_keys( $cprefs ) as $type ) {
953 $parts = explode( '/', $type );
954 if( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
955 $skey = mimeTypeMatch( $type, $sprefs );
957 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
965 foreach( array_keys( $combine ) as $type ) {
966 if( $combine[$type] > $bestq ) {
968 $bestq = $combine[$type];
977 * Returns an array where the values in the first array are replaced by the
978 * values in the second array with the corresponding keys
982 function wfArrayLookup( $a, $b ) {
983 return array_flip( array_intersect( array_flip( $a ), array_keys( $b ) ) );
987 * Convenience function; returns MediaWiki timestamp for the present time.
990 function wfTimestampNow() {
992 return wfTimestamp( TS_MW
, time() );
996 * Reference-counted warning suppression
998 function wfSuppressWarnings( $end = false ) {
999 static $suppressCount = 0;
1000 static $originalLevel = false;
1003 if ( $suppressCount ) {
1005 if ( !$suppressCount ) {
1006 error_reporting( $originalLevel );
1010 if ( !$suppressCount ) {
1011 $originalLevel = error_reporting( E_ALL
& ~
( E_WARNING | E_NOTICE
) );
1018 * Restore error level to previous value
1020 function wfRestoreWarnings() {
1021 wfSuppressWarnings( true );
1024 # Autodetect, convert and provide timestamps of various types
1027 * Unix time - the number of seconds since 1970-01-01 00:00:00 UTC
1029 define('TS_UNIX', 0);
1032 * MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
1037 * MySQL DATETIME (YYYY-MM-DD HH:MM:SS)
1042 * RFC 2822 format, for E-mail and HTTP headers
1044 define('TS_RFC2822', 3);
1047 * An Exif timestamp (YYYY:MM:DD HH:MM:SS)
1049 * @link http://exif.org/Exif2-2.PDF The Exif 2.2 spec, see page 28 for the
1050 * DateTime tag and page 36 for the DateTimeOriginal and
1051 * DateTimeDigitized tags.
1053 define('TS_EXIF', 4);
1056 * Oracle format time.
1058 define('TS_ORACLE', 5);
1061 * @param mixed $outputtype A timestamp in one of the supported formats, the
1062 * function will autodetect which format is supplied
1063 and act accordingly.
1064 * @return string Time in the format specified in $outputtype
1066 function wfTimestamp($outputtype=TS_UNIX
,$ts=0) {
1067 wfdebug("ts: $ts\n");
1070 } elseif (preg_match("/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)$/",$ts,$da)) {
1072 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1073 (int)$da[2],(int)$da[3],(int)$da[1]);
1074 } elseif (preg_match("/^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/",$ts,$da)) {
1076 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1077 (int)$da[2],(int)$da[3],(int)$da[1]);
1078 } elseif (preg_match("/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/",$ts,$da)) {
1080 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1081 (int)$da[2],(int)$da[3],(int)$da[1]);
1082 } elseif (preg_match("/^(\d{1,13})$/",$ts,$datearray)) {
1085 } elseif (preg_match('/^(\d{1,2})-(...)-(\d\d(\d\d)?) (\d\d)\.(\d\d)\.(\d\d)/', $ts, $da)) {
1087 $uts = strtotime(preg_replace('/(\d\d)\.(\d\d)\.(\d\d)(\.(\d+))?/', "$1:$2:$3",
1088 str_replace("+00:00", "UTC", $ts)));
1090 # Bogus value; fall back to the epoch...
1091 wfDebug("wfTimestamp() fed bogus time value: $outputtype; $ts\n");
1096 switch($outputtype) {
1100 return gmdate( 'YmdHis', $uts );
1102 return gmdate( 'Y-m-d H:i:s', $uts );
1103 // This shouldn't ever be used, but is included for completeness
1105 return gmdate( 'Y:m:d H:i:s', $uts );
1107 return gmdate( 'D, d M Y H:i:s', $uts ) . ' GMT';
1109 return gmdate( 'd-M-y h.i.s A', $uts) . ' +00:00';
1111 wfDebugDieBacktrace( 'wfTimestamp() called with illegal output type.');
1116 * Return a formatted timestamp, or null if input is null.
1117 * For dealing with nullable timestamp columns in the database.
1118 * @param int $outputtype
1122 function wfTimestampOrNull( $outputtype = TS_UNIX
, $ts = null ) {
1123 if( is_null( $ts ) ) {
1126 return wfTimestamp( $outputtype, $ts );
1131 * Check where as the operating system is Windows
1133 * @return bool True if it's windows, False otherwise.
1135 function wfIsWindows() {
1136 if (substr(php_uname(), 0, 7) == 'Windows') {
1144 * Swap two variables
1146 function swap( &$x, &$y ) {
1152 function wfGetSiteNotice() {
1153 global $wgSiteNotice, $wgTitle, $wgOut;
1154 $fname = 'wfGetSiteNotice';
1155 wfProfileIn( $fname );
1157 $notice = wfMsg( 'sitenotice' );
1158 if( $notice == '<sitenotice>' ||
$notice == '-' ) {
1161 if( $notice == '' ) {
1162 # We may also need to override a message with eg downtime info
1163 # FIXME: make this work!
1164 $notice = $wgSiteNotice;
1166 if($notice != '-' && $notice != '') {
1167 $specialparser = new Parser();
1168 $parserOutput = $specialparser->parse( $notice, $wgTitle, $wgOut->mParserOptions
, false );
1169 $notice = $parserOutput->getText();
1171 wfProfileOut( $fname );
1176 * Format an XML element with given attributes and, optionally, text content.
1177 * Element and attribute names are assumed to be ready for literal inclusion.
1178 * Strings are assumed to not contain XML-illegal characters; special
1179 * characters (<, >, &) are escaped but illegals are not touched.
1181 * @param string $element
1182 * @param array $attribs Name=>value pairs. Values will be escaped.
1183 * @param string $contents NULL to make an open tag only; '' for a contentless closed tag (default)
1186 function wfElement( $element, $attribs = null, $contents = '') {
1187 $out = '<' . $element;
1188 if( !is_null( $attribs ) ) {
1189 foreach( $attribs as $name => $val ) {
1190 $out .= ' ' . $name . '="' . htmlspecialchars( $val ) . '"';
1193 if( is_null( $contents ) ) {
1196 if( $contents == '' ) {
1200 $out .= htmlspecialchars( $contents );
1201 $out .= "</$element>";
1208 * Format an XML element as with wfElement(), but run text through the
1209 * UtfNormal::cleanUp() validator first to ensure that no invalid UTF-8
1212 * @param string $element
1213 * @param array $attribs Name=>value pairs. Values will be escaped.
1214 * @param string $contents NULL to make an open tag only; '' for a contentless closed tag (default)
1217 function wfElementClean( $element, $attribs = array(), $contents = '') {
1219 $attribs = array_map( array( 'UtfNormal', 'cleanUp' ), $attribs );
1222 $contents = UtfNormal
::cleanUp( $contents );
1224 return wfElement( $element, $attribs, $contents );
1228 * Create a namespace selector
1230 * @param mixed $selected The namespace which should be selected, default ''
1231 * @param string $allnamespaces Value of a special item denoting all namespaces. Null to not include (default)
1232 * @return Html string containing the namespace selector
1234 function &HTMLnamespaceselector($selected = '', $allnamespaces = null) {
1236 $s = "<select name='namespace' class='namespaceselector'>\n";
1237 $arr = $wgContLang->getFormattedNamespaces();
1238 if( !is_null($allnamespaces) ) {
1239 $arr = array($allnamespaces => wfMsgHtml('namespacesall')) +
$arr;
1241 foreach ($arr as $index => $name) {
1242 if ($index < NS_MAIN
) continue;
1244 $name = $index !== 0 ?
$name : wfMsgHtml('blanknamespace');
1246 if ($index === $selected) {
1247 $s .= wfElement("option",
1248 array("value" => $index, "selected" => "selected"),
1251 $s .= wfElement("option", array("value" => $index), $name);
1254 $s .= "</select>\n";
1258 /** Global singleton instance of MimeMagic. This is initialized on demand,
1259 * please always use the wfGetMimeMagic() function to get the instance.
1265 /** Factory functions for the global MimeMagic object.
1266 * This function always returns the same singleton instance of MimeMagic.
1267 * That objects will be instantiated on the first call to this function.
1268 * If needed, the MimeMagic.php file is automatically included by this function.
1269 * @return MimeMagic the global MimeMagic objects.
1271 function &wfGetMimeMagic() {
1272 global $wgMimeMagic;
1274 if (!is_null($wgMimeMagic)) {
1275 return $wgMimeMagic;
1278 if (!class_exists("MimeMagic")) {
1280 require_once("MimeMagic.php");
1283 $wgMimeMagic= new MimeMagic();
1285 return $wgMimeMagic;
1290 * Tries to get the system directory for temporary files.
1291 * The TMPDIR, TMP, and TEMP environment variables are checked in sequence,
1292 * and if none are set /tmp is returned as the generic Unix default.
1294 * NOTE: When possible, use the tempfile() function to create temporary
1295 * files to avoid race conditions on file creation, etc.
1299 function wfTempDir() {
1300 foreach( array( 'TMPDIR', 'TMP', 'TEMP' ) as $var ) {
1301 $tmp = getenv( $var );
1302 if( $tmp && file_exists( $tmp ) && is_dir( $tmp ) && is_writable( $tmp ) ) {
1306 # Hope this is Unix of some kind!
1311 * Make directory, and make all parent directories if they don't exist
1313 function wfMkdirParents( $fullDir, $mode ) {
1314 $parts = explode( '/', $fullDir );
1317 foreach ( $parts as $dir ) {
1318 $path .= $dir . '/';
1319 if ( !is_dir( $path ) ) {
1320 if ( !mkdir( $path, $mode ) ) {
1329 * Increment a statistics counter
1331 function wfIncrStats( $key ) {
1332 global $wgDBname, $wgMemc;
1333 $key = "$wgDBname:stats:$key";
1334 if ( is_null( $wgMemc->incr( $key ) ) ) {
1335 $wgMemc->add( $key, 1 );
1340 * @param mixed $nr The number to format
1341 * @param int $acc The number of digits after the decimal point, default 2
1342 * @param bool $round Whether or not to round the value, default true
1345 function wfPercent( $nr, $acc = 2, $round = true ) {
1346 $ret = sprintf( "%.${acc}f", $nr );
1347 return $round ?
round( $ret, $acc ) . '%' : "$ret%";
1351 * Encrypt a username/password.
1353 * @param string $userid ID of the user
1354 * @param string $password Password of the user
1355 * @return string Hashed password
1357 function wfEncryptPassword( $userid, $password ) {
1358 global $wgPasswordSalt;
1359 $p = md5( $password);
1362 return md5( "{$userid}-{$p}" );
1368 * Appends to second array if $value differs from that in $default
1370 function wfAppendToArrayIfNotDefault( $key, $value, $default, &$changed ) {
1371 if ( is_null( $changed ) ) {
1372 wfDebugDieBacktrace('GlobalFunctions::wfAppendToArrayIfNotDefault got null');
1374 if ( $default[$key] !== $value ) {
1375 $changed[$key] = $value;
1380 * Since wfMsg() and co suck, they don't return false if the message key they
1381 * looked up didn't exist but a XHTML string, this function checks for the
1382 * nonexistance of messages by looking at wfMsg() output
1384 * @param $msg The message key looked up
1385 * @param $wfMsgOut The output of wfMsg*()
1388 function wfNoMsg( $msg, $wfMsgOut ) {
1389 return $wfMsgOut === "<$msg>";