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