Made strong/em handling more forgiving against unbalanced ticks
[mediawiki.git] / includes / GlobalFunctions.php
blob00ab811cc8d6986e08fac3bfad23ef86eff3d37a
1 <?php
2 # Global functions used everywhere
4 $wgNumberOfArticles = -1; # Unset
5 $wgTotalViews = -1;
6 $wgTotalEdits = -1;
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 );
28 return $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 ) {
42 return
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" ) {
51 static $trans;
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;
72 mt_srand( $seed );
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 );
86 if ( "" == $a ) {
87 if( "" == $q ) {
88 $a = $wgScript;
89 } else {
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 ugly hack for toplevel wikis
97 $a = "/{$a}&{$q}";
99 return $a;
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 );
149 return $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 function wfMungeToUtf8($string) {
168 global $wgInputEncoding; # This is debatable
169 #$string = iconv($wgInputEncoding, "UTF-8", $string);
170 $string = preg_replace ( '/&#([0-9]+);/e', 'wfUtf8Sequence($1)', $string );
171 $string = preg_replace ( '/&#x([0-9a-f]+);/ie', 'wfUtf8Sequence(0x$1)', $string );
172 # Should also do named entities here
173 return $string;
176 # Converts a single UTF-8 character into the corresponding HTML character entity
177 function wfUtf8Entity( $char ) {
178 # Find the length
179 $z = ord( $char{0} );
180 if ( $z & 0x80 ) {
181 $length = 0;
182 while ( $z & 0x80 ) {
183 $length++;
184 $z <<= 1;
186 } else {
187 $length = 1;
190 if ( $length != strlen( $char ) ) {
191 return "";
193 if ( $length == 1 ) {
194 return $char;
197 # Mask off the length-determining bits and shift back to the original location
198 $z &= 0xff;
199 $z >>= $length;
201 # Add in the free bits from subsequent bytes
202 for ( $i=1; $i<$length; $i++ ) {
203 $z <<= 6;
204 $z |= ord( $char{$i} ) & 0x3f;
207 # Make entity
208 return "&#$z;";
211 # Converts all multi-byte characters in a UTF-8 string into the appropriate character entity
212 function wfUtf8ToHTML($string) {
213 return preg_replace_callback( '/[\\xc0-\\xfd][\\x80-\\xbf]*/', 'wfUtf8Entity', $string );
216 function wfDebug( $text, $logonly = false )
218 global $wgOut, $wgDebugLogFile, $wgDebugComments, $wgProfileOnly;
220 if ( isset( $wgOut ) && $wgDebugComments && !$logonly ) {
221 $wgOut->debug( $text );
223 if ( "" != $wgDebugLogFile && !$wgProfileOnly ) {
224 error_log( $text, 3, $wgDebugLogFile );
228 function logProfilingData()
230 global $wgRequestTime, $wgDebugLogFile;
231 global $wgProfiling, $wgProfileStack, $wgProfileLimit, $wgUser;
232 $now = wfTime();
234 list( $usec, $sec ) = explode( " ", $wgRequestTime );
235 $start = (float)$sec + (float)$usec;
236 $elapsed = $now - $start;
237 if ( "" != $wgDebugLogFile ) {
238 $prof = wfGetProfilingOutput( $start, $elapsed );
239 $forward = "";
240 if( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) )
241 $forward = " forwarded for " . $_SERVER['HTTP_X_FORWARDED_FOR'];
242 if( !empty( $_SERVER['HTTP_CLIENT_IP'] ) )
243 $forward .= " client IP " . $_SERVER['HTTP_CLIENT_IP'];
244 if( !empty( $_SERVER['HTTP_FROM'] ) )
245 $forward .= " from " . $_SERVER['HTTP_FROM'];
246 if( $forward )
247 $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
248 if($wgUser->getId() == 0)
249 $forward .= " anon";
250 $log = sprintf( "%s\t%04.3f\t%s\n",
251 gmdate( "YmdHis" ), $elapsed,
252 urldecode( $_SERVER['REQUEST_URI'] . $forward ) );
253 error_log( $log . $prof, 3, $wgDebugLogFile );
258 function wfReadOnly()
260 global $wgReadOnlyFile;
262 if ( "" == $wgReadOnlyFile ) { return false; }
263 return is_file( $wgReadOnlyFile );
266 $wgReplacementKeys = array( "$1", "$2", "$3", "$4", "$5", "$6", "$7", "$8", "$9" );
268 # Get a message from anywhere
269 function wfMsg( $key ) {
270 $args = func_get_args();
271 if ( count( $args ) ) {
272 array_shift( $args );
274 return wfMsgReal( $key, $args, true );
277 # Get a message from the language file
278 function wfMsgNoDB( $key ) {
279 $args = func_get_args();
280 if ( count( $args ) ) {
281 array_shift( $args );
283 return wfMsgReal( $key, $args, false );
286 # Really get a message
287 function wfMsgReal( $key, $args, $useDB ) {
288 global $wgReplacementKeys, $wgMessageCache, $wgLang;
290 $fname = "wfMsg";
291 wfProfileIn( $fname );
292 if ( $wgMessageCache ) {
293 $message = $wgMessageCache->get( $key, $useDB );
294 } elseif ( $wgLang ) {
295 $message = $wgLang->getMessage( $key );
296 } else {
297 wfDebug( "No language object when getting $key\n" );
298 $message = "&lt;$key&gt;";
301 # Replace arguments
302 if( count( $args ) ) {
303 $message = str_replace( $wgReplacementKeys, $args, $message );
305 wfProfileOut( $fname );
306 return $message;
309 function wfCleanFormFields( $fields )
311 wfDebugDieBacktrace( "Call to obsolete wfCleanFormFields(). Use wgRequest instead..." );
314 function wfMungeQuotes( $in )
316 $out = str_replace( "%", "%25", $in );
317 $out = str_replace( "'", "%27", $out );
318 $out = str_replace( "\"", "%22", $out );
319 return $out;
322 function wfDemungeQuotes( $in )
324 $out = str_replace( "%22", "\"", $in );
325 $out = str_replace( "%27", "'", $out );
326 $out = str_replace( "%25", "%", $out );
327 return $out;
330 function wfCleanQueryVar( $var )
332 wfDebugDieBacktrace( "Call to obsolete function wfCleanQueryVar(); use wgRequest instead" );
335 function wfSpecialPage()
337 global $wgUser, $wgOut, $wgTitle, $wgLang;
339 /* FIXME: this list probably shouldn't be language-specific, per se */
340 $validSP = $wgLang->getValidSpecialPages();
341 $sysopSP = $wgLang->getSysopSpecialPages();
342 $devSP = $wgLang->getDeveloperSpecialPages();
344 $wgOut->setArticleRelated( false );
345 $wgOut->setRobotpolicy( "noindex,follow" );
347 $bits = split( "/", $wgTitle->getDBkey(), 2 );
348 $t = $bits[0];
349 if( empty( $bits[1] ) ) {
350 $par = NULL;
351 } else {
352 $par = $bits[1];
355 if ( array_key_exists( $t, $validSP ) ||
356 ( $wgUser->isSysop() && array_key_exists( $t, $sysopSP ) ) ||
357 ( $wgUser->isDeveloper() && array_key_exists( $t, $devSP ) ) ) {
358 if($par !== NULL)
359 $wgTitle = Title::makeTitle( Namespace::getSpecial(), $t );
361 $wgOut->setPageTitle( wfMsg( strtolower( $wgTitle->getText() ) ) );
363 $inc = "Special" . $t . ".php";
364 require_once( $inc );
365 $call = "wfSpecial" . $t;
366 $call( $par );
367 } else if ( array_key_exists( $t, $sysopSP ) ) {
368 $wgOut->sysopRequired();
369 } else if ( array_key_exists( $t, $devSP ) ) {
370 $wgOut->developerRequired();
371 } else {
372 $wgOut->errorpage( "nosuchspecialpage", "nospecialpagetext" );
376 function wfSearch( $s )
378 $se = new SearchEngine( $s );
379 $se->showResults();
382 function wfGo( $s )
383 { # pick the nearest match
384 $se = new SearchEngine( $s );
385 $se->goResult();
388 # Just like exit() but makes a note of it.
389 function wfAbruptExit(){
390 static $called = false;
391 if ( $called ){
392 exit();
394 $called = true;
396 if( function_exists( "debug_backtrace" ) ){ // PHP >= 4.3
397 $bt = debug_backtrace();
398 for($i = 0; $i < count($bt) ; $i++){
399 $file = $bt[$i]["file"];
400 $line = $bt[$i]["line"];
401 wfDebug("WARNING: Abrupt exit in $file at line $line\n");
403 } else {
404 wfDebug("WARNING: Abrupt exit\n");
406 exit();
409 function wfDebugDieBacktrace( $msg = "" ) {
410 $msg .= "\n<p>Backtrace:</p>\n<ul>\n";
411 $backtrace = debug_backtrace();
412 foreach( $backtrace as $call ) {
413 $f = explode( DIRECTORY_SEPARATOR, $call['file'] );
414 $file = $f[count($f)-1];
415 $msg .= "<li>" . $file . " line " . $call['line'] . ", in ";
416 if( !empty( $call['class'] ) ) $msg .= $call['class'] . "::";
417 $msg .= $call['function'] . "()</li>\n";
419 die( $msg );
422 function wfNumberOfArticles()
424 global $wgNumberOfArticles;
426 wfLoadSiteStats();
427 return $wgNumberOfArticles;
430 /* private */ function wfLoadSiteStats()
432 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
433 if ( -1 != $wgNumberOfArticles ) return;
435 $sql = "SELECT ss_total_views, ss_total_edits, ss_good_articles " .
436 "FROM site_stats WHERE ss_row_id=1";
437 $res = wfQuery( $sql, DB_READ, "wfLoadSiteStats" );
439 if ( 0 == wfNumRows( $res ) ) { return; }
440 else {
441 $s = wfFetchObject( $res );
442 $wgTotalViews = $s->ss_total_views;
443 $wgTotalEdits = $s->ss_total_edits;
444 $wgNumberOfArticles = $s->ss_good_articles;
448 function wfEscapeHTML( $in )
450 return str_replace(
451 array( "&", "\"", ">", "<" ),
452 array( "&amp;", "&quot;", "&gt;", "&lt;" ),
453 $in );
456 function wfEscapeHTMLTagsOnly( $in ) {
457 return str_replace(
458 array( "\"", ">", "<" ),
459 array( "&quot;", "&gt;", "&lt;" ),
460 $in );
463 function wfUnescapeHTML( $in )
465 $in = str_replace( "&lt;", "<", $in );
466 $in = str_replace( "&gt;", ">", $in );
467 $in = str_replace( "&quot;", "\"", $in );
468 $in = str_replace( "&amp;", "&", $in );
469 return $in;
472 function wfImageDir( $fname )
474 global $wgUploadDirectory;
476 $hash = md5( $fname );
477 $oldumask = umask(0);
478 $dest = $wgUploadDirectory . "/" . $hash{0};
479 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
480 $dest .= "/" . substr( $hash, 0, 2 );
481 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
483 umask( $oldumask );
484 return $dest;
487 function wfImageThumbDir( $fname , $subdir="thumb")
489 return wfImageArchiveDir( $fname, $subdir );
492 function wfImageArchiveDir( $fname , $subdir="archive")
494 global $wgUploadDirectory;
496 $hash = md5( $fname );
497 $oldumask = umask(0);
499 # Suppress warning messages here; if the file itself can't
500 # be written we'll worry about it then.
501 $archive = "{$wgUploadDirectory}/{$subdir}";
502 if ( ! is_dir( $archive ) ) { @mkdir( $archive, 0777 ); }
503 $archive .= "/" . $hash{0};
504 if ( ! is_dir( $archive ) ) { @mkdir( $archive, 0777 ); }
505 $archive .= "/" . substr( $hash, 0, 2 );
506 if ( ! is_dir( $archive ) ) { @mkdir( $archive, 0777 ); }
508 umask( $oldumask );
509 return $archive;
512 function wfRecordUpload( $name, $oldver, $size, $desc, $copyStatus = "", $source = "" )
514 global $wgUser, $wgLang, $wgTitle, $wgOut, $wgDeferredUpdateList;
515 global $wgUseCopyrightUpload;
517 $fname = "wfRecordUpload";
519 $sql = "SELECT img_name,img_size,img_timestamp,img_description,img_user," .
520 "img_user_text FROM image WHERE img_name='" . wfStrencode( $name ) . "'";
521 $res = wfQuery( $sql, DB_READ, $fname );
523 $now = wfTimestampNow();
524 $won = wfInvertTimestamp( $now );
525 $size = IntVal( $size );
527 if ( $wgUseCopyrightUpload )
529 $textdesc = "== " . wfMsg ( "filedesc" ) . " ==\n" . $desc . "\n" .
530 "== " . wfMsg ( "filestatus" ) . " ==\n" . $copyStatus . "\n" .
531 "== " . wfMsg ( "filesource" ) . " ==\n" . $source ;
533 else $textdesc = $desc ;
535 $now = wfTimestampNow();
536 $won = wfInvertTimestamp( $now );
538 if ( 0 == wfNumRows( $res ) ) {
539 $sql = "INSERT INTO image (img_name,img_size,img_timestamp," .
540 "img_description,img_user,img_user_text) VALUES ('" .
541 wfStrencode( $name ) . "',$size,'{$now}','" .
542 wfStrencode( $desc ) . "', '" . $wgUser->getID() .
543 "', '" . wfStrencode( $wgUser->getName() ) . "')";
544 wfQuery( $sql, DB_WRITE, $fname );
546 $sql = "SELECT cur_id,cur_text FROM cur WHERE cur_namespace=" .
547 Namespace::getImage() . " AND cur_title='" .
548 wfStrencode( $name ) . "'";
549 $res = wfQuery( $sql, DB_READ, $fname );
550 if ( 0 == wfNumRows( $res ) ) {
551 $common =
552 Namespace::getImage() . ",'" .
553 wfStrencode( $name ) . "','" .
554 wfStrencode( $desc ) . "','" . $wgUser->getID() . "','" .
555 wfStrencode( $wgUser->getName() ) . "','" . $now .
556 "',1";
557 $sql = "INSERT INTO cur (cur_namespace,cur_title," .
558 "cur_comment,cur_user,cur_user_text,cur_timestamp,cur_is_new," .
559 "cur_text,inverse_timestamp,cur_touched) VALUES (" .
560 $common .
561 ",'" . wfStrencode( $textdesc ) . "','{$won}','{$now}')";
562 wfQuery( $sql, DB_WRITE, $fname );
563 $id = wfInsertId() or 0; # We should throw an error instead
565 $titleObj = Title::makeTitle( NS_IMAGE, $name );
566 RecentChange::notifyNew( $now, $titleObj, 0, $wgUser, $desc );
568 $u = new SearchUpdate( $id, $name, $desc );
569 $u->doUpdate();
571 } else {
572 $s = wfFetchObject( $res );
574 $sql = "INSERT INTO oldimage (oi_name,oi_archive_name,oi_size," .
575 "oi_timestamp,oi_description,oi_user,oi_user_text) VALUES ('" .
576 wfStrencode( $s->img_name ) . "','" .
577 wfStrencode( $oldver ) .
578 "',{$s->img_size},'{$s->img_timestamp}','" .
579 wfStrencode( $s->img_description ) . "','" .
580 wfStrencode( $s->img_user ) . "','" .
581 wfStrencode( $s->img_user_text) . "')";
582 wfQuery( $sql, DB_WRITE, $fname );
584 $sql = "UPDATE image SET img_size={$size}," .
585 "img_timestamp='" . wfTimestampNow() . "',img_user='" .
586 $wgUser->getID() . "',img_user_text='" .
587 wfStrencode( $wgUser->getName() ) . "', img_description='" .
588 wfStrencode( $desc ) . "' WHERE img_name='" .
589 wfStrencode( $name ) . "'";
590 wfQuery( $sql, DB_WRITE, $fname );
592 $sql = "UPDATE cur SET cur_touched='{$now}' WHERE cur_namespace=" .
593 Namespace::getImage() . " AND cur_title='" .
594 wfStrencode( $name ) . "'";
595 wfQuery( $sql, DB_WRITE, $fname );
598 $log = new LogPage( wfMsg( "uploadlogpage" ), wfMsg( "uploadlogpagetext" ) );
599 $da = wfMsg( "uploadedimage", "[[:" . $wgLang->getNsText(
600 Namespace::getImage() ) . ":{$name}|{$name}]]" );
601 $ta = wfMsg( "uploadedimage", $name );
602 $log->addEntry( $da, $desc, $ta );
606 /* Some generic result counters, pulled out of SearchEngine */
608 function wfShowingResults( $offset, $limit )
610 global $wgLang;
611 return wfMsg( "showingresults", $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+1 ) );
614 function wfShowingResultsNum( $offset, $limit, $num )
616 global $wgLang;
617 return wfMsg( "showingresultsnum", $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+1 ), $wgLang->formatNum( $num ) );
620 function wfViewPrevNext( $offset, $limit, $link, $query = "", $atend = false )
622 global $wgUser, $wgLang;
623 $fmtLimit = $wgLang->formatNum( $limit );
624 $prev = wfMsg( "prevn", $fmtLimit );
625 $next = wfMsg( "nextn", $fmtLimit );
626 $link = wfUrlencode( $link );
628 $sk = $wgUser->getSkin();
629 if ( 0 != $offset ) {
630 $po = $offset - $limit;
631 if ( $po < 0 ) { $po = 0; }
632 $q = "limit={$limit}&offset={$po}";
633 if ( "" != $query ) { $q .= "&{$query}"; }
634 $plink = "<a href=\"" . wfLocalUrlE( $link, $q ) . "\">{$prev}</a>";
635 } else { $plink = $prev; }
637 $no = $offset + $limit;
638 $q = "limit={$limit}&offset={$no}";
639 if ( "" != $query ) { $q .= "&{$query}"; }
641 if ( $atend ) {
642 $nlink = $next;
643 } else {
644 $nlink = "<a href=\"" . wfLocalUrlE( $link, $q ) . "\">{$next}</a>";
646 $nums = wfNumLink( $offset, 20, $link , $query ) . " | " .
647 wfNumLink( $offset, 50, $link, $query ) . " | " .
648 wfNumLink( $offset, 100, $link, $query ) . " | " .
649 wfNumLink( $offset, 250, $link, $query ) . " | " .
650 wfNumLink( $offset, 500, $link, $query );
652 return wfMsg( "viewprevnext", $plink, $nlink, $nums );
655 function wfNumLink( $offset, $limit, $link, $query = "" )
657 global $wgUser, $wgLang;
658 if ( "" == $query ) { $q = ""; }
659 else { $q = "{$query}&"; }
660 $q .= "limit={$limit}&offset={$offset}";
662 $fmtLimit = $wgLang->formatNum( $limit );
663 $s = "<a href=\"" . wfLocalUrlE( $link, $q ) . "\">{$fmtLimit}</a>";
664 return $s;
667 function wfClientAcceptsGzip() {
668 global $wgUseGzip;
669 if( $wgUseGzip ) {
670 # FIXME: we may want to blacklist some broken browsers
671 if( preg_match(
672 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
673 $_SERVER["HTTP_ACCEPT_ENCODING"],
674 $m ) ) {
675 if( ( $m[1] == "q" ) && ( $m[2] == 0 ) ) return false;
676 wfDebug( " accepts gzip\n" );
677 return true;
680 return false;
683 # Yay, more global functions!
684 function wfCheckLimits( $deflimit = 50, $optionname = "rclimit" ) {
685 global $wgUser, $wgRequest;
687 $limit = $wgRequest->getInt( 'limit', 0 );
688 if( $limit < 0 ) $limit = 0;
689 if( ( $limit == 0 ) && ( $optionname != "" ) ) {
690 $limit = (int)$wgUser->getOption( $optionname );
692 if( $limit <= 0 ) $limit = $deflimit;
693 if( $limit > 5000 ) $limit = 5000; # We have *some* limits...
695 $offset = $wgRequest->getInt( 'offset', 0 );
696 if( $offset < 0 ) $offset = 0;
697 if( $offset > 65000 ) $offset = 65000; # do we need a max? what?
699 return array( $limit, $offset );
702 # Escapes the given text so that it may be output using addWikiText()
703 # without any linking, formatting, etc. making its way through. This
704 # is achieved by substituting certain characters with HTML entities.
705 # As required by the callers, <nowiki> is not used. It currently does
706 # not filter out characters which have special meaning only at the
707 # start of a line, such as "*".
708 function wfEscapeWikiText( $text )
710 $text = str_replace(
711 array( '[', '|', "'", 'ISBN ' , '://' , "\n=" ),
712 array( '&#91;', '&#124;', '&#39;', 'ISBN&#32;', '&#58;//' , "\n&#61;" ),
713 htmlspecialchars($text) );
714 return $text;
717 function wfQuotedPrintable( $string, $charset = "" )
719 # Probably incomplete; see RFC 2045
720 if( empty( $charset ) ) {
721 global $wgInputEncoding;
722 $charset = $wgInputEncoding;
724 $charset = strtoupper( $charset );
725 $charset = str_replace( "ISO-8859", "ISO8859", $charset ); // ?
727 $illegal = '\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\xff=';
728 $replace = $illegal . '\t ?_';
729 if( !preg_match( "/[$illegal]/", $string ) ) return $string;
730 $out = "=?$charset?Q?";
731 $out .= preg_replace( "/([$replace])/e", 'sprintf("=%02X",ord("$1"))', $string );
732 $out .= "?=";
733 return $out;
736 function wfTime(){
737 $st = explode( " ", microtime() );
738 return (float)$st[0] + (float)$st[1];
741 # Changes the first character to an HTML entity
742 function wfHtmlEscapeFirst( $text ) {
743 $ord = ord($text);
744 $newText = substr($text, 1);
745 return "&#$ord;$newText";
748 # Sets dest to source and returns the original value of dest
749 function wfSetVar( &$dest, $source )
751 $temp = $dest;
752 $dest = $source;
753 return $temp;
756 # Sets dest to a reference to source and returns the original dest
757 function &wfSetRef( &$dest, &$source )
759 $temp =& $dest;
760 $dest =& $source;
761 return $temp;
764 # This function takes two arrays as input, and returns a CGI-style string, e.g.
765 # "days=7&limit=100". Options in the first array override options in the second.
766 # Options set to "" will not be output.
767 function wfArrayToCGI( $array1, $array2 = NULL )
769 if ( !is_null( $array2 ) ) {
770 $array1 = $array1 + $array2;
773 $cgi = "";
774 foreach ( $array1 as $key => $value ) {
775 if ( "" !== $value ) {
776 if ( "" != $cgi ) {
777 $cgi .= "&";
779 $cgi .= "{$key}={$value}";
782 return $cgi;
785 # This is obsolete, use SquidUpdate::purge()
786 function wfPurgeSquidServers ($urlArr) {
787 SquidUpdate::purge( $urlArr );
790 # Windows-compatible version of escapeshellarg()
791 function wfEscapeShellArg( )
793 $args = func_get_args();
794 $first = true;
795 $retVal = "";
796 foreach ( $args as $arg ) {
797 if ( !$first ) {
798 $retVal .= " ";
799 } else {
800 $first = false;
803 if (substr(php_uname(), 0, 7) == "Windows") {
804 $retVal .= '"' . str_replace( '"','\"', $arg ) . '"';
805 } else {
806 $retVal .= escapeshellarg( $arg );
809 return $retVal;
812 # wfMerge attempts to merge differences between three texts.
813 # Returns true for a clean merge and false for failure or a conflict.
815 function wfMerge( $old, $mine, $yours, &$result ){
816 global $wgDiff3;
818 # This check may also protect against code injection in
819 # case of broken installations.
820 if(! file_exists( $wgDiff3 ) ){
821 return false;
824 # Make temporary files
825 $td = "/tmp/";
826 $oldtextFile = fopen( $oldtextName = tempnam( $td, "merge-old-" ), "w" );
827 $mytextFile = fopen( $mytextName = tempnam( $td, "merge-mine-" ), "w" );
828 $yourtextFile = fopen( $yourtextName = tempnam( $td, "merge-your-" ), "w" );
830 fwrite( $oldtextFile, $old ); fclose( $oldtextFile );
831 fwrite( $mytextFile, $mine ); fclose( $mytextFile );
832 fwrite( $yourtextFile, $yours ); fclose( $yourtextFile );
834 # Check for a conflict
835 $cmd = wfEscapeShellArg( $wgDiff3 ) . " -a --overlap-only " .
836 wfEscapeShellArg( $mytextName ) . " " .
837 wfEscapeShellArg( $oldtextName ) . " " .
838 wfEscapeShellArg( $yourtextName );
839 $handle = popen( $cmd, "r" );
841 if( fgets( $handle ) ){
842 $conflict = true;
843 } else {
844 $conflict = false;
846 pclose( $handle );
848 # Merge differences
849 $cmd = wfEscapeShellArg( $wgDiff3 ) . " -a -e --merge " .
850 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
851 $handle = popen( $cmd, "r" );
852 $result = "";
853 do {
854 $data = fread( $handle, 8192 );
855 if ( strlen( $data ) == 0 ) {
856 break;
858 $result .= $data;
859 } while ( true );
860 pclose( $handle );
861 unlink( $mytextName ); unlink( $oldtextName ); unlink( $yourtextName );
862 return ! $conflict;
865 function wfVarDump( $var )
867 global $wgOut;
868 $s = str_replace("\n","<br>\n", var_export( $var, true ) . "\n");
869 if ( headers_sent() || !@is_object( $wgOut ) ) {
870 print $s;
871 } else {
872 $wgOut->addHTML( $s );
876 # Provide a simple HTTP error.
877 function wfHttpError( $code, $label, $desc ) {
878 global $wgOut;
879 $wgOut->disable();
880 header( "HTTP/1.0 $code $label" );
881 header( "Status: $code $label" );
882 $wgOut->sendCacheControl();
884 # Don't send content if it's a HEAD request.
885 if( $_SERVER['REQUEST_METHOD'] == 'HEAD' ) {
886 header( "Content-type: text/plain" );
887 print "$desc\n";
891 # Converts an Accept-* header into an array mapping string values to quality factors
892 function wfAcceptToPrefs( $accept, $def = "*/*" ) {
893 # No arg means accept anything (per HTTP spec)
894 if( !$accept ) {
895 return array( $def => 1 );
898 $prefs = array();
900 $parts = explode( ",", $accept );
902 foreach( $parts as $part ) {
903 # FIXME: doesn't deal with params like 'text/html; level=1'
904 @list( $value, $qpart ) = explode( ";", $part );
905 if( !isset( $qpart ) ) {
906 $prefs[$value] = 1;
907 } elseif( preg_match( '/q\s*=\s*(\d*\.\d+)/', $qpart, $match ) ) {
908 $prefs[$value] = $match[1];
912 return $prefs;
915 /* private */ function mimeTypeMatch( $type, $avail ) {
916 if( array_key_exists($type, $avail) ) {
917 return $type;
918 } else {
919 $parts = explode( '/', $type );
920 if( array_key_exists( $parts[0] . '/*', $avail ) ) {
921 return $parts[0] . '/*';
922 } elseif( array_key_exists( '*/*', $avail ) ) {
923 return '*/*';
924 } else {
925 return NULL;
930 # FIXME: doesn't handle params like 'text/plain; charset=UTF-8'
931 # XXX: generalize to negotiate other stuff
932 function wfNegotiateType( $cprefs, $sprefs ) {
933 $combine = array();
935 foreach( array_keys($sprefs) as $type ) {
936 $parts = explode( '/', $type );
937 if( $parts[1] != '*' ) {
938 $ckey = mimeTypeMatch( $type, $cprefs );
939 if( $ckey ) {
940 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
945 foreach( array_keys( $cprefs ) as $type ) {
946 $parts = explode( '/', $type );
947 if( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
948 $skey = mimeTypeMatch( $type, $sprefs );
949 if( $skey ) {
950 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
955 $bestq = 0;
956 $besttype = NULL;
958 foreach( array_keys( $combine ) as $type ) {
959 if( $combine[$type] > $bestq ) {
960 $besttype = $type;
961 $bestq = $combine[$type];
965 return $besttype;