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