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 ) {
292 if ( $wgRequest->getVal( 'debugmsg' ) )
294 $args = func_get_args();
295 if ( count( $args ) ) {
296 array_shift( $args );
298 return wfMsgReal( $key, $args, true );
301 # Get a message from the language file
302 function wfMsgNoDB( $key ) {
303 $args = func_get_args();
304 if ( count( $args ) ) {
305 array_shift( $args );
307 return wfMsgReal( $key, $args, false );
310 # Really get a message
311 function wfMsgReal( $key, $args, $useDB ) {
312 global $wgReplacementKeys, $wgMessageCache, $wgLang;
315 wfProfileIn( $fname );
316 if ( $wgMessageCache ) {
317 $message = $wgMessageCache->get( $key, $useDB );
318 } elseif ( $wgLang ) {
319 $message = $wgLang->getMessage( $key );
321 wfDebug( "No language object when getting $key\n" );
322 $message = "<$key>";
326 if( count( $args ) ) {
327 $message = str_replace( $wgReplacementKeys, $args, $message );
329 wfProfileOut( $fname );
333 function wfCleanFormFields( $fields )
335 wfDebugDieBacktrace( 'Call to obsolete wfCleanFormFields(). Use wgRequest instead...' );
338 function wfMungeQuotes( $in )
340 $out = str_replace( '%', '%25', $in );
341 $out = str_replace( "'", '%27', $out );
342 $out = str_replace( '"', '%22', $out );
346 function wfDemungeQuotes( $in )
348 $out = str_replace( '%22', '"', $in );
349 $out = str_replace( '%27', "'", $out );
350 $out = str_replace( '%25', '%', $out );
354 function wfCleanQueryVar( $var )
356 wfDebugDieBacktrace( 'Call to obsolete function wfCleanQueryVar(); use wgRequest instead' );
359 function wfSearch( $s )
361 $se = new SearchEngine( $s );
366 { # pick the nearest match
367 $se = new SearchEngine( $s );
371 # Just like exit() but makes a note of it.
372 # Commits open transactions except if the error parameter is set
373 function wfAbruptExit( $error = false ){
374 global $wgLoadBalancer;
375 static $called = false;
381 if( function_exists( 'debug_backtrace' ) ){ // PHP >= 4.3
382 $bt = debug_backtrace();
383 for($i = 0; $i < count($bt) ; $i++
){
384 $file = $bt[$i]['file'];
385 $line = $bt[$i]['line'];
386 wfDebug("WARNING: Abrupt exit in $file at line $line\n");
389 wfDebug('WARNING: Abrupt exit\n');
392 $wgLoadBalancer->closeAll();
397 function wfErrorExit() {
398 wfAbruptExit( true );
401 function wfDebugDieBacktrace( $msg = '' ) {
402 global $wgCommandLineMode;
404 if ( function_exists( 'debug_backtrace' ) ) {
405 if ( $wgCommandLineMode ) {
406 $msg .= "\nBacktrace:\n";
408 $msg .= "\n<p>Backtrace:</p>\n<ul>\n";
410 $backtrace = debug_backtrace();
411 foreach( $backtrace as $call ) {
412 $f = explode( DIRECTORY_SEPARATOR
, $call['file'] );
413 $file = $f[count($f)-1];
414 if ( $wgCommandLineMode ) {
415 $msg .= "$file line {$call['line']} calls ";
417 $msg .= '<li>' . $file . " line " . $call['line'] . ' calls ';
419 if( !empty( $call['class'] ) ) $msg .= $call['class'] . '::';
420 $msg .= $call['function'] . "()";
422 if ( $wgCommandLineMode ) {
432 function wfNumberOfArticles()
434 global $wgNumberOfArticles;
437 return $wgNumberOfArticles;
440 /* private */ function wfLoadSiteStats()
442 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
443 $fname = 'wfLoadSiteStats';
445 if ( -1 != $wgNumberOfArticles ) return;
446 $dbr =& wfGetDB( DB_SLAVE
);
447 $s = $dbr->getArray( 'site_stats',
448 array( 'ss_total_views', 'ss_total_edits', 'ss_good_articles' ),
449 array( 'ss_row_id' => 1 ), $fname
452 if ( $s === false ) {
455 $wgTotalViews = $s->ss_total_views
;
456 $wgTotalEdits = $s->ss_total_edits
;
457 $wgNumberOfArticles = $s->ss_good_articles
;
461 function wfEscapeHTML( $in )
464 array( '&', '"', '>', '<' ),
465 array( '&', '"', '>', '<' ),
469 function wfEscapeHTMLTagsOnly( $in ) {
471 array( '"', '>', '<' ),
472 array( '"', '>', '<' ),
476 function wfUnescapeHTML( $in )
478 $in = str_replace( '<', '<', $in );
479 $in = str_replace( '>', '>', $in );
480 $in = str_replace( '"', '"', $in );
481 $in = str_replace( '&', '&', $in );
485 function wfImageDir( $fname )
487 global $wgUploadDirectory;
489 $hash = md5( $fname );
490 $oldumask = umask(0);
491 $dest = $wgUploadDirectory . '/' . $hash{0};
492 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
493 $dest .= '/' . substr( $hash, 0, 2 );
494 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
500 function wfImageThumbDir( $fname , $subdir='thumb')
502 return wfImageArchiveDir( $fname, $subdir );
505 function wfImageArchiveDir( $fname , $subdir='archive')
507 global $wgUploadDirectory;
509 $hash = md5( $fname );
510 $oldumask = umask(0);
512 # Suppress warning messages here; if the file itself can't
513 # be written we'll worry about it then.
514 $archive = "{$wgUploadDirectory}/{$subdir}";
515 if ( ! is_dir( $archive ) ) { @mkdir
( $archive, 0777 ); }
516 $archive .= '/' . $hash{0};
517 if ( ! is_dir( $archive ) ) { @mkdir
( $archive, 0777 ); }
518 $archive .= '/' . substr( $hash, 0, 2 );
519 if ( ! is_dir( $archive ) ) { @mkdir
( $archive, 0777 ); }
525 function wfRecordUpload( $name, $oldver, $size, $desc, $copyStatus = "", $source = "" )
527 global $wgUser, $wgLang, $wgTitle, $wgOut, $wgDeferredUpdateList;
528 global $wgUseCopyrightUpload;
530 $fname = 'wfRecordUpload';
531 $dbw =& wfGetDB( DB_MASTER
);
533 # img_name must be unique
534 if ( !$dbw->indexUnique( 'image', 'img_name' ) ) {
535 wfDebugDieBacktrace( 'Database schema not up to date, please run maintenance/archives/patch-image_name_unique.sql' );
539 $now = wfTimestampNow();
540 $won = wfInvertTimestamp( $now );
541 $size = IntVal( $size );
543 if ( $wgUseCopyrightUpload )
545 $textdesc = '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $desc . "\n" .
546 '== ' . wfMsg ( 'filestatus' ) . " ==\n" . $copyStatus . "\n" .
547 '== ' . wfMsg ( 'filesource' ) . " ==\n" . $source ;
549 else $textdesc = $desc ;
551 $now = wfTimestampNow();
552 $won = wfInvertTimestamp( $now );
554 # Test to see if the row exists using INSERT IGNORE
555 # This avoids race conditions by locking the row until the commit, and also
556 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
557 $dbw->insert( 'image',
561 'img_timestamp' => $now,
562 'img_description' => $desc,
563 'img_user' => $wgUser->getID(),
564 'img_user_text' => $wgUser->getName(),
567 $descTitle = Title
::makeTitle( NS_IMAGE
, $name );
569 if ( $dbw->affectedRows() ) {
570 # Successfully inserted, this is a new image
571 $id = $descTitle->getArticleID();
574 $seqVal = $dbw->nextSequenceValue( 'cur_cur_id_seq' );
575 $dbw->insertArray( 'cur',
578 'cur_namespace' => NS_IMAGE
,
579 'cur_title' => $name,
580 'cur_comment' => $desc,
581 'cur_user' => $wgUser->getID(),
582 'cur_user_text' => $wgUser->getName(),
583 'cur_timestamp' => $now,
585 'cur_text' => $textdesc,
586 'inverse_timestamp' => $won,
587 'cur_touched' => $now
590 $id = $dbw->insertId() or 0; # We should throw an error instead
592 RecentChange
::notifyNew( $now, $descTitle, 0, $wgUser, $desc );
594 $u = new SearchUpdate( $id, $name, $desc );
598 # Collision, this is an update of an image
599 # Get current image row for update
600 $s = $dbw->getArray( 'image', array( 'img_name','img_size','img_timestamp','img_description',
601 'img_user','img_user_text' ), array( 'img_name' => $name ), $fname, 'FOR UPDATE' );
603 # Insert it into oldimage
604 $dbw->insertArray( 'oldimage',
606 'oi_name' => $s->img_name
,
607 'oi_archive_name' => $oldver,
608 'oi_size' => $s->img_size
,
609 'oi_timestamp' => $s->img_timestamp
,
610 'oi_description' => $s->img_description
,
611 'oi_user' => $s->img_user
,
612 'oi_user_text' => $s->img_user_text
616 # Update the current image row
617 $dbw->updateArray( 'image',
620 'img_timestamp' => wfTimestampNow(),
621 'img_user' => $wgUser->getID(),
622 'img_user_text' => $wgUser->getName(),
623 'img_description' => $desc,
624 ), array( /* WHERE */
629 # Invalidate the cache for the description page
630 $descTitle->invalidateCache();
633 $log = new LogPage( wfMsg( 'uploadlogpage' ), wfMsg( 'uploadlogpagetext' ) );
634 $da = wfMsg( 'uploadedimage', '[[:' . $wgLang->getNsText(
635 Namespace::getImage() ) . ":{$name}|{$name}]]" );
636 $ta = wfMsg( 'uploadedimage', $name );
637 $log->addEntry( $da, $desc, $ta );
641 /* Some generic result counters, pulled out of SearchEngine */
643 function wfShowingResults( $offset, $limit )
646 return wfMsg( 'showingresults', $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+
1 ) );
649 function wfShowingResultsNum( $offset, $limit, $num )
652 return wfMsg( 'showingresultsnum', $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+
1 ), $wgLang->formatNum( $num ) );
655 function wfViewPrevNext( $offset, $limit, $link, $query = '', $atend = false )
657 global $wgUser, $wgLang;
658 $fmtLimit = $wgLang->formatNum( $limit );
659 $prev = wfMsg( 'prevn', $fmtLimit );
660 $next = wfMsg( 'nextn', $fmtLimit );
661 $link = wfUrlencode( $link );
663 $sk = $wgUser->getSkin();
664 if ( 0 != $offset ) {
665 $po = $offset - $limit;
666 if ( $po < 0 ) { $po = 0; }
667 $q = "limit={$limit}&offset={$po}";
668 if ( '' != $query ) { $q .= "&{$query}"; }
669 $plink = '<a href="' . wfLocalUrlE( $link, $q ) . "\">{$prev}</a>";
670 } else { $plink = $prev; }
672 $no = $offset +
$limit;
673 $q = "limit={$limit}&offset={$no}";
674 if ( "" != $query ) { $q .= "&{$query}"; }
679 $nlink = '<a href="' . wfLocalUrlE( $link, $q ) . "\">{$next}</a>";
681 $nums = wfNumLink( $offset, 20, $link , $query ) . ' | ' .
682 wfNumLink( $offset, 50, $link, $query ) . ' | ' .
683 wfNumLink( $offset, 100, $link, $query ) . ' | ' .
684 wfNumLink( $offset, 250, $link, $query ) . ' | ' .
685 wfNumLink( $offset, 500, $link, $query );
687 return wfMsg( 'viewprevnext', $plink, $nlink, $nums );
690 function wfNumLink( $offset, $limit, $link, $query = '' )
692 global $wgUser, $wgLang;
693 if ( '' == $query ) { $q = ''; }
694 else { $q = "{$query}&"; }
695 $q .= "limit={$limit}&offset={$offset}";
697 $fmtLimit = $wgLang->formatNum( $limit );
698 $s = '<a href="' . wfLocalUrlE( $link, $q ) . "\">{$fmtLimit}</a>";
702 function wfClientAcceptsGzip() {
705 # FIXME: we may want to blacklist some broken browsers
707 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
708 $_SERVER['HTTP_ACCEPT_ENCODING'],
710 if( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) return false;
711 wfDebug( " accepts gzip\n" );
718 # Yay, more global functions!
719 function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) {
720 global $wgUser, $wgRequest;
722 $limit = $wgRequest->getInt( 'limit', 0 );
723 if( $limit < 0 ) $limit = 0;
724 if( ( $limit == 0 ) && ( $optionname != '' ) ) {
725 $limit = (int)$wgUser->getOption( $optionname );
727 if( $limit <= 0 ) $limit = $deflimit;
728 if( $limit > 5000 ) $limit = 5000; # We have *some* limits...
730 $offset = $wgRequest->getInt( 'offset', 0 );
731 if( $offset < 0 ) $offset = 0;
733 return array( $limit, $offset );
736 # Escapes the given text so that it may be output using addWikiText()
737 # without any linking, formatting, etc. making its way through. This
738 # is achieved by substituting certain characters with HTML entities.
739 # As required by the callers, <nowiki> is not used. It currently does
740 # not filter out characters which have special meaning only at the
741 # start of a line, such as "*".
742 function wfEscapeWikiText( $text )
745 array( '[', '|', "'", 'ISBN ' , '://' , "\n=" ),
746 array( '[', '|', ''', 'ISBN ', '://' , "\n=" ),
747 htmlspecialchars($text) );
751 function wfQuotedPrintable( $string, $charset = '' )
753 # Probably incomplete; see RFC 2045
754 if( empty( $charset ) ) {
755 global $wgInputEncoding;
756 $charset = $wgInputEncoding;
758 $charset = strtoupper( $charset );
759 $charset = str_replace( 'ISO-8859', 'ISO8859', $charset ); // ?
761 $illegal = '\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\xff=';
762 $replace = $illegal . '\t ?_';
763 if( !preg_match( "/[$illegal]/", $string ) ) return $string;
764 $out = "=?$charset?Q?";
765 $out .= preg_replace( "/([$replace])/e", 'sprintf("=%02X",ord("$1"))', $string );
771 $st = explode( ' ', microtime() );
772 return (float)$st[0] +
(float)$st[1];
775 # Changes the first character to an HTML entity
776 function wfHtmlEscapeFirst( $text ) {
778 $newText = substr($text, 1);
779 return "&#$ord;$newText";
782 # Sets dest to source and returns the original value of dest
783 # If source is NULL, it just returns the value, it doesn't set the variable
784 function wfSetVar( &$dest, $source )
787 if ( !is_null( $source ) ) {
793 # As for wfSetVar except setting a bit
794 function wfSetBit( &$dest, $bit, $state = true ) {
795 $temp = (bool)($dest & $bit );
796 if ( !is_null( $state ) ) {
806 # This function takes two arrays as input, and returns a CGI-style string, e.g.
807 # "days=7&limit=100". Options in the first array override options in the second.
808 # Options set to "" will not be output.
809 function wfArrayToCGI( $array1, $array2 = NULL )
811 if ( !is_null( $array2 ) ) {
812 $array1 = $array1 +
$array2;
816 foreach ( $array1 as $key => $value ) {
817 if ( '' !== $value ) {
821 $cgi .= "{$key}={$value}";
827 # This is obsolete, use SquidUpdate::purge()
828 function wfPurgeSquidServers ($urlArr) {
829 SquidUpdate
::purge( $urlArr );
832 # Windows-compatible version of escapeshellarg()
833 function wfEscapeShellArg( )
835 $args = func_get_args();
838 foreach ( $args as $arg ) {
845 if ( wfIsWindows() ) {
846 $retVal .= '"' . str_replace( '"','\"', $arg ) . '"';
848 $retVal .= escapeshellarg( $arg );
854 # wfMerge attempts to merge differences between three texts.
855 # Returns true for a clean merge and false for failure or a conflict.
857 function wfMerge( $old, $mine, $yours, &$result ){
860 # This check may also protect against code injection in
861 # case of broken installations.
862 if(! file_exists( $wgDiff3 ) ){
866 # Make temporary files
868 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
869 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
870 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
872 fwrite( $oldtextFile, $old ); fclose( $oldtextFile );
873 fwrite( $mytextFile, $mine ); fclose( $mytextFile );
874 fwrite( $yourtextFile, $yours ); fclose( $yourtextFile );
876 # Check for a conflict
877 $cmd = wfEscapeShellArg( $wgDiff3 ) . ' -a --overlap-only ' .
878 wfEscapeShellArg( $mytextName ) . ' ' .
879 wfEscapeShellArg( $oldtextName ) . ' ' .
880 wfEscapeShellArg( $yourtextName );
881 $handle = popen( $cmd, 'r' );
883 if( fgets( $handle ) ){
891 $cmd = wfEscapeShellArg( $wgDiff3 ) . ' -a -e --merge ' .
892 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
893 $handle = popen( $cmd, 'r' );
896 $data = fread( $handle, 8192 );
897 if ( strlen( $data ) == 0 ) {
903 unlink( $mytextName ); unlink( $oldtextName ); unlink( $yourtextName );
907 function wfVarDump( $var )
910 $s = str_replace("\n","<br>\n", var_export( $var, true ) . "\n");
911 if ( headers_sent() ||
!@is_object
( $wgOut ) ) {
914 $wgOut->addHTML( $s );
918 # Provide a simple HTTP error.
919 function wfHttpError( $code, $label, $desc ) {
922 header( "HTTP/1.0 $code $label" );
923 header( "Status: $code $label" );
924 $wgOut->sendCacheControl();
926 # Don't send content if it's a HEAD request.
927 if( $_SERVER['REQUEST_METHOD'] == 'HEAD' ) {
928 header( 'Content-type: text/plain' );
933 # Converts an Accept-* header into an array mapping string values to quality factors
934 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
935 # No arg means accept anything (per HTTP spec)
937 return array( $def => 1 );
942 $parts = explode( ',', $accept );
944 foreach( $parts as $part ) {
945 # FIXME: doesn't deal with params like 'text/html; level=1'
946 @list
( $value, $qpart ) = explode( ';', $part );
947 if( !isset( $qpart ) ) {
949 } elseif( preg_match( '/q\s*=\s*(\d*\.\d+)/', $qpart, $match ) ) {
950 $prefs[$value] = $match[1];
957 /* private */ function mimeTypeMatch( $type, $avail ) {
958 if( array_key_exists($type, $avail) ) {
961 $parts = explode( '/', $type );
962 if( array_key_exists( $parts[0] . '/*', $avail ) ) {
963 return $parts[0] . '/*';
964 } elseif( array_key_exists( '*/*', $avail ) ) {
972 # FIXME: doesn't handle params like 'text/plain; charset=UTF-8'
973 # XXX: generalize to negotiate other stuff
974 function wfNegotiateType( $cprefs, $sprefs ) {
977 foreach( array_keys($sprefs) as $type ) {
978 $parts = explode( '/', $type );
979 if( $parts[1] != '*' ) {
980 $ckey = mimeTypeMatch( $type, $cprefs );
982 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
987 foreach( array_keys( $cprefs ) as $type ) {
988 $parts = explode( '/', $type );
989 if( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
990 $skey = mimeTypeMatch( $type, $sprefs );
992 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1000 foreach( array_keys( $combine ) as $type ) {
1001 if( $combine[$type] > $bestq ) {
1003 $bestq = $combine[$type];
1011 # Returns an array where the values in the first array are replaced by the
1012 # values in the second array with the corresponding keys
1013 function wfArrayLookup( $a, $b )
1015 return array_flip( array_intersect( array_flip( $a ), array_keys( $b ) ) );
1018 # Since Windows is so different to any of the other popular OSes, it seems appropriate
1019 # to have a simple way to test for its presence
1020 function wfIsWindows() {
1021 if (substr(php_uname(), 0, 7) == 'Windows') {
1029 # Ideally we'd be using actual time fields in the db
1030 function wfTimestamp2Unix( $ts ) {
1031 return gmmktime( ( (int)substr( $ts, 8, 2) ),
1032 (int)substr( $ts, 10, 2 ), (int)substr( $ts, 12, 2 ),
1033 (int)substr( $ts, 4, 2 ), (int)substr( $ts, 6, 2 ),
1034 (int)substr( $ts, 0, 4 ) );
1037 function wfUnix2Timestamp( $unixtime ) {
1038 return gmdate( "YmdHis", $unixtime );
1041 function wfTimestampNow() {
1043 return gmdate( "YmdHis" );
1046 # Sorting hack for MySQL 3, which doesn't use index sorts for DESC
1047 function wfInvertTimestamp( $ts ) {
1055 # Reference-counted warning suppression
1056 function wfSuppressWarnings( $end = false ) {
1057 static $suppressCount = 0;
1058 static $originalLevel = false;
1061 if ( $suppressCount ) {
1063 if ( !$suppressCount ) {
1064 error_reporting( $originalLevel );
1068 if ( !$suppressCount ) {
1069 $originalLevel = error_reporting( E_ALL
& ~
( E_WARNING | E_NOTICE
) );
1075 # Restore error level to previous value
1076 function wfRestoreWarnings() {
1077 wfSuppressWarnings( true );
1080 # Autodetect, convert and provide timestamps of various types
1081 define("TS_UNIX",0); # Standard unix timestamp (number of seconds since 1 Jan 1970)
1082 define("TS_MW",1); # Mediawiki concatenated string timestamp (yyyymmddhhmmss)
1083 define("TS_DB",2); # Standard database timestamp (yyyy-mm-dd hh:mm:ss)
1085 function wfTimestamp($outputtype=TS_UNIX
,$ts=0) {
1086 if (preg_match("/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)$/",$ts,$da)) {
1088 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1089 (int)$da[2],(int)$da[3],(int)$da[1]);
1090 } elseif (preg_match("/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/",$ts,$da)) {
1092 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1093 (int)$da[2],(int)$da[3],(int)$da[1]);
1094 } elseif (preg_match("/^(\d{1,13})$/",$ts,$datearray)) {
1101 switch($outputtype) {
1106 return gmdate( "YmdHis", $uts );
1109 return gmdate( "Y-m-d H:i:s", $uts );