expand comment
[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 $args = func_get_args();
292 if ( count( $args ) ) {
293 array_shift( $args );
294 }
295 return wfMsgReal( $key, $args, true );
296 }
297
298 # Get a message from the language file
299 function wfMsgNoDB( $key ) {
300 $args = func_get_args();
301 if ( count( $args ) ) {
302 array_shift( $args );
303 }
304 return wfMsgReal( $key, $args, false );
305 }
306
307 # Really get a message
308 function wfMsgReal( $key, $args, $useDB ) {
309 global $wgReplacementKeys, $wgMessageCache, $wgLang;
310
311 $fname = 'wfMsg';
312 wfProfileIn( $fname );
313 if ( $wgMessageCache ) {
314 $message = $wgMessageCache->get( $key, $useDB );
315 } elseif ( $wgLang ) {
316 $message = $wgLang->getMessage( $key );
317 } else {
318 wfDebug( "No language object when getting $key\n" );
319 $message = "&lt;$key&gt;";
320 }
321
322 # Replace arguments
323 if( count( $args ) ) {
324 $message = str_replace( $wgReplacementKeys, $args, $message );
325 }
326 wfProfileOut( $fname );
327 return $message;
328 }
329
330 function wfCleanFormFields( $fields )
331 {
332 wfDebugDieBacktrace( 'Call to obsolete wfCleanFormFields(). Use wgRequest instead...' );
333 }
334
335 function wfMungeQuotes( $in )
336 {
337 $out = str_replace( '%', '%25', $in );
338 $out = str_replace( "'", '%27', $out );
339 $out = str_replace( '"', '%22', $out );
340 return $out;
341 }
342
343 function wfDemungeQuotes( $in )
344 {
345 $out = str_replace( '%22', '"', $in );
346 $out = str_replace( '%27', "'", $out );
347 $out = str_replace( '%25', '%', $out );
348 return $out;
349 }
350
351 function wfCleanQueryVar( $var )
352 {
353 wfDebugDieBacktrace( 'Call to obsolete function wfCleanQueryVar(); use wgRequest instead' );
354 }
355
356 function wfSearch( $s )
357 {
358 $se = new SearchEngine( $s );
359 $se->showResults();
360 }
361
362 function wfGo( $s )
363 { # pick the nearest match
364 $se = new SearchEngine( $s );
365 $se->goResult();
366 }
367
368 # Just like exit() but makes a note of it.
369 # Commits open transactions except if the error parameter is set
370 function wfAbruptExit( $error = false ){
371 global $wgLoadBalancer;
372 static $called = false;
373 if ( $called ){
374 exit();
375 }
376 $called = true;
377
378 if( function_exists( 'debug_backtrace' ) ){ // PHP >= 4.3
379 $bt = debug_backtrace();
380 for($i = 0; $i < count($bt) ; $i++){
381 $file = $bt[$i]['file'];
382 $line = $bt[$i]['line'];
383 wfDebug("WARNING: Abrupt exit in $file at line $line\n");
384 }
385 } else {
386 wfDebug('WARNING: Abrupt exit\n');
387 }
388 if ( !$error ) {
389 $wgLoadBalancer->closeAll();
390 }
391 exit();
392 }
393
394 function wfErrorExit() {
395 wfAbruptExit( true );
396 }
397
398 function wfDebugDieBacktrace( $msg = '' ) {
399 global $wgCommandLineMode;
400
401 if ( function_exists( 'debug_backtrace' ) ) {
402 if ( $wgCommandLineMode ) {
403 $msg .= "\nBacktrace:\n";
404 } else {
405 $msg .= "\n<p>Backtrace:</p>\n<ul>\n";
406 }
407 $backtrace = debug_backtrace();
408 foreach( $backtrace as $call ) {
409 $f = explode( DIRECTORY_SEPARATOR, $call['file'] );
410 $file = $f[count($f)-1];
411 if ( $wgCommandLineMode ) {
412 $msg .= "$file line {$call['line']} calls ";
413 } else {
414 $msg .= '<li>' . $file . " line " . $call['line'] . ' calls ';
415 }
416 if( !empty( $call['class'] ) ) $msg .= $call['class'] . '::';
417 $msg .= $call['function'] . "()";
418
419 if ( $wgCommandLineMode ) {
420 $msg .= "\n";
421 } else {
422 $msg .= "</li>\n";
423 }
424 }
425 }
426 die( $msg );
427 }
428
429 function wfNumberOfArticles()
430 {
431 global $wgNumberOfArticles;
432
433 wfLoadSiteStats();
434 return $wgNumberOfArticles;
435 }
436
437 /* private */ function wfLoadSiteStats()
438 {
439 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
440 $fname = 'wfLoadSiteStats';
441
442 if ( -1 != $wgNumberOfArticles ) return;
443 $dbr =& wfGetDB( DB_SLAVE );
444 $s = $dbr->getArray( 'site_stats',
445 array( 'ss_total_views', 'ss_total_edits', 'ss_good_articles' ),
446 array( 'ss_row_id' => 1 ), $fname
447 );
448
449 if ( $s === false ) {
450 return;
451 } else {
452 $wgTotalViews = $s->ss_total_views;
453 $wgTotalEdits = $s->ss_total_edits;
454 $wgNumberOfArticles = $s->ss_good_articles;
455 }
456 }
457
458 function wfEscapeHTML( $in )
459 {
460 return str_replace(
461 array( '&', '"', '>', '<' ),
462 array( '&amp;', '&quot;', '&gt;', '&lt;' ),
463 $in );
464 }
465
466 function wfEscapeHTMLTagsOnly( $in ) {
467 return str_replace(
468 array( '"', '>', '<' ),
469 array( '&quot;', '&gt;', '&lt;' ),
470 $in );
471 }
472
473 function wfUnescapeHTML( $in )
474 {
475 $in = str_replace( '&lt;', '<', $in );
476 $in = str_replace( '&gt;', '>', $in );
477 $in = str_replace( '&quot;', '"', $in );
478 $in = str_replace( '&amp;', '&', $in );
479 return $in;
480 }
481
482 function wfImageDir( $fname )
483 {
484 global $wgUploadDirectory;
485
486 $hash = md5( $fname );
487 $oldumask = umask(0);
488 $dest = $wgUploadDirectory . '/' . $hash{0};
489 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
490 $dest .= '/' . substr( $hash, 0, 2 );
491 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
492
493 umask( $oldumask );
494 return $dest;
495 }
496
497 function wfImageThumbDir( $fname , $subdir='thumb')
498 {
499 return wfImageArchiveDir( $fname, $subdir );
500 }
501
502 function wfImageArchiveDir( $fname , $subdir='archive')
503 {
504 global $wgUploadDirectory;
505
506 $hash = md5( $fname );
507 $oldumask = umask(0);
508
509 # Suppress warning messages here; if the file itself can't
510 # be written we'll worry about it then.
511 $archive = "{$wgUploadDirectory}/{$subdir}";
512 if ( ! is_dir( $archive ) ) { @mkdir( $archive, 0777 ); }
513 $archive .= '/' . $hash{0};
514 if ( ! is_dir( $archive ) ) { @mkdir( $archive, 0777 ); }
515 $archive .= '/' . substr( $hash, 0, 2 );
516 if ( ! is_dir( $archive ) ) { @mkdir( $archive, 0777 ); }
517
518 umask( $oldumask );
519 return $archive;
520 }
521
522 function wfRecordUpload( $name, $oldver, $size, $desc, $copyStatus = "", $source = "" )
523 {
524 global $wgUser, $wgLang, $wgTitle, $wgOut, $wgDeferredUpdateList;
525 global $wgUseCopyrightUpload;
526
527 $fname = 'wfRecordUpload';
528 $dbw =& wfGetDB( DB_MASTER );
529
530 # img_name must be unique
531 if ( !$dbw->indexUnique( 'image', 'img_name' ) ) {
532 wfDebugDieBacktrace( 'Database schema not up to date, please run maintenance/archives/patch-image_name_unique.sql' );
533 }
534
535
536 $now = wfTimestampNow();
537 $won = wfInvertTimestamp( $now );
538 $size = IntVal( $size );
539
540 if ( $wgUseCopyrightUpload )
541 {
542 $textdesc = '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $desc . "\n" .
543 '== ' . wfMsg ( 'filestatus' ) . " ==\n" . $copyStatus . "\n" .
544 '== ' . wfMsg ( 'filesource' ) . " ==\n" . $source ;
545 }
546 else $textdesc = $desc ;
547
548 $now = wfTimestampNow();
549 $won = wfInvertTimestamp( $now );
550
551 # Test to see if the row exists using INSERT IGNORE
552 # This avoids race conditions by locking the row until the commit, and also
553 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
554 $dbw->insert( 'image',
555 array(
556 'img_name' => $name,
557 'img_size'=> $size,
558 'img_timestamp' => $now,
559 'img_description' => $desc,
560 'img_user' => $wgUser->getID(),
561 'img_user_text' => $wgUser->getName(),
562 ), $fname, 'IGNORE'
563 );
564 $descTitle = Title::makeTitle( NS_IMAGE, $name );
565
566 if ( $dbw->affectedRows() ) {
567 # Successfully inserted, this is a new image
568 $id = $descTitle->getArticleID();
569
570 if ( $id == 0 ) {
571 $seqVal = $dbw->nextSequenceValue( 'cur_cur_id_seq' );
572 $dbw->insertArray( 'cur',
573 array(
574 'cur_id' => $seqVal,
575 'cur_namespace' => NS_IMAGE,
576 'cur_title' => $name,
577 'cur_comment' => $desc,
578 'cur_user' => $wgUser->getID(),
579 'cur_user_text' => $wgUser->getName(),
580 'cur_timestamp' => $now,
581 'cur_is_new' => 1,
582 'cur_text' => $textdesc,
583 'inverse_timestamp' => $won,
584 'cur_touched' => $now
585 ), $fname
586 );
587 $id = $dbw->insertId() or 0; # We should throw an error instead
588
589 RecentChange::notifyNew( $now, $descTitle, 0, $wgUser, $desc );
590
591 $u = new SearchUpdate( $id, $name, $desc );
592 $u->doUpdate();
593 }
594 } else {
595 # Collision, this is an update of an image
596 # Get current image row for update
597 $s = $dbw->getArray( 'image', array( 'img_name','img_size','img_timestamp','img_description',
598 'img_user','img_user_text' ), array( 'img_name' => $name ), $fname, 'FOR UPDATE' );
599
600 # Insert it into oldimage
601 $dbw->insertArray( 'oldimage',
602 array(
603 'oi_name' => $s->img_name,
604 'oi_archive_name' => $oldver,
605 'oi_size' => $s->img_size,
606 'oi_timestamp' => $s->img_timestamp,
607 'oi_description' => $s->img_description,
608 'oi_user' => $s->img_user,
609 'oi_user_text' => $s->img_user_text
610 ), $fname
611 );
612
613 # Update the current image row
614 $dbw->updateArray( 'image',
615 array( /* SET */
616 'img_size' => $size,
617 'img_timestamp' => wfTimestampNow(),
618 'img_user' => $wgUser->getID(),
619 'img_user_text' => $wgUser->getName(),
620 'img_description' => $desc,
621 ), array( /* WHERE */
622 'img_name' => $name
623 ), $fname
624 );
625
626 # Invalidate the cache for the description page
627 $descTitle->invalidateCache();
628 }
629
630 $log = new LogPage( wfMsg( 'uploadlogpage' ), wfMsg( 'uploadlogpagetext' ) );
631 $da = wfMsg( 'uploadedimage', '[[:' . $wgLang->getNsText(
632 Namespace::getImage() ) . ":{$name}|{$name}]]" );
633 $ta = wfMsg( 'uploadedimage', $name );
634 $log->addEntry( $da, $desc, $ta );
635 }
636
637
638 /* Some generic result counters, pulled out of SearchEngine */
639
640 function wfShowingResults( $offset, $limit )
641 {
642 global $wgLang;
643 return wfMsg( 'showingresults', $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+1 ) );
644 }
645
646 function wfShowingResultsNum( $offset, $limit, $num )
647 {
648 global $wgLang;
649 return wfMsg( 'showingresultsnum', $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+1 ), $wgLang->formatNum( $num ) );
650 }
651
652 function wfViewPrevNext( $offset, $limit, $link, $query = '', $atend = false )
653 {
654 global $wgUser, $wgLang;
655 $fmtLimit = $wgLang->formatNum( $limit );
656 $prev = wfMsg( 'prevn', $fmtLimit );
657 $next = wfMsg( 'nextn', $fmtLimit );
658 $link = wfUrlencode( $link );
659
660 $sk = $wgUser->getSkin();
661 if ( 0 != $offset ) {
662 $po = $offset - $limit;
663 if ( $po < 0 ) { $po = 0; }
664 $q = "limit={$limit}&offset={$po}";
665 if ( '' != $query ) { $q .= "&{$query}"; }
666 $plink = '<a href="' . wfLocalUrlE( $link, $q ) . "\">{$prev}</a>";
667 } else { $plink = $prev; }
668
669 $no = $offset + $limit;
670 $q = "limit={$limit}&offset={$no}";
671 if ( "" != $query ) { $q .= "&{$query}"; }
672
673 if ( $atend ) {
674 $nlink = $next;
675 } else {
676 $nlink = '<a href="' . wfLocalUrlE( $link, $q ) . "\">{$next}</a>";
677 }
678 $nums = wfNumLink( $offset, 20, $link , $query ) . ' | ' .
679 wfNumLink( $offset, 50, $link, $query ) . ' | ' .
680 wfNumLink( $offset, 100, $link, $query ) . ' | ' .
681 wfNumLink( $offset, 250, $link, $query ) . ' | ' .
682 wfNumLink( $offset, 500, $link, $query );
683
684 return wfMsg( 'viewprevnext', $plink, $nlink, $nums );
685 }
686
687 function wfNumLink( $offset, $limit, $link, $query = '' )
688 {
689 global $wgUser, $wgLang;
690 if ( '' == $query ) { $q = ''; }
691 else { $q = "{$query}&"; }
692 $q .= "limit={$limit}&offset={$offset}";
693
694 $fmtLimit = $wgLang->formatNum( $limit );
695 $s = '<a href="' . wfLocalUrlE( $link, $q ) . "\">{$fmtLimit}</a>";
696 return $s;
697 }
698
699 function wfClientAcceptsGzip() {
700 global $wgUseGzip;
701 if( $wgUseGzip ) {
702 # FIXME: we may want to blacklist some broken browsers
703 if( preg_match(
704 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
705 $_SERVER['HTTP_ACCEPT_ENCODING'],
706 $m ) ) {
707 if( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) return false;
708 wfDebug( " accepts gzip\n" );
709 return true;
710 }
711 }
712 return false;
713 }
714
715 # Yay, more global functions!
716 function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) {
717 global $wgUser, $wgRequest;
718
719 $limit = $wgRequest->getInt( 'limit', 0 );
720 if( $limit < 0 ) $limit = 0;
721 if( ( $limit == 0 ) && ( $optionname != '' ) ) {
722 $limit = (int)$wgUser->getOption( $optionname );
723 }
724 if( $limit <= 0 ) $limit = $deflimit;
725 if( $limit > 5000 ) $limit = 5000; # We have *some* limits...
726
727 $offset = $wgRequest->getInt( 'offset', 0 );
728 if( $offset < 0 ) $offset = 0;
729
730 return array( $limit, $offset );
731 }
732
733 # Escapes the given text so that it may be output using addWikiText()
734 # without any linking, formatting, etc. making its way through. This
735 # is achieved by substituting certain characters with HTML entities.
736 # As required by the callers, <nowiki> is not used. It currently does
737 # not filter out characters which have special meaning only at the
738 # start of a line, such as "*".
739 function wfEscapeWikiText( $text )
740 {
741 $text = str_replace(
742 array( '[', '|', "'", 'ISBN ' , '://' , "\n=" ),
743 array( '&#91;', '&#124;', '&#39;', 'ISBN&#32;', '&#58;//' , "\n&#61;" ),
744 htmlspecialchars($text) );
745 return $text;
746 }
747
748 function wfQuotedPrintable( $string, $charset = '' )
749 {
750 # Probably incomplete; see RFC 2045
751 if( empty( $charset ) ) {
752 global $wgInputEncoding;
753 $charset = $wgInputEncoding;
754 }
755 $charset = strtoupper( $charset );
756 $charset = str_replace( 'ISO-8859', 'ISO8859', $charset ); // ?
757
758 $illegal = '\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\xff=';
759 $replace = $illegal . '\t ?_';
760 if( !preg_match( "/[$illegal]/", $string ) ) return $string;
761 $out = "=?$charset?Q?";
762 $out .= preg_replace( "/([$replace])/e", 'sprintf("=%02X",ord("$1"))', $string );
763 $out .= '?=';
764 return $out;
765 }
766
767 function wfTime(){
768 $st = explode( ' ', microtime() );
769 return (float)$st[0] + (float)$st[1];
770 }
771
772 # Changes the first character to an HTML entity
773 function wfHtmlEscapeFirst( $text ) {
774 $ord = ord($text);
775 $newText = substr($text, 1);
776 return "&#$ord;$newText";
777 }
778
779 # Sets dest to source and returns the original value of dest
780 # If source is NULL, it just returns the value, it doesn't set the variable
781 function wfSetVar( &$dest, $source )
782 {
783 $temp = $dest;
784 if ( !is_null( $source ) ) {
785 $dest = $source;
786 }
787 return $temp;
788 }
789
790 # As for wfSetVar except setting a bit
791 function wfSetBit( &$dest, $bit, $state = true ) {
792 $temp = (bool)($dest & $bit );
793 if ( !is_null( $state ) ) {
794 if ( $state ) {
795 $dest |= $bit;
796 } else {
797 $dest &= ~$bit;
798 }
799 }
800 return $temp;
801 }
802
803 # This function takes two arrays as input, and returns a CGI-style string, e.g.
804 # "days=7&limit=100". Options in the first array override options in the second.
805 # Options set to "" will not be output.
806 function wfArrayToCGI( $array1, $array2 = NULL )
807 {
808 if ( !is_null( $array2 ) ) {
809 $array1 = $array1 + $array2;
810 }
811
812 $cgi = '';
813 foreach ( $array1 as $key => $value ) {
814 if ( '' !== $value ) {
815 if ( '' != $cgi ) {
816 $cgi .= '&';
817 }
818 $cgi .= "{$key}={$value}";
819 }
820 }
821 return $cgi;
822 }
823
824 # This is obsolete, use SquidUpdate::purge()
825 function wfPurgeSquidServers ($urlArr) {
826 SquidUpdate::purge( $urlArr );
827 }
828
829 # Windows-compatible version of escapeshellarg()
830 function wfEscapeShellArg( )
831 {
832 $args = func_get_args();
833 $first = true;
834 $retVal = '';
835 foreach ( $args as $arg ) {
836 if ( !$first ) {
837 $retVal .= ' ';
838 } else {
839 $first = false;
840 }
841
842 if ( wfIsWindows() ) {
843 $retVal .= '"' . str_replace( '"','\"', $arg ) . '"';
844 } else {
845 $retVal .= escapeshellarg( $arg );
846 }
847 }
848 return $retVal;
849 }
850
851 # wfMerge attempts to merge differences between three texts.
852 # Returns true for a clean merge and false for failure or a conflict.
853
854 function wfMerge( $old, $mine, $yours, &$result ){
855 global $wgDiff3;
856
857 # This check may also protect against code injection in
858 # case of broken installations.
859 if(! file_exists( $wgDiff3 ) ){
860 return false;
861 }
862
863 # Make temporary files
864 $td = '/tmp/';
865 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
866 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
867 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
868
869 fwrite( $oldtextFile, $old ); fclose( $oldtextFile );
870 fwrite( $mytextFile, $mine ); fclose( $mytextFile );
871 fwrite( $yourtextFile, $yours ); fclose( $yourtextFile );
872
873 # Check for a conflict
874 $cmd = wfEscapeShellArg( $wgDiff3 ) . ' -a --overlap-only ' .
875 wfEscapeShellArg( $mytextName ) . ' ' .
876 wfEscapeShellArg( $oldtextName ) . ' ' .
877 wfEscapeShellArg( $yourtextName );
878 $handle = popen( $cmd, 'r' );
879
880 if( fgets( $handle ) ){
881 $conflict = true;
882 } else {
883 $conflict = false;
884 }
885 pclose( $handle );
886
887 # Merge differences
888 $cmd = wfEscapeShellArg( $wgDiff3 ) . ' -a -e --merge ' .
889 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
890 $handle = popen( $cmd, 'r' );
891 $result = '';
892 do {
893 $data = fread( $handle, 8192 );
894 if ( strlen( $data ) == 0 ) {
895 break;
896 }
897 $result .= $data;
898 } while ( true );
899 pclose( $handle );
900 unlink( $mytextName ); unlink( $oldtextName ); unlink( $yourtextName );
901 return ! $conflict;
902 }
903
904 function wfVarDump( $var )
905 {
906 global $wgOut;
907 $s = str_replace("\n","<br>\n", var_export( $var, true ) . "\n");
908 if ( headers_sent() || !@is_object( $wgOut ) ) {
909 print $s;
910 } else {
911 $wgOut->addHTML( $s );
912 }
913 }
914
915 # Provide a simple HTTP error.
916 function wfHttpError( $code, $label, $desc ) {
917 global $wgOut;
918 $wgOut->disable();
919 header( "HTTP/1.0 $code $label" );
920 header( "Status: $code $label" );
921 $wgOut->sendCacheControl();
922
923 # Don't send content if it's a HEAD request.
924 if( $_SERVER['REQUEST_METHOD'] == 'HEAD' ) {
925 header( 'Content-type: text/plain' );
926 print "$desc\n";
927 }
928 }
929
930 # Converts an Accept-* header into an array mapping string values to quality factors
931 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
932 # No arg means accept anything (per HTTP spec)
933 if( !$accept ) {
934 return array( $def => 1 );
935 }
936
937 $prefs = array();
938
939 $parts = explode( ',', $accept );
940
941 foreach( $parts as $part ) {
942 # FIXME: doesn't deal with params like 'text/html; level=1'
943 @list( $value, $qpart ) = explode( ';', $part );
944 if( !isset( $qpart ) ) {
945 $prefs[$value] = 1;
946 } elseif( preg_match( '/q\s*=\s*(\d*\.\d+)/', $qpart, $match ) ) {
947 $prefs[$value] = $match[1];
948 }
949 }
950
951 return $prefs;
952 }
953
954 /* private */ function mimeTypeMatch( $type, $avail ) {
955 if( array_key_exists($type, $avail) ) {
956 return $type;
957 } else {
958 $parts = explode( '/', $type );
959 if( array_key_exists( $parts[0] . '/*', $avail ) ) {
960 return $parts[0] . '/*';
961 } elseif( array_key_exists( '*/*', $avail ) ) {
962 return '*/*';
963 } else {
964 return NULL;
965 }
966 }
967 }
968
969 # FIXME: doesn't handle params like 'text/plain; charset=UTF-8'
970 # XXX: generalize to negotiate other stuff
971 function wfNegotiateType( $cprefs, $sprefs ) {
972 $combine = array();
973
974 foreach( array_keys($sprefs) as $type ) {
975 $parts = explode( '/', $type );
976 if( $parts[1] != '*' ) {
977 $ckey = mimeTypeMatch( $type, $cprefs );
978 if( $ckey ) {
979 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
980 }
981 }
982 }
983
984 foreach( array_keys( $cprefs ) as $type ) {
985 $parts = explode( '/', $type );
986 if( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
987 $skey = mimeTypeMatch( $type, $sprefs );
988 if( $skey ) {
989 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
990 }
991 }
992 }
993
994 $bestq = 0;
995 $besttype = NULL;
996
997 foreach( array_keys( $combine ) as $type ) {
998 if( $combine[$type] > $bestq ) {
999 $besttype = $type;
1000 $bestq = $combine[$type];
1001 }
1002 }
1003
1004 return $besttype;
1005 }
1006
1007 # Array lookup
1008 # Returns an array where the values in the first array are replaced by the
1009 # values in the second array with the corresponding keys
1010 function wfArrayLookup( $a, $b )
1011 {
1012 return array_flip( array_intersect( array_flip( $a ), array_keys( $b ) ) );
1013 }
1014
1015 # Since Windows is so different to any of the other popular OSes, it seems appropriate
1016 # to have a simple way to test for its presence
1017 function wfIsWindows() {
1018 if (substr(php_uname(), 0, 7) == 'Windows') {
1019 return true;
1020 } else {
1021 return false;
1022 }
1023 }
1024
1025
1026 # Ideally we'd be using actual time fields in the db
1027 function wfTimestamp2Unix( $ts ) {
1028 return gmmktime( ( (int)substr( $ts, 8, 2) ),
1029 (int)substr( $ts, 10, 2 ), (int)substr( $ts, 12, 2 ),
1030 (int)substr( $ts, 4, 2 ), (int)substr( $ts, 6, 2 ),
1031 (int)substr( $ts, 0, 4 ) );
1032 }
1033
1034 function wfUnix2Timestamp( $unixtime ) {
1035 return gmdate( "YmdHis", $unixtime );
1036 }
1037
1038 function wfTimestampNow() {
1039 # return NOW
1040 return gmdate( "YmdHis" );
1041 }
1042
1043 # Sorting hack for MySQL 3, which doesn't use index sorts for DESC
1044 function wfInvertTimestamp( $ts ) {
1045 return strtr(
1046 $ts,
1047 "0123456789",
1048 "9876543210"
1049 );
1050 }
1051
1052 # Reference-counted warning suppression
1053 function wfSuppressWarnings( $end = false ) {
1054 static $suppressCount = 0;
1055 static $originalLevel = false;
1056
1057 if ( $end ) {
1058 if ( $suppressCount ) {
1059 $suppressCount --;
1060 if ( !$suppressCount ) {
1061 error_reporting( $originalLevel );
1062 }
1063 }
1064 } else {
1065 if ( !$suppressCount ) {
1066 $originalLevel = error_reporting( E_ALL & ~( E_WARNING | E_NOTICE ) );
1067 }
1068 $suppressCount++;
1069 }
1070 }
1071
1072 # Restore error level to previous value
1073 function wfRestoreWarnings() {
1074 wfSuppressWarnings( true );
1075 }
1076
1077 # Autodetect, convert and provide timestamps of various types
1078 define("TS_UNIX",0); # Standard unix timestamp (number of seconds since 1 Jan 1970)
1079 define("TS_MW",1); # Mediawiki concatenated string timestamp (yyyymmddhhmmss)
1080 define("TS_DB",2); # Standard database timestamp (yyyy-mm-dd hh:mm:ss)
1081
1082 function wfTimestamp($outputtype=TS_UNIX,$ts=0) {
1083 if (preg_match("/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)$/",$ts,$da)) {
1084 # TS_DB
1085 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1086 (int)$da[2],(int)$da[3],(int)$da[1]);
1087 } elseif (preg_match("/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/",$ts,$da)) {
1088 # TS_MW
1089 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1090 (int)$da[2],(int)$da[3],(int)$da[1]);
1091 } elseif (preg_match("/^(\d{1,13})$/",$ts,$datearray)) {
1092 # TS_UNIX
1093 $uts=$ts;
1094 }
1095
1096 if ($ts==0)
1097 $uts=time();
1098 switch($outputtype) {
1099 case TS_UNIX:
1100 return $uts;
1101 break;
1102 case TS_MW:
1103 return gmdate( "YmdHis", $uts );
1104 break;
1105 case TS_DB:
1106 return gmdate( "Y-m-d H:i:s", $uts );
1107 break;
1108 default:
1109 return;
1110 }
1111 }
1112
1113 ?>