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