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