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