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