2 # Global functions used everywhere
5 $wgNumberOfArticles = -1; # Unset
9 require_once( 'DatabaseFunctions.php' );
10 require_once( 'UpdateClasses.php' );
11 require_once( 'LogPage.php' );
14 * Compatibility functions
17 # PHP <4.3.x is not actively supported; 4.1.x and 4.2.x might or might not work.
18 # <4.1.x will not work, as we use a number of features introduced in 4.1.0
19 # such as the new autoglobals.
21 if( !function_exists('iconv') ) {
22 # iconv support is not in the default configuration and so may not be present.
23 # Assume will only ever use utf-8 and iso-8859-1.
24 # This will *not* work in all circumstances.
25 function iconv( $from, $to, $string ) {
26 if(strcasecmp( $from, $to ) == 0) return $string;
27 if(strcasecmp( $from, 'utf-8' ) == 0) return utf8_decode( $string );
28 if(strcasecmp( $to, 'utf-8' ) == 0) return utf8_encode( $string );
33 if( !function_exists('file_get_contents') ) {
34 # Exists in PHP 4.3.0+
35 function file_get_contents( $filename ) {
36 return implode( '', file( $filename ) );
40 if( !function_exists('is_a') ) {
41 # Exists in PHP 4.2.0+
42 function is_a( $object, $class_name ) {
44 (strcasecmp( get_class( $object ), $class_name ) == 0) ||
45 is_subclass_of( $object, $class_name );
49 # html_entity_decode exists in PHP 4.3.0+ but is FATALLY BROKEN even then,
50 # with no UTF-8 support.
51 function do_html_entity_decode( $string, $quote_style=ENT_COMPAT
, $charset='ISO-8859-1' ) {
53 if( !isset( $trans ) ) {
54 $trans = array_flip( get_html_translation_table( HTML_ENTITIES
, $quote_style ) );
55 # Assumes $charset will always be the same through a run, and only understands
56 # utf-8 or default. Note - mixing latin1 named entities and unicode numbered
57 # ones will result in a bad link.
58 if( strcasecmp( 'utf-8', $charset ) == 0 ) {
59 $trans = array_map( 'utf8_encode', $trans );
62 return strtr( $string, $trans );
65 $wgRandomSeeded = false;
67 # Seed Mersenne Twister
68 # Only necessary in PHP < 4.2.0
69 function wfSeedRandom()
71 global $wgRandomSeeded;
73 if ( ! $wgRandomSeeded && version_compare( phpversion(), '4.2.0' ) < 0 ) {
74 $seed = hexdec(substr(md5(microtime()),-8)) & 0x7fffffff;
76 $wgRandomSeeded = true;
80 # Generates a URL from a URL-encoded title and a query string
81 # Title::getLocalURL() is preferred in most cases
83 function wfLocalUrl( $a, $q = '' )
85 global $wgServer, $wgScript, $wgArticlePath;
87 $a = str_replace( ' ', '_', $a );
93 $a = "{$wgScript}?{$q}";
95 } else if ( '' == $q ) {
96 $a = str_replace( "$1", $a, $wgArticlePath );
97 } else if ($wgScript != '' ) {
98 $a = "{$wgScript}?title={$a}&{$q}";
99 } else { //XXX hackish solution for toplevel wikis
105 function wfLocalUrlE( $a, $q = '' )
107 return wfEscapeHTML( wfLocalUrl( $a, $q ) );
108 # die( "Call to obsolete function wfLocalUrlE()" );
111 function wfFullUrl( $a, $q = '' ) {
112 wfDebugDieBacktrace( 'Call to obsolete function wfFullUrl(); use Title::getFullURL' );
115 function wfFullUrlE( $a, $q = '' ) {
116 wfDebugDieBacktrace( 'Call to obsolete function wfFullUrlE(); use Title::getFullUrlE' );
120 // orphan function wfThumbUrl( $img )
122 // global $wgUploadPath;
124 // $nt = Title::newFromText( $img );
125 // if( !$nt ) return "";
127 // $name = $nt->getDBkey();
128 // $hash = md5( $name );
130 // $url = "{$wgUploadPath}/thumb/" . $hash{0} . "/" .
131 // substr( $hash, 0, 2 ) . "/{$name}";
132 // return wfUrlencode( $url );
136 function wfImageArchiveUrl( $name )
138 global $wgUploadPath;
140 $hash = md5( substr( $name, 15) );
141 $url = "{$wgUploadPath}/archive/" . $hash{0} . "/" .
142 substr( $hash, 0, 2 ) . "/{$name}";
143 return wfUrlencode($url);
146 function wfUrlencode ( $s )
148 $s = urlencode( $s );
149 $s = preg_replace( '/%3[Aa]/', ':', $s );
150 $s = preg_replace( '/%2[Ff]/', '/', $s );
155 function wfUtf8Sequence($codepoint) {
156 if($codepoint < 0x80) return chr($codepoint);
157 if($codepoint < 0x800) return chr($codepoint >> 6 & 0x3f |
0xc0) .
158 chr($codepoint & 0x3f |
0x80);
159 if($codepoint < 0x10000) return chr($codepoint >> 12 & 0x0f |
0xe0) .
160 chr($codepoint >> 6 & 0x3f |
0x80) .
161 chr($codepoint & 0x3f |
0x80);
162 if($codepoint < 0x100000) return chr($codepoint >> 18 & 0x07 |
0xf0) . # Double-check this
163 chr($codepoint >> 12 & 0x3f |
0x80) .
164 chr($codepoint >> 6 & 0x3f |
0x80) .
165 chr($codepoint & 0x3f |
0x80);
166 # Doesn't yet handle outside the BMP
167 return "&#$codepoint;";
170 # Converts numeric character entities to UTF-8
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
180 # Converts a single UTF-8 character into the corresponding HTML character entity
181 function wfUtf8Entity( $matches ) {
184 $z = ord( $char{0} );
187 while ( $z & 0x80 ) {
195 if ( $length != strlen( $char ) ) {
198 if ( $length == 1 ) {
202 # Mask off the length-determining bits and shift back to the original location
206 # Add in the free bits from subsequent bytes
207 for ( $i=1; $i<$length; $i++
) {
209 $z |
= ord( $char{$i} ) & 0x3f;
216 # Converts all multi-byte characters in a UTF-8 string into the appropriate character entity
217 function wfUtf8ToHTML($string) {
218 return preg_replace_callback( '/[\\xc0-\\xfd][\\x80-\\xbf]*/', 'wfUtf8Entity', $string );
221 function wfDebug( $text, $logonly = false )
223 global $wgOut, $wgDebugLogFile, $wgDebugComments, $wgProfileOnly, $wgDebugRawPage;
225 # Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
226 if ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' && !$wgDebugRawPage ) {
230 if ( isset( $wgOut ) && $wgDebugComments && !$logonly ) {
231 $wgOut->debug( $text );
233 if ( "" != $wgDebugLogFile && !$wgProfileOnly ) {
234 error_log( $text, 3, $wgDebugLogFile );
238 # Log for database errors
239 function wfLogDBError( $text ) {
240 global $wgDBerrorLog;
241 if ( $wgDBerrorLog ) {
242 $text = date("D M j G:i:s T Y") . "\t$text";
243 error_log( $text, 3, $wgDBerrorLog );
247 function logProfilingData()
249 global $wgRequestTime, $wgDebugLogFile, $wgDebugRawPage, $wgRequest;
250 global $wgProfiling, $wgProfileStack, $wgProfileLimit, $wgUser;
253 list( $usec, $sec ) = explode( " ", $wgRequestTime );
254 $start = (float)$sec +
(float)$usec;
255 $elapsed = $now - $start;
256 if ( $wgProfiling ) {
257 $prof = wfGetProfilingOutput( $start, $elapsed );
259 if( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) )
260 $forward = ' forwarded for ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
261 if( !empty( $_SERVER['HTTP_CLIENT_IP'] ) )
262 $forward .= ' client IP ' . $_SERVER['HTTP_CLIENT_IP'];
263 if( !empty( $_SERVER['HTTP_FROM'] ) )
264 $forward .= ' from ' . $_SERVER['HTTP_FROM'];
266 $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
267 if($wgUser->getId() == 0)
269 $log = sprintf( "%s\t%04.3f\t%s\n",
270 gmdate( 'YmdHis' ), $elapsed,
271 urldecode( $_SERVER['REQUEST_URI'] . $forward ) );
272 if ( '' != $wgDebugLogFile && ( $wgRequest->getVal('action') != 'raw' ||
$wgDebugRawPage ) ) {
273 error_log( $log . $prof, 3, $wgDebugLogFile );
279 function wfReadOnly()
281 global $wgReadOnlyFile;
283 if ( "" == $wgReadOnlyFile ) { return false; }
284 return is_file( $wgReadOnlyFile );
287 $wgReplacementKeys = array( "$1", "$2", "$3", "$4", "$5", "$6", "$7", "$8", "$9" );
289 # Get a message from anywhere
290 function wfMsg( $key ) {
291 $args = func_get_args();
292 if ( count( $args ) ) {
293 array_shift( $args );
295 return wfMsgReal( $key, $args, true );
298 # Get a message from the language file
299 function wfMsgNoDB( $key ) {
300 $args = func_get_args();
301 if ( count( $args ) ) {
302 array_shift( $args );
304 return wfMsgReal( $key, $args, false );
307 # Really get a message
308 function wfMsgReal( $key, $args, $useDB ) {
309 global $wgReplacementKeys, $wgMessageCache, $wgLang;
312 wfProfileIn( $fname );
313 if ( $wgMessageCache ) {
314 $message = $wgMessageCache->get( $key, $useDB );
315 } elseif ( $wgLang ) {
316 $message = $wgLang->getMessage( $key );
318 wfDebug( "No language object when getting $key\n" );
319 $message = "<$key>";
323 if( count( $args ) ) {
324 $message = str_replace( $wgReplacementKeys, $args, $message );
326 wfProfileOut( $fname );
330 function wfCleanFormFields( $fields )
332 wfDebugDieBacktrace( 'Call to obsolete wfCleanFormFields(). Use wgRequest instead...' );
335 function wfMungeQuotes( $in )
337 $out = str_replace( '%', '%25', $in );
338 $out = str_replace( "'", '%27', $out );
339 $out = str_replace( '"', '%22', $out );
343 function wfDemungeQuotes( $in )
345 $out = str_replace( '%22', '"', $in );
346 $out = str_replace( '%27', "'", $out );
347 $out = str_replace( '%25', '%', $out );
351 function wfCleanQueryVar( $var )
353 wfDebugDieBacktrace( 'Call to obsolete function wfCleanQueryVar(); use wgRequest instead' );
356 function wfSearch( $s )
358 $se = new SearchEngine( $s );
363 { # pick the nearest match
364 $se = new SearchEngine( $s );
368 # Just like exit() but makes a note of it.
369 # Commits open transactions except if the error parameter is set
370 function wfAbruptExit( $error = false ){
371 global $wgLoadBalancer;
372 static $called = false;
378 if( function_exists( 'debug_backtrace' ) ){ // PHP >= 4.3
379 $bt = debug_backtrace();
380 for($i = 0; $i < count($bt) ; $i++
){
381 $file = $bt[$i]['file'];
382 $line = $bt[$i]['line'];
383 wfDebug("WARNING: Abrupt exit in $file at line $line\n");
386 wfDebug('WARNING: Abrupt exit\n');
389 $wgLoadBalancer->closeAll();
394 function wfErrorExit() {
395 wfAbruptExit( true );
398 function wfDebugDieBacktrace( $msg = '' ) {
399 global $wgCommandLineMode;
401 if ( function_exists( 'debug_backtrace' ) ) {
402 if ( $wgCommandLineMode ) {
403 $msg .= "\nBacktrace:\n";
405 $msg .= "\n<p>Backtrace:</p>\n<ul>\n";
407 $backtrace = debug_backtrace();
408 foreach( $backtrace as $call ) {
409 $f = explode( DIRECTORY_SEPARATOR
, $call['file'] );
410 $file = $f[count($f)-1];
411 if ( $wgCommandLineMode ) {
412 $msg .= "$file line {$call['line']} calls ";
414 $msg .= '<li>' . $file . " line " . $call['line'] . ' calls ';
416 if( !empty( $call['class'] ) ) $msg .= $call['class'] . '::';
417 $msg .= $call['function'] . "()";
419 if ( $wgCommandLineMode ) {
429 function wfNumberOfArticles()
431 global $wgNumberOfArticles;
434 return $wgNumberOfArticles;
437 /* private */ function wfLoadSiteStats()
439 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
440 $fname = 'wfLoadSiteStats';
442 if ( -1 != $wgNumberOfArticles ) return;
443 $dbr =& wfGetDB( DB_SLAVE
);
444 $s = $dbr->getArray( 'site_stats',
445 array( 'ss_total_views', 'ss_total_edits', 'ss_good_articles' ),
446 array( 'ss_row_id' => 1 ), $fname
449 if ( $s === false ) {
452 $wgTotalViews = $s->ss_total_views
;
453 $wgTotalEdits = $s->ss_total_edits
;
454 $wgNumberOfArticles = $s->ss_good_articles
;
458 function wfEscapeHTML( $in )
461 array( '&', '"', '>', '<' ),
462 array( '&', '"', '>', '<' ),
466 function wfEscapeHTMLTagsOnly( $in ) {
468 array( '"', '>', '<' ),
469 array( '"', '>', '<' ),
473 function wfUnescapeHTML( $in )
475 $in = str_replace( '<', '<', $in );
476 $in = str_replace( '>', '>', $in );
477 $in = str_replace( '"', '"', $in );
478 $in = str_replace( '&', '&', $in );
482 function wfImageDir( $fname )
484 global $wgUploadDirectory;
486 $hash = md5( $fname );
487 $oldumask = umask(0);
488 $dest = $wgUploadDirectory . '/' . $hash{0};
489 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
490 $dest .= '/' . substr( $hash, 0, 2 );
491 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
497 function wfImageThumbDir( $fname , $subdir='thumb')
499 return wfImageArchiveDir( $fname, $subdir );
502 function wfImageArchiveDir( $fname , $subdir='archive')
504 global $wgUploadDirectory;
506 $hash = md5( $fname );
507 $oldumask = umask(0);
509 # Suppress warning messages here; if the file itself can't
510 # be written we'll worry about it then.
511 $archive = "{$wgUploadDirectory}/{$subdir}";
512 if ( ! is_dir( $archive ) ) { @mkdir
( $archive, 0777 ); }
513 $archive .= '/' . $hash{0};
514 if ( ! is_dir( $archive ) ) { @mkdir
( $archive, 0777 ); }
515 $archive .= '/' . substr( $hash, 0, 2 );
516 if ( ! is_dir( $archive ) ) { @mkdir
( $archive, 0777 ); }
522 function wfRecordUpload( $name, $oldver, $size, $desc, $copyStatus = "", $source = "" )
524 global $wgUser, $wgLang, $wgTitle, $wgOut, $wgDeferredUpdateList;
525 global $wgUseCopyrightUpload;
527 $fname = 'wfRecordUpload';
528 $dbw =& wfGetDB( DB_MASTER
);
530 # img_name must be unique
531 if ( !$dbw->indexUnique( 'image', 'img_name' ) ) {
532 wfDebugDieBacktrace( 'Database schema not up to date, please run maintenance/archives/patch-image_name_unique.sql' );
536 $now = wfTimestampNow();
537 $won = wfInvertTimestamp( $now );
538 $size = IntVal( $size );
540 if ( $wgUseCopyrightUpload )
542 $textdesc = '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $desc . "\n" .
543 '== ' . wfMsg ( 'filestatus' ) . " ==\n" . $copyStatus . "\n" .
544 '== ' . wfMsg ( 'filesource' ) . " ==\n" . $source ;
546 else $textdesc = $desc ;
548 $now = wfTimestampNow();
549 $won = wfInvertTimestamp( $now );
551 # Test to see if the row exists using INSERT IGNORE
552 # This avoids race conditions by locking the row until the commit, and also
553 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
554 $dbw->insert( 'image',
558 'img_timestamp' => $now,
559 'img_description' => $desc,
560 'img_user' => $wgUser->getID(),
561 'img_user_text' => $wgUser->getName(),
564 $descTitle = Title
::makeTitle( NS_IMAGE
, $name );
566 if ( $dbw->affectedRows() ) {
567 # Successfully inserted, this is a new image
568 $id = $descTitle->getArticleID();
571 $seqVal = $dbw->nextSequenceValue( 'cur_cur_id_seq' );
572 $dbw->insertArray( 'cur',
575 'cur_namespace' => NS_IMAGE
,
576 'cur_title' => $name,
577 'cur_comment' => $desc,
578 'cur_user' => $wgUser->getID(),
579 'cur_user_text' => $wgUser->getName(),
580 'cur_timestamp' => $now,
582 'cur_text' => $textdesc,
583 'inverse_timestamp' => $won,
584 'cur_touched' => $now
587 $id = $dbw->insertId() or 0; # We should throw an error instead
589 RecentChange
::notifyNew( $now, $descTitle, 0, $wgUser, $desc );
591 $u = new SearchUpdate( $id, $name, $desc );
595 # Collision, this is an update of an image
596 # Get current image row for update
597 $s = $dbw->getArray( 'image', array( 'img_name','img_size','img_timestamp','img_description',
598 'img_user','img_user_text' ), array( 'img_name' => $name ), $fname, 'FOR UPDATE' );
600 # Insert it into oldimage
601 $dbw->insertArray( 'oldimage',
603 'oi_name' => $s->img_name
,
604 'oi_archive_name' => $oldver,
605 'oi_size' => $s->img_size
,
606 'oi_timestamp' => $s->img_timestamp
,
607 'oi_description' => $s->img_description
,
608 'oi_user' => $s->img_user
,
609 'oi_user_text' => $s->img_user_text
613 # Update the current image row
614 $dbw->updateArray( 'image',
617 'img_timestamp' => wfTimestampNow(),
618 'img_user' => $wgUser->getID(),
619 'img_user_text' => $wgUser->getName(),
620 'img_description' => $desc,
621 ), array( /* WHERE */
626 # Invalidate the cache for the description page
627 $descTitle->invalidateCache();
630 $log = new LogPage( wfMsg( 'uploadlogpage' ), wfMsg( 'uploadlogpagetext' ) );
631 $da = wfMsg( 'uploadedimage', '[[:' . $wgLang->getNsText(
632 Namespace::getImage() ) . ":{$name}|{$name}]]" );
633 $ta = wfMsg( 'uploadedimage', $name );
634 $log->addEntry( $da, $desc, $ta );
638 /* Some generic result counters, pulled out of SearchEngine */
640 function wfShowingResults( $offset, $limit )
643 return wfMsg( 'showingresults', $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+
1 ) );
646 function wfShowingResultsNum( $offset, $limit, $num )
649 return wfMsg( 'showingresultsnum', $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+
1 ), $wgLang->formatNum( $num ) );
652 function wfViewPrevNext( $offset, $limit, $link, $query = '', $atend = false )
654 global $wgUser, $wgLang;
655 $fmtLimit = $wgLang->formatNum( $limit );
656 $prev = wfMsg( 'prevn', $fmtLimit );
657 $next = wfMsg( 'nextn', $fmtLimit );
658 $link = wfUrlencode( $link );
660 $sk = $wgUser->getSkin();
661 if ( 0 != $offset ) {
662 $po = $offset - $limit;
663 if ( $po < 0 ) { $po = 0; }
664 $q = "limit={$limit}&offset={$po}";
665 if ( '' != $query ) { $q .= "&{$query}"; }
666 $plink = '<a href="' . wfLocalUrlE( $link, $q ) . "\">{$prev}</a>";
667 } else { $plink = $prev; }
669 $no = $offset +
$limit;
670 $q = "limit={$limit}&offset={$no}";
671 if ( "" != $query ) { $q .= "&{$query}"; }
676 $nlink = '<a href="' . wfLocalUrlE( $link, $q ) . "\">{$next}</a>";
678 $nums = wfNumLink( $offset, 20, $link , $query ) . ' | ' .
679 wfNumLink( $offset, 50, $link, $query ) . ' | ' .
680 wfNumLink( $offset, 100, $link, $query ) . ' | ' .
681 wfNumLink( $offset, 250, $link, $query ) . ' | ' .
682 wfNumLink( $offset, 500, $link, $query );
684 return wfMsg( 'viewprevnext', $plink, $nlink, $nums );
687 function wfNumLink( $offset, $limit, $link, $query = '' )
689 global $wgUser, $wgLang;
690 if ( '' == $query ) { $q = ''; }
691 else { $q = "{$query}&"; }
692 $q .= "limit={$limit}&offset={$offset}";
694 $fmtLimit = $wgLang->formatNum( $limit );
695 $s = '<a href="' . wfLocalUrlE( $link, $q ) . "\">{$fmtLimit}</a>";
699 function wfClientAcceptsGzip() {
702 # FIXME: we may want to blacklist some broken browsers
704 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
705 $_SERVER['HTTP_ACCEPT_ENCODING'],
707 if( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) return false;
708 wfDebug( " accepts gzip\n" );
715 # Yay, more global functions!
716 function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) {
717 global $wgUser, $wgRequest;
719 $limit = $wgRequest->getInt( 'limit', 0 );
720 if( $limit < 0 ) $limit = 0;
721 if( ( $limit == 0 ) && ( $optionname != '' ) ) {
722 $limit = (int)$wgUser->getOption( $optionname );
724 if( $limit <= 0 ) $limit = $deflimit;
725 if( $limit > 5000 ) $limit = 5000; # We have *some* limits...
727 $offset = $wgRequest->getInt( 'offset', 0 );
728 if( $offset < 0 ) $offset = 0;
730 return array( $limit, $offset );
733 # Escapes the given text so that it may be output using addWikiText()
734 # without any linking, formatting, etc. making its way through. This
735 # is achieved by substituting certain characters with HTML entities.
736 # As required by the callers, <nowiki> is not used. It currently does
737 # not filter out characters which have special meaning only at the
738 # start of a line, such as "*".
739 function wfEscapeWikiText( $text )
742 array( '[', '|', "'", 'ISBN ' , '://' , "\n=" ),
743 array( '[', '|', ''', 'ISBN ', '://' , "\n=" ),
744 htmlspecialchars($text) );
748 function wfQuotedPrintable( $string, $charset = '' )
750 # Probably incomplete; see RFC 2045
751 if( empty( $charset ) ) {
752 global $wgInputEncoding;
753 $charset = $wgInputEncoding;
755 $charset = strtoupper( $charset );
756 $charset = str_replace( 'ISO-8859', 'ISO8859', $charset ); // ?
758 $illegal = '\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\xff=';
759 $replace = $illegal . '\t ?_';
760 if( !preg_match( "/[$illegal]/", $string ) ) return $string;
761 $out = "=?$charset?Q?";
762 $out .= preg_replace( "/([$replace])/e", 'sprintf("=%02X",ord("$1"))', $string );
768 $st = explode( ' ', microtime() );
769 return (float)$st[0] +
(float)$st[1];
772 # Changes the first character to an HTML entity
773 function wfHtmlEscapeFirst( $text ) {
775 $newText = substr($text, 1);
776 return "&#$ord;$newText";
779 # Sets dest to source and returns the original value of dest
780 # If source is NULL, it just returns the value, it doesn't set the variable
781 function wfSetVar( &$dest, $source )
784 if ( !is_null( $source ) ) {
790 # As for wfSetVar except setting a bit
791 function wfSetBit( &$dest, $bit, $state = true ) {
792 $temp = (bool)($dest & $bit );
793 if ( !is_null( $state ) ) {
803 # This function takes two arrays as input, and returns a CGI-style string, e.g.
804 # "days=7&limit=100". Options in the first array override options in the second.
805 # Options set to "" will not be output.
806 function wfArrayToCGI( $array1, $array2 = NULL )
808 if ( !is_null( $array2 ) ) {
809 $array1 = $array1 +
$array2;
813 foreach ( $array1 as $key => $value ) {
814 if ( '' !== $value ) {
818 $cgi .= "{$key}={$value}";
824 # This is obsolete, use SquidUpdate::purge()
825 function wfPurgeSquidServers ($urlArr) {
826 SquidUpdate
::purge( $urlArr );
829 # Windows-compatible version of escapeshellarg()
830 function wfEscapeShellArg( )
832 $args = func_get_args();
835 foreach ( $args as $arg ) {
842 if ( wfIsWindows() ) {
843 $retVal .= '"' . str_replace( '"','\"', $arg ) . '"';
845 $retVal .= escapeshellarg( $arg );
851 # wfMerge attempts to merge differences between three texts.
852 # Returns true for a clean merge and false for failure or a conflict.
854 function wfMerge( $old, $mine, $yours, &$result ){
857 # This check may also protect against code injection in
858 # case of broken installations.
859 if(! file_exists( $wgDiff3 ) ){
863 # Make temporary files
865 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
866 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
867 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
869 fwrite( $oldtextFile, $old ); fclose( $oldtextFile );
870 fwrite( $mytextFile, $mine ); fclose( $mytextFile );
871 fwrite( $yourtextFile, $yours ); fclose( $yourtextFile );
873 # Check for a conflict
874 $cmd = wfEscapeShellArg( $wgDiff3 ) . ' -a --overlap-only ' .
875 wfEscapeShellArg( $mytextName ) . ' ' .
876 wfEscapeShellArg( $oldtextName ) . ' ' .
877 wfEscapeShellArg( $yourtextName );
878 $handle = popen( $cmd, 'r' );
880 if( fgets( $handle ) ){
888 $cmd = wfEscapeShellArg( $wgDiff3 ) . ' -a -e --merge ' .
889 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
890 $handle = popen( $cmd, 'r' );
893 $data = fread( $handle, 8192 );
894 if ( strlen( $data ) == 0 ) {
900 unlink( $mytextName ); unlink( $oldtextName ); unlink( $yourtextName );
904 function wfVarDump( $var )
907 $s = str_replace("\n","<br>\n", var_export( $var, true ) . "\n");
908 if ( headers_sent() ||
!@is_object
( $wgOut ) ) {
911 $wgOut->addHTML( $s );
915 # Provide a simple HTTP error.
916 function wfHttpError( $code, $label, $desc ) {
919 header( "HTTP/1.0 $code $label" );
920 header( "Status: $code $label" );
921 $wgOut->sendCacheControl();
923 # Don't send content if it's a HEAD request.
924 if( $_SERVER['REQUEST_METHOD'] == 'HEAD' ) {
925 header( 'Content-type: text/plain' );
930 # Converts an Accept-* header into an array mapping string values to quality factors
931 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
932 # No arg means accept anything (per HTTP spec)
934 return array( $def => 1 );
939 $parts = explode( ',', $accept );
941 foreach( $parts as $part ) {
942 # FIXME: doesn't deal with params like 'text/html; level=1'
943 @list
( $value, $qpart ) = explode( ';', $part );
944 if( !isset( $qpart ) ) {
946 } elseif( preg_match( '/q\s*=\s*(\d*\.\d+)/', $qpart, $match ) ) {
947 $prefs[$value] = $match[1];
954 /* private */ function mimeTypeMatch( $type, $avail ) {
955 if( array_key_exists($type, $avail) ) {
958 $parts = explode( '/', $type );
959 if( array_key_exists( $parts[0] . '/*', $avail ) ) {
960 return $parts[0] . '/*';
961 } elseif( array_key_exists( '*/*', $avail ) ) {
969 # FIXME: doesn't handle params like 'text/plain; charset=UTF-8'
970 # XXX: generalize to negotiate other stuff
971 function wfNegotiateType( $cprefs, $sprefs ) {
974 foreach( array_keys($sprefs) as $type ) {
975 $parts = explode( '/', $type );
976 if( $parts[1] != '*' ) {
977 $ckey = mimeTypeMatch( $type, $cprefs );
979 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
984 foreach( array_keys( $cprefs ) as $type ) {
985 $parts = explode( '/', $type );
986 if( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
987 $skey = mimeTypeMatch( $type, $sprefs );
989 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
997 foreach( array_keys( $combine ) as $type ) {
998 if( $combine[$type] > $bestq ) {
1000 $bestq = $combine[$type];
1008 # Returns an array where the values in the first array are replaced by the
1009 # values in the second array with the corresponding keys
1010 function wfArrayLookup( $a, $b )
1012 return array_flip( array_intersect( array_flip( $a ), array_keys( $b ) ) );
1015 # Since Windows is so different to any of the other popular OSes, it seems appropriate
1016 # to have a simple way to test for its presence
1017 function wfIsWindows() {
1018 if (substr(php_uname(), 0, 7) == 'Windows') {
1026 # Ideally we'd be using actual time fields in the db
1027 function wfTimestamp2Unix( $ts ) {
1028 return gmmktime( ( (int)substr( $ts, 8, 2) ),
1029 (int)substr( $ts, 10, 2 ), (int)substr( $ts, 12, 2 ),
1030 (int)substr( $ts, 4, 2 ), (int)substr( $ts, 6, 2 ),
1031 (int)substr( $ts, 0, 4 ) );
1034 function wfUnix2Timestamp( $unixtime ) {
1035 return gmdate( "YmdHis", $unixtime );
1038 function wfTimestampNow() {
1040 return gmdate( "YmdHis" );
1043 # Sorting hack for MySQL 3, which doesn't use index sorts for DESC
1044 function wfInvertTimestamp( $ts ) {
1052 # Reference-counted warning suppression
1053 function wfSuppressWarnings( $end = false ) {
1054 static $suppressCount = 0;
1055 static $originalLevel = false;
1058 if ( $suppressCount ) {
1060 if ( !$suppressCount ) {
1061 error_reporting( $originalLevel );
1065 if ( !$suppressCount ) {
1066 $originalLevel = error_reporting( E_ALL
& ~
( E_WARNING | E_NOTICE
) );
1072 # Restore error level to previous value
1073 function wfRestoreWarnings() {
1074 wfSuppressWarnings( true );
1077 # Autodetect, convert and provide timestamps of various types
1078 define("TS_UNIX",0); # Standard unix timestamp
1079 define("TS_MW",1); # Mediawiki concatenated string timestamp (yyyymmddhhmmss)
1080 define("TS_DB",2); # Standard database timestamp (yyyy-mm-dd hh:mm:ss)
1082 function wfTimestamp($outputtype=TS_UNIX
,$ts=0) {
1083 if (preg_match("/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)$/",$ts,$da)) {
1085 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1086 (int)$da[2],(int)$da[3],(int)$da[1]);
1087 } elseif (preg_match("/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/",$ts,$da)) {
1089 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1090 (int)$da[2],(int)$da[3],(int)$da[1]);
1091 } elseif (preg_match("/^(\d{1,13})$/",$ts,$datearray)) {
1098 switch($outputtype) {
1103 return gmdate( "YmdHis", $uts );
1106 return gmdate( "Y-m-d H:i:s", $uts );