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