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 * Get a random decimal value between 0 and 1, in a way
129 * not likely to give duplicate values for any realistic
130 * number of articles.
134 function wfRandom() {
135 # The maximum random value is "only" 2^31-1, so get two random
136 # values to reduce the chance of dupes
137 $max = mt_getrandmax();
138 $rand = number_format( mt_rand() * mt_rand()
139 / $max / $max, 12, '.', '' );
144 * We want / and : to be included as literal characters in our title URLs.
145 * %2F in the page titles seems to fatally break for some reason.
150 function wfUrlencode ( $s ) {
151 $s = urlencode( $s );
152 $s = preg_replace( '/%3[Aa]/', ':', $s );
153 $s = preg_replace( '/%2[Ff]/', '/', $s );
159 * Return the UTF-8 sequence for a given Unicode code point.
160 * Currently doesn't work for values outside the Basic Multilingual Plane.
162 * @param string $codepoint UTF-8 code point.
163 * @return string HTML UTF-8 Entitie such as 'Ӓ'.
165 function wfUtf8Sequence( $codepoint ) {
166 if($codepoint < 0x80) return chr($codepoint);
167 if($codepoint < 0x800) return chr($codepoint >> 6 & 0x3f |
0xc0) .
168 chr($codepoint & 0x3f |
0x80);
169 if($codepoint < 0x10000) return chr($codepoint >> 12 & 0x0f |
0xe0) .
170 chr($codepoint >> 6 & 0x3f |
0x80) .
171 chr($codepoint & 0x3f |
0x80);
172 if($codepoint < 0x110000) return chr($codepoint >> 18 & 0x07 |
0xf0) .
173 chr($codepoint >> 12 & 0x3f |
0x80) .
174 chr($codepoint >> 6 & 0x3f |
0x80) .
175 chr($codepoint & 0x3f |
0x80);
177 # There should be no assigned code points outside this range, but...
178 return "&#$codepoint;";
182 * Converts numeric character entities to UTF-8
184 * @param string $string String to convert.
185 * @return string Converted string.
187 function wfMungeToUtf8( $string ) {
188 global $wgInputEncoding; # This is debatable
189 #$string = iconv($wgInputEncoding, "UTF-8", $string);
190 $string = preg_replace ( '/&#([0-9]+);/e', 'wfUtf8Sequence($1)', $string );
191 $string = preg_replace ( '/&#x([0-9a-f]+);/ie', 'wfUtf8Sequence(0x$1)', $string );
192 # Should also do named entities here
197 * Converts a single UTF-8 character into the corresponding HTML character
198 * entity (for use with preg_replace_callback)
200 * @param array $matches
203 function wfUtf8Entity( $matches ) {
204 $codepoint = utf8ToCodepoint( $matches[0] );
205 return "&#$codepoint;";
209 * Converts all multi-byte characters in a UTF-8 string into the appropriate
212 function wfUtf8ToHTML($string) {
213 return preg_replace_callback( '/[\\xc0-\\xfd][\\x80-\\xbf]*/', 'wfUtf8Entity', $string );
217 * Sends a line to the debug log if enabled or, optionally, to a comment in output.
218 * In normal operation this is a NOP.
220 * Controlling globals:
221 * $wgDebugLogFile - points to the log file
222 * $wgProfileOnly - if set, normal debug messages will not be recorded.
223 * $wgDebugRawPage - if false, 'action=raw' hits will not result in debug output.
224 * $wgDebugComments - if on, some debug items may appear in comments in the HTML output.
226 * @param string $text
227 * @param bool $logonly Set true to avoid appearing in HTML when $wgDebugComments is set
229 function wfDebug( $text, $logonly = false ) {
230 global $wgOut, $wgDebugLogFile, $wgDebugComments, $wgProfileOnly, $wgDebugRawPage;
232 # Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
233 if ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' && !$wgDebugRawPage ) {
237 if ( isset( $wgOut ) && $wgDebugComments && !$logonly ) {
238 $wgOut->debug( $text );
240 if ( '' != $wgDebugLogFile && !$wgProfileOnly ) {
241 error_log( $text, 3, $wgDebugLogFile );
246 * Log for database errors
247 * @param string $text Database error message.
249 function wfLogDBError( $text ) {
250 global $wgDBerrorLog;
251 if ( $wgDBerrorLog ) {
252 $text = date('D M j G:i:s T Y') . "\t".$text;
253 error_log( $text, 3, $wgDBerrorLog );
260 function logProfilingData() {
261 global $wgRequestTime, $wgDebugLogFile, $wgDebugRawPage, $wgRequest;
262 global $wgProfiling, $wgProfileStack, $wgProfileLimit, $wgUser;
265 list( $usec, $sec ) = explode( ' ', $wgRequestTime );
266 $start = (float)$sec +
(float)$usec;
267 $elapsed = $now - $start;
268 if ( $wgProfiling ) {
269 $prof = wfGetProfilingOutput( $start, $elapsed );
271 if( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) )
272 $forward = ' forwarded for ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
273 if( !empty( $_SERVER['HTTP_CLIENT_IP'] ) )
274 $forward .= ' client IP ' . $_SERVER['HTTP_CLIENT_IP'];
275 if( !empty( $_SERVER['HTTP_FROM'] ) )
276 $forward .= ' from ' . $_SERVER['HTTP_FROM'];
278 $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
279 if($wgUser->getId() == 0)
281 $log = sprintf( "%s\t%04.3f\t%s\n",
282 gmdate( 'YmdHis' ), $elapsed,
283 urldecode( $_SERVER['REQUEST_URI'] . $forward ) );
284 if ( '' != $wgDebugLogFile && ( $wgRequest->getVal('action') != 'raw' ||
$wgDebugRawPage ) ) {
285 error_log( $log . $prof, 3, $wgDebugLogFile );
291 * Check if the wiki read-only lock file is present. This can be used to lock
292 * off editing functions, but doesn't guarantee that the database will not be
296 function wfReadOnly() {
297 global $wgReadOnlyFile;
299 if ( '' == $wgReadOnlyFile ) {
302 return is_file( $wgReadOnlyFile );
307 * Get a message from anywhere, for the UI elements
309 function wfMsg( $key ) {
312 if ( $wgRequest->getVal( 'debugmsg' ) ) {
313 if ( $key == 'linktrail' /* a special case where we want to return something specific */ )
314 return "/^()(.*)$/sD";
318 $args = func_get_args();
319 if ( count( $args ) ) {
320 array_shift( $args );
322 return wfMsgReal( $key, $args, true );
326 * Get a message from anywhere, for the content
328 function wfMsgForContent( $key ) {
330 if ( $wgRequest->getVal( 'debugmsg' ) ) {
331 if ( $key == 'linktrail' /* a special case where we want to return something specific */ )
332 return "/^()(.*)$/sD";
336 $args = func_get_args();
337 if ( count( $args ) ) {
338 array_shift( $args );
340 return wfMsgReal( $key, $args, true, true );
346 * Get a message from the language file, for the UI elements
348 function wfMsgNoDB( $key ) {
349 $args = func_get_args();
350 if ( count( $args ) ) {
351 array_shift( $args );
353 return wfMsgReal( $key, $args, false );
357 * Get a message from the language file, for the content
359 function wfMsgNoDBForContent( $key ) {
361 $args = func_get_args();
362 if ( count( $args ) ) {
363 array_shift( $args );
365 return wfMsgReal( $key, $args, false, true );
370 * Really get a message
372 function wfMsgReal( $key, $args, $useDB, $forContent=false ) {
373 static $replacementKeys = array( '$1', '$2', '$3', '$4', '$5', '$6', '$7', '$8', '$9' );
374 global $wgParser, $wgMsgParserOptions;
375 global $wgContLang, $wgLanguageCode;
377 global $wgMessageCache;
378 $cache = &$wgMessageCache;
379 $lang = &$wgContLang;
382 if(in_array($wgLanguageCode, $wgContLang->getVariants())){
383 global $wgLang, $wgMessageCache;
384 $cache = &$wgMessageCache;
395 wfProfileIn( $fname );
396 if ( is_object($cache) ) {
397 $message = $cache->get( $key, $useDB, $forContent );
398 } elseif (is_object($lang)) {
399 $message = $lang->getMessage( $key );
401 $message = Language
::getMessage($key);
402 if(strstr($message, '{{' ) !== false) {
403 $message = $wgParser->transformMsg($message, $wgMsgParserOptions);
406 wfDebug( "No language object when getting $key\n" );
407 $message = "<$key>";
411 if( count( $args ) ) {
412 $message = str_replace( $replacementKeys, $args, $message );
414 wfProfileOut( $fname );
421 * Just like exit() but makes a note of it.
422 * Commits open transactions except if the error parameter is set
424 function wfAbruptExit( $error = false ){
425 global $wgLoadBalancer;
426 static $called = false;
432 if( function_exists( 'debug_backtrace' ) ){ // PHP >= 4.3
433 $bt = debug_backtrace();
434 for($i = 0; $i < count($bt) ; $i++
){
435 $file = $bt[$i]['file'];
436 $line = $bt[$i]['line'];
437 wfDebug("WARNING: Abrupt exit in $file at line $line\n");
440 wfDebug('WARNING: Abrupt exit\n');
443 $wgLoadBalancer->closeAll();
451 function wfErrorExit() {
452 wfAbruptExit( true );
456 * Die with a backtrace
457 * This is meant as a debugging aid to track down where bad data comes from.
458 * Shouldn't be used in production code except maybe in "shouldn't happen" areas.
460 * @param string $msg Message shown when dieing.
462 function wfDebugDieBacktrace( $msg = '' ) {
463 global $wgCommandLineMode;
465 if ( function_exists( 'debug_backtrace' ) ) {
466 if ( $wgCommandLineMode ) {
467 $msg .= "\nBacktrace:\n";
469 $msg .= "\n<p>Backtrace:</p>\n<ul>\n";
471 $backtrace = debug_backtrace();
472 foreach( $backtrace as $call ) {
473 $f = explode( DIRECTORY_SEPARATOR
, $call['file'] );
474 $file = $f[count($f)-1];
475 if ( $wgCommandLineMode ) {
476 $msg .= "$file line {$call['line']} calls ";
478 $msg .= '<li>' . $file . ' line ' . $call['line'] . ' calls ';
480 if( !empty( $call['class'] ) ) $msg .= $call['class'] . '::';
481 $msg .= $call['function'] . '()';
483 if ( $wgCommandLineMode ) {
494 /* Some generic result counters, pulled out of SearchEngine */
500 function wfShowingResults( $offset, $limit ) {
502 return wfMsg( 'showingresults', $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+
1 ) );
508 function wfShowingResultsNum( $offset, $limit, $num ) {
510 return wfMsg( 'showingresultsnum', $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+
1 ), $wgLang->formatNum( $num ) );
516 function wfViewPrevNext( $offset, $limit, $link, $query = '', $atend = false ) {
517 global $wgUser, $wgLang;
518 $fmtLimit = $wgLang->formatNum( $limit );
519 $prev = wfMsg( 'prevn', $fmtLimit );
520 $next = wfMsg( 'nextn', $fmtLimit );
522 if( is_object( $link ) ) {
525 $title =& Title
::newFromText( $link );
526 if( is_null( $title ) ) {
531 $sk = $wgUser->getSkin();
532 if ( 0 != $offset ) {
533 $po = $offset - $limit;
534 if ( $po < 0 ) { $po = 0; }
535 $q = "limit={$limit}&offset={$po}";
536 if ( '' != $query ) { $q .= '&'.$query; }
537 $plink = '<a href="' . $title->escapeLocalUrl( $q ) . "\">{$prev}</a>";
538 } else { $plink = $prev; }
540 $no = $offset +
$limit;
541 $q = 'limit='.$limit.'&offset='.$no;
542 if ( '' != $query ) { $q .= '&'.$query; }
547 $nlink = '<a href="' . $title->escapeLocalUrl( $q ) . "\">{$next}</a>";
549 $nums = wfNumLink( $offset, 20, $title, $query ) . ' | ' .
550 wfNumLink( $offset, 50, $title, $query ) . ' | ' .
551 wfNumLink( $offset, 100, $title, $query ) . ' | ' .
552 wfNumLink( $offset, 250, $title, $query ) . ' | ' .
553 wfNumLink( $offset, 500, $title, $query );
555 return wfMsg( 'viewprevnext', $plink, $nlink, $nums );
561 function wfNumLink( $offset, $limit, &$title, $query = '' ) {
562 global $wgUser, $wgLang;
563 if ( '' == $query ) { $q = ''; }
564 else { $q = $query.'&'; }
565 $q .= 'limit='.$limit.'&offset='.$offset;
567 $fmtLimit = $wgLang->formatNum( $limit );
568 $s = '<a href="' . $title->escapeLocalUrl( $q ) . "\">{$fmtLimit}</a>";
574 * @todo FIXME: we may want to blacklist some broken browsers
576 * @return bool Whereas client accept gzip compression
578 function wfClientAcceptsGzip() {
581 # FIXME: we may want to blacklist some broken browsers
583 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
584 $_SERVER['HTTP_ACCEPT_ENCODING'],
586 if( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) return false;
587 wfDebug( " accepts gzip\n" );
595 * Yay, more global functions!
597 function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) {
599 return $wgRequest->getLimitOffset( $deflimit, $optionname );
603 * Escapes the given text so that it may be output using addWikiText()
604 * without any linking, formatting, etc. making its way through. This
605 * is achieved by substituting certain characters with HTML entities.
606 * As required by the callers, <nowiki> is not used. It currently does
607 * not filter out characters which have special meaning only at the
608 * start of a line, such as "*".
610 * @param string $text Text to be escaped
612 function wfEscapeWikiText( $text ) {
614 array( '[', '|', "'", 'ISBN ' , '://' , "\n=", '{{' ),
615 array( '[', '|', ''', 'ISBN ', '://' , "\n=", '{{' ),
616 htmlspecialchars($text) );
623 function wfQuotedPrintable( $string, $charset = '' ) {
624 # Probably incomplete; see RFC 2045
625 if( empty( $charset ) ) {
626 global $wgInputEncoding;
627 $charset = $wgInputEncoding;
629 $charset = strtoupper( $charset );
630 $charset = str_replace( 'ISO-8859', 'ISO8859', $charset ); // ?
632 $illegal = '\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\xff=';
633 $replace = $illegal . '\t ?_';
634 if( !preg_match( "/[$illegal]/", $string ) ) return $string;
635 $out = "=?$charset?Q?";
636 $out .= preg_replace( "/([$replace])/e", 'sprintf("=%02X",ord("$1"))', $string );
646 $st = explode( ' ', microtime() );
647 return (float)$st[0] +
(float)$st[1];
651 * Changes the first character to an HTML entity
653 function wfHtmlEscapeFirst( $text ) {
655 $newText = substr($text, 1);
656 return "&#$ord;$newText";
660 * Sets dest to source and returns the original value of dest
661 * If source is NULL, it just returns the value, it doesn't set the variable
663 function wfSetVar( &$dest, $source ) {
665 if ( !is_null( $source ) ) {
672 * As for wfSetVar except setting a bit
674 function wfSetBit( &$dest, $bit, $state = true ) {
675 $temp = (bool)($dest & $bit );
676 if ( !is_null( $state ) ) {
687 * This function takes two arrays as input, and returns a CGI-style string, e.g.
688 * "days=7&limit=100". Options in the first array override options in the second.
689 * Options set to "" will not be output.
691 function wfArrayToCGI( $array1, $array2 = NULL )
693 if ( !is_null( $array2 ) ) {
694 $array1 = $array1 +
$array2;
698 foreach ( $array1 as $key => $value ) {
699 if ( '' !== $value ) {
703 $cgi .= $key.'='.$value;
710 * This is obsolete, use SquidUpdate::purge()
713 function wfPurgeSquidServers ($urlArr) {
714 SquidUpdate
::purge( $urlArr );
718 * Windows-compatible version of escapeshellarg()
719 * Windows doesn't recognise single-quotes in the shell, but the escapeshellarg()
720 * function puts single quotes in regardless of OS
722 function wfEscapeShellArg( ) {
723 $args = func_get_args();
726 foreach ( $args as $arg ) {
733 if ( wfIsWindows() ) {
734 $retVal .= '"' . str_replace( '"','\"', $arg ) . '"';
736 $retVal .= escapeshellarg( $arg );
743 * wfMerge attempts to merge differences between three texts.
744 * Returns true for a clean merge and false for failure or a conflict.
746 function wfMerge( $old, $mine, $yours, &$result ){
749 # This check may also protect against code injection in
750 # case of broken installations.
751 if(! file_exists( $wgDiff3 ) ){
755 # Make temporary files
757 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
758 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
759 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
761 fwrite( $oldtextFile, $old ); fclose( $oldtextFile );
762 fwrite( $mytextFile, $mine ); fclose( $mytextFile );
763 fwrite( $yourtextFile, $yours ); fclose( $yourtextFile );
765 # Check for a conflict
766 $cmd = wfEscapeShellArg( $wgDiff3 ) . ' -a --overlap-only ' .
767 wfEscapeShellArg( $mytextName ) . ' ' .
768 wfEscapeShellArg( $oldtextName ) . ' ' .
769 wfEscapeShellArg( $yourtextName );
770 $handle = popen( $cmd, 'r' );
772 if( fgets( $handle ) ){
780 $cmd = wfEscapeShellArg( $wgDiff3 ) . ' -a -e --merge ' .
781 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
782 $handle = popen( $cmd, 'r' );
785 $data = fread( $handle, 8192 );
786 if ( strlen( $data ) == 0 ) {
792 unlink( $mytextName ); unlink( $oldtextName ); unlink( $yourtextName );
799 function wfVarDump( $var ) {
801 $s = str_replace("\n","<br>\n", var_export( $var, true ) . "\n");
802 if ( headers_sent() ||
!@is_object
( $wgOut ) ) {
805 $wgOut->addHTML( $s );
810 * Provide a simple HTTP error.
812 function wfHttpError( $code, $label, $desc ) {
815 header( "HTTP/1.0 $code $label" );
816 header( "Status: $code $label" );
817 $wgOut->sendCacheControl();
819 # Don't send content if it's a HEAD request.
820 if( $_SERVER['REQUEST_METHOD'] == 'HEAD' ) {
821 header( 'Content-type: text/plain' );
827 * Converts an Accept-* header into an array mapping string values to quality
830 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
831 # No arg means accept anything (per HTTP spec)
833 return array( $def => 1 );
838 $parts = explode( ',', $accept );
840 foreach( $parts as $part ) {
841 # FIXME: doesn't deal with params like 'text/html; level=1'
842 @list
( $value, $qpart ) = explode( ';', $part );
843 if( !isset( $qpart ) ) {
845 } elseif( preg_match( '/q\s*=\s*(\d*\.\d+)/', $qpart, $match ) ) {
846 $prefs[$value] = $match[1];
857 function mimeTypeMatch( $type, $avail ) {
858 if( array_key_exists($type, $avail) ) {
861 $parts = explode( '/', $type );
862 if( array_key_exists( $parts[0] . '/*', $avail ) ) {
863 return $parts[0] . '/*';
864 } elseif( array_key_exists( '*/*', $avail ) ) {
873 * @todo FIXME: doesn't handle params like 'text/plain; charset=UTF-8'
874 * XXX: generalize to negotiate other stuff
876 function wfNegotiateType( $cprefs, $sprefs ) {
879 foreach( array_keys($sprefs) as $type ) {
880 $parts = explode( '/', $type );
881 if( $parts[1] != '*' ) {
882 $ckey = mimeTypeMatch( $type, $cprefs );
884 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
889 foreach( array_keys( $cprefs ) as $type ) {
890 $parts = explode( '/', $type );
891 if( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
892 $skey = mimeTypeMatch( $type, $sprefs );
894 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
902 foreach( array_keys( $combine ) as $type ) {
903 if( $combine[$type] > $bestq ) {
905 $bestq = $combine[$type];
914 * Returns an array where the values in the first array are replaced by the
915 * values in the second array with the corresponding keys
919 function wfArrayLookup( $a, $b ) {
920 return array_flip( array_intersect( array_flip( $a ), array_keys( $b ) ) );
925 * Ideally we'd be using actual time fields in the db
928 function wfTimestamp2Unix( $ts ) {
929 return gmmktime( ( (int)substr( $ts, 8, 2) ),
930 (int)substr( $ts, 10, 2 ), (int)substr( $ts, 12, 2 ),
931 (int)substr( $ts, 4, 2 ), (int)substr( $ts, 6, 2 ),
932 (int)substr( $ts, 0, 4 ) );
938 function wfUnix2Timestamp( $unixtime ) {
939 return gmdate( 'YmdHis', $unixtime );
945 function wfTimestampNow() {
947 return gmdate( 'YmdHis' );
951 * Sorting hack for MySQL 3, which doesn't use index sorts for DESC
953 function wfInvertTimestamp( $ts ) {
962 * Reference-counted warning suppression
964 function wfSuppressWarnings( $end = false ) {
965 static $suppressCount = 0;
966 static $originalLevel = false;
969 if ( $suppressCount ) {
971 if ( !$suppressCount ) {
972 error_reporting( $originalLevel );
976 if ( !$suppressCount ) {
977 $originalLevel = error_reporting( E_ALL
& ~
( E_WARNING | E_NOTICE
) );
984 * Restore error level to previous value
986 function wfRestoreWarnings() {
987 wfSuppressWarnings( true );
990 # Autodetect, convert and provide timestamps of various types
992 /** Standard unix timestamp (number of seconds since 1 Jan 1970) */
994 /** MediaWiki concatenated string timestamp (yyyymmddhhmmss) */
996 /** Standard database timestamp (yyyy-mm-dd hh:mm:ss) */
1002 function wfTimestamp($outputtype=TS_UNIX
,$ts=0) {
1003 if (preg_match("/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)$/",$ts,$da)) {
1005 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1006 (int)$da[2],(int)$da[3],(int)$da[1]);
1007 } elseif (preg_match("/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/",$ts,$da)) {
1009 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1010 (int)$da[2],(int)$da[3],(int)$da[1]);
1011 } elseif (preg_match("/^(\d{1,13})$/",$ts,$datearray)) {
1018 switch($outputtype) {
1023 return gmdate( 'YmdHis', $uts );
1026 return gmdate( 'Y-m-d H:i:s', $uts );
1034 * Check where as the operating system is Windows
1037 * @return bool True if it's windows, False otherwise.
1039 function wfIsWindows() {
1040 if (substr(php_uname(), 0, 7) == 'Windows') {