81739bafef683dee053dd95cd33e15ffce7635d3
[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 wfImageUrl( $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}/" . $hash{0} . "/" .
103 substr( $hash, 0, 2 ) . "/{$name}";
104 return wfUrlencode( $url );
105 }
106
107 function wfImagePath( $img )
108 {
109 global $wgUploadDirectory;
110
111 $nt = Title::newFromText( $img );
112 if( !$nt ) return "";
113
114 $name = $nt->getDBkey();
115 $hash = md5( $name );
116
117 $path = "{$wgUploadDirectory}/" . $hash{0} . "/" .
118 substr( $hash, 0, 2 ) . "/{$name}";
119 return $path;
120 }
121
122 function wfThumbUrl( $img )
123 {
124 global $wgUploadPath;
125
126 $nt = Title::newFromText( $img );
127 if( !$nt ) return "";
128
129 $name = $nt->getDBkey();
130 $hash = md5( $name );
131
132 $url = "{$wgUploadPath}/thumb/" . $hash{0} . "/" .
133 substr( $hash, 0, 2 ) . "/{$name}";
134 return wfUrlencode( $url );
135 }
136
137
138 function wfImageThumbUrl( $name, $subdir="thumb" )
139 {
140 global $wgUploadPath;
141
142 $hash = md5( $name );
143 $url = "{$wgUploadPath}/{$subdir}/" . $hash{0} . "/" .
144 substr( $hash, 0, 2 ) . "/{$name}";
145 return wfUrlencode($url);
146 }
147
148 function wfImageArchiveUrl( $name )
149 {
150 global $wgUploadPath;
151
152 $hash = md5( substr( $name, 15) );
153 $url = "{$wgUploadPath}/archive/" . $hash{0} . "/" .
154 substr( $hash, 0, 2 ) . "/{$name}";
155 return wfUrlencode($url);
156 }
157
158 function wfUrlencode ( $s )
159 {
160 $s = urlencode( $s );
161 $s = preg_replace( "/%3[Aa]/", ":", $s );
162 $s = preg_replace( "/%2[Ff]/", "/", $s );
163
164 return $s;
165 }
166
167 function wfUtf8Sequence($codepoint) {
168 if($codepoint < 0x80) return chr($codepoint);
169 if($codepoint < 0x800) return chr($codepoint >> 6 & 0x3f | 0xc0) .
170 chr($codepoint & 0x3f | 0x80);
171 if($codepoint < 0x10000) return chr($codepoint >> 12 & 0x0f | 0xe0) .
172 chr($codepoint >> 6 & 0x3f | 0x80) .
173 chr($codepoint & 0x3f | 0x80);
174 if($codepoint < 0x100000) return chr($codepoint >> 18 & 0x07 | 0xf0) . # Double-check this
175 chr($codepoint >> 12 & 0x3f | 0x80) .
176 chr($codepoint >> 6 & 0x3f | 0x80) .
177 chr($codepoint & 0x3f | 0x80);
178 # Doesn't yet handle outside the BMP
179 return "&#$codepoint;";
180 }
181
182 function wfMungeToUtf8($string) {
183 global $wgInputEncoding; # This is debatable
184 #$string = iconv($wgInputEncoding, "UTF-8", $string);
185 $string = preg_replace ( '/&#([0-9]+);/e', 'wfUtf8Sequence($1)', $string );
186 $string = preg_replace ( '/&#x([0-9a-f]+);/ie', 'wfUtf8Sequence(0x$1)', $string );
187 # Should also do named entities here
188 return $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 include_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 $archive = "{$wgUploadDirectory}/{$subdir}";
474 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
475 $archive .= "/" . $hash{0};
476 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
477 $archive .= "/" . substr( $hash, 0, 2 );
478 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
479
480 umask( $oldumask );
481 return $archive;
482 }
483
484 function wfRecordUpload( $name, $oldver, $size, $desc, $copyStatus = "", $source = "" )
485 {
486 global $wgUser, $wgLang, $wgTitle, $wgOut, $wgDeferredUpdateList;
487 global $wgUseCopyrightUpload;
488
489 $fname = "wfRecordUpload";
490
491 $sql = "SELECT img_name,img_size,img_timestamp,img_description,img_user," .
492 "img_user_text FROM image WHERE img_name='" . wfStrencode( $name ) . "'";
493 $res = wfQuery( $sql, DB_READ, $fname );
494
495 $now = wfTimestampNow();
496 $won = wfInvertTimestamp( $now );
497 $size = IntVal( $size );
498
499 if ( $wgUseCopyrightUpload )
500 {
501 $textdesc = "== " . wfMsg ( "filedesc" ) . " ==\n" . $desc . "\n" .
502 "== " . wfMsg ( "filestatus" ) . " ==\n" . $copyStatus . "\n" .
503 "== " . wfMsg ( "filesource" ) . " ==\n" . $source ;
504 }
505 else $textdesc = $desc ;
506
507 $now = wfTimestampNow();
508 $won = wfInvertTimestamp( $now );
509
510 if ( 0 == wfNumRows( $res ) ) {
511 $sql = "INSERT INTO image (img_name,img_size,img_timestamp," .
512 "img_description,img_user,img_user_text) VALUES ('" .
513 wfStrencode( $name ) . "',$size,'{$now}','" .
514 wfStrencode( $desc ) . "', '" . $wgUser->getID() .
515 "', '" . wfStrencode( $wgUser->getName() ) . "')";
516 wfQuery( $sql, DB_WRITE, $fname );
517
518 $sql = "SELECT cur_id,cur_text FROM cur WHERE cur_namespace=" .
519 Namespace::getImage() . " AND cur_title='" .
520 wfStrencode( $name ) . "'";
521 $res = wfQuery( $sql, DB_READ, $fname );
522 if ( 0 == wfNumRows( $res ) ) {
523 $common =
524 Namespace::getImage() . ",'" .
525 wfStrencode( $name ) . "','" .
526 wfStrencode( $desc ) . "','" . $wgUser->getID() . "','" .
527 wfStrencode( $wgUser->getName() ) . "','" . $now .
528 "',1";
529 $sql = "INSERT INTO cur (cur_namespace,cur_title," .
530 "cur_comment,cur_user,cur_user_text,cur_timestamp,cur_is_new," .
531 "cur_text,inverse_timestamp,cur_touched) VALUES (" .
532 $common .
533 ",'" . wfStrencode( $textdesc ) . "','{$won}','{$now}')";
534 wfQuery( $sql, DB_WRITE, $fname );
535 $id = wfInsertId() or 0; # We should throw an error instead
536
537 $titleObj = Title::makeTitle( NS_IMAGE, $name );
538 RecentChange::notifyNew( $now, $titleObj, 0, $wgUser, $desc );
539
540 $u = new SearchUpdate( $id, $name, $desc );
541 $u->doUpdate();
542 }
543 } else {
544 $s = wfFetchObject( $res );
545
546 $sql = "INSERT INTO oldimage (oi_name,oi_archive_name,oi_size," .
547 "oi_timestamp,oi_description,oi_user,oi_user_text) VALUES ('" .
548 wfStrencode( $s->img_name ) . "','" .
549 wfStrencode( $oldver ) .
550 "',{$s->img_size},'{$s->img_timestamp}','" .
551 wfStrencode( $s->img_description ) . "','" .
552 wfStrencode( $s->img_user ) . "','" .
553 wfStrencode( $s->img_user_text) . "')";
554 wfQuery( $sql, DB_WRITE, $fname );
555
556 $sql = "UPDATE image SET img_size={$size}," .
557 "img_timestamp='" . wfTimestampNow() . "',img_user='" .
558 $wgUser->getID() . "',img_user_text='" .
559 wfStrencode( $wgUser->getName() ) . "', img_description='" .
560 wfStrencode( $desc ) . "' WHERE img_name='" .
561 wfStrencode( $name ) . "'";
562 wfQuery( $sql, DB_WRITE, $fname );
563
564 $sql = "UPDATE cur SET cur_touched='{$now}' WHERE cur_namespace=" .
565 Namespace::getImage() . " AND cur_title='" .
566 wfStrencode( $name ) . "'";
567 wfQuery( $sql, DB_WRITE, $fname );
568 }
569
570 $log = new LogPage( wfMsg( "uploadlogpage" ), wfMsg( "uploadlogpagetext" ) );
571 $da = wfMsg( "uploadedimage", "[[:" . $wgLang->getNsText(
572 Namespace::getImage() ) . ":{$name}|{$name}]]" );
573 $ta = wfMsg( "uploadedimage", $name );
574 $log->addEntry( $da, $desc, $ta );
575 }
576
577
578 /* Some generic result counters, pulled out of SearchEngine */
579
580 function wfShowingResults( $offset, $limit )
581 {
582 global $wgLang;
583 return wfMsg( "showingresults", $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+1 ) );
584 }
585
586 function wfShowingResultsNum( $offset, $limit, $num )
587 {
588 global $wgLang;
589 return wfMsg( "showingresultsnum", $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+1 ), $wgLang->formatNum( $num ) );
590 }
591
592 function wfViewPrevNext( $offset, $limit, $link, $query = "", $atend = false )
593 {
594 global $wgUser, $wgLang;
595 $fmtLimit = $wgLang->formatNum( $limit );
596 $prev = wfMsg( "prevn", $fmtLimit );
597 $next = wfMsg( "nextn", $fmtLimit );
598 $link = wfUrlencode( $link );
599
600 $sk = $wgUser->getSkin();
601 if ( 0 != $offset ) {
602 $po = $offset - $limit;
603 if ( $po < 0 ) { $po = 0; }
604 $q = "limit={$limit}&offset={$po}";
605 if ( "" != $query ) { $q .= "&{$query}"; }
606 $plink = "<a href=\"" . wfLocalUrlE( $link, $q ) . "\">{$prev}</a>";
607 } else { $plink = $prev; }
608
609 $no = $offset + $limit;
610 $q = "limit={$limit}&offset={$no}";
611 if ( "" != $query ) { $q .= "&{$query}"; }
612
613 if ( $atend ) {
614 $nlink = $next;
615 } else {
616 $nlink = "<a href=\"" . wfLocalUrlE( $link, $q ) . "\">{$next}</a>";
617 }
618 $nums = wfNumLink( $offset, 20, $link , $query ) . " | " .
619 wfNumLink( $offset, 50, $link, $query ) . " | " .
620 wfNumLink( $offset, 100, $link, $query ) . " | " .
621 wfNumLink( $offset, 250, $link, $query ) . " | " .
622 wfNumLink( $offset, 500, $link, $query );
623
624 return wfMsg( "viewprevnext", $plink, $nlink, $nums );
625 }
626
627 function wfNumLink( $offset, $limit, $link, $query = "" )
628 {
629 global $wgUser, $wgLang;
630 if ( "" == $query ) { $q = ""; }
631 else { $q = "{$query}&"; }
632 $q .= "limit={$limit}&offset={$offset}";
633
634 $fmtLimit = $wgLang->formatNum( $limit );
635 $s = "<a href=\"" . wfLocalUrlE( $link, $q ) . "\">{$fmtLimit}</a>";
636 return $s;
637 }
638
639 function wfClientAcceptsGzip() {
640 global $wgUseGzip;
641 if( $wgUseGzip ) {
642 # FIXME: we may want to blacklist some broken browsers
643 if( preg_match(
644 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
645 $_SERVER["HTTP_ACCEPT_ENCODING"],
646 $m ) ) {
647 if( ( $m[1] == "q" ) && ( $m[2] == 0 ) ) return false;
648 wfDebug( " accepts gzip\n" );
649 return true;
650 }
651 }
652 return false;
653 }
654
655 # Yay, more global functions!
656 function wfCheckLimits( $deflimit = 50, $optionname = "rclimit" ) {
657 global $wgUser, $wgRequest;
658
659 $limit = $wgRequest->getInt( 'limit', 0 );
660 if( $limit < 0 ) $limit = 0;
661 if( ( $limit == 0 ) && ( $optionname != "" ) ) {
662 $limit = (int)$wgUser->getOption( $optionname );
663 }
664 if( $limit <= 0 ) $limit = $deflimit;
665 if( $limit > 5000 ) $limit = 5000; # We have *some* limits...
666
667 $offset = $wgRequest->getInt( 'offset', 0 );
668 if( $offset < 0 ) $offset = 0;
669 if( $offset > 65000 ) $offset = 65000; # do we need a max? what?
670
671 return array( $limit, $offset );
672 }
673
674 # Escapes the given text so that it may be output using addWikiText()
675 # without any linking, formatting, etc. making its way through. This
676 # is achieved by substituting certain characters with HTML entities.
677 # As required by the callers, <nowiki> is not used. It currently does
678 # not filter out characters which have special meaning only at the
679 # start of a line, such as "*".
680 function wfEscapeWikiText( $text )
681 {
682 $text = str_replace(
683 array( '[', '|', "'", 'ISBN ' , '://' , "\n=" ),
684 array( '&#91;', '&#124;', '&#39;', 'ISBN&#32;', '&#58;//' , "\n&#61;" ),
685 htmlspecialchars($text) );
686 return $text;
687 }
688
689 function wfQuotedPrintable( $string, $charset = "" )
690 {
691 # Probably incomplete; see RFC 2045
692 if( empty( $charset ) ) {
693 global $wgInputEncoding;
694 $charset = $wgInputEncoding;
695 }
696 $charset = strtoupper( $charset );
697 $charset = str_replace( "ISO-8859", "ISO8859", $charset ); // ?
698
699 $illegal = '\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\xff=';
700 $replace = $illegal . '\t ?_';
701 if( !preg_match( "/[$illegal]/", $string ) ) return $string;
702 $out = "=?$charset?Q?";
703 $out .= preg_replace( "/([$replace])/e", 'sprintf("=%02X",ord("$1"))', $string );
704 $out .= "?=";
705 return $out;
706 }
707
708 function wfTime(){
709 $st = explode( " ", microtime() );
710 return (float)$st[0] + (float)$st[1];
711 }
712
713 # Changes the first character to an HTML entity
714 function wfHtmlEscapeFirst( $text ) {
715 $ord = ord($text);
716 $newText = substr($text, 1);
717 return "&#$ord;$newText";
718 }
719
720 # Sets dest to source and returns the original value of dest
721 function wfSetVar( &$dest, $source )
722 {
723 $temp = $dest;
724 $dest = $source;
725 return $temp;
726 }
727
728 # Sets dest to a reference to source and returns the original dest
729 function &wfSetRef( &$dest, &$source )
730 {
731 $temp =& $dest;
732 $dest =& $source;
733 return $temp;
734 }
735
736 # This function takes two arrays as input, and returns a CGI-style string, e.g.
737 # "days=7&limit=100". Options in the first array override options in the second.
738 # Options set to "" will not be output.
739 function wfArrayToCGI( $array1, $array2 = NULL )
740 {
741 if ( !is_null( $array2 ) ) {
742 $array1 = $array1 + $array2;
743 }
744
745 $cgi = "";
746 foreach ( $array1 as $key => $value ) {
747 if ( "" !== $value ) {
748 if ( "" != $cgi ) {
749 $cgi .= "&";
750 }
751 $cgi .= "{$key}={$value}";
752 }
753 }
754 return $cgi;
755 }
756
757 # This is obsolete, use SquidUpdate::purge()
758 function wfPurgeSquidServers ($urlArr) {
759 SquidUpdate::purge( $urlArr );
760 }
761
762 # Windows-compatible version of escapeshellarg()
763 function wfEscapeShellArg( )
764 {
765 $args = func_get_args();
766 $first = true;
767 $retVal = "";
768 foreach ( $args as $arg ) {
769 if ( !$first ) {
770 $retVal .= " ";
771 } else {
772 $first = false;
773 }
774
775 if (substr(php_uname(), 0, 7) == "Windows") {
776 $retVal .= "\"$arg\"";
777 } else {
778 $retVal .= escapeshellarg( $arg );
779 }
780 }
781 return $retVal;
782 }
783
784 # wfMerge attempts to merge differences between three texts.
785 # Returns true for a clean merge and false for failure or a conflict.
786
787 function wfMerge( $old, $mine, $yours, &$result ){
788 global $wgDiff3;
789
790 # This check may also protect against code injection in
791 # case of broken installations.
792 if(! file_exists( $wgDiff3 ) ){
793 return false;
794 }
795
796 # Make temporary files
797 $td = "/tmp/";
798 $oldtextFile = fopen( $oldtextName = tempnam( $td, "merge-old-" ), "w" );
799 $mytextFile = fopen( $mytextName = tempnam( $td, "merge-mine-" ), "w" );
800 $yourtextFile = fopen( $yourtextName = tempnam( $td, "merge-your-" ), "w" );
801
802 fwrite( $oldtextFile, $old ); fclose( $oldtextFile );
803 fwrite( $mytextFile, $mine ); fclose( $mytextFile );
804 fwrite( $yourtextFile, $yours ); fclose( $yourtextFile );
805
806 # Check for a conflict
807 $cmd = wfEscapeShellArg( $wgDiff3 ) . " -a --overlap-only " .
808 wfEscapeShellArg( $mytextName ) . " " .
809 wfEscapeShellArg( $oldtextName ) . " " .
810 wfEscapeShellArg( $yourtextName );
811 $handle = popen( $cmd, "r" );
812
813 if( fgets( $handle ) ){
814 $conflict = true;
815 } else {
816 $conflict = false;
817 }
818 pclose( $handle );
819
820 # Merge differences
821 $cmd = wfEscapeShellArg( $wgDiff3 ) . " -a -e --merge " .
822 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
823 $handle = popen( $cmd, "r" );
824 $result = "";
825 do {
826 $data = fread( $handle, 8192 );
827 if ( strlen( $data ) == 0 ) {
828 break;
829 }
830 $result .= $data;
831 } while ( true );
832 pclose( $handle );
833 unlink( $mytextName ); unlink( $oldtextName ); unlink( $yourtextName );
834 return ! $conflict;
835 }
836
837 function wfVarDump( $var )
838 {
839 global $wgOut;
840 $s = str_replace("\n","<br>\n", var_export( $var, true ) . "\n");
841 if ( headers_sent() || !@is_object( $wgOut ) ) {
842 print $s;
843 } else {
844 $wgOut->addHTML( $s );
845 }
846 }
847
848 ?>