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