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, $wgReadOnly;
224 if ( '' == $wgReadOnlyFile ) {
228 // Set $wgReadOnly and unset $wgReadOnlyFile, for faster access next time
229 if ( is_file( $wgReadOnlyFile ) ) {
234 $wgReadOnlyFile = '';
240 * Get a message from anywhere, for the current user language
244 function wfMsg( $key ) {
245 $args = func_get_args();
246 array_shift( $args );
247 return wfMsgReal( $key, $args, true );
251 * Get a message from anywhere, for the current global language
253 function wfMsgForContent( $key ) {
254 global $wgForceUIMsgAsContentMsg;
255 $args = func_get_args();
256 array_shift( $args );
258 if( is_array( $wgForceUIMsgAsContentMsg ) &&
259 in_array( $key, $wgForceUIMsgAsContentMsg ) )
261 return wfMsgReal( $key, $args, true, $forcontent );
265 * Get a message from the language file, for the UI elements
267 function wfMsgNoDB( $key ) {
268 $args = func_get_args();
269 array_shift( $args );
270 return wfMsgReal( $key, $args, false );
274 * Get a message from the language file, for the content
276 function wfMsgNoDBForContent( $key ) {
277 global $wgForceUIMsgAsContentMsg;
278 $args = func_get_args();
279 array_shift( $args );
281 if( is_array( $wgForceUIMsgAsContentMsg ) &&
282 in_array( $key, $wgForceUIMsgAsContentMsg ) )
284 return wfMsgReal( $key, $args, false, $forcontent );
289 * Really get a message
291 function wfMsgReal( $key, $args, $useDB, $forContent=false ) {
292 $fname = 'wfMsgReal';
293 wfProfileIn( $fname );
295 $message = wfMsgGetKey( $key, $useDB, $forContent );
296 $message = wfMsgReplaceArgs( $message, $args );
297 wfProfileOut( $fname );
302 * Fetch a message string value, but don't replace any keys yet.
305 * @param bool $forContent
309 function wfMsgGetKey( $key, $useDB, $forContent = false ) {
310 global $wgParser, $wgMsgParserOptions;
311 global $wgContLang, $wgLanguageCode;
312 global $wgMessageCache, $wgLang;
314 if( is_object( $wgMessageCache ) ) {
315 $message = $wgMessageCache->get( $key, $useDB, $forContent );
318 $lang = &$wgContLang;
323 wfSuppressWarnings();
325 if( is_object( $lang ) ) {
326 $message = $lang->getMessage( $key );
332 $message = Language
::getMessage($key);
333 if(strstr($message, '{{' ) !== false) {
334 $message = $wgParser->transformMsg($message, $wgMsgParserOptions);
341 * Replace message parameter keys on the given formatted output.
343 * @param string $message
348 function wfMsgReplaceArgs( $message, $args ) {
349 static $replacementKeys = array( '$1', '$2', '$3', '$4', '$5', '$6', '$7', '$8', '$9' );
351 # Fix windows line-endings
352 # Some messages are split with explode("\n", $msg)
353 $message = str_replace( "\r", '', $message );
356 if( count( $args ) ) {
357 $message = str_replace( $replacementKeys, $args, $message );
363 * Return an HTML-escaped version of a message.
364 * Parameter replacements, if any, are done *after* the HTML-escaping,
365 * so parameters may contain HTML (eg links or form controls). Be sure
366 * to pre-escape them if you really do want plaintext, or just wrap
367 * the whole thing in htmlspecialchars().
370 * @param string ... parameters
373 function wfMsgHtml( $key ) {
374 $args = func_get_args();
375 array_shift( $args );
376 return wfMsgReplaceArgs( htmlspecialchars( wfMsgGetKey( $key, true ) ), $args );
380 * Just like exit() but makes a note of it.
381 * Commits open transactions except if the error parameter is set
383 function wfAbruptExit( $error = false ){
384 global $wgLoadBalancer;
385 static $called = false;
391 if( function_exists( 'debug_backtrace' ) ){ // PHP >= 4.3
392 $bt = debug_backtrace();
393 for($i = 0; $i < count($bt) ; $i++
){
394 $file = $bt[$i]['file'];
395 $line = $bt[$i]['line'];
396 wfDebug("WARNING: Abrupt exit in $file at line $line\n");
399 wfDebug('WARNING: Abrupt exit\n');
402 $wgLoadBalancer->closeAll();
410 function wfErrorExit() {
411 wfAbruptExit( true );
415 * Die with a backtrace
416 * This is meant as a debugging aid to track down where bad data comes from.
417 * Shouldn't be used in production code except maybe in "shouldn't happen" areas.
419 * @param string $msg Message shown when dieing.
421 function wfDebugDieBacktrace( $msg = '' ) {
422 global $wgCommandLineMode;
424 $backtrace = wfBacktrace();
425 if ( $backtrace !== false ) {
426 if ( $wgCommandLineMode ) {
427 $msg .= "\nBacktrace:\n$backtrace";
429 $msg .= "\n<p>Backtrace:</p>\n$backtrace";
436 function wfBacktrace() {
437 global $wgCommandLineMode;
438 if ( !function_exists( 'debug_backtrace' ) ) {
442 if ( $wgCommandLineMode ) {
447 $backtrace = debug_backtrace();
448 foreach( $backtrace as $call ) {
449 if( isset( $call['file'] ) ) {
450 $f = explode( DIRECTORY_SEPARATOR
, $call['file'] );
451 $file = $f[count($f)-1];
455 if( isset( $call['line'] ) ) {
456 $line = $call['line'];
460 if ( $wgCommandLineMode ) {
461 $msg .= "$file line $line calls ";
463 $msg .= '<li>' . $file . ' line ' . $line . ' calls ';
465 if( !empty( $call['class'] ) ) $msg .= $call['class'] . '::';
466 $msg .= $call['function'] . '()';
468 if ( $wgCommandLineMode ) {
474 if ( $wgCommandLineMode ) {
484 /* Some generic result counters, pulled out of SearchEngine */
490 function wfShowingResults( $offset, $limit ) {
492 return wfMsg( 'showingresults', $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+
1 ) );
498 function wfShowingResultsNum( $offset, $limit, $num ) {
500 return wfMsg( 'showingresultsnum', $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+
1 ), $wgLang->formatNum( $num ) );
506 function wfViewPrevNext( $offset, $limit, $link, $query = '', $atend = false ) {
507 global $wgUser, $wgLang;
508 $fmtLimit = $wgLang->formatNum( $limit );
509 $prev = wfMsg( 'prevn', $fmtLimit );
510 $next = wfMsg( 'nextn', $fmtLimit );
512 if( is_object( $link ) ) {
515 $title =& Title
::newFromText( $link );
516 if( is_null( $title ) ) {
521 $sk = $wgUser->getSkin();
522 if ( 0 != $offset ) {
523 $po = $offset - $limit;
524 if ( $po < 0 ) { $po = 0; }
525 $q = "limit={$limit}&offset={$po}";
526 if ( '' != $query ) { $q .= '&'.$query; }
527 $plink = '<a href="' . $title->escapeLocalUrl( $q ) . "\">{$prev}</a>";
528 } else { $plink = $prev; }
530 $no = $offset +
$limit;
531 $q = 'limit='.$limit.'&offset='.$no;
532 if ( '' != $query ) { $q .= '&'.$query; }
537 $nlink = '<a href="' . $title->escapeLocalUrl( $q ) . "\">{$next}</a>";
539 $nums = wfNumLink( $offset, 20, $title, $query ) . ' | ' .
540 wfNumLink( $offset, 50, $title, $query ) . ' | ' .
541 wfNumLink( $offset, 100, $title, $query ) . ' | ' .
542 wfNumLink( $offset, 250, $title, $query ) . ' | ' .
543 wfNumLink( $offset, 500, $title, $query );
545 return wfMsg( 'viewprevnext', $plink, $nlink, $nums );
551 function wfNumLink( $offset, $limit, &$title, $query = '' ) {
552 global $wgUser, $wgLang;
553 if ( '' == $query ) { $q = ''; }
554 else { $q = $query.'&'; }
555 $q .= 'limit='.$limit.'&offset='.$offset;
557 $fmtLimit = $wgLang->formatNum( $limit );
558 $s = '<a href="' . $title->escapeLocalUrl( $q ) . "\">{$fmtLimit}</a>";
564 * @todo FIXME: we may want to blacklist some broken browsers
566 * @return bool Whereas client accept gzip compression
568 function wfClientAcceptsGzip() {
571 # FIXME: we may want to blacklist some broken browsers
573 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
574 $_SERVER['HTTP_ACCEPT_ENCODING'],
576 if( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) return false;
577 wfDebug( " accepts gzip\n" );
585 * Yay, more global functions!
587 function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) {
589 return $wgRequest->getLimitOffset( $deflimit, $optionname );
593 * Escapes the given text so that it may be output using addWikiText()
594 * without any linking, formatting, etc. making its way through. This
595 * is achieved by substituting certain characters with HTML entities.
596 * As required by the callers, <nowiki> is not used. It currently does
597 * not filter out characters which have special meaning only at the
598 * start of a line, such as "*".
600 * @param string $text Text to be escaped
602 function wfEscapeWikiText( $text ) {
604 array( '[', '|', '\'', 'ISBN ' , '://' , "\n=", '{{' ),
605 array( '[', '|', ''', 'ISBN ', '://' , "\n=", '{{' ),
606 htmlspecialchars($text) );
613 function wfQuotedPrintable( $string, $charset = '' ) {
614 # Probably incomplete; see RFC 2045
615 if( empty( $charset ) ) {
616 global $wgInputEncoding;
617 $charset = $wgInputEncoding;
619 $charset = strtoupper( $charset );
620 $charset = str_replace( 'ISO-8859', 'ISO8859', $charset ); // ?
622 $illegal = '\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\xff=';
623 $replace = $illegal . '\t ?_';
624 if( !preg_match( "/[$illegal]/", $string ) ) return $string;
625 $out = "=?$charset?Q?";
626 $out .= preg_replace( "/([$replace])/e", 'sprintf("=%02X",ord("$1"))', $string );
632 * Returns an escaped string suitable for inclusion in a string literal
633 * for JavaScript source code.
634 * Illegal control characters are assumed not to be present.
636 * @param string $string
639 function wfEscapeJsString( $string ) {
640 // See ECMA 262 section 7.8.4 for string literal format
648 # To avoid closing the element or CDATA section
652 return strtr( $string, $pairs );
660 $st = explode( ' ', microtime() );
661 return (float)$st[0] +
(float)$st[1];
665 * Changes the first character to an HTML entity
667 function wfHtmlEscapeFirst( $text ) {
669 $newText = substr($text, 1);
670 return "&#$ord;$newText";
674 * Sets dest to source and returns the original value of dest
675 * If source is NULL, it just returns the value, it doesn't set the variable
677 function wfSetVar( &$dest, $source ) {
679 if ( !is_null( $source ) ) {
686 * As for wfSetVar except setting a bit
688 function wfSetBit( &$dest, $bit, $state = true ) {
689 $temp = (bool)($dest & $bit );
690 if ( !is_null( $state ) ) {
701 * This function takes two arrays as input, and returns a CGI-style string, e.g.
702 * "days=7&limit=100". Options in the first array override options in the second.
703 * Options set to "" will not be output.
705 function wfArrayToCGI( $array1, $array2 = NULL )
707 if ( !is_null( $array2 ) ) {
708 $array1 = $array1 +
$array2;
712 foreach ( $array1 as $key => $value ) {
713 if ( '' !== $value ) {
717 $cgi .= urlencode( $key ) . '=' . urlencode( $value );
724 * This is obsolete, use SquidUpdate::purge()
727 function wfPurgeSquidServers ($urlArr) {
728 SquidUpdate
::purge( $urlArr );
732 * Windows-compatible version of escapeshellarg()
733 * Windows doesn't recognise single-quotes in the shell, but the escapeshellarg()
734 * function puts single quotes in regardless of OS
736 function wfEscapeShellArg( ) {
737 $args = func_get_args();
740 foreach ( $args as $arg ) {
747 if ( wfIsWindows() ) {
748 $retVal .= '"' . str_replace( '"','\"', $arg ) . '"';
750 $retVal .= escapeshellarg( $arg );
757 * wfMerge attempts to merge differences between three texts.
758 * Returns true for a clean merge and false for failure or a conflict.
760 function wfMerge( $old, $mine, $yours, &$result ){
763 # This check may also protect against code injection in
764 # case of broken installations.
765 if(! file_exists( $wgDiff3 ) ){
769 # Make temporary files
771 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
772 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
773 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
775 fwrite( $oldtextFile, $old ); fclose( $oldtextFile );
776 fwrite( $mytextFile, $mine ); fclose( $mytextFile );
777 fwrite( $yourtextFile, $yours ); fclose( $yourtextFile );
779 # Check for a conflict
780 $cmd = wfEscapeShellArg( $wgDiff3 ) . ' -a --overlap-only ' .
781 wfEscapeShellArg( $mytextName ) . ' ' .
782 wfEscapeShellArg( $oldtextName ) . ' ' .
783 wfEscapeShellArg( $yourtextName );
784 $handle = popen( $cmd, 'r' );
786 if( fgets( $handle, 1024 ) ){
794 $cmd = wfEscapeShellArg( $wgDiff3 ) . ' -a -e --merge ' .
795 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
796 $handle = popen( $cmd, 'r' );
799 $data = fread( $handle, 8192 );
800 if ( strlen( $data ) == 0 ) {
806 unlink( $mytextName ); unlink( $oldtextName ); unlink( $yourtextName );
813 function wfVarDump( $var ) {
815 $s = str_replace("\n","<br />\n", var_export( $var, true ) . "\n");
816 if ( headers_sent() ||
!@is_object
( $wgOut ) ) {
819 $wgOut->addHTML( $s );
824 * Provide a simple HTTP error.
826 function wfHttpError( $code, $label, $desc ) {
829 header( "HTTP/1.0 $code $label" );
830 header( "Status: $code $label" );
831 $wgOut->sendCacheControl();
833 header( 'Content-type: text/html' );
834 print "<html><head><title>" .
835 htmlspecialchars( $label ) .
836 "</title></head><body><h1>" .
837 htmlspecialchars( $label ) .
839 htmlspecialchars( $desc ) .
840 "</p></body></html>\n";
844 * Converts an Accept-* header into an array mapping string values to quality
847 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
848 # No arg means accept anything (per HTTP spec)
850 return array( $def => 1 );
855 $parts = explode( ',', $accept );
857 foreach( $parts as $part ) {
858 # FIXME: doesn't deal with params like 'text/html; level=1'
859 @list
( $value, $qpart ) = explode( ';', $part );
860 if( !isset( $qpart ) ) {
862 } elseif( preg_match( '/q\s*=\s*(\d*\.\d+)/', $qpart, $match ) ) {
863 $prefs[$value] = $match[1];
871 * Checks if a given MIME type matches any of the keys in the given
872 * array. Basic wildcards are accepted in the array keys.
874 * Returns the matching MIME type (or wildcard) if a match, otherwise
877 * @param string $type
878 * @param array $avail
882 function mimeTypeMatch( $type, $avail ) {
883 if( array_key_exists($type, $avail) ) {
886 $parts = explode( '/', $type );
887 if( array_key_exists( $parts[0] . '/*', $avail ) ) {
888 return $parts[0] . '/*';
889 } elseif( array_key_exists( '*/*', $avail ) ) {
898 * Returns the 'best' match between a client's requested internet media types
899 * and the server's list of available types. Each list should be an associative
900 * array of type to preference (preference is a float between 0.0 and 1.0).
901 * Wildcards in the types are acceptable.
903 * @param array $cprefs Client's acceptable type list
904 * @param array $sprefs Server's offered types
907 * @todo FIXME: doesn't handle params like 'text/plain; charset=UTF-8'
908 * XXX: generalize to negotiate other stuff
910 function wfNegotiateType( $cprefs, $sprefs ) {
913 foreach( array_keys($sprefs) as $type ) {
914 $parts = explode( '/', $type );
915 if( $parts[1] != '*' ) {
916 $ckey = mimeTypeMatch( $type, $cprefs );
918 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
923 foreach( array_keys( $cprefs ) as $type ) {
924 $parts = explode( '/', $type );
925 if( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
926 $skey = mimeTypeMatch( $type, $sprefs );
928 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
936 foreach( array_keys( $combine ) as $type ) {
937 if( $combine[$type] > $bestq ) {
939 $bestq = $combine[$type];
948 * Returns an array where the values in the first array are replaced by the
949 * values in the second array with the corresponding keys
953 function wfArrayLookup( $a, $b ) {
954 return array_flip( array_intersect( array_flip( $a ), array_keys( $b ) ) );
958 * Convenience function; returns MediaWiki timestamp for the present time.
961 function wfTimestampNow() {
963 return wfTimestamp( TS_MW
, time() );
967 * Reference-counted warning suppression
969 function wfSuppressWarnings( $end = false ) {
970 static $suppressCount = 0;
971 static $originalLevel = false;
974 if ( $suppressCount ) {
976 if ( !$suppressCount ) {
977 error_reporting( $originalLevel );
981 if ( !$suppressCount ) {
982 $originalLevel = error_reporting( E_ALL
& ~
( E_WARNING | E_NOTICE
) );
989 * Restore error level to previous value
991 function wfRestoreWarnings() {
992 wfSuppressWarnings( true );
995 # Autodetect, convert and provide timestamps of various types
998 * Unix time - the number of seconds since 1970-01-01 00:00:00 UTC
1000 define('TS_UNIX', 0);
1003 * MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
1008 * MySQL DATETIME (YYYY-MM-DD HH:MM:SS)
1013 * RFC 2822 format, for E-mail and HTTP headers
1015 define('TS_RFC2822', 3);
1018 * An Exif timestamp (YYYY:MM:DD HH:MM:SS)
1020 * @link http://exif.org/Exif2-2.PDF The Exif 2.2 spec, see page 28 for the
1021 * DateTime tag and page 36 for the DateTimeOriginal and
1022 * DateTimeDigitized tags.
1024 define('TS_EXIF', 4);
1028 * @param mixed $outputtype A timestamp in one of the supported formats, the
1029 * function will autodetect which format is supplied
1030 and act accordingly.
1031 * @return string Time in the format specified in $outputtype
1033 function wfTimestamp($outputtype=TS_UNIX
,$ts=0) {
1036 } elseif (preg_match("/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)$/",$ts,$da)) {
1038 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1039 (int)$da[2],(int)$da[3],(int)$da[1]);
1040 } elseif (preg_match("/^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/",$ts,$da)) {
1042 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1043 (int)$da[2],(int)$da[3],(int)$da[1]);
1044 } elseif (preg_match("/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/",$ts,$da)) {
1046 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1047 (int)$da[2],(int)$da[3],(int)$da[1]);
1048 } elseif (preg_match("/^(\d{1,13})$/",$ts,$datearray)) {
1052 # Bogus value; fall back to the epoch...
1053 wfDebug("wfTimestamp() fed bogus time value: $outputtype; $ts\n");
1058 switch($outputtype) {
1062 return gmdate( 'YmdHis', $uts );
1064 return gmdate( 'Y-m-d H:i:s', $uts );
1065 // This shouldn't ever be used, but is included for completeness
1067 return gmdate( 'Y:m:d H:i:s', $uts );
1069 return gmdate( 'D, d M Y H:i:s', $uts ) . ' GMT';
1071 wfDebugDieBacktrace( 'wfTimestamp() called with illegal output type.');
1076 * Return a formatted timestamp, or null if input is null.
1077 * For dealing with nullable timestamp columns in the database.
1078 * @param int $outputtype
1082 function wfTimestampOrNull( $outputtype = TS_UNIX
, $ts = null ) {
1083 if( is_null( $ts ) ) {
1086 return wfTimestamp( $outputtype, $ts );
1091 * Check where as the operating system is Windows
1093 * @return bool True if it's windows, False otherwise.
1095 function wfIsWindows() {
1096 if (substr(php_uname(), 0, 7) == 'Windows') {
1104 * Swap two variables
1106 function swap( &$x, &$y ) {
1112 function wfGetSiteNotice() {
1113 global $wgSiteNotice, $wgTitle, $wgOut;
1114 $fname = 'wfGetSiteNotice';
1115 wfProfileIn( $fname );
1117 $notice = wfMsg( 'sitenotice' );
1118 if( $notice == '<sitenotice>' ||
$notice == '-' ) {
1121 if( $notice == '' ) {
1122 # We may also need to override a message with eg downtime info
1123 # FIXME: make this work!
1124 $notice = $wgSiteNotice;
1126 if($notice != '-' && $notice != '') {
1127 $specialparser = new Parser();
1128 $parserOutput = $specialparser->parse( $notice, $wgTitle, $wgOut->mParserOptions
, false );
1129 $notice = $parserOutput->getText();
1131 wfProfileOut( $fname );
1136 * Format an XML element with given attributes and, optionally, text content.
1137 * Element and attribute names are assumed to be ready for literal inclusion.
1138 * Strings are assumed to not contain XML-illegal characters; special
1139 * characters (<, >, &) are escaped but illegals are not touched.
1141 * @param string $element
1142 * @param array $attribs Name=>value pairs. Values will be escaped.
1143 * @param bool $contents NULL to make an open tag only; '' for a contentless closed tag (default)
1146 function wfElement( $element, $attribs = null, $contents = '') {
1147 $out = '<' . $element;
1148 if( !is_null( $attribs ) ) {
1149 foreach( $attribs as $name => $val ) {
1150 $out .= ' ' . $name . '="' . htmlspecialchars( $val ) . '"';
1153 if( is_null( $contents ) ) {
1156 if( $contents == '' ) {
1160 $out .= htmlspecialchars( $contents );
1161 $out .= "</$element>";
1168 * Format an XML element as with wfElement(), but run text through the
1169 * UtfNormal::cleanUp() validator first to ensure that no invalid UTF-8
1172 * @param string $element
1173 * @param array $attribs Name=>value pairs. Values will be escaped.
1174 * @param bool $contents NULL to make an open tag only; '' for a contentless closed tag (default)
1177 function wfElementClean( $element, $attribs = array(), $contents = '') {
1179 $attribs = array_map( array( 'UtfNormal', 'cleanUp' ), $attribs );
1182 $contents = UtfNormal
::cleanUp( $contents );
1184 return wfElement( $element, $attribs, $contents );
1187 /** Global singleton instance of MimeMagic. This is initialized on demand,
1188 * please always use the wfGetMimeMagic() function to get the instance.
1194 /** Factory functions for the global MimeMagic object.
1195 * This function always returns the same singleton instance of MimeMagic.
1196 * That objects will be instantiated on the first call to this function.
1197 * If needed, the MimeMagic.php file is automatically included by this function.
1198 * @return MimeMagic the global MimeMagic objects.
1200 function &wfGetMimeMagic() {
1201 global $wgMimeMagic;
1203 if (!is_null($wgMimeMagic)) {
1204 return $wgMimeMagic;
1207 if (!class_exists("MimeMagic")) {
1209 require_once("MimeMagic.php");
1212 $wgMimeMagic= new MimeMagic();
1214 return $wgMimeMagic;
1219 * Tries to get the system directory for temporary files.
1220 * The TMPDIR, TMP, and TEMP environment variables are checked in sequence,
1221 * and if none are set /tmp is returned as the generic Unix default.
1223 * NOTE: When possible, use the tempfile() function to create temporary
1224 * files to avoid race conditions on file creation, etc.
1228 function wfTempDir() {
1229 foreach( array( 'TMPDIR', 'TMP', 'TEMP' ) as $var ) {
1230 $tmp = getenv( $var );
1231 if( $tmp && file_exists( $tmp ) && is_dir( $tmp ) && is_writable( $tmp ) ) {
1235 # Hope this is Unix of some kind!
1240 * Make directory, and make all parent directories if they don't exist
1242 function wfMkdirParents( $fullDir, $mode ) {
1243 $parts = explode( '/', $fullDir );
1246 foreach ( $parts as $dir ) {
1247 $path .= $dir . '/';
1248 if ( !is_dir( $path ) ) {
1249 if ( !mkdir( $path, $mode ) ) {
1258 * Increment a statistics counter
1260 function wfIncrStats( $key ) {
1261 global $wgDBname, $wgMemc;
1262 $key = "$wgDBname:stats:$key";
1263 if ( is_null( $wgMemc->incr( $key ) ) ) {
1264 $wgMemc->add( $key, 1 );