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