* Added RFC to list of strings to escape
[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 = wfMsgForContentNoTrans( $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 = wfMsgForContentNoTrans( $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 * @obsolete Please return control to the caller or throw an exception
604 */
605 function wfAbruptExit( $error = false ){
606 global $wgLoadBalancer;
607 static $called = false;
608 if ( $called ){
609 exit( -1 );
610 }
611 $called = true;
612
613 if( function_exists( 'debug_backtrace' ) ){ // PHP >= 4.3
614 $bt = debug_backtrace();
615 for($i = 0; $i < count($bt) ; $i++){
616 $file = isset($bt[$i]['file']) ? $bt[$i]['file'] : "unknown";
617 $line = isset($bt[$i]['line']) ? $bt[$i]['line'] : "unknown";
618 wfDebug("WARNING: Abrupt exit in $file at line $line\n");
619 }
620 } else {
621 wfDebug('WARNING: Abrupt exit\n');
622 }
623
624 wfProfileClose();
625 logProfilingData();
626
627 if ( !$error ) {
628 $wgLoadBalancer->closeAll();
629 }
630 exit( -1 );
631 }
632
633 /**
634 * @obsolete Please return control the caller or throw an exception
635 */
636 function wfErrorExit() {
637 wfAbruptExit( true );
638 }
639
640 /**
641 * Print a simple message and die, returning nonzero to the shell if any.
642 * Plain die() fails to return nonzero to the shell if you pass a string.
643 * @param string $msg
644 */
645 function wfDie( $msg='' ) {
646 echo $msg;
647 die( 1 );
648 }
649
650 /**
651 * Throw a debugging exception. This function previously once exited the process,
652 * but now throws an exception instead, with similar results.
653 *
654 * @param string $msg Message shown when dieing.
655 */
656 function wfDebugDieBacktrace( $msg = '' ) {
657 throw new MWException( $msg );
658 }
659
660 /**
661 * Fetch server name for use in error reporting etc.
662 * Use real server name if available, so we know which machine
663 * in a server farm generated the current page.
664 * @return string
665 */
666 function wfHostname() {
667 if ( function_exists( 'posix_uname' ) ) {
668 // This function not present on Windows
669 $uname = @posix_uname();
670 } else {
671 $uname = false;
672 }
673 if( is_array( $uname ) && isset( $uname['nodename'] ) ) {
674 return $uname['nodename'];
675 } else {
676 # This may be a virtual server.
677 return $_SERVER['SERVER_NAME'];
678 }
679 }
680
681 /**
682 * Returns a HTML comment with the elapsed time since request.
683 * This method has no side effects.
684 * @return string
685 */
686 function wfReportTime() {
687 global $wgRequestTime;
688
689 $now = wfTime();
690 $elapsed = $now - $wgRequestTime;
691
692 $com = sprintf( "<!-- Served by %s in %01.3f secs. -->",
693 wfHostname(), $elapsed );
694 return $com;
695 }
696
697 function wfBacktrace() {
698 global $wgCommandLineMode;
699 if ( !function_exists( 'debug_backtrace' ) ) {
700 return false;
701 }
702
703 if ( $wgCommandLineMode ) {
704 $msg = '';
705 } else {
706 $msg = "<ul>\n";
707 }
708 $backtrace = debug_backtrace();
709 foreach( $backtrace as $call ) {
710 if( isset( $call['file'] ) ) {
711 $f = explode( DIRECTORY_SEPARATOR, $call['file'] );
712 $file = $f[count($f)-1];
713 } else {
714 $file = '-';
715 }
716 if( isset( $call['line'] ) ) {
717 $line = $call['line'];
718 } else {
719 $line = '-';
720 }
721 if ( $wgCommandLineMode ) {
722 $msg .= "$file line $line calls ";
723 } else {
724 $msg .= '<li>' . $file . ' line ' . $line . ' calls ';
725 }
726 if( !empty( $call['class'] ) ) $msg .= $call['class'] . '::';
727 $msg .= $call['function'] . '()';
728
729 if ( $wgCommandLineMode ) {
730 $msg .= "\n";
731 } else {
732 $msg .= "</li>\n";
733 }
734 }
735 if ( $wgCommandLineMode ) {
736 $msg .= "\n";
737 } else {
738 $msg .= "</ul>\n";
739 }
740
741 return $msg;
742 }
743
744
745 /* Some generic result counters, pulled out of SearchEngine */
746
747
748 /**
749 * @todo document
750 */
751 function wfShowingResults( $offset, $limit ) {
752 global $wgLang;
753 return wfMsg( 'showingresults', $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+1 ) );
754 }
755
756 /**
757 * @todo document
758 */
759 function wfShowingResultsNum( $offset, $limit, $num ) {
760 global $wgLang;
761 return wfMsg( 'showingresultsnum', $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+1 ), $wgLang->formatNum( $num ) );
762 }
763
764 /**
765 * @todo document
766 */
767 function wfViewPrevNext( $offset, $limit, $link, $query = '', $atend = false ) {
768 global $wgLang;
769 $fmtLimit = $wgLang->formatNum( $limit );
770 $prev = wfMsg( 'prevn', $fmtLimit );
771 $next = wfMsg( 'nextn', $fmtLimit );
772
773 if( is_object( $link ) ) {
774 $title =& $link;
775 } else {
776 $title = Title::newFromText( $link );
777 if( is_null( $title ) ) {
778 return false;
779 }
780 }
781
782 if ( 0 != $offset ) {
783 $po = $offset - $limit;
784 if ( $po < 0 ) { $po = 0; }
785 $q = "limit={$limit}&offset={$po}";
786 if ( '' != $query ) { $q .= '&'.$query; }
787 $plink = '<a href="' . $title->escapeLocalUrl( $q ) . "\">{$prev}</a>";
788 } else { $plink = $prev; }
789
790 $no = $offset + $limit;
791 $q = 'limit='.$limit.'&offset='.$no;
792 if ( '' != $query ) { $q .= '&'.$query; }
793
794 if ( $atend ) {
795 $nlink = $next;
796 } else {
797 $nlink = '<a href="' . $title->escapeLocalUrl( $q ) . "\">{$next}</a>";
798 }
799 $nums = wfNumLink( $offset, 20, $title, $query ) . ' | ' .
800 wfNumLink( $offset, 50, $title, $query ) . ' | ' .
801 wfNumLink( $offset, 100, $title, $query ) . ' | ' .
802 wfNumLink( $offset, 250, $title, $query ) . ' | ' .
803 wfNumLink( $offset, 500, $title, $query );
804
805 return wfMsg( 'viewprevnext', $plink, $nlink, $nums );
806 }
807
808 /**
809 * @todo document
810 */
811 function wfNumLink( $offset, $limit, &$title, $query = '' ) {
812 global $wgLang;
813 if ( '' == $query ) { $q = ''; }
814 else { $q = $query.'&'; }
815 $q .= 'limit='.$limit.'&offset='.$offset;
816
817 $fmtLimit = $wgLang->formatNum( $limit );
818 $s = '<a href="' . $title->escapeLocalUrl( $q ) . "\">{$fmtLimit}</a>";
819 return $s;
820 }
821
822 /**
823 * @todo document
824 * @todo FIXME: we may want to blacklist some broken browsers
825 *
826 * @return bool Whereas client accept gzip compression
827 */
828 function wfClientAcceptsGzip() {
829 global $wgUseGzip;
830 if( $wgUseGzip ) {
831 # FIXME: we may want to blacklist some broken browsers
832 if( preg_match(
833 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
834 $_SERVER['HTTP_ACCEPT_ENCODING'],
835 $m ) ) {
836 if( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) return false;
837 wfDebug( " accepts gzip\n" );
838 return true;
839 }
840 }
841 return false;
842 }
843
844 /**
845 * Obtain the offset and limit values from the request string;
846 * used in special pages
847 *
848 * @param $deflimit Default limit if none supplied
849 * @param $optionname Name of a user preference to check against
850 * @return array
851 *
852 */
853 function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) {
854 global $wgRequest;
855 return $wgRequest->getLimitOffset( $deflimit, $optionname );
856 }
857
858 /**
859 * Escapes the given text so that it may be output using addWikiText()
860 * without any linking, formatting, etc. making its way through. This
861 * is achieved by substituting certain characters with HTML entities.
862 * As required by the callers, <nowiki> is not used. It currently does
863 * not filter out characters which have special meaning only at the
864 * start of a line, such as "*".
865 *
866 * @param string $text Text to be escaped
867 */
868 function wfEscapeWikiText( $text ) {
869 $text = str_replace(
870 array( '[', '|', '\'', 'ISBN ', 'RFC ', '://', "\n=", '{{' ),
871 array( '&#91;', '&#124;', '&#39;', 'ISBN&#32;', 'RFC&#32;', '&#58;//', "\n&#61;", '&#123;&#123;' ),
872 htmlspecialchars($text) );
873 return $text;
874 }
875
876 /**
877 * @todo document
878 */
879 function wfQuotedPrintable( $string, $charset = '' ) {
880 # Probably incomplete; see RFC 2045
881 if( empty( $charset ) ) {
882 global $wgInputEncoding;
883 $charset = $wgInputEncoding;
884 }
885 $charset = strtoupper( $charset );
886 $charset = str_replace( 'ISO-8859', 'ISO8859', $charset ); // ?
887
888 $illegal = '\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\xff=';
889 $replace = $illegal . '\t ?_';
890 if( !preg_match( "/[$illegal]/", $string ) ) return $string;
891 $out = "=?$charset?Q?";
892 $out .= preg_replace( "/([$replace])/e", 'sprintf("=%02X",ord("$1"))', $string );
893 $out .= '?=';
894 return $out;
895 }
896
897
898 /**
899 * @todo document
900 * @return float
901 */
902 function wfTime() {
903 return microtime(true);
904 }
905
906 /**
907 * Sets dest to source and returns the original value of dest
908 * If source is NULL, it just returns the value, it doesn't set the variable
909 */
910 function wfSetVar( &$dest, $source ) {
911 $temp = $dest;
912 if ( !is_null( $source ) ) {
913 $dest = $source;
914 }
915 return $temp;
916 }
917
918 /**
919 * As for wfSetVar except setting a bit
920 */
921 function wfSetBit( &$dest, $bit, $state = true ) {
922 $temp = (bool)($dest & $bit );
923 if ( !is_null( $state ) ) {
924 if ( $state ) {
925 $dest |= $bit;
926 } else {
927 $dest &= ~$bit;
928 }
929 }
930 return $temp;
931 }
932
933 /**
934 * This function takes two arrays as input, and returns a CGI-style string, e.g.
935 * "days=7&limit=100". Options in the first array override options in the second.
936 * Options set to "" will not be output.
937 */
938 function wfArrayToCGI( $array1, $array2 = NULL )
939 {
940 if ( !is_null( $array2 ) ) {
941 $array1 = $array1 + $array2;
942 }
943
944 $cgi = '';
945 foreach ( $array1 as $key => $value ) {
946 if ( '' !== $value ) {
947 if ( '' != $cgi ) {
948 $cgi .= '&';
949 }
950 $cgi .= urlencode( $key ) . '=' . urlencode( $value );
951 }
952 }
953 return $cgi;
954 }
955
956 /**
957 * This is obsolete, use SquidUpdate::purge()
958 * @deprecated
959 */
960 function wfPurgeSquidServers ($urlArr) {
961 SquidUpdate::purge( $urlArr );
962 }
963
964 /**
965 * Windows-compatible version of escapeshellarg()
966 * Windows doesn't recognise single-quotes in the shell, but the escapeshellarg()
967 * function puts single quotes in regardless of OS
968 */
969 function wfEscapeShellArg( ) {
970 $args = func_get_args();
971 $first = true;
972 $retVal = '';
973 foreach ( $args as $arg ) {
974 if ( !$first ) {
975 $retVal .= ' ';
976 } else {
977 $first = false;
978 }
979
980 if ( wfIsWindows() ) {
981 // Escaping for an MSVC-style command line parser
982 // Ref: http://mailman.lyra.org/pipermail/scite-interest/2002-March/000436.html
983 // Double the backslashes before any double quotes. Escape the double quotes.
984 $tokens = preg_split( '/(\\\\*")/', $arg, -1, PREG_SPLIT_DELIM_CAPTURE );
985 $arg = '';
986 $delim = false;
987 foreach ( $tokens as $token ) {
988 if ( $delim ) {
989 $arg .= str_replace( '\\', '\\\\', substr( $token, 0, -1 ) ) . '\\"';
990 } else {
991 $arg .= $token;
992 }
993 $delim = !$delim;
994 }
995 // Double the backslashes before the end of the string, because
996 // we will soon add a quote
997 if ( preg_match( '/^(.*?)(\\\\+)$/', $arg, $m ) ) {
998 $arg = $m[1] . str_replace( '\\', '\\\\', $m[2] );
999 }
1000
1001 // Add surrounding quotes
1002 $retVal .= '"' . $arg . '"';
1003 } else {
1004 $retVal .= escapeshellarg( $arg );
1005 }
1006 }
1007 return $retVal;
1008 }
1009
1010 /**
1011 * wfMerge attempts to merge differences between three texts.
1012 * Returns true for a clean merge and false for failure or a conflict.
1013 */
1014 function wfMerge( $old, $mine, $yours, &$result ){
1015 global $wgDiff3;
1016
1017 # This check may also protect against code injection in
1018 # case of broken installations.
1019 if(! file_exists( $wgDiff3 ) ){
1020 wfDebug( "diff3 not found\n" );
1021 return false;
1022 }
1023
1024 # Make temporary files
1025 $td = wfTempDir();
1026 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
1027 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
1028 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
1029
1030 fwrite( $oldtextFile, $old ); fclose( $oldtextFile );
1031 fwrite( $mytextFile, $mine ); fclose( $mytextFile );
1032 fwrite( $yourtextFile, $yours ); fclose( $yourtextFile );
1033
1034 # Check for a conflict
1035 $cmd = $wgDiff3 . ' -a --overlap-only ' .
1036 wfEscapeShellArg( $mytextName ) . ' ' .
1037 wfEscapeShellArg( $oldtextName ) . ' ' .
1038 wfEscapeShellArg( $yourtextName );
1039 $handle = popen( $cmd, 'r' );
1040
1041 if( fgets( $handle, 1024 ) ){
1042 $conflict = true;
1043 } else {
1044 $conflict = false;
1045 }
1046 pclose( $handle );
1047
1048 # Merge differences
1049 $cmd = $wgDiff3 . ' -a -e --merge ' .
1050 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
1051 $handle = popen( $cmd, 'r' );
1052 $result = '';
1053 do {
1054 $data = fread( $handle, 8192 );
1055 if ( strlen( $data ) == 0 ) {
1056 break;
1057 }
1058 $result .= $data;
1059 } while ( true );
1060 pclose( $handle );
1061 unlink( $mytextName ); unlink( $oldtextName ); unlink( $yourtextName );
1062
1063 if ( $result === '' && $old !== '' && $conflict == false ) {
1064 wfDebug( "Unexpected null result from diff3. Command: $cmd\n" );
1065 $conflict = true;
1066 }
1067 return ! $conflict;
1068 }
1069
1070 /**
1071 * @todo document
1072 */
1073 function wfVarDump( $var ) {
1074 global $wgOut;
1075 $s = str_replace("\n","<br />\n", var_export( $var, true ) . "\n");
1076 if ( headers_sent() || !@is_object( $wgOut ) ) {
1077 print $s;
1078 } else {
1079 $wgOut->addHTML( $s );
1080 }
1081 }
1082
1083 /**
1084 * Provide a simple HTTP error.
1085 */
1086 function wfHttpError( $code, $label, $desc ) {
1087 global $wgOut;
1088 $wgOut->disable();
1089 header( "HTTP/1.0 $code $label" );
1090 header( "Status: $code $label" );
1091 $wgOut->sendCacheControl();
1092
1093 header( 'Content-type: text/html' );
1094 print "<html><head><title>" .
1095 htmlspecialchars( $label ) .
1096 "</title></head><body><h1>" .
1097 htmlspecialchars( $label ) .
1098 "</h1><p>" .
1099 htmlspecialchars( $desc ) .
1100 "</p></body></html>\n";
1101 }
1102
1103 /**
1104 * Converts an Accept-* header into an array mapping string values to quality
1105 * factors
1106 */
1107 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
1108 # No arg means accept anything (per HTTP spec)
1109 if( !$accept ) {
1110 return array( $def => 1 );
1111 }
1112
1113 $prefs = array();
1114
1115 $parts = explode( ',', $accept );
1116
1117 foreach( $parts as $part ) {
1118 # FIXME: doesn't deal with params like 'text/html; level=1'
1119 @list( $value, $qpart ) = explode( ';', $part );
1120 if( !isset( $qpart ) ) {
1121 $prefs[$value] = 1;
1122 } elseif( preg_match( '/q\s*=\s*(\d*\.\d+)/', $qpart, $match ) ) {
1123 $prefs[$value] = $match[1];
1124 }
1125 }
1126
1127 return $prefs;
1128 }
1129
1130 /**
1131 * Checks if a given MIME type matches any of the keys in the given
1132 * array. Basic wildcards are accepted in the array keys.
1133 *
1134 * Returns the matching MIME type (or wildcard) if a match, otherwise
1135 * NULL if no match.
1136 *
1137 * @param string $type
1138 * @param array $avail
1139 * @return string
1140 * @private
1141 */
1142 function mimeTypeMatch( $type, $avail ) {
1143 if( array_key_exists($type, $avail) ) {
1144 return $type;
1145 } else {
1146 $parts = explode( '/', $type );
1147 if( array_key_exists( $parts[0] . '/*', $avail ) ) {
1148 return $parts[0] . '/*';
1149 } elseif( array_key_exists( '*/*', $avail ) ) {
1150 return '*/*';
1151 } else {
1152 return NULL;
1153 }
1154 }
1155 }
1156
1157 /**
1158 * Returns the 'best' match between a client's requested internet media types
1159 * and the server's list of available types. Each list should be an associative
1160 * array of type to preference (preference is a float between 0.0 and 1.0).
1161 * Wildcards in the types are acceptable.
1162 *
1163 * @param array $cprefs Client's acceptable type list
1164 * @param array $sprefs Server's offered types
1165 * @return string
1166 *
1167 * @todo FIXME: doesn't handle params like 'text/plain; charset=UTF-8'
1168 * XXX: generalize to negotiate other stuff
1169 */
1170 function wfNegotiateType( $cprefs, $sprefs ) {
1171 $combine = array();
1172
1173 foreach( array_keys($sprefs) as $type ) {
1174 $parts = explode( '/', $type );
1175 if( $parts[1] != '*' ) {
1176 $ckey = mimeTypeMatch( $type, $cprefs );
1177 if( $ckey ) {
1178 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1179 }
1180 }
1181 }
1182
1183 foreach( array_keys( $cprefs ) as $type ) {
1184 $parts = explode( '/', $type );
1185 if( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
1186 $skey = mimeTypeMatch( $type, $sprefs );
1187 if( $skey ) {
1188 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1189 }
1190 }
1191 }
1192
1193 $bestq = 0;
1194 $besttype = NULL;
1195
1196 foreach( array_keys( $combine ) as $type ) {
1197 if( $combine[$type] > $bestq ) {
1198 $besttype = $type;
1199 $bestq = $combine[$type];
1200 }
1201 }
1202
1203 return $besttype;
1204 }
1205
1206 /**
1207 * Array lookup
1208 * Returns an array where the values in the first array are replaced by the
1209 * values in the second array with the corresponding keys
1210 *
1211 * @return array
1212 */
1213 function wfArrayLookup( $a, $b ) {
1214 return array_flip( array_intersect( array_flip( $a ), array_keys( $b ) ) );
1215 }
1216
1217 /**
1218 * Convenience function; returns MediaWiki timestamp for the present time.
1219 * @return string
1220 */
1221 function wfTimestampNow() {
1222 # return NOW
1223 return wfTimestamp( TS_MW, time() );
1224 }
1225
1226 /**
1227 * Reference-counted warning suppression
1228 */
1229 function wfSuppressWarnings( $end = false ) {
1230 static $suppressCount = 0;
1231 static $originalLevel = false;
1232
1233 if ( $end ) {
1234 if ( $suppressCount ) {
1235 --$suppressCount;
1236 if ( !$suppressCount ) {
1237 error_reporting( $originalLevel );
1238 }
1239 }
1240 } else {
1241 if ( !$suppressCount ) {
1242 $originalLevel = error_reporting( E_ALL & ~( E_WARNING | E_NOTICE ) );
1243 }
1244 ++$suppressCount;
1245 }
1246 }
1247
1248 /**
1249 * Restore error level to previous value
1250 */
1251 function wfRestoreWarnings() {
1252 wfSuppressWarnings( true );
1253 }
1254
1255 # Autodetect, convert and provide timestamps of various types
1256
1257 /**
1258 * Unix time - the number of seconds since 1970-01-01 00:00:00 UTC
1259 */
1260 define('TS_UNIX', 0);
1261
1262 /**
1263 * MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
1264 */
1265 define('TS_MW', 1);
1266
1267 /**
1268 * MySQL DATETIME (YYYY-MM-DD HH:MM:SS)
1269 */
1270 define('TS_DB', 2);
1271
1272 /**
1273 * RFC 2822 format, for E-mail and HTTP headers
1274 */
1275 define('TS_RFC2822', 3);
1276
1277 /**
1278 * ISO 8601 format with no timezone: 1986-02-09T20:00:00Z
1279 *
1280 * This is used by Special:Export
1281 */
1282 define('TS_ISO_8601', 4);
1283
1284 /**
1285 * An Exif timestamp (YYYY:MM:DD HH:MM:SS)
1286 *
1287 * @url http://exif.org/Exif2-2.PDF The Exif 2.2 spec, see page 28 for the
1288 * DateTime tag and page 36 for the DateTimeOriginal and
1289 * DateTimeDigitized tags.
1290 */
1291 define('TS_EXIF', 5);
1292
1293 /**
1294 * Oracle format time.
1295 */
1296 define('TS_ORACLE', 6);
1297
1298 /**
1299 * @param mixed $outputtype A timestamp in one of the supported formats, the
1300 * function will autodetect which format is supplied
1301 * and act accordingly.
1302 * @return string Time in the format specified in $outputtype
1303 */
1304 function wfTimestamp($outputtype=TS_UNIX,$ts=0) {
1305 $uts = 0;
1306 $da = array();
1307 if ($ts==0) {
1308 $uts=time();
1309 } elseif (preg_match("/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)$/D",$ts,$da)) {
1310 # TS_DB
1311 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1312 (int)$da[2],(int)$da[3],(int)$da[1]);
1313 } elseif (preg_match("/^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/D",$ts,$da)) {
1314 # TS_EXIF
1315 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1316 (int)$da[2],(int)$da[3],(int)$da[1]);
1317 } elseif (preg_match("/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/D",$ts,$da)) {
1318 # TS_MW
1319 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1320 (int)$da[2],(int)$da[3],(int)$da[1]);
1321 } elseif (preg_match("/^(\d{1,13})$/D",$ts,$datearray)) {
1322 # TS_UNIX
1323 $uts = $ts;
1324 } elseif (preg_match('/^(\d{1,2})-(...)-(\d\d(\d\d)?) (\d\d)\.(\d\d)\.(\d\d)/', $ts, $da)) {
1325 # TS_ORACLE
1326 $uts = strtotime(preg_replace('/(\d\d)\.(\d\d)\.(\d\d)(\.(\d+))?/', "$1:$2:$3",
1327 str_replace("+00:00", "UTC", $ts)));
1328 } elseif (preg_match('/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})Z$/', $ts, $da)) {
1329 # TS_ISO_8601
1330 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1331 (int)$da[2],(int)$da[3],(int)$da[1]);
1332 } else {
1333 # Bogus value; fall back to the epoch...
1334 wfDebug("wfTimestamp() fed bogus time value: $outputtype; $ts\n");
1335 $uts = 0;
1336 }
1337
1338
1339 switch($outputtype) {
1340 case TS_UNIX:
1341 return $uts;
1342 case TS_MW:
1343 return gmdate( 'YmdHis', $uts );
1344 case TS_DB:
1345 return gmdate( 'Y-m-d H:i:s', $uts );
1346 case TS_ISO_8601:
1347 return gmdate( 'Y-m-d\TH:i:s\Z', $uts );
1348 // This shouldn't ever be used, but is included for completeness
1349 case TS_EXIF:
1350 return gmdate( 'Y:m:d H:i:s', $uts );
1351 case TS_RFC2822:
1352 return gmdate( 'D, d M Y H:i:s', $uts ) . ' GMT';
1353 case TS_ORACLE:
1354 return gmdate( 'd-M-y h.i.s A', $uts) . ' +00:00';
1355 default:
1356 throw new MWException( 'wfTimestamp() called with illegal output type.');
1357 }
1358 }
1359
1360 /**
1361 * Return a formatted timestamp, or null if input is null.
1362 * For dealing with nullable timestamp columns in the database.
1363 * @param int $outputtype
1364 * @param string $ts
1365 * @return string
1366 */
1367 function wfTimestampOrNull( $outputtype = TS_UNIX, $ts = null ) {
1368 if( is_null( $ts ) ) {
1369 return null;
1370 } else {
1371 return wfTimestamp( $outputtype, $ts );
1372 }
1373 }
1374
1375 /**
1376 * Check if the operating system is Windows
1377 *
1378 * @return bool True if it's Windows, False otherwise.
1379 */
1380 function wfIsWindows() {
1381 if (substr(php_uname(), 0, 7) == 'Windows') {
1382 return true;
1383 } else {
1384 return false;
1385 }
1386 }
1387
1388 /**
1389 * Swap two variables
1390 */
1391 function swap( &$x, &$y ) {
1392 $z = $x;
1393 $x = $y;
1394 $y = $z;
1395 }
1396
1397 function wfGetCachedNotice( $name ) {
1398 global $wgOut, $parserMemc, $wgDBname;
1399 $fname = 'wfGetCachedNotice';
1400 wfProfileIn( $fname );
1401
1402 $needParse = false;
1403 $notice = wfMsgForContent( $name );
1404 if( $notice == '&lt;'. $name . ';&gt' || $notice == '-' ) {
1405 wfProfileOut( $fname );
1406 return( false );
1407 }
1408
1409 $cachedNotice = $parserMemc->get( $wgDBname . ':' . $name );
1410 if( is_array( $cachedNotice ) ) {
1411 if( md5( $notice ) == $cachedNotice['hash'] ) {
1412 $notice = $cachedNotice['html'];
1413 } else {
1414 $needParse = true;
1415 }
1416 } else {
1417 $needParse = true;
1418 }
1419
1420 if( $needParse ) {
1421 if( is_object( $wgOut ) ) {
1422 $parsed = $wgOut->parse( $notice );
1423 $parserMemc->set( $wgDBname . ':' . $name, array( 'html' => $parsed, 'hash' => md5( $notice ) ), 600 );
1424 $notice = $parsed;
1425 } else {
1426 wfDebug( 'wfGetCachedNotice called for ' . $name . ' with no $wgOut available' );
1427 $notice = '';
1428 }
1429 }
1430
1431 wfProfileOut( $fname );
1432 return $notice;
1433 }
1434
1435 function wfGetNamespaceNotice() {
1436 global $wgTitle;
1437
1438 # Paranoia
1439 if ( !isset( $wgTitle ) || !is_object( $wgTitle ) )
1440 return "";
1441
1442 $fname = 'wfGetNamespaceNotice';
1443 wfProfileIn( $fname );
1444
1445 $key = "namespacenotice-" . $wgTitle->getNsText();
1446 $namespaceNotice = wfGetCachedNotice( $key );
1447 if ( $namespaceNotice && substr ( $namespaceNotice , 0 ,7 ) != "<p>&lt;" ) {
1448 $namespaceNotice = '<div id="namespacebanner">' . $namespaceNotice . "</div>";
1449 } else {
1450 $namespaceNotice = "";
1451 }
1452
1453 wfProfileOut( $fname );
1454 return $namespaceNotice;
1455 }
1456
1457 function wfGetSiteNotice() {
1458 global $wgUser, $wgSiteNotice;
1459 $fname = 'wfGetSiteNotice';
1460 wfProfileIn( $fname );
1461 $siteNotice = '';
1462
1463 if( wfRunHooks( 'SiteNoticeBefore', array( &$siteNotice ) ) ) {
1464 if( is_object( $wgUser ) && $wgUser->isLoggedIn() ) {
1465 $siteNotice = wfGetCachedNotice( 'sitenotice' );
1466 $siteNotice = !$siteNotice ? $wgSiteNotice : $siteNotice;
1467 } else {
1468 $anonNotice = wfGetCachedNotice( 'anonnotice' );
1469 if( !$anonNotice ) {
1470 $siteNotice = wfGetCachedNotice( 'sitenotice' );
1471 $siteNotice = !$siteNotice ? $wgSiteNotice : $siteNotice;
1472 } else {
1473 $siteNotice = $anonNotice;
1474 }
1475 }
1476 }
1477
1478 wfRunHooks( 'SiteNoticeAfter', array( &$siteNotice ) );
1479 wfProfileOut( $fname );
1480 return $siteNotice;
1481 }
1482
1483 /** Global singleton instance of MimeMagic. This is initialized on demand,
1484 * please always use the wfGetMimeMagic() function to get the instance.
1485 *
1486 * @private
1487 */
1488 $wgMimeMagic= NULL;
1489
1490 /** Factory functions for the global MimeMagic object.
1491 * This function always returns the same singleton instance of MimeMagic.
1492 * That objects will be instantiated on the first call to this function.
1493 * If needed, the MimeMagic.php file is automatically included by this function.
1494 * @return MimeMagic the global MimeMagic objects.
1495 */
1496 function &wfGetMimeMagic() {
1497 global $wgMimeMagic;
1498
1499 if (!is_null($wgMimeMagic)) {
1500 return $wgMimeMagic;
1501 }
1502
1503 if (!class_exists("MimeMagic")) {
1504 #include on demand
1505 require_once("MimeMagic.php");
1506 }
1507
1508 $wgMimeMagic= new MimeMagic();
1509
1510 return $wgMimeMagic;
1511 }
1512
1513
1514 /**
1515 * Tries to get the system directory for temporary files.
1516 * The TMPDIR, TMP, and TEMP environment variables are checked in sequence,
1517 * and if none are set /tmp is returned as the generic Unix default.
1518 *
1519 * NOTE: When possible, use the tempfile() function to create temporary
1520 * files to avoid race conditions on file creation, etc.
1521 *
1522 * @return string
1523 */
1524 function wfTempDir() {
1525 foreach( array( 'TMPDIR', 'TMP', 'TEMP' ) as $var ) {
1526 $tmp = getenv( $var );
1527 if( $tmp && file_exists( $tmp ) && is_dir( $tmp ) && is_writable( $tmp ) ) {
1528 return $tmp;
1529 }
1530 }
1531 # Hope this is Unix of some kind!
1532 return '/tmp';
1533 }
1534
1535 /**
1536 * Make directory, and make all parent directories if they don't exist
1537 */
1538 function wfMkdirParents( $fullDir, $mode = 0777 ) {
1539 if ( strval( $fullDir ) === '' ) {
1540 return true;
1541 }
1542
1543 # Go back through the paths to find the first directory that exists
1544 $currentDir = $fullDir;
1545 $createList = array();
1546 while ( strval( $currentDir ) !== '' && !file_exists( $currentDir ) ) {
1547 # Strip trailing slashes
1548 $currentDir = rtrim( $currentDir, '/\\' );
1549
1550 # Add to create list
1551 $createList[] = $currentDir;
1552
1553 # Find next delimiter searching from the end
1554 $p = max( strrpos( $currentDir, '/' ), strrpos( $currentDir, '\\' ) );
1555 if ( $p === false ) {
1556 $currentDir = false;
1557 } else {
1558 $currentDir = substr( $currentDir, 0, $p );
1559 }
1560 }
1561
1562 if ( count( $createList ) == 0 ) {
1563 # Directory specified already exists
1564 return true;
1565 } elseif ( $currentDir === false ) {
1566 # Went all the way back to root and it apparently doesn't exist
1567 return false;
1568 }
1569
1570 # Now go forward creating directories
1571 $createList = array_reverse( $createList );
1572 foreach ( $createList as $dir ) {
1573 # use chmod to override the umask, as suggested by the PHP manual
1574 if ( !mkdir( $dir, $mode ) || !chmod( $dir, $mode ) ) {
1575 return false;
1576 }
1577 }
1578 return true;
1579 }
1580
1581 /**
1582 * Increment a statistics counter
1583 */
1584 function wfIncrStats( $key ) {
1585 global $wgDBname, $wgMemc;
1586 $key = "$wgDBname:stats:$key";
1587 if ( is_null( $wgMemc->incr( $key ) ) ) {
1588 $wgMemc->add( $key, 1 );
1589 }
1590 }
1591
1592 /**
1593 * @param mixed $nr The number to format
1594 * @param int $acc The number of digits after the decimal point, default 2
1595 * @param bool $round Whether or not to round the value, default true
1596 * @return float
1597 */
1598 function wfPercent( $nr, $acc = 2, $round = true ) {
1599 $ret = sprintf( "%.${acc}f", $nr );
1600 return $round ? round( $ret, $acc ) . '%' : "$ret%";
1601 }
1602
1603 /**
1604 * Encrypt a username/password.
1605 *
1606 * @param string $userid ID of the user
1607 * @param string $password Password of the user
1608 * @return string Hashed password
1609 */
1610 function wfEncryptPassword( $userid, $password ) {
1611 global $wgPasswordSalt;
1612 $p = md5( $password);
1613
1614 if($wgPasswordSalt)
1615 return md5( "{$userid}-{$p}" );
1616 else
1617 return $p;
1618 }
1619
1620 /**
1621 * Appends to second array if $value differs from that in $default
1622 */
1623 function wfAppendToArrayIfNotDefault( $key, $value, $default, &$changed ) {
1624 if ( is_null( $changed ) ) {
1625 throw new MWException('GlobalFunctions::wfAppendToArrayIfNotDefault got null');
1626 }
1627 if ( $default[$key] !== $value ) {
1628 $changed[$key] = $value;
1629 }
1630 }
1631
1632 /**
1633 * Since wfMsg() and co suck, they don't return false if the message key they
1634 * looked up didn't exist but a XHTML string, this function checks for the
1635 * nonexistance of messages by looking at wfMsg() output
1636 *
1637 * @param $msg The message key looked up
1638 * @param $wfMsgOut The output of wfMsg*()
1639 * @return bool
1640 */
1641 function wfEmptyMsg( $msg, $wfMsgOut ) {
1642 return $wfMsgOut === "&lt;$msg&gt;";
1643 }
1644
1645 /**
1646 * Find out whether or not a mixed variable exists in a string
1647 *
1648 * @param mixed needle
1649 * @param string haystack
1650 * @return bool
1651 */
1652 function in_string( $needle, $str ) {
1653 return strpos( $str, $needle ) !== false;
1654 }
1655
1656 function wfSpecialList( $page, $details ) {
1657 global $wgContLang;
1658 $details = $details ? ' ' . $wgContLang->getDirMark() . "($details)" : "";
1659 return $page . $details;
1660 }
1661
1662 /**
1663 * Returns a regular expression of url protocols
1664 *
1665 * @return string
1666 */
1667 function wfUrlProtocols() {
1668 global $wgUrlProtocols;
1669
1670 // Support old-style $wgUrlProtocols strings, for backwards compatibility
1671 // with LocalSettings files from 1.5
1672 if ( is_array( $wgUrlProtocols ) ) {
1673 $protocols = array();
1674 foreach ($wgUrlProtocols as $protocol)
1675 $protocols[] = preg_quote( $protocol, '/' );
1676
1677 return implode( '|', $protocols );
1678 } else {
1679 return $wgUrlProtocols;
1680 }
1681 }
1682
1683 /**
1684 * Execute a shell command, with time and memory limits mirrored from the PHP
1685 * configuration if supported.
1686 * @param $cmd Command line, properly escaped for shell.
1687 * @param &$retval optional, will receive the program's exit code.
1688 * (non-zero is usually failure)
1689 * @return collected stdout as a string (trailing newlines stripped)
1690 */
1691 function wfShellExec( $cmd, &$retval=null ) {
1692 global $IP, $wgMaxShellMemory;
1693
1694 if( ini_get( 'safe_mode' ) ) {
1695 wfDebug( "wfShellExec can't run in safe_mode, PHP's exec functions are too broken.\n" );
1696 $retval = 1;
1697 return "Unable to run external programs in safe mode.";
1698 }
1699
1700 if ( php_uname( 's' ) == 'Linux' ) {
1701 $time = ini_get( 'max_execution_time' );
1702 $mem = intval( $wgMaxShellMemory );
1703
1704 if ( $time > 0 && $mem > 0 ) {
1705 $script = "$IP/bin/ulimit.sh";
1706 if ( is_executable( $script ) ) {
1707 $cmd = escapeshellarg( $script ) . " $time $mem $cmd";
1708 }
1709 }
1710 } elseif ( php_uname( 's' ) == 'Windows NT' ) {
1711 # This is a hack to work around PHP's flawed invocation of cmd.exe
1712 # http://news.php.net/php.internals/21796
1713 $cmd = '"' . $cmd . '"';
1714 }
1715 wfDebug( "wfShellExec: $cmd\n" );
1716
1717 $output = array();
1718 $retval = 1; // error by default?
1719 $lastline = exec( $cmd, $output, $retval );
1720 return implode( "\n", $output );
1721
1722 }
1723
1724 /**
1725 * This function works like "use VERSION" in Perl, the program will die with a
1726 * backtrace if the current version of PHP is less than the version provided
1727 *
1728 * This is useful for extensions which due to their nature are not kept in sync
1729 * with releases, and might depend on other versions of PHP than the main code
1730 *
1731 * Note: PHP might die due to parsing errors in some cases before it ever
1732 * manages to call this function, such is life
1733 *
1734 * @see perldoc -f use
1735 *
1736 * @param mixed $version The version to check, can be a string, an integer, or
1737 * a float
1738 */
1739 function wfUsePHP( $req_ver ) {
1740 $php_ver = PHP_VERSION;
1741
1742 if ( version_compare( $php_ver, (string)$req_ver, '<' ) )
1743 throw new MWException( "PHP $req_ver required--this is only $php_ver" );
1744 }
1745
1746 /**
1747 * This function works like "use VERSION" in Perl except it checks the version
1748 * of MediaWiki, the program will die with a backtrace if the current version
1749 * of MediaWiki is less than the version provided.
1750 *
1751 * This is useful for extensions which due to their nature are not kept in sync
1752 * with releases
1753 *
1754 * @see perldoc -f use
1755 *
1756 * @param mixed $version The version to check, can be a string, an integer, or
1757 * a float
1758 */
1759 function wfUseMW( $req_ver ) {
1760 global $wgVersion;
1761
1762 if ( version_compare( $wgVersion, (string)$req_ver, '<' ) )
1763 throw new MWException( "MediaWiki $req_ver required--this is only $wgVersion" );
1764 }
1765
1766 /**
1767 * Escape a string to make it suitable for inclusion in a preg_replace()
1768 * replacement parameter.
1769 *
1770 * @param string $string
1771 * @return string
1772 */
1773 function wfRegexReplacement( $string ) {
1774 $string = str_replace( '\\', '\\\\', $string );
1775 $string = str_replace( '$', '\\$', $string );
1776 return $string;
1777 }
1778
1779 /**
1780 * Return the final portion of a pathname.
1781 * Reimplemented because PHP5's basename() is buggy with multibyte text.
1782 * http://bugs.php.net/bug.php?id=33898
1783 *
1784 * PHP's basename() only considers '\' a pathchar on Windows and Netware.
1785 * We'll consider it so always, as we don't want \s in our Unix paths either.
1786 *
1787 * @param string $path
1788 * @return string
1789 */
1790 function wfBaseName( $path ) {
1791 if( preg_match( '#([^/\\\\]*)[/\\\\]*$#', $path, $matches ) ) {
1792 return $matches[1];
1793 } else {
1794 return '';
1795 }
1796 }
1797
1798 /**
1799 * Make a URL index, appropriate for the el_index field of externallinks.
1800 */
1801 function wfMakeUrlIndex( $url ) {
1802 wfSuppressWarnings();
1803 $bits = parse_url( $url );
1804 wfRestoreWarnings();
1805 if ( !$bits || $bits['scheme'] !== 'http' ) {
1806 return false;
1807 }
1808 // Reverse the labels in the hostname, convert to lower case
1809 $reversedHost = strtolower( implode( '.', array_reverse( explode( '.', $bits['host'] ) ) ) );
1810 // Add an extra dot to the end
1811 if ( substr( $reversedHost, -1, 1 ) !== '.' ) {
1812 $reversedHost .= '.';
1813 }
1814 // Reconstruct the pseudo-URL
1815 $index = "http://$reversedHost";
1816 // Leave out user and password. Add the port, path, query and fragment
1817 if ( isset( $bits['port'] ) ) $index .= ':' . $bits['port'];
1818 if ( isset( $bits['path'] ) ) {
1819 $index .= $bits['path'];
1820 } else {
1821 $index .= '/';
1822 }
1823 if ( isset( $bits['query'] ) ) $index .= '?' . $bits['query'];
1824 if ( isset( $bits['fragment'] ) ) $index .= '#' . $bits['fragment'];
1825 return $index;
1826 }
1827
1828 /**
1829 * Do any deferred updates and clear the list
1830 * TODO: This could be in Wiki.php if that class made any sense at all
1831 */
1832 function wfDoUpdates()
1833 {
1834 global $wgPostCommitUpdateList, $wgDeferredUpdateList;
1835 foreach ( $wgDeferredUpdateList as $update ) {
1836 $update->doUpdate();
1837 }
1838 foreach ( $wgPostCommitUpdateList as $update ) {
1839 $update->doUpdate();
1840 }
1841 $wgDeferredUpdateList = array();
1842 $wgPostCommitUpdateList = array();
1843 }
1844
1845 /**
1846 * More or less "markup-safe" explode()
1847 * Ignores any instances of the separator inside <...>
1848 * @param string $separator
1849 * @param string $text
1850 * @return array
1851 */
1852 function wfExplodeMarkup( $separator, $text ) {
1853 $placeholder = "\x00";
1854
1855 // Just in case...
1856 $text = str_replace( $placeholder, '', $text );
1857
1858 // Trim stuff
1859 $replacer = new ReplacerCallback( $separator, $placeholder );
1860 $cleaned = preg_replace_callback( '/(<.*?>)/', array( $replacer, 'go' ), $text );
1861
1862 $items = explode( $separator, $cleaned );
1863 foreach( $items as $i => $str ) {
1864 $items[$i] = str_replace( $placeholder, $separator, $str );
1865 }
1866
1867 return $items;
1868 }
1869
1870 class ReplacerCallback {
1871 function ReplacerCallback( $from, $to ) {
1872 $this->from = $from;
1873 $this->to = $to;
1874 }
1875
1876 function go( $matches ) {
1877 return str_replace( $this->from, $this->to, $matches[1] );
1878 }
1879 }
1880
1881
1882 /**
1883 * Convert an arbitrarily-long digit string from one numeric base
1884 * to another, optionally zero-padding to a minimum column width.
1885 *
1886 * Supports base 2 through 36; digit values 10-36 are represented
1887 * as lowercase letters a-z. Input is case-insensitive.
1888 *
1889 * @param $input string of digits
1890 * @param $sourceBase int 2-36
1891 * @param $destBase int 2-36
1892 * @param $pad int 1 or greater
1893 * @return string or false on invalid input
1894 */
1895 function wfBaseConvert( $input, $sourceBase, $destBase, $pad=1 ) {
1896 if( $sourceBase < 2 ||
1897 $sourceBase > 36 ||
1898 $destBase < 2 ||
1899 $destBase > 36 ||
1900 $pad < 1 ||
1901 $sourceBase != intval( $sourceBase ) ||
1902 $destBase != intval( $destBase ) ||
1903 $pad != intval( $pad ) ||
1904 !is_string( $input ) ||
1905 $input == '' ) {
1906 return false;
1907 }
1908
1909 $digitChars = '0123456789abcdefghijklmnopqrstuvwxyz';
1910 $inDigits = array();
1911 $outChars = '';
1912
1913 // Decode and validate input string
1914 $input = strtolower( $input );
1915 for( $i = 0; $i < strlen( $input ); $i++ ) {
1916 $n = strpos( $digitChars, $input{$i} );
1917 if( $n === false || $n > $sourceBase ) {
1918 return false;
1919 }
1920 $inDigits[] = $n;
1921 }
1922
1923 // Iterate over the input, modulo-ing out an output digit
1924 // at a time until input is gone.
1925 while( count( $inDigits ) ) {
1926 $work = 0;
1927 $workDigits = array();
1928
1929 // Long division...
1930 foreach( $inDigits as $digit ) {
1931 $work *= $sourceBase;
1932 $work += $digit;
1933
1934 if( $work < $destBase ) {
1935 // Gonna need to pull another digit.
1936 if( count( $workDigits ) ) {
1937 // Avoid zero-padding; this lets us find
1938 // the end of the input very easily when
1939 // length drops to zero.
1940 $workDigits[] = 0;
1941 }
1942 } else {
1943 // Finally! Actual division!
1944 $workDigits[] = intval( $work / $destBase );
1945
1946 // Isn't it annoying that most programming languages
1947 // don't have a single divide-and-remainder operator,
1948 // even though the CPU implements it that way?
1949 $work = $work % $destBase;
1950 }
1951 }
1952
1953 // All that division leaves us with a remainder,
1954 // which is conveniently our next output digit.
1955 $outChars .= $digitChars[$work];
1956
1957 // And we continue!
1958 $inDigits = $workDigits;
1959 }
1960
1961 while( strlen( $outChars ) < $pad ) {
1962 $outChars .= '0';
1963 }
1964
1965 return strrev( $outChars );
1966 }
1967
1968 /**
1969 * Create an object with a given name and an array of construct parameters
1970 * @param string $name
1971 * @param array $p parameters
1972 */
1973 function wfCreateObject( $name, $p ){
1974 $p = array_values( $p );
1975 switch ( count( $p ) ) {
1976 case 0:
1977 return new $name;
1978 case 1:
1979 return new $name( $p[0] );
1980 case 2:
1981 return new $name( $p[0], $p[1] );
1982 case 3:
1983 return new $name( $p[0], $p[1], $p[2] );
1984 case 4:
1985 return new $name( $p[0], $p[1], $p[2], $p[3] );
1986 case 5:
1987 return new $name( $p[0], $p[1], $p[2], $p[3], $p[4] );
1988 case 6:
1989 return new $name( $p[0], $p[1], $p[2], $p[3], $p[4], $p[5] );
1990 default:
1991 throw new MWException( "Too many arguments to construtor in wfCreateObject" );
1992 }
1993 }
1994
1995 /**
1996 * Aliases for modularized functions
1997 */
1998 function wfGetHTTP( $url, $timeout = 'default' ) {
1999 return Http::get( $url, $timeout );
2000 }
2001 function wfIsLocalURL( $url ) {
2002 return Http::isLocalURL( $url );
2003 }
2004
2005 ?>