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