Suppress PHP warnings on failure to create thumbnail subdirectories. This should...
[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
434 # Suppress warning messages here; if the file itself can't
435 # be written we'll worry about it then.
436 $archive = "{$wgUploadDirectory}/{$subdir}";
437 if ( ! is_dir( $archive ) ) { @mkdir( $archive, 0777 ); }
438 $archive .= "/" . $hash{0};
439 if ( ! is_dir( $archive ) ) { @mkdir( $archive, 0777 ); }
440 $archive .= "/" . substr( $hash, 0, 2 );
441 if ( ! is_dir( $archive ) ) { @mkdir( $archive, 0777 ); }
442
443 umask( $oldumask );
444 return $archive;
445 }
446
447 function wfRecordUpload( $name, $oldver, $size, $desc, $copyStatus = "", $source = "" )
448 {
449 global $wgUser, $wgLang, $wgTitle, $wgOut, $wgDeferredUpdateList;
450 global $wgUseCopyrightUpload;
451
452 $fname = "wfRecordUpload";
453
454 $sql = "SELECT img_name,img_size,img_timestamp,img_description,img_user," .
455 "img_user_text FROM image WHERE img_name='" . wfStrencode( $name ) . "'";
456 $res = wfQuery( $sql, DB_READ, $fname );
457
458 $now = wfTimestampNow();
459 $won = wfInvertTimestamp( $now );
460 $size = IntVal( $size );
461
462 if ( $wgUseCopyrightUpload )
463 {
464 $textdesc = "== " . wfMsg ( "filedesc" ) . " ==\n" . $desc . "\n" .
465 "== " . wfMsg ( "filestatus" ) . " ==\n" . $copyStatus . "\n" .
466 "== " . wfMsg ( "filesource" ) . " ==\n" . $source ;
467 }
468 else $textdesc = $desc ;
469
470 $now = wfTimestampNow();
471 $won = wfInvertTimestamp( $now );
472
473 if ( 0 == wfNumRows( $res ) ) {
474 $sql = "INSERT INTO image (img_name,img_size,img_timestamp," .
475 "img_description,img_user,img_user_text) VALUES ('" .
476 wfStrencode( $name ) . "',$size,'{$now}','" .
477 wfStrencode( $desc ) . "', '" . $wgUser->getID() .
478 "', '" . wfStrencode( $wgUser->getName() ) . "')";
479 wfQuery( $sql, DB_WRITE, $fname );
480
481 $sql = "SELECT cur_id,cur_text FROM cur WHERE cur_namespace=" .
482 Namespace::getImage() . " AND cur_title='" .
483 wfStrencode( $name ) . "'";
484 $res = wfQuery( $sql, DB_READ, $fname );
485 if ( 0 == wfNumRows( $res ) ) {
486 $common =
487 Namespace::getImage() . ",'" .
488 wfStrencode( $name ) . "','" .
489 wfStrencode( $desc ) . "','" . $wgUser->getID() . "','" .
490 wfStrencode( $wgUser->getName() ) . "','" . $now .
491 "',1";
492 $sql = "INSERT INTO cur (cur_namespace,cur_title," .
493 "cur_comment,cur_user,cur_user_text,cur_timestamp,cur_is_new," .
494 "cur_text,inverse_timestamp,cur_touched) VALUES (" .
495 $common .
496 ",'" . wfStrencode( $textdesc ) . "','{$won}','{$now}')";
497 wfQuery( $sql, DB_WRITE, $fname );
498 $id = wfInsertId() or 0; # We should throw an error instead
499
500 $titleObj = Title::makeTitle( NS_IMAGE, $name );
501 RecentChange::notifyNew( $now, $titleObj, 0, $wgUser, $desc );
502
503 $u = new SearchUpdate( $id, $name, $desc );
504 $u->doUpdate();
505 }
506 } else {
507 $s = wfFetchObject( $res );
508
509 $sql = "INSERT INTO oldimage (oi_name,oi_archive_name,oi_size," .
510 "oi_timestamp,oi_description,oi_user,oi_user_text) VALUES ('" .
511 wfStrencode( $s->img_name ) . "','" .
512 wfStrencode( $oldver ) .
513 "',{$s->img_size},'{$s->img_timestamp}','" .
514 wfStrencode( $s->img_description ) . "','" .
515 wfStrencode( $s->img_user ) . "','" .
516 wfStrencode( $s->img_user_text) . "')";
517 wfQuery( $sql, DB_WRITE, $fname );
518
519 $sql = "UPDATE image SET img_size={$size}," .
520 "img_timestamp='" . wfTimestampNow() . "',img_user='" .
521 $wgUser->getID() . "',img_user_text='" .
522 wfStrencode( $wgUser->getName() ) . "', img_description='" .
523 wfStrencode( $desc ) . "' WHERE img_name='" .
524 wfStrencode( $name ) . "'";
525 wfQuery( $sql, DB_WRITE, $fname );
526
527 $sql = "UPDATE cur SET cur_touched='{$now}' WHERE cur_namespace=" .
528 Namespace::getImage() . " AND cur_title='" .
529 wfStrencode( $name ) . "'";
530 wfQuery( $sql, DB_WRITE, $fname );
531 }
532
533 $log = new LogPage( wfMsg( "uploadlogpage" ), wfMsg( "uploadlogpagetext" ) );
534 $da = wfMsg( "uploadedimage", "[[:" . $wgLang->getNsText(
535 Namespace::getImage() ) . ":{$name}|{$name}]]" );
536 $ta = wfMsg( "uploadedimage", $name );
537 $log->addEntry( $da, $desc, $ta );
538 }
539
540
541 /* Some generic result counters, pulled out of SearchEngine */
542
543 function wfShowingResults( $offset, $limit )
544 {
545 global $wgLang;
546 return wfMsg( "showingresults", $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+1 ) );
547 }
548
549 function wfShowingResultsNum( $offset, $limit, $num )
550 {
551 global $wgLang;
552 return wfMsg( "showingresultsnum", $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+1 ), $wgLang->formatNum( $num ) );
553 }
554
555 function wfViewPrevNext( $offset, $limit, $link, $query = "", $atend = false )
556 {
557 global $wgUser, $wgLang;
558 $fmtLimit = $wgLang->formatNum( $limit );
559 $prev = wfMsg( "prevn", $fmtLimit );
560 $next = wfMsg( "nextn", $fmtLimit );
561 $link = wfUrlencode( $link );
562
563 $sk = $wgUser->getSkin();
564 if ( 0 != $offset ) {
565 $po = $offset - $limit;
566 if ( $po < 0 ) { $po = 0; }
567 $q = "limit={$limit}&offset={$po}";
568 if ( "" != $query ) { $q .= "&{$query}"; }
569 $plink = "<a href=\"" . wfLocalUrlE( $link, $q ) . "\">{$prev}</a>";
570 } else { $plink = $prev; }
571
572 $no = $offset + $limit;
573 $q = "limit={$limit}&offset={$no}";
574 if ( "" != $query ) { $q .= "&{$query}"; }
575
576 if ( $atend ) {
577 $nlink = $next;
578 } else {
579 $nlink = "<a href=\"" . wfLocalUrlE( $link, $q ) . "\">{$next}</a>";
580 }
581 $nums = wfNumLink( $offset, 20, $link , $query ) . " | " .
582 wfNumLink( $offset, 50, $link, $query ) . " | " .
583 wfNumLink( $offset, 100, $link, $query ) . " | " .
584 wfNumLink( $offset, 250, $link, $query ) . " | " .
585 wfNumLink( $offset, 500, $link, $query );
586
587 return wfMsg( "viewprevnext", $plink, $nlink, $nums );
588 }
589
590 function wfNumLink( $offset, $limit, $link, $query = "" )
591 {
592 global $wgUser, $wgLang;
593 if ( "" == $query ) { $q = ""; }
594 else { $q = "{$query}&"; }
595 $q .= "limit={$limit}&offset={$offset}";
596
597 $fmtLimit = $wgLang->formatNum( $limit );
598 $s = "<a href=\"" . wfLocalUrlE( $link, $q ) . "\">{$fmtLimit}</a>";
599 return $s;
600 }
601
602 function wfClientAcceptsGzip() {
603 global $wgUseGzip;
604 if( $wgUseGzip ) {
605 # FIXME: we may want to blacklist some broken browsers
606 if( preg_match(
607 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
608 $_SERVER["HTTP_ACCEPT_ENCODING"],
609 $m ) ) {
610 if( ( $m[1] == "q" ) && ( $m[2] == 0 ) ) return false;
611 wfDebug( " accepts gzip\n" );
612 return true;
613 }
614 }
615 return false;
616 }
617
618 # Yay, more global functions!
619 function wfCheckLimits( $deflimit = 50, $optionname = "rclimit" ) {
620 global $wgUser, $wgRequest;
621
622 $limit = $wgRequest->getInt( 'limit', 0 );
623 if( $limit < 0 ) $limit = 0;
624 if( ( $limit == 0 ) && ( $optionname != "" ) ) {
625 $limit = (int)$wgUser->getOption( $optionname );
626 }
627 if( $limit <= 0 ) $limit = $deflimit;
628 if( $limit > 5000 ) $limit = 5000; # We have *some* limits...
629
630 $offset = $wgRequest->getInt( 'offset', 0 );
631 if( $offset < 0 ) $offset = 0;
632 if( $offset > 65000 ) $offset = 65000; # do we need a max? what?
633
634 return array( $limit, $offset );
635 }
636
637 # Escapes the given text so that it may be output using addWikiText()
638 # without any linking, formatting, etc. making its way through. This
639 # is achieved by substituting certain characters with HTML entities.
640 # As required by the callers, <nowiki> is not used. It currently does
641 # not filter out characters which have special meaning only at the
642 # start of a line, such as "*".
643 function wfEscapeWikiText( $text )
644 {
645 $text = str_replace(
646 array( '[', '|', "'", 'ISBN ' , '://' , "\n=" ),
647 array( '&#91;', '&#124;', '&#39;', 'ISBN&#32;', '&#58;//' , "\n&#61;" ),
648 htmlspecialchars($text) );
649 return $text;
650 }
651
652 function wfQuotedPrintable( $string, $charset = "" )
653 {
654 # Probably incomplete; see RFC 2045
655 if( empty( $charset ) ) {
656 global $wgInputEncoding;
657 $charset = $wgInputEncoding;
658 }
659 $charset = strtoupper( $charset );
660 $charset = str_replace( "ISO-8859", "ISO8859", $charset ); // ?
661
662 $illegal = '\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\xff=';
663 $replace = $illegal . '\t ?_';
664 if( !preg_match( "/[$illegal]/", $string ) ) return $string;
665 $out = "=?$charset?Q?";
666 $out .= preg_replace( "/([$replace])/e", 'sprintf("=%02X",ord("$1"))', $string );
667 $out .= "?=";
668 return $out;
669 }
670
671 function wfTime(){
672 $st = explode( " ", microtime() );
673 return (float)$st[0] + (float)$st[1];
674 }
675
676 # Changes the first character to an HTML entity
677 function wfHtmlEscapeFirst( $text ) {
678 $ord = ord($text);
679 $newText = substr($text, 1);
680 return "&#$ord;$newText";
681 }
682
683 # Sets dest to source and returns the original value of dest
684 function wfSetVar( &$dest, $source )
685 {
686 $temp = $dest;
687 $dest = $source;
688 return $temp;
689 }
690
691 # Sets dest to a reference to source and returns the original dest
692 function &wfSetRef( &$dest, &$source )
693 {
694 $temp =& $dest;
695 $dest =& $source;
696 return $temp;
697 }
698
699 # This function takes two arrays as input, and returns a CGI-style string, e.g.
700 # "days=7&limit=100". Options in the first array override options in the second.
701 # Options set to "" will not be output.
702 function wfArrayToCGI( $array1, $array2 = NULL )
703 {
704 if ( !is_null( $array2 ) ) {
705 $array1 = $array1 + $array2;
706 }
707
708 $cgi = "";
709 foreach ( $array1 as $key => $value ) {
710 if ( "" !== $value ) {
711 if ( "" != $cgi ) {
712 $cgi .= "&";
713 }
714 $cgi .= "{$key}={$value}";
715 }
716 }
717 return $cgi;
718 }
719
720 # This is obsolete, use SquidUpdate::purge()
721 function wfPurgeSquidServers ($urlArr) {
722 SquidUpdate::purge( $urlArr );
723 }
724
725 # Windows-compatible version of escapeshellarg()
726 function wfEscapeShellArg( )
727 {
728 $args = func_get_args();
729 $first = true;
730 $retVal = "";
731 foreach ( $args as $arg ) {
732 if ( !$first ) {
733 $retVal .= " ";
734 } else {
735 $first = false;
736 }
737
738 if (substr(php_uname(), 0, 7) == "Windows") {
739 $retVal .= "\"$arg\"";
740 } else {
741 $retVal .= escapeshellarg( $arg );
742 }
743 }
744 return $retVal;
745 }
746
747 # wfMerge attempts to merge differences between three texts.
748 # Returns true for a clean merge and false for failure or a conflict.
749
750 function wfMerge( $old, $mine, $yours, &$result ){
751 global $wgDiff3;
752
753 # This check may also protect against code injection in
754 # case of broken installations.
755 if(! file_exists( $wgDiff3 ) ){
756 return false;
757 }
758
759 # Make temporary files
760 $td = "/tmp/";
761 $oldtextFile = fopen( $oldtextName = tempnam( $td, "merge-old-" ), "w" );
762 $mytextFile = fopen( $mytextName = tempnam( $td, "merge-mine-" ), "w" );
763 $yourtextFile = fopen( $yourtextName = tempnam( $td, "merge-your-" ), "w" );
764
765 fwrite( $oldtextFile, $old ); fclose( $oldtextFile );
766 fwrite( $mytextFile, $mine ); fclose( $mytextFile );
767 fwrite( $yourtextFile, $yours ); fclose( $yourtextFile );
768
769 # Check for a conflict
770 $cmd = wfEscapeShellArg( $wgDiff3 ) . " -a --overlap-only " .
771 wfEscapeShellArg( $mytextName ) . " " .
772 wfEscapeShellArg( $oldtextName ) . " " .
773 wfEscapeShellArg( $yourtextName );
774 $handle = popen( $cmd, "r" );
775
776 if( fgets( $handle ) ){
777 $conflict = true;
778 } else {
779 $conflict = false;
780 }
781 pclose( $handle );
782
783 # Merge differences
784 $cmd = wfEscapeShellArg( $wgDiff3 ) . " -a -e --merge " .
785 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
786 $handle = popen( $cmd, "r" );
787 $result = "";
788 do {
789 $data = fread( $handle, 8192 );
790 if ( strlen( $data ) == 0 ) {
791 break;
792 }
793 $result .= $data;
794 } while ( true );
795 pclose( $handle );
796 unlink( $mytextName ); unlink( $oldtextName ); unlink( $yourtextName );
797 return ! $conflict;
798 }
799
800 function wfVarDump( $var )
801 {
802 global $wgOut;
803 $s = str_replace("\n","<br>\n", var_export( $var, true ) . "\n");
804 if ( headers_sent() || !@is_object( $wgOut ) ) {
805 print $s;
806 } else {
807 $wgOut->addHTML( $s );
808 }
809 }
810
811 # Provide a simple HTTP error.
812 function wfHttpError( $code, $label, $desc ) {
813 global $wgOut;
814 $wgOut->disable();
815 header( "HTTP/1.0 $code $label" );
816 header( "Status: $code $label" );
817 $wgOut->sendCacheControl();
818
819 # Don't send content if it's a HEAD request.
820 if( $_SERVER['REQUEST_METHOD'] == 'HEAD' ) {
821 header( "Content-type: text/plain" );
822 print "$desc\n";
823 }
824 }
825
826 # Converts an Accept-* header into an array mapping string values to quality factors
827 function wfAcceptToPrefs( $accept, $def = "*/*" ) {
828 # No arg means accept anything (per HTTP spec)
829 if( !$accept ) {
830 return array( $def => 1 );
831 }
832
833 $prefs = array();
834
835 $parts = explode( ",", $accept );
836
837 foreach( $parts as $part ) {
838 # FIXME: doesn't deal with params like 'text/html; level=1'
839 @list( $value, $qpart ) = explode( ";", $part );
840 if( !isset( $qpart ) ) {
841 $prefs[$value] = 1;
842 } elseif( preg_match( '/q\s*=\s*(\d*\.\d+)/', $qpart, $match ) ) {
843 $prefs[$value] = $match[1];
844 }
845 }
846
847 return $prefs;
848 }
849
850 /* private */ function mimeTypeMatch( $type, $avail ) {
851 if( array_key_exists($type, $avail) ) {
852 return $type;
853 } else {
854 $parts = explode( '/', $type );
855 if( array_key_exists( $parts[0] . '/*', $avail ) ) {
856 return $parts[0] . '/*';
857 } elseif( array_key_exists( '*/*', $avail ) ) {
858 return '*/*';
859 } else {
860 return NULL;
861 }
862 }
863 }
864
865 # FIXME: doesn't handle params like 'text/plain; charset=UTF-8'
866 # XXX: generalize to negotiate other stuff
867 function wfNegotiateType( $cprefs, $sprefs ) {
868 $combine = array();
869
870 foreach( array_keys($sprefs) as $type ) {
871 $parts = explode( '/', $type );
872 if( $parts[1] != '*' ) {
873 $ckey = mimeTypeMatch( $type, $cprefs );
874 if( $ckey ) {
875 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
876 }
877 }
878 }
879
880 foreach( array_keys( $cprefs ) as $type ) {
881 $parts = explode( '/', $type );
882 if( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
883 $skey = mimeTypeMatch( $type, $sprefs );
884 if( $skey ) {
885 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
886 }
887 }
888 }
889
890 $bestq = 0;
891 $besttype = NULL;
892
893 foreach( array_keys( $combine ) as $type ) {
894 if( $combine[$type] > $bestq ) {
895 $besttype = $type;
896 $bestq = $combine[$type];
897 }
898 }
899
900 return $besttype;
901 }
902
903 ?>