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