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