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