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