With &debugmsg=1, PHP output a warning because the link trail no longer
[mediawiki.git] / includes / GlobalFunctions.php
blob7508fb9f60c483a57dd89fce637b2328de49c7bb
1 <?php
2 # Global functions used everywhere
3 # $Id$
5 $wgNumberOfArticles = -1; # Unset
6 $wgTotalViews = -1;
7 $wgTotalEdits = -1;
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 );
29 return $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 ) {
43 return
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' ) {
52 static $trans;
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;
75 mt_srand( $seed );
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 );
89 if ( '' == $a ) {
90 if( '' == $q ) {
91 $a = $wgScript;
92 } else {
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
100 $a = "/{$a}?{$q}";
102 return $a;
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 );
152 return $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
177 return $string;
180 # Converts a single UTF-8 character into the corresponding HTML character entity
181 function wfUtf8Entity( $matches ) {
182 $char = $matches[0];
183 # Find the length
184 $z = ord( $char{0} );
185 if ( $z & 0x80 ) {
186 $length = 0;
187 while ( $z & 0x80 ) {
188 $length++;
189 $z <<= 1;
191 } else {
192 $length = 1;
195 if ( $length != strlen( $char ) ) {
196 return '';
198 if ( $length == 1 ) {
199 return $char;
202 # Mask off the length-determining bits and shift back to the original location
203 $z &= 0xff;
204 $z >>= $length;
206 # Add in the free bits from subsequent bytes
207 for ( $i=1; $i<$length; $i++ ) {
208 $z <<= 6;
209 $z |= ord( $char{$i} ) & 0x3f;
212 # Make entity
213 return "&#$z;";
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 ) {
227 return;
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;
251 $now = wfTime();
253 list( $usec, $sec ) = explode( " ", $wgRequestTime );
254 $start = (float)$sec + (float)$usec;
255 $elapsed = $now - $start;
256 if ( $wgProfiling ) {
257 $prof = wfGetProfilingOutput( $start, $elapsed );
258 $forward = '';
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'];
265 if( $forward )
266 $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
267 if($wgUser->getId() == 0)
268 $forward .= ' anon';
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 global $wgRequest;
292 if ( $wgRequest->getVal( 'debugmsg' ) )
294 if ( $key == 'linktrail' /* a special case where we want to return something specific */ )
295 return "/^()(.*)$/sD";
296 else
297 return $key;
299 $args = func_get_args();
300 if ( count( $args ) ) {
301 array_shift( $args );
303 return wfMsgReal( $key, $args, true );
306 # Get a message from the language file
307 function wfMsgNoDB( $key ) {
308 $args = func_get_args();
309 if ( count( $args ) ) {
310 array_shift( $args );
312 return wfMsgReal( $key, $args, false );
315 # Really get a message
316 function wfMsgReal( $key, $args, $useDB ) {
317 global $wgReplacementKeys, $wgMessageCache, $wgLang;
319 $fname = 'wfMsg';
320 wfProfileIn( $fname );
321 if ( $wgMessageCache ) {
322 $message = $wgMessageCache->get( $key, $useDB );
323 } elseif ( $wgLang ) {
324 $message = $wgLang->getMessage( $key );
325 } else {
326 wfDebug( "No language object when getting $key\n" );
327 $message = "&lt;$key&gt;";
330 # Replace arguments
331 if( count( $args ) ) {
332 $message = str_replace( $wgReplacementKeys, $args, $message );
334 wfProfileOut( $fname );
335 return $message;
338 function wfCleanFormFields( $fields )
340 wfDebugDieBacktrace( 'Call to obsolete wfCleanFormFields(). Use wgRequest instead...' );
343 function wfMungeQuotes( $in )
345 $out = str_replace( '%', '%25', $in );
346 $out = str_replace( "'", '%27', $out );
347 $out = str_replace( '"', '%22', $out );
348 return $out;
351 function wfDemungeQuotes( $in )
353 $out = str_replace( '%22', '"', $in );
354 $out = str_replace( '%27', "'", $out );
355 $out = str_replace( '%25', '%', $out );
356 return $out;
359 function wfCleanQueryVar( $var )
361 wfDebugDieBacktrace( 'Call to obsolete function wfCleanQueryVar(); use wgRequest instead' );
364 function wfSearch( $s )
366 $se = new SearchEngine( $s );
367 $se->showResults();
370 function wfGo( $s )
371 { # pick the nearest match
372 $se = new SearchEngine( $s );
373 $se->goResult();
376 # Just like exit() but makes a note of it.
377 # Commits open transactions except if the error parameter is set
378 function wfAbruptExit( $error = false ){
379 global $wgLoadBalancer;
380 static $called = false;
381 if ( $called ){
382 exit();
384 $called = true;
386 if( function_exists( 'debug_backtrace' ) ){ // PHP >= 4.3
387 $bt = debug_backtrace();
388 for($i = 0; $i < count($bt) ; $i++){
389 $file = $bt[$i]['file'];
390 $line = $bt[$i]['line'];
391 wfDebug("WARNING: Abrupt exit in $file at line $line\n");
393 } else {
394 wfDebug('WARNING: Abrupt exit\n');
396 if ( !$error ) {
397 $wgLoadBalancer->closeAll();
399 exit();
402 function wfErrorExit() {
403 wfAbruptExit( true );
406 function wfDebugDieBacktrace( $msg = '' ) {
407 global $wgCommandLineMode;
409 if ( function_exists( 'debug_backtrace' ) ) {
410 if ( $wgCommandLineMode ) {
411 $msg .= "\nBacktrace:\n";
412 } else {
413 $msg .= "\n<p>Backtrace:</p>\n<ul>\n";
415 $backtrace = debug_backtrace();
416 foreach( $backtrace as $call ) {
417 $f = explode( DIRECTORY_SEPARATOR, $call['file'] );
418 $file = $f[count($f)-1];
419 if ( $wgCommandLineMode ) {
420 $msg .= "$file line {$call['line']} calls ";
421 } else {
422 $msg .= '<li>' . $file . " line " . $call['line'] . ' calls ';
424 if( !empty( $call['class'] ) ) $msg .= $call['class'] . '::';
425 $msg .= $call['function'] . "()";
427 if ( $wgCommandLineMode ) {
428 $msg .= "\n";
429 } else {
430 $msg .= "</li>\n";
434 die( $msg );
437 function wfNumberOfArticles()
439 global $wgNumberOfArticles;
441 wfLoadSiteStats();
442 return $wgNumberOfArticles;
445 /* private */ function wfLoadSiteStats()
447 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
448 $fname = 'wfLoadSiteStats';
450 if ( -1 != $wgNumberOfArticles ) return;
451 $dbr =& wfGetDB( DB_SLAVE );
452 $s = $dbr->getArray( 'site_stats',
453 array( 'ss_total_views', 'ss_total_edits', 'ss_good_articles' ),
454 array( 'ss_row_id' => 1 ), $fname
457 if ( $s === false ) {
458 return;
459 } else {
460 $wgTotalViews = $s->ss_total_views;
461 $wgTotalEdits = $s->ss_total_edits;
462 $wgNumberOfArticles = $s->ss_good_articles;
466 function wfEscapeHTML( $in )
468 return str_replace(
469 array( '&', '"', '>', '<' ),
470 array( '&amp;', '&quot;', '&gt;', '&lt;' ),
471 $in );
474 function wfEscapeHTMLTagsOnly( $in ) {
475 return str_replace(
476 array( '"', '>', '<' ),
477 array( '&quot;', '&gt;', '&lt;' ),
478 $in );
481 function wfUnescapeHTML( $in )
483 $in = str_replace( '&lt;', '<', $in );
484 $in = str_replace( '&gt;', '>', $in );
485 $in = str_replace( '&quot;', '"', $in );
486 $in = str_replace( '&amp;', '&', $in );
487 return $in;
490 function wfImageDir( $fname )
492 global $wgUploadDirectory;
494 $hash = md5( $fname );
495 $oldumask = umask(0);
496 $dest = $wgUploadDirectory . '/' . $hash{0};
497 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
498 $dest .= '/' . substr( $hash, 0, 2 );
499 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
501 umask( $oldumask );
502 return $dest;
505 function wfImageThumbDir( $fname , $subdir='thumb')
507 return wfImageArchiveDir( $fname, $subdir );
510 function wfImageArchiveDir( $fname , $subdir='archive')
512 global $wgUploadDirectory;
514 $hash = md5( $fname );
515 $oldumask = umask(0);
517 # Suppress warning messages here; if the file itself can't
518 # be written we'll worry about it then.
519 $archive = "{$wgUploadDirectory}/{$subdir}";
520 if ( ! is_dir( $archive ) ) { @mkdir( $archive, 0777 ); }
521 $archive .= '/' . $hash{0};
522 if ( ! is_dir( $archive ) ) { @mkdir( $archive, 0777 ); }
523 $archive .= '/' . substr( $hash, 0, 2 );
524 if ( ! is_dir( $archive ) ) { @mkdir( $archive, 0777 ); }
526 umask( $oldumask );
527 return $archive;
530 function wfRecordUpload( $name, $oldver, $size, $desc, $copyStatus = "", $source = "" )
532 global $wgUser, $wgLang, $wgTitle, $wgOut, $wgDeferredUpdateList;
533 global $wgUseCopyrightUpload;
535 $fname = 'wfRecordUpload';
536 $dbw =& wfGetDB( DB_MASTER );
538 # img_name must be unique
539 if ( !$dbw->indexUnique( 'image', 'img_name' ) ) {
540 wfDebugDieBacktrace( 'Database schema not up to date, please run maintenance/archives/patch-image_name_unique.sql' );
544 $now = wfTimestampNow();
545 $won = wfInvertTimestamp( $now );
546 $size = IntVal( $size );
548 if ( $wgUseCopyrightUpload )
550 $textdesc = '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $desc . "\n" .
551 '== ' . wfMsg ( 'filestatus' ) . " ==\n" . $copyStatus . "\n" .
552 '== ' . wfMsg ( 'filesource' ) . " ==\n" . $source ;
554 else $textdesc = $desc ;
556 $now = wfTimestampNow();
557 $won = wfInvertTimestamp( $now );
559 # Test to see if the row exists using INSERT IGNORE
560 # This avoids race conditions by locking the row until the commit, and also
561 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
562 $dbw->insert( 'image',
563 array(
564 'img_name' => $name,
565 'img_size'=> $size,
566 'img_timestamp' => $now,
567 'img_description' => $desc,
568 'img_user' => $wgUser->getID(),
569 'img_user_text' => $wgUser->getName(),
570 ), $fname, 'IGNORE'
572 $descTitle = Title::makeTitle( NS_IMAGE, $name );
574 if ( $dbw->affectedRows() ) {
575 # Successfully inserted, this is a new image
576 $id = $descTitle->getArticleID();
578 if ( $id == 0 ) {
579 $seqVal = $dbw->nextSequenceValue( 'cur_cur_id_seq' );
580 $dbw->insertArray( 'cur',
581 array(
582 'cur_id' => $seqVal,
583 'cur_namespace' => NS_IMAGE,
584 'cur_title' => $name,
585 'cur_comment' => $desc,
586 'cur_user' => $wgUser->getID(),
587 'cur_user_text' => $wgUser->getName(),
588 'cur_timestamp' => $now,
589 'cur_is_new' => 1,
590 'cur_text' => $textdesc,
591 'inverse_timestamp' => $won,
592 'cur_touched' => $now
593 ), $fname
595 $id = $dbw->insertId() or 0; # We should throw an error instead
597 RecentChange::notifyNew( $now, $descTitle, 0, $wgUser, $desc );
599 $u = new SearchUpdate( $id, $name, $desc );
600 $u->doUpdate();
602 } else {
603 # Collision, this is an update of an image
604 # Get current image row for update
605 $s = $dbw->getArray( 'image', array( 'img_name','img_size','img_timestamp','img_description',
606 'img_user','img_user_text' ), array( 'img_name' => $name ), $fname, 'FOR UPDATE' );
608 # Insert it into oldimage
609 $dbw->insertArray( 'oldimage',
610 array(
611 'oi_name' => $s->img_name,
612 'oi_archive_name' => $oldver,
613 'oi_size' => $s->img_size,
614 'oi_timestamp' => $s->img_timestamp,
615 'oi_description' => $s->img_description,
616 'oi_user' => $s->img_user,
617 'oi_user_text' => $s->img_user_text
618 ), $fname
621 # Update the current image row
622 $dbw->updateArray( 'image',
623 array( /* SET */
624 'img_size' => $size,
625 'img_timestamp' => wfTimestampNow(),
626 'img_user' => $wgUser->getID(),
627 'img_user_text' => $wgUser->getName(),
628 'img_description' => $desc,
629 ), array( /* WHERE */
630 'img_name' => $name
631 ), $fname
634 # Invalidate the cache for the description page
635 $descTitle->invalidateCache();
638 $log = new LogPage( wfMsg( 'uploadlogpage' ), wfMsg( 'uploadlogpagetext' ) );
639 $da = wfMsg( 'uploadedimage', '[[:' . $wgLang->getNsText(
640 Namespace::getImage() ) . ":{$name}|{$name}]]" );
641 $ta = wfMsg( 'uploadedimage', $name );
642 $log->addEntry( $da, $desc, $ta );
646 /* Some generic result counters, pulled out of SearchEngine */
648 function wfShowingResults( $offset, $limit )
650 global $wgLang;
651 return wfMsg( 'showingresults', $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+1 ) );
654 function wfShowingResultsNum( $offset, $limit, $num )
656 global $wgLang;
657 return wfMsg( 'showingresultsnum', $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+1 ), $wgLang->formatNum( $num ) );
660 function wfViewPrevNext( $offset, $limit, $link, $query = '', $atend = false )
662 global $wgUser, $wgLang;
663 $fmtLimit = $wgLang->formatNum( $limit );
664 $prev = wfMsg( 'prevn', $fmtLimit );
665 $next = wfMsg( 'nextn', $fmtLimit );
666 $link = wfUrlencode( $link );
668 $sk = $wgUser->getSkin();
669 if ( 0 != $offset ) {
670 $po = $offset - $limit;
671 if ( $po < 0 ) { $po = 0; }
672 $q = "limit={$limit}&offset={$po}";
673 if ( '' != $query ) { $q .= "&{$query}"; }
674 $plink = '<a href="' . wfLocalUrlE( $link, $q ) . "\">{$prev}</a>";
675 } else { $plink = $prev; }
677 $no = $offset + $limit;
678 $q = "limit={$limit}&offset={$no}";
679 if ( "" != $query ) { $q .= "&{$query}"; }
681 if ( $atend ) {
682 $nlink = $next;
683 } else {
684 $nlink = '<a href="' . wfLocalUrlE( $link, $q ) . "\">{$next}</a>";
686 $nums = wfNumLink( $offset, 20, $link , $query ) . ' | ' .
687 wfNumLink( $offset, 50, $link, $query ) . ' | ' .
688 wfNumLink( $offset, 100, $link, $query ) . ' | ' .
689 wfNumLink( $offset, 250, $link, $query ) . ' | ' .
690 wfNumLink( $offset, 500, $link, $query );
692 return wfMsg( 'viewprevnext', $plink, $nlink, $nums );
695 function wfNumLink( $offset, $limit, $link, $query = '' )
697 global $wgUser, $wgLang;
698 if ( '' == $query ) { $q = ''; }
699 else { $q = "{$query}&"; }
700 $q .= "limit={$limit}&offset={$offset}";
702 $fmtLimit = $wgLang->formatNum( $limit );
703 $s = '<a href="' . wfLocalUrlE( $link, $q ) . "\">{$fmtLimit}</a>";
704 return $s;
707 function wfClientAcceptsGzip() {
708 global $wgUseGzip;
709 if( $wgUseGzip ) {
710 # FIXME: we may want to blacklist some broken browsers
711 if( preg_match(
712 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
713 $_SERVER['HTTP_ACCEPT_ENCODING'],
714 $m ) ) {
715 if( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) return false;
716 wfDebug( " accepts gzip\n" );
717 return true;
720 return false;
723 # Yay, more global functions!
724 function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) {
725 global $wgUser, $wgRequest;
727 $limit = $wgRequest->getInt( 'limit', 0 );
728 if( $limit < 0 ) $limit = 0;
729 if( ( $limit == 0 ) && ( $optionname != '' ) ) {
730 $limit = (int)$wgUser->getOption( $optionname );
732 if( $limit <= 0 ) $limit = $deflimit;
733 if( $limit > 5000 ) $limit = 5000; # We have *some* limits...
735 $offset = $wgRequest->getInt( 'offset', 0 );
736 if( $offset < 0 ) $offset = 0;
738 return array( $limit, $offset );
741 # Escapes the given text so that it may be output using addWikiText()
742 # without any linking, formatting, etc. making its way through. This
743 # is achieved by substituting certain characters with HTML entities.
744 # As required by the callers, <nowiki> is not used. It currently does
745 # not filter out characters which have special meaning only at the
746 # start of a line, such as "*".
747 function wfEscapeWikiText( $text )
749 $text = str_replace(
750 array( '[', '|', "'", 'ISBN ' , '://' , "\n=" ),
751 array( '&#91;', '&#124;', '&#39;', 'ISBN&#32;', '&#58;//' , "\n&#61;" ),
752 htmlspecialchars($text) );
753 return $text;
756 function wfQuotedPrintable( $string, $charset = '' )
758 # Probably incomplete; see RFC 2045
759 if( empty( $charset ) ) {
760 global $wgInputEncoding;
761 $charset = $wgInputEncoding;
763 $charset = strtoupper( $charset );
764 $charset = str_replace( 'ISO-8859', 'ISO8859', $charset ); // ?
766 $illegal = '\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\xff=';
767 $replace = $illegal . '\t ?_';
768 if( !preg_match( "/[$illegal]/", $string ) ) return $string;
769 $out = "=?$charset?Q?";
770 $out .= preg_replace( "/([$replace])/e", 'sprintf("=%02X",ord("$1"))', $string );
771 $out .= '?=';
772 return $out;
775 function wfTime(){
776 $st = explode( ' ', microtime() );
777 return (float)$st[0] + (float)$st[1];
780 # Changes the first character to an HTML entity
781 function wfHtmlEscapeFirst( $text ) {
782 $ord = ord($text);
783 $newText = substr($text, 1);
784 return "&#$ord;$newText";
787 # Sets dest to source and returns the original value of dest
788 # If source is NULL, it just returns the value, it doesn't set the variable
789 function wfSetVar( &$dest, $source )
791 $temp = $dest;
792 if ( !is_null( $source ) ) {
793 $dest = $source;
795 return $temp;
798 # As for wfSetVar except setting a bit
799 function wfSetBit( &$dest, $bit, $state = true ) {
800 $temp = (bool)($dest & $bit );
801 if ( !is_null( $state ) ) {
802 if ( $state ) {
803 $dest |= $bit;
804 } else {
805 $dest &= ~$bit;
808 return $temp;
811 # This function takes two arrays as input, and returns a CGI-style string, e.g.
812 # "days=7&limit=100". Options in the first array override options in the second.
813 # Options set to "" will not be output.
814 function wfArrayToCGI( $array1, $array2 = NULL )
816 if ( !is_null( $array2 ) ) {
817 $array1 = $array1 + $array2;
820 $cgi = '';
821 foreach ( $array1 as $key => $value ) {
822 if ( '' !== $value ) {
823 if ( '' != $cgi ) {
824 $cgi .= '&';
826 $cgi .= "{$key}={$value}";
829 return $cgi;
832 # This is obsolete, use SquidUpdate::purge()
833 function wfPurgeSquidServers ($urlArr) {
834 SquidUpdate::purge( $urlArr );
837 # Windows-compatible version of escapeshellarg()
838 function wfEscapeShellArg( )
840 $args = func_get_args();
841 $first = true;
842 $retVal = '';
843 foreach ( $args as $arg ) {
844 if ( !$first ) {
845 $retVal .= ' ';
846 } else {
847 $first = false;
850 if ( wfIsWindows() ) {
851 $retVal .= '"' . str_replace( '"','\"', $arg ) . '"';
852 } else {
853 $retVal .= escapeshellarg( $arg );
856 return $retVal;
859 # wfMerge attempts to merge differences between three texts.
860 # Returns true for a clean merge and false for failure or a conflict.
862 function wfMerge( $old, $mine, $yours, &$result ){
863 global $wgDiff3;
865 # This check may also protect against code injection in
866 # case of broken installations.
867 if(! file_exists( $wgDiff3 ) ){
868 return false;
871 # Make temporary files
872 $td = '/tmp/';
873 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
874 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
875 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
877 fwrite( $oldtextFile, $old ); fclose( $oldtextFile );
878 fwrite( $mytextFile, $mine ); fclose( $mytextFile );
879 fwrite( $yourtextFile, $yours ); fclose( $yourtextFile );
881 # Check for a conflict
882 $cmd = wfEscapeShellArg( $wgDiff3 ) . ' -a --overlap-only ' .
883 wfEscapeShellArg( $mytextName ) . ' ' .
884 wfEscapeShellArg( $oldtextName ) . ' ' .
885 wfEscapeShellArg( $yourtextName );
886 $handle = popen( $cmd, 'r' );
888 if( fgets( $handle ) ){
889 $conflict = true;
890 } else {
891 $conflict = false;
893 pclose( $handle );
895 # Merge differences
896 $cmd = wfEscapeShellArg( $wgDiff3 ) . ' -a -e --merge ' .
897 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
898 $handle = popen( $cmd, 'r' );
899 $result = '';
900 do {
901 $data = fread( $handle, 8192 );
902 if ( strlen( $data ) == 0 ) {
903 break;
905 $result .= $data;
906 } while ( true );
907 pclose( $handle );
908 unlink( $mytextName ); unlink( $oldtextName ); unlink( $yourtextName );
909 return ! $conflict;
912 function wfVarDump( $var )
914 global $wgOut;
915 $s = str_replace("\n","<br>\n", var_export( $var, true ) . "\n");
916 if ( headers_sent() || !@is_object( $wgOut ) ) {
917 print $s;
918 } else {
919 $wgOut->addHTML( $s );
923 # Provide a simple HTTP error.
924 function wfHttpError( $code, $label, $desc ) {
925 global $wgOut;
926 $wgOut->disable();
927 header( "HTTP/1.0 $code $label" );
928 header( "Status: $code $label" );
929 $wgOut->sendCacheControl();
931 # Don't send content if it's a HEAD request.
932 if( $_SERVER['REQUEST_METHOD'] == 'HEAD' ) {
933 header( 'Content-type: text/plain' );
934 print "$desc\n";
938 # Converts an Accept-* header into an array mapping string values to quality factors
939 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
940 # No arg means accept anything (per HTTP spec)
941 if( !$accept ) {
942 return array( $def => 1 );
945 $prefs = array();
947 $parts = explode( ',', $accept );
949 foreach( $parts as $part ) {
950 # FIXME: doesn't deal with params like 'text/html; level=1'
951 @list( $value, $qpart ) = explode( ';', $part );
952 if( !isset( $qpart ) ) {
953 $prefs[$value] = 1;
954 } elseif( preg_match( '/q\s*=\s*(\d*\.\d+)/', $qpart, $match ) ) {
955 $prefs[$value] = $match[1];
959 return $prefs;
962 /* private */ function mimeTypeMatch( $type, $avail ) {
963 if( array_key_exists($type, $avail) ) {
964 return $type;
965 } else {
966 $parts = explode( '/', $type );
967 if( array_key_exists( $parts[0] . '/*', $avail ) ) {
968 return $parts[0] . '/*';
969 } elseif( array_key_exists( '*/*', $avail ) ) {
970 return '*/*';
971 } else {
972 return NULL;
977 # FIXME: doesn't handle params like 'text/plain; charset=UTF-8'
978 # XXX: generalize to negotiate other stuff
979 function wfNegotiateType( $cprefs, $sprefs ) {
980 $combine = array();
982 foreach( array_keys($sprefs) as $type ) {
983 $parts = explode( '/', $type );
984 if( $parts[1] != '*' ) {
985 $ckey = mimeTypeMatch( $type, $cprefs );
986 if( $ckey ) {
987 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
992 foreach( array_keys( $cprefs ) as $type ) {
993 $parts = explode( '/', $type );
994 if( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
995 $skey = mimeTypeMatch( $type, $sprefs );
996 if( $skey ) {
997 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1002 $bestq = 0;
1003 $besttype = NULL;
1005 foreach( array_keys( $combine ) as $type ) {
1006 if( $combine[$type] > $bestq ) {
1007 $besttype = $type;
1008 $bestq = $combine[$type];
1012 return $besttype;
1015 # Array lookup
1016 # Returns an array where the values in the first array are replaced by the
1017 # values in the second array with the corresponding keys
1018 function wfArrayLookup( $a, $b )
1020 return array_flip( array_intersect( array_flip( $a ), array_keys( $b ) ) );
1023 # Since Windows is so different to any of the other popular OSes, it seems appropriate
1024 # to have a simple way to test for its presence
1025 function wfIsWindows() {
1026 if (substr(php_uname(), 0, 7) == 'Windows') {
1027 return true;
1028 } else {
1029 return false;
1034 # Ideally we'd be using actual time fields in the db
1035 function wfTimestamp2Unix( $ts ) {
1036 return gmmktime( ( (int)substr( $ts, 8, 2) ),
1037 (int)substr( $ts, 10, 2 ), (int)substr( $ts, 12, 2 ),
1038 (int)substr( $ts, 4, 2 ), (int)substr( $ts, 6, 2 ),
1039 (int)substr( $ts, 0, 4 ) );
1042 function wfUnix2Timestamp( $unixtime ) {
1043 return gmdate( "YmdHis", $unixtime );
1046 function wfTimestampNow() {
1047 # return NOW
1048 return gmdate( "YmdHis" );
1051 # Sorting hack for MySQL 3, which doesn't use index sorts for DESC
1052 function wfInvertTimestamp( $ts ) {
1053 return strtr(
1054 $ts,
1055 "0123456789",
1056 "9876543210"
1060 # Reference-counted warning suppression
1061 function wfSuppressWarnings( $end = false ) {
1062 static $suppressCount = 0;
1063 static $originalLevel = false;
1065 if ( $end ) {
1066 if ( $suppressCount ) {
1067 $suppressCount --;
1068 if ( !$suppressCount ) {
1069 error_reporting( $originalLevel );
1072 } else {
1073 if ( !$suppressCount ) {
1074 $originalLevel = error_reporting( E_ALL & ~( E_WARNING | E_NOTICE ) );
1076 $suppressCount++;
1080 # Restore error level to previous value
1081 function wfRestoreWarnings() {
1082 wfSuppressWarnings( true );
1085 # Autodetect, convert and provide timestamps of various types
1086 define("TS_UNIX",0); # Standard unix timestamp (number of seconds since 1 Jan 1970)
1087 define("TS_MW",1); # Mediawiki concatenated string timestamp (yyyymmddhhmmss)
1088 define("TS_DB",2); # Standard database timestamp (yyyy-mm-dd hh:mm:ss)
1090 function wfTimestamp($outputtype=TS_UNIX,$ts=0) {
1091 if (preg_match("/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)$/",$ts,$da)) {
1092 # TS_DB
1093 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1094 (int)$da[2],(int)$da[3],(int)$da[1]);
1095 } elseif (preg_match("/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/",$ts,$da)) {
1096 # TS_MW
1097 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1098 (int)$da[2],(int)$da[3],(int)$da[1]);
1099 } elseif (preg_match("/^(\d{1,13})$/",$ts,$datearray)) {
1100 # TS_UNIX
1101 $uts=$ts;
1104 if ($ts==0)
1105 $uts=time();
1106 switch($outputtype) {
1107 case TS_UNIX:
1108 return $uts;
1109 break;
1110 case TS_MW:
1111 return gmdate( "YmdHis", $uts );
1112 break;
1113 case TS_DB:
1114 return gmdate( "Y-m-d H:i:s", $uts );
1115 break;
1116 default:
1117 return;