5 * Global functions used everywhere
10 * Some globals and requires needed
14 * Total number of articles
15 * @global integer $wgNumberOfArticles
17 $wgNumberOfArticles = -1; # Unset
19 * Total number of views
20 * @global integer $wgTotalViews
24 * Total number of edits
25 * @global integer $wgTotalEdits
30 require_once( 'DatabaseFunctions.php' );
31 require_once( 'UpdateClasses.php' );
32 require_once( 'LogPage.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
88 * @param string $charset Encoding set to use (default 'ISO-8859-1')
90 function do_html_entity_decode( $string, $quote_style=ENT_COMPAT
, $charset='ISO-8859-1' ) {
92 if( !isset( $trans ) ) {
93 $trans = array_flip( get_html_translation_table( HTML_ENTITIES
, $quote_style ) );
94 # Assumes $charset will always be the same through a run, and only understands
95 # utf-8 or default. Note - mixing latin1 named entities and unicode numbered
96 # ones will result in a bad link.
97 if( strcasecmp( 'utf-8', $charset ) == 0 ) {
98 $trans = array_map( 'utf8_encode', $trans );
101 return strtr( $string, $trans );
106 * Where as we got a random seed
107 * @var bool $wgTotalViews
109 $wgRandomSeeded = false;
112 * Seed Mersenne Twister
113 * Only necessary in PHP < 4.2.0
117 function wfSeedRandom() {
118 global $wgRandomSeeded;
120 if ( ! $wgRandomSeeded && version_compare( phpversion(), '4.2.0' ) < 0 ) {
121 $seed = hexdec(substr(md5(microtime()),-8)) & 0x7fffffff;
123 $wgRandomSeeded = true;
128 * We want / and : to be included as literal characters in our title URLs.
129 * %2F in the page titles seems to fatally break for some reason.
134 function wfUrlencode ( $s ) {
135 $s = urlencode( $s );
136 $s = preg_replace( '/%3[Aa]/', ':', $s );
137 $s = preg_replace( '/%2[Ff]/', '/', $s );
143 * Return the UTF-8 sequence for a given Unicode code point.
144 * Currently doesn't work for values outside the Basic Multilingual Plane.
146 * @param string $codepoint UTF-8 code point.
147 * @return string HTML UTF-8 Entitie such as 'Ӓ'.
149 function wfUtf8Sequence( $codepoint ) {
150 if($codepoint < 0x80) return chr($codepoint);
151 if($codepoint < 0x800) return chr($codepoint >> 6 & 0x3f |
0xc0) .
152 chr($codepoint & 0x3f |
0x80);
153 if($codepoint < 0x10000) return chr($codepoint >> 12 & 0x0f |
0xe0) .
154 chr($codepoint >> 6 & 0x3f |
0x80) .
155 chr($codepoint & 0x3f |
0x80);
156 if($codepoint < 0x110000) return chr($codepoint >> 18 & 0x07 |
0xf0) .
157 chr($codepoint >> 12 & 0x3f |
0x80) .
158 chr($codepoint >> 6 & 0x3f |
0x80) .
159 chr($codepoint & 0x3f |
0x80);
161 # There should be no assigned code points outside this range, but...
162 return "&#$codepoint;";
166 * Converts numeric character entities to UTF-8
168 * @param string $string String to convert.
169 * @return string Converted string.
171 function wfMungeToUtf8( $string ) {
172 global $wgInputEncoding; # This is debatable
173 #$string = iconv($wgInputEncoding, "UTF-8", $string);
174 $string = preg_replace ( '/&#([0-9]+);/e', 'wfUtf8Sequence($1)', $string );
175 $string = preg_replace ( '/&#x([0-9a-f]+);/ie', 'wfUtf8Sequence(0x$1)', $string );
176 # Should also do named entities here
181 * Converts a single UTF-8 character into the corresponding HTML character
182 * entity (for use with preg_replace_callback)
184 * @param array $matches
187 function wfUtf8Entity( $matches ) {
188 $codepoint = utf8ToCodepoint( $matches[0] );
189 return "&#$codepoint;";
193 * Converts all multi-byte characters in a UTF-8 string into the appropriate
196 function wfUtf8ToHTML($string) {
197 return preg_replace_callback( '/[\\xc0-\\xfd][\\x80-\\xbf]*/', 'wfUtf8Entity', $string );
201 * Sends a line to the debug log if enabled or, optionally, to a comment in output.
202 * In normal operation this is a NOP.
204 * Controlling globals:
205 * $wgDebugLogFile - points to the log file
206 * $wgProfileOnly - if set, normal debug messages will not be recorded.
207 * $wgDebugRawPage - if false, 'action=raw' hits will not result in debug output.
208 * $wgDebugComments - if on, some debug items may appear in comments in the HTML output.
210 * @param string $text
211 * @param bool $logonly Set true to avoid appearing in HTML when $wgDebugComments is set
213 function wfDebug( $text, $logonly = false ) {
214 global $wgOut, $wgDebugLogFile, $wgDebugComments, $wgProfileOnly, $wgDebugRawPage;
216 # Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
217 if ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' && !$wgDebugRawPage ) {
221 if ( isset( $wgOut ) && $wgDebugComments && !$logonly ) {
222 $wgOut->debug( $text );
224 if ( '' != $wgDebugLogFile && !$wgProfileOnly ) {
225 error_log( $text, 3, $wgDebugLogFile );
230 * Log for database errors
231 * @param string $text Database error message.
233 function wfLogDBError( $text ) {
234 global $wgDBerrorLog;
235 if ( $wgDBerrorLog ) {
236 $text = date('D M j G:i:s T Y') . "\t".$text;
237 error_log( $text, 3, $wgDBerrorLog );
244 function logProfilingData() {
245 global $wgRequestTime, $wgDebugLogFile, $wgDebugRawPage, $wgRequest;
246 global $wgProfiling, $wgProfileStack, $wgProfileLimit, $wgUser;
249 list( $usec, $sec ) = explode( ' ', $wgRequestTime );
250 $start = (float)$sec +
(float)$usec;
251 $elapsed = $now - $start;
252 if ( $wgProfiling ) {
253 $prof = wfGetProfilingOutput( $start, $elapsed );
255 if( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) )
256 $forward = ' forwarded for ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
257 if( !empty( $_SERVER['HTTP_CLIENT_IP'] ) )
258 $forward .= ' client IP ' . $_SERVER['HTTP_CLIENT_IP'];
259 if( !empty( $_SERVER['HTTP_FROM'] ) )
260 $forward .= ' from ' . $_SERVER['HTTP_FROM'];
262 $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
263 if($wgUser->getId() == 0)
265 $log = sprintf( "%s\t%04.3f\t%s\n",
266 gmdate( 'YmdHis' ), $elapsed,
267 urldecode( $_SERVER['REQUEST_URI'] . $forward ) );
268 if ( '' != $wgDebugLogFile && ( $wgRequest->getVal('action') != 'raw' ||
$wgDebugRawPage ) ) {
269 error_log( $log . $prof, 3, $wgDebugLogFile );
275 * Check if the wiki read-only lock file is present. This can be used to lock
276 * off editing functions, but doesn't guarantee that the database will not be
280 function wfReadOnly() {
281 global $wgReadOnlyFile;
283 if ( '' == $wgReadOnlyFile ) {
286 return is_file( $wgReadOnlyFile );
291 * Get a message from anywhere, for the UI elements
293 function wfMsg( $key ) {
296 if ( $wgRequest->getVal( 'debugmsg' ) ) {
297 if ( $key == 'linktrail' /* a special case where we want to return something specific */ )
298 return "/^()(.*)$/sD";
302 $args = func_get_args();
303 if ( count( $args ) ) {
304 array_shift( $args );
306 return wfMsgReal( $key, $args, true );
310 * Get a message from anywhere, for the content
312 function wfMsgForContent( $key ) {
314 if ( $wgRequest->getVal( 'debugmsg' ) ) {
315 if ( $key == 'linktrail' /* a special case where we want to return something specific */ )
316 return "/^()(.*)$/sD";
320 $args = func_get_args();
321 if ( count( $args ) ) {
322 array_shift( $args );
324 return wfMsgReal( $key, $args, true, true );
330 * Get a message from the language file, for the UI elements
332 function wfMsgNoDB( $key ) {
333 $args = func_get_args();
334 if ( count( $args ) ) {
335 array_shift( $args );
337 return wfMsgReal( $key, $args, false );
341 * Get a message from the language file, for the content
343 function wfMsgNoDBForContent( $key ) {
345 $args = func_get_args();
346 if ( count( $args ) ) {
347 array_shift( $args );
349 return wfMsgReal( $key, $args, false, true );
354 * Really get a message
356 function wfMsgReal( $key, $args, $useDB, $forContent=false ) {
357 static $replacementKeys = array( '$1', '$2', '$3', '$4', '$5', '$6', '$7', '$8', '$9' );
358 global $wgParser, $wgMsgParserOptions;
359 global $wgContLang, $wgLanguageCode;
361 global $wgMessageCache;
362 $cache = &$wgMessageCache;
363 $lang = &$wgContLang;
366 if(in_array($wgLanguageCode, $wgContLang->getVariants())){
367 global $wgLang, $wgMessageCache;
368 $cache = &$wgMessageCache;
379 wfProfileIn( $fname );
380 if ( is_object($cache) ) {
381 $message = $cache->get( $key, $useDB, $forContent );
382 } elseif (is_object($lang)) {
383 $message = $lang->getMessage( $key );
385 $message = Language
::getMessage($key);
386 if(strstr($message, '{{' ) !== false) {
387 $message = $wgParser->transformMsg($message, $wgMsgParserOptions);
390 wfDebug( "No language object when getting $key\n" );
391 $message = "<$key>";
395 if( count( $args ) ) {
396 $message = str_replace( $replacementKeys, $args, $message );
398 wfProfileOut( $fname );
405 * Just like exit() but makes a note of it.
406 * Commits open transactions except if the error parameter is set
408 function wfAbruptExit( $error = false ){
409 global $wgLoadBalancer;
410 static $called = false;
416 if( function_exists( 'debug_backtrace' ) ){ // PHP >= 4.3
417 $bt = debug_backtrace();
418 for($i = 0; $i < count($bt) ; $i++
){
419 $file = $bt[$i]['file'];
420 $line = $bt[$i]['line'];
421 wfDebug("WARNING: Abrupt exit in $file at line $line\n");
424 wfDebug('WARNING: Abrupt exit\n');
427 $wgLoadBalancer->closeAll();
435 function wfErrorExit() {
436 wfAbruptExit( true );
440 * Die with a backtrace
441 * This is meant as a debugging aid to track down where bad data comes from.
442 * Shouldn't be used in production code except maybe in "shouldn't happen" areas.
444 * @param string $msg Message shown when dieing.
446 function wfDebugDieBacktrace( $msg = '' ) {
447 global $wgCommandLineMode;
449 if ( function_exists( 'debug_backtrace' ) ) {
450 if ( $wgCommandLineMode ) {
451 $msg .= "\nBacktrace:\n";
453 $msg .= "\n<p>Backtrace:</p>\n<ul>\n";
455 $backtrace = debug_backtrace();
456 foreach( $backtrace as $call ) {
457 $f = explode( DIRECTORY_SEPARATOR
, $call['file'] );
458 $file = $f[count($f)-1];
459 if ( $wgCommandLineMode ) {
460 $msg .= "$file line {$call['line']} calls ";
462 $msg .= '<li>' . $file . ' line ' . $call['line'] . ' calls ';
464 if( !empty( $call['class'] ) ) $msg .= $call['class'] . '::';
465 $msg .= $call['function'] . '()';
467 if ( $wgCommandLineMode ) {
478 /* Some generic result counters, pulled out of SearchEngine */
484 function wfShowingResults( $offset, $limit ) {
486 return wfMsg( 'showingresults', $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+
1 ) );
492 function wfShowingResultsNum( $offset, $limit, $num ) {
494 return wfMsg( 'showingresultsnum', $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+
1 ), $wgLang->formatNum( $num ) );
500 function wfViewPrevNext( $offset, $limit, $link, $query = '', $atend = false ) {
501 global $wgUser, $wgLang;
502 $fmtLimit = $wgLang->formatNum( $limit );
503 $prev = wfMsg( 'prevn', $fmtLimit );
504 $next = wfMsg( 'nextn', $fmtLimit );
506 if( is_object( $link ) ) {
509 $title =& Title
::newFromText( $link );
510 if( is_null( $title ) ) {
515 $sk = $wgUser->getSkin();
516 if ( 0 != $offset ) {
517 $po = $offset - $limit;
518 if ( $po < 0 ) { $po = 0; }
519 $q = "limit={$limit}&offset={$po}";
520 if ( '' != $query ) { $q .= '&'.$query; }
521 $plink = '<a href="' . $title->escapeLocalUrl( $q ) . "\">{$prev}</a>";
522 } else { $plink = $prev; }
524 $no = $offset +
$limit;
525 $q = 'limit='.$limit.'&offset='.$no;
526 if ( '' != $query ) { $q .= '&'.$query; }
531 $nlink = '<a href="' . $title->escapeLocalUrl( $q ) . "\">{$next}</a>";
533 $nums = wfNumLink( $offset, 20, $title, $query ) . ' | ' .
534 wfNumLink( $offset, 50, $title, $query ) . ' | ' .
535 wfNumLink( $offset, 100, $title, $query ) . ' | ' .
536 wfNumLink( $offset, 250, $title, $query ) . ' | ' .
537 wfNumLink( $offset, 500, $title, $query );
539 return wfMsg( 'viewprevnext', $plink, $nlink, $nums );
545 function wfNumLink( $offset, $limit, &$title, $query = '' ) {
546 global $wgUser, $wgLang;
547 if ( '' == $query ) { $q = ''; }
548 else { $q = $query.'&'; }
549 $q .= 'limit='.$limit.'&offset='.$offset;
551 $fmtLimit = $wgLang->formatNum( $limit );
552 $s = '<a href="' . $title->escapeLocalUrl( $q ) . "\">{$fmtLimit}</a>";
558 * @todo FIXME: we may want to blacklist some broken browsers
560 * @return bool Whereas client accept gzip compression
562 function wfClientAcceptsGzip() {
565 # FIXME: we may want to blacklist some broken browsers
567 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
568 $_SERVER['HTTP_ACCEPT_ENCODING'],
570 if( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) return false;
571 wfDebug( " accepts gzip\n" );
579 * Yay, more global functions!
581 function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) {
583 return $wgRequest->getLimitOffset( $deflimit, $optionname );
587 * Escapes the given text so that it may be output using addWikiText()
588 * without any linking, formatting, etc. making its way through. This
589 * is achieved by substituting certain characters with HTML entities.
590 * As required by the callers, <nowiki> is not used. It currently does
591 * not filter out characters which have special meaning only at the
592 * start of a line, such as "*".
594 * @param string $text Text to be escaped
596 function wfEscapeWikiText( $text ) {
598 array( '[', '|', "'", 'ISBN ' , '://' , "\n=", '{{' ),
599 array( '[', '|', ''', 'ISBN ', '://' , "\n=", '{{' ),
600 htmlspecialchars($text) );
607 function wfQuotedPrintable( $string, $charset = '' ) {
608 # Probably incomplete; see RFC 2045
609 if( empty( $charset ) ) {
610 global $wgInputEncoding;
611 $charset = $wgInputEncoding;
613 $charset = strtoupper( $charset );
614 $charset = str_replace( 'ISO-8859', 'ISO8859', $charset ); // ?
616 $illegal = '\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\xff=';
617 $replace = $illegal . '\t ?_';
618 if( !preg_match( "/[$illegal]/", $string ) ) return $string;
619 $out = "=?$charset?Q?";
620 $out .= preg_replace( "/([$replace])/e", 'sprintf("=%02X",ord("$1"))', $string );
630 $st = explode( ' ', microtime() );
631 return (float)$st[0] +
(float)$st[1];
635 * Changes the first character to an HTML entity
637 function wfHtmlEscapeFirst( $text ) {
639 $newText = substr($text, 1);
640 return "&#$ord;$newText";
644 * Sets dest to source and returns the original value of dest
645 * If source is NULL, it just returns the value, it doesn't set the variable
647 function wfSetVar( &$dest, $source ) {
649 if ( !is_null( $source ) ) {
656 * As for wfSetVar except setting a bit
658 function wfSetBit( &$dest, $bit, $state = true ) {
659 $temp = (bool)($dest & $bit );
660 if ( !is_null( $state ) ) {
671 * This function takes two arrays as input, and returns a CGI-style string, e.g.
672 * "days=7&limit=100". Options in the first array override options in the second.
673 * Options set to "" will not be output.
675 function wfArrayToCGI( $array1, $array2 = NULL )
677 if ( !is_null( $array2 ) ) {
678 $array1 = $array1 +
$array2;
682 foreach ( $array1 as $key => $value ) {
683 if ( '' !== $value ) {
687 $cgi .= $key.'='.$value;
694 * This is obsolete, use SquidUpdate::purge()
697 function wfPurgeSquidServers ($urlArr) {
698 SquidUpdate
::purge( $urlArr );
702 * Windows-compatible version of escapeshellarg()
703 * Windows doesn't recognise single-quotes in the shell, but the escapeshellarg()
704 * function puts single quotes in regardless of OS
706 function wfEscapeShellArg( ) {
707 $args = func_get_args();
710 foreach ( $args as $arg ) {
717 if ( wfIsWindows() ) {
718 $retVal .= '"' . str_replace( '"','\"', $arg ) . '"';
720 $retVal .= escapeshellarg( $arg );
727 * wfMerge attempts to merge differences between three texts.
728 * Returns true for a clean merge and false for failure or a conflict.
730 function wfMerge( $old, $mine, $yours, &$result ){
733 # This check may also protect against code injection in
734 # case of broken installations.
735 if(! file_exists( $wgDiff3 ) ){
739 # Make temporary files
741 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
742 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
743 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
745 fwrite( $oldtextFile, $old ); fclose( $oldtextFile );
746 fwrite( $mytextFile, $mine ); fclose( $mytextFile );
747 fwrite( $yourtextFile, $yours ); fclose( $yourtextFile );
749 # Check for a conflict
750 $cmd = wfEscapeShellArg( $wgDiff3 ) . ' -a --overlap-only ' .
751 wfEscapeShellArg( $mytextName ) . ' ' .
752 wfEscapeShellArg( $oldtextName ) . ' ' .
753 wfEscapeShellArg( $yourtextName );
754 $handle = popen( $cmd, 'r' );
756 if( fgets( $handle ) ){
764 $cmd = wfEscapeShellArg( $wgDiff3 ) . ' -a -e --merge ' .
765 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
766 $handle = popen( $cmd, 'r' );
769 $data = fread( $handle, 8192 );
770 if ( strlen( $data ) == 0 ) {
776 unlink( $mytextName ); unlink( $oldtextName ); unlink( $yourtextName );
783 function wfVarDump( $var ) {
785 $s = str_replace("\n","<br>\n", var_export( $var, true ) . "\n");
786 if ( headers_sent() ||
!@is_object
( $wgOut ) ) {
789 $wgOut->addHTML( $s );
794 * Provide a simple HTTP error.
796 function wfHttpError( $code, $label, $desc ) {
799 header( "HTTP/1.0 $code $label" );
800 header( "Status: $code $label" );
801 $wgOut->sendCacheControl();
803 # Don't send content if it's a HEAD request.
804 if( $_SERVER['REQUEST_METHOD'] == 'HEAD' ) {
805 header( 'Content-type: text/plain' );
811 * Converts an Accept-* header into an array mapping string values to quality
814 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
815 # No arg means accept anything (per HTTP spec)
817 return array( $def => 1 );
822 $parts = explode( ',', $accept );
824 foreach( $parts as $part ) {
825 # FIXME: doesn't deal with params like 'text/html; level=1'
826 @list
( $value, $qpart ) = explode( ';', $part );
827 if( !isset( $qpart ) ) {
829 } elseif( preg_match( '/q\s*=\s*(\d*\.\d+)/', $qpart, $match ) ) {
830 $prefs[$value] = $match[1];
841 function mimeTypeMatch( $type, $avail ) {
842 if( array_key_exists($type, $avail) ) {
845 $parts = explode( '/', $type );
846 if( array_key_exists( $parts[0] . '/*', $avail ) ) {
847 return $parts[0] . '/*';
848 } elseif( array_key_exists( '*/*', $avail ) ) {
857 * @todo FIXME: doesn't handle params like 'text/plain; charset=UTF-8'
858 * XXX: generalize to negotiate other stuff
860 function wfNegotiateType( $cprefs, $sprefs ) {
863 foreach( array_keys($sprefs) as $type ) {
864 $parts = explode( '/', $type );
865 if( $parts[1] != '*' ) {
866 $ckey = mimeTypeMatch( $type, $cprefs );
868 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
873 foreach( array_keys( $cprefs ) as $type ) {
874 $parts = explode( '/', $type );
875 if( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
876 $skey = mimeTypeMatch( $type, $sprefs );
878 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
886 foreach( array_keys( $combine ) as $type ) {
887 if( $combine[$type] > $bestq ) {
889 $bestq = $combine[$type];
898 * Returns an array where the values in the first array are replaced by the
899 * values in the second array with the corresponding keys
903 function wfArrayLookup( $a, $b ) {
904 return array_flip( array_intersect( array_flip( $a ), array_keys( $b ) ) );
909 * Ideally we'd be using actual time fields in the db
912 function wfTimestamp2Unix( $ts ) {
913 return gmmktime( ( (int)substr( $ts, 8, 2) ),
914 (int)substr( $ts, 10, 2 ), (int)substr( $ts, 12, 2 ),
915 (int)substr( $ts, 4, 2 ), (int)substr( $ts, 6, 2 ),
916 (int)substr( $ts, 0, 4 ) );
922 function wfUnix2Timestamp( $unixtime ) {
923 return gmdate( 'YmdHis', $unixtime );
929 function wfTimestampNow() {
931 return gmdate( 'YmdHis' );
935 * Sorting hack for MySQL 3, which doesn't use index sorts for DESC
937 function wfInvertTimestamp( $ts ) {
946 * Reference-counted warning suppression
948 function wfSuppressWarnings( $end = false ) {
949 static $suppressCount = 0;
950 static $originalLevel = false;
953 if ( $suppressCount ) {
955 if ( !$suppressCount ) {
956 error_reporting( $originalLevel );
960 if ( !$suppressCount ) {
961 $originalLevel = error_reporting( E_ALL
& ~
( E_WARNING | E_NOTICE
) );
968 * Restore error level to previous value
970 function wfRestoreWarnings() {
971 wfSuppressWarnings( true );
974 # Autodetect, convert and provide timestamps of various types
976 /** Standard unix timestamp (number of seconds since 1 Jan 1970) */
978 /** MediaWiki concatenated string timestamp (yyyymmddhhmmss) */
980 /** Standard database timestamp (yyyy-mm-dd hh:mm:ss) */
986 function wfTimestamp($outputtype=TS_UNIX
,$ts=0) {
987 if (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)) {
1002 switch($outputtype) {
1007 return gmdate( 'YmdHis', $uts );
1010 return gmdate( 'Y-m-d H:i:s', $uts );
1018 * Check where as the operating system is Windows
1021 * @return bool True if it's windows, False otherwise.
1023 function wfIsWindows() {
1024 if (substr(php_uname(), 0, 7) == 'Windows') {