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