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