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