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