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