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