category redirect bug fix
[mediawiki.git] / includes / GlobalFunctions.php
blobc06fedea7eed530836cfc2fdac471d683382a13a
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 # Seed Mersenne Twister
67 # Only necessary in PHP < 4.2.0
68 function wfSeedRandom()
70 global $wgRandomSeeded;
72 if ( ! $wgRandomSeeded && version_compare( phpversion(), '4.2.0' ) < 0 ) {
73 $seed = hexdec(substr(md5(microtime()),-8)) & 0x7fffffff;
74 mt_srand( $seed );
75 $wgRandomSeeded = true;
79 # Generates a URL from a URL-encoded title and a query string
80 # Title::getLocalURL() is preferred in most cases
82 function wfLocalUrl( $a, $q = '' )
84 global $wgServer, $wgScript, $wgArticlePath;
86 $a = str_replace( ' ', '_', $a );
88 if ( '' == $a ) {
89 if( '' == $q ) {
90 $a = $wgScript;
91 } else {
92 $a = "{$wgScript}?{$q}";
94 } else if ( '' == $q ) {
95 $a = str_replace( "$1", $a, $wgArticlePath );
96 } else if ($wgScript != '' ) {
97 $a = "{$wgScript}?title={$a}&{$q}";
98 } else { //XXX hackish solution for toplevel wikis
99 $a = "/{$a}?{$q}";
101 return $a;
104 function wfLocalUrlE( $a, $q = '' )
106 return wfEscapeHTML( wfLocalUrl( $a, $q ) );
107 # die( "Call to obsolete function wfLocalUrlE()" );
110 function wfFullUrl( $a, $q = '' ) {
111 wfDebugDieBacktrace( 'Call to obsolete function wfFullUrl(); use Title::getFullURL' );
114 function wfFullUrlE( $a, $q = '' ) {
115 wfDebugDieBacktrace( 'Call to obsolete function wfFullUrlE(); use Title::getFullUrlE' );
119 // orphan function wfThumbUrl( $img )
121 // global $wgUploadPath;
123 // $nt = Title::newFromText( $img );
124 // if( !$nt ) return "";
126 // $name = $nt->getDBkey();
127 // $hash = md5( $name );
129 // $url = "{$wgUploadPath}/thumb/" . $hash{0} . "/" .
130 // substr( $hash, 0, 2 ) . "/{$name}";
131 // return wfUrlencode( $url );
135 function wfImageArchiveUrl( $name )
137 global $wgUploadPath;
139 $hash = md5( substr( $name, 15) );
140 $url = "{$wgUploadPath}/archive/" . $hash{0} . "/" .
141 substr( $hash, 0, 2 ) . "/{$name}";
142 return wfUrlencode($url);
145 function wfUrlencode ( $s )
147 $s = urlencode( $s );
148 $s = preg_replace( '/%3[Aa]/', ':', $s );
149 $s = preg_replace( '/%2[Ff]/', '/', $s );
151 return $s;
154 function wfUtf8Sequence($codepoint) {
155 if($codepoint < 0x80) return chr($codepoint);
156 if($codepoint < 0x800) return chr($codepoint >> 6 & 0x3f | 0xc0) .
157 chr($codepoint & 0x3f | 0x80);
158 if($codepoint < 0x10000) return chr($codepoint >> 12 & 0x0f | 0xe0) .
159 chr($codepoint >> 6 & 0x3f | 0x80) .
160 chr($codepoint & 0x3f | 0x80);
161 if($codepoint < 0x100000) return chr($codepoint >> 18 & 0x07 | 0xf0) . # Double-check this
162 chr($codepoint >> 12 & 0x3f | 0x80) .
163 chr($codepoint >> 6 & 0x3f | 0x80) .
164 chr($codepoint & 0x3f | 0x80);
165 # Doesn't yet handle outside the BMP
166 return "&#$codepoint;";
169 # Converts numeric character entities to UTF-8
170 function wfMungeToUtf8($string) {
171 global $wgInputEncoding; # This is debatable
172 #$string = iconv($wgInputEncoding, "UTF-8", $string);
173 $string = preg_replace ( '/&#([0-9]+);/e', 'wfUtf8Sequence($1)', $string );
174 $string = preg_replace ( '/&#x([0-9a-f]+);/ie', 'wfUtf8Sequence(0x$1)', $string );
175 # Should also do named entities here
176 return $string;
179 # Converts a single UTF-8 character into the corresponding HTML character entity
180 function wfUtf8Entity( $matches ) {
181 $char = $matches[0];
182 # Find the length
183 $z = ord( $char{0} );
184 if ( $z & 0x80 ) {
185 $length = 0;
186 while ( $z & 0x80 ) {
187 $length++;
188 $z <<= 1;
190 } else {
191 $length = 1;
194 if ( $length != strlen( $char ) ) {
195 return '';
197 if ( $length == 1 ) {
198 return $char;
201 # Mask off the length-determining bits and shift back to the original location
202 $z &= 0xff;
203 $z >>= $length;
205 # Add in the free bits from subsequent bytes
206 for ( $i=1; $i<$length; $i++ ) {
207 $z <<= 6;
208 $z |= ord( $char{$i} ) & 0x3f;
211 # Make entity
212 return "&#$z;";
215 # Converts all multi-byte characters in a UTF-8 string into the appropriate character entity
216 function wfUtf8ToHTML($string) {
217 return preg_replace_callback( '/[\\xc0-\\xfd][\\x80-\\xbf]*/', 'wfUtf8Entity', $string );
220 function wfDebug( $text, $logonly = false )
222 global $wgOut, $wgDebugLogFile, $wgDebugComments, $wgProfileOnly, $wgDebugRawPage;
224 # Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
225 if ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' && !$wgDebugRawPage ) {
226 return;
229 if ( isset( $wgOut ) && $wgDebugComments && !$logonly ) {
230 $wgOut->debug( $text );
232 if ( "" != $wgDebugLogFile && !$wgProfileOnly ) {
233 error_log( $text, 3, $wgDebugLogFile );
237 # Log for database errors
238 function wfLogDBError( $text ) {
239 global $wgDBerrorLog;
240 if ( $wgDBerrorLog ) {
241 $text = date("D M j G:i:s T Y") . "\t$text";
242 error_log( $text, 3, $wgDBerrorLog );
246 function logProfilingData()
248 global $wgRequestTime, $wgDebugLogFile, $wgDebugRawPage, $wgRequest;
249 global $wgProfiling, $wgProfileStack, $wgProfileLimit, $wgUser;
250 $now = wfTime();
252 list( $usec, $sec ) = explode( " ", $wgRequestTime );
253 $start = (float)$sec + (float)$usec;
254 $elapsed = $now - $start;
255 if ( $wgProfiling ) {
256 $prof = wfGetProfilingOutput( $start, $elapsed );
257 $forward = '';
258 if( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) )
259 $forward = ' forwarded for ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
260 if( !empty( $_SERVER['HTTP_CLIENT_IP'] ) )
261 $forward .= ' client IP ' . $_SERVER['HTTP_CLIENT_IP'];
262 if( !empty( $_SERVER['HTTP_FROM'] ) )
263 $forward .= ' from ' . $_SERVER['HTTP_FROM'];
264 if( $forward )
265 $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
266 if($wgUser->getId() == 0)
267 $forward .= ' anon';
268 $log = sprintf( "%s\t%04.3f\t%s\n",
269 gmdate( 'YmdHis' ), $elapsed,
270 urldecode( $_SERVER['REQUEST_URI'] . $forward ) );
271 if ( '' != $wgDebugLogFile && ( $wgRequest->getVal('action') != 'raw' || $wgDebugRawPage ) ) {
272 error_log( $log . $prof, 3, $wgDebugLogFile );
278 function wfReadOnly()
280 global $wgReadOnlyFile;
282 if ( "" == $wgReadOnlyFile ) { return false; }
283 return is_file( $wgReadOnlyFile );
286 $wgReplacementKeys = array( "$1", "$2", "$3", "$4", "$5", "$6", "$7", "$8", "$9" );
288 # Get a message from anywhere
289 function wfMsg( $key ) {
290 $args = func_get_args();
291 if ( count( $args ) ) {
292 array_shift( $args );
294 return wfMsgReal( $key, $args, true );
297 # Get a message from the language file
298 function wfMsgNoDB( $key ) {
299 $args = func_get_args();
300 if ( count( $args ) ) {
301 array_shift( $args );
303 return wfMsgReal( $key, $args, false );
306 # Really get a message
307 function wfMsgReal( $key, $args, $useDB ) {
308 global $wgReplacementKeys, $wgMessageCache, $wgLang;
310 $fname = 'wfMsg';
311 wfProfileIn( $fname );
312 if ( $wgMessageCache ) {
313 $message = $wgMessageCache->get( $key, $useDB );
314 } elseif ( $wgLang ) {
315 $message = $wgLang->getMessage( $key );
316 } else {
317 wfDebug( "No language object when getting $key\n" );
318 $message = "&lt;$key&gt;";
321 # Replace arguments
322 if( count( $args ) ) {
323 $message = str_replace( $wgReplacementKeys, $args, $message );
325 wfProfileOut( $fname );
326 return $message;
329 function wfCleanFormFields( $fields )
331 wfDebugDieBacktrace( 'Call to obsolete wfCleanFormFields(). Use wgRequest instead...' );
334 function wfMungeQuotes( $in )
336 $out = str_replace( '%', '%25', $in );
337 $out = str_replace( "'", '%27', $out );
338 $out = str_replace( '"', '%22', $out );
339 return $out;
342 function wfDemungeQuotes( $in )
344 $out = str_replace( '%22', '"', $in );
345 $out = str_replace( '%27', "'", $out );
346 $out = str_replace( '%25', '%', $out );
347 return $out;
350 function wfCleanQueryVar( $var )
352 wfDebugDieBacktrace( 'Call to obsolete function wfCleanQueryVar(); use wgRequest instead' );
355 function wfSearch( $s )
357 $se = new SearchEngine( $s );
358 $se->showResults();
361 function wfGo( $s )
362 { # pick the nearest match
363 $se = new SearchEngine( $s );
364 $se->goResult();
367 # Just like exit() but makes a note of it.
368 # Commits open transactions except if the error parameter is set
369 function wfAbruptExit( $error = false ){
370 global $wgLoadBalancer;
371 static $called = false;
372 if ( $called ){
373 exit();
375 $called = true;
377 if( function_exists( 'debug_backtrace' ) ){ // PHP >= 4.3
378 $bt = debug_backtrace();
379 for($i = 0; $i < count($bt) ; $i++){
380 $file = $bt[$i]['file'];
381 $line = $bt[$i]['line'];
382 wfDebug("WARNING: Abrupt exit in $file at line $line\n");
384 } else {
385 wfDebug('WARNING: Abrupt exit\n');
387 if ( !$error ) {
388 $wgLoadBalancer->closeAll();
390 exit();
393 function wfErrorExit() {
394 wfAbruptExit( true );
397 function wfDebugDieBacktrace( $msg = '' ) {
398 global $wgCommandLineMode;
400 if ( function_exists( 'debug_backtrace' ) ) {
401 if ( $wgCommandLineMode ) {
402 $msg .= "\nBacktrace:\n";
403 } else {
404 $msg .= "\n<p>Backtrace:</p>\n<ul>\n";
406 $backtrace = debug_backtrace();
407 foreach( $backtrace as $call ) {
408 $f = explode( DIRECTORY_SEPARATOR, $call['file'] );
409 $file = $f[count($f)-1];
410 if ( $wgCommandLineMode ) {
411 $msg .= "$file line {$call['line']} calls ";
412 } else {
413 $msg .= '<li>' . $file . " line " . $call['line'] . ' calls ';
415 if( !empty( $call['class'] ) ) $msg .= $call['class'] . '::';
416 $msg .= $call['function'] . "()";
418 if ( $wgCommandLineMode ) {
419 $msg .= "\n";
420 } else {
421 $msg .= "</li>\n";
425 die( $msg );
428 function wfNumberOfArticles()
430 global $wgNumberOfArticles;
432 wfLoadSiteStats();
433 return $wgNumberOfArticles;
436 /* private */ function wfLoadSiteStats()
438 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
439 $fname = 'wfLoadSiteStats';
441 if ( -1 != $wgNumberOfArticles ) return;
442 $dbr =& wfGetDB( DB_SLAVE );
443 $s = $dbr->getArray( 'site_stats',
444 array( 'ss_total_views', 'ss_total_edits', 'ss_good_articles' ),
445 array( 'ss_row_id' => 1 ), $fname
448 if ( $s === false ) {
449 return;
450 } else {
451 $wgTotalViews = $s->ss_total_views;
452 $wgTotalEdits = $s->ss_total_edits;
453 $wgNumberOfArticles = $s->ss_good_articles;
457 function wfEscapeHTML( $in )
459 return str_replace(
460 array( '&', '"', '>', '<' ),
461 array( '&amp;', '&quot;', '&gt;', '&lt;' ),
462 $in );
465 function wfEscapeHTMLTagsOnly( $in ) {
466 return str_replace(
467 array( '"', '>', '<' ),
468 array( '&quot;', '&gt;', '&lt;' ),
469 $in );
472 function wfUnescapeHTML( $in )
474 $in = str_replace( '&lt;', '<', $in );
475 $in = str_replace( '&gt;', '>', $in );
476 $in = str_replace( '&quot;', '"', $in );
477 $in = str_replace( '&amp;', '&', $in );
478 return $in;
481 function wfImageDir( $fname )
483 global $wgUploadDirectory;
485 $hash = md5( $fname );
486 $oldumask = umask(0);
487 $dest = $wgUploadDirectory . '/' . $hash{0};
488 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
489 $dest .= '/' . substr( $hash, 0, 2 );
490 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
492 umask( $oldumask );
493 return $dest;
496 function wfImageThumbDir( $fname , $subdir='thumb')
498 return wfImageArchiveDir( $fname, $subdir );
501 function wfImageArchiveDir( $fname , $subdir='archive')
503 global $wgUploadDirectory;
505 $hash = md5( $fname );
506 $oldumask = umask(0);
508 # Suppress warning messages here; if the file itself can't
509 # be written we'll worry about it then.
510 $archive = "{$wgUploadDirectory}/{$subdir}";
511 if ( ! is_dir( $archive ) ) { @mkdir( $archive, 0777 ); }
512 $archive .= '/' . $hash{0};
513 if ( ! is_dir( $archive ) ) { @mkdir( $archive, 0777 ); }
514 $archive .= '/' . substr( $hash, 0, 2 );
515 if ( ! is_dir( $archive ) ) { @mkdir( $archive, 0777 ); }
517 umask( $oldumask );
518 return $archive;
521 function wfRecordUpload( $name, $oldver, $size, $desc, $copyStatus = "", $source = "" )
523 global $wgUser, $wgLang, $wgTitle, $wgOut, $wgDeferredUpdateList;
524 global $wgUseCopyrightUpload;
526 $fname = 'wfRecordUpload';
527 $dbw =& wfGetDB( DB_MASTER );
529 # img_name must be unique
530 if ( !$dbw->indexUnique( 'image', 'img_name' ) ) {
531 wfDebugDieBacktrace( 'Database schema not up to date, please run maintenance/archives/patch-image_name_unique.sql' );
535 $now = wfTimestampNow();
536 $won = wfInvertTimestamp( $now );
537 $size = IntVal( $size );
539 if ( $wgUseCopyrightUpload )
541 $textdesc = '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $desc . "\n" .
542 '== ' . wfMsg ( 'filestatus' ) . " ==\n" . $copyStatus . "\n" .
543 '== ' . wfMsg ( 'filesource' ) . " ==\n" . $source ;
545 else $textdesc = $desc ;
547 $now = wfTimestampNow();
548 $won = wfInvertTimestamp( $now );
550 # Test to see if the row exists using INSERT IGNORE
551 # This avoids race conditions by locking the row until the commit, and also
552 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
553 $dbw->insert( 'image',
554 array(
555 'img_name' => $name,
556 'img_size'=> $size,
557 'img_timestamp' => $now,
558 'img_description' => $desc,
559 'img_user' => $wgUser->getID(),
560 'img_user_text' => $wgUser->getName(),
561 ), $fname, 'IGNORE'
563 $descTitle = Title::makeTitle( NS_IMAGE, $name );
565 if ( $dbw->affectedRows() ) {
566 # Successfully inserted, this is a new image
567 $id = $descTitle->getArticleID();
569 if ( $id == 0 ) {
570 $seqVal = $dbw->nextSequenceValue( 'cur_cur_id_seq' );
571 $dbw->insertArray( 'cur',
572 array(
573 'cur_id' => $seqVal,
574 'cur_namespace' => NS_IMAGE,
575 'cur_title' => $name,
576 'cur_comment' => $desc,
577 'cur_user' => $wgUser->getID(),
578 'cur_user_text' => $wgUser->getName(),
579 'cur_timestamp' => $now,
580 'cur_is_new' => 1,
581 'cur_text' => $textdesc,
582 'inverse_timestamp' => $won,
583 'cur_touched' => $now
584 ), $fname
586 $id = $dbw->insertId() or 0; # We should throw an error instead
588 RecentChange::notifyNew( $now, $descTitle, 0, $wgUser, $desc );
590 $u = new SearchUpdate( $id, $name, $desc );
591 $u->doUpdate();
593 } else {
594 # Collision, this is an update of an image
595 # Get current image row for update
596 $s = $dbw->getArray( 'image', array( 'img_name','img_size','img_timestamp','img_description',
597 'img_user','img_user_text' ), array( 'img_name' => $name ), $fname, 'FOR UPDATE' );
599 # Insert it into oldimage
600 $dbw->insertArray( 'oldimage',
601 array(
602 'oi_name' => $s->img_name,
603 'oi_archive_name' => $oldver,
604 'oi_size' => $s->img_size,
605 'oi_timestamp' => $s->img_timestamp,
606 'oi_description' => $s->img_description,
607 'oi_user' => $s->img_user,
608 'oi_user_text' => $s->img_user_text
609 ), $fname
612 # Update the current image row
613 $dbw->updateArray( 'image',
614 array( /* SET */
615 'img_size' => $size,
616 'img_timestamp' => wfTimestampNow(),
617 'img_user' => $wgUser->getID(),
618 'img_user_text' => $wgUser->getName(),
619 'img_description' => $desc,
620 ), array( /* WHERE */
621 'img_name' => $name
622 ), $fname
625 # Invalidate the cache for the description page
626 $descTitle->invalidateCache();
629 $log = new LogPage( wfMsg( 'uploadlogpage' ), wfMsg( 'uploadlogpagetext' ) );
630 $da = wfMsg( 'uploadedimage', '[[:' . $wgLang->getNsText(
631 Namespace::getImage() ) . ":{$name}|{$name}]]" );
632 $ta = wfMsg( 'uploadedimage', $name );
633 $log->addEntry( $da, $desc, $ta );
637 /* Some generic result counters, pulled out of SearchEngine */
639 function wfShowingResults( $offset, $limit )
641 global $wgLang;
642 return wfMsg( 'showingresults', $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+1 ) );
645 function wfShowingResultsNum( $offset, $limit, $num )
647 global $wgLang;
648 return wfMsg( 'showingresultsnum', $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+1 ), $wgLang->formatNum( $num ) );
651 function wfViewPrevNext( $offset, $limit, $link, $query = '', $atend = false )
653 global $wgUser, $wgLang;
654 $fmtLimit = $wgLang->formatNum( $limit );
655 $prev = wfMsg( 'prevn', $fmtLimit );
656 $next = wfMsg( 'nextn', $fmtLimit );
657 $link = wfUrlencode( $link );
659 $sk = $wgUser->getSkin();
660 if ( 0 != $offset ) {
661 $po = $offset - $limit;
662 if ( $po < 0 ) { $po = 0; }
663 $q = "limit={$limit}&offset={$po}";
664 if ( '' != $query ) { $q .= "&{$query}"; }
665 $plink = '<a href="' . wfLocalUrlE( $link, $q ) . "\">{$prev}</a>";
666 } else { $plink = $prev; }
668 $no = $offset + $limit;
669 $q = "limit={$limit}&offset={$no}";
670 if ( "" != $query ) { $q .= "&{$query}"; }
672 if ( $atend ) {
673 $nlink = $next;
674 } else {
675 $nlink = '<a href="' . wfLocalUrlE( $link, $q ) . "\">{$next}</a>";
677 $nums = wfNumLink( $offset, 20, $link , $query ) . ' | ' .
678 wfNumLink( $offset, 50, $link, $query ) . ' | ' .
679 wfNumLink( $offset, 100, $link, $query ) . ' | ' .
680 wfNumLink( $offset, 250, $link, $query ) . ' | ' .
681 wfNumLink( $offset, 500, $link, $query );
683 return wfMsg( 'viewprevnext', $plink, $nlink, $nums );
686 function wfNumLink( $offset, $limit, $link, $query = '' )
688 global $wgUser, $wgLang;
689 if ( '' == $query ) { $q = ''; }
690 else { $q = "{$query}&"; }
691 $q .= "limit={$limit}&offset={$offset}";
693 $fmtLimit = $wgLang->formatNum( $limit );
694 $s = '<a href="' . wfLocalUrlE( $link, $q ) . "\">{$fmtLimit}</a>";
695 return $s;
698 function wfClientAcceptsGzip() {
699 global $wgUseGzip;
700 if( $wgUseGzip ) {
701 # FIXME: we may want to blacklist some broken browsers
702 if( preg_match(
703 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
704 $_SERVER['HTTP_ACCEPT_ENCODING'],
705 $m ) ) {
706 if( ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) return false;
707 wfDebug( " accepts gzip\n" );
708 return true;
711 return false;
714 # Yay, more global functions!
715 function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) {
716 global $wgUser, $wgRequest;
718 $limit = $wgRequest->getInt( 'limit', 0 );
719 if( $limit < 0 ) $limit = 0;
720 if( ( $limit == 0 ) && ( $optionname != '' ) ) {
721 $limit = (int)$wgUser->getOption( $optionname );
723 if( $limit <= 0 ) $limit = $deflimit;
724 if( $limit > 5000 ) $limit = 5000; # We have *some* limits...
726 $offset = $wgRequest->getInt( 'offset', 0 );
727 if( $offset < 0 ) $offset = 0;
728 if( $offset > 65000 ) $offset = 65000; # do we need a max? what?
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 )
741 $text = str_replace(
742 array( '[', '|', "'", 'ISBN ' , '://' , "\n=" ),
743 array( '&#91;', '&#124;', '&#39;', 'ISBN&#32;', '&#58;//' , "\n&#61;" ),
744 htmlspecialchars($text) );
745 return $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 );
763 $out .= '?=';
764 return $out;
767 function wfTime(){
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 ) {
774 $ord = ord($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 )
783 $temp = $dest;
784 if ( !is_null( $source ) ) {
785 $dest = $source;
787 return $temp;
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 ) ) {
794 if ( $state ) {
795 $dest |= $bit;
796 } else {
797 $dest &= ~$bit;
800 return $temp;
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;
812 $cgi = '';
813 foreach ( $array1 as $key => $value ) {
814 if ( '' !== $value ) {
815 if ( '' != $cgi ) {
816 $cgi .= '&';
818 $cgi .= "{$key}={$value}";
821 return $cgi;
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();
833 $first = true;
834 $retVal = '';
835 foreach ( $args as $arg ) {
836 if ( !$first ) {
837 $retVal .= ' ';
838 } else {
839 $first = false;
842 if ( wfIsWindows() ) {
843 $retVal .= '"' . str_replace( '"','\"', $arg ) . '"';
844 } else {
845 $retVal .= escapeshellarg( $arg );
848 return $retVal;
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 ){
855 global $wgDiff3;
857 # This check may also protect against code injection in
858 # case of broken installations.
859 if(! file_exists( $wgDiff3 ) ){
860 return false;
863 # Make temporary files
864 $td = '/tmp/';
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 ) ){
881 $conflict = true;
882 } else {
883 $conflict = false;
885 pclose( $handle );
887 # Merge differences
888 $cmd = wfEscapeShellArg( $wgDiff3 ) . ' -a -e --merge ' .
889 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
890 $handle = popen( $cmd, 'r' );
891 $result = '';
892 do {
893 $data = fread( $handle, 8192 );
894 if ( strlen( $data ) == 0 ) {
895 break;
897 $result .= $data;
898 } while ( true );
899 pclose( $handle );
900 unlink( $mytextName ); unlink( $oldtextName ); unlink( $yourtextName );
901 return ! $conflict;
904 function wfVarDump( $var )
906 global $wgOut;
907 $s = str_replace("\n","<br>\n", var_export( $var, true ) . "\n");
908 if ( headers_sent() || !@is_object( $wgOut ) ) {
909 print $s;
910 } else {
911 $wgOut->addHTML( $s );
915 # Provide a simple HTTP error.
916 function wfHttpError( $code, $label, $desc ) {
917 global $wgOut;
918 $wgOut->disable();
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' );
926 print "$desc\n";
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)
933 if( !$accept ) {
934 return array( $def => 1 );
937 $prefs = array();
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 ) ) {
945 $prefs[$value] = 1;
946 } elseif( preg_match( '/q\s*=\s*(\d*\.\d+)/', $qpart, $match ) ) {
947 $prefs[$value] = $match[1];
951 return $prefs;
954 /* private */ function mimeTypeMatch( $type, $avail ) {
955 if( array_key_exists($type, $avail) ) {
956 return $type;
957 } else {
958 $parts = explode( '/', $type );
959 if( array_key_exists( $parts[0] . '/*', $avail ) ) {
960 return $parts[0] . '/*';
961 } elseif( array_key_exists( '*/*', $avail ) ) {
962 return '*/*';
963 } else {
964 return NULL;
969 # FIXME: doesn't handle params like 'text/plain; charset=UTF-8'
970 # XXX: generalize to negotiate other stuff
971 function wfNegotiateType( $cprefs, $sprefs ) {
972 $combine = array();
974 foreach( array_keys($sprefs) as $type ) {
975 $parts = explode( '/', $type );
976 if( $parts[1] != '*' ) {
977 $ckey = mimeTypeMatch( $type, $cprefs );
978 if( $ckey ) {
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 );
988 if( $skey ) {
989 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
994 $bestq = 0;
995 $besttype = NULL;
997 foreach( array_keys( $combine ) as $type ) {
998 if( $combine[$type] > $bestq ) {
999 $besttype = $type;
1000 $bestq = $combine[$type];
1004 return $besttype;
1007 # Array lookup
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') {
1019 return true;
1020 } else {
1021 return false;
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() {
1039 # return NOW
1040 return gmdate( "YmdHis" );
1043 # Sorting hack for MySQL 3, which doesn't use index sorts for DESC
1044 function wfInvertTimestamp( $ts ) {
1045 return strtr(
1046 $ts,
1047 "0123456789",
1048 "9876543210"
1052 # Reference-counted warning suppression
1053 function wfSuppressWarnings( $end = false ) {
1054 static $suppressCount = 0;
1055 static $originalLevel = false;
1057 if ( $end ) {
1058 if ( $suppressCount ) {
1059 $suppressCount --;
1060 if ( !$suppressCount ) {
1061 error_reporting( $originalLevel );
1064 } else {
1065 if ( !$suppressCount ) {
1066 $originalLevel = error_reporting( E_ALL & ~( E_WARNING | E_NOTICE ) );
1068 $suppressCount++;
1072 # Restore error level to previous value
1073 function wfRestoreWarnings() {
1074 wfSuppressWarnings( true );