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