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