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 * Where as we got a random seed
84 * @var bool $wgTotalViews
86 $wgRandomSeeded = false;
89 * Seed Mersenne Twister
90 * Only necessary in PHP < 4.2.0
94 function wfSeedRandom() {
95 global $wgRandomSeeded;
97 if ( ! $wgRandomSeeded && version_compare( phpversion(), '4.2.0' ) < 0 ) {
98 $seed = hexdec(substr(md5(microtime()),-8)) & 0x7fffffff;
100 $wgRandomSeeded = true;
105 * Get a random decimal value between 0 and 1, in a way
106 * not likely to give duplicate values for any realistic
107 * number of articles.
111 function wfRandom() {
112 # The maximum random value is "only" 2^31-1, so get two random
113 # values to reduce the chance of dupes
114 $max = mt_getrandmax();
115 $rand = number_format( (mt_rand() * $max +
mt_rand())
116 / $max / $max, 12, '.', '' );
121 * We want / and : to be included as literal characters in our title URLs.
122 * %2F in the page titles seems to fatally break for some reason.
127 function wfUrlencode ( $s ) {
128 $s = urlencode( $s );
129 $s = preg_replace( '/%3[Aa]/', ':', $s );
130 $s = preg_replace( '/%2[Ff]/', '/', $s );
136 * Sends a line to the debug log if enabled or, optionally, to a comment in output.
137 * In normal operation this is a NOP.
139 * Controlling globals:
140 * $wgDebugLogFile - points to the log file
141 * $wgProfileOnly - if set, normal debug messages will not be recorded.
142 * $wgDebugRawPage - if false, 'action=raw' hits will not result in debug output.
143 * $wgDebugComments - if on, some debug items may appear in comments in the HTML output.
145 * @param string $text
146 * @param bool $logonly Set true to avoid appearing in HTML when $wgDebugComments is set
148 function wfDebug( $text, $logonly = false ) {
149 global $wgOut, $wgDebugLogFile, $wgDebugComments, $wgProfileOnly, $wgDebugRawPage;
151 # Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
152 if ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' && !$wgDebugRawPage ) {
156 if ( isset( $wgOut ) && $wgDebugComments && !$logonly ) {
157 $wgOut->debug( $text );
159 if ( '' != $wgDebugLogFile && !$wgProfileOnly ) {
160 # Strip unprintables; they can switch terminal modes when binary data
161 # gets dumped, which is pretty annoying.
162 $text = preg_replace( '![\x00-\x08\x0b\x0c\x0e-\x1f]!', ' ', $text );
163 @error_log
( $text, 3, $wgDebugLogFile );
168 * Log for database errors
169 * @param string $text Database error message.
171 function wfLogDBError( $text ) {
172 global $wgDBerrorLog;
173 if ( $wgDBerrorLog ) {
174 $text = date('D M j G:i:s T Y') . "\t".$text;
175 error_log( $text, 3, $wgDBerrorLog );
182 function logProfilingData() {
183 global $wgRequestTime, $wgDebugLogFile, $wgDebugRawPage, $wgRequest;
184 global $wgProfiling, $wgProfileStack, $wgProfileLimit, $wgUser;
187 list( $usec, $sec ) = explode( ' ', $wgRequestTime );
188 $start = (float)$sec +
(float)$usec;
189 $elapsed = $now - $start;
190 if ( $wgProfiling ) {
191 $prof = wfGetProfilingOutput( $start, $elapsed );
193 if( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) )
194 $forward = ' forwarded for ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
195 if( !empty( $_SERVER['HTTP_CLIENT_IP'] ) )
196 $forward .= ' client IP ' . $_SERVER['HTTP_CLIENT_IP'];
197 if( !empty( $_SERVER['HTTP_FROM'] ) )
198 $forward .= ' from ' . $_SERVER['HTTP_FROM'];
200 $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
201 if( $wgUser->isAnon() )
203 $log = sprintf( "%s\t%04.3f\t%s\n",
204 gmdate( 'YmdHis' ), $elapsed,
205 urldecode( $_SERVER['REQUEST_URI'] . $forward ) );
206 if ( '' != $wgDebugLogFile && ( $wgRequest->getVal('action') != 'raw' ||
$wgDebugRawPage ) ) {
207 error_log( $log . $prof, 3, $wgDebugLogFile );
213 * Check if the wiki read-only lock file is present. This can be used to lock
214 * off editing functions, but doesn't guarantee that the database will not be
218 function wfReadOnly() {
219 global $wgReadOnlyFile;
221 if ( '' == $wgReadOnlyFile ) {
224 return is_file( $wgReadOnlyFile );
229 * Get a message from anywhere, for the current user language
233 function wfMsg( $key ) {
234 $args = func_get_args();
235 array_shift( $args );
236 return wfMsgReal( $key, $args, true );
240 * Get a message from anywhere, for the current global language
242 function wfMsgForContent( $key ) {
243 global $wgForceUIMsgAsContentMsg;
244 $args = func_get_args();
245 array_shift( $args );
247 if( is_array( $wgForceUIMsgAsContentMsg ) &&
248 in_array( $key, $wgForceUIMsgAsContentMsg ) )
250 return wfMsgReal( $key, $args, true, $forcontent );
254 * Get a message from the language file, for the UI elements
256 function wfMsgNoDB( $key ) {
257 $args = func_get_args();
258 array_shift( $args );
259 return wfMsgReal( $key, $args, false );
263 * Get a message from the language file, for the content
265 function wfMsgNoDBForContent( $key ) {
266 global $wgForceUIMsgAsContentMsg;
267 $args = func_get_args();
268 array_shift( $args );
270 if( is_array( $wgForceUIMsgAsContentMsg ) &&
271 in_array( $key, $wgForceUIMsgAsContentMsg ) )
273 return wfMsgReal( $key, $args, false, $forcontent );
278 * Really get a message
280 function wfMsgReal( $key, $args, $useDB, $forContent=false ) {
281 static $replacementKeys = array( '$1', '$2', '$3', '$4', '$5', '$6', '$7', '$8', '$9' );
282 global $wgParser, $wgMsgParserOptions;
283 global $wgContLang, $wgLanguageCode;
284 global $wgMessageCache, $wgLang;
286 $fname = 'wfMsgReal';
287 wfProfileIn( $fname );
289 if( is_object( $wgMessageCache ) ) {
290 $message = $wgMessageCache->get( $key, $useDB, $forContent );
293 $lang = &$wgContLang;
298 wfSuppressWarnings();
300 if( is_object( $lang ) ) {
301 $message = $lang->getMessage( $key );
307 $message = Language
::getMessage($key);
308 if(strstr($message, '{{' ) !== false) {
309 $message = $wgParser->transformMsg($message, $wgMsgParserOptions);
313 # Fix windows line-endings
314 # Some messages are split with explode("\n", $msg)
315 $message = str_replace( "\r", '', $message );
318 if( count( $args ) ) {
319 $message = str_replace( $replacementKeys, $args, $message );
321 wfProfileOut( $fname );
328 * Just like exit() but makes a note of it.
329 * Commits open transactions except if the error parameter is set
331 function wfAbruptExit( $error = false ){
332 global $wgLoadBalancer;
333 static $called = false;
339 if( function_exists( 'debug_backtrace' ) ){ // PHP >= 4.3
340 $bt = debug_backtrace();
341 for($i = 0; $i < count($bt) ; $i++
){
342 $file = $bt[$i]['file'];
343 $line = $bt[$i]['line'];
344 wfDebug("WARNING: Abrupt exit in $file at line $line\n");
347 wfDebug('WARNING: Abrupt exit\n');
350 $wgLoadBalancer->closeAll();
358 function wfErrorExit() {
359 wfAbruptExit( true );
363 * Die with a backtrace
364 * This is meant as a debugging aid to track down where bad data comes from.
365 * Shouldn't be used in production code except maybe in "shouldn't happen" areas.
367 * @param string $msg Message shown when dieing.
369 function wfDebugDieBacktrace( $msg = '' ) {
370 global $wgCommandLineMode;
372 $backtrace = wfBacktrace();
373 if ( $backtrace !== false ) {
374 if ( $wgCommandLineMode ) {
375 $msg .= "\nBacktrace:\n$backtrace";
377 $msg .= "\n<p>Backtrace:</p>\n$backtrace";
383 function wfBacktrace() {
384 global $wgCommandLineMode;
385 if ( !function_exists( 'debug_backtrace' ) ) {
389 if ( $wgCommandLineMode ) {
394 $backtrace = debug_backtrace();
395 foreach( $backtrace as $call ) {
396 if( isset( $call['file'] ) ) {
397 $f = explode( DIRECTORY_SEPARATOR
, $call['file'] );
398 $file = $f[count($f)-1];
402 if( isset( $call['line'] ) ) {
403 $line = $call['line'];
407 if ( $wgCommandLineMode ) {
408 $msg .= "$file line $line calls ";
410 $msg .= '<li>' . $file . ' line ' . $line . ' calls ';
412 if( !empty( $call['class'] ) ) $msg .= $call['class'] . '::';
413 $msg .= $call['function'] . '()';
415 if ( $wgCommandLineMode ) {
421 if ( $wgCommandLineMode ) {
431 /* Some generic result counters, pulled out of SearchEngine */
437 function wfShowingResults( $offset, $limit ) {
439 return wfMsg( 'showingresults', $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+
1 ) );
445 function wfShowingResultsNum( $offset, $limit, $num ) {
447 return wfMsg( 'showingresultsnum', $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+
1 ), $wgLang->formatNum( $num ) );
453 function wfViewPrevNext( $offset, $limit, $link, $query = '', $atend = false ) {
454 global $wgUser, $wgLang;
455 $fmtLimit = $wgLang->formatNum( $limit );
456 $prev = wfMsg( 'prevn', $fmtLimit );
457 $next = wfMsg( 'nextn', $fmtLimit );
459 if( is_object( $link ) ) {
462 $title =& Title
::newFromText( $link );
463 if( is_null( $title ) ) {
468 $sk = $wgUser->getSkin();
469 if ( 0 != $offset ) {
470 $po = $offset - $limit;
471 if ( $po < 0 ) { $po = 0; }
472 $q = "limit={$limit}&offset={$po}";
473 if ( '' != $query ) { $q .= '&'.$query; }
474 $plink = '<a href="' . $title->escapeLocalUrl( $q ) . "\">{$prev}</a>";
475 } else { $plink = $prev; }
477 $no = $offset +
$limit;
478 $q = 'limit='.$limit.'&offset='.$no;
479 if ( '' != $query ) { $q .= '&'.$query; }
484 $nlink = '<a href="' . $title->escapeLocalUrl( $q ) . "\">{$next}</a>";
486 $nums = wfNumLink( $offset, 20, $title, $query ) . ' | ' .
487 wfNumLink( $offset, 50, $title, $query ) . ' | ' .
488 wfNumLink( $offset, 100, $title, $query ) . ' | ' .
489 wfNumLink( $offset, 250, $title, $query ) . ' | ' .
490 wfNumLink( $offset, 500, $title, $query );
492 return wfMsg( 'viewprevnext', $plink, $nlink, $nums );
498 function wfNumLink( $offset, $limit, &$title, $query = '' ) {
499 global $wgUser, $wgLang;
500 if ( '' == $query ) { $q = ''; }
501 else { $q = $query.'&'; }
502 $q .= 'limit='.$limit.'&offset='.$offset;
504 $fmtLimit = $wgLang->formatNum( $limit );
505 $s = '<a href="' . $title->escapeLocalUrl( $q ) . "\">{$fmtLimit}</a>";
511 * @todo FIXME: we may want to blacklist some broken browsers
513 * @return bool Whereas client accept gzip compression
515 function wfClientAcceptsGzip() {
518 # FIXME: we may want to blacklist some broken browsers
520 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
521 $_SERVER['HTTP_ACCEPT_ENCODING'],
523 if( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) return false;
524 wfDebug( " accepts gzip\n" );
532 * Yay, more global functions!
534 function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) {
536 return $wgRequest->getLimitOffset( $deflimit, $optionname );
540 * Escapes the given text so that it may be output using addWikiText()
541 * without any linking, formatting, etc. making its way through. This
542 * is achieved by substituting certain characters with HTML entities.
543 * As required by the callers, <nowiki> is not used. It currently does
544 * not filter out characters which have special meaning only at the
545 * start of a line, such as "*".
547 * @param string $text Text to be escaped
549 function wfEscapeWikiText( $text ) {
551 array( '[', '|', '\'', 'ISBN ' , '://' , "\n=", '{{' ),
552 array( '[', '|', ''', 'ISBN ', '://' , "\n=", '{{' ),
553 htmlspecialchars($text) );
560 function wfQuotedPrintable( $string, $charset = '' ) {
561 # Probably incomplete; see RFC 2045
562 if( empty( $charset ) ) {
563 global $wgInputEncoding;
564 $charset = $wgInputEncoding;
566 $charset = strtoupper( $charset );
567 $charset = str_replace( 'ISO-8859', 'ISO8859', $charset ); // ?
569 $illegal = '\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\xff=';
570 $replace = $illegal . '\t ?_';
571 if( !preg_match( "/[$illegal]/", $string ) ) return $string;
572 $out = "=?$charset?Q?";
573 $out .= preg_replace( "/([$replace])/e", 'sprintf("=%02X",ord("$1"))', $string );
579 * Returns an escaped string suitable for inclusion in a string literal
580 * for JavaScript source code.
581 * Illegal control characters are assumed not to be present.
583 * @param string $string
586 function wfEscapeJsString( $string ) {
587 // See ECMA 262 section 7.8.4 for string literal format
595 # To avoid closing the element or CDATA section
599 return strtr( $string, $pairs );
607 $st = explode( ' ', microtime() );
608 return (float)$st[0] +
(float)$st[1];
612 * Changes the first character to an HTML entity
614 function wfHtmlEscapeFirst( $text ) {
616 $newText = substr($text, 1);
617 return "&#$ord;$newText";
621 * Sets dest to source and returns the original value of dest
622 * If source is NULL, it just returns the value, it doesn't set the variable
624 function wfSetVar( &$dest, $source ) {
626 if ( !is_null( $source ) ) {
633 * As for wfSetVar except setting a bit
635 function wfSetBit( &$dest, $bit, $state = true ) {
636 $temp = (bool)($dest & $bit );
637 if ( !is_null( $state ) ) {
648 * This function takes two arrays as input, and returns a CGI-style string, e.g.
649 * "days=7&limit=100". Options in the first array override options in the second.
650 * Options set to "" will not be output.
652 function wfArrayToCGI( $array1, $array2 = NULL )
654 if ( !is_null( $array2 ) ) {
655 $array1 = $array1 +
$array2;
659 foreach ( $array1 as $key => $value ) {
660 if ( '' !== $value ) {
664 $cgi .= urlencode( $key ) . '=' . urlencode( $value );
671 * This is obsolete, use SquidUpdate::purge()
674 function wfPurgeSquidServers ($urlArr) {
675 SquidUpdate
::purge( $urlArr );
679 * Windows-compatible version of escapeshellarg()
680 * Windows doesn't recognise single-quotes in the shell, but the escapeshellarg()
681 * function puts single quotes in regardless of OS
683 function wfEscapeShellArg( ) {
684 $args = func_get_args();
687 foreach ( $args as $arg ) {
694 if ( wfIsWindows() ) {
695 $retVal .= '"' . str_replace( '"','\"', $arg ) . '"';
697 $retVal .= escapeshellarg( $arg );
704 * wfMerge attempts to merge differences between three texts.
705 * Returns true for a clean merge and false for failure or a conflict.
707 function wfMerge( $old, $mine, $yours, &$result ){
710 # This check may also protect against code injection in
711 # case of broken installations.
712 if(! file_exists( $wgDiff3 ) ){
716 # Make temporary files
718 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
719 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
720 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
722 fwrite( $oldtextFile, $old ); fclose( $oldtextFile );
723 fwrite( $mytextFile, $mine ); fclose( $mytextFile );
724 fwrite( $yourtextFile, $yours ); fclose( $yourtextFile );
726 # Check for a conflict
727 $cmd = wfEscapeShellArg( $wgDiff3 ) . ' -a --overlap-only ' .
728 wfEscapeShellArg( $mytextName ) . ' ' .
729 wfEscapeShellArg( $oldtextName ) . ' ' .
730 wfEscapeShellArg( $yourtextName );
731 $handle = popen( $cmd, 'r' );
733 if( fgets( $handle, 1024 ) ){
741 $cmd = wfEscapeShellArg( $wgDiff3 ) . ' -a -e --merge ' .
742 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
743 $handle = popen( $cmd, 'r' );
746 $data = fread( $handle, 8192 );
747 if ( strlen( $data ) == 0 ) {
753 unlink( $mytextName ); unlink( $oldtextName ); unlink( $yourtextName );
760 function wfVarDump( $var ) {
762 $s = str_replace("\n","<br />\n", var_export( $var, true ) . "\n");
763 if ( headers_sent() ||
!@is_object
( $wgOut ) ) {
766 $wgOut->addHTML( $s );
771 * Provide a simple HTTP error.
773 function wfHttpError( $code, $label, $desc ) {
776 header( "HTTP/1.0 $code $label" );
777 header( "Status: $code $label" );
778 $wgOut->sendCacheControl();
780 header( 'Content-type: text/html' );
781 print "<html><head><title>" .
782 htmlspecialchars( $label ) .
783 "</title></head><body><h1>" .
784 htmlspecialchars( $label ) .
786 htmlspecialchars( $desc ) .
787 "</p></body></html>\n";
791 * Converts an Accept-* header into an array mapping string values to quality
794 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
795 # No arg means accept anything (per HTTP spec)
797 return array( $def => 1 );
802 $parts = explode( ',', $accept );
804 foreach( $parts as $part ) {
805 # FIXME: doesn't deal with params like 'text/html; level=1'
806 @list
( $value, $qpart ) = explode( ';', $part );
807 if( !isset( $qpart ) ) {
809 } elseif( preg_match( '/q\s*=\s*(\d*\.\d+)/', $qpart, $match ) ) {
810 $prefs[$value] = $match[1];
818 * Checks if a given MIME type matches any of the keys in the given
819 * array. Basic wildcards are accepted in the array keys.
821 * Returns the matching MIME type (or wildcard) if a match, otherwise
824 * @param string $type
825 * @param array $avail
829 function mimeTypeMatch( $type, $avail ) {
830 if( array_key_exists($type, $avail) ) {
833 $parts = explode( '/', $type );
834 if( array_key_exists( $parts[0] . '/*', $avail ) ) {
835 return $parts[0] . '/*';
836 } elseif( array_key_exists( '*/*', $avail ) ) {
845 * Returns the 'best' match between a client's requested internet media types
846 * and the server's list of available types. Each list should be an associative
847 * array of type to preference (preference is a float between 0.0 and 1.0).
848 * Wildcards in the types are acceptable.
850 * @param array $cprefs Client's acceptable type list
851 * @param array $sprefs Server's offered types
854 * @todo FIXME: doesn't handle params like 'text/plain; charset=UTF-8'
855 * XXX: generalize to negotiate other stuff
857 function wfNegotiateType( $cprefs, $sprefs ) {
860 foreach( array_keys($sprefs) as $type ) {
861 $parts = explode( '/', $type );
862 if( $parts[1] != '*' ) {
863 $ckey = mimeTypeMatch( $type, $cprefs );
865 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
870 foreach( array_keys( $cprefs ) as $type ) {
871 $parts = explode( '/', $type );
872 if( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
873 $skey = mimeTypeMatch( $type, $sprefs );
875 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
883 foreach( array_keys( $combine ) as $type ) {
884 if( $combine[$type] > $bestq ) {
886 $bestq = $combine[$type];
895 * Returns an array where the values in the first array are replaced by the
896 * values in the second array with the corresponding keys
900 function wfArrayLookup( $a, $b ) {
901 return array_flip( array_intersect( array_flip( $a ), array_keys( $b ) ) );
905 * Convenience function; returns MediaWiki timestamp for the present time.
908 function wfTimestampNow() {
910 return wfTimestamp( TS_MW
, time() );
914 * Reference-counted warning suppression
916 function wfSuppressWarnings( $end = false ) {
917 static $suppressCount = 0;
918 static $originalLevel = false;
921 if ( $suppressCount ) {
923 if ( !$suppressCount ) {
924 error_reporting( $originalLevel );
928 if ( !$suppressCount ) {
929 $originalLevel = error_reporting( E_ALL
& ~
( E_WARNING | E_NOTICE
) );
936 * Restore error level to previous value
938 function wfRestoreWarnings() {
939 wfSuppressWarnings( true );
942 # Autodetect, convert and provide timestamps of various types
945 * Unix time - the number of seconds since 1970-01-01 00:00:00 UTC
947 define('TS_UNIX', 0);
950 * MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
955 * MySQL DATETIME (YYYY-MM-DD HH:MM:SS)
960 * RFC 2822 format, for E-mail and HTTP headers
962 define('TS_RFC2822', 3);
965 * An Exif timestamp (YYYY:MM:DD HH:MM:SS)
967 * @link http://exif.org/Exif2-2.PDF The Exif 2.2 spec, see page 28 for the
968 * DateTime tag and page 36 for the DateTimeOriginal and
969 * DateTimeDigitized tags.
971 define('TS_EXIF', 4);
975 * @param mixed $outputtype A timestamp in one of the supported formats, the
976 * function will autodetect which format is supplied
978 * @return string Time in the format specified in $outputtype
980 function wfTimestamp($outputtype=TS_UNIX
,$ts=0) {
983 } elseif (preg_match("/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)$/",$ts,$da)) {
985 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
986 (int)$da[2],(int)$da[3],(int)$da[1]);
987 } elseif (preg_match("/^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/",$ts,$da)) {
989 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
990 (int)$da[2],(int)$da[3],(int)$da[1]);
991 } elseif (preg_match("/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/",$ts,$da)) {
993 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
994 (int)$da[2],(int)$da[3],(int)$da[1]);
995 } elseif (preg_match("/^(\d{1,13})$/",$ts,$datearray)) {
999 # Bogus value; fall back to the epoch...
1000 wfDebug("wfTimestamp() fed bogus time value: $outputtype; $ts\n");
1005 switch($outputtype) {
1009 return gmdate( 'YmdHis', $uts );
1011 return gmdate( 'Y-m-d H:i:s', $uts );
1012 // This shouldn't ever be used, but is included for completeness
1014 return gmdate( 'Y:m:d H:i:s', $uts );
1016 return gmdate( 'D, d M Y H:i:s', $uts ) . ' GMT';
1018 wfDebugDieBacktrace( 'wfTimestamp() called with illegal output type.');
1023 * Return a formatted timestamp, or null if input is null.
1024 * For dealing with nullable timestamp columns in the database.
1025 * @param int $outputtype
1029 function wfTimestampOrNull( $outputtype = TS_UNIX
, $ts = null ) {
1030 if( is_null( $ts ) ) {
1033 return wfTimestamp( $outputtype, $ts );
1038 * Check where as the operating system is Windows
1040 * @return bool True if it's windows, False otherwise.
1042 function wfIsWindows() {
1043 if (substr(php_uname(), 0, 7) == 'Windows') {
1051 * Swap two variables
1053 function swap( &$x, &$y ) {
1059 function wfGetSiteNotice() {
1060 global $wgSiteNotice, $wgTitle, $wgOut;
1061 $fname = 'wfGetSiteNotice';
1062 wfProfileIn( $fname );
1064 $notice = wfMsg( 'sitenotice' );
1065 if($notice == '<sitenotice>') $notice = '';
1066 # Allow individual wikis to turn it off
1067 if ( $notice == '-' ) {
1070 if ($notice == '') {
1071 $notice = $wgSiteNotice;
1073 if($notice != '-' && $notice != '') {
1074 $specialparser = new Parser();
1075 $parserOutput = $specialparser->parse( $notice, $wgTitle, $wgOut->mParserOptions
, false );
1076 $notice = $parserOutput->getText();
1079 wfProfileOut( $fname );
1084 * Format an XML element with given attributes and, optionally, text content.
1085 * Element and attribute names are assumed to be ready for literal inclusion.
1086 * Strings are assumed to not contain XML-illegal characters; special
1087 * characters (<, >, &) are escaped but illegals are not touched.
1089 * @param string $element
1090 * @param array $attribs Name=>value pairs. Values will be escaped.
1091 * @param bool $contents NULL to make an open tag only; '' for a contentless closed tag (default)
1094 function wfElement( $element, $attribs = array(), $contents = '') {
1095 $out = '<' . $element;
1096 foreach( $attribs as $name => $val ) {
1097 $out .= ' ' . $name . '="' . htmlspecialchars( $val ) . '"';
1099 if( is_null( $contents ) ) {
1102 if( $contents == '' ) {
1106 $out .= htmlspecialchars( $contents );
1107 $out .= "</$element>";
1114 * Format an XML element as with wfElement(), but run text through the
1115 * UtfNormal::cleanUp() validator first to ensure that no invalid UTF-8
1118 * @param string $element
1119 * @param array $attribs Name=>value pairs. Values will be escaped.
1120 * @param bool $contents NULL to make an open tag only; '' for a contentless closed tag (default)
1123 function wfElementClean( $element, $attribs = array(), $contents = '') {
1125 $attribs = array_map( array( 'UtfNormal', 'cleanUp' ), $attribs );
1127 return wfElement( $element, $attribs, UtfNormal
::cleanUp( $contents ) );
1130 /** Global singleton instance of MimeMagic. This is initialized on demand,
1131 * please always use the wfGetMimeMagic() function to get the instance.
1137 /** Factory functions for the global MimeMagic object.
1138 * This function always returns the same singleton instance of MimeMagic.
1139 * That objects will be instantiated on the first call to this function.
1140 * If needed, the MimeMagic.php file is automatically included by this function.
1141 * @return MimeMagic the global MimeMagic objects.
1143 function &wfGetMimeMagic() {
1144 global $wgMimeMagic;
1146 if (!is_null($wgMimeMagic)) {
1147 return $wgMimeMagic;
1150 if (!class_exists("MimeMagic")) {
1152 require_once("MimeMagic.php");
1155 $wgMimeMagic= new MimeMagic();
1157 return $wgMimeMagic;
1162 * Tries to get the system directory for temporary files.
1163 * The TMPDIR, TMP, and TEMP environment variables are checked in sequence,
1164 * and if none are set /tmp is returned as the generic Unix default.
1166 * NOTE: When possible, use the tempfile() function to create temporary
1167 * files to avoid race conditions on file creation, etc.
1171 function wfTempDir() {
1172 foreach( array( 'TMPDIR', 'TMP', 'TEMP' ) as $var ) {
1173 $tmp = getenv( 'TMPDIR' );
1174 if( $tmp && file_exists( $tmp ) && is_dir( $tmp ) && is_writable( $tmp ) ) {
1178 # Hope this is Unix of some kind!
1183 * Make directory, and make all parent directories if they don't exist
1185 function wfMkdirParents( $fullDir, $mode ) {
1186 $parts = explode( '/', $fullDir );
1189 foreach ( $parts as $dir ) {
1190 $path .= $dir . '/';
1191 if ( !is_dir( $path ) ) {
1192 if ( !mkdir( $path, $mode ) ) {