2 # Global functions used everywhere
4 $wgNumberOfArticles = -1; # Unset
8 require_once( 'DatabaseFunctions.php' );
9 require_once( 'UpdateClasses.php' );
10 require_once( 'LogPage.php' );
13 * Compatibility functions
16 # PHP <4.3.x is not actively supported; 4.1.x and 4.2.x might or might not work.
17 # <4.1.x will not work, as we use a number of features introduced in 4.1.0
18 # such as the new autoglobals.
20 if( !function_exists('iconv') ) {
21 # iconv support is not in the default configuration and so may not be present.
22 # Assume will only ever use utf-8 and iso-8859-1.
23 # This will *not* work in all circumstances.
24 function iconv( $from, $to, $string ) {
25 if(strcasecmp( $from, $to ) == 0) return $string;
26 if(strcasecmp( $from, 'utf-8' ) == 0) return utf8_decode( $string );
27 if(strcasecmp( $to, 'utf-8' ) == 0) return utf8_encode( $string );
32 if( !function_exists('file_get_contents') ) {
33 # Exists in PHP 4.3.0+
34 function file_get_contents( $filename ) {
35 return implode( '', file( $filename ) );
39 if( !function_exists('is_a') ) {
40 # Exists in PHP 4.2.0+
41 function is_a( $object, $class_name ) {
43 (strcasecmp( get_class( $object ), $class_name ) == 0) ||
44 is_subclass_of( $object, $class_name );
48 # html_entity_decode exists in PHP 4.3.0+ but is FATALLY BROKEN even then,
49 # with no UTF-8 support.
50 function do_html_entity_decode( $string, $quote_style=ENT_COMPAT
, $charset='ISO-8859-1' ) {
52 if( !isset( $trans ) ) {
53 $trans = array_flip( get_html_translation_table( HTML_ENTITIES
, $quote_style ) );
54 # Assumes $charset will always be the same through a run, and only understands
55 # utf-8 or default. Note - mixing latin1 named entities and unicode numbered
56 # ones will result in a bad link.
57 if( strcasecmp( 'utf-8', $charset ) == 0 ) {
58 $trans = array_map( 'utf8_encode', $trans );
61 return strtr( $string, $trans );
64 $wgRandomSeeded = false;
66 function wfSeedRandom()
68 global $wgRandomSeeded;
70 if ( ! $wgRandomSeeded ) {
71 $seed = hexdec(substr(md5(microtime()),-8)) & 0x7fffffff;
73 $wgRandomSeeded = true;
77 # Generates a URL from a URL-encoded title and a query string
78 # Title::getLocalURL() is preferred in most cases
80 function wfLocalUrl( $a, $q = '' )
82 global $wgServer, $wgScript, $wgArticlePath;
84 $a = str_replace( ' ', '_', $a );
90 $a = "{$wgScript}?{$q}";
92 } else if ( '' == $q ) {
93 $a = str_replace( "$1", $a, $wgArticlePath );
94 } else if ($wgScript != '' ) {
95 $a = "{$wgScript}?title={$a}&{$q}";
96 } else { //XXX hackish solution for toplevel wikis
102 function wfLocalUrlE( $a, $q = '' )
104 return wfEscapeHTML( wfLocalUrl( $a, $q ) );
105 # die( "Call to obsolete function wfLocalUrlE()" );
108 function wfFullUrl( $a, $q = '' ) {
109 wfDebugDieBacktrace( 'Call to obsolete function wfFullUrl(); use Title::getFullURL' );
112 function wfFullUrlE( $a, $q = '' ) {
113 wfDebugDieBacktrace( 'Call to obsolete function wfFullUrlE(); use Title::getFullUrlE' );
117 // orphan function wfThumbUrl( $img )
119 // global $wgUploadPath;
121 // $nt = Title::newFromText( $img );
122 // if( !$nt ) return "";
124 // $name = $nt->getDBkey();
125 // $hash = md5( $name );
127 // $url = "{$wgUploadPath}/thumb/" . $hash{0} . "/" .
128 // substr( $hash, 0, 2 ) . "/{$name}";
129 // return wfUrlencode( $url );
133 function wfImageArchiveUrl( $name )
135 global $wgUploadPath;
137 $hash = md5( substr( $name, 15) );
138 $url = "{$wgUploadPath}/archive/" . $hash{0} . "/" .
139 substr( $hash, 0, 2 ) . "/{$name}";
140 return wfUrlencode($url);
143 function wfUrlencode ( $s )
145 $s = urlencode( $s );
146 $s = preg_replace( '/%3[Aa]/', ':', $s );
147 $s = preg_replace( '/%2[Ff]/', '/', $s );
152 function wfUtf8Sequence($codepoint) {
153 if($codepoint < 0x80) return chr($codepoint);
154 if($codepoint < 0x800) return chr($codepoint >> 6 & 0x3f |
0xc0) .
155 chr($codepoint & 0x3f |
0x80);
156 if($codepoint < 0x10000) return chr($codepoint >> 12 & 0x0f |
0xe0) .
157 chr($codepoint >> 6 & 0x3f |
0x80) .
158 chr($codepoint & 0x3f |
0x80);
159 if($codepoint < 0x100000) return chr($codepoint >> 18 & 0x07 |
0xf0) . # Double-check this
160 chr($codepoint >> 12 & 0x3f |
0x80) .
161 chr($codepoint >> 6 & 0x3f |
0x80) .
162 chr($codepoint & 0x3f |
0x80);
163 # Doesn't yet handle outside the BMP
164 return "&#$codepoint;";
167 # Converts numeric character entities to UTF-8
168 function wfMungeToUtf8($string) {
169 global $wgInputEncoding; # This is debatable
170 #$string = iconv($wgInputEncoding, "UTF-8", $string);
171 $string = preg_replace ( '/&#([0-9]+);/e', 'wfUtf8Sequence($1)', $string );
172 $string = preg_replace ( '/&#x([0-9a-f]+);/ie', 'wfUtf8Sequence(0x$1)', $string );
173 # Should also do named entities here
177 # Converts a single UTF-8 character into the corresponding HTML character entity
178 function wfUtf8Entity( $matches ) {
181 $z = ord( $char{0} );
184 while ( $z & 0x80 ) {
192 if ( $length != strlen( $char ) ) {
195 if ( $length == 1 ) {
199 # Mask off the length-determining bits and shift back to the original location
203 # Add in the free bits from subsequent bytes
204 for ( $i=1; $i<$length; $i++
) {
206 $z |
= ord( $char{$i} ) & 0x3f;
213 # Converts all multi-byte characters in a UTF-8 string into the appropriate character entity
214 function wfUtf8ToHTML($string) {
215 return preg_replace_callback( '/[\\xc0-\\xfd][\\x80-\\xbf]*/', 'wfUtf8Entity', $string );
218 function wfDebug( $text, $logonly = false )
220 global $wgOut, $wgDebugLogFile, $wgDebugComments, $wgProfileOnly;
222 if ( isset( $wgOut ) && $wgDebugComments && !$logonly ) {
223 $wgOut->debug( $text );
225 if ( "" != $wgDebugLogFile && !$wgProfileOnly ) {
226 error_log( $text, 3, $wgDebugLogFile );
230 # Log for database errors
231 function wfLogDBError( $text ) {
232 global $wgDBerrorLog;
233 if ( $wgDBerrorLog ) {
234 $text = date("D M j G:i:s T Y") . "\t$text";
235 error_log( $text, 3, $wgDBerrorLog );
239 function logProfilingData()
241 global $wgRequestTime, $wgDebugLogFile;
242 global $wgProfiling, $wgProfileStack, $wgProfileLimit, $wgUser;
245 list( $usec, $sec ) = explode( " ", $wgRequestTime );
246 $start = (float)$sec +
(float)$usec;
247 $elapsed = $now - $start;
248 if ( $wgProfiling ) {
249 $prof = wfGetProfilingOutput( $start, $elapsed );
251 if( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) )
252 $forward = ' forwarded for ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
253 if( !empty( $_SERVER['HTTP_CLIENT_IP'] ) )
254 $forward .= ' client IP ' . $_SERVER['HTTP_CLIENT_IP'];
255 if( !empty( $_SERVER['HTTP_FROM'] ) )
256 $forward .= ' from ' . $_SERVER['HTTP_FROM'];
258 $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
259 if($wgUser->getId() == 0)
261 $log = sprintf( "%s\t%04.3f\t%s\n",
262 gmdate( 'YmdHis' ), $elapsed,
263 urldecode( $_SERVER['REQUEST_URI'] . $forward ) );
264 if ( '' != $wgDebugLogFile ) {
265 error_log( $log . $prof, 3, $wgDebugLogFile );
271 function wfReadOnly()
273 global $wgReadOnlyFile;
275 if ( "" == $wgReadOnlyFile ) { return false; }
276 return is_file( $wgReadOnlyFile );
279 $wgReplacementKeys = array( "$1", "$2", "$3", "$4", "$5", "$6", "$7", "$8", "$9" );
281 # Get a message from anywhere
282 function wfMsg( $key ) {
283 $args = func_get_args();
284 if ( count( $args ) ) {
285 array_shift( $args );
287 return wfMsgReal( $key, $args, true );
290 # Get a message from the language file
291 function wfMsgNoDB( $key ) {
292 $args = func_get_args();
293 if ( count( $args ) ) {
294 array_shift( $args );
296 return wfMsgReal( $key, $args, false );
299 # Really get a message
300 function wfMsgReal( $key, $args, $useDB ) {
301 global $wgReplacementKeys, $wgMessageCache, $wgLang;
304 wfProfileIn( $fname );
305 if ( $wgMessageCache ) {
306 $message = $wgMessageCache->get( $key, $useDB );
307 } elseif ( $wgLang ) {
308 $message = $wgLang->getMessage( $key );
310 wfDebug( "No language object when getting $key\n" );
311 $message = "<$key>";
315 if( count( $args ) ) {
316 $message = str_replace( $wgReplacementKeys, $args, $message );
318 wfProfileOut( $fname );
322 function wfCleanFormFields( $fields )
324 wfDebugDieBacktrace( 'Call to obsolete wfCleanFormFields(). Use wgRequest instead...' );
327 function wfMungeQuotes( $in )
329 $out = str_replace( '%', '%25', $in );
330 $out = str_replace( "'", '%27', $out );
331 $out = str_replace( '"', '%22', $out );
335 function wfDemungeQuotes( $in )
337 $out = str_replace( '%22', '"', $in );
338 $out = str_replace( '%27', "'", $out );
339 $out = str_replace( '%25', '%', $out );
343 function wfCleanQueryVar( $var )
345 wfDebugDieBacktrace( 'Call to obsolete function wfCleanQueryVar(); use wgRequest instead' );
348 function wfSearch( $s )
350 $se = new SearchEngine( $s );
355 { # pick the nearest match
356 $se = new SearchEngine( $s );
360 # Just like exit() but makes a note of it.
361 function wfAbruptExit(){
362 static $called = false;
368 if( function_exists( 'debug_backtrace' ) ){ // PHP >= 4.3
369 $bt = debug_backtrace();
370 for($i = 0; $i < count($bt) ; $i++
){
371 $file = $bt[$i]['file'];
372 $line = $bt[$i]['line'];
373 wfDebug("WARNING: Abrupt exit in $file at line $line\n");
376 wfDebug('WARNING: Abrupt exit\n');
381 function wfDebugDieBacktrace( $msg = '' ) {
382 global $wgCommandLineMode;
384 if ( function_exists( 'debug_backtrace' ) ) {
385 if ( $wgCommandLineMode ) {
386 $msg .= "\nBacktrace:\n";
388 $msg .= "\n<p>Backtrace:</p>\n<ul>\n";
390 $backtrace = debug_backtrace();
391 foreach( $backtrace as $call ) {
392 $f = explode( DIRECTORY_SEPARATOR
, $call['file'] );
393 $file = $f[count($f)-1];
394 if ( $wgCommandLineMode ) {
395 $msg .= "$file line {$call['line']} calls ";
397 $msg .= '<li>' . $file . " line " . $call['line'] . ' calls ';
399 if( !empty( $call['class'] ) ) $msg .= $call['class'] . '::';
400 $msg .= $call['function'] . "()";
402 if ( $wgCommandLineMode ) {
412 function wfNumberOfArticles()
414 global $wgNumberOfArticles;
417 return $wgNumberOfArticles;
420 /* private */ function wfLoadSiteStats()
422 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
423 $fname = 'wfLoadSiteStats';
425 if ( -1 != $wgNumberOfArticles ) return;
426 $dbr =& wfGetDB( DB_READ
);
427 $s = $dbr->getArray( 'site_stats',
428 array( 'ss_total_views', 'ss_total_edits', 'ss_good_articles' ),
429 array( 'ss_row_id' => 1 ), $fname
432 if ( $s === false ) {
435 $wgTotalViews = $s->ss_total_views
;
436 $wgTotalEdits = $s->ss_total_edits
;
437 $wgNumberOfArticles = $s->ss_good_articles
;
441 function wfEscapeHTML( $in )
444 array( '&', '"', '>', '<' ),
445 array( '&', '"', '>', '<' ),
449 function wfEscapeHTMLTagsOnly( $in ) {
451 array( '"', '>', '<' ),
452 array( '"', '>', '<' ),
456 function wfUnescapeHTML( $in )
458 $in = str_replace( '<', '<', $in );
459 $in = str_replace( '>', '>', $in );
460 $in = str_replace( '"', '"', $in );
461 $in = str_replace( '&', '&', $in );
465 function wfImageDir( $fname )
467 global $wgUploadDirectory;
469 $hash = md5( $fname );
470 $oldumask = umask(0);
471 $dest = $wgUploadDirectory . '/' . $hash{0};
472 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
473 $dest .= '/' . substr( $hash, 0, 2 );
474 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
480 function wfImageThumbDir( $fname , $subdir='thumb')
482 return wfImageArchiveDir( $fname, $subdir );
485 function wfImageArchiveDir( $fname , $subdir='archive')
487 global $wgUploadDirectory;
489 $hash = md5( $fname );
490 $oldumask = umask(0);
492 # Suppress warning messages here; if the file itself can't
493 # be written we'll worry about it then.
494 $archive = "{$wgUploadDirectory}/{$subdir}";
495 if ( ! is_dir( $archive ) ) { @mkdir
( $archive, 0777 ); }
496 $archive .= '/' . $hash{0};
497 if ( ! is_dir( $archive ) ) { @mkdir
( $archive, 0777 ); }
498 $archive .= '/' . substr( $hash, 0, 2 );
499 if ( ! is_dir( $archive ) ) { @mkdir
( $archive, 0777 ); }
505 function wfRecordUpload( $name, $oldver, $size, $desc, $copyStatus = "", $source = "" )
507 global $wgUser, $wgLang, $wgTitle, $wgOut, $wgDeferredUpdateList;
508 global $wgUseCopyrightUpload;
510 $fname = 'wfRecordUpload';
511 $dbw =& wfGetDB( DB_WRITE
);
513 # img_name must be unique
514 $indexInfo = $dbw->indexInfo( 'image', 'img_name' );
515 if ( $indexInfo && $indexInfo->Non_unique
) {
516 wfDebugDieBacktrace( 'Database schema not up to date, please run maintenance/archives/patch-img_name_unique.sql' );
520 $now = wfTimestampNow();
521 $won = wfInvertTimestamp( $now );
522 $size = IntVal( $size );
524 if ( $wgUseCopyrightUpload )
526 $textdesc = '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $desc . "\n" .
527 '== ' . wfMsg ( 'filestatus' ) . " ==\n" . $copyStatus . "\n" .
528 '== ' . wfMsg ( 'filesource' ) . " ==\n" . $source ;
530 else $textdesc = $desc ;
532 $now = wfTimestampNow();
533 $won = wfInvertTimestamp( $now );
535 # Test to see if the row exists using INSERT IGNORE
536 # This avoids race conditions by locking the row until the commit, and also
537 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
538 $dbw->insertArray( 'image',
542 'img_timestamp' => $now,
543 'img_description' => $desc,
544 'img_user' => $wgUser->getID(),
545 'img_user_text' => $wgUser->getName(),
549 if ( $dbw->affectedRows() ) {
550 # Successfully inserted, this is a new image
552 $sql = 'SELECT cur_id,cur_text FROM cur WHERE cur_namespace=' .
553 Namespace::getImage() . " AND cur_title='" .
554 wfStrencode( $name ) . "'";
555 $res = wfQuery( $sql, DB_READ
, $fname );
556 if ( 0 == wfNumRows( $res ) ) {
558 Namespace::getImage() . ",'" .
559 wfStrencode( $name ) . "','" .
560 wfStrencode( $desc ) . "','" . $wgUser->getID() . "','" .
561 wfStrencode( $wgUser->getName() ) . "','" . $now .
563 $sql = 'INSERT INTO cur (cur_namespace,cur_title,' .
564 'cur_comment,cur_user,cur_user_text,cur_timestamp,cur_is_new,' .
565 'cur_text,inverse_timestamp,cur_touched) VALUES (' .
567 ",'" . wfStrencode( $textdesc ) . "','{$won}','{$now}')";
568 wfQuery( $sql, DB_WRITE
, $fname );
569 $id = wfInsertId() or 0; # We should throw an error instead
571 $titleObj = Title
::makeTitle( NS_IMAGE
, $name );
572 RecentChange
::notifyNew( $now, $titleObj, 0, $wgUser, $desc );
574 $u = new SearchUpdate( $id, $name, $desc );
578 # Collision, this is an update of an image
579 $s = $dbw->getArray( 'image', array( 'img_name','img_size','img_timestamp','img_description',
580 'img_user','img_user_text' ), array( 'img_name' => $name ), $fname, 'FOR UPDATE' );
581 $s = wfFetchObject( $res );
583 $sql = 'INSERT INTO oldimage (oi_name,oi_archive_name,oi_size,' .
584 "oi_timestamp,oi_description,oi_user,oi_user_text) VALUES ('" .
585 wfStrencode( $s->img_name
) . "','" .
586 wfStrencode( $oldver ) .
587 "',{$s->img_size},'{$s->img_timestamp}','" .
588 wfStrencode( $s->img_description
) . "','" .
589 wfStrencode( $s->img_user
) . "','" .
590 wfStrencode( $s->img_user_text
) . "')";
591 wfQuery( $sql, DB_WRITE
, $fname );
593 $sql = "UPDATE image SET img_size={$size}," .
594 "img_timestamp='" . wfTimestampNow() . "',img_user='" .
595 $wgUser->getID() . "',img_user_text='" .
596 wfStrencode( $wgUser->getName() ) . "', img_description='" .
597 wfStrencode( $desc ) . "' WHERE img_name='" .
598 wfStrencode( $name ) . "'";
599 wfQuery( $sql, DB_WRITE
, $fname );
601 $sql = "UPDATE cur SET cur_touched='{$now}' WHERE cur_namespace=" .
602 Namespace::getImage() . " AND cur_title='" .
603 wfStrencode( $name ) . "'";
604 wfQuery( $sql, DB_WRITE
, $fname );
607 $log = new LogPage( wfMsg( 'uploadlogpage' ), wfMsg( 'uploadlogpagetext' ) );
608 $da = wfMsg( 'uploadedimage', '[[:' . $wgLang->getNsText(
609 Namespace::getImage() ) . ":{$name}|{$name}]]" );
610 $ta = wfMsg( 'uploadedimage', $name );
611 $log->addEntry( $da, $desc, $ta );
615 /* Some generic result counters, pulled out of SearchEngine */
617 function wfShowingResults( $offset, $limit )
620 return wfMsg( 'showingresults', $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+
1 ) );
623 function wfShowingResultsNum( $offset, $limit, $num )
626 return wfMsg( 'showingresultsnum', $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+
1 ), $wgLang->formatNum( $num ) );
629 function wfViewPrevNext( $offset, $limit, $link, $query = '', $atend = false )
631 global $wgUser, $wgLang;
632 $fmtLimit = $wgLang->formatNum( $limit );
633 $prev = wfMsg( 'prevn', $fmtLimit );
634 $next = wfMsg( 'nextn', $fmtLimit );
635 $link = wfUrlencode( $link );
637 $sk = $wgUser->getSkin();
638 if ( 0 != $offset ) {
639 $po = $offset - $limit;
640 if ( $po < 0 ) { $po = 0; }
641 $q = "limit={$limit}&offset={$po}";
642 if ( '' != $query ) { $q .= "&{$query}"; }
643 $plink = '<a href="' . wfLocalUrlE( $link, $q ) . "\">{$prev}</a>";
644 } else { $plink = $prev; }
646 $no = $offset +
$limit;
647 $q = "limit={$limit}&offset={$no}";
648 if ( "" != $query ) { $q .= "&{$query}"; }
653 $nlink = '<a href="' . wfLocalUrlE( $link, $q ) . "\">{$next}</a>";
655 $nums = wfNumLink( $offset, 20, $link , $query ) . ' | ' .
656 wfNumLink( $offset, 50, $link, $query ) . ' | ' .
657 wfNumLink( $offset, 100, $link, $query ) . ' | ' .
658 wfNumLink( $offset, 250, $link, $query ) . ' | ' .
659 wfNumLink( $offset, 500, $link, $query );
661 return wfMsg( 'viewprevnext', $plink, $nlink, $nums );
664 function wfNumLink( $offset, $limit, $link, $query = '' )
666 global $wgUser, $wgLang;
667 if ( '' == $query ) { $q = ''; }
668 else { $q = "{$query}&"; }
669 $q .= "limit={$limit}&offset={$offset}";
671 $fmtLimit = $wgLang->formatNum( $limit );
672 $s = '<a href="' . wfLocalUrlE( $link, $q ) . "\">{$fmtLimit}</a>";
676 function wfClientAcceptsGzip() {
679 # FIXME: we may want to blacklist some broken browsers
681 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
682 $_SERVER['HTTP_ACCEPT_ENCODING'],
684 if( ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) return false;
685 wfDebug( " accepts gzip\n" );
692 # Yay, more global functions!
693 function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) {
694 global $wgUser, $wgRequest;
696 $limit = $wgRequest->getInt( 'limit', 0 );
697 if( $limit < 0 ) $limit = 0;
698 if( ( $limit == 0 ) && ( $optionname != '' ) ) {
699 $limit = (int)$wgUser->getOption( $optionname );
701 if( $limit <= 0 ) $limit = $deflimit;
702 if( $limit > 5000 ) $limit = 5000; # We have *some* limits...
704 $offset = $wgRequest->getInt( 'offset', 0 );
705 if( $offset < 0 ) $offset = 0;
706 if( $offset > 65000 ) $offset = 65000; # do we need a max? what?
708 return array( $limit, $offset );
711 # Escapes the given text so that it may be output using addWikiText()
712 # without any linking, formatting, etc. making its way through. This
713 # is achieved by substituting certain characters with HTML entities.
714 # As required by the callers, <nowiki> is not used. It currently does
715 # not filter out characters which have special meaning only at the
716 # start of a line, such as "*".
717 function wfEscapeWikiText( $text )
720 array( '[', '|', "'", 'ISBN ' , '://' , "\n=" ),
721 array( '[', '|', ''', 'ISBN ', '://' , "\n=" ),
722 htmlspecialchars($text) );
726 function wfQuotedPrintable( $string, $charset = '' )
728 # Probably incomplete; see RFC 2045
729 if( empty( $charset ) ) {
730 global $wgInputEncoding;
731 $charset = $wgInputEncoding;
733 $charset = strtoupper( $charset );
734 $charset = str_replace( 'ISO-8859', 'ISO8859', $charset ); // ?
736 $illegal = '\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\xff=';
737 $replace = $illegal . '\t ?_';
738 if( !preg_match( "/[$illegal]/", $string ) ) return $string;
739 $out = "=?$charset?Q?";
740 $out .= preg_replace( "/([$replace])/e", 'sprintf("=%02X",ord("$1"))', $string );
746 $st = explode( ' ', microtime() );
747 return (float)$st[0] +
(float)$st[1];
750 # Changes the first character to an HTML entity
751 function wfHtmlEscapeFirst( $text ) {
753 $newText = substr($text, 1);
754 return "&#$ord;$newText";
757 # Sets dest to source and returns the original value of dest
758 function wfSetVar( &$dest, $source )
765 # Sets dest to a reference to source and returns the original dest
766 # Pity that doesn't work in PHP
767 function &wfSetRef( &$dest, &$source )
769 die( "You can't rebind a variable in the caller's scope" );
772 # This function takes two arrays as input, and returns a CGI-style string, e.g.
773 # "days=7&limit=100". Options in the first array override options in the second.
774 # Options set to "" will not be output.
775 function wfArrayToCGI( $array1, $array2 = NULL )
777 if ( !is_null( $array2 ) ) {
778 $array1 = $array1 +
$array2;
782 foreach ( $array1 as $key => $value ) {
783 if ( '' !== $value ) {
787 $cgi .= "{$key}={$value}";
793 # This is obsolete, use SquidUpdate::purge()
794 function wfPurgeSquidServers ($urlArr) {
795 SquidUpdate
::purge( $urlArr );
798 # Windows-compatible version of escapeshellarg()
799 function wfEscapeShellArg( )
801 $args = func_get_args();
804 foreach ( $args as $arg ) {
811 if ( wfIsWindows() ) {
812 $retVal .= '"' . str_replace( '"','\"', $arg ) . '"';
814 $retVal .= escapeshellarg( $arg );
820 # wfMerge attempts to merge differences between three texts.
821 # Returns true for a clean merge and false for failure or a conflict.
823 function wfMerge( $old, $mine, $yours, &$result ){
826 # This check may also protect against code injection in
827 # case of broken installations.
828 if(! file_exists( $wgDiff3 ) ){
832 # Make temporary files
834 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
835 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
836 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
838 fwrite( $oldtextFile, $old ); fclose( $oldtextFile );
839 fwrite( $mytextFile, $mine ); fclose( $mytextFile );
840 fwrite( $yourtextFile, $yours ); fclose( $yourtextFile );
842 # Check for a conflict
843 $cmd = wfEscapeShellArg( $wgDiff3 ) . ' -a --overlap-only ' .
844 wfEscapeShellArg( $mytextName ) . ' ' .
845 wfEscapeShellArg( $oldtextName ) . ' ' .
846 wfEscapeShellArg( $yourtextName );
847 $handle = popen( $cmd, 'r' );
849 if( fgets( $handle ) ){
857 $cmd = wfEscapeShellArg( $wgDiff3 ) . ' -a -e --merge ' .
858 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
859 $handle = popen( $cmd, 'r' );
862 $data = fread( $handle, 8192 );
863 if ( strlen( $data ) == 0 ) {
869 unlink( $mytextName ); unlink( $oldtextName ); unlink( $yourtextName );
873 function wfVarDump( $var )
876 $s = str_replace("\n","<br>\n", var_export( $var, true ) . "\n");
877 if ( headers_sent() ||
!@is_object
( $wgOut ) ) {
880 $wgOut->addHTML( $s );
884 # Provide a simple HTTP error.
885 function wfHttpError( $code, $label, $desc ) {
888 header( "HTTP/1.0 $code $label" );
889 header( "Status: $code $label" );
890 $wgOut->sendCacheControl();
892 # Don't send content if it's a HEAD request.
893 if( $_SERVER['REQUEST_METHOD'] == 'HEAD' ) {
894 header( 'Content-type: text/plain' );
899 # Converts an Accept-* header into an array mapping string values to quality factors
900 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
901 # No arg means accept anything (per HTTP spec)
903 return array( $def => 1 );
908 $parts = explode( ',', $accept );
910 foreach( $parts as $part ) {
911 # FIXME: doesn't deal with params like 'text/html; level=1'
912 @list
( $value, $qpart ) = explode( ';', $part );
913 if( !isset( $qpart ) ) {
915 } elseif( preg_match( '/q\s*=\s*(\d*\.\d+)/', $qpart, $match ) ) {
916 $prefs[$value] = $match[1];
923 /* private */ function mimeTypeMatch( $type, $avail ) {
924 if( array_key_exists($type, $avail) ) {
927 $parts = explode( '/', $type );
928 if( array_key_exists( $parts[0] . '/*', $avail ) ) {
929 return $parts[0] . '/*';
930 } elseif( array_key_exists( '*/*', $avail ) ) {
938 # FIXME: doesn't handle params like 'text/plain; charset=UTF-8'
939 # XXX: generalize to negotiate other stuff
940 function wfNegotiateType( $cprefs, $sprefs ) {
943 foreach( array_keys($sprefs) as $type ) {
944 $parts = explode( '/', $type );
945 if( $parts[1] != '*' ) {
946 $ckey = mimeTypeMatch( $type, $cprefs );
948 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
953 foreach( array_keys( $cprefs ) as $type ) {
954 $parts = explode( '/', $type );
955 if( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
956 $skey = mimeTypeMatch( $type, $sprefs );
958 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
966 foreach( array_keys( $combine ) as $type ) {
967 if( $combine[$type] > $bestq ) {
969 $bestq = $combine[$type];
977 # Returns an array where the values in the first array are replaced by the
978 # values in the second array with the corresponding keys
979 function wfArrayLookup( $a, $b )
981 return array_flip( array_intersect( array_flip( $a ), array_keys( $b ) ) );
984 # Since Windows is so different to any of the other popular OSes, it seems appropriate
985 # to have a simple way to test for its presence
986 function wfIsWindows() {
987 if (substr(php_uname(), 0, 7) == 'Windows') {
995 # Ideally we'd be using actual time fields in the db
996 function wfTimestamp2Unix( $ts ) {
997 return gmmktime( ( (int)substr( $ts, 8, 2) ),
998 (int)substr( $ts, 10, 2 ), (int)substr( $ts, 12, 2 ),
999 (int)substr( $ts, 4, 2 ), (int)substr( $ts, 6, 2 ),
1000 (int)substr( $ts, 0, 4 ) );
1003 function wfUnix2Timestamp( $unixtime ) {
1004 return gmdate( "YmdHis", $unixtime );
1007 function wfTimestampNow() {
1009 return gmdate( "YmdHis" );
1012 # Sorting hack for MySQL 3, which doesn't use index sorts for DESC
1013 function wfInvertTimestamp( $ts ) {
1021 # Reference-counted warning suppression
1022 function wfSuppressWarnings( $end = false ) {
1023 static $suppressCount = 0;
1024 static $originalLevel = false;
1027 if ( $suppressCount ) {
1029 if ( !$suppressCount ) {
1030 error_reporting( $originalLevel );
1034 if ( !$suppressCount ) {
1035 $originalLevel = error_reporting( E_ALL
& ~
( E_WARNING | E_NOTICE
) );
1041 # Restore error level to previous value
1042 function wfRestoreWarnings() {
1043 wfSuppressWarnings( true );