wfImageUrl moved from Globalfunctions to Image
[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 include_once( "DatabaseFunctions.php" );
9 include_once( "UpdateClasses.php" );
10 include_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 $wgRandomSeeded = false;
40
41 function wfSeedRandom()
42 {
43 global $wgRandomSeeded;
44
45 if ( ! $wgRandomSeeded ) {
46 $seed = hexdec(substr(md5(microtime()),-8)) & 0x7fffffff;
47 mt_srand( $seed );
48 $wgRandomSeeded = true;
49 }
50 }
51
52 # Generates a URL from a URL-encoded title and a query string
53 # Title::getLocalURL() is preferred in most cases
54 #
55 function wfLocalUrl( $a, $q = "" )
56 {
57 global $wgServer, $wgScript, $wgArticlePath;
58
59 $a = str_replace( " ", "_", $a );
60
61 if ( "" == $a ) {
62 if( "" == $q ) {
63 $a = $wgScript;
64 } else {
65 $a = "{$wgScript}?{$q}";
66 }
67 } else if ( "" == $q ) {
68 $a = str_replace( "$1", $a, $wgArticlePath );
69 } else if ($wgScript != '' ) {
70 $a = "{$wgScript}?title={$a}&{$q}";
71 } else { //XXX ugly hack for toplevel wikis
72 $a = "/{$a}&{$q}";
73 }
74 return $a;
75 }
76
77 function wfLocalUrlE( $a, $q = "" )
78 {
79 return wfEscapeHTML( wfLocalUrl( $a, $q ) );
80 # die( "Call to obsolete function wfLocalUrlE()" );
81 }
82
83 function wfFullUrl( $a, $q = "" ) {
84 wfDebugDieBacktrace( "Call to obsolete function wfFullUrl(); use Title::getFullURL" );
85 }
86
87 function wfFullUrlE( $a, $q = "" ) {
88 wfDebugDieBacktrace( "Call to obsolete function wfFullUrlE(); use Title::getFullUrlE" );
89
90 }
91
92 function wfImagePath( $img )
93 {
94 global $wgUploadDirectory;
95
96 $nt = Title::newFromText( $img );
97 if( !$nt ) return "";
98
99 $name = $nt->getDBkey();
100 $hash = md5( $name );
101
102 $path = "{$wgUploadDirectory}/" . $hash{0} . "/" .
103 substr( $hash, 0, 2 ) . "/{$name}";
104 return $path;
105 }
106
107 function wfThumbUrl( $img )
108 {
109 global $wgUploadPath;
110
111 $nt = Title::newFromText( $img );
112 if( !$nt ) return "";
113
114 $name = $nt->getDBkey();
115 $hash = md5( $name );
116
117 $url = "{$wgUploadPath}/thumb/" . $hash{0} . "/" .
118 substr( $hash, 0, 2 ) . "/{$name}";
119 return wfUrlencode( $url );
120 }
121
122
123 function wfImageThumbUrl( $name, $subdir="thumb" )
124 {
125 global $wgUploadPath;
126
127 $hash = md5( $name );
128 $url = "{$wgUploadPath}/{$subdir}/" . $hash{0} . "/" .
129 substr( $hash, 0, 2 ) . "/{$name}";
130 return wfUrlencode($url);
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 function wfDebug( $text, $logonly = false )
177 {
178 global $wgOut, $wgDebugLogFile, $wgDebugComments, $wgProfileOnly;
179
180 if ( isset( $wgOut ) && $wgDebugComments && !$logonly ) {
181 $wgOut->debug( $text );
182 }
183 if ( "" != $wgDebugLogFile && !$wgProfileOnly ) {
184 error_log( $text, 3, $wgDebugLogFile );
185 }
186 }
187
188 function logProfilingData()
189 {
190 global $wgRequestTime, $wgDebugLogFile;
191 global $wgProfiling, $wgProfileStack, $wgProfileLimit, $wgUser;
192 $now = wfTime();
193
194 list( $usec, $sec ) = explode( " ", $wgRequestTime );
195 $start = (float)$sec + (float)$usec;
196 $elapsed = $now - $start;
197 if ( "" != $wgDebugLogFile ) {
198 $prof = wfGetProfilingOutput( $start, $elapsed );
199 $forward = "";
200 if( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) )
201 $forward = " forwarded for " . $_SERVER['HTTP_X_FORWARDED_FOR'];
202 if( !empty( $_SERVER['HTTP_CLIENT_IP'] ) )
203 $forward .= " client IP " . $_SERVER['HTTP_CLIENT_IP'];
204 if( !empty( $_SERVER['HTTP_FROM'] ) )
205 $forward .= " from " . $_SERVER['HTTP_FROM'];
206 if( $forward )
207 $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
208 if($wgUser->getId() == 0)
209 $forward .= " anon";
210 $log = sprintf( "%s\t%04.3f\t%s\n",
211 gmdate( "YmdHis" ), $elapsed,
212 urldecode( $_SERVER['REQUEST_URI'] . $forward ) );
213 error_log( $log . $prof, 3, $wgDebugLogFile );
214 }
215 }
216
217
218 function wfReadOnly()
219 {
220 global $wgReadOnlyFile;
221
222 if ( "" == $wgReadOnlyFile ) { return false; }
223 return is_file( $wgReadOnlyFile );
224 }
225
226 $wgReplacementKeys = array( "$1", "$2", "$3", "$4", "$5", "$6", "$7", "$8", "$9" );
227
228 # Get a message from anywhere
229 function wfMsg( $key ) {
230 $args = func_get_args();
231 if ( count( $args ) ) {
232 array_shift( $args );
233 }
234 return wfMsgReal( $key, $args, true );
235 }
236
237 # Get a message from the language file
238 function wfMsgNoDB( $key ) {
239 $args = func_get_args();
240 if ( count( $args ) ) {
241 array_shift( $args );
242 }
243 return wfMsgReal( $key, $args, false );
244 }
245
246 # Really get a message
247 function wfMsgReal( $key, $args, $useDB ) {
248 global $wgReplacementKeys, $wgMessageCache, $wgLang;
249
250 $fname = "wfMsg";
251 wfProfileIn( $fname );
252 if ( $wgMessageCache ) {
253 $message = $wgMessageCache->get( $key, $useDB );
254 } elseif ( $wgLang ) {
255 $message = $wgLang->getMessage( $key );
256 } else {
257 wfDebug( "No language object when getting $key\n" );
258 $message = "&lt;$key&gt;";
259 }
260
261 # Replace arguments
262 if( count( $args ) ) {
263 $message = str_replace( $wgReplacementKeys, $args, $message );
264 }
265 wfProfileOut( $fname );
266 return $message;
267 }
268
269 function wfCleanFormFields( $fields )
270 {
271 wfDebugDieBacktrace( "Call to obsolete wfCleanFormFields(). Use wgRequest instead..." );
272 }
273
274 function wfMungeQuotes( $in )
275 {
276 $out = str_replace( "%", "%25", $in );
277 $out = str_replace( "'", "%27", $out );
278 $out = str_replace( "\"", "%22", $out );
279 return $out;
280 }
281
282 function wfDemungeQuotes( $in )
283 {
284 $out = str_replace( "%22", "\"", $in );
285 $out = str_replace( "%27", "'", $out );
286 $out = str_replace( "%25", "%", $out );
287 return $out;
288 }
289
290 function wfCleanQueryVar( $var )
291 {
292 wfDebugDieBacktrace( "Call to obsolete function wfCleanQueryVar(); use wgRequest instead" );
293 }
294
295 function wfSpecialPage()
296 {
297 global $wgUser, $wgOut, $wgTitle, $wgLang;
298
299 /* FIXME: this list probably shouldn't be language-specific, per se */
300 $validSP = $wgLang->getValidSpecialPages();
301 $sysopSP = $wgLang->getSysopSpecialPages();
302 $devSP = $wgLang->getDeveloperSpecialPages();
303
304 $wgOut->setArticleRelated( false );
305 $wgOut->setRobotpolicy( "noindex,follow" );
306
307 $bits = split( "/", $wgTitle->getDBkey(), 2 );
308 $t = $bits[0];
309 if( empty( $bits[1] ) ) {
310 $par = NULL;
311 } else {
312 $par = $bits[1];
313 }
314
315 if ( array_key_exists( $t, $validSP ) ||
316 ( $wgUser->isSysop() && array_key_exists( $t, $sysopSP ) ) ||
317 ( $wgUser->isDeveloper() && array_key_exists( $t, $devSP ) ) ) {
318 if($par !== NULL)
319 $wgTitle = Title::makeTitle( Namespace::getSpecial(), $t );
320
321 $wgOut->setPageTitle( wfMsg( strtolower( $wgTitle->getText() ) ) );
322
323 $inc = "Special" . $t . ".php";
324 include_once( $inc );
325 $call = "wfSpecial" . $t;
326 $call( $par );
327 } else if ( array_key_exists( $t, $sysopSP ) ) {
328 $wgOut->sysopRequired();
329 } else if ( array_key_exists( $t, $devSP ) ) {
330 $wgOut->developerRequired();
331 } else {
332 $wgOut->errorpage( "nosuchspecialpage", "nospecialpagetext" );
333 }
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 $archive = "{$wgUploadDirectory}/{$subdir}";
459 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
460 $archive .= "/" . $hash{0};
461 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
462 $archive .= "/" . substr( $hash, 0, 2 );
463 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
464
465 umask( $oldumask );
466 return $archive;
467 }
468
469 function wfRecordUpload( $name, $oldver, $size, $desc, $copyStatus = "", $source = "" )
470 {
471 global $wgUser, $wgLang, $wgTitle, $wgOut, $wgDeferredUpdateList;
472 global $wgUseCopyrightUpload;
473
474 $fname = "wfRecordUpload";
475
476 $sql = "SELECT img_name,img_size,img_timestamp,img_description,img_user," .
477 "img_user_text FROM image WHERE img_name='" . wfStrencode( $name ) . "'";
478 $res = wfQuery( $sql, DB_READ, $fname );
479
480 $now = wfTimestampNow();
481 $won = wfInvertTimestamp( $now );
482 $size = IntVal( $size );
483
484 if ( $wgUseCopyrightUpload )
485 {
486 $textdesc = "== " . wfMsg ( "filedesc" ) . " ==\n" . $desc . "\n" .
487 "== " . wfMsg ( "filestatus" ) . " ==\n" . $copyStatus . "\n" .
488 "== " . wfMsg ( "filesource" ) . " ==\n" . $source ;
489 }
490 else $textdesc = $desc ;
491
492 $now = wfTimestampNow();
493 $won = wfInvertTimestamp( $now );
494
495 if ( 0 == wfNumRows( $res ) ) {
496 $sql = "INSERT INTO image (img_name,img_size,img_timestamp," .
497 "img_description,img_user,img_user_text) VALUES ('" .
498 wfStrencode( $name ) . "',$size,'{$now}','" .
499 wfStrencode( $desc ) . "', '" . $wgUser->getID() .
500 "', '" . wfStrencode( $wgUser->getName() ) . "')";
501 wfQuery( $sql, DB_WRITE, $fname );
502
503 $sql = "SELECT cur_id,cur_text FROM cur WHERE cur_namespace=" .
504 Namespace::getImage() . " AND cur_title='" .
505 wfStrencode( $name ) . "'";
506 $res = wfQuery( $sql, DB_READ, $fname );
507 if ( 0 == wfNumRows( $res ) ) {
508 $common =
509 Namespace::getImage() . ",'" .
510 wfStrencode( $name ) . "','" .
511 wfStrencode( $desc ) . "','" . $wgUser->getID() . "','" .
512 wfStrencode( $wgUser->getName() ) . "','" . $now .
513 "',1";
514 $sql = "INSERT INTO cur (cur_namespace,cur_title," .
515 "cur_comment,cur_user,cur_user_text,cur_timestamp,cur_is_new," .
516 "cur_text,inverse_timestamp,cur_touched) VALUES (" .
517 $common .
518 ",'" . wfStrencode( $textdesc ) . "','{$won}','{$now}')";
519 wfQuery( $sql, DB_WRITE, $fname );
520 $id = wfInsertId() or 0; # We should throw an error instead
521
522 $titleObj = Title::makeTitle( NS_IMAGE, $name );
523 RecentChange::notifyNew( $now, $titleObj, 0, $wgUser, $desc );
524
525 $u = new SearchUpdate( $id, $name, $desc );
526 $u->doUpdate();
527 }
528 } else {
529 $s = wfFetchObject( $res );
530
531 $sql = "INSERT INTO oldimage (oi_name,oi_archive_name,oi_size," .
532 "oi_timestamp,oi_description,oi_user,oi_user_text) VALUES ('" .
533 wfStrencode( $s->img_name ) . "','" .
534 wfStrencode( $oldver ) .
535 "',{$s->img_size},'{$s->img_timestamp}','" .
536 wfStrencode( $s->img_description ) . "','" .
537 wfStrencode( $s->img_user ) . "','" .
538 wfStrencode( $s->img_user_text) . "')";
539 wfQuery( $sql, DB_WRITE, $fname );
540
541 $sql = "UPDATE image SET img_size={$size}," .
542 "img_timestamp='" . wfTimestampNow() . "',img_user='" .
543 $wgUser->getID() . "',img_user_text='" .
544 wfStrencode( $wgUser->getName() ) . "', img_description='" .
545 wfStrencode( $desc ) . "' WHERE img_name='" .
546 wfStrencode( $name ) . "'";
547 wfQuery( $sql, DB_WRITE, $fname );
548
549 $sql = "UPDATE cur SET cur_touched='{$now}' WHERE cur_namespace=" .
550 Namespace::getImage() . " AND cur_title='" .
551 wfStrencode( $name ) . "'";
552 wfQuery( $sql, DB_WRITE, $fname );
553 }
554
555 $log = new LogPage( wfMsg( "uploadlogpage" ), wfMsg( "uploadlogpagetext" ) );
556 $da = wfMsg( "uploadedimage", "[[:" . $wgLang->getNsText(
557 Namespace::getImage() ) . ":{$name}|{$name}]]" );
558 $ta = wfMsg( "uploadedimage", $name );
559 $log->addEntry( $da, $desc, $ta );
560 }
561
562
563 /* Some generic result counters, pulled out of SearchEngine */
564
565 function wfShowingResults( $offset, $limit )
566 {
567 global $wgLang;
568 return wfMsg( "showingresults", $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+1 ) );
569 }
570
571 function wfShowingResultsNum( $offset, $limit, $num )
572 {
573 global $wgLang;
574 return wfMsg( "showingresultsnum", $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+1 ), $wgLang->formatNum( $num ) );
575 }
576
577 function wfViewPrevNext( $offset, $limit, $link, $query = "", $atend = false )
578 {
579 global $wgUser, $wgLang;
580 $fmtLimit = $wgLang->formatNum( $limit );
581 $prev = wfMsg( "prevn", $fmtLimit );
582 $next = wfMsg( "nextn", $fmtLimit );
583 $link = wfUrlencode( $link );
584
585 $sk = $wgUser->getSkin();
586 if ( 0 != $offset ) {
587 $po = $offset - $limit;
588 if ( $po < 0 ) { $po = 0; }
589 $q = "limit={$limit}&offset={$po}";
590 if ( "" != $query ) { $q .= "&{$query}"; }
591 $plink = "<a href=\"" . wfLocalUrlE( $link, $q ) . "\">{$prev}</a>";
592 } else { $plink = $prev; }
593
594 $no = $offset + $limit;
595 $q = "limit={$limit}&offset={$no}";
596 if ( "" != $query ) { $q .= "&{$query}"; }
597
598 if ( $atend ) {
599 $nlink = $next;
600 } else {
601 $nlink = "<a href=\"" . wfLocalUrlE( $link, $q ) . "\">{$next}</a>";
602 }
603 $nums = wfNumLink( $offset, 20, $link , $query ) . " | " .
604 wfNumLink( $offset, 50, $link, $query ) . " | " .
605 wfNumLink( $offset, 100, $link, $query ) . " | " .
606 wfNumLink( $offset, 250, $link, $query ) . " | " .
607 wfNumLink( $offset, 500, $link, $query );
608
609 return wfMsg( "viewprevnext", $plink, $nlink, $nums );
610 }
611
612 function wfNumLink( $offset, $limit, $link, $query = "" )
613 {
614 global $wgUser, $wgLang;
615 if ( "" == $query ) { $q = ""; }
616 else { $q = "{$query}&"; }
617 $q .= "limit={$limit}&offset={$offset}";
618
619 $fmtLimit = $wgLang->formatNum( $limit );
620 $s = "<a href=\"" . wfLocalUrlE( $link, $q ) . "\">{$fmtLimit}</a>";
621 return $s;
622 }
623
624 function wfClientAcceptsGzip() {
625 global $wgUseGzip;
626 if( $wgUseGzip ) {
627 # FIXME: we may want to blacklist some broken browsers
628 if( preg_match(
629 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
630 $_SERVER["HTTP_ACCEPT_ENCODING"],
631 $m ) ) {
632 if( ( $m[1] == "q" ) && ( $m[2] == 0 ) ) return false;
633 wfDebug( " accepts gzip\n" );
634 return true;
635 }
636 }
637 return false;
638 }
639
640 # Yay, more global functions!
641 function wfCheckLimits( $deflimit = 50, $optionname = "rclimit" ) {
642 global $wgUser, $wgRequest;
643
644 $limit = $wgRequest->getInt( 'limit', 0 );
645 if( $limit < 0 ) $limit = 0;
646 if( ( $limit == 0 ) && ( $optionname != "" ) ) {
647 $limit = (int)$wgUser->getOption( $optionname );
648 }
649 if( $limit <= 0 ) $limit = $deflimit;
650 if( $limit > 5000 ) $limit = 5000; # We have *some* limits...
651
652 $offset = $wgRequest->getInt( 'offset', 0 );
653 if( $offset < 0 ) $offset = 0;
654 if( $offset > 65000 ) $offset = 65000; # do we need a max? what?
655
656 return array( $limit, $offset );
657 }
658
659 # Escapes the given text so that it may be output using addWikiText()
660 # without any linking, formatting, etc. making its way through. This
661 # is achieved by substituting certain characters with HTML entities.
662 # As required by the callers, <nowiki> is not used. It currently does
663 # not filter out characters which have special meaning only at the
664 # start of a line, such as "*".
665 function wfEscapeWikiText( $text )
666 {
667 $text = str_replace(
668 array( '[', '|', "'", 'ISBN ' , '://' , "\n=" ),
669 array( '&#91;', '&#124;', '&#39;', 'ISBN&#32;', '&#58;//' , "\n&#61;" ),
670 htmlspecialchars($text) );
671 return $text;
672 }
673
674 function wfQuotedPrintable( $string, $charset = "" )
675 {
676 # Probably incomplete; see RFC 2045
677 if( empty( $charset ) ) {
678 global $wgInputEncoding;
679 $charset = $wgInputEncoding;
680 }
681 $charset = strtoupper( $charset );
682 $charset = str_replace( "ISO-8859", "ISO8859", $charset ); // ?
683
684 $illegal = '\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\xff=';
685 $replace = $illegal . '\t ?_';
686 if( !preg_match( "/[$illegal]/", $string ) ) return $string;
687 $out = "=?$charset?Q?";
688 $out .= preg_replace( "/([$replace])/e", 'sprintf("=%02X",ord("$1"))', $string );
689 $out .= "?=";
690 return $out;
691 }
692
693 function wfTime(){
694 $st = explode( " ", microtime() );
695 return (float)$st[0] + (float)$st[1];
696 }
697
698 # Changes the first character to an HTML entity
699 function wfHtmlEscapeFirst( $text ) {
700 $ord = ord($text);
701 $newText = substr($text, 1);
702 return "&#$ord;$newText";
703 }
704
705 # Sets dest to source and returns the original value of dest
706 function wfSetVar( &$dest, $source )
707 {
708 $temp = $dest;
709 $dest = $source;
710 return $temp;
711 }
712
713 # Sets dest to a reference to source and returns the original dest
714 function &wfSetRef( &$dest, &$source )
715 {
716 $temp =& $dest;
717 $dest =& $source;
718 return $temp;
719 }
720
721 # This function takes two arrays as input, and returns a CGI-style string, e.g.
722 # "days=7&limit=100". Options in the first array override options in the second.
723 # Options set to "" will not be output.
724 function wfArrayToCGI( $array1, $array2 = NULL )
725 {
726 if ( !is_null( $array2 ) ) {
727 $array1 = $array1 + $array2;
728 }
729
730 $cgi = "";
731 foreach ( $array1 as $key => $value ) {
732 if ( "" !== $value ) {
733 if ( "" != $cgi ) {
734 $cgi .= "&";
735 }
736 $cgi .= "{$key}={$value}";
737 }
738 }
739 return $cgi;
740 }
741
742 # This is obsolete, use SquidUpdate::purge()
743 function wfPurgeSquidServers ($urlArr) {
744 SquidUpdate::purge( $urlArr );
745 }
746
747 # Windows-compatible version of escapeshellarg()
748 function wfEscapeShellArg( )
749 {
750 $args = func_get_args();
751 $first = true;
752 $retVal = "";
753 foreach ( $args as $arg ) {
754 if ( !$first ) {
755 $retVal .= " ";
756 } else {
757 $first = false;
758 }
759
760 if (substr(php_uname(), 0, 7) == "Windows") {
761 $retVal .= "\"$arg\"";
762 } else {
763 $retVal .= escapeshellarg( $arg );
764 }
765 }
766 return $retVal;
767 }
768
769 # wfMerge attempts to merge differences between three texts.
770 # Returns true for a clean merge and false for failure or a conflict.
771
772 function wfMerge( $old, $mine, $yours, &$result ){
773 global $wgDiff3;
774
775 # This check may also protect against code injection in
776 # case of broken installations.
777 if(! file_exists( $wgDiff3 ) ){
778 return false;
779 }
780
781 # Make temporary files
782 $td = "/tmp/";
783 $oldtextFile = fopen( $oldtextName = tempnam( $td, "merge-old-" ), "w" );
784 $mytextFile = fopen( $mytextName = tempnam( $td, "merge-mine-" ), "w" );
785 $yourtextFile = fopen( $yourtextName = tempnam( $td, "merge-your-" ), "w" );
786
787 fwrite( $oldtextFile, $old ); fclose( $oldtextFile );
788 fwrite( $mytextFile, $mine ); fclose( $mytextFile );
789 fwrite( $yourtextFile, $yours ); fclose( $yourtextFile );
790
791 # Check for a conflict
792 $cmd = wfEscapeShellArg( $wgDiff3 ) . " -a --overlap-only " .
793 wfEscapeShellArg( $mytextName ) . " " .
794 wfEscapeShellArg( $oldtextName ) . " " .
795 wfEscapeShellArg( $yourtextName );
796 $handle = popen( $cmd, "r" );
797
798 if( fgets( $handle ) ){
799 $conflict = true;
800 } else {
801 $conflict = false;
802 }
803 pclose( $handle );
804
805 # Merge differences
806 $cmd = wfEscapeShellArg( $wgDiff3 ) . " -a -e --merge " .
807 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
808 $handle = popen( $cmd, "r" );
809 $result = "";
810 do {
811 $data = fread( $handle, 8192 );
812 if ( strlen( $data ) == 0 ) {
813 break;
814 }
815 $result .= $data;
816 } while ( true );
817 pclose( $handle );
818 unlink( $mytextName ); unlink( $oldtextName ); unlink( $yourtextName );
819 return ! $conflict;
820 }
821
822 function wfVarDump( $var )
823 {
824 global $wgOut;
825 $s = str_replace("\n","<br>\n", var_export( $var, true ) . "\n");
826 if ( headers_sent() || !@is_object( $wgOut ) ) {
827 print $s;
828 } else {
829 $wgOut->addHTML( $s );
830 }
831 }
832
833 # Provide a simple HTTP error.
834 function wfHttpError( $code, $label, $desc ) {
835 global $wgOut;
836 $wgOut->disable();
837 header( "HTTP/1.0 $code $label" );
838 header( "Status: $code $label" );
839 $wgOut->sendCacheControl();
840
841 # Don't send content if it's a HEAD request.
842 if( $_SERVER['REQUEST_METHOD'] == 'HEAD' ) {
843 header( "Content-type: text/plain" );
844 print "$desc\n";
845 }
846 }
847
848 # Converts an Accept-* header into an array mapping string values to quality factors
849 function wfAcceptToPrefs( $accept, $def = "*/*" ) {
850 # No arg means accept anything (per HTTP spec)
851 if( !$accept ) {
852 return array( $def => 1 );
853 }
854
855 $prefs = array();
856
857 $parts = explode( ",", $accept );
858
859 foreach( $parts as $part ) {
860 # FIXME: doesn't deal with params like 'text/html; level=1'
861 @list( $value, $qpart ) = explode( ";", $part );
862 if( !isset( $qpart ) ) {
863 $prefs[$value] = 1;
864 } elseif( preg_match( '/q\s*=\s*(\d*\.\d+)/', $qpart, $match ) ) {
865 $prefs[$value] = $match[1];
866 }
867 }
868
869 return $prefs;
870 }
871
872 /* private */ function mimeTypeMatch( $type, $avail ) {
873 if( array_key_exists($type, $avail) ) {
874 return $type;
875 } else {
876 $parts = explode( '/', $type );
877 if( array_key_exists( $parts[0] . '/*', $avail ) ) {
878 return $parts[0] . '/*';
879 } elseif( array_key_exists( '*/*', $avail ) ) {
880 return '*/*';
881 } else {
882 return NULL;
883 }
884 }
885 }
886
887 # FIXME: doesn't handle params like 'text/plain; charset=UTF-8'
888 # XXX: generalize to negotiate other stuff
889 function wfNegotiateType( $cprefs, $sprefs ) {
890 $combine = array();
891
892 foreach( array_keys($sprefs) as $type ) {
893 $parts = explode( '/', $type );
894 if( $parts[1] != '*' ) {
895 $ckey = mimeTypeMatch( $type, $cprefs );
896 if( $ckey ) {
897 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
898 }
899 }
900 }
901
902 foreach( array_keys( $cprefs ) as $type ) {
903 $parts = explode( '/', $type );
904 if( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
905 $skey = mimeTypeMatch( $type, $sprefs );
906 if( $skey ) {
907 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
908 }
909 }
910 }
911
912 $bestq = 0;
913 $besttype = NULL;
914
915 foreach( array_keys( $combine ) as $type ) {
916 if( $combine[$type] > $bestq ) {
917 $besttype = $type;
918 $bestq = $combine[$type];
919 }
920 }
921
922 return $besttype;
923 }
924
925 ?>