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