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