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