ee48231420ab3039317377a34ae1ab5f0af31bc4
[lhc/web/wiklou.git] / includes / GlobalFunctions.php
1 <?php
2
3 /**
4 * Global functions used everywhere
5 * @package MediaWiki
6 */
7
8 /**
9 * Some globals and requires needed
10 */
11
12 /**
13 * Total number of articles
14 * @global integer $wgNumberOfArticles
15 */
16 $wgNumberOfArticles = -1; # Unset
17 /**
18 * Total number of views
19 * @global integer $wgTotalViews
20 */
21 $wgTotalViews = -1;
22 /**
23 * Total number of edits
24 * @global integer $wgTotalEdits
25 */
26 $wgTotalEdits = -1;
27
28
29 require_once( 'DatabaseFunctions.php' );
30 require_once( 'normal/UtfNormalUtil.php' );
31 require_once( 'XmlFunctions.php' );
32
33 /**
34 * Compatibility functions
35 * PHP <4.3.x is not actively supported; 4.1.x and 4.2.x might or might not work.
36 * <4.1.x will not work, as we use a number of features introduced in 4.1.0
37 * such as the new autoglobals.
38 */
39 if( !function_exists('iconv') ) {
40 # iconv support is not in the default configuration and so may not be present.
41 # Assume will only ever use utf-8 and iso-8859-1.
42 # This will *not* work in all circumstances.
43 function iconv( $from, $to, $string ) {
44 if(strcasecmp( $from, $to ) == 0) return $string;
45 if(strcasecmp( $from, 'utf-8' ) == 0) return utf8_decode( $string );
46 if(strcasecmp( $to, 'utf-8' ) == 0) return utf8_encode( $string );
47 return $string;
48 }
49 }
50
51 if( !function_exists('file_get_contents') ) {
52 # Exists in PHP 4.3.0+
53 function file_get_contents( $filename ) {
54 return implode( '', file( $filename ) );
55 }
56 }
57
58 if( !function_exists('is_a') ) {
59 # Exists in PHP 4.2.0+
60 function is_a( $object, $class_name ) {
61 return
62 (strcasecmp( get_class( $object ), $class_name ) == 0) ||
63 is_subclass_of( $object, $class_name );
64 }
65 }
66
67 # UTF-8 substr function based on a PHP manual comment
68 if ( !function_exists( 'mb_substr' ) ) {
69 function mb_substr( $str, $start ) {
70 preg_match_all( '/./us', $str, $ar );
71
72 if( func_num_args() >= 3 ) {
73 $end = func_get_arg( 2 );
74 return join( '', array_slice( $ar[0], $start, $end ) );
75 } else {
76 return join( '', array_slice( $ar[0], $start ) );
77 }
78 }
79 }
80
81 if( !function_exists( 'floatval' ) ) {
82 /**
83 * First defined in PHP 4.2.0
84 * @param mixed $var;
85 * @return float
86 */
87 function floatval( $var ) {
88 return (float)$var;
89 }
90 }
91
92 if ( !function_exists( 'array_diff_key' ) ) {
93 /**
94 * Exists in PHP 5.1.0+
95 * Not quite compatible, two-argument version only
96 * Null values will cause problems due to this use of isset()
97 */
98 function array_diff_key( $left, $right ) {
99 $result = $left;
100 foreach ( $left as $key => $value ) {
101 if ( isset( $right[$key] ) ) {
102 unset( $result[$key] );
103 }
104 }
105 return $result;
106 }
107 }
108
109
110 /**
111 * Wrapper for clone() for PHP 4, for the moment.
112 * PHP 5 won't let you declare a 'clone' function, even conditionally,
113 * so it has to be a wrapper with a different name.
114 */
115 function wfClone( $object ) {
116 // WARNING: clone() is not a function in PHP 5, so function_exists fails.
117 if( version_compare( PHP_VERSION, '5.0' ) < 0 ) {
118 return $object;
119 } else {
120 return clone( $object );
121 }
122 }
123
124 /**
125 * Where as we got a random seed
126 * @var bool $wgTotalViews
127 */
128 $wgRandomSeeded = false;
129
130 /**
131 * Seed Mersenne Twister
132 * Only necessary in PHP < 4.2.0
133 *
134 * @return bool
135 */
136 function wfSeedRandom() {
137 global $wgRandomSeeded;
138
139 if ( ! $wgRandomSeeded && version_compare( phpversion(), '4.2.0' ) < 0 ) {
140 $seed = hexdec(substr(md5(microtime()),-8)) & 0x7fffffff;
141 mt_srand( $seed );
142 $wgRandomSeeded = true;
143 }
144 }
145
146 /**
147 * Get a random decimal value between 0 and 1, in a way
148 * not likely to give duplicate values for any realistic
149 * number of articles.
150 *
151 * @return string
152 */
153 function wfRandom() {
154 # The maximum random value is "only" 2^31-1, so get two random
155 # values to reduce the chance of dupes
156 $max = mt_getrandmax();
157 $rand = number_format( (mt_rand() * $max + mt_rand())
158 / $max / $max, 12, '.', '' );
159 return $rand;
160 }
161
162 /**
163 * We want / and : to be included as literal characters in our title URLs.
164 * %2F in the page titles seems to fatally break for some reason.
165 *
166 * @param $s String:
167 * @return string
168 */
169 function wfUrlencode ( $s ) {
170 $s = urlencode( $s );
171 $s = preg_replace( '/%3[Aa]/', ':', $s );
172 $s = preg_replace( '/%2[Ff]/', '/', $s );
173
174 return $s;
175 }
176
177 /**
178 * Sends a line to the debug log if enabled or, optionally, to a comment in output.
179 * In normal operation this is a NOP.
180 *
181 * Controlling globals:
182 * $wgDebugLogFile - points to the log file
183 * $wgProfileOnly - if set, normal debug messages will not be recorded.
184 * $wgDebugRawPage - if false, 'action=raw' hits will not result in debug output.
185 * $wgDebugComments - if on, some debug items may appear in comments in the HTML output.
186 *
187 * @param $text String
188 * @param $logonly Bool: set true to avoid appearing in HTML when $wgDebugComments is set
189 */
190 function wfDebug( $text, $logonly = false ) {
191 global $wgOut, $wgDebugLogFile, $wgDebugComments, $wgProfileOnly, $wgDebugRawPage;
192
193 # Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
194 if ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' && !$wgDebugRawPage ) {
195 return;
196 }
197
198 if ( isset( $wgOut ) && $wgDebugComments && !$logonly ) {
199 $wgOut->debug( $text );
200 }
201 if ( '' != $wgDebugLogFile && !$wgProfileOnly ) {
202 # Strip unprintables; they can switch terminal modes when binary data
203 # gets dumped, which is pretty annoying.
204 $text = preg_replace( '![\x00-\x08\x0b\x0c\x0e-\x1f]!', ' ', $text );
205 @error_log( $text, 3, $wgDebugLogFile );
206 }
207 }
208
209 /**
210 * Send a line to a supplementary debug log file, if configured, or main debug log if not.
211 * $wgDebugLogGroups[$logGroup] should be set to a filename to send to a separate log.
212 *
213 * @param $logGroup String
214 * @param $text String
215 * @param $public Bool: whether to log the event in the public log if no private
216 * log file is specified, (default true)
217 */
218 function wfDebugLog( $logGroup, $text, $public = true ) {
219 global $wgDebugLogGroups, $wgDBname;
220 if( $text{strlen( $text ) - 1} != "\n" ) $text .= "\n";
221 if( isset( $wgDebugLogGroups[$logGroup] ) ) {
222 $time = wfTimestamp( TS_DB );
223 @error_log( "$time $wgDBname: $text", 3, $wgDebugLogGroups[$logGroup] );
224 } else if ( $public === true ) {
225 wfDebug( $text, true );
226 }
227 }
228
229 /**
230 * Log for database errors
231 * @param $text String: database error message.
232 */
233 function wfLogDBError( $text ) {
234 global $wgDBerrorLog;
235 if ( $wgDBerrorLog ) {
236 $host = trim(`hostname`);
237 $text = date('D M j G:i:s T Y') . "\t$host\t".$text;
238 error_log( $text, 3, $wgDBerrorLog );
239 }
240 }
241
242 /**
243 * @todo document
244 */
245 function logProfilingData() {
246 global $wgRequestTime, $wgDebugLogFile, $wgDebugRawPage, $wgRequest;
247 global $wgProfiling, $wgUser;
248 $now = wfTime();
249
250 $elapsed = $now - $wgRequestTime;
251 if ( $wgProfiling ) {
252 $prof = wfGetProfilingOutput( $wgRequestTime, $elapsed );
253 $forward = '';
254 if( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) )
255 $forward = ' forwarded for ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
256 if( !empty( $_SERVER['HTTP_CLIENT_IP'] ) )
257 $forward .= ' client IP ' . $_SERVER['HTTP_CLIENT_IP'];
258 if( !empty( $_SERVER['HTTP_FROM'] ) )
259 $forward .= ' from ' . $_SERVER['HTTP_FROM'];
260 if( $forward )
261 $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
262 if( is_object($wgUser) && $wgUser->isAnon() )
263 $forward .= ' anon';
264 $log = sprintf( "%s\t%04.3f\t%s\n",
265 gmdate( 'YmdHis' ), $elapsed,
266 urldecode( $_SERVER['REQUEST_URI'] . $forward ) );
267 if ( '' != $wgDebugLogFile && ( $wgRequest->getVal('action') != 'raw' || $wgDebugRawPage ) ) {
268 error_log( $log . $prof, 3, $wgDebugLogFile );
269 }
270 }
271 }
272
273 /**
274 * Check if the wiki read-only lock file is present. This can be used to lock
275 * off editing functions, but doesn't guarantee that the database will not be
276 * modified.
277 * @return bool
278 */
279 function wfReadOnly() {
280 global $wgReadOnlyFile, $wgReadOnly;
281
282 if ( !is_null( $wgReadOnly ) ) {
283 return (bool)$wgReadOnly;
284 }
285 if ( '' == $wgReadOnlyFile ) {
286 return false;
287 }
288 // Set $wgReadOnly for faster access next time
289 if ( is_file( $wgReadOnlyFile ) ) {
290 $wgReadOnly = file_get_contents( $wgReadOnlyFile );
291 } else {
292 $wgReadOnly = false;
293 }
294 return (bool)$wgReadOnly;
295 }
296
297
298 /**
299 * Get a message from anywhere, for the current user language.
300 *
301 * Use wfMsgForContent() instead if the message should NOT
302 * change depending on the user preferences.
303 *
304 * Note that the message may contain HTML, and is therefore
305 * not safe for insertion anywhere. Some functions such as
306 * addWikiText will do the escaping for you. Use wfMsgHtml()
307 * if you need an escaped message.
308 *
309 * @param $key String: lookup key for the message, usually
310 * defined in languages/Language.php
311 */
312 function wfMsg( $key ) {
313 $args = func_get_args();
314 array_shift( $args );
315 return wfMsgReal( $key, $args, true );
316 }
317
318 /**
319 * Same as above except doesn't transform the message
320 */
321 function wfMsgNoTrans( $key ) {
322 $args = func_get_args();
323 array_shift( $args );
324 return wfMsgReal( $key, $args, true, false );
325 }
326
327 /**
328 * Get a message from anywhere, for the current global language
329 * set with $wgLanguageCode.
330 *
331 * Use this if the message should NOT change dependent on the
332 * language set in the user's preferences. This is the case for
333 * most text written into logs, as well as link targets (such as
334 * the name of the copyright policy page). Link titles, on the
335 * other hand, should be shown in the UI language.
336 *
337 * Note that MediaWiki allows users to change the user interface
338 * language in their preferences, but a single installation
339 * typically only contains content in one language.
340 *
341 * Be wary of this distinction: If you use wfMsg() where you should
342 * use wfMsgForContent(), a user of the software may have to
343 * customize over 70 messages in order to, e.g., fix a link in every
344 * possible language.
345 *
346 * @param $key String: lookup key for the message, usually
347 * defined in languages/Language.php
348 */
349 function wfMsgForContent( $key ) {
350 global $wgForceUIMsgAsContentMsg;
351 $args = func_get_args();
352 array_shift( $args );
353 $forcontent = true;
354 if( is_array( $wgForceUIMsgAsContentMsg ) &&
355 in_array( $key, $wgForceUIMsgAsContentMsg ) )
356 $forcontent = false;
357 return wfMsgReal( $key, $args, true, $forcontent );
358 }
359
360 /**
361 * Same as above except doesn't transform the message
362 */
363 function wfMsgForContentNoTrans( $key ) {
364 global $wgForceUIMsgAsContentMsg;
365 $args = func_get_args();
366 array_shift( $args );
367 $forcontent = true;
368 if( is_array( $wgForceUIMsgAsContentMsg ) &&
369 in_array( $key, $wgForceUIMsgAsContentMsg ) )
370 $forcontent = false;
371 return wfMsgReal( $key, $args, true, $forcontent, false );
372 }
373
374 /**
375 * Get a message from the language file, for the UI elements
376 */
377 function wfMsgNoDB( $key ) {
378 $args = func_get_args();
379 array_shift( $args );
380 return wfMsgReal( $key, $args, false );
381 }
382
383 /**
384 * Get a message from the language file, for the content
385 */
386 function wfMsgNoDBForContent( $key ) {
387 global $wgForceUIMsgAsContentMsg;
388 $args = func_get_args();
389 array_shift( $args );
390 $forcontent = true;
391 if( is_array( $wgForceUIMsgAsContentMsg ) &&
392 in_array( $key, $wgForceUIMsgAsContentMsg ) )
393 $forcontent = false;
394 return wfMsgReal( $key, $args, false, $forcontent );
395 }
396
397
398 /**
399 * Really get a message
400 * @return $key String: key to get.
401 * @return $args
402 * @return $useDB Boolean
403 * @return String: the requested message.
404 */
405 function wfMsgReal( $key, $args, $useDB, $forContent=false, $transform = true ) {
406 $fname = 'wfMsgReal';
407
408 $message = wfMsgGetKey( $key, $useDB, $forContent, $transform );
409 $message = wfMsgReplaceArgs( $message, $args );
410 return $message;
411 }
412
413 /**
414 * This function provides the message source for messages to be edited which are *not* stored in the database.
415 * @param $key String:
416 */
417 function wfMsgWeirdKey ( $key ) {
418 $subsource = str_replace ( ' ' , '_' , $key ) ;
419 $source = wfMsg ( $subsource ) ;
420 if ( $source == "&lt;{$subsource}&gt;" ) {
421 # Try again with first char lower case
422 $subsource = strtolower ( substr ( $subsource , 0 , 1 ) ) . substr ( $subsource , 1 ) ;
423 $source = wfMsg ( $subsource ) ;
424 }
425 if ( $source == "&lt;{$subsource}&gt;" ) {
426 # Didn't work either, return blank text
427 $source = "" ;
428 }
429 return $source ;
430 }
431
432 /**
433 * Fetch a message string value, but don't replace any keys yet.
434 * @param string $key
435 * @param bool $useDB
436 * @param bool $forContent
437 * @return string
438 * @private
439 */
440 function wfMsgGetKey( $key, $useDB, $forContent = false, $transform = true ) {
441 global $wgParser, $wgMsgParserOptions, $wgContLang, $wgMessageCache, $wgLang;
442
443 if ( is_object( $wgMessageCache ) )
444 $transstat = $wgMessageCache->getTransform();
445
446 if( is_object( $wgMessageCache ) ) {
447 if ( ! $transform )
448 $wgMessageCache->disableTransform();
449 $message = $wgMessageCache->get( $key, $useDB, $forContent );
450 } else {
451 if( $forContent ) {
452 $lang = &$wgContLang;
453 } else {
454 $lang = &$wgLang;
455 }
456
457 wfSuppressWarnings();
458
459 if( is_object( $lang ) ) {
460 $message = $lang->getMessage( $key );
461 } else {
462 $message = false;
463 }
464 wfRestoreWarnings();
465 if($message === false)
466 $message = Language::getMessage($key);
467 if ( $transform && strstr( $message, '{{' ) !== false ) {
468 $message = $wgParser->transformMsg($message, $wgMsgParserOptions);
469 }
470 }
471
472 if ( is_object( $wgMessageCache ) && ! $transform )
473 $wgMessageCache->setTransform( $transstat );
474
475 return $message;
476 }
477
478 /**
479 * Replace message parameter keys on the given formatted output.
480 *
481 * @param string $message
482 * @param array $args
483 * @return string
484 * @private
485 */
486 function wfMsgReplaceArgs( $message, $args ) {
487 # Fix windows line-endings
488 # Some messages are split with explode("\n", $msg)
489 $message = str_replace( "\r", '', $message );
490
491 // Replace arguments
492 if ( count( $args ) ) {
493 if ( is_array( $args[0] ) ) {
494 foreach ( $args[0] as $key => $val ) {
495 $message = str_replace( '$' . $key, $val, $message );
496 }
497 } else {
498 foreach( $args as $n => $param ) {
499 $replacementKeys['$' . ($n + 1)] = $param;
500 }
501 $message = strtr( $message, $replacementKeys );
502 }
503 }
504
505 return $message;
506 }
507
508 /**
509 * Return an HTML-escaped version of a message.
510 * Parameter replacements, if any, are done *after* the HTML-escaping,
511 * so parameters may contain HTML (eg links or form controls). Be sure
512 * to pre-escape them if you really do want plaintext, or just wrap
513 * the whole thing in htmlspecialchars().
514 *
515 * @param string $key
516 * @param string ... parameters
517 * @return string
518 */
519 function wfMsgHtml( $key ) {
520 $args = func_get_args();
521 array_shift( $args );
522 return wfMsgReplaceArgs( htmlspecialchars( wfMsgGetKey( $key, true ) ), $args );
523 }
524
525 /**
526 * Return an HTML version of message
527 * Parameter replacements, if any, are done *after* parsing the wiki-text message,
528 * so parameters may contain HTML (eg links or form controls). Be sure
529 * to pre-escape them if you really do want plaintext, or just wrap
530 * the whole thing in htmlspecialchars().
531 *
532 * @param string $key
533 * @param string ... parameters
534 * @return string
535 */
536 function wfMsgWikiHtml( $key ) {
537 global $wgOut;
538 $args = func_get_args();
539 array_shift( $args );
540 return wfMsgReplaceArgs( $wgOut->parse( wfMsgGetKey( $key, true ), /* can't be set to false */ true ), $args );
541 }
542
543 /**
544 * Returns message in the requested format
545 * @param string $key Key of the message
546 * @param array $options Processing rules:
547 * <i>parse<i>: parses wikitext to html
548 * <i>parseinline<i>: parses wikitext to html and removes the surrounding p's added by parser or tidy
549 * <i>escape<i>: filters message trough htmlspecialchars
550 * <i>replaceafter<i>: parameters are substituted after parsing or escaping
551 */
552 function wfMsgExt( $key, $options ) {
553 global $wgOut, $wgMsgParserOptions, $wgParser;
554
555 $args = func_get_args();
556 array_shift( $args );
557 array_shift( $args );
558
559 if( !is_array($options) ) {
560 $options = array($options);
561 }
562
563 $string = wfMsgGetKey( $key, true, false, false );
564
565 if( !in_array('replaceafter', $options) ) {
566 $string = wfMsgReplaceArgs( $string, $args );
567 }
568
569 if( in_array('parse', $options) ) {
570 $string = $wgOut->parse( $string, true, true );
571 } elseif ( in_array('parseinline', $options) ) {
572 $string = $wgOut->parse( $string, true, true );
573 $m = array();
574 if( preg_match( "~^<p>(.*)\n?</p>$~", $string, $m ) ) {
575 $string = $m[1];
576 }
577 } elseif ( in_array('parsemag', $options) ) {
578 global $wgTitle;
579 $parser = new Parser();
580 $parserOptions = new ParserOptions();
581 $parserOptions->setInterfaceMessage( true );
582 $parser->startExternalParse( $wgTitle, $parserOptions, OT_MSG );
583 $string = $parser->transformMsg( $string, $parserOptions );
584 }
585
586 if ( in_array('escape', $options) ) {
587 $string = htmlspecialchars ( $string );
588 }
589
590 if( in_array('replaceafter', $options) ) {
591 $string = wfMsgReplaceArgs( $string, $args );
592 }
593
594 return $string;
595 }
596
597
598 /**
599 * Just like exit() but makes a note of it.
600 * Commits open transactions except if the error parameter is set
601 */
602 function wfAbruptExit( $error = false ){
603 global $wgLoadBalancer;
604 static $called = false;
605 if ( $called ){
606 exit( -1 );
607 }
608 $called = true;
609
610 if( function_exists( 'debug_backtrace' ) ){ // PHP >= 4.3
611 $bt = debug_backtrace();
612 for($i = 0; $i < count($bt) ; $i++){
613 $file = isset($bt[$i]['file']) ? $bt[$i]['file'] : "unknown";
614 $line = isset($bt[$i]['line']) ? $bt[$i]['line'] : "unknown";
615 wfDebug("WARNING: Abrupt exit in $file at line $line\n");
616 }
617 } else {
618 wfDebug('WARNING: Abrupt exit\n');
619 }
620
621 wfProfileClose();
622 logProfilingData();
623
624 if ( !$error ) {
625 $wgLoadBalancer->closeAll();
626 }
627 exit( -1 );
628 }
629
630 /**
631 * @todo document
632 */
633 function wfErrorExit() {
634 wfAbruptExit( true );
635 }
636
637 /**
638 * Print a simple message and die, returning nonzero to the shell if any.
639 * Plain die() fails to return nonzero to the shell if you pass a string.
640 * @param string $msg
641 */
642 function wfDie( $msg='' ) {
643 echo $msg;
644 die( -1 );
645 }
646
647 /**
648 * Die with a backtrace
649 * This is meant as a debugging aid to track down where bad data comes from.
650 * Shouldn't be used in production code except maybe in "shouldn't happen" areas.
651 *
652 * @param string $msg Message shown when dieing.
653 */
654 function wfDebugDieBacktrace( $msg = '' ) {
655 global $wgCommandLineMode;
656
657 $backtrace = wfBacktrace();
658 if ( $backtrace !== false ) {
659 if ( $wgCommandLineMode ) {
660 $msg .= "\nBacktrace:\n$backtrace";
661 } else {
662 $msg .= "\n<p>Backtrace:</p>\n$backtrace";
663 }
664 }
665 echo $msg;
666 echo wfReportTime()."\n";
667 die( -1 );
668 }
669
670 /**
671 * Fetch server name for use in error reporting etc.
672 * Use real server name if available, so we know which machine
673 * in a server farm generated the current page.
674 * @return string
675 */
676 function wfHostname() {
677 if ( function_exists( 'posix_uname' ) ) {
678 // This function not present on Windows
679 $uname = @posix_uname();
680 } else {
681 $uname = false;
682 }
683 if( is_array( $uname ) && isset( $uname['nodename'] ) ) {
684 return $uname['nodename'];
685 } else {
686 # This may be a virtual server.
687 return $_SERVER['SERVER_NAME'];
688 }
689 }
690
691 /**
692 * Returns a HTML comment with the elapsed time since request.
693 * This method has no side effects.
694 * @return string
695 */
696 function wfReportTime() {
697 global $wgRequestTime;
698
699 $now = wfTime();
700 $elapsed = $now - $wgRequestTime;
701
702 $com = sprintf( "<!-- Served by %s in %01.3f secs. -->",
703 wfHostname(), $elapsed );
704 return $com;
705 }
706
707 function wfBacktrace() {
708 global $wgCommandLineMode;
709 if ( !function_exists( 'debug_backtrace' ) ) {
710 return false;
711 }
712
713 if ( $wgCommandLineMode ) {
714 $msg = '';
715 } else {
716 $msg = "<ul>\n";
717 }
718 $backtrace = debug_backtrace();
719 foreach( $backtrace as $call ) {
720 if( isset( $call['file'] ) ) {
721 $f = explode( DIRECTORY_SEPARATOR, $call['file'] );
722 $file = $f[count($f)-1];
723 } else {
724 $file = '-';
725 }
726 if( isset( $call['line'] ) ) {
727 $line = $call['line'];
728 } else {
729 $line = '-';
730 }
731 if ( $wgCommandLineMode ) {
732 $msg .= "$file line $line calls ";
733 } else {
734 $msg .= '<li>' . $file . ' line ' . $line . ' calls ';
735 }
736 if( !empty( $call['class'] ) ) $msg .= $call['class'] . '::';
737 $msg .= $call['function'] . '()';
738
739 if ( $wgCommandLineMode ) {
740 $msg .= "\n";
741 } else {
742 $msg .= "</li>\n";
743 }
744 }
745 if ( $wgCommandLineMode ) {
746 $msg .= "\n";
747 } else {
748 $msg .= "</ul>\n";
749 }
750
751 return $msg;
752 }
753
754
755 /* Some generic result counters, pulled out of SearchEngine */
756
757
758 /**
759 * @todo document
760 */
761 function wfShowingResults( $offset, $limit ) {
762 global $wgLang;
763 return wfMsg( 'showingresults', $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+1 ) );
764 }
765
766 /**
767 * @todo document
768 */
769 function wfShowingResultsNum( $offset, $limit, $num ) {
770 global $wgLang;
771 return wfMsg( 'showingresultsnum', $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+1 ), $wgLang->formatNum( $num ) );
772 }
773
774 /**
775 * @todo document
776 */
777 function wfViewPrevNext( $offset, $limit, $link, $query = '', $atend = false ) {
778 global $wgLang;
779 $fmtLimit = $wgLang->formatNum( $limit );
780 $prev = wfMsg( 'prevn', $fmtLimit );
781 $next = wfMsg( 'nextn', $fmtLimit );
782
783 if( is_object( $link ) ) {
784 $title =& $link;
785 } else {
786 $title = Title::newFromText( $link );
787 if( is_null( $title ) ) {
788 return false;
789 }
790 }
791
792 if ( 0 != $offset ) {
793 $po = $offset - $limit;
794 if ( $po < 0 ) { $po = 0; }
795 $q = "limit={$limit}&offset={$po}";
796 if ( '' != $query ) { $q .= '&'.$query; }
797 $plink = '<a href="' . $title->escapeLocalUrl( $q ) . "\">{$prev}</a>";
798 } else { $plink = $prev; }
799
800 $no = $offset + $limit;
801 $q = 'limit='.$limit.'&offset='.$no;
802 if ( '' != $query ) { $q .= '&'.$query; }
803
804 if ( $atend ) {
805 $nlink = $next;
806 } else {
807 $nlink = '<a href="' . $title->escapeLocalUrl( $q ) . "\">{$next}</a>";
808 }
809 $nums = wfNumLink( $offset, 20, $title, $query ) . ' | ' .
810 wfNumLink( $offset, 50, $title, $query ) . ' | ' .
811 wfNumLink( $offset, 100, $title, $query ) . ' | ' .
812 wfNumLink( $offset, 250, $title, $query ) . ' | ' .
813 wfNumLink( $offset, 500, $title, $query );
814
815 return wfMsg( 'viewprevnext', $plink, $nlink, $nums );
816 }
817
818 /**
819 * @todo document
820 */
821 function wfNumLink( $offset, $limit, &$title, $query = '' ) {
822 global $wgLang;
823 if ( '' == $query ) { $q = ''; }
824 else { $q = $query.'&'; }
825 $q .= 'limit='.$limit.'&offset='.$offset;
826
827 $fmtLimit = $wgLang->formatNum( $limit );
828 $s = '<a href="' . $title->escapeLocalUrl( $q ) . "\">{$fmtLimit}</a>";
829 return $s;
830 }
831
832 /**
833 * @todo document
834 * @todo FIXME: we may want to blacklist some broken browsers
835 *
836 * @return bool Whereas client accept gzip compression
837 */
838 function wfClientAcceptsGzip() {
839 global $wgUseGzip;
840 if( $wgUseGzip ) {
841 # FIXME: we may want to blacklist some broken browsers
842 if( preg_match(
843 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
844 $_SERVER['HTTP_ACCEPT_ENCODING'],
845 $m ) ) {
846 if( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) return false;
847 wfDebug( " accepts gzip\n" );
848 return true;
849 }
850 }
851 return false;
852 }
853
854 /**
855 * Obtain the offset and limit values from the request string;
856 * used in special pages
857 *
858 * @param $deflimit Default limit if none supplied
859 * @param $optionname Name of a user preference to check against
860 * @return array
861 *
862 */
863 function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) {
864 global $wgRequest;
865 return $wgRequest->getLimitOffset( $deflimit, $optionname );
866 }
867
868 /**
869 * Escapes the given text so that it may be output using addWikiText()
870 * without any linking, formatting, etc. making its way through. This
871 * is achieved by substituting certain characters with HTML entities.
872 * As required by the callers, <nowiki> is not used. It currently does
873 * not filter out characters which have special meaning only at the
874 * start of a line, such as "*".
875 *
876 * @param string $text Text to be escaped
877 */
878 function wfEscapeWikiText( $text ) {
879 $text = str_replace(
880 array( '[', '|', '\'', 'ISBN ' , '://' , "\n=", '{{' ),
881 array( '&#91;', '&#124;', '&#39;', 'ISBN&#32;', '&#58;//' , "\n&#61;", '&#123;&#123;' ),
882 htmlspecialchars($text) );
883 return $text;
884 }
885
886 /**
887 * @todo document
888 */
889 function wfQuotedPrintable( $string, $charset = '' ) {
890 # Probably incomplete; see RFC 2045
891 if( empty( $charset ) ) {
892 global $wgInputEncoding;
893 $charset = $wgInputEncoding;
894 }
895 $charset = strtoupper( $charset );
896 $charset = str_replace( 'ISO-8859', 'ISO8859', $charset ); // ?
897
898 $illegal = '\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\xff=';
899 $replace = $illegal . '\t ?_';
900 if( !preg_match( "/[$illegal]/", $string ) ) return $string;
901 $out = "=?$charset?Q?";
902 $out .= preg_replace( "/([$replace])/e", 'sprintf("=%02X",ord("$1"))', $string );
903 $out .= '?=';
904 return $out;
905 }
906
907
908 /**
909 * @todo document
910 * @return float
911 */
912 function wfTime() {
913 return microtime(true);
914 }
915
916 /**
917 * Sets dest to source and returns the original value of dest
918 * If source is NULL, it just returns the value, it doesn't set the variable
919 */
920 function wfSetVar( &$dest, $source ) {
921 $temp = $dest;
922 if ( !is_null( $source ) ) {
923 $dest = $source;
924 }
925 return $temp;
926 }
927
928 /**
929 * As for wfSetVar except setting a bit
930 */
931 function wfSetBit( &$dest, $bit, $state = true ) {
932 $temp = (bool)($dest & $bit );
933 if ( !is_null( $state ) ) {
934 if ( $state ) {
935 $dest |= $bit;
936 } else {
937 $dest &= ~$bit;
938 }
939 }
940 return $temp;
941 }
942
943 /**
944 * This function takes two arrays as input, and returns a CGI-style string, e.g.
945 * "days=7&limit=100". Options in the first array override options in the second.
946 * Options set to "" will not be output.
947 */
948 function wfArrayToCGI( $array1, $array2 = NULL )
949 {
950 if ( !is_null( $array2 ) ) {
951 $array1 = $array1 + $array2;
952 }
953
954 $cgi = '';
955 foreach ( $array1 as $key => $value ) {
956 if ( '' !== $value ) {
957 if ( '' != $cgi ) {
958 $cgi .= '&';
959 }
960 $cgi .= urlencode( $key ) . '=' . urlencode( $value );
961 }
962 }
963 return $cgi;
964 }
965
966 /**
967 * This is obsolete, use SquidUpdate::purge()
968 * @deprecated
969 */
970 function wfPurgeSquidServers ($urlArr) {
971 SquidUpdate::purge( $urlArr );
972 }
973
974 /**
975 * Windows-compatible version of escapeshellarg()
976 * Windows doesn't recognise single-quotes in the shell, but the escapeshellarg()
977 * function puts single quotes in regardless of OS
978 */
979 function wfEscapeShellArg( ) {
980 $args = func_get_args();
981 $first = true;
982 $retVal = '';
983 foreach ( $args as $arg ) {
984 if ( !$first ) {
985 $retVal .= ' ';
986 } else {
987 $first = false;
988 }
989
990 if ( wfIsWindows() ) {
991 // Escaping for an MSVC-style command line parser
992 // Ref: http://mailman.lyra.org/pipermail/scite-interest/2002-March/000436.html
993 // Double the backslashes before any double quotes. Escape the double quotes.
994 $tokens = preg_split( '/(\\\\*")/', $arg, -1, PREG_SPLIT_DELIM_CAPTURE );
995 $arg = '';
996 $delim = false;
997 foreach ( $tokens as $token ) {
998 if ( $delim ) {
999 $arg .= str_replace( '\\', '\\\\', substr( $token, 0, -1 ) ) . '\\"';
1000 } else {
1001 $arg .= $token;
1002 }
1003 $delim = !$delim;
1004 }
1005 // Double the backslashes before the end of the string, because
1006 // we will soon add a quote
1007 if ( preg_match( '/^(.*?)(\\\\+)$/', $arg, $m ) ) {
1008 $arg = $m[1] . str_replace( '\\', '\\\\', $m[2] );
1009 }
1010
1011 // Add surrounding quotes
1012 $retVal .= '"' . $arg . '"';
1013 } else {
1014 $retVal .= escapeshellarg( $arg );
1015 }
1016 }
1017 return $retVal;
1018 }
1019
1020 /**
1021 * wfMerge attempts to merge differences between three texts.
1022 * Returns true for a clean merge and false for failure or a conflict.
1023 */
1024 function wfMerge( $old, $mine, $yours, &$result ){
1025 global $wgDiff3;
1026
1027 # This check may also protect against code injection in
1028 # case of broken installations.
1029 if(! file_exists( $wgDiff3 ) ){
1030 wfDebug( "diff3 not found\n" );
1031 return false;
1032 }
1033
1034 # Make temporary files
1035 $td = wfTempDir();
1036 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
1037 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
1038 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
1039
1040 fwrite( $oldtextFile, $old ); fclose( $oldtextFile );
1041 fwrite( $mytextFile, $mine ); fclose( $mytextFile );
1042 fwrite( $yourtextFile, $yours ); fclose( $yourtextFile );
1043
1044 # Check for a conflict
1045 $cmd = $wgDiff3 . ' -a --overlap-only ' .
1046 wfEscapeShellArg( $mytextName ) . ' ' .
1047 wfEscapeShellArg( $oldtextName ) . ' ' .
1048 wfEscapeShellArg( $yourtextName );
1049 $handle = popen( $cmd, 'r' );
1050
1051 if( fgets( $handle, 1024 ) ){
1052 $conflict = true;
1053 } else {
1054 $conflict = false;
1055 }
1056 pclose( $handle );
1057
1058 # Merge differences
1059 $cmd = $wgDiff3 . ' -a -e --merge ' .
1060 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
1061 $handle = popen( $cmd, 'r' );
1062 $result = '';
1063 do {
1064 $data = fread( $handle, 8192 );
1065 if ( strlen( $data ) == 0 ) {
1066 break;
1067 }
1068 $result .= $data;
1069 } while ( true );
1070 pclose( $handle );
1071 unlink( $mytextName ); unlink( $oldtextName ); unlink( $yourtextName );
1072
1073 if ( $result === '' && $old !== '' && $conflict == false ) {
1074 wfDebug( "Unexpected null result from diff3. Command: $cmd\n" );
1075 $conflict = true;
1076 }
1077 return ! $conflict;
1078 }
1079
1080 /**
1081 * @todo document
1082 */
1083 function wfVarDump( $var ) {
1084 global $wgOut;
1085 $s = str_replace("\n","<br />\n", var_export( $var, true ) . "\n");
1086 if ( headers_sent() || !@is_object( $wgOut ) ) {
1087 print $s;
1088 } else {
1089 $wgOut->addHTML( $s );
1090 }
1091 }
1092
1093 /**
1094 * Provide a simple HTTP error.
1095 */
1096 function wfHttpError( $code, $label, $desc ) {
1097 global $wgOut;
1098 $wgOut->disable();
1099 header( "HTTP/1.0 $code $label" );
1100 header( "Status: $code $label" );
1101 $wgOut->sendCacheControl();
1102
1103 header( 'Content-type: text/html' );
1104 print "<html><head><title>" .
1105 htmlspecialchars( $label ) .
1106 "</title></head><body><h1>" .
1107 htmlspecialchars( $label ) .
1108 "</h1><p>" .
1109 htmlspecialchars( $desc ) .
1110 "</p></body></html>\n";
1111 }
1112
1113 /**
1114 * Converts an Accept-* header into an array mapping string values to quality
1115 * factors
1116 */
1117 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
1118 # No arg means accept anything (per HTTP spec)
1119 if( !$accept ) {
1120 return array( $def => 1 );
1121 }
1122
1123 $prefs = array();
1124
1125 $parts = explode( ',', $accept );
1126
1127 foreach( $parts as $part ) {
1128 # FIXME: doesn't deal with params like 'text/html; level=1'
1129 @list( $value, $qpart ) = explode( ';', $part );
1130 if( !isset( $qpart ) ) {
1131 $prefs[$value] = 1;
1132 } elseif( preg_match( '/q\s*=\s*(\d*\.\d+)/', $qpart, $match ) ) {
1133 $prefs[$value] = $match[1];
1134 }
1135 }
1136
1137 return $prefs;
1138 }
1139
1140 /**
1141 * Checks if a given MIME type matches any of the keys in the given
1142 * array. Basic wildcards are accepted in the array keys.
1143 *
1144 * Returns the matching MIME type (or wildcard) if a match, otherwise
1145 * NULL if no match.
1146 *
1147 * @param string $type
1148 * @param array $avail
1149 * @return string
1150 * @private
1151 */
1152 function mimeTypeMatch( $type, $avail ) {
1153 if( array_key_exists($type, $avail) ) {
1154 return $type;
1155 } else {
1156 $parts = explode( '/', $type );
1157 if( array_key_exists( $parts[0] . '/*', $avail ) ) {
1158 return $parts[0] . '/*';
1159 } elseif( array_key_exists( '*/*', $avail ) ) {
1160 return '*/*';
1161 } else {
1162 return NULL;
1163 }
1164 }
1165 }
1166
1167 /**
1168 * Returns the 'best' match between a client's requested internet media types
1169 * and the server's list of available types. Each list should be an associative
1170 * array of type to preference (preference is a float between 0.0 and 1.0).
1171 * Wildcards in the types are acceptable.
1172 *
1173 * @param array $cprefs Client's acceptable type list
1174 * @param array $sprefs Server's offered types
1175 * @return string
1176 *
1177 * @todo FIXME: doesn't handle params like 'text/plain; charset=UTF-8'
1178 * XXX: generalize to negotiate other stuff
1179 */
1180 function wfNegotiateType( $cprefs, $sprefs ) {
1181 $combine = array();
1182
1183 foreach( array_keys($sprefs) as $type ) {
1184 $parts = explode( '/', $type );
1185 if( $parts[1] != '*' ) {
1186 $ckey = mimeTypeMatch( $type, $cprefs );
1187 if( $ckey ) {
1188 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1189 }
1190 }
1191 }
1192
1193 foreach( array_keys( $cprefs ) as $type ) {
1194 $parts = explode( '/', $type );
1195 if( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
1196 $skey = mimeTypeMatch( $type, $sprefs );
1197 if( $skey ) {
1198 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1199 }
1200 }
1201 }
1202
1203 $bestq = 0;
1204 $besttype = NULL;
1205
1206 foreach( array_keys( $combine ) as $type ) {
1207 if( $combine[$type] > $bestq ) {
1208 $besttype = $type;
1209 $bestq = $combine[$type];
1210 }
1211 }
1212
1213 return $besttype;
1214 }
1215
1216 /**
1217 * Array lookup
1218 * Returns an array where the values in the first array are replaced by the
1219 * values in the second array with the corresponding keys
1220 *
1221 * @return array
1222 */
1223 function wfArrayLookup( $a, $b ) {
1224 return array_flip( array_intersect( array_flip( $a ), array_keys( $b ) ) );
1225 }
1226
1227 /**
1228 * Convenience function; returns MediaWiki timestamp for the present time.
1229 * @return string
1230 */
1231 function wfTimestampNow() {
1232 # return NOW
1233 return wfTimestamp( TS_MW, time() );
1234 }
1235
1236 /**
1237 * Reference-counted warning suppression
1238 */
1239 function wfSuppressWarnings( $end = false ) {
1240 static $suppressCount = 0;
1241 static $originalLevel = false;
1242
1243 if ( $end ) {
1244 if ( $suppressCount ) {
1245 --$suppressCount;
1246 if ( !$suppressCount ) {
1247 error_reporting( $originalLevel );
1248 }
1249 }
1250 } else {
1251 if ( !$suppressCount ) {
1252 $originalLevel = error_reporting( E_ALL & ~( E_WARNING | E_NOTICE ) );
1253 }
1254 ++$suppressCount;
1255 }
1256 }
1257
1258 /**
1259 * Restore error level to previous value
1260 */
1261 function wfRestoreWarnings() {
1262 wfSuppressWarnings( true );
1263 }
1264
1265 # Autodetect, convert and provide timestamps of various types
1266
1267 /**
1268 * Unix time - the number of seconds since 1970-01-01 00:00:00 UTC
1269 */
1270 define('TS_UNIX', 0);
1271
1272 /**
1273 * MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
1274 */
1275 define('TS_MW', 1);
1276
1277 /**
1278 * MySQL DATETIME (YYYY-MM-DD HH:MM:SS)
1279 */
1280 define('TS_DB', 2);
1281
1282 /**
1283 * RFC 2822 format, for E-mail and HTTP headers
1284 */
1285 define('TS_RFC2822', 3);
1286
1287 /**
1288 * ISO 8601 format with no timezone: 1986-02-09T20:00:00Z
1289 *
1290 * This is used by Special:Export
1291 */
1292 define('TS_ISO_8601', 4);
1293
1294 /**
1295 * An Exif timestamp (YYYY:MM:DD HH:MM:SS)
1296 *
1297 * @url http://exif.org/Exif2-2.PDF The Exif 2.2 spec, see page 28 for the
1298 * DateTime tag and page 36 for the DateTimeOriginal and
1299 * DateTimeDigitized tags.
1300 */
1301 define('TS_EXIF', 5);
1302
1303 /**
1304 * Oracle format time.
1305 */
1306 define('TS_ORACLE', 6);
1307
1308 /**
1309 * @param mixed $outputtype A timestamp in one of the supported formats, the
1310 * function will autodetect which format is supplied
1311 * and act accordingly.
1312 * @return string Time in the format specified in $outputtype
1313 */
1314 function wfTimestamp($outputtype=TS_UNIX,$ts=0) {
1315 $uts = 0;
1316 $da = array();
1317 if ($ts==0) {
1318 $uts=time();
1319 } elseif (preg_match("/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)$/",$ts,$da)) {
1320 # TS_DB
1321 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1322 (int)$da[2],(int)$da[3],(int)$da[1]);
1323 } elseif (preg_match("/^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/",$ts,$da)) {
1324 # TS_EXIF
1325 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1326 (int)$da[2],(int)$da[3],(int)$da[1]);
1327 } elseif (preg_match("/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/",$ts,$da)) {
1328 # TS_MW
1329 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1330 (int)$da[2],(int)$da[3],(int)$da[1]);
1331 } elseif (preg_match("/^(\d{1,13})$/",$ts,$datearray)) {
1332 # TS_UNIX
1333 $uts=$ts;
1334 } elseif (preg_match('/^(\d{1,2})-(...)-(\d\d(\d\d)?) (\d\d)\.(\d\d)\.(\d\d)/', $ts, $da)) {
1335 # TS_ORACLE
1336 $uts = strtotime(preg_replace('/(\d\d)\.(\d\d)\.(\d\d)(\.(\d+))?/', "$1:$2:$3",
1337 str_replace("+00:00", "UTC", $ts)));
1338 } elseif (preg_match('/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})Z$/', $ts, $da)) {
1339 # TS_ISO_8601
1340 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1341 (int)$da[2],(int)$da[3],(int)$da[1]);
1342 } else {
1343 # Bogus value; fall back to the epoch...
1344 wfDebug("wfTimestamp() fed bogus time value: $outputtype; $ts\n");
1345 $uts = 0;
1346 }
1347
1348
1349 switch($outputtype) {
1350 case TS_UNIX:
1351 return $uts;
1352 case TS_MW:
1353 return gmdate( 'YmdHis', $uts );
1354 case TS_DB:
1355 return gmdate( 'Y-m-d H:i:s', $uts );
1356 case TS_ISO_8601:
1357 return gmdate( 'Y-m-d\TH:i:s\Z', $uts );
1358 // This shouldn't ever be used, but is included for completeness
1359 case TS_EXIF:
1360 return gmdate( 'Y:m:d H:i:s', $uts );
1361 case TS_RFC2822:
1362 return gmdate( 'D, d M Y H:i:s', $uts ) . ' GMT';
1363 case TS_ORACLE:
1364 return gmdate( 'd-M-y h.i.s A', $uts) . ' +00:00';
1365 default:
1366 wfDebugDieBacktrace( 'wfTimestamp() called with illegal output type.');
1367 }
1368 }
1369
1370 /**
1371 * Return a formatted timestamp, or null if input is null.
1372 * For dealing with nullable timestamp columns in the database.
1373 * @param int $outputtype
1374 * @param string $ts
1375 * @return string
1376 */
1377 function wfTimestampOrNull( $outputtype = TS_UNIX, $ts = null ) {
1378 if( is_null( $ts ) ) {
1379 return null;
1380 } else {
1381 return wfTimestamp( $outputtype, $ts );
1382 }
1383 }
1384
1385 /**
1386 * Check if the operating system is Windows
1387 *
1388 * @return bool True if it's Windows, False otherwise.
1389 */
1390 function wfIsWindows() {
1391 if (substr(php_uname(), 0, 7) == 'Windows') {
1392 return true;
1393 } else {
1394 return false;
1395 }
1396 }
1397
1398 /**
1399 * Swap two variables
1400 */
1401 function swap( &$x, &$y ) {
1402 $z = $x;
1403 $x = $y;
1404 $y = $z;
1405 }
1406
1407 function wfGetCachedNotice( $name ) {
1408 global $wgOut, $parserMemc, $wgDBname;
1409 $fname = 'wfGetCachedNotice';
1410 wfProfileIn( $fname );
1411
1412 $needParse = false;
1413 $notice = wfMsgForContent( $name );
1414 if( $notice == '&lt;'. $name . ';&gt' || $notice == '-' ) {
1415 wfProfileOut( $fname );
1416 return( false );
1417 }
1418
1419 $cachedNotice = $parserMemc->get( $wgDBname . ':' . $name );
1420 if( is_array( $cachedNotice ) ) {
1421 if( md5( $notice ) == $cachedNotice['hash'] ) {
1422 $notice = $cachedNotice['html'];
1423 } else {
1424 $needParse = true;
1425 }
1426 } else {
1427 $needParse = true;
1428 }
1429
1430 if( $needParse ) {
1431 if( is_object( $wgOut ) ) {
1432 $parsed = $wgOut->parse( $notice );
1433 $parserMemc->set( $wgDBname . ':' . $name, array( 'html' => $parsed, 'hash' => md5( $notice ) ), 600 );
1434 $notice = $parsed;
1435 } else {
1436 wfDebug( 'wfGetCachedNotice called for ' . $name . ' with no $wgOut available' );
1437 $notice = '';
1438 }
1439 }
1440
1441 wfProfileOut( $fname );
1442 return $notice;
1443 }
1444
1445 function wfGetNamespaceNotice() {
1446 global $wgTitle;
1447
1448 # Paranoia
1449 if ( !isset( $wgTitle ) || !is_object( $wgTitle ) )
1450 return "";
1451
1452 $fname = 'wfGetNamespaceNotice';
1453 wfProfileIn( $fname );
1454
1455 $key = "namespacenotice-" . $wgTitle->getNsText();
1456 $namespaceNotice = wfGetCachedNotice( $key );
1457 if ( $namespaceNotice && substr ( $namespaceNotice , 0 ,7 ) != "<p>&lt;" ) {
1458 $namespaceNotice = '<div id="namespacebanner">' . $namespaceNotice . "</div>";
1459 } else {
1460 $namespaceNotice = "";
1461 }
1462
1463 wfProfileOut( $fname );
1464 return $namespaceNotice;
1465 }
1466
1467 function wfGetSiteNotice() {
1468 global $wgUser, $wgSiteNotice;
1469 $fname = 'wfGetSiteNotice';
1470 wfProfileIn( $fname );
1471
1472 if( is_object( $wgUser ) && $wgUser->isLoggedIn() ) {
1473 $siteNotice = wfGetCachedNotice( 'sitenotice' );
1474 $siteNotice = !$siteNotice ? $wgSiteNotice : $siteNotice;
1475 } else {
1476 $anonNotice = wfGetCachedNotice( 'anonnotice' );
1477 if( !$anonNotice ) {
1478 $siteNotice = wfGetCachedNotice( 'sitenotice' );
1479 $siteNotice = !$siteNotice ? $wgSiteNotice : $siteNotice;
1480 } else {
1481 $siteNotice = $anonNotice;
1482 }
1483 }
1484
1485 wfProfileOut( $fname );
1486 return( $siteNotice );
1487 }
1488
1489 /** Global singleton instance of MimeMagic. This is initialized on demand,
1490 * please always use the wfGetMimeMagic() function to get the instance.
1491 *
1492 * @private
1493 */
1494 $wgMimeMagic= NULL;
1495
1496 /** Factory functions for the global MimeMagic object.
1497 * This function always returns the same singleton instance of MimeMagic.
1498 * That objects will be instantiated on the first call to this function.
1499 * If needed, the MimeMagic.php file is automatically included by this function.
1500 * @return MimeMagic the global MimeMagic objects.
1501 */
1502 function &wfGetMimeMagic() {
1503 global $wgMimeMagic;
1504
1505 if (!is_null($wgMimeMagic)) {
1506 return $wgMimeMagic;
1507 }
1508
1509 $wgMimeMagic= new MimeMagic();
1510
1511 return $wgMimeMagic;
1512 }
1513
1514
1515 /**
1516 * Tries to get the system directory for temporary files.
1517 * The TMPDIR, TMP, and TEMP environment variables are checked in sequence,
1518 * and if none are set /tmp is returned as the generic Unix default.
1519 *
1520 * NOTE: When possible, use the tempfile() function to create temporary
1521 * files to avoid race conditions on file creation, etc.
1522 *
1523 * @return string
1524 */
1525 function wfTempDir() {
1526 foreach( array( 'TMPDIR', 'TMP', 'TEMP' ) as $var ) {
1527 $tmp = getenv( $var );
1528 if( $tmp && file_exists( $tmp ) && is_dir( $tmp ) && is_writable( $tmp ) ) {
1529 return $tmp;
1530 }
1531 }
1532 # Hope this is Unix of some kind!
1533 return '/tmp';
1534 }
1535
1536 /**
1537 * Make directory, and make all parent directories if they don't exist
1538 */
1539 function wfMkdirParents( $fullDir, $mode ) {
1540 $parts = explode( '/', $fullDir );
1541 $path = '';
1542
1543 foreach ( $parts as $dir ) {
1544 $path .= $dir . '/';
1545 if ( !is_dir( $path ) ) {
1546 if ( !mkdir( $path, $mode ) ) {
1547 return false;
1548 }
1549 }
1550 }
1551 return true;
1552 }
1553
1554 /**
1555 * Increment a statistics counter
1556 */
1557 function wfIncrStats( $key ) {
1558 global $wgDBname, $wgMemc;
1559 $key = "$wgDBname:stats:$key";
1560 if ( is_null( $wgMemc->incr( $key ) ) ) {
1561 $wgMemc->add( $key, 1 );
1562 }
1563 }
1564
1565 /**
1566 * @param mixed $nr The number to format
1567 * @param int $acc The number of digits after the decimal point, default 2
1568 * @param bool $round Whether or not to round the value, default true
1569 * @return float
1570 */
1571 function wfPercent( $nr, $acc = 2, $round = true ) {
1572 $ret = sprintf( "%.${acc}f", $nr );
1573 return $round ? round( $ret, $acc ) . '%' : "$ret%";
1574 }
1575
1576 /**
1577 * Encrypt a username/password.
1578 *
1579 * @param string $userid ID of the user
1580 * @param string $password Password of the user
1581 * @return string Hashed password
1582 */
1583 function wfEncryptPassword( $userid, $password ) {
1584 global $wgPasswordSalt;
1585 $p = md5( $password);
1586
1587 if($wgPasswordSalt)
1588 return md5( "{$userid}-{$p}" );
1589 else
1590 return $p;
1591 }
1592
1593 /**
1594 * Appends to second array if $value differs from that in $default
1595 */
1596 function wfAppendToArrayIfNotDefault( $key, $value, $default, &$changed ) {
1597 if ( is_null( $changed ) ) {
1598 wfDebugDieBacktrace('GlobalFunctions::wfAppendToArrayIfNotDefault got null');
1599 }
1600 if ( $default[$key] !== $value ) {
1601 $changed[$key] = $value;
1602 }
1603 }
1604
1605 /**
1606 * Since wfMsg() and co suck, they don't return false if the message key they
1607 * looked up didn't exist but a XHTML string, this function checks for the
1608 * nonexistance of messages by looking at wfMsg() output
1609 *
1610 * @param $msg The message key looked up
1611 * @param $wfMsgOut The output of wfMsg*()
1612 * @return bool
1613 */
1614 function wfEmptyMsg( $msg, $wfMsgOut ) {
1615 return $wfMsgOut === "&lt;$msg&gt;";
1616 }
1617
1618 /**
1619 * Find out whether or not a mixed variable exists in a string
1620 *
1621 * @param mixed needle
1622 * @param string haystack
1623 * @return bool
1624 */
1625 function in_string( $needle, $str ) {
1626 return strpos( $str, $needle ) !== false;
1627 }
1628
1629 function wfSpecialList( $page, $details ) {
1630 global $wgContLang;
1631 $details = $details ? ' ' . $wgContLang->getDirMark() . "($details)" : "";
1632 return $page . $details;
1633 }
1634
1635 /**
1636 * Returns a regular expression of url protocols
1637 *
1638 * @return string
1639 */
1640 function wfUrlProtocols() {
1641 global $wgUrlProtocols;
1642
1643 // Support old-style $wgUrlProtocols strings, for backwards compatibility
1644 // with LocalSettings files from 1.5
1645 if ( is_array( $wgUrlProtocols ) ) {
1646 $protocols = array();
1647 foreach ($wgUrlProtocols as $protocol)
1648 $protocols[] = preg_quote( $protocol, '/' );
1649
1650 return implode( '|', $protocols );
1651 } else {
1652 return $wgUrlProtocols;
1653 }
1654 }
1655
1656 /**
1657 * Execute a shell command, with time and memory limits mirrored from the PHP
1658 * configuration if supported.
1659 * @param $cmd Command line, properly escaped for shell.
1660 * @param &$retval optional, will receive the program's exit code.
1661 * (non-zero is usually failure)
1662 * @return collected stdout as a string (trailing newlines stripped)
1663 */
1664 function wfShellExec( $cmd, &$retval=null ) {
1665 global $IP;
1666
1667 if( ini_get( 'safe_mode' ) ) {
1668 wfDebug( "wfShellExec can't run in safe_mode, PHP's exec functions are too broken.\n" );
1669 $retval = 1;
1670 return "Unable to run external programs in safe mode.";
1671 }
1672
1673 if ( php_uname( 's' ) == 'Linux' ) {
1674 $time = ini_get( 'max_execution_time' );
1675 $mem = ini_get( 'memory_limit' );
1676 if( preg_match( '/^([0-9]+)[Mm]$/', trim( $mem ), $m ) ) {
1677 $mem = intval( $m[1] * (1024*1024) );
1678 }
1679 if ( $time > 0 && $mem > 0 ) {
1680 $script = "$IP/bin/ulimit.sh";
1681 if ( is_executable( $script ) ) {
1682 $memKB = intval( $mem / 1024 );
1683 $cmd = escapeshellarg( $script ) . " $time $memKB $cmd";
1684 }
1685 }
1686 } elseif ( php_uname( 's' ) == 'Windows NT' ) {
1687 # This is a hack to work around PHP's flawed invocation of cmd.exe
1688 # http://news.php.net/php.internals/21796
1689 $cmd = '"' . $cmd . '"';
1690 }
1691 wfDebug( "wfShellExec: $cmd\n" );
1692
1693 $output = array();
1694 $retval = 1; // error by default?
1695 $lastline = exec( $cmd, $output, $retval );
1696 return implode( "\n", $output );
1697
1698 }
1699
1700 /**
1701 * This function works like "use VERSION" in Perl, the program will die with a
1702 * backtrace if the current version of PHP is less than the version provided
1703 *
1704 * This is useful for extensions which due to their nature are not kept in sync
1705 * with releases, and might depend on other versions of PHP than the main code
1706 *
1707 * Note: PHP might die due to parsing errors in some cases before it ever
1708 * manages to call this function, such is life
1709 *
1710 * @see perldoc -f use
1711 *
1712 * @param mixed $version The version to check, can be a string, an integer, or
1713 * a float
1714 */
1715 function wfUsePHP( $req_ver ) {
1716 $php_ver = PHP_VERSION;
1717
1718 if ( version_compare( $php_ver, (string)$req_ver, '<' ) )
1719 wfDebugDieBacktrace( "PHP $req_ver required--this is only $php_ver" );
1720 }
1721
1722 /**
1723 * This function works like "use VERSION" in Perl except it checks the version
1724 * of MediaWiki, the program will die with a backtrace if the current version
1725 * of MediaWiki is less than the version provided.
1726 *
1727 * This is useful for extensions which due to their nature are not kept in sync
1728 * with releases
1729 *
1730 * @see perldoc -f use
1731 *
1732 * @param mixed $version The version to check, can be a string, an integer, or
1733 * a float
1734 */
1735 function wfUseMW( $req_ver ) {
1736 global $wgVersion;
1737
1738 if ( version_compare( $wgVersion, (string)$req_ver, '<' ) )
1739 wfDebugDieBacktrace( "MediaWiki $req_ver required--this is only $wgVersion" );
1740 }
1741
1742 /**
1743 * Escape a string to make it suitable for inclusion in a preg_replace()
1744 * replacement parameter.
1745 *
1746 * @param string $string
1747 * @return string
1748 */
1749 function wfRegexReplacement( $string ) {
1750 $string = str_replace( '\\', '\\\\', $string );
1751 $string = str_replace( '$', '\\$', $string );
1752 return $string;
1753 }
1754
1755 /**
1756 * Return the final portion of a pathname.
1757 * Reimplemented because PHP5's basename() is buggy with multibyte text.
1758 * http://bugs.php.net/bug.php?id=33898
1759 *
1760 * PHP's basename() only considers '\' a pathchar on Windows and Netware.
1761 * We'll consider it so always, as we don't want \s in our Unix paths either.
1762 *
1763 * @param string $path
1764 * @return string
1765 */
1766 function wfBaseName( $path ) {
1767 if( preg_match( '#([^/\\\\]*)[/\\\\]*$#', $path, $matches ) ) {
1768 return $matches[1];
1769 } else {
1770 return '';
1771 }
1772 }
1773
1774 /**
1775 * Make a URL index, appropriate for the el_index field of externallinks.
1776 */
1777 function wfMakeUrlIndex( $url ) {
1778 wfSuppressWarnings();
1779 $bits = parse_url( $url );
1780 wfRestoreWarnings();
1781 if ( !$bits || $bits['scheme'] !== 'http' ) {
1782 return false;
1783 }
1784 // Reverse the labels in the hostname, convert to lower case
1785 $reversedHost = strtolower( implode( '.', array_reverse( explode( '.', $bits['host'] ) ) ) );
1786 // Add an extra dot to the end
1787 if ( substr( $reversedHost, -1, 1 ) !== '.' ) {
1788 $reversedHost .= '.';
1789 }
1790 // Reconstruct the pseudo-URL
1791 $index = "http://$reversedHost";
1792 // Leave out user and password. Add the port, path, query and fragment
1793 if ( isset( $bits['port'] ) ) $index .= ':' . $bits['port'];
1794 if ( isset( $bits['path'] ) ) {
1795 $index .= $bits['path'];
1796 } else {
1797 $index .= '/';
1798 }
1799 if ( isset( $bits['query'] ) ) $index .= '?' . $bits['query'];
1800 if ( isset( $bits['fragment'] ) ) $index .= '#' . $bits['fragment'];
1801 return $index;
1802 }
1803
1804 /**
1805 * Do any deferred updates and clear the list
1806 * TODO: This could be in Wiki.php if that class made any sense at all
1807 */
1808 function wfDoUpdates()
1809 {
1810 global $wgPostCommitUpdateList, $wgDeferredUpdateList;
1811 foreach ( $wgDeferredUpdateList as $update ) {
1812 $update->doUpdate();
1813 }
1814 foreach ( $wgPostCommitUpdateList as $update ) {
1815 $update->doUpdate();
1816 }
1817 $wgDeferredUpdateList = array();
1818 $wgPostCommitUpdateList = array();
1819 }
1820
1821 /**
1822 * More or less "markup-safe" explode()
1823 * Ignores any instances of the separator inside <...>
1824 * @param string $separator
1825 * @param string $text
1826 * @return array
1827 */
1828 function wfExplodeMarkup( $separator, $text ) {
1829 $placeholder = "\x00";
1830
1831 // Just in case...
1832 $text = str_replace( $placeholder, '', $text );
1833
1834 // Trim stuff
1835 $replacer = new ReplacerCallback( $separator, $placeholder );
1836 $cleaned = preg_replace_callback( '/(<.*?>)/', array( $replacer, 'go' ), $text );
1837
1838 $items = explode( $separator, $cleaned );
1839 foreach( $items as $i => $str ) {
1840 $items[$i] = str_replace( $placeholder, $separator, $str );
1841 }
1842
1843 return $items;
1844 }
1845
1846 class ReplacerCallback {
1847 function ReplacerCallback( $from, $to ) {
1848 $this->from = $from;
1849 $this->to = $to;
1850 }
1851
1852 function go( $matches ) {
1853 return str_replace( $this->from, $this->to, $matches[1] );
1854 }
1855 }
1856
1857 /***** DEPRECATED INTERFACES *******/
1858 function wfGetForwardedFor() { return ProxyTools::getForwardedFor(); }
1859 function wfGetIP() { return ProxyTools::getIP(); }
1860 function wfIP2Unsigned($ip) { return ProxyTools::IP2Unsigned($ip); }
1861 function wfIP2Hex($ip) { return ProxyTools::IP2Hex($ip); }
1862 function wfIsIPPublic($ip) { return ProxyTools::isIPPublic($ip); }
1863 function wfProxyCheck() { return ProxyTools::proxyCheck(); }
1864 function wfParseCIDR($range) { return ProxyTools::parseCIDR($range); }
1865 function wfIsLocallyBlockedProxy($ip) { return ProxyTools::isLocallyBlockedProxy($ip); }
1866
1867 function wfGetCache($type) { return ObjectCacheManager::getCache($type); }
1868 function wfGetMainCache() { return ObjectCacheManager::getMainCache(); }
1869 function wfGetMessageCacheStorage() { return ObjectCacheManager::getMessageCache(); }
1870 function wfGetParserCacheStorage() { return ObjectCacheManager::getParserCache(); }
1871
1872 function renderMath($tex) { return MathRenderer::renderMath($tex); }
1873
1874 function showCreditsPage($article) { return Credits::showCreditsPage($article); }
1875 function getCredits($article, $cnt, $showIfMax=true) { return Credits::getCredits($article,$cnt,$showIfMax); }
1876
1877 function wfGetHTTP( $url, $timeout = 'default' ) { return HttpFunctions::getHTTP($url,$timeout); }
1878 function wfIsLocalURL( $url ) { return HttpFunctions::isLocalURL($url); }
1879
1880 ?>