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