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