In Special:Watchlist?magic=yes, show links to non-existent pages in red
[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 if( !function_exists('is_a') ) {
40 # Exists in PHP 4.2.0+
41 function is_a( $object, $class_name ) {
42 return
43 (strcasecmp( get_class( $object ), $class_name ) == 0) ||
44 is_subclass_of( $object, $class_name );
45 }
46 }
47
48 # html_entity_decode exists in PHP 4.3.0+ but is FATALLY BROKEN even then,
49 # with no UTF-8 support.
50 function do_html_entity_decode( $string, $quote_style=ENT_COMPAT, $charset='ISO-8859-1' ) {
51 static $trans;
52 if( !isset( $trans ) ) {
53 $trans = array_flip( get_html_translation_table( HTML_ENTITIES, $quote_style ) );
54 # Assumes $charset will always be the same through a run, and only understands
55 # utf-8 or default. Note - mixing latin1 named entities and unicode numbered
56 # ones will result in a bad link.
57 if( strcasecmp( 'utf-8', $charset ) == 0 ) {
58 $trans = array_map( 'utf8_encode', $trans );
59 }
60 }
61 return strtr( $string, $trans );
62 }
63
64 $wgRandomSeeded = false;
65
66 # Seed Mersenne Twister
67 # Only necessary in PHP < 4.2.0
68 function wfSeedRandom()
69 {
70 global $wgRandomSeeded;
71
72 if ( ! $wgRandomSeeded && version_compare( phpversion(), '4.2.0' ) < 0 ) {
73 $seed = hexdec(substr(md5(microtime()),-8)) & 0x7fffffff;
74 mt_srand( $seed );
75 $wgRandomSeeded = true;
76 }
77 }
78
79 # Generates a URL from a URL-encoded title and a query string
80 # Title::getLocalURL() is preferred in most cases
81 #
82 function wfLocalUrl( $a, $q = '' )
83 {
84 global $wgServer, $wgScript, $wgArticlePath;
85
86 $a = str_replace( ' ', '_', $a );
87
88 if ( '' == $a ) {
89 if( '' == $q ) {
90 $a = $wgScript;
91 } else {
92 $a = "{$wgScript}?{$q}";
93 }
94 } else if ( '' == $q ) {
95 $a = str_replace( "$1", $a, $wgArticlePath );
96 } else if ($wgScript != '' ) {
97 $a = "{$wgScript}?title={$a}&{$q}";
98 } else { //XXX hackish solution for toplevel wikis
99 $a = "/{$a}?{$q}";
100 }
101 return $a;
102 }
103
104 function wfLocalUrlE( $a, $q = '' )
105 {
106 return wfEscapeHTML( wfLocalUrl( $a, $q ) );
107 # die( "Call to obsolete function wfLocalUrlE()" );
108 }
109
110 function wfFullUrl( $a, $q = '' ) {
111 wfDebugDieBacktrace( 'Call to obsolete function wfFullUrl(); use Title::getFullURL' );
112 }
113
114 function wfFullUrlE( $a, $q = '' ) {
115 wfDebugDieBacktrace( 'Call to obsolete function wfFullUrlE(); use Title::getFullUrlE' );
116
117 }
118
119 // orphan function wfThumbUrl( $img )
120 //{
121 // global $wgUploadPath;
122 //
123 // $nt = Title::newFromText( $img );
124 // if( !$nt ) return "";
125 //
126 // $name = $nt->getDBkey();
127 // $hash = md5( $name );
128 //
129 // $url = "{$wgUploadPath}/thumb/" . $hash{0} . "/" .
130 // substr( $hash, 0, 2 ) . "/{$name}";
131 // return wfUrlencode( $url );
132 //}
133
134
135 function wfImageArchiveUrl( $name )
136 {
137 global $wgUploadPath;
138
139 $hash = md5( substr( $name, 15) );
140 $url = "{$wgUploadPath}/archive/" . $hash{0} . "/" .
141 substr( $hash, 0, 2 ) . "/{$name}";
142 return wfUrlencode($url);
143 }
144
145 function wfUrlencode ( $s )
146 {
147 $s = urlencode( $s );
148 $s = preg_replace( '/%3[Aa]/', ':', $s );
149 $s = preg_replace( '/%2[Ff]/', '/', $s );
150
151 return $s;
152 }
153
154 function wfUtf8Sequence($codepoint) {
155 if($codepoint < 0x80) return chr($codepoint);
156 if($codepoint < 0x800) return chr($codepoint >> 6 & 0x3f | 0xc0) .
157 chr($codepoint & 0x3f | 0x80);
158 if($codepoint < 0x10000) return chr($codepoint >> 12 & 0x0f | 0xe0) .
159 chr($codepoint >> 6 & 0x3f | 0x80) .
160 chr($codepoint & 0x3f | 0x80);
161 if($codepoint < 0x100000) return chr($codepoint >> 18 & 0x07 | 0xf0) . # Double-check this
162 chr($codepoint >> 12 & 0x3f | 0x80) .
163 chr($codepoint >> 6 & 0x3f | 0x80) .
164 chr($codepoint & 0x3f | 0x80);
165 # Doesn't yet handle outside the BMP
166 return "&#$codepoint;";
167 }
168
169 # Converts numeric character entities to UTF-8
170 function wfMungeToUtf8($string) {
171 global $wgInputEncoding; # This is debatable
172 #$string = iconv($wgInputEncoding, "UTF-8", $string);
173 $string = preg_replace ( '/&#([0-9]+);/e', 'wfUtf8Sequence($1)', $string );
174 $string = preg_replace ( '/&#x([0-9a-f]+);/ie', 'wfUtf8Sequence(0x$1)', $string );
175 # Should also do named entities here
176 return $string;
177 }
178
179 # Converts a single UTF-8 character into the corresponding HTML character entity
180 function wfUtf8Entity( $matches ) {
181 $char = $matches[0];
182 # Find the length
183 $z = ord( $char{0} );
184 if ( $z & 0x80 ) {
185 $length = 0;
186 while ( $z & 0x80 ) {
187 $length++;
188 $z <<= 1;
189 }
190 } else {
191 $length = 1;
192 }
193
194 if ( $length != strlen( $char ) ) {
195 return '';
196 }
197 if ( $length == 1 ) {
198 return $char;
199 }
200
201 # Mask off the length-determining bits and shift back to the original location
202 $z &= 0xff;
203 $z >>= $length;
204
205 # Add in the free bits from subsequent bytes
206 for ( $i=1; $i<$length; $i++ ) {
207 $z <<= 6;
208 $z |= ord( $char{$i} ) & 0x3f;
209 }
210
211 # Make entity
212 return "&#$z;";
213 }
214
215 # Converts all multi-byte characters in a UTF-8 string into the appropriate character entity
216 function wfUtf8ToHTML($string) {
217 return preg_replace_callback( '/[\\xc0-\\xfd][\\x80-\\xbf]*/', 'wfUtf8Entity', $string );
218 }
219
220 function wfDebug( $text, $logonly = false )
221 {
222 global $wgOut, $wgDebugLogFile, $wgDebugComments, $wgProfileOnly, $wgDebugRawPage;
223
224 # Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
225 if ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' && !$wgDebugRawPage ) {
226 return;
227 }
228
229 if ( isset( $wgOut ) && $wgDebugComments && !$logonly ) {
230 $wgOut->debug( $text );
231 }
232 if ( "" != $wgDebugLogFile && !$wgProfileOnly ) {
233 error_log( $text, 3, $wgDebugLogFile );
234 }
235 }
236
237 # Log for database errors
238 function wfLogDBError( $text ) {
239 global $wgDBerrorLog;
240 if ( $wgDBerrorLog ) {
241 $text = date("D M j G:i:s T Y") . "\t$text";
242 error_log( $text, 3, $wgDBerrorLog );
243 }
244 }
245
246 function logProfilingData()
247 {
248 global $wgRequestTime, $wgDebugLogFile, $wgDebugRawPage, $wgRequest;
249 global $wgProfiling, $wgProfileStack, $wgProfileLimit, $wgUser;
250 $now = wfTime();
251
252 list( $usec, $sec ) = explode( " ", $wgRequestTime );
253 $start = (float)$sec + (float)$usec;
254 $elapsed = $now - $start;
255 if ( $wgProfiling ) {
256 $prof = wfGetProfilingOutput( $start, $elapsed );
257 $forward = '';
258 if( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) )
259 $forward = ' forwarded for ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
260 if( !empty( $_SERVER['HTTP_CLIENT_IP'] ) )
261 $forward .= ' client IP ' . $_SERVER['HTTP_CLIENT_IP'];
262 if( !empty( $_SERVER['HTTP_FROM'] ) )
263 $forward .= ' from ' . $_SERVER['HTTP_FROM'];
264 if( $forward )
265 $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
266 if($wgUser->getId() == 0)
267 $forward .= ' anon';
268 $log = sprintf( "%s\t%04.3f\t%s\n",
269 gmdate( 'YmdHis' ), $elapsed,
270 urldecode( $_SERVER['REQUEST_URI'] . $forward ) );
271 if ( '' != $wgDebugLogFile && ( $wgRequest->getVal('action') != 'raw' || $wgDebugRawPage ) ) {
272 error_log( $log . $prof, 3, $wgDebugLogFile );
273 }
274 }
275 }
276
277
278 function wfReadOnly()
279 {
280 global $wgReadOnlyFile;
281
282 if ( "" == $wgReadOnlyFile ) { return false; }
283 return is_file( $wgReadOnlyFile );
284 }
285
286 $wgReplacementKeys = array( "$1", "$2", "$3", "$4", "$5", "$6", "$7", "$8", "$9" );
287
288 # Get a message from anywhere
289 function wfMsg( $key ) {
290 $args = func_get_args();
291 if ( count( $args ) ) {
292 array_shift( $args );
293 }
294 return wfMsgReal( $key, $args, true );
295 }
296
297 # Get a message from the language file
298 function wfMsgNoDB( $key ) {
299 $args = func_get_args();
300 if ( count( $args ) ) {
301 array_shift( $args );
302 }
303 return wfMsgReal( $key, $args, false );
304 }
305
306 # Really get a message
307 function wfMsgReal( $key, $args, $useDB ) {
308 global $wgReplacementKeys, $wgMessageCache, $wgLang;
309
310 $fname = 'wfMsg';
311 wfProfileIn( $fname );
312 if ( $wgMessageCache ) {
313 $message = $wgMessageCache->get( $key, $useDB );
314 } elseif ( $wgLang ) {
315 $message = $wgLang->getMessage( $key );
316 } else {
317 wfDebug( "No language object when getting $key\n" );
318 $message = "&lt;$key&gt;";
319 }
320
321 # Replace arguments
322 if( count( $args ) ) {
323 $message = str_replace( $wgReplacementKeys, $args, $message );
324 }
325 wfProfileOut( $fname );
326 return $message;
327 }
328
329 function wfCleanFormFields( $fields )
330 {
331 wfDebugDieBacktrace( 'Call to obsolete wfCleanFormFields(). Use wgRequest instead...' );
332 }
333
334 function wfMungeQuotes( $in )
335 {
336 $out = str_replace( '%', '%25', $in );
337 $out = str_replace( "'", '%27', $out );
338 $out = str_replace( '"', '%22', $out );
339 return $out;
340 }
341
342 function wfDemungeQuotes( $in )
343 {
344 $out = str_replace( '%22', '"', $in );
345 $out = str_replace( '%27', "'", $out );
346 $out = str_replace( '%25', '%', $out );
347 return $out;
348 }
349
350 function wfCleanQueryVar( $var )
351 {
352 wfDebugDieBacktrace( 'Call to obsolete function wfCleanQueryVar(); use wgRequest instead' );
353 }
354
355 function wfSearch( $s )
356 {
357 $se = new SearchEngine( $s );
358 $se->showResults();
359 }
360
361 function wfGo( $s )
362 { # pick the nearest match
363 $se = new SearchEngine( $s );
364 $se->goResult();
365 }
366
367 # Just like exit() but makes a note of it.
368 # Commits open transactions except if the error parameter is set
369 function wfAbruptExit( $error = false ){
370 global $wgLoadBalancer;
371 static $called = false;
372 if ( $called ){
373 exit();
374 }
375 $called = true;
376
377 if( function_exists( 'debug_backtrace' ) ){ // PHP >= 4.3
378 $bt = debug_backtrace();
379 for($i = 0; $i < count($bt) ; $i++){
380 $file = $bt[$i]['file'];
381 $line = $bt[$i]['line'];
382 wfDebug("WARNING: Abrupt exit in $file at line $line\n");
383 }
384 } else {
385 wfDebug('WARNING: Abrupt exit\n');
386 }
387 if ( !$error ) {
388 $wgLoadBalancer->closeAll();
389 }
390 exit();
391 }
392
393 function wfErrorExit() {
394 wfAbruptExit( true );
395 }
396
397 function wfDebugDieBacktrace( $msg = '' ) {
398 global $wgCommandLineMode;
399
400 if ( function_exists( 'debug_backtrace' ) ) {
401 if ( $wgCommandLineMode ) {
402 $msg .= "\nBacktrace:\n";
403 } else {
404 $msg .= "\n<p>Backtrace:</p>\n<ul>\n";
405 }
406 $backtrace = debug_backtrace();
407 foreach( $backtrace as $call ) {
408 $f = explode( DIRECTORY_SEPARATOR, $call['file'] );
409 $file = $f[count($f)-1];
410 if ( $wgCommandLineMode ) {
411 $msg .= "$file line {$call['line']} calls ";
412 } else {
413 $msg .= '<li>' . $file . " line " . $call['line'] . ' calls ';
414 }
415 if( !empty( $call['class'] ) ) $msg .= $call['class'] . '::';
416 $msg .= $call['function'] . "()";
417
418 if ( $wgCommandLineMode ) {
419 $msg .= "\n";
420 } else {
421 $msg .= "</li>\n";
422 }
423 }
424 }
425 die( $msg );
426 }
427
428 function wfNumberOfArticles()
429 {
430 global $wgNumberOfArticles;
431
432 wfLoadSiteStats();
433 return $wgNumberOfArticles;
434 }
435
436 /* private */ function wfLoadSiteStats()
437 {
438 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
439 $fname = 'wfLoadSiteStats';
440
441 if ( -1 != $wgNumberOfArticles ) return;
442 $dbr =& wfGetDB( DB_SLAVE );
443 $s = $dbr->getArray( 'site_stats',
444 array( 'ss_total_views', 'ss_total_edits', 'ss_good_articles' ),
445 array( 'ss_row_id' => 1 ), $fname
446 );
447
448 if ( $s === false ) {
449 return;
450 } else {
451 $wgTotalViews = $s->ss_total_views;
452 $wgTotalEdits = $s->ss_total_edits;
453 $wgNumberOfArticles = $s->ss_good_articles;
454 }
455 }
456
457 function wfEscapeHTML( $in )
458 {
459 return str_replace(
460 array( '&', '"', '>', '<' ),
461 array( '&amp;', '&quot;', '&gt;', '&lt;' ),
462 $in );
463 }
464
465 function wfEscapeHTMLTagsOnly( $in ) {
466 return str_replace(
467 array( '"', '>', '<' ),
468 array( '&quot;', '&gt;', '&lt;' ),
469 $in );
470 }
471
472 function wfUnescapeHTML( $in )
473 {
474 $in = str_replace( '&lt;', '<', $in );
475 $in = str_replace( '&gt;', '>', $in );
476 $in = str_replace( '&quot;', '"', $in );
477 $in = str_replace( '&amp;', '&', $in );
478 return $in;
479 }
480
481 function wfImageDir( $fname )
482 {
483 global $wgUploadDirectory;
484
485 $hash = md5( $fname );
486 $oldumask = umask(0);
487 $dest = $wgUploadDirectory . '/' . $hash{0};
488 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
489 $dest .= '/' . substr( $hash, 0, 2 );
490 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
491
492 umask( $oldumask );
493 return $dest;
494 }
495
496 function wfImageThumbDir( $fname , $subdir='thumb')
497 {
498 return wfImageArchiveDir( $fname, $subdir );
499 }
500
501 function wfImageArchiveDir( $fname , $subdir='archive')
502 {
503 global $wgUploadDirectory;
504
505 $hash = md5( $fname );
506 $oldumask = umask(0);
507
508 # Suppress warning messages here; if the file itself can't
509 # be written we'll worry about it then.
510 $archive = "{$wgUploadDirectory}/{$subdir}";
511 if ( ! is_dir( $archive ) ) { @mkdir( $archive, 0777 ); }
512 $archive .= '/' . $hash{0};
513 if ( ! is_dir( $archive ) ) { @mkdir( $archive, 0777 ); }
514 $archive .= '/' . substr( $hash, 0, 2 );
515 if ( ! is_dir( $archive ) ) { @mkdir( $archive, 0777 ); }
516
517 umask( $oldumask );
518 return $archive;
519 }
520
521 function wfRecordUpload( $name, $oldver, $size, $desc, $copyStatus = "", $source = "" )
522 {
523 global $wgUser, $wgLang, $wgTitle, $wgOut, $wgDeferredUpdateList;
524 global $wgUseCopyrightUpload;
525
526 $fname = 'wfRecordUpload';
527 $dbw =& wfGetDB( DB_MASTER );
528
529 # img_name must be unique
530 if ( !$dbw->indexUnique( 'image', 'img_name' ) ) {
531 wfDebugDieBacktrace( 'Database schema not up to date, please run maintenance/archives/patch-image_name_unique.sql' );
532 }
533
534
535 $now = wfTimestampNow();
536 $won = wfInvertTimestamp( $now );
537 $size = IntVal( $size );
538
539 if ( $wgUseCopyrightUpload )
540 {
541 $textdesc = '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $desc . "\n" .
542 '== ' . wfMsg ( 'filestatus' ) . " ==\n" . $copyStatus . "\n" .
543 '== ' . wfMsg ( 'filesource' ) . " ==\n" . $source ;
544 }
545 else $textdesc = $desc ;
546
547 $now = wfTimestampNow();
548 $won = wfInvertTimestamp( $now );
549
550 # Test to see if the row exists using INSERT IGNORE
551 # This avoids race conditions by locking the row until the commit, and also
552 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
553 $dbw->insert( 'image',
554 array(
555 'img_name' => $name,
556 'img_size'=> $size,
557 'img_timestamp' => $now,
558 'img_description' => $desc,
559 'img_user' => $wgUser->getID(),
560 'img_user_text' => $wgUser->getName(),
561 ), $fname, 'IGNORE'
562 );
563 $descTitle = Title::makeTitle( NS_IMAGE, $name );
564
565 if ( $dbw->affectedRows() ) {
566 # Successfully inserted, this is a new image
567 $id = $descTitle->getArticleID();
568
569 if ( $id == 0 ) {
570 $seqVal = $dbw->nextSequenceValue( 'cur_cur_id_seq' );
571 $dbw->insertArray( 'cur',
572 array(
573 'cur_id' => $seqVal,
574 'cur_namespace' => NS_IMAGE,
575 'cur_title' => $name,
576 'cur_comment' => $desc,
577 'cur_user' => $wgUser->getID(),
578 'cur_user_text' => $wgUser->getName(),
579 'cur_timestamp' => $now,
580 'cur_is_new' => 1,
581 'cur_text' => $textdesc,
582 'inverse_timestamp' => $won,
583 'cur_touched' => $now
584 ), $fname
585 );
586 $id = $dbw->insertId() or 0; # We should throw an error instead
587
588 RecentChange::notifyNew( $now, $descTitle, 0, $wgUser, $desc );
589
590 $u = new SearchUpdate( $id, $name, $desc );
591 $u->doUpdate();
592 }
593 } else {
594 # Collision, this is an update of an image
595 # Get current image row for update
596 $s = $dbw->getArray( 'image', array( 'img_name','img_size','img_timestamp','img_description',
597 'img_user','img_user_text' ), array( 'img_name' => $name ), $fname, 'FOR UPDATE' );
598
599 # Insert it into oldimage
600 $dbw->insertArray( 'oldimage',
601 array(
602 'oi_name' => $s->img_name,
603 'oi_archive_name' => $oldver,
604 'oi_size' => $s->img_size,
605 'oi_timestamp' => $s->img_timestamp,
606 'oi_description' => $s->img_description,
607 'oi_user' => $s->img_user,
608 'oi_user_text' => $s->img_user_text
609 ), $fname
610 );
611
612 # Update the current image row
613 $dbw->updateArray( 'image',
614 array( /* SET */
615 'img_size' => $size,
616 'img_timestamp' => wfTimestampNow(),
617 'img_user' => $wgUser->getID(),
618 'img_user_text' => $wgUser->getName(),
619 'img_description' => $desc,
620 ), array( /* WHERE */
621 'img_name' => $name
622 ), $fname
623 );
624
625 # Invalidate the cache for the description page
626 $descTitle->invalidateCache();
627 }
628
629 $log = new LogPage( wfMsg( 'uploadlogpage' ), wfMsg( 'uploadlogpagetext' ) );
630 $da = wfMsg( 'uploadedimage', '[[:' . $wgLang->getNsText(
631 Namespace::getImage() ) . ":{$name}|{$name}]]" );
632 $ta = wfMsg( 'uploadedimage', $name );
633 $log->addEntry( $da, $desc, $ta );
634 }
635
636
637 /* Some generic result counters, pulled out of SearchEngine */
638
639 function wfShowingResults( $offset, $limit )
640 {
641 global $wgLang;
642 return wfMsg( 'showingresults', $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+1 ) );
643 }
644
645 function wfShowingResultsNum( $offset, $limit, $num )
646 {
647 global $wgLang;
648 return wfMsg( 'showingresultsnum', $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+1 ), $wgLang->formatNum( $num ) );
649 }
650
651 function wfViewPrevNext( $offset, $limit, $link, $query = '', $atend = false )
652 {
653 global $wgUser, $wgLang;
654 $fmtLimit = $wgLang->formatNum( $limit );
655 $prev = wfMsg( 'prevn', $fmtLimit );
656 $next = wfMsg( 'nextn', $fmtLimit );
657 $link = wfUrlencode( $link );
658
659 $sk = $wgUser->getSkin();
660 if ( 0 != $offset ) {
661 $po = $offset - $limit;
662 if ( $po < 0 ) { $po = 0; }
663 $q = "limit={$limit}&offset={$po}";
664 if ( '' != $query ) { $q .= "&{$query}"; }
665 $plink = '<a href="' . wfLocalUrlE( $link, $q ) . "\">{$prev}</a>";
666 } else { $plink = $prev; }
667
668 $no = $offset + $limit;
669 $q = "limit={$limit}&offset={$no}";
670 if ( "" != $query ) { $q .= "&{$query}"; }
671
672 if ( $atend ) {
673 $nlink = $next;
674 } else {
675 $nlink = '<a href="' . wfLocalUrlE( $link, $q ) . "\">{$next}</a>";
676 }
677 $nums = wfNumLink( $offset, 20, $link , $query ) . ' | ' .
678 wfNumLink( $offset, 50, $link, $query ) . ' | ' .
679 wfNumLink( $offset, 100, $link, $query ) . ' | ' .
680 wfNumLink( $offset, 250, $link, $query ) . ' | ' .
681 wfNumLink( $offset, 500, $link, $query );
682
683 return wfMsg( 'viewprevnext', $plink, $nlink, $nums );
684 }
685
686 function wfNumLink( $offset, $limit, $link, $query = '' )
687 {
688 global $wgUser, $wgLang;
689 if ( '' == $query ) { $q = ''; }
690 else { $q = "{$query}&"; }
691 $q .= "limit={$limit}&offset={$offset}";
692
693 $fmtLimit = $wgLang->formatNum( $limit );
694 $s = '<a href="' . wfLocalUrlE( $link, $q ) . "\">{$fmtLimit}</a>";
695 return $s;
696 }
697
698 function wfClientAcceptsGzip() {
699 global $wgUseGzip;
700 if( $wgUseGzip ) {
701 # FIXME: we may want to blacklist some broken browsers
702 if( preg_match(
703 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
704 $_SERVER['HTTP_ACCEPT_ENCODING'],
705 $m ) ) {
706 if( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) return false;
707 wfDebug( " accepts gzip\n" );
708 return true;
709 }
710 }
711 return false;
712 }
713
714 # Yay, more global functions!
715 function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) {
716 global $wgUser, $wgRequest;
717
718 $limit = $wgRequest->getInt( 'limit', 0 );
719 if( $limit < 0 ) $limit = 0;
720 if( ( $limit == 0 ) && ( $optionname != '' ) ) {
721 $limit = (int)$wgUser->getOption( $optionname );
722 }
723 if( $limit <= 0 ) $limit = $deflimit;
724 if( $limit > 5000 ) $limit = 5000; # We have *some* limits...
725
726 $offset = $wgRequest->getInt( 'offset', 0 );
727 if( $offset < 0 ) $offset = 0;
728
729 return array( $limit, $offset );
730 }
731
732 # Escapes the given text so that it may be output using addWikiText()
733 # without any linking, formatting, etc. making its way through. This
734 # is achieved by substituting certain characters with HTML entities.
735 # As required by the callers, <nowiki> is not used. It currently does
736 # not filter out characters which have special meaning only at the
737 # start of a line, such as "*".
738 function wfEscapeWikiText( $text )
739 {
740 $text = str_replace(
741 array( '[', '|', "'", 'ISBN ' , '://' , "\n=" ),
742 array( '&#91;', '&#124;', '&#39;', 'ISBN&#32;', '&#58;//' , "\n&#61;" ),
743 htmlspecialchars($text) );
744 return $text;
745 }
746
747 function wfQuotedPrintable( $string, $charset = '' )
748 {
749 # Probably incomplete; see RFC 2045
750 if( empty( $charset ) ) {
751 global $wgInputEncoding;
752 $charset = $wgInputEncoding;
753 }
754 $charset = strtoupper( $charset );
755 $charset = str_replace( 'ISO-8859', 'ISO8859', $charset ); // ?
756
757 $illegal = '\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\xff=';
758 $replace = $illegal . '\t ?_';
759 if( !preg_match( "/[$illegal]/", $string ) ) return $string;
760 $out = "=?$charset?Q?";
761 $out .= preg_replace( "/([$replace])/e", 'sprintf("=%02X",ord("$1"))', $string );
762 $out .= '?=';
763 return $out;
764 }
765
766 function wfTime(){
767 $st = explode( ' ', microtime() );
768 return (float)$st[0] + (float)$st[1];
769 }
770
771 # Changes the first character to an HTML entity
772 function wfHtmlEscapeFirst( $text ) {
773 $ord = ord($text);
774 $newText = substr($text, 1);
775 return "&#$ord;$newText";
776 }
777
778 # Sets dest to source and returns the original value of dest
779 # If source is NULL, it just returns the value, it doesn't set the variable
780 function wfSetVar( &$dest, $source )
781 {
782 $temp = $dest;
783 if ( !is_null( $source ) ) {
784 $dest = $source;
785 }
786 return $temp;
787 }
788
789 # As for wfSetVar except setting a bit
790 function wfSetBit( &$dest, $bit, $state = true ) {
791 $temp = (bool)($dest & $bit );
792 if ( !is_null( $state ) ) {
793 if ( $state ) {
794 $dest |= $bit;
795 } else {
796 $dest &= ~$bit;
797 }
798 }
799 return $temp;
800 }
801
802 # This function takes two arrays as input, and returns a CGI-style string, e.g.
803 # "days=7&limit=100". Options in the first array override options in the second.
804 # Options set to "" will not be output.
805 function wfArrayToCGI( $array1, $array2 = NULL )
806 {
807 if ( !is_null( $array2 ) ) {
808 $array1 = $array1 + $array2;
809 }
810
811 $cgi = '';
812 foreach ( $array1 as $key => $value ) {
813 if ( '' !== $value ) {
814 if ( '' != $cgi ) {
815 $cgi .= '&';
816 }
817 $cgi .= "{$key}={$value}";
818 }
819 }
820 return $cgi;
821 }
822
823 # This is obsolete, use SquidUpdate::purge()
824 function wfPurgeSquidServers ($urlArr) {
825 SquidUpdate::purge( $urlArr );
826 }
827
828 # Windows-compatible version of escapeshellarg()
829 function wfEscapeShellArg( )
830 {
831 $args = func_get_args();
832 $first = true;
833 $retVal = '';
834 foreach ( $args as $arg ) {
835 if ( !$first ) {
836 $retVal .= ' ';
837 } else {
838 $first = false;
839 }
840
841 if ( wfIsWindows() ) {
842 $retVal .= '"' . str_replace( '"','\"', $arg ) . '"';
843 } else {
844 $retVal .= escapeshellarg( $arg );
845 }
846 }
847 return $retVal;
848 }
849
850 # wfMerge attempts to merge differences between three texts.
851 # Returns true for a clean merge and false for failure or a conflict.
852
853 function wfMerge( $old, $mine, $yours, &$result ){
854 global $wgDiff3;
855
856 # This check may also protect against code injection in
857 # case of broken installations.
858 if(! file_exists( $wgDiff3 ) ){
859 return false;
860 }
861
862 # Make temporary files
863 $td = '/tmp/';
864 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
865 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
866 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
867
868 fwrite( $oldtextFile, $old ); fclose( $oldtextFile );
869 fwrite( $mytextFile, $mine ); fclose( $mytextFile );
870 fwrite( $yourtextFile, $yours ); fclose( $yourtextFile );
871
872 # Check for a conflict
873 $cmd = wfEscapeShellArg( $wgDiff3 ) . ' -a --overlap-only ' .
874 wfEscapeShellArg( $mytextName ) . ' ' .
875 wfEscapeShellArg( $oldtextName ) . ' ' .
876 wfEscapeShellArg( $yourtextName );
877 $handle = popen( $cmd, 'r' );
878
879 if( fgets( $handle ) ){
880 $conflict = true;
881 } else {
882 $conflict = false;
883 }
884 pclose( $handle );
885
886 # Merge differences
887 $cmd = wfEscapeShellArg( $wgDiff3 ) . ' -a -e --merge ' .
888 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
889 $handle = popen( $cmd, 'r' );
890 $result = '';
891 do {
892 $data = fread( $handle, 8192 );
893 if ( strlen( $data ) == 0 ) {
894 break;
895 }
896 $result .= $data;
897 } while ( true );
898 pclose( $handle );
899 unlink( $mytextName ); unlink( $oldtextName ); unlink( $yourtextName );
900 return ! $conflict;
901 }
902
903 function wfVarDump( $var )
904 {
905 global $wgOut;
906 $s = str_replace("\n","<br>\n", var_export( $var, true ) . "\n");
907 if ( headers_sent() || !@is_object( $wgOut ) ) {
908 print $s;
909 } else {
910 $wgOut->addHTML( $s );
911 }
912 }
913
914 # Provide a simple HTTP error.
915 function wfHttpError( $code, $label, $desc ) {
916 global $wgOut;
917 $wgOut->disable();
918 header( "HTTP/1.0 $code $label" );
919 header( "Status: $code $label" );
920 $wgOut->sendCacheControl();
921
922 # Don't send content if it's a HEAD request.
923 if( $_SERVER['REQUEST_METHOD'] == 'HEAD' ) {
924 header( 'Content-type: text/plain' );
925 print "$desc\n";
926 }
927 }
928
929 # Converts an Accept-* header into an array mapping string values to quality factors
930 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
931 # No arg means accept anything (per HTTP spec)
932 if( !$accept ) {
933 return array( $def => 1 );
934 }
935
936 $prefs = array();
937
938 $parts = explode( ',', $accept );
939
940 foreach( $parts as $part ) {
941 # FIXME: doesn't deal with params like 'text/html; level=1'
942 @list( $value, $qpart ) = explode( ';', $part );
943 if( !isset( $qpart ) ) {
944 $prefs[$value] = 1;
945 } elseif( preg_match( '/q\s*=\s*(\d*\.\d+)/', $qpart, $match ) ) {
946 $prefs[$value] = $match[1];
947 }
948 }
949
950 return $prefs;
951 }
952
953 /* private */ function mimeTypeMatch( $type, $avail ) {
954 if( array_key_exists($type, $avail) ) {
955 return $type;
956 } else {
957 $parts = explode( '/', $type );
958 if( array_key_exists( $parts[0] . '/*', $avail ) ) {
959 return $parts[0] . '/*';
960 } elseif( array_key_exists( '*/*', $avail ) ) {
961 return '*/*';
962 } else {
963 return NULL;
964 }
965 }
966 }
967
968 # FIXME: doesn't handle params like 'text/plain; charset=UTF-8'
969 # XXX: generalize to negotiate other stuff
970 function wfNegotiateType( $cprefs, $sprefs ) {
971 $combine = array();
972
973 foreach( array_keys($sprefs) as $type ) {
974 $parts = explode( '/', $type );
975 if( $parts[1] != '*' ) {
976 $ckey = mimeTypeMatch( $type, $cprefs );
977 if( $ckey ) {
978 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
979 }
980 }
981 }
982
983 foreach( array_keys( $cprefs ) as $type ) {
984 $parts = explode( '/', $type );
985 if( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
986 $skey = mimeTypeMatch( $type, $sprefs );
987 if( $skey ) {
988 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
989 }
990 }
991 }
992
993 $bestq = 0;
994 $besttype = NULL;
995
996 foreach( array_keys( $combine ) as $type ) {
997 if( $combine[$type] > $bestq ) {
998 $besttype = $type;
999 $bestq = $combine[$type];
1000 }
1001 }
1002
1003 return $besttype;
1004 }
1005
1006 # Array lookup
1007 # Returns an array where the values in the first array are replaced by the
1008 # values in the second array with the corresponding keys
1009 function wfArrayLookup( $a, $b )
1010 {
1011 return array_flip( array_intersect( array_flip( $a ), array_keys( $b ) ) );
1012 }
1013
1014 # Since Windows is so different to any of the other popular OSes, it seems appropriate
1015 # to have a simple way to test for its presence
1016 function wfIsWindows() {
1017 if (substr(php_uname(), 0, 7) == 'Windows') {
1018 return true;
1019 } else {
1020 return false;
1021 }
1022 }
1023
1024
1025 # Ideally we'd be using actual time fields in the db
1026 function wfTimestamp2Unix( $ts ) {
1027 return gmmktime( ( (int)substr( $ts, 8, 2) ),
1028 (int)substr( $ts, 10, 2 ), (int)substr( $ts, 12, 2 ),
1029 (int)substr( $ts, 4, 2 ), (int)substr( $ts, 6, 2 ),
1030 (int)substr( $ts, 0, 4 ) );
1031 }
1032
1033 function wfUnix2Timestamp( $unixtime ) {
1034 return gmdate( "YmdHis", $unixtime );
1035 }
1036
1037 function wfTimestampNow() {
1038 # return NOW
1039 return gmdate( "YmdHis" );
1040 }
1041
1042 # Sorting hack for MySQL 3, which doesn't use index sorts for DESC
1043 function wfInvertTimestamp( $ts ) {
1044 return strtr(
1045 $ts,
1046 "0123456789",
1047 "9876543210"
1048 );
1049 }
1050
1051 # Reference-counted warning suppression
1052 function wfSuppressWarnings( $end = false ) {
1053 static $suppressCount = 0;
1054 static $originalLevel = false;
1055
1056 if ( $end ) {
1057 if ( $suppressCount ) {
1058 $suppressCount --;
1059 if ( !$suppressCount ) {
1060 error_reporting( $originalLevel );
1061 }
1062 }
1063 } else {
1064 if ( !$suppressCount ) {
1065 $originalLevel = error_reporting( E_ALL & ~( E_WARNING | E_NOTICE ) );
1066 }
1067 $suppressCount++;
1068 }
1069 }
1070
1071 # Restore error level to previous value
1072 function wfRestoreWarnings() {
1073 wfSuppressWarnings( true );
1074 }
1075
1076 ?>