temporary removal of tokenizer for performance
[lhc/web/wiklou.git] / includes / GlobalFunctions.php
1 <?php
2 # Global functions used everywhere
3
4 $wgNumberOfArticles = -1; # Unset
5 $wgTotalViews = -1;
6 $wgTotalEdits = -1;
7
8 require_once( "DatabaseFunctions.php" );
9 require_once( "UpdateClasses.php" );
10 require_once( "LogPage.php" );
11
12 /*
13 * Compatibility functions
14 */
15
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.
19
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;
29 }
30 }
31
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 ) );
36 }
37 }
38
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 ) );
45 }
46 }
47
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 );
59 }
60 }
61 return strtr( $string, $trans );
62 }
63
64 $wgRandomSeeded = false;
65
66 function wfSeedRandom()
67 {
68 global $wgRandomSeeded;
69
70 if ( ! $wgRandomSeeded ) {
71 $seed = hexdec(substr(md5(microtime()),-8)) & 0x7fffffff;
72 mt_srand( $seed );
73 $wgRandomSeeded = true;
74 }
75 }
76
77 # Generates a URL from a URL-encoded title and a query string
78 # Title::getLocalURL() is preferred in most cases
79 #
80 function wfLocalUrl( $a, $q = "" )
81 {
82 global $wgServer, $wgScript, $wgArticlePath;
83
84 $a = str_replace( " ", "_", $a );
85
86 if ( "" == $a ) {
87 if( "" == $q ) {
88 $a = $wgScript;
89 } else {
90 $a = "{$wgScript}?{$q}";
91 }
92 } else if ( "" == $q ) {
93 $a = str_replace( "$1", $a, $wgArticlePath );
94 } else if ($wgScript != '' ) {
95 $a = "{$wgScript}?title={$a}&{$q}";
96 } else { //XXX hackish solution for toplevel wikis
97 $a = "/{$a}?{$q}";
98 }
99 return $a;
100 }
101
102 function wfLocalUrlE( $a, $q = "" )
103 {
104 return wfEscapeHTML( wfLocalUrl( $a, $q ) );
105 # die( "Call to obsolete function wfLocalUrlE()" );
106 }
107
108 function wfFullUrl( $a, $q = "" ) {
109 wfDebugDieBacktrace( "Call to obsolete function wfFullUrl(); use Title::getFullURL" );
110 }
111
112 function wfFullUrlE( $a, $q = "" ) {
113 wfDebugDieBacktrace( "Call to obsolete function wfFullUrlE(); use Title::getFullUrlE" );
114
115 }
116
117 // orphan function wfThumbUrl( $img )
118 //{
119 // global $wgUploadPath;
120 //
121 // $nt = Title::newFromText( $img );
122 // if( !$nt ) return "";
123 //
124 // $name = $nt->getDBkey();
125 // $hash = md5( $name );
126 //
127 // $url = "{$wgUploadPath}/thumb/" . $hash{0} . "/" .
128 // substr( $hash, 0, 2 ) . "/{$name}";
129 // return wfUrlencode( $url );
130 //}
131
132
133 function wfImageArchiveUrl( $name )
134 {
135 global $wgUploadPath;
136
137 $hash = md5( substr( $name, 15) );
138 $url = "{$wgUploadPath}/archive/" . $hash{0} . "/" .
139 substr( $hash, 0, 2 ) . "/{$name}";
140 return wfUrlencode($url);
141 }
142
143 function wfUrlencode ( $s )
144 {
145 $s = urlencode( $s );
146 $s = preg_replace( "/%3[Aa]/", ":", $s );
147 $s = preg_replace( "/%2[Ff]/", "/", $s );
148
149 return $s;
150 }
151
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;";
165 }
166
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;
174 }
175
176 # Converts a single UTF-8 character into the corresponding HTML character entity
177 function wfUtf8Entity( $matches ) {
178 $char = $matches[0];
179 # Find the length
180 $z = ord( $char{0} );
181 if ( $z & 0x80 ) {
182 $length = 0;
183 while ( $z & 0x80 ) {
184 $length++;
185 $z <<= 1;
186 }
187 } else {
188 $length = 1;
189 }
190
191 if ( $length != strlen( $char ) ) {
192 return "";
193 }
194 if ( $length == 1 ) {
195 return $char;
196 }
197
198 # Mask off the length-determining bits and shift back to the original location
199 $z &= 0xff;
200 $z >>= $length;
201
202 # Add in the free bits from subsequent bytes
203 for ( $i=1; $i<$length; $i++ ) {
204 $z <<= 6;
205 $z |= ord( $char{$i} ) & 0x3f;
206 }
207
208 # Make entity
209 return "&#$z;";
210 }
211
212 # Converts all multi-byte characters in a UTF-8 string into the appropriate character entity
213 function wfUtf8ToHTML($string) {
214 return preg_replace_callback( '/[\\xc0-\\xfd][\\x80-\\xbf]*/', 'wfUtf8Entity', $string );
215 }
216
217 function wfDebug( $text, $logonly = false )
218 {
219 global $wgOut, $wgDebugLogFile, $wgDebugComments, $wgProfileOnly;
220
221 if ( isset( $wgOut ) && $wgDebugComments && !$logonly ) {
222 $wgOut->debug( $text );
223 }
224 if ( "" != $wgDebugLogFile && !$wgProfileOnly ) {
225 error_log( $text, 3, $wgDebugLogFile );
226 }
227 }
228
229 function logProfilingData()
230 {
231 global $wgRequestTime, $wgDebugLogFile;
232 global $wgProfiling, $wgProfileStack, $wgProfileLimit, $wgUser;
233 $now = wfTime();
234
235 list( $usec, $sec ) = explode( " ", $wgRequestTime );
236 $start = (float)$sec + (float)$usec;
237 $elapsed = $now - $start;
238 if ( "" != $wgDebugLogFile ) {
239 $prof = wfGetProfilingOutput( $start, $elapsed );
240 $forward = "";
241 if( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) )
242 $forward = " forwarded for " . $_SERVER['HTTP_X_FORWARDED_FOR'];
243 if( !empty( $_SERVER['HTTP_CLIENT_IP'] ) )
244 $forward .= " client IP " . $_SERVER['HTTP_CLIENT_IP'];
245 if( !empty( $_SERVER['HTTP_FROM'] ) )
246 $forward .= " from " . $_SERVER['HTTP_FROM'];
247 if( $forward )
248 $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
249 if($wgUser->getId() == 0)
250 $forward .= " anon";
251 $log = sprintf( "%s\t%04.3f\t%s\n",
252 gmdate( "YmdHis" ), $elapsed,
253 urldecode( $_SERVER['REQUEST_URI'] . $forward ) );
254 error_log( $log . $prof, 3, $wgDebugLogFile );
255 }
256 }
257
258
259 function wfReadOnly()
260 {
261 global $wgReadOnlyFile;
262
263 if ( "" == $wgReadOnlyFile ) { return false; }
264 return is_file( $wgReadOnlyFile );
265 }
266
267 $wgReplacementKeys = array( "$1", "$2", "$3", "$4", "$5", "$6", "$7", "$8", "$9" );
268
269 # Get a message from anywhere
270 function wfMsg( $key ) {
271 $args = func_get_args();
272 if ( count( $args ) ) {
273 array_shift( $args );
274 }
275 return wfMsgReal( $key, $args, true );
276 }
277
278 # Get a message from the language file
279 function wfMsgNoDB( $key ) {
280 $args = func_get_args();
281 if ( count( $args ) ) {
282 array_shift( $args );
283 }
284 return wfMsgReal( $key, $args, false );
285 }
286
287 # Really get a message
288 function wfMsgReal( $key, $args, $useDB ) {
289 global $wgReplacementKeys, $wgMessageCache, $wgLang;
290
291 $fname = "wfMsg";
292 wfProfileIn( $fname );
293 if ( $wgMessageCache ) {
294 $message = $wgMessageCache->get( $key, $useDB );
295 } elseif ( $wgLang ) {
296 $message = $wgLang->getMessage( $key );
297 } else {
298 wfDebug( "No language object when getting $key\n" );
299 $message = "&lt;$key&gt;";
300 }
301
302 # Replace arguments
303 if( count( $args ) ) {
304 $message = str_replace( $wgReplacementKeys, $args, $message );
305 }
306 wfProfileOut( $fname );
307 return $message;
308 }
309
310 function wfCleanFormFields( $fields )
311 {
312 wfDebugDieBacktrace( "Call to obsolete wfCleanFormFields(). Use wgRequest instead..." );
313 }
314
315 function wfMungeQuotes( $in )
316 {
317 $out = str_replace( "%", "%25", $in );
318 $out = str_replace( "'", "%27", $out );
319 $out = str_replace( "\"", "%22", $out );
320 return $out;
321 }
322
323 function wfDemungeQuotes( $in )
324 {
325 $out = str_replace( "%22", "\"", $in );
326 $out = str_replace( "%27", "'", $out );
327 $out = str_replace( "%25", "%", $out );
328 return $out;
329 }
330
331 function wfCleanQueryVar( $var )
332 {
333 wfDebugDieBacktrace( "Call to obsolete function wfCleanQueryVar(); use wgRequest instead" );
334 }
335
336 function wfSearch( $s )
337 {
338 $se = new SearchEngine( $s );
339 $se->showResults();
340 }
341
342 function wfGo( $s )
343 { # pick the nearest match
344 $se = new SearchEngine( $s );
345 $se->goResult();
346 }
347
348 # Just like exit() but makes a note of it.
349 function wfAbruptExit(){
350 static $called = false;
351 if ( $called ){
352 exit();
353 }
354 $called = true;
355
356 if( function_exists( "debug_backtrace" ) ){ // PHP >= 4.3
357 $bt = debug_backtrace();
358 for($i = 0; $i < count($bt) ; $i++){
359 $file = $bt[$i]["file"];
360 $line = $bt[$i]["line"];
361 wfDebug("WARNING: Abrupt exit in $file at line $line\n");
362 }
363 } else {
364 wfDebug("WARNING: Abrupt exit\n");
365 }
366 exit();
367 }
368
369 function wfDebugDieBacktrace( $msg = "" ) {
370 $msg .= "\n<p>Backtrace:</p>\n<ul>\n";
371 $backtrace = debug_backtrace();
372 foreach( $backtrace as $call ) {
373 $f = explode( DIRECTORY_SEPARATOR, $call['file'] );
374 $file = $f[count($f)-1];
375 $msg .= "<li>" . $file . " line " . $call['line'] . ", in ";
376 if( !empty( $call['class'] ) ) $msg .= $call['class'] . "::";
377 $msg .= $call['function'] . "()</li>\n";
378 }
379 die( $msg );
380 }
381
382 function wfNumberOfArticles()
383 {
384 global $wgNumberOfArticles;
385
386 wfLoadSiteStats();
387 return $wgNumberOfArticles;
388 }
389
390 /* private */ function wfLoadSiteStats()
391 {
392 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
393 if ( -1 != $wgNumberOfArticles ) return;
394
395 $sql = "SELECT ss_total_views, ss_total_edits, ss_good_articles " .
396 "FROM site_stats WHERE ss_row_id=1";
397 $res = wfQuery( $sql, DB_READ, "wfLoadSiteStats" );
398
399 if ( 0 == wfNumRows( $res ) ) { return; }
400 else {
401 $s = wfFetchObject( $res );
402 $wgTotalViews = $s->ss_total_views;
403 $wgTotalEdits = $s->ss_total_edits;
404 $wgNumberOfArticles = $s->ss_good_articles;
405 }
406 }
407
408 function wfEscapeHTML( $in )
409 {
410 return str_replace(
411 array( "&", "\"", ">", "<" ),
412 array( "&amp;", "&quot;", "&gt;", "&lt;" ),
413 $in );
414 }
415
416 function wfEscapeHTMLTagsOnly( $in ) {
417 return str_replace(
418 array( "\"", ">", "<" ),
419 array( "&quot;", "&gt;", "&lt;" ),
420 $in );
421 }
422
423 function wfUnescapeHTML( $in )
424 {
425 $in = str_replace( "&lt;", "<", $in );
426 $in = str_replace( "&gt;", ">", $in );
427 $in = str_replace( "&quot;", "\"", $in );
428 $in = str_replace( "&amp;", "&", $in );
429 return $in;
430 }
431
432 function wfImageDir( $fname )
433 {
434 global $wgUploadDirectory;
435
436 $hash = md5( $fname );
437 $oldumask = umask(0);
438 $dest = $wgUploadDirectory . "/" . $hash{0};
439 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
440 $dest .= "/" . substr( $hash, 0, 2 );
441 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
442
443 umask( $oldumask );
444 return $dest;
445 }
446
447 function wfImageThumbDir( $fname , $subdir="thumb")
448 {
449 return wfImageArchiveDir( $fname, $subdir );
450 }
451
452 function wfImageArchiveDir( $fname , $subdir="archive")
453 {
454 global $wgUploadDirectory;
455
456 $hash = md5( $fname );
457 $oldumask = umask(0);
458
459 # Suppress warning messages here; if the file itself can't
460 # be written we'll worry about it then.
461 $archive = "{$wgUploadDirectory}/{$subdir}";
462 if ( ! is_dir( $archive ) ) { @mkdir( $archive, 0777 ); }
463 $archive .= "/" . $hash{0};
464 if ( ! is_dir( $archive ) ) { @mkdir( $archive, 0777 ); }
465 $archive .= "/" . substr( $hash, 0, 2 );
466 if ( ! is_dir( $archive ) ) { @mkdir( $archive, 0777 ); }
467
468 umask( $oldumask );
469 return $archive;
470 }
471
472 function wfRecordUpload( $name, $oldver, $size, $desc, $copyStatus = "", $source = "" )
473 {
474 global $wgUser, $wgLang, $wgTitle, $wgOut, $wgDeferredUpdateList;
475 global $wgUseCopyrightUpload;
476
477 $fname = "wfRecordUpload";
478
479 $sql = "SELECT img_name,img_size,img_timestamp,img_description,img_user," .
480 "img_user_text FROM image WHERE img_name='" . wfStrencode( $name ) . "'";
481 $res = wfQuery( $sql, DB_READ, $fname );
482
483 $now = wfTimestampNow();
484 $won = wfInvertTimestamp( $now );
485 $size = IntVal( $size );
486
487 if ( $wgUseCopyrightUpload )
488 {
489 $textdesc = "== " . wfMsg ( "filedesc" ) . " ==\n" . $desc . "\n" .
490 "== " . wfMsg ( "filestatus" ) . " ==\n" . $copyStatus . "\n" .
491 "== " . wfMsg ( "filesource" ) . " ==\n" . $source ;
492 }
493 else $textdesc = $desc ;
494
495 $now = wfTimestampNow();
496 $won = wfInvertTimestamp( $now );
497
498 if ( 0 == wfNumRows( $res ) ) {
499 $sql = "INSERT INTO image (img_name,img_size,img_timestamp," .
500 "img_description,img_user,img_user_text) VALUES ('" .
501 wfStrencode( $name ) . "',$size,'{$now}','" .
502 wfStrencode( $desc ) . "', '" . $wgUser->getID() .
503 "', '" . wfStrencode( $wgUser->getName() ) . "')";
504 wfQuery( $sql, DB_WRITE, $fname );
505
506 $sql = "SELECT cur_id,cur_text FROM cur WHERE cur_namespace=" .
507 Namespace::getImage() . " AND cur_title='" .
508 wfStrencode( $name ) . "'";
509 $res = wfQuery( $sql, DB_READ, $fname );
510 if ( 0 == wfNumRows( $res ) ) {
511 $common =
512 Namespace::getImage() . ",'" .
513 wfStrencode( $name ) . "','" .
514 wfStrencode( $desc ) . "','" . $wgUser->getID() . "','" .
515 wfStrencode( $wgUser->getName() ) . "','" . $now .
516 "',1";
517 $sql = "INSERT INTO cur (cur_namespace,cur_title," .
518 "cur_comment,cur_user,cur_user_text,cur_timestamp,cur_is_new," .
519 "cur_text,inverse_timestamp,cur_touched) VALUES (" .
520 $common .
521 ",'" . wfStrencode( $textdesc ) . "','{$won}','{$now}')";
522 wfQuery( $sql, DB_WRITE, $fname );
523 $id = wfInsertId() or 0; # We should throw an error instead
524
525 $titleObj = Title::makeTitle( NS_IMAGE, $name );
526 RecentChange::notifyNew( $now, $titleObj, 0, $wgUser, $desc );
527
528 $u = new SearchUpdate( $id, $name, $desc );
529 $u->doUpdate();
530 }
531 } else {
532 $s = wfFetchObject( $res );
533
534 $sql = "INSERT INTO oldimage (oi_name,oi_archive_name,oi_size," .
535 "oi_timestamp,oi_description,oi_user,oi_user_text) VALUES ('" .
536 wfStrencode( $s->img_name ) . "','" .
537 wfStrencode( $oldver ) .
538 "',{$s->img_size},'{$s->img_timestamp}','" .
539 wfStrencode( $s->img_description ) . "','" .
540 wfStrencode( $s->img_user ) . "','" .
541 wfStrencode( $s->img_user_text) . "')";
542 wfQuery( $sql, DB_WRITE, $fname );
543
544 $sql = "UPDATE image SET img_size={$size}," .
545 "img_timestamp='" . wfTimestampNow() . "',img_user='" .
546 $wgUser->getID() . "',img_user_text='" .
547 wfStrencode( $wgUser->getName() ) . "', img_description='" .
548 wfStrencode( $desc ) . "' WHERE img_name='" .
549 wfStrencode( $name ) . "'";
550 wfQuery( $sql, DB_WRITE, $fname );
551
552 $sql = "UPDATE cur SET cur_touched='{$now}' WHERE cur_namespace=" .
553 Namespace::getImage() . " AND cur_title='" .
554 wfStrencode( $name ) . "'";
555 wfQuery( $sql, DB_WRITE, $fname );
556 }
557
558 $log = new LogPage( wfMsg( "uploadlogpage" ), wfMsg( "uploadlogpagetext" ) );
559 $da = wfMsg( "uploadedimage", "[[:" . $wgLang->getNsText(
560 Namespace::getImage() ) . ":{$name}|{$name}]]" );
561 $ta = wfMsg( "uploadedimage", $name );
562 $log->addEntry( $da, $desc, $ta );
563 }
564
565
566 /* Some generic result counters, pulled out of SearchEngine */
567
568 function wfShowingResults( $offset, $limit )
569 {
570 global $wgLang;
571 return wfMsg( "showingresults", $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+1 ) );
572 }
573
574 function wfShowingResultsNum( $offset, $limit, $num )
575 {
576 global $wgLang;
577 return wfMsg( "showingresultsnum", $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+1 ), $wgLang->formatNum( $num ) );
578 }
579
580 function wfViewPrevNext( $offset, $limit, $link, $query = "", $atend = false )
581 {
582 global $wgUser, $wgLang;
583 $fmtLimit = $wgLang->formatNum( $limit );
584 $prev = wfMsg( "prevn", $fmtLimit );
585 $next = wfMsg( "nextn", $fmtLimit );
586 $link = wfUrlencode( $link );
587
588 $sk = $wgUser->getSkin();
589 if ( 0 != $offset ) {
590 $po = $offset - $limit;
591 if ( $po < 0 ) { $po = 0; }
592 $q = "limit={$limit}&offset={$po}";
593 if ( "" != $query ) { $q .= "&{$query}"; }
594 $plink = "<a href=\"" . wfLocalUrlE( $link, $q ) . "\">{$prev}</a>";
595 } else { $plink = $prev; }
596
597 $no = $offset + $limit;
598 $q = "limit={$limit}&offset={$no}";
599 if ( "" != $query ) { $q .= "&{$query}"; }
600
601 if ( $atend ) {
602 $nlink = $next;
603 } else {
604 $nlink = "<a href=\"" . wfLocalUrlE( $link, $q ) . "\">{$next}</a>";
605 }
606 $nums = wfNumLink( $offset, 20, $link , $query ) . " | " .
607 wfNumLink( $offset, 50, $link, $query ) . " | " .
608 wfNumLink( $offset, 100, $link, $query ) . " | " .
609 wfNumLink( $offset, 250, $link, $query ) . " | " .
610 wfNumLink( $offset, 500, $link, $query );
611
612 return wfMsg( "viewprevnext", $plink, $nlink, $nums );
613 }
614
615 function wfNumLink( $offset, $limit, $link, $query = "" )
616 {
617 global $wgUser, $wgLang;
618 if ( "" == $query ) { $q = ""; }
619 else { $q = "{$query}&"; }
620 $q .= "limit={$limit}&offset={$offset}";
621
622 $fmtLimit = $wgLang->formatNum( $limit );
623 $s = "<a href=\"" . wfLocalUrlE( $link, $q ) . "\">{$fmtLimit}</a>";
624 return $s;
625 }
626
627 function wfClientAcceptsGzip() {
628 global $wgUseGzip;
629 if( $wgUseGzip ) {
630 # FIXME: we may want to blacklist some broken browsers
631 if( preg_match(
632 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
633 $_SERVER["HTTP_ACCEPT_ENCODING"],
634 $m ) ) {
635 if( ( $m[1] == "q" ) && ( $m[2] == 0 ) ) return false;
636 wfDebug( " accepts gzip\n" );
637 return true;
638 }
639 }
640 return false;
641 }
642
643 # Yay, more global functions!
644 function wfCheckLimits( $deflimit = 50, $optionname = "rclimit" ) {
645 global $wgUser, $wgRequest;
646
647 $limit = $wgRequest->getInt( 'limit', 0 );
648 if( $limit < 0 ) $limit = 0;
649 if( ( $limit == 0 ) && ( $optionname != "" ) ) {
650 $limit = (int)$wgUser->getOption( $optionname );
651 }
652 if( $limit <= 0 ) $limit = $deflimit;
653 if( $limit > 5000 ) $limit = 5000; # We have *some* limits...
654
655 $offset = $wgRequest->getInt( 'offset', 0 );
656 if( $offset < 0 ) $offset = 0;
657 if( $offset > 65000 ) $offset = 65000; # do we need a max? what?
658
659 return array( $limit, $offset );
660 }
661
662 # Escapes the given text so that it may be output using addWikiText()
663 # without any linking, formatting, etc. making its way through. This
664 # is achieved by substituting certain characters with HTML entities.
665 # As required by the callers, <nowiki> is not used. It currently does
666 # not filter out characters which have special meaning only at the
667 # start of a line, such as "*".
668 function wfEscapeWikiText( $text )
669 {
670 $text = str_replace(
671 array( '[', '|', "'", 'ISBN ' , '://' , "\n=" ),
672 array( '&#91;', '&#124;', '&#39;', 'ISBN&#32;', '&#58;//' , "\n&#61;" ),
673 htmlspecialchars($text) );
674 return $text;
675 }
676
677 function wfQuotedPrintable( $string, $charset = "" )
678 {
679 # Probably incomplete; see RFC 2045
680 if( empty( $charset ) ) {
681 global $wgInputEncoding;
682 $charset = $wgInputEncoding;
683 }
684 $charset = strtoupper( $charset );
685 $charset = str_replace( "ISO-8859", "ISO8859", $charset ); // ?
686
687 $illegal = '\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\xff=';
688 $replace = $illegal . '\t ?_';
689 if( !preg_match( "/[$illegal]/", $string ) ) return $string;
690 $out = "=?$charset?Q?";
691 $out .= preg_replace( "/([$replace])/e", 'sprintf("=%02X",ord("$1"))', $string );
692 $out .= "?=";
693 return $out;
694 }
695
696 function wfTime(){
697 $st = explode( " ", microtime() );
698 return (float)$st[0] + (float)$st[1];
699 }
700
701 # Changes the first character to an HTML entity
702 function wfHtmlEscapeFirst( $text ) {
703 $ord = ord($text);
704 $newText = substr($text, 1);
705 return "&#$ord;$newText";
706 }
707
708 # Sets dest to source and returns the original value of dest
709 function wfSetVar( &$dest, $source )
710 {
711 $temp = $dest;
712 $dest = $source;
713 return $temp;
714 }
715
716 # Sets dest to a reference to source and returns the original dest
717 function &wfSetRef( &$dest, &$source )
718 {
719 $temp =& $dest;
720 $dest =& $source;
721 return $temp;
722 }
723
724 # This function takes two arrays as input, and returns a CGI-style string, e.g.
725 # "days=7&limit=100". Options in the first array override options in the second.
726 # Options set to "" will not be output.
727 function wfArrayToCGI( $array1, $array2 = NULL )
728 {
729 if ( !is_null( $array2 ) ) {
730 $array1 = $array1 + $array2;
731 }
732
733 $cgi = "";
734 foreach ( $array1 as $key => $value ) {
735 if ( "" !== $value ) {
736 if ( "" != $cgi ) {
737 $cgi .= "&";
738 }
739 $cgi .= "{$key}={$value}";
740 }
741 }
742 return $cgi;
743 }
744
745 # This is obsolete, use SquidUpdate::purge()
746 function wfPurgeSquidServers ($urlArr) {
747 SquidUpdate::purge( $urlArr );
748 }
749
750 # Windows-compatible version of escapeshellarg()
751 function wfEscapeShellArg( )
752 {
753 $args = func_get_args();
754 $first = true;
755 $retVal = "";
756 foreach ( $args as $arg ) {
757 if ( !$first ) {
758 $retVal .= " ";
759 } else {
760 $first = false;
761 }
762
763 if (substr(php_uname(), 0, 7) == "Windows") {
764 $retVal .= '"' . str_replace( '"','\"', $arg ) . '"';
765 } else {
766 $retVal .= escapeshellarg( $arg );
767 }
768 }
769 return $retVal;
770 }
771
772 # wfMerge attempts to merge differences between three texts.
773 # Returns true for a clean merge and false for failure or a conflict.
774
775 function wfMerge( $old, $mine, $yours, &$result ){
776 global $wgDiff3;
777
778 # This check may also protect against code injection in
779 # case of broken installations.
780 if(! file_exists( $wgDiff3 ) ){
781 return false;
782 }
783
784 # Make temporary files
785 $td = "/tmp/";
786 $oldtextFile = fopen( $oldtextName = tempnam( $td, "merge-old-" ), "w" );
787 $mytextFile = fopen( $mytextName = tempnam( $td, "merge-mine-" ), "w" );
788 $yourtextFile = fopen( $yourtextName = tempnam( $td, "merge-your-" ), "w" );
789
790 fwrite( $oldtextFile, $old ); fclose( $oldtextFile );
791 fwrite( $mytextFile, $mine ); fclose( $mytextFile );
792 fwrite( $yourtextFile, $yours ); fclose( $yourtextFile );
793
794 # Check for a conflict
795 $cmd = wfEscapeShellArg( $wgDiff3 ) . " -a --overlap-only " .
796 wfEscapeShellArg( $mytextName ) . " " .
797 wfEscapeShellArg( $oldtextName ) . " " .
798 wfEscapeShellArg( $yourtextName );
799 $handle = popen( $cmd, "r" );
800
801 if( fgets( $handle ) ){
802 $conflict = true;
803 } else {
804 $conflict = false;
805 }
806 pclose( $handle );
807
808 # Merge differences
809 $cmd = wfEscapeShellArg( $wgDiff3 ) . " -a -e --merge " .
810 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
811 $handle = popen( $cmd, "r" );
812 $result = "";
813 do {
814 $data = fread( $handle, 8192 );
815 if ( strlen( $data ) == 0 ) {
816 break;
817 }
818 $result .= $data;
819 } while ( true );
820 pclose( $handle );
821 unlink( $mytextName ); unlink( $oldtextName ); unlink( $yourtextName );
822 return ! $conflict;
823 }
824
825 function wfVarDump( $var )
826 {
827 global $wgOut;
828 $s = str_replace("\n","<br>\n", var_export( $var, true ) . "\n");
829 if ( headers_sent() || !@is_object( $wgOut ) ) {
830 print $s;
831 } else {
832 $wgOut->addHTML( $s );
833 }
834 }
835
836 # Provide a simple HTTP error.
837 function wfHttpError( $code, $label, $desc ) {
838 global $wgOut;
839 $wgOut->disable();
840 header( "HTTP/1.0 $code $label" );
841 header( "Status: $code $label" );
842 $wgOut->sendCacheControl();
843
844 # Don't send content if it's a HEAD request.
845 if( $_SERVER['REQUEST_METHOD'] == 'HEAD' ) {
846 header( "Content-type: text/plain" );
847 print "$desc\n";
848 }
849 }
850
851 # Converts an Accept-* header into an array mapping string values to quality factors
852 function wfAcceptToPrefs( $accept, $def = "*/*" ) {
853 # No arg means accept anything (per HTTP spec)
854 if( !$accept ) {
855 return array( $def => 1 );
856 }
857
858 $prefs = array();
859
860 $parts = explode( ",", $accept );
861
862 foreach( $parts as $part ) {
863 # FIXME: doesn't deal with params like 'text/html; level=1'
864 @list( $value, $qpart ) = explode( ";", $part );
865 if( !isset( $qpart ) ) {
866 $prefs[$value] = 1;
867 } elseif( preg_match( '/q\s*=\s*(\d*\.\d+)/', $qpart, $match ) ) {
868 $prefs[$value] = $match[1];
869 }
870 }
871
872 return $prefs;
873 }
874
875 /* private */ function mimeTypeMatch( $type, $avail ) {
876 if( array_key_exists($type, $avail) ) {
877 return $type;
878 } else {
879 $parts = explode( '/', $type );
880 if( array_key_exists( $parts[0] . '/*', $avail ) ) {
881 return $parts[0] . '/*';
882 } elseif( array_key_exists( '*/*', $avail ) ) {
883 return '*/*';
884 } else {
885 return NULL;
886 }
887 }
888 }
889
890 # FIXME: doesn't handle params like 'text/plain; charset=UTF-8'
891 # XXX: generalize to negotiate other stuff
892 function wfNegotiateType( $cprefs, $sprefs ) {
893 $combine = array();
894
895 foreach( array_keys($sprefs) as $type ) {
896 $parts = explode( '/', $type );
897 if( $parts[1] != '*' ) {
898 $ckey = mimeTypeMatch( $type, $cprefs );
899 if( $ckey ) {
900 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
901 }
902 }
903 }
904
905 foreach( array_keys( $cprefs ) as $type ) {
906 $parts = explode( '/', $type );
907 if( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
908 $skey = mimeTypeMatch( $type, $sprefs );
909 if( $skey ) {
910 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
911 }
912 }
913 }
914
915 $bestq = 0;
916 $besttype = NULL;
917
918 foreach( array_keys( $combine ) as $type ) {
919 if( $combine[$type] > $bestq ) {
920 $besttype = $type;
921 $bestq = $combine[$type];
922 }
923 }
924
925 return $besttype;
926 }
927
928 # Array lookup
929 # Returns an array where the values in the first array are replaced by the
930 # values in the second array with the corresponding keys
931 function wfArrayLookup( $a, $b )
932 {
933 return array_flip( array_intersect( array_flip( $a ), array_keys( $b ) ) );
934 }
935
936 ?>