remove memcached polution ... ah, and namespace notices on the way
[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 $wgUser, $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 $wgUser, $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 $retVal .= '"' . str_replace( '"','\"', $arg ) . '"';
960 } else {
961 $retVal .= escapeshellarg( $arg );
962 }
963 }
964 return $retVal;
965 }
966
967 /**
968 * wfMerge attempts to merge differences between three texts.
969 * Returns true for a clean merge and false for failure or a conflict.
970 */
971 function wfMerge( $old, $mine, $yours, &$result ){
972 global $wgDiff3;
973
974 # This check may also protect against code injection in
975 # case of broken installations.
976 if(! file_exists( $wgDiff3 ) ){
977 wfDebug( "diff3 not found\n" );
978 return false;
979 }
980
981 # Make temporary files
982 $td = wfTempDir();
983 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
984 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
985 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
986
987 fwrite( $oldtextFile, $old ); fclose( $oldtextFile );
988 fwrite( $mytextFile, $mine ); fclose( $mytextFile );
989 fwrite( $yourtextFile, $yours ); fclose( $yourtextFile );
990
991 # Check for a conflict
992 $cmd = $wgDiff3 . ' -a --overlap-only ' .
993 wfEscapeShellArg( $mytextName ) . ' ' .
994 wfEscapeShellArg( $oldtextName ) . ' ' .
995 wfEscapeShellArg( $yourtextName );
996 $handle = popen( $cmd, 'r' );
997
998 if( fgets( $handle, 1024 ) ){
999 $conflict = true;
1000 } else {
1001 $conflict = false;
1002 }
1003 pclose( $handle );
1004
1005 # Merge differences
1006 $cmd = $wgDiff3 . ' -a -e --merge ' .
1007 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
1008 $handle = popen( $cmd, 'r' );
1009 $result = '';
1010 do {
1011 $data = fread( $handle, 8192 );
1012 if ( strlen( $data ) == 0 ) {
1013 break;
1014 }
1015 $result .= $data;
1016 } while ( true );
1017 pclose( $handle );
1018 unlink( $mytextName ); unlink( $oldtextName ); unlink( $yourtextName );
1019
1020 if ( $result === '' && $old !== '' && $conflict == false ) {
1021 wfDebug( "Unexpected null result from diff3. Command: $cmd\n" );
1022 $conflict = true;
1023 }
1024 return ! $conflict;
1025 }
1026
1027 /**
1028 * @todo document
1029 */
1030 function wfVarDump( $var ) {
1031 global $wgOut;
1032 $s = str_replace("\n","<br />\n", var_export( $var, true ) . "\n");
1033 if ( headers_sent() || !@is_object( $wgOut ) ) {
1034 print $s;
1035 } else {
1036 $wgOut->addHTML( $s );
1037 }
1038 }
1039
1040 /**
1041 * Provide a simple HTTP error.
1042 */
1043 function wfHttpError( $code, $label, $desc ) {
1044 global $wgOut;
1045 $wgOut->disable();
1046 header( "HTTP/1.0 $code $label" );
1047 header( "Status: $code $label" );
1048 $wgOut->sendCacheControl();
1049
1050 header( 'Content-type: text/html' );
1051 print "<html><head><title>" .
1052 htmlspecialchars( $label ) .
1053 "</title></head><body><h1>" .
1054 htmlspecialchars( $label ) .
1055 "</h1><p>" .
1056 htmlspecialchars( $desc ) .
1057 "</p></body></html>\n";
1058 }
1059
1060 /**
1061 * Converts an Accept-* header into an array mapping string values to quality
1062 * factors
1063 */
1064 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
1065 # No arg means accept anything (per HTTP spec)
1066 if( !$accept ) {
1067 return array( $def => 1 );
1068 }
1069
1070 $prefs = array();
1071
1072 $parts = explode( ',', $accept );
1073
1074 foreach( $parts as $part ) {
1075 # FIXME: doesn't deal with params like 'text/html; level=1'
1076 @list( $value, $qpart ) = explode( ';', $part );
1077 if( !isset( $qpart ) ) {
1078 $prefs[$value] = 1;
1079 } elseif( preg_match( '/q\s*=\s*(\d*\.\d+)/', $qpart, $match ) ) {
1080 $prefs[$value] = $match[1];
1081 }
1082 }
1083
1084 return $prefs;
1085 }
1086
1087 /**
1088 * Checks if a given MIME type matches any of the keys in the given
1089 * array. Basic wildcards are accepted in the array keys.
1090 *
1091 * Returns the matching MIME type (or wildcard) if a match, otherwise
1092 * NULL if no match.
1093 *
1094 * @param string $type
1095 * @param array $avail
1096 * @return string
1097 * @access private
1098 */
1099 function mimeTypeMatch( $type, $avail ) {
1100 if( array_key_exists($type, $avail) ) {
1101 return $type;
1102 } else {
1103 $parts = explode( '/', $type );
1104 if( array_key_exists( $parts[0] . '/*', $avail ) ) {
1105 return $parts[0] . '/*';
1106 } elseif( array_key_exists( '*/*', $avail ) ) {
1107 return '*/*';
1108 } else {
1109 return NULL;
1110 }
1111 }
1112 }
1113
1114 /**
1115 * Returns the 'best' match between a client's requested internet media types
1116 * and the server's list of available types. Each list should be an associative
1117 * array of type to preference (preference is a float between 0.0 and 1.0).
1118 * Wildcards in the types are acceptable.
1119 *
1120 * @param array $cprefs Client's acceptable type list
1121 * @param array $sprefs Server's offered types
1122 * @return string
1123 *
1124 * @todo FIXME: doesn't handle params like 'text/plain; charset=UTF-8'
1125 * XXX: generalize to negotiate other stuff
1126 */
1127 function wfNegotiateType( $cprefs, $sprefs ) {
1128 $combine = array();
1129
1130 foreach( array_keys($sprefs) as $type ) {
1131 $parts = explode( '/', $type );
1132 if( $parts[1] != '*' ) {
1133 $ckey = mimeTypeMatch( $type, $cprefs );
1134 if( $ckey ) {
1135 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1136 }
1137 }
1138 }
1139
1140 foreach( array_keys( $cprefs ) as $type ) {
1141 $parts = explode( '/', $type );
1142 if( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
1143 $skey = mimeTypeMatch( $type, $sprefs );
1144 if( $skey ) {
1145 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1146 }
1147 }
1148 }
1149
1150 $bestq = 0;
1151 $besttype = NULL;
1152
1153 foreach( array_keys( $combine ) as $type ) {
1154 if( $combine[$type] > $bestq ) {
1155 $besttype = $type;
1156 $bestq = $combine[$type];
1157 }
1158 }
1159
1160 return $besttype;
1161 }
1162
1163 /**
1164 * Array lookup
1165 * Returns an array where the values in the first array are replaced by the
1166 * values in the second array with the corresponding keys
1167 *
1168 * @return array
1169 */
1170 function wfArrayLookup( $a, $b ) {
1171 return array_flip( array_intersect( array_flip( $a ), array_keys( $b ) ) );
1172 }
1173
1174 /**
1175 * Convenience function; returns MediaWiki timestamp for the present time.
1176 * @return string
1177 */
1178 function wfTimestampNow() {
1179 # return NOW
1180 return wfTimestamp( TS_MW, time() );
1181 }
1182
1183 /**
1184 * Reference-counted warning suppression
1185 */
1186 function wfSuppressWarnings( $end = false ) {
1187 static $suppressCount = 0;
1188 static $originalLevel = false;
1189
1190 if ( $end ) {
1191 if ( $suppressCount ) {
1192 --$suppressCount;
1193 if ( !$suppressCount ) {
1194 error_reporting( $originalLevel );
1195 }
1196 }
1197 } else {
1198 if ( !$suppressCount ) {
1199 $originalLevel = error_reporting( E_ALL & ~( E_WARNING | E_NOTICE ) );
1200 }
1201 ++$suppressCount;
1202 }
1203 }
1204
1205 /**
1206 * Restore error level to previous value
1207 */
1208 function wfRestoreWarnings() {
1209 wfSuppressWarnings( true );
1210 }
1211
1212 # Autodetect, convert and provide timestamps of various types
1213
1214 /**
1215 * Unix time - the number of seconds since 1970-01-01 00:00:00 UTC
1216 */
1217 define('TS_UNIX', 0);
1218
1219 /**
1220 * MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
1221 */
1222 define('TS_MW', 1);
1223
1224 /**
1225 * MySQL DATETIME (YYYY-MM-DD HH:MM:SS)
1226 */
1227 define('TS_DB', 2);
1228
1229 /**
1230 * RFC 2822 format, for E-mail and HTTP headers
1231 */
1232 define('TS_RFC2822', 3);
1233
1234 /**
1235 * ISO 8601 format with no timezone: 1986-02-09T20:00:00Z
1236 *
1237 * This is used by Special:Export
1238 */
1239 define('TS_ISO_8601', 4);
1240
1241 /**
1242 * An Exif timestamp (YYYY:MM:DD HH:MM:SS)
1243 *
1244 * @link http://exif.org/Exif2-2.PDF The Exif 2.2 spec, see page 28 for the
1245 * DateTime tag and page 36 for the DateTimeOriginal and
1246 * DateTimeDigitized tags.
1247 */
1248 define('TS_EXIF', 5);
1249
1250 /**
1251 * Oracle format time.
1252 */
1253 define('TS_ORACLE', 6);
1254
1255 /**
1256 * @param mixed $outputtype A timestamp in one of the supported formats, the
1257 * function will autodetect which format is supplied
1258 and act accordingly.
1259 * @return string Time in the format specified in $outputtype
1260 */
1261 function wfTimestamp($outputtype=TS_UNIX,$ts=0) {
1262 $uts = 0;
1263 if ($ts==0) {
1264 $uts=time();
1265 } elseif (preg_match("/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)$/",$ts,$da)) {
1266 # TS_DB
1267 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1268 (int)$da[2],(int)$da[3],(int)$da[1]);
1269 } elseif (preg_match("/^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/",$ts,$da)) {
1270 # TS_EXIF
1271 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1272 (int)$da[2],(int)$da[3],(int)$da[1]);
1273 } elseif (preg_match("/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/",$ts,$da)) {
1274 # TS_MW
1275 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1276 (int)$da[2],(int)$da[3],(int)$da[1]);
1277 } elseif (preg_match("/^(\d{1,13})$/",$ts,$datearray)) {
1278 # TS_UNIX
1279 $uts=$ts;
1280 } elseif (preg_match('/^(\d{1,2})-(...)-(\d\d(\d\d)?) (\d\d)\.(\d\d)\.(\d\d)/', $ts, $da)) {
1281 # TS_ORACLE
1282 $uts = strtotime(preg_replace('/(\d\d)\.(\d\d)\.(\d\d)(\.(\d+))?/', "$1:$2:$3",
1283 str_replace("+00:00", "UTC", $ts)));
1284 } elseif (preg_match('/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})Z$/', $ts, $da)) {
1285 # TS_ISO_8601
1286 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1287 (int)$da[2],(int)$da[3],(int)$da[1]);
1288 } else {
1289 # Bogus value; fall back to the epoch...
1290 wfDebug("wfTimestamp() fed bogus time value: $outputtype; $ts\n");
1291 $uts = 0;
1292 }
1293
1294
1295 switch($outputtype) {
1296 case TS_UNIX:
1297 return $uts;
1298 case TS_MW:
1299 return gmdate( 'YmdHis', $uts );
1300 case TS_DB:
1301 return gmdate( 'Y-m-d H:i:s', $uts );
1302 case TS_ISO_8601:
1303 return gmdate( 'Y-m-d\TH:i:s\Z', $uts );
1304 // This shouldn't ever be used, but is included for completeness
1305 case TS_EXIF:
1306 return gmdate( 'Y:m:d H:i:s', $uts );
1307 case TS_RFC2822:
1308 return gmdate( 'D, d M Y H:i:s', $uts ) . ' GMT';
1309 case TS_ORACLE:
1310 return gmdate( 'd-M-y h.i.s A', $uts) . ' +00:00';
1311 default:
1312 wfDebugDieBacktrace( 'wfTimestamp() called with illegal output type.');
1313 }
1314 }
1315
1316 /**
1317 * Return a formatted timestamp, or null if input is null.
1318 * For dealing with nullable timestamp columns in the database.
1319 * @param int $outputtype
1320 * @param string $ts
1321 * @return string
1322 */
1323 function wfTimestampOrNull( $outputtype = TS_UNIX, $ts = null ) {
1324 if( is_null( $ts ) ) {
1325 return null;
1326 } else {
1327 return wfTimestamp( $outputtype, $ts );
1328 }
1329 }
1330
1331 /**
1332 * Check if the operating system is Windows
1333 *
1334 * @return bool True if it's Windows, False otherwise.
1335 */
1336 function wfIsWindows() {
1337 if (substr(php_uname(), 0, 7) == 'Windows') {
1338 return true;
1339 } else {
1340 return false;
1341 }
1342 }
1343
1344 /**
1345 * Swap two variables
1346 */
1347 function swap( &$x, &$y ) {
1348 $z = $x;
1349 $x = $y;
1350 $y = $z;
1351 }
1352
1353 function wfGetCachedNotice( $name ) {
1354 global $wgOut, $parserMemc, $wgDBname;
1355 $fname = 'wfGetCachedNotice';
1356 wfProfileIn( $fname );
1357
1358 $needParse = false;
1359 $notice = wfMsgForContent( $name );
1360 if( $notice == '&lt;'. $name . ';&gt' || $notice == '-' ) {
1361 wfProfileOut( $fname );
1362 return( false );
1363 }
1364
1365 $cachedNotice = $parserMemc->get( $wgDBname . ':' . $name );
1366 if( is_array( $cachedNotice ) ) {
1367 if( md5( $notice ) == $cachedNotice['hash'] ) {
1368 $notice = $cachedNotice['html'];
1369 } else {
1370 $needParse = true;
1371 }
1372 } else {
1373 $needParse = true;
1374 }
1375
1376 if( $needParse ) {
1377 if( is_object( $wgOut ) ) {
1378 $parsed = $wgOut->parse( $notice );
1379 $parserMemc->set( $wgDBname . ':' . $name, array( 'html' => $parsed, 'hash' => md5( $notice ) ), 600 );
1380 $notice = $parsed;
1381 } else {
1382 wfDebug( 'wfGetCachedNotice called for ' . $name . ' with no $wgOut available' );
1383 $notice = '';
1384 }
1385 }
1386
1387 wfProfileOut( $fname );
1388 return $notice;
1389 }
1390
1391 function wfGetNamespaceNotice() {
1392 global $wgTitle;
1393
1394 # Paranoia
1395 if ( !isset( $wgTitle ) || !is_object( $wgTitle ) )
1396 return "";
1397
1398 $fname = 'wfGetNamespaceNotice';
1399 wfProfileIn( $fname );
1400
1401 $key = "namespacenotice-" . $wgTitle->getNsText();
1402 $namespaceNotice = wfGetCachedNotice( $key );
1403 if ( $namespaceNotice && substr ( $namespaceNotice , 0 ,7 ) != "<p>&lt;" ) {
1404 $namespaceNotice = '<div id="namespacebanner">' . $namespaceNotice . "</div>";
1405 } else {
1406 $namespaceNotice = "";
1407 }
1408
1409 wfProfileOut( $fname );
1410 return $namespaceNotice;
1411 }
1412
1413 function wfGetSiteNotice() {
1414 global $wgUser, $wgSiteNotice;
1415 $fname = 'wfGetSiteNotice';
1416 wfProfileIn( $fname );
1417
1418 if( is_object( $wgUser ) && $wgUser->isLoggedIn() ) {
1419 $siteNotice = wfGetCachedNotice( 'sitenotice' );
1420 $siteNotice = !$siteNotice ? $wgSiteNotice : $siteNotice;
1421 } else {
1422 $anonNotice = wfGetCachedNotice( 'anonnotice' );
1423 if( !$anonNotice ) {
1424 $siteNotice = wfGetCachedNotice( 'sitenotice' );
1425 $siteNotice = !$siteNotice ? $wgSiteNotice : $siteNotice;
1426 } else {
1427 $siteNotice = $anonNotice;
1428 }
1429 }
1430
1431 wfProfileOut( $fname );
1432 return( $siteNotice );
1433 }
1434
1435 /**
1436 * Format an XML element with given attributes and, optionally, text content.
1437 * Element and attribute names are assumed to be ready for literal inclusion.
1438 * Strings are assumed to not contain XML-illegal characters; special
1439 * characters (<, >, &) are escaped but illegals are not touched.
1440 *
1441 * @param string $element
1442 * @param array $attribs Name=>value pairs. Values will be escaped.
1443 * @param string $contents NULL to make an open tag only; '' for a contentless closed tag (default)
1444 * @return string
1445 */
1446 function wfElement( $element, $attribs = null, $contents = '') {
1447 $out = '<' . $element;
1448 if( !is_null( $attribs ) ) {
1449 foreach( $attribs as $name => $val ) {
1450 $out .= ' ' . $name . '="' . htmlspecialchars( $val ) . '"';
1451 }
1452 }
1453 if( is_null( $contents ) ) {
1454 $out .= '>';
1455 } else {
1456 if( $contents == '' ) {
1457 $out .= ' />';
1458 } else {
1459 $out .= '>' . htmlspecialchars( $contents ) . "</$element>";
1460 }
1461 }
1462 return $out;
1463 }
1464
1465 /**
1466 * Format an XML element as with wfElement(), but run text through the
1467 * UtfNormal::cleanUp() validator first to ensure that no invalid UTF-8
1468 * is passed.
1469 *
1470 * @param string $element
1471 * @param array $attribs Name=>value pairs. Values will be escaped.
1472 * @param string $contents NULL to make an open tag only; '' for a contentless closed tag (default)
1473 * @return string
1474 */
1475 function wfElementClean( $element, $attribs = array(), $contents = '') {
1476 if( $attribs ) {
1477 $attribs = array_map( array( 'UtfNormal', 'cleanUp' ), $attribs );
1478 }
1479 if( $contents ) {
1480 $contents = UtfNormal::cleanUp( $contents );
1481 }
1482 return wfElement( $element, $attribs, $contents );
1483 }
1484
1485 // Shortcuts
1486 function wfOpenElement( $element, $attribs = null ) { return wfElement( $element, $attribs, null ); }
1487 function wfCloseElement( $element ) { return "</$element>"; }
1488
1489 /**
1490 * Create a namespace selector
1491 *
1492 * @param mixed $selected The namespace which should be selected, default ''
1493 * @param string $allnamespaces Value of a special item denoting all namespaces. Null to not include (default)
1494 * @return Html string containing the namespace selector
1495 */
1496 function &HTMLnamespaceselector($selected = '', $allnamespaces = null) {
1497 global $wgContLang;
1498 if( $selected !== '' ) {
1499 if( is_null( $selected ) ) {
1500 // No namespace selected; let exact match work without hitting Main
1501 $selected = '';
1502 } else {
1503 // Let input be numeric strings without breaking the empty match.
1504 $selected = intval( $selected );
1505 }
1506 }
1507 $s = "<select name='namespace' class='namespaceselector'>\n\t";
1508 $arr = $wgContLang->getFormattedNamespaces();
1509 if( !is_null($allnamespaces) ) {
1510 $arr = array($allnamespaces => wfMsgHtml('namespacesall')) + $arr;
1511 }
1512 foreach ($arr as $index => $name) {
1513 if ($index < NS_MAIN) continue;
1514
1515 $name = $index !== 0 ? $name : wfMsgHtml('blanknamespace');
1516
1517 if ($index === $selected) {
1518 $s .= wfElement("option",
1519 array("value" => $index, "selected" => "selected"),
1520 $name);
1521 } else {
1522 $s .= wfElement("option", array("value" => $index), $name);
1523 }
1524 }
1525 $s .= "\n</select>\n";
1526 return $s;
1527 }
1528
1529 /** Global singleton instance of MimeMagic. This is initialized on demand,
1530 * please always use the wfGetMimeMagic() function to get the instance.
1531 *
1532 * @access private
1533 */
1534 $wgMimeMagic= NULL;
1535
1536 /** Factory functions for the global MimeMagic object.
1537 * This function always returns the same singleton instance of MimeMagic.
1538 * That objects will be instantiated on the first call to this function.
1539 * If needed, the MimeMagic.php file is automatically included by this function.
1540 * @return MimeMagic the global MimeMagic objects.
1541 */
1542 function &wfGetMimeMagic() {
1543 global $wgMimeMagic;
1544
1545 if (!is_null($wgMimeMagic)) {
1546 return $wgMimeMagic;
1547 }
1548
1549 if (!class_exists("MimeMagic")) {
1550 #include on demand
1551 require_once("MimeMagic.php");
1552 }
1553
1554 $wgMimeMagic= new MimeMagic();
1555
1556 return $wgMimeMagic;
1557 }
1558
1559
1560 /**
1561 * Tries to get the system directory for temporary files.
1562 * The TMPDIR, TMP, and TEMP environment variables are checked in sequence,
1563 * and if none are set /tmp is returned as the generic Unix default.
1564 *
1565 * NOTE: When possible, use the tempfile() function to create temporary
1566 * files to avoid race conditions on file creation, etc.
1567 *
1568 * @return string
1569 */
1570 function wfTempDir() {
1571 foreach( array( 'TMPDIR', 'TMP', 'TEMP' ) as $var ) {
1572 $tmp = getenv( $var );
1573 if( $tmp && file_exists( $tmp ) && is_dir( $tmp ) && is_writable( $tmp ) ) {
1574 return $tmp;
1575 }
1576 }
1577 # Hope this is Unix of some kind!
1578 return '/tmp';
1579 }
1580
1581 /**
1582 * Make directory, and make all parent directories if they don't exist
1583 */
1584 function wfMkdirParents( $fullDir, $mode ) {
1585 $parts = explode( '/', $fullDir );
1586 $path = '';
1587
1588 foreach ( $parts as $dir ) {
1589 $path .= $dir . '/';
1590 if ( !is_dir( $path ) ) {
1591 if ( !mkdir( $path, $mode ) ) {
1592 return false;
1593 }
1594 }
1595 }
1596 return true;
1597 }
1598
1599 /**
1600 * Increment a statistics counter
1601 */
1602 function wfIncrStats( $key ) {
1603 global $wgDBname, $wgMemc;
1604 /* LIVE HACK AVOID MEMCACHED ACCESSES DURING HIGH LOAD */
1605 if ($wgDBname != 'enwiki' and $wgDBname != 'dewiki' and $wgDBname != 'commonswiki' and $wgDBname != 'testwiki')
1606 return true;
1607 static $socket;
1608 if (!$socket) {
1609 $socket=socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
1610 $statline="{$wgDBname} - 1 1 1 1 1 -total\n";
1611 socket_sendto($socket,$statline,strlen($statline),0,"webster","3811");
1612 }
1613 $statline="{$wgDBname} - 1 1 1 1 1 {$key}\n";
1614 socket_sendto($socket,$statline,strlen($statline),0,"webster","3811");
1615 return true;
1616
1617 $key = "$wgDBname:stats:$key";
1618 if ( is_null( $wgMemc->incr( $key ) ) ) {
1619 $wgMemc->add( $key, 1 );
1620 }
1621 }
1622
1623 /**
1624 * @param mixed $nr The number to format
1625 * @param int $acc The number of digits after the decimal point, default 2
1626 * @param bool $round Whether or not to round the value, default true
1627 * @return float
1628 */
1629 function wfPercent( $nr, $acc = 2, $round = true ) {
1630 $ret = sprintf( "%.${acc}f", $nr );
1631 return $round ? round( $ret, $acc ) . '%' : "$ret%";
1632 }
1633
1634 /**
1635 * Encrypt a username/password.
1636 *
1637 * @param string $userid ID of the user
1638 * @param string $password Password of the user
1639 * @return string Hashed password
1640 */
1641 function wfEncryptPassword( $userid, $password ) {
1642 global $wgPasswordSalt;
1643 $p = md5( $password);
1644
1645 if($wgPasswordSalt)
1646 return md5( "{$userid}-{$p}" );
1647 else
1648 return $p;
1649 }
1650
1651 /**
1652 * Appends to second array if $value differs from that in $default
1653 */
1654 function wfAppendToArrayIfNotDefault( $key, $value, $default, &$changed ) {
1655 if ( is_null( $changed ) ) {
1656 wfDebugDieBacktrace('GlobalFunctions::wfAppendToArrayIfNotDefault got null');
1657 }
1658 if ( $default[$key] !== $value ) {
1659 $changed[$key] = $value;
1660 }
1661 }
1662
1663 /**
1664 * Since wfMsg() and co suck, they don't return false if the message key they
1665 * looked up didn't exist but a XHTML string, this function checks for the
1666 * nonexistance of messages by looking at wfMsg() output
1667 *
1668 * @param $msg The message key looked up
1669 * @param $wfMsgOut The output of wfMsg*()
1670 * @return bool
1671 */
1672 function wfEmptyMsg( $msg, $wfMsgOut ) {
1673 return $wfMsgOut === "&lt;$msg&gt;";
1674 }
1675
1676 /**
1677 * Find out whether or not a mixed variable exists in a string
1678 *
1679 * @param mixed needle
1680 * @param string haystack
1681 * @return bool
1682 */
1683 function in_string( $needle, $str ) {
1684 return strpos( $str, $needle ) !== false;
1685 }
1686
1687 /**
1688 * Returns a regular expression of url protocols
1689 *
1690 * @return string
1691 */
1692 function wfUrlProtocols() {
1693 global $wgUrlProtocols;
1694
1695 $protocols = array();
1696 foreach ($wgUrlProtocols as $protocol)
1697 $protocols[] = preg_quote( $protocol, '/' );
1698
1699 return implode( '|', $protocols );
1700 }
1701
1702 /**
1703 * Check if a string is well-formed XML.
1704 * Must include the surrounding tag.
1705 *
1706 * @param string $text
1707 * @return bool
1708 *
1709 * @todo Error position reporting return
1710 */
1711 function wfIsWellFormedXml( $text ) {
1712 $parser = xml_parser_create( "UTF-8" );
1713
1714 # case folding violates XML standard, turn it off
1715 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
1716
1717 if( !xml_parse( $parser, $text, true ) ) {
1718 $err = xml_error_string( xml_get_error_code( $parser ) );
1719 $position = xml_get_current_byte_index( $parser );
1720 //$fragment = $this->extractFragment( $html, $position );
1721 //$this->mXmlError = "$err at byte $position:\n$fragment";
1722 xml_parser_free( $parser );
1723 return false;
1724 }
1725 xml_parser_free( $parser );
1726 return true;
1727 }
1728
1729 /**
1730 * Check if a string is a well-formed XML fragment.
1731 * Wraps fragment in an <html> bit and doctype, so it can be a fragment
1732 * and can use HTML named entities.
1733 *
1734 * @param string $text
1735 * @return bool
1736 */
1737 function wfIsWellFormedXmlFragment( $text ) {
1738 $html =
1739 Sanitizer::hackDocType() .
1740 '<html>' .
1741 $text .
1742 '</html>';
1743 return wfIsWellFormedXml( $html );
1744 }
1745
1746 /**
1747 * shell_exec() with time and memory limits mirrored from the PHP configuration,
1748 * if supported.
1749 */
1750 function wfShellExec( $cmd )
1751 {
1752 global $IP;
1753
1754 if ( php_uname( 's' ) == 'Linux' ) {
1755 $time = ini_get( 'max_execution_time' );
1756 $mem = ini_get( 'memory_limit' );
1757 if( preg_match( '/^([0-9]+)[Mm]$/', trim( $mem ), $m ) ) {
1758 $mem = intval( $m[1] * (1024*1024) );
1759 }
1760 if ( $time > 0 && $mem > 0 ) {
1761 $script = "$IP/bin/ulimit.sh";
1762 if ( is_executable( $script ) ) {
1763 $memKB = intval( $mem / 1024 );
1764 $cmd = escapeshellarg( $script ) . " $time $memKB $cmd";
1765 }
1766 }
1767 }
1768 return shell_exec( $cmd );
1769 }
1770
1771 /**
1772 * This function works like "use VERSION" in Perl, the program will die with a
1773 * backtrace if the current version of PHP is less than the version provided
1774 *
1775 * This is useful for extensions which due to their nature are not kept in sync
1776 * with releases, and might depend on other versions of PHP than the main code
1777 *
1778 * Note: PHP might die due to parsing errors in some cases before it ever
1779 * manages to call this function, such is life
1780 *
1781 * @see perldoc -f use
1782 *
1783 * @param mixed $version The version to check, can be a string, an integer, or
1784 * a float
1785 */
1786 function wfUsePHP( $req_ver ) {
1787 $php_ver = PHP_VERSION;
1788
1789 if ( version_compare( $php_ver, (string)$req_ver, '<' ) )
1790 wfDebugDieBacktrace( "PHP $req_ver required--this is only $php_ver" );
1791 }
1792
1793 /**
1794 * This function works like "use VERSION" in Perl except it checks the version
1795 * of MediaWiki, the program will die with a backtrace if the current version
1796 * of MediaWiki is less than the version provided.
1797 *
1798 * This is useful for extensions which due to their nature are not kept in sync
1799 * with releases
1800 *
1801 * @see perldoc -f use
1802 *
1803 * @param mixed $version The version to check, can be a string, an integer, or
1804 * a float
1805 */
1806 function wfUseMW( $req_ver ) {
1807 global $wgVersion;
1808
1809 if ( version_compare( $wgVersion, (string)$req_ver, '<' ) )
1810 wfDebugDieBacktrace( "MediaWiki $req_ver required--this is only $wgVersion" );
1811 }
1812
1813 /**
1814 * Escape a string to make it suitable for inclusion in a preg_replace()
1815 * replacement parameter.
1816 *
1817 * @param string $string
1818 * @return string
1819 */
1820 function wfRegexReplacement( $string ) {
1821 $string = str_replace( '\\', '\\\\', $string );
1822 $string = str_replace( '$', '\\$', $string );
1823 return $string;
1824 }
1825
1826 /**
1827 * Return the final portion of a pathname.
1828 * Reimplemented because PHP5's basename() is buggy with multibyte text.
1829 * http://bugs.php.net/bug.php?id=33898
1830 *
1831 * PHP's basename() only considers '\' a pathchar on Windows and Netware.
1832 * We'll consider it so always, as we don't want \s in our Unix paths either.
1833 *
1834 * @param string $path
1835 * @return string
1836 */
1837 function wfBaseName( $path ) {
1838 if( preg_match( '#([^/\\\\]*)[/\\\\]*$#', $path, $matches ) ) {
1839 return $matches[1];
1840 } else {
1841 return '';
1842 }
1843 }
1844
1845 /**
1846 * Make a URL index, appropriate for the el_index field of externallinks.
1847 */
1848 function wfMakeUrlIndex( $url ) {
1849 wfSuppressWarnings();
1850 $bits = parse_url( $url );
1851 wfRestoreWarnings();
1852 if ( !$bits || $bits['scheme'] !== 'http' ) {
1853 return false;
1854 }
1855 // Reverse the labels in the hostname, convert to lower case
1856 $reversedHost = strtolower( implode( '.', array_reverse( explode( '.', $bits['host'] ) ) ) );
1857 // Add an extra dot to the end
1858 if ( substr( $reversedHost, -1, 1 ) !== '.' ) {
1859 $reversedHost .= '.';
1860 }
1861 // Reconstruct the pseudo-URL
1862 $index = "http://$reversedHost";
1863 // Leave out user and password. Add the port, path, query and fragment
1864 if ( isset( $bits['port'] ) ) $index .= ':' . $bits['port'];
1865 if ( isset( $bits['path'] ) ) {
1866 $index .= $bits['path'];
1867 } else {
1868 $index .= '/';
1869 }
1870 if ( isset( $bits['query'] ) ) $index .= '?' . $bits['query'];
1871 if ( isset( $bits['fragment'] ) ) $index .= '#' . $bits['fragment'];
1872 return $index;
1873 }
1874
1875 /**
1876 * Do any deferred updates and clear the list
1877 * TODO: This could be in Wiki.php if that class made any sense at all
1878 */
1879 function wfDoUpdates()
1880 {
1881 global $wgPostCommitUpdateList, $wgDeferredUpdateList;
1882 foreach ( $wgDeferredUpdateList as $update ) {
1883 $update->doUpdate();
1884 }
1885 foreach ( $wgPostCommitUpdateList as $update ) {
1886 $update->doUpdate();
1887 }
1888 $wgDeferredUpdateList = array();
1889 $wgPostCommitUpdateList = array();
1890 }
1891
1892 ?>